mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-19 16:29:42 +01:00
ebb98120dc1334af7b0236bcef44d45512fffbfb
917
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
067f7a0815 |
feat(telemetry): send product lifecycle events and agent run failure cause (#22250)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - First-party telemetry tells the team which product steps people finish > - Telemetry did not record when a model is connected, when a task is created, completed, or blocked, when a plan is created or approved, or when an artifact is created > - Telemetry also did not tell why an agent run failed, so failures could not be grouped by cause > - This pull request syncs the new telemetry contract and sends these events from the server once per real change > - The benefit is a product funnel and a failure breakdown that use only enums, booleans, and counts ## Linked Issues or Issue Description **Subsystem affected** Server telemetry (`packages/shared/src/telemetry`, `server/src/services/product-telemetry.ts`) and the emit sites in the issue, document, work product, interaction, and AI connection services. **Problem or motivation** The team cannot measure the main product path. There is no event for a new model connection, a new task, a completed task, a blocked task, a new plan, an approved plan, or a new artifact. `agent.task_run` tells that a run failed, but not why. The signup funnel also must know when the onboarding wizard created the first task. **Proposed solution** Register the events in the telemetry backend. Sync the generated contract here. Add typed helpers. Send each event once, after the transaction that makes the change commits. Use fixed enums for every kind, reason, and cause. **Alternatives considered** A post-commit action queue on the issue service only. The native status path and many other callers use an external transaction without that queue, so most agent completions would not send an event. A generic after-commit hook on the database client covers every caller. **Roadmap alignment** This is telemetry for existing features. It adds no new product feature. **Additional context** This change depends on paperclipai/telemetry-backend#150, which is merged. Deploy that backend change before this change ships. Until then, the collector rejects the new event names. ## What Changed - Sync `generated/paperclip-telemetry.ts` from the backend branch as a direct copy. Regenerate `posthog-direct/enum-fallbacks.generated.ts` with `scripts/generate-posthog-direct-fixtures.mjs`. The loader golden file did not change. - Add `afterTransactionCommit()` to `@paperclipai/db`. It runs a callback after the outermost transaction commits. It drops the callback on rollback. Outside a transaction it runs the callback at once. A callback that throws never fails the committed work. - Add helpers `trackModelConnected`, `trackTaskCreated`, `trackTaskCompleted`, `trackTaskBlocked`, `trackPlanCreated`, `trackPlanApproved`, and `trackArtifactCreated`. Add `failureCause` to `trackAgentTaskRun`. Assign the new events to `operational_enum_count` retention. - Add `server/src/services/product-telemetry.ts`. It sends each event after commit inside `withTelemetryCompany()`, so Cloud direct delivery gets `company_id` for background writes. - Emit sites: - `model.connected`: `aiConnectionService.save`, for a new connection only. A reconnect sends nothing. `first_for_company` is true when the company had no earlier model connection. - `task.created`: `issueService.create`, after the insert. A deduplicated create, a company import, and a chat conversation send nothing. `created_by_kind` is `routine` for routine runs, `onboarding` for the onboarding wizard's first task, and otherwise `user`, `agent`, or `system`. - `task.completed` and `task.blocked`: `issueService.update`, when the status changes to `done` or `blocked`. The same status again sends nothing. - `plan.created`: `documentService.upsertIssueDocument`, for the first revision of the `plan` document. - `plan.approved`: the accept path of a `request_confirmation` that targets the task's `plan` document. - `artifact.created`: `workProductService.createForIssue` (`direct`), the promotion route (`promotion`), and a run file deliverable (`run_deliverable`). - `agent.task_run.failure_cause`: `emitAgentTaskRun`, for `failed`, `timed_out`, and `interrupted` runs only. - `blocked_reason` mapping: unfinished blocking tasks give `waiting_on_task`. Otherwise an unblock owner of a person or the board gives `waiting_for_person`, and an agent owner gives `waiting_for_agent`. A system write with neither gives `needs_recovery`. A person or agent write with neither gives `unspecified`. - `failure_cause` mapping (stored `errorCode`, with `resultJson.providerFailure.category` for generic provider and adapter codes): - `missing_access`: auth and permission codes (`acpx_auth_required`, `provider_auth_failed`, `user_secret_missing`, `github_access_denied`, `github_repo_not_accessible`, `permission_denied`, `project_access_denied`, `configuration_incomplete`, `connection_unavailable`, `signing_secret_unconfigured`), and provider category `authentication` or `permission`. - `provider_limit`: `provider_quota`, `native_provider_usage_limit`, `native_provider_overloaded`, `github_rate_limited`, `ai_connection_busy`, and provider category `rate_limit`, `quota_exhausted`, or `overloaded`. - `provider_error`: `native_provider_model_rejected`, `provider_transport_failed`, `codex_transient_upstream`, `provider_failed`, `provider_tool_definition_invalid`, and the other provider categories. - `waiting_for_person`: `execution_reconciliation_required`, every code in `EXECUTION_RECONCILIATION_CAUSES`, `issue_waiting_for_response`, and `issue_continuation_waiting_on_review`. - `task_changed`: the task was reassigned, paused, closed, blocked, or stopped by a person (`operator_interrupted`, `cancelled`, `interrupted`, `issue_*` lifecycle codes, `agent_paused`, `queued_comment_discarded`). - `platform_error`: process, server, workspace, sandbox, runner, and storage codes (`process_lost`, `server_shutdown_interrupted`, `setup_failed`, `workspace_*`, `environment_provider_unavailable`, `controller_lease_lost`, and others). - `agent_error`: `adapter_failed` without a provider failure, `invalid_output`, `invalid_response`, `tool_error`, `acpx_turn_failed`, `test_run_failed`, `prompt_injection_blocked`, `tool_execution_outcome_unknown`, `timeout`. - `unknown`: any other code, or no code. - On Cloud direct delivery, every new emit site names the responsible person with `withTelemetryActor()` and `resolveTelemetryPerson()`, as `agent.task_run` does: the task creator, else the task's responsible user, else the run owner. `task.created` uses the creating user, else the agent's on-behalf user. `model.connected` uses the user who owns the connection. A live request still wins. The self-hosted collector envelope does not change. - `failure_cause` builds on the run failure code sets in `continuation-cause.ts`. A test fails when a code in those sets has no telemetry code. The provider failure category decides only for `adapter_failed`, `provider_failed`, or no code. - Work product providers outside `paperclip`, `github`, `vercel`, and `s3` are sent as `custom`. - The dispatch workspace check and execution recovery write `blocked` directly. They call the same after-commit helper, with the task's real blockers and unblock owner. The blocker read runs in a savepoint in the issue dependency layer, so a failed read never aborts the block write. - Update the telemetry README with the emit rules, the after-commit rule, and the `failure_cause` source. - Refresh `tests/runner-e2e/source-sdk-public-inputs.json`, because its check reported a change. ## Privacy Review Privacy review requested. Every new dimension is a fixed enum, a boolean, or a count. No dimension carries a title, a body, a plan step, a connection or account name, an email, a URL, a repository name, a prompt, an error message, or an endpoint address. `failure_cause` is a code that the server picks. The run's error text is never sent. The tests check that a provider message and a connection name do not reach the event. ## Verification - `pnpm vitest run packages/shared/src/telemetry/`: 7 files pass, including the new `product-events.test.ts` (helper payloads, omitted optional values, collector envelope with only registered dimensions, retention class). - `packages/db/src/after-transaction-commit.test.ts`: 4 pass (after commit, rollback drop, savepoint, outside a transaction). - `server/src/__tests__/product-telemetry.test.ts`: 14 pass. They check that each event fires once with the right kind and company scope, that a rollback sends nothing, that a repeated status sends nothing, that a later plan revision sends nothing, and that a reconnect sends nothing. - `server/src/__tests__/agent-task-run-telemetry.test.ts`: 35 pass, including the `failure_cause` mapping table and the emit path. - `server/src/__tests__/issue-thread-interactions-service.test.ts -t Plan`: `plan.approved` fires for a plan confirmation and not for an unrelated confirmation. - `server/src/__tests__/posthog-direct-telemetry.test.ts`: the Cloud direct path sends `company_id`, `user_id`, and `attributed_via` for background lifecycle events, an event with no person stays on the workspace, and `failure_cause` passes through. A self-hosted test checks that a person scope leaves the collector events unchanged. - Existing telemetry tests (connector, interaction, run finalizer, heartbeat, AI connection): 299 pass. - `pnpm --filter @paperclipai/shared typecheck`, `pnpm --filter @paperclipai/db typecheck`, and `pnpm --filter @paperclipai/server typecheck`: pass. - `pnpm verify` returned exit 2 (global CI input changed). Required CI supplies the broad coverage. ## Risks - Merge order: merge and deploy paperclipai/telemetry-backend#150 first. If this change ships first, the collector quarantines the new events. The product behavior does not change. - `afterTransactionCommit` uses the existing open-transaction marker in the database client. A callback that a savepoint registers runs when the outer transaction commits, even if that savepoint rolled back. - `task.blocked` adds one small indexed read inside the update transaction, only when a task enters `blocked`. - `failure_cause` adds one small read for a failed run when the caller did not pass the error code. It runs off the run's critical path, as before. - Low risk otherwise. No schema migration. No change to existing event dimensions. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code, with tool use (shell, Git, tests). ## 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> |
||
|
|
92dbf39e6f |
feat(analytics): attribute agent work and onboarding steps to a person on Cloud (#22260)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud sends product events straight to PostHog: server
events from `server/src/services/posthog-direct/` and browser events
from `ui/src/lib/analytics/`
> - A person-level funnel goes from sign-up to the first finished task
> - Agent-driven events (`agent.task_run`, `agent.task_completed`,
`agent.first_heartbeat`) used `workspace:<stackId>` as the distinct id,
so the funnel broke at those steps
> - The in-workspace onboarding wizard sent no step events, so we could
not see where people stop before their first agent
> - This pull request attributes agent work to the responsible person on
the Cloud direct path, and adds consent-gated onboarding step events in
the browser
> - The benefit is one PostHog person per customer across sign-up,
onboarding, agent runs, and task completion. Self-hosted output does not
change.
## Linked Issues or Issue Description
**Subsystem affected**
Cloud product analytics: Cloud direct PostHog delivery (server) and
browser product analytics (UI onboarding wizard).
**Problem or motivation**
A PostHog funnel from sign-up to the first finished task cannot follow
one person. Agent-driven events run in the background, with no signed-in
request, so they use the workspace id as the distinct id. The onboarding
wizard also sends no events, so we cannot see which step people leave.
**Proposed solution**
Give background emit sites a narrow scope that names the person
responsible for the work. Use the task creator first, then the task's
responsible user, then the run owner. Keep the signed-in request user
first. Add `attributed_via` to every Cloud direct event. Add four
browser events to the onboarding wizard. Send them through the existing
analytics module, so the consent rules stay the same.
**Alternatives considered**
A lookup in the transport at send time. We did not use it: it adds
database reads to the telemetry path and loses the emit site's context.
A new contract event for onboarding steps. We did not use it: the server
does not see the wizard steps, and the UI must never send
`PAPERCLIP_EVENTS` names.
**Additional context**
Self-hosted installs keep the collector path. The collector envelope
stays byte-identical (a test checks it).
## What Changed
- `server/src/telemetry-company-scope.ts`: add `withTelemetryActor({
companyId, person }, fn)`, `scopedTelemetryPerson()`, and
`resolveTelemetryPerson()`. The resolver picks the task creator, then
the task's responsible user, then the run owner. It ignores
`local-board`. `withTelemetryCompany` now calls `withTelemetryActor`.
- `server/src/services/posthog-direct/request-context.ts`: a signed-in
request user wins (`attributed_via: request`). Without one, the scoped
person is used.
- `server/src/services/posthog-direct/event-shape.ts`: every Cloud
direct event (including `cloud.workspace_started`) has `attributed_via`
(`request`, `task_creator`, `task_assigner`, `run_owner`, or `none`). An
event with a person keeps today's person-event shape (no
`$process_person_profile: false`).
- `server/src/services/agent-task-run-telemetry.ts`: `agent.task_run`
reads the task creator and responsible user in the existing agent query
(one left join, no new query), and the run's `responsibleUserId`.
- `server/src/routes/issues.ts`: `agent.task_completed` uses the issue
row that the route already has, and the agent actor's `onBehalfOfUserId`
as the run owner.
- `server/src/services/heartbeat/agent-status.ts`:
`agent.first_heartbeat` uses the agent's `createdByUserId` (already
loaded) as the run owner.
- `ui/src/lib/analytics/product-analytics.ts`: add
`captureProductAnalyticsEvent()`. It captures only with a browser
analytics config and granted consent. Events from before posthog-js
loads wait in a queue (at most 50) and keep their time. Withdrawn
consent or a change of signed-in person drops the queue.
- `ui/src/lib/analytics/onboarding-analytics.ts` and
`ui/src/components/OnboardingWizard.tsx`: capture `onboarding_opened`,
`onboarding_step_viewed`, `onboarding_step_completed` (with `step` and,
for `connect_model` and `launch`, `outcome`), and
`onboarding_dismissed`. `step` is `create_agent`, `connect_model`,
`review`, or `launch`. No event has free text.
- Docs: `packages/shared/src/telemetry/README.md` (Cloud Direct
Delivery) and `doc/cloud-browser-analytics.md` (new "Onboarding events"
section).
## Verification
- `server/src/__tests__/posthog-direct-telemetry.test.ts`: attribution
matrix (creator, assigner, run owner, none stays on
`workspace:<stackId>` with `$process_person_profile: false`), the
request user wins over the scope, and the self-hosted collector envelope
is byte-identical with a person scope.
- `server/src/__tests__/agent-task-run-telemetry.test.ts` (embedded
Postgres): `agent.task_run` scope for creator, assigner, run owner, and
nobody; another company's task is never read.
- `server/src/__tests__/issue-telemetry-routes.test.ts`:
`agent.task_completed` scope for creator and assigner.
- `server/src/__tests__/heartbeat-process-recovery.test.ts`:
`agent.first_heartbeat` scope is the agent owner.
- `ui/src/components/OnboardingWizard.test.tsx`: a launch for the old
company that settles after a switch to another company does not end the
new analytics session.
- `ui/src/lib/analytics/onboarding-analytics.test.tsx`: each transition
fires once, held events drop on a person change, a stale opening step is
not a view, dismissal fires once, nothing is captured when analytics is
off or consent is `denied` or `ask`, and queued events keep their time.
- `ui/src/lib/analytics/product-analytics-events.test.ts` still passes
(the UI never captures a `PAPERCLIP_EVENTS` name).
- Local Cloud-mode run: an isolated instance (own Postgres, trusted
Cloud tenant headers, `PAPERCLIP_POSTHOG_HOST` set to a local capture
server, never real PostHog). A stub stood in for posthog-js and sent
through the `/_ph` proxy.
- A user created a task and assigned it to the agent. `agent.task_run`
arrived with `distinct_id: paperclip-id:local-user-1`, `attributed_via:
task_creator`, the raw `task_id`, and no `$process_person_profile`. (The
run itself failed locally because the Cloud runner is not available. The
event still shows the attribution.)
- `agent.first_heartbeat` arrived with the same person and
`attributed_via: run_owner`. `server.started` kept
`workspace:stack-local` with `attributed_via: none`.
- Headless Chromium walked the wizard: `onboarding_opened`
(create_agent), `onboarding_step_viewed` (create_agent),
`onboarding_step_completed` (create_agent), `onboarding_step_viewed`
(connect_model), `onboarding_step_completed` (connect_model, `api_key`),
`onboarding_step_viewed` (review), `onboarding_step_completed` (review),
`onboarding_step_completed` (launch, `succeeded`). Each fired once, with
the signed-in user as the distinct id. Events from before posthog-js
loaded arrived with their original time.
- A second walk left the onboarding page on the connect step and sent
one `onboarding_dismissed` (connect_model).
## Risks
- Low risk for self-hosted: the collector path never reads the new
scope, and a test checks the envelope bytes.
- Cloud: agent events move from the workspace person to a real person.
Insights that count `workspace:` distinct ids for these events will
change. `attributed_via` lets a query filter or split them.
- `task_assigner` uses the task's responsible user. Paperclip does not
store who assigned a task, so this is the person who owns or delegated
the task.
- Privacy: the new data is Cloud-only and uses ids that Cloud events
already carry. No new free text, email, or name goes on an event.
**Privacy review requested** for the Cloud attribution change (per
`rules/data-paths.mdc`). The generated contract does not change:
`attributed_via` is a Cloud-only property, like `stack_id` and
`user_id`.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, headless browser).
## 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
- [x] All Paperclip CI gates are green
- [x] 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>
|
||
|
|
c600d69242 |
Let plugin connectors declare their tool timeout (#22249)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Plugins can serve connector tools from their worker (`transport: "plugin"`, added in #22004, #22019 and #22201). > - The tool gateway runs these tools with a fixed 10 s default timeout. > - Some plugin tools call backends that take 12–20 s. These calls fail every time with "Tool execution timed out", even though the plugin's own HTTP client waits much longer. > - The plugin connector design said that the connector, not a fixed gateway constant, sets the timeout. > - This pull request lets a plugin method or a single static tool declare `timeoutMs`, and gives plugin-served tools a 30 s default. > - The benefit is that a plugin connector can serve slow tools like other connectors can, within the same 60 s gateway ceiling. ## Linked Issues or Issue Description Refs #22004, #22019, #22201. Refs #20746. **Relationship to #20746.** This PR builds alongside #20746. It does not supersede it. #20746 changes the default for legacy top-level plugin tools (provider `paperclip_plugin`) to 60 s. This PR changes only plugin-served connector tools (provider `paperclip_plugin_connection`, `transport: "plugin"`). The two PRs touch different branches of the gateway and can merge in either order. This PR does not pin the legacy default in its tests, so #20746 does not break them. **Current behavior** A plugin connector tool always times out after 10 s, unless the caller sends `timeoutMs`. Agents and runners do not send it. The worker RPC also stops at 30 s. **Proposed behavior** A plugin can declare `timeoutMs` (1000–60000 ms) on a `transport: "plugin"` method or on one static tool. The gateway uses that value. If nothing is declared, the gateway waits 30 s. **Reason and benefit** Plugin tools whose backends take longer than 10 s can now work. Plugin authors control the value in the manifest, and the gateway keeps its 60 s ceiling. **Breaking changes** None. Existing manifests stay valid. Only plugin-served tools get the new 30 s default. ## What Changed - `packages/shared`: `timeoutMs` is a new optional field on `ConnectionMethodDef` and on `PluginConnectorToolDef`. The validator accepts integers from 1000 to 60000 only. It rejects `timeoutMs` on methods that do not use `transport: "plugin"`. New exported constants: `PLUGIN_CONNECTOR_TOOL_TIMEOUT_MIN_MS`, `PLUGIN_CONNECTOR_TOOL_TIMEOUT_MAX_MS`, and `PLUGIN_CONNECTOR_TOOL_DEFAULT_TIMEOUT_MS` (30000). - `server/src/services/plugin-connector-runtime.ts`: `pluginConnectionToolTimeoutMs()` resolves the timeout in this order: the tool's value, then the method's value, then 30 s. The worker `executeTool` RPC now gets the gateway timeout plus 1 s. Thus the gateway's `tool_timeout` error is what callers see, and the 30 s RPC default no longer cuts off a longer declared timeout. - `server/src/services/tool-gateway.ts`: `executePluginConnectionTool` now applies the timeout itself, after it loads the connection. All three plugin paths use it: session, assigned-tool and direct calls (`executeTool`), test calls (`executeTestCall`), and approved action execution. If a caller sends `timeoutMs`, that value wins, as before. It is still clamped to 60 s. Approved actions keep their fixed 60 s budget. - Other transports do not change. Remote MCP, local stdio, built-in and legacy plugin tools keep their timeouts. (#20746 separately proposes a 60 s default for legacy plugin tools.) - Docs: `doc/plugins/PLUGIN_SPEC.md` §11A and the plugin SDK README describe the field, its range, and the default. The SDK manifest type gets the field from `@paperclipai/shared`. ### Why 30 s 30 s is the same as the plugin worker manager's default RPC timeout. So, before this change, the worker already allowed 30 s, and only the gateway's 10 s limit stopped the call. With 30 s, the common 12–20 s backend case works without a declaration. It is also well under the 60 s ceiling. Tools that need more time can declare up to 60 s. ## Verification - New `server/src/__tests__/plugin-connector-tool-timeout.test.ts` runs the real gateway invocation path against an embedded Postgres and a fake worker. Fake timers make the 12 s backend free in wall-clock time: - With method `timeoutMs: 30000`, a 12 s tool succeeds through `executeTool` and through `executeTestCall`. The worker RPC timeout is 31000. - With tool `timeoutMs: 5000`, a 12 s tool fails at 5 s with `504 tool_timeout`. - With no declaration, a 12 s tool succeeds (it failed at the old 10 s), and a 45 s tool times out at 30 s. - Manifest values above 60000, below 1000, or not integers are rejected. A caller `timeoutMs: 120000` is clamped to 60 s. - A legacy plugin tool (`paperclip_plugin`, a different provider path) never reaches the connector runtime, and a caller deadline still applies. This test does not pin the legacy default, because #20746 changes it. - Remote MCP, local stdio and REST timeouts do not change in this PR. Their existing timeout tests in `tool-gateway.test.ts` and `google-workspace-rest-transport.test.ts` still apply. - Red/green: with the source change reverted, 4 of these 5 tests fail. The legacy-tool test passes both ways, as expected. - `packages/shared/src/plugin-apps.test.ts`: validation cases for the range, non-integer values, and non-plugin methods. - Commands run: - `pnpm --filter @paperclipai/shared typecheck && pnpm --filter @paperclipai/server typecheck && pnpm --filter @paperclipai/plugin-sdk typecheck` - `cd server && npx vitest run src/__tests__/plugin-connector-tool-timeout.test.ts src/__tests__/plugin-connectors-plugin-transport.test.ts src/__tests__/plugin-connector-agent-grant.test.ts` (20 passed) - `cd packages/shared && npx vitest run src/plugin-apps.test.ts src/app-definitions.test.ts` (76 passed) - `pnpm check:module-boundaries` - Full suite not run locally. CI supplies it. ## Risks - Low risk. Plugin-served tools now wait up to 30 s instead of 10 s by default. An agent turn can wait longer for a slow or stuck plugin tool, but never longer than the existing 60 s ceiling. - The connection row lookup now runs before the timeout timer starts. This is one indexed query. - Dynamic tool lists (`kind: "dynamic"`) use the method's `timeoutMs`. Per-tool values apply to static tools only. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code with tool use (shell, file edits, test runs). ## 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> |
||
|
|
d4b7ae5532 |
fix(tasks): require merged PR deliverables before native completion (#22244)
Keep native tasks with declared pull request deliverables active until
GitHub verifies every deliverable is merged. Preserve delivery guidance
in follow-up contracts and recheck the current outputs under task locks.
Use bounded incomplete-work feedback during reassessment, including for
saved non-Done reports. Serialize work-product restoration and identity
changes with completion. Preserve configured reviews and conversations.
Add regression coverage and repair the CI fixtures exposed during
qualification. All CI checks pass on
|
||
|
|
52cf30f131 |
test(release-smoke): follow onboarding into the standing chat (#22259)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The release workflow runs a Docker onboarding smoke on the real npm artifact before it publishes a nightly or beta > - #22077 changed onboarding. "Get started" now opens the lead's standing chat. It does not create a first task or project > - That PR updated the e2e tests, but it did not update the release smoke > - The smoke still expects an `/issues/` landing, so every nightly smoke fails, and no nightly can publish > - This pull request changes the smoke to assert the new chat-first contract > - The benefit is that the nightly lane can publish again, and the smoke still guards the first-run experience ## Linked Issues or Issue Description Refs #22077 **What happened?** The release smoke `docker-auth-onboarding.spec.ts` fails at `expect(page).toHaveURL(/\/issues\//)`. The page is on `/<prefix>/chats/<agent id>`. The failure occurs on the first attempt and on the retry. The scheduled nightly on 2026-11-18 and a dispatched nightly for `2026.1118.0-canary.828200` both failed at this step. **Steps to reproduce** 1. Run the release workflow with `channel=nightly` on a canary that contains #22077. 2. Look at the `smoke_nightly / smoke` job. **Expected behavior** The smoke follows onboarding into the chat and passes when the artifact works. ## What Changed - Expect the launch to land on `/chats/<lead agent id>`, not on `/issues/`. - Assert that the task list and the project list are empty after launch. - Assert that exactly one chat exists, with `originKind: "onboarding_chat"`, no project, and the lead as `conversationAgentId`. - Assert that the chat composer renders. - Replace the old "no run" check. Now the smoke polls until the live welcome run is queued for the lead. The provider mock serves no completions, so the smoke does not check the welcome text. - Remove the `FIRST_TASK_TITLE` constant, because onboarding no longer seeds a task. ## Verification - `tsc --noEmit --strict` on the spec passes. - I checked the asserted fields against `server/src/services/onboarding-chat.ts`, `GET /companies/:companyId/chats` and `tests/e2e/conference-room-typing-intro.spec.ts`. - Full check: the `Release Smoke` workflow (or a nightly dispatch after merge) must pass the `smoke` job. ## Risks - Low risk. The change is test-only. - The welcome-run assertion depends on the UI requesting the welcome in a visible headless tab. If that is not true in CI, the poll times out after 30 seconds. Then remove or relax that one assertion. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with tool use (shell, GitHub CLI). ## 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 - [ ] 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 - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
4434714824 |
Fix sidebar Recents task order and archive visibility (#22251)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The sidebar gives people quick access to tasks, chats, and projects they recently opened. > - Expanding a parent or project in Recents can show tasks the person never opened. > - Archiving a task from the inbox leaves it in Recents. > - This change gives each recent task its own row and removes tasks archived for the current viewer. > - People can reopen an individual task and keep saved shortcuts above More. ## Linked Issues or Issue Description **What existing behavior does this improve?** Recents in the Standard and Classic sidebars. **Subsystem affected** Board navigation and task summaries. **Current behavior** Opening a parent or project can show other tasks beneath it. A recent subtask moves its parent group when reopened. Archiving a task leaves its recent link visible. **Proposed behavior** Show each visited task in its own row, in recent activity order. Keep canceled and completed tasks eligible. Remove tasks archived for the current viewer from Recents. Preserve saved pins. **Reason and benefit** People can find the task they opened by its own position in the list. Archiving removes its recent link without removing a saved shortcut. **Breaking changes** The Recents rows no longer expand into task lists. Project links still open the project. The navigation summary adds an optional personal archive flag. Related work: #22219, #22024, #21904, and #20450. ## What Changed - Render task, agent chat, and project rows directly in Standard Recents. Keep the existing controls to pin each kind of row. - Render standalone task rows with the existing Classic action menus. Remove sidebar child loading and refresh code. - Derive the viewer’s archive state using the existing inbox rule. Filter archived tasks out of Recents while retaining authorized pinned shortcuts. - Cover independent parent and child order, canceled and archived tasks, pin retention, and the Classic Archive action. ## Verification - Reproduced the empty Recents row after cancellation before the fix. - On the rebased branch, 424 focused UI and live-update tests and the UI typecheck passed on macOS. - Ran 77 issue-summary and OpenAPI integration tests with embedded PostgreSQL on macOS. The Runner source SDK registry check passed on the pushed revision. - The updated sidebar test renders 402 recent rows. A deliberate repeated task lookup made the input-read guard fail. The restored implementation passed. - The paused-assignee browser test checks the task detail heading in each interface. Both variants reproduced the CI locator failure locally and passed with the scoped locator. - All 17 focused Storybook browser checks passed in Chromium on macOS. - Run `pnpm verify` for local selection. The product documentation change requests broader GitHub CI coverage. - Open a parent task and a child task in either sidebar. Reopen the child and check that its row moves ahead of the parent. Cancel the child and check that it stays visible. Archive it and check that its recent row disappears. - On commit `8051038099`, [GitHub CI](https://github.com/paperclipai/paperclip/actions/runs/44421716811) passed, including the required verification and end-to-end checks. - [Greptile](https://github.com/paperclipai/paperclip/pull/22251#issuecomment-6994494812) rated the same commit 5/5. Its review thread is resolved. ## Risks - Recents uses the same viewer-specific archive rule as the inbox. Archiving prunes the local recent entry. A restored task can enter Recents again when opened. - Task summaries still return authorized tasks for saved pins. Child and unread counts remain in the existing API response for older clients. - The change requires no database migration. ## Model Used - OpenAI GPT-6 via Codex with shell, GitHub CLI, Vitest, and Chromium. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Scott Tong <1504818+scotttong@users.noreply.github.com> Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
3f263e4faf |
feat(ui): align routine controls and remember list views (#22182)
## Thinking Path > - Paperclip helps people manage AI agents and their work. > - Routines define recurring work and create tasks. > - People need the same controls to find and inspect routines as they use for tasks. > - The routine list had different search controls and no detailed filters or column choices. > - This pull request aligns the controls and remembers each person's view. > - People can share a filtered link and see the responsible person beside the agent. ## Linked Issues or Issue Description **What existing behavior does this improve?** The Routines list controls and metadata in the current and classic interfaces. **Subsystem affected** ui/ — the React board. **Current behavior** Routines use different search controls from Tasks. The list has limited view settings and no filters for project, agent, enabled state, responsible person, or source. Routine metadata is fixed. **Proposed behavior** Show New routine on the left. Show Search, Sort, Filter, Group, Columns, and View all tasks on the right, in that order. Use the shared Tasks search and filter controls. Show the responsible person next to the agent. Let people choose metadata columns. Save filters, search, sort, and grouping in the URL. Remember view settings per person and company in local storage. Use a play icon for manual runs. **Reason and benefit** People can scan routine ownership, find a subset, share its link, and return to their preferred columns and view. **Breaking changes** The list uses metadata columns with horizontal scrolling on narrow screens. Existing company-level sort and group preferences are read as a fallback. No API or database change is required. Related work: Refs #22009, Refs #18606, Refs #18317. The open PR search found no duplicate of this list-control change. ROADMAP.md lists Routines as shipped and has no overlapping control work. ## What Changed - Align both Routines toolbars with the requested order and shared search and button styles. - Extract the existing Tasks filter group and checkbox row for reuse by Routines. - Add project, agent, enabled, responsible person, and source filters. - Keep linked filters ahead of saved filters. Preserve unrelated URL parameters. - Save preferences per person and company. Keep the controls usable when storage is unavailable. - Add selectable Project, Agent, Responsible user, Last run, and Enabled columns. - Use play-only manual run buttons with accessible names and pending indicators. - Correct the empty message when a status filter excludes every routine. - Add production-page Storybook examples and browser tests for both interfaces. ## Verification - Linux checkout, Node 25.9.0, system Chromium 148.0.7778.96. - The final change includes master through `07d9316218`. It uses the shared routine creation form and the upstream Runner test and SDK source-pin fixes. - 68 tests pass across eight focused UI suites at `440a9eb6a7`. UI typecheck, token gates, and whitespace checks pass. - Two new directory-error cases fail before the fix and pass after it. Both pages keep routine rows mounted, show an error with Retry, and restore responsible names after retry. - 59 checks pass across the SDK source-pin, public-type, and evidence suites. - The Runner test program typechecks after building its eval dependency. A local run of the native-session test file passed 300 tests. One additional test could not run because the local debug Runner binary was absent. CI must cover that case. - Storybook builds and all 13 browser checks pass on `64a87af7c085426d09eb8aa48bf9491487565990` after the latest master integration. They cover current and Classic controls, filters, columns, links, selection alignment, Recent Runs, mobile overflow, and shared toolbar behavior. - Storybook examples: Default, LinkedFilters, Classic, ClassicSelection, and ClassicRuns. They mount production pages with fictional API responses. Screenshots cover light, dark, filters, custom columns, and mobile. The baseline manifest has no snapshots; these are visual review captures. - Earlier preference, shared-link, title-link, compact-row, and filter-render-cost regressions have red/green evidence. The scheduled-routine journey has 17 passing unit checks from the prior revision. - The shared selector has three large-list cases with 1,200 routines and 120 folders. All filters are active. Each case checks row order and folder counts. Work counters throw if filtering repeatedly scans selected IDs or folder counts scan the routine list for each folder. Both deliberate regressions fail; the unchanged selector passes. Both Routines pages use this selector. The latest commit adds only these tests; production source is unchanged. - [CI at `64a87af7c0`](https://github.com/paperclipai/paperclip/actions/runs/44416091562) passed all jobs, including typecheck, Build, Runner, general tests, serialized tests, and E2E. [Final-head CI at `440a9eb6a7`](https://github.com/paperclipai/paperclip/actions/runs/44419144971) now passes on attempt 2. All 52 executed jobs pass; one file-selection job is skipped. Typecheck, Build, all test shards, E2E, Runner, and the aggregate verify gate pass. The first attempt failed in the timing-sensitive watchdog fixture; its retry passes. - `pnpm verify` returned exit 2 because this branch needs broad CI coverage. Final-head CI passes. Greptile and Ponytail both give 5/5 at `440a9eb6a75184a35001e99a17e6856b7cdb0bd5`. All 20 inline threads are resolved. - Prior CI at `10a5b0813b` passed all general and serialized test shards, all E2E shards, and Build. It failed on a circular test-mock type and a stale SDK source pin. Master now contains both repairs; the final branch uses those repairs. - The two Routines page bodies were already duplicated. This PR reduces them and shares list data, controls, rows, and view state. Codie owns the remaining page-shell consolidation as later work. - Live provider execution and scheduler behavior are outside this presentation change. Protected Storybook publication still requires a configured human reviewer; no deployment approval is inferred from merge authorization. ## Risks View settings now include filters. A person can return to a filtered list. The URL and active filter button show that state. Shared filter URLs override local filters. Column choices stay local. The shared filter extraction can affect Tasks, so its component and toolbar checks are included. No migration is needed. ## Model Used OpenAI GPT-6 through Codex. The runtime does not expose a more specific model revision. Used reasoning, source editing, shell tools, and browser automation. No sub-agents were used. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
45c3f4caa2 |
fix(connectors): require an install before an agent reaches a plugin connector (#22237)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plugins can add connectors that serve their own tools (`transport: "plugin"`, #22004, #22019, #22201) > - The activation rule is that an agent gets a connector's tools only through an install of an active connection for that agent > - An agent with no install could still list and call a plugin connector's tools, and the plugin worker ran them with that agent's run context > - This pull request makes the tool access policy require the install for plugin-served connections > - The benefit is that a plugin connector reaches only the agents it is installed for ## Linked Issues or Issue Description Refs #22004 Refs #22019 Refs #22201 **Subsystem affected** Tool access policy and tool gateway (plugin-served connectors). **Problem or motivation** A plugin connection was installed for agent A only. Agent B, a standard agent with no install, called one of its tools. The plugin worker got a run context with B's agent id. **Root cause** An install gives access only through the connection's app profile binding. The policy does not check installs. For an agent outside that profile, the policy goes on to its other allow routes. The common route is the unscoped `tools:use` grant that every new standard agent receives (`NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS`). `governedByConnectionProfile` is false for B, because B is not bound to the connection's profile. So `explicitGrant` allowed the tool for discovery and invocation. Organization-grant connections ran the worker. Per-agent connections listed the tools and reached grant resolution. **Expected behavior** An agent without an install for the connection (or a company install) sees no tools and cannot call them. An installed agent is not affected. ## What Changed - `server/src/services/tool-access-policy.ts`: for an agent caller on a connection whose stored transport is `plugin`, deny with the new reason `deny_connection_not_installed` unless an install exists for that agent or the company. The check runs before profiles, grants, trust rules and allow policies, so none of them can replace the install. It reads the transport from the stored connection, not from the caller. The install read uses the decision cache, so a listing batch reads it once per connection. - `packages/shared/src/types/tool-access.ts`: add `deny_connection_not_installed` to `ToolAccessReasonCode`. - `doc/connections/CONNECTOR-PLAYBOOK.md`: document the rule. - Legacy plugin tools (`paperclip_plugin`) keep their own implicit-install gate and are not changed. ## Verification - New `server/src/__tests__/plugin-connector-install-gate.test.ts` (embedded Postgres, real routes). Both agents get the default standard-agent grants, including the unscoped `tools:use`. For an organization-grant connection and a per-agent connection installed for A only: - A lists the tool through its gateway session and its Paperclip Runner assigned-tool gateway, and a call reaches the worker. - B (with its own install of an unrelated connection) lists none of them in either path. - B's direct call by name through its gateway session, its runner gateway, and the runner's `paperclip_call_assigned_tool` is refused. The worker is never called. - Before the fix, both cases failed: B listed the tool. - Regression suites pass: `tool-access-policy-service`, `tool-access-policy-index`, `tool-gateway`, `tool-gateway-service`, `tool-gateway-*`, `prompt-injection-gateway`, `plugin-connectors-plugin-transport` (legacy plugin tools), `plugin-connectors-circleback-parity`, `plugin-connector-agent-grant`, `heartbeat-runtime-mcp-servers`, `run-preparation`, `tool-access-service`, `generic-mcp-connection`, `remote-mcp-connectors`, `railway-connection`, `aws-mcp-connector`, `mcp-protocol-versions`, `google-workspace-*`. - `tsc --noEmit` passes for `server`, `packages/shared` and `ui` source. ## Risks - Behavior change: an uninstalled agent loses access to plugin-served connection tools it reached before through a general grant, a trust rule or an allow policy. That access broke the activation rule. Installed agents and company installs are not affected. - The board's per-agent access check now shows `deny_connection_not_installed` for agents without an install. - Built-in (non-plugin) connections are not changed by this pull request. They have the same policy path. Whether to require installs for them is a separate decision, because existing setups may depend on it. - No migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, test runs). ## 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> |
||
|
|
07d9316218 |
fix: restore master's typecheck and runner SDK input pin (#22242)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - #22235 added a runner regression test for a turn lost to a mid-run `runnerd` restore > - That test reads `startTurn.mock` inside the initializer of `startTurn` itself > - The CI test-program typecheck rejects this with TS7022 and TS7024, so master fails "Typecheck + Release Registry" > - This pull request counts calls in a local variable instead > - The benefit is that master typechecks again, and the test behaves exactly as before ## Linked Issues or Issue Description Refs #22235, Refs #22234 **What happened?** After #22235 merged, `ci / Typecheck + Release Registry` failed on `packages/paperclip-runner/src/native-session-runtime.test.ts(724)` with TS7022 ("'startTurn' implicitly has type 'any'...") and TS7024. **Steps to reproduce** 1. Run the CI typecheck lane (`typecheck test programs`) on master after #22235. 2. See TS7022 and TS7024 at line 724 of the test. **Expected behavior** The test program typechecks. ## What Changed - The `startTurn` mock in the new test uses a local call counter instead of reading its own `mock.calls`. - `tests/runner-e2e/source-sdk-public-inputs.json`: refresh the pin for `packages/shared/src/app-definitions/github.json`, which #22234 changed without updating it. The Runner support suite fails on master without this. ## Verification - `npx tsc -p packages/paperclip-runner/tsconfig.test.json --noEmit` reports no errors in the test file. - `npx vitest run src/native-session-runtime.test.ts` in `packages/paperclip-runner`: 301/301 pass. ## Risks - Low risk. This changes a test and regenerates a pin with the repository script (`node tests/runner-e2e/source-sdk-public-inputs.mjs <sha> --write`). `source-sdk-public-inputs.test.mjs`: 13/13 pass. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use. ## 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> |
||
|
|
fcaf748607 |
chore(lockfile): refresh pnpm lockfiles (#22220)
## Thinking Path > - Paperclip uses a dependency lock for reproducible builds. > - Dependency changes on master need matching lock entries. > - Paid eval reports also pin a reviewed offline correction. > - Reports must install before paid model work starts. > - This automated PR keeps the lock and report proof together. ## Linked Issues or Issue Description **What happened?** Dependency manifests on master changed after the last committed lock refresh. **Expected behavior** Frozen installs must match those manifests. Eval reports must retain matching offline lock proof. **Steps to reproduce** Run a frozen install before and after this lock refresh. ## What Changed - Refresh the dependency lock from the manifests on master. - Refresh the sandbox provider lockfiles from their manifests on master. - Include the matching offline report correction and hashes. - Resync the SDK public source proof's lock pins from the refreshed lock. ## Verification - Pinned pnpm resolution completed with lifecycle scripts disabled. - The report proof refresh accepted the reviewed committed baseline. - The workflow rejected changes outside the lock and report proof files. ## Risks The lockfile bot merges this PR without CI or review when every added package version is at least 3 days old on npm. Otherwise the PR waits for a maintainer, and the daily refresh tries again. The bot merges only the exact commit this workflow generated from manifests already reviewed on master. Unknown report lock baselines remain blocked. This update changes no permissions or paid enable gates. ## Model Used None — generated by pnpm and the deterministic report-lock updater. ## Checklist - [x] Thinking path and problem description included - [x] Generated lock and matching report proof included - [x] Release-age gate decides between bot merge and maintainer review Co-authored-by: lockfile-bot <lockfile-bot@users.noreply.github.com> |
||
|
|
33fac97cad |
feat(routines): ship the redesigned routine page and let live webhooks be tested again (#22205)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Routines start agent work on a schedule, from a webhook, or on demand > - The routine detail page split one routine across eight sections behind a section sidebar (overview, triggers, variables, secrets, delivery, runs, activity, history) > - People had to hunt through sections to see what a routine does and to change it, and a finished webhook could not be tested again without starting the routine > - This pull request makes the approved two-column routine page, one Edit dialog and one Webhook dialog the real routed page, and lets a live webhook go back into test mode > - The benefit is one page that answers what the routine does, when it runs, who runs it and what it made, with every change in one dialog ## Linked Issues or Issue Description **Problem** The routine detail page spreads one routine over eight sections and a section sidebar. Changing a routine means visiting several sections, each with its own save bar. A webhook that is already live cannot be tested again: the API only accepts `setupPending: false`, so testing a live webhook starts the routine. **Proposed solution** Ship the reviewed design (stories `routine-page-design`, `routine-edit-dialog-design`, `routine-webhook-dialog-design`) as the routed page in both UI shells, wired to the real API. Let `PATCH /api/routine-triggers/:id` accept `setupPending: true` for a live webhook so the next events are checked but never start the routine. **Alternatives considered** Keep the sections and restyle them. The owner rejected this: the section sidebar should go. ## What Changed - `/routines/:id` renders `RoutinePage` in both shells (`RoutineDetail.production.tsx` is removed). Status switch, Repeats rows, default agent, responsible user, project, Asks for, Secrets, Run rules, Managed by plugin, Instructions with Show all, copy and the comment count, and History. - History is paged: 20 tasks per page from `GET /companies/:id/issues?originKind=routine_execution&originId=…&sortField=created&sortDir=desc&limit=21&offset=…`, with a real Load more. Coalesced runs show as "folded into a task". - A failed refetch keeps the loaded page on screen (`useQueryView`); a History failure shows `QueryErrorState` in place. - Header: Edit, "…" (Version history, Audit log, Archive / Restore) and Run now. In the streamlined desktop shell they sit in the breadcrumb toolbar; elsewhere above the page. - Version history (`/routines/:id/history`, restore and restored-webhook keys kept) and Audit log (`/routines/:id/activity`, `RoutineAuditActivity`) open as sub-views with a way back. Old section addresses and `?tab=` redirect to `/routines/:id`. - Edit dialog saves title, instructions, variables, secrets, agent, project and responsible user in one request against the revision the dialog opened with (save conflict shows "changed while you were editing"). The first schedule is created, changed or removed after that. Priority and delivery settings are never sent, so saved values stay. - Webhooks are created, changed, tested and removed (with Undo) right away from the Edit dialog, with the Webhook dialog nested inside it. Closing the Webhook dialog ends setup or test mode. A webhook left in test mode shows "Testing · events don’t run" on the page and offers Finish testing. - Responsibility (only with `enableResponsibilities`): the page shows direct and through-project responsibilities from the link lookup; the dialog links or unlinks the direct one. With the flag off nothing is fetched or shown. - The routines list creates routines with the same dialog in create mode, filed in the open folder, and opens the new routine page. - Server: `setupPending: true` on a live webhook enters test mode (planned by a pure `planTriggerUpdate`, which also gives the activity action) (422 for other trigger kinds; 409 for a disabled or removed webhook or an archived routine). Test deliveries keep the last real delivery as `lastWebhookDelivery.previous`, and finishing testing restores it. Activity `routine.trigger_test_started`. - Additions to the reviewed design, from review, so no capability is lost: the schedule popover has Pause/Resume; standing-check and API rows open a small popover with Pause/Resume and Remove; removing a trigger from the page leaves a "… removed. Undo" line under Repeats. Stories: `StandingCheckOpened`, `ScheduleTriggerPaused(Opened)`, `RemovedWithUndo`. - Save is several requests (routine, schedule, responsibility). It changes only the schedule the form opened with, records each finished step, and a partial failure says what was saved and that saving again finishes it. The dialog cannot be dismissed while saving. Failed reads show a Retry state, never empty choices. - Removed: the routine section sidebar and contextual sidebar, the trigger wizard, trigger cards, save bar, section components and their tests. - Storybook: the three routine stories moved to `stories/routines` as current production stories, a new story mounts the routed page against a fixture API, and stories that used the old page were updated or removed. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/routines-e2e.test.ts` (17/17) and `src/__tests__/routines-service.test.ts` (105/105). - `pnpm exec vitest run` on the routine page, routines list, routine form, webhook instructions, Layout, shell navigation, audit and editor tests: 275 tests pass. - `cd ui && npx tsc -p tsconfig.json --noEmit`, `node scripts/check-token-gates.mjs`, `node scripts/check-maps.mjs`, `node scripts/storybook-catalog.mjs --check`: pass. - `pnpm verify` exits 2 (global CI input changed); required CI supplies the broad coverage. - Manual: an isolated worktree instance (`pnpm paperclipai worktree init --empty`, `pnpm dev`) with a seeded routine. Headless Playwright: an old `/triggers` address redirects, no section sidebar, History shows 20 then 23 after Load more, the schedule popover opens, pause and resume, Edit → Add webhook → created key → Finish, title save, Test webhook → Finish testing, Version history, Audit log shows "Started testing a webhook", phone width has no horizontal overflow, and Create routine from the list opens the new page. No console errors or failed API calls. ## Risks - Behaviour change: the section pages are gone. Old links redirect to the single page. - The delivery-setting editors (concurrency, catch-up, activity gate) and priority are removed from the UI. Saved values stay, and the API still accepts them. - The create dialog no longer offers a folder picker or delivery settings. A new routine goes into the folder the list is showing and takes the default settings. - Replace key in the Webhook dialog acts at once, as in the reviewed design. The old confirmation is gone. - No migration. `lastWebhookDelivery.previous` is an optional field inside the existing jsonb column. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use (shell, file edits, headless browser) and subagents for the server change and the Storybook move. ## 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 Fable 5.2 <noreply@anthropic.com> |
||
|
|
651749bdb4 |
feat(connections): AWS connector with credentials minted per connection (#22195)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents use outside services through connections, and the control plane holds each connection's credentials > - Companies want agents to "do things on AWS" with exactly the permissions they choose, without Paperclip storing long-lived AWS keys or rebuilding the AWS API > - AWS hosts an MCP server that runs any AWS API call in its own sandbox, and it accepts a one-hour bearer token that can be minted from IAM credentials > - This pull request adds an AWS connection that mints that token for each connection at call time. The role method proves the connection with the company's workload identity issuer (#22083), so no AWS key is stored > - The benefit is that each AWS connection carries its own role and permissions, AWS enforces them, and agents never see any AWS credential ## Linked Issues or Issue Description Refs #22083 (workload identity issuer) and #22191 (spike findings). **Subsystem affected** Connections (tool access), tool gateway, shared app definitions, instance settings. **Problem or motivation** Paperclip has no way to connect AWS. AWS's hosted MCP server needs a bearer token from AWS Sign-in, minted from IAM credentials. No existing credential path mints a header at call time from a role or key. **Proposed solution** Methods can declare `credentialMinter: "aws_mcp"`. The gateway and connection health checks mint the `Authorization` header at call time, and they share one in-memory cache per connection and grant (about 55 minutes). There are two methods: - Role (`AssumeRoleWithWebIdentity` with a Paperclip-signed connection token). - Access key (the key directly, `GetFederationToken`, or `AssumeRole`). Read-only connections add `ReadOnlyAccess` and `AWSMCPSignInOAuthAccessPolicy` as session policies, so AWS refuses changes. The feature is behind the `enableAwsConnector` experimental setting. **Alternatives considered** - Run AWS's `mcp-proxy-for-aws` process on the control plane. Rejected: it adds a Python runtime and processes, and gives nothing the token exchange does not. - Put credentials in the agent sandbox and use the AWS CLI. Deferred: there is no per-call governance, and every sandbox would need the CLI. - Add a new `credentialSource`. Rejected: it needs a migration, and the `vercel_connect` database rules do not fit stored access keys. ## What Changed - `packages/shared`: - `credentialMinter` on connection methods. The validator requires `mcp_remote` and `api_key`, and does not allow `keyPlacement` or another credential source. - The `aws` app definition (two methods, reviewed tools, `mcpSessionRequired`, experimental key). - The `enableAwsConnector` setting in the catalog, types and validators. - `aws` added to the connectable apps. - `server/src/services/connectors/aws/mcp-credentials.ts`: - Settings parsing and checks. The URL must be AWS's endpoint for the saved region, and the role ARN must be valid. - The minter: role or key session, read-only session policies, Sign-in exchange, cache keyed on settings, key references and status, in-flight de-duplication, eviction. - A plain-language error mapping that never shows AWS's own text, because that text can contain account IDs and ARNs. - Gateway (`resolveCredentialHeadersUnrecorded`), credential access (`resolveCredentialHeaders`), catalog discovery and health-failure mapping: - The AWS branch. - After a 401, the gateway evicts the token and mints again, then requires an explicit retry (no replay). Discovery lists again. - Setup: - Minted methods may save a draft without contacting the provider. The role must trust a connection that already exists. - Saving an AWS role draft publishes the company's issuer, so AWS can validate it when the customer registers it. - `workload-identity.ts`: a draft connection can get a token, so setup can test it. Disabled, archived or switched-off connections still get none. - `server/package.json`: `@aws-sdk/client-sts` and `@aws-sdk/client-signin`. The lockfile is left to the refresh workflow. - Artwork: AWS light and dark marks from LobeHub's MIT icon set (already licensed in the repo). The manifest entry passes the brand checks. - `scripts/ingest-app-definitions.mjs`: minted methods are exempt from the `keyPlacement` requirement. The override source is `scripts/app-definition-overrides/aws.json`. Permission reviews are added. - UI: the experimental settings toggle, in alphabetical position. - Docs: `doc/connections/AWS.md`, the connections index, the issuer API doc (draft rule), and the plan's phase table. ## Verification - `server/src/services/connectors/aws/mcp-credentials.test.ts` (7 tests) covers these items: - Both methods and the read-only policies. - Caching, revision, forced refresh, expiry and eviction. - Concurrent de-duplication. - The error mapping, with no AWS text leaking. - Settings validation, including the URL and region check and the rule that an unknown access level means read only. - `server/src/__tests__/aws-mcp-connector.test.ts` (3 tests, real setup, catalog and gateway code with a fake AWS and a session-requiring fake MCP server) covers these items: - The setting gates setup. - The access key is never sent as a header or stored in config. - A cached token is reused. - After a 401, a fresh token is minted and the call is not replayed. - Role draft-then-resume publishes the issuer. - The signed token has the right `iss`, `sub` and `aud`. - An AWS refusal shows a plain health message without the account ID. - Red/green: - Removing the gateway hook fails the access-key test. - Turning off `mcpSessionRequired` fails both integration tests. - Removing draft support for minted methods fails both integration tests. - Restoring each change passes again. - Nearby suites: `tool-gateway-service`, `tool-access-service`, `remote-mcp-connectors`, `instance-settings-service`, `workload-identity`, plus the new files. 775 of 775 pass. - Shared `app-definitions.test.ts` passes (42), including new `credentialMinter` schema tests. UI `InstanceExperimentalSettings` (63) and the brand asset tests pass. `check-app-brand-assets` validates 112 identities. - Typecheck is clean for `packages/shared`, `server` and `ui`. The only UI errors are in Storybook's generated catalog files, which this worktree has not built. - **Real AWS** (Paperclip dev account, integrated code path, issuer behind a temporary public tunnel): - Access key, read only: 8 tools listed. `run_script` `ListBuckets` succeeded in 8.9 s on a cold sandbox. AWS refused `CreateBucket` ("no session policy allows"). - Role: the draft was saved without contacting AWS, and the issuer was published. After an IAM provider and a role trusting only that connection were created, resuming setup listed 8 tools. `ListBuckets` succeeded in 12.8 s. The role's own permissions refused `CreateBucket`. - This run found two bugs the fakes did not: AWS needs MCP sessions for calls, and the role method needs draft-first setup with the issuer published. Both are fixed and both now have tests. - All IAM users, keys, roles, providers and buckets were deleted, and a listing confirmed it. - Not run: Paperclip Cloud staging (the setting is off by default), and `AssumeRole` from an access key with a role ARN against real AWS (unit tests only). ## Risks - The feature is off by default, behind `enableAwsConnector`. No migration. - New dependencies `@aws-sdk/client-sts` and `@aws-sdk/client-signin` are in the existing `@aws-sdk` family (the server already uses `client-s3`). - Minted tokens are held only in process memory. A restart mints again. A cached token can outlive a deactivated key by up to an hour, unless AWS returns 401, which evicts it. - `aws___run_script` is classified as a write, so the normal approval and ask-first policy applies. Read-only connections rely on AWS session policies. - The guided setup screen and the CloudFormation template are not in this PR. Setup uses the generic form and the documented draft and resume steps. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, AWS SDK for JavaScript against the Paperclip dev AWS account, a Cloudflare quick tunnel, an exploration subagent). ## 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> Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
f0bd99ba8a |
fix(recovery): wait out a sandbox the provider could not start, with no Retry (#22194)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A task that runs in a sandbox environment first gets a lease from the environment provider (for example Daytona) > - Sometimes the provider creates the sandbox but cannot start it. Daytona then puts the sandbox in its `error` state > - The Daytona plugin deletes that failed sandbox and rethrows the provider error. The error has no HTTP status and no errno, so the host cannot tell that it is a provider-side failure > - The run fails with `setup_failed`, and the task rests on "Retry when ready". No agent work had started, and a fresh sandbox works, so a person must click Retry for something the system can do itself > - Recovery must just work, and the target for runs that need Retry is 0% > - This pull request makes the plugin report a removed sandbox that the provider could not start as structured evidence (the step and the provider state). The host classifies it as a transient provider failure. The task then uses the existing bounded retries and the provider-outage wait from #22139 > - The benefit is that a provider start failure delays the task by seconds instead of stranding it on Retry ## Linked Issues or Issue Description Refs #22139 (the provider-outage wait lane that this failure now reaches). Refs #22128 (setup failure after work; this failure happens before any work, so that path did not apply). **What happened?** In a restart-chaos wave with graceful release swaps on 2026-11-18, two tasks started a run at 14:51:15Z and 14:51:24Z. Both runs failed at 14:51:53Z with `setup_failed` and `failureCause: lease_acquire_failed`. The cause was `Sandbox <id> failed to start with status: error, error reason: null` from the Daytona SDK, for two different sandboxes at the same moment. Both tasks rested on Retry. A Retry click started each task again, and both tasks completed. **Expected behavior** A sandbox that the provider cannot start is a provider failure before any agent work. Paperclip deletes it and tries again with a new sandbox, with no Retry. If the provider keeps failing, the task waits for the provider without a Retry, and a person gets a working Retry only after the 30-minute ceiling. **Steps to reproduce** 1. Make the Daytona create call fail while the new sandbox is in the provider's `error` state. 2. Assign a task to an agent that uses that environment. 3. The run fails with `setup_failed`, and the task rests on Retry. ## What Changed - Plugin SDK (`environment-creation-cleanup.ts`, `environment-acquire-error.ts`, `index.ts`): new `PluginEnvironmentAcquisitionError`. It carries the acquisition diagnostic (step, elapsed time, budget, provider state) for a failed allocation that the provider already removed, with no cleanup envelope. The acquire RPC error data (`paperclip/environment-acquire-error/v1`) now carries this diagnostic. `readEnvironmentAcquisitionDiagnostic` reads it from that envelope. The existing cleanup envelope path is unchanged. No provider text crosses the RPC. - Daytona plugin (`plugin.ts`): `destroyFailedCreation` returns the state of the sandbox that it deleted. When a create fails without an HTTP status and the deleted sandbox was in the `error` state, the plugin throws `PluginEnvironmentAcquisitionError` with `providerState: "error"`. A `build_failed` sandbox (a deterministic snapshot build failure) and any other state keep the original error. - Server (`environment-runtime.ts`): the acquire path records the diagnostic for this run also when the error has no cleanup envelope. A cleanup envelope for another run, company or environment still records nothing. - Server (`environment-provider-unavailable-error.ts`): an acquisition diagnostic with `providerState: "error"` is the transient reason `provider_start_failed` ("the provider could not start the sandbox"). It becomes `EnvironmentProviderUnavailableError`, so the run uses the two bounded retries and then the provider-outage wait lane (one probe per environment, 30-minute ceiling). - `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed pins for the changed SDK sources (generated by `node tests/runner-e2e/source-sdk-public-inputs.mjs <sha> --write`). Module boundaries: the change to the shared SDK contract is additive. The Daytona plugin owns the provider state. The host reads only the closed diagnostic fields. A plugin that does not use the new class behaves as before. ## Verification - `packages/plugins/sandbox-providers/daytona`: `npx vitest run src/plugin.test.ts -t "failed sandbox creation cleanup"` (37 passed). New: "reports a sandbox that failed to start as a removed allocation with its observed step" (red before the plugin change, green after) and "keeps the create error when the removed sandbox was build_failed / started". - `packages/plugins/sdk`: `npx vitest run tests/environment-acquire-error.test.ts tests/environment-creation-cleanup.test.ts` (50 passed). New: the diagnostic crosses the real worker RPC without provider text, and forged or unstructured envelopes give no diagnostic. - `server`: `npx vitest run src/services/environment-provider-unavailable-error.test.ts src/__tests__/environment-acquisition-diagnostics.test.ts` (74 passed). New: the reason is `provider_start_failed` with a transient provider failure, and a diagnostic that was not recorded for this run is not retried. - `server`: `npx vitest run src/__tests__/environment-runtime.test.ts -t "provider could not start|retains uncertain plugin creation"` (12 passed). New: "records the step of a sandbox the provider could not start and removed" for a worker error (red before the runtime change, green after) and for a forged error (not recorded). - `server`: `npx vitest run src/services/__tests__/run-failure-diagnostics.test.ts src/__tests__/heartbeat-process-recovery.test.ts -t "provider|acquisition|diagnostic"` (167 passed). - Typecheck: `server` `tsc --noEmit`, `pnpm run typecheck` in `packages/plugins/sdk` and in the Daytona plugin all pass. - `pnpm verify` exits 2 (the SDK input registry is a global CI input). Required CI supplies the broad coverage. ## Risks - **Automatic retries for a deterministic start failure.** If a provider image or configuration made every sandbox go to `error`, the task now waits in the provider-outage lane instead of resting on Retry at once. The lane uses one probe per environment on a 1, 2, then 5 minute backoff, and it hands the task to a person with a working Retry after 30 minutes. The aggregate automatic-run brake is unchanged. `build_failed` is not retried by this change. - **Shared SDK contract.** The new field is additive. An older host ignores it, and the run fails as before. - No database migration. No UI change. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, used in Claude Code with tool use (shell, file edits) and extended reasoning. ## 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 - [x] All Paperclip CI gates are green - [x] 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> |
||
|
|
a9dc0df9da |
fix(ui): clarify dashboard proposal hierarchy (#22180)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - An agent can propose dashboard areas and responsibilities in one card. > - The card put the area name above a separate “New area” row. > - Responsibility rows had no type label and no visible parent structure. > - This pull request puts area changes in the heading and nests responsibility changes below it. > - People can see what each change creates and where it belongs before they apply it. ## Linked Issues or Issue Description **What existing behavior does this improve?** The dashboard proposal card in task conversations and the dashboard edit module. **Subsystem affected** The board UI and its Storybook examples. **Current behavior** “New area” appears in a row below the area title. New responsibilities appear at the same level. Their type is not stated. **Proposed behavior** “New area” appears beside the area title. Each new responsibility has a label and sits below its parent area. Existing areas have a separate label. Area headings follow the heading level in the dashboard module. **Reason and benefit** The person can see the parent area, the change type and the text to review in that order. Long proposals are easier to scan. **Breaking changes** None. Proposal inputs, indexes, dependencies and apply/decline endpoints stay the same. ## What Changed - Put area changes and their controls in the area heading. - Nest responsibility rows under each area. Label additions, rewords, moves and removals. - Keep the drop/keep dependency behavior and the existing apply payload. - Keep area classification and group partitions in one helper. Expose whether each group has an existing parent area. - Add Storybook examples for the new hierarchy, a narrow layout and a mix of new and existing areas. - Add focused component and browser checks for the hierarchy, responsive layout and apply payload. ## Verification - 24 focused unit tests passed across the proposal card, dashboard module and dashboard helpers. - 25 Chromium checks passed against current-source Storybook after the review refactor, with one worker and no retries. They cover six proposal states in light and dark themes at widths of 390 and 960 pixels, plus the existing apply payload. - The UI typecheck passed in low-memory mode after the review refactor. The initial implementation also passed the static Storybook build; current-head CI supplies broad build coverage. - 30 map/catalog tests passed. Catalog checks, token gates and whitespace checks passed. - A hierarchy regression failed before the fix and passed after it. A later hosted-story check found a skipped heading level. The fix passed the expanded browser checks. - Initial concurrent browser, build and typecheck runs hit the workspace memory limit. The final browser pass used one worker and the typecheck used low-memory mode. - The first CI build stopped because its runner received a shutdown signal after the UI build completed. A new CI run checks the review fixes. - The local verification selector returned exit 2 because the new browser spec is a global CI input. [Current-head CI](https://github.com/paperclipai/paperclip/actions/runs/44333497172) passed typecheck, build, all selected test suites, E2E shards and the final verify gate for `e71916cdde90ede313cc167ab8cfb8a5c3bb501a`. No visual baseline comparison was run because the baseline manifest has no published snapshots. - [Greptile reviewed the current head](https://github.com/paperclipai/paperclip/pull/22180#issuecomment-6982500386) at 5/5 with no findings. Both earlier maintainability threads are resolved; two Paperclip reviews remain pending. ## Risks Low risk. This changes UI structure and labels. Long text and drop/keep controls must continue to fit at narrow widths. The focused browser checks cover those states. Storybook uses synthetic API data and does not prove server persistence or permissions. ## Model Used OpenAI GPT-6 through Codex, with reasoning, 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
3c460f20cc |
feat(analytics): ask EU, UK and Swiss visitors before Cloud browser analytics (#22186)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip Cloud can send browser product analytics and session replays to PostHog. Self-hosted installs never do this. > - Today, browser analytics starts for every Cloud visitor after the page settles. > - Visitors in the EU, the EEA, the UK and Switzerland must agree before analytics cookies and session recordings start. > - This pull request adds a consent step for these visitors and a switch in the user's profile settings. > - The benefit is that Cloud analytics follows the owner decision: ask in Europe, keep the current behavior elsewhere, and let every user change the choice. ## Linked Issues or Issue Description **Subsystem affected** Paperclip Cloud browser product analytics (`ui/src/lib/analytics`, `ProductAnalyticsGate`, the session route, and Profile settings). **Problem or motivation** Browser analytics and session replay start for every Cloud visitor without a choice. EU, EEA, UK and Swiss visitors must consent first. The privacy policy draft also says that users can change the choice in settings. No such setting exists. **Proposed solution** Ask visitors in the EU, the EEA, the UK and Switzerland with a small bottom banner (Accept or Decline). Do not load posthog-js before they accept. Treat Do Not Track and Global Privacy Control as a decline for these visitors. Keep the choice in `localStorage`. Add a "Product analytics" switch to Profile settings for every user when browser analytics is on. **Alternatives considered** A server-side country from a trusted edge header. Paperclip Cloud has no such header today: Cloudflare records are DNS-only, so no `CF-IPCountry` arrives, and the Railway edge adds no country header. This PR supports an optional header (`PAPERCLIP_POSTHOG_COUNTRY_HEADER`) for a future edge, and uses the browser time zone until then. ## What Changed - `packages/shared`: `browserAnalytics` has a new optional `consentRequired: boolean | null`. - `packages/shared/src/analytics-consent.ts` (new): the one region policy. `countryRequiresAnalyticsConsent` (EU and EEA with outermost regions and Svalbard, GB with the Crown Dependencies and Gibraltar, CH) and `timeZoneRequiresAnalyticsConsent` (`Europe/*`, EU, EEA and UK zones outside Europe, and unknown zones such as `UTC` or `Etc/*`). The server and the UI both use it. - `server`: `resolveBrowserAnalyticsConfig` sets `consentRequired` from the header that `PAPERCLIP_POSTHOG_COUNTRY_HEADER` names. No header or an unknown code (`XX`) gives `null`. - `ui/src/lib/analytics/consent.ts` (new): decides `granted`, `denied` or `ask`. Order: for a visitor who must consent, Do Not Track or Global Privacy Control gives `denied` (also over a stored Accept); then the choice made on this page; then the stored choice; then the region (server value, else browser time zone). The choice is in `localStorage` key `paperclip.analyticsConsent`. All storage access is in `try/catch`. A cross-tab `storage` event updates the page. - `ProductAnalyticsGate`: one effect calls `syncProductAnalytics(config, consent)`. Shows `AnalyticsConsentBanner` when consent is `ask`. Accept loads posthog-js at once, without a reload. - `product-analytics.ts`: new `syncProductAnalytics`. It starts, opts in, opts out (`opt_out_capturing()` and `stopSessionRecording()`) or cancels a pending load. Any consent other than `granted` stops analytics. If consent is withdrawn while the script downloads, `init()` does not run until a later opt-in. - `AnalyticsConsentBanner` (new): a labelled bottom region with plain copy, a privacy policy link, and Decline and Accept buttons (shared `Button`). The copy says that recordings hide what you type and your messages, documents and connected accounts, but may show page names like task titles. It does not block the page. On mobile it sits above the bottom navigation. - `ProductAnalyticsSetting` (new) in Profile settings: a "Product analytics" switch (shared `ToggleSwitch`). It shows only when browser analytics is on for the instance. When GPC or DNT blocks analytics, it is off and disabled and says why. - `doc/cloud-browser-analytics.md`: new Consent section (signal, behavior table, storage key, how to reset) and the new variable. - `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the changed shared validator. ## Verification - Red/green: the 7 new `ProductAnalyticsGate` consent tests fail against the master gate (7 failed, 3 passed). The 5 review-fix tests (failed write with working read, cross-tab change, decline during script download, granted -> ask from another tab, granted -> ask from a session refresh) fail on the first commit (5 failed, 16 passed). All pass now. - `cd ui && npx vitest run src/lib/analytics src/components/ProductAnalyticsGate.test.tsx src/components/AnalyticsConsentBanner.test.tsx src/components/ProductAnalyticsSetting.test.tsx src/pages/ProfileSettings.test.tsx`: 267 tests pass. - `cd server && npx vitest run src/__tests__/cloud-posthog-browser.test.ts src/__tests__/auth-routes.test.ts src/__tests__/auth-session-route.test.ts`: 87 tests pass. `packages/shared` `analytics-consent.test.ts` passes. `tsc --noEmit` for `ui`, `server` and `packages/shared` shows no new errors. - `pnpm verify` exits 2 (a doc is a global CI input). Required CI gives the broad coverage. - Real check in headless Chromium. I ran a local Cloud-managed instance (external local PostgreSQL, `PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN`, `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`). `PAPERCLIP_POSTHOG_HOST` pointed at a local capture server, not PostHog. The capture server served a small stand-in for `array.js` that sets a `ph_*` cookie and `localStorage` key and posts `/e/` events. I set the visitor region with the browser time zone: | Visitor | Result | | --- | --- | | `Europe/Berlin`, no choice, 18 s wait | Banner shows. 0 `/_ph` requests. No `ph_*` cookie or storage key. | | Then Accept (keyboard Enter) | Banner closes. `GET /_ph/static/array.js` and `POST /_ph/e/` in 3 s. Key is `granted`. After reload: no banner, events continue. | | `Europe/London`, Decline, wait, reload, wait | No banner. 0 `/_ph` requests. No `ph_*` cookie or storage key. Key is `denied`. | | `Europe/Zurich` with Global Privacy Control | No banner. 0 `/_ph` requests. No `ph_*` cookie or storage key. | | `America/New_York` | No banner. posthog-js loads after the page settles, as before. | | Profile settings switch (US) | Shows on. Off: client is opted out at once. On: opt-in, events continue. | - I ran the browser check again after the review fixes, with the same results. - Screenshots (banner light, banner dark, mobile 375 px light and dark, settings switch): see the PR comment. - Cold load (local dev server, fresh browser context per run, median of 7, ms): | Build | Time zone | FCP | DOMContentLoaded | load | | --- | --- | --- | --- | --- | | master | New York | 728 / 724 | 687 / 684 | 689 / 686 | | this PR | New York | 748 / 724 | 708 / 684 | 710 / 686 | | master | Berlin | 740 | 694 | 697 | | this PR | Berlin | 756 / 724 | 716 / 684 | 718 / 686 | The second round gives the same medians for master and this PR. The first-round difference is noise. The consent code adds no request and no load-time wait. ## Risks - Region by time zone is approximate. It asks some visitors outside the EU (for example `Europe/Istanbul`, or `UTC` browsers). This is the safe direction. - A forged country header (only when `PAPERCLIP_POSTHOG_COUNTRY_HEADER` is set) changes only the default for that visitor's own browser. - The choice is per browser. A user on a new browser sees the banner again (in consent regions). - Visitors in consent regions now send no browser analytics until they accept. Expect fewer EU/UK sessions in PostHog. - Self-hosted installs: no change. They get no `browserAnalytics` config, so no banner, no switch and no load. ## Model Used - Claude Opus 5.5 (claude-opus-5-5), Anthropic, used through Claude Code with tool use (shell, file edits, headless browser). ## 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> |
||
|
|
2a43fe3e34 |
feat(telemetry): add company_id to Cloud direct events from background work (#22183)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip Cloud sends server telemetry straight to PostHog (`server/src/services/posthog-direct/`) > - Request events get `company_id` from the request context. Background events have no request. > - So `agent.task_run`, `routine.run`, `connection.invoked`, and other background events arrive with `stack_id` but without `company_id`. On staging, 66 of 66 `agent.task_run` events had a null `company_id`. > - Without `company_id`, product analytics cannot split agent and routine activity by company. > - This pull request lets each background emit site name the company of the entity that it reports on. Only the direct PostHog transport reads that company. > - The benefit is that Cloud background events carry `company_id`, and the self-hosted collector output does not change. ## Linked Issues or Issue Description Refs #22006 **Subsystem affected** Server telemetry: Cloud direct delivery to PostHog (`server/src/services/posthog-direct/`) and the server emit sites for background events. **Problem or motivation** Cloud direct events from background work have no `company_id`. Heartbeat runs, scheduled routines, connection invocations, and interaction updates do not run inside an HTTP request, so the request context gives no company. On paperclip.staging, all 66 sampled `agent.task_run` events had `company_id` null. **Proposed solution** Add a small AsyncLocalStorage scope, `withTelemetryCompany(companyId, fn)`, in `server/src/telemetry-company-scope.ts`. Each background emit site wraps its typed `track*` call with the company id of the row that it already has. The direct transport reads the scope at track time, through the existing `captureEventContext()` seam. A live request company still wins. The collector path never reads the scope. **Alternatives considered** 1. An optional context argument on the shared `track*` helpers. This changes the public helpers in `@paperclipai/shared` for a Cloud-only value, so I did not use it. 2. A scope around each whole work unit (heartbeat run, routine run, invocation). The emit calls are fire-and-forget and are spread across many modules, so it is easy to miss one or to leak a company into other work. A scope at the emit site is narrow and explicit. 3. Let the transport look up the company in the database. The transport must not query the database. **Roadmap alignment** This completes the Cloud direct PostHog work from #22006. It does not change the telemetry contract. ## What Changed - Add `server/src/telemetry-company-scope.ts`. It has `withTelemetryCompany(companyId, fn)` and `scopedTelemetryCompanyId()`. With no company id, it calls `fn` directly. - `capturePostHogEventContext()` uses the scoped company when no live request gives a company. The request company, user, and session behave as before. - Wrap these emit sites with the company of their entity: - `agent.task_run` (`emitAgentTaskRun`, `emitAgentTaskRunById`; `companyId` is now part of the run that the function reads). This covers heartbeat, native runtime, recovery, run-dispatch, and watchdog callers. - `routine.run` (`routineService` dispatch, which covers scheduler, webhook, and manual runs) - `agent.first_heartbeat` (heartbeat agent status) - `connection.created`, `connection.updated`, `connection.invoked` - `interaction.created`, `interaction.resolved` - `agent.task_completed` (issue route; the issue company is the fallback when the request gives no company) - Request-only events (`project.created`, `goal.created`, `agent.created`, `routine.created`, `skill.imported`) keep the request context. `server.started` and `error_handler.crash` are not company-scoped. Dynamic plugin and `question_response.delivery` events are not in the contract, so the direct path drops them. - Update the "Cloud Direct Delivery" section of `packages/shared/src/telemetry/README.md`. Design note on module boundaries: the scope lives beside `server/src/telemetry.ts`, not inside `posthog-direct/`. Emit sites do not import the transport, and the transport does not know which services exist. The shared telemetry package does not change. ## Verification - Red/green: with the source changes removed, these 4 new tests fail. With the changes, they pass. - `agent-task-run-telemetry.test.ts`: `emitAgentTaskRun` and `emitAgentTaskRunById` track in the run company scope. - `routine-run-telemetry.test.ts`: a routine run tracks in the routine company scope. - `posthog-direct-telemetry.test.ts`: on Cloud, background `agent.task_run` and `routine.run` (also after an `await`) carry `company_id`, and an unscoped event does not. - `posthog-direct-telemetry.test.ts`: a live request company wins over the scope, and the scope fills the gap when the request has no company. - Red/green per emit family: the tests for `connection.created`, `connection.updated`, `connection.invoked`, `interaction.created`, `interaction.resolved`, `agent.first_heartbeat`, and `agent.task_completed` assert the company scope at track time. With the emit-site wrappers removed, all 7 assertions fail. - New guard test: on self-hosted, a scoped `agent.task_run` and `routine.run` produce a byte-identical collector envelope with no `company` text. - `cd server && npx vitest run` on 16 telemetry, PostHog, routine, heartbeat status, interaction, and connector test files: 408 passed. - `pnpm --filter @paperclipai/server typecheck`: passed. - Local check with a real `posthog-node` client sent to a local capture server (never real PostHog), embedded Postgres, and a real `routineService.tickScheduledTriggers()` tick plus `emitAgentTaskRun`: - Cloud mode: the captured `routine.run` (`source: schedule`) and `agent.task_run` both had the seeded `company_id`, plus `stack_id` and `environment`. `server.started` had no `company_id`. - Self-hosted mode: the collector body from this branch and from `origin/master` are identical after I normalize random ids and timestamps. - I did not boot a full Cloud-managed server, because it needs S3 and an external Postgres. The check above uses the same server modules and the real PostHog client. ## Risks - Privacy review: this is a Telemetry change under `rules/data-paths.mdc`, so I request a privacy review. Background Cloud events now send the real Paperclip `company_id` to PostHog. #22006 already approved `company_id` as a Cloud direct property for request events. This PR only fills it for background events. It adds no new property, dimension, or event, so the generated contract does not change. `packages/shared/src/telemetry/README.md` is updated in this PR. - Low runtime risk. The self-hosted collector path does not read the scope, and a test proves its output does not change. - On Cloud, more events now have `company_id`. No event loses a field. - If a request with a company tracks an event for an entity in a different company, the request company wins. This is the same as before this change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, and test runs). ## 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 - [x] All Paperclip CI gates are green - [x] 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> |
||
|
|
1c556d5340 |
fix(native): never rest a task blocked on the agent's own blocker (#22140)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - A native run ends with one semantic report. A `paperclip_block`
report names a blocker, its owner and the unblock action
> - The status arbiter binds a task-wide blocker. When the owner is not
a person, it binds the blocker to the same agent and wakes that agent
> - The dispatcher refuses those self-wakes
(`chat_control_recovery_proof_unresolved`), because only continuation
and retry effects are proof for a native wake. The task then rests
blocked with no owner, no wake and no Retry
> - #21959 continues a system blocker in a fresh session, but only for
the reason codes `environment_unavailable` and `tool_unavailable`. A
restart-chaos rerun showed the same dead end with the reason code
`tool_output_failure`
> - This pull request makes sure that a blocker that the agent reports
for itself always has a next owner: the automatic environment lane, one
bounded self-continuation, or a person with a Retry that works
> - The benefit is that no task rests blocked with nobody to act, and no
path wakes the agent in a loop
## Linked Issues or Issue Description
Refs #21959
**What happened?**
A native OpenCode run (DeepSeek) said that every tool call returned the
text "cryptic". It reported `paperclip_block` with owner `{kind:
system}`, scope `task_wide`, reason code `tool_output_failure`, and an
unblock action about the tool-output failure. The run succeeded with
disposition `blocked`. The arbiter bound the blocker to the same agent
(`task_wide_blocker_bound`). The `notify-owner` wake coalesced, and the
`blocker-owner` wake was skipped as
`chat_control_recovery_proof_unresolved`. The task rested blocked
(`needs_attention`, 0 blockers), with no Retry and no wake. An earlier
rerun showed the same shape with reason code `environment_unavailable`,
which #21959 fixed for those two codes only.
**Expected behavior**
A blocker that the agent reports for its own tools or environment is a
harness problem. Paperclip continues it automatically, with a bound. A
blocker that the agent says it owns gets one fresh session. A blocker
that needs a person goes to a person, with a clear prompt and a Retry
that starts the task again. Nothing is left with nobody.
**Steps to reproduce**
1. Run a native task. Make the agent call `paperclip_block` with owner
kind `system`, scope `task_wide` and a reason code other than
`environment_unavailable` or `tool_unavailable` (for example
`tool_output_failure`).
2. See the decision `task_wide_blocker_bound` with the agent as the
unblock owner.
3. See both owner wakes refused, and the task blocked with no Retry.
**Paperclip version or commit**
`master` at
|
||
|
|
069ec8a74e |
fix(restart-chaos): exempt a continuation of an uncommitted follow-up run from completion_once (#22137)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The restart-chaos harness grades each task after deploy-like restarts, and the `completion_once` rule finds tasks that an agent completed twice > - A follow-up comment can arrive while a task runs. The run that answers it can complete the task again, and the grader exempts that run > - The grader did not exempt a recovery continuation of that answering run when the answering run failed before it committed a completion > - So the grader reported a duplicate completion for correct product behavior, and the wave headline counted a false duplicated side effect and an extra turn > - This pull request makes a continuation (a run with `retryOfRunId`) of an answering run that never committed a completion count as the answering run > - The benefit is that wave results show real duplicates only, and a real second completion after a committed one still fails ## Linked Issues or Issue Description **What happened?** In a restart-chaos staging-mix wave, task t128 (opencode, fault K13) graded `completion_once` as failed with the detail "duplicate completion: runs 38a8772f, 833314ed each reported completion". The wake evidence shows this sequence: - Run 38a8772f completed the task (accepted disposition `done`) and posted the DONE comment. - The follow-up comment arrived before that completion. Its first two runs (5707e93a and 2c1d364e) failed before a provider turn, so they did not receive it. - Run c5f9a5a4 received the follow-up and started a provider turn. It then failed with `native_session_retry_exhausted` and did not commit a completion. - Execution recovery started run 833314ed with `retryOfRunId` = c5f9a5a4 (wake reason `issue_recovery_action_restored`). That run applied the follow-up and committed `done`. The grader marked only c5f9a5a4 as the answering run. Run 833314ed was a continuation of it, but the grader counted it as a second completion and as an extra turn. **Expected behavior** A continuation of the answering run must count as the answering run when the answering run did not commit a completion. A continuation that completes again after the answering run committed its completion must still fail `completion_once`. **Steps to reproduce** 1. Use the t128 wake evidence shape: a first run that completes, two follow-up runs that fail before a provider turn, an answering run that fails without a completion, and a recovery run with `retryOfRunId` set to the answering run that completes. 2. Grade it with `gradeStagingMix` through `evidenceCompletion` or `completionEvidence`. 3. Before this change, `completion_once` fails with "duplicate completion: runs 38a8772f, 833314ed each reported completion". ## What Changed - `tests/restart-chaos/follow-up-delivery.ts`: add `continuedRunId` (reads `retryOfRunId` from the run context or the wake payload) and `followUpAnsweringRuns`. The new function returns the runs that answered a follow-up, plus each continuation of an answering run that did not commit a `done` result. - `tests/restart-chaos/staging-mix-retry.ts`: `evidenceCompletion` and `runsAfterDone` use `followUpAnsweringRuns` to set `answersFollowUp` and to separate answered runs from extra turns. `followUpsAnsweredLater` and the wait statistics are not changed, so one follow-up still counts as one answer. - `tests/restart-chaos/wake-evidence.ts`: `completionEvidence` (the record that the wave grade uses) uses the same function. - `tests/restart-chaos/staging-mix-retry.test.ts`: add a t128 test group from the real wave evidence. One test shows the continuation passes. One test shows a continuation after a committed answering completion still fails. ## Verification - Red before the fix: `passes when the continuation of an answering run that never committed completes the follow-up` failed (`completionRunIds` returned both 38a8772f and 833314ed). - Green after the fix: both new tests pass, and all existing truth-table and follow-up tests pass. - `npx vitest run --config tests/restart-chaos/vitest.config.ts`: 71 files, 844 tests passed. - `tsc -p tests/restart-chaos/tsconfig.json --noEmit`: passed. - I regraded the real t128 wake evidence and comments with the fixed functions. The result is one completer (38a8772f), no extra turns, and answered runs c5f9a5a4 and 833314ed. - `pnpm verify` exited 2 because `follow-up-delivery.ts` is a global CI input. Required CI supplies the broad coverage. ## Risks - Low risk. The change is in the restart-chaos test harness only. It does not change product code. - The exemption needs an explicit `retryOfRunId` link to the answering run. A recovery run with no link (for example the t005 case) still fails, as before. - If the answering run committed `done`, its continuation is not exempt, so a real second completion still fails. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, used in Claude Code with tool use (shell, file edits, test runs). ## 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 - [x] All Paperclip CI gates are green - [x] 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> |
||
|
|
43b2d8be22 |
feat(dashboard): add an experimental areas and responsibilities dashboard (#22069)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The dashboard is the first page a person sees in a company > - The classic dashboard shows agents, runs, costs and recent tasks > - It does not show what the person is responsible for, or if that work goes well > - People think in areas, such as Fundraising or Customers, and in the things they own in each area > - This pull request adds a dashboard built on areas and responsibilities, behind an experimental setting that is off by default > - The benefit is that a person sees what they own, how it is going, and what agents do for it, on one page ## Linked Issues or Issue Description No public issue exists for this work. The description follows the feature request template. **Subsystem affected** Dashboard, navigation, the task conversation, routines, and the instance experimental settings. **Problem or motivation** The classic dashboard counts agents and tasks. It does not say what a person owns or if it goes well. People who run a company with agents want to see their areas, the responsibilities in each area, the bar each one must meet, and the agents and routines that serve it. **Proposed solution** A person owns responsibilities. Each responsibility belongs to an area and has a bar, a number to reach. Projects, tasks and routines link to a responsibility, and the page shows its status from those links. An agent can interview the person and draft the dashboard. The person accepts or declines each change, and any change can be undone from a saved version. **Alternatives considered** Add the same data to the classic dashboard. That page is a fixed set of cards for company activity, so a second, person-centred page is clearer. The setting lets a person pick one of the two. **Roadmap alignment** This is an experimental feature behind `enableResponsibilities`. It is off by default and changes nothing for a person who leaves it off. ## What Changed - Add the setting "Areas & Responsibilities dashboard" (`enableResponsibilities`, off by default). On, Dashboard in the sidebar opens the new page, and the classic dashboard link is not shown in the sidebars or the command palette. Off, nothing changes. - Add tables and migrations 0492 to 0497 for areas, responsibilities, links to work, metrics, status reports, saved dashboard versions, and model-call records for summaries. - Add the API: areas, responsibilities, links, bars, metrics, status reports, summaries, runs, automation, and the dashboard conversation with versions and undo. Each route checks company access and writes to the activity log. - Add four task conversations with an agent: about a bar, about an automation, about a routine, and about the whole dashboard. The agent proposes a change. Nothing applies until a person accepts it. - Add standing checks: routines that an agent carries out on its heartbeat and reports. - Add the Dashboard page: search, counts, areas that open and close, a primary New area button, and a message box at the bottom of the page. Add the responsibility page with its bar, metrics, work and routines. - Add the Paperclip skill sections and runner API entries that let an agent use these routes. The runner skill inventory is regenerated (166 to 174 rows). - Keep the new runner API tests in their own file so `runner-api.test.ts` stays at 985 lines. - Onboarding is not changed. The onboarding changes that build on this work are a separate pull request. ## Verification - Type checks pass for `packages/db`, `packages/shared`, `server` (all layers) and `ui`. - `pnpm --filter @paperclipai/db check:migrations` passes. A new `drizzle-kit generate` run produces no further change. - Tests for every changed file pass: 26 server test files (3,009 tests), 116 UI test files (1,991 tests) and 28 shared test files (432 tests). - The runner capability inventory checks pass. - I started the app on a local database that already held earlier data. Master's new migrations and these migrations applied without error. With the setting on, the Dashboard and a responsibility page loaded with no console or server errors. The More menu and the command palette show one Dashboard. - I did not run `pnpm verify`, the full local suite, or the browser suites. Required CI covers them. - The agent conversations are tested with simulated agents. No real model has run them. ## Risks - Medium. The change is large, and the setting is off by default. With it off, the new routes refuse requests and the UI is unchanged. - Migrations only add tables and columns. Two replace a CHECK constraint, and one builds an index `CONCURRENTLY`. These two have the `online_compatible` override with a reason in the file, and the second one is listed in `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`. - Master can add migrations before this merges. The migrations then need new numbers. - `responsibilities.ts` (1,663 lines), `responsibility-summaries.ts` (1,239 lines) and one Storybook fixture file (1,305 lines) are new files over 1,000 lines. They each keep one cohesive unit together: the service for one table family, the model-call path for summaries, and the fixtures that the stories share. No existing file crosses 1,000 lines. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude: Claude Fable 5.2 (`claude-fable-5-2`) wrote most of the change, with Claude Sonnet 5.5 (`claude-sonnet-5-5`) for the final steps. Both used tool use, code execution and browser checks. ## 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 - [ ] 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 - [ ] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Scott Tong <scott@scottsmbpm5max.lan> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> |
||
|
|
4afcbfc0c7 |
fix(native): retry transient provider refusals while reattaching a handed-off run (#22118)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A release swap hands live native runs from the outgoing server to the incoming server. The incoming server reattaches each run to its original sandbox. > - Reattachment first resumes the exact sandbox lease through the sandbox provider plugin. > - In a release-swap wave, one reattach resume got an HTTP 502 from the provider gateway. The host did not retry it. The run failed with the generic `setup_failed` code after 13 minutes of agent work. > - The task then stayed blocked with a Retry banner for about 10 minutes, until the fresh-continuation fallback reached its bound and started a new run. > - This pull request retries a transient provider refusal during reattachment, with a bounded budget. It also reads the provider status from the plugin RPC error envelope, so the host sees the 502. > - The benefit is that a brief gateway failure during a swap is invisible to the user. The same run continues and no Retry banner shows. ## Linked Issues or Issue Description **What happened?** During a graceful release swap, the incoming server reattached a live native run to its retained sandbox. The `environmentResumeLease` plugin call failed with an HTML "502 Bad Gateway" body 280 ms after the reattach started. The other 18 handed-off runs in the same swap reattached in about 8 seconds. The host treated the 502 as an unknown error, so the run failed with `setup_failed`. The task stayed `blocked` with `canRetry: true` until the fresh-continuation fallback created a new run 10 minutes later. **Expected behavior** A transient provider refusal (HTTP 408/425/429/5xx, a connection errno, or a plugin RPC deadline) during reattachment is retried within a bounded budget. The same run continues hands-off. A definite refusal (for example HTTP 409) or a confirmed missing sandbox still fails at once with its own named reason. **Steps to reproduce** 1. Start a remote native run on a reusable sandbox. 2. Send SIGTERM to the server so it hands the run to the next server. 3. Make the first `environmentResumeLease` call on the incoming server fail with HTTP 502. 4. See that the run fails with `setup_failed` and the task shows Retry. **Paperclip version or commit** `master` at |
||
|
|
ea154ce55e |
Add bulk keyed issue document reads for native helpers (#22105)
## Thinking Path
> - Paperclip manages work for AI agents.
> - Native helpers read task documents through authorized API tools.
> - A scan of 146 cases needs one saved response and one download per
case.
> - The document service can read the same key across authorized tasks
with bounded queries.
> - This pull request adds a bounded bulk read with the existing task
access policy.
> - Helpers can transfer one batch and check current revisions before
fetching changed bodies.
## Linked Issues or Issue Description
**Subsystem affected**
Task document REST API, shared query contracts, and native API
discovery.
**Problem or motivation**
Per-task document reads make native sync scans cost hundreds of tool
calls. Task list timestamps do not prove that document content is
unchanged.
**Proposed solution**
Add `GET
/api/companies/{companyId}/issue-documents?key=notes&issueIds=...`. Read
up to 200 task UUIDs under current company and task permissions. Return
current bodies and revision metadata, or metadata alone with
`includeBody=false`.
**Alternatives considered**
Generic request batching would add tool execution and partial failure
rules. One bulk resource read removes the per-case relay cost with the
existing tools. Do not skip documents based only on task-row timestamps.
Keep managed skill files immutable; cleanup of copied skill test
fixtures belongs to those tests.
**Roadmap alignment**
This improves existing task documents and native API access. It adds no
new workflow or UI. The roadmap has no duplicate bulk document read
work. No duplicate open pull request was found.
## What Changed
- Add a bulk keyed document route and a company-scoped document reader.
Reuse the current batched task-read policy and completed-task read
receipts.
- Preserve request order and deduplicate IDs. Return `document: null`
for readable tasks without the key. Omit unreadable, hidden, foreign and
missing tasks without revealing which exist.
- Bound requests to 200 IDs and responses to 8 MiB of JSON bytes. Check
encoded body sizes in SQL before fetching bodies in the same read
snapshot. Build JSON within the byte budget. Oversized responses fail
with 413 and are never saved as partial artifacts.
- Admit at most two active reads per actor and eight per server
instance. Extra requests receive 429 with Retry-After. Keep the slot
until both the database work and response settle.
- Batch completed-handoff lookups and group child receipts by parent.
Extend the existing event batch writer for ordinary non-waking receipts
with atomic sequence allocation. Stored receipt shapes stay unchanged
for existing consumers.
- Expose revision-only reads without selecting document bodies. Document
native discovery, one save plus one download, and complete-inventory
checks.
- Add real HTTP, database and artifact tests for 146 open and completed
cases, 200 maximum-size bodies, metadata overhead, access failures,
query limits and JSON expansion. Cover admission limits, failure
cleanup, and concurrent event writers. Refresh the shared SDK source
pins.
## Verification
Final revision: `93dc8b029600211d79a050650f3dff82e5dad52f`.
- [CI run 44212220917, attempt
3](https://github.com/paperclipai/paperclip/actions/runs/44212220917)
passed. This includes typecheck, build, general tests, Runner checks,
serialized server suites, all e2e shards, and the final verify gate.
-
[Build](https://github.com/paperclipai/paperclip/actions/runs/44212220917/job/134506305267),
[e2e](https://github.com/paperclipai/paperclip/actions/runs/44212220917/job/134506309117),
and
[verify](https://github.com/paperclipai/paperclip/actions/runs/44212220917/job/134510062263)
are green.
- [Linux CI job
134506309291](https://github.com/paperclipai/paperclip/actions/runs/44212220917/job/134506309291)
passed all 16 bulk document integration tests. This includes the native
transfer of all 146 documents with the saved size and hash,
completed-case receipt batching, and size-only rejection of 200
maximum-size documents.
- [Greptile
review](https://github.com/paperclipai/paperclip/pull/22105#issuecomment-6965449032)
is 5/5 on the final revision. All review threads are resolved. Security
checks pass. GitHub reports CLEAN and MERGEABLE.
- Local server typecheck passed on macOS with Node 25.6.1. The focused
run below passed 177 tests; the Linux-only transfer test was skipped
locally and then passed in CI.
```sh
pnpm --filter @paperclipai/server typecheck
cd server
pnpm exec vitest run \
src/routes/issue-document-batch.test.ts \
src/services/native-runtime/issue-document-batch.integration.test.ts \
src/__tests__/documents-service.test.ts \
src/__tests__/openapi-routes.test.ts \
src/__tests__/heartbeat-run-event-atomic-append.test.ts \
src/__tests__/chat-completion-delivery.test.ts \
src/__tests__/native-child-task-read-routes.test.ts
```
- Shared typecheck and build passed. From `packages/shared/`, `pnpm exec
vitest run src/validators/issue.test.ts` passed 61 tests before the
rebase; the batch query contract did not change in the rebase.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`
passed. Runtime and lockfile pins are unchanged.
- `pnpm verify --explain` returned exit 2 because the API docs and
shared contracts require broader CI. The successful CI run above
supplies that coverage.
Failure and recovery record:
- Both performance findings reproduced before the fixes. Scale tests now
verify a size-only query for 200 large documents and one handoff lookup
plus two receipt-write statements for 146 completed cases. Concurrent
writers retain contiguous unique sequences and decoded payloads.
- Initial local runs found missing shared exports and OpenAPI route
coverage. These are fixed. Fixtures now respect Linux-only installation,
thrown cross-company denials, and the ES2022 TypeScript target. Rebase
conflicts preserved the onboarding coverage from master.
- CI attempt 1 interrupted Build, e2e shard 7 and six general-test
shards with runner shutdown signals. Attempt 2 recovered the tests but
its [Build
job](https://github.com/paperclipai/paperclip/actions/runs/44212220917/job/134499680425)
also received a shutdown signal and exited 143. No compiler or test
assertion failure was found in those interrupted job logs. The reason
the runners stopped remains unknown. Attempt 3 recovered Build and its
dependent verify gate on the same revision. Earlier interruptions are
not counted as passes.
## Risks
- Additive API only. No migration or existing endpoint response change.
- Helpers must adopt the batch response to gain the tool-call reduction.
They must verify that every requested task is present before treating
the scan as complete. Unreadable tasks are intentionally omitted.
- Split large document batches when the route returns 413. Metadata
remains available without bodies. Concurrency limits are per server
instance and can refuse simultaneous reads with 429; callers retry after
an active read finishes.
- This does not change company-owned helper inventory expiry or cleanup
tests, installed skill permissions, or generic tool batching. It does
not deploy to a tenant.
## Model Used
OpenAI `gpt-6.1-sol` through Codex in T3 Code, with xhigh reasoning,
tool use, and code execution. Context window size was not exposed.
## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
|
||
|
|
bf55063567 |
fix(server): keep chat titles current and space verification retries (#22102)
## Thinking Path > - Paperclip manages AI agents and their work. > - Agent chats use persistent tasks, and remote runs verify their provider files before execution. > - A chat keeps the name that its agent had when the chat was created. > - A fast gateway failure can consume both verification attempts before the gateway recovers. > - This change updates generated chat titles on an agent rename and waits before a verification retry. > - Chats show the current name, and a short gateway fault has time to clear. ## Linked Issues or Issue Description **What happened?** Renaming an agent leaves existing generated chat titles unchanged. Remote provider verification also retries a transport failure immediately. Two fast HTTP 502 responses can fail startup before the model starts. **Expected behavior** Generated chat titles follow an agent rename. A read-only verification retry gives the remote gateway time to recover. Verification still rejects incompatible files and stops after two attempts. **Steps to reproduce** 1. Open a chat with an agent, then rename that agent. Inspect the task linked from a run: its title still has the old agent name. 2. Make the remote verification transport return HTTP 502 for one second. Start verification. Both immediate attempts fail before the transport recovers. Related: #22087 covers a provider connection failure during lease acquisition. This change covers a later provider-file verification request. ## What Changed - Update matching generated chat titles in the agent configuration transaction. Preserve custom chat titles, ordinary task titles, and other agents' chats. - Record each changed chat as `issue.updated` and publish its event after commit so open pages refresh. Roll back the rename and queued events if audit persistence fails. - Derive new chat titles from the current agent name under the existing company transaction lock. Both user-opened and proactive chats use this path, including a create that read the old name before a rename committed. - Acquire that company lock before proactive chat delivery takes chat or agent row locks, so delivery and renames use a consistent lock order. - Wait one second before the second remote verification attempt. Keep the existing attempt limit, transport timeouts, artifact checks, and failure codes. - Add route and startup-verification regressions. Document the retry delay. - Wait for the connection-review E2E fixture to save its Ask first permission before it creates a task or navigates away. ## Verification - Final acceptance on `3fb74ffaf6fa0ee2ecbe5dba3d01d252cb0c986f`: [full CI run](https://github.com/paperclipai/paperclip/actions/runs/44208144377) is green, all 61 reported checks are complete with no failures, Greptile is 5/5 on this exact commit, all review threads are resolved, and GitHub reports the branch clean and mergeable. - Red/green: the rename test retained the old titles before the fix. The gateway recovery test consumed both attempts before the one-second recovery point. Both pass with the changes. - The live-update and concurrent-create tests failed on the first PR revision: no title events were published, and a paused chat creation retained the old name. The fixes queue events for publication after commit and re-read the agent name under the company lock. Both reproductions now pass. - `pnpm exec vitest run server/src/__tests__/agent-configuration-save.test.ts server/src/__tests__/agent-chat-messages.test.ts server/src/__tests__/agent-conversations.test.ts server/src/services/native-runtime/remote-provider-pack.test.ts server/src/services/native-runtime/remote-provider-pack-verification.test.ts`: 191 passed on macOS, including the concurrent rename/message regression. - `pnpm --filter @paperclipai/server typecheck`: passed, including source and test layers. - Earlier CI on `de2a0a4` failed in the release-registry watchdog self-test ([job log](https://github.com/paperclipai/paperclip/actions/runs/44202511888/job/134460224014)). Its 1.5-second watchdog fired during `starting the file's tests`; the assertion expected `test "waits forever"`. Both reporter files are unchanged from the base and current head. `node --test scripts/ci/stalled-file-reporter.test.mjs` passed all 7 tests on macOS with Node v25.6.1. The current revision also passed the Linux Typecheck + Release Registry CI check; no reporter code was changed. - CI on `c83fcd9` failed the connection-review failure journey ([shard log](https://github.com/paperclipai/paperclip/actions/runs/44204043415/job/134465938135)). Navigation aborted the pending permission save, so the fixture tool ran without creating the expected approval card. A temporary two-second delay on that save reproduced the failure locally. With the response wait, the same delayed-save reproduction passed. The temporary delay is removed from the diff. - `node scripts/typecheck-test-projects.mjs --reuse-declarations tests/e2e`: passed using the server declarations from the same application source revision. - Before the rebase, the complete connection-review spec passed 4 journeys and skipped the controlled-restart journey under the default configuration. On `95fb2aa`, rebased onto `9032f55d83e`, the provider-failure journey, all 190 focused tests, server typecheck, and E2E test-project typecheck passed again. The dedicated controlled-restart suite was not run. - A concurrent rename/message regression reproduced PostgreSQL `40P01: deadlock detected` on `95fb2aa`. Delivery now takes the shared company lock before the chat and agent locks. The regression uses observed PostgreSQL blockers to stage the collision, and both operations commit with the fix. Concurrent creation also waits behind the same lock and retains the renamed title. - The application tree for `3fb74ff` passed all 191 focused tests and server typecheck. The subsequent rebase onto `96907f5518c` changed only `.github/CODEOWNERS` compared with that tested tree. The full CI run for this revision is now green. - CI jobs on `95fb2aa` were interrupted after their runners received shutdown signals: [server shard](https://github.com/paperclipai/paperclip/actions/runs/44206614135/job/134474311777), [workspace shard](https://github.com/paperclipai/paperclip/actions/runs/44206614135/job/134474311921), [typecheck/release registry](https://github.com/paperclipai/paperclip/actions/runs/44206614135/job/134474310521), and [serialized server shard](https://github.com/paperclipai/paperclip/actions/runs/44206614135/job/134474311690). The typecheck job is labelled failed, but its active step was cancelled. These interruptions did not supply passing test evidence. The fresh CI run on `3fb74ff` completed without failures. - `pnpm verify --explain`: exit 2. The changed recovery document requires broad CI coverage. Required CI supplies the full test and build coverage; no full local suite or build was run. - `git diff --check` and a Gitleaks scan of the diff passed. The diff was also checked for personal data and private identifiers. ## Risks - An inconclusive verification takes one extra second before its last attempt. A persistent outage still fails with the existing named error. No provider turn or artifact mutation is replayed by this retry. - Only chat titles that match the previous generated title change. Earlier stale titles and custom titles need an explicit correction. - Proactive chat delivery now shares the existing company writer lock with agent configuration. Concurrent writes in that company wait for the active transaction to finish. - No schema, session, checkpoint, launch identity, or pack identity changes. State saved by the previous release carries forward with the same verification checks and attempt limit. - Revert this commit to restore the previous behavior. Existing title updates are metadata and need no schema rollback. ## Model Used - OpenAI Codex, `gpt-6.1-sol`, xhigh reasoning, with source inspection, browser investigation, and local 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
ce27dde855 |
Start onboarding in chat and defer execution until the user chooses work (#22077)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Onboarding connects an agent and gives the user a place to discuss work. > - The previous flow created an execution task and project before the user chose a scope. > - A standing chat can gather the goal and clear exit criteria first. > - This pull request opens chat after onboarding and starts a live welcome after the chat is visible. > - The agent proposes work for acceptance, or creates a task when the user explicitly requests one. > - Subscription setup and shared question state must work for this first conversation to succeed. ## Linked Issues or Issue Description **Subsystem affected** Company onboarding, agent chat, local subscription setup, task numbering, and shared interaction views. **Problem or motivation** The first session creates work before the user has agreed to a goal. Standing chats consume task numbers. An answered chat question can remain pending in the inbox. Claude code entry requires an extra click, and switching from Claude to Codex can leave an incompatible model selected. **Proposed solution** Open an owner-bound chat for every new company. Start a live welcome after the chat paints in a visible tab. Gather scope in conversation and use the existing task acceptance flow. Keep chat records out of the task number sequence. Publish question responses to shared caches and cancel stale reads. Submit pasted Claude codes once and wait for verified sign-in before connecting. **Alternatives considered** A fixed welcome would not use the onboarding context. A hidden execution task would still create work and consume a task number. Keep the existing task proposal and acceptance contract instead. **Roadmap alignment** This improves the shipped Agent Chat and Personal & Shared AI Accounts flows in ROADMAP.md. It does not add a separate execution or approval system. Related prior work: Refs #19643 and #19512. Related route handoff work: Refs #12557. This change replaces the automatic first task with chat; it also repairs the subscription and shared question state paths used during that journey. ## What Changed - Finish onboarding in agent chat for default and team-template companies. Create no execution task or project. - Queue one live welcome after visible chat content paints. Pass company goals and the initial idea as context. Preserve access, budget, and hiring controls. - Instruct the agent to gather a goal and exit criteria, offer an interview, and propose tasks for acceptance. Allow direct creation on an explicit user request. - Leave new standing chats unnumbered. The first execution task receives number 1. Preserve existing identifiers. - Synchronize answered question cards across chat and inbox, including concurrent requests and inactive cached views. - Submit a pasted Claude authorization code once. Show connection progress and hide the restart link while sign-in is still preparing. Detect rejected OAuth codes promptly. Clear incompatible models when the provider changes. - Use `Work with [agent name]` as the default chat composer placeholder. - Add regression coverage and update onboarding documentation and API notes. ## Verification - Completed a real Claude subscription journey on macOS with an isolated local database. Authorized the account, pasted the real code, and reached the review step without clicking Submit code or Connect. Get started opened chat and the live welcome run succeeded. The company had zero execution tasks, zero projects, and task counter 0. - On rebased commit c664949858, 6 browser cases passed for paste-to-connect-to-chat, task-free onboarding, existing-company routing, the native connection probe gate, desktop/mobile planning, and two-tab chat/inbox question synchronization. - On the rebased head, 419 focused UI tests passed. The focused server and adapter run passed 160 tests and hit one `socket hang up` in the existing authenticated chat route test. The full 72-test conversation suite passed on one repeat. The cause of that first socket failure remains unconfirmed; the passing repeat does not establish its cause. - UI typecheck and server declaration typecheck pass after the rebase. The first server check found a missing local dependency from master; a frozen-lockfile install repaired it. No dependency manifest or lockfile change was needed. - The first Greptile review found two welcome edge cases. Four new tests reproduced both before the fix. On commit b380f14ef9, all 114 onboarding and queue tests pass, including timeout retries and queued welcomes replaced by a user message or chat reset. Server source and focused test type checks pass on this revision. - [Greptile review](https://github.com/paperclipai/paperclip/pull/22077#issuecomment-6961533641) gives rebased commit |
||
|
|
f295e496db |
fix(daytona): retry lease acquisition after a provider connection failure (#22087)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agent runs on Daytona start with a lease acquisition in the Daytona plugin > - When the host cannot reach Daytona, the Daytona SDK raises a connection error that has no HTTP status and no errno > - The host only retries a lease failure that carries structured evidence, so this failure became `setup_failed` and the task waited for a person to press Retry > - This pull request makes the plugin report the SDK connection error as a closed transport code that the host already retries > - The benefit is that a short network blip during sandbox startup no longer needs a Retry click ## Linked Issues or Issue Description **What happened?** In a restart-chaos wave (201 tasks, 6 graceful release swaps), the host could not resolve or reach Daytona for about 12 minutes. One task needed a Retry click. Its only run failed with `setup_failed` (`lease_acquire_failed`) and the message `Failed to acquire lease for environment "Daytona warm ..." (sandbox): read EADDRNOTAVAIL`. Automatic recovery did not continue the task because `setup_failed` is not a transient setup code. The task stayed failed for about 100 minutes until the grader pressed Retry. **Expected behavior** A lease acquisition that fails because the provider could not be reached is retried automatically with the bounded bootstrap budget, as `environment_provider_unavailable`. A person never needs to press Retry for a network blip. **Steps to reproduce** 1. Use the Daytona provider. 2. Make a Daytona API call during lease setup fail at the transport level (no HTTP response), for example with `read EADDRNOTAVAIL` or `getaddrinfo ENOTFOUND`. 3. See that the run fails with `setup_failed` and the task shows Retry. **Paperclip version or commit** master `ca34aca777` (wave) and `02ee538be9`. Root cause: the pinned `@daytonaio/sdk` converts an Axios transport error into `DaytonaConnectionError` (or `DaytonaConnectionTimeoutError`). It keeps neither the errno nor the cause. The worker RPC therefore sent no provider diagnostic, and `readTransientLeaseAcquisitionFailure` returned `null`. ## What Changed - The Daytona plugin wraps a `DaytonaConnectionError` from lease acquisition in an error with code `CONNECTION_FAILED`, and a `DaytonaConnectionTimeoutError` with code `ETIMEDOUT`. The message is unchanged. It reads the SDK class name only, never message text. - The plugin SDK closed diagnostic set accepts `CONNECTION_FAILED`, so the code crosses the worker RPC. - The host treats `CONNECTION_FAILED` as a transient connection failure. The run becomes `environment_provider_unavailable` and uses the existing bounded bootstrap retry (30 s, 60 s) and the automatic-run brake. - Refreshed `tests/runner-e2e/source-sdk-public-inputs.json` for the changed SDK file. ## Verification - Red/green: with the source change removed, the new plugin tests (`reports a DaytonaConnectionError during setup as a transient transport failure`, timeout variant) and the new host tests (`treats errno CONNECTION_FAILED as transient`, `retries a provider connection failure reported across the worker RPC`) fail. With the change, they pass. - `cd packages/plugins/sandbox-providers/daytona && npx vitest run` (637 passed). - `npx vitest run server/src/services/environment-provider-unavailable-error.test.ts packages/plugins/sdk/tests/environment-acquire-error.test.ts` (66 passed). - `pnpm typecheck` in the Daytona plugin passes. - `pnpm verify` asks for broad CI coverage because the SDK input registry changed. CI supplies that coverage. ## Risks - Low risk. A wrong Daytona API URL also produces `DaytonaConnectionError`. It now gets two bounded retries (about 90 s) before the same Retry state as before. - The retries count toward the automatic-run brake, so a long outage cannot multiply run starts across the company. - A create that timed out on the client keeps its existing creation-cleanup envelope. The retry is a new creation attempt with its own identity. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## 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> |
||
|
|
23ce68a8dc |
feat(connections): end Google access when a Paperclip-managed Google connection is removed (#22065)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Connectors let agents use Google Workspace through a Google sign-in
that Paperclip Cloud manages for the user
> - When a user removes a Paperclip-managed Google connection, Paperclip
deletes the tokens locally, but the grant stays live at Google
> - Google's OAuth review expects that a disconnect ends the app's
access, and users expect it too
> - Google's revoke ends the user's whole grant to the shared client, so
only the Paperclip Cloud broker can decide when it is safe to revoke
> - This pull request asks the broker to revoke each removed grant,
keeps local removal unconditional, and tells the user the outcome in
plain language
> - The benefit is that removal ends Google access when no other
Paperclip connection needs it, and the user knows what to do when it did
not
## Linked Issues or Issue Description
**Subsystem affected**
Connectors: Paperclip-managed Google Workspace and the legacy
per-service Google connections (server removal, shared contracts,
connection UI).
**Problem or motivation**
Removing a Paperclip-managed Google connection or grant was local only.
The refresh token was deleted in Paperclip, but Google still listed
Paperclip as having access to the account. The docs said so ("Removal is
local for managed grants").
**Proposed solution**
On removal, send each removed grant's refresh token to the broker's
signed `POST /v1/connector/revoke`. The broker revokes at Google only
when no other live binding could share the grant. Paperclip records the
broker's outcome code and shows one of three plain messages. Local
removal never waits on, or fails because of, that call.
**Alternatives considered**
Call Google's revoke endpoint from the app. This ends the user's whole
grant to the shared client and can break their other Google connections,
so the broker owns the decision.
**Additional context**
Older brokers answer 409 `REVOCATION_NOT_AVAILABLE`. The app treats
that, a timeout, and a network error as "could not end access at Google"
and still removes the connection.
## What Changed
- `paperclip-cloud-connector.ts`: `revoke()` takes an optional
`timeoutMs`, returns the broker's `outcome` from an allowlist, and keeps
`REVOCATION_NOT_AVAILABLE` as an allowed rejection reason.
- New `tool-access/connections/google-access-removal.ts`. For a managed
Google connection, `prepare()` reads each removed grant's refresh token
and returns a `send()` step. `send()` calls the broker for each distinct
token, one after another, under one 5-second deadline. Every result and
every error (including a Paperclip Cloud client that cannot be created)
becomes an outcome code. It never rejects and never logs a token. An
unexpected error is logged with the error name only and reported as
`unexpected_error`.
- Order for removing a whole connection: read the tokens, run the whole
local teardown (grants, installs, app profile, gateway tokens, runtime
slots, catalog, OAuth state, archive the connection), call the broker,
delete the sent refresh-token secrets whatever the outcome, then delete
the remaining secrets. A failure anywhere in the teardown makes no
broker call. Order for removing one grant: read the token, commit the
revocation, call the broker, delete the grant's refresh-token secret.
`send()` owns the call and the deletion through an injected
secret-removal function.
- Owed revocations: a revoked managed Google grant whose refresh-token
secret still exists (and that nothing live uses) is sent by every later
removal, then the secret is deleted. This covers a process stop after
the teardown and before the call, with no new column. Once the secret is
deleted, nothing is sent again.
- Shared tokens: the shared (organization) sign-in writes the same
secret refs to the organization grant and the connection. So revoking an
organization grant alone neither calls the broker nor deletes the
secret, because the connection still uses that token; removing the
connection does both. The same rule applies to any refresh token still
used by another live grant or connection.
- Audit history: once the broker call settles, a
`connection.google_access_removal` audit event records `reasonCode` =
result and `providerAccess` (plus `grantId` for a single grant). If that
write fails, the removal still succeeds and the failure is logged.
- Revoke signs with the subject that consented to the grant
(`providerTenant.externalId`, saved by the managed callback from the
claim). Grants saved without it fall back to the refresh rule. Refresh
is unchanged; see Risks.
- `removal.ts` and `grants.ts`: `providerAccess: { provider, result,
outcomes }` goes to the responses and to the `tool_connection.archived`
and `tool_connection.grant_revoked` activity entries. The tool access
audit field `providerRevocation` keeps its Vercel meaning only.
- `packages/shared`: `ManagedGoogleAccessRemoval`,
`ManagedGoogleRevocationOutcome`, `ConnectionGrantRevocationResult`.
- UI: one helper, `connectionRemovalToast`, builds the removal toast
(base sentence plus the Google notice, tone and action) for Connectors,
Connections and the app page. No codes are shown.
- API: `docs/api/tool-connections.md` documents both DELETE responses
and `providerAccess`. The OpenAPI registration describes the optional
field and its four results.
- Docs: `GOOGLE-WORKSPACE.md` (order, owed revocations, decision table),
`GMAIL.md`, the Google connector memory note, and the help page on
deleting connection data.
Decision table, judged over the distinct tokens sent in this removal:
| Outcomes | `result` | User message |
| --- | --- | --- |
| Every token `revoked` | `ended` | "Paperclip's access to this Google
account was also ended at Google." |
| Any failure-type code: `provider_revocation_failed`,
`binding_not_known` (the broker had no record, so Google was not
called), `provider_revocation_disabled`, `revocation_in_progress`,
`revocation_not_available`, `broker_unavailable`, `broker_error`,
`credential_unavailable`, `unexpected_error` | `not_ended` | "Paperclip
removed the connection but couldn't end its access at Google. You can
remove Paperclip from your Google account's third-party connections." +
"Open Google account connections" |
| Only `other_connections_remain` | `other_connections_remain` | "Other
Paperclip connections still use this Google account, so Google keeps
Paperclip's access until you remove those too." |
| At least one `revoked`, the rest `other_connections_remain` |
`ended_unconfirmed` | "Paperclip's access was ended at Google. If more
than one Google account was connected here, check your Google account's
third-party connections to be sure." + "Open Google account connections"
|
Grants record no Google account identity: the managed callback saves
`externalId` (the Paperclip subject), `name` (the provider name), and
OAuth timing and scopes, and none of the 14 scopes returns an account
identifier. So the last row is always `ended_unconfirmed`. This includes
two tokens of one user and several agent grants on one Google account.
## Verification
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/google-managed-connection-removal.test.ts
src/services/tool-access
src/services/paperclip-cloud-connector-revoke.test.ts
src/services/paperclip-cloud-connector.test.ts
src/__tests__/tool-connection-removal.test.ts
src/__tests__/tool-access-service.test.ts
src/__tests__/openapi-routes.test.ts` (714 passed)
- `pnpm --filter @paperclipai/ui exec vitest run
src/features/connections/googleAccessRemoval.test.ts src/pages/apps`
(passed)
- Server test typecheck (`node server/scripts/typecheck-layers.mjs`)
passes.
- Red then green: the server tests failed on `master` sources (21), then
each review round's new tests failed on the previous head and pass now.
They cover: the order on both paths, local failure before the grant
commit making no call and the retry sending, cleanup failure after the
call making no second call, a process stop between commit and call being
sent on retry with the secret deleted after, a Paperclip Cloud client
that cannot be created, the consenting subject for an organization
grant, sequential sends under one deadline, each row of the decision
table (per-agent and same-user cases give `ended_unconfirmed`, a mixed
failure gives `not_ended`), the unexpected-error log without a token, no
token in any log call, the delete-stored-data option, and a toast test
per surface.
- Added time, measured locally with a stubbed broker that answers at
once: median 22.1 ms against 20.3 ms without the broker step (12 runs
each), about 2 ms. With a real broker, one round trip per removed token,
capped at 5 seconds in total.
- `pnpm verify` exits 2 (a global CI input changed), so required CI
supplies the broad coverage.
- Not verified against a live broker or a real Google account.
## Risks
- A removal of a managed Google connection or grant can take up to 5
seconds longer when the broker is slow.
- Refresh subject is not changed in this PR. In the broker
(`recordProviderGrant`), a ledger row's subject is fixed when the row is
first written, and a refresh under another subject leaves that row
untouched. So moving refresh to a new subject could stop updating the
row's last-seen time. After 200 days the row would then count as not
live, and a later removal elsewhere could revoke at Google while this
connection still works. That risk cannot be ruled out from code for rows
written before this release, so both refresh paths keep their old rules.
The two refresh paths already use different subject orders today: the
gateway prefers `connectorSubjectAgentId` and then
`connectorSubjectUserId`, while background refresh prefers the grant's
own subject. That is pre-existing, and this PR leaves it unchanged.
Revoke uses the consenting subject, which matches the claim-time ledger
row. When the row was first written by a refresh under a different
subject, the broker answers `binding_not_known` and the user gets the
warning.
- Repeated removals can send an already-removed token again; the broker
returns its recorded outcome and changes nothing at Google.
- Against an older broker, users see the "could not end access at
Google" message, which is accurate.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`) in 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>
|
||
|
|
b43a08201c |
chore(lockfile): refresh pnpm lockfiles (#22020)
## Thinking Path > - Paperclip uses a dependency lock for reproducible builds. > - Dependency changes on master need matching lock entries. > - Paid eval reports also pin a reviewed offline correction. > - Reports must install before paid model work starts. > - This automated PR keeps the lock and report proof together. ## Linked Issues or Issue Description **What happened?** Dependency manifests on master changed after the last committed lock refresh. **Expected behavior** Frozen installs must match those manifests. Eval reports must retain matching offline lock proof. **Steps to reproduce** Run a frozen install before and after this lock refresh. ## What Changed - Refresh the dependency lock from the manifests on master. - Refresh the sandbox provider lockfiles from their manifests on master. - Include the matching offline report correction and hashes. - Resync the SDK public source proof's lock pins from the refreshed lock. ## Verification - Pinned pnpm resolution completed with lifecycle scripts disabled. - The report proof refresh accepted the reviewed committed baseline. - The workflow rejected changes outside the lock and report proof files. ## Risks The lockfile bot merges this PR without CI or review when every added package version is at least 3 days old on npm. Otherwise the PR waits for a maintainer, and the daily refresh tries again. The bot merges only the exact commit this workflow generated from manifests already reviewed on master. Unknown report lock baselines remain blocked. This update changes no permissions or paid enable gates. ## Model Used None — generated by pnpm and the deterministic report-lock updater. ## Checklist - [x] Thinking path and problem description included - [x] Generated lock and matching report proof included - [x] Release-age gate decides between bot merge and maintainer review Co-authored-by: lockfile-bot <lockfile-bot@users.noreply.github.com> |
||
|
|
f4cb69205e |
Let plugin workers serve connector tools (plugin transport) (#22019)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plugins can now add connector types to the Connectors catalog (#22004), but only for transports the host already runs (remote MCP, local stdio) > - A plugin cannot yet serve a connector's tools itself, and legacy plugin tools (top-level manifest `tools`) still reach every agent without a connection or install > - A plugin should be able to ship a full connector: settings, credentials, tools, grants, policies and audit, like a built-in one > - This pull request adds the `plugin` transport, the SDK API to serve it, and moves legacy plugin tools under the same activation rules without changing today's access > - The benefit is that any connector can live in a plugin, and agents get plugin tools only when an operator enables them ## Linked Issues or Issue Description Refs #22004 **Subsystem affected** Plugins (SDK, worker protocol, manifest), Connectors (tool access, catalog discovery), tool gateway, database. **Problem or motivation** A plugin connector can only describe an existing transport. There is no way for a plugin worker to serve a connector's tools with per-connection settings and credentials. Legacy plugin tools are visible to every agent as soon as the plugin is enabled, which is the opposite of the connector activation rules. **Proposed solution** Add a `plugin` transport. The gateway keeps every decision (grant, policy, approval, rate limit, audit) and calls the plugin worker with the connection, its settings and a per-call credential. Legacy top-level tools become one implicit connector per plugin. Existing installations keep exactly their current access through a one-time migration. **Alternatives considered** Move legacy tools to connection tool names (`app.<connection>:<tool>`). Rejected: names change, so existing tool policies and agent instructions that name `plugin:tool` would stop matching (a possible widening or loss). Legacy tools keep their names and handlers; only their visibility is now gated by an install of the implicit connector. ## What Changed - `packages/db`: migration `0491` widens `tool_connections_transport_check` with `plugin` (`NOT VALID`, annotated `online_compatible`), and adds `plugin_connector_legacy_access`, seeded with one row per installed legacy-tools plugin and company. - `packages/shared`: method schema gains `settingsSchema` and `tools` (`{ kind: "static", list: [{ name, displayName?, description?, risk, parametersSchema }] } | { kind: "dynamic" }`), only for `transport: "plugin"`; tool names must match `[a-z0-9_]`; plugin-served methods use `none` or `api_key`. The connect API accepts `settings`. - `packages/plugins/sdk`: `ToolRunContext.connection` (`id`, `appSlug`, `methodKey`, `grantId`, `settings`, `credential?`); `ctx.connectors.register(appSlug, toolName, fn)` and `ctx.connectors.listTools(appSlug, fn)`; new `listConnectorTools` RPC; `executeTool` routes connector calls by `appSlug`. A worker refuses to start when a declared static tool (or dynamic lister) has no handler. The test harness gains `executeConnectorTool` and `listConnectorTools`. - `server/src/services/plugin-connector-runtime.ts`: routes one call to the plugin's worker; a stopped worker is a `PluginWorkerUnavailableError`. - Connect flow (`tool-access.ts`): a `plugin` method creates a `paperclip_plugin` application and a `plugin` connection with `config = { sourceTemplateKey, connectionMethodKey, settings }`, validated against `settingsSchema`. Credentials, grants, credential policy, installs and profiles use the existing code. - Catalog: static tools come from the definition, dynamic tools from `listConnectorTools`, with the existing version hashing and retirement. Tool risk comes from the declaration. - Gateway: plugin connections join connected-tool discovery and both execution paths (direct and approved actions). For each call the gateway resolves the grant and, for `api_key`, the credential for that call only. The run context comes only from the session. A stopped worker returns `503 plugin_connector_unavailable` with `retryable: true`. The token broker refuses to export plugin connector credentials. - Legacy tools: a plugin with top-level `tools` and no `apps` gets an implicit connector (slug `default`, named after the plugin, no authentication). Its tools keep their names, handlers and today's access decision, and an agent sees them only when a connection of that connector is installed for it or for the company. The connector's saved action rules (Off, Ask first) can only restrict them. `completeLegacyPluginToolAccess` turns each migration row into such a connection with a company install, at boot and when a disabled plugin is enabled again; it is single-flight across servers, resumes a draft left by an interrupted attempt, and never overrides an operator's later changes. - Catalog: tools a dynamic connector stops offering are retired from discovery; `listConnectorTools` carries the connection's `companyId`, and uses the acting person's grant for personal connections. - Board: the setup flow renders `settingsSchema` with the shared JSON Schema form, sends `settings`, and restores saved settings on resume and reconnect. - `create-paperclip-plugin --template connector` now scaffolds a plugin connector (`apps` + `ctx.connectors.register` + a harness test). SDK README and `PLUGIN_SPEC.md` describe connectors; top-level `tools` stay documented as legacy. - `inferToolRisk` moves to `tool-risk-inference.ts` so the catalog can reuse it. Design notes where the spec left room: - OAuth for `plugin`-transport methods is not supported in this PR (`none` and `api_key` only); OAuth plugin connectors can use `mcp_remote` today. Noted as follow-up. - Board "Test" calls on a plugin connection pass an empty `agentId`/`runId`, because there is no agent run. - Companies created after the upgrade get no automatic legacy connection; they follow the normal activation rules. ## Verification - `server`: `npx vitest run src/__tests__/plugin-connectors-plugin-transport.test.ts` (new): - rules 1-3: a ready plugin and configured accounts give no tools; an install for agent A gives only A the tools; agent B is denied on invocation; - the worker receives `runContext.connection` with the right id, method, grant, settings and the call's credential; spoofed arguments do not change it; each account calls with its own key; results do not contain the key; - invalid settings are rejected (422); a stopped worker is `503 plugin_connector_unavailable` (retryable); a disabled plugin hides the tools; - dynamic tools are listed through the worker and a tool it stops offering is retired; - rule 5: a new installation of a legacy-tools plugin gives no tools; an installation recorded by the migration keeps the same tool names for every agent, through one company-wide connection (two concurrent carry-overs make one; an interrupted draft is finished; a retry keeps an operator's restriction), and is not also exposed as connection tools; Ask first and Off on the implicit connector restrict the legacy tools; - the token broker refuses to export a plugin connection's credential. - Existing gateway plugin-tool tests (`tool-gateway`, `tool-gateway-service`, `prompt-injection-gateway`) now set up the legacy grant an existing installation has, and pass unchanged otherwise. - Regression: `plugin-connectors-circleback-parity`, `tool-gateway`, `tool-gateway-service`, `prompt-injection-gateway`, `tool-access-service` (846 passed), plus `connector-tool-policy`, `plugin-lifecycle-restart`, `remote-mcp-connectors`, `ai-connection-router` in an earlier run. - UI: `AppsConnect.test.tsx` covers sending plugin settings from the settings schema. - SDK: `tests/worker-rpc-host.test.ts` (start refusal without handlers, connector routing, tool listing). Scaffold: `entrypoints.test.ts`. - `packages/db`: `pnpm typecheck` including `check:migrations`; server layered typecheck (sources and tests); `tsc --noEmit` for shared, SDK, scaffold and UI. ## Risks - Behavior change for new installations: legacy plugin tools no longer reach agents until an operator connects the plugin's connector. Installations that exist at upgrade time keep their tools through the migration rows. - The migration widens a check constraint (`NOT VALID`) and copies plugin × company rows into a new table. Both are fast; the previous release never writes `plugin`. - Calls depend on the plugin worker; when it is down the agent gets a retryable error. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file editing, test execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have 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> |
||
|
|
904c01d1a3 |
feat(mcp): graduate Assistant connections (MCP) out of experimental (#22015)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Assistant connections (MCP) let an outside assistant, or another
Paperclip instance, sign in as a person and use the `/mcp/paperclip`
endpoint
> - The feature was behind the experimental `enablePublicMcp` setting.
The setting was off by default and in practice off on Cloud stacks
> - Instance-to-instance work (one person's agent files a task on a
colleague's instance) fails when the receiving instance has the setting
off
> - This pull request moves the feature out of Experimental. It is now
always on, and a stored or Cloud-managed "off" value is ignored
> - The benefit is that every authenticated instance with a public URL,
including Cloud workspaces, accepts assistant connections with no setup
step
## Linked Issues or Issue Description
**Subsystem affected**
Public MCP (`server/src/services/public-mcp/`), instance settings,
Connectors → Assistant Connection (MCP) setup page, Experimental
settings page.
**Problem or motivation**
A remote MCP connector on one instance cannot use another instance's
`/mcp/paperclip` unless an admin on the other instance finds and turns
on an experimental toggle. On Cloud, the toggle is off and is managed by
the fleet. Instance-to-instance delegation therefore does not work by
default.
**Proposed solution**
Remove the gate. Keep `enablePublicMcp` only as a compatibility key, the
same way `enableApps` was graduated: old stored rows, PATCH bodies and
Cloud managed configs still parse, but the effective value is always
`true`.
**Alternatives considered**
An instance-admin kill switch that defaults ON. I did not keep one. Each
person already controls access: a connection exists only after that
person approves OAuth consent for one company, and the person or an
admin can revoke it. Deployment policy (authenticated mode and a valid
public URL) still decides whether the endpoint exists. A second switch
would add a state that can silently break instance-to-instance work
again. A schema migration was also not needed: the value lives in the
`experimental` JSON column, and the stored key becomes inert.
**Roadmap alignment**
Requested by the maintainer to enable instance-to-instance
communication.
## What Changed
- `packages/shared`: `enablePublicMcp` is a deprecated compatibility
key. The schema default is `true`. The feature catalog entry is
"Assistant connections (compatibility)" with both defaults `true`.
- `server` instance settings: normalization always returns
`enablePublicMcp: true`. The Cloud managed overlay skips the key, so a
fleet value of `false` cannot disable it. Removed the key from the Cloud
staging experimental-key list. Removed the client-mirror policy step
that ran only when the toggle changed.
- `server` public MCP: personal discovery, OAuth, tools, setup and event
delivery no longer read instance settings (`isEnabled()` returns `true`
for the personal endpoint without a DB read). Dot, Grok and Muse agent
connections keep their own experimental settings.
- `server` Cloud paths: the client-mirror sync, the hosted event
authority, the ingress-handoff expiry worker and the idle sleep proof
treat the front door as enabled. The warm-standby `503
workspace_unclaimed` behavior is unchanged.
- `server` Dot/Grok gates: they no longer also require
`enablePublicMcp`. Error messages no longer tell people to enable
Assistant connections.
- `ui`: removed the Experimental toggle, the "Enable assistant
connections / Open Experimental settings" block on the Assistant
Connection page, and the "Enable Assistant connections (MCP)" hint in
Dot setup. Updated the Dot and Grok copy.
- Storybook: deleted the Experimental-setting story and removed the
"enable the experiment" step from the journey and presenter.
- Docs: `doc/public-mcp.md` ("Enable an instance", "Start from
Connections", `GET /api/mcp/setup`), `doc/openai-dot-runner.md`,
`doc/idle-grok-dispatch.md`, and the agent-access map.
- Tests: new red/green tests for "enabled with no setting stored" and "a
stored or managed off value is ignored". Removed the tests for the
"disabled" behavior, which no longer exists.
## Verification
- Red/green: with the old source and the new tests,
`instance-settings-readonly.test.ts`,
`instance-settings-service.test.ts` and `public-mcp.test.ts` fail (4
failures, and the public-MCP suite fails in `beforeAll` because
`isEnabled()` was `false` with no setting stored). With the new source
they pass.
- `server`: `public-mcp.test.ts`, instance-settings (readonly, service,
managed overlay), `managed-config`, `cloud-event-authority`,
`events-work`, `dot-runner`, `dot-oauth-onboarding` and
`agent-runtime-assignments`. 354 passed.
- Cloud client-mirror lifecycle
(`client-mirror-lifecycle.postgres.test.ts`, skipped in CI) passed
against a local Postgres 17 with
`PAPERCLIP_MCP_SLEEP_TEST_DATABASE_URL`. 6/6, plus `events-work` 28/28.
- Idle and sleep: `idle-incoming-wake` (service and route),
`idle-deadline-proof`, `idle-incoming-wake-capability`,
`idle-sleep-proof`, `client-mirror-ack`, `recovery-deadline-acceptance`
and `idle-completed-history` pass. The warm-standby test now also
asserts that discovery after the claim does no SQL read.
- `ui`: `InstanceExperimentalSettings`, `AssistantConnection`,
`NewAgentDialog`, `NewAgent` and `ExternalAgentInviteDialog.muse` pass.
267 passed.
- Typecheck: `packages/shared`, `server` and `ui` pass. `node
scripts/check-maps.mjs` passes.
- `pnpm verify`: see the CI checks on this PR.
- After the deploy: confirm
`/.well-known/oauth-protected-resource/mcp/paperclip` and `/mcp/setup`
return 200 on paperclip.staging without changing any setting.
## Risks
- Behavior change: instances that had the setting off now serve
discovery, OAuth and `/mcp/paperclip`. Security invariants are
unchanged: the endpoint is still mounted only in authenticated mode with
a valid public URL, OAuth still needs a real signed-in user's consent,
local implicit board authority cannot approve, and revocation works the
same way.
- Cloud sleep: on a managed stack, the MCP sleep proof blocks sleep
until the client mirror publishes the tenant front door to Cloud. The
client-mirror sync runs at boot and does this once. Stacks that already
had the flag on use this path today. A stack whose Cloud connector
cannot publish the mirror would stay awake. Watch fleet sleep after the
deploy.
- Personal public-MCP requests now read instance settings one time less.
- Fleet admin: the Cloud fleet catalog can still show and set
`enablePublicMcp`. The value is ignored. Removing it from the fleet
catalog is a separate change in the Cloud repo.
- No migration. The `0354` trigger still compares the stored key. That
causes at most one extra connector-runtime invalidation if an old client
writes the key.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, test execution).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have 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>
|
||
|
|
78cf5aa81a |
feat(public-mcp): let paperclip_create_task assign a person or no one (#22011)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The public MCP endpoint (`/mcp/paperclip`) lets an outside assistant, or another Paperclip instance, act in a company as a person. > - The `paperclip_create_task` tool requires `assigneeAgentId`. > - So every task that an outside caller files starts an agent run on the receiving instance and spends its budget. > - A colleague on another instance must be able to file work for a person, or for nobody, without that cost. > - This pull request makes the agent assignee optional and accepts `assigneeUserId`, the same field the REST issues API uses. > - The benefit is that instance-to-instance task filing does not spend the receiving company's budget unless the caller picks an agent. ## Linked Issues or Issue Description **Subsystem affected** Public MCP endpoint (`/mcp/paperclip`), tool `paperclip_create_task`. **Problem or motivation** `paperclip_create_task` requires `assigneeAgentId`. A caller cannot create a task for a person or an unassigned task. One Paperclip instance can connect to another through the generic remote MCP connector, and people use this to file tasks on a colleague's instance. Every such task wakes an agent on the receiving instance and can spend its budget. **Proposed solution** Make `assigneeAgentId` optional and accept `assigneeUserId`, the same field the REST issues API uses. Reject both at once. Only an agent assignee starts a run. Add a read-only `paperclip_list_people` tool so the caller can find a person's user ID. **Alternatives considered** A new MCP-only assignee field. We did not use it, because the REST API already has `assigneeUserId` and its checks. **Roadmap alignment** This supports instance-to-instance communication through the public MCP endpoint. It does not duplicate planned core work in ROADMAP.md. ## What Changed - `paperclip_create_task`: `assigneeAgentId` is optional. The tool accepts `assigneeUserId`, with the same shape as the REST issues API. - `paperclip_create_task`: a schema refinement rejects a call that has both assignees. The rejection occurs before the server writes an idempotency receipt or a task. - `paperclip_create_task`: the tool description says that an agent assignee may start work and spend budget, and that a person or no assignee does not start a run. The `scheduling` result text now matches the assignee type. - New read-only tool `paperclip_list_people`. It uses the existing `GET /companies/:companyId/user-directory` route, which only needs company access. It returns user ID, name and role. It does not return email. - The task goes through the same REST create route as before. Company scope, the `tasks:assign` decision (which also checks that a person is an active member), activity logging and the service checks all still apply. - `doc/public-mcp.md`: documents the three assignee shapes and the new tool. - `tests/runner-e2e/public-mcp-grading.ts`: adds `paperclip_list_people` to the read-only tool list. - The stdio server (`packages/mcp-server`) already uses `createIssueInputSchema`, which accepts both fields. It does not change. ## Verification - New test in `server/src/__tests__/public-mcp.test.ts`. It uses the real issue and access routes. It proves: - a task for a person and an unassigned task are created as `todo`, and their `requestId` replays return the same result; - neither shape wakes an agent, and the company has no heartbeat runs; - a task for an agent still wakes that agent one time; - both assignees at once are rejected with a clear message, and no receipt is written; - a member of another company is rejected (HTTP 403 from the REST assignment check), with a result identical to a user ID that does not exist; - `paperclip_list_people` returns members without email and without other companies' users. - Red first: the test failed with "Unknown Paperclip operation" before the change. Green after the change. - `cd server && npx vitest run src/__tests__/public-mcp.test.ts`: 85 passed (also after the rebase on `origin/master`). - `npx vitest run --config tests/runner-e2e/vitest.config.ts tests/runner-e2e/public-mcp-grading.test.ts tests/runner-e2e/public-mcp-expanded-flow.test.ts tests/runner-e2e/public-mcp-invitation-grading.test.ts`: 81 passed. - `cd server && npx tsc --noEmit -p .`: passed. - `pnpm verify` exits 2 because a doc changed (a global CI input). CI supplies the broad coverage. ## Risks - Low risk. The change only adds optional input. Existing calls with `assigneeAgentId` behave the same. - An unassigned task is created as `todo`, the same status as before. No code path wakes an agent for a task without an agent assignee. - `paperclip_list_people` shows member names and roles to any connection with read scope. The same data is already available to any company member in the UI assignee picker through the same route. ## 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> |
||
|
|
b1efe32c60 |
feat(connections): name and guide connections to another Paperclip instance (#22018)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Each Paperclip instance serves an assistant connection (MCP) at `/mcp/paperclip`, and any instance can connect a remote MCP server by its address > - So one instance's agents can file and follow tasks on another instance, for example a colleague's > - But the other instance's tools look like the agent's own Paperclip tools: same product, similar names, and the connection prefix was a generic internal link key > - An agent can then file local work on someone else's instance, or the reverse > - This pull request recognizes a Paperclip address, names the connection and tool prefix after that instance, adds agent instructions, and refuses a connection to the same instance > - The benefit is that agents can tell their own Paperclip from a connected one ## Linked Issues or Issue Description **Subsystem affected** Connections: "Connect your own MCP server" (generic remote MCP) and the tool gateway names that agents see. **Problem or motivation** When instance A connects instance B through `/mcp/paperclip`, A's agents get B's `paperclip_create_task` and other tools. The tool prefix came from an internal key (`app-gallery🔗<uuid>`), so native runners saw `app_mcp_app_gallery_link_paperclip_create_task_…`. Nothing told the agent that the tools act on a different instance. An agent could send internal work to another organization by mistake. **Proposed solution** Recognize an address whose path is `/mcp/paperclip`. Use only the typed address, never data from the remote server. Name the connection after the host (`acme Paperclip`). Use that name as the tool prefix for these connections only. Add default agent instructions. Refuse the instance's own address with `paperclip_self_connection` (422). **Alternatives considered** Read the company name from the remote `paperclip_connection` tool. This needs an extra authenticated call during setup, and it puts remote-controlled text in names and instructions. The host is enough to identify the stack. Require approval for each write. We rejected this: actions start on, the same as other connections. **Roadmap alignment** Supports instance-to-instance work through existing MCP connections. It adds no new transport. ## What Changed - `packages/shared/src/paperclip-peer.ts`: detect a Paperclip MCP address, derive a label and name, compare with own origins (loopback hosts on the same port are equal), and build default agent instructions. - `server/src/services/tool-access.ts`: default name and default agent instructions for a new Paperclip connection. Instructions that the person supplies are kept. - `server/src/routes/tool-access.ts`: refuse the instance's own address before any network request. - `server/src/services/tool-gateway.ts`: use the prefix recorded on a Paperclip connection (`paperclipPeerToolNamespace`, derived from its address at creation). Renames never change it. Other connections, and Paperclip connections made before this change, keep their current tool names. - `ui/src/pages/apps/generic-mcp-connect.ts`: same default name in the setup flow. - `doc/connections/GENERIC-REMOTE-MCP.md`: new section "Connecting another Paperclip instance". ## Verification - `packages/shared`: `npx vitest run src/paperclip-peer.test.ts`, 20 passed. - `server`: `npx vitest run src/__tests__/generic-mcp-connection.test.ts`, 98 passed. The naming, instructions, self-connection and tool-prefix tests fail on the base revision and pass with this change (red/green). - `ui`: `npx vitest run src/pages/apps/generic-mcp-connect.test.ts`, 29 passed. - `tsc --noEmit` passes for `packages/shared` and `server`. - Live check with two local instances. Instance B was in authenticated mode on port 3201 with assistant connections on. Instance A was on port 3202. - A connected to `http://localhost:3201/mcp/paperclip`. The name was `localhost-3201 Paperclip`. A registered with B by dynamic client registration and asked for read, write, configure and offline access. - B's consent page showed "Connect Paperclip localhost-3202 to Paperclip". After approval, A had all 37 tools active, writes included. - From A, `paperclip_connection` returned B's company. `paperclip_create_task` created `ACM-1` on B. - An agent session on A listed `mcp.localhost-3201-paperclip-…:paperclip-create-task` (runner name `app_mcp_localhost_3201_p_paperclip_create_task_…`). Before the gateway change, the name was `app_mcp_app_gallery_link_paperclip_connection_…`. The run received the connection instructions. - Connecting A to `http://localhost:3202/mcp/paperclip` returned 422 `paperclip_self_connection`. ## Risks - Low risk. Only connections whose address path is exactly `/mcp/paperclip` change. Other connections keep their names, instructions and tool names. - A Paperclip connection created before this change keeps its original tool names, because only connections that record `paperclipPeerToolNamespace` at creation get the new prefix. Saved exact tool-name rules and pending approvals for those connections keep matching. They also get no default instructions; people can add them. - Native runners keep only 20 characters of the namespace (`mcp_` uses 4), so long host labels are cut. The tool part stays complete. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, browser pane). ## 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> |
||
|
|
7f9867895c |
fix(ui): keep automated work out of personal recents (#22024)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The sidebar helps each person return to their own work. > - A task visit previously added any readable task to personal recents. > - Automated updates also moved old tasks above newer personal work. > - The Mine inbox already defines personal participation. > - This pull request applies that rule to recent task candidates and preserves their order during background updates. > - Users can see current task status without a stream of unrelated automated work. ## Linked Issues or Issue Description **What happened?** Routine tasks and imported GitHub review tasks appeared in personal recents after a read. Later agent updates moved these tasks up the list. A connected account or stored creator ID could make these tasks look like personal work. **Expected behavior** A task must pass the viewer's existing Mine participation rule before it appears in personal recents. Routine ownership, connected-account provenance and reads alone do not qualify. A viewer can qualify through manual creation, assignment, a direct comment, an allowed user action or a live request addressed to them. Inbox archive state does not remove personal history. Passive reads and machine updates must not advance its order. **Steps to reproduce** 1. Open an automated routine task or imported review task without participating in it. 2. Check the sidebar recents. 3. Let an agent update an older task while newer personal work is in the list. 4. Before this fix, the automated task appears and background updates can move older tasks up. ## What Changed - Add a viewer participation field to bounded navigation summaries. Reuse the canonical Mine query and existing access checks. The field is a read projection; no database migration is needed. - Show only confirmed personal tasks. Remove old nonparticipants after a successful read. Do not trust participation from local storage or full task caches. - Keep status and title snapshots current without changing personal order. Explicit local edits and comments can advance recency. - Migrate browser history once to a new storage version. Older tabs cannot restore machine-driven ordering. - Keep confirmed rows visible if a new batch request fails. Keep these facts within the current account and company. Hidden candidates do not bypass the one-second reorder delay. - Record sidebar renames as local activity. Place a first passive visit below existing history. - Use the saved comment time for comments sent with reassignment or custom run settings. Pending sends do not advance recency. - Keep readable subtasks as context beneath qualifying parents. Keep inbox archive independent of recents. - Update the design rules, UI behavior notes, regression tests and Runner source contract pin. ## Verification - Current head: `92ece0e61859a6c54b714b3611f062ff9b5633bb`. The PR merges cleanly with current master. - Latest red/green: both configured-comment cases failed before the fix and now pass. Reassignment and custom run settings advance recency only after the comment saves, using its saved time. - Latest local checks: 339 tests passed across IssueDetail and recent storage, hooks and sidebar. UI typecheck and diff checks passed. - Earlier local coverage: 592 targeted API/UI tests passed. After the master conflict resolution, all 29 overlapping Gmail tests and the 548-input source registry check passed. - Both Greptile and Paperclip Review report 5/5 on the current head. All four review threads are resolved. - Current-head [CI attempt 2](https://github.com/paperclipai/paperclip/actions/runs/44132164473) passed, including the final verify gate, build, typecheck, browser shards, serialized tests, Runner checks and all general-test shards. The workspace-a (1/2) retry passed after the first attempt hit an asynchronous jsdom/Radix event error in NewAgentDialog. - `pnpm verify` requires broader CI because DESIGN.md changed. No full local suite or deployed-browser acceptance was claimed. This change is not deployed. ## Risks - Unknown eligibility stays hidden until the summary succeeds. Failed requests preserve saved candidates and previously confirmed state within the current account and company, including after batch changes. - This intentionally removes automated tasks from old personal history when the viewer has no qualifying participation. - Readable subtasks under a personal parent remain context. They do not become independent recent entries from machine activity. - No task ownership, routine definition, inbox membership or permission rule changes. ## Model Used OpenAI GPT-6, running as Codex, with reasoning, repository tools and focused test execution. No additional model workers were used. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
8172d27089 |
feat(cloud): browser product analytics through a same-origin PostHog proxy (#22012)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip Cloud runs the same app for hosted customers, and the same UI ships in the npm package. > - The PostHog project for Cloud gets only server events today. It has no page views, sessions, replays or people. > - So the Product and Web analytics pages are empty, and we cannot see how Cloud users move through the board. > - This pull request adds browser analytics for Cloud only. It is off until an operator sets two switches on a Cloud stack. > - Self-hosted installs do not change: they never download posthog-js and never serve the PostHog proxy. > - The benefit is real page views, sessions, heatmaps, Web Vitals and masked session replays for Cloud, linked to the user and the workspace. ## Linked Issues or Issue Description **Subsystem affected** Board UI (analytics bootstrap and privacy markers), server session payload and a new same-origin proxy route, shared validators. **Problem or motivation** Cloud sends only server events to PostHog. There is no browser SDK, so PostHog has no page views, sessions, replays or identified people for Cloud. We cannot see where Cloud users get stuck. **Proposed solution** The signed-in session gives the UI a PostHog config only on a Cloud-managed stack with `PAPERCLIP_POSTHOG_PROJECT_TOKEN` and `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. The UI loads posthog-js after the page settles. Events go through a strict same-origin proxy at `/_ph`, so ad blockers do not drop them. Replay masks all text and all inputs by default. **Alternatives considered** Bake a key into the UI build: refused, because the same build ships to self-hosted users. A generic reverse proxy: refused, because it would forward any path. Mask only content areas: refused, because a missed surface would leak; masking is deny by default. **Additional context** This is the browser part of the Cloud direct PostHog plan. The server direct sender is already on master (#22006). Fleet configuration is a separate change. PostHog person deletion on account deletion is a follow-up. ## What Changed - Uses the shared Cloud PostHog config (`resolveCloudPostHogConfig` in `server/src/services/cloud-posthog-config.ts`, already on master from the server direct-sending change). This PR does not change it. - `server/src/services/cloud-posthog-browser.ts`: `resolveBrowserAnalyticsConfig` returns `{ token, apiHost: "/_ph", uiHost, environment, stackId, replayEnabled }` only when `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. `environment` is always set: the explicit variable, else `staging` for a `*.staging.paperclip.app` host, else `production`. - `GET /api/auth/get-session` carries the new optional `browserAnalytics` field (the existing signed-in bootstrap request, so no new request on the cold path). `packages/shared` has `browserAnalyticsConfigSchema` and the session schema field. - `server/src/routes/posthog-proxy.ts`: a strict proxy, mounted before the body parsers and only when browser analytics is on. It forwards only these requests and answers 404 to all others without contacting PostHog: - `POST /e/`, `/i/v0/e/`, `/batch/`, `/s/`, `/flags/`, `/decide/` to the ingest host. - `GET /array/<token>/config(.js)` and `GET /static/[<version>/]<name>.js` to the assets host (derived from the ingest host). - `stream.pipeline` joins the streams, so an error on either side (PostHog closes the connection partway through a response, or the browser goes away) closes both and never goes unhandled. It builds a new header set from an allowlist plus `X-Forwarded-For`. It never forwards the inbound Host, Cookie or Authorization headers. It drops `Set-Cookie` from responses. Bodies stream; nothing is buffered. It refuses bodies over 64 MiB (413, also for chunked bodies that grow past the limit) and limits requests in flight to 16 per client address and 256 in total (429). - `ui/src/lib/analytics/product-analytics.ts` (the only module that talks to posthog-js) and `ui/src/components/ProductAnalyticsGate.tsx`: - posthog-js loads after the page settles (or at a 15 s deadline), only when the session has a config. It loads as PostHog's browser script `/_ph/static/array.js` through the proxy, the same way posthog-js itself loads its extensions (recorder, web vitals). It is not an npm dependency and is in no bundle chunk. - Init: page views on history change, page leave, autocapture, Web Vitals, heatmaps, `person_profiles: "identified_only"`, `tracing_headers` for our own host only, replay only when `replayEnabled`. Surveys, product tours, web experiments and conversations are off. - Super properties on every event: `deployment_source: "cloud"` and `environment`. - After sign-in: `identify(session.userId, { email, name })` (person properties only). `session.userId` is the authenticated actor's user id verbatim (for example `paperclip-id:...`): `GET /api/auth/get-session` copies `req.actor.userId` into it, and server events use that same actor id as `distinct_id`, so browser and server events land on one person. Tests: `auth-routes.test.ts` (the session returns the actor id verbatim) and `ProductAnalyticsGate.test.tsx` (identify uses it) and `group("workspace", stackId)`. On sign-out: `reset()`, then the super properties again. `useSignOut` calls it before it leaves the page, because Cloud sign-out navigates away while the session query is still populated. - Privacy (`ui/src/lib/analytics/privacy.ts`), deny by default: - Replay masks every text node (`maskTextSelector: "*"` with `maskTextFn`) and every input value (`maskAllInputs`). - Only elements with `ANALYTICS_UNMASK_PROPS` show their text: sidebar items whose label is a fixed string (`analyticsChrome`, added at the 99 call sites with literal labels), and a shared `Button`, `Label`, `TabsTrigger` or `EmptyState` only when its caller passes `analyticsChrome`. None of them opts in by default, because they also render customer text (agent names, document titles). Sidebar items with dynamic labels (recent tasks, agents, projects) stay masked. - Replay masks attribute values too (`maskAttributeFn`, deny by default). Only layout attributes (`class`, `style`, `role`, `data-state`, SVG geometry), rrweb metadata and stylesheet links keep their values. `title`, `aria-label`, `alt`, `placeholder`, `src`, `href`, `data-*` and element references (`id`, `for`, `aria-labelledby`, `aria-describedby`, `aria-controls`, which often embed names or slugs) are always masked, even on unmasked chrome. So the organization switcher's `aria-label`, task titles in `title` attributes, image sources and download links with file paths never reach a replay. - `before_send` (`scrubCapturedEvent`) drops the `title` property from every event, because posthog-js copies `document.title` (task and organization names) into page views. Every URL string in every event, including replay meta events, keeps only its origin and path: query and hash values never leave (they can hold tokens, `code`/`state`, file paths or search text), and the token segment of `/board-claim/<token>` and `/invite/<token>` is redacted. It recurses only into plain objects and arrays, so the `Date` timestamp stays intact. - `ANALYTICS_MASK_CLASS` keeps customer content masked even inside unmasked chrome: `MarkdownBody` (task and issue bodies, comments, chat messages, documents and artifact markdown), `MarkdownEditor`, the task chat thread, the issue chat thread, the comment timeline, the file viewer (source, markdown and CSV views) and the organization name in the organization switcher. Text in any `contenteditable` editor is always masked. - `ANALYTICS_NO_CAPTURE_CLASS` (`ph-no-capture`, a blank box in replay) on every password-type `Input` (about 40 secret, token and API key fields), environment variable values and new secret values. - Autocapture never records element text or attribute values (`mask_all_text`, `mask_all_element_attributes`). - Connected-account content (Google user data and Slack data: email bodies, calendar events, Slack messages in tasks, chat, tool results, previews) never appears unmasked in a replay. Replay masks all text by default; nothing that renders connected-account content is in the unmask allowlist; autocapture records no element text anywhere (`mask_all_text`). `ui/src/lib/analytics/unmask-allowlist.test.ts` pins the allowlist: only 7 files may spread the unmask attribute, sidebar opt-ins need a literal label, and any `analyticsChrome` opt-in on `Button`/`Label`/`TabsTrigger`/`EmptyState` fails until it is added to a reviewed list (empty today). The same test renders Gmail, Calendar and Slack-style tool results next to unmasked navigation and checks they are masked. - Guard test: UI code must never call `capture()` with a `PAPERCLIP_EVENTS` name, so each event has one sender. - Docs: `doc/cloud-browser-analytics.md` (switches, per-stack opt-out, proxy allowlist, identity, privacy) and a link from `doc/observability.md`. - No new npm dependency and no lockfile change: posthog-js comes from PostHog through the proxy at run time. (An earlier revision added `posthog-js` to `ui/package.json`; the Runner support suite requires every `ui` dependency in the reviewed lockfile, which a pull request cannot update, so the script approach replaced it.) ## Verification - `pnpm verify`: see the result below. - Focused tests: - `server/src/__tests__/cloud-posthog-browser.test.ts`: exposure matrix (self-hosted with every switch set, Cloud without token, without stack ID, without the browser switch, switch not `1`, enabled, replay off), environment fallback, proxy mount only when enabled, allowed routes, 404 for disallowed methods and paths (including `//host` and `..` paths) with no upstream contact, Host/Cookie/Authorization stripped, `Set-Cookie` dropped, 502 when PostHog is down, and no unhandled error when PostHog closes a response partway (red on the old `pipe()` code, green now). - `server/src/__tests__/auth-routes.test.ts`: the session carries `browserAnalytics` only on Cloud with the token and the switch. - `ui/src/lib/analytics/*.test.ts`, `ui/src/components/ProductAnalyticsGate.test.tsx`: no import of posthog-js without a config or when signed out; load after the page settles, once; identify, group, reset with a mocked posthog; email and name never become event properties; deny-by-default replay masking; guard test. - Real run (local, headless Chromium, production UI build, never the real PostHog project): - Self-hosted server, no env: 0 requests for PostHog's script and 0 requests to `/_ph` in 9 cold loads and in a 40 s session with navigation. `browserAnalytics` is `null`. `/_ph/e/` falls through to the UI. - Cloud config: a full Cloud boot needs S3, a managed database and the control plane. So a small local stand-in served the same production UI build, mounted the real proxy from `server/src/routes/posthog-proxy.ts`, added the real `resolveBrowserAnalyticsConfig()` output to the session, and forwarded other API calls to the local server. `PAPERCLIP_POSTHOG_HOST` pointed at a local capture server. - Captured through `/_ph` only (0 requests to any posthog.com host): `$pageview` on each client navigation (5), `$identify` with `$set: { email, name }`, `$groupidentify`, `$groups: { workspace: <stack id> }` on events, `environment` and `deployment_source` on every event, `$web_vitals`, `$autocapture` with no `$el_text`, `$$heatmap`, and 10 `$snapshot` replay events. A search of every decoded `/e/` and `/s/` payload (events, replay text and replay attributes) found the email only in `$identify`'s `$set`, and found none of: the task body, the typed comment, the task title, the organization name. No Cookie header reached the capture server. 96 of 113 API requests carried `X-POSTHOG-SESSION-ID` (the others ran before posthog-js loaded). - Client-side visits to `/invite/INVITESECRET123` and `/cli-auth/abc?token=CLISECRET456` reached PostHog as `/invite/REDACTED` and `/cli-auth/abc` (no query); neither secret was in any payload. - Disallowed proxy requests (`PUT /_ph/e/`, `GET /_ph/api/projects/`, `POST /_ph/static/x.js`) answered 404. - Sample replay payload (decoded rrweb text nodes from a captured `/s/` request). The task body, the typed comment, the task title, the organization name and the email were not in any replay payload: ```json {"text_nodes": [ {"parentTag": "title", "textContent": "****** ** * *********"}, {"parentTag": "a", "textContent": "**** ** **** *******"}, {"parentTag": "span", "textContent": "****** **"}, {"parentTag": "span", "textContent": "*** ****"}, {"parentTag": "span", "textContent": "Tasks"}, {"parentTag": "span", "textContent": "Inbox"}, {"parentTag": "h2", "textContent": "******* *******"}, {"parentTag": "p", "textContent": "****** *** * ******* ** ******"} ]} ``` - Cold load, 9 fresh-profile loads each, median, same stand-in with analytics off and on: | | DOMContentLoaded | Board content visible | | --- | --- | --- | | Analytics off | 128 ms | 336 ms | | Analytics on | 126 ms | 334 ms | Final head. The difference is inside run-to-run noise (earlier pairs: 332/335 ms and 335/348 ms). PostHog's script loads only after the content is visible. ## Risks - Inert by default. Without a Cloud-managed stack, a project token, a stack ID and `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`, the session field is `null`, the proxy is not mounted and no analytics code runs. The OSS package does not change behavior. - Per-stack opt-out: `PAPERCLIP_POSTHOG_REPLAY_ENABLED=0` turns replay off; unsetting `PAPERCLIP_POSTHOG_BROWSER_ENABLED` turns all browser analytics off. Both apply on the next restart. - Replay text shown in the clear comes only from fixed sidebar labels and from shared components whose caller opts in. Today no `Button`, `Label`, `TabsTrigger` or `EmptyState` call site opts in, so replays show layout, clicks and navigation with most copy masked. Opting in fixed-label call sites is a follow-up. Review sample replays on staging before production. - Image `src` values are masked, so images record as empty boxes. Sandboxed iframes (HTML artifacts, MCP apps) also record as empty boxes. Replays therefore show layout and product copy, not customer media. - PostHog's script is not version-pinned: the assets host serves its current browser build, as for any PostHog snippet install, and posthog-js already loads its extensions from that host at run time. It runs only on Cloud stacks with the browser switch on. - The proxy needs no sign-in, like PostHog's documented proxies: posthog-js sends some events while a page unloads, and the proxy can only reach the two PostHog hosts, on the listed paths, with the public project token. Body size and in-flight limits bound the load one client can add. - posthog-js rejects bots (including headless browsers) on its own, which is the wanted production behavior. - `SidebarNavItem.production.tsx`, `Sidebar*.tsx` and the shared `ui/*` components changed by one attribute each; no visual change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, headless browser runs). ## 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> |
||
|
|
7f1f0eef67 |
fix(google-workspace): request free/busy with read & write Calendar, and update connector docs (#22026)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The built-in Google Workspace connector gives agents Gmail, Drive and Calendar through one connection, behind an experimental setting > - The user picks each service as read only or read & write. Paperclip then requests only scopes from a fixed list of 14 > - Read & write Calendar requested `calendar.calendarlist.readonly` and `calendar.events`. Our code assumed `calendar.events` also covers free/busy lookups > - Google's REST `freeBusy.query` does not accept `calendar.events`. So the REST `suggest_time` tool cannot read free/busy on a read & write grant, and falls back to reading each attendee's events > - This pull request adds `calendar.events.freebusy` (already one of the 14) to the read & write Calendar selection of the unified connection, and stops treating `calendar.events` as implying free/busy > - The benefit is that `suggest_time` on REST can see coworkers who share only free/busy, and the stored grant no longer claims a permission that Google did not give. It also brings three Google connector planning docs up to date ## Linked Issues or Issue Description Refs #22016, #22017, #22010, #22014 **What happened?** The read & write Calendar selection of the unified Google Workspace connection requests `calendar.calendarlist.readonly` and `calendar.events`. `toolScopes.calendar.suggest_time` lists `calendar.events` as sufficient, and `googleWorkspaceEffectiveScopes` treats `calendar.events` as implying `calendar.events.freebusy`. Google's two references differ: - REST [`freeBusy.query`](https://developers.google.com/workspace/calendar/api/v3/reference/freebusy/query), checked 2026-11-17: "This request allows authorization with at least one of the following scopes:" `calendar.readonly`, `calendar`, `calendar.events.freebusy`, `calendar.freebusy`. `calendar.events` is not in the list. - Google's hosted Calendar MCP [`suggest_time`](https://developers.google.com/workspace/calendar/api/v3/reference/mcp/tools_list/suggest_time), checked 2026-11-17: "Requires one of the following OAuth scopes:" `calendar`, `calendar.readonly`, `calendar.events`, `calendar.events.freebusy`, `calendar.freebusy`. Here `calendar.events` is accepted. So `calendar.events` is enough for Google's MCP tool but not for the REST endpoint that our REST `suggest_time` uses. **Expected behavior** A user who picks read & write Calendar gets a grant that allows `freeBusy.query`. A grant that does not have the free/busy permission is not recorded as having it. Grants made before this change keep working as read & write. **Steps to reproduce** 1. Call `googleWorkspaceSelectedScopes({ calendar: "write" })`. It returns two scopes, without `calendar.events.freebusy`. 2. Call `googleWorkspaceEffectiveScopes(readOnlyCalendarScopes, [calendar.events])`. It returns `calendar.events.freebusy`, which Google did not grant. 3. With Calendar on the REST transport, `suggest_time` on a read & write grant gets an insufficient-scope answer from `freeBusy.query` and uses the events fallback. ## What Changed - `packages/shared/src/google-workspace-connectors.ts`: - `googleWorkspaceSelectedScopes` adds selection-level scopes from a new `SELECTION_ADDED_SCOPES` map. Read & write Calendar adds `calendar.events.freebusy`. The per-service `calendar.write` profile (`SERVICE_PROFILES["calendar.write"]`) is unchanged, because the Cloud broker matches legacy profiles by exact scope set. - `googleWorkspaceEffectiveScopes` no longer expands `calendar.events` to `calendar.events.freebusy`. `calendar.events` still implies `calendar.events.readonly`. `calendar.readonly` still implies free/busy, which Google's reference allows. - `googleWorkspaceSelectionForScopes` is unchanged. It needs the legacy write profile's scopes, so a two-scope grant and a three-scope grant both read back as read & write. - `toolScopes.calendar.suggest_time` is unchanged. It still accepts `calendar.events`: Google's MCP tool accepts it, and on REST the tool has an events-based fallback that names attendees it cannot read. - Counts: default all-read-and-write selection is now 10 scopes (was 9); all read-only stays 8; the union of all 27 selections stays exactly the 14. - Tests (written first and seen failing on `master`): - `packages/shared/src/google-workspace-connectors.test.ts`: scopes for read and for read & write Calendar; the legacy `calendar.write` profile keeps two scopes; default count 10 and read-only count 8; old two-scope grant, new three-scope grant and partial consent (user declines free/busy) all round-trip as read & write and keep `list_calendars`, `list_events`, `suggest_time`, `create_event` and `delete_event`; no recorded free/busy that Google did not grant. The existing exhaustive test still checks that no selection requests a scope outside the 14. - `server/src/__tests__/tool-access-service.test.ts`: customer-owned Workspace OAuth with read & write Calendar asks Google for all three scopes. With and without free/busy in Google's answer, the connection is active, the Calendar tools are listed, the grant stores exactly what Google granted, and it reads back as read & write. - Stale tests on `master` fixed: `#22014` made Gmail 9 of 9 in the REST tool set while `#22016` still expected 3 Gmail REST tools. `google-workspace-rest-dispatch.test.ts` and `google-workspace-rest-transport.test.ts` now derive the Gmail list from the allowlist and use Chat as the service with no REST tools. - Docs: `doc/connections/GOOGLE-WORKSPACE.md`, `doc/connections/GOOGLE-WORKSPACE-SERVICE-CONSENT.md` and `doc/connections/tool-method-permission-reviews.json` say ten scopes and explain the Calendar change. - Docs: `doc/memory/google-connector-memory.md` (shipped PRs #22010, #22014, #22016, #22017; three Nov 17 decisions; "Where Google content is kept" replaced with #22010's inventory, what deletion keeps and its limits; Scopes section; REST tools status table; still-open list), `doc/plans/2026-11-17-google-workspace-production-checklist.md` (help page and retention audit ticked with #22010; REST tool progress), `doc/plans/2026-11-17-google-workspace-code-fixes.md` (fix 6 done with limits; section 9 status table; fix 10 note). - `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed pins for the changed shared files. Not changed: - `server/src/google-workspace-rest-tools/**`. Another change owns that folder. Its README open question about this scope is now resolved and can be removed there. - The picker disclosure (`googleWorkspaceDisclosure.ts`). Read & write Calendar already says agents "can see your calendars, events and free/busy times". With this change that line is accurate on REST too. Behavior for existing grants: a saved read & write grant without free/busy still reads back as read & write, keeps every Calendar tool, and refreshes without change. Nothing prompts the user to reconnect. A user who chooses read & write Calendar in the picker is asked for the new scope. An account-page reconnect without a new choice still restores the exact saved request, as before. Cloud broker and Google Console: no change needed. `calendar.events.freebusy` is one of the 14 in `workspace.all`, the broker accepts any nonempty subset of `workspace.all` (`doc/connections/GOOGLE-WORKSPACE-SERVICE-CONSENT.md`), and the legacy `calendar.write` profile's exact scope set did not change. ## Verification - `cd packages/shared && npx vitest run src/google-workspace-connectors.test.ts src/app-definitions.test.ts`: 55 passed. On `master` the new shared tests fail (3 failed). - `cd server && npx vitest run src/__tests__/tool-access-service.test.ts -t "free/busy"`: 2 passed. With `master`'s `google-workspace-connectors.ts`: 2 failed. - `cd server && npx vitest run src/__tests__/google-workspace-rest-transport.test.ts src/services/google-workspace-rest-dispatch.test.ts`: 29 passed (4 failed on `master` before this change). - `cd ui && npx vitest run src/features/connections/GoogleWorkspaceServices.test.tsx src/pages/apps/AppDetail.test.tsx`: 115 passed. - `cd packages/shared && npx tsc --noEmit -p .`: clean. - `pnpm verify` exits 2 (a global CI input changed), so required CI supplies the broad coverage. - Docs facts checked against `gh pr view` for #22010, #22014, #22016, #22017, the code, and paperclipai/paperclip-website PR 197 (still a draft; does not mention OpenRouter). ## Risks - Low risk. The submitted set of 14 does not change, and the broker contract does not change. - New read & write Calendar grants record `calendar.events.freebusy` next to `calendar.events`. Code that reads stored scopes sees one more scope. All consumers (callback, refresh, discovery, picker pre-fill) are covered by the tests above. - A read-only Calendar request on an account that Google reports only `calendar.events` for no longer records free/busy. That matches what Google granted; `suggest_time` is then not offered on that grant. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use, web fetch 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> |
||
|
|
01451fae5b |
Let plugins add connector types to the Connectors catalog (#22004)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents use external services through connectors: a catalog of connector types, connections (accounts) per type, and per-agent installs, policies and audit in the tool gateway > - Today only core can add a connector type. Every type is a JSON definition compiled into `@paperclipai/shared` > - Plugins can add agent tools, but those tools skip connections, grants, per-agent installs and the Connectors page > - This pull request lets a plugin add connector types with the same definition schema, and makes them behave exactly like built-in connectors > - The benefit is that a connector can ship as a plugin, and an operator controls it with the same Connectors page and the same access rules ## Linked Issues or Issue Description **Subsystem affected** Plugins, Connectors (tool access), tool gateway **Problem or motivation** A plugin cannot add a connector type to the Connectors catalog. Plugin tools (`tools` in the manifest) do not use connections, credentials per account, agent installs, policies or the Connectors page. **Proposed solution** Add a manifest field `apps` (gated by a new `connectors.provide` capability). Each entry uses the built-in app-definition schema. The host namespaces the slug by plugin key and runs setup, OAuth, discovery, grants, policies and audit through the existing code. This is the first of two pull requests. The second adds a `plugin` transport so a plugin worker can serve the tools itself. **Activation rules (product requirements)** 1. Installing or enabling a plugin grants no tools. It only adds connector types to the catalog. 2. Connecting an account grants no tools. 3. An agent gets the tools only from an agent install or a company install of an active connection. Discovery and invocation both enforce this. 4. A disabled or uninstalled plugin (or an upgrade that removes the app) hides its connector types and connections from the Connectors APIs and they reach no agent. Saved setup survives disable and comes back on re-enable. Uninstall keeps rows archived for audit and revokes credentials. **Alternatives considered** Keep plugin tools (`tools`) as the only plugin path. Rejected: they bypass connections, per-account credentials, per-agent installs and the Connectors page. ## What Changed - `packages/shared`: new capability `connectors.provide`; manifest `apps` validated with `appDefinitionSchema`. The validator rejects apps without the capability, duplicate slugs, host-derived fields (`plugin`, `aiConnectionRouter`, `experimentalFeatureKey`, `availability`), and methods that need provider code in the host (REST adapters, chat channels, AI runtimes). - `packages/shared/src/plugin-apps.ts`: reversible namespaced slugs (`plugin-<hex plugin key>-<slug>`), the catalog entry builder, and `reviewedToolRisk`. - `packages/shared/src/app-definitions.ts`: catalog lookups (`getConnectableAppDefinition`, `getAppStoreDefinition`, ...) also resolve the current plugin apps. The set is replaced on each read of plugin state, so a built-in app is never shadowed. - App definitions can declare `reviewedTools` (reviewed read/write/destructive names and the risk for unlisted tools). Circleback's reviewed risk moves from `server/src/services/connectors/circleback/risk.ts` into `circleback.json`, with the same classification. A copy of the definition now classifies tools the same way. - `validators/json-schema.ts`: `jsonSchemaSchema` moves to its own module to break an import cycle between the plugin and app-definition validators (still re-exported from `validators/plugin.ts`). - `server/src/services/plugin-app-catalog.ts`: reads ready plugins from the `plugins` table and answers "is this connection's connector available". It does not trust in-memory lifecycle events, because several lifecycle managers and processes can share one database. - Gateway: connected-tool discovery and `resolveConnectionGrant` drop connections from an unavailable plugin connector. Built-in connections do not read the plugins table. - Connectors APIs: the gallery lists ready plugin apps (with the same Cloud connector profile filter as core); `listConnections` and `listApplications` hide unavailable plugin connections; setup entry points refresh plugin apps first. - Plugin uninstall archives the plugin's connections through the standard connection removal (grants revoked, owned credentials deleted, rows kept). - UI: the gallery response registers plugin apps for the setup screens; `/apps/connect?source=plugin-…` loads the gallery first and shows an unavailable state when the plugin is disabled. - Docs: `doc/plugins/PLUGIN_SPEC.md` section 11A and the capability list. Design choices where the spec left room (picked to match "a plugin connector behaves like a built-in connector"): - Only `ready` plugins provide connectors. `error` and `upgrade_pending` hide them, the same as the AI connection router plugins. - `rest_api` is rejected for plugin apps in this PR. Core REST connectors need reviewed adapter code in the host, so a definition alone cannot work. The `plugin` transport in the next PR covers that case. - Disabled plugin connections are hidden from list endpoints. Reading one connection by id still works, so audit links keep resolving. ## Verification - `packages/shared`: `npx vitest run src/plugin-apps.test.ts src/validators/ src/app-definitions.test.ts` (416 passed). New tests: manifest validation, slug namespacing, no shadowing of built-in apps, reviewed risk. - `server`: `npx vitest run src/__tests__/plugin-connectors-circleback-parity.test.ts` (new). A test-only plugin (`server/src/__tests__/fixtures/plugin-connectors/circleback-parity/`) ships an unmodified copy of `circleback.json`. The same journey runs against built-in Circleback and the plugin copy with a recorded DCR OAuth + MCP fixture, and must give identical catalog risk/status, suggested defaults and per-agent tool sets. It covers each rule: - Rule 1: the gallery adds only the namespaced type; no connections exist; no agent tool changes. - Rule 2: two signed-in accounts, no agent sees a tool. - Rule 3: an install for agent A gives only A the tools of that connection; agent B is denied on invocation; each account calls the provider with its own credential. - Rule 4: disable hides the type, both connections and applications, removes tools from discovery and invocation (404) and blocks new setup, while built-in Circleback is unchanged; installs and grants are byte-identical; re-enable restores tools with the same names; an upgrade that removes the app hides it; uninstall archives both connections, revokes grants and deletes owned secrets. - Red/green: removing the gateway gate or the declared review makes the test fail. - An env-gated live check (`PAPERCLIP_CIRCLEBACK_LIVE=1`) starts the real Circleback sign-in for both connectors and compares the requests. It never runs in CI. I did not run it for this PR. - Regression: `ai-connection-router`, `connector-tool-policy`, `mcp-apps`, `plugin-lifecycle-restart`, `tool-access-service`, `braintrust-connection`, `remote-mcp-connectors`, `connection-intents-service`, `tool-gateway` (796 passed). - `ui`: `app-connect-policy.test.ts`, `AppsConnect.test.tsx` (new plugin cases) pass. - `tsc --noEmit` for shared, server, ui (only pre-existing ungenerated Storybook catalog errors), plugin SDK and CLI. - `pnpm verify --explain` selects a broad plan because a doc under `doc/plugins` changed; CI supplies that coverage. ## Risks - No migration. Built-in connectors only gain one string check per discovery; the plugins table is read only when a plugin connection is present. - Circleback's reviewed risk is now data. The behavior is the same, and the existing policy tests and new tests cover it. - Connection intents (agent connection requests in chat) still search only built-in apps. Plugin connectors can be set up from the Connectors page. This is a follow-up. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file editing, test execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have 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> |
||
|
|
c652c813bc |
feat(google-workspace): per-service transport switch for REST-backed tools (off by default) (#22016)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents use Google Workspace through one built-in `google-workspace` connection and the tool gateway > - Today every Google tool call goes to Google's hosted Workspace MCP servers, which are a Developer Preview and cannot be offered to the public > - #22000 added Paperclip's own Gmail tools over Google's REST APIs in `server/src/google-workspace-rest-tools/`, but nothing calls them yet > - This pull request adds one per-service transport switch and connects the gateway to the REST tools behind it. Every service stays on Google's MCP servers, so production behavior does not change > - The benefit is that a service moves to the REST tools with a one-line, reviewed change once all its tools exist, and moves back the same way ## Linked Issues or Issue Description Refs #22000 **Subsystem affected** Tool gateway and catalog discovery for the built-in Google Workspace connection. **Problem or motivation** Google's Workspace MCP servers are a Developer Preview. Paperclip launches on its own tools over Google's REST APIs. The REST tools exist (#22000), but the gateway cannot call them, and there is no way to choose them per service. **Proposed solution** Add a per-service transport setting (`google_mcp` or `paperclip_rest`) in the shared Google Workspace module. Add one server adapter that is the only importer of the REST folder. When a service is set to `paperclip_rest`, the gateway call path and discovery use the adapter in process. All gateway controls stay the same. **Alternatives considered** A loopback or hosted MCP endpoint for the REST tools. It adds a connection, JSON-RPC framing and the protocol probe to every call, and authenticated public deployments refuse loopback addresses. An environment variable or instance setting. A plain constant keeps every flip a reviewed code change. ## What Changed - `packages/shared/src/google-workspace-connectors.ts`: adds `GOOGLE_WORKSPACE_TOOL_TRANSPORT` (every service is `google_mcp`), `transport` on the result of `googleWorkspaceToolTarget`, and `googleWorkspaceServiceToolNames`. - New `server/src/services/google-workspace-rest-dispatch.ts`: the only importer of the REST folder. It keeps only the bearer token from the gateway's credential headers, passes the gateway's egress-guarded fetch and cancellation signal, and returns either the MCP result or a token problem. `googleWorkspaceRestTransportGaps()` lists allowlisted tools that a `paperclip_rest` service does not implement. Today Calendar is eligible (9 of 9) and Gmail is not (3 of 9); nothing is flipped. - `server/src/services/tool-gateway.ts` (`executeRemoteHttpTool`): for a `paperclip_rest` tool, the gateway rechecks the current grant, calls the adapter, and returns through the same result handling as the MCP path. Google's insufficient-scope answer maps to `oauth_insufficient_scope`. A rejected token forces a refresh and returns `oauth_refreshed_retry_required` without a replay. A passed deadline returns `tool_timeout`. The audit record names the protocol `Google Workspace REST`. The grant recheck is now one shared helper for both paths. A timed-out Google Workspace write, on either transport, now returns `tool_timeout` with a warning that the change may or may not have been made; a timed-out read keeps the plain timeout message. - `server/src/services/tool-access/catalog/discovery.ts`: for a `paperclip_rest` service, discovery and health run one REST probe with the caller's token, then list the REST tools under the same names and scope filter. A 401 refreshes and probes again. A second 401 on a managed grant marks it `needs_reauthorization`. Any other probe failure makes only that service unavailable. - `server/src/google-workspace-rest-tools/`: adds `probe.ts` and its export. Each service has an ordered list of cheap reads with the scopes that allow each (Gmail: `users.getProfile`; Calendar: one calendar list entry, one primary-calendar event, or one minute of free/busy). The probe uses the first read the grant allows. A grant that allows none is listed without a probe, and an insufficient-scope answer never drops a service. It also and lets `boundary.test.ts` allow exactly the adapter as the importer. The README now describes the implemented seam, how to flip a service, and the removal procedure. - `doc/connections/GOOGLE-WORKSPACE.md`: describes the transport setting. - `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed pins for the changed shared files. ## Verification - `cd server && npx vitest run src/__tests__/google-workspace-rest-transport.test.ts`: 15 tests. They were red before the gateway and discovery changes (10 failed), and green after. With Gmail set to `paperclip_rest` through a test-only change of the map, the tests use the real managed setup, discovery, gateway, policy and screening with a fake Google fetch. They prove: discovery lists the same tool names filtered by scopes after one probe; a read runs with the caller's token and is audited; a draft waits for approval and then runs; a tool outside the grant and a narrowed grant are refused before any Google request; Google's insufficient scope maps to `oauth_insufficient_scope`; a 401 refreshes the token, is not replayed, and the retry uses the new token; an injected email is blocked; a passed deadline aborts the Google request and returns `tool_timeout`; the experimental-feature gate stops calls and discovery; a failed Gmail probe leaves Docs usable and Gmail comes back; a lasting 401 asks for reconnection. A timed-out draft carries the uncertain-write warning in the error, the invocation record and the audit entry on both transports, and an approved REST draft whose request was lost returns the warning. With the default map, a call goes to `gmailmcp.googleapis.com` and the adapter is never called. - `cd server && npx vitest run src/services/google-workspace-rest-dispatch.test.ts src/google-workspace-rest-tools`: eligibility (no partial flip), bearer-only forwarding, signal and fetch pass-through, token outcome mapping, probe, boundary. - `cd packages/shared && npx vitest run src/google-workspace-connectors.test.ts`: every service defaults to `google_mcp`. - Existing Google tests are unchanged and pass: `google-workspace-injection-screening.test.ts`, the Google cases in `tool-gateway-service.test.ts` and `tool-access-service.test.ts` (142 Workspace/Google/Gmail cases). - `npx tsc --noEmit` for `packages/shared` and `server`: clean. - `pnpm verify`: exit 2 (a doc under `doc/` is a global CI input), so required CI supplies broad coverage. - Speed, stubbed fetch, 300 calls after warm-up: the adapter adds about 15 µs per call. A full `gmail__get_message` through `executeTool` took a median of 18.2 ms on REST and 18.3 ms on MCP (p90 21.6 ms and 22.3 ms). The REST path adds no waits, no extra round trips and no dynamic imports. ## Risks - Low risk for production: every service stays on `google_mcp`, and the default-map test proves the adapter is not called. - The server now loads the REST folder at start. It uses only modules the server already loads (MCP SDK, zod). - A later flip must add a probe and the API host for each new REST service. The `Record` type of the probe table makes typecheck fail when a REST service has no probe. - On `paperclip_rest`, MCP resources, MCP Tasks and elicitation do not exist for that service. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, through Claude Code with tool use (shell, file edits, test runs). ## 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> |
||
|
|
d1b5cfe038 |
feat(connections): let users delete data read through a connection (#22010)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents call connected apps, such as Google Workspace, through
Paperclip's tool gateway
> - Paperclip saves part of each tool result, approval previews, app
views and the full run transcripts that contain tool output
> - No user action deleted this data. Removing the connection left it in
place
> - Google's restricted-scope review requires that users can delete the
data an app obtained, and that the privacy policy says how
> - This pull request adds "Delete data read through this connection"
for any connection, on the connection's page and as an option when you
remove it
> - The benefit is that the picker text ("They stay there until you
delete them") is now true, and the privacy policy can link to a help
page
## Linked Issues or Issue Description
**Subsystem affected**
Connections (tool gateway audit tables, run logs, run events) and the
Connectors UI.
**Problem or motivation**
Paperclip stores content from a connection's tool calls in several
places and gives users no way to delete it:
- `tool_invocations.arguments_summary/result_summary` and
`tool_call_events.arguments_summary/request_summary/result_summary` keep
the first ~4,000 characters of each redacted value
(`summarizeToolValue`, `tool-access-policy.ts` `redactArguments`). No
retention limit.
- `tool_action_requests` keeps `canonical_arguments_summary`,
`preview_markdown` and `signed_arguments`. The linked approval card
(`issue_thread_interactions`) keeps copies in `payload.detailsMarkdown`,
`payload.toolAction.previewMarkdown`,
`payload.toolAction.argumentsSummaryJson` and
`result.toolAction.resultSummary`.
- `tool_mcp_app_views` keeps `tool_input` and `tool_result` for MCP app
views.
- Run transcripts hold full tool output: the run log (`local_file` with
an optional S3 mirror, or `s3_segments`/`s3_archive` object journals),
`heartbeat_run_events.message/payload`, and
`heartbeat_runs.stdout_excerpt/stderr_excerpt`. Neither run-log store
had a delete path.
- Connection removal (`removal.ts`) archives the connection and revokes
credentials. It deletes no content.
**Proposed solution**
A durable, resumable, company-scoped deletion request per connection.
See "Design" below.
**Alternatives considered**
- Delete synchronously in the request. Rejected: an interrupted request
leaves partial state that needs a person to retry it.
- Delete only the run events that mention the connection. Rejected: tool
output also reaches the model's later messages, so the safe unit is the
whole run transcript.
- Delete the audit rows. Rejected: counts, outcomes and hashes feed the
activity history and usage counts.
## Design
**Rule.** The job never drops a reference to content it has not
confirmed deleted. It is marked complete, and writes the
`tool_connection.content_deleted` activity entry, only after every step
succeeded. A step that cannot confirm its work throws. The request then
stays pending, the UI says "Paperclip keeps trying until it finishes",
and the worker retries it.
**Store inventory.** Every place that stores tool arguments, results or
previews. I found them from `summarizeToolValue`, `redactArguments`,
`writeAudit`, and every column or JSON field named like summary,
preview, arguments, result, toolInput or toolResult.
| Store | Content | Cleared by this PR | Proof |
| --- | --- | --- | --- |
| `tool_invocations.arguments_summary`, `result_summary`, `progress` |
Redacted request/result preview, provider progress | Yes: `summary`
becomes `""` with `contentDeletedAt`; `progress` null; size and sha256
kept | content-deletion test 1 |
| `tool_call_events.arguments_summary`, `request_summary`,
`result_summary` | Same previews | Yes, same | test 1 |
| `tool_access_audit_events.details.argumentsSummary` (`writeAudit`) |
Argument preview | Yes, same; decision, ids, size, hash kept | test 1 |
| `tool_action_requests.canonical_arguments_summary`,
`preview_markdown`, `signed_arguments` | Approval preview and arguments
| Yes, for settled requests | test 1, card retry test |
| Approval card in `issue_thread_interactions`:
`payload.detailsMarkdown`, `payload.toolAction.previewMarkdown`,
`payload.toolAction.argumentsSummaryJson`,
`result.toolAction.resultSummary` | Approval preview, arguments,
executed result | Yes. Cards are found from every settled request of a
batch, in the same transaction | test 1, card retry test |
| `heartbeat_runs.context_snapshot` and `agent_wakeup_requests.payload`
(`toolAction(s)[].resultSummary`,
`paperclipAgentMessage.untrustedToolResults[].resultSummary`) | Approved
action result delivered to the agent | Yes, for settled runs and settled
wakes | test 1 |
| `tool_mcp_app_views.tool_input`, `tool_result`, `model_context` | App
view input, result, shared context | Yes: rows deleted | test 1 |
| Run log: object journal, archive journal, original `local_file` log
and its legacy S3 mirror | Full transcript | Yes, every copy, for each
settled run that called the connection or received an approved result |
run-log-store tests, test 1 |
| `heartbeat_run_events.message`, `payload` | Transcript events | Yes,
except structural events (lifecycle, terminal, presentation, usage,
compaction, session/turn start, `native.*`) | test 1 |
| `heartbeat_runs.stdout_excerpt`, `stderr_excerpt`, and every string
`summary`, `result`, `message`, `text`, `output`, `content` or `body` at
any depth of `result_json` (including `nativeResult`, `acceptedResult`,
`semanticResult` and their `continuation`) | Output excerpts and final
answer | Yes; schema and control fields kept | test 1, canary |
| `approvals.payload` (formal board approval) | Tool name, risk and
hashes only | Not needed: no content | — |
| `tool_mcp_tasks` | Request hash and sealed provider task id; no result
| Not needed: no content | — |
| `tool_mcp_elicitations.questions` and their question cards | Questions
the provider asked a person | No. These are provider prompts, not tool
results, and the answered question stays in the task. Follow-up if
wanted | — |
| `tool_mcp_skills`, `tool_mcp_skill_files`, `tool_catalog_entries` |
Skills and tool descriptions the provider publishes | No. These are
provider definitions, not data read through tool calls | — |
| Transcripts of later runs that read an app view's `model_context` |
Shared app context | No. Nothing records which runs read it. The help
page says so. Follow-up | — |
| `issue_comments.body`, issue documents (including continuation
summaries), files, chat messages | Task content written by agents or
Paperclip | No, by design. The user removes it by editing or deleting it
or the task. The confirmation says in bold that anything agents wrote
into tasks is not removed, and so does the help page. The canary
excludes `issue_comments.body` by name for this reason | canary asserts
it is kept |
| Raw provider traces | Full provider traffic | No. Admin opt-in,
encrypted, expire within 24 hours | — |
| Feedback exports already sent | Run logs the user chose to share | No.
Already outside Paperclip | — |
| Content of runs of a deleted task or company | Same stores | No.
Follow-up | — |
**Durable request (schema change).** I added one table,
`tool_connection_content_deletions`, and migration `0490`. I followed
`doc/DATABASE.md`: edited the schema, exported it from
`packages/db/src/schema/index.ts`, ran `pnpm db:generate`, and ran the
migration drift and compatibility tests. The classifier marks it
`online_compatible` (a new table and its indexes only). No existing
table can hold a durable per-connection request with a cutoff time,
cursor, counts and retry state. Without it, an interrupted deletion
could resume only when a person pressed the button again.
**Resume after restart.** The worker uses the shared
`registerDeadlineWork` lifecycle on a new
`tool-connection-content-deletion` queue. The request insert signals the
queue in the same transaction. At server start the worker runs once,
`next()` finds any pending row, and processing continues from the saved
phase and cursor. Nobody presses anything. `next()` returns a deadline
only while a pending row exists, so an idle instance sends no recurring
query. A failure records `attempts` and `last_error` and retries after
30 seconds.
**One run selection.** `runsWithStoredContentSql` selects the runs whose
transcripts are deleted: runs that made a tool call or tool-call event
through the connection, and runs whose context lists one of the
connection's approved action requests, limited to runs that still hold a
log, an excerpt, result text or a content event. The dialog count, its
in-progress warning and the job's `runs` phase all use this one
function.
**Phases.** `invocations`, `events`, `auditEvents`, `appViews`,
`deliveredResults` (50 action requests per page; matching runs and wakes
are locked with `FOR UPDATE` before their documents are rewritten),
`runs` (the shared selection, 50 run ids per page, then one run at a
time), `done`.
**Canary test.** `tool-connection-content-deletion-canary.test.ts` puts
a unique marker in a tool call's arguments and result, an approved
action with a preview, a result delivered to a later run and its wake, a
native run that quotes the marker in its answer and events, a run log
migrated from a local file with an S3 mirror to an object journal, an
MCP App view and the audit tables. It checks that the marker is first
present in the database, the object store, the legacy mirror and the log
files. After the deletion it scans every `text`, `varchar`, `json` and
`jsonb` column of every table found through `information_schema` (no
hand-written table list), every object in both stores and every file
under the log directory. Any hit fails with the table and column or the
key. It runs three times: a complete deletion, a deletion interrupted
twice by storage failures and resumed, and two deletions for different
connections on one task at the same time. The only exclusion is
`issue_comments.body`, named with its reason.
**Batching and time budget.** Tool rows are read in pages of 200 with
keyset pagination on the existing `(company_id, created_at)` indexes,
bounded by the request time. Each page's writes and the saved progress
commit in one transaction. Counts are therefore exact, and a crash
repeats at most one page, idempotently. Runs advance one at a time from
the shared selection. Each 1,000-event page is its own step. Log removal
is its own step and runs before its progress transaction, so object
storage calls never run inside a database transaction. The 10-second
budget is checked after every step. Nothing changes on the agent boot or
tool-call path.
**In-flight work.** A run counts as settled only when its status is
terminal, `finished_at` is set, cost accounting is done, and no native
finalization is open. Calls, approvals, events, app views, delivered
results and transcripts tied to other runs or wakes are skipped and
counted. The confirmation says "N runs are still working and will be
skipped. Delete again after they finish."
**Permissions.** Board users with configure access (connection manager
or creator) can delete, like `DELETE /tool-connections/:id`. Agents,
viewers and other companies are refused. The activity entries
`tool_connection.content_deletion_requested` and
`tool_connection.content_deleted` hold counts only.
**UI reads.** The dialog loads counts once when it opens. While a
deletion runs, it polls `GET
/tool-connections/:id/stored-content/deletion`, a single indexed row
read, every 2 seconds. Polling stops when the job completes or the
dialog closes. The Delete button is not gated on counts.
## What Changed
- `packages/db`: new `tool_connection_content_deletions` table and
migration `0490` (online compatible: new table and its indexes only).
- `packages/shared`: `ToolConnectionStoredContent`,
`ToolConnectionContentDeletion` and counts types; optional
`contentDeletedAt` on `ToolRedactedValueSummary`.
- `server`: `RunLogStore.remove`, which deletes every copy of a run's
log (`composeRunLogStore`); `content-deletion.ts` service; deadline
worker wired into startup and pre-drain; `GET
/tool-connections/:id/stored-content`, `POST` and `GET
/tool-connections/:id/stored-content/deletion`, and `DELETE
/tool-connections/:id?deleteStoredContent=true`; OpenAPI entries.
- `ui`: "Delete data" row on the connection's Permissions tab with a
confirmation that shows counts, skipped runs, and "This cannot be
undone"; "Also delete data read through this connection" checkbox in the
Connectors removal dialog.
- Docs: user help
`docs/guides/board-operator/deleting-connection-data.md` (for the
privacy policy link) and an API note in
`doc/connections/CONNECTOR-PLAYBOOK.md`.
- `tests/runner-e2e/source-sdk-public-inputs.json` refreshed for the
shared type change.
`server/src/routes/tool-access.ts` (3,010 lines) and
`ui/src/pages/apps/Browse.tsx` (1,722 lines) grow by about 40 and 20
lines. The routes reuse that file's connection access checks; the dialog
reuses the existing removal confirmation. The new logic lives in its own
files.
## Verification
- `server/src/__tests__/tool-connection-content-deletion.test.ts`
(embedded PostgreSQL): content is gone from every "Yes" store in the
inventory; rows, hashes and sizes stay; another connection and another
company are untouched; a running run is skipped and is deleted after it
settles; a storage failure leaves the request pending with `retrying`,
and the next pass completes it; an approval-card update that fails once
is cleared on the retry; an unrecognised log backend keeps the pointer,
keeps the job pending and writes no completion entry; a zero time budget
yields after every step and still finishes; a repeat request returns the
pending one; agents and outsiders are refused; removal with
`deleteStoredContent=true` queues the deletion.
- `run-log-store.test.ts` and `object-run-log-store.test.ts`: `remove`
deletes local and mirrored logs and object journals, removes a migrated
run's original local file and mirror with its journal, refuses an object
log when object storage is not configured, and is idempotent.
- `ui/.../StoredContentDeletion.test.tsx`: confirmation text, counts,
skipped-run warning, and the request.
- Red: these tests fail on `master` because `remove`, the service and
the routes do not exist. Green on this branch.
- Ran: the tests above, `openapi-routes`,
`server-startup-feedback-export`, `tool-connection-removal`,
`packages/db` migration drift and compatibility tests, all
`ui/src/pages/apps` tests (950), `pnpm check:token-gates`, server and UI
`tsc --noEmit`. `pnpm verify` exits 2 (global CI input changed), so
required CI supplies broad coverage.
## Risks
- Deleting is permanent by design. The confirmation says so.
- A `local_file` log written on another replica's local disk stays on
that pod's disk until the pod is replaced; its S3 mirror is deleted. New
logs on S3-configured instances use object journals, which are deleted.
- On versioned buckets, earlier object versions remain until the
bucket's lifecycle policy removes them (the existing journal delete path
does not remove versions).
- Not in this PR (follow-ups): the "No" rows of the inventory (except
agent-written task content, which is out of scope by design), mainly the
same deletion when a task or a company is deleted, and later runs that
read an app view's shared context.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via 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>
|
||
|
|
55b692d532 |
feat(telemetry): send Cloud server telemetry directly to PostHog (#22006)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server sends first-party telemetry events through a collector. The collector anonymizes the events and copies them into PostHog. > - Paperclip Cloud is our own service. It needs real IDs (workspace, user, agent, task) so that a person can go from a PostHog event to the exact workspace and task. > - The collector path hashes these IDs. It also cannot link a server event to the browser session that caused it. > - This pull request adds a server-owned direct sender for Cloud only. Self-hosted installs keep the collector path with no change. > - The benefit is real IDs and session links on Cloud, and no change to self-hosted privacy. ## Linked Issues or Issue Description **Subsystem affected** Server telemetry (`packages/shared/src/telemetry`, `server/src/telemetry.ts`). **Problem or motivation** All Cloud telemetry goes through the collector. The collector hashes the install ID, agent IDs and task IDs. So, on Cloud, you cannot find the workspace, user or task of an event. Server events also cannot show in a browser session replay. **Proposed solution** On a Cloud-managed server that has `PAPERCLIP_POSTHOG_PROJECT_TOKEN`, `PAPERCLIP_CLOUD_STACK_ID` and `PAPERCLIP_POSTHOG_ENVIRONMENT`, send each telemetry batch straight to PostHog with `posthog-node`. Use the same event shape that the telemetry backend loader makes today, and add the real IDs. Keep every other install on the collector. **Alternatives considered** Send real IDs through the collector. We did not do this, because the collector exists to anonymize self-hosted data. **Roadmap alignment** This is Cloud analytics infrastructure. It does not change a core product feature. ## What Changed - Add `server/src/services/cloud-posthog-config.ts`. `resolveCloudPostHogConfig()` returns `null` unless the instance is Cloud-managed and has a token and a stack ID. `isPostHogDirectDeliveryEnabled()` also requires an environment and the kill switch on (`PAPERCLIP_POSTHOG_DIRECT` is not `0`). - Add a narrow `TelemetryTransport` seam to `TelemetryClient` in `packages/shared`. With a transport, each flushed batch goes to the transport and never to the collector. Without one, the client does what it did before. A transport can capture per-event context at track time. The context does not go into the collector envelope. - Typed helpers hash `task_id` unless the transport sets `hashesPrivateRefs: false`. Private `source_ref` values (for example a private repository name) are customer content, so they stay hashed on every path, Cloud included, with `source_ref_hashed: true`. - Add `server/src/services/posthog-direct/`: - `event-shape.ts` builds PostHog messages with the loader's event names, metadata keys and key order, the deterministic event uuid formula, and the unknown-enum fallback. It drops events that the backend quarantines (unregistered names). - `enum-fallbacks.generated.ts` holds the backend fallback rules. Enum values come from the shared generated contract. - `transport.ts` loads `posthog-node` with dynamic `import()` only on the first Cloud send. - `request-context.ts` is Cloud-only Express middleware. It reads only `X-POSTHOG-SESSION-ID` and `X-POSTHOG-WINDOW-ID`. It ignores `X-POSTHOG-DISTINCT-ID`. The acting user comes only from the authenticated request actor. Context stops when the response finishes, so later background work does not use that user. - `server/src/telemetry.ts` selects exactly one sender per process. On start, the Cloud sender sends `$groupidentify` (group `workspace`, key = stack ID) and one `cloud.workspace_started` event with `install_hash` (sha256 of the raw install ID). Both go straight to `posthog-node` and are not in `PAPERCLIP_EVENTS`. - `distinct_id` is the acting user ID, else `workspace:<stackId>`. Events without an acting user keep `$process_person_profile: false`. GeoIP stays off on all server events. - Shutdown flushes the client and then shuts down `posthog-node`. - Add `scripts/generate-posthog-direct-fixtures.mjs`. It runs the telemetry backend's own ingest and loader on one envelope and writes the golden fixture and the fallback table. The script header tells how to regenerate them. - Update `packages/shared/src/telemetry/README.md` with a "Cloud Direct Delivery" section about the privacy boundary. - Add `posthog-node@5.38.2` to `server/package.json`. This PR does not change `pnpm-lock.yaml`, because the lockfile refresh workflow owns it. Intended differences from the loader output on Cloud: `distinct_id` (user or workspace, not the HMAC install ID), raw `agent_id`, raw `task_id` (private `source_ref` stays hashed), and these added properties: `stack_id`, `company_id` and `user_id` when known, `environment`, `$groups`, `$session_id` and `$window_id`. The uuid formula is the same. The uuid is different only when the dimensions are different (raw `task_id`). ## Verification - `pnpm verify` returned exit 2 (a global CI input changed: the new script). I ran focused checks. Required CI supplies the broad coverage. - Focused tests pass: `packages/shared` `src/telemetry` (6 files, 42 tests). Server: `posthog-direct-telemetry`, `posthog-direct-event-shape`, `cloud-posthog-config`, `shared-telemetry-events`, `heartbeat-status-preserving-telemetry`, `issue-thread-interactions-telemetry`, `native-run-finalizer-telemetry`, `agent-task-run-telemetry`, `error-handler` (9 files, 115 tests), and `server-startup-feedback-export` (133 tests). - `tsc --noEmit` passes for `packages/shared`, `server` and `cli`. - New tests: - Config matrix: not Cloud, no token, no stack ID, no environment, kill switch, browser and replay flags. - Self-hosted: `posthog-node` is never loaded, the collector gets the batch, and the envelope bytes are the same as before (with `task_id` hashed). Tracing headers are ignored. - Cloud: a private `source_ref` stays hashed and the raw repository name never reaches the sender. - Cloud: one batch goes only to PostHog. Real IDs, `$groups`, `environment` on every event. `cloud.workspace_started` reaches the PostHog sender with `install_hash`. No other event has `install_hash`. - Golden: our builder output equals the backend loader output, except the intended differences above. Key order is the same. - `distinct_id`: user, agent and anonymous requests. A spoofed `X-POSTHOG-DISTINCT-ID` never changes `distinct_id` or `user_id`. A bad session header is dropped. Work after the response ends does not keep the user (red without the response-end guard, green with it). - Kill switch and a missing environment both fall back to the collector. - Local run with a real server and a local capture server (no real PostHog project): - Cloud mode (authenticated, local Postgres, `PAPERCLIP_POSTHOG_HOST` set to the capture server): the capture server got `$groupidentify`, `cloud.workspace_started`, `server.started` and `goal.created` on `/batch/`. `goal.created` from a Cloud tenant user had `distinct_id` = that user, `user_id`, `company_id`, `$session_id`, `$window_id`, `$groups` and no `$process_person_profile`. The spoofed distinct ID header was not used. Nothing went to `/ingest`. `SIGTERM` ran the `telemetry_flush` step and sent the queued events. - Self-hosted mode (same token variables but no Cloud signal): the capture server got only `/ingest` with the normal envelope. Nothing went to `/batch/`. - Runtime dependency note: `posthog-node` loads with dynamic `import()` only on Cloud with direct delivery on. The load happens after startup, outside the boot path. The unit test mocks the package to count loads. The local run used the real package. ## Risks - Medium. This is a telemetry change, so a privacy review is requested. Self-hosted output does not change. The direct path is off unless all three Cloud variables are set, so a merge does nothing until fleet config sets them. - Cloud events with an acting user create PostHog person profiles keyed by the Paperclip user ID. This is intended under the Cloud terms. - The fallback table can drift if the backend adds a new normalization rule. A test fails when a rule does not match the shared enum contract. Enum values come from the shared contract, so new enum values do not drift. - `posthog-node` keeps network failures in its own queue and drops events that PostHog rejects. The client does not resend these, so events are not sent twice. - `pnpm-lock.yaml` is not in this PR. The lockfile refresh workflow adds `posthog-node` after merge. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, local server runs). ## 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> |
||
|
|
35c4526887 |
fix(ui): clean up routines controls and folder loading (#22009)
## Thinking Path > - Paperclip helps people manage AI agents and their work. > - Routines define work that repeats and provide controls to find and organize it. > - The routine list appeared before its folder data. The folder rail then moved the list. > - The page also repeated its folder summary and showed an extra selection control. > - This change loads the folder view with the list and reduces the controls. > - The result is a stable page with consistent folder rows and clear icon controls. ## Linked Issues or Issue Description **What existing behavior does this improve?** The Routines list page and its folder navigation. **Current behavior** The page shows a Select button, a repeated “All routines” summary, and text buttons for Sort and Group. A delayed folder response moves the visible list and can show “Unknown folder.” Folder names and counts use different columns. **Proposed behavior** Remove Select and the repeated summary. Show Sort and Group as named icon buttons. Wait for the initial folder read before showing a folder-based list. Align folder icons, names, and counts. Show folder read errors with a retry control. Keep routines readable after an error or a 15-second request deadline. **Reason and benefit** Operators can scan the list without a layout shift or repeated page labels. Sorting, grouping, search, folder navigation, and per-row filing remain available. **Breaking changes** The routine list no longer has bulk selection. Each row retains its Move to menu. No API or database contract changes. The roadmap has no overlapping page cleanup. The open routines PR search found backend, archive, and scheduling changes, with no matching list cleanup. ## What Changed - Remove the selection control, its unused bulk mode, and the repeated folder summary. - Use icon buttons with accessible names for Sort and Group. Keep them beside search on small screens. - Load folder data before the initial folder list appears. Keep cached rows visible during a folder refresh. Show folder read errors. - Use the same icon, name, count, and action columns for All routines, folders, and Unfiled. - Add regressions for delayed folder data, failed reads, retry recovery and stalled requests. - Keep cached folder names and rows visible after refresh failures. Suppress empty-folder prompts when the first read fails. - Update the Storybook test to use the new accessible button names. - Use the shared fail-fast retry helper with an explicit reason. The query-error policy check passes. - Remove the unused folder-row grid token. ## Verification - Revision: `27d70d1a37bda20496793bbff0fc6adf3a037e80`. Local Linux checkout, Node 25.9.0, Chromium 151. - Red/green: delayed folders, failed folder reads, stalled requests and saved folder filters each failed before their fixes. All now pass. Failed background reads preserve the routine link and folder navigation. A failed first read shows all routines; Retry restores the saved folder or Unfiled filter. - `pnpm --dir ui exec vitest run src/pages/Routines.test.tsx src/components/folders/FolderControls.test.tsx src/api/client.test.ts`: 51 tests pass. - Chromium checks pass for delayed first reveal, folder filters, Sort, Group, search, mobile folder selection, failed folder reads, the 15-second deadline, and retry recovery. No page errors occurred. - Storybook: the routine toolbar interaction test passes with the new button names. Seven interaction and geometry tests pass. The multi-story navigation test could not finish in the local dev server. Chromium reported insufficient resources. The first attempts also needed a browser install and the supported preview hostname. These attempts are not a full suite pass. - The visual baseline manifest has zero snapshots and no archive URL. There is no published baseline to refresh. Screenshots were captured for review; no baseline archive was created. - `pnpm --dir ui exec tsc --noEmit`: passes after stopping the local preview servers. An earlier overlapping attempt hit the workspace memory limit and is not a pass. - `node scripts/check-query-error-rendering.mjs --enforce --summary`: passes with zero findings. - `git diff --check`: passes. The ignored Storybook catalog was generated. - The original `pnpm verify` run selected 578 files and was stopped after source edits. It is not a pass. Focused checks above cover the final source. Required CI is running for the new revision. - Current-head Greptile and Paperclip reviews both give 5/5. All review threads are resolved. Build, policy and typecheck have passed. Remaining server suites are running. Squash auto-merge is enabled and waits for required checks. - Setup note: full preflight could not build Rust binaries because Cargo is absent. - Screenshots use the local source UI with sample API and WebSocket responses. They do not show a staging deployment or prove backend behavior. ## Risks Low risk. The initial folder view now waits for two reads. A folder read has a 15-second deadline and an explicit retry. A failed read with no cached data shows the routines without folder groups. Other group modes do not wait for folder data. Cached background reads keep the visible rows. Shared folder row alignment also applies to the legacy routines page. ## Model Used OpenAI Codex, GPT-6. The runtime did not expose a more specific model revision. Used reasoning, shell execution, and browser automation. No sub-agents were used. ## 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 - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
bc0a236b95 | feat(runner): accept a resume-compatible build for a relaunched released Runner (#21976) | ||
|
|
66ac5d7aa0 |
fix(google): keep Paperclip's Google client inside the 14 submitted scopes (#22001)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The built-in Google Workspace connector uses Paperclip's own Google OAuth client through the Paperclip Cloud broker, or a customer-owned client > - Google is reviewing that client for exactly 14 scopes (Gmail read/compose, Drive read/file, Docs, Sheets, Slides, Calendar) > - The code still accepted the old 21-scope union for the unified connection, and other Paperclip-managed Google methods (Gmail archive, Chat, People, Workspace Search) could ask the same client for scopes outside the submission > - A consent request for an undeclared scope through the verified client breaks the review > - This pull request makes the 14 an explicit constant, enforces it on every unified-connection request, callback and refresh, and stops new consent for managed Google profiles outside it > - The benefit is that Paperclip's Google client cannot request a scope that Google has not reviewed, while saved connections keep working ## Linked Issues or Issue Description Refs the plan in `doc/plans/2026-11-17-google-workspace-code-fixes.md` (items 2, 3 and part of 10). **What happened?** The unified `workspace.all` profile was the 21-scope legacy union, and `isGoogleWorkspaceScopeGrant` accepted any subset of it. The Gmail `paperclip-archive` method asked for `gmail.modify`. The Chat, People and Workspace Search cards had Paperclip-managed methods with Chat, Contacts, Directory, profile and `calendar.readonly` scopes. None of these are in the Google submission. **Expected behavior** Paperclip's own Google client requests, stores and refreshes only the 14 submitted scopes. New managed setup is not offered for anything else. **Steps to reproduce** 1. Advertise `gmail.archive` (or `chat.read`) from the broker. 2. Open Apps. The managed archive/Chat method is offered, and starting it signs a broker session for scopes outside the 14. 3. Refresh a unified grant: the signed binding lists all 21 legacy scopes. ## What Changed - `packages/shared/src/google-workspace-connectors.ts`: add `GOOGLE_WORKSPACE_SUBMITTED_SCOPES` (the 14, written out by hand). `workspace.all` now uses it. `isGoogleWorkspaceScopeGrant` checks against it. Add `googleWorkspaceProfileWithinSubmittedScopes`. - `server/src/services/paperclip-cloud-connector.ts`: add `paperclipCloudConnectorConsentAllowed`. `startAuthorization` refuses a Google profile outside the 14 before any broker call. `appWithPaperclipCloudConnectorAvailability` does not offer those methods for new setup, even when the broker advertises them. - `authorization-start.ts`: a saved connection on such a profile cannot restart consent (`paperclip_cloud_connector_scope_not_offered`, 422). - Capping contract, the same on managed and customer-owned OAuth (`paperclip-cloud-connector.ts` `openCredentials`, `cloud-callback.ts`, `direct-callback.ts`, `grant-refresh.ts`): Paperclip caps Google's reported scopes to the 14 (`googleWorkspaceSubmittedScopesIn`) and to the saved request, then continues. A scope outside the 14 is ignored and never enables an action. Only missing scope evidence or an empty result marks the grant for reconnecting. Reconnecting with a new service choice always works. What Paperclip *requests* stays fail-closed: an outgoing unified authorization request with any scope outside the 14 is rejected. - Docs: `doc/connections/GOOGLE-WORKSPACE.md`, `doc/connections/GOOGLE-WORKSPACE-SERVICE-CONSENT.md`. - `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed pins for the changed shared file. ### Investigation **Scope flow, unified connection.** Both paths start in `authorization-start.ts`. The requested set comes from the picker (`googleWorkspaceSelectedScopes`), a saved draft, or the saved grant, and must be inside the method's `scopesHint` (the 14 since the connector was added in #15545). Managed: `cloudConnector.startAuthorization` signs `scp` = the request; the broker validates it as a subset of its registry; the claim is unsealed with the request as AAD; `cloud-callback.ts` caps Google's grant to the request. Customer-owned: `direct-callback.ts` checks Google's raw `scope`, then caps it. Refresh: managed refresh signs `scp` = the profile definition (previously 21) and unseals with that set as AAD; customer refresh checks the raw `scope`. **What depends on the 21-scope set.** Only the managed refresh binding (`scp` and envelope AAD) and tests. The broker (`paperclip-cloud` origin/master, `src/connections/providers.ts`, `broker.ts`) accepts any nonempty, duplicate-free subset of its `workspace.all` union for session, claim and refresh, and seals with the signed `scp`. So narrowing the app's `workspace.all` to 14 keeps the contract. I narrowed the definition itself instead of adding a parallel check. A saved unified grant can still report one of the 7 extra scopes: older app versions signed the 21-scope `workspace.all` binding on refresh, and Google can return scopes the same client was granted before. This PR therefore caps those scopes instead of failing the grant. **Managed Google methods.** See the table below. The broker's origin/master registry has no `gmail.archive` profile, so `paperclip-archive` could not reach the managed client today. | App / method | Profile | Scopes | Before | After | | --- | --- | --- | --- | --- | | google-workspace / paperclip-workspace | workspace.all | subset of the 14 | 21 accepted | 14 only | | gmail / paperclip-read, paperclip-draft | gmail.read, gmail.draft | gmail.readonly, gmail.compose | offered | offered | | drive, docs, sheets, slides, calendar / paperclip-read, paperclip-write | per service | inside the 14 | offered | offered | | gmail / paperclip-archive | gmail.archive | + gmail.modify | offered if advertised | saved only | | google-chat / paperclip-read, paperclip-write | chat.read, chat.write | chat.* | offered if advertised | saved only | | google-people / paperclip-read | people.read | directory, contacts, userinfo.profile | offered if advertised | saved only | | google-workspace-search / paperclip-read | workspace-search.read | + calendar.readonly, chat.messages.readonly | offered if advertised | saved only | "Saved only": the method stays in the app definition so saved connections resolve their method, refresh and run. New setup and new consent are refused. Customer-owned methods are unchanged. ### Broker changes needed in paperclip-cloud (not in this PR) 1. Narrow the `workspace.all` request allowlist for `session` (and the provider URL) to the 14. On refresh and claim, cap Google's reported scopes to the allowlist (or ignore extras) instead of rejecting with `provider_rejected`, and keep accepting a signed `scp` binding of the old 21 from older app versions until they are retired. 2. Drop or disable `chat.read`, `chat.write`, `people.read`, `workspace-search.read` for new sessions on the verified client. Keep refresh for saved grants until the owner retires them. 3. Do not merge the `gmail-archive-oauth-profile` branch for the Paperclip-managed client. ## Verification - Red first, then green: `pnpm exec vitest run packages/shared/src/google-workspace-connectors.test.ts server/src/services/paperclip-cloud-connector.test.ts` (13 new or changed tests failed before the change). - Red first, then green: `pnpm exec vitest run server/src/__tests__/tool-access-service.test.ts -t "refuses new managed setup|saved Paperclip-managed Gmail archive|fails closed on invalid refreshed|pilot"` (8 failed before the change). - Red first, then green: `pnpm exec vitest run server/src/__tests__/tool-access-service.test.ts -t "caps a|keeps a .* grant on its submitted|reconnects a"` (4 capping tests failed on the earlier fail-closed revision; both reconnect tests pass). - `pnpm exec vitest run server/src/__tests__/tool-access-service.test.ts -t "combined Workspace|Workspace|Gmail|managed"`: 161 passed. Full `tool-access-service` and `connection-management.integration` files: 599 passed on the earlier revision. - `pnpm exec vitest run packages/shared/src/app-definitions.test.ts server/src/services/gmail-tool-governance.test.ts server/src/services/gmail-archive-tool-policy.test.ts`: pass. - `pnpm --filter @paperclipai/shared typecheck`, `pnpm --filter @paperclipai/server typecheck`: pass. - `pnpm verify` returned exit 2 (a global CI input changed). Required CI supplies the broad coverage. ## Risks - Rollout order is app first, then broker. Refresh now signs the 14. If the broker narrows `workspace.all` first, refresh from app versions that still sign 21 (including self-hosted instances on the broker) fails until they upgrade. - A saved unified grant whose provider-reported scopes include a scope outside the 14 keeps working on its in-set scopes; the extra scopes no longer enable any action. A grant with only out-of-set scopes needs reconnecting, and a reconnect with a new service choice succeeds. - When the broker narrows `workspace.all` to the 14, it must cap or ignore extra scopes on refresh and claim (it re-validates them today), not reject saved grants. - Saved Chat, People, Workspace Search and Gmail archive managed connections keep working, but their owners cannot reconnect them through Paperclip's Google client. They see a 422 with a plain message. The owner must decide whether to retire them. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## 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 - [x] All Paperclip CI gates are green - [x] 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> |
||
|
|
55228527cf |
test(restart-chaos): keep a run waiting on an active model request as its U1 owner (#21986)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The restart-chaos harness grades every task with universal checks.
U1 checks that a task always has a live owner or an item a person can
act on.
> - U1 stops counting a `running` run as the owner after 3 minutes with
no new run evidence. It does this even while the run's provider turn is
still active.
> - R5 in the same harness already allows an active provider turn 10
minutes of quiet (#21730), because one model request can be slow.
> - In restart-chaos rerun 11 (task t001, OpenCode), one model request
stayed quiet for 7.5 minutes. U1 failed the task, but the API reported
the run `running` and the task `working` for the whole time, and the run
then succeeded.
> - This pull request makes U1 use the same provider-turn bound as R5.
> - The benefit is that U1 no longer reports a slow model request as an
unowned task, and it still fails a run that stays quiet for more than 10
minutes.
## Linked Issues or Issue Description
Refs #21730
**What happened?**
Restart-chaos rerun 11 A1 (master
|
||
|
|
54f8068df4 |
fix(chaos): confirm a task that rests just before its deadline (#21979)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The restart-chaos harness grades whether tasks come to rest after faults > - The task observer must see rest for REST_CONFIRM_MS before it records rest > - The deadline check ran on the same poll and timed the task out first > - A task that went done shortly before its deadline got graded R1 fail "no_rest_within_budget" > - This pull request gives such a task up to REST_CONFIRM_MS more to confirm > - The benefit is that the harness no longer reports false R1 failures ## Linked Issues or Issue Description **What happened?** A task that reaches a resting status (for example done) shortly before its deadline is graded R1 fail "no_rest_within_budget (last status done)". The observer needs REST_CONFIRM_MS of confirmed rest before it calls onRest. The deadline check right after it fires on the same poll and sets timedOut. Example: wave w-20261117T061432-s7106, task t025 went done at 06:59:32.8Z and task_timed_out was logged at 06:59:34.1Z. **Expected behavior** The task is graded as rested, with restAt set to the time rest started. **Steps to reproduce** Run a wave where a task goes done less than REST_CONFIRM_MS before its deadline. The new observer unit test reproduces it without the fix. ## What Changed - `TaskObserver.poll` now skips the deadline timeout while a rest candidate began at or before the deadline and has not yet had REST_CONFIRM_MS. - Added three tests in `observer.test.ts`: rest just before the deadline passes, a running task times out, and a task that starts resting after the deadline times out. ## Verification - `pnpm exec vitest run --config tests/restart-chaos/vitest.config.ts tests/restart-chaos/observer.test.ts tests/restart-chaos/governance.test.ts` passes (49 tests). - The new "rest just before the deadline" test fails without the fix and passes with it. - `pnpm verify` exits 2 because the harness test change needs broader CI coverage. CI supplies it. ## Risks - Low risk. Only a task already resting before its deadline gets up to REST_CONFIRM_MS (12 s) extra. Real timeouts are unchanged. ## Model Used - Claude Sonnet 5.5 (Anthropic), model ID claude-sonnet-5-5, 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 Sonnet 5.5 <noreply@anthropic.com> |
||
|
|
6d117998c8 |
fix(ci): skip reviewed-lock checks for a pending Dependabot lock in the Runner support suite (#21942)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Dependabot pull requests that change `pnpm-lock.yaml` are the only way, other than the lockfile refresh, that lock content changes > - #19356 let a verified Dependabot lockfile pass CI. The server's reporting-lock policy test skips when `PAPERCLIP_CI_PR_AUTHOR` is `dependabot[bot]`, and the lockfile refresh renews the proof after the merge > - #19537 then made the Runner support suite a required check. That job does not set `PAPERCLIP_CI_PR_AUTHOR`, and the suite's own reviewed-lock checks have no Dependabot skip > - So every Dependabot lockfile pull request fails `ci / Runner support suite` and `ci / verify`. The last one that merged, #17364, merged before #19537 > - This pull request gives the support suite the same Dependabot skip as the server test > - The benefit is that Dependabot dependency updates can merge again, with the same lock trust rules as before ## Linked Issues or Issue Description Refs #19356, #19537, #19614, #17172, #19575. Rebased onto `master` after #21943, which fixed the unrelated `qualify_test_selection` failure that a CI file change triggers. **What happened?** Dependabot pull request #17172 changes `pnpm-lock.yaml`. `ci / Runner support suite` fails in four test files, and `ci / verify` fails because of it: - `prepare-report-lock.test.ts` > installs only the reviewed dependency correction (4 cases): the committed lock hash is not in `report-lock.json`. - `source-sdk-public-type.test.ts`: the shared setup throws "Committed SDK reference lock is not reviewed". - `source-sdk-evidence.test.ts` > seals a normal producer-certified reviewed-reference SDK: the same error. - `source-sdk-public-inputs.test.mjs` > the committed SDK public source pins match this checkout's committed tree: `pnpm-lock.yaml` is stale in `source-sdk-public-inputs.json`. A Dependabot pull request may not change `report-lock.json`, `report-lock.patch` or the SDK pins. `lockfile-trust.mjs` rejects that change, and `refresh-lockfile.yml` renews those files after the merge. So the pull request can never pass. **Expected behavior** A verified Dependabot lockfile passes the Runner support suite, as it already passes the server's reporting-lock policy test. Other authors keep every check. **Steps to reproduce** 1. Open a Dependabot pull request that changes `pnpm-lock.yaml`, such as #17172. 2. Let CI run. `ci / Runner support suite` fails in the four files above. ## What Changed - `.github/workflows/pr-trusted.yml`: the `verify_runner_e2e_support` job sets `PAPERCLIP_CI_PR_AUTHOR` from the pull request author, like the general test job. - `tests/runner-e2e/prepare-report-lock.test.ts`, `source-sdk-evidence.test.ts`, `source-sdk-public-inputs.test.mjs`: the test cases that need a reviewed committed lock skip when `PAPERCLIP_CI_PR_AUTHOR` is `dependabot[bot]`. This uses the same check as `server/scripts/reporting-lock-policy.test.mjs`. The other cases in these files still run. - `tests/runner-e2e/vitest.config.ts`: on a Dependabot pull request, the suite excludes `source-sdk-public-type.test.ts`. Its shared `beforeAll` prepares the reviewed SDK reference, so every case in the file needs a reviewed lock. - `tests/runner-e2e/source-sdk-public-type.ts`: the installed TypeScript, Babel parser and Zod package hash checks move into an exported `verifySdkProofPackages`, which `verifySdkPublicSource` calls. The lockfile refresh renews the lock and source pins after a merge, but keeps these package hashes. - `tests/runner-e2e/source-sdk-proof-packages.test.ts` (new): runs `verifySdkProofPackages` against the installed packages on every pull request, including Dependabot ones, and checks that a changed package pin is rejected. So a Dependabot update of one of those packages still fails until its pins are reviewed. ## Verification - Red, then green, with a real Dependabot lock: I committed the `pnpm-lock.yaml` and `package.json` changes of #17172 on top of this branch in a local commit (not pushed). Then I ran `node node_modules/vitest/vitest.mjs run --config tests/runner-e2e/vitest.config.ts` on the four files: - Without `PAPERCLIP_CI_PR_AUTHOR`: 4 files failed and the same 6 tests failed as in CI. - With `PAPERCLIP_CI_PR_AUTHOR=dependabot[bot]`: 3 files passed, 33 tests passed and 6 skipped. `source-sdk-public-type.test.ts` was excluded. - On this branch with master's lock: `pnpm test:e2e:runner:unit` passed (Vitest: 687 files, 11640 tests; node tests passed). - `node --test .github/scripts/tests/*.test.mjs`: 808 passed. - After the package check change: the five affected files (`source-sdk-proof-packages`, `source-sdk-public-type`, `source-sdk-evidence`, `source-sdk-public-inputs`, `prepare-report-lock`) pass, 71 tests. `tsc --noEmit -p tests/runner-e2e/tsconfig.json` passes. - `pr.yml` calls `pr-trusted.yml@master`, so this pull request's own CI does not use the new job variable. The first Dependabot pull request after the merge checks it. ## Risks - A Dependabot update of TypeScript, the Babel parser or Zod still fails the suite until a maintainer reviews the new package pins. That is deliberate. - On a Dependabot pull request, the suite no longer checks the committed lock against the reviewed proof. The policy job still requires that the lock comes from a verified Dependabot commit (`lockfile-trust.mjs pr`), and the lockfile refresh still admits the lock and renews the proof and the SDK pins after the merge. That is the same trust as #19356. - `PAPERCLIP_CI_PR_AUTHOR` is the pull request author from the GitHub event. A contributor cannot set it to `dependabot[bot]`. Other commits pushed to a Dependabot branch are still checked by the policy job. - No runtime code changes. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used 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 --------- Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
d258f478fc |
test(ci): stop the live-run census hanging server shards, and name any stalled test file (#21941)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - PR CI splits the server tests across 12 shards; `ci / verify` fails when any shard fails > - Since 2026-11-16 the server shards were cancelled at their 20-minute job limit with no output (shard 2/12 five times, plus shards 1, 3 and 9), which blocked unrelated pull requests until reruns > - Turbo prints a task's output only when it ends, so a cancelled shard never names the stuck file > - Recomputing each cancelled shard's file list at its own merge commit put `issue-recovery-live-run-agent-census.test.ts` in 12 of 14 of them; it is also the slowest file in passing shards (235-300 s) > - That census started 9-14 real agent runs per file while `setTimeout` was faked, waited on them with no bound, and had 30-minute test timeouts, so a stuck wait could never fail inside the job > - This pull request stops the census from starting real runs, bounds every wait, and adds a CI reporter that fails a run naming any file that stops making progress > - The benefit is that this file cannot hang a shard, and the next stuck file fails in minutes with its name and step in the log ## Linked Issues or Issue Description Refs #21867 (the same fix for the sibling agent-row census), #21831 (the behavior this census guards) **What happened?** `ci / General tests (server (2/12))` was cancelled at 20m16s in actions runs 43865258195, 43926799428, 43932238377, 43934278368, 43944290677 and 43935722497 (both attempts), and other server shards hit the same limit (for example 43901003914 shard 1, 43945768035 shard 3, 43845343831 shard 9). The hung jobs show CPU near 0 for the last 9 minutes and printed nothing after `Running //#test:run:general`. Shard membership changes with every merge commit. To compare the shards, I recomputed each job's file list at its exact merge commit with `GITHUB_WORKFLOW=PR` (the PR workflow removes the native-runner suites from these shards, so a local dry run without it gives a different list). `server/src/__tests__/issue-recovery-live-run-agent-census.test.ts` was in 12 of the 14 hung shards. Why that file: - During its 10-minute fake-timer warm-up, the "live" task was `in_progress` with no run. That is real assigned work, so recovery woke its agent and a real `process`-adapter run started while `setTimeout` was faked. The run lost its lease ("Legacy controller lease lost"), recovery retried, and a local run of the file showed 13 real run executions. - No wait in the file had a bound, and each test had a 30-minute timeout, so a delivery pass waiting on a faked timer or a run holding a lock never failed inside the 20-minute job. - Under local CPU contention, 3 of 4 copies of the old file failed the census assertion (39 settled checks, caused by the stray runs), and each copy took about 270 s with 9-14 real runs. Fixing the runs exposed a second problem in the fixture: the seeded tasks were stamped "now". The first 5-minute backstop after the live run's first hint re-checks rows changed within 5 minutes before the last full pass, so it re-checked all 860 seeded tasks. The old file passed only because the stray runs happened to trigger that backstop during the warm-up. **Expected behavior** The census never starts a real run, every wait has a bound that names what it waited for, and a CI test file that stops making progress fails the job quickly with its name. ## What Changed - `issue-recovery-live-run-agent-census.test.ts` - The live task is a settled review until its run starts; `startLiveRun` now writes the checkout (`in_progress` + `executionRunId`) the way execution start does. - Population agents and the held agent take no on-demand wakes (`wakeOnDemand: false`), so a recovery check cannot dispatch a run. The census counts queue checks, so this does not change what it measures. - The seeded population is backdated 2 hours ("settled long before the window", as the file's comment already said). - Each step (seed, worker start, run start, run-event tick, fake-timer advance, pass settlement, direct writes) has a real 20-second bound captured before the timers are faked, with a message naming the step. Test timeout is 4 minutes instead of 30. - New `scripts/ci/stalled-file-reporter.mjs`, enabled in GitHub Actions from the root `vitest.config.ts`: when a running file starts no test or hook and reports no result for 8 minutes (`PAPERCLIP_VITEST_FILE_STALL_MS` overrides), it prints a `::error file=...` annotation naming the file and the step it was in, cancels the run and exits 1. The slowest healthy server file runs about 5 minutes in total, so 8 minutes without any progress means a stuck file. Tests: `scripts/ci/stalled-file-reporter.test.mjs` (added to `test:release-registry`). ## Verification - Census, red: the old file runs 13 real agent runs locally (`heartbeat execution setup failed`, `LegacyControllerLeaseLostError`); with 4 copies under CPU contention, 3 failed with 39 settled checks at about 270 s each. - Census, green: 4/4 tests pass, 0 real runs, about 80 s locally. - Census still guards #21831: with the `ag.status <> 'running'` line removed from `changed-tasks.ts`, the first test fails with 534 settled checks and 540 backstop checks, the numbers #21831 recorded. - Reporter, red/green: the real-Vitest case (a file awaiting a promise that never settles, with a 10-minute test timeout) is still running when the 20-second test bound ends without the reporter; with the reporter it exits 1 in about 8 s and prints the annotation naming the file and the test. - Reporter on a real server file: `PAPERCLIP_VITEST_FILE_STALL_MS=3000` on `issue-recovery-recorded-decision-idle.test.ts` prints the annotation naming the file and step and exits 1. - `node --test scripts/ci/stalled-file-reporter.test.mjs`: 5/5 pass. ## Risks - Test and CI-tooling change only. No product code changed. - The census's agents no longer take on-demand wakes. The census measures recovery queue checks, not dispatch, and still fails without the #21831 fix. - The reporter stops the whole CI run when one file stalls for 8 minutes. A legitimate single test or hook that runs more than 8 minutes with no other progress in its file would now fail; none exists today (the slowest whole file is about 5 minutes). The limit is configurable. - Other fake-timer recovery files still have long test timeouts and unbounded pass waits (for example `issue-recovery-activity-hints`, 30 minutes). The reporter now caps any of them at 8 minutes without progress and names the file; bounding them is follow-up work. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## 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> |
||
|
|
f33c4cf6f7 |
feat(links): cache rich link status in the database and load it on idle (#21746)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Task text contains links to pull requests and other work. > - A link has useful status that should be visible when a task opens. > - The current cache lives in the server process and the browser. > - A new browser or server restart has no stored status to show. > - This pull request stores link status in the database and reads it in batches. > - Idle page work updates stale status without a hover or a delay to task data. ## Linked Issues or Issue Description **Problem or motivation** PR status is unknown in a new browser until the user points to each link. The process cache cannot supply saved status after a server restart. Related work: #20593 and #20654. A search found no other PR for database link caching. **Proposed solution** Store status by company, viewer and canonical resource URL. Read saved status in one indexed batch query. After document load and core request settlement, use browser idle time to update missing or stale status. Use the same query for hover and idle work. **Alternatives considered** Adding provider calls to task reads would delay task loading. Company-wide reuse of personal GitHub results would cross viewer access boundaries. A periodic server worker would create work when no page needs the result. **Roadmap alignment** This extends the shipped rich-link feature. It does not duplicate a roadmap project or add a new provider integration. ## What Changed - Add an additive, repeat-safe `link_previews` migration. Store channel, resource kind, free-form status, JSON metadata and freshness. The table has no task relationship or GitHub status enum. - Bound each company/viewer cache to 1,000 rows across concurrent server instances. Remove rows expired for over 30 days during writes. Limit provider lookups to 600 requests per minute per scope/process. Keep cached batch reads available during backoff. - Add a database store owned by the link service. Reuse canonical results across tasks. Keep company and viewer isolation. Save hover and idle results. Preserve last known status during an outage and cache unavailable results. - Add a board-only batch GET endpoint, including viewer-role access. It reads at most 50 URLs with one indexed select and makes no provider calls. Both endpoints use private, no-store HTTP responses. - Add a page coordinator for mounted rich links. Reuse browser data, share pending reads, and defer provider work until document load, core request settlement and browser idle time. Limit automatic work to 200 unique links and three requests in flight. Remove queued work when links leave the page. Keep encoded batch URLs below 6 KB. - Keep exact navigation URLs, status styling, anchored cards and keyboard access. Add a page-load Storybook case and browser regression. The link service owns cache policy and provider calls. The browser coordinator owns page timing. The shared contract adds only the batch limit and response shape. The database adds storage because process and browser caches cannot serve a new browser session. Plugin resolver registration is outside this change; storage accepts future provider channels and status values. ## Verification - **All 93 affected tests pass:** 40 link service, real PostgreSQL and HTTP cases, plus 53 OpenAPI cases. Two SQL regressions and one HTTP case failed before the storage repair. Concurrent writers now retain at most 1,000 rows per company/viewer; cleanup removes long-expired rows and keeps recent stale status. Request backoff preserves cached reads and isolates companies/viewers. The earlier eight concurrent hydration regressions also pass. Focused store/service/unit types pass. Commands: `pnpm exec vitest run server/src/__tests__/link-previews.test.ts server/src/__tests__/link-preview-store.integration.test.ts server/src/__tests__/link-preview-routes.test.ts --maxWorkers=1` and `pnpm exec vitest run server/src/__tests__/openapi-routes.test.ts --maxWorkers=1`. - **All 50 affected server tests passed before the later server-only repairs** on the master-integrated source: 20 recovery/deadline cases, one authenticated review-counts HTTP case, 10 link-service cases, 13 real PostgreSQL cache cases and six link-route cases. Command: `pnpm exec vitest run server/src/__tests__/issue-recovery-deadlines.test.ts server/src/__tests__/tool-connection-review-counts-http.test.ts server/src/__tests__/link-previews.test.ts server/src/__tests__/link-preview-store.integration.test.ts server/src/__tests__/link-preview-routes.test.ts --maxWorkers=1`. - Reproduced the CI watchdog assertion locally twice before the test repair. Ordinary assignment recovery can win `wakeReason` while the watchdog wake coalesces into the same successful run with its full mandate. The test now verifies the persisted watchdog identity, watched issue and stopped fingerprint, plus exactly one review run. All 21 recovery/HTTP cases passed before integrating master; all 50 affected cases pass after integration. No runtime behavior was changed for this repair. - **Fresh static Storybook build and all 22 browser cases pass**, with two workers and retries disabled. They cover states, anchored hover, keyboard access, exact navigation, duplicate requests, reload persistence, expiry and saved-status hydration followed by one idle refresh. The first browser attempt could not launch because this session lacked Chromium; installing the expected browser resolved setup. That attempt had no behavioral verdict. - The cache repair remains covered by four PostgreSQL red/green regressions for expired memory and newer durable status during provider failure/timeout, plus check-time precedence and failed-read recovery. Earlier UI/database/focused server type and migration safety/compatibility/replay checks remain unchanged-input evidence. - Master `77ddf260bf9a3de3dcb8456a60f4f809d67401fd` is integrated cleanly. Link migration 0489 and its snapshot chain are unchanged. SDK source validation checks 545 inputs with no stale source identities or changed runtime/lock pins. Whitespace validation passes. - `pnpm verify --explain` returns exit 2 and requires broad CI. No full local suite or deployed acceptance is claimed. Earlier local full-server type checks exceeded memory; current-head CI supplies broad type/build/test coverage. - [Previous CI 43900336895](https://github.com/paperclipai/paperclip/actions/runs/43900336895) passed full types/build but failed on embedded PostgreSQL startup (`ECONNREFUSED`), the watchdog assertion above, and unrelated plan-task browser cleanup (activity-log foreign key on company deletion). One failed-jobs retry was requested. Its browser shard 7 now passes without code changes; the exact deletion-race cause remains unproven. The watchdog assertion is repaired in this revision. The previous failures remain recorded, not counted as an overall pass. - [Prior CI 43905482848](https://github.com/paperclipai/paperclip/actions/runs/43905482848) passed full types, build and all eight browser shards. Several test jobs were cancelled; the run has no overall pass. Its concurrent update finding is repaired. [Next CI 43909197530](https://github.com/paperclipai/paperclip/actions/runs/43909197530) also passed types, build and all browser shards, but several server jobs were cancelled. Greptile and Paperclip Review gave that revision 5/5. Its security scan found unbounded retained cache rows. The quota, retention and request-limit repair above addresses that finding. All ten review threads are resolved. - [Current CI 43912947278](https://github.com/paperclipai/paperclip/actions/runs/43912947278), fresh code reviews and a fresh security scan are pending on `335d89ef1668dcdeb66bb2059512a7c2da29e273`. Auto-merge is disabled until the current revision clears its gates. Published head: `335d89ef1668dcdeb66bb2059512a7c2da29e273`. Local head: `b37b87c704a2ba8a65233c689a6a743f4011ce14`. Both have tree `643ebd19b9729b1e6a6bb695442269c3db32be3a`; GitHub tree creation verified equality. ## Risks - Each company/viewer retains at most 1,000 rows. Writes remove excess rows and entries whose freshness expired over 30 days ago. Inactive scopes remain bounded and are cleaned on the next write. Company deletion removes all rows. No periodic worker runs. Scope writes use a transaction lock; the existing deadline and concurrency budget cover that work. - Last known status can be stale until idle or hover work completes. Provider failures keep that status through the negative-cache window. - Automatic enrichment adds bounded provider traffic. It runs only for mounted supported links, once per mount, with the existing timeout and server concurrency limit. - Cache storage is viewer-scoped because provider results can be private. New viewers load their own results. This prevents reuse across users with different repository access. ## Model Used OpenAI Codex, based on GPT-6, with reasoning, repository tools, code execution and browser automation. The runtime does not expose the exact serving model ID or context-window size. No subagents were used. ## 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 --------- Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: Paperclip <Paperclip-Paperclip@users.noreply.github.com> |
||
|
|
b816c95f96 |
chore(lockfile): refresh pnpm lockfiles (#21936)
## Thinking Path > - Paperclip uses a dependency lock for reproducible builds. > - Dependency changes on master need matching lock entries. > - Paid eval reports also pin a reviewed offline correction. > - Reports must install before paid model work starts. > - This automated PR keeps the lock and report proof together. ## Linked Issues or Issue Description **What happened?** Dependency manifests on master changed after the last committed lock refresh. **Expected behavior** Frozen installs must match those manifests. Eval reports must retain matching offline lock proof. **Steps to reproduce** Run a frozen install before and after this lock refresh. ## What Changed - Refresh the dependency lock from the manifests on master. - Refresh the sandbox provider lockfiles from their manifests on master. - Include the matching offline report correction and hashes. - Resync the SDK public source proof's lock pins from the refreshed lock. ## Verification - Pinned pnpm resolution completed with lifecycle scripts disabled. - The report proof refresh accepted the reviewed committed baseline. - The workflow rejected changes outside the lock and report proof files. ## Risks The lockfile bot merges this PR without CI or review when every added package version is at least 3 days old on npm. Otherwise the PR waits for a maintainer, and the daily refresh tries again. The bot merges only the exact commit this workflow generated from manifests already reviewed on master. Unknown report lock baselines remain blocked. This update changes no permissions or paid enable gates. ## Model Used None — generated by pnpm and the deterministic report-lock updater. ## Checklist - [x] Thinking path and problem description included - [x] Generated lock and matching report proof included - [x] Release-age gate decides between bot merge and maintainer review Co-authored-by: lockfile-bot <lockfile-bot@users.noreply.github.com> |
||
|
|
77ddf260bf |
fix(runner-e2e): keep the supervisor off the heartbeat graph and ship the plugin SDK build (#21860)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The paid Runner Full-Stack E2E workflow proves chat features against a real source server > - Since master |
||
|
|
698c371b1b |
fix(ui): keep new Recents tasks ready to open from cache (#21904)
Track warmed tasks per query client, company, and account so tasks added to the top Recents rows receive the existing idle preload. Preserve the batch limit, cache ownership, and retry-on-revisit behavior. Add unit and browser regressions for later additions, held API responses, editor retention, and message position. Extend controlled performance coverage and document timing results. Co-Authored-By: Paperclip <noreply@paperclip.ing> |
||
|
|
991f773d7f |
fix(ui): align recent task status icons and move fold controls right (#21859)
## Thinking Path > - Paperclip helps people manage AI agents for work. > - The sidebar shows recent tasks and their subtasks. > - A left fold control moves parent tasks away from the status column. > - Status icons must stay in one column so people can scan tasks. > - This pull request moves the fold control to the right. > - The child guide now starts below the parent status icon. ## Linked Issues or Issue Description Follow-up to #21649. Related sidebar alignment work: #20926. Related experimental Recents work: #12314. This change corrects the status column in the shipped subtask group. **What happened?** Parent tasks with subtasks moved 20 pixels to the right. Their status icons did not align with tasks that had no subtasks. **Expected behavior** All top-level task status icons align. The child guide is centered below the parent status icon. The fold control is on the right. **Steps to reproduce** 1. Open a sidebar with a recent parent task and a task that has no subtasks. 2. Compare their status icons. 3. Expand the parent and compare the child guide with its status icon. ## What Changed - Remove the left offset from parent task rows. - Put the fold control in a separate right slot. - Center the child guide below the parent status slot. - Add browser checks for alignment, narrow rows, unread parents, both themes, and separate Classic menu and fold controls. ## Verification - The browser regression failed before the fix: the status icons differed by 20 pixels. - Final browser run: 44 checks passed. It covers 20 states in both themes, folding, paging, unread state, light and dark alignment, and the Classic action menu. - The focused component and request-performance suites passed: 46 tests. - Final source is based on master `29903bed59b1`. UI typecheck and the focused browser-test typecheck passed. The published head is `b8287aec1f55aa182b44622d72b20fe7ed7ce0e6`. Its tree matches the tested local tree `958e8d901ed1fec9ae17c164271eda4d25edca45`. - `pnpm verify --base origin/master` returned exit 2. It requires broad CI because the browser suite changed. Focused checks pass. [CI 43803650911](https://github.com/paperclipai/paperclip/actions/runs/43803650911) passes typecheck, build, all eight E2E shards, policy, Runner checks, all nine serialized server suites, all twelve general server shards, and [final verification](https://github.com/paperclipai/paperclip/actions/runs/43803650911/job/133095032900). All 62 check runs are clean: 57 success, 3 skipped, and 2 neutral. No checks are pending or failed. The legacy Snyk status also passes. - [Greptile review](https://github.com/paperclipai/paperclip/pull/21859#issuecomment-6907272673) is 5/5 on head `b8287aec1f55aa182b44622d72b20fe7ed7ce0e6`. The check passed. There are no review threads or actionable findings. The separate source review also reports 5/5. - Screenshots use production components with HTTP and session fixtures in Chromium on Linux. No deployed-instance or image-baseline comparison is claimed. - No database or API behavior changes. ## Risks Low risk. The change adjusts layout in the shared task group. The fold button remains separate from the task link and the Classic action menu. Exact unread counts and request limits keep their current behavior. ## Model Used OpenAI Codex, GPT-6. Exact deployment model ID was not supplied by the runtime. ## Checklist - [x] I have searched GitHub for duplicate or related PRs and linked them above - [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 (this is a sidebar layout bug fix) - [x] I have linked public issues or described the issue in this PR - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub references) - [x] My branch name describes the change and has no internal task ID - [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 (no command or subsystem behavior change) - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip <noreply@paperclip.ing> |
||
|
|
f7a3497e9d |
fix(evals): compare browser zones by clock, wait for the reloaded profile name, bind accounting reads by returned run (#21760)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The chat-feature eval catalog runs real agent conversations and grades the saved outcome > - Chat-eval cohort 16 (OpenCode with a DeepSeek model) had three failures that were not product failures of the chat agent > - One setup check compared time zone names, one observer read a form before it filled, and one grader accepted only exact query digests > - An eval that fails valid behavior hides real regressions behind noise, so each check must grade the outcome, not an incidental detail > - This pull request fixes the three checks, and it fixes a first-frame empty display name on the Profile page > - The benefit is that these three cases now fail only for the behavior they test ## Linked Issues or Issue Description **What happened?** Three chat-eval cases failed in cohort 16 (OpenCode, `openrouter/deepseek/deepseek-v4.1-flash-1017`) on correct behavior. (1) `activity.routine-audit`: setup threw "Browser timezone override did not apply (America/Buenos_Aires)". At 11:00-11:59 UTC the picker selects `America/Argentina/Buenos_Aires`, and Chrome reports that zone by its alias `America/Buenos_Aires`. The check compared names. (2) `navigation-preferences.edit-profile`: the name saved correctly, but the observer read the display-name field once, right after reload, and got an empty value. (3) `budgets-costs.spend-breakdown`: the answer was correct, but the grader accepted company cost reports only for `period=all` or `period=month`. The agent read `costs/by-agent` and `costs/summary` for the requested week, and that range covers the unpriced run. **Expected behavior** Each case passes when the product and the agent do the requested work. Each case fails when they do not. **Steps to reproduce** 1. Run `chat-features.runner-opencode.local.activity.routine-audit` between 11:00 and 11:59 UTC. 2. Run `chat-features.runner-opencode.local.navigation-preferences.edit-profile` and look at `profileAfterReload`. 3. Grade the retained cohort 16 observation of `budgets-costs.spend-breakdown` with the old grader. **Additional context** The run tool inputs are saved only as SHA-256 digests, so a grader binds a read by recomputing the digest of inputs it can check. For the cohort 16 spend-breakdown reads, the inputs were recovered this way: `from=2026-11-09T00:00:00.000Z`, `to=2026-11-16T00:00:00.000Z`. ## What Changed - `internal-routine-audit.ts`: the browser override check compares the UTC offset of the requested and reported zones, now and 182 days later, instead of the zone names. An unknown zone or a different clock still fails setup. - `identity-profile.ts`: after reload, `settledFieldValue` waits up to 15 s for the display name to reach the saved value, then records what the person sees. The grade still fails a name that does not arrive. - `ProfileSettings.tsx`: unedited fields show the session's saved name and image from the first frame. Before, a session restored from the saved read cache rendered an empty name until an effect filled it. - `identity-accounting.ts`: `readSavedAccounting` also accepts a company cost report whose checked `from`/`to` covers the unpriced run's cost event. The run log keeps only the input digest, so the grader recomputes digests for covering ranges: UTC day boundaries (with or without milliseconds or seconds, date-only, end of day), local midnights at each whole-hour offset, and the run's own `startedAt` and cost-event instants. A pending run (no cost event) counts only through `costs/summary`, `costs/data-quality` or its own run record, because the other reports sum cost events. A link to the run does not count, because the run id is in the task description. The run-log redaction is not changed. - Oracle versions bumped: `routine-audit.v7`, `spend-breakdown.structural.v6`, `identity-profile.v4`. ## Verification - Red/green: each new test fails on the old code and passes on the new code. - `internal-remaining.test.ts`: every candidate zone, reported by its own name, its ICU name and known browser aliases, passes at every hour in January and July. A different clock, a zone with daylight saving time and an unknown name fail. - `identity-personal.test.ts`: the settled read returns the saved name after empty reads, and returns a wrong name when the saved name never arrives. - `ProfileSettings.test.tsx`: the first rendered frame with a cached session shows "Alex Chen", not `""`. - `identity-accounting.test.ts`: the cohort 16 week-range reads pass, as do other covering ranges. Negative controls fail: no reads, run-list reads with unchecked inputs, ranges that exclude the run, another company, a denied read, a read by another run, and a read of a different run record with a link to the target run. - The retained cohort 16 spend-breakdown observation passes the new grader, and fails with its reads removed. - `pnpm test:e2e:runner:unit`: 686 files passed. `pnpm test:e2e:runner:typecheck` passed. `ui` ProfileSettings tests passed. `scripts/check-token-gates.mjs` is clean. - One narrow paid run of the three cases on this branch (result in a comment below). ## Risks - Low risk. The changes are in eval code, plus a small Profile page state change. - A covering range in a form outside the recomputed set (for example 08:00 at -03:00) is not recognized. That is a false negative, not a false pass. - The Profile page now keeps an unedited field in step with the session. A refetch still resets drafts, as before. ## Model Used - Claude, model ID `claude-opus-5-5`, used 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> |