mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 18:07:00 +01:00
Preserve Copilot token verification in the current agent lifecycle
Move environment and metadata checks into the upstream services, retain connection access and authentication failure handling, and follow mainline migration 0320 with additive Copilot migration 0321. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
commit
6dd65ca5f7
200 files changed
+14307
-6935
No files matched your search
@@ -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")));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,17 @@ remote workspace. Supply a workspace-relative `contentRef`, basename `filename`,
|
||||
The tool verifies the file, stores an attachment and artifact work product, and
|
||||
binds it to the response. Generic API tools and a legacy API key are unnecessary.
|
||||
|
||||
The completion gate permits a narrow sentence-bound exception for one requested
|
||||
file when the following sentence explicitly qualifies it, for example:
|
||||
`Write memory.txt. This is personal memory, not a task deliverable.` or
|
||||
`Write internal-proof.txt. This is an internal verification file, not a deliverable.`
|
||||
Each qualifier applies to one file in the immediately preceding request sentence.
|
||||
Separate file requests can each qualify when each has its own following qualifier.
|
||||
Multiple files requested in one sentence, unqualified report requests, and explicit
|
||||
attachment/download requests still need verified accessible publication evidence. Saying only “for internal verification”
|
||||
does not establish this exception. Expected denied native writes in a negative
|
||||
test are separately recognized as denied attempts, not requested deliverables.
|
||||
|
||||
Wait for the receipt. It includes `attachmentId`, `contentPath`, and
|
||||
`downloadPath`, along with the existing command, revision, entity references,
|
||||
and disposition. Reuse the original key after an ambiguous result. A receipt
|
||||
|
||||
@@ -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.
|
||||
@@ -681,3 +681,46 @@ and are atomically deleted before code exchange. The `code_verifier` column hold
|
||||
this non-secret binding for this namespace; Slack bot installation does not use
|
||||
PKCE. Removal and manual recovery invalidate outstanding attempts under the same
|
||||
credential-mutation lease used by configuration.
|
||||
|
||||
|
||||
## Transaction-aware delivery work signals
|
||||
|
||||
Five existing delivery queues use process-local work signals to avoid empty
|
||||
polling. Register work **before** writing a queue row, on that row's transaction:
|
||||
|
||||
```ts
|
||||
await db.transaction(async tx => {
|
||||
await signalDatabaseWork(tx, "queue-topic");
|
||||
await tx.insert(existingQueueTable).values(row);
|
||||
});
|
||||
```
|
||||
|
||||
`createDb` instruments transaction callbacks and nested savepoints. Subscribers
|
||||
receive intent immediately and settlement only after the outer transaction
|
||||
finishes. Caller-owned transactions therefore need no extra post-commit wrapper.
|
||||
Dedicated clients from `withDedicatedDbConnection` share the owner's signal
|
||||
scope. No schema changes, triggers, dedicated listener connection, or periodic
|
||||
queries are installed by this API.
|
||||
|
||||
The first registered write in a transaction fetches `pg_current_xact_id()`.
|
||||
Awaiting registration is required: a failure at that point must prevent the
|
||||
queue write. Unrelated transactions add no queries. If the transaction rejects,
|
||||
the coordinator probes `pg_xact_status(xid)` through the root pool before scanning
|
||||
the queue. An in-progress transaction remains unresolved even when the queue
|
||||
currently looks empty. Committed/aborted results permit reconciliation; NULL
|
||||
means PostgreSQL has discarded an old, no-longer-active transaction's outcome.
|
||||
The existing durable queue supplies the work in either case. Probe failures
|
||||
retain the idle hold and schedule another attempt. Work signals never replay
|
||||
queries or convert a failed database operation into success.
|
||||
|
||||
This uses PostgreSQL's transaction-information functions (this path requires
|
||||
PostgreSQL 14+; embedded PostgreSQL uses 18). See the
|
||||
[PostgreSQL transaction information documentation](https://www.postgresql.org/docs/18/functions-info.html#FUNCTIONS-PG-SNAPSHOT).
|
||||
The process-local intent survives coordinator replacement, but not process exit.
|
||||
Startup scans recover committed queue rows. Independent DB clients, other
|
||||
processes, late transactions from an old process, and database failover need an
|
||||
explicit ownership/wake protocol; these signals are not cross-process messaging.
|
||||
Use the same root client for in-process writers. New queue insertion paths must
|
||||
register before writing, or they can remain unseen until the next startup or
|
||||
another notification. Tests should verify both the producer and its outer
|
||||
transaction boundary.
|
||||
+30
-3
@@ -1250,9 +1250,9 @@ It owns bounded run projections, database encoding checks, task session reads an
|
||||
writes, explicit resumes, session compaction, and usage/billing helpers.
|
||||
`createHeartbeatRunState(db)` binds these operations without doing database work
|
||||
during construction. The encoding-check cache belongs to each factory instance.
|
||||
`heartbeat.ts` keeps run execution, session-goal recovery, cost accounting writes,
|
||||
and status transitions, and re-exports the existing public helpers. Keep session
|
||||
policy changes separate from run orchestration changes.
|
||||
`heartbeat.ts` keeps run execution and session-goal recovery, and re-exports the
|
||||
existing public helpers. Keep session policy changes separate from run
|
||||
orchestration changes.
|
||||
|
||||
Retry scheduling is in `server/src/services/heartbeat/retries.ts`. It owns bounded
|
||||
retry schedules, connection and workspace contention deferrals, shared-workspace
|
||||
@@ -1281,6 +1281,25 @@ its process-wide execution and wakeup promise sets. Forwarding callbacks preserv
|
||||
construction order for retry and recovery services. Keep queue policy changes
|
||||
separate from this extraction and from adapter execution changes.
|
||||
|
||||
Run lifecycle handling is in `server/src/services/heartbeat/run-lifecycle.ts`.
|
||||
It owns status transitions, run events and progress, liveness classification,
|
||||
completion handoffs, issue-comment finalization, and runtime/cost settlement.
|
||||
`createHeartbeatLifecycle` binds the database and explicit reporting, recovery,
|
||||
and wakeup callbacks without starting work. The service supplies terminal
|
||||
reporting and forwarding callbacks preserve construction order for the other
|
||||
heartbeat modules. Existing public helpers remain re-exported by `heartbeat.ts`.
|
||||
Keep lifecycle policy changes separate from this extraction and adapter execution.
|
||||
|
||||
Run cancellation and cleanup are in `server/src/services/heartbeat/run-control.ts`.
|
||||
It owns Stop, agent and budget cancellation, environment lease release, and
|
||||
resumption of saved comments after execution stops. `createHeartbeatRunControl`
|
||||
binds the database, lifecycle and admission callbacks, and shared executor
|
||||
barriers without starting work. The service retains the process-wide execution
|
||||
and cancellation maps so scheduler and route instances observe the same owners.
|
||||
Forwarding callbacks preserve construction order for budget, retry, recovery,
|
||||
and queue services. Existing public helpers remain re-exported by `heartbeat.ts`.
|
||||
Keep cancellation policy changes separate from this extraction and execution.
|
||||
|
||||
## Wake Context Delivery
|
||||
|
||||
Built-in adapters deliver wake context through the run prompt, including structured
|
||||
@@ -1428,6 +1447,14 @@ the updated sandbox image with the matching runner qualification changes.
|
||||
|
||||
### Native runner restart recovery
|
||||
|
||||
Custom source-mode HTTP launchers should create their listener with
|
||||
`createPaperclipHttpServer` from `server/src/http/server.ts`, passing the selected
|
||||
API origin as `apiUrl`. This registers the native Runner WebSocket transport
|
||||
before execution is admitted. Plain Express `app.listen()` or Node
|
||||
`createServer(app)` alone does not initialize that transport and native runs
|
||||
fail with `runner_prp_websocket_server_not_configured`. Browser live events still
|
||||
use their separate authenticated setup.
|
||||
|
||||
Project discovery through `list_projects` returns up to 50 compact summaries.
|
||||
It uses `GET /api/companies/:companyId/projects?view=summary&limit=50&cursor=...`;
|
||||
the cursor is optional. The database reads bounded summary projections. Agent
|
||||
|
||||
@@ -37,6 +37,16 @@ workspace: their independent agent copy therefore lives under the excluded
|
||||
`.paperclip-runtime/agent-files/<agent>/<run>/` area. It is not included in task
|
||||
workspace sync, Git staging, or task deliverables.
|
||||
|
||||
Sandbox transfer scratch lives separately under
|
||||
`.paperclip-runtime/paperclip-runner/agent-file-transfers/<agent>/<run>/`.
|
||||
Workspace-staging transfer scratch stays outside `AGENT_HOME`, including
|
||||
recovery after controller restart. Remote warm Codex checkpoints may temporarily
|
||||
stage changed-file payloads under `AGENT_HOME/.paperclip-runtime/checkpoint-*`;
|
||||
these are checkpoint scratch, not managed personal files. Cleanup removes
|
||||
only the original materialization's agent directory and transfer scratch
|
||||
through its owned lease. A later warm turn keeps that original materialization
|
||||
identity; it does not grant collection or cleanup of another run's files.
|
||||
|
||||
Claude CLI runs keep the working-copy location in each run's prompt, separate
|
||||
from the cached system instructions. A new copy path alone does not reset the
|
||||
task session. Each turn names the current copy for relative file references;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -22,7 +22,115 @@ 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)
|
||||
## User-selected models (2026-10-06)
|
||||
|
||||
Native Pi accepts any explicit provider/model ID. The settings builder, server,
|
||||
release profile, and Rust runner do not restrict selection to a qualification
|
||||
model. Pi must acknowledge the exact selection before a prompt and on recovery;
|
||||
unavailable models fail clearly without selecting a substitute. Runtime package,
|
||||
version, command, permission, and process-ownership checks remain enforced.
|
||||
|
||||
Bind the selected provider's credentials in the agent environment, for example
|
||||
`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`, or `OPENROUTER_API_KEY`.
|
||||
Custom models use `PAPERCLIP_PI_PROVIDERS`, an explicit JSON object in Pi's
|
||||
`models.json` providers format. The runner writes it into the private Pi home,
|
||||
forwards explicitly bound credential references, and includes its digest in
|
||||
recovery identity. Credential commands and control-plane credential references
|
||||
are rejected. General AWS IAM keys are excluded; Bedrock uses `AWS_BEARER_TOKEN_BEDROCK`. Choose a thinking level supported by the selected model (`off`
|
||||
for a model without reasoning).
|
||||
|
||||
The DeepSeek model IDs throughout the historical qualification results below
|
||||
identify those attempts; they are not a product allowlist. Those results do not
|
||||
qualify this merge or additional models.
|
||||
|
||||
|
||||
## 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. The subsequent live callback snapshot changes the shared sidecar again,
|
||||
so Copilot now uses still-unqualified profile v14 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 +205,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 +387,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 +1163,62 @@ 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.
|
||||
|
||||
|
||||
## Cold process admission budget
|
||||
|
||||
Pi cold `session.open`, including process replacement and durable reopen, has a
|
||||
60-second admission budget. The controller shares one deadline across its cold
|
||||
open/recovery command and provider identity barriers (`session.open`, replacement
|
||||
`run.attach`, and replacement `runner.drain`). A live adopted runner keeps the
|
||||
ordinary 30-second waits. Rust gives only Pi's sidecar `session.open` request the
|
||||
60-second budget; initialize, attach, turn start and other sidecar commands stay
|
||||
at 30 seconds. Inner ACP handshake (30 seconds), post-admission verification
|
||||
(8 seconds), cancellation (2 seconds), and close (7 seconds) are unchanged.
|
||||
|
||||
Timeout still poisons and retires the Rust sidecar process group. Closing the
|
||||
controller during its startup wait rejects that wait and uses the existing owned
|
||||
process cleanup. Callers must await transport close in their cleanup path.
|
||||
This is trusted controller timing policy, outside the immutable Pi wrapper/profile
|
||||
closure; it does not change profile 13, runtime 1.0.0, or the explicit model.
|
||||
|
||||
The credential-free closed-startup regression requires the real
|
||||
`session_ensure_failed` rejection within 60 seconds, with no prompt, no provider
|
||||
identity and confirmed cleanup. Its child watchdog is 80 seconds (20 seconds for
|
||||
cleanup after admission), inside a 90-second test timeout. Failed evidence stays
|
||||
in its reported temporary directory. These margins do not extend production
|
||||
command deadlines or qualify a target platform without a fresh run.
|
||||
@@ -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. |
|
||||
|
||||
@@ -110,7 +110,7 @@ single successful browser task do not establish that qualification.
|
||||
## Remote verification
|
||||
|
||||
Do not run Docker on a developer laptop when using remote verification. The
|
||||
`Docker Runner check` workflow offers maintainer-authorized manual EC2 image
|
||||
`Docker Runner check` workflow offers maintainer-authorized manual Linux image
|
||||
builds and broad source checks without provider credentials. It records the
|
||||
source revision, resolved lock digest and immutable image reference. Paid
|
||||
Product E2E remains behind the protected default-branch workflow and environment.
|
||||
|
||||
@@ -0,0 +1,867 @@
|
||||
# Instance sleep and scheduler inventory
|
||||
|
||||
Date: 2026-10-08
|
||||
|
||||
Status: Inventory with first delivery-coordinator implementation; full idle sleep remains open
|
||||
|
||||
Code baseline: `0ac194450`
|
||||
|
||||
Paperclip should release idle database connections and allow inactive customer
|
||||
instances to sleep without losing scheduled work, incoming events, accounting,
|
||||
or recovery. Thousands of individually hosted instances make empty polling a
|
||||
material cost even when each query is cheap.
|
||||
|
||||
**Architectural direction: triage each loop before choosing its replacement.**
|
||||
Work caused by a committed change or incoming event should run from that event.
|
||||
Work caused by the passage of time belongs in one in-process, instance-wide
|
||||
scheduler. A later external-waker adapter publishes only the stack's next wake
|
||||
time. Routine definitions and execution decisions remain inside the stack.
|
||||
|
||||
Immediate delivery does not have to pass through the scheduler. Its delayed
|
||||
retry does. The same service can contain both categories; classify its work
|
||||
paths rather than treating its current polling loop as one indivisible job.
|
||||
|
||||
The database already closes idle pooled connections after 60 seconds and opens
|
||||
new connections on demand. The primary work is eliminating unnecessary queries
|
||||
and coordinating background work, connections, and hosting sleep.
|
||||
|
||||
## First slice: transaction-aware delivery notifications and shared scheduling
|
||||
|
||||
Updated: 2026-10-09. This implementation covers five existing durable queues:
|
||||
|
||||
- [x] JOB-04: feedback exports register intent before the export write.
|
||||
- [x] JOB-22: completion receipts register intent inside their transaction, including caller-owned and nested transactions. No extra post-commit action is needed from callers.
|
||||
- [x] JOB-23: connection continuations register intent before enqueue.
|
||||
- [x] JOB-25: question answers register intent before enqueue.
|
||||
- [x] JOB-24: tool receipts and review resolution register intent before enqueue.
|
||||
- [x] `createDb` centrally defers delivery wakes until the outer transaction settles. Dedicated child pools share the owning client's signal scope.
|
||||
- [x] One scheduler owns pending-work and failure retries. Empty, settled queues have no recurring deadline or database scan.
|
||||
- [x] Unresolved local writes prevent idle admission. Recovery probes PostgreSQL's transaction status before scanning the existing queue and clears the hold once both are settled.
|
||||
- [x] Tests cover nested commits, rollback, late commit/abort after a lost client response, concurrent writes during a sweep, worker replacement, restart recovery, drain/standby, and shutdown.
|
||||
- [ ] Prove the complete instance writer-admission and idle/resume boundary across all other work.
|
||||
- [ ] Migrate other actual scheduled work and expose the whole instance's earliest deadline to an external waker.
|
||||
- [ ] Verify actual app and database sleep on the hosting providers.
|
||||
|
||||
Existing delivery rows remain authoritative; no tables or migrations are added.
|
||||
A producer adds one awaited `notifyDeliveryWork(tx, queue)` before its write.
|
||||
`createDb().transaction()` and nested savepoints are instrumented centrally. The
|
||||
first opted-in write fetches the outer transaction's XID; unrelated transactions
|
||||
add no SQL. A rejected transaction with a known XID is reconciled with
|
||||
`pg_xact_status` before the queue scan. An empty scan cannot discharge an
|
||||
in-progress transaction. Committed, aborted, or aged-out XIDs can be discharged
|
||||
after scanning. A failed status query retains the hold and a retry deadline.
|
||||
|
||||
The scheduler retains startup sweeps, retry deadlines while durable work exists,
|
||||
and retries after failures. Idle drain permits transaction and queue checks but
|
||||
does not start deliveries; warm standby suppresses both. There is no
|
||||
unconditional 60-second recovery pass.
|
||||
Feedback flushes remain serialized and cancellable, with a 30-second upload
|
||||
limit. Vote routes return after saving rather than waiting for upload. Tool
|
||||
receipts awaiting review or execution still retain their retry cadence.
|
||||
|
||||
**Scope:** notifications and unresolved-XID tracking are process-local to a
|
||||
`createDb` owner and its dedicated child pools. They do not observe direct SQL,
|
||||
an independently created client, or another process. Such writers need an
|
||||
explicit wake/reconciliation integration before this mechanism can support
|
||||
them. Startup scans recover already committed durable rows; they do not prove
|
||||
that transactions still running in an old process have finished. Cross-process
|
||||
handoff/fencing is separate work, as is PostgreSQL failover during uncertainty.
|
||||
|
||||
This removes these five empty polling loops; it does not establish whole-stack
|
||||
sleep. `nextWakeAt` covers only registered queues. Database connection teardown,
|
||||
other background loops, full idle reconciliation, and external wake registration
|
||||
remain separate work.
|
||||
|
||||
Implementation: `packages/db/src/work-signals.ts`,
|
||||
`server/src/services/work-scheduler.ts`, `delivery-work-coordinator.ts`, and
|
||||
`delivery-work-notifications.ts`.
|
||||
|
||||
## Using this checklist
|
||||
|
||||
Items have stable IDs so they can become separate issues or PRs. All boxes start
|
||||
unchecked: an existing mechanism or a recommendation is not proof that the
|
||||
sleep journey has passed. Mark an item complete only after its completion
|
||||
criteria have evidence, and append the issue/PR and verification result to it.
|
||||
Record deferrals with a reason and the capability that must remain awake.
|
||||
|
||||
Source links identify files in the audited revision. Function names and stated
|
||||
cadences are navigation aids; recheck them when implementing a later revision.
|
||||
Cadences describe ordinary claimed-instance operation. Warm-standby, idle-drain,
|
||||
configuration, or feature gates can suppress individual paths. This inventory
|
||||
does not establish the actual deployed fleet configuration.
|
||||
|
||||
## Triage before implementation
|
||||
|
||||
Use this question for every operation: **If no new request or event arrives,
|
||||
does this operation still need to happen at a particular future time?**
|
||||
|
||||
- **Yes: clock-driven.** Register that deadline with the internal scheduler.
|
||||
Examples are a routine at 09:00, a retry after backoff, and a session expiry.
|
||||
- **No: event-driven or on demand.** Invoke it from the owning committed mutation,
|
||||
verified external event, or user request. An empty queue is not a scheduled
|
||||
task. Examples are delivering a newly committed answer and refreshing a UI
|
||||
after an issue changes.
|
||||
|
||||
Many existing sweeps combine both. Separate their immediate dispatch from their
|
||||
retry/timeout/recovery paths. Persistent transports and active-operation
|
||||
keepalives are lifecycle requirements, not idle business schedules; their
|
||||
ownership and shutdown need separate treatment.
|
||||
|
||||
The tables below are a first-pass mechanism triage grounded in the inventory.
|
||||
They select where to investigate first, not permission to delete a recovery
|
||||
path. Detailed checklist items remain the implementation and verification record.
|
||||
|
||||
### Work that genuinely needs a clock
|
||||
|
||||
| Checklist items | Reason time matters | What belongs in the scheduler |
|
||||
| --- | --- | --- |
|
||||
| JOB-08 Agent timer heartbeats and issue monitors | The user explicitly requested future checks. | The next enabled heartbeat/monitor deadline; none when unconfigured. |
|
||||
| JOB-09 Routine cron triggers | A routine must run even without new incoming activity. | Existing `nextRunAt`, retaining catch-up and timezone semantics. |
|
||||
| JOB-07 Plugin scheduled jobs | A plugin may declare real recurring work. | Declared job deadlines; plugin load/configuration events update registration. |
|
||||
| JOB-29 Backups | A backup guarantee has a time requirement. | The next backup if this instance owns it; otherwise the explicit external backup owner. |
|
||||
| JOB-18, JOB-19 Login and setup expiry | An abandoned session/resource must expire even if nobody returns. | Actual expiry and failed-cleanup retry times, only while relevant sessions exist. |
|
||||
| JOB-11, JOB-21 Decision and secret/token expiry | Decision deadlines and some deletion/retention obligations are time-based. | Required expiry/scrub deadlines. Check validity synchronously on use regardless of whether physical cleanup ran. |
|
||||
| JOB-10 Decision retention | An unchanged item can become old enough to archive. | The next actual retention deadline; immediate change handling and notification delivery are event-driven. |
|
||||
| JOB-12, JOB-13 External objects and status cards | Some configured freshness/update policies require future work. | Only time-based refresh/evaluation deadlines; reactive updates use events. |
|
||||
| JOB-27, JOB-28 Retries and watchdogs | A retry delay or absence of expected progress can itself require action. | Concrete retry, lease-expiry, monitor, or watchdog deadlines for existing work. |
|
||||
|
||||
### Work whose normal path should stop polling
|
||||
|
||||
| Checklist items | Preferred normal trigger | Clock-driven remainder or qualification |
|
||||
| --- | --- | --- |
|
||||
| JOB-04 Feedback exports | Committed export enqueue. | Backoff after delivery failure and durable recovery of outstanding exports. No empty five-second scan. |
|
||||
| JOB-22 Chat completion delivery | Committed task completion/update. An existing postcommit fast path is already present. | Delivery retries and recovery; the current fast path is best-effort, so prove replacement reliability before removing its sweep. |
|
||||
| JOB-23 Connection continuation delivery | Committed connection availability/change and pending continuation enqueue. | Failed-delivery retry/claim recovery. |
|
||||
| JOB-25 Question response delivery | Committed user answer. | Retry/claim expiry while delivery is outstanding. |
|
||||
| JOB-24 Tool action reviews and deliveries | Committed approval/rejection or action enqueue. | Review expiry and delivery retries. |
|
||||
| JOB-26 Cost accounting | Arrival or durable capture of a usage receipt/result. | Recovery of unresolved receipts/reservations and failed writes. Accounting debt cannot be dropped. |
|
||||
| JOB-05 MCP and Dot events | Committed source event or subscription change. | Delivery retries and required expiry cleanup. |
|
||||
| JOB-01 Chat reconciliation | Incoming message, committed publication, or endpoint configuration change. | Split its lanes: delivery retry and missed-event recovery are temporal; socket ownership is NET work. |
|
||||
| JOB-02 Email reconciliation | Verified webhook, outgoing send, or endpoint configuration change. | Retry and provider catch-up guarantees; socket reception and catch-up are NET-01/NET-02. |
|
||||
| JOB-03 Browser-use cleanup | Browser/session lifecycle change. | Register actual idle/expiry/reconciliation deadlines while sessions exist; active leases remain protected. |
|
||||
| JOB-06 Execution-control reconciliation | Execution state transitions and committed control requests. | Timeout, lease-expiry, abandoned-operation, and failed-delivery recovery. Split the lanes before changing cadence. |
|
||||
| JOB-14 GitHub events and continuity | Verified webhook and connection lifecycle change where supported. | Credential deadlines; bounded polling only for providers/events without adequate push or replay guarantees. |
|
||||
| JOB-15 Merge confirmations | Verified merge event for an outstanding candidate. | Bounded fallback only while candidates exist and webhook/replay coverage is insufficient. |
|
||||
| JOB-16 Terminal workspaces | Committed terminal task/tree transition. | Cooldown, failed-cleanup retry, and recovery of outstanding cleanup. |
|
||||
| JOB-17 Sandbox cleanup | Resource release or failed acquire/release. | Retry/backoff and provider/fleet orphan recovery. |
|
||||
| JOB-20 Connection health | Use of the connection or configuration change. | Proactive checks only where a defined freshness guarantee requires them. |
|
||||
| JOB-10, JOB-11 Decision effects and notifications | Committed decision/relevant source mutation. | Expiry/retention stays in the clock-driven category. |
|
||||
| JOB-12, JOB-13 Reactive external objects/cards | Verified provider event or relevant local mutation. | Configured time-based refresh stays in the clock-driven category. |
|
||||
| JOB-27, JOB-28 Queued runs, assignments, and dependencies | Committed enqueue, assignment, terminal result, or dependency transition. | Time-based recovery/watchdogs stay in the clock-driven category. |
|
||||
| AUX-01, AUX-03 Telemetry and plugin log flushing | First buffered entry activates a bounded flush. | Batch delay and failed-delivery retry while nonempty; no empty heartbeat. |
|
||||
| AUX-04 Import spools and runtime status expiry | Spool creation/completion, startup, or access to an expiring in-memory value. | Schedule only required file-retention/cleanup deadlines. Lazy expiration can handle noncontractual memory cleanup. |
|
||||
| UI-01, UI-02 Stable UI data | Existing live events, initial read, foreground return, and reconnect reconciliation. | Preserve bounded fallback during a genuine realtime outage or active operation. Reconcile subscription gaps because live events are not replayed. |
|
||||
| UI-03, UI-04, UI-06 Recovery, app updates, and setup | Foreground/online/user activity and bounded setup state. | Client-side retry/update deadlines where needed; these do not become tenant server jobs. |
|
||||
|
||||
JOB-30 is removal of the aggregate polling wrapper after its constituents are
|
||||
handled, not a new scheduled job. DB-01–DB-03 concern the connection pool;
|
||||
DB-04/DB-05 concern probes. NET-01–NET-07, UI-05, and AUX-05 concern transport or
|
||||
plugin lifetime. AUX-02/AUX-06 require checking actual exporter/SDK traffic.
|
||||
SCH, WAKE, SAFE, HOST, and TEST items are infrastructure, policy, or verification
|
||||
work rather than business jobs. This keeps every inventory item accounted for
|
||||
without making the scheduler responsible for every source of activity.
|
||||
|
||||
### Qualification before removing a poll
|
||||
|
||||
- [ ] **TRI-01 — Identify the real trigger and every producer.** For each
|
||||
event-driven candidate, list the committed mutations/external events that
|
||||
create work, including alternate API paths and recovery writers. **Complete
|
||||
when:** every supported producer has an owned dispatch path and the service
|
||||
needs no scan to discover normal new work.
|
||||
|
||||
- [ ] **TRI-02 — Separate first delivery from delayed recovery.** Record which
|
||||
paths are immediate, which have a concrete due time, and which depend on an
|
||||
external provider's push capabilities. **Complete when:** each migrated lane
|
||||
has an explicit trigger and its remaining deadlines are enumerated.
|
||||
|
||||
- [ ] **TRI-03 — Prove durable delivery before retiring its backstop.** A
|
||||
best-effort callback after commit is not a durable queue consumer. Cover
|
||||
commit-before-signal crashes, lost signals while the process stays alive,
|
||||
handler failures, concurrent producers, and restart. **Complete when:** an
|
||||
outstanding record cannot become invisible indefinitely. Retain a bounded,
|
||||
explicitly justified reconciliation path until this is proven; document its
|
||||
wake cost rather than assuming startup recovery covers every failure.
|
||||
|
||||
- [ ] **TRI-04 — Order work by avoidable idle traffic and migration risk.**
|
||||
Record expected idle SQL/network reduction and the smallest focused proof for
|
||||
the next item. **Complete when:** the next PR has one clear boundary and does
|
||||
not require the entire scheduler or all connector lifecycles to be finished.
|
||||
|
||||
### Initial implementation shortlist
|
||||
|
||||
1. **DB-04/DB-05: health and probe separation.** A self-contained source of
|
||||
avoidable demand, independent of building a scheduler. Verify actual callers
|
||||
so the new endpoint is used.
|
||||
2. **JOB-04: event-driven feedback exports.** A contained first dispatch
|
||||
migration. Triage its enqueue, failed-export behavior, and recovery first;
|
||||
put only actual retry/batch deadlines in scheduling infrastructure.
|
||||
3. **JOB-22/JOB-25: completion and answer delivery.** Reuse existing postcommit
|
||||
paths where possible, after proving that durable delivery can replace the
|
||||
sweep rather than merely supplement it.
|
||||
4. **JOB-01/JOB-02/JOB-03: frequent empty chat, email, and browser scans.** Large
|
||||
baseline benefit, but split the component lanes and preserve configured
|
||||
transports, expiry, and recovery. Resource absence must be invalidated when
|
||||
a new resource is committed.
|
||||
5. **SCH with JOB-09: routine scheduling as the first true clock-driven slice.**
|
||||
Existing `nextRunAt` makes the real scheduler requirement concrete. Add other
|
||||
temporal paths and then the external-waker adapter.
|
||||
|
||||
This order supersedes starting by routing the feedback polling loop through a
|
||||
generic scheduler. Event-driven improvements can ship before that scheduler is
|
||||
complete. The resulting service still needs an owned way to retry failures.
|
||||
|
||||
## Provider behavior and cost model
|
||||
|
||||
| Layer | Documented behavior | Consequence |
|
||||
| --- | --- | --- |
|
||||
| Neon | Normally suspends after five minutes without active queries. Idle-in-transaction connections count as active; ordinary idle connections do not necessarily block suspension. New connection requests can reset inactivity. | Stop empty SQL polling and connection churn; do not force-close active transactions. |
|
||||
| Railway | Detailed Serverless documentation specifies five minutes without outbound packets, sampled so actual sleep is roughly 5–10 minutes. Private-network traffic and responses count. Enabling Serverless requires a deployment to affect the container. | Every recurring source of packets matters. Even a DB-free endpoint can keep the app awake when repeatedly called externally. |
|
||||
| Unikraft | `on` waits for connections/HTTP requests to finish; `idle` can suspend inactive TCP connections. Active HTTP requests prevent suspension. Stateful mode resumes a snapshot. | Quiesce connections deliberately and explicitly protect background work from premature suspension. |
|
||||
|
||||
Provider sources: [Neon compute lifecycle](https://neon.com/docs/introduction/compute-lifecycle),
|
||||
[Neon compute management](https://neon.com/docs/manage/endpoints/),
|
||||
[Railway Serverless](https://docs.railway.com/deployments/serverless),
|
||||
[Unikraft scale to zero](https://unikraft.com/docs/features/scale-to-zero).
|
||||
|
||||
Neon usage is reported in CU-seconds. The transcript's five-minute concern is
|
||||
primarily an idle-timeout cost, not a universal billing quantum. With a
|
||||
five-minute timeout, a trivial hourly check creates roughly an 8.3% active-time
|
||||
floor before useful work; checking every five minutes can leave compute
|
||||
continuously active. This illustration assumes the default timeout and excludes
|
||||
other traffic, processing time, and storage charges. Verify actual endpoint
|
||||
settings and the applicable plan. See [Neon usage calculations](https://neon.com/docs/introduction/usage-calculations).
|
||||
|
||||
## 1. Internal scheduler for true deadlines
|
||||
|
||||
- [ ] **SCH-01 — Establish the instance-wide scheduler boundary.** Route
|
||||
application-owned delayed jobs, recurring jobs, retry deadlines, and required
|
||||
expiry/cleanup/maintenance deadlines through one scheduler shared across all
|
||||
companies. Immediate event/queue dispatch remains in its owning service;
|
||||
running-work tracking is shared with sleep admission. Keep domain handlers and
|
||||
their authorization/atomic claims in their existing services. **Complete
|
||||
when:** one scheduling interface supports true temporal obligations, company
|
||||
scope remains explicit, and self-hosted operation requires no external service.
|
||||
|
||||
- [ ] **SCH-02 — Model work and deadlines explicitly.** Track a stable job/lane
|
||||
identity, company scope where applicable, due time, pending/running state,
|
||||
retry policy, and whether running work blocks sleep. Accept running-work
|
||||
information from event-driven handlers without forcing their dispatch through
|
||||
the scheduler. Distinguish scheduled
|
||||
work, immediate queued work, waiting for an external event, and passive
|
||||
configuration/history. **Complete when:** an empty lane has no recurring SQL
|
||||
check, and the scheduler can explain outstanding work and the earliest due
|
||||
time without querying the database on every timer tick.
|
||||
|
||||
- [ ] **SCH-03 — Reconstruct state and handle committed changes.** Seed the
|
||||
scheduler from existing durable domain records on startup; use committed
|
||||
mutations to register, reschedule, cancel, or activate work. In-memory hints
|
||||
cannot be the sole record of an obligation. Define how all supported writers
|
||||
invalidate hints; initially retain the existing single-process boundary.
|
||||
**Complete when:** restart and a crash between commit and notification recover
|
||||
work, and creating an earlier deadline updates the scheduler immediately.
|
||||
|
||||
- [ ] **SCH-04 — Implement local scheduling and catch-up.** Arm the nearest
|
||||
necessary local timer and run due handlers with bounded concurrency and
|
||||
per-lane overlap protection. Preserve each domain's timezone, missed-run,
|
||||
coalescing, priority, and retry semantics. **Complete when:** delayed callbacks,
|
||||
clock changes, restart, and duplicate activation cannot silently lose work or
|
||||
bypass existing execution claims.
|
||||
|
||||
- [ ] **SCH-05 — Expose an aggregate next wake time.** Compute the earliest
|
||||
required deadline across the whole instance, including retries, cleanup,
|
||||
accounting, and maintenance. Represent no scheduled work as no alarm; represent
|
||||
unknown obligations as a sleep blocker. **Complete when:** adding, moving,
|
||||
removing, or completing the earliest item correctly changes the aggregate.
|
||||
|
||||
- [ ] **SCH-06 — Integrate running-work ownership and drain.** Reuse
|
||||
[task admission](../../server/src/services/task-admission.ts),
|
||||
[idle admission](../../server/src/middleware/idle-admission.ts), and the
|
||||
[existing sleep protocol](../idle-sleep-safety.md). Track handler completion
|
||||
even after an HTTP response or client disconnect. **Complete when:** draining
|
||||
prevents new scheduled admissions and waits for accepted work without losing
|
||||
fire-and-forget work or mutations racing the final check.
|
||||
|
||||
- [ ] **SCH-07 — Classify transport and SDK timer exceptions.** Business
|
||||
scheduling belongs to the scheduler. Protocol pings, socket deadlines, and
|
||||
active-operation lease renewals can remain local to their transports, but
|
||||
must have explicit start/stop ownership and participate in sleep blocking.
|
||||
Browser timers use a separate foreground/activity policy. **Complete when:**
|
||||
exceptions are inventoried and owned; no hidden independent timer can renew
|
||||
an idle connector indefinitely after its scheduler lane is stopped.
|
||||
|
||||
- [ ] **SCH-08 — Make scheduler migration incremental and observable.** Migrate
|
||||
each inventory item below independently. Report pending work, next deadline,
|
||||
active holds, and unknown/unmigrated blockers through local diagnostics.
|
||||
Avoid periodic SQL or remote reporting merely to observe inactivity.
|
||||
**Complete when:** an operator can explain why a stack is awake and a migrated
|
||||
lane can be rolled back without duplicate processing. Preserve the telemetry
|
||||
review rules if any first-party event contract changes.
|
||||
|
||||
## 2. External waker adapter later
|
||||
|
||||
The minimal external model is `(stack, nextWakeTime)`. Operational delivery may
|
||||
also carry a generation/idempotency value and delivery status. It must not
|
||||
require copying every routine, agent configuration, or permission into Cloud.
|
||||
The internal scheduler remains authoritative about what to execute.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
D[Temporal obligations and retry deadlines] --> S[Instance scheduler]
|
||||
S --> L[Local timer while awake]
|
||||
S -->|stack, nextWakeTime, generation| W[External waker adapter]
|
||||
W --> G[Wake-aware ingress or provider wake]
|
||||
U[User request or webhook] --> G
|
||||
G -->|Reconcile due deadlines on wake| S
|
||||
G -->|Verified request or event| H
|
||||
L --> H[Existing domain handlers]
|
||||
S --> H
|
||||
```
|
||||
|
||||
- [ ] **WAKE-01 — Define the adapter and local-only behavior.** Support
|
||||
setting/replacing and cancelling the next alarm. No external adapter is
|
||||
required to use the internal scheduler. **Complete when:** timed work remains
|
||||
local and the instance remains awake if no durable external wake is available;
|
||||
introducing the internal scheduler alone never authorizes sleeping through a
|
||||
deadline.
|
||||
|
||||
- [ ] **WAKE-02 — Make alarm publication durable and acknowledge it before sleep.**
|
||||
Persist publication intent/generation or use an equivalent recoverable
|
||||
handshake. Recheck that the acknowledged alarm still covers the earliest
|
||||
deadline before sleeping. **Complete when:** failure, lost responses, and a
|
||||
concurrently moved-earlier deadline keep the instance awake until covered;
|
||||
local scheduling continues during external-waker outages.
|
||||
|
||||
- [ ] **WAKE-03 — Handle duplicate, stale, delayed, and missed wake delivery.**
|
||||
Fence stale generations, retry failed delivery, reconcile due work after
|
||||
wake, and retain domain-level atomic claims. **Complete when:** a repeated
|
||||
doorbell does not duplicate work, and missed deadlines follow each domain's
|
||||
explicit catch-up policy. Do not claim exactly-once network delivery.
|
||||
|
||||
- [ ] **WAKE-04 — Serialize ingress, sleep, deploy, and wake.** Buffer or retry
|
||||
incoming requests while draining; authenticate external control and preserve
|
||||
webhook verification and acknowledgement deadlines. The host must bind its
|
||||
final stop decision to the correct process/provider generation. **Complete
|
||||
when:** requests arriving during sleep entry are neither lost nor admitted
|
||||
into a process being stopped. Multi-replica support requires shared fencing.
|
||||
|
||||
- [ ] **WAKE-05 — Implement and qualify provider adapters.** Evaluate Unikraft
|
||||
scheduled `start` operations and a shared durable delayed-delivery mechanism
|
||||
for Railway. Verify that provider resume actually invokes due-work processing,
|
||||
including stateful resume without process startup. **Complete when:** an
|
||||
isolated instance wakes for its earliest deadline and no waker polls sleeping
|
||||
tenant databases. See [Unikraft scheduled wake-ups](https://unikraft.com/docs/features/cron-jobs).
|
||||
|
||||
- [ ] **WAKE-06 — Protect active background execution on the host.** Connect
|
||||
active-work holds to the provider's sleep controls. Unikraft exposes a
|
||||
reference-counted disable mechanism; account for its signal delay. **Complete
|
||||
when:** startup, transactions, agent control, finalization, and cleanup cannot
|
||||
be suspended halfway through accepted work. See [Unikraft application sleep controls](https://unikraft.com/docs/tutorials/scale-to-zero-triggers).
|
||||
|
||||
- [ ] **WAKE-07 — Validate wake concentration and cost.** Capacity-test concurrent
|
||||
scheduled wakes, apply bounded dispatch, and use jitter only where semantics
|
||||
permit. **Complete when:** scheduler backlog/delivery delay is observable and
|
||||
a midnight burst does not silently skip customer jobs. Avoid periodically
|
||||
waking all tenants just to discover whether any work exists.
|
||||
|
||||
## 3. Database and health
|
||||
|
||||
- [ ] **DB-01 — Qualify the existing idle pool behavior.**
|
||||
[client.ts](../../packages/db/src/client.ts) already defaults
|
||||
`DATABASE_IDLE_TIMEOUT_SECONDS` to 60; `0` disables reaping. Keep the existing
|
||||
Drizzle handle and lazy reconnection; evaluate 30 seconds after pollers become
|
||||
quiet. **Complete when:** idle connections disappear and a subsequent read,
|
||||
write, and transaction work after actual provider suspension without per-route
|
||||
lifecycle code. Existing tests are in
|
||||
[client.test.ts](../../packages/db/src/client.test.ts).
|
||||
|
||||
- [ ] **DB-02 — Preserve disconnect and transaction safety.** `.end()` permanently
|
||||
shuts down the pool and must not become an idle operation. Reconnection does
|
||||
not authorize replaying an interrupted write. **Complete when:** existing
|
||||
transaction isolation after disconnect and explicitly idempotent retry rules
|
||||
still hold; ambiguous commits are not blindly replayed. See
|
||||
[database retry behavior](../DATABASE.md#connection-loss-and-retries).
|
||||
|
||||
- [ ] **DB-03 — Cover every client and socket.** Better Auth shares the main DB;
|
||||
the optional plugin migration pool uses the same idle configuration. Utility,
|
||||
backup, and dedicated advisory-lock connections are bounded work. The audited
|
||||
postgres.js version has a 60-second TCP keepalive; keepalive is not SQL.
|
||||
**Complete when:** all pools can reach zero when idle, reserved/active work is
|
||||
protected, and no new persistent LISTEN or health-ping connection is introduced
|
||||
as a substitute for polling. Sources:
|
||||
[DB client](../../packages/db/src/client.ts),
|
||||
[auth adapter](../../server/src/auth/better-auth.ts),
|
||||
[backup library](../../packages/db/src/backup-lib.ts).
|
||||
|
||||
- [ ] **DB-04 — Split process liveness from DB readiness.** Claimed-instance
|
||||
[health](../../server/src/routes/health.ts) executes `SELECT 1`; auth and deep
|
||||
checks may perform additional queries. Install cheap liveness before session
|
||||
and actor resolution. **Complete when:** normal liveness produces no SQL,
|
||||
explicit deep readiness still tests DB health, and signed claim/bootstrap
|
||||
mutations retain their existing validation and tracking.
|
||||
|
||||
- [ ] **DB-05 — Audit external probes and configured endpoints.** Inspect the
|
||||
fleet gateway, uptime monitors, deployment checks, DB pool settings, and Neon
|
||||
suspend configuration. The [ECS example](../../docker/ecs-task-definition.json)
|
||||
probes every 30 seconds; it is not evidence of Railway fleet behavior.
|
||||
**Complete when:** sleeping is an expected state, repeated checks do not wake
|
||||
tenants or reconnect to Neon, and readiness errors remain distinguishable
|
||||
from intentional sleep. Railway's built-in health checks are deployment-only:
|
||||
[provider documentation](https://docs.railway.com/deployments/healthchecks).
|
||||
|
||||
## 4. Server scheduling migration inventory
|
||||
|
||||
Apply the triage above to each operation within these services. Remove polling
|
||||
from event-driven normal paths and route only real deadlines through the internal
|
||||
scheduler. Preserve durable delivery, startup recovery, and domain-level claims.
|
||||
Longer polling intervals alone do not complete an item.
|
||||
|
||||
- [ ] **JOB-01 — Chat reconciliation.** Current: every **1s**, with multiple
|
||||
runtime/delivery/publication lanes and SQL even without connectors. Change:
|
||||
disarm empty lanes and activate on committed events or deadlines. **Complete
|
||||
when:** a tenant with no chat obligations issues no chat SQL and new inbound,
|
||||
publication, and recovery work still runs. Sources:
|
||||
[app.ts](../../server/src/app.ts),
|
||||
[chat-channels.ts](../../server/src/services/chat-channels.ts).
|
||||
|
||||
- [ ] **JOB-02 — Email reconciliation.** Current: every **1s**, querying active
|
||||
endpoints even when none exist. Change: initialize resource/pending state and
|
||||
update on endpoint changes, webhook receipt, sends, and retries. **Complete
|
||||
when:** empty mail state produces no polling SQL and new work activates the
|
||||
worker without restart. Source:
|
||||
[email-channels.ts](../../server/src/services/email-channels.ts).
|
||||
|
||||
- [ ] **JOB-03 — Browser-use cleanup.** Current: every **3s** with due-session
|
||||
queries even when empty. Change: register actual session reconciliation/expiry
|
||||
deadlines. **Complete when:** no sessions means no queries, while active leases,
|
||||
expiry, and failed cleanup remain recoverable. Sources:
|
||||
[app.ts](../../server/src/app.ts),
|
||||
[browser-use.ts](../../server/src/services/browser-use.ts).
|
||||
|
||||
- [ ] **JOB-04 — Feedback exports.** Current: every **5s**, querying the queue
|
||||
even without a configured share client. Change: committed enqueue signals and
|
||||
durable retries. **Complete when:** empty exports are quiet and queued exports
|
||||
survive restart and temporary delivery failure. Sources:
|
||||
[app.ts](../../server/src/app.ts),
|
||||
[feedback.ts](../../server/src/services/feedback.ts).
|
||||
|
||||
- [ ] **JOB-05 — Public MCP and Dot event dispatch.** Current: **2s** per started
|
||||
dispatcher, including SQL-backed enablement, expiry, and delivery scans.
|
||||
Change: cache capability state and schedule delivery/retry/expiry work.
|
||||
**Complete when:** disabled/empty dispatchers are DB-free and pending events
|
||||
retain subscription scope, expiry, and replay safety. Source:
|
||||
[events.ts](../../server/src/services/public-mcp/events.ts).
|
||||
|
||||
- [ ] **JOB-06 — Execution-control reconciliation.** Current: independent
|
||||
**15s** recovery/delivery lanes, including when the main heartbeat is disabled.
|
||||
Change: activate lanes from durable pending work and deadlines. **Complete
|
||||
when:** empty lanes are quiet and abandoned finalizations, replacements,
|
||||
continuations, status/disposition delivery, and login expiry still recover.
|
||||
Sources: [index.ts](../../server/src/index.ts),
|
||||
[execution-control-deadline.ts](../../server/src/services/execution-control-deadline.ts).
|
||||
|
||||
- [ ] **JOB-07 — Plugin job scheduling.** Current: **30s** SQL even without jobs.
|
||||
Change: register nearest `nextRunAt` and signal registration/update/removal.
|
||||
**Complete when:** empty plugins/jobs produce no scheduler SQL and due jobs
|
||||
retain atomic ownership. The plugin job coordinator itself is event-driven,
|
||||
not another periodic loop. Sources:
|
||||
[plugin-job-scheduler.ts](../../server/src/services/plugin-job-scheduler.ts),
|
||||
[plugin-job-coordinator.ts](../../server/src/services/plugin-job-coordinator.ts).
|
||||
|
||||
- [ ] **JOB-08 — Agent timer heartbeats and issue monitors.** Current: **30s**
|
||||
agent/monitor scans; agent-level disabled heartbeats still require discovery.
|
||||
Change: register each relevant deadline and aggregate locally. **Complete
|
||||
when:** no timer work means no queries, and due work preserves pause, budget,
|
||||
authorization, and atomic wake admission. Source:
|
||||
[heartbeat.ts](../../server/src/services/heartbeat.ts), `tickTimers`.
|
||||
|
||||
- [ ] **JOB-09 — Routine cron triggers.** Current: **30s** due-trigger query.
|
||||
Change: use existing `nextRunAt` in the internal scheduler. **Complete when:**
|
||||
timezone, catch-up/coalescing, concurrency, project pause, edits, and deletion
|
||||
behave correctly; external waking can be added without relocating routines.
|
||||
Source: [routines.ts](../../server/src/services/routines.ts), `tickScheduledTriggers`.
|
||||
|
||||
- [ ] **JOB-10 — Decision retention and notifications.** Current: every **30s**,
|
||||
builds the complete attention feed for each active company before archiving
|
||||
and delivering notifications. Change: relevant mutation signals, actual
|
||||
retention deadlines, and batched maintenance. **Complete when:** unchanged
|
||||
idle companies do not rebuild feeds and required archive/notification behavior
|
||||
remains timely. Source: [index.ts](../../server/src/index.ts), `runRetentionSweep`.
|
||||
|
||||
- [ ] **JOB-11 — Decision expiry and recovery.** Current: **30s** scans for stuck
|
||||
effects, continuations, and TTLs. Change: schedule their actual deadlines and
|
||||
signal committed effects. **Complete when:** expiration remains authoritative
|
||||
at action time and interrupted effects recover without perpetual empty scans.
|
||||
Source: [decisions.ts](../../server/src/services/decisions.ts), `sweepExpired`.
|
||||
|
||||
- [ ] **JOB-12 — External-object refresh.** Current: **30s** scans, including a
|
||||
DB feature check when disabled. Change: invalidate cached capability on settings
|
||||
changes; register `nextRefreshAt`; use webhook signals where supported.
|
||||
**Complete when:** disabled/empty state is quiet and promised refresh freshness
|
||||
has an owned deadline. Sources:
|
||||
[external-objects.ts](../../server/src/services/external-objects.ts),
|
||||
[instance-settings.ts](../../server/src/services/instance-settings.ts).
|
||||
|
||||
- [ ] **JOB-13 — Status-card evaluation.** Current: **30s**, including a DB
|
||||
feature check when disabled. Change: register `nextEvalAt` and relevant event
|
||||
invalidations. **Complete when:** no capability/due cards means no queries,
|
||||
and evaluation preserves existing assignment and cancellation behavior.
|
||||
Source: [status-cards.ts](../../server/src/services/status-cards.ts).
|
||||
|
||||
- [ ] **JOB-14 — GitHub events and connection continuity.** Current: **30s**
|
||||
connection scans; provider calls depend on configured/due work. Change:
|
||||
webhook-first activation plus explicit poll fallback, credential, and retry
|
||||
deadlines. **Complete when:** empty state is quiet and configured connections
|
||||
retain their delivery and continuity guarantees. Source:
|
||||
[index.ts](../../server/src/index.ts), `scheduleGitHubConnectionEventPoll` and
|
||||
`scheduleGitHubConnectionContinuitySweep`.
|
||||
|
||||
- [ ] **JOB-15 — Merged pull-request confirmations.** Current: **30s** pending
|
||||
confirmation scan, followed by GitHub checks for matching candidates. Change:
|
||||
activate on merge events with bounded polling fallback only while candidates
|
||||
exist. **Complete when:** confirmation resolution remains authorized and
|
||||
restart-safe, with no empty scan. Source:
|
||||
[issue-thread-interactions.ts](../../server/src/services/issue-thread-interactions.ts).
|
||||
|
||||
- [ ] **JOB-16 — Terminal workspace cleanup.** Current: **30s** candidate scans.
|
||||
Change: enqueue from terminal transitions and cooldown deadlines. **Complete
|
||||
when:** empty state is quiet, and cleanup still checks current task state,
|
||||
artifacts, deliveries, and ownership before deleting resources. Source:
|
||||
[execution-workspaces.ts](../../server/src/services/execution-workspaces.ts).
|
||||
|
||||
- [ ] **JOB-17 — Sandbox cleanup and orphan spools.** Current: **30s** scans even
|
||||
when attempts have longer staleness/backoff. Change: durable cleanup queue with
|
||||
next retry, immediate failed-release activation, and provider/fleet backstop.
|
||||
**Complete when:** idle scans stop without leaking paid sandboxes or ignoring
|
||||
malformed/unpersisted spool entries. Source:
|
||||
[heartbeat.ts](../../server/src/services/heartbeat.ts), `sweepPendingCleanupLeases`.
|
||||
|
||||
- [ ] **JOB-18 — Adapter login and setup-token reapers.** Current: **30s**
|
||||
durable-session/lease scans, alongside local one-shot timers. Change: register
|
||||
actual expiry and cleanup retry times. **Complete when:** abandoned logins and
|
||||
interrupted teardown still release sandboxes across restart, without scans
|
||||
when no obligations exist. Source:
|
||||
[index.ts](../../server/src/index.ts), adapter and setup-token reaper wiring.
|
||||
|
||||
- [ ] **JOB-19 — Custom-image setup expiry.** Current: **30s** active-session
|
||||
expiry scans. Change: register `expiresAt` and cleanup attempts. **Complete
|
||||
when:** no sessions means no SQL and expired provider resources are released.
|
||||
Source: [environment-custom-images.ts](../../server/src/services/environment-custom-images.ts).
|
||||
|
||||
- [ ] **JOB-20 — Tool connection health.** Current: **30s** DB inventory;
|
||||
provider probes are conditional. Change: check on use/configuration change,
|
||||
with explicit deadlines for any promised proactive health checks. **Complete
|
||||
when:** quiet connections stop creating empty scans and failures remain
|
||||
visible within the agreed freshness contract. Source:
|
||||
[index.ts](../../server/src/index.ts), `tools.sweepConnectionHealth`.
|
||||
|
||||
- [ ] **JOB-21 — Secret proposals and expired action tokens.** Current: **30s**
|
||||
expiry/cleanup queries. Change: enforce expiry synchronously on use and
|
||||
register required scrub/cleanup deadlines. **Complete when:** idle cleanup
|
||||
does not extend authorization or secret-retention periods. Sources:
|
||||
[secret-proposals.ts](../../server/src/services/secret-proposals.ts),
|
||||
[index.ts](../../server/src/index.ts).
|
||||
|
||||
- [ ] **JOB-22 — Chat completion delivery.** Current: **30s** outbox scan plus
|
||||
an existing postcommit fast path. Change: extend that signal and register
|
||||
retries only while pending. **Complete when:** committed completions survive
|
||||
restart, duplicate activation, and provider failure without empty polling.
|
||||
Source: [index.ts](../../server/src/index.ts).
|
||||
|
||||
- [ ] **JOB-23 — Connection continuation delivery.** Current: **30s** outbox
|
||||
scans. Change: committed signals, retry deadlines, and startup reconciliation.
|
||||
**Complete when:** newly available connections resume eligible work once,
|
||||
preserve execution gates, and have no empty SQL loop. Source:
|
||||
[index.ts](../../server/src/index.ts).
|
||||
|
||||
- [ ] **JOB-24 — Tool action reviews and deliveries.** Current: **30s**
|
||||
review/session/outbox scans. Change: register review expiry and delivery
|
||||
deadlines; activate after committed decisions. **Complete when:** approval,
|
||||
rejection, expiry, and delivery retain authorization and replay protection.
|
||||
Source: [index.ts](../../server/src/index.ts).
|
||||
|
||||
- [ ] **JOB-25 — Question response delivery.** Current: **30s** outbox scans.
|
||||
Change: committed-answer activation, durable retry deadlines, and startup
|
||||
recovery. **Complete when:** responses preserve attempt-generation fencing
|
||||
and recover from delivery failure without polling empty queues. Source:
|
||||
[question-response-delivery.ts](../../server/src/services/question-response-delivery.ts).
|
||||
|
||||
- [ ] **JOB-26 — Cost accounting and decision-model recovery.** Current:
|
||||
**30s** reconciliation even when empty. Change: pending-receipt signals,
|
||||
spool awareness, and durable retries. **Complete when:** no empty queries,
|
||||
but unresolved receipts/reservations remain tracked and cannot be discarded
|
||||
to permit sleep. Source: [heartbeat.ts](../../server/src/services/heartbeat.ts),
|
||||
`reconcileCostAccounting`.
|
||||
|
||||
- [ ] **JOB-27 — Run recovery, scheduled retries, and queued work.** Current:
|
||||
**30s** orphan/retry/queue/stranded-assignment scans. Change: remain responsive
|
||||
while work exists, register retry/control deadlines, and reconcile on startup
|
||||
or wake. **Complete when:** quiet state has no scans and interrupted runs do
|
||||
not duplicate provider work or lose continuation. Source:
|
||||
[index.ts](../../server/src/index.ts), periodic heartbeat recovery chain.
|
||||
|
||||
- [ ] **JOB-28 — Dependencies, task watchdogs, silent runs, and stale locks.**
|
||||
Current: additional **30s** scans. Change: dependency/run transition signals,
|
||||
active-run-only monitoring, actual timeout deadlines, and startup backstops.
|
||||
**Complete when:** recovery remains scoped and fenced, and a completed task
|
||||
still receives any owed watchdog review. Source:
|
||||
[heartbeat.ts](../../server/src/services/heartbeat.ts).
|
||||
|
||||
- [ ] **JOB-29 — Automatic database backups.** Current: enabled by default,
|
||||
typically **hourly**, with separate dump connections. Change: register with
|
||||
the internal scheduler; later assign durable waking or explicitly transfer
|
||||
backup responsibility to managed infrastructure. **Complete when:** backup
|
||||
and restore guarantees are demonstrated, active backup blocks sleep, and a
|
||||
merely configured future backup no longer blocks indefinitely once covered
|
||||
by an external alarm. Source: [index.ts](../../server/src/index.ts).
|
||||
|
||||
- [ ] **JOB-30 — Replace the main tick and its disabled branch.** Current:
|
||||
default **30s** main tick; setting `HEARTBEAT_SCHEDULER_ENABLED=false` still
|
||||
leaves accounting, external-object, cleanup, and GitHub work, plus independent
|
||||
workers. Change: migrate all lanes before retiring aggregate polling.
|
||||
**Complete when:** disabled scheduling semantics remain documented and no
|
||||
legacy fallback quietly reintroduces recurring SQL. Sources:
|
||||
[index.ts](../../server/src/index.ts), [config.ts](../../server/src/config.ts).
|
||||
|
||||
## 5. Connectors and transport lifetime
|
||||
|
||||
- [ ] **NET-01 — AgentMail socket ownership.** Current: outbound WebSocket and
|
||||
**20s** DB lease renewal; its renewal bypasses the top-level background gate.
|
||||
Change: prefer webhook mode for hosted stacks; otherwise retain an awake
|
||||
receiver or use shared durable ingress. **Complete when:** explicit suspend
|
||||
closes all associated timers and message reception/replay still works.
|
||||
Source: [email-channels.ts](../../server/src/services/email-channels.ts).
|
||||
|
||||
- [ ] **NET-02 — AgentMail catch-up.** Current: roughly **one-minute** provider
|
||||
reconciliation even in webhook mode. Change: catch up on wake/connect and at
|
||||
an owned recovery deadline. **Complete when:** checkpoints and deduplication
|
||||
survive lost webhooks, with a defined maximum recovery delay. Source:
|
||||
[email-channels.ts](../../server/src/services/email-channels.ts).
|
||||
|
||||
- [ ] **NET-03 — Discord Gateway.** Current: persistent connection and **5s** DB
|
||||
ownership renewal. Change: keep unsupported stacks awake initially; evaluate
|
||||
a shared ingress worker owning the connection, lease, and durable delivery.
|
||||
**Complete when:** idle tenant sleep does not silently stop timely reception
|
||||
or weaken ownership fencing. Sources:
|
||||
[chat-channels.ts](../../server/src/services/chat-channels.ts),
|
||||
[chat-sdk-runtime.ts](../../server/src/services/chat-sdk-runtime.ts).
|
||||
|
||||
- [ ] **NET-04 — Photon iMessage.** Current: several gRPC subscriptions, **5s**
|
||||
ownership renewal, and **15s** catch-up. Change: explicit transport lifecycle
|
||||
and, where required, shared durable receiving. **Complete when:** resume
|
||||
preserves ordered checkpoints and detects replay/history gaps; stopping the
|
||||
top-level chat loop also retires dependent work safely. Source:
|
||||
[receiver.ts](../../server/src/services/photon/receiver.ts).
|
||||
|
||||
- [ ] **NET-05 — Slack webhook ingress.** Current transport already uses webhook
|
||||
mode. Change: qualify it through wake-aware ingress rather than introducing
|
||||
a persistent receiver. **Complete when:** cold start meets provider timing
|
||||
through durable acknowledgement/retry where necessary, with signature
|
||||
verification, deduplication, and company scope preserved. Source:
|
||||
[chat-sdk-runtime.ts](../../server/src/services/chat-sdk-runtime.ts).
|
||||
|
||||
- [ ] **NET-06 — HTTP idle connections.** Current server keepalive is **185s**
|
||||
to outlive common proxy defaults. Change: explicitly close idle sockets during
|
||||
drain and qualify provider-specific connection policies. **Complete when:**
|
||||
quiet sockets do not prevent intended sleep, and normal proxy reuse does not
|
||||
gain intermittent 502/ECONNRESET failures. Source:
|
||||
[index.ts](../../server/src/index.ts).
|
||||
|
||||
- [ ] **NET-07 — Active execution transports and lease renewals.** Inventory
|
||||
runner/PRP connections, HTTP/2 bridge pings, native/legacy controller leases,
|
||||
terminal SSH keepalives, browser viewport ownership, and per-operation claims.
|
||||
Retain their required cadence during work. **Complete when:** active operations
|
||||
hold the instance awake and unused transports retire; no arbitrary heartbeat
|
||||
disabling is used to manufacture sleep. Sources:
|
||||
[native-session-executor.ts](../../server/src/services/native-runtime/native-session-executor.ts),
|
||||
[legacy-controller-lease.ts](../../server/src/services/legacy-controller-lease.ts),
|
||||
[HTTP/2 bridge](../../packages/adapter-utils/src/http2-bridge-server.ts),
|
||||
[terminal WebSocket](../../server/src/realtime/environment-custom-image-terminal-ws.ts).
|
||||
|
||||
## 6. Browser demand
|
||||
|
||||
These client-side schedules do not run in the server scheduler. Consolidate
|
||||
their activity policy so a parked browser does not create artificial tenant
|
||||
demand. Preserve real-time behavior while a person is actively using the app.
|
||||
|
||||
- [ ] **UI-01 — Live WebSocket and fallback polling.** Hidden tabs already close
|
||||
the main socket; visible tabs receive **30s** pings and use **15s** refetch
|
||||
fallback when disconnected. Change: distinguish intentional sleep from
|
||||
outage and decide whether unattended visible tabs may become inactive.
|
||||
**Complete when:** reconnection does not create a self-wake loop and returning
|
||||
users reconcile missed state. Source:
|
||||
[LiveUpdatesProvider.tsx](../../ui/src/context/LiveUpdatesProvider.tsx).
|
||||
|
||||
- [ ] **UI-02 — Stable page queries.** Current issue views poll at **1–3s**,
|
||||
browser/artifact views at **3–5s**, and agents/costs/reviews/settings at
|
||||
**5–60s**. Change: extend event invalidation and active-work-only fallback;
|
||||
reuse [polling.ts](../../ui/src/lib/polling.ts) and
|
||||
[useSharedPolling.ts](../../ui/src/hooks/useSharedPolling.ts).
|
||||
**Complete when:** idle views stop artificial demand without hiding updates;
|
||||
multiple tabs do not duplicate avoidable work. Starting sources:
|
||||
[IssueDetail.tsx](../../ui/src/pages/IssueDetail.tsx),
|
||||
[Costs.tsx](../../ui/src/pages/Costs.tsx),
|
||||
[useTaskBrowsers.ts](../../ui/src/hooks/useTaskBrowsers.ts).
|
||||
|
||||
- [ ] **UI-03 — Cloud-access error recovery.** Current transient-error retries
|
||||
run every **5s**, explicitly in background tabs; bootstrap has faster polling.
|
||||
Change: visibility/online gating and wake-aware recovery, with bounded
|
||||
bootstrap behavior. **Complete when:** a hidden tab that last received 502/503
|
||||
cannot keep waking its tenant indefinitely. Source:
|
||||
[CloudAccessGate.tsx](../../ui/src/components/CloudAccessGate.tsx).
|
||||
|
||||
- [ ] **UI-04 — Service-worker update checks.** Current update check is
|
||||
**hourly**, regardless of visibility. Change: check on foreground activity or
|
||||
serve shell/update assets from shared static hosting. **Complete when:** a
|
||||
parked hidden tab does not periodically wake its tenant to fetch `/sw.js`.
|
||||
Source: [service-worker-updates.ts](../../ui/src/lib/service-worker-updates.ts).
|
||||
|
||||
- [ ] **UI-05 — Plugin SSE streams.** Current EventSource lacks visibility
|
||||
gating and holds an HTTP response open. Change: explicit visibility/idle
|
||||
lifetime with reconciliation or replay on reconnect. **Complete when:**
|
||||
plugin state remains correct and abandoned streams do not block sleep.
|
||||
Sources: [bridge.ts](../../ui/src/plugins/bridge.ts),
|
||||
[plugin routes](../../server/src/routes/plugins.ts).
|
||||
|
||||
- [ ] **UI-06 — Setup and enrollment polling.** OAuth/chat setup often polls at
|
||||
**1.5–3s**, email setup at **10s**, commonly while pending. Change: keep these
|
||||
responsive during the bounded workflow; stop on terminal state, close, or
|
||||
inactivity with a deliberate resume path. **Complete when:** abandoned setup
|
||||
creates neither permanent demand nor lost completion evidence. Sources:
|
||||
[ConnectionSetupFlow.tsx](../../ui/src/features/connections/ConnectionSetupFlow.tsx),
|
||||
[chat setup](../../ui/src/pages/apps/chat/ChatEndpointSetup.tsx),
|
||||
[email setup](../../ui/src/pages/apps/chat/EmailEndpointSetup.tsx).
|
||||
|
||||
## 7. Lower traffic housekeeping and plugins
|
||||
|
||||
- [ ] **AUX-01 — First-party telemetry.** The **60s** flush returns without
|
||||
sending when its queue is empty. Change: register flush/retry work only when
|
||||
needed and drain or durably retain pending batches. **Complete when:** empty
|
||||
telemetry is network-quiet and delivery semantics remain explicit. Preserve
|
||||
generated-contract, README, and privacy-review requirements for event changes.
|
||||
Sources: [telemetry.ts](../../server/src/telemetry.ts),
|
||||
[telemetry client](../../packages/shared/src/telemetry/client.ts).
|
||||
|
||||
- [ ] **AUX-02 — Optional OpenTelemetry.** No configured OTLP endpoint means a
|
||||
no-op tracer; this is separate from first-party telemetry and the local run
|
||||
log. Change: inspect exporter batching/connection behavior only when enabled;
|
||||
avoid a perpetual stream of idle-maintenance spans. **Complete when:** the
|
||||
endpoint gate remains intact and configured exporters do not defeat intended
|
||||
sleep after their pending work settles. Source:
|
||||
[instrumentation.ts](../../server/src/instrumentation.ts).
|
||||
|
||||
- [ ] **AUX-03 — Plugin log buffer.** The **5s** flush avoids SQL when empty.
|
||||
Change: schedule a bounded flush after the first buffered entry and include
|
||||
pending writes in drain. **Complete when:** no empty timer is needed and log
|
||||
persistence has a defined shutdown/sleep boundary. Source:
|
||||
[plugin-host-services.ts](../../server/src/services/plugin-host-services.ts).
|
||||
|
||||
- [ ] **AUX-04 — Import spools and in-memory status expiry.** Hourly import
|
||||
cleanup already avoids SQL when the local spool is absent/empty. Runtime
|
||||
status expiry is memory-only. Change: use actual deadlines or opportunistic
|
||||
cleanup where timing is not contractual. **Complete when:** neither causes an
|
||||
unnecessary external wake, while retained files and required cleanup remain
|
||||
tracked. Sources:
|
||||
[company-import-transfers.ts](../../server/src/services/company-import-transfers.ts),
|
||||
[index.ts](../../server/src/index.ts).
|
||||
|
||||
- [ ] **AUX-05 — Plugin worker lifecycle.** Enabled plugins can execute arbitrary
|
||||
background work; host timers cannot prove they are quiet. Change: explicit
|
||||
quiesce/resume, scheduled-job registration, ingress ownership, and lazy provider
|
||||
worker startup where appropriate. **Complete when:** supported plugins prove
|
||||
quiescence; unsupported plugins remain a named blocker. Source:
|
||||
[plugin-worker-manager.ts](../../server/src/services/plugin-worker-manager.ts).
|
||||
|
||||
- [ ] **AUX-06 — Verify low-priority and third-party sources at runtime.**
|
||||
Announcements are request-driven with caching; no dedicated periodic server
|
||||
application-update check was found. Plugin log retention has no production
|
||||
caller in the audited revision. **Complete when:** packet traces confirm these
|
||||
classifications and identify any SDK, gRPC, HTTP agent, monitoring, remote
|
||||
client, or plugin traffic omitted by static inspection. Source:
|
||||
[announcement-feed.ts](../../server/src/services/announcement-feed.ts).
|
||||
|
||||
## 8. Sleep eligibility and alternative hosting
|
||||
|
||||
- [ ] **SAFE-01 — Separate claimed inactivity from unclaimed warm standby.**
|
||||
Existing warm standby bypasses SQL and recurring work only for empty,
|
||||
unclaimed instances. Change: add claimed-instance behavior through explicit
|
||||
scheduler/quiescence contracts. **Complete when:** an inactive claimed tenant
|
||||
can become quiet without impersonating an unclaimed tenant or disrupting
|
||||
signed claim handling. Source:
|
||||
[cloud-warm-standby.ts](../../server/src/services/cloud-warm-standby.ts).
|
||||
|
||||
- [ ] **SAFE-02 — Replace conservative blockers one capability at a time.**
|
||||
Current safety blocks every enabled plugin, configured backups, API keys,
|
||||
active routines/connections, nonterminal issues, and many retained records.
|
||||
Change: distinguish current obligations from passive capability/history only
|
||||
when a validated wake/recovery contract exists. **Complete when:** waiting for
|
||||
a human or retaining completed history can permit sleep, while unknown state,
|
||||
cleanup/accounting debt, and unhandled transports remain blockers. Sources:
|
||||
[idle-sleep-safety.ts](../../server/src/services/idle-sleep-safety.ts),
|
||||
[idle-local-work.ts](../../server/src/services/idle-local-work.ts).
|
||||
|
||||
- [ ] **SAFE-03 — Validate cold start and stateful resume.** A snapshot preserves
|
||||
memory, not the validity of external sockets, credentials, or leases. Change:
|
||||
recheck deadlines and ownership on resume, recover stale connections, and
|
||||
avoid replaying uncertain operations. **Complete when:** long sleeps,
|
||||
expired sessions, and remote controller changes produce correct recovery
|
||||
rather than duplicate execution or prolonged ingress rejection.
|
||||
|
||||
- [ ] **HOST-01 — Evaluate colocated PostgreSQL separately.** Public authenticated
|
||||
deployments currently reject an unset `DATABASE_URL` rather than falling back
|
||||
to embedded PostgreSQL. Prototype explicit loopback PostgreSQL or deliberately
|
||||
revise that deployment contract. **Complete when:** persistent storage,
|
||||
backups/restores, upgrades, memory cost, and sleep/resume are qualified, with
|
||||
agent execution isolated from the controller/database. This option does not
|
||||
remove scheduler or wake requirements. Source:
|
||||
[index.ts](../../server/src/index.ts), `assertCloudDatabaseContract`.
|
||||
|
||||
## 9. Delivery order and acceptance
|
||||
|
||||
1. Complete mechanism triage for the selected first slice: normal trigger,
|
||||
producer coverage, durable dispatch, and remaining temporal obligations.
|
||||
2. Ship DB-free health/probe handling and contained event-driven migrations.
|
||||
Measure empty-worker SQL reduction while preserving delivery backstops until
|
||||
their replacements are proven. These changes do not depend on a full scheduler.
|
||||
3. Build the internal scheduler around true deadlines, starting with routines
|
||||
and adding required retry/expiry/maintenance paths. Then add the external-waker
|
||||
adapter and acknowledged alarm protocol before sleeping scheduled workloads.
|
||||
4. Qualify connector transports, plugin lifecycle, browser demand, and provider
|
||||
resume behavior. Expand eligibility only with evidence.
|
||||
|
||||
- [ ] **TEST-01 — Measure an empty claimed tenant.** After startup settles, prove
|
||||
zero app-originated SQL and no unintended outgoing packets, then observe actual
|
||||
Neon and hosting sleep. Use provider/control-plane metrics so measurement
|
||||
itself does not wake the tenant DB. Compare against the original baseline.
|
||||
|
||||
- [ ] **TEST-02 — Prove first-use recovery.** After real sleep, perform an
|
||||
authenticated read, write, and transaction. Verify persistent results, no
|
||||
duplicate effects, and measured end-to-end latency including authentication
|
||||
and database startup.
|
||||
|
||||
- [ ] **TEST-03 — Prove scheduled work.** Exercise routines, a moved-earlier
|
||||
deadline, cancellation, retry, expiry, and maintenance through restart/sleep.
|
||||
Deliver duplicate/stale wakes and simulate external-waker failure. Verify
|
||||
catch-up, claims, and awake fallback.
|
||||
|
||||
- [ ] **TEST-04 — Prove event ingress.** Deliver a verified webhook while asleep
|
||||
and while entering sleep. Exercise a connector with its supported receiver
|
||||
strategy. Verify acknowledgements, replay, company scope, and persistence.
|
||||
|
||||
- [ ] **TEST-05 — Prove active-work protection.** Attempt sleep during a run,
|
||||
transaction, backup, finalization, cleanup attempt, and pending accounting
|
||||
receipt. Verify the intended blocker/hold and safe release after settlement.
|
||||
|
||||
- [ ] **TEST-06 — Prove browser inactivity behavior.** Test hidden tabs,
|
||||
unattended visible tabs, reconnect/error states, plugin streams, and multiple
|
||||
tabs. Verify returning users see reconciled state without an accidental wake
|
||||
storm.
|
||||
|
||||
- [ ] **TEST-07 — Prove crash, ownership, and rollout behavior.** Test a crash
|
||||
around commit/alarm publication, stale drain owner, provider stop racing a
|
||||
deployment, and long stateful suspension. Roll back migrated lanes without
|
||||
duplicate workers. Measure fleet wake concurrency and actual compute savings
|
||||
before broad enablement.
|
||||
|
||||
Each implementation PR should run the smallest relevant checks first and the
|
||||
repository-required verification for its handoff scope. This documentation-only
|
||||
checklist does not claim any provider sleep/wake test has passed.
|
||||
@@ -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(
|
||||
|
||||
@@ -52,11 +52,11 @@
|
||||
"dependencies": {
|
||||
"@paperclipai/adapter-utils": "workspace:*",
|
||||
"picocolors": "^1.1.1",
|
||||
"ws": "^8.21.3"
|
||||
"ws": "^8.22.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@types/ws": "^8.18.2",
|
||||
"typescript": "^7.0.2"
|
||||
},
|
||||
"engines": {
|
||||
|
||||
@@ -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:*",
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -3,6 +3,7 @@ import { drizzle as drizzlePg } from "drizzle-orm/postgres-js";
|
||||
import { readFile, readdir } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import postgres from "postgres";
|
||||
import { installDatabaseWorkSignals } from "./work-signals.js";
|
||||
import * as schema from "./schema/index.js";
|
||||
|
||||
const MIGRATIONS_FOLDER = fileURLToPath(new URL("./migrations", import.meta.url));
|
||||
@@ -268,6 +269,10 @@ export async function withDedicatedDbConnection<T>(db: Db, action: (dedicated: D
|
||||
|
||||
export function createDb(url: string, options?: DatabaseClientOptions) {
|
||||
const resolved = resolveDatabaseClientOptions(options ?? databaseClientOptionsFromEnv());
|
||||
return createDbClient(url, resolved);
|
||||
}
|
||||
|
||||
function createDbClient(url: string, resolved: DatabaseClientOptions, owner?: object) {
|
||||
const sql = postgres(url, postgresJsOptions(resolved));
|
||||
const key = hostPortKeyOrNull(url);
|
||||
if (key) registerClient(key, sql);
|
||||
@@ -275,10 +280,10 @@ export function createDb(url: string, options?: DatabaseClientOptions) {
|
||||
// postgres.js calls that error "write CONNECTION_CLOSED" too, so the
|
||||
// message cannot establish that replay is safe. Leave retries to callers
|
||||
// that know the complete operation is idempotent.
|
||||
const db = drizzlePg(sql, { schema });
|
||||
dedicatedDbFactories.set(db, () => createDb(url, {
|
||||
const db = installDatabaseWorkSignals(drizzlePg(sql, { schema }), owner);
|
||||
dedicatedDbFactories.set(db, () => createDbClient(url, {
|
||||
...resolved, maxConnections: 1, applicationName: "paperclip-workspace-finalization-lock",
|
||||
}));
|
||||
}, db));
|
||||
return db;
|
||||
}
|
||||
|
||||
|
||||
@@ -42,3 +42,5 @@ export { loadWithoutEmbeddedPostgresExitHooks } from "./embedded-postgres-lifecy
|
||||
export { issueRelations } from "./schema/issue_relations.js";
|
||||
export { issueReferenceMentions } from "./schema/issue_reference_mentions.js";
|
||||
export * from "./schema/index.js";
|
||||
|
||||
export { signalDatabaseWork, subscribeDatabaseWork, databaseWorkPending, reconcileDatabaseWork } from "./work-signals.js";
|
||||
@@ -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;
|
||||
File renamed without changes.
+70
-4
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"id": "8e8297b3-1ae2-44d5-8841-f74637ce0395",
|
||||
"id": "d6277736-9c05-4304-8d16-52dc0d2fbaef",
|
||||
"prevId": "af0b2d33-956b-4b12-8d68-8b4e14c991b2",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
@@ -3914,6 +3914,45 @@
|
||||
"notNull": true,
|
||||
"default": "'idle'"
|
||||
},
|
||||
"lifecycle_state": {
|
||||
"name": "lifecycle_state",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'ready'"
|
||||
},
|
||||
"lifecycle_required_plugin_ids": {
|
||||
"name": "lifecycle_required_plugin_ids",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"lifecycle_holds": {
|
||||
"name": "lifecycle_holds",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'[]'::jsonb"
|
||||
},
|
||||
"lifecycle_version": {
|
||||
"name": "lifecycle_version",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 0
|
||||
},
|
||||
"lifecycle_error": {
|
||||
"name": "lifecycle_error",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"lifecycle_operation": {
|
||||
"name": "lifecycle_operation",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"reports_to": {
|
||||
"name": "reports_to",
|
||||
"type": "uuid",
|
||||
@@ -4026,6 +4065,33 @@
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"agents_lifecycle_work_idx": {
|
||||
"name": "agents_lifecycle_work_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "lifecycle_state",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "updated_at",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"agents_company_status_idx": {
|
||||
"name": "agents_company_status_idx",
|
||||
"columns": [
|
||||
@@ -4266,7 +4332,7 @@
|
||||
"checkConstraints": {
|
||||
"ai_connection_defaults_provider_check": {
|
||||
"name": "ai_connection_defaults_provider_check",
|
||||
"value": "\"ai_connection_defaults\".\"provider\" in ('anthropic','openai','openrouter','xai','google','github')"
|
||||
"value": "\"ai_connection_defaults\".\"provider\" in ('anthropic','openai','openrouter','xai','google')"
|
||||
},
|
||||
"ai_connection_defaults_method_check": {
|
||||
"name": "ai_connection_defaults_method_check",
|
||||
@@ -4739,7 +4805,7 @@
|
||||
"checkConstraints": {
|
||||
"ai_provider_defaults_provider_check": {
|
||||
"name": "ai_provider_defaults_provider_check",
|
||||
"value": "\"ai_provider_defaults\".\"provider\" in ('anthropic','openai','openrouter','xai','google','github')"
|
||||
"value": "\"ai_provider_defaults\".\"provider\" in ('anthropic','openai','openrouter','xai','google')"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
@@ -56355,4 +56421,4 @@
|
||||
"schemas": {},
|
||||
"tables": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1409
-13
File diff suppressed because it is too large.
Load diff
+9
-2
@@ -2231,8 +2231,15 @@
|
||||
{
|
||||
"idx": 320,
|
||||
"version": "7",
|
||||
"when": 1791490887469,
|
||||
"tag": "0320_copilot_defaults",
|
||||
"when": 1791497222457,
|
||||
"tag": "0320_daily_onslaught",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 321,
|
||||
"version": "7",
|
||||
"when": 1791497222458,
|
||||
"tag": "0321_copilot_defaults",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { createDb, withDedicatedDbConnection } from "./client.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js";
|
||||
import { databaseWorkPending, installDatabaseWorkSignals, reconcileDatabaseWork, signalDatabaseWork, subscribeDatabaseWork } from "./work-signals.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
(support.supported ? describe : describe.skip)("database work signals", () => {
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
beforeAll(async () => {
|
||||
temporary = await startEmbeddedPostgresTestDatabase("work-signals-");
|
||||
db = createDb(temporary.connectionString);
|
||||
await db.execute(sql`create table work_signal_test (id text primary key)`);
|
||||
}, 90_000);
|
||||
afterAll(async () => { await temporary?.cleanup(); });
|
||||
|
||||
it("defers nested savepoint notifications until the outer commit and preserves return values", async () => {
|
||||
const events: string[] = [];
|
||||
const unsubscribe = subscribeDatabaseWork(db, "nested", event => events.push(event));
|
||||
try {
|
||||
const result = await db.transaction(async tx => {
|
||||
await tx.transaction(async nested => {
|
||||
await signalDatabaseWork(nested, "nested");
|
||||
await nested.execute(sql`insert into work_signal_test values ('nested')`);
|
||||
});
|
||||
expect(events).toEqual(["intent"]);
|
||||
expect(databaseWorkPending(db, "nested")).toBe(true);
|
||||
expect(await db.execute(sql`select * from work_signal_test where id = 'nested'`)).toHaveLength(0);
|
||||
return 123;
|
||||
});
|
||||
expect(result).toBe(123);
|
||||
expect(events).toEqual(["intent", "settled"]);
|
||||
expect(databaseWorkPending(db, "nested")).toBe(false);
|
||||
expect(await db.execute(sql`select * from work_signal_test where id = 'nested'`)).toHaveLength(1);
|
||||
} finally { unsubscribe(); }
|
||||
});
|
||||
|
||||
it("reconciles a rollback without leaving a permanent pending flag", async () => {
|
||||
await expect(db.transaction(async tx => {
|
||||
await signalDatabaseWork(tx, "rollback");
|
||||
await tx.execute(sql`insert into work_signal_test values ('rollback')`);
|
||||
throw new Error("abort");
|
||||
})).rejects.toThrow("abort");
|
||||
await reconcileDatabaseWork(db, "rollback");
|
||||
expect(databaseWorkPending(db, "rollback")).toBe(false);
|
||||
expect(await db.execute(sql`select * from work_signal_test where id = 'rollback'`)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("keeps outer ownership after a caught savepoint rollback", async () => {
|
||||
const events: string[] = [];
|
||||
const unsubscribe = subscribeDatabaseWork(db, "savepoint", event => events.push(event));
|
||||
try {
|
||||
await db.transaction(async tx => {
|
||||
await expect(tx.transaction(async nested => {
|
||||
await signalDatabaseWork(nested, "savepoint");
|
||||
await nested.execute(sql`insert into work_signal_test values ('savepoint')`);
|
||||
throw new Error("rollback savepoint");
|
||||
})).rejects.toThrow("rollback savepoint");
|
||||
expect(databaseWorkPending(db, "savepoint")).toBe(true);
|
||||
expect(events).toEqual(["intent"]);
|
||||
await signalDatabaseWork(tx, "savepoint");
|
||||
await tx.execute(sql`insert into work_signal_test values ('savepoint-retry')`);
|
||||
});
|
||||
expect(events).toEqual(["intent", "intent", "settled"]);
|
||||
expect(databaseWorkPending(db, "savepoint")).toBe(false);
|
||||
} finally { unsubscribe(); }
|
||||
});
|
||||
|
||||
it.each(["commit", "abort"])("does not clear a late %s until PostgreSQL reports a settled transaction", async outcome => {
|
||||
// Inject a lost response at the client boundary while a REAL transaction
|
||||
// remains open on PostgreSQL. The status probe and row visibility are real.
|
||||
const raw = drizzle(db.$client);
|
||||
const transaction = raw.transaction.bind(raw);
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
let wrote!: () => void;
|
||||
const written = new Promise<void>(resolve => { wrote = resolve; });
|
||||
let serverDone!: Promise<unknown>;
|
||||
raw.transaction = ((callback: any) => {
|
||||
serverDone = transaction(async tx => {
|
||||
const result = await callback(tx);
|
||||
wrote();
|
||||
await gate;
|
||||
if (outcome === "abort") throw new Error("server abort");
|
||||
return result;
|
||||
});
|
||||
// Observe rejection immediately; tests await the same result below.
|
||||
void serverDone.catch(() => {});
|
||||
return written.then(() => { throw new Error("lost transaction response"); });
|
||||
}) as typeof raw.transaction;
|
||||
const owner = installDatabaseWorkSignals(raw);
|
||||
const topic = `late-${outcome}`;
|
||||
try {
|
||||
await expect(owner.transaction(async tx => {
|
||||
await signalDatabaseWork(tx, topic);
|
||||
await tx.execute(sql`insert into work_signal_test values (${topic})`);
|
||||
})).rejects.toThrow("lost transaction response");
|
||||
await reconcileDatabaseWork(owner, topic);
|
||||
expect(databaseWorkPending(owner, topic)).toBe(true);
|
||||
expect(await db.execute(sql`select * from work_signal_test where id = ${topic}`)).toHaveLength(0);
|
||||
release(); await serverDone.catch(() => {});
|
||||
await reconcileDatabaseWork(owner, topic);
|
||||
expect(databaseWorkPending(owner, topic)).toBe(false);
|
||||
expect(await db.execute(sql`select * from work_signal_test where id = ${topic}`)).toHaveLength(outcome === "commit" ? 1 : 0);
|
||||
} finally { release(); await serverDone?.catch(() => {}); }
|
||||
});
|
||||
|
||||
it("recovers after a real backend disconnect without replaying the queue write", async () => {
|
||||
await expect(db.transaction(async tx => {
|
||||
await signalDatabaseWork(tx, "disconnect");
|
||||
await tx.execute(sql`insert into work_signal_test values ('disconnect')`);
|
||||
const [{ pid }] = await tx.execute(sql`select pg_backend_pid() as pid`);
|
||||
await db.execute(sql`select pg_terminate_backend(${pid as number})`);
|
||||
await tx.execute(sql`select 1`);
|
||||
})).rejects.toThrow();
|
||||
await reconcileDatabaseWork(db, "disconnect");
|
||||
expect(databaseWorkPending(db, "disconnect")).toBe(false);
|
||||
expect(await db.execute(sql`select * from work_signal_test where id = 'disconnect'`)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("shares notifications with dedicated child pools but isolates unrelated roots and topics", async () => {
|
||||
const listener = vi.fn();
|
||||
const other = createDb(temporary.connectionString);
|
||||
const unsubscribe = subscribeDatabaseWork(db, "dedicated", listener);
|
||||
try {
|
||||
await other.transaction(tx => signalDatabaseWork(tx, "dedicated"));
|
||||
await db.transaction(tx => signalDatabaseWork(tx, "other"));
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
await withDedicatedDbConnection(db, dedicated => dedicated.transaction(tx => signalDatabaseWork(tx, "dedicated")));
|
||||
expect(listener.mock.calls.map(([event]) => event)).toEqual(["intent", "settled"]);
|
||||
} finally { unsubscribe(); await other.$client.end(); }
|
||||
});
|
||||
|
||||
it("never changes transaction success because a listener throws", async () => {
|
||||
const warn = vi.spyOn(process, "emitWarning").mockImplementation(() => {});
|
||||
const unsubscribe = subscribeDatabaseWork(db, "listener", () => { throw new Error("listener"); });
|
||||
try {
|
||||
await expect(db.transaction(async tx => { await signalDatabaseWork(tx, "listener"); return 7; })).resolves.toBe(7);
|
||||
expect(warn).toHaveBeenCalledTimes(2);
|
||||
} finally { unsubscribe(); warn.mockRestore(); }
|
||||
});
|
||||
});
|
||||
|
||||
describe("work signal query boundaries", () => {
|
||||
it("adds no SQL to transactions which do not register queue work", async () => {
|
||||
const execute = vi.fn();
|
||||
const connection = installDatabaseWorkSignals({ execute, transaction: async (callback: any) => callback({ execute, transaction: async () => {} }) });
|
||||
await expect(connection.transaction(async () => 19)).resolves.toBe(19);
|
||||
expect(execute).not.toHaveBeenCalled();
|
||||
});
|
||||
it("fails before the write if XID acquisition fails, without retaining uncertainty", async () => {
|
||||
const execute = vi.fn().mockRejectedValue(new Error("disconnected"));
|
||||
const connection = installDatabaseWorkSignals({ execute, transaction: async (callback: any) => callback({ execute, transaction: async () => {} }) });
|
||||
const write = vi.fn();
|
||||
await expect(connection.transaction(async (tx: any) => { await signalDatabaseWork(tx, "failed"); write(); })).rejects.toThrow("disconnected");
|
||||
expect(write).not.toHaveBeenCalled();
|
||||
expect(databaseWorkPending(connection, "failed")).toBe(false);
|
||||
});
|
||||
it("rejects registration on an autocommit root", async () => {
|
||||
const connection = installDatabaseWorkSignals({ execute: vi.fn(), transaction: vi.fn() });
|
||||
await expect(signalDatabaseWork(connection, "bad")).rejects.toThrow("inside a transaction");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
// Process-local hints about existing durable queues. No SQL triggers, tables,
|
||||
// background timers, or driver query replay. Only opted-in transactions fetch
|
||||
// an XID, so unrelated transactions keep their existing SQL behavior.
|
||||
type Listener = (event: "intent" | "settled") => void;
|
||||
type Transaction = { topics: Set<string>; xid?: Promise<string>; uncertain: boolean };
|
||||
type Scope = { listeners: Map<string, Set<Listener>>; transactions: Set<Transaction>; root: Connection };
|
||||
type Context = { scope: Scope; transaction?: Transaction };
|
||||
type Connection = { transaction: (...args: any[]) => Promise<any>; execute: (...args: any[]) => Promise<any> };
|
||||
const contexts = new WeakMap<object, Context>();
|
||||
|
||||
function publish(scope: Scope, topic: string, event: "intent" | "settled" = "settled") {
|
||||
for (const listener of scope.listeners.get(topic) ?? []) {
|
||||
try { listener(event); }
|
||||
catch (error) { process.emitWarning(`Database work listener failed: ${String(error)}`); }
|
||||
}
|
||||
}
|
||||
|
||||
/** Installed once by createDb; dedicated child pools share their owner's scope. */
|
||||
export function installDatabaseWorkSignals<T extends Connection>(db: T, owner?: object): T {
|
||||
const scope = (owner && contexts.get(owner)?.scope) || { listeners: new Map(), transactions: new Set(), root: db };
|
||||
install(db, { scope });
|
||||
return db;
|
||||
}
|
||||
|
||||
function install(connection: Connection, context: Context) {
|
||||
contexts.set(connection, context);
|
||||
const transaction = connection.transaction;
|
||||
connection.transaction = async function (callback, ...options) {
|
||||
// Nested savepoints belong to the outermost transaction. Even a released
|
||||
// savepoint must not wake a consumer before its parent commits.
|
||||
const state = context.transaction ?? { topics: new Set<string>(), uncertain: false };
|
||||
try {
|
||||
const result = await transaction.call(this, async (tx: Connection) => {
|
||||
install(tx, { scope: context.scope, transaction: state });
|
||||
return callback(tx);
|
||||
}, ...options);
|
||||
if (!context.transaction) context.scope.transactions.delete(state);
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (!context.transaction) {
|
||||
// An XID is known before the first opted-in write can execute. If
|
||||
// acquisition itself failed there cannot be a corresponding write.
|
||||
if (state.xid) state.uncertain = true;
|
||||
else context.scope.transactions.delete(state);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
if (!context.transaction) for (const topic of state.topics) publish(context.scope, topic);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Await BEFORE the queue write, on its transaction. Nested transactions work. */
|
||||
export async function signalDatabaseWork(connection: object, topic: string): Promise<void> {
|
||||
const context = contexts.get(connection);
|
||||
if (!context) return; // Lightweight service test doubles have no DB lifecycle.
|
||||
const state = context.transaction;
|
||||
if (!state) throw new Error("Database work must be registered inside a transaction");
|
||||
state.topics.add(topic);
|
||||
context.scope.transactions.add(state);
|
||||
publish(context.scope, topic, "intent");
|
||||
if (!state.xid) {
|
||||
state.xid = (connection as Connection).execute(sql`select pg_current_xact_id()::text as xid`)
|
||||
.then((rows: { xid: string }[]) => rows[0]!.xid);
|
||||
}
|
||||
// Keep a failed acquisition distinguishable from an uncertain queue write.
|
||||
try { await state.xid; }
|
||||
catch (error) { state.xid = undefined; throw error; }
|
||||
}
|
||||
|
||||
export function databaseWorkPending(owner: object, topic: string): boolean {
|
||||
return [...(contexts.get(owner)?.scope.transactions ?? [])].some(state => state.topics.has(topic));
|
||||
}
|
||||
|
||||
/** Resolve only failed transactions, on a fresh root-pool statement. Call
|
||||
* BEFORE the queue scan so rows from a newly confirmed commit are visible.
|
||||
* NULL means the XID aged out; it can no longer be in progress, so scanning
|
||||
* the durable queue is sufficient even though its outcome is unavailable.
|
||||
*/
|
||||
export async function reconcileDatabaseWork(owner: object, topic: string): Promise<void> {
|
||||
const scope = contexts.get(owner)?.scope;
|
||||
if (!scope) return;
|
||||
for (const state of [...scope.transactions]) {
|
||||
if (!state.uncertain || !state.topics.has(topic) || !state.xid) continue;
|
||||
const xid = await state.xid;
|
||||
const rows = await scope.root.execute(sql`select pg_xact_status(${xid}::xid8) as status`);
|
||||
if (rows[0]?.status === "in progress") continue;
|
||||
if (!rows.length || ![null, "committed", "aborted"].includes(rows[0].status)) {
|
||||
throw new Error("Unexpected database transaction status");
|
||||
}
|
||||
scope.transactions.delete(state);
|
||||
for (const affected of state.topics) publish(scope, affected);
|
||||
}
|
||||
}
|
||||
|
||||
/** Includes intent, outer settlement, and uncertainty-resolution changes. */
|
||||
export function subscribeDatabaseWork(owner: object, topic: string, listener: Listener): () => void {
|
||||
const context = contexts.get(owner);
|
||||
if (!context) throw new Error("Database work subscriptions require createDb");
|
||||
let listeners = context.scope.listeners.get(topic);
|
||||
if (!listeners) context.scope.listeners.set(topic, listeners = new Set());
|
||||
listeners.add(listener);
|
||||
if (databaseWorkPending(owner, topic)) {
|
||||
try { listener("intent"); } catch (error) { process.emitWarning(`Database work listener failed: ${String(error)}`); }
|
||||
}
|
||||
return () => { listeners.delete(listener); };
|
||||
}
|
||||
@@ -6513,17 +6513,23 @@ 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 providerNode = process.platform === "linux" ? join(root, "node") : process.execPath;
|
||||
if (process.platform === "linux") {
|
||||
await cp(process.execPath, providerNode, { dereference: true });
|
||||
await chmod(providerNode, 0o500);
|
||||
expect((await stat(providerNode)).mode & 0o777).toBe(0o500);
|
||||
}
|
||||
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",
|
||||
runnerBinary: defaultCapabilityRunnerdBinary(), stateDirectory: root, runnerFilesystemRoot: root,
|
||||
providerNodeCommand: process.execPath, providerNodeCommandSha256: digest(process.execPath),
|
||||
providerNodeCommand: providerNode, providerNodeCommandSha256: digest(providerNode),
|
||||
acpxSidecarPath: sidecarPath, acpxSidecarSha256: digest(sidecarPath),
|
||||
providerPackAuthorityDigest: `sha256:${"d".repeat(64)}`,
|
||||
lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 },
|
||||
|
||||
@@ -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?(
|
||||
|
||||
@@ -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";
|
||||
@@ -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");
|
||||
|
||||
@@ -1340,6 +1340,7 @@ export const PLUGIN_CAPABILITIES = [
|
||||
"approvals.read",
|
||||
"issue.documents.read",
|
||||
"agents.read",
|
||||
"agents.lifecycle.manage",
|
||||
"goals.read",
|
||||
"goals.create",
|
||||
"goals.update",
|
||||
|
||||
@@ -2858,3 +2858,7 @@ export { updatePrimaryAgentSchema, type UpdatePrimaryAgent, type PrimaryAgentPre
|
||||
export * from "./agent-avatar-upload.js";
|
||||
|
||||
export type { DotBinding, DotInvitation, DotConnection, DotPairing } from "./dot-invitations.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";
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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";
|
||||
@@ -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 });
|
||||
});
|
||||
});
|
||||
@@ -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";
|
||||
@@ -155,8 +154,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);
|
||||
|
||||
@@ -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).
|
||||
|
||||
Generated
+19
-33
@@ -43,7 +43,7 @@ patchedDependencies:
|
||||
hash: 6st5fzvttegjv64llnfegwwpca
|
||||
path: patches/acpx@0.12.0.patch
|
||||
acpx@0.13.1:
|
||||
hash: btis2ixbxfyq422xwpnza3ncle
|
||||
hash: j4huaoi2baejrlq7vdcgzlx54m
|
||||
path: patches/acpx@0.13.1.patch
|
||||
embedded-postgres@18.1.0-beta.16:
|
||||
hash: 55uhvnotpqyiy37rn3pqpukhei
|
||||
@@ -347,15 +347,15 @@ importers:
|
||||
specifier: ^1.1.1
|
||||
version: 1.1.1
|
||||
ws:
|
||||
specifier: ^8.21.3
|
||||
version: 8.21.3
|
||||
specifier: ^8.22.0
|
||||
version: 8.22.0
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^24.0.0
|
||||
version: 24.13.3
|
||||
'@types/ws':
|
||||
specifier: ^8.18.1
|
||||
version: 8.18.1
|
||||
specifier: ^8.18.2
|
||||
version: 8.18.2
|
||||
typescript:
|
||||
specifier: ^7.0.2
|
||||
version: 7.0.2
|
||||
@@ -508,7 +508,7 @@ importers:
|
||||
version: 0.160.0
|
||||
acpx:
|
||||
specifier: 0.13.1
|
||||
version: 0.13.1(patch_hash=btis2ixbxfyq422xwpnza3ncle)
|
||||
version: 0.13.1(patch_hash=j4huaoi2baejrlq7vdcgzlx54m)
|
||||
ajv:
|
||||
specifier: ^8.20.0
|
||||
version: 8.20.0
|
||||
@@ -982,7 +982,7 @@ importers:
|
||||
version: 8.18.0
|
||||
acpx:
|
||||
specifier: 0.13.1
|
||||
version: 0.13.1(patch_hash=btis2ixbxfyq422xwpnza3ncle)
|
||||
version: 0.13.1(patch_hash=j4huaoi2baejrlq7vdcgzlx54m)
|
||||
ai:
|
||||
specifier: 7.0.130
|
||||
version: 7.0.130(zod@4.4.3)
|
||||
@@ -1065,8 +1065,8 @@ importers:
|
||||
specifier: 1.76.1
|
||||
version: 1.76.1
|
||||
ws:
|
||||
specifier: ^8.21.3
|
||||
version: 8.21.3
|
||||
specifier: ^8.22.0
|
||||
version: 8.22.0
|
||||
zod:
|
||||
specifier: ^4.4.3
|
||||
version: 4.4.3
|
||||
@@ -1109,8 +1109,8 @@ importers:
|
||||
specifier: ^7.2.1
|
||||
version: 7.2.1
|
||||
'@types/ws':
|
||||
specifier: ^8.18.1
|
||||
version: 8.18.1
|
||||
specifier: ^8.18.2
|
||||
version: 8.18.2
|
||||
cross-env:
|
||||
specifier: ^10.1.0
|
||||
version: 10.1.0
|
||||
@@ -5349,8 +5349,8 @@ packages:
|
||||
'@types/webxr@0.5.24':
|
||||
resolution: {integrity: sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==}
|
||||
|
||||
'@types/ws@8.18.1':
|
||||
resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
|
||||
'@types/ws@8.18.2':
|
||||
resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==}
|
||||
|
||||
'@typescript/typescript-aix-ppc64@7.0.2':
|
||||
resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==}
|
||||
@@ -8994,18 +8994,6 @@ packages:
|
||||
wrappy@1.0.2:
|
||||
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
|
||||
|
||||
ws@8.21.3:
|
||||
resolution: {integrity: sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==}
|
||||
engines: {node: '>=10.0.0'}
|
||||
peerDependencies:
|
||||
bufferutil: ^4.0.1
|
||||
utf-8-validate: '>=5.0.2'
|
||||
peerDependenciesMeta:
|
||||
bufferutil:
|
||||
optional: true
|
||||
utf-8-validate:
|
||||
optional: true
|
||||
|
||||
ws@8.22.0:
|
||||
resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==}
|
||||
engines: {node: '>=10.0.0'}
|
||||
@@ -10160,11 +10148,11 @@ snapshots:
|
||||
'@discordjs/rest': 2.6.3
|
||||
'@discordjs/util': 1.2.0
|
||||
'@sapphire/async-queue': 1.5.5
|
||||
'@types/ws': 8.18.1
|
||||
'@types/ws': 8.18.2
|
||||
'@vladfrangu/async_event_emitter': 2.4.7
|
||||
discord-api-types: 0.38.55
|
||||
tslib: 2.8.1
|
||||
ws: 8.21.3
|
||||
ws: 8.22.0
|
||||
transitivePeerDependencies:
|
||||
- bufferutil
|
||||
- utf-8-validate
|
||||
@@ -12723,9 +12711,9 @@ snapshots:
|
||||
'@slack/logger': 4.0.1
|
||||
'@slack/web-api': 7.19.0
|
||||
'@types/node': 24.13.3
|
||||
'@types/ws': 8.18.1
|
||||
'@types/ws': 8.18.2
|
||||
eventemitter3: 5.0.4
|
||||
ws: 8.21.3
|
||||
ws: 8.22.0
|
||||
transitivePeerDependencies:
|
||||
- bufferutil
|
||||
- debug
|
||||
@@ -13310,7 +13298,7 @@ snapshots:
|
||||
|
||||
'@types/webxr@0.5.24': {}
|
||||
|
||||
'@types/ws@8.18.1':
|
||||
'@types/ws@8.18.2':
|
||||
dependencies:
|
||||
'@types/node': 24.13.3
|
||||
|
||||
@@ -13503,7 +13491,7 @@ snapshots:
|
||||
- bare-buffer
|
||||
- react-native-b4a
|
||||
|
||||
acpx@0.13.1(patch_hash=btis2ixbxfyq422xwpnza3ncle):
|
||||
acpx@0.13.1(patch_hash=j4huaoi2baejrlq7vdcgzlx54m):
|
||||
dependencies:
|
||||
'@agentclientprotocol/sdk': 1.4.0(zod@4.4.3)
|
||||
commander: 15.0.0
|
||||
@@ -17297,8 +17285,6 @@ snapshots:
|
||||
|
||||
wrappy@1.0.2: {}
|
||||
|
||||
ws@8.21.3: {}
|
||||
|
||||
ws@8.22.0: {}
|
||||
|
||||
wsl-utils@0.1.0:
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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();
|
||||
@@ -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 });
|
||||
}
|
||||
});
|
||||
+2
-2
@@ -106,7 +106,7 @@
|
||||
"smol-toml": "^1.4.2",
|
||||
"ssh2": "^1.17.0",
|
||||
"svix": "1.76.1",
|
||||
"ws": "^8.21.3",
|
||||
"ws": "^8.22.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"bundleDependencies": [
|
||||
@@ -129,7 +129,7 @@
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/sharp": "^0.32.0",
|
||||
"@types/supertest": "^7.2.1",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@types/ws": "^8.18.2",
|
||||
"cross-env": "^10.1.0",
|
||||
"supertest": "^7.0.0",
|
||||
"tsx": "^4.23.15",
|
||||
|
||||
@@ -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)
|
||||
@@ -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: () => ({
|
||||
}) };
|
||||
});
|
||||
@@ -1199,3 +1199,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,29 @@
|
||||
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"]],
|
||||
["pass", ["COPILOT_AUTH_REQUIRED"]], ["fail", ["COPILOT_MODEL_UNAVAILABLE"]],
|
||||
] 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"]],
|
||||
["pass", ["copilot_metadata_verified"]], ["warn", ["copilot_metadata_verified"]],
|
||||
] 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, 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, 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 () => {
|
||||
|
||||
@@ -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(() => ({
|
||||
@@ -317,8 +317,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();
|
||||
@@ -679,6 +679,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);
|
||||
|
||||
@@ -1251,7 +1261,7 @@ describe("agent permission routes", () => {
|
||||
expect.objectContaining({
|
||||
status: "idle",
|
||||
}),
|
||||
{ createdByUserId: "agent-admin-user", claudeLogin: { storedSessionId: null, ownerUserId: "agent-admin-user", applyExistingWithoutClaim: false } },
|
||||
{ createdByUserId: "agent-admin-user", responsibleUserId: "agent-admin-user", claudeLogin: { storedSessionId: null, ownerUserId: "agent-admin-user", applyExistingWithoutClaim: false } },
|
||||
);
|
||||
expect(mockAccessService.setPrincipalPermission).toHaveBeenCalledWith(
|
||||
companyId,
|
||||
@@ -1381,7 +1391,7 @@ describe("agent permission routes", () => {
|
||||
},
|
||||
},
|
||||
}),
|
||||
{ createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
|
||||
{ createdByUserId: "board-user", responsibleUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1417,7 +1427,7 @@ describe("agent permission routes", () => {
|
||||
model: DEFAULT_OPENCODE_LOCAL_MODEL,
|
||||
}),
|
||||
}),
|
||||
{ createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
|
||||
{ createdByUserId: "board-user", responsibleUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1455,7 +1465,7 @@ describe("agent permission routes", () => {
|
||||
model: "anthropic/claude-sonnet-4-5",
|
||||
}),
|
||||
}),
|
||||
{ createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
|
||||
{ createdByUserId: "board-user", responsibleUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1495,7 +1505,7 @@ describe("agent permission routes", () => {
|
||||
},
|
||||
}),
|
||||
{
|
||||
createdByUserId: "board-user",
|
||||
createdByUserId: "board-user", responsibleUserId: "board-user",
|
||||
claudeLogin: {
|
||||
storedSessionId: null,
|
||||
ownerUserId: "board-user",
|
||||
@@ -1516,9 +1526,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({
|
||||
@@ -1534,8 +1545,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",
|
||||
@@ -1556,19 +1566,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,
|
||||
});
|
||||
@@ -1587,7 +1587,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",
|
||||
@@ -1604,19 +1604,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,
|
||||
});
|
||||
@@ -1639,8 +1629,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();
|
||||
});
|
||||
|
||||
@@ -1670,7 +1660,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 () => {
|
||||
@@ -1687,7 +1677,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",
|
||||
}));
|
||||
@@ -1726,7 +1716,7 @@ describe("agent permission routes", () => {
|
||||
expect.objectContaining({
|
||||
defaultEnvironmentId: environmentId,
|
||||
}),
|
||||
{ createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
|
||||
{ createdByUserId: "board-user", responsibleUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1812,7 +1802,7 @@ describe("agent permission routes", () => {
|
||||
adapterType: adapterCase.adapterType,
|
||||
defaultEnvironmentId: environmentId,
|
||||
}),
|
||||
{ createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
|
||||
{ createdByUserId: "board-user", responsibleUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -2291,3 +2281,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");
|
||||
|
||||
@@ -1005,7 +1005,7 @@ describe("agent skill routes", () => {
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
{ createdByUserId: "local-board", claudeLogin: { storedSessionId: null, ownerUserId: "local-board", applyExistingWithoutClaim: false } },
|
||||
{ createdByUserId: "local-board", responsibleUserId: "local-board", claudeLogin: { storedSessionId: null, ownerUserId: "local-board", applyExistingWithoutClaim: false } },
|
||||
);
|
||||
expect(mockTrackAgentCreated).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
@@ -1055,7 +1055,7 @@ describe("agent skill routes", () => {
|
||||
expect.objectContaining({
|
||||
role: "security",
|
||||
}),
|
||||
{ createdByUserId: "local-board", claudeLogin: { storedSessionId: null, ownerUserId: "local-board", applyExistingWithoutClaim: false } },
|
||||
{ createdByUserId: "local-board", responsibleUserId: "local-board", claudeLogin: { storedSessionId: null, ownerUserId: "local-board", applyExistingWithoutClaim: false } },
|
||||
);
|
||||
expect(mockTrackAgentCreated).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
@@ -1491,7 +1491,7 @@ describe("agent skill routes", () => {
|
||||
}),
|
||||
}),
|
||||
{
|
||||
createdByUserId: "local-board",
|
||||
createdByUserId: "local-board", responsibleUserId: "local-board",
|
||||
claudeLogin: {
|
||||
storedSessionId: null,
|
||||
ownerUserId: "local-board",
|
||||
@@ -1575,3 +1575,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),
|
||||
}) };
|
||||
});
|
||||
@@ -117,10 +117,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));
|
||||
const mockSelectAiConnection = vi.hoisted(() => vi.fn(async (_input: unknown) => ({ connectionId: "copilot-connection", grantId: "copilot-grant" })));
|
||||
const mockAiCredential = vi.hoisted(() => vi.fn(async (_selection: unknown) => "synthetic-copilot-token"));
|
||||
@@ -1113,3 +1110,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,8 +67,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",
|
||||
@@ -145,7 +147,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);
|
||||
});
|
||||
|
||||
@@ -161,7 +163,7 @@ describe("approvalService resolution idempotency", () => {
|
||||
expect.objectContaining({
|
||||
adapterConfig: approved.payload.adapterConfig,
|
||||
}),
|
||||
{ createdByUserId: expectedCreator },
|
||||
{ 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" });
|
||||
|
||||
@@ -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, describe, expect, it, vi } from "vitest
|
||||
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;
|
||||
const instructionOperator = { type: "board", userId: "local-board", source: "local_implicit" } as const;
|
||||
async function writeInstructionEntry(agent: { id: string; companyId: string }, entryFile: string, content: string) {
|
||||
@@ -134,9 +154,11 @@ 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);
|
||||
|
||||
afterEach(async () => {
|
||||
await lifecycleWorker.sweep();
|
||||
await db.delete(routineTriggers);
|
||||
await db.delete(routines);
|
||||
await db.delete(issueThreadInteractions);
|
||||
@@ -158,6 +180,7 @@ describeEmbeddedPostgres("built-in agents", () => {
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await lifecycleWorker.stop();
|
||||
await tempDb?.cleanup();
|
||||
});
|
||||
|
||||
@@ -498,7 +521,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,
|
||||
@@ -540,7 +563,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: {
|
||||
@@ -585,7 +608,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",
|
||||
@@ -677,7 +700,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",
|
||||
@@ -715,7 +738,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",
|
||||
@@ -959,7 +982,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",
|
||||
@@ -969,7 +992,7 @@ describeEmbeddedPostgres("built-in agents", () => {
|
||||
permissions: {},
|
||||
});
|
||||
|
||||
await expect(agentService(db).create(companyId, {
|
||||
await expect(createAgentLifecycle(db).requestHire(companyId, {
|
||||
name: "Spoof",
|
||||
role: "engineer",
|
||||
status: "idle",
|
||||
@@ -1222,7 +1245,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",
|
||||
@@ -1297,7 +1320,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",
|
||||
@@ -1409,9 +1432,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",
|
||||
@@ -1434,7 +1483,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,
|
||||
@@ -1462,7 +1512,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",
|
||||
@@ -1515,7 +1565,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",
|
||||
@@ -1524,7 +1575,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,5 @@
|
||||
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
|
||||
import { subscribeDeliveryWork, DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, asc, eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
@@ -7,7 +9,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro
|
||||
import { settleInterruptedNativeBootstrap, terminalizeLegacyExecution } from "../services/legacy-execution-recovery.js";
|
||||
import { getExecutionBlocker } from "../services/execution-blocker.js";
|
||||
import { settleUnrecoverableExecutions } from "../services/execution-recovery-resolution.js";
|
||||
import { issueService } from "../services/issues.js";
|
||||
import { executeIssuePostCommitActions, type IssuePostCommitAction, issueService } from "../services/issues.js";
|
||||
import { buildLowTrustSourceTrust } from "../services/source-trust.js";
|
||||
import { documentService } from "../services/documents.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
@@ -51,6 +53,57 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
};
|
||||
return { companyId, agentId, sourceId, runId, task, create, finish, rows, due, wakeup, service, run };
|
||||
}
|
||||
it("dispatches a committed completion without activity publication and recovers after restart", async () => {
|
||||
const f = await seed();
|
||||
const run = vi.fn(() => f.service.sweepPending());
|
||||
const makeWorker = () => {
|
||||
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => { throw error; } });
|
||||
const worker = coordinator.register(DELIVERY_QUEUES.chatCompletion, { retryMs: 60_000, run, hasPending: f.service.hasPending });
|
||||
return { ...worker, stop: coordinator.stop };
|
||||
};
|
||||
const worker = makeWorker();
|
||||
try {
|
||||
await worker.ready;
|
||||
expect(await f.service.hasPending()).toBe(false);
|
||||
expect(run).toHaveBeenCalledTimes(1);
|
||||
await f.finish(); // Service mutation alone: no route activity callback.
|
||||
await vi.waitFor(() => expect(f.wakeup).toHaveBeenCalledTimes(1));
|
||||
expect(await f.service.hasPending()).toBe(true); // queued receipt still owed
|
||||
} finally { await worker.stop(); }
|
||||
// Admit the first reporting turn; later completions need a new turn.
|
||||
await f.run();
|
||||
// A second task commits while no consumer is registered.
|
||||
const next = await f.create();
|
||||
await f.finish(next.id);
|
||||
const restarted = makeWorker();
|
||||
try {
|
||||
await restarted.ready;
|
||||
expect(f.wakeup).toHaveBeenCalledTimes(2);
|
||||
} finally { await restarted.stop(); }
|
||||
});
|
||||
it("automatically notifies after a caller-owned transaction commits", async () => {
|
||||
const f = await seed();
|
||||
const notified = vi.fn();
|
||||
const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.chatCompletion, notified);
|
||||
try {
|
||||
const actions: IssuePostCommitAction[] = [];
|
||||
await db.transaction(async tx => {
|
||||
await issueService(db).update(f.task.id, { status: "done" }, tx, [], actions);
|
||||
expect(notified).not.toHaveBeenCalled();
|
||||
});
|
||||
expect(notified).toHaveBeenCalledTimes(1);
|
||||
expect(actions).toEqual([]);
|
||||
await executeIssuePostCommitActions(db, actions);
|
||||
expect(notified).toHaveBeenCalledTimes(1);
|
||||
const rolledBack: IssuePostCommitAction[] = [];
|
||||
await expect(db.transaction(async tx => {
|
||||
await issueService(db).update(f.task.id, { status: "todo" }, tx, [], rolledBack);
|
||||
throw new Error("rollback");
|
||||
})).rejects.toThrow("rollback");
|
||||
expect(notified).toHaveBeenCalledTimes(1);
|
||||
expect((await f.rows())[0]?.status).toBe("pending");
|
||||
} finally { unsubscribe(); }
|
||||
});
|
||||
it("records authenticated origins and atomically creates one event per Done transition", async () => {
|
||||
const f = await seed();
|
||||
expect(await db.select().from(handoffs).where(eq(handoffs.taskId, f.task.id))).toMatchObject([{ conversationId: f.sourceId, sessionGeneration: 0 }]);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -122,6 +122,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,
|
||||
}));
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { subscribeDeliveryWork } from "../services/delivery-work-notifications.js";
|
||||
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
@@ -780,7 +782,11 @@ describeEmbeddedPostgres("connectionIntentService", () => {
|
||||
it("recovers a resolution after a failed dispatch and acknowledges an already queued wake exactly once", async () => {
|
||||
const service = connectionIntentService(db);
|
||||
const pending = await service.request(claims, "airtable");
|
||||
const notified = vi.fn();
|
||||
const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.connection, notified);
|
||||
await service.decline(pending.interactionId!, claims.responsible_user_id);
|
||||
unsubscribe();
|
||||
expect(notified).toHaveBeenCalledTimes(1);
|
||||
const wakeup = vi.fn().mockRejectedValueOnce(new Error("simulated crash before durable enqueue"));
|
||||
const deliveries = connectionIntentDeliveryService(db, { wakeup } as never);
|
||||
await expect(deliveries.deliver(pending.interactionId!)).rejects.toThrow("simulated crash");
|
||||
|
||||
@@ -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" });
|
||||
});
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { installDatabaseWorkSignals } from "../../../packages/db/src/work-signals.js";
|
||||
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
|
||||
import { notifyDeliveryWork, DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
|
||||
import { idleWorkSnapshot } from "../services/task-admission.js";
|
||||
|
||||
const coordinators: ReturnType<typeof createDeliveryWorkCoordinator>[] = [];
|
||||
afterEach(async () => { for (const c of coordinators.splice(0)) await c.stop(); vi.useRealTimers(); });
|
||||
function setup() {
|
||||
vi.useFakeTimers();
|
||||
let outcome = "committed";
|
||||
let rejectCommit = false;
|
||||
const execute = vi.fn(async () => [{ xid: "42", status: outcome }]);
|
||||
const owner = installDatabaseWorkSignals({ execute, async transaction(callback: (tx: any) => Promise<any>) {
|
||||
const result = await callback({ execute, transaction: owner.transaction });
|
||||
if (rejectCommit) throw new Error("lost commit reply");
|
||||
return result;
|
||||
} });
|
||||
const canRun = vi.fn(() => true), canReconcile = vi.fn(() => false), onError = vi.fn();
|
||||
const coordinator = createDeliveryWorkCoordinator({ owner, canRun, canReconcile, onError });
|
||||
coordinators.push(coordinator);
|
||||
const enqueue = (queue = DELIVERY_QUEUES.feedback as typeof DELIVERY_QUEUES[keyof typeof DELIVERY_QUEUES]) =>
|
||||
owner.transaction(tx => notifyDeliveryWork(tx, queue));
|
||||
return { owner, canRun, canReconcile, onError, coordinator, enqueue, execute,
|
||||
failCommit: () => { rejectCommit = true; outcome = "in progress"; }, settle: (status = "committed") => { outcome = status; } };
|
||||
}
|
||||
function task() { return { retryMs: 5000, run: vi.fn(async () => {}), hasPending: vi.fn(async () => false) }; }
|
||||
|
||||
describe("delivery work coordinator", () => {
|
||||
it("leaves five empty queues with no deadlines, timers, or periodic queries", async () => {
|
||||
const s = setup();
|
||||
const tasks = Object.values(DELIVERY_QUEUES).map(queue => {
|
||||
const t = task(); return { queue, t, worker: s.coordinator.register(queue, t) };
|
||||
});
|
||||
await Promise.all(tasks.map(t => t.worker.ready));
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
expect(s.coordinator.nextWakeAt()).toBeNull();
|
||||
await vi.advanceTimersByTimeAsync(3_600_000);
|
||||
for (const { queue, t } of tasks) {
|
||||
expect(t.run).toHaveBeenCalledTimes(1);
|
||||
await s.enqueue(queue); await s.enqueue(queue);
|
||||
}
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
for (const { t } of tasks) expect(t.run).toHaveBeenCalledTimes(2);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
});
|
||||
it("does not postpone an already committed wake when another producer starts writing", async () => {
|
||||
const s = setup(), t = task();
|
||||
await s.coordinator.register(DELIVERY_QUEUES.feedback, t).ready;
|
||||
await s.enqueue();
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
const writing = s.owner.transaction(async tx => {
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.feedback);
|
||||
await gate;
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(t.run).toHaveBeenCalledTimes(2);
|
||||
release(); await writing;
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(t.run).toHaveBeenCalledTimes(3);
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
});
|
||||
it("fences unresolved writes until the server settles, then scans and releases the idle hold", async () => {
|
||||
const s = setup(), t = task();
|
||||
await s.coordinator.register(DELIVERY_QUEUES.feedback, t).ready;
|
||||
s.failCommit();
|
||||
await expect(s.enqueue()).rejects.toThrow("lost commit reply");
|
||||
expect(idleWorkSnapshot().active).toBe(1);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(t.run).toHaveBeenCalledTimes(2); // Empty scan cannot clear unresolved write.
|
||||
expect(idleWorkSnapshot().active).toBe(1);
|
||||
expect(s.coordinator.nextWakeAt()).not.toBeNull();
|
||||
s.settle();
|
||||
await vi.advanceTimersByTimeAsync(5001);
|
||||
expect(t.run.mock.calls.length).toBeGreaterThanOrEqual(3);
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
it("retains unresolved intent across coordinator replacement", async () => {
|
||||
const s = setup(), t = task();
|
||||
await s.coordinator.register(DELIVERY_QUEUES.feedback, t).ready;
|
||||
s.failCommit(); await expect(s.enqueue()).rejects.toThrow();
|
||||
await s.coordinator.stop();
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
const replacement = createDeliveryWorkCoordinator({ owner: s.owner, canRun: () => true, onError: vi.fn() });
|
||||
coordinators.push(replacement);
|
||||
await replacement.register(DELIVERY_QUEUES.feedback, t).ready;
|
||||
expect(idleWorkSnapshot().active).toBe(1);
|
||||
s.settle(); await vi.advanceTimersByTimeAsync(5001);
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
expect(replacement.nextWakeAt()).toBeNull();
|
||||
});
|
||||
it("retries pending deliveries and transient failures, then goes quiet", async () => {
|
||||
const s = setup(), t = task();
|
||||
t.run.mockRejectedValueOnce(new Error("database disconnected"));
|
||||
t.hasPending.mockResolvedValueOnce(true);
|
||||
await s.coordinator.register(DELIVERY_QUEUES.feedback, t).ready;
|
||||
expect(s.onError).toHaveBeenCalledTimes(1);
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
expect(t.run).toHaveBeenCalledTimes(3);
|
||||
expect(s.coordinator.nextWakeAt()).toBeNull();
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
});
|
||||
it("does not overlap a sweep or lose a commit during its final pending check", async () => {
|
||||
const s = setup(), t = task();
|
||||
let release!: (pending: boolean) => void;
|
||||
t.hasPending.mockImplementationOnce(() => new Promise(resolve => { release = resolve; }));
|
||||
s.coordinator.register(DELIVERY_QUEUES.connection, t);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await s.enqueue(DELIVERY_QUEUES.connection);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(t.run).toHaveBeenCalledTimes(1);
|
||||
release(false);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(t.run).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("reconciles a rollback during idle drain and releases the empty-queue hold without dispatching", async () => {
|
||||
const s = setup(), t = task();
|
||||
await s.coordinator.register(DELIVERY_QUEUES.feedback, t).ready;
|
||||
s.canRun.mockReturnValue(false);
|
||||
s.canReconcile.mockReturnValue(true);
|
||||
s.failCommit(); await expect(s.enqueue()).rejects.toThrow("lost commit reply");
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(idleWorkSnapshot().active).toBe(1);
|
||||
expect(t.run).toHaveBeenCalledTimes(1);
|
||||
s.settle("aborted");
|
||||
await vi.advanceTimersByTimeAsync(5001);
|
||||
expect(t.run).toHaveBeenCalledTimes(1);
|
||||
expect(t.hasPending).toHaveBeenCalled();
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
expect(s.coordinator.nextWakeAt()).toBeNull();
|
||||
});
|
||||
it("keeps committed pending work recoverable during drain without starting deliveries", async () => {
|
||||
const s = setup(), t = task();
|
||||
await s.coordinator.register(DELIVERY_QUEUES.feedback, t).ready;
|
||||
s.canRun.mockReturnValue(false);
|
||||
s.canReconcile.mockReturnValue(true);
|
||||
t.hasPending.mockResolvedValue(true);
|
||||
await s.enqueue();
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(t.run).toHaveBeenCalledTimes(1);
|
||||
expect(s.coordinator.nextWakeAt()).not.toBeNull();
|
||||
s.canRun.mockReturnValue(true);
|
||||
t.hasPending.mockResolvedValue(false);
|
||||
await vi.advanceTimersByTimeAsync(5001);
|
||||
expect(t.run).toHaveBeenCalledTimes(2);
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
});
|
||||
it("does not query during standby and resumes when admission opens", async () => {
|
||||
const s = setup(), t = task(); s.canRun.mockReturnValue(false);
|
||||
await s.coordinator.register(DELIVERY_QUEUES.toolAction, t).ready;
|
||||
await s.enqueue(DELIVERY_QUEUES.toolAction);
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
expect(t.run).not.toHaveBeenCalled();
|
||||
expect(t.hasPending).not.toHaveBeenCalled();
|
||||
s.canRun.mockReturnValue(true);
|
||||
await vi.advanceTimersByTimeAsync(5001);
|
||||
expect(t.run).toHaveBeenCalledTimes(1);
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
});
|
||||
it("awaits in-flight work on shutdown and releases the subscription for restart", async () => {
|
||||
const s = setup(), t = task();
|
||||
let release!: () => void;
|
||||
t.run.mockImplementationOnce(() => new Promise(resolve => { release = resolve; }));
|
||||
s.coordinator.register(DELIVERY_QUEUES.chatCompletion, t);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
const stopped = vi.fn();
|
||||
const stopping = s.coordinator.stop().then(stopped);
|
||||
await s.enqueue(DELIVERY_QUEUES.chatCompletion);
|
||||
expect(stopped).not.toHaveBeenCalled();
|
||||
release(); await stopping;
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
});
|
||||
it("cancels an abortable delivery before awaiting shutdown", async () => {
|
||||
const s = setup();
|
||||
const hasPending = vi.fn(async () => false);
|
||||
const run = vi.fn((signal: AbortSignal) => new Promise<void>((_resolve, reject) => {
|
||||
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
|
||||
}));
|
||||
s.coordinator.register(DELIVERY_QUEUES.feedback, { retryMs: 5000, run, hasPending });
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await s.coordinator.stop();
|
||||
expect(run.mock.calls[0]?.[0].aborted).toBe(true);
|
||||
expect(hasPending).not.toHaveBeenCalled();
|
||||
expect(s.onError).not.toHaveBeenCalled();
|
||||
expect(idleWorkSnapshot().active).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { subscribeDeliveryWork } from "../services/delivery-work-notifications.js";
|
||||
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
@@ -800,6 +802,8 @@ describeEmbeddedPostgres("feedbackService.saveIssueVote", () => {
|
||||
sessionId,
|
||||
});
|
||||
|
||||
const notified = vi.fn();
|
||||
const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.feedback, notified);
|
||||
await flushingSvc.saveIssueVote({
|
||||
issueId,
|
||||
targetType: "issue_comment",
|
||||
@@ -808,7 +812,12 @@ describeEmbeddedPostgres("feedbackService.saveIssueVote", () => {
|
||||
authorUserId: "user-1",
|
||||
allowSharing: true,
|
||||
});
|
||||
await flushingSvc.flushPendingFeedbackTraces();
|
||||
unsubscribe();
|
||||
expect(notified).toHaveBeenCalledTimes(1);
|
||||
expect(await flushingSvc.hasPendingFeedbackTraces()).toBe(true);
|
||||
// The route and worker may request a flush together after the commit.
|
||||
await Promise.all([flushingSvc.flushPendingFeedbackTraces(), flushingSvc.flushPendingFeedbackTraces()]);
|
||||
expect(await flushingSvc.hasPendingFeedbackTraces()).toBe(false);
|
||||
|
||||
expect(uploadTraceBundle).toHaveBeenCalledTimes(1);
|
||||
const bundle = uploadTraceBundle.mock.calls[0]?.[0] as Record<string, unknown> | undefined;
|
||||
@@ -1152,6 +1161,30 @@ describeEmbeddedPostgres("feedbackService.saveIssueVote", () => {
|
||||
expect(uploadTraceBundle).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("leaves aborted and unstarted exports available for recovery after shutdown", async () => {
|
||||
const first = await seedIssueWithAgentComment();
|
||||
const second = await seedIssueWithAgentComment();
|
||||
const shutdown = new AbortController();
|
||||
const uploadTraceBundle = vi.fn().mockResolvedValue({ objectKey: "saved" })
|
||||
.mockImplementationOnce(async (_bundle, signal: AbortSignal) => {
|
||||
shutdown.abort(new Error("shutdown"));
|
||||
signal.throwIfAborted();
|
||||
});
|
||||
const flushingSvc = feedbackService(db, { shareClient: { uploadTraceBundle } });
|
||||
for (const item of [first, second]) {
|
||||
await flushingSvc.saveIssueVote({ issueId: item.issueId, targetType: "issue_comment",
|
||||
targetId: item.commentId, vote: "up", authorUserId: "user-1", allowSharing: true });
|
||||
}
|
||||
expect(await flushingSvc.flushPendingFeedbackTraces({ signal: shutdown.signal }))
|
||||
.toMatchObject({ attempted: 1, sent: 0, failed: 1 });
|
||||
const rows = await db.select().from(feedbackExports);
|
||||
expect(rows.filter(row => row.status === "failed")).toHaveLength(1);
|
||||
expect(rows.filter(row => row.status === "pending")).toHaveLength(1);
|
||||
expect(await flushingSvc.hasPendingFeedbackTraces()).toBe(true);
|
||||
expect(await flushingSvc.flushPendingFeedbackTraces()).toMatchObject({ attempted: 2, sent: 2, failed: 0 });
|
||||
expect(await flushingSvc.hasPendingFeedbackTraces()).toBe(false);
|
||||
});
|
||||
|
||||
it("marks pending shared traces as failed when no feedback export backend is configured", async () => {
|
||||
const { companyId, issueId, commentId } = await seedIssueWithAgentComment();
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { gunzipSync } from "node:zlib";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createFeedbackTraceShareClientFromConfig } from "../services/feedback-share-client.js";
|
||||
import { FEEDBACK_UPLOAD_TIMEOUT_MS, createFeedbackTraceShareClientFromConfig } from "../services/feedback-share-client.js";
|
||||
|
||||
describe("feedback trace share client", () => {
|
||||
beforeEach(() => {
|
||||
@@ -12,6 +12,7 @@ describe("feedback trace share client", () => {
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("defaults to telemetry.paperclip.ing when no backend url is configured", async () => {
|
||||
@@ -98,4 +99,43 @@ describe("feedback trace share client", () => {
|
||||
expect(parsed.objectKey.endsWith("/export-1.json")).toBe(true);
|
||||
expect(parsed.bundle.envelope).toEqual({ hello: "world" });
|
||||
});
|
||||
it.each(["headers", "body"])("cancels a stalled upload at its deadline while waiting for %s", async phase => {
|
||||
const deadline = new AbortController();
|
||||
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(deadline.signal);
|
||||
let started!: () => void;
|
||||
const waiting = new Promise<void>(resolve => { started = resolve; });
|
||||
vi.mocked(fetch).mockImplementation(async (_url, options) => {
|
||||
const block = () => new Promise<never>((_resolve, reject) => {
|
||||
options!.signal!.addEventListener("abort", () => reject(options!.signal!.reason), { once: true });
|
||||
started();
|
||||
});
|
||||
if (phase === "headers") return block();
|
||||
return { ok: true, json: block } as unknown as Response;
|
||||
});
|
||||
const client = createFeedbackTraceShareClientFromConfig({ feedbackExportBackendUrl: undefined, feedbackExportBackendToken: undefined });
|
||||
const bundle = { companyId: "company", traceId: "trace" } as Parameters<typeof client.uploadTraceBundle>[0];
|
||||
const uploading = client.uploadTraceBundle(bundle);
|
||||
const rejected = expect(uploading).rejects.toThrow("upload deadline");
|
||||
await waiting;
|
||||
expect(timeout).toHaveBeenCalledWith(FEEDBACK_UPLOAD_TIMEOUT_MS);
|
||||
deadline.abort(new Error("upload deadline"));
|
||||
await rejected;
|
||||
});
|
||||
|
||||
it("passes shutdown cancellation through to a pending upload", async () => {
|
||||
const shutdown = new AbortController();
|
||||
let started!: () => void;
|
||||
const waiting = new Promise<void>(resolve => { started = resolve; });
|
||||
vi.mocked(fetch).mockImplementation((_url, options) => new Promise((_resolve, reject) => {
|
||||
options!.signal!.addEventListener("abort", () => reject(options!.signal!.reason), { once: true });
|
||||
started();
|
||||
}));
|
||||
const client = createFeedbackTraceShareClientFromConfig({ feedbackExportBackendUrl: undefined, feedbackExportBackendToken: undefined });
|
||||
const bundle = { companyId: "company", traceId: "trace" } as Parameters<typeof client.uploadTraceBundle>[0];
|
||||
const rejected = expect(client.uploadTraceBundle(bundle, shutdown.signal)).rejects.toThrow("shutdown");
|
||||
await waiting;
|
||||
shutdown.abort(new Error("shutdown"));
|
||||
await rejected;
|
||||
});
|
||||
|
||||
});
|
||||
@@ -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) => ({
|
||||
|
||||
@@ -8,6 +8,7 @@ const mockFeedbackService = vi.hoisted(() => ({
|
||||
listIssueVotesForUser: vi.fn(),
|
||||
listFeedbackTraces: vi.fn(),
|
||||
saveIssueVote: vi.fn(),
|
||||
flushPendingFeedbackTraces: vi.fn(() => new Promise(() => {})),
|
||||
}));
|
||||
|
||||
const mockIssueService = vi.hoisted(() => ({
|
||||
@@ -18,9 +19,6 @@ const mockIssueService = vi.hoisted(() => ({
|
||||
findMentionedAgents: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockFeedbackExportService = vi.hoisted(() => ({
|
||||
flushPendingFeedbackTraces: vi.fn(async () => ({ attempted: 1, sent: 1, failed: 0 })),
|
||||
}));
|
||||
const mockAccessService = vi.hoisted(() => ({
|
||||
canUser: vi.fn(),
|
||||
hasPermission: vi.fn(),
|
||||
@@ -138,7 +136,7 @@ async function createApp(actor: Record<string, unknown>) {
|
||||
(req as any).actor = actor;
|
||||
next();
|
||||
});
|
||||
app.use("/api", issueRoutes({} as any, {} as any, { feedbackExportService: mockFeedbackExportService }));
|
||||
app.use("/api", issueRoutes({} as any, {} as any));
|
||||
const routeErrors: string[] = [];
|
||||
app.locals.routeErrors = routeErrors;
|
||||
app.use((error: unknown, _req: express.Request, _res: express.Response, next: express.NextFunction) => {
|
||||
@@ -152,11 +150,6 @@ async function createApp(actor: Record<string, unknown>) {
|
||||
describe("issue feedback trace routes", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockFeedbackExportService.flushPendingFeedbackTraces.mockResolvedValue({
|
||||
attempted: 1,
|
||||
sent: 1,
|
||||
failed: 0,
|
||||
});
|
||||
mockHeartbeatService.wakeup.mockResolvedValue(undefined);
|
||||
mockHeartbeatService.reportRunActivity.mockResolvedValue(undefined);
|
||||
mockHeartbeatService.getRun.mockResolvedValue(null);
|
||||
@@ -174,7 +167,7 @@ describe("issue feedback trace routes", () => {
|
||||
mockLogActivity.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("flushes a newly shared feedback trace immediately after saving the vote", async () => {
|
||||
it("returns the saved vote without waiting for feedback uploads", async () => {
|
||||
const targetId = "11111111-1111-4111-8111-111111111111";
|
||||
mockIssueService.getById.mockResolvedValue({
|
||||
id: "issue-1",
|
||||
@@ -211,11 +204,9 @@ describe("issue feedback trace routes", () => {
|
||||
});
|
||||
|
||||
expect([200, 201]).toContain(res.status);
|
||||
expect(mockFeedbackExportService.flushPendingFeedbackTraces).toHaveBeenCalledWith({
|
||||
companyId: "company-1",
|
||||
traceId: "trace-1",
|
||||
limit: 1,
|
||||
});
|
||||
expect(mockFeedbackService.saveIssueVote).toHaveBeenCalledTimes(1);
|
||||
expect(mockFeedbackService.flushPendingFeedbackTraces).not.toHaveBeenCalled();
|
||||
|
||||
});
|
||||
|
||||
it("rejects non-board callers before fetching a feedback trace", async () => {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { subscribeDeliveryWork } from "../services/delivery-work-notifications.js";
|
||||
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
@@ -231,11 +233,15 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => {
|
||||
expect(created.payload.questions.map((question) => question.id)).toEqual(["repo", "scope", "hosting"]);
|
||||
expect(await interactionsSvc.create(issue, input, { userId: "local-board" })).toEqual(created);
|
||||
await expect(interactionsSvc.answerQuestions(issue, created.id, { answers: [{ questionId: "repo", optionIds: [], otherText: "https://example.com/repo" }] }, { userId: "local-board" })).rejects.toThrow("requires an answer");
|
||||
const notified = vi.fn();
|
||||
const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.question, notified);
|
||||
const answered = await interactionsSvc.answerQuestions(issue, created.id, { answers: [
|
||||
{ questionId: "repo", optionIds: [], otherText: "https://example.com/repo" },
|
||||
{ questionId: "scope", optionIds: ["all"] },
|
||||
{ questionId: "hosting", optionIds: ["existing", "new"] },
|
||||
] }, { userId: "local-board" });
|
||||
unsubscribe();
|
||||
expect(notified).toHaveBeenCalledTimes(1);
|
||||
expect(answered.status).toBe("answered");
|
||||
});
|
||||
|
||||
@@ -1025,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);
|
||||
|
||||
@@ -208,7 +208,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();
|
||||
@@ -245,12 +247,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
|
||||
@@ -261,18 +258,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()
|
||||
@@ -299,7 +298,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";
|
||||
@@ -256,11 +257,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,
|
||||
|
||||
@@ -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 }]);
|
||||
});
|
||||
|
||||
@@ -44,11 +44,17 @@ const {
|
||||
const completionSweepMock = vi.fn(async () => undefined);
|
||||
const createAppMock = vi.fn(async () => Object.assign((_: unknown, __: unknown) => {}, {
|
||||
locals: {
|
||||
deliveryWork: {
|
||||
register: (_queue: string, task: { run: () => Promise<unknown> }) => ({
|
||||
ready: task.run().catch(() => undefined), wake: vi.fn(),
|
||||
}),
|
||||
stop: vi.fn(async () => {}),
|
||||
},
|
||||
toolGateway: {
|
||||
sweepActionReviews: vi.fn(async () => ({ scanned: 0 })),
|
||||
cleanupExpiredSessions: vi.fn(async () => ({ deletedCount: 0 })),
|
||||
},
|
||||
toolActionDeliveries: { sweepPending: vi.fn(async () => ({ scanned: 0, delivered: 0 })) },
|
||||
toolActionDeliveries: { hasPending: vi.fn(async () => false), sweepPending: vi.fn(async () => ({ scanned: 0, delivered: 0 })) },
|
||||
},
|
||||
}) as never);
|
||||
const createBetterAuthInstanceMock = vi.fn(() => ({}));
|
||||
@@ -133,6 +139,7 @@ const {
|
||||
};
|
||||
const routineServiceFactoryMock = vi.fn(() => routineServiceMock);
|
||||
const feedbackExportServiceMock = {
|
||||
hasPendingFeedbackTraces: vi.fn(async () => false),
|
||||
flushPendingFeedbackTraces: vi.fn(async () => ({ attempted: 0, sent: 0, failed: 0 })),
|
||||
};
|
||||
const feedbackServiceFactoryMock = vi.fn(() => feedbackExportServiceMock);
|
||||
@@ -363,16 +370,18 @@ vi.mock("../services/index.js", () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../services/chat-completion-delivery.js", () => ({ chatCompletionDeliveryService: () => ({ sweepPending: completionSweepMock }) }));
|
||||
vi.mock("../services/chat-completion-delivery.js", () => ({ chatCompletionDeliveryService: () => ({ hasPending: vi.fn(async () => false), sweepPending: completionSweepMock }) }));
|
||||
|
||||
vi.mock("../services/connection-intent-delivery.js", () => ({
|
||||
connectionIntentDeliveryService: vi.fn(() => ({
|
||||
hasPending: vi.fn(async () => false),
|
||||
sweepPending: vi.fn(async () => ({ scanned: 0, failed: 0 })),
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../services/question-response-delivery.js", () => ({
|
||||
questionResponseDeliveryService: vi.fn(() => ({
|
||||
hasPending: vi.fn(async () => false),
|
||||
sweepPending: vi.fn(async () => ({
|
||||
scanned: 0,
|
||||
steered: 0,
|
||||
@@ -675,6 +684,22 @@ describe("startServer feedback export wiring", () => {
|
||||
expect(completionSweepMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps activity-driven completion scans scoped to the changed task", async () => {
|
||||
await startServer();
|
||||
completionSweepMock.mockClear();
|
||||
const { publishLiveEvent } = await import("../services/live-events.js");
|
||||
publishLiveEvent({ companyId: "company-one", type: "activity.logged", payload: {
|
||||
action: "issue.updated", entityId: "task-one",
|
||||
} });
|
||||
expect(completionSweepMock).toHaveBeenCalled();
|
||||
for (const args of completionSweepMock.mock.calls) {
|
||||
expect(args).toEqual([{ companyId: "company-one", taskId: "task-one" }]);
|
||||
}
|
||||
completionSweepMock.mockClear();
|
||||
publishLiveEvent({ companyId: "company-two", type: "activity.logged", payload: { action: "issue.updated" } });
|
||||
expect(completionSweepMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("never invokes the retired review detector at startup or on periodic recovery", async () => {
|
||||
loadConfigMock.mockReturnValue(buildTestConfig({
|
||||
heartbeatSchedulerEnabled: true,
|
||||
|
||||
Loaded 100 of 200 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user