The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
Add durable agent runtime synchronization hooks (#16499)
Nicky Leach9f4a956b9068
diff --git a/cli/src/__tests__/worktree.test.ts b/cli/src/__tests__/worktree.test.tsindex 4396c2716c..d86751f0d2 100644--- a/cli/src/__tests__/worktree.test.ts+++ b/cli/src/__tests__/worktree.test.ts@@ -1823,7 +1823,7 @@ describe("worktree helpers", () => {const seededUsers = await targetDb.select().from(authUsers);expect(seededUsers.some((row) => row.email === "[email protected]")).toBe(true);const restoredEvents = await targetDb.$client`- SELECT id, action FROM resource_lifecycle_events WHERE resource_id = ${legacyAgentId} ORDER BY id+ SELECT id, action FROM resource_lifecycle_events WHERE resource_id = ${legacyAgentId} AND resource_type = 'agent' ORDER BY id`;expect(restoredEvents.map(row => row.action)).toEqual(["pause", "create"]);expect(Number(restoredEvents[1].id)).toBeGreaterThan(Number(restoredEvents[0].id));diff --git a/doc/DATABASE.md b/doc/DATABASE.mdindex 18a686ce79..b6ab2ec8d5 100644--- a/doc/DATABASE.md+++ b/doc/DATABASE.md@@ -950,3 +950,16 @@ This disposable fixture compares the real ownership, recovery-action and statusdelivery queries, including complete positional results and database plans.All data is synthetic. Query timings exclude process liveness probes, HTTP andprovider work.++### Agent runtime synchronization journal++Migration 0347 adds the opt-in `agent_runtime` resource stream. Database triggers+record content-free configuration invalidations and managed file audit events in+`resource_lifecycle_events`. They share the mutation transaction and fail the+mutation if journal insertion fails. An INSERT trigger sends an empty PostgreSQL+notification on `paperclip_plugin_lifecycle` after commit. The host subscribes+only when a ready runtime subscriber is installed. This feature requires a+session-compatible database connection; do not enable it through a transaction+pooler. Reconnection scans the durable journal. Existing process-local work+signals continue to serve other delivery queues. See+[the plugin contract](plugins/AGENT_RUNTIME_SYNC.md).diff --git a/doc/plugins/AGENT_RUNTIME_SYNC.md b/doc/plugins/AGENT_RUNTIME_SYNC.mdnew file mode 100644index 0000000000..c018a96f4b--- /dev/null+++ b/doc/plugins/AGENT_RUNTIME_SYNC.md@@ -0,0 +1,67 @@+# Agent runtime synchronization++Plugins can opt into committed agent runtime changes with+`resourceLifecycle: ["agent_runtime"]` and `events.subscribe`.+Implement `onResourceLifecycle` and handle `update` and `delete`.+Existing agent and project subscriptions do not receive this new resource type.+Manual inbox reads retain both legacy streams regardless of automatic subscriptions.+They include runtime events only when the manifest opts into `agent_runtime`.++An event contains company identity, agent identity in `resourceId`, a numeric+sequence serialized as `id`, and its action. It contains no file contents,+configuration, or credentials. Treat `id` as an opaque decimal revision, not a+JavaScript floating-point value. Delivery is at least once and ordered per agent.+Return `acknowledged` only after external effects finish. Return `retry` after an+unfinished operation, or `deferred` when configuration is missing. Startup,+plugin startup, and configuration changes recover unacknowledged work.++The host records configuration changes at the database mutation boundary. This+covers API saves, rollback, plugin writes, and background writers. No-op updates+and heartbeat accounting do not create runtime work. Instruction edits, file+deletions, restores, and run writeback use the file audit boundary. Pending hires+produce no update until approval. Returning to the ready lifecycle phase requests+synchronization after preparation or resume. Existing agents receive a one-time+baseline when the migration runs. Agent deletion leaves a durable delete event.++PostgreSQL notifications wake the existing durable dispatcher only after commit,+including writes through independent clients. Notifications carry no identifiers+or contents. The journal remains authoritative. The listener scans on connection+and reconnection so a dropped notification does not lose committed work. There+is no recurring empty-inbox poll. Existing retry deadlines still retry failed work.+A process opens one listener connection only after a ready plugin opts into+`agent_runtime`. The database connection must support session-level `LISTEN`;+transaction-mode poolers are not supported for this opt-in feature. Startup waits+for listener registration. It releases the listener after the last runtime+subscriber is disabled or removed. Legacy subscriptions keep process-local work signals.++A plugin that also has `agents.lifecycle.manage` can call+`ctx.agents.getRuntime(agentId, companyId)` from a company-scoped invocation.+Only the enabled, ready plugin selected in that agent's required lifecycle set+can read these inputs. The result supplies the latest runtime revision, the+normalized agent configuration, instruction root and entry filename, and that+plugin's own instance secrets. Instruction paths use the same managed-folder+recovery as the instruction reader. A missing or cross-company agent returns null.+The instruction root identifies host files that the trusted worker can package+through its existing filesystem access. This API grants no arbitrary path reads.+Never expose instance secrets through UI data, logs, plugin state, or agent files.++Re-read current state before external effects. A queued event can be older than+the returned revision. Fence stale revisions at the destination and use its+conditional writes. Current configuration is desired state, not a frozen run+snapshot or permission to change an active provider session. Execution admission+and provider activation keep their existing checks. The private transport consumer+is a separate integration.++Filesystem changes outside Paperclip's managed write APIs do not emit these+hooks. Filesystem publication and the database journal are not one filesystem+transaction. A failed managed write must be repaired through the same API before+claiming synchronization. Upstream repository detection remains owned by the+source integration.++Successful file saves record the current desired state. Identical retries and+already-applied deletions repair a missing journal event if a prior save published+bytes before its database transaction failed. Audit rows carry their runtime+revision, so repeated identical saves against that revision create no audit rows+or events. Later runtime changes invalidate that deduplication. The file API still+returns `changed: false` for identical content and keeps conditional-write checks.+Consumers can skip rewriting content whose hash already matches.diff --git a/maps/agent-access-map/plugins.md b/maps/agent-access-map/plugins.mdindex 2f81f2062e..7e889819ff 100644--- a/maps/agent-access-map/plugins.md+++ b/maps/agent-access-map/plugins.md@@ -56,6 +56,14 @@ own policy and access review.Gaps: Company-scoped configuration value does not turn the instance management routeinto an agent route.+Runtime synchronization is a host-to-plugin contract. An opt-in `agent_runtime`+subscriber receives committed changes through `onResourceLifecycle`. The runtime+reader requires `agents.lifecycle.manage`, the invocation company, and selection+as that agent's owning lifecycle plugin. Disabled and unrelated plugins cannot+read its instance secrets. See [contract](../../doc/plugins/AGENT_RUNTIME_SYNC.md)+and [database regressions](../../server/src/__tests__/agent-runtime-hooks.test.ts).+This does not add an ordinary agent API.+## `contributions`Review: `baseline`.diff --git a/maps/feature-map/plugins.md b/maps/feature-map/plugins.mdindex 5126c080c3..eb48fa23e6 100644--- a/maps/feature-map/plugins.md+++ b/maps/feature-map/plugins.md@@ -51,6 +51,9 @@ Manual: Open the contributed page by navigation and cold deep link, perform a hareload is not a lifecycle action in the plugin manager.- Installing a plugin does not authorize every host capability or external action.+- Runtime synchronization is opt-in and uses durable resource delivery. See+ [the contract](../../doc/plugins/AGENT_RUNTIME_SYNC.md) and+ [database regressions](../../server/src/__tests__/agent-runtime-hooks.test.ts).- Plugin-provided routes are dynamic; this map covers the host lifecycle, not every third-party feature.- Environment-driver plugins also need the [environment](./execution-environments.md) checks.diff --git a/packages/db/src/migrations/0347_flippant_imperial_guard.sql b/packages/db/src/migrations/0347_flippant_imperial_guard.sqlnew file mode 100644index 0000000000..ce64c887a9--- /dev/null+++ b/packages/db/src/migrations/0347_flippant_imperial_guard.sql@@ -0,0 +1,77 @@+ALTER TABLE "resource_lifecycle_events" DROP CONSTRAINT IF EXISTS "resource_lifecycle_events_resource_type_check";--> statement-breakpoint+ALTER TABLE "resource_lifecycle_events" DROP CONSTRAINT IF EXISTS "resource_lifecycle_events_action_check";--> statement-breakpoint+ALTER TABLE "resource_lifecycle_events" ADD CONSTRAINT "resource_lifecycle_events_resource_type_check" CHECK ("resource_lifecycle_events"."resource_type" IN ('agent', 'project', 'agent_runtime'));--> statement-breakpoint+ALTER TABLE "resource_lifecycle_events" ADD CONSTRAINT "resource_lifecycle_events_action_check" CHECK (("resource_lifecycle_events"."resource_type" = 'agent_runtime' AND "resource_lifecycle_events"."action" IN ('update', 'delete')) OR "resource_lifecycle_events"."action" = 'create' OR ("resource_lifecycle_events"."resource_type" = 'project' AND "resource_lifecycle_events"."action" IN ('update', 'archive', 'delete')) OR ("resource_lifecycle_events"."resource_type" = 'agent' AND "resource_lifecycle_events"."action" IN ('pause', 'resume', 'terminate')));+--> statement-breakpoint+CREATE OR REPLACE FUNCTION paperclip_record_agent_runtime(p_company uuid, p_agent uuid) RETURNS bigint+LANGUAGE plpgsql SET search_path = public, pg_temp AS $$+DECLARE revision bigint;+BEGIN+ PERFORM 1 FROM agents WHERE company_id = p_company AND id = p_agent+ AND status NOT IN ('pending_approval', 'terminated') FOR UPDATE;+ IF FOUND THEN+ INSERT INTO resource_lifecycle_events(company_id, resource_type, resource_id, action)+ VALUES (p_company, 'agent_runtime', p_agent, 'update') RETURNING id INTO revision;+ END IF;+ RETURN revision;+END;+$$;+--> statement-breakpoint+CREATE OR REPLACE FUNCTION paperclip_agent_runtime_changed() RETURNS trigger+LANGUAGE plpgsql SET search_path = public, pg_temp AS $$+BEGIN+ IF TG_OP = 'DELETE' THEN+ INSERT INTO resource_lifecycle_events(company_id, resource_type, resource_id, action)+ VALUES (OLD.company_id, 'agent_runtime', OLD.id, 'delete');+ RETURN OLD;+ END IF;+ IF TG_OP = 'UPDATE' AND+ jsonb_build_array(OLD.name, OLD.role, OLD.title, OLD.capabilities, OLD.reports_to, OLD.adapter_type, OLD.adapter_config, OLD.runtime_config, OLD.default_environment_id, OLD.permissions, OLD.metadata, OLD.lifecycle_required_plugin_ids)+ IS NOT DISTINCT FROM+ jsonb_build_array(NEW.name, NEW.role, NEW.title, NEW.capabilities, NEW.reports_to, NEW.adapter_type, NEW.adapter_config, NEW.runtime_config, NEW.default_environment_id, NEW.permissions, NEW.metadata, NEW.lifecycle_required_plugin_ids)+ AND NOT (OLD.status = 'pending_approval' AND NEW.status <> 'pending_approval')+ AND NOT (NEW.lifecycle_state = 'ready' AND OLD.lifecycle_state <> 'ready') THEN+ RETURN NEW;+ END IF;+ PERFORM paperclip_record_agent_runtime(NEW.company_id, NEW.id);+ RETURN NEW;+END;+$$;+--> statement-breakpoint+DROP TRIGGER IF EXISTS paperclip_agent_runtime_changed ON agents;+CREATE TRIGGER paperclip_agent_runtime_changed AFTER INSERT OR UPDATE OR DELETE ON agents+ FOR EACH ROW EXECUTE FUNCTION paperclip_agent_runtime_changed();+--> statement-breakpoint+CREATE OR REPLACE FUNCTION paperclip_agent_runtime_files_changed() RETURNS trigger+LANGUAGE plpgsql SET search_path = public, pg_temp AS $$+DECLARE revision bigint;+BEGIN+ IF NEW.entity_type = 'agent' AND NEW.action IN ('agent.files_updated', 'agent.instructions_path_updated',+ 'agent.instructions_bundle_updated', 'agent.instructions_file_updated', 'agent.instructions_file_deleted', 'plugin.managed_agent.reset') THEN+ revision := paperclip_record_agent_runtime(NEW.company_id, NEW.entity_id::uuid);+ NEW.details := coalesce(NEW.details, '{}'::jsonb) || jsonb_build_object('agentRuntimeRevision', revision::text);+ END IF;+ RETURN NEW;+END;+$$;+--> statement-breakpoint+DROP TRIGGER IF EXISTS paperclip_agent_runtime_files_changed ON activity_log;+CREATE TRIGGER paperclip_agent_runtime_files_changed BEFORE INSERT ON activity_log+ FOR EACH ROW EXECUTE FUNCTION paperclip_agent_runtime_files_changed();+--> statement-breakpoint+CREATE OR REPLACE FUNCTION paperclip_notify_plugin_lifecycle() RETURNS trigger+LANGUAGE plpgsql SET search_path = public, pg_temp AS $$+BEGIN+ PERFORM pg_notify('paperclip_plugin_lifecycle', '');+ RETURN NEW;+END;+$$;+--> statement-breakpoint+DROP TRIGGER IF EXISTS paperclip_notify_plugin_lifecycle ON resource_lifecycle_events;+CREATE TRIGGER paperclip_notify_plugin_lifecycle AFTER INSERT ON resource_lifecycle_events+ FOR EACH ROW WHEN (NEW.resource_type = 'agent_runtime') EXECUTE FUNCTION paperclip_notify_plugin_lifecycle();+--> statement-breakpoint+INSERT INTO resource_lifecycle_events(company_id, resource_type, resource_id, action)+ SELECT company_id, 'agent_runtime', id, 'update' FROM agents a+ WHERE status NOT IN ('pending_approval', 'terminated') AND NOT EXISTS (+ SELECT 1 FROM resource_lifecycle_events e WHERE e.company_id = a.company_id AND e.resource_type = 'agent_runtime' AND e.resource_id = a.id);diff --git a/packages/db/src/migrations/meta/0342_snapshot.json b/packages/db/src/migrations/meta/0347_snapshot.jsonsimilarity index 98%rename from packages/db/src/migrations/meta/0342_snapshot.jsonrename to packages/db/src/migrations/meta/0347_snapshot.jsonindex d29b15d865..bfe2f69dde 100644--- a/packages/db/src/migrations/meta/0342_snapshot.json+++ b/packages/db/src/migrations/meta/0347_snapshot.json@@ -1,6 +1,6 @@{- "id": "e9a4bbc2-b22c-48a1-a74c-f108cd7b20ec",- "prevId": "927d7532-059b-4a4f-846a-5e3445a81891",+ "id": "491a5dd7-2599-4da2-a180-59835521aaaf",+ "prevId": "40048887-b6ac-4334-b77b-6b8fc4b52701","version": "7","dialect": "postgresql","tables": {@@ -4098,6 +4098,12 @@"primaryKey": false,"notNull": false},+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },"created_at": {"name": "created_at","type": "timestamp with time zone",@@ -24974,6 +24980,13 @@"primaryKey": false,"notNull": false},+ "provider_kind": {+ "name": "provider_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'openai_dot'"+ },"generation": {"name": "generation","type": "integer",@@ -25601,6 +25614,18 @@"primaryKey": false,"notNull": false},+ "pending_returned_at": {+ "name": "pending_returned_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "observed_at": {+ "name": "observed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },"source_event_id": {"name": "source_event_id","type": "text",@@ -30685,6 +30710,495 @@"checkConstraints": {},"isRLSEnabled": false},+ "public.grok_bot_dispatches": {+ "name": "grok_bot_dispatches",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "routine_id": {+ "name": "routine_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "binding_id": {+ "name": "binding_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "binding_generation": {+ "name": "binding_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "routine_revision": {+ "name": "routine_revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "assignment_id": {+ "name": "assignment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "source_event_id": {+ "name": "source_event_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "challenge_hash": {+ "name": "challenge_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'prepared'"+ },+ "http_status": {+ "name": "http_status",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "sent_at": {+ "name": "sent_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "acknowledged_at": {+ "name": "acknowledged_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "grok_dispatch_event_uq": {+ "name": "grok_dispatch_event_uq",+ "columns": [+ {+ "expression": "binding_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "binding_generation",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "routine_revision",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_event_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "grok_dispatch_company_status_idx": {+ "name": "grok_dispatch_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "grok_dispatch_assignment_kind_idx": {+ "name": "grok_dispatch_assignment_kind_idx",+ "columns": [+ {+ "expression": "assignment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "grok_bot_dispatches_company_id_companies_id_fk": {+ "name": "grok_bot_dispatches_company_id_companies_id_fk",+ "tableFrom": "grok_bot_dispatches",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "grok_bot_dispatches_routine_id_grok_bot_routines_id_fk": {+ "name": "grok_bot_dispatches_routine_id_grok_bot_routines_id_fk",+ "tableFrom": "grok_bot_dispatches",+ "tableTo": "grok_bot_routines",+ "columnsFrom": [+ "routine_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "grok_bot_dispatches_binding_id_dot_agent_bindings_id_fk": {+ "name": "grok_bot_dispatches_binding_id_dot_agent_bindings_id_fk",+ "tableFrom": "grok_bot_dispatches",+ "tableTo": "dot_agent_bindings",+ "columnsFrom": [+ "binding_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "grok_bot_dispatches_grant_id_mcp_oauth_grants_id_fk": {+ "name": "grok_bot_dispatches_grant_id_mcp_oauth_grants_id_fk",+ "tableFrom": "grok_bot_dispatches",+ "tableTo": "mcp_oauth_grants",+ "columnsFrom": [+ "grant_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "grok_bot_dispatches_assignment_id_dot_runner_assignments_id_fk": {+ "name": "grok_bot_dispatches_assignment_id_dot_runner_assignments_id_fk",+ "tableFrom": "grok_bot_dispatches",+ "tableTo": "dot_runner_assignments",+ "columnsFrom": [+ "assignment_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.grok_bot_routines": {+ "name": "grok_bot_routines",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "binding_id": {+ "name": "binding_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "binding_generation": {+ "name": "binding_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "bot_name": {+ "name": "bot_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "secret_id": {+ "name": "secret_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "secret_version": {+ "name": "secret_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "verified_grant_id": {+ "name": "verified_grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "verified_at": {+ "name": "verified_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_contact_at": {+ "name": "last_contact_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "recovery_required_at": {+ "name": "recovery_required_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "recovery_reason": {+ "name": "recovery_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "grok_routines_binding_uq": {+ "name": "grok_routines_binding_uq",+ "columns": [+ {+ "expression": "binding_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "grok_routines_company_agent_idx": {+ "name": "grok_routines_company_agent_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "grok_bot_routines_company_id_companies_id_fk": {+ "name": "grok_bot_routines_company_id_companies_id_fk",+ "tableFrom": "grok_bot_routines",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "grok_bot_routines_agent_id_agents_id_fk": {+ "name": "grok_bot_routines_agent_id_agents_id_fk",+ "tableFrom": "grok_bot_routines",+ "tableTo": "agents",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "grok_bot_routines_binding_id_dot_agent_bindings_id_fk": {+ "name": "grok_bot_routines_binding_id_dot_agent_bindings_id_fk",+ "tableFrom": "grok_bot_routines",+ "tableTo": "dot_agent_bindings",+ "columnsFrom": [+ "binding_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "grok_bot_routines_secret_id_company_secrets_id_fk": {+ "name": "grok_bot_routines_secret_id_company_secrets_id_fk",+ "tableFrom": "grok_bot_routines",+ "tableTo": "company_secrets",+ "columnsFrom": [+ "secret_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "grok_bot_routines_verified_grant_id_mcp_oauth_grants_id_fk": {+ "name": "grok_bot_routines_verified_grant_id_mcp_oauth_grants_id_fk",+ "tableFrom": "grok_bot_routines",+ "tableTo": "mcp_oauth_grants",+ "columnsFrom": [+ "verified_grant_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },"public.heartbeat_run_events": {"name": "heartbeat_run_events","schema": "",@@ -32014,6 +32528,54 @@"concurrently": false,"method": "btree","with": {}+ },+ "heartbeat_runs_company_ctx_paperclip_issue_created_idx": {+ "name": "heartbeat_runs_company_ctx_paperclip_issue_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "(\"context_snapshot\" -> 'paperclipIssue' ->> 'id')",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": true,+ "method": "btree",+ "with": {}+ },+ "heartbeat_runs_company_origin_issue_idx": {+ "name": "heartbeat_runs_company_origin_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "coalesce(\n \"native_issue_id\"::text,\n nullif(\"context_snapshot\"->>'issueId', ''),\n nullif(\"context_snapshot\"->>'taskId', ''),\n nullif(\"context_snapshot\"->>'taskKey', '')\n )",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": true,+ "method": "btree",+ "with": {}}},"foreignKeys": {@@ -46599,11 +47161,11 @@"checkConstraints": {"resource_lifecycle_events_resource_type_check": {"name": "resource_lifecycle_events_resource_type_check",- "value": "\"resource_lifecycle_events\".\"resource_type\" IN ('agent', 'project')"+ "value": "\"resource_lifecycle_events\".\"resource_type\" IN ('agent', 'project', 'agent_runtime')"},"resource_lifecycle_events_action_check": {"name": "resource_lifecycle_events_action_check",- "value": "\"resource_lifecycle_events\".\"action\" = 'create' OR (\"resource_lifecycle_events\".\"resource_type\" = 'project' AND \"resource_lifecycle_events\".\"action\" IN ('update', 'archive', 'delete')) OR (\"resource_lifecycle_events\".\"resource_type\" = 'agent' AND \"resource_lifecycle_events\".\"action\" IN ('pause', 'resume', 'terminate'))"+ "value": "(\"resource_lifecycle_events\".\"resource_type\" = 'agent_runtime' AND \"resource_lifecycle_events\".\"action\" IN ('update', 'delete')) OR \"resource_lifecycle_events\".\"action\" = 'create' OR (\"resource_lifecycle_events\".\"resource_type\" = 'project' AND \"resource_lifecycle_events\".\"action\" IN ('update', 'archive', 'delete')) OR (\"resource_lifecycle_events\".\"resource_type\" = 'agent' AND \"resource_lifecycle_events\".\"action\" IN ('pause', 'resume', 'terminate'))"}},"isRLSEnabled": false@@ -58432,6 +58994,18 @@"name": "mcp_attachment_uploads","schema": "","columns": {+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "work_session_id": {+ "name": "work_session_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },"id": {"name": "id","type": "uuid",@@ -58576,6 +59150,19 @@}},"foreignKeys": {+ "mcp_attachment_uploads_grant_id_mcp_oauth_grants_id_fk": {+ "name": "mcp_attachment_uploads_grant_id_mcp_oauth_grants_id_fk",+ "tableFrom": "mcp_attachment_uploads",+ "tableTo": "mcp_oauth_grants",+ "columnsFrom": [+ "grant_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },"mcp_attachment_uploads_company_id_companies_id_fk": {"name": "mcp_attachment_uploads_company_id_companies_id_fk","tableFrom": "mcp_attachment_uploads",@@ -59052,6 +59639,12 @@"name": "mcp_file_tickets","schema": "","columns": {+ "work_session_id": {+ "name": "work_session_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },"token_hash": {"name": "token_hash","type": "text",diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.jsonindex 00a90de13c..fd5469a18c 100644--- a/packages/db/src/migrations/meta/_journal.json+++ b/packages/db/src/migrations/meta/_journal.json@@ -2416,6 +2416,13 @@"when": 1791989860950,"tag": "0346_cloudy_whiplash","breakpoints": true+ },+ {+ "idx": 347,+ "version": "7",+ "when": 1792100545989,+ "tag": "0347_flippant_imperial_guard",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/src/schema/resource_lifecycle_events.ts b/packages/db/src/schema/resource_lifecycle_events.tsindex d107f7f1f7..8ae05bd641 100644--- a/packages/db/src/schema/resource_lifecycle_events.ts+++ b/packages/db/src/schema/resource_lifecycle_events.ts@@ -6,7 +6,7 @@ import { companies } from "./companies.js";export const resourceLifecycleEvents = pgTable("resource_lifecycle_events", {id: bigint("id", { mode: "number" }).primaryKey().generatedAlwaysAsIdentity(),companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),- resourceType: text("resource_type").$type<"agent" | "project">().notNull(),+ resourceType: text("resource_type").$type<"agent" | "project" | "agent_runtime">().notNull(),resourceId: uuid("resource_id").notNull(),action: text("action").$type<"create" | "update" | "archive" | "delete" | "pause" | "resume" | "terminate">().notNull(),createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),@@ -14,6 +14,6 @@ export const resourceLifecycleEvents = pgTable("resource_lifecycle_events", {resourceIdx: uniqueIndex("resource_lifecycle_events_creation_idx").on(table.companyId, table.resourceType, table.resourceId).where(sql`${table.action} = 'create'`),companyIdx: index("resource_lifecycle_events_company_idx").on(table.companyId, table.id),resourceOrderIdx: index("resource_lifecycle_events_resource_order_idx").on(table.companyId, table.resourceType, table.resourceId, table.id),- resourceTypeCheck: check("resource_lifecycle_events_resource_type_check", sql`${table.resourceType} IN ('agent', 'project')`),- actionCheck: check("resource_lifecycle_events_action_check", sql`${table.action} = 'create' OR (${table.resourceType} = 'project' AND ${table.action} IN ('update', 'archive', 'delete')) OR (${table.resourceType} = 'agent' AND ${table.action} IN ('pause', 'resume', 'terminate'))`),+ resourceTypeCheck: check("resource_lifecycle_events_resource_type_check", sql`${table.resourceType} IN ('agent', 'project', 'agent_runtime')`),+ actionCheck: check("resource_lifecycle_events_action_check", sql`(${table.resourceType} = 'agent_runtime' AND ${table.action} IN ('update', 'delete')) OR ${table.action} = 'create' OR (${table.resourceType} = 'project' AND ${table.action} IN ('update', 'archive', 'delete')) OR (${table.resourceType} = 'agent' AND ${table.action} IN ('pause', 'resume', 'terminate'))`),}));diff --git a/packages/plugins/sdk/src/host-client-factory.ts b/packages/plugins/sdk/src/host-client-factory.tsindex ce90ceeaf7..6c34d6c5b9 100644--- a/packages/plugins/sdk/src/host-client-factory.ts+++ b/packages/plugins/sdk/src/host-client-factory.ts@@ -273,6 +273,7 @@ export interface HostServices {/** Provides `agents.list`, `agents.get`, `agents.pause`, `agents.resume`, `agents.invoke`. */agents: {list(params: WorkerToHostMethods["agents.list"][0]): Promise<WorkerToHostMethods["agents.list"][1]>;+ getRuntime?(params: WorkerToHostMethods["agents.getRuntime"][0]): Promise<WorkerToHostMethods["agents.getRuntime"][1]>;get(params: WorkerToHostMethods["agents.get"][0]): Promise<WorkerToHostMethods["agents.get"][1]>;pause(params: WorkerToHostMethods["agents.pause"][0]): Promise<WorkerToHostMethods["agents.pause"][1]>;resume(params: WorkerToHostMethods["agents.resume"][0]): Promise<WorkerToHostMethods["agents.resume"][1]>;@@ -491,6 +492,7 @@ const METHOD_CAPABILITY_MAP: Record<WorkerToHostMethodName, PluginCapability | n// Agents"agents.list": "agents.read","agents.get": "agents.read",+ "agents.getRuntime": "agents.lifecycle.manage","agents.pause": "agents.pause","agents.resume": "agents.resume","agents.invoke": "agents.invoke",@@ -979,6 +981,10 @@ export function createHostClientHandlers("agents.list": gated("agents.list", async (params) => {return services.agents.list(params);}),+ "agents.getRuntime": gated("agents.getRuntime", async (params) => {+ if (!services.agents.getRuntime) throw new Error("Agent runtime state is unavailable");+ return services.agents.getRuntime(params);+ }),"agents.get": gated("agents.get", async (params) => {return services.agents.get(params);}),diff --git a/packages/plugins/sdk/src/index.ts b/packages/plugins/sdk/src/index.tsindex d6ab601b7a..b966b1b830 100644--- a/packages/plugins/sdk/src/index.ts+++ b/packages/plugins/sdk/src/index.ts@@ -270,6 +270,7 @@ export type {PluginIssueSubtree,PluginIssueSummariesClient,PluginAgentsClient,+ PluginAgentRuntimeState,PluginAccessClient,PluginAccessMembersClient,PluginAccessInvitesClient,diff --git a/packages/plugins/sdk/src/protocol.ts b/packages/plugins/sdk/src/protocol.tsindex cc5d11d154..6e0d1f15e8 100644--- a/packages/plugins/sdk/src/protocol.ts+++ b/packages/plugins/sdk/src/protocol.ts@@ -1,3 +1,4 @@+import type { PluginAgentRuntimeState } from "./types.js";import type { AgentLifecycleRequest, AgentLifecycleResult } from "@paperclipai/shared";import type { AiConnectionRouterRequest, AiConnectionRouterResult } from "@paperclipai/shared";/**@@ -2113,6 +2114,10 @@ export interface WorkerToHostMethods {params: { companyId: string; status?: string; limit?: number; offset?: number },result: Agent[],];+ "agents.getRuntime": [+ params: { agentId: string; companyId: string },+ result: PluginAgentRuntimeState | null,+ ];"agents.get": [params: { agentId: string; companyId: string },result: Agent | null,diff --git a/packages/plugins/sdk/src/testing.ts b/packages/plugins/sdk/src/testing.tsindex 9159c346ce..479bd998d8 100644--- a/packages/plugins/sdk/src/testing.ts+++ b/packages/plugins/sdk/src/testing.ts@@ -2081,6 +2081,10 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {},},agents: {+ async getRuntime() {+ requireCapability(manifest, capabilitySet, "agents.lifecycle.manage");+ throw new Error("Agent runtime state requires a host service fixture");+ },async list(input) {requireCapability(manifest, capabilitySet, "agents.read");const companyId = requireCompanyId(input?.companyId);diff --git a/packages/plugins/sdk/src/types.ts b/packages/plugins/sdk/src/types.tsindex d553744bbb..c79a5698be 100644--- a/packages/plugins/sdk/src/types.ts+++ b/packages/plugins/sdk/src/types.ts@@ -599,6 +599,7 @@ export type ResourceLifecycleEvent = {} & (| { resourceType: "agent"; action: "create" | "pause" | "resume" | "terminate" }| { resourceType: "project"; action: "create" | "update" | "archive" | "delete" }+ | { resourceType: "agent_runtime"; action: "update" | "delete" });/** Return acknowledged only after durable effects finish. Retry unfinished work;@@ -1686,7 +1687,16 @@ export interface PluginApprovalsClient {* Requires `agents.read` for reads; `agents.pause` / `agents.resume` /* `agents.invoke` for write operations.*/+export interface PluginAgentRuntimeState {+ revision: string;+ agent: Agent;+ instructionsRootPath: string | null;+ instructionsEntryFile: string;+ instanceSecrets: Record<string, string>;+}+export interface PluginAgentsClient {+ getRuntime(agentId: string, companyId: string): Promise<PluginAgentRuntimeState | null>;list(input: { companyId: string; status?: Agent["status"]; limit?: number; offset?: number }): Promise<Agent[]>;get(agentId: string, companyId: string): Promise<Agent | null>;/** Pause an agent. Throws if agent is terminated or not found. Requires `agents.pause`. */diff --git a/packages/plugins/sdk/src/worker-rpc-host.ts b/packages/plugins/sdk/src/worker-rpc-host.tsindex 9f08052250..4812054450 100644--- a/packages/plugins/sdk/src/worker-rpc-host.ts+++ b/packages/plugins/sdk/src/worker-rpc-host.ts@@ -1155,6 +1155,9 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost},agents: {+ async getRuntime(agentId, companyId) {+ return callHost("agents.getRuntime", { agentId, companyId });+ },async list(input) {return callHost("agents.list", {companyId: input.companyId,diff --git a/packages/plugins/sdk/tests/host-client-factory.test.ts b/packages/plugins/sdk/tests/host-client-factory.test.tsindex 2c87650af5..31655d3682 100644--- a/packages/plugins/sdk/tests/host-client-factory.test.ts+++ b/packages/plugins/sdk/tests/host-client-factory.test.ts@@ -418,3 +418,20 @@ describe("createHostClientHandlers capability gating for LOOA-641 methods", () =expect(list).not.toHaveBeenCalled();});});+++describe("agent runtime reader", () => {+ it("requires lifecycle capability and the host invocation company before accessing runtime inputs", async () => {+ const getRuntime = vi.fn(async () => null);+ const services = { agents: { getRuntime } } as unknown as HostServices;+ const params = { companyId: "company-a", agentId: "agent-a" };+ const context = { invocationScope: { companyId: "company-a" } };+ const denied = createHostClientHandlers({ pluginId: "runtime", capabilities: ["agents.read"], services });+ await expect(denied["agents.getRuntime"](params, context)).rejects.toBeInstanceOf(CapabilityDeniedError);+ const allowed = createHostClientHandlers({ pluginId: "runtime", capabilities: ["agents.lifecycle.manage"], services });+ await expect(allowed["agents.getRuntime"](params, { invocationScope: { companyId: "other" } })).rejects.toBeInstanceOf(InvocationScopeDeniedError);+ expect(getRuntime).not.toHaveBeenCalled();+ await expect(allowed["agents.getRuntime"](params, context)).resolves.toBeNull();+ expect(getRuntime).toHaveBeenCalledOnce();+ });+});diff --git a/packages/shared/src/types/plugin.ts b/packages/shared/src/types/plugin.tsindex 7a44d3aa7f..384f9e9b4c 100644--- a/packages/shared/src/types/plugin.ts+++ b/packages/shared/src/types/plugin.ts@@ -690,7 +690,7 @@ export interface PaperclipPluginManifestV1 {/** Required participant in agent preparation, stop, resume, and cleanup. */agentLifecycle?: true;/** Durable, acknowledged resource events delivered to onResourceLifecycle. Requires events.subscribe. */- resourceLifecycle?: Array<"agent" | "project">;+ resourceLifecycle?: Array<"agent" | "project" | "agent_runtime">;/** Opt into the native pooled-connection catalog, setup, and management UI. */aiConnectionRouter?: { name: string; description: string };/** Entrypoint paths relative to the package root. */diff --git a/packages/shared/src/validators/plugin.ts b/packages/shared/src/validators/plugin.tsindex 24faa172fb..ca6fa07963 100644--- a/packages/shared/src/validators/plugin.ts+++ b/packages/shared/src/validators/plugin.ts@@ -783,7 +783,7 @@ export const pluginManifestV1Schema = z.object({).optional(),capabilities: z.array(z.enum(PLUGIN_CAPABILITIES)).min(1),agentLifecycle: z.literal(true).optional(),- resourceLifecycle: z.array(z.enum(["agent", "project"])).min(1).max(2).optional(),+ resourceLifecycle: z.array(z.enum(["agent", "project", "agent_runtime"])).min(1).max(3).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),diff --git a/server/src/__tests__/agent-runtime-hooks.test.ts b/server/src/__tests__/agent-runtime-hooks.test.tsnew file mode 100644index 0000000000..3fba2a9575--- /dev/null+++ b/server/src/__tests__/agent-runtime-hooks.test.ts@@ -0,0 +1,260 @@+import { randomUUID } from "node:crypto";+import { createServer, connect, type Socket } from "node:net";+import { EventEmitter } from "node:events";+import fs from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { and, eq, sql } from "drizzle-orm";+import { activityLog, agents, companies, createDb, pluginCompanySettings, pluginConfig, plugins, resourceLifecycleEvents, type Db } from "@paperclipai/db";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";+import { pluginAgentRuntimeState } from "../services/plugin-agent-runtime-state.js";+import { pluginLifecycleInbox } from "../services/plugin-lifecycle-inbox.js";+import { registerPluginLifecycleDelivery } from "../services/plugin-lifecycle-delivery.js";+import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";+import { resolveManagedInstructionsRoot } from "../services/agent-instructions.js";+import { agentFileStore } from "../services/agent-file-store.js";+import { agentInstructionRevisionService } from "../services/agent-instruction-revisions.js";++const support = await getEmbeddedPostgresTestSupport();+const describeDatabase = support.supported ? describe : describe.skip;++describeDatabase("agent runtime synchronization hooks", () => {+ let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;+ let db: Db;+ let companyId: string;+ let pluginId: string;+ let agentId: string;+ let home: string;+ beforeAll(async () => {+ database = await startEmbeddedPostgresTestDatabase("paperclip-agent-runtime-");+ db = createDb(database.connectionString);+ home = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-agent-runtime-home-"));+ }, 90_000);+ afterAll(async () => { await database?.cleanup(); await fs.rm(home, { recursive: true, force: true }); });+ afterEach(() => { vi.unstubAllEnvs(); vi.restoreAllMocks(); });+ beforeEach(async () => {+ vi.stubEnv("PAPERCLIP_HOME", home);+ companyId = randomUUID(); pluginId = randomUUID(); agentId = randomUUID();+ await db.insert(companies).values({ id: companyId, name: "Runtime fixture", issuePrefix: `R${companyId.slice(0, 6)}` });+ await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "runtime-fixture", version: "1.0.0", status: "ready",+ manifestJson: { resourceLifecycle: ["agent_runtime"], capabilities: ["events.subscribe", "agents.lifecycle.manage"] } as never });+ await db.insert(pluginConfig).values({ pluginId, companyId, configJson: {} });+ await db.insert(agents).values({ id: agentId, companyId, name: "Runtime agent", lifecycleRequiredPluginIds: [pluginId] });+ });+ const events = () => db.select().from(resourceLifecycleEvents).where(and(eq(resourceLifecycleEvents.companyId, companyId), eq(resourceLifecycleEvents.resourceType, "agent_runtime"))).orderBy(resourceLifecycleEvents.id);++ it("captures all configuration writers while ignoring no-op and heartbeat bookkeeping updates", async () => {+ expect(await events()).toHaveLength(1);+ await db.update(agents).set({ name: "Runtime agent", updatedAt: new Date(), lastHeartbeatAt: new Date(), spendMonthUtc: "2099-01" }).where(eq(agents.id, agentId));+ expect(await events()).toHaveLength(1);+ await db.update(agents).set({ adapterConfig: { model: "fixture" }, permissions: { canCreateAgents: true } }).where(eq(agents.id, agentId));+ await db.update(agents).set({ runtimeConfig: { fixture: true } }).where(eq(agents.id, agentId));+ const rows = await events();+ expect(rows).toHaveLength(3);+ expect(rows.every(row => row.resourceId === agentId)).toBe(true);+ expect(Object.keys(rows[0]).sort()).toEqual(["action", "companyId", "createdAt", "id", "resourceId", "resourceType"]);+ });++ it("captures instruction saves, deletion and writeback through the shared file store", async () => {+ const actor = { type: "board" as const, userId: "local-board", source: "local_implicit" as const };+ await agentFileStore(db).write({ companyId, agentId, path: "AGENTS.md", bytes: Buffer.from("instructions"), baseHash: null }, actor);+ const saved = await agentFileStore(db).write({ companyId, agentId, path: "notes.txt", bytes: Buffer.from("notes"), baseHash: null }, actor);+ const beforeDelete = (await events()).length;+ await agentFileStore(db).write({ companyId, agentId, path: "notes.txt", bytes: null, baseHash: saved.contentHash }, actor);+ expect(await events()).toHaveLength(beforeDelete + 1);+ expect(await events()).toContainEqual(expect.objectContaining({ resourceId: agentId, action: "update" }));+ });++ it("records a managed reset even when only its supporting files changed", async () => {+ const before = (await events()).length;+ await db.insert(activityLog).values({ companyId, actorType: "plugin", actorId: pluginId, action: "plugin.managed_agent.reset", entityType: "agent", entityId: agentId });+ expect(await events()).toHaveLength(before + 1);+ });++ it("rolls configuration and its event back together and rejects a change when journaling fails", async () => {+ const before = await events();+ await expect(db.transaction(async tx => {+ await tx.update(agents).set({ name: "Rolled back" }).where(eq(agents.id, agentId));+ throw new Error("rollback");+ })).rejects.toThrow("rollback");+ expect(await events()).toEqual(before);+ await db.execute((await import("drizzle-orm")).sql`ALTER TABLE resource_lifecycle_events ADD CONSTRAINT runtime_fixture_failure CHECK (resource_type <> 'agent_runtime') NOT VALID`);+ try { await expect(db.update(agents).set({ name: "Failed" }).where(eq(agents.id, agentId))).rejects.toThrow(); }+ finally { await db.execute((await import("drizzle-orm")).sql`ALTER TABLE resource_lifecycle_events DROP CONSTRAINT runtime_fixture_failure`); }+ expect((await db.select().from(agents).where(eq(agents.id, agentId)))[0].name).toBe("Runtime agent");+ expect(await events()).toEqual(before);+ });++ it.each(["file-write", "file-delete", "instructions"])("repairs runtime delivery when %s is retried after journal failure", async writer => {+ const actor = { type: "board" as const, userId: "local-board", source: "local_implicit" as const };+ const instructions = agentInstructionRevisionService(db);+ const initial = await instructions.commit({ companyId, agentId, entryFile: "AGENTS.md", content: "original", baseRevisionId: null, source: "api" }, actor);+ const store = agentFileStore(db);+ const saved = writer === "file-delete" ? await store.write({ companyId, agentId, path: "notes.txt", bytes: Buffer.from("notes"), baseHash: null }, actor) : null;+ const save = () => writer === "instructions"+ ? instructions.commit({ companyId, agentId, entryFile: "AGENTS.md", content: "changed", baseRevisionId: initial.revision.id, source: "api" }, actor)+ : store.write({ companyId, agentId, path: saved ? "notes.txt" : "AGENTS.md", bytes: saved ? null : Buffer.from("changed"), baseHash: saved ? saved.contentHash : initial.revision.contentHash }, actor);+ const inbox = pluginLifecycleInbox(db, pluginId);+ for (const event of await events()) await inbox.acknowledge(companyId, String(event.id));+ const before = await events();+ await db.execute(sql`ALTER TABLE resource_lifecycle_events ADD CONSTRAINT file_runtime_failure CHECK (resource_type <> 'agent_runtime') NOT VALID`);+ try { await expect(save()).rejects.toThrow(); }+ finally { await db.execute(sql`ALTER TABLE resource_lifecycle_events DROP CONSTRAINT file_runtime_failure`); }+ expect(await events()).toEqual(before);+ expect(await store.read(companyId, agentId, saved ? "notes.txt" : "AGENTS.md", actor)).toEqual(saved ? null : Buffer.from("changed"));+ expect(await save()).toMatchObject({ changed: false });+ expect(await events()).toHaveLength(before.length + 1);+ expect(await inbox.list(companyId, 100, undefined, ["agent_runtime"])).toEqual([expect.objectContaining({ resourceId: agentId, action: "update" })]);+ const repaired = await events();+ const audits = await db.select().from(activityLog).where(eq(activityLog.entityId, agentId)).orderBy(activityLog.id);+ for (let replay = 0; replay < 5; replay++) expect(await save()).toMatchObject({ changed: false });+ expect(await events()).toEqual(repaired);+ expect(await db.select().from(activityLog).where(eq(activityLog.entityId, agentId)).orderBy(activityLog.id)).toEqual(audits);+ expect((await pluginAgentRuntimeState(db, pluginId, companyId, agentId))!.revision).toBe(String((await events()).at(-1)!.id));+ });++ it("repairs a failed save even when that content hash was recorded before an intervening change", async () => {+ const actor = { type: "board" as const, userId: "local-board", source: "local_implicit" as const };+ const store = agentFileStore(db);+ const target = { companyId, agentId, path: "AGENTS.md" };+ const first = await store.write({ ...target, bytes: Buffer.from("first"), baseHash: null }, actor);+ const second = await store.write({ ...target, bytes: Buffer.from("second"), baseHash: first.contentHash }, actor);+ await store.write({ ...target, bytes: Buffer.from("first"), baseHash: second.contentHash }, actor);+ const before = (await events()).length;+ const save = () => store.write({ ...target, bytes: Buffer.from("second"), baseHash: first.contentHash }, actor);+ await db.execute(sql`ALTER TABLE resource_lifecycle_events ADD CONSTRAINT repeated_hash_failure CHECK (resource_type <> 'agent_runtime') NOT VALID`);+ try { await expect(save()).rejects.toThrow(); }+ finally { await db.execute(sql`ALTER TABLE resource_lifecycle_events DROP CONSTRAINT repeated_hash_failure`); }+ expect(await save()).toMatchObject({ changed: false });+ expect(await events()).toHaveLength(before + 1);+ await save();+ expect(await events()).toHaveLength(before + 1);+ });++ it("keeps old subscriptions isolated and replays runtime events in order until acknowledged", async () => {+ await db.update(agents).set({ name: "New name" }).where(eq(agents.id, agentId));+ const inbox = pluginLifecycleInbox(db, pluginId);+ expect(await inbox.list(companyId)).toEqual([]);+ const [first] = await inbox.list(companyId, 100, undefined, ["agent_runtime"]);+ expect(await inbox.list(companyId, 100, undefined, ["agent_runtime"])).toEqual([first]);+ const rows = await events();+ await expect(inbox.acknowledge(companyId, String(rows[1].id))).rejects.toMatchObject({ status: 409 });+ await inbox.acknowledge(companyId, first.id);+ expect(await inbox.list(companyId, 100, undefined, ["agent_runtime"])).toEqual([expect.objectContaining({ id: String(rows[1].id) })]);+ });++ it.each([{}, { instructionsBundleMode: "managed", instructionsRootPath: "/missing/previous-home" }])("recovers effective managed instruction paths from disk for %j", async adapterConfig => {+ const [agent] = await db.update(agents).set({ adapterConfig }).where(eq(agents.id, agentId)).returning();+ const root = resolveManagedInstructionsRoot(agent);+ await fs.mkdir(root, { recursive: true });+ await fs.writeFile(path.join(root, "GUIDE.md"), "restored instructions");+ const state = await pluginAgentRuntimeState(db, pluginId, companyId, agentId);+ expect(state).toMatchObject({ instructionsRootPath: root, instructionsEntryFile: "GUIDE.md" });+ expect(await fs.readFile(path.join(state!.instructionsRootPath!, state!.instructionsEntryFile), "utf8")).toBe("restored instructions");+ });++ it("resolves instructions without reading or hashing bundle contents", async () => {+ const [agent] = await db.select().from(agents).where(eq(agents.id, agentId));+ const root = resolveManagedInstructionsRoot(agent);+ await fs.mkdir(root, { recursive: true });+ await fs.writeFile(path.join(root, "AGENTS.md"), "instructions");+ await fs.writeFile(path.join(root, "support.bin"), Buffer.alloc(1024 * 1024));+ const read = vi.spyOn(fs, "readFile");+ expect(await pluginAgentRuntimeState(db, pluginId, companyId, agentId)).toMatchObject({ instructionsRootPath: root, instructionsEntryFile: "AGENTS.md" });+ expect(read.mock.calls.filter(([file]) => String(file).startsWith(`${root}${path.sep}`))).toEqual([]);+ });++ it("uses the company reporting graph for runtime health data", async () => {+ const [manager] = await db.insert(agents).values({ companyId, name: "Manager" }).returning();+ await db.update(agents).set({ reportsTo: manager.id }).where(eq(agents.id, agentId));+ expect((await pluginAgentRuntimeState(db, pluginId, companyId, agentId))!.agent.orgChainHealth?.status).toBe("healthy");+ await db.update(agents).set({ reportsTo: agentId }).where(eq(agents.id, manager.id));+ expect((await pluginAgentRuntimeState(db, pluginId, companyId, agentId))!.agent.orgChainHealth?.status).toBe("invalid_org_chain");+ });++ it("scopes runtime inputs to the enabled owning plugin and returns the current revision", async () => {+ const state = await pluginAgentRuntimeState(db, pluginId, companyId, agentId);+ expect(state).toMatchObject({ revision: String((await events()).at(-1)!.id), agent: { id: agentId }, instructionsEntryFile: "AGENTS.md", instanceSecrets: {} });+ expect(await pluginAgentRuntimeState(db, pluginId, randomUUID(), agentId)).toBeNull();+ await expect(pluginAgentRuntimeState(db, randomUUID(), companyId, agentId)).rejects.toMatchObject({ status: 403 });+ await db.insert(pluginCompanySettings).values({ companyId, pluginId, enabled: false });+ await expect(pluginAgentRuntimeState(db, pluginId, companyId, agentId)).rejects.toMatchObject({ status: 403 });+ });++ it("does not broadcast legacy lifecycle events to runtime listeners", async () => {+ const notifications: string[] = [];+ const listener = await db.$client.listen("paperclip_plugin_lifecycle", payload => { notifications.push(payload); });+ try {+ await db.transaction(async tx => {+ await tx.insert(resourceLifecycleEvents).values({ companyId, resourceType: "project", resourceId: randomUUID(), action: "update" });+ await tx.execute(sql`SELECT pg_notify('paperclip_plugin_lifecycle', 'barrier')`);+ });+ await vi.waitFor(() => expect(notifications).toContain("barrier"));+ expect(notifications).toEqual(["barrier"]);+ await db.update(agents).set({ name: "Notify runtime" }).where(eq(agents.id, agentId));+ await vi.waitFor(() => expect(notifications).toEqual(["barrier", ""]));+ } finally { await listener.unlisten(); }+ });++ it("wakes delivery after a commit on an independent database client, without polling", async () => {+ const other = createDb(database.connectionString);+ const call = vi.fn(async (_plugin, _method, event) => ({ eventId: event.id, status: "acknowledged" }));+ const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => { throw error; } });+ const delivery = registerPluginLifecycleDelivery(coordinator, db, { call, isRunning: () => true, onConfigApplied: () => () => {} } as never, new EventEmitter() as never);+ try {+ await delivery.ready;+ await vi.waitFor(() => expect(call).toHaveBeenCalled(), { timeout: 5000 });+ const delivered = () => call.mock.calls.filter(call => call[2].companyId === companyId);+ const initialCount = (await events()).length;+ await vi.waitFor(() => expect(delivered()).toHaveLength(initialCount), { timeout: 5000 });+ const before = delivered().length;+ await other.transaction(async tx => {+ await tx.update(agents).set({ name: "Independent writer" }).where(eq(agents.id, agentId));+ expect(delivered()).toHaveLength(before);+ });+ await vi.waitFor(() => expect(delivered().length).toBeGreaterThan(before), { timeout: 5000 });+ expect(delivered().at(-1)![2]).toMatchObject({ companyId, resourceId: agentId, resourceType: "agent_runtime" });+ } finally { delivery.dispose(); await coordinator.stop(); await other.$client.end(); }+ });+ it("recovers work committed during real listener connection loss without another write", async () => {+ const target = new URL(database.connectionString);+ const upstreamHost = target.hostname; const upstreamPort = Number(target.port);+ let blocked = false;+ const sockets = new Set<Socket>();+ const proxy = createServer(client => {+ if (blocked) { client.destroy(); return; }+ const upstream = connect(upstreamPort, upstreamHost);+ for (const socket of [client, upstream]) {+ sockets.add(socket);+ socket.on("error", () => { client.destroy(); upstream.destroy(); });+ socket.on("close", () => { sockets.delete(socket); client.destroy(); upstream.destroy(); });+ }+ client.pipe(upstream); upstream.pipe(client);+ });+ await new Promise<void>(resolve => proxy.listen(0, "127.0.0.1", resolve));+ target.hostname = "127.0.0.1"; target.port = String((proxy.address() as { port: number }).port);+ const listenerDb = createDb(target.toString(), { connectTimeoutSeconds: 1 });+ const call = vi.fn(async (_plugin, _method, event) => ({ eventId: event.id, status: "acknowledged" }));+ const coordinator = createDeliveryWorkCoordinator({ owner: listenerDb, canRun: () => true, onError: () => {} });+ const delivery = registerPluginLifecycleDelivery(coordinator, listenerDb, { call, isRunning: () => true, onConfigApplied: () => () => {} } as never, new EventEmitter() as never);+ try {+ await delivery.ready;+ const inbox = pluginLifecycleInbox(db, pluginId);+ await vi.waitFor(async () => expect(await inbox.list(companyId, 100, undefined, ["agent_runtime"])).toEqual([]), { timeout: 5000 });+ await vi.waitFor(() => expect(coordinator.nextWakeAt()).toBeNull(), { timeout: 5000 });+ blocked = true;+ for (const socket of sockets) socket.destroy();+ await db.update(agents).set({ name: "Changed while disconnected" }).where(eq(agents.id, agentId));+ const queued = (await events()).at(-1)!;+ expect(call.mock.calls.some(call => call[2].id === String(queued.id))).toBe(false);+ blocked = false;+ await vi.waitFor(() => expect(call.mock.calls.some(call => call[2].id === String(queued.id))).toBe(true), { timeout: 10000 });+ } finally {+ blocked = false; delivery.dispose(); await coordinator.stop(); await listenerDb.$client.end({ timeout: 1 });+ for (const socket of sockets) socket.destroy();+ await new Promise<void>(resolve => proxy.close(() => resolve()));+ }+ }, 20000);++});diff --git a/server/src/__tests__/plugin-lifecycle-delivery.test.ts b/server/src/__tests__/plugin-lifecycle-delivery.test.tsindex f745dcdc0e..95eee6ca0c 100644--- a/server/src/__tests__/plugin-lifecycle-delivery.test.ts+++ b/server/src/__tests__/plugin-lifecycle-delivery.test.ts@@ -10,7 +10,7 @@ import { pluginLifecycleInbox } from "../services/plugin-lifecycle-inbox.js";import { pluginRegistryService } from "../services/plugin-registry.js";import { recordProjectLifecycleEvent, recordResourceCreationEvent } from "../services/resource-lifecycle-events.js";import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../services/delivery-work-notifications.js";-import type { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";+import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";import type { PluginLifecycleManager } from "../services/plugin-lifecycle.js";import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";@@ -27,6 +27,7 @@ describePostgres("durable plugin lifecycle delivery", () => {afterAll(async () => { await database?.cleanup(); });afterEach(() => { vi.restoreAllMocks(); });beforeEach(async () => {+ vi.spyOn(db.$client, "listen").mockResolvedValue({ unlisten: vi.fn(), state: {} } as never);await db.delete(plugins);companyId = randomUUID(); pluginId = randomUUID();await db.insert(companies).values({ id: companyId, name: "Delivery fixture", issuePrefix: `L${companyId.slice(0, 6)}` });@@ -53,6 +54,22 @@ describePostgres("durable plugin lifecycle delivery", () => {const worker = registerPluginLifecycleDelivery(coordinator as never, db, { call, isRunning: running, onConfigApplied } as unknown as PluginWorkerManager, lifecycle as unknown as PluginLifecycleManager);return { call, running, wake, lifecycle, worker, applied: () => { for (const listener of configApplied) listener(); }, run: () => task.run(new AbortController().signal), pending: () => task.hasPending(), nextRunAt: () => task.nextRunAt?.(), settled: () => task.onSettled?.() };}+ it.each([false, true])("does not wait for queued plugin callbacks during startup (runtime subscriber: %s)", async runtime => {+ if (runtime) await db.update(plugins).set({ manifestJson: { resourceLifecycle: ["project", "agent_runtime"], capabilities: ["events.subscribe"] } as never }).where(eq(plugins.id, pluginId));+ await event();+ let release!: () => void;+ const blocked = new Promise<void>(resolve => { release = resolve; });+ const call = vi.fn(async (_plugin, _method, input) => { await blocked; return { eventId: input.id, status: "acknowledged" }; });+ const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: () => {} });+ const worker = registerPluginLifecycleDelivery(coordinator, db, { call, isRunning: () => true, onConfigApplied: () => () => {} } as never, new EventEmitter() as never);+ let ready = false;+ void worker.ready.then(() => { ready = true; });+ try {+ await vi.waitFor(() => expect(call).toHaveBeenCalled(), { timeout: 5000 });+ await vi.waitFor(() => expect(ready).toBe(true));+ expect(await pluginLifecycleInbox(db, pluginId).list(companyId)).toHaveLength(1);+ } finally { release(); worker.dispose(); await coordinator.stop(); }+ });it("drains creation before transitions, recovers acknowledgments across dispatcher replacement, and ignores agent events", async () => {const id = await event(); await event(id, "update"); await event(id, "delete");await db.transaction(tx => recordResourceCreationEvent(tx as unknown as Db, companyId, "agent", randomUUID()));@@ -176,6 +193,7 @@ describePostgres("durable plugin lifecycle delivery", () => {});it("retains a failed scan across a retry skipped during idle drain", async () => {await event(); const d = delivery();+ await d.worker.ready;const select = vi.spyOn(db, "select").mockImplementationOnce(() => { throw new Error("database unavailable"); });await expect(d.run()).rejects.toThrow("database unavailable");// The coordinator's drain path checks hasPending without calling run.@@ -193,6 +211,59 @@ describePostgres("durable plugin lifecycle delivery", () => {await registry.upsertCompanySettings(pluginId, companyId, { enabled: true, settingsJson: {} });expect((await registry.getConfig(pluginId, companyId))?.configJson).toEqual({ first: true, second: true });}, 5000);+ it("retries listener setup through durable delivery after an enable-time failure", async () => {+ const d = delivery();+ await d.worker.ready;+ await db.update(plugins).set({ manifestJson: { resourceLifecycle: ["agent_runtime"], capabilities: ["events.subscribe"] } as never }).where(eq(plugins.id, pluginId));+ const listen = vi.mocked(db.$client.listen);+ listen.mockRejectedValueOnce(new Error("temporary listener outage"));+ d.lifecycle.emit("plugin.enabled");+ await vi.waitFor(() => expect(listen).toHaveBeenCalledTimes(1));+ expect(await d.pending()).toBe(true);+ await d.run();+ expect(listen).toHaveBeenCalledTimes(2);+ expect(await d.pending()).toBe(false);+ d.worker.dispose();+ });+ it("unregisters the listener on the last disable or unload and can subscribe again", async () => {+ await db.update(plugins).set({ manifestJson: { resourceLifecycle: ["agent_runtime"], capabilities: ["events.subscribe"] } as never }).where(eq(plugins.id, pluginId));+ const otherPluginId = randomUUID();+ await db.insert(plugins).values({ id: otherPluginId, pluginKey: otherPluginId, packageName: "other-runtime", version: "1.0.0", status: "ready", manifestJson: { resourceLifecycle: ["agent_runtime"], capabilities: ["events.subscribe"] } as never });+ await db.insert(pluginConfig).values({ pluginId: otherPluginId, companyId, configJson: {} });+ const first = { unlisten: vi.fn(), state: {} };+ const second = { unlisten: vi.fn(), state: {} };+ const third = { unlisten: vi.fn(), state: {} };+ const listen = vi.mocked(db.$client.listen).mockResolvedValueOnce(first as never).mockResolvedValueOnce(second as never).mockResolvedValueOnce(third as never);+ const d = delivery();+ await d.worker.ready;+ await db.update(plugins).set({ status: "disabled" }).where(eq(plugins.id, pluginId));+ d.lifecycle.emit("plugin.status_changed");+ await d.run();+ expect(first.unlisten).not.toHaveBeenCalled();+ await db.update(plugins).set({ status: "disabled" }).where(eq(plugins.id, otherPluginId));+ d.lifecycle.emit("plugin.disabled");+ await vi.waitFor(() => expect(first.unlisten).toHaveBeenCalledTimes(1));+ await db.update(plugins).set({ status: "ready" }).where(eq(plugins.id, pluginId));+ d.lifecycle.emit("plugin.enabled");+ await d.run();+ expect(listen).toHaveBeenCalledTimes(2);+ const registry = pluginRegistryService(db);+ await registry.upsertCompanySettings(pluginId, companyId, { enabled: false, settingsJson: {} });+ d.applied();+ await vi.waitFor(() => expect(second.unlisten).toHaveBeenCalledTimes(1));+ await registry.upsertCompanySettings(pluginId, companyId, { enabled: true, settingsJson: {} });+ d.applied(); await d.run();+ expect(listen).toHaveBeenCalledTimes(3);+ await db.delete(plugins).where(eq(plugins.id, pluginId));+ d.lifecycle.emit("plugin.unloaded");+ await vi.waitFor(() => expect(third.unlisten).toHaveBeenCalledTimes(1));+ expect(first.unlisten).toHaveBeenCalledTimes(1);+ expect(second.unlisten).toHaveBeenCalledTimes(1);+ d.worker.dispose();+ expect(d.lifecycle.listenerCount("plugin.status_changed")).toBe(0);+ expect(d.lifecycle.listenerCount("plugin.disabled")).toBe(0);+ expect(d.lifecycle.listenerCount("plugin.unloaded")).toBe(0);+ });it("records failed delivery scope and stage without provider secrets", async () => {await event(); const d = delivery();const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});diff --git a/server/src/__tests__/plugin-managed-agents.test.ts b/server/src/__tests__/plugin-managed-agents.test.tsindex e07ba0e1fc..e29f946673 100644--- a/server/src/__tests__/plugin-managed-agents.test.ts+++ b/server/src/__tests__/plugin-managed-agents.test.ts@@ -3,10 +3,11 @@ import { randomUUID } from "node:crypto";import { promises as fs } from "node:fs";import os from "node:os";import path from "node:path";-import { eq } from "drizzle-orm";+import { and, eq } from "drizzle-orm";import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import {activityLog,+ resourceLifecycleEvents,agentConfigRevisions,agentInstructionRevisions,agentInstructionHeads,@@ -366,6 +367,7 @@ describeEmbeddedPostgres("plugin-managed agents", () => {adapterConfig: {},instructions: {entryFile: "AGENTS.md",+ files: { "TOOLS.md": "# Stock tools\n" },content: ["# LLM Wiki Maintainer","",@@ -415,12 +417,17 @@ describeEmbeddedPostgres("plugin-managed agents", () => {expect(history).toHaveLength(0);expect(await db.select().from(agentInstructionHeads).where(eq(agentInstructionHeads.agentId, created.agentId!))).toHaveLength(0);+ const runtimeEvents = () => db.select().from(resourceLifecycleEvents).where(and(eq(resourceLifecycleEvents.resourceType, "agent_runtime"), eq(resourceLifecycleEvents.resourceId, created.agentId!)));+ await fs.writeFile(path.join(path.dirname(instructionsFilePath as string), "TOOLS.md"), "custom tools");+ const runtimeCount = (await runtimeEvents()).length;const repeated = await services.agents.managedReset({ companyId, agentKey: "wiki-maintainer" });expect(repeated.status).toBe("reset");+ expect(await runtimeEvents()).toHaveLength(runtimeCount + 2);+ expect(await fs.readFile(path.join(path.dirname(instructionsFilePath as string), "TOOLS.md"), "utf8")).toBe("# Stock tools\n");expect(await db.select().from(agentInstructionRevisions).where(eq(agentInstructionRevisions.agentId, created.agentId!))).toHaveLength(0);const audit = await db.select().from(activityLog).where(eq(activityLog.action, "agent.files_updated"));- expect(audit).toHaveLength(1);+ expect(audit).toHaveLength(2);expect(audit.every((row) => row.actorType === "plugin" && row.actorId === pluginId)).toBe(true);const bundles = agentInstructionsService(db);await bundles.writeFile(repeated.agent!, "CUSTOM.md", "# Alternate configured entry\n");diff --git a/server/src/__tests__/resource-lifecycle-events.test.ts b/server/src/__tests__/resource-lifecycle-events.test.tsindex f7b263d40f..13602dfb11 100644--- a/server/src/__tests__/resource-lifecycle-events.test.ts+++ b/server/src/__tests__/resource-lifecycle-events.test.ts@@ -1,7 +1,7 @@import { createAgentLifecycle, configureAgentLifecycle } from "../services/agent-lifecycle.js";import { randomUUID } from "node:crypto";import { readFileSync } from "node:fs";-import { eq, sql } from "drizzle-orm";+import { and, eq, ne, sql } from "drizzle-orm";import { agentApiKeys, agents, budgetPolicies, companies, costEvents, createDb, pluginCompanySettings, pluginLifecycleAcknowledgments, plugins, projects, resourceLifecycleEvents, type Db } from "@paperclipai/db";import { createHostClientHandlers } from "@paperclipai/plugin-sdk";import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";@@ -40,7 +40,7 @@ describePostgres("Resource lifecycle events", () => {});afterEach(() => { vi.unstubAllEnvs(); });- const events = () => db.select().from(resourceLifecycleEvents).where(eq(resourceLifecycleEvents.companyId, companyId));+ const events = () => db.select().from(resourceLifecycleEvents).where(and(eq(resourceLifecycleEvents.companyId, companyId), ne(resourceLifecycleEvents.resourceType, "agent_runtime")));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);@@ -475,6 +475,18 @@ describePostgres("Resource lifecycle events", () => {expect(await inbox.list(companyId)).toEqual([expect.objectContaining({ action: "create" })]);});+ it.each([{ resourceLifecycle: ["project"] }, { resourceLifecycle: ["agent_runtime"] }] as const)("preserves legacy manual streams with automatic subscription %j", async ({ resourceLifecycle }) => {+ const plugin = await createPlugin();+ await createAgent();+ await db.insert(resourceLifecycleEvents).values({ companyId, resourceType: "project", resourceId: randomUUID(), action: "create" });+ const services = buildHostServices(db, plugin.id, plugin.pluginKey, createPluginEventBus(), undefined, { manifest: { resourceLifecycle } as never });+ const handlers = createHostClientHandlers({ pluginId: plugin.id, capabilities: ["events.subscribe"], services });+ try {+ const rows = await handlers["events.listLifecycle"]({ companyId }, { invocationScope: { companyId } });+ expect(new Set(rows.map(row => row.resourceType))).toEqual(new Set(resourceLifecycle[0] === "agent_runtime" ? ["agent", "project", "agent_runtime"] : ["agent", "project"]));+ } finally { services.dispose(); }+ });+it("enforces capability, invocation company, plugin availability, and company boundaries through host RPC", async () => {const plugin = await createPlugin();await createAgent();diff --git a/server/src/app.ts b/server/src/app.tsindex ac90c20557..14814f6441 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -1265,6 +1265,7 @@ export async function createApp(});app.locals.deliveryWork = deliveryWork;const resourceLifecycleDelivery = registerPluginLifecycleDelivery(deliveryWork, db, workerManager, lifecycle);+ await resourceLifecycleDelivery.ready;if (opts.feedbackExportService) {deliveryWork.register(DELIVERY_QUEUES.feedback, {retryMs: FEEDBACK_EXPORT_FLUSH_INTERVAL_MS,diff --git a/server/src/services/agent-file-store.ts b/server/src/services/agent-file-store.tsindex 24dfc00217..4f31bf98d3 100644--- a/server/src/services/agent-file-store.ts+++ b/server/src/services/agent-file-store.ts@@ -4,8 +4,8 @@ import { cachedAgentFileManifest, checkpointSnapshot, type AgentFileManifest } fimport { constants } from "node:fs";import { Readable } from "node:stream";import path from "node:path";-import { and, eq } from "drizzle-orm";-import { agents, activityLog, agentInstructionHeads, agentInstructionRevisions, type Db } from "@paperclipai/db";+import { and, desc, eq, isNull, sql } from "drizzle-orm";+import { agents, activityLog, agentInstructionHeads, agentInstructionRevisions, resourceLifecycleEvents, type Db } from "@paperclipai/db";import { captureDirectorySnapshot, mergeDirectoryWithBaseline, type DirectorySnapshot } from "@paperclipai/adapter-utils/workspace-restore-merge";import { HttpError, conflict, notFound, unprocessable } from "../errors.js";import { authorizeInstructionCommit, authorizeInstructionRead } from "./agent-instruction-authorization.js";@@ -161,6 +161,22 @@ export async function snapshotAgentFiles(root: string, enforceLimits = true): Prreturn (await inspectAgentDirectory(root, enforceLimits)).snapshot;}+export async function isAgentFileSaveRecorded(tx: Tx, agent: Agent, relative: string, contentHash: string | null): Promise<boolean> {+ if (agent.status === "pending_approval" || agent.status === "terminated") return true;+ const [latest] = await tx.select({ id: resourceLifecycleEvents.id }).from(resourceLifecycleEvents)+ .where(and(eq(resourceLifecycleEvents.companyId, agent.companyId), eq(resourceLifecycleEvents.resourceType, "agent_runtime"), eq(resourceLifecycleEvents.resourceId, agent.id)))+ .orderBy(desc(resourceLifecycleEvents.id)).limit(1);+ if (!latest) return false;+ const hash = sql<string>`${activityLog.details}->>'contentHash'`;+ const [recorded] = await tx.select({ id: activityLog.id }).from(activityLog)+ .innerJoin(resourceLifecycleEvents, and(eq(resourceLifecycleEvents.id, latest.id), eq(activityLog.createdAt, resourceLifecycleEvents.createdAt))).where(and(+ eq(activityLog.companyId, agent.companyId), eq(activityLog.entityType, "agent"), eq(activityLog.entityId, agent.id), eq(activityLog.action, "agent.files_updated"),+ eq(sql<string>`${activityLog.details}->>'agentRuntimeRevision'`, String(latest.id)),+ eq(sql<string>`${activityLog.details}->>'path'`, relative), contentHash === null ? isNull(hash) : eq(hash, contentHash),+ )).limit(1);+ return Boolean(recorded);+}+export function agentFileStore(db: Db) {async function locked<T>(companyId: string, agentId: string, actor: AuthorizationActor, write: boolean,fn: (tx: Tx, agent: Agent, root: string, bound: AuthorizationActor) => Promise<T>) {@@ -203,7 +219,10 @@ export function agentFileStore(db: Db) {const previous = await inspectAgentFile(root, relative);const currentHash = previous?.hash ?? null;const incomingHash = input.bytes === null ? null : fileHash(input.bytes);- if (currentHash === incomingHash) return { contentHash: currentHash, changed: false };+ if (currentHash === incomingHash) {+ if (!await isAgentFileSaveRecorded(tx, agent, relative, incomingHash)) await audit(tx, agent, bound, { path: relative, contentHash: incomingHash });+ return { contentHash: currentHash, changed: false };+ }if (currentHash !== input.baseHash) throw conflict("This file changed since it was read. Reload before saving.", { code: "AGENT_FILE_CONFLICT", path: relative, currentHash });if (input.bytes === null && relative === deriveBundleState(agent).entryFile) throw unprocessable("The configured instruction entry cannot be deleted");if (input.bytes !== null) {diff --git a/server/src/services/agent-instruction-revisions.ts b/server/src/services/agent-instruction-revisions.tsindex 8a60208e31..f7f3619d3f 100644--- a/server/src/services/agent-instruction-revisions.ts+++ b/server/src/services/agent-instruction-revisions.ts@@ -1,6 +1,6 @@import { updateAgentConfigurationInTransaction } from "./agent-configuration-transaction.js";import { createHash } from "node:crypto";-import { adoptAgentFiles, agentFileToken } from "./agent-file-store.js";+import { adoptAgentFiles, agentFileToken, isAgentFileSaveRecorded } from "./agent-file-store.js";import { and, desc, eq, getTableColumns, lt, or, sql } from "drizzle-orm";import {activityLog,@@ -247,6 +247,12 @@ export function agentInstructionRevisionService(db: Db) {): null;const candidate = bytes ?? Buffer.from(restored!.contentBase64, "base64");+ const recordSave = (row: Revision) => tx.insert(activityLog).values({ companyId: input.companyId,+ actorType: bound.type === "plugin" ? "plugin" : bound.type === "board" ? "user" : "agent",+ actorId: (bound.type === "plugin" ? bound.pluginId : bound.type === "board" ? bound.userId : bound.agentId)!,+ agentId: bound.type === "agent" ? bound.agentId : null, runId: row.sourceRunId,+ responsibleUserId: row.responsibleUserId, action: "agent.files_updated", entityType: "agent", entityId: input.agentId,+ details: { path: input.entryFile, contentHash: row.contentHash, source: restored ? "legacy_restore" : (input as InstructionCommitInput).source } });const bindEntry = async () => {if (!state.agent.adapterConfig.instructionsRootPath ||@@ -267,6 +273,7 @@ export function agentInstructionRevisionService(db: Db) {// An exact replay can safely return the durable receipt even after its base// advanced. Restore also deduplicates identical content, preserving history.if (current && current.contentBase64 === candidate.toString("base64")) {+ if (!await isAgentFileSaveRecorded(tx, state.agent, input.entryFile, current.contentHash)) await recordSave(current);await bindEntry();return { row: current, changed: false };}@@ -287,12 +294,7 @@ export function agentInstructionRevisionService(db: Db) {}await materializeInstructionBytes(state.root, state.entryFile, candidate);const row = currentRow(input, input.entryFile, candidate, bound);- await tx.insert(activityLog).values({ companyId: input.companyId,- actorType: bound.type === "plugin" ? "plugin" : bound.type === "board" ? "user" : "agent",- actorId: (bound.type === "plugin" ? bound.pluginId : bound.type === "board" ? bound.userId : bound.agentId)!,- agentId: bound.type === "agent" ? bound.agentId : null, runId: row.sourceRunId,- responsibleUserId: row.responsibleUserId, action: "agent.files_updated", entityType: "agent", entityId: input.agentId,- details: { path: input.entryFile, contentHash: row.contentHash, source: restored ? "legacy_restore" : (input as InstructionCommitInput).source } });+ await recordSave(row);await bindEntry();return { row, changed: true };});diff --git a/server/src/services/agent-instructions.ts b/server/src/services/agent-instructions.tsindex 4f66a27545..1729e8be83 100644--- a/server/src/services/agent-instructions.ts+++ b/server/src/services/agent-instructions.ts@@ -495,6 +495,11 @@ export function agentInstructionsService(db?: Db) {eq(agentInstructionHeads.agentId, agent.id), eq(agentInstructionHeads.entryFile, entryFile)));if (head) throw unprocessable("This entry has revision history. Use the instruction content API with its baseRevisionId to update it.", { code: "INSTRUCTION_REVISION_REQUIRED" });}+ async function getBundleLocation(agent: AgentLike): Promise<{ rootPath: string | null; entryFile: string }> {+ const state = await recoverManagedBundleState(agent, deriveBundleState(agent));+ if (state.rootPath) await assertInstructionPathSafe(state.rootPath, state.entryFile);+ return { rootPath: state.rootPath, entryFile: state.entryFile };+ }async function getBundle(agent: AgentLike): Promise<AgentInstructionsBundle> {const state = await recoverManagedBundleState(agent, deriveBundleState(agent));if (!state.rootPath) return toBundle(agent, state, []);@@ -818,6 +823,7 @@ export function agentInstructionsService(db?: Db) {}return {+ getBundleLocation,getBundle,readFile,updateBundle,diff --git a/server/src/services/plugin-agent-runtime-state.ts b/server/src/services/plugin-agent-runtime-state.tsnew file mode 100644index 0000000000..fa775c5d9e--- /dev/null+++ b/server/src/services/plugin-agent-runtime-state.ts@@ -0,0 +1,32 @@+import { and, desc, eq } from "drizzle-orm";+import { agents, plugins, pluginCompanySettings, resourceLifecycleEvents, type Db } from "@paperclipai/db";+import type { PluginAgentRuntimeState } from "@paperclipai/plugin-sdk";+import { agentRecordQueries } from "../lib/agent-records.js";+import { forbidden } from "../errors.js";+import { agentInstructionsService } from "./agent-instructions.js";+import { agentInstanceSecretService } from "./agent-instance-secrets.js";++export async function pluginAgentRuntimeState(db: Db, pluginId: string, companyId: string, agentId: string): Promise<PluginAgentRuntimeState | null> {+ return db.transaction(async tx => {+ const [agent] = await tx.select().from(agents)+ .where(and(eq(agents.companyId, companyId), eq(agents.id, agentId))).for("share");+ if (!agent) return null;+ const [plugin] = await tx.select().from(plugins).where(eq(plugins.id, pluginId));+ const [settings] = await tx.select().from(pluginCompanySettings).where(and(eq(pluginCompanySettings.companyId, companyId), eq(pluginCompanySettings.pluginId, pluginId)));+ if (plugin?.status !== "ready" || settings?.enabled === false || !plugin?.manifestJson.capabilities?.includes("agents.lifecycle.manage")+ || !plugin.manifestJson.resourceLifecycle?.includes("agent_runtime") || !agent.lifecycleRequiredPluginIds?.includes(pluginId)) {+ throw forbidden("Agent runtime state requires the owning lifecycle plugin");+ }+ const [latest] = await tx.select({ id: resourceLifecycleEvents.id }).from(resourceLifecycleEvents)+ .where(and(eq(resourceLifecycleEvents.companyId, companyId), eq(resourceLifecycleEvents.resourceType, "agent_runtime"), eq(resourceLifecycleEvents.resourceId, agentId)))+ .orderBy(desc(resourceLifecycleEvents.id)).limit(1);+ const instructions = await agentInstructionsService().getBundleLocation(agent);+ const records = agentRecordQueries(tx as unknown as Db);+ const companyAgents = await records.listCompanyAgentRows(companyId);+ return {+ revision: String(latest?.id ?? 0), agent: records.normalizeAgentRow(agent, companyAgents) as PluginAgentRuntimeState["agent"],+ instructionsRootPath: instructions.rootPath, instructionsEntryFile: instructions.entryFile,+ instanceSecrets: await agentInstanceSecretService(tx as unknown as Db).read({ companyId, agentId, pluginId }),+ };+ });+}diff --git a/server/src/services/plugin-host-services.ts b/server/src/services/plugin-host-services.tsindex 1c592fb4cb..87788bed6c 100644--- a/server/src/services/plugin-host-services.ts+++ b/server/src/services/plugin-host-services.ts@@ -1,3 +1,4 @@+import { pluginAgentRuntimeState } from "./plugin-agent-runtime-state.js";import { createAgentLifecycle } from "./agent-lifecycle.js";import type { Db } from "@paperclipai/db";import {@@ -1698,7 +1699,7 @@ export function buildHostServices(events: {async listLifecycle(params) {- return lifecycleInbox.list(ensureCompanyId(params.companyId), params.limit, params.afterId);+ return lifecycleInbox.list(ensureCompanyId(params.companyId), params.limit, params.afterId, options.manifest?.resourceLifecycle?.includes("agent_runtime") ? ["agent", "project", "agent_runtime"] : ["agent", "project"]);},async acknowledgeLifecycle(params) {await lifecycleInbox.acknowledge(ensureCompanyId(params.companyId), params.eventId);@@ -2995,6 +2996,11 @@ export function buildHostServices(},agents: {+ async getRuntime(params) {+ const companyId = ensureCompanyId(params.companyId);+ await ensurePluginAvailableForCompany(companyId);+ return pluginAgentRuntimeState(db, pluginId, companyId, params.agentId);+ },async list(params) {const companyId = ensureCompanyId(params.companyId);await ensurePluginAvailableForCompany(companyId);diff --git a/server/src/services/plugin-lifecycle-delivery.ts b/server/src/services/plugin-lifecycle-delivery.tsindex 24c5dbc26d..5eea93f183 100644--- a/server/src/services/plugin-lifecycle-delivery.ts+++ b/server/src/services/plugin-lifecycle-delivery.ts@@ -19,6 +19,7 @@ export function registerPluginLifecycleDelivery(// Startup and every wake remain pending until an admitted run inspects the inbox.// The coordinator may reconcile signals while idle drain prevents dispatch.let pending = true;+ let disposed = false;const retryAt = new Map<string, number>();const retryMs = 30_000;const delivery = coordinator.register(DELIVERY_QUEUES.pluginLifecycle, {@@ -37,6 +38,7 @@ export function registerPluginLifecycleDelivery(async run(signal) {pending = false;try {+ await ensureListening();for (const [key, at] of retryAt) if (at <= Date.now()) retryAt.delete(key);const configured = await db.select({ plugin: plugins, companyId: pluginConfig.companyId }).from(plugins).innerJoin(pluginConfig, eq(pluginConfig.pluginId, plugins.id))@@ -104,19 +106,54 @@ export function registerPluginLifecycleDelivery(}},});- function wake() { pending = true; delivery.wake(); }- const unsubscribeConfig = manager.onConfigApplied(wake);- lifecycle.on("plugin.loaded", wake);- lifecycle.on("plugin.enabled", wake);- lifecycle.on("plugin.worker_started", wake);+ function wake() { if (disposed) return; pending = true; delivery.wake(); }+ let listening: Awaited<ReturnType<Db["$client"]["listen"]>> | undefined;+ let listenerUpdate = Promise.resolve();+ function ensureListening() {+ const update = listenerUpdate.then(async () => {+ if (disposed || !db.$client?.listen) return;+ const installed = await db.select({ manifest: plugins.manifestJson }).from(plugins)+ .innerJoin(pluginConfig, eq(pluginConfig.pluginId, plugins.id))+ .leftJoin(pluginCompanySettings, and(eq(pluginCompanySettings.pluginId, plugins.id), eq(pluginCompanySettings.companyId, pluginConfig.companyId)))+ .where(and(eq(plugins.status, "ready"), or(isNull(pluginCompanySettings.enabled), eq(pluginCompanySettings.enabled, true))));+ if (disposed) return;+ const wanted = installed.some(plugin => plugin.manifest.resourceLifecycle?.includes("agent_runtime") && plugin.manifest.capabilities?.includes("events.subscribe"));+ if (wanted) listening ??= await db.$client.listen("paperclip_plugin_lifecycle", wake, wake);+ else if (listening) {+ const subscription = listening;+ listening = undefined;+ await subscription.unlisten();+ }+ });+ listenerUpdate = update.catch(() => {});+ return update;+ }+ function pluginChanged() {+ wake();+ void ensureListening().catch(wake);+ }+ const listenerReady = ensureListening();+ const unsubscribeConfig = manager.onConfigApplied(pluginChanged);+ lifecycle.on("plugin.loaded", pluginChanged);+ lifecycle.on("plugin.enabled", pluginChanged);+ lifecycle.on("plugin.worker_started", pluginChanged);+ lifecycle.on("plugin.status_changed", pluginChanged);+ lifecycle.on("plugin.disabled", pluginChanged);+ lifecycle.on("plugin.unloaded", pluginChanged);return {...delivery,+ ready: listenerReady,wake,dispose() {+ disposed = true;+ void listenerUpdate.then(() => listening?.unlisten()).catch(() => {});unsubscribeConfig();- lifecycle.off("plugin.loaded", wake);- lifecycle.off("plugin.enabled", wake);- lifecycle.off("plugin.worker_started", wake);+ lifecycle.off("plugin.loaded", pluginChanged);+ lifecycle.off("plugin.enabled", pluginChanged);+ lifecycle.off("plugin.worker_started", pluginChanged);+ lifecycle.off("plugin.status_changed", pluginChanged);+ lifecycle.off("plugin.disabled", pluginChanged);+ lifecycle.off("plugin.unloaded", pluginChanged);},};}diff --git a/server/src/services/plugin-lifecycle-inbox.ts b/server/src/services/plugin-lifecycle-inbox.tsindex e7aa0a4bf7..8f9d9ea285 100644--- a/server/src/services/plugin-lifecycle-inbox.ts+++ b/server/src/services/plugin-lifecycle-inbox.ts@@ -36,7 +36,7 @@ export function pluginLifecycleInbox(db: Db, pluginId: string) {if (afterId !== undefined && (typeof afterId !== "string" || !/^[1-9]\d*$/.test(afterId) || !Number.isSafeInteger(Number(afterId)))) throw badRequest("Invalid lifecycle page id");await assertAvailable(db, companyId);const rows = await db.select().from(resourceLifecycleEvents)- .where(and(eq(resourceLifecycleEvents.companyId, companyId), unacknowledged, firstForResource, resourceTypes ? inArray(resourceLifecycleEvents.resourceType, resourceTypes) : undefined, afterId === undefined ? undefined : gt(resourceLifecycleEvents.id, Number(afterId))))+ .where(and(eq(resourceLifecycleEvents.companyId, companyId), unacknowledged, firstForResource, inArray(resourceLifecycleEvents.resourceType, resourceTypes ?? ["agent", "project"]), afterId === undefined ? undefined : gt(resourceLifecycleEvents.id, Number(afterId)))).orderBy(asc(resourceLifecycleEvents.id)).limit(limit);return rows.map(row => ({ ...row, id: String(row.id), createdAt: row.createdAt.toISOString() })) as ResourceLifecycleEvent[];},