Files
PaperClipAI/server/src/services/plugin-lifecycle-delivery.ts
T
Nicky LeachandClaude Opus 5.5 be20d4ad97 fix(projects): keep projects on the storage chosen at creation (#19036)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A project stores its work in Core/local storage or in a storage
plugin
> - Today, Core finds the installed default each time it reads a project
> - So installing a default storage plugin moves existing projects,
without a saved change
> - Agents that cannot reach the new storage then lose access to new
workspaces
> - This pull request makes Core apply the default once, when it creates
a project
> - The benefit is that a project stays on its storage until a person
moves it

## Linked Issues or Issue Description

No issue exists. This describes the problem. I searched open pull
requests for related work and found no duplicate.

**What existing behavior does this improve?**

How Core chooses the storage for a project when a plugin claims
`defaultForProjects`.

**Current behavior**

Installing such a plugin changes the storage of every existing project
with no explicit choice. Disabling the plugin changes it back. Nothing
is saved, so the project has no fixed owner. Execution environments and
storage are separate contracts, so an agent can lose access to new
workspaces on a project that it used before.

**Proposed behavior**

Core saves the storage choice on the project when it creates the
project. A project with no saved choice uses Core/local storage. A
plugin-backed project stays attached to its plugin. A Core/local project
can move to a plugin.

**Reason and benefit**

A project stays on its storage until a person moves it, so installing or
disabling a plugin does not change where work goes.

**Alternatives considered**

- Keep the default at read time and add a process that saves a choice on
existing projects when a plugin arrives. This adds a background step and
a race with new projects.
- Add a new database column. The existing policy field already holds the
choice, so a migration is not necessary.

## What Changed

- `resolveProjectWorkspaceProvider` reads only the saved choice. It no
longer applies an installed default.
- `withDefaultProjectStorage` applies the default when Core creates a
project, including a personal private project. With more than one
default, a project with no explicit choice is refused. This is the
existing conflict rule, now applied at creation.
- `projectService.update` refuses a change of storage on a plugin-backed
project. An update that omits the field keeps the attachment.
- Plugin lifecycle delivery sends project events to a storage provider
only for projects attached to it, and for deleted projects. Core
acknowledges the other events for that provider. Other plugins continue
to receive all project events.
- The project settings control has no "Inherit" option. It is locked on
a plugin-backed project.
- `ProjectWorkspaceProviderConfiguration.source` no longer has the
`"default"` value.
- A project with no repository or folder ignores its saved storage
choice when a task runs. A storage plugin cannot manage this type of
project, so its tasks use a plain task directory. Without this change,
the second run of a task reset the agent session, and remote agents
could not use an empty task directory.
- The plugin SDK README and the plugin authoring guide describe the new
rules.

## Verification

- `npx vitest run
server/src/__tests__/project-workspace-provider.integration.test.ts
server/src/__tests__/plugin-lifecycle-delivery.test.ts
server/src/__tests__/plugin-workspaces.integration.test.ts
packages/plugins/sdk/tests/workspace-provider.test.ts`: 93 tests pass.
- `npx vitest run src/components/ProjectProperties.concurrency.test.tsx`
in `ui/`: 9 tests pass.
- `pnpm --filter @paperclipai/server typecheck` and `pnpm --filter
@paperclipai/ui typecheck` pass.
- `npx vitest run` on `heartbeat-session-preparation`,
`workspace-preparation`, `remote-workspace-source`,
`project-workspace-provider.integration`, and
`plugin-workspaces.integration` in `server/`: 231 tests pass.
- I did not run the full test suite locally. CI runs it.
- I did not test this change on a running instance.

## Risks

- **Behavior change at upgrade:** an existing project that uses a plugin
only through the installed default, with no saved choice, moves to
Core/local storage after upgrade. Its plugin files stay in place, but
new work does not use them until an operator sets
`storageProviderPluginId` on the project. This pull request has no
automatic backfill.
- **Missed lifecycle events:** a provider does not receive events for a
Core/local project. If the project moves to that provider later, the
update event starts its reconcile.
- **One-way move:** a person cannot move a plugin-backed project back
through the API or the UI. This is intended. If a plugin is disabled,
the project fails closed, as it does today for an explicit choice.
- This pull request does not stop a person from assigning an agent to a
project with storage that the agent cannot reach. That is follow-up
work.
- This changes core plugin behavior, and I did not discuss it in `#dev`
first. Maintainers can tell me if they want a discussion before review.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code, with tool
use and code execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:07:29 -08:00

182 lines
9.9 KiB
TypeScript

import { projectInstanceSecretService } from "./project-instance-secrets.js";
import { and, asc, eq, isNull, or, sql } from "drizzle-orm";
import { pluginCompanySettings, pluginConfig, plugins, projects, type Db } from "@paperclipai/db";
import { logger } from "../middleware/logger.js";
import { pluginLifecycleInbox } from "./plugin-lifecycle-inbox.js";
import { DELIVERY_QUEUES } from "./delivery-work-notifications.js";
import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js";
import { parseProjectExecutionWorkspacePolicy } from "./execution-workspace-policy.js";
import { isWorkspaceProvider } from "./project-workspace-provider.js";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
import type { PluginLifecycleManager } from "./plugin-lifecycle.js";
type Coordinator = ReturnType<typeof createDeliveryWorkCoordinator>;
/** The journal is the queue. Notifications only wake its single local dispatcher. */
export function registerPluginLifecycleDelivery(
coordinator: Coordinator,
db: Db,
manager: Pick<PluginWorkerManager, "call" | "isRunning" | "onConfigApplied">,
lifecycle: Pick<PluginLifecycleManager, "on" | "off">,
) {
// 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 refreshedRuntimeCompanies = new Set<string>();
const retryMs = 30_000;
const delivery = coordinator.register(DELIVERY_QUEUES.pluginLifecycle, {
retryMs,
hasPending: async () => pending,
onSettled: () => { pending = true; },
nextRunAt() {
if (!pending) return null;
let next: number | null = null;
for (const at of retryAt.values()) {
// An expired deadline during idle drain must not schedule a busy loop.
if (at > Date.now() && (next === null || at < next)) next = at;
}
return next;
},
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))
.where(eq(plugins.status, "ready"))
.orderBy(asc(plugins.installOrder), asc(pluginConfig.companyId));
for (const { plugin, companyId } of configured) {
const types = plugin.manifestJson.resourceLifecycle;
if (!types?.length || !plugin.manifestJson.capabilities.includes("events.subscribe")) continue;
const [disabled] = await db.select({ id: pluginCompanySettings.id }).from(pluginCompanySettings)
.where(and(eq(pluginCompanySettings.pluginId, plugin.id), eq(pluginCompanySettings.companyId, companyId), eq(pluginCompanySettings.enabled, false)));
if (disabled) continue;
if (types.includes("agent_runtime") && !refreshedRuntimeCompanies.has(companyId)) {
await db.execute(sql`SELECT paperclip_invalidate_company_agent_runtimes(${companyId}::uuid)`);
refreshedRuntimeCompanies.add(companyId);
}
const inbox = pluginLifecycleInbox(db, plugin.id);
let afterId: string | undefined;
// Visit independent resources past a failed or deferred head.
for (;;) {
if (signal.aborted) return;
const events = await inbox.list(companyId, 100, afterId, types);
for (const event of events) {
if (signal.aborted) return;
const retryKey = `${plugin.id}:${event.id}`;
if (retryAt.has(retryKey)) { pending = true; continue; }
if (!manager.isRunning(plugin.id)) { pending = true; break; }
let stage = "eligibility";
try {
// Recheck enablement for each invocation; a disable during a batch must stop delivery.
const [enabled] = await db.select({ manifest: plugins.manifestJson }).from(plugins)
.leftJoin(pluginCompanySettings, and(eq(pluginCompanySettings.pluginId, plugins.id), eq(pluginCompanySettings.companyId, companyId)))
.where(and(eq(plugins.id, plugin.id), eq(plugins.status, "ready"),
or(isNull(pluginCompanySettings.enabled), eq(pluginCompanySettings.enabled, true))));
if (!enabled?.manifest.resourceLifecycle?.includes(event.resourceType) || !enabled.manifest.capabilities.includes("events.subscribe")) break;
if (event.resourceType === "project" && isWorkspaceProvider(enabled.manifest)) {
stage = "ownership";
const [project] = await db.select({ policy: projects.executionWorkspacePolicy }).from(projects)
.where(and(eq(projects.id, event.resourceId), eq(projects.companyId, companyId)));
if (project && parseProjectExecutionWorkspacePolicy(project.policy)?.storageProviderPluginId !== plugin.id) {
await inbox.acknowledge(companyId, event.id);
wake();
continue;
}
}
stage = "credentials";
const credentials = event.resourceType === "project" && enabled.manifest.capabilities.includes("projects.instance-secrets")
? await projectInstanceSecretService(db, plugin.id).prepare(event) : undefined;
stage = "callback";
const result = await manager.call(plugin.id, "resourceLifecycle", credentials ? { ...event, instanceSecrets: credentials.instanceSecrets } : event, 30_000);
stage = "result";
if (result?.eventId !== event.id || !["acknowledged", "retry", "deferred"].includes(result.status)) {
throw new Error("Invalid resource lifecycle result");
}
if (signal.aborted) return;
if (result.status === "acknowledged") {
stage = "acknowledgment";
if (result.instanceSecrets !== undefined && !credentials) throw new Error("Project instance secrets outside callback scope");
await inbox.acknowledge(companyId, event.id, credentials ? { snapshot: credentials.snapshot, changes: result.instanceSecrets ?? {} } : undefined);
// An acknowledgment exposes the next event for this resource. Drain immediately.
wake();
} else if (result.status === "retry") {
retryAt.set(retryKey, Date.now() + retryMs);
pending = true;
}
} catch (error) {
retryAt.set(retryKey, Date.now() + retryMs);
// Provider error messages/data may contain secrets; retain only routing
// identifiers, the failed stage, and the protocol's numeric error code.
const code = (error as { code?: unknown } | null)?.code;
logger.warn({ pluginId: plugin.id, companyId, eventId: event.id, stage,
...(typeof code === "number" ? { rpcCode: code } : {}) }, "Resource lifecycle delivery failed; retry scheduled");
// Failed RPCs and uncertain acknowledgments leave durable work for replay.
pending = true;
}
}
if (events.length < 100) break;
afterId = events.at(-1)!.id;
}
}
} catch (error) {
pending = true; // A failed scan must survive a retry skipped during idle drain.
throw error;
}
},
});
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", 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);
},
};
}