Commit Graph
589 Commits
Author SHA1 Message Date
DottaandPaperclip 079fb1fe63 fix(secrets): add env-name secret guardrails, collision recovery, and API-access clarity (#22982)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Operators configure agent and environment secrets across Environment
variables and Secret access settings
> - Three common mistakes currently fail poorly or leak credentials:
pasting a token into an environment variable name passes validation and
leaks into run settings and logs, converting a plain environment
variable onto an existing secret name dead-ends with a disabled submit
button, and adding an API-access secret does not clarify that processes
will not see `$NAME` unless it is also bound as an environment variable
> - Secret configuration should prevent credential leaks by default and
recover cleanly from common setup mistakes
> - This pull request rejects and redacts secret-shaped environment
variable names and access aliases across shared, server, and UI layers,
adds "Use existing secret" and "Save as new version" recovery actions on
secret name collisions, and explains API-only vs `$NAME` delivery with
an "Also bind as env var" quick action
> - The benefit is safer secret handling with zero raw token leaks in
errors, settings, or logs and a smoother operator workflow

## Linked Issues or Issue Description

**What happened?**

Three issues occur when operators configure agent and environment
secrets:

1. Pasting a credential token (for example `github_pat_...`, `ghp_...`,
or `sk-...`) into an environment variable Name field passes
`^[A-Za-z_][A-Za-z0-9_]*$` for underscore-based tokens (such as
`github_pat_...` and `ghp_...`) or echoes the raw token in the server
error message for dashed tokens (such as `sk-...`). Existing redactors
also scrub only values, not secret-shaped object keys, so legacy or
rejected payloads leak the token in run settings and logs.
2. Converting a plain environment variable to a secret via
`ConvertToSecretPopover` (or creating a secret via
`CreateSecretPopover`) disables submission with `"A secret with this
name already exists"` whenever the suggested name already exists,
forcing the operator to cancel and switch flows manually.
3. Binding a secret under `Secret access > API access (no env var)` does
not state clearly that agent processes and shell scripts will not see
`$NAME` unless the secret is also bound under Environment variables, and
provides no quick action to add the matching environment variable
binding.

**Expected behavior**

1. Both UI and server reject secret-shaped environment variable names
and access aliases with an actionable error that never echoes the token,
mask accidental token input immediately in the UI, and redact
secret-shaped keys in adapter configs, event payloads, command/text
redaction, and HTTP 4xx/5xx request logs.
2. When a secret name already exists in `CreateSecretPopover` /
`ConvertToSecretPopover`, the popover lets the operator bind the
existing secret directly or save the typed value as a new version
(rotate) without dead-ending.
3. `AgentSecretAccessEditor` clearly explains that API-access secrets
are not injected as `$NAME` in the process environment and offers an
`"Also bind as env var"` quick action for API-only bindings.

**Steps to reproduce**

1. Open an agent's Secrets & variables settings and paste a GitHub
fine-grained PAT (`github_pat_...`) into an environment variable Name
field and save; observe that it is accepted and returned verbatim in
redacted adapter config / logs.
2. Create a company secret named `gh_token`, then add a plain env var
`GH_TOKEN` with a value and click "Store as secret"; observe the
disabled `"Store & bind"` dead end.
3. Bind a secret under `Secret access > API access (no env var)` and
observe that no guidance mentions `$NAME` visibility for
processes/scripts and no quick action exists to also bind it as an
environment variable.

**Paperclip version or commit**

Reproduced on `origin/master` commit
`2d065677959b585065ff3fec8718156a4cf6f41d`.

## What Changed

- **Shared credential-token detection
(`packages/shared/src/validators/secret.ts`,
`packages/shared/src/validators/index.ts`,
`packages/shared/src/index.ts`)**: Exported `ENV_VAR_NAME_RE`,
`looksLikeCredentialToken`, `SECRET_SHAPED_ENV_NAME_ERROR`, and
`SECRET_SHAPED_ACCESS_ALIAS_ERROR` as a single source of truth shared by
`adapter-utils`, `server`, and `ui`. Updated pinned registry
`tests/runner-e2e/source-sdk-public-inputs.json`.
- **Server validation and defense-in-depth redaction
(`server/src/services/secrets.ts`, `server/src/redaction.ts`,
`server/src/middleware/redact-sensitive.ts`,
`packages/adapter-utils/src/command-redaction.ts`)**:
- Rejected credential-shaped env var names and `access.*` aliases in
`normalizeEnvConfig`, `normalizeAdapterConfigForPersistenceInternal`,
`assertSecretBindingConfigPath`, `resolveEnvBindings`, and
`resolveAdapterConfigForRuntime` without echoing the raw token.
- Redacted secret-shaped object keys in `redactAgentAdapterConfig`,
`sanitizeRecord`, and HTTP log `redactSensitive`, and expanded
`command-redaction.ts` / `redaction.ts` token patterns and hints to
cover `github_pat_`, `sk_live_`/`sk_test_`, `rk_live_`/`rk_test_`, Slack
(`xox*-`), AWS (`AKIA`/`ASIA`), Google (`AIza`), and GitLab (`glpat-`)
tokens.
- **UI env-name guardrails
(`ui/src/components/environment-variables-editor/sensitive.ts`,
`model.ts`, `Row.tsx`, `index.tsx`,
`ui/src/components/AgentSecretAccessEditor.tsx`)**:
- Flagged credential-shaped variable names and access aliases
immediately with an inline error, masked the input (`type="password"` +
`ANALYTICS_NO_CAPTURE_CLASS`), redacted credential-shaped names in the
unsaved-changes summary, disabled inline Save while present, and dropped
credential-shaped aliases from emitted access maps.
- **Plain-to-secret collision recovery
(`ui/src/components/environment-variables-editor/CreateSecretPopover.tsx`,
`Row.tsx`, `index.tsx`, `ui/src/components/AgentSecretAccessEditor.tsx`,
`ui/src/components/AgentConfigForm.tsx`,
`ui/src/pages/CompanyEnvironments.tsx`,
`ui/src/components/ProjectProperties.tsx`)**:
- Replaced the dead-end duplicate-name error in `SecretPopoverForm` with
an inline recovery panel offering `"Use existing secret"` and `"Save as
new version"` (when active and rotatable), wired to `secretsApi.rotate`
across agent, environment, and project editors.
- **API-access vs `$NAME` clarity
(`ui/src/components/AgentSecretAccessEditor.tsx`,
`ui/src/lib/secret-delivery.ts`,
`ui/src/components/AgentConfigForm.tsx`)**:
- Clarified under `API access (no env var)` that processes and shell
scripts will not see `$NAME` unless bound under Environment variables
above, and added an `"Also bind as env var"` quick action on API-only
secret summaries wired to `AgentConfigForm`.
- **Tests**: Extended existing owner suites
(`server/src/__tests__/redaction.test.ts`,
`server/src/__tests__/redact-sensitive.test.ts`,
`server/src/__tests__/agents-adapter-config-user-secret.test.ts`,
`ui/src/components/environment-variables-editor/model.test.ts`,
`ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx`,
`ui/src/components/AgentSecretAccessEditor.test.tsx`).

## Verification

- `pnpm vitest run
ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx
ui/src/components/AgentSecretAccessEditor.test.tsx
ui/src/components/environment-variables-editor/model.test.ts
ui/src/components/environment-variables-editor/sensitive.test.ts
server/src/__tests__/redaction.test.ts
server/src/__tests__/redact-sensitive.test.ts` — 6 files, 149/149
passed.
- `pnpm vitest run --hookTimeout=120000 --testTimeout=120000
server/src/__tests__/agents-adapter-config-user-secret.test.ts` — 1
file, 6/6 passed (embedded Postgres route test verifying HTTP 422
rejection without token echo for `github_pat_`, `ghp_`, and `sk-` env
var names).
- `pnpm vitest run packages/adapter-utils/src/command-redaction.test.ts`
— 1 file, 43/43 passed.
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/adapter-utils typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — PASS (0 errors, Storybook catalog clean).
- `pnpm check:token-gates` — PASS (all 4 token gates clean).
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/redaction.test.ts
server/src/__tests__/redact-sensitive.test.ts
server/src/__tests__/agents-adapter-config-user-secret.test.ts
ui/src/components/environment-variables-editor/model.test.ts
ui/src/components/environment-variables-editor/EnvironmentVariablesEditor.test.tsx
ui/src/components/AgentSecretAccessEditor.test.tsx` — PASS.
- `pnpm verify --base 2d06567795
--explain` — `source-sdk-public-inputs.json` verified in sync; exited 2
due to broad input (`tests/runner-e2e/source-sdk-public-inputs.json`),
deferring repo-wide matrix to sharded PR CI.

## Risks

- Low risk. `looksLikeCredentialToken` matches only explicit provider
credential prefixes (`gh[pousr]_`, `github_pat_`, `sk-`,
`sk_live_`/`sk_test_`, `rk_live_`/`rk_test_`, `xox[baprs]-`,
`AKIA`/`ASIA`, `AIza`, `glpat-`, `npm_`, `hf_`, `lin_api_`, `sbp_`,
`SG.`, JWTs, PEM headers, `Bearer `) so ordinary uppercase or long env
var names are unaffected.
- Legacy agent or environment records that already stored a
secret-shaped env var key will now have that key masked as
`***REDACTED***` on reads and skipped with a redacted warning at runtime
(preserving existing heartbeats) and rejected on subsequent saves until
removed/renamed.
- No database migrations are required.

## Model Used

- Google Gemini (Antigravity agentic coding assistant with extended
reasoning, tool use, and local command 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>
2026-11-25 22:08:28 +00:00
Dottaandlucktastic a74b4f8196 feat(retry): let a board user grant one agent the task Retry (#22988)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - When a run stops in a state that needs board approval, Paperclip
holds the task until a board user presses Retry (`POST
/api/issues/{id}/retry`).
> - Some companies run an operations agent that reviews stopped tasks
and identifies routine Retries, but the route currently rejects every
agent with `403 Board access required`.
> - The only workaround is sharing a board key with the agent, which
grants unrelated board powers and hides which agent requested the Retry.
> - This pull request adds one narrow, opt-in permission key
(`tasks:retry`) that a board user can grant to a named agent so the
agent can call `POST /api/issues/{id}/retry` as that person, under all
existing gates and a per-task daily cap.
> - The benefit is that routine Retries stop waiting on manual clicks
while preserving least privilege, existing pause/budget/hold gates, and
full audit attribution for both the agent and the granting person.

## Linked Issues or Issue Description

- Closes #21633
- Supersedes #21634 (rebased cleanly onto current `master` with synced
SDK public input pins, OpenAPI `429` response documentation, and
additional route integration coverage for pause gates, revoked grants,
inactive grantors, cross-company isolation, and chat tasks)
- Refs #20081 and #18599 (broader delegate proposals; this change stays
narrow to one action, one grant per agent, and a per-task daily cap)

## What Changed

- `packages/shared/src/constants.ts`: add `tasks:retry` to
`PERMISSION_KEYS`. New agents do not receive it by default.
- `server/src/services/agent-task-retry.ts` (new):
- `agentTaskRetryActor`: resolves the agent's unscoped `tasks:retry`
grant and the active same-company board member who saved it. Grants
without a granting user (for example, agent-written rows), grants saved
with a scope, revoked grants, and inactive grantors return `null` and
fail closed. Returns a board actor scoped strictly to the agent's
company with `isInstanceAdmin: false`.
- `agentOwnsRun`: verifies that the supplied run ID is a valid UUID
belonging to the calling agent in the same company.
- `recordAgentTaskRetry`: under a per-task PostgreSQL transaction
advisory lock (`agent-task-retry:{issueId}`), enforces a rolling 24-hour
cap of 3 Retries per agent per task (`429` with `details.code:
"agent_task_retry_cap_reached"`), counts replays of the same
`idempotencyKey` once, and writes `issue.retry_requested_by_agent` to
`activity_log` with the agent, run ID, `grantedByUserId`, and
`idempotencyKey`.
- `server/src/routes/issues.ts` (`POST /issues/:id/retry`; small
+33-line delegation calling into
`server/src/services/agent-task-retry.ts` so the existing >1,000-line
route module does not absorb service logic): for an agent with a valid
`tasks:retry` grant, enforces the agent's own limits first (refuses
scoped `skill_test`/`task_bridge` keys, requires the agent's own run ID,
enforces `issue:read` and actor-class/interaction `issue:mutate`
boundaries), then runs the existing board Retry checks as the granting
person (preserving visibility, `issue:mutate`, pause, budget, hold, and
blocker gates). Refuses chat tasks (`403`) and cross-company tasks
(`404`). Agents without a valid grant keep getting `403`.
- `server/src/routes/openapi.ts`: remove `POST /api/issues/{id}/retry`
from `BOARD_ONLY_OPERATIONS` so granted agents can discover it via API
search, and document `429` in the endpoint responses.
- `doc/agent-permission-defaults.md` and `docs/api/issues.md`: document
`tasks:retry`, its default-off behavior, run/key requirements, daily
cap, and activity attribution.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refresh the pin for
`packages/shared/src/constants.ts`.
- `server/src/__tests__/issue-scheduled-retry-routes.test.ts` and
`server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts`:
add 14 embedded-Postgres route integration tests and 1 mocked-boundary
test covering default refusal, agent-written grant refusal,
board-granted Retry promotion + activity attribution, pause-gate
preservation, grantor visibility gates, revoked grant / suspended
grantor fail-closed, cross-company 404, chat task 403, daily cap 429,
idempotency replay counting, foreign run ID refusal, scoped grant
refusal, low-trust read/write boundary enforcement, and scoped key
refusal.

## Verification

- RED check on base `2d065677959b585065ff3fec8718156a4cf6f41d` before
production changes:
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-scheduled-retry-routes.test.ts -t "agent Retry with
a board user's tasks:retry grant"` failed because granted agents
received `403 Board access required` instead of `202` / `429` / `404`
and logged 0 `issue.retry_requested_by_agent` events.
- GREEN checks on head `14b5591073ea591251f2d24710a32e3c725a090c`:
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/server
typecheck`: passed (0 errors across `@paperclipai/shared` and all 7
`@paperclipai/server` typecheck layers).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-scheduled-retry-routes.test.ts
src/__tests__/openapi-routes.test.ts
src/__tests__/agent-default-configure-grants.test.ts`: passed (112/112
tests, including all 14 embedded-Postgres `agent Retry with a board
user's tasks:retry grant` tests and default-grant verification).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-agent-mutation-ownership-routes.test.ts`: passed
(229/229 tests).
- `pnpm exec vitest run --root tests/runner-e2e
source-sdk-public-inputs.test.mjs source-sdk-evidence.test.ts
source-sdk-public-type.test.ts
chat-catalog-domains/identity-accounting.test.ts`: passed (4 files,
98/98 tests).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check`: passed (`changed: false`, 578 inputs in sync).
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/issue-scheduled-retry-routes.test.ts
server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts`:
passed (`110 nightly suites validated, 2 test file(s) checked`).
- `pnpm verify --base 2d06567795
--explain`: exited 2 (`Global CI input changed:
doc/agent-permission-defaults.md`); sharded PR CI covers the full suite.

## Risks

- A granted agent acts with the granting board user's authority on `POST
/api/issues/{id}/retry` within the agent's company. Revoking the grant
or deactivating the granting user immediately closes access.
- The per-task daily cap counts `issue.retry_requested_by_agent` rows in
`activity_log`; pruning `activity_log` within 24 hours would reset that
window early.
- Downstream Retry domain records name the granting user; the initiating
agent and run are recorded in the corresponding
`issue.retry_requested_by_agent` activity entry.
- Sandboxed agents using the sandbox callback bridge remain blocked from
this route; this change does not widen the bridge.

## Model Used

- Google Gemini (Antigravity agentic coding assistant with extended
reasoning, shell execution, file editing, and automated test
verification), building on #21634 (originally co-authored by lucktastic
and Claude Opus 5.5).

## 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: lucktastic <13757243+lucktastic@users.noreply.github.com>
2026-11-25 22:06:37 +00:00
Dotta 168253f74d fix(telemetry): send agent.task_completed when a native run closes a task (#22963)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip sends product telemetry, and the `agent.task_completed`
event counts each task that an agent finishes
> - Only the REST issue update route (`server/src/routes/issues.ts`)
sent `agent.task_completed` when an agent moved a task to `done`
> - Native runs close tasks through `commitNativeStatusDecision` in
`server/src/services/native-runtime/status-decision-committer.ts`, which
bypasses the REST route and therefore sent `agent.task_run` without ever
sending `agent.task_completed`
> - Deployments where agents close tasks through native runs
consequently under-report completed tasks
> - This pull request supersedes #21206 (rebased onto current `master`),
sending `agent.task_completed` once after a committed native transition
into `done` without blocking finalization, with full company/person
telemetry scope and underlying Paperclip runner harness `adapter_type`
resolution
> - The benefit is accurate, deduplicated `agent.task_completed`
telemetry across both API and native completion paths

## Linked Issues or Issue Description

Refs #21206

**What happened?**
A native run closes a task through `commitNativeStatusDecision` in
`server/src/services/native-runtime/status-decision-committer.ts`. The
task moves to `done` and the run sends `agent.task_run`, but no
`agent.task_completed` event is sent because the only sender is
`server/src/routes/issues.ts` and native completion does not go through
that route.

**Expected behavior**
Paperclip sends one `agent.task_completed` event each time an agent
moves a task into `done`, on both the REST issue route and native status
commits. The event carries the same dimensions, runner harness
`adapter_type`, company scope, and person attribution as the issue
route. Replayed commits and tasks that were already `done` send nothing.

**Steps to reproduce**
1. Seed a native run ready to commit a `done` status decision on an
`in_progress` task.
2. Call `commitNativeStatusDecision` (or `finalizeNativeRun`) with a
`done` decision.
3. Observe that the task moves to `done`, while
`trackAgentTaskCompleted` is called 0 times.

**Paperclip version or commit**
`master` at `2d065677959b585065ff3fec8718156a4cf6f41d`.

## What Changed

- `server/src/services/agent-task-run-telemetry.ts`: add
`emitAgentTaskCompleted`. It loads the agent within the task's
`companyId`, resolves the underlying runner harness with
`telemetryAdapterType(agent)`, resolves person attribution with
`resolveTelemetryPerson`, wraps `trackAgentTaskCompleted` in
`withTelemetryActor({ companyId, person }, ...)`, and never throws.
- `server/src/services/native-runtime/status-decision-committer.ts`:
select `originRun.responsibleUserId` alongside `originRun.agentId`,
capture the completion payload only when the committed transaction
transitions `issue.status` from non-`done` to `done` with an origin
agent, and invoke `void emitAgentTaskCompleted(input.db, completedTask)`
after commit when `!committed.replayed` so slow lookups cannot block run
finalization.
-
`server/src/services/native-runtime/native-task-completed-telemetry.test.ts`:
add embedded-Postgres regression tests covering single emission (with
company scope, person attribution, and underlying runner harness
`adapter_type`), no duplicate on replay, non-blocking commit while
telemetry is pending, and no emission when the task was already `done`.
- `server/src/__tests__/agent-task-run-telemetry.test.ts`: add unit/DB
coverage for `emitAgentTaskCompleted` (company/person scope, runner
harness `adapterType`, cross-company agent isolation, and error
swallowing).
-
`server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts`:
add an end-to-end `finalizeNativeRun` integration test verifying a real
native run completion emits `agent.task_completed` once through the real
`trackAgentTaskCompleted` path and emits no duplicates on replay or
reconciliation.

Note: this PR supersedes #21206 (whose fork branch had merge conflicts
with pruned test suites and predated `withTelemetryActor` /
`telemetryAdapterType` on `master`, and whose fork repository did not
allow maintainer pushes from this account).

## Verification

- **RED (before fix on `2d065677959b585065ff3fec8718156a4cf6f41d`):**
`pnpm --dir server exec vitest run
src/services/native-runtime/native-task-completed-telemetry.test.ts`
Result: 1 failed | 1 passed — `sends agent.task_completed once with
company, person, and harness adapter_type when the runner closes a task`
failed with `AssertionError: expected "vi.fn()" to be called 1 times,
but got 0 times`.
- **GREEN (after fix):**
`pnpm --dir server exec vitest run
src/services/native-runtime/native-task-completed-telemetry.test.ts
src/__tests__/agent-task-run-telemetry.test.ts
src/services/native-runtime/native-run-finalizer-telemetry.test.ts
src/__tests__/heartbeat-status-preserving-telemetry.test.ts
src/__tests__/issue-telemetry-routes.test.ts`
Result: **5/5 files, 106/106 tests passed**
(`native-task-completed-telemetry.test.ts` 3/3,
`agent-task-run-telemetry.test.ts` 55/55,
`native-run-finalizer-telemetry.test.ts` 42/42 including end-to-end
`finalizeNativeRun`, `issue-telemetry-routes.test.ts` 5/5,
`heartbeat-status-preserving-telemetry.test.ts` 1/1).
- **Typecheck:** `pnpm --filter @paperclipai/server typecheck` —
**PASS** (0 errors across all layers).
- **Test budget:** `node scripts/check-test-budget.mjs --files
server/src/services/native-runtime/native-task-completed-telemetry.test.ts
server/src/__tests__/agent-task-run-telemetry.test.ts
server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts`
— **PASS** (110 nightly suites validated, 3 test files checked).
- **Broader suite:** `pnpm verify --base
2d06567795 --explain` conservatively
selected 1948/2302 files; PR CI supplies the full sharded server,
runner, typecheck, and build verification.
- **Runtime dependency assumption
(`rules/runtime-dependency-boundaries.mdc`):**
`commitNativeStatusDecision` fires `void emitAgentTaskCompleted(...)`
after transaction commit without awaiting it;
`native-task-completed-telemetry.test.ts` verifies with a
never-resolving promise that run finalization returns immediately even
if the telemetry lookup hangs.

## Risks

- Low risk. Emission runs after transaction commit as fire-and-forget
and catches all errors, so a rolled-back commit sends nothing and a
telemetry fault cannot fail or delay a status commit.
- Deployments where native runs close tasks will see
`agent.task_completed` counts rise to reflect actual completions, which
is the intended fix.

## Model Used

- Google Antigravity (`antigravity`, tool use and code execution),
building on and rebasing #21206 onto `master`.

## 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
2026-11-25 16:02:12 -06:00
Dotta 702368ffaf feat(github): graduate GitHub review bots out of experimental (#22996)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - GitHub Code Review Bot connects an agent to a dedicated GitHub App
so it reviews pull requests and responds to GitHub mentions
> - The feature was gated behind the default-off
`enableGitHubReviewBots` experimental instance setting, hiding the
catalog card, setup routes, identity links, and channel creation
> - People had to find and flip an instance-level experimental switch
before they could connect a GitHub review agent
> - This pull request graduates GitHub review bots to a normal always-on
feature, keeping `enableGitHubReviewBots` only as a deprecated
compatibility key that always resolves to `true`
> - The benefit is that every Paperclip instance exposes GitHub Code
Review Bot setup, discovery, and management by default without requiring
feature flags

## Linked Issues or Issue Description

**What existing behavior does this improve?**
GitHub Code Review Bot discovery, catalog visibility, setup/management
routes, identity-link endpoints, and Agent Channels visibility
(`enableGitHubReviewBots`).

**Subsystem affected**
Cross-cutting (`packages/shared`, `server/`, `ui/`, Storybook, E2E
specs, docs).

**Current behavior**
GitHub Code Review Bot is hidden from Connectors, `connections_search`,
chat-endpoint creation, identity-link confirmation, and UI
setup/settings routes until an instance admin turns on **Settings →
Experimental → GitHub review bots** (`enableGitHubReviewBots`).

**Proposed behavior**
GitHub Code Review Bot is always available as a standard feature on
every instance (self-hosted and Cloud), matching AgentMail and graduated
features such as Assistant connections (`enablePublicMcp`) and the AWS
connector (`enableAwsConnector`). `enableGitHubReviewBots` stays in
schemas and the feature catalog only as a deprecated compatibility key
that always normalizes to `true`, ignores stored or Cloud-managed
`false` values, and does not reject legacy `false` patches. Experimental
chat providers (Slack, Discord, Microsoft Teams, Telegram, iMessage
Photon, Speko) remain gated by `enableChatConnectors`.

**Reason and benefit**
Users can connect and manage GitHub review agents directly from
Connectors without an admin enabling an experimental flag first, and
Cloud stacks no longer require managed feature-flag overrides to expose
GitHub review bots.

**Breaking changes**
No schema migration or breaking API change. Existing rows, API patches,
and Cloud managed configs that still carry `enableGitHubReviewBots`
continue to parse cleanly, while the effective value is always `true`.
Instances that previously kept `enableGitHubReviewBots` off now display
GitHub Code Review Bot in Connectors and allow authorized managers
(`tools:manage_connections`) to create GitHub review bot endpoints.

## What Changed

- `packages/shared`: marked `enableGitHubReviewBots` as a deprecated
compatibility key in types, Zod defaults (`true`), and
`INSTANCE_FEATURE_CATALOG` (`cloudDefault: true`, `selfHostedDefault:
true`); updated `channelMethodEnabled` in `connector-availability.ts` so
`github` is always enabled alongside `agentmail`.
- `server` instance settings and Cloud staging:
`normalizeExperimentalSettings` always returns `enableGitHubReviewBots:
true`; `applyManagedExperimentalOverlay` and `updateExperimental` ignore
retired `enableGitHubReviewBots` entries so Cloud managed configs cannot
turn it off and legacy `false` patches are not rejected; removed
`enableGitHubReviewBots` from `CLOUD_STAGING_EXPERIMENTAL_KEYS`.
- `server` chat channels, discovery, and OpenAPI: allowed `github` in
`assertChatProviderEnabledForCreate`, `assertIdentityProviderEnabled`,
`assertIdentityLinkAccess`, and `connection-intents` discovery without
experimental flags while keeping `enableChatConnectors` enforcement for
experimental chat providers; updated the OpenAPI endpoint description.
- `ui` and Storybook: removed the **GitHub review bots** Experimental
settings toggle card; simplified `useChatConnectorsEnabled` and
`chatProviderVisible` so `github` and `github-code-review-bot` are
always visible; bypassed experimental loading wait for `provider=github`
in `ChatConnectorsExperimentalGate`; made the classic Agent Detail
Channels tab and `AgentChannelsPanel` empty-state copy always reflect
available agent identities; updated `canEnterAppsConnect`, `Browse`,
`ConnectionSetupFlow`, and `github-connections.stories.tsx`.
- Tests, E2E, runner-e2e, docs, and maps: updated unit, integration,
managed-overlay, runner-e2e, and Playwright E2E specs; refreshed
`tests/runner-e2e/source-sdk-public-inputs.json`; updated
`doc/connections/GITHUB.md`, `doc/connections/GITHUB-REVIEW-BOT.md`, and
`maps/feature-map/chat-channels.md`.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/server
typecheck && pnpm --filter @paperclipai/ui typecheck` — passed.
- `node scripts/check-maps.mjs && node scripts/storybook-catalog.mjs` —
passed.
- `pnpm vitest run packages/shared/src/validators/instance.test.ts
packages/shared/src/connector-availability.test.ts
packages/shared/src/feature-catalog.test.ts
server/src/__tests__/instance-settings-service.test.ts
server/src/__tests__/instance-settings-managed-overlay.test.ts
server/src/__tests__/instance-settings-cloud-defaults.test.ts
server/src/routes/chat-channels.identity.test.ts
server/src/__tests__/connection-intents-service.test.ts
server/src/__tests__/chat-channels/slack-ingress-and-threads.integration.test.ts
server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts`
— all passed.
- `pnpm vitest run ui/src/pages/apps/app-connect-policy.test.ts
ui/src/components/chat/ExternallyConnectedTaskBanner.test.tsx
ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx` —
3 files, 62 tests passed.
- `pnpm --dir tests/runner-e2e vitest run github-review-journey.test.ts`
— 56 tests passed.
- `pnpm verify --explain` — confirmed
`tests/runner-e2e/source-sdk-public-inputs.json` is current; exited 2
for broad CI coverage (handled by required GitHub CI gates on this PR).

## Risks

- Behavioral shift: instances that had `enableGitHubReviewBots` off now
show GitHub Code Review Bot in Connectors and allow authorized users
with `tools:manage_connections` to configure GitHub review bots.
Existing permission boundaries (`tools:manage_connections`, company
scoping, GitHub App OAuth/installation consent) are unchanged.
- `useIssueChatBinding` now queries `/api/issues/:issueId/chat-binding`
for normal tasks even when `enableChatConnectors` is off so GitHub-bound
task banners remain visible; experimental chat bindings remain filtered
out by `chatProviderVisible` while `enableChatConnectors` is off.
- No database migration is required; stored `enableGitHubReviewBots`
JSON values become inert.

> 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

- Google Gemini (high reasoning) in Antigravity, 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
- [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
2026-11-25 16:01:38 -06:00
DottaandClaude Opus 5.5 73369c5d46 feat(connections): AWS connector out of experimental; role ARN comes back from the agent (#22994)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The AWS connector lets agents work in an AWS account through AWS's
hosted MCP server, with a per-connection role and short-lived
credentials (#22083, #22195, #22233, #22626)
> - It has been behind the `enableAwsConnector` experimental setting. It
is now proven on paperclip.staging: a connection was set up end to end,
and the daily QA routine's agent uses it to read private test evidence
from S3
> - On the role step, the person still had to paste the role ARN back,
even when their own agent created the role and reported the ARN in its
live checklist
> - This pull request takes the connector out of experimental and has
the page pick up the role ARN from the agent, keeping the field for
people who set the role up by hand
> - The benefit is AWS available to everyone, with a setup that is
"paste a prompt, press Test connection"

## Linked Issues or Issue Description

Refs #22233 (role setup), #22626 (live agent checklist).

**Subsystem affected**
Connections (AWS app definition, role setup UI), instance experimental
settings.

**Problem or motivation**
- The AWS connector works, but is hidden unless an operator turns on an
experimental flag.
- The setup page always showed a Role ARN field, and the person had to
copy the ARN from the agent's summary into it.

**Proposed solution**
- Remove `experimentalFeatureKey` from the AWS app definition.
`enableAwsConnector` becomes a compatibility key: stored and
Cloud-managed values are ignored, and old clients' writes are accepted
(same pattern as `enableMcpAggregators` and `enablePublicMcp`).
- Move the Role ARN field into "Or do it by hand". When the agent
finishes, take the ARN from its finish summary, accepting only an IAM
role ARN for this connection's own role name
(`paperclip-<connectionId>`), so a summary cannot point the connection
at another role. "Test connection" then works with nothing to paste. The
by-hand section opens on its own when a test fails or the agent finished
without a usable ARN.

**Alternatives considered**
- Letting the agent save the ARN through the checklist API: more surface
on a token-only route. Reading it from the finish summary needs no new
API, and the test still proves the role trusts only this connection.
- Removing the field entirely: people who use CloudFormation or IAM by
hand still need it.

## What Changed

- `packages/shared/src/app-definitions/aws.json`,
`scripts/app-definition-overrides/aws.json`: no
`experimentalFeatureKey`.
- `packages/shared/src/feature-catalog.ts`, `validators/instance.ts`:
`enableAwsConnector` is "(compatibility)", default on.
- `server/src/services/instance-settings.ts`: always on; Cloud-managed
values skipped; old clients' writes accepted.
- `ui/src/pages/InstanceExperimentalSettings.tsx`: the AWS toggle is
removed.
- `ui/src/features/connections/aws-role-arn.ts` (new): the role ARN rule
and `roleArnFromAgentSummary`.
- `ui/src/features/connections/AwsRoleSetup.tsx`: Role ARN under "Or do
it by hand", auto-filled from the agent's summary, with copy updated
("hands back the role when it finishes", "the Role ARN field below").
- `doc/connections/AWS.md`: no longer described as experimental.

## Verification

- Server: `aws-mcp-connector.test.ts` (connects even with a stored
`enableAwsConnector: false`),
`instance-settings-managed-overlay.test.ts` (stays on with stored and
Cloud-managed false; an old client's false write is accepted),
`instance-settings-service.test.ts`: 68 passed. The 4 new flag tests
fail against master's source (red/green).
- Shared: `app-definitions.test.ts` 43 passed;
`scripts/app-definition-overrides.test.mjs` 3 passed.
- UI: `aws-role-arn.test.ts` 3 passed (this connection's ARN from a
summary, including role paths and a trailing period; another role, a
longer name, a short account and no ARN are rejected). UI typecheck
clean.
- Storybook (headless Playwright, current branch): the default view has
no Role ARN field; "agent done" shows "Your agent's role is ready. Test
the connection to finish." with Test connection enabled; "test failed"
opens "Or do it by hand" with the field at its end. No page errors.
- Live: the connector was set up end to end on paperclip.staging (Test
connection passed) and is in daily use by the QA routine. To re-check
after deploy without the flag.

## Risks

- Every instance now shows the AWS connector. It was already proven on
staging; access is per connection and read-only connections are capped
by AWS's `ReadOnlyAccess`.
- The ARN auto-fill trusts only an ARN naming this connection's own
role, and Test connection still verifies AWS accepts it, so a wrong or
foreign ARN cannot be saved silently.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, Storybook with headless Playwright, the live staging
instance).

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:44:59 -06:00
87fadcb108 feat(annotations): one-tap reactions on artifact comments (#22989)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - People review agent artifacts (plans, documents, routine
descriptions, and case documents) with inline annotation comments
> - Today a person must type a full reply to say "done", "checked",
"looks good", or "I have a question"
> - This slows down quick review feedback, and a question inside a reply
does not automatically bring the assignee back
> - This pull request adds four one-tap reactions to each annotation
comment: Done, Check, Thumbs up, and Question
> - A person's first Question reaction on an open task saves a durable
wake receipt and wakes the task's assignee in a dedicated follow-up run
to reply in that comment's thread (respecting chat ownership and wake
rate limits)
> - The benefit is fast review feedback without extra typing, while
agents can read and set the same reactions through the API

## Linked Issues or Issue Description

Refs #21637 (supersedes on current `master` with renumbered Drizzle
migration, OpenAPI/experimental route contracts, durable wake receipts,
chat ownership and rate-limit hardening, and current UI test suite)
Refs #9336 (agent wake notifications for document annotation threads)
Refs #9674 (agents cannot read inline document review comments)

**What problem does this solve?**
A reviewer cannot quickly acknowledge or question an annotation comment
on an artifact. A short answer requires a typed reply, and nothing tells
the agent that a person has a question about a comment.

**Proposed solution**
Add four fixed reactions per annotation comment: `done`, `check`,
`thumbs_up`, and `question`. One tap adds a reaction and a second tap
removes it. Each person or agent can add each reaction once per comment.
A person's first `question` reaction on an open task commits a durable
wake receipt in the same transaction and wakes the assignee once in a
dedicated follow-up turn, with the comment included in the wake context.

**Alternatives considered**
Free-form emoji reactions. Fixed named reactions keep the API contract
stable for agents and avoid storing arbitrary emoji strings on the
server.

## What Changed

- `packages/db`: Added `document_annotation_comment_reactions` table
(`company_id`, `comment_id`, `reaction`, `actor_type`, `actor_id`,
`created_at`, `removed_at`) with check constraints, cascade delete on
comment deletion, and unique `(comment_id, reaction, actor_type,
actor_id)` index. Generated online-compatible migration
`0510_clear_speedball.sql`, refreshed Drizzle snapshot
`0510_snapshot.json`, and pruned `0505_snapshot.json`.
- `packages/shared`: Added `DOCUMENT_ANNOTATION_COMMENT_REACTIONS`,
`DocumentAnnotationCommentReactionName`,
`DocumentAnnotationCommentReactionActor`,
`DocumentAnnotationCommentReactionSummary`, optional `reactions` on
`DocumentAnnotationComment`, and
`documentAnnotationCommentReactionSchema`.
- `server`: Added `setCommentReaction` in `document-annotations.ts`
using soft-delete (`removed_at`) and upsert revival (`(xmax = 0)` for
`firstAdd`), and attached reaction summaries (`count`, `actors`,
`reactedByMe`) to thread/comment reads.
- `server` routes & contracts: Added `PUT` and `DELETE
.../annotations/:threadId/comments/:commentId/reactions/:reaction` for
issues, routines, and cases, registered them in `openapi.ts`,
`experimental-api-metadata.ts`, and `experimental-api-paths.ts`, and
logged activity (`*.document_annotation_comment_reaction_added` /
`_removed`) only when a row changes.
- `server` durable wake, chat ownership, rate limits &
`packages/adapter-utils`:
- A person's first `question` reaction on an open assigned issue inserts
a recoverable `deferred_issue_execution` receipt in
`agent_wakeup_requests` in the same DB transaction
(`annotation-question-reaction:<id>`), passes `executionWaitRequestId`
to `heartbeat.wakeup` (`reason: "issue_commented"`, `allowRunCoalescing:
false`), resumes via `resumeDeferredExecutionReceipts` if immediate wake
fails, and defers behind busy turns without duplicating receipts.
- Recognized human annotation question reactions
(`isHumanAnnotationQuestionWake`) as an independent wake cause for idle
waiting agent chats while strictly enforcing chat ownership
(`!conversationAgentId || conversationUserId === actorId`) across
service, route, wake preflight, locked admission, and recovery queries.
- Bounded distinct-comment question wakes under `issues ... FOR UPDATE`
to at most 1 pending/in-flight wake per `(companyId, issueId, agentId)`
and at most 3 original question receipts (`idempotency_key LIKE
'annotation-question-reaction:%'`) per `(companyId, issueId, user)` in a
rolling 10-minute window.
- `renderPaperclipWakePrompt` instructs the agent to answer the question
in the annotation thread.
- `ui`: Added four one-tap reaction buttons (`✅`, `✔️`, `👍`, `❓`) under
each non-optimistic annotation comment in `DocumentAnnotationPanel` /
`DocumentAnnotationPopover`, with counts, `aria-pressed`, hover tooltips
naming actors, optimistic updates, client-scoped write serialization
across panel/popover remounts (`WeakMap<QueryClient, Map<string,
TargetReactionState>>`), live-update refetch overlay preservation,
deferred invalidation while writes are pending, and updated Storybook
fixture.
- `docs/api` & `tests/runner-e2e`: Documented the reaction endpoints and
wake bounds in `docs/api/issues.md` and `docs/api/routines.md`, and
refreshed `tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `pnpm --filter @paperclipai/db run check:migrations` and
`migration-compatibility.ts`: `0510_clear_speedball.sql` classified
`online_compatible`.
- `pnpm --filter @paperclipai/db exec vitest run
src/migration-snapshot-drift.test.ts
src/migration-compatibility.test.ts`: passed (117/117).
- `pnpm --filter @paperclipai/adapter-utils exec vitest run
src/server-utils.test.ts -t "question reaction"`: passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/document-annotations-service.test.ts` (20/20, embedded
Postgres — covering durable wake recovery, idle waiting-chat wake,
busy-turn deferral, non-owner chat wake denial, and rolling-window +
pending-backlog wake bounds across full queue admission),
`src/__tests__/document-annotation-routes.test.ts` (20/20),
`src/__tests__/routine-document-annotation-routes.test.ts`,
`src/modules/wake-queue/application/issue-wake-admission.test.ts`
(15/15), and `src/modules/wake-queue/domain/policy.test.ts`: all passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/openapi-routes.test.ts`: passed (59/59).
- `pnpm --filter @paperclipai/ui exec vitest run
src/hooks/useDocumentAnnotationMutations.test.tsx`: passed (9/9,
covering optimistic updates, serialized writes across remounts,
live-update refetch preservation, deferred invalidation across comments,
and rendered `ThreadCard` DOM buttons/toggles).
- Package typechecks (`@paperclipai/shared`, `@paperclipai/db`,
`@paperclipai/adapter-utils`, `@paperclipai/server` all 7 layers,
`@paperclipai/ui` + Storybook catalog): all passed.
- `pnpm check:token-gates`, `node scripts/check-module-boundaries.mjs`,
and `node scripts/check-test-budget.mjs`: all passed.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check`: in sync (`inputs: 579, changed: false`).
- Full-stack Playwright verification against a throwaway local server +
embedded PostgreSQL: created a task, `plan` document, and annotation
thread; verified invalid reaction returns `400`; clicked `thumbs_up` and
`question` in the real document viewer; reloaded to prove PostgreSQL
persistence; toggled `thumbs_up` off and reloaded to verify removal
persisted.
- PR CI on `4d892c8067`: 83/83 executed checks passing (including `ci /
verify`, `ci / e2e` + all 16 E2E shards, all General/Serialized server
shards, `Build`, `Typecheck + Release Registry`, `Verify Paperclip
Runner`, `Superagent Security Scan`, and `Greptile Review` 5/5 with 0
unresolved threads).

## Risks

- Low risk. Migration `0510_clear_speedball.sql` only creates a new
table and its indexes (`online_compatible`), so running releases are
unaffected.
- `reactions` is optional on `DocumentAnnotationComment`, preserving
backward compatibility for existing clients.
- Question wakes are bounded by soft-delete revival (`firstAdd`), chat
ownership enforcement, single pending/in-flight wake per `(companyId,
issueId, agentId)`, and at most 3 original question wakes per
`(companyId, issueId, user)` per 10-minute window.

> 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

- Google Gemini (`gemini-3-pro` / Antigravity agentic coding environment
with shell execution, file editing, embedded PostgreSQL, and Playwright
verification), rebasing and extending prior work originally authored
with Claude Opus 5.5 in #21637.

## 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: lucktastic <13757243+lucktastic@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 15:33:38 -06:00
DottaandPaperclip 0f52d90993 fix(github): detect writes outside GitHub App installations and stop advising Refresh access (#22978)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agents use managed GitHub App connections through the tool gateway
to open issues, post comments, and perform approved writes on GitHub
repositories.
> - A GitHub App user-to-server token can write only to repositories
inside accounts where the Paperclip GitHub App is installed; even on a
public third-party repository, GitHub rejects writes with `403 Resource
not accessible by integration`.
> - Previously, Paperclip did not check the App's installed accounts
before posting an approval card, mapped every `403 Resource not
accessible by integration` to `github_access_denied`, and told both the
user ("Manage GitHub access") and the agent ("select Refresh access") to
repair access through a flow that cannot reach third-party
organizations.
> - This wastes human approvals on doomed writes and sends operators
into a dead-end permission refresh loop.
> - This pull request adds a pre-check before posting approval cards for
managed GitHub App writes outside installed accounts, distinguishes
`github_repo_outside_app_installations` and
`github_app_installation_suspended` from `github_access_denied` across
server classification, MCP routes, and continuation delivery, and
renders accurate UI guidance without a misleading "Manage GitHub access"
link for external repositories.
> - The benefit is that unreachable external-org writes fail immediately
with actionable alternatives (post directly on GitHub, use a PAT
connection, or have an org admin install the App and refresh access),
suspended installations get explicit unsuspend guidance, and missing
repository grants on installed organizations keep the existing "Manage
GitHub access" and "Refresh access" repair flow.

## Linked Issues or Issue Description

No public issue exists. Refs #19315, #19655, #20141.

**What happened?**
When an agent requested an approval-gated GitHub write targeting a
public repository owned by an external organization where the Paperclip
GitHub App was not installed, Paperclip posted a normal approval card.
After the user approved it, GitHub returned `403 Resource not accessible
by integration`, and both the failed approval card and agent
continuation instructions advised clicking "Manage GitHub access" and
"Refresh access", which cannot grant write access to a third-party
organization.

**Expected behavior**
Paperclip should check managed GitHub App write targets against the
grant's installed accounts before posting an approval card, fail
unreachable external-organization writes cleanly without wasting an
approval, preserve suspended installations separately with unsuspend
guidance, keep incomplete webhook-invalidated snapshots on
`github_access_denied` until refreshed, and present accurate
alternatives in both the UI card and agent continuation instructions.

**Steps to reproduce**
1. Connect GitHub via the managed GitHub App installed on one
organization (for example `acme`), with an approval policy on GitHub
writes.
2. Ask an agent to run `create_issue` or `add_issue_comment` targeting a
repository in an external organization where the App is not installed
(for example `external-org/public-repo`).
3. Previously, Paperclip posted an approval card, executed it upon
approval, received `403 Resource not accessible by integration`, and
showed "GitHub access needed" / "Manage GitHub access" plus "Refresh
access" instructions.

**Paperclip version or commit**
`2d065677959b` (`master`, merged cleanly with `331e1a9fd3`)

**Deployment mode**
Local / Paperclip Cloud managed GitHub App connection

## What Changed

- `server/src/services/tool-access/github-access-discovery.ts`,
`packages/db/src/schema/tool_access.ts`,
`packages/shared/src/types/tool-access.ts`,
`packages/shared/src/validators/tool-access.ts`: Preserved suspended
installation owner logins separately in optional
`suspendedInstallationOwnerLogins` so active `installationOwnerLogins`
stays unchanged while suspended orgs are distinguishable from
uninstalled orgs. Added `github_repo_outside_app_installations` to
`ToolAccessReasonCode` and updated
`tests/runner-e2e/source-sdk-public-inputs.json`.
- `server/src/services/tool-access/github-access-errors.ts`: Added
`github_repo_outside_app_installations`,
`github_app_installation_suspended`, `isGitHubAccessErrorCode`,
`extractGitHubTarget` (`owner`+`repo`, `repository: "owner/repo"`,
`organization`/`org`, `fork_repository` destination-only handling, and
GitHub API URL fallback), `suspendedManagedGitHubOwner`,
`findUnreachableManagedGitHubTarget`,
`githubOutsideAppInstallationsInstructions`,
`githubSuspendedInstallationInstructions`, and
`githubAccessErrorInstructions`. Webhook-invalidated/incomplete
snapshots (`bindingSync` set or `installationIds` ahead of
`installationOwnerLogins` with `repositories` cleared) skip pre-check
blocking and stay on `github_access_denied` on runtime `403` until
access is refreshed.
- `server/src/services/tool-access-policy.ts` and
`server/src/services/tool-gateway.ts`: Reused the already-resolved
remote tool context from `resolveGovernedToolCall` (avoiding redundant
connection/grant lookups for non-GitHub providers), routed unreachable
approval-requiring managed GitHub writes through the canonical policy
denial path with `{ claimIdempotencyKey: false }` (inserting
`idempotencyKey: null` atomically in the single `INSERT` so retries
after installing the App are never falsely replayed), and propagated
`github_repo_outside_app_installations` /
`github_app_installation_suspended` (HTTP 403) without echoing raw
provider text into trusted instructions.
- `server/src/routes/tool-gateway.ts`,
`server/src/services/tool-action-delivery.ts`,
`server/src/services/continuation-cause.ts`,
`server/src/services/agent-task-run-telemetry.ts`: Treated all GitHub
access error codes as MCP `tools/call` `isError: true` results, routed
continuation wakes through `githubAccessErrorInstructions`, and
registered `github_repo_outside_app_installations` and
`github_app_installation_suspended` as person-owned `missing_access`
failure codes.
- `ui/src/components/IssueThreadInteractionCard.tsx` and
`ui/storybook/stories/questions-and-approvals/connection-reviews.stories.tsx`:
Added dedicated alert states for `github_repo_outside_app_installations`
("Repository outside GitHub App access", omitting dead-end "Manage
GitHub access") and `github_app_installation_suspended` ("GitHub App
installation suspended", with unsuspend guidance and "Manage GitHub
access"), using existing design tokens only, while keeping "GitHub
access needed" for `github_access_denied`.
- `doc/connections/GITHUB.md`: Documented pre-check, suspended
installation, incomplete webhook snapshot, and error classification
behavior.
- Added unit, UI component, and embedded-Postgres integration tests in
`server/src/services/tool-access/github-access-errors.test.ts`,
`server/src/__tests__/github-grant-metadata.test.ts`,
`server/src/__tests__/tool-gateway.test.ts`,
`server/src/__tests__/tool-gateway-action-approvals.test.ts`, and
`ui/src/components/IssueThreadInteractionCard.test.tsx`.

## Verification

- `pnpm vitest run
server/src/services/tool-access/github-access-errors.test.ts
server/src/services/tool-access/github-default-owner.test.ts
server/src/__tests__/github-grant-metadata.test.ts
ui/src/components/IssueThreadInteractionCard.test.tsx`: 4 files, 140/140
passed.
- `pnpm vitest run server/src/__tests__/tool-gateway.test.ts -t
"GitHub"`: 13/13 passed (covers pre-check blocking with atomic
`idempotencyKey: null`, installed-org missing-repo
`github_access_denied`, direct + MCP HTTP route `isError: true`,
approved-card runtime 403 URL classification, post-install retry,
suspended installation `github_app_installation_suspended`, and
webhook-invalidated `bindingSync` snapshot pass-through).
- `pnpm vitest run
server/src/__tests__/tool-gateway-action-approvals.test.ts -t "tells the
agent how to recover from"`: 9/9 passed (including
`github_repo_outside_app_installations` and
`github_app_installation_suspended` continuation wakes).
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/db typecheck && pnpm --filter @paperclipai/server typecheck
&& pnpm --filter @paperclipai/ui typecheck`: passed (0 errors across all
7 server layers, shared, db migration safety/compatibility, and UI +
Storybook catalog).
- `pnpm check:token-gates`: all 4 gates clean.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
6714ad6b68 --check`: passed (`changed:
false`, 578 inputs).
- `node scripts/check-test-budget.mjs --files
server/src/services/tool-access/github-access-errors.test.ts
server/src/__tests__/github-grant-metadata.test.ts
server/src/__tests__/tool-gateway.test.ts
server/src/__tests__/tool-gateway-action-approvals.test.ts
ui/src/components/IssueThreadInteractionCard.test.tsx`: PASS (`113
nightly suites validated, 5 test file(s) checked`).
- PR CI on `6714ad6b68`: 81/81 executed checks passed (`0 failing, 0
pending, 0 cancelled, 6 skipped`), including `ci / verify`, `ci / e2e` +
all 16 E2E shards, all General tests, all 9 Serialized server shards,
all Verify Paperclip Runner lanes, `Build`, `Typecheck + Release
Registry`, `Superagent Security Scan`, `Socket Security`, `Contributor
trust`, `commitperclip`, `Snyk`, and `Greptile Review` (5/5, 0
unresolved threads).
- Not tested against a live GitHub App installation.

## Risks

- Low risk. No SQL database migration is required
(`suspendedInstallationOwnerLogins` is an optional property inside the
existing `connection_grants.provider_tenant` JSONB column, and
`errorCode` is already an open string field).
- Pre-check blocking only activates for approval-requiring non-read
writes on managed GitHub connections that have a complete, populated
grant snapshot (`login` and non-empty `installationOwnerLogins`, without
`bindingSync` invalidation). PAT connections, legacy/empty/incomplete
snapshots, installed organizations, suspended installations, the user's
own personal account, read tools, and upstream `fork_repository` source
repos retain their existing behavior.
- Pre-check denials insert `idempotencyKey: null` atomically so retrying
the same write after an org admin installs the App and access is
refreshed never hits a stale denial replay.

## Model Used

- Google Gemini (Antigravity agent) with tool use and local code/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
- [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>
2026-11-25 15:33:31 -06:00
Dotta 38e3a71669 fix(connections): use Slack MCP user OAuth flow and surface OAuth errors in setup UI (#22976)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Apps and Connections let operators connect external providers
through remote MCP servers and OAuth.
> - Slack's curated `mcp-oauth` method pins Slack's bot install
endpoints (`oauth/v2/authorize` and `oauth.v2.access`) while sending
user-only scopes (`search:read.public`, `search:read.private`, etc.) in
`scope`, so Slack rejects sign-in with `"Invalid permissions
requested"`.
> - In addition, when OAuth fails or returns an error for a
customer-owned OAuth app like Slack, `ConnectionSetupFlow`'s `KeyStep`
drops `oauthError` completely, hiding the failure banner, and
`OAuthClientFields` hides the method's `guidanceMd` prerequisites.
> - This pull request switches Slack's `mcp-oauth` method to Slack's
documented MCP user OAuth endpoints (`oauth/v2_user/authorize` and
`oauth.v2.user.access`), propagates allowlisted RFC OAuth
`providerError` codes without reflecting untrusted provider prose,
displays OAuth errors and popup fallback links on `KeyStep`, and renders
setup prerequisites (`guidanceMd`) beside customer OAuth fields.
> - The benefit is that customer-owned Slack MCP sign-in succeeds
(including when resuming pre-fix drafts) and any OAuth error or Slack
MCP prerequisite is clearly shown to the user.

## Linked Issues or Issue Description

Fixes: #13935
Refs #17258
Refs #14037

Builds on #17258 (`fix/slack-mcp-user-oauth-flow`) and adds the missing
customer-OAuth error surface and setup guidance in
`ConnectionSetupFlow`.

## What Changed

- Updated `packages/shared/src/app-definitions/slack.json` and
`scripts/ingest-app-definitions.mjs` so Slack's `mcp-oauth` method uses
`https://slack.com/oauth/v2_user/authorize` and
`https://slack.com/api/oauth.v2.user.access`, and added Slack MCP
prerequisites (`User Token Scopes`, callback URL, and `Model Context
Protocol`) to `guidanceMd`.
- Updated `server/src/routes/tool-access.ts` to propagate allowlisted
RFC `providerError` codes (`normalizeOAuthProviderError`, excluding
`unrecognized`) via `provider_error` on OAuth recovery redirects and
connection-intent postMessages, while continuing to never read or
reflect untrusted `error_description` or `error_uri`.
- Updated `ui/src/features/connections/ConnectionSetupFlow.tsx` and
`ui/src/lib/oauthWindowOutcome.ts` so:
- `KeyStep` renders `oauthError` (not only `connectMutation.error`) and
the `"Open sign-in in a new tab"` fallback link when popups are blocked.
- `oauthCallbackErrorMessage` and `oauthFailureMessage` map allowlisted
`providerError` values (such as `invalid_scope`, `invalid_redirect_uri`,
`invalid_client`) and Paperclip failure codes (including
`slack_mcp_access_disabled`) to actionable Paperclip-authored copy.
- Opener popup polling reads same-origin failure `code` and
`provider_error` details from the returned callback URL.
- `OAuthClientFields` renders `method.guidanceMd` for required
customer-owned OAuth apps whose client secret is optional.
- Updated `tests/runner-e2e/source-sdk-public-inputs.json` for the
changed `@paperclipai/shared` sources.
- Updated Slack OAuth test fixtures in
`server/src/__tests__/tool-access-service.test.ts` and
`server/src/services/tool-access/oauth/client-settings.test.ts`, and
added regressions in `packages/shared/src/app-definitions.test.ts`,
`server/src/__tests__/tool-access-service.test.ts`,
`ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts`, and
`ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx`.

## Verification

- Shared, UI, and OAuth client-settings unit + DOM tests (95/95 passed):
- `pnpm exec vitest run packages/shared/src/app-definitions.test.ts
ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts
ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx
ui/src/features/connections/ConnectionSetupFlow.architecture.test.ts
server/src/services/tool-access/oauth/client-settings.test.ts`
- Embedded-Postgres server OAuth start + legacy-draft upgrade + callback
error redirect + redaction tests:
- `pnpm exec vitest run server/src/__tests__/tool-access-service.test.ts
-t "uses Slack user OAuth endpoints even for legacy drafts|starts OAuth
from|refreshes|personal|slack"` (33 passed)
- `pnpm exec vitest run
server/src/__tests__/generic-mcp-connection.test.ts -t "returns browser
denials|denied and cancelled callbacks|redacts"` (9 passed)
- Typechecks & guardrails:
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` (all passed)
- `node scripts/check-test-budget.mjs --files
packages/shared/src/app-definitions.test.ts
server/src/__tests__/tool-access-service.test.ts
server/src/services/tool-access/oauth/client-settings.test.ts
ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts
ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx`
(PASS)
- `pnpm verify --base 2d06567795
--explain` (exit 2 due to `scripts/ingest-app-definitions.mjs` being a
global CI input; `tests/runner-e2e/source-sdk-public-inputs.json`
verified in sync; sharded PR CI supplies broad repo coverage).

## Risks

- Low risk. The endpoint change applies only to Slack's `mcp-oauth` tool
method; Slack chat-channel setup and Slack search OAuth retain their
existing bot/user flows.
- Resuming a pre-fix Slack MCP draft automatically re-resolves the
updated `v2_user` endpoints from the catalog definition during
`startOAuth` and overwrites the stored bot URLs.
- Only allowlisted RFC OAuth error codes (`normalizeOAuthProviderError`)
are forwarded in `provider_error`; untrusted provider
`error_description` and `error_uri` values are never read or echoed.

## Model Used

- Claude Opus 4.6 by Anthropic (in Antigravity with tool use, shell
execution, and file editing). Used for root-cause analysis, test-driven
implementation, and local verification.

## 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
2026-11-25 15:33:26 -06:00
DottaandPaperclip 64bef50be0 feat(cloud): add Cloud starter inference proxy, migration modal, and PostHog A/B telemetry (#22966)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted Cloud onboarding currently requires new users to connect a
model provider subscription or API key before their first agent can run
> - That upfront credential step creates drop-off before a new user sees
their first agent do real work
> - We need an opt-in, managed Cloud capability that runs the first
agent right away through a server-side proxy, keeps the raw provider key
out of sandboxes and browsers, prompts the user to connect their own
provider when starter inference runs out, and measures treatment vs.
control in PostHog
> - This pull request adds the default-off `enableCloudTrialInference`
managed feature, the server-side OpenRouter reverse proxy with ephemeral
per-run tokens, the blocking model-connection and agent-migration modal
with Storybook stories, and Cloud-only PostHog A/B cohort and funnel
telemetry
> - The benefit is zero-friction first-agent onboarding on Cloud stacks
enrolled in the experiment, with automatic migration to the user's own
model provider and clean A/B observability

## Linked Issues or Issue Description

**Subsystem affected**

Cross-cutting (`packages/shared`, `packages/paperclip-runner`,
`server/`, `ui/`)

**Problem or motivation**

New Cloud users must connect an AI subscription or API key before they
can run their first agent. We want to A/B test letting eligible Cloud
workspaces start their first agent right away with managed starter
inference (OpenCode / GPT-6 Luna in Paperclip Runner) without exposing
any raw upstream API key to the sandbox, database, or browser, and then
guide the user to connect their own model provider when starter
inference runs out.

**Proposed solution**

Add an experimental managed feature flag (`enableCloudTrialInference`,
off by default on both Cloud and self-hosted) that:

- Routes starter-inference runs through a server-side OpenRouter reverse
proxy (`/api/internal/cloud-inference/v1/*`) authenticated with
ephemeral per-run bearer tokens so the raw OpenRouter key never leaves
server memory.
- Enforces the configured starter model, detects upstream HTTP 402
exhaustion, invalidates active run tokens, reports exhaustion back to
the Cloud control plane, and broadcasts `cloud_trial.status.updated`
over live events.
- Displays a blocking modal (`CloudTrialExhaustedModal`) when starter
inference runs out while agents still depend on it, lets the user
connect their own model provider, automatically migrates trial agents to
that provider's default harness and model, clears incompatible provider
sessions, and resumes paused work.
- Stamps the `cloud-trial-inference` (`treatment` / `control`) cohort
onto Cloud-only server and browser PostHog telemetry and records
Cloud-only funnel events (`$feature_flag_called`, `cloud_trial.started`,
`cloud_trial.key_issued`, `cloud_trial.exhausted`,
`cloud_trial.modal_shown`, `cloud_trial.migrated`,
`cloud_trial.migration_failed`) without affecting self-hosted telemetry.

**Alternatives considered**

- Passing a capped OpenRouter API key directly into the agent sandbox
environment: rejected because a sandboxed agent or user could read and
reuse the raw key outside Paperclip.
- Showing starter dollar amounts or a usage progress bar in the UI:
rejected in favor of a simple prompt asking the user to connect a model
provider to continue.

**Roadmap alignment**

Supports hosted onboarding activation experiments while staying strictly
gated behind a default-off managed feature flag (`cloudDefault: false`,
`selfHostedDefault: false`) so self-hosted installs and unflagged Cloud
stacks see zero behavior change.

**Additional context**

Paired with the private Cloud control plane key-management service PR
that provisions per-stack capped OpenRouter child keys and enforces
single-trial caps across accounts.

## What Changed

- **Shared contracts & feature flag (`packages/shared`)**:
- Added `enableCloudTrialInference` (`tier: "managed"`, `cloudDefault:
false`, `selfHostedDefault: false`) to `feature-catalog.ts`,
`types/instance.ts`, and `validators/instance.ts`.
- Added `packages/shared/src/cloud-inference.ts` with trial status
types, migration schemas, provider-to-harness migration defaults, and
telemetry event validation.
- Added `cloud_trial.status.updated` to `LIVE_EVENT_TYPES`,
`cloudTrialInference` to `agentRuntimeConfigSchema`, and optional
`cloudTrialInferenceEnabled` to `browserAnalyticsConfigSchema`.
- **Paperclip Runner (`packages/paperclip-runner`)**:
- Updated OpenCode server driver (`opencode-server-driver.ts`) and
`configured-environment.ts` to accept `PAPERCLIP_OPENROUTER_PROXY_URL`
and `PAPERCLIP_OPENROUTER_PROXY_TOKEN`.
- Updated `provider-failure.ts` to classify HTTP 402 as quota exhaustion
and redact `sk-or-` key material.
- **Server proxy, migration, and onboarding (`server/`)**:
- Added `server/src/services/cloud-trial-inference.ts` and
`server/src/routes/cloud-inference.ts` for server-memory key custody,
ephemeral per-run proxy tokens, model guard, HTTP 402 exhaustion
handling, agent migration, blocked-run resume, and company-scoped
status/migrate/telemetry routes.
- Wired proxy mounting in `server/src/app.ts`, runtime env & cleanup in
`heartbeat.ts` / `execution-configuration.ts`, `cloud_trial_exhausted`
error code in `run-completion.ts`, and starter-agent seeding in
`onboarding-seed.ts`.
- **PostHog A/B telemetry (`server/`, `ui/`)**:
- Resolved `cloudTrialInferenceEnabled` from `PAPERCLIP_MANAGED_CONFIG`
in `cloud-posthog-config.ts` and `cloud-posthog-browser.ts`.
- Stamped `cloud_trial_inference_enabled` and
`$feature/cloud-trial-inference` on `workspace` groups,
`cloud.workspace_started`, direct server PostHog events, and browser
PostHog super-properties plus `$set_once.cloud_trial_inference_cohort`.
- Added Cloud-only direct PostHog helpers (`trackCloudPostHogEvent`,
`trackCloudTrialExposure`) in `server/src/telemetry.ts` and wired
exposure + lifecycle funnel events (no-op on self-hosted).
- **UI & Storybook (`ui/`)**:
- Added `ui/src/api/cloud-inference.ts`, `CloudTrialExhaustedModal.tsx`,
`CloudTrialGate.tsx`, and optional `hideCancel` / `hideProviderHeading`
props on `AiProviderSetup.tsx`.
- Wired `CloudTrialGate` into `Layout.tsx` / `Layout.production.tsx`,
live-event invalidation into `LiveUpdatesProvider.tsx`, starter
onboarding card into `OnboardingWizard.tsx`, and the experimental card
into `InstanceExperimentalSettings.tsx`.
- Added Storybook stories in
`ui/storybook/stories/onboarding/cloud-trial-exhausted-modal.stories.tsx`
covering single agent, multiple agents, migrating, migration succeeded,
and migration error states.

## Verification

- `pnpm --filter @paperclipai/shared build`: passed.
- `pnpm --filter @paperclipai/paperclip-runner build`: passed
(TypeScript, protocol manifest, Cargo release build, replay golden
parity).
- `pnpm --filter @paperclipai/ui typecheck` & `node
scripts/storybook-catalog.mjs --check`: passed (372 files, 3484
stories).
- `pnpm --filter @paperclipai/server exec tsc --noEmit`: passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/cloud-trial-inference.test.ts
src/__tests__/cloud-posthog-config.test.ts
src/__tests__/cloud-posthog-browser.test.ts
src/__tests__/posthog-direct-event-shape.test.ts
src/__tests__/posthog-direct-telemetry.test.ts
src/__tests__/auth-routes.test.ts`: 6 files, 144/144 passed.
- `pnpm --filter @paperclipai/ui exec vitest run
src/lib/analytics/product-analytics.test.ts
src/lib/analytics/product-analytics-events.test.ts`: 2 files, 14/14
passed.
- Verified Storybook stories interactively in the embedded browser
(`ExhaustedSingleAgent`, `ExhaustedMultipleAgents`,
`MigrationSucceeded`) with passing `play()` interactions and zero
console errors, plus live end-to-end onboarding → exhaustion → blocking
modal → provider connect → agent migration flow against a mock
OpenRouter server.

## Risks

- **Default-off isolation**: `enableCloudTrialInference` defaults to
`false` everywhere, and Cloud stacks hide `instance.experimental.*`
controls by default, so existing self-hosted and unflagged Cloud stacks
have zero behavior change.
- **Key custody boundary**: Raw OpenRouter keys stay strictly in server
process memory; sandboxes only receive short-lived per-run proxy tokens
invalidated on run exit or exhaustion.
- **PostHog direct contract**: Existing self-hosted collector envelopes
remain unchanged; `posthog-direct-event-shape.test.ts` and
`product-analytics-events.test.ts` verify event shape and ownership
invariants.
- **CI coverage**: Broad workspace suites and E2E lanes were not run
locally and will run on PR CI.

## Model Used

- Google Gemini (Antigravity agentic assistant) with code editing,
terminal execution, browser verification, and test tools.

## 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 14:44:42 -06:00
TonioandClaude Fable 5.2 a336e295f6 feat(ui): turn Connectors into a Plugins marketplace (#22869)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents reach outside tools through connectors, which people add on
the Connectors page
> - That page is one long list. Each row mixes the catalog entry with
its accounts, so it is hard to scan and hard to tell what is installed
> - Some connectors also bring skills, but the page does not show them
> - This pull request renames the page to Plugins and changes the browse
view into a marketplace of small cards grouped by category. Each card
opens a plugin page that holds the accounts, the skills and the tool
permissions
> - The benefit is a catalog that people can scan fast, with one place
per connector for its accounts and its skills. Connector behavior does
not change

## Linked Issues or Issue Description

**Subsystem affected**

UI: the Connectors (Apps catalog) pages under `ui/src/pages/apps/` and
the navigation labels that point to them.

**Problem or motivation**

The Connectors browse page is a vertical list of large rows. A row shows
the catalog entry and every account under it. People must expand rows to
see what is connected. The page does not show which skills come with a
connector.

**Proposed solution**

- Rename the page from Connectors to Plugins in the navigation, the
breadcrumbs, and the page titles. A single app is still called a
connector.
- Remove the Browse / Review rail. The page header carries the title, a
Review shortcut, and an Add menu for a custom MCP server, a pasted
config, or an assistant connection.
- Show the catalog as a marketplace under one "All" tab: "Most used" and
"New and noteworthy" for first-party connectors, then one block per
category. Composio and Arcade connectors sit in the same blocks. A block
shows at most nine plugins, its total, and a "See all" link to a
category page at `/apps/category/:categoryId`.
- Use a compact card: logo, name, description, and one corner control.
The control is a plus to connect, a check when connected, or a warning
when an account needs attention.
- Open a plugin page at `/apps/plugin/:pluginKey` from each card. The
page has Connect in its header and groups Accounts, Connector, Skills,
Tool permissions, and Information as blocks. Tool permissions shows a
connected account's actions as Reads and Writes, each with a group
policy and per-action policies.
- Start sign-in straight from the card for a one-click connector: one
OAuth method that Paperclip can start itself, with nothing to fill in
and no warning to read. The success screen states who can use the
connection and links to where that changes.
- Search reads plugin titles only.
- Keep the account list on the Installed filter.

**Related pull requests**

A search of open and closed pull requests for the Connectors browse
page, a plugins or connectors marketplace, connector categories, and
one-click sign-in found no duplicate. #22863 compresses connector logo
files and does not overlap with these pages.

**Alternatives considered**

- An experimental setting that keeps the old page. The product owner
chose to replace the page for everyone.
- A new backend link between connectors and catalog skills. This pull
request stays in the front end. The pairing for GitHub is a constant in
`PluginSkills.tsx`.
- Real categories for Composio apps. Its public catalog file has names
only, so those apps are sorted by keywords in the name and the rest go
to "Other". Arcade's catalog states a category, which is now carried
through `AggregatorAppCatalogEntry.category`.

## What Changed

- `Browse.tsx`: keeps all data loading, connect logic, and dialogs. The
render now has five views: marketplace, category page, flat results
grid, Installed list, and plugin page. The default source is `all`; the
`paperclip` source is removed.
- `PluginMarketplace.tsx` (new): `PluginTile`, `PluginShelf` (count and
"See all"), `PluginCategories`, and the category labels.
- `PluginsHeader.tsx` (new): page title, Review shortcut with the
pending count, and the Add menu.
- `PluginPageSections.tsx` (new): plugin page header, Connector row, and
Information facts read from the app definition.
- `PluginPermissions.tsx` (new): Reads and Writes blocks for a connected
account. Saves go through `useConnectionPermissionSave` and restate
agent access exactly as the per-connection page does. The four helpers
it shares with that page moved from `AppDetail.tsx` to
`app-detail/saved-permissions.ts` with no behavior change.
- `PluginSkills.tsx` (new): lists built-in connector skills, skills that
a connected server publishes, and paired catalog skills. "Add skill"
calls the existing catalog install endpoint.
- `plugin-categories.ts` (new): maps Arcade categories onto the Plugins
categories and guesses a category from the name for apps that state
none.
- `features/connections/one-click-oauth.ts` (new): the one-click rule
and the hand-over of the sign-in window from the card's click to the
connect flow. A browser only opens that window during a click, so the
card opens it and `ConnectionSetupFlow` takes it over. If the window is
blocked, or the page is reloaded, the ordinary confirmation screen
shows.
- `ConnectionSetupFlow.tsx`: takes the handed-over window, starts
sign-in when the app qualifies, and adds a "Change" link beside the
stated default on the success screen.
- `apps-rail.ts` (new), `AppsSidebar*.tsx`, `Layout*.tsx`: the
marketplace pages have no second rail. Chat setup and detail keep
theirs, and the developer pages keep one while a developer tab is on.
- `ConnectorCard`: new `variant="page"` that renders the accounts as one
block with "Add account" at the bottom.
- `ConnectorsToolbar.tsx`: source filters first, a wider "Search
plugins" field on the right.
- `App.tsx`, `Layout.tsx`, `Layout.production.tsx`: new
`apps/plugin/:pluginKey` and `apps/category/:categoryId` routes and
reserved subpaths.
- Navigation and breadcrumb labels: "Connectors" becomes "Plugins" in 19
files, and the instance plugin system becomes "System plugins".
- `packages/shared/src/aggregator-app-catalog.ts`: optional `category`
on a catalog entry, set from Arcade's catalog.
- `ui/storybook/prototypes/ConnectorCatalogNavigation.tsx`: keeps its
own five-source list so the older prototype still builds.
- Tests: label renames in the specs and stories that named Connectors or
"Search connectors". Seven specs now reach the custom-server setup
through the Add menu. New specs: `one-click-connect`, `plugins-browse`.
`apps-prosumer-mcp-flow` also covers the plugin page permissions and the
success-screen link.

Kept on purpose, so current flows and specs continue to work: the
`Connector list` list label, `data-app-slug` and `data-connected` on
each card, and the `<Verb> <App name>` button names.

## Verification

- `cd ui && pnpm typecheck`: pass.
- `pnpm run check:token-gates`: pass.
- `cd ui && npx vitest run`: 564 files, 7,059 tests pass, 1 skipped.
- `cd packages/shared && npx vitest run
src/aggregator-app-catalog.test.ts`: 9 tests pass.
- `PAPERCLIP_RUNNER_BINARY=/usr/bin/true npx playwright test --config
tests/e2e/playwright.config.ts` for the 15 spec files under
`tests/e2e/*.spec.ts` that touch the Plugins pages, plus
`one-click-connect` and `plugins-browse`: all pass (3 skipped by their
own conditions).
- Storybook: built this branch and master and ran the interaction tests
of the 253 stories in the files that mount the browse page. Master
passes 230; this branch passes the same 230. The 23 that fail do so on
master too.
- Manual: opened Plugins, a category page, a plugin page, the Installed
filter, and Review on a local instance.
- Not run locally: `execution-recovery/recovery.spec.ts`,
`in-feed-native/connections.spec.ts`, the runner e2e tests, and the
repo-wide typecheck (it needs the Rust toolchain). A real provider
sign-in was not completed; the one-click test stops at the point the
flow starts. `pnpm verify` exits 2 and names CI as the source of broad
coverage.

## Risks

- The page changes for every user. People who know the old list must
learn the new layout. The Installed filter keeps the old account list.
- The instance plugin system is renamed "System plugins" in the settings
navigation, breadcrumbs, and its management page, so the two areas no
longer share a name. URLs and lower-case mentions of "plugin" inside
sentences are unchanged.
- One-click connect skips the screen that states the access default
("Connects for everyone in your organization, available to all agents")
and offers Change. The default is applied without being shown first; the
success screen states it and links to the permissions page.
- Most Composio apps (about 1,100 of 1,583) land in "Other", and the
keyword guess is sometimes wrong. Correct categories need category data
in the catalog file.
- The plugin page can now save action permissions. It uses the same save
path and access derivation as the per-connection page and waits for all
four reads before it enables the controls. The account picker for
several accounts and the read-only view have no test.
- The Smoke Lab developer page has no link from the browse page; it is
reachable by URL.
- e2e specs that this pull request did not run locally can fail on
selectors. CI must confirm them.
- "New and noteworthy" is a fixed list in code. The catalog has no date
to sort by.
- Skill pairing is a front-end constant. Nothing records that a skill
came from a connector, so removing a connector does not remove the
skill.
- The per-connection permissions page is not restyled in this pull
request.

> 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 Fable 5.2 (`claude-fable-5-2`) through Claude Code, with tool
use, code execution, and subagents for read-only code search.

## 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)
- [ ] 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

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

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 19:16:24 +00:00
DottaandClaude Opus 5.5 a0d5f275af test(e2e): grade the question journey's saved reference by its complete token (#22949)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The daily QA staging smoke runs the `question-answer-resume` product
journey against a real agent
> - The board answers the agent's reference question with the text `Use
<marker>.`
> - The grader required the literal text `Use <marker>.` in the saved
note
> - Agents read `Use X.` as an instruction. Some save `Use X.`, others
save only `X`. Both notes are correct
> - This pull request grades the saved note by the complete marker
token, not by the answer's instruction wording
> - The benefit is that the smoke case no longer fails at random on a
correct note

## Linked Issues or Issue Description

**Describe the bug**
The QA staging smoke case `question-answer-resume` failed with
`journey_operation_failed`. The failed checks were
`question-resume.complete-evidence` and `question-document-reloaded`.

**Steps to reproduce**
1. Run the QA staging smoke journeys (full run on 2026-11-25).
2. The agent asks for a reference. The board answers `Use
AMBERjourney179560441987913f9fa70.`
3. The agent saves `Welcome to the club meetup this afternoon — we're
glad you're here; reference: AMBERjourney179560441987913f9fa70.`
4. The grader fails the note because it does not contain the word `Use`.

**Expected behavior**
A note that contains the complete submitted reference and the selected
time passes. A second campaign on the same day passed only because that
agent kept `Use` in the note.

**Additional context**
The private record also showed 4 `Invalid JSON body` responses. They
come from one failed `POST /api/issues/{id}/interactions` call that the
agent made itself, before it retried with a valid body and got 201. That
call is not the cause of the failure. The journey and the server route
are correct.

## What Changed

- Add `includesSubmittedReference` in
`tests/runner-e2e/question-resume-scoring.ts`. It matches the complete
marker token with no extra letters or digits on either side.
- Use it in `question-resume.complete-evidence` and in
`question-document-reloaded`.
- `waitForClarificationDocument` waits for the complete marker
(`submittedReferencePattern`), not for `Use <marker>.`. Before, a
correct note without `Use` timed out in the browser readback.
- Change the old unit test that rejected a note with only the marker. It
now accepts that note. New cases reject a shortened marker, an extended
marker, and a prefixed marker.

## Verification

- Red: the new cases failed on the old grader (3 failed, 144 passed).
The new readback case timed out on the old wait (1 failed, 3 passed).
- Green: `pnpm exec vitest run --config
tests/runner-e2e/vitest.config.ts` on the question-resume,
clarification, and question-documentation tests: 6 files, 170 tests
pass.
- `pnpm test:e2e:runner:typecheck` passes.
- After merge: a single-case `qa-staging-smoke.yml` run for
`question-answer-resume` on the new harness pin.

## Risks

Low risk. Test code only. The grader still requires the full marker. The
marker is a unique nonce, so a truncated or changed reference still
fails.

## 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>
2026-11-25 11:09:02 -06:00
DottaandPaperclip c5107f12fe feat(runner): flip Google Antigravity ACPX profile to qualified (#22939)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Runner executes native ACPX providers using
release-verified profiles, capability declarations, and provider packs
> - Google Antigravity is wired across Runner, server routes, UI
pickers, and remote provider packs, but its ACPX profile remained
`qualificationStatus: "pending"` behind operator candidate grants
> - The owner waived the paid-key `runner-e2e-paid` gate on 2026-11-25
so Google Antigravity can ship to staging and be tested there live
> - This pull request flips the Google Antigravity ACPX profile from
`pending` to `qualified` (profile revision 2), updates its capability
declaration while keeping `recovery: "unverified"`, enables ordinary
server/UI/pack admission without candidate grants, and updates tests and
qualification docs honestly
> - The benefit is that Google Antigravity enters the default
`linux-x64` remote provider pack and ordinary board setup/execution
flows on staging, while candidate-era v1 saved sessions are cleanly
rejected and unverified recovery/paid-key evidence remains honestly
labeled

## Linked Issues or Issue Description

Refs #22923
Refs #22935 (merge after #22935
`fix/per-turn-harness-on-warm-environment`)

**What existing behavior does this improve?**
Google Antigravity native ACPX profile qualification, remote
provider-pack assembly, and Paperclip Runner agent setup/admission
across `packages/paperclip-runner`, `packages/adapter-utils`,
`packages/adapters/codex-local`, `server`, `ui`, and `tests/runner-e2e`.

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
`packages/paperclip-runner/acpx-profiles.json` declares `antigravity` at
`agentProfileVersion: 1` with `qualificationStatus: "pending"`.
`PAPERCLIP_RUNNER_ACPX_PROFILES` marks `antigravity.qualified = false`,
remote `linux-x64` provider packs exclude Antigravity unless built with
`--candidate-providers=antigravity`, and server/Runner admission
requires a short-lived operator candidate grant.

**Proposed behavior**
Remove `qualificationStatus: "pending"` from `antigravity` and bump
`agentProfileVersion` from `1` to `2` so candidate-era v1 saved state is
refused permanently as `provider_state_incompatible`. Flip
`PAPERCLIP_RUNNER_ACPX_PROFILES.antigravity.qualified` to `true`, mark
`ACPX_CAPABILITY_PROFILES.antigravity` as `qualified` with `models:
"explicit-provider-verified"` while keeping `recovery: "unverified"`,
require an explicit provider model in config builders and server
validation, and admit qualified Antigravity through the ordinary ACPX
path without candidate grants.

**Reason and benefit**
Unblocks staging deployment and live testing of Google Antigravity under
the 2026-11-25 owner waiver of `runner-e2e-paid`, including default
`linux-x64` provider pack inclusion (local `darwin-arm64` continues to
use `paperclipai runtime setup antigravity`).

**Breaking changes**
Any candidate-era v1 Google Antigravity saved session state is
intentionally refused as `provider_state_incompatible` due to the
`agentProfileVersion` bump (`1` -> `2`).

## What Changed

- **Runner profile & generated contracts**:
- `packages/paperclip-runner/acpx-profiles.json`: removed
`qualificationStatus: "pending"` on `antigravity` and bumped
`agentProfileVersion` from `1` to `2`.
- Regenerated
`packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts` and
`packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs`
(`qualification_pending: false`).
- `packages/paperclip-runner/src/drivers/acpx/capability-profiles.ts`:
set `antigravity.qualification` to `"qualified"` and `models` to
`"explicit-provider-verified"` when released; kept `recovery:
"unverified"` (never claiming `session-load` without live proof).
- **Adapter utils & config builder**:
- `packages/adapter-utils/src/paperclip-runner-permissions.ts`: flipped
`PAPERCLIP_RUNNER_ACPX_PROFILES.antigravity.qualified` to `true`.
- `packages/adapters/codex-local/src/ui/build-config.ts`: added
`"antigravity"` to the explicit-provider-model validation check.
- **Server admission & routes**:
- `server/src/services/native-runtime/provider-profile.ts`: added
`antigravity: null` to `DEFAULT_ACPX_RUNNER_MODELS`, included
`antigravity` in explicit-model-required and qualified ACPX checks.
- `server/src/services/native-runtime/acpx-qualification.ts`:
short-circuited `resolveAntigravityCandidateAdmission` to return
`undefined` once `qualificationStatus !== "pending"`.
- `server/src/routes/agents.ts`: allowed qualified `antigravity` without
`experimental.enableNativeRunner` (matching Copilot and UI rules),
preserved empty model on provisional setup draft transitions, and
allowed `setupOnly` draft creation before model selection.
- **Tests**:
- Updated Runner TS/Rust tests (`profile-compatibility.test.ts`,
`candidate-provider-pack.test.mjs`, `release-provider-pack.test.mjs`,
`antigravity-provider-pack-smoke.test.mjs`,
`candidate-admission*.test.ts`, `antigravity-models.test.ts`,
`acpx-runtime-sidecar.test.ts`, `runner-core` Rust unit/integration
tests).
- Updated `@paperclipai/adapter-utils`,
`@paperclipai/adapter-codex-local`, `@paperclipai/server`,
`@paperclipai/ui`, and `tests/runner-e2e` (`catalog.test.ts`,
`controller-rolling-deployment.test.ts`) tests for qualified Antigravity
behavior.
- **Documentation & maps**:
- `doc/plans/2026-11-22-antigravity-qualification.md`,
`doc/plans/2026-11-25-antigravity-cloud-rollout.md`, and
`packages/paperclip-runner/README.md`: recorded the 2026-11-25 owner
waiver of `runner-e2e-paid` for staging verification while keeping all
`NOT RUN` paid-key rows honestly marked `NOT RUN` / deferred.
- Minimal in-place accuracy updates in
`maps/feature-map/instance-operations.md` and
`maps/agent-access-map/instance-operations.md` (`node
scripts/check-maps.mjs` passing).

## Verification

- `pnpm --filter @paperclipai/paperclip-runner build` (TS + Rust release
binary + `check:acpx-profiles`, `generate-antigravity-models --check`,
`check:protocol-types`,
capability/attestation/traceability/replay-golden checks) — passed.
- `pnpm --filter @paperclipai/paperclip-runner test:typescript:prep`
(468 tests) and focused Runner Vitest suites
(`acpx-runtime-sidecar.test.ts` 127/127, `antigravity-models.test.ts`
22/22, `candidate-admission*.test.ts`, `profile-compatibility.test.ts`,
`runnerd-codex-transport-antigravity-release.test.ts`, pack script
tests) — passed.
- Rust tests in `packages/paperclip-runner/runner`: `cargo fmt --all --
--check`, `paperclip_process_table` (3/3), `paperclip_runner_core --lib`
(670/670, skipping macOS-incompatible `task_memory::tests::monitor_*`),
`paperclip-runnerd` bin tests (11/11), and `acpx_provider_resolutions`
(12/12) — passed.
- `packages/adapter-utils` (`paperclip-runner-permissions.test.ts`
50/50) and `packages/adapters/codex-local` (`build-config.test.ts`
64/64) — passed.
- `scripts/__tests__/prepare-runner-release-image.test.mjs`, `node
scripts/check-maps.mjs`, and `node
tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check` — passed.
- Server suites: `adapter-routes.test.ts` (36/36), `registry.test.ts`
(67/67), `agent-adapter-validation-routes.test.ts` (`Antigravity|YAML`),
`antigravity-connection-probe.test.ts`,
`antigravity-save-refusal.test.ts`, `antigravity-release.test.ts`
(10/10), `acpx-qualification.test.ts` (39/39),
`antigravity-candidate-admission.test.ts`,
`remote-provider-pack.test.ts` (60/60),
`native-session-executor.test.ts` (`Antigravity|provider pack`),
`plugin-runner-credentials.test.ts`,
`plugin-runner-credential-names.test.ts`,
`antigravity-plugin-task-credential-writeback.test.ts` — passed.
- CLI (`runtime.test.ts`, `runtime-setup.test.ts` 15/15), UI (6
Antigravity/setup suites 58/58 + `AgentConfigForm.render.test.tsx`), and
`tests/runner-e2e` (`catalog.test.ts`,
`controller-rolling-deployment.test.ts`,
`antigravity-qualification.test.ts`, `eval-gateway-drain.test.ts`, and
690+ unit files) — passed.
- Typechecks: `@paperclipai/adapter-utils`,
`@paperclipai/adapter-codex-local`, `@paperclipai/paperclip-runner`,
`@paperclipai/server` (all 7 layers), `@paperclipai/ui`, and `pnpm
test:e2e:runner:typecheck` — all passed.
- **Not run locally**: Live paid-key `runner-e2e` suites
(`antigravity-qualification`, `antigravity-model-lineup`,
`antigravity-agent-journey`) were waived by the owner on 2026-11-25 to
enable staging testing and remain marked `NOT RUN` / deferred in the
qualification docs. Rust `task_memory::tests::monitor_*` cgroup tests
require Linux CI.

## Risks

- **Merge sequencing**: Merge after #22935
(`fix/per-turn-harness-on-warm-environment`) so warm environments keep
Antigravity on its per-turn lifecycle.
- **Deferred live qualification**: Paid-key `antigravity-qualification`
cells have not run in CI;
`ACPX_CAPABILITY_PROFILES.antigravity.recovery` remains `"unverified"`
until live multi-turn and restart continuity are verified on staging.
- **Profile version reset**: Bumping `agentProfileVersion` from `1` to
`2` intentionally rejects any candidate-era v1 saved sessions as
`provider_state_incompatible`; new runs start a clean replacement
conversation in the same workspace.
- **Remote provider pack targets**: Remote provider packs intentionally
target `linux-x64` (Core Docker images and Linux sandboxes); local
`darwin-arm64` hosts continue to provision via `paperclipai runtime
setup antigravity`.

> 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

- Google Gemini (Antigravity agent 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
- [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>
2026-11-25 09:02:06 -06:00
DottaandClaude Opus 5.5 1bea1eeaed fix(ai-connections): delete the saved Google Antigravity sign-in on disconnect (#22931)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - AI connections let a company sign in to a model provider, and Google
Antigravity uses a Google account sign-in with a long-lived refresh
token
> - When a user disconnected that account, or removed its connection,
Paperclip marked the grant revoked but kept the saved sign-in in its
database
> - The obvious fix, revoking the token at Google, is unsafe here: the
sign-in uses the OAuth client of Google's own Antigravity runtime, and
Google revocation removes the grant for that whole client
> - A revoke would sign the person out of their own Antigravity app or
CLI and out of every other Paperclip connection for that Google account
> - This pull request deletes Paperclip's saved sign-in on disconnect
and removal, does not call Google, and says plainly that the sign-in
stays valid at Google until the person removes it there
> - The benefit is that "disconnect" does what the person expects in
Paperclip, never breaks their other tools, and never leaves a usable
token behind in Paperclip

## Linked Issues or Issue Description

No issue exists. This follows the feature request template.

**Subsystem affected**

AI connections: Google Antigravity subscription sign-in, its disconnect
and connection removal paths, the connection removal transaction, and
the disconnect messages in the UI and activity log.

**Problem or motivation**

Disconnecting a Google Antigravity subscription account marked the
connection grant revoked in Paperclip only. The saved sign-in (an
encrypted company secret that holds the refresh token) was not deleted.
Connection removal kept it too, because removal only deletes secrets in
the app-owned key namespace. Separately, connection removal revoked the
grants and then released usage-limit holds in two separate writes, so a
failure between them left the grants revoked while held work kept
waiting.

**Proposed solution**

On disconnect or removal, delete Paperclip's saved sign-in and record
the result in plain words. Do not call Google's token revocation. Keep a
saved sign-in that another grant or target still uses. If the delete
fails, keep the reference and let the next disconnect retry. Never
delete a sign-in that a reconnect saved in the meantime. Commit the
grant revocation and the hold release in one transaction, as the
single-grant revoke already does.

**Alternatives considered**

Revoking the refresh token at `https://oauth2.googleapis.com/revoke`
(the first revision of this pull request). The saved credential always
uses client
`1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com`
(`sanitizeAntigravityCredential` rejects any other), which belongs to
Google's own Antigravity runtime that Paperclip runs for sign-in.
Google's OAuth guide for installed apps ("Token revocation") says
revocation "removes all OAuth 2.0 scopes previously granted to a
project" and invalidates tokens for all clients registered under that
project. So a revoke would sign the person out of every Antigravity
sign-in for that account, not only Paperclip's. Paperclip has no client
of its own for this sign-in, so it cannot revoke only its own access.

**Roadmap alignment**

This is work item 5 of the merged plan
`doc/plans/2026-11-25-antigravity-cloud-rollout.md` (gap G10). This pull
request updates G10, item 5 and the security table there to record the
decision.

## What Changed

- `server/src/services/antigravity-access-removal.ts`: for a Google
Antigravity subscription connection, deletes the grant's own saved
sign-in (the private `ai-<grant>` or `ai_<grant>` slot only). It keeps a
sign-in that a live grant or connection elsewhere, a secret binding or
user-secret declaration on another target, or another consumer (agent
profile, routine trigger, secret proposal) still uses. On connection
removal, other grants of the same connection do not count. The delete
passes the saved version, and the grant must still be revoked, so a
reconnect that saved a new version is never deleted. A failed delete
keeps the grant's reference so the next disconnect retries, and the
retry finds a sign-in that is already marked deleted and finishes the
purge. It also clears the quota-recovery file for that grant.
- New `server/src/services/connection-secret-consumers.ts`: one
`findSecretConsumers` check for "is this secret used elsewhere?".
Connection removal (`classifyConnectionSecrets`), managed Google removal
(`secretsHeldElsewhere`) and this change use it. Removal keeps its rule
that any grant or connection counts; the two Google paths count only
live ones. Managed Google removal now also respects bindings,
declarations and other consumers, which only keeps more secrets.
- `packages/shared`: new `AiSignInRemoval` result (`savedSignIn: deleted
| kept_shared | not_deleted`, `providerSignIn: still_valid`) on the
grant revocation result and the connection removal summary.
- `grants.ts`, `removal.ts`, `routes/tool-access.ts`: return and log the
result. Removal does not clear a grant reference whose delete failed,
and its final reference clear only touches revoked grants, so a
reconnect that lands during removal keeps its sign-in.
- `removal.ts`: the grant revocation and the usage-limit hold release
now commit in one transaction.
- `ai-connections.ts`: a personal reconnect reuses the grant's existing
secret definition only if the owner created it, it is live, and it is a
Paperclip-managed local definition. Otherwise the reconnect is refused
in plain words and no token is written.
- UI: the AI account disconnect shows a toast, and connection removal
and the audit feed show the result in plain words, for example
"Paperclip deleted its saved Google sign-in. The sign-in stays valid at
Google until you remove it in your Google account's third-party
connections. Removing it there also signs this Google account out of
Antigravity everywhere." A failed delete says "Paperclip couldn't delete
its saved Google sign-in. Disconnect again to retry."
- Docs: `doc/connections/AI-CONNECTIONS.md` and the rollout plan.
- The first revision's direct Google call and its retry branch in the
Google revocation queue are removed. `google-pending-revocation.ts` is
unchanged from `master`.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed pins for
the changed shared export.

## Verification

- `npx vitest run src/__tests__/antigravity-disconnect-sign-in.test.ts`
(server, embedded Postgres, network calls fail the test): 17 cases.
Disconnect through the route deletes the sign-in, makes no network call,
logs the result with no token, and the owner can reconnect. Connection
removal deletes it, also when a second grant of the same connection
references it. It is kept when a grant on another live connection, a
binding on another target, a declaration on another target, or a routine
trigger uses it. A failed delete (forced by a database trigger) is
reported, keeps the reference, and the next disconnect deletes it, for
disconnect and removal, and also when the failure comes after the
sign-in was marked deleted. A reconnect during the delete, or during
connection removal, keeps its sign-in. A personal reconnect is refused
when the slot was created by someone else, deleted, or moved to another
provider, and no token is written. A hold-release failure during removal
leaves every grant active and the sign-in saved.
- Red/green: with `master`'s `grants.ts`, `removal.ts`,
`ai-connections.ts` and `routes/tool-access.ts`, the disconnect and
removal cases fail. Each guard was also removed on its own, and its case
failed: the saved-version check, the revoked-only final clear, the
half-deleted retry, the same-connection exclusion, and the definition
ownership check.
- `ui`: `npx vitest run
src/features/connections/googleAccessRemoval.test.ts` (13 pass, 5 new).
- Connection removal and managed Google tests pass:
`tool-connection-removal`, `tool-access-service`,
`google-managed-connection-removal`, `google-pending-revocation`,
`ai-connections`, and the browser-use, client-credentials, generic MCP,
Braintrust, 1Password and remote MCP connection suites.
- Server typecheck passes. UI `tsc` shows no errors in changed files.
`pnpm verify` selects about 1,900 test files for this change (removal is
widely imported), so required CI supplies that broad coverage.

## Risks

- The Google sign-in stays valid at Google after a disconnect. The UI
and activity log say so and link to the Google account page. This is
deliberate; see Alternatives considered.
- A reconnect still keeps older versions of a rotated shared secret, as
before this change.
- Company deletion does not change here.
- No schema change and 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, web reading of
Google's OAuth documentation).

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 08:52:03 -06:00
DottaandClaude Opus 5.5 aa85bcb518 feat(plugins): carry a Google sign-in to plugin Runners for Google Antigravity (#22933)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plugin environments (for example, an agent computer) run agents as
plugin Runner tasks. Core sends each task one typed credential, and gets
refreshed sign-ins back through the task's `credentials` snapshot.
> - #22930 let a Google Antigravity task carry a Gemini API key. A
Google subscription sign-in was still refused with "Google sign-in is
not supported."
> - The Cloud rollout plan (#22923) needs both routes. This is gaps G3
and G4 and work item 2: deliver the sign-in, and save a rotated refresh
token safely, as Codex does.
> - This pull request sends the saved, sanitized sign-in as the
`antigravity` `provider-env` credential under
`PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`. It saves a refreshed
token from the snapshot only after the generation, epoch and Google
account checks.
> - The benefit is that a plugin (for example, the Cloud agent computer)
can run an Antigravity task with a person's Google sign-in, and token
refreshes are not lost or saved to the wrong account. The picker, Test
and save refusals for plugin targets (item 6) and the qualification flip
(item 8) stay out of scope.

## Linked Issues or Issue Description

Refs #22923
Refs #22930

**What problem does this solve?**
A plugin Runner task cannot use a Google sign-in for Google Antigravity.
Core refuses it at run start. There is also no path to save a refresh
token that the Runner rotated on the plugin's computer.

**Proposed solution**
Add the sign-in variable as a second `antigravity` key set in
`provider-env`. Core reads the sign-in from the run's private managed
home, runs it through `sanitizeAntigravityCredential`, and sends that
exact output. Core saves the write-back binding (grant, secret, session
epoch, and a SHA-256 of the starting sign-in) on the lease. When the
task stops, Core reads the snapshot and saves a new token only if all
checks pass.

**Alternatives considered**
A new credential type for the sign-in. `provider-env` already has the
exact-set check, the credential binding contract and the cross-check
against the Runner's allowlists. The Cloud plan already describes the
Launcher row as "`GEMINI_API_KEY` or the sign-in key".

## What Changed

- `packages/plugins/sdk/src/environment-tasks.ts`: the `antigravity` key
sets are now `GEMINI_API_KEY` or
`PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`. A mix of both stays
rejected.
- `server/src/services/native-runtime/plugin-runner-credentials.ts`:
with no Gemini API key, Core reads `antigravity-acp/acp_token.json` from
the selected managed home and sends the sanitizer's complete output
(client ID, client secret, refresh token, token URI, `scopes`, and
`project_id` when present). It never sends an access token or the
account email. The task needs write-back authority. A sign-in supplied
through the environment is refused. An unreadable or invalid saved
sign-in fails with "The selected Google Antigravity account is
unavailable. Reconnect the Google account, then retry." No error
contains credential text.
- `server/src/services/ai-connection-runtime.ts`: a Google subscription
run now returns a write-back binding with `google.credentialSha256` of
the starting sign-in.
- `server/src/services/managed-ai-credential-writeback.ts`: new
`syncManagedAntigravityCredential`. It requires an active grant, the
same secret reference and session epoch, a Google subscription
connection, and a saved sign-in that still hashes to the starting
generation. It verifies a changed token with the existing account check
(`prepareAntigravityCredentialWriteback`) in a private temporary home,
then rechecks all of the above under the account lock before it rotates
the secret. It writes `ai_connection.credential_refreshed` on save. For
a different account, or a connection with no saved account, it saves
nothing, writes `ai_connection.credential_refresh_refused` with a plain
reason, and settles as `account_refused`.
- `server/src/services/plugin-task-credential-writeback.ts`: a handoff
with a Google binding takes the snapshot's `provider-env` `antigravity`
sign-in and uses the Google write-back. Codex is unchanged.
- `server/src/services/native-runtime/native-session-executor.ts`: a
sign-in credential needs a Google write-back binding, and a Codex
credential needs a non-Google one.
-
`server/src/services/native-runtime/antigravity-runner-credentials.ts`:
the account mismatch is a typed error. The message is unchanged.
- Docs: `doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md` and
`doc/plugins/PLUGIN_RUNNER_EXECUTION.md` describe the sign-in
credential, where the Runner stages it, and the snapshot that the plugin
must return.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the
changed SDK source.

## Verification

- Red first: with the source changes removed, 22 of the new and updated
tests failed (the refusal, no write-back binding, no Google write-back).
- Green after the change:
- `cd server && npx vitest run
src/__tests__/antigravity-plugin-task-credential-writeback.test.ts` (11
passed, embedded PostgreSQL): delivery of the exact sanitized sign-in;
same-account rotation saved and logged; a second rotation during the
account check saved; a different account refused and recorded in plain
words; unchanged token with no Google call; reconnect (new generation
and epoch) and a revoked grant discard the write-back without an export;
a Google outage keeps the handoff pending and the next cleanup saves it;
Codex, API-key and invalid snapshots refused. No token, client secret or
access token in lease metadata, activity rows or errors.
- `cd server && npx vitest run
src/services/native-runtime/plugin-runner-credentials.test.ts
src/__tests__/plugin-runner-credential-names.test.ts` (39 passed). The
names test checks that the Runner forwards the sign-in variable to the
sidecar and keeps it out of the provider process.
- `cd packages/plugins/sdk && npx vitest run
tests/environment-task-release-resume.test.ts
tests/environment-tasks.test.ts` (104 passed)
  - `cd server && pnpm typecheck` (clean)
  - `pnpm verify` (see the CI run for broad coverage)
- No live run, no Google login and no real token was used. All Google
calls are fixtures.

## Risks

- Low for current users. Plugin targets still refuse Antigravity in the
picker, Test and save (item 6), so no existing agent reaches this path
until item 6 merges.
- The lease now stores a SHA-256 of the starting sign-in. It is a
one-way digest of a high-entropy token, and it is the same kind of
generation value that Core already derives for the local route.
- If Google rotates the token during the account check and the database
save then fails, the cleanup retries from the plugin's snapshot. Google
does not normally rotate these refresh tokens, so this matches the local
route's exposure without its recovery journal.
- The Launcher must return the Runner's `auth-refresh.json` (or
`acp_token.json` before lease close) in the snapshot. A Launcher that
returns the starting sign-in only records `unchanged`, so no token is
lost on the Core side, but a rotation on the computer would not be
saved.

> 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, in Claude Code with
tool use (shell, file edits, test runs). Standard context window,
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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:43:49 -06:00
DottaandPaperclip 57bd302c81 feat(antigravity): add hosted Google loopback-relay sign-in (#22932)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Google Antigravity supports Google account sign-in through Paperclip
Runner's pinned, isolated `agy_acp_server.par` process.
> - On `authenticated + public` deployments (including hosted Cloud
instances), `supportsLocalAiLogin` returns `false`, and the user's
browser cannot directly reach the server's `127.0.0.1:<ephemeral_port>`
loopback callback listener.
> - Because `client_secret` lives only inside `agy_acp_server.par` and
uses PKCE with a one-shot `127.0.0.1` listener, hosted deployments need
an authenticated relay path instead of an anonymous callback route or
extracted secret.
> - This pull request adds an authenticated loopback-relay flow across
Runner, server policy/routes/redaction, and the UI so users on hosted
deployments can sign in with Google, copy the `127.0.0.1` redirect URL
from their address bar, and paste it to complete authentication.
> - The benefit is that Google Antigravity subscription sign-in works on
hosted public deployments while keeping Claude, OpenAI, and Grok
server-host login disabled and preventing SSRF, secret leakage, or
cross-tenant access.

## Linked Issues or Issue Description

Refs #22923

**Subsystem affected**
Cross-cutting (packages/paperclip-runner, packages/shared, server/, ui/)

**Problem or motivation**
Google Antigravity sign-in launches Paperclip's pinned, isolated
`agy_acp_server.par` closure, which opens a one-shot
`127.0.0.1:<ephemeral_port>` OAuth callback listener. On hosted
`authenticated + public` deployments, server-host login routes are
blocked and the user's browser cannot connect to the server's loopback
interface, so users cannot sign in with a Google account on Cloud or
remote instances.

**Proposed solution**
Add an authenticated loopback-relay flow:
1. Runner exposes a single-use `submitRedirect(rawRedirectUrl)` handler
on `AntigravityBrowserLoginState` that validates the pasted URL (length,
printable ASCII, `http://127.0.0.1:<expectedPort>/`, no
credentials/hash, no duplicate `state`/`code`, no `error` param,
`timingSafeEqual` state check, bounded 5-attempt bad-paste cap, SHA-256
reused-code tracking) and issues an SSRF-proof reconstructed `GET` to
`expectedRedirect.origin` with `redirect: "manual"`.
2. Server adds `supportsHostedGoogleAiLogin` (exposed on `/api/health`
as `hostedGoogleAiLoginSupported`), permits Google through the
authenticated `/api/companies/:companyId/ai-connections/local/*` routes
while keeping `anthropic`/`openai`/`xai` blocked on public deployments,
accepts up to 4096-character redirect URLs on `/code` while preserving
Claude's 512-byte limit, runs the loopback relay outside DB
transactions, falls back cleanly when a stack has no active `local`
environment row, and redacts `browserCode`/`redirectUrl` and marks
`/code` secret-sensitive.
3. UI enables Google sign-in for `antigravity_runtime` on non-local
environments when `hostedGoogleAiLoginSupported` is true, renders the
external Google sign-in link plus plain-language `127.0.0.1` copy/paste
instructions with analytics masking/no-capture markers, and triggers an
immediate status check after submission.

**Alternatives considered**
- Adding an anonymous public OAuth callback route on the server:
rejected because it widens the unauthenticated attack surface and cannot
change the loopback `redirect_uri` bound inside `agy_acp_server.par`.
- Extracting Google OAuth `client_secret` out of `agy_acp_server.par`:
rejected by policy; secrets remain owned solely inside the pinned
closure.

## What Changed

- `packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts` &
`packages/paperclip-runner/src/index.ts` &
`server/src/vendor/paperclip-runner/index.ts`: add single-use
`submitRedirect` on `AntigravityBrowserLoginState` with strict
validation, `timingSafeEqual` state verification, 5-attempt cap, bounded
SHA-256 reused-code set, and SSRF-proof loopback relay.
- `packages/shared/src/ai-connections.ts`: add
`LOCAL_AI_LOGIN_CODE_MAX_LENGTH` (4096), `localAiLoginCodeSchema`, and
`submitLocalAiLoginCodeSchema` while preserving Claude's 512-byte
`BROWSER_CODE_MAX_LENGTH` and `browserCodeSchema`.
- `server/src/services/local-ai-login-policy.ts` &
`server/src/routes/health.ts`: add `supportsHostedGoogleAiLogin` and
expose `hostedGoogleAiLoginSupported` on `/api/health`.
- `server/src/services/local-ai-browser-login.ts`,
`server/src/services/local-ai-login.ts`,
`server/src/routes/ai-connections.ts`: permit hosted Google sign-in on
authenticated public deployments while keeping Claude/OpenAI/Grok
blocked; enforce `Cache-Control: no-store`, owner/company/active/expiry
checks, and Claude's 512-byte cap; run Google `submitRedirect` outside
any DB transaction; fall back cleanly to an active environment or
savepoint-wrapped `ensureLocalEnvironment` when no active `local`
environment row exists.
- `server/src/middleware/redact-sensitive.ts`,
`server/src/middleware/http-log-redaction.ts`,
`server/src/middleware/http-log-policy.ts`: redact
`browserCode`/`redirectUrl`/`redirect_url` unconditionally and classify
`/api/companies/:companyId/ai-connections/local/attempts/:sessionId/code`
as secret-sensitive (`local_ai_login_code`).
- `ui/src/api/health.ts`,
`ui/src/components/ai-connections/useLocalAiLogin.ts`,
`ui/src/components/AdapterLoginChrome.tsx`,
`ui/src/components/new-agent/AgentProviderConnection.tsx`,
`ui/src/components/ai-connections/AiConnectionCredentialStep.tsx`,
`ui/src/components/OnboardingWizard.tsx`: enable hosted Google sign-in
for `antigravity_runtime` on hosted/non-local environments, render the
hosted `127.0.0.1` redirect paste flow with `ANALYTICS_MASK_CLASS` and
`ANALYTICS_NO_CAPTURE_CLASS`, preserve retryable paste errors inline,
and trigger immediate status re-check on submit.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the
updated `packages/shared/src/ai-connections.ts` schema.
- Unit, integration, and UI tests across `antigravity-auth.test.ts`,
`local-ai-login-policy.test.ts`, `health.test.ts`,
`health-dev-server-token.test.ts`, `redact-sensitive.test.ts`,
`http-log-policy.test.ts`, `antigravity-local-ai-login.test.ts`,
`ai-connections.test.ts`, `AdapterLoginChrome.test.tsx`,
`useLocalAiLogin.test.tsx`, and `AgentProviderConnection.test.tsx`.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter
@paperclipai/paperclip-runner typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — passed.
- `pnpm --filter @paperclipai/shared exec vitest run
src/validators/claude-setup-token-session.test.ts` — 15/15 passed.
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/drivers/acpx/antigravity-auth.test.ts
src/drivers/acpx/antigravity-auth-stream-order.test.ts` — 33/33 passed
(including real `127.0.0.1` loopback HTTP relay with fake ACP peer,
bad-paste cap, reused-code rejection, single-use, and non-200 failure).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/local-ai-login-policy.test.ts src/__tests__/health.test.ts
src/__tests__/health-dev-server-token.test.ts
src/__tests__/redact-sensitive.test.ts
src/__tests__/http-log-policy.test.ts
src/__tests__/antigravity-local-ai-login.test.ts` — all passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/ai-connections.test.ts` — 167/167 passed against embedded
PostgreSQL (including hosted Google end-to-end route test, redaction of
activity and HTTP logs, and continued blocking of Anthropic/OpenAI/xAI
on hosted public deployments).
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/AdapterLoginChrome.test.tsx
src/components/ai-connections/useLocalAiLogin.test.tsx
src/components/new-agent/AgentProviderConnection.test.tsx` — 30/30
passed.
- `pnpm verify --explain` returned exit 2
(`tests/runner-e2e/source-sdk-public-inputs.json` broad input); required
CI supplies full-repo coverage.
- Note: live end-to-end sign-in against real `agy_acp_server.par` and
Google OAuth on a live Cloud stack was not run in this unit/integration
environment and remains a live-staging verification step.

## Risks

- Low-to-moderate risk. All hosted Google sign-in endpoints stay
authenticated, company-scoped, owner-bound, and `Cache-Control:
no-store`; `localAiLoginSupported` remains `false` on `authenticated +
public` deployments so Claude, OpenAI, and Grok server-host login stay
blocked.
- Loopback relay runs strictly against the validated
`127.0.0.1:<ephemeral_port>` origin printed by `agy_acp_server.par` with
`redirect: "manual"` and a 5-second timeout, outside any database
transaction.
- No database migrations are required.

## Model Used

- Google Gemini (Antigravity agent 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
- [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>
2026-11-25 07:36:36 -06:00
DottaandClaude Opus 5.5 07d444a717 feat(plugins): carry a Gemini API key to plugin Runners for Google Antigravity (#22930)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plugin environments (for example, an agent computer) run agents as
plugin Runner tasks. Core sends each task one typed credential.
> - The typed `provider-env` credential carries API keys for Grok,
Copilot and OpenCode. It has no entry for Google Antigravity.
> - So an Antigravity agent cannot get its Gemini API key on a plugin
Runner task. This is gap G3 and work item 1 in the Antigravity Cloud
rollout plan (#22923).
> - This pull request adds `antigravity` to `provider-env`, with the
single variable set `GEMINI_API_KEY`. It follows the Copilot pattern
from #22359.
> - The benefit is that a plugin (for example, the Paperclip Cloud agent
computer) can now accept a Gemini API key for an Antigravity task.
Google sign-in, the plugin-target refusal and the qualification flip
stay out of scope.

## Linked Issues or Issue Description

Refs #22923
Refs #22359

**What problem does this solve?**
A plugin Runner task cannot carry a Gemini API key. `provider-env`
accepts only `grok`, `copilot` and `opencode`, and Core throws "Plugin
Runner does not support the selected credential provider" for
Antigravity.

**Proposed solution**
Add `antigravity: [["GEMINI_API_KEY"]]` to the published key sets and to
the `provider-env` provider enum. Core transfers only that key. Core
refuses a Google sign-in or a missing key with a plain message.

**Alternatives considered**
A new credential type only for Gemini. The generic `provider-env` type
already has the exact-set check, the binding contract and the
cross-check against the Runner's allowlists, so a new type adds no
value.

## What Changed

- `packages/plugins/sdk/src/environment-tasks.ts`:
`ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS` has `antigravity:
[["GEMINI_API_KEY"]]`. The `provider-env` provider enum accepts
`antigravity`. Mixed, partial and extra variable sets stay rejected.
- `server/src/services/native-runtime/plugin-runner-credentials.ts`: for
provider `antigravity`, Core sends only `GEMINI_API_KEY`. Core refuses a
Google sign-in document (`PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`)
or a missing or blank key with "Plugin Runner supports Google
Antigravity only with a Gemini API key. Google sign-in is not
supported." No key value is in any error message.
- Tests: SDK schema cases (accept the key; reject a sign-in document, a
key mixed with a sign-in document, `GOOGLE_API_KEY`, extra routing
variables, empty values, and the key under another provider). Core
transfer and refusal cases. Dispatch only for the matching `antigravity`
harness, with no key in persisted lease metadata or in a worker error. A
Runner check that the Antigravity process gets the key and no `GOOGLE_*`
or other `GEMINI_*` variable.
- Docs: `doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md` and
`doc/plugins/PLUGIN_RUNNER_EXECUTION.md` list the new set, the binding
requirement and the sign-in refusal.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the
changed SDK source.

## Verification

- Red first: the new tests failed before the change (the schema rejected
`antigravity`, and Core threw "does not support the selected credential
provider").
- Green after the change:
  - `cd packages/plugins/sdk && npx vitest run tests/` (322 passed)
- `cd server && npx vitest run
src/__tests__/plugin-runner-credential-names.test.ts
src/services/native-runtime/plugin-runner-credentials.test.ts
src/__tests__/environment-task-runtime.test.ts` (94 passed)
- `cd packages/plugins/sdk && npx tsc --noEmit -p .` and `cd server &&
npx tsc --noEmit -p .` (clean)
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`
(no change)
- `pnpm verify` asks for broad CI coverage (exit 2) because an SDK test
file changed. Required CI supplies that coverage.
- No live run. Antigravity on a plugin target stays refused by Core
until a later change lifts that refusal, so this change is not reachable
in a run yet.

## Risks

- Low risk. The change adds one enum value and one key set. Existing
providers keep the same behavior.
- Plugins that validate with an older SDK reject an `antigravity`
credential. This is the expected fail-closed result.
- The key reaches the Runner only through the typed credential. The
Runner still requires a matching `PAPERCLIP_ACPX_CREDENTIAL_BINDING` and
still removes other `GOOGLE_*` and `GEMINI_*` variables.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits) and extended thinking.

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:03:49 -06:00
DottaandPaperclip e198f77cea fix(ui): remove obsolete Experimental harness picker from new agent dialog (#22919)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - When a user creates a new agent, `AgentBasicsDialog` shows top-level
adapter cards for each supported harness.
> - Both OpenCode and Grok Build already resolve automatically to
Paperclip Runner through their main adapter cards on supported targets
(`#17120`, `#17922`).
> - However, `AgentBasicsDialog` still rendered an **Advanced ->
Experimental harness** dropdown listing **Grok Build (Paperclip
Runner)** and **OpenCode (Paperclip Runner)** left over from the phased
Runner rollout.
> - Showing both the main cards and a separate experimental Paperclip
Runner dropdown for the same two harnesses confuses users into thinking
the main cards do not use Paperclip Runner.
> - This pull request removes the obsolete dropdown and dead selection
state from `AgentBasicsDialog`, cleans up its Storybook story and
visual-test override, and updates the E2E tests to pick the main Grok
Build and OpenCode cards.
> - The benefit is a single clear creation path for every harness
without duplicate experimental entries.

## Linked Issues or Issue Description

Refs #15993, Refs #17120, Refs #17922.

**What happened?**

When `enableNativeRunner` is enabled, the **Choose an adapter** step in
`AgentBasicsDialog` displays both the top-level **Grok Build** and
**OpenCode** cards and an **Advanced -> Experimental harness** dropdown
containing **Grok Build (Paperclip Runner)** and **OpenCode (Paperclip
Runner)**.

**Expected behavior**

The new-agent adapter picker should show only the main adapter cards,
because selecting **Grok Build** or **OpenCode** already sends `runner:
"auto"` and resolves to Paperclip Runner automatically on supported
targets and managed Paperclip Cloud sandboxes.

**Steps to reproduce**

1. Enable `enableNativeRunner` in instance experimental settings.
2. Open the **New Agent** dialog, enter a name, and click **Choose
adapter**.
3. Expand **Advanced** and observe the duplicate **Experimental
harness** dropdown listing Grok Build and OpenCode.

## What Changed

- Removed the **Advanced -> Experimental harness**
`<details>`/`SelectPopover` block and dead `runnerProvider`,
`experimentalRunnerAvailable`, and `advancedRunnerOptions` code from
`ui/src/components/new-agent/AgentBasicsDialog.tsx`, along with
unreachable `"claude"` / `"grok"` branches in its `paperclip_runner`
update payload.
- Removed the obsolete `ExperimentalNativeHarnesses` story from
`ui/storybook/stories/agents/codex-runner/creation.stories.tsx` and its
visual-test selector/branch in
`tests/storybook-visual/storybook-visual.spec.ts`.
- Updated `tests/e2e/onboarding.spec.ts` to assert the **Advanced**
section is absent even when `enableNativeRunner` is enabled, select the
main **Grok Build** card, and verify the saved setup agent still
resolves to `paperclip_runner` (`provider: "acpx"`, `acpxAgent: "grok"`,
`model: "grok-4.7"`).
- Updated
`tests/runner-e2e/chat-catalog-domains/identity-new-company-native.ts`
to select the main **OpenCode** card instead of the removed dropdown.

## Verification

- `pnpm --filter @paperclipai/ui typecheck` passed.
- `node scripts/run-tsc.mjs -p tests/tsconfig.playwright.json --noEmit
&& node scripts/run-tsc.mjs -p tests/e2e/tsconfig.json --noEmit && node
scripts/run-tsc.mjs -p tests/runner-e2e/tsconfig.json --noEmit` passed.
- `node scripts/check-test-budget.mjs --base origin/master` and `node
scripts/storybook-catalog.mjs` passed.
- `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/chat-catalog-domains/identity-new-company-native.test.ts`
passed (51/51 tests).
- `pnpm exec playwright test --config tests/e2e/playwright.config.ts
tests/e2e/onboarding.spec.ts -g "name-only setup saves the Grok Build
Paperclip Runner adapter"` passed locally (1/1).
- `pnpm verify` exited 2 because
`tests/storybook-visual/storybook-visual.spec.ts` is unclassified; full
workspace, build, and E2E verification is covered by required PR CI.

## Risks

- Low risk. The main **Grok Build** and **OpenCode** cards already
resolve to Paperclip Runner on all supported platforms and managed Cloud
sandboxes via `resolveNewAgentRunnerForCompany`.
- On platforms where Paperclip Runner is not supported for Grok Build or
OpenCode (for example Linux ARM64), the main cards fall back to the
legacy adapter instead of forcing `paperclip_runner`, which matches
Codex and Claude Code behavior.

## Model Used

- Google Gemini (Antigravity agent with tool use, file editing, and
terminal 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>
2026-11-25 06:14:45 -06:00
DottaandClaude Opus 5.5 87083fe982 fix(e2e): retry transient journey API read failures (#22917)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Product journeys test real hiring and delegation on a hosted test
stack every day.
> - A journey reads the API many times. The Cloud provider also reads it
when it prepares the lead agent and when it records a new hire.
> - Those provider reads have no retry. One dropped connection fails the
whole journey with `api_request_failed`.
> - #22914 made the failure code visible. The next staging run showed
`api_request_failed` at the moment the hired agent first appeared.
> - This pull request makes `ConnectionApi` repeat a read after a
transient failure. It never repeats a write.
> - The benefit is that a single network failure does not fail a long,
paid journey.

## Linked Issues or Issue Description

Refs #22914

**What happened?**
The QA staging smoke ran `hire-delegate-reuse` alone on the harness pin
that contains #22914. The journey failed with `api_request_failed`,
while the lead agent's hiring run was still running. At that point the
observer records the new agent through `session.own`. In the Cloud
provider, that call reconciles the hire and prepares its budget, with
about 15 API reads and no retry. An earlier failure today was in setup,
during the lead agent's readiness poll. That path also has no retry.

**Expected behavior**
A dropped connection or a gateway error on a read is retried. A real
error, for example a 404, still fails at once. A write is never sent
twice.

**Steps to reproduce**
Run the new `connection-support` test against the previous code. A GET
that fails once with a socket error rejects with `api_request_failed`
instead of reading the next response.

**Paperclip version or commit**
Harness pin 0e4dcd9be8.

## What Changed

- `ConnectionApi.response` tries a GET up to three times when the
request throws or the status is 408, 429, 502, 503 or 504. It waits 250
ms, then 500 ms. Each attempt keeps the caller's timeout. Callers that
use `scopedApi` still stop at the lifecycle deadline.
- POST, PATCH, PUT and DELETE are sent once, as before.
- A note in `tests/runner-e2e/PRODUCT-JOURNEYS.md`.

## Verification

- Red: the new test failed on the previous code (`api_request_failed`
instead of the third response).
- Green: full runner-e2e Vitest suite, `npx vitest run --config
tests/runner-e2e/vitest.config.ts`: 693 files, 11,714 tests pass.
- `node scripts/typecheck-test-projects.mjs tests/runner-e2e` passes.
- SDK input pins refreshed. No change.
- After merge, I will pin `QA_SMOKE_HARNESS_SHA` to the merge commit and
run `hire-delegate-reuse` alone on staging.

## Risks

- Low risk. The change is test harness code only.
- A read that fails three times can take up to three times the caller's
timeout when the caller does not use a lifecycle scope. Journey callers
use `scopedApi`, which keeps the original deadline.
- A read repeated after a cancelled lifecycle can still reach the
server. It is a read, so it does not change state.

> 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, GitHub CLI, read-only AWS S3 evidence access).

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 06:03:23 -06:00
DottaandClaude Opus 5.5 0e4dcd9be8 fix(e2e): wait for hire retries and keep API failure codes in journey evidence (#22914)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Product journeys test real hiring and delegation on a hosted test
stack every day.
> - The hire-delegate-reuse journey failed on three attempts today, at
three different steps.
> - One failure graded a hired agent's run as final while its
exact-session retry was still scheduled. #22826 fixed the same gap for
agent task journeys, but the hire observer has its own run check.
> - The other two failures recorded only `journey_operation_failed`. The
API client gives fixed failure codes, but the journey result dropped
them.
> - This pull request makes the hire observer wait for a scheduled
same-run retry, and it keeps the fixed API failure codes in the
evidence.
> - The benefit is fewer false failures, and a clear failure code when a
hosted API call fails.

## Linked Issues or Issue Description

Refs #22826, #22825

**What happened?**
The daily QA staging smoke failed `hire-delegate-reuse` three times on
2026-11-25:
1. Setup failed after the lead agent was created. The result said only
`journey_operation_failed`.
2. The lead hired the teammate and replied. On the next observation the
journey failed with `journey_operation_failed`.
3. The first delegated task completed. During the review task, the hired
agent's run was `running`. One second later the journey failed with
`hire_native_run_failed`.

**Expected behavior**
A failed native run with an agent-owned exact-session retry scheduled
inside the campaign deadline is still in progress. The journey keeps
observing it. A failure caused by an API status or transport error is
recorded with that fixed code, for example `api_status_500`.

**Steps to reproduce**
Run the new tests against the previous code. `assertHireRuns` throws
`hire_native_run_failed` for a pending same-run retry. `journeyFailure`
turns `ConnectionFailure("api_status_500")` into
`journey_operation_failed`.

**Paperclip version or commit**
Harness pin 6d5541b109 on the QA staging
smoke.

## What Changed

- `assertHireRuns` takes an optional campaign deadline. With it, a run
that `isPendingNativeRecovery` accepts is not treated as failed. The
observer passes `options.deadlineAt`. The idle wait still needs every
run to succeed, so a pending retry never counts as completion.
- `journeyFailure` keeps a `ConnectionFailure` code when it is one of
the fixed codes: `api_status_NNN`, `api_request_failed`,
`sensitive_api_request_failed`, `invalid_api_route`,
`invalid_api_timeout`. It matches the class by name as well, because the
Cloud provider can load its own copy of the class. Other errors still
become `journey_operation_failed`.

## Verification

- Red: the new hire recovery test and three new `journeyFailure` tests
failed on the previous code.
- Green: `npx vitest run --config tests/runner-e2e/vitest.config.ts` on
`hire-delegate-evidence`, `hire-delegate-flow`, `journey-failure`,
`agent-recovery` and `campaign`: 124 tests pass.
- `node scripts/typecheck-test-projects.mjs tests/runner-e2e` passes.
- SDK input pins refreshed with `source-sdk-public-inputs.mjs --write`.
No change.
- After merge, I will pin `QA_SMOKE_HARNESS_SHA` to the merge commit and
run `hire-delegate-reuse` alone on staging.

## Risks

- Low risk. The change is test harness code only.
- The retry wait uses the same strict predicate as #22826: native
runtime, agent-owned recovery, remaining attempts, no successor, and a
retry time inside the deadline. Terminal and exhausted failures still
fail at once.
- Only fixed, identifier-shaped codes are kept. Free-form messages, URLs
and response bodies are still dropped.

> 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, GitHub CLI, read-only AWS S3 evidence access).

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 05:18:07 -06:00
DottaandClaude Opus 5.5 8de6686739 fix(apps): save action choices when the provider no longer offers some actions (#22877)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Connections give agents actions in other apps, and the Permissions
page controls which actions agents can use
> - A managed Google Workspace connection moved from Paperclip's REST
tools to Google's MCP servers (#22815)
> - Google's MCP servers do not list two Gmail actions, so the catalog
refresh marked them as removed (`disabled`, `mcp_tool_removed`)
> - The Permissions page still sent these two actions as enabled, and
the server refused every save that contained them, except on remote MCP
aggregators
> - An admin could not release the 34 held actions, so the connection
stayed unusable
> - This pull request makes the server accept a removed action for every
connection kind, and makes the UI stop sending disabled or removed
actions
> - The benefit is that an admin can always save the review after a
provider removes actions, and a disabled action still cannot be turned
on

## Linked Issues or Issue Description

Refs #22815

**What happened?**

On a managed Google Workspace connection that runs on Google's MCP
servers, the Permissions page showed "Review 34 new actions". After
"Turn all on" and "Save choices", the save failed with the message
"Couldn't save that — Disabled actions cannot be enabled". The held
actions stayed held.

**What did you expect to happen?**

The save releases the reviewed actions. Actions that Google no longer
offers stay off and do not block the save.

**Steps to reproduce**

1. Connect Google Workspace with the managed method while the transport
is Paperclip REST. Keep all actions on.
2. Move the connection to Google's MCP servers (#22815). The refresh
holds the actions for review, and Google's listing does not include
`gmail__list_threads` and `gmail__search_messages`.
3. Open the connection's Permissions page. Select "Review 34 new
actions", then "Turn all on", then "Save choices".
4. See the error "Disabled actions cannot be enabled".

**Cause**

- `useConnectionPermissionSave.ts` sent `enabledCatalogEntryIds:
[...next.enabled]`. This set came from the saved profile and still
contained the two removed actions.
- `finishGalleryAppConnection` in `server/src/services/tool-access.ts`
refused an enabled row with `status === "disabled"`. It accepted a
removed row (`quarantineReason === "mcp_tool_removed"`) only for remote
MCP aggregators (`isRemoteMcpConnectorMethod`). The catalog refresh
writes `mcp_tool_removed` also for Google Workspace and plugin
connections, so these connections did not get the same exception.

## What Changed

- Server: `finishGalleryAppConnection` accepts a row that the provider's
listing removed (`mcp_tool_removed`) for every connection kind. Only the
catalog refresh writes this marker, and only when the provider's listing
no longer has the action. This is the same behavior that remote MCP
aggregators already had. Any other disabled row is still refused with
"Disabled actions cannot be enabled". A removed row is not active, so
the gateway does not offer it to agents.
- Shared: `@paperclipai/shared` has three named predicates in
`tool-catalog-availability.ts`. `isCatalogEntryOffered` is true for
active and held actions. `isCatalogEntryRemovedByProvider` is true for
`removed` rows and for `disabled` rows with `mcp_tool_removed`.
`isCatalogEntryBlocked` is true for every other disabled row. The server
and the UI use these predicates, so the rule is in one place.
- Server: the review coverage check ignores a reviewed id that the
provider removed after the page loaded. Before this change, that save
failed with "Action review decisions must cover every currently
quarantined action exactly once".
- Server: a save no longer sets a `removed` row back to active.
- UI: a new `withoutUnavailableActions` helper drops catalog entries
that are not offered (`isCatalogEntryOffered` is false) from an enabled
list.
- UI: the Permissions page save (`finishAppPermissions` in
`useConnectionPermissionSave.ts`) sends only available actions as
enabled or Ask first. The page already showed and counted only active
and held actions, so the removed actions do not show, count, or toggle.
The page has no existing pattern for removed actions, so this change
adds no new text.
- UI: the setup flow (`ConnectionSetupFlow.tsx`, which also serves
task-hosted setup) and the pasted-config flow (`PasteConfigTab.tsx`)
also drop disabled actions before they finish a connection. Before this
change, a provider-blocked action (for example a Gmail write action on a
read-only method) could make the first save fail the same way.
`RemoteMcpProductionSetup.tsx` already sends only active actions.
`QuarantinedActionsReview` in `SetupPanel.tsx` selects only from held
actions.

## Verification

- Red, then green:
`server/src/__tests__/google-workspace-mcp-transport.test.ts` → "saves
the review when Google no longer offers actions that were on, and still
refuses a disabled action". The test saves a managed Google Workspace
connection on REST, moves it to Google's MCP servers while Google does
not list `list_threads` and `search_messages`, then saves the review
with the removed actions in the enabled list. Before the fix it failed
with "Disabled actions cannot be enabled". After the fix it passes. The
same test makes sure that a disabled action without the removal marker
is still refused, and that agents are not offered the removed actions.
- Red, then green:
`ui/src/pages/apps/app-detail/action-permissions.test.ts` →
"finishAppPermissions never asks to turn on an action Google no longer
offers or a disabled action". Without the filter, the test fails.
- `packages/shared/src/tool-catalog-availability.test.ts` covers the
three predicates.
- The transport test also sends the removed ids in
`reviewedCatalogEntryIds`. Without the coverage fix it fails with
"Action review decisions must cover every currently quarantined action
exactly once". It also makes sure that the removed rows stay disabled
after the save.
- Local runs: `google-workspace-mcp-transport.test.ts` and
`tool-access-service.test.ts` (542 passed). UI tests in `app-detail`,
`features/connections` and `pages/tools` (143 passed).
- `pnpm verify` selected the full server suite (1520 files) because
`tool-access.ts` is a shared service. On this machine, under load from
other sessions, 31 of 33876 tests failed. The run output did not keep
the names of the failed tests. The touched test files pass when run
alone, and the CI server shards run the full suite on the final head.
- `tsc --noEmit` for `server` and for `ui/src`.

## Risks

- Low risk. The security rule stays: a disabled action that the provider
did not remove cannot be turned on.
- Behavior change: Google Workspace and plugin connections now accept a
removed action in the enabled list, as remote MCP aggregators already
did. The UI no longer sends removed actions, so after a save from the
page a removed action stays off if the provider lists it again.

## 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 04:32:26 -06:00
DottaandClaude Opus 5.5 3fbf872d9e fix(antigravity): make the task thread read in plain language (#22886)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A task thread shows what an agent did during a run, as a list of
activity rows under its reply
> - Google Antigravity runs (ordinary and `/swarm`) send no tool
identity, so each row was named after the CLI's display title
> - Users saw rows like "Ran a command · failed Run
mcp_paperclip_paperclip_finish", "Ran File runtime paperclip runner acpx
…", lowercased sentences, and a sha256 dump
> - Each attached file also showed twice, nothing marked a message as a
swarm request, and a refused send only showed a short toast
> - This pull request gives Antigravity tool calls the identity other
harnesses send, and makes the thread read the same live and after the
run
> - The benefit is a task thread that reads in plain language for
Antigravity, with fixes that also help other harnesses

## Linked Issues or Issue Description

**What happened?**
In a live Antigravity `/swarm` run, the task thread showed raw tool
names and internal paths. Examples: "Run mcp_paperclip_paperclip_finish
· failed", "Ran File runtime paperclip runner acpx 5230… antigravity
home … SKILL md", "Ran Swarm started in the task folder with gemini 3 8
flash low …" (lowercased, punctuation removed), "Registered title:
u1.txt, sha256: 7692…". The live list and the finished list used
different words. The CLI's first reads of u1.txt failed ("must be an
absolute path") and were read again successfully, but the thread showed
"failed". Each file showed twice: a file card, and an agent message
"Prepared u1.txt for this response." with a second card. The user's
bubble did not show that the message was a swarm request. When the
server refused a send (for example `/swarm` in Plan mode), only a short
toast explained it.

**Expected behavior**
Rows say what the agent did in plain words, the same while live and
after the run. No raw tool names, internal paths, hashes or key/value
dumps. The refused-then-accepted completion call is hidden as for every
other harness. A failure that a later call recovered reads as "retried".
Each file shows once. A swarm request has a small "Swarm" marker. A
refused send keeps an inline, dismissible error under the composer.

**Steps to reproduce**
1. Assign a task to a Google Antigravity agent with the experimental
swarm setting on.
2. Send `/swarm Create u1.txt containing "one" and u2.txt containing
"two", one helper per file, then verify both.`
3. Expand the activity list while the run is live, and again after it
finishes.
4. Put another task in Plan mode and send `/swarm do something`.

## What Changed

- Runner (Antigravity-owned): new `antigravity-tool-identity.ts` names
each call. Paperclip bridge tools become
`mcp__paperclip__<canonicalRunnerToolName(tool)>` (from the CLI's
`mcp_paperclip_<tool>`, an ordinary run's `paperclip_<tool>` title, or
ACP `_meta.mcp`). Native CLI tools keep their own names (`run_command`,
`view_file`, …) with the command as the subject. Reads of the CLI's own
built-in files (its private Antigravity home) are dropped. Swarm
progress lines get one neutral identity (`swarm_update`) whose subject
is the plain sentence. Swarm file locations are task-relative.
- Runner: a narrow activity-adapter hook (`createToolEventProjection`)
applies this in both places that pump an ACPX turn (in-process driver
and sidecar). The sidecar now keeps a provider-supplied tool detail
instead of overwriting it.
- UI: live rows use the call's subject, drop raw technical names
(Paperclip's own tools need no source label), and use the same "verb +
subject" form as settled rows, so both lists read the same.
- UI: a bridge call recorded under its own id (providers that pass no
tool-use id) joins the provider's row for the same Paperclip tool, in
the live log and in stored events. `register_deliverable` reads
"Attached u1.txt"; content digests never show in an input summary.
- UI: a failed call whose later call of the same tool on the same target
succeeded shows as "· retried" (token-only, same muted style).
Unrecovered failures stay "· failed".
- UI: generated "Prepared <file> for this response." receipts are hidden
for any file that already shows as the run's file card (before, only
images).
- Server + shared + UI: `IssueComment.nativeCommand` ("swarm") is
derived read-only from the server's own activity record on comment list,
get and the POST response. The user's bubble shows a small "Swarm" note.
The `/swarm` eligibility rule (`isAntigravityAgent`,
`antigravitySwarmAvailable`) now lives in `packages/shared`; the
composer shows a light hint when the text starts with `/swarm` and the
assignee can run a swarm.
- UI: the composer keeps the server's message as an inline, dismissible
error after any 4xx refusal, until dismissed or the next send. The
optimistic "Working" row behaviour is unchanged.

Not changed, by design: after a reload, a settled run's activity is
deferred behind "More run output" for every native harness (cold-load
speed), so Antigravity already matches the others.

## Verification

- Red/green runner test `antigravity-tool-identity.test.ts` with a
fixture rebuilt from a live swarm run's updates (ids, paths and hashes
replaced): names, subjects, dropped internal reads, hidden finish
identity, ordinary-run titles and `_meta.mcp`.
- Red/green UI test `antigravity-thread.test.tsx` renders the real run's
stored events (settled) and the same events through the live run-log
parser. It asserts the exact rows, "retried" reads, one "Attached" row
per file, no finish rows, no raw names/paths/hashes, and live ==
settled. It fails on master (raw "Ran Swarm update …", "Read · failed",
"Registered title: …, sha256: …").
- Red/green `TaskChatThread.test.tsx`: a prepared text file shows once;
a refused send shows the server message inline until dismissed and the
Working row clears; only a server-marked comment shows "Swarm".
- `TaskChatComposer.test.tsx`: the `/swarm` hint shows only for an
Antigravity assignee with the setting on.
- Server `antigravity-swarm-request-path.test.ts` (embedded Postgres):
only the user's recorded request is marked; text, metadata, another
user's or an agent's comment are not.
- Local: paperclip-runner acpx/sidecar/provider-events suites, UI
task-chat/transcript/adapters/thread/hooks suites (1630 tests), server
swarm suite, and shared/server/ui/runner typechecks pass. `pnpm verify`
exited 2 (broad input), so CI supplies the broad coverage.

Before (live swarm run, done state):

```
Ran This swarm runs on the google account of this agent s google connection
Ran File runtime paperclip runner acpx 523076a3 3689 4b28 9910 c101bc6b64d8 97d9fb76f6aa11b6 a…
Ran File u1 txt · failed  u1.txt
Ran a command · failed
Registered title: u1.txt, sha256: 7692c3ad3540bb803c020b3aee66cd8887123234ea0c6e7143c0…
```

After (same events, settled and live):

```
Swarm  This swarm runs on the Google account of this agent's Google connection.
Swarm  Started helper writer1: Create a file named u1.txt in the current workspace directory containing exactly "one"
Read · retried  u1.txt
Read  u1.txt
$ shasum -a 256 u1.txt u2.txt; wc -c u1.txt u2.txt
Attached  u1.txt
Swarm  Files changed in the task folder: u1.txt, u2.txt
```

## Risks

- Live tool rows for all harnesses no longer show a raw technical name
("Paperclip · search_tasks", "Bash") next to the activity. Rows with a
concrete subject now read like settled rows ("Read README.md", "$ npm
test"). This is a deliberate wording change.
- `register_deliverable` reads "Attached <file>" for all harnesses.
- Generated file receipts are hidden for any file with its own card, not
only images. Human text and agent progress with attachments stay visible
(the same marker and link checks as for images).
- Bridge-call pairing is display only and matches only a Paperclip tool
of the same name that is in flight. Claude already shares one id and is
unchanged.
- One extra indexed activity-log query per comment list or get. No
schema 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 (`claude-opus-5-5`) 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 01:45:06 -06:00
DottaandClaude Opus 5.5 cd8bcfba16 fix(antigravity): swarm usage on Stop/kill, honest recovery text, clean thread text, run-record receipt (#22865)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Google Antigravity agents can run Google's native `/swarm` from a
task (#22733, experimental flag)
> - The first complete live run of `/swarm` found gaps: a stopped or
killed swarm recorded no usage, the lost-process text asked for Retry
while Paperclip recovered on its own, CLI-only text and local `file://`
paths reached the task thread, and the swarm's settings receipt never
reached the run record
> - Usage must always be recorded, recovery must just work, and users
must not see local paths or internal jargon
> - This pull request fixes each gap at the module that owns it, with a
red/green test for each
> - The benefit is a swarm whose cost, recovery and thread text match
what happened

## Linked Issues or Issue Description

Refs #22733, #22731

**What happened?**
In a live local run of `/swarm` (Gemini 3.8 Flash and Gemini 4 Neon,
Google sign-in):
- A swarm stopped after 29 s with 7 helpers recorded 0 tokens. A swarm
whose CLI process was killed also recorded 0 tokens.
- After the CLI process died, the failure text said "Retry starts a
fresh swarm in the same task folder" and was marked not retryable, but
Paperclip recovered on its own with a fresh swarm.
- The thread showed "Run /swarm board (default shortcut alt+s) to open
the live board", a stray "." line, links to absolute local
`file:///…/<company id>/<task id>/a.txt` paths (on ordinary Antigravity
replies too), and a mention of "the Paperclip swarm rules".
- The structured swarm receipt (requested and confirmed model, channel,
CLI version, account match) was not in the run record.

**What did you expect?**
Usage recorded for every swarm, text that matches automatic recovery, a
thread without CLI hints or local paths, and a queryable receipt.

**Steps to reproduce**
Run `/swarm` on a task for an Antigravity agent, then Stop it or kill
the `agy acp` process, and read the run usage and the thread.

## What Changed

- **Usage on Stop and process death** (`antigravity-swarm-runtime.ts`).
A stopped prompt's own answer is awaited within the grace window and its
`usage` is kept. When no answer arrives (the CLI exited, or did not
answer in time), the token counts the CLI streamed in `usage_update`
(`_meta.usage`, read with the shared ACP converter) are kept; after an
earlier answered prompt they only raise a counter (per-counter maximum),
because a streamed count may be session-wide, so nothing is counted
twice. The usage is one receipt per run request, so a recovery run never
counts it again. What cannot be known: if the CLI exits before it
streams any token counts, that prompt's usage is lost with the process.
The pinned CLI 1.5.15 declares `usage_update` and a prompt-answer
`usage`; whether it fills `_meta.usage` mid-prompt is not proven live.
- **Lost CLI process.** The failure is retryable and says "Files the
helpers already wrote stay in the task folder", with no instruction to
press Retry. Automatic recovery is unchanged and is bounded by the
server's existing per-request cap (three failed attempts, then a plain
refusal); a new database test pins that cap for the lost-process error
code across continuation, recovery and assignment wakes.
- **Terminal hint split across chunks**
(`antigravity-swarm-presentation.ts`). The swarm passes raw coordinator
text to a streaming filter that holds text that could still become the
hint, so the hint and its trailing period are dropped wherever the CLI
splits them. The fake CLI now streams the hint in the recorded live
pieces.
- **Local file links, both Antigravity routes**
(`antigravity-local-links.ts`, wired in `runtime-host.ts` for agent
`antigravity` only). No existing mechanism did this: other harnesses
only emit file-reference events, and an ordinary Antigravity reply
showed the same links. Before a reply leaves the Runner, a link to a
task-folder file becomes its folder-relative path in code (the thread
opens a nested path as a task-folder file; a root-level name stays plain
text beside its deliverable link, as before, since the thread never
opened the `file://` target), a descriptive label keeps the path beside
it, other `file://` links keep only their label, a bare task-folder
prefix is removed, and the folder named on its own reads "the task
folder". Sentence punctuation stays outside file names. `/api/...` and
web links are unchanged. Text that could still become a link is held
across chunks.
- **Swarm rules** tell the coordinator that its text is shown in the
task thread: name files by task-folder path, no absolute paths or
`file://` links, no terminal commands, shortcuts or live board, no
mention of the rules.
- **Swarm receipt in the run record** (`antigravity-activity.ts`,
`profile-activity.ts`). The sidecar's status sanitizer dropped
`antigravitySwarmReceipt`. It now reaches the run as a
`provider.notice.recorded` event (category `antigravity_swarm_receipt`)
through the same post-turn hook as Cursor's native receipt. It carries
requested and confirmed model, thinking level, mode, channel, CLI
version and whether the CLI sign-in matches the connection. No account,
path, session id or instruction text. No protocol schema change.
- The link parsing reuses `localTarget` and `workspaceRelativePath`, now
exported from `live/workspace-file-reference.ts`.
- The public SDK input registry is resynced for a `packages/shared`
change that landed on master.
- **Ledger** (`doc/plans/2026-11-22-antigravity-qualification.md`): what
the live swarm and Neon runs prove, and what they do not.
- Not changed: the user's own `/swarm` comment has no marker in the
thread. The thread has no per-message marker for Plan-mode requests
either, and comments do not store `nativeCommand`, so there is no
pattern to reuse.

## Verification

- Red/green: the new runtime and presentation tests fail on the old
source (6 failed) and pass with the fix; the receipt test fails without
the `antigravity` activity registration.
- `cd packages/paperclip-runner && npx vitest run src/drivers/acpx
src/cli/acpx-runtime-sidecar.test.ts`: 120 files, 2239 passed.
- `cd server && npx vitest run
src/services/antigravity-swarm.db.test.ts`: 52 passed.
- `pnpm run check:acpx-profiles`,
`scripts/contracts/contract-fingerprints.test.mjs` and `node
tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`
(unchanged) pass.
- `pnpm verify` exits 2 (the fake CLI fixture is a broad input), so CI
supplies the broad coverage.
- Not run: a live swarm (no paid or live runs from this change).

## Risks

- Low to medium. The link filter applies to every Antigravity reply. It
holds a short tail of text that could still become a link or local path,
and releases it before the next non-text event and at turn end. A tool
event that arrives in the middle of a link releases the partial link
unchanged.
- A lost swarm process is now marked retryable. The server's recovery
decision does not read this flag; automatic recovery behaves as before.

## 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>
2026-11-24 22:06:59 -06:00
627d59c5aa fix(inbox): group repeated provider failures and clear recovered tasks (#22846)
## Thinking Path

> - Paperclip helps people manage work that agents do.
> - The inbox tells a person which tasks need a decision.
> - A provider usage limit can stop several attempts on one task or
affect several tasks.
> - Separate failure cards made it hard to tell which tasks still needed
attention.
> - This change groups failures using the account, reset time, or retry
links that Paperclip can verify.
> - A person can now see which task to retry, which tasks are waiting,
and which ones recovered.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

It improves the Coordinator inbox when a provider limits usage.

**Current behavior**

Repeated run failures can fill the inbox. Resolved failures can still
appear beside open decisions.

**Proposed behavior**

Show personal actions in Needs you, automatic retries and snoozes in
Waiting, and past events in History. Keep an archived retry chain hidden
during automatic attempts. Return it to Needs you when a person must
act.

**Additional context**

Related work includes #18020 on completed tasks, #9704 on archive
behavior, and #21570 on usage limits in chat.

## What Changed

- Group verified account and reset windows. When that evidence is
missing, count linked attempts per task and show the tasks in a
collapsible group.
- Separate the reported reset time from each task’s retry schedule. Keep
unresolved ownership recoveries visible after task closure. Use
persisted native retry requests to preserve the original archive and
increment the attempt count.
- Keep personal archive in the card menu. Put decision receipts and run
logs in History.
- Align inbox filters, tabs, and history. Share empty-state artwork and
placement across Inbox, Goals, Routines, and Secrets.
- Index run-history pages and resumed-work lookups, and rate-limit
history requests per company and viewer. Add synthetic fixtures for both
grouping paths and a manual walkthrough.

## Verification

- The author and a human tester completed the synthetic retry-chain
walkthrough. Chromium also verified archive, repeat failure, exhaustion,
and recovery.
- The 64 focused server tests and the UI and server typechecks passed
before rebasing. See `doc/testing/coordinator-inbox-test-drive.md` to
repeat the manual checks.
- The shared SDK input check and all 64 focused server tests passed
after rebasing. The OpenAPI suite (59 tests), API catalog suite (2,309
tests), and both demo seed paths passed locally after the CI fixes.
- The affected inbox and native-runtime suites passed locally after
merging the upstream conformance test fix in #22854. The browser
access-denial scenarios passed three runs each for 403 and 404.
- The migration checks and 79 focused tests passed, including an
index-plan regression with 5,000 unrelated runs. The migration and query
plan were reverified after renumbering. [Full CI on
`cf52b80161`](https://github.com/paperclipai/paperclip/actions/runs/45529834793)
passed after rerunning a timed-out server shard.

## Risks

The attention feed reads retry ancestry. Long chains can increase query
cost. Task and company checks bound the traversal, and cycle detection
stops repeated visits. Providers that omit the reset time leave the card
with an unknown reset. Migration 0508 adds two indexes concurrently.
Each run-history page returns at most 100 records.

## Model Used

OpenAI Codex, GPT-6 family, with repository editing, local test
execution, and browser verification.

## 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 <scott@scotts-mbp-m5-max.local>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-24 18:33:27 -08:00
Nicky Leach 0c3ed144cb Label opt-in traces with the public instance hostname (#22856) 2026-11-24 18:08:46 -08:00
DottaandClaude Opus 5.5 12944919c6 feat(google): keep Google Technical Information at most 30 days and keep Google data out of training exports (#22842)
Adds a durable, sleep-aware 30-day sweep for Google Technical Information, keeps Google results out of decision training and shared feedback traces, and deletes the remaining copies of a cleaned run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:57:23 -06:00
DottaandClaude Opus 5.5 3ad8f00192 feat(antigravity): trusted /swarm from the task composer, behind an experimental flag (#22733)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Google Antigravity agents can run Google's native `/swarm` (a
coordinator, helpers and a verifier) only on the Antigravity CLI
> - #22731 adds a verified CLI route to the Runner, but nothing selects
it yet
> - A swarm must start only when the signed-in user asks for it, only
when an admin turned the experimental feature on, and never silently run
as an ordinary request when it cannot run
> - This pull request adds the trusted `/swarm` request in the task
composer, the server checks and run selection behind an experimental
flag, removes Paperclip delegation tools from a swarm turn, and adds the
attended catalog cells, docs and ledger
> - The benefit is that a user can start a native swarm from a task, and
gets one plain message when it is not available

## Linked Issues or Issue Description

Refs #22731, #22727, #22728, #22701

**Subsystem affected**
Task composer (UI), issue comments API, run selection (server),
Paperclip Runner tool bridge, runner-e2e catalog, docs.

**Problem or motivation**
A user who writes `/swarm <request>` to a Google Antigravity agent
should get a real native swarm in the task folder. Today `/swarm` is
neutralised text, and the task runs as an ordinary request.

**Proposed solution**
Read a leading `/swarm` with the shared rule from #22727 in the
composer, send it as a structured request, check it on the server, and
select the CLI route from #22731 for that run only.

## What Changed

- **Trusted start (UI).** `parseSwarmCommand` in `composer-commands.ts`
uses `parseLeadingUserCommand` (the one rule from #22727). A leading
`/swarm` in the task composer sends the request text with
`nativeCommand: "swarm"`; a bare `/swarm` asks for a request; `/swarm`
with an assignee change is refused; `/swarm` anywhere else stays text. A
resent draft keeps the structured request.
- **Contract.** `addIssueCommentSchema` gains `nativeCommand: "swarm"`.
`instance.experimental.enableAntigravitySwarm` (feature catalog,
settings page, server defaults), off by default. No Cloud policy in
Core.
- **Server (`services/antigravity-swarm.ts`, comments route, runtime
selection).**
- The comments route accepts `nativeCommand` only from a signed-in board
user. When a swarm cannot run it answers 422 with one plain message and
posts nothing: flag off, not a Google Antigravity assignee, a chat, Plan
mode.
- An accepted request is recorded in the activity log
(`issue.antigravity_swarm_requested`, server-written) and the assignee's
wake carries the comment id. Comment text is never read as a command.
- Run selection makes the run a swarm only when that activity record
exists. It refuses a remote or cloud environment and Plan mode with a
plain run failure, so a swarm is never run as an ordinary request. It
logs `issue.antigravity_swarm_started` in plain language: helper actions
are auto-approved, Paperclip does not sandbox the helpers and cannot see
their shell commands, and usage is one total.
- The native execution input sets the Antigravity provider mode `swarm`
for that run only, and carries the verified request in its own field,
`provider.swarmRequest` (the Runner contract accepts it only with that
mode and requires it there, 1 to 16,000 characters). The Runner copies
it into the model envelope as `swarmRequest`; the swarm route sends
exactly `/swarm <swarmRequest>` and never reads `task.prompt`, which
holds rendered wake comments, task context and text the Runner adds
(handoff, attachments, queued messages).
- The swarm turn contract (mode `swarm`, envelope
`paperclip.native-model-envelope.v3`, `swarmRequest` of 1 to 16,000
characters) is declared as `antigravitySwarmTurn` in
`protocol/provider-schemas/acpx-sidecar.schema.json` and generated into
TypeScript, so the pack `contractDigest` covers it (it changes; older
image packs are rebuilt rather than reused). Provider profile
`commandDigest`s and versions are unchanged, so no saved session is
reset.
- What the swarm sees of the task: only the request. The title, the
description (which other people or agents may have written) and other
comments are not part of the prompt; the coordinator can read them
through Paperclip's task tools as data if it needs context.
- An empty `/swarm` or one over 16,000 characters is refused in the
composer, by the comments route (422, nothing posted) and at run
selection (plain run failure), so it never runs as ordinary work.
- A swarm run never takes queued messages, and Interrupt treats it as
already started: it stops the swarm and delivers the queued message as
the next ordinary request, before or after the provider accepted the
turn.
- Retry after Stop, and past the three automatic attempts, counts only
when the signed-in user asked for it (their own Retry request on the
task after the last attempt). Wake reasons and copied run context are
not proof: a recovery that copies the request marker, an automatic retry
on the user's behalf, or an agent wake that names `task_retry` stay
bounded.
- **Runner.** For a swarm turn the Paperclip bridge drops delegation
tools (`paperclip_create_task`, `paperclip_create_issue`, hire/assign
tools); the instructions also tell the coordinator not to delegate.
- **runner-e2e.** `antigravity-swarm` suite, 5 local cells
(`two-helpers-and-verifier`, `stop-mid-swarm`, `process-loss-retry`,
`follow-up-after-swarm`, `flag-off-refusal`), explicit-only, never in
`--all` or CI matrix jobs. There is no automated executor yet: the
launcher refuses the cells and points at the live recipe. Catalog counts
updated (1392 cells).
- **Docs.** `tests/runner-e2e/SUITES.md`, `doc/evals.md`, and the
`/swarm` section, ledger row and live recipe in
`doc/plans/2026-11-22-antigravity-qualification.md`.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/services/antigravity-swarm.test.ts`: 2 passed (red first: module
missing; Plan mode red then green).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-comment-reopen-routes.test.ts -t swarm`: 3 passed; 2
red against the route without this change.
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/task-chat/TaskChatComposer.test.tsx`: 164 passed,
including 4 new `/swarm` tests (red first).
- Runner: `vitest run src/drivers/acpx/antigravity-swarm-*.test.ts`: 69
passed (route tool filter red first).
- runner-e2e: `antigravity-swarm.test.ts` (red first) plus the catalog,
selector and Antigravity tests: 28 files passed.
- Typecheck: server, UI (except generated Storybook files absent from a
worktree) and runner: no errors.
- Live, real CLI 1.5.15 with the owner's sign-in, through the driver:
the receipt verified (pinned identity, task folder, `auto` read back,
`gemini-3.8-flash` + `low`). Google then refused the prompt with its 429
quota text; the driver reported it as a typed "out of quota" failure,
retired the CLI and nothing was written.
- **Not run live yet:** the full Paperclip proof (swarm to Done, Stop,
kill and Retry, follow-up, flag off). This PR is merged only after it
passes. Recipe:
`doc/plans/2026-11-22-antigravity-qualification.md#swarm-live-proof`.

## Risks

### Security notes: the trust boundary

Helpers are auto-approved and Paperclip does not sandbox the CLI on a
local computer, so the boundary is who asked and what text is sent.
Every input that can influence it:

**(a) Whether a run is a swarm**
- `nativeCommand: "swarm"` on the comment request: accepted only from a
signed-in board user; the request record
(`issue.antigravity_swarm_requested`, actor = that user, `commentId`)
commits in the same transaction as the comment. Paperclip-written.
- `antigravitySwarmCommentId` on the wake/run context: set only by the
comments route and by run selection. It is a pointer, never trusted
alone: selection re-verifies comment id + task + company + human author
(no agent author) + a matching record by the same user.
- The pending request for marker-less wakes: the task's latest human
comment, verified the same way.
- Retry inheritance: the run's `retryOfRunId` chain (server-written),
bounded to 8 hops on the same task.
- Manual vs automatic: a request's first run, or a user's own Retry
request (`task_retry` / `retry_failed_run`, requested by a user, not
`initiatedBy` automation) after the last attempt. Not the wake reason
string.
- Instance flag `enableAntigravitySwarm` (admin), the assignee's adapter
config (Google Antigravity), execution target (local only), work mode
(Standard only: Plan, Ask and any other mode are refused, at comment
time and at run time), chat vs task: all Paperclip-owned settings.
- Prior attempts on the same request (run status rows):
Paperclip-written.

**(b) What text and tools the swarm gets**
- The prompt: `/swarm ` + `provider.swarmRequest`, which is the recorded
comment body minus a leading `/swarm`, trimmed, byte for byte (tested
through the production input builder and envelope with a merged wake
that contains an agent comment). The verified request.
- The system prompt append: only Paperclip-authored text: Paperclip's
fixed execution prompt, the run's hand-in values (the server-written
completion revision and criterion IDs that
`paperclip_finish`/`paperclip_block` require; never a criterion's
requirement text), and the fixed swarm rules. **The swarm runs without
the agent's own instructions**: the instruction bundle and connection
instructions are left out, because an agent with an editable
instructions folder can rewrite its instructions in an earlier ordinary
run, the helpers act under auto mode, and Paperclip keeps no
user-approved copy of those instructions to trust instead.
- Tools: only Paperclip's own MCP bridge (any other assigned tool server
refuses the swarm), with delegation, hiring, routing and generic API
operations removed. Paperclip's permission handler approves a CLI
permission request only when its tool name is `mcp_paperclip_<tool>` and
`<tool>` is one the run's bridge admits; everything else is refused, and
the CLI then ends the turn. Tool descriptions are Paperclip-authored;
tool results (for example other comments) are data the coordinator
reads, not the request.
- Model and mode: the agent's configured model, Antigravity's `auto`
mode, both read back and pinned by the receipt.
- Not sent: task title, description, wake comments, continuation events,
attachments, queued messages, handoff text.

Known residual: a Retry or recovery run that has not yet been selected
(still preparing) does not carry the request marker, so an Interrupt in
that short window keeps the message for the turn boundary instead of
stopping the run; the message is delivered after the run ends.

- Off by default and local only. With the flag on, helpers act under
Antigravity's `auto` mode. **Paperclip does not sandbox them on a local
computer**, and their tool calls never reach Paperclip, so helper shell
commands can write outside the task folder where the CLI's own sandbox
allows (workspace plus temp directories). The settings text, the
activity log and the plan doc say so.
- On macOS the CLI uses its own Google sign-in from the login keychain,
not Paperclip's stored connection.
- Google's consumer terms have a clause about third-party tools that
access the service. A legal read is pending; this PR does not claim
compliance.
- `/swarm` as the first word of a composer message is now a swarm
request for every agent; for agents other than Google Antigravity the
server refuses it with a plain message. To send the literal text, put
other text first.
- The new runner-e2e cells are attended only and have no automated
executor.

> 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`.

Review round 2 (head a2decc65f3): Greptile's "swarms must guess
completion fields" fixed as above (runner `nativeSystemInstructions`,
red first 1 in the fake-CLI swarm runtime test; request text to the CLI
still exactly `/swarm <request>`); CI typecheck failure was a TS18046 in
`acpx-runtime-sidecar.test.ts` (test-program typecheck), fixed; master
merged, its pruned `heartbeat-provider-limit-wait` and
`provider-failure-classification` suites dropped, with this branch's
swarm cases kept in `antigravity-swarm-provider-limit.test.ts` and
`antigravity-swarm.test.ts`. No protocol schema change. Round 3 (head
1444503e84, from live run6): CLI 1.5.15 names a client MCP call
`mcp_<server>_<tool>` with no `_meta` (payload recorded from the pinned
CLI, now the fake CLI's fixture), so Paperclip's permission handler
refused the coordinator's own `get_task_context` and the CLI ended the
turn on the denial. The handler now approves only tools the run's
Paperclip bridge admits, by that name, and fails closed otherwise; a
refused Paperclip tool is reported as such, not as a helper blocked
outside the task folder. A swarm turn without a hand-in fails plainly
(`ANTIGRAVITY_SWARM_NO_RESULT`: "The swarm ended without doing any
work"), every swarm-route failure code settles as
`antigravity_swarm_unavailable` (no automatic retry; Retry offered), and
selection never starts another swarm automatically after one; a lost CLI
process still recovers on its own. The run history always records
whether the CLI's sign-in matches the connection account (with the
reason when unknown). Usage-limit evidence is scoped by the executed
provider mode, so limits from pre-scope swarms hold only swarms. Red
first: runtime 5, server 3.

Then (head 74454a17f3): an empty `/swarm` body now gets the documented
422 `antigravity_swarm_unavailable` instead of a generic 400
(`addIssueSwarmCommentSchema`, route red first 1); an empty ordinary
comment keeps its 400.

Review round (earlier head):
- `pnpm --filter @paperclipai/server exec vitest run` on the swarm,
request-path, native-execution-input, first-turn, queued-comments and
comment-route tests: 475 passed. Red first: request path 1, execution
input 3, empty/over-long DB 3 and route 2, Interrupt during a swarm 2,
Retry proof 2.
- Runner `src/drivers/acpx src/contracts`: passed; swarm runtime red
first 6 (request field, verbatim text, empty, over-long, no field,
request only in the rendered prompt).
- UI `TaskChatComposer.test.tsx`: over-long `/swarm` refused (red first
1).
- Typecheck: server (layers), UI and runner: no errors.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell,
file edit) 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:54:23 -06:00
021be2c56d perf(ci): split local-verify tests so release registry runs them in parallel (#22819)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Every pull request runs the "Typecheck + Release Registry" CI job.
> - In a recent PR run that ran all checks, this job was the longest
check (450s). In other recent PR runs it took 405s and 413s.
> - In those runs, the `release registry tests` task took 178–202s.
Almost all of that time was one file:
`scripts/__tests__/local-verify.test.mjs`. Its tests ran one after the
other for ~200s, because `node --test` runs the tests in one file in
sequence.
> - While that task runs, it holds one of the three slots of the
typecheck lane and adds CPU load. This makes server declarations and
test projects start later and run slower.
> - This pull request splits the file into three balanced files, so
`node --test` runs them in parallel processes.
> - The benefit is a shorter release registry task (local measurement:
179s → 65s for these tests) and a shorter Typecheck + Release Registry
job.

## Linked Issues or Issue Description

No existing GitHub issue covers this, so here is the issue, following
the enhancement template.

**What existing behavior does this improve?**
How long the CI job "Typecheck + Release Registry" takes on PRs that
select the release registry tests.

**Subsystem affected**
CI and repository scripts (`scripts/__tests__`,
`test:release-registry`).

**Current behavior**
In the PR runs that select it, the job is the longest check (405–450s).
Its `release registry tests` task takes ~200s. Almost all of that time
comes from `scripts/__tests__/local-verify.test.mjs`. `node --test` runs
the tests in one file in sequence.

**Proposed behavior**
Move the shared fixture into a helper module. Split the tests into three
files with similar run times, so `node --test` runs them in parallel
processes.

**Reason and benefit**
Faster CI feedback for many PRs. What the tests check does not change.

**Breaking changes**
None. Only test files and the `test:release-registry` file list change.

## What Changed

- Moved `fixture()` and `repository` from
`scripts/__tests__/local-verify.test.mjs` to a new helper module,
`scripts/__tests__/local-verify-fixture.mjs`. The code is the same.
- Split the tests into three files with similar run times (measured on
CI):
- `local-verify.test.mjs` (~70s): real selected execution, plus the fast
snapshot and plan tests.
- `local-verify-partitions.test.mjs` (~68s): the general-workspaces-b/c
partition tests, installed dependency invalidation, and local server
selection.
- `local-verify-reuse.test.mjs` (~61s): explicit full execution, source
mutation and interruption, stale SDK pins, and edit during
fingerprinting.
- Added the two new files to `test:release-registry` in `package.json`.
- Refreshed `tests/runner-e2e/source-sdk-public-inputs.json`, because
`package.json` is a pinned SDK public input.
- The test bodies are the same. Only the imports changed.

## Verification

- Original file alone: `node --test
scripts/__tests__/local-verify.test.mjs` → 179s wall time (4 vCPU).
- Three new files: `node --test
scripts/__tests__/local-verify*.test.mjs` → 65s wall time. Each run has
the same 15 tests.
- In this sandbox, one test ("an edit between diff discovery and
fingerprinting...") fails both before and after the change. The cause is
a local `git` launcher wrapper that refuses a recursive call. CI does
not have this wrapper. The CI `Typecheck + Release Registry` job on this
PR runs all of the tests.
- Expected CI effect: the `release registry tests` task goes from ~200s
to ~70–100s (the CI runner has more CPU load than the local test). The
task frees its lane slot ~100s earlier. For PRs that select release
registry tests, I expect the Typecheck + Release Registry job to save
~30–60s (from ~405–450s). PRs that do not select release registry tests
are not affected.

## Risks

- Low risk. This change affects only test files.
- The three files now run at the same time. Each test uses its own
temporary fixture directory, so the tests do not share state.
- More parallel processes add CPU load to the 4 vCPU typecheck runner
for a shorter time. The total CPU work is the same.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), run as a Claude Code agent 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 (14/15 pass locally; the
one failure is the sandbox git wrapper and also fails on master)
- [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>
2026-11-24 17:13:10 -08:00
DottaandClaude Opus 5.5 8c04793a4a feat(google): delete content read from Google when access ends (#22836)
Every way a Google connection ends now starts the durable connection content deletion on its own, and Paperclip never resumes a cleaned harness session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:32:11 -06:00
Dotta de4b60fc54 refactor(test): prune 28 completed migration, prose-grep, and Storybook fixture tests (#22832)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Over recent sprints, the test suite accumulated completed one-time
SQL migration backfill tests, brittle static prose-matching guidance
tests, and non-production Storybook fixture/prototype/feasibility-probe
tests that add compile and CI maintenance cost without testing live
behavioral invariants.
> - Core database migration guards, active runtime migration services,
security/safety static guards, and active adapter suites must stay
intact.
> - This pull request deletes 28 audited low-value test files (-1,894
LOC), preserves the one genuine schema validation assertion from
`chat-communication-guidance.test.ts` inside
`packages/shared/src/validators/chat-channels.test.ts`, prunes the 5
deleted server test keys from
`scripts/general-server-shard-durations.json`, and refreshes
`tests/runner-e2e/source-sdk-public-inputs.json`.
> - The benefit is cleaner, higher-signal test coverage with zero lost
invariants and synchronized SDK public source pins.

## Linked Issues or Issue Description

Refs #22804

**What existing behavior does this improve?**
Test suite signal-to-noise ratio and maintenance overhead across
`packages/db`, `packages/shared`, `packages/skills-catalog`, `server`,
`ui/storybook`, `scripts`, and `tests/speko-voice-proof`.

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
28 test files test already-shipped one-time migrations/dead backfills,
static markdown/copy wording, non-production Storybook
fixtures/prototypes, or a superseded voice feasibility probe.

**Proposed behavior**
Remove the 28 low-value test files while preserving all core migration
integrity suites, active runtime migration services, security static
guards, live adapter suites, and the genuine `updateChatEndpointSchema`
assertion.

## What Changed

- **Completed one-time migrations & dead backfills (3 files deleted, 444
LOC):**
- Deleted
`packages/db/src/better-auth-account-issuer-migration.test.ts`,
`packages/db/src/chat-telegram-draft-ids-migration.test.ts`, and
`server/src/__tests__/tool-oauth-legacy-backfill.test.ts` (zero
production callers outside barrel re-export).
- Retained all core DB migration guards (`check-migration-safety`,
`migration-compatibility`, `migration-snapshot-drift`,
`check-pr-migration-order`) and active runtime migration/legacy-recovery
services.
- **Brittle static prose/wording grep tests (9 files deleted, 317
LOC):**
- Deleted `packages/shared/src/connection-intent-guidance.test.ts`,
`packages/shared/src/telemetry/readme-contract.test.ts`,
`packages/skills-catalog/src/release-content-cases-contract.test.ts`,
`server/src/__tests__/secret-entry-guidance.test.ts`,
`server/src/__tests__/primary-agent-guidance.test.ts`,
`server/src/services/chat-communication-guidance.test.ts`,
`server/src/services/onboarding-greeting.test.ts`,
`ui/src/lib/agent-onboarding-prompt.test.ts`, and
`ui/src/lib/grok-bot-setup-prompt.test.ts`.
- Moved the one genuine schema validation assertion
(`updateChatEndpointSchema` `communicationInstructions`) into
`packages/shared/src/validators/chat-channels.test.ts`.
- Retained `cli-invocation-safety.test.ts` and all real
security/auth/prompt-injection guards.
- **Non-production Storybook fixture / prototype / feasibility-probe
tests (16 files deleted, 1,182 LOC):**
- Deleted 10 Storybook fixture/prototype/mock-API tests, 2 unreferenced
Storybook audit script tests, and 4 superseded
`tests/speko-voice-proof/*.test.mjs` feasibility probe tests.
- **Manifest & SDK pin hygiene:**
- Pruned the 5 deleted server test keys and reconciled coverage counts
in `scripts/general-server-shard-durations.json`.
- Synced `tests/runner-e2e/source-sdk-public-inputs.json` via `node
tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --write` (0 files
deleted under `tests/runner-e2e/`).

## Verification

- `node scripts/check-maps.mjs` — **PASS** (35 areas, 192 capabilities
aligned)
- `node scripts/check-test-budget.mjs --base origin/master` — **PASS**
(588 nightly suites validated)
- `pnpm exec vitest run` on retained suites (`chat-channels`,
`telemetry`, `skills-catalog`, `check-migration-safety`,
`migration-compatibility`, `migration-snapshot-drift`, `runner-api`) —
**15/15 files, 2,532/2,532 PASS**
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` and `vitest run --config
tests/runner-e2e/vitest.config.ts
tests/runner-e2e/source-sdk-public-inputs.test.mjs` — **PASS (13/13)**
- `node --test scripts/typecheck-test-programs.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/storybook-catalog.test.mjs` — **103/103 PASS**
- Typecheck (`@paperclipai/shared`, `@paperclipai/db` incl.
`check:migrations`, `@paperclipai/skills-catalog`, `node
scripts/ci-typecheck-lane.mjs --typecheck-ui`) — **PASS (0 errors)**

## Risks

- Low risk: zero production code changed, zero core DB migration or
auth/security guards removed, and zero dangling references across
`maps/`, `scripts/`, `.github/`, or `tsconfig*.json`.

## Model Used

- Google Gemini (Antigravity agent swarm) with extended reasoning, tool
use, and local test execution (`typecheck-opt`, `verifier`,
`ci-pipeline`).

## 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
2026-11-24 16:39:22 -06:00
6d5541b109 fix(e2e): observe scheduled native retries before grading tasks (#22826)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Product journeys observe native tasks until their useful result is
complete.
> - A native session can time out while the server schedules an
exact-session retry.
> - The run status is temporarily failed while its retry remains
scheduled.
> - The observer currently grades that temporary state as a final
failure.
> - This pull request keeps observing a bound scheduled retry within the
original deadline.
> - The benefit is a grade based on the completed task, with terminal
failures and work limits preserved.

## Linked Issues or Issue Description

**What happened?**
A build-and-revise task prepared its ZIP, then hit a five-minute native
session timeout. The API reported agent-owned exact-session recovery on
the same run with one of three attempts used and a retry scheduled
before the campaign deadline. The journey raised `agent_run_failed`
before that retry could occur.

**Expected behavior**
Observe a proven scheduled retry on the same run within the original
deadline. Require a later successful run and the existing independent
artifact checks. A pending retry cannot pass the journey.

**Steps to reproduce**
Run the new agent-recovery regression against the previous observer. A
realistic failed native run with a scheduled retry fails immediately.
The corrected observer sees the same run succeed and still fails
terminal, exhausted, foreign and late recovery states.

**Paperclip version or commit**
Reproduced from 28aa32e7d7. Affected
source files were unchanged on current master before publication. The
documentation incorporates current master changes.

**Deployment mode**
Credential-free task-observer calibration on Linux. The observed hosted
failure supplied the original diagnosis. No full-stack staging recovery
pass is claimed.

## What Changed

- Pass the original campaign deadline to agent task validation.
- Reuse the existing native recovery predicate after company, task,
agent, environment and model checks.
- Accept older API projections that omit a successor when no successor
exists. Continue to reject an actual successor.
- Require succeeded or explicitly checked cancelled runs for settlement.
Never settle a failed recovery snapshot.
- Add controlled success, deadline and negative recovery tests. Preserve
the original budgets and run limits.

## Verification

- Red: three new recovery checks failed against the previous observer:
premature terminal grading, premature settlement and the wrong deadline
failure.
- Green: 194 tests pass across agent-recovery, agent-evidence and
onboarding-first-task.
- Local test-project typecheck could not complete: the host killed the
compiler with SIGKILL. `pnpm verify --explain` could not select checks
because the managed Git storage guard rejects `git ls-files`. Neither
attempt is a pass.
- Review follow-up at `b2957a3112df1cbcce80bba441cc0415bed1f86c`: the
shared task read now waits for pending recovery before it reaches any
consumer. This covers Plan revision, Plan approval, protected-action
decisions, replies and artifact reads. Four journey regression checks
fail before this gate and pass after it. All 202 focused recovery,
agent-evidence, onboarding and Plan checks pass. Fresh CI and review on
this head are pending. No new paid test, protected pin update or staging
deployment was made.

## Risks

- Waiting requires an explicit native retry projection, a matching
cause, agent ownership, remaining attempts and a retry time inside the
existing deadline. Other failures still stop immediately.
- Older projections omit the optional successor field. The compatibility
change accepts only null or absent values.
- No provider timeout or runtime recovery policy changes. A full
authorized staging run must still prove acceptance.

## Model Used

OpenAI GPT-6 through Codex, with reasoning, source editing, shell tools
and Chromium. The runtime does not expose a more specific model
revision.

## 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: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 16:34:32 -06:00
DottaandPaperclip 3128be7cda fix(e2e): preserve exact spacing around handoff mentions (#22825)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Product journeys check that a person can hire and delegate through
chat.
> - The journey selects real agent and project mentions in the composer.
> - Each selection inserts a trailing space for the next typed word.
> - The helper then types the complete next source slice, including its
own whitespace.
> - This pull request removes the inserted space through normal keyboard
editing before continuing.
> - The benefit is one exact saved message with the existing strict
identity and count checks.

## Linked Issues or Issue Description

**What happened?**
The hiring journey saves two spaces after its agent mention and an
unwanted space before the comma after its project mention. Its exact
saved-body assertion fails after the delegated task completes. The
retained historical observation lacks the original message comparison.
This PR reproduces the spacing defect directly in the production
composer; it does not claim those missing historical inputs were
recovered.

**Expected behavior**
Normal mention selection must preserve the exact requested body,
including whitespace and punctuation, and save it exactly once.

**Steps to reproduce**
Run the production composer browser spec with the quoted checklist
reference. Before the repair, the saved message has an extra space after
each selected mention. After the repair, the body matches exactly.

**Paperclip version or commit**
Reproduced from source at 28aa32e7d7. The
affected source files were unchanged on current master before
publication.

**Deployment mode**
Local Linux Chromium control with the real production and streamlined
composers. No model or staging credentials. Related merged #22821
repairs a separate routine journey.

## What Changed

- Check the collapsed caret before removing exactly one editor-added
space. Refuse to send if the caret does not match.
- Preserve exact agent/project mention identities and the single-message
assertion.
- Retain private byte counts, SHA-256 body hashes, IDs and comparison
results before grading. Do not retain raw bodies.
- Extend the real composer test with the quoted checklist reference.
Keep wrong-agent, duplicate and missing-project rejection.

## Verification

- Red: the production composer browser check failed with extra spaces
around both mention chips.
- Green: all 6 composer browser checks pass with the corrected helper.
- All 75 focused hiring flow and evidence tests pass. A changed-body
control proves the failure receipt survives grading.
- Local test-project typecheck could not complete: the host killed the
compiler with SIGKILL. `pnpm verify --explain` could not select checks
because the managed Git storage guard rejects `git ls-files`. Neither
attempt is a pass.
- Final head `99338b2a3f0717489f09cd949353ed2d12248e3e`: [selected
CI](https://github.com/paperclipai/paperclip/actions/runs/45491682386)
passes, including Typecheck + Release Registry, four support shards, six
Runner package shards, static checks and aggregate verify. Build and
unrelated suites are skipped by the test-only path policy. Greptile is
5/5 on this head. There are no review threads. No new paid test,
protected pin update or staging deployment was made.

## Risks

- The browser helper depends on the shipped mention insertion caret
contract. A missing trailing space stops the send instead of deleting a
mention.
- The historical cause remains an inference from an independently
reproduced defect. A future full run must establish staging acceptance.

## Model Used

OpenAI GPT-6 through Codex, with reasoning, source editing, shell tools
and Chromium. The runtime does not expose a more specific model
revision.

## 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>
2026-11-24 16:05:37 -06:00
DottaandPaperclip 823e90d8b2 fix(e2e): follow current routine form and schedule controls (#22821)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The scheduled-routine journey checks creation, timed execution,
saved output and pause.
> - The routine page redesign changed its form and schedule controls.
> - The journey still used the old title placeholder, Responsible picker
and trigger editor.
> - It stopped before it could measure scheduling, even after the New
routine button fix.
> - This pull request follows the current controls and adds a
production-component browser regression.
> - The benefit is a usable schedule test with the same independent
behavior checks.

## Linked Issues or Issue Description

Refs #22182 and #22205. Related open #22340 changes other routine page
details; it does not update this journey.

**What happened?**
The scheduled-routine journey opens New routine, then times out on the
removed Routine title placeholder. The current form labels that field
Title. It has a Default agent picker and a separate Project picker. The
old journey also expects the removed Schedule trigger region and Enable
trigger control.

**Expected behavior**
The journey must use the current form, resume its owned schedule,
observe one attributed scheduled run, pause it, and check the next full
schedule boundary.

**Steps to reproduce**
Run the new credential-free browser control against the previous UI
actions. It renders the production RoutineEditDialog and fails waiting
for the old Routine title placeholder. The same control passes with this
repair.

**Paperclip version or commit**
Reproduced from master at d128e2db6f.
Published on current master after checking that all four existing
changed files were unchanged.

**Deployment mode**
Local Chromium production-component control, with no app server, model
or testing credentials. The observed staging failure supplied the
original report. This PR has no fresh full-stack staging pass.

## What Changed

- Extract the routine browser actions into a small journey-owned module.
- Fill Title and Instructions by accessible name. Open the agent and
project pickers explicitly.
- Use the schedule popover's Resume and Pause controls. Wait for each
exact trigger PATCH.
- Read created-task history on the base routine page. Keep configuration
version history separate.
- Add a Chromium control using the actual form, entity selectors and
routine page. It checks exact owner/project selection, missing-choice
refusal and the two owned trigger mutations. Unrelated display/editor
boundaries are stubbed.
- Keep the scheduler, native run, output, reload, duplicate-run,
deadline and cleanup oracles intact.
- Document the control and its limited acceptance scope.

## Verification

- Red: the production-component browser control timed out on
`getByPlaceholder("Routine title")` with the original actions.
- Green: `BROWSER_EXECUTABLE_PATH=/usr/bin/chromium node --import
/tmp/pap5819-tools/node_modules/tsx/dist/loader.mjs
tests/runner-e2e/product-journeys/routine-schedule-ui.browser.mjs`
passes.
- Focused Vitest: all 17 tests in routine-schedule-entry,
routine-schedule-evidence and routine-schedule-flow pass. The temporary
config selects only those suites.
- Local tools: Node 25.9.0, Vitest 5.0.3, Playwright 1.62.1 and system
Chromium. Dependencies were installed outside the checkout; no lockfile
changed.
- `pnpm verify` could not select tests: the managed Git storage guard
rejects `git ls-files`. This attempt has no verification verdict. The
first head passed selected CI. Those results do not qualify the revised
head; fresh CI and review remain pending.
- No new paid run, protected test-harness pin change or staging
deployment was made. Full scheduled acceptance remains separate.

- Review regression: the production route resolver rejects the old
/history task read; all 17 focused tests pass after the correction.
- Isolated dependency layout: the previous browser check cannot resolve
React without root React/React DOM. The revised check resolves UI-owned
peers and passes in that layout.

## Risks

- These actions target the current redesigned routine UI. An old UI
paired with this harness would not match the controls.
- The browser regression stubs unrelated display/editor boundaries. It
proves the real control actions, not a complete scheduler or
native-provider run.
- The fixture owns one schedule. Multiple matching schedule controls
cause an error rather than selecting an arbitrary trigger.

> 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

OpenAI GPT-6 in Codex, with tool use for source edits, Chromium, local
tests and GitHub API operations.

## 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>
2026-11-24 15:19:57 -06:00
DottaandClaude Opus 5.5 4401962e69 feat(google-workspace): run the six launch services on Google's MCP servers again (#22815)
Gmail, Drive, Docs, Sheets, Slides and Calendar go back to google_mcp because of Google's Workspace AI Tools Addendum; the REST tool set stays as the fallback. The REST argument checks that need no request to Google run before each MCP call, a Calendar delete reads the event first and refuses a recurring series, and a refresh that replaces saved REST definitions holds nothing for review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:44:03 -06:00
DottaandPaperclip 1a36a8f3c0 fix(e2e): wait for agreeing dependency run observations (#22802)
## Thinking Path

> - Paperclip lets people manage AI agents and their work.
> - A blocked task must start once after its blocker is complete.
> - The dependency journey checks this through task and agent run reads.
> - These independent reads can see the same run at different stages of
completion.
> - The collector can stop while the agent read still says `running`.
> - This pull request waits for both reads to agree before it saves the
finished and reopened points.
> - The test can then measure the completed work with the existing
strict rules.

## Linked Issues or Issue Description

**What happened?**

The dependency journey can report `dependency_one_automatic_resume`
after one correct automatic run. Its completion wait accepts the task
run as `succeeded` while the agent run read still says `running`. A
later read agrees, but the saved finished point remains split.

**Expected behavior**

Wait for matching task and agent run facts within the existing campaign
deadline. Keep the two observations independent. Fail if they never
agree.

**Steps to reproduce**

Use the flow fixture to return a completed task run and a lagging agent
run detail. Run the new `agent detail still running after task detail
completed` case against the old collector. It fails with
`dependency_one_automatic_resume`.

**Paperclip version or commit**

Base: `3ca9b6d471e100fe248c650f30453db4d3bc55fb`.
Related: #21732 added valid wake producers. That repair is already
present and does not address this read timing error.

## What Changed

- Compare task and agent run facts with the same normalized facts used
by the grader.
- Require agreement before the collector ends its completion wait and
after it reopens the result.
- Tag fixture projections explicitly, with separate agent lag counters
before and after reopening.
- Share the full settled predicate between both waits; agreeing stale
reads cannot count as completion.
- Add temporary and permanent cases for agent lag, task-only and
agreeing stale run views, task status, missing document, active locks
and native phase.
- Document the completion wait. Keep the grader, run budget and deadline
unchanged.

## Verification

- Red: the new lagging-read regression fails on the base collector with
`dependency_one_automatic_resume`.
- Green: three focused dependency suites pass, 126 tests. This includes
permanent disagreement, duplicate or unrelated runs, early execution,
history and output checks.
- Command: `node /tmp/pap5740-test-tools/node_modules/vitest/vitest.mjs
run --config /tmp/pap5740-test-tools/vitest.config.mjs`. The temporary
config selects
`tests/runner-e2e/product-journeys/task-dependency-resume*.test.ts`.
Tools: Vitest 5.0.3, Playwright 1.62.1 and Zod 4.
- `pnpm verify` could not run: the managed Git storage guard rejects
`git ls-files` with `paperclip_git_storage_limit`. CI must supply
broader checks.
- No new paid journey was run. Staging acceptance remains open. No
reviewed harness pin was changed.
- Follow-up commit: `16bb94c256769fe76b014e865259b742b35773ea`. The
reopened-only regression fails on the prior commit with
`dependency_one_automatic_resume`; it passes after this repair.
- Second follow-up: `45d60118fb36fd1f426e088f263d04c91484cfee`. Ten of
twelve new stale-state cases fail on `16bb94c`; all pass after sharing
the settled predicate.
- Exact finished-run binding:
`24d7b2f67a9f51ac6d996211f651a92772ff2a55`. Both reopened projections
must match the normalized saved finished-run facts. Two additional
agreeing-but-different run-facts cases fail before this change and pass
afterward.
- CI and Greptile passed on `16bb94c`; reviews also cleared `45d6011`.
Fresh CI and reviews are pending on `24d7b2f`.

## Risks

Low risk. A mismatch now uses the remaining campaign wait rather than
reaching the grader early. Permanent disagreement still fails at the
deadline. This change does not start another agent run, alter production
state, replace either independent read, or relax the grader.

## Model Used

OpenAI GPT-6 through Codex, with reasoning and code execution. The
runtime did not expose a more specific model ID.

## 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>
2026-11-24 13:34:14 -06:00
Dotta cffd17e78a perf(ci): Phase 3 PR CI under 3m — 4x Runner support, 12x E2E, incremental TS 7 cache, pure-Node postinstall, and rebalanced shards (#22804)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Pull request CI verifies every change before merge across build,
typecheck, server tests, Runner tests, and Playwright E2E shards.
> - After Phase 1 (#22679) and Phase 2 (#22729), full-fanout PR CI still
takes 9m45s wall-clock on 4-core AWS runners because of five
bottlenecks: an unsharded 7m22s `Runner support suite`, stale
server/chat/Runner shard duration manifests plus newly landed SSH/soak
whales, 28s of `pnpm -r run postinstall` replay on every job, cold
server/UI typecheck and single-build overhead, and 3 oversized (>180s)
Playwright E2E specs across 8 shards with double-start Postgres template
boot.
> - Docs-only prose edits under `doc/**` and `docs/**` also fanned out
to 66 CI jobs because only three doc paths bypassed global dependencies.
> - This pull request shards `Runner support suite` 4 ways with `pool:
"threads"`, shards E2E 12 ways after splitting the 3 oversized specs and
removing double-start Postgres boot, adds pure-Node workspace
postinstall replay, adds read-only master-warmed incremental TS 7 and
Runner dist caches, rebalances all server/chat/Runner duration
manifests, demotes 48 new non-invariant soak whales to nightly, and
routes audited prose docs without triggering 66-job storms.
> - The benefit is driving ordinary PR CI toward under 3 minutes
wall-clock while preserving every invariant check, cache boundary, and
full master/nightly test coverage.

## Linked Issues or Issue Description

Refs #22679
Refs #22729

**What existing behavior does this improve?**
Pull request CI wall-clock latency across
`.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`,
`.github/actions/setup-ci-dependencies/action.yml`, typecheck
orchestration, Vitest/Runner lanes, and Playwright E2E shards.

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
Full-fanout PR CI takes 9m45s on 4-core runners (run `45440355579`),
dominated by `Runner support suite` (7m22s), `e2e shards` (5m02s–6m24s),
`General tests (server/chat)` (5m37s–6m01s), `Verify Paperclip Runner
(vitest package)` (6m25s on stale manifests), `Typecheck` (4m13s–6m30s),
`Build` (~4m), and 28s of `pnpm -r postinstall` per job. Prose edits
under `doc/**` trigger 66 jobs.

**Proposed behavior**
Shard `Runner support suite` (4x) and `e2e_shards` (12x), split the 3
oversized E2E specs, boot disposable E2E Postgres in a single
non-durable start, replay workspace `postinstall` in pure Node (<1s),
cache prebuilt Runner dist and TS 7 `.tsbuildinfo` from canonical
`master` pushes (read-only in PRs), use emit-only server compile in
ordinary PR `Build`, rebalance all shard duration manifests, demote 48
new non-invariant soak whales to nightly, and route audited prose docs
cleanly.

## What Changed

- **Pure-Node postinstall replay
(`scripts/replay-workspace-postinstall.mjs`,
`.github/actions/setup-ci-dependencies/action.yml`):** Replaces the 28s
`pnpm -r --if-present run postinstall && pnpm run postinstall` call on
every CI job with a pure-Node parallel runner (~0.84s locally) with
fallback for older checkouts.
- **4-way sharded `Runner support suite` + `threads` pool
(`.github/ci-task-matrix.json`, `.github/workflows/pr-trusted.yml`,
`tests/runner-e2e/run-unit.mjs`, `tests/runner-e2e/vitest.config.ts`):**
Shards Vitest and `node:test` suites 4 ways (`--shard-index 0..3
--shard-count 4`) and switches `tests/runner-e2e` to `pool: "threads"`
with CPU-aware `maxWorkers` while preserving `isolate: true`.
- **12-way E2E shards, single-start E2E Postgres boot, and 3 oversized
spec splits (`tests/e2e/start-e2e-server.ts`, `tests/e2e/*.spec.ts`,
`tests/e2e/playwright.config.ts`, `scripts/e2e-shard.mjs`,
`scripts/e2e-shard-durations.json`, `.github/ci-task-matrix.json`):**
Boots cold ephemeral E2E Postgres in one `initdb --no-sync` +
non-durable `postgresql.conf` start overlapped with server module
import; splits `agent-chat-projects`, `chat-adapters-ui-providers`, and
`chat-adapters-ui-messaging` cleanly with zero tests removed; balances
all 54 specs across 12 shards (6.8s spread).
- **Incremental TS 7 typecheck & Runner dist caching
(`server/scripts/typecheck-layers.mjs`, `scripts/ci-typecheck-lane.mjs`,
`scripts/typecheck-test-programs.mjs`,
`scripts/typecheck-test-projects.mjs`,
`.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`):** Preserves portable
`.tsbuildinfo`/`.d.ts` with `layer-map.json` invalidation and
stale-declaration pruning, wires read-only `runner-dist-v1` and
`typecheck-incremental-v1` restores in `pr-trusted.yml` (zero
`actions/cache/save`) paired with canonical-`master`-only guarded
writers in `release-verify.yml`, skips redundant Runner Rust `cargo
check` on TS-only shared PRs, and uses LPT scheduling with concurrency 3
(4-core) / 4 (8-core).
- **Emit-only PR `Build` & audited prose doc routing
(`.github/workflows/pr-trusted.yml`, `.github/scripts/ci-inputs.mjs`):**
Passes `PAPERCLIP_TSC_EMIT_ONLY=1` on ordinary PR `Build` jobs (full
`pnpm build` on `full-ci` / `master`), and classifies audited prose
Markdown under `doc/**` and `docs/**` as `guidance` / `historical` while
keeping `docs/api/**`, JSON/TS fixtures, `maps/**`, and unknown files
fail-closed.
- **Rebalanced shard manifests & new soak demotions
(`scripts/ci/nightly-only-suites.json`,
`scripts/*-shard-durations.json`,
`packages/paperclip-runner/scripts/vitest-lane-durations.json`,
`packages/paperclip-runner/vitest.config.ts`,
`packages/paperclip-runner/scripts/vitest-sequencer.mjs`):** Demotes 48
newly landed/grown non-invariant soak suites (including 4 real-SSH
integration suites) to nightly, refreshes all 4 timing manifests from
live CI measurements (0.1s–0.6s LPT skew), and scales Runner package
Vitest CI `maxWorkers` to 3 on 4-core / 6 on 8-core.

## Verification

- `node --test .github/scripts/tests/*.test.mjs
scripts/__tests__/runner-release-crate-cache.test.mjs
scripts/__tests__/public-install-closure.test.mjs
scripts/__tests__/merge-queue-checks-workflow.test.mjs
scripts/__tests__/e2e-shard.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
scripts/__tests__/runner-vitest-package-lanes.test.mjs
scripts/typecheck-test-programs.test.mjs
scripts/check-test-budget.test.mjs
scripts/ci/test-selection-pr-timings.test.mjs
scripts/ci/test-selection-timings.test.mjs` — **973/973 PASS**
- `node scripts/check-test-budget.mjs --base origin/master` — **PASS**
(`609` nightly suites validated, zero protected invariants demoted)
- `node scripts/check-maps.mjs` — **PASS**
- `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/source-sdk-public-inputs.test.mjs
tests/runner-e2e/unit-launcher.test.mjs` — **PASS**
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
scripts/vitest-sequencer.test.mjs` — **PASS**
- `cd server && node ../node_modules/vitest/vitest.mjs run
scripts/typecheck-layers.test.mjs
scripts/typecheck-layers-incremental.test.mjs` — **56/56 PASS** (real TS
7.0.2 incremental soundness tests)
- `node scripts/run-tsc.mjs -p tests/e2e/tsconfig.json --noEmit && node
scripts/run-tsc.mjs -p tests/tsconfig.playwright.json --noEmit && pnpm
run test:e2e:runner:typecheck` — **0 errors**
- Live Playwright smoke passed across all 6 split E2E spec files on the
cold non-durable Postgres boot path
(`PAPERCLIP_TEST_POSTGRES_TEMPLATE=0`).
- Live sharded `tests/runner-e2e` runs passed under `pool: "threads",
maxWorkers: 4` (shard `1/4` 172/172 PASS; shard `2/4` all Vitest + 65/65
`node:test` PASS).

## Risks

- **Cache invalidation on incremental typecheck / Runner dist:**
Mitigated by exact-key hashing (including
`packages/{shared,adapter-utils,plugins/sdk}/src/**` and
`packages/paperclip-runner/spec/**`) with no `restore-keys:` on
`runner-dist-v1`, SHA-256 self-validation inside
`prepare-runner-vendor.mjs`, `layer-map.json` invalidation + stale
`.d.ts` pruning in `typecheck-layers.mjs`, and read-only PR restores
(only canonical `master` pushes save caches).
- **Shard rebalancing & soak demotions:** All demoted suites remain in
`nightly-only-suites.json` and run on `full-ci` / `master` / nightly;
`check-test-budget.mjs` enforces zero protected invariants are demoted.
- **Workflow security boundaries:** `ci-routing.yml`, `pr.yml`,
`CODEOWNERS`, and all `runs-on:` expressions are unchanged;
`pr-trusted.yml` performs zero `actions/cache/save` calls.

## Model Used

- Google Gemini (Antigravity agent swarm) with extended reasoning, tool
use, and local code/test execution across 6 parallel worker roles
(`ci-pipeline`, `vitest-runner`, `server-prune`, `e2e-opt`,
`typecheck-opt`, `verifier`).

## 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
2026-11-24 13:25:46 -06:00
3ca9b6d471 refactor(plugin-sdk): remove archivedState from the resume result (#22443)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native Runner sessions can run in a remote environment task that a
plugin provider owns
> - A provider can relaunch a parked Runner as the next run, and it
reports the result to Core
> - The resume result could carry `archivedState`, so Core could check
that the park was a settled cut
> - #22442 makes the provider the authority on the park, and Core stops
reading `archivedState`
> - This pull request removes the field from the SDK result schema
> - The benefit is a smaller provider contract with no unused fields

## Linked Issues or Issue Description

Refs #22442

**What existing behavior does this improve?**

The environment task resume result contract in the plugin SDK.

**Subsystem affected**

`packages/plugins/sdk` (environment tasks), and the tests in
`server/src/services/native-runtime` that build resume results.

**Current behavior**

After #22442, a resumed relaunch result can carry an optional
`archivedState`. Core accepts it and does not read it.

**Proposed behavior**

The resume result has no `archivedState` field. The strict schema
refuses it.

**Reason and benefit**

The field has no reader. Removing it keeps the contract to the fields
that Core uses.

**Breaking changes**

A provider that still sends `archivedState` on a resume result fails the
schema check, and the relaunch fails. Deploy this with or after the
provider change that stops sending the field.

**Additional context**

Stacked on #22442.

## What Changed

- SDK: removed `archivedState` from the `resume` result schema, and
simplified the relaunch check in `parseEnvironmentTaskResult`.
- SDK test: a relaunch result with `archivedState` now fails; one
without it passes.
- `plugin-runner-task.test.ts`: removed the field from the fixtures, and
removed the test that checked Core ignores it.
- `plugin-runner-release-resume.integration.test.ts`: the fixture
provider no longer returns the field.
- `doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md`: removed the note about the
field.

## Verification

- `pnpm run typecheck` in `server` (builds all dependent packages):
pass.
- `pnpm vitest run
src/services/native-runtime/plugin-runner-task.test.ts` in `server`: 116
passed.
- `pnpm vitest run tests/environment-task-release-resume.test.ts` in
`packages/plugins/sdk`: 48 passed.
- I did not run the embedded-Postgres integration suite locally. CI runs
it.

## Risks

- A provider that still sends the field makes the relaunch fail. Deploy
this with or after the provider change that stops sending it. It can
ship in the same deploy as #22442.
- Low risk otherwise: the change removes an unused optional field.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code with tool use
(shell, file edit, code search). Extended thinking on.

## 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

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 10:25:32 -08:00
0b2acfb956 refactor(runner): let the provider decide whether a released Runner relaunches (#22442)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native Runner sessions can run in a remote environment task that a
plugin provider owns
> - After a turn, the provider can park the Runner, and the next run can
relaunch it from the saved state
> - Core kept its own local record of each released Runner, and the
provider kept its park record too
> - Core lost its copy when the local session directory was not durable.
Then Core restored from a checkpoint although a park existed, and the
turn was slower
> - This pull request makes the provider the only authority on the park.
Core resumes the source from its durable checkpoint, and the provider
answers "resumed" or "unavailable"
> - The benefit is fewer missed relaunches, and less code in Core

## Linked Issues or Issue Description

**What existing behavior does this improve?**

The relaunch of a parked Runner for the next run of a native session.

**Subsystem affected**

Native runtime: `server/src/services/native-runtime`, the Runner control
plane in `packages/paperclip-runner`, and the environment task SDK.

**Current behavior**

Core writes a released-Runner record (source identity, task id and scope
digest) to the local session directory when a release completes. Core
relaunches a parked Runner only when that record exists. Core also
checks the archived Runner state on the provider's relaunch reply. When
the local directory is gone (for example, after the server process
restarts on a new host), Core restores from a checkpoint into a fresh
task, although the provider still has the park.

**Proposed behavior**

Core resumes the source identity from its durable controller checkpoint
on the lease's current task. The provider decides from its own park
record. When no park of that source exists, the provider answers
`unavailable`, and Core starts a fresh task from the saved session, as
it does today for other unavailable answers.

**Reason and benefit**

One record for one fact. Core no longer needs local state to relaunch,
so more runs relaunch. The change removes about 160 lines.

**Breaking changes**

A provider must answer `unavailable` when it has no park for the
requested source. A provider that answers with an error instead makes
the resume fail. The `archivedState` field on a resumed relaunch result
becomes optional. Providers can continue to send it; Core does not read
it.

**Additional context**

Reattach to a live Runner process in the same server is not changed. A
relaunch after a restart still requires the process configuration to
match, because the relaunch reuses the parked launch. A changed
configuration starts a fresh task.

## What Changed

- Removed the local released-Runner record: its writer, its readers, the
scope digest, and the resume and retire callbacks that cleared it.
- Derived the relaunch source from the durable Runner identity. Kept the
check that the task is the lease's current task.
- After a restart, Core takes the released source from the durable
identity for every provider that releases tasks: one that relaunches the
parked Runner, and one that hands it over.
- Added a test that a checkpoint saved with the old released-Runner
record still loads.
- When a restart recovery resumes a released source and the provider
answers `unavailable` with the task stopped and its state saved, Core
now starts a fresh task from the saved session, as it does for a
relaunch. The fallback finishes the old task's startup context before it
inspects the replacement task. An executor test covers this path.
- Updated the SDK source pin in
`tests/runner-e2e/source-sdk-public-inputs.json`.
- Stopped the check of the archived state on the relaunch reply. Removed
`isSettledReleasedRunnerCut` and the resume `settled` hook.
- SDK: a resumed relaunch result no longer requires `archivedState`.
- Updated `doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md` and the tests.

## Verification

- `pnpm run typecheck` in `server` (builds all dependent packages):
pass.
- `pnpm vitest run
src/services/native-runtime/plugin-runner-task.test.ts
src/services/native-runtime/remote-warm-session-recovery.test.ts` in
`server`: 147 passed.
- `pnpm vitest run
src/services/native-runtime/native-session-executor.test.ts -t "releases
settled|accepts only the
attached|released|relaunch|warm|unavailable|recover"` in `server`: 594
passed.
- `runnerd-codex-transport.test.ts` in `packages/paperclip-runner`: 337
passed.
- SDK release and resume tests in `packages/plugins/sdk`: 48 passed.
- `runnerd-codex-transport-release-resume.test.ts -t relaunched` in
`packages/paperclip-runner`: 3 passed. `pnpm run typecheck` in
`packages/paperclip-runner`: pass.
- `tests/runner-e2e/source-sdk-public-inputs.test.mjs`: 13 passed.
- `plugin-runner-release-resume.integration.test.ts -t "completes claude
runs through a retained adopted process"`: pass. I did not run the rest
of the two embedded-Postgres integration suites locally. CI runs them.

## Risks

- A provider that does not answer `unavailable` for a missing park makes
the resume fail. Deploy the provider change first, or in the same deploy
before this Core version takes traffic. This PR and #22443 are one stack
and can ship in one deploy.
- A server restart now relies on the existing unavailable-reuse fallback
to start a fresh task. Tests cover this path.
- Medium risk overall: the change is in the warm-session path. The cold
path is not changed.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code with tool use
(shell, file edit, code search). Extended thinking on.

## 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: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 10:25:32 -08:00
DottaandClaude Opus 5.5 8b616b949d fix(connections): drop MCP wording and the MCP guide link from Google Workspace setup (#22793)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use Google Workspace through the built-in Google Workspace
connection
> - Since #22634, Gmail, Drive, Docs, Sheets, Slides, and Calendar run
on Paperclip's own REST tools, not on Google's hosted MCP servers
> - The connect screen still showed "Secure MCP sign-in" and a "Review
requirements" link to Google's MCP servers guide
> - This text is wrong for this connection, it is internal jargon, and
Google's OAuth reviewers read this screen
> - This pull request removes the MCP wording and the MCP guide link
from Google Workspace setup and from its audit details
> - The benefit is that users and reviewers see only true, plain text
for this connection

## Linked Issues or Issue Description

Refs #22634

**What happened?**

On a Cloud workspace, the Google Workspace connect page showed the
subtitle "Secure MCP sign-in" while the sign-in opened and after it
failed to open. The setup page also showed a "Review requirements" link
to `developers.google.com/workspace/guides/configure-mcp-servers`. On a
self-hosted instance, the "How to set up a Google OAuth client" link
went to the same MCP servers guide. Audit details for a Google REST call
showed "Transport: mcp_remote" and "MCP method: tools/call".

**What did you expect to happen?**

The connect page says "Secure sign-in". The Paperclip-managed method on
Cloud has no requirements link, because the user has no requirements to
review. On a self-hosted instance, the customer-owned client method
links to Google's OAuth client guide. Audit details for a Google REST
call do not show MCP terms.

**Steps to reproduce**

1. Turn on the Google Workspace connector in **Settings →
Experimental**.
2. Open **Apps** and choose **Google Workspace**.
3. Start the sign-in, then close or block the sign-in window.
4. Before this change: the header shows "Secure MCP sign-in", and the
setup step shows "Review requirements" with a link to Google's MCP
servers guide.

## What Changed

- `ui/src/features/connections/ConnectionSetupFlow.tsx`:
`OAuthConnectStateScreen` shows "Secure sign-in" for a curated app. A
server that the user pasted as an MCP server keeps "Secure MCP sign-in".
This is generic: there is no Google-specific code.
- `packages/shared/src/app-definitions/google-workspace.json`: remove
the top-level `docsUrl` (the MCP servers guide). The Paperclip-managed
method now has no "Review requirements" link. The customer-owned
method's `consoleLinks.docs` is now Google's OAuth client guide
(`create-credentials#oauth-client-id`). The "Review requirements" link
and the self-hosted "How to set up a Google OAuth client" link both use
it. Its guidance text names the Gmail, Drive, Docs, Sheets, Slides, and
Calendar APIs instead of "the Google Workspace MCP APIs". This file is a
reviewed definition: `scripts/ingest-app-definitions.mjs` copies it
as-is, so a regeneration keeps the fix.
- `server/src/services/tool-gateway.ts`: an audit record for a Google
Workspace REST call no longer has `mcpMethod`.
- `ui/src/pages/tools/AuditTab.tsx`: audit details show the connection
type label ("Remote HTTP") as "Type" instead of the raw `mcp_remote`
value. This uses the same label as the connection's "Connection
details".
- `doc/connections/GOOGLE-WORKSPACE.md`: the self-hosted section links
Google's OAuth client guide.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed pinned
inputs.

## Verification

- Red first, then green:
- `packages/shared/src/google-workspace-setup-links.test.ts`: no Google
Workspace method links the MCP servers guide, the managed method has no
requirements link, the customer method links the OAuth client guide, and
method text has no "MCP". It failed 4/4 before the fix.
- `ui/src/features/connections/OAuthConnectStateScreen.google.test.tsx`:
in the preparing, opening, and "couldn't open the sign-in window"
states, the Google Workspace screen shows "Secure sign-in", no "MCP",
and no link to `configure-mcp-servers`. A pasted server keeps "Secure
MCP sign-in". It failed 3/4 before the fix.
- `server/src/__tests__/google-workspace-rest-transport.test.ts`: the
Gmail REST audit record has no `mcpMethod`. It failed without the server
change.
- `npx vitest run` for shared app definition tests (67 passed),
`ui/src/pages/tools` and `ui/src/pages/apps/app-detail` (121 passed),
and the server REST transport file (53 passed).
- `tsc --noEmit` for `server` and `ui`: no new errors.
- `pnpm verify` exits 2 because a doc under `doc/connections` is a
global CI input. Required CI supplies the broad coverage.

## Risks

- Low risk. Text and link changes only, plus one optional audit field.
- Other curated OAuth apps now show "Secure sign-in" instead of "Secure
MCP sign-in" on the sign-in state screen. The new text is true for every
curated app.
- Audit details for all connectors show "Type: Remote HTTP" instead of
"Transport: mcp_remote".
- Saved Google Workspace connections still show
`https://workspacemcp.googleapis.com/mcp/v1` as the address in
"Connection details". It is the stored connection identity. This pull
request does not change stored data.

## Model Used

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

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:01:21 -06:00
4daeab5c76 Add count, newest-first and lean run reads to customer-success inspection (#22781)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud can inspect a tenant stack read-only through the
customer-success inspection API
> - That API can only list rows in id order. It has no totals, and each
run row holds large JSON columns
> - A customer-success agent must page every run of a stack to find the
latest run or the failed-run total
> - That is too slow and too large for a refresh across many stacks
> - This pull request adds a `count` operation, a creation-time `order`
for lists, and a lean `summary` view for runs
> - The benefit is one small read per metric, with the same read-only,
company-scoped rules

## Linked Issues or Issue Description

**Subsystem affected**

Server: the customer-success inspection API (`/api/customer-success/v1`)
and its shared query contract.

**Problem or motivation**

Customer-success inspection reads cannot answer summary questions. To
get the latest run, the run count or the failed-run count, a reader must
page through every run. Each run row can be hundreds of KB, because it
holds the result, usage, context snapshot and runner profile.

**Proposed solution**

Add read-only summary reads to the inspection contract: a `count` that
groups by status, a newest-first or oldest-first `order` for `list`, and
a `summary` view of runs without the large JSON columns.

**Alternatives considered**

Paging all runs with a smaller page size. That still reads every large
row. A new aggregated endpoint outside the reader catalog. That would
skip the existing catalog, permit and transaction rules.

## What Changed

- `packages/shared/src/customer-success.ts`: add the `count` operation,
`order` (`newest`/`oldest`, `list` only), `view` (`summary`, `runs`
list/get only), `InspectionCount`, and `inspectionReadPath()`. The
parser rejects these fields where they do not apply.
- `server/src/services/customer-success-inspection.ts`: `count` returns
`{total, byStatus}` (grouped by the reader's `status` column, or
`byStatus: null`). `order` sorts by `createdAt`, then id. `view:
"summary"` selects the `RUN_SUMMARY_COLUMNS` allowlist and adds
`durationMs`. All reads stay in the same read-only, repeatable-read
transaction and keep the existing run redaction.
- `server/src/routes/customer-success.ts`: serve the same handler on
`/read` and the new `/read-v2`. `/read` refuses queries that use the new
features. A tenant without `/read-v2` answers 404, so Cloud fails closed
with `tenant_inspection_version_unsupported`.
- `server/src/__tests__/customer-success.test.ts`: tests for counts,
company scope, newest-first paging, the summary allowlist and duration,
parser bounds, and the path split.
- `server/src/__tests__/customer-success-cloud.test.ts`: the registry
double now has the batch reads (`getStacks`, `getAccounts`) that the
current Cloud broker uses. The test also runs a count and a newest-first
summary read end to end.
- `server/src/__tests__/openapi-routes.test.ts`: list `/read-v2` with
the other inspection protocol routes.
- `doc/CUSTOMER-SUCCESS-INSPECTION.md`: document the summary reads and
the path split.

## Verification

- `cd server && pnpm exec vitest run
src/__tests__/customer-success.test.ts
src/__tests__/openapi-routes.test.ts
src/__tests__/customer-success-run-liveness.test.ts`: 78 tests pass.
- Red check: the new count/order/summary test fails against the previous
service (`Unsupported inspection operation`).
- Coordinated qualification with a local build of the Cloud broker
branch: `PAPERCLIP_INSPECTION_CLOUD_DIST=… pnpm exec vitest run
src/__tests__/customer-success-cloud.test.ts` passes, including the
count and newest-first summary reads over `/read-v2`.

## Risks

- Low risk. The new features are read-only and use the existing catalog,
company boundary, permit check and read-only transaction.
- The summary view is an allowlist. A new run column stays out of the
summary until someone adds it.
- Mixed versions are safe in both orders. An older Cloud never sends the
new fields. A newer Cloud sends them only to `/read-v2`, and an older
tenant answers 404 there.
- No migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits) and extended thinking.

## 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:41:16 -06:00
Dotta 0731cd3afc perf(ci): Phase 2 PR CI under 4 minutes (dynamic workers, fast E2E boot, typecheck overlap, test-budget gate) (#22729)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Pull-request CI checks run on every commit before maintainers can
merge code
> - PR #22679 cut PR CI from 15–30+ minutes down toward 4.5–5.5 minutes
on 4-core runners
> - Remaining wall-clock bottlenecks sit in unsharded `workspaces-b`,
serial typecheck preparation, E2E server/UI startup, fixed Vitest worker
caps, and remaining soak and duplicated UI tests
> - This pull request adds Phase 2 optimizations across server soak
triage, typecheck DAG overlap, E2E fast boot and shard balance, dynamic
CPU-aware workers, pure-Node workspace link preflight, UI pruning, and
permanent test-budget enforcement
> - The benefit is ordinary feature PRs finish in ~3.1–3.8 minutes on
4-core runners and scale automatically to ~2.0–3.0 minutes on 8-core
runners while keeping core invariants and nightly coverage intact

## Linked Issues or Issue Description

Refs #22679

**Problem Statement**
After #22679 landed, several PR lanes still took 4.5–6 minutes on 4-core
runners (`general-workspaces-b` ran unsharded, `Typecheck + Release
Registry` waited on a serial server build before starting UI and
test-program checks, E2E shards paid full `cli onboard` + minified UI
build overhead, and Vitest worker counts did not scale with runner CPU
count).

**Proposed Solution**
Split `general-workspaces-b` across two duration-balanced shards,
overlap typecheck preparation tasks behind a shared runner-vendor node,
replace E2E `onboard` with a direct template-PG boot + unminified inline
UI build, scale Vitest/Playwright/Typecheck workers dynamically by CPU
and RAM, replace `tsx` in workspace-link preflight with pure Node, prune
redundant mocked UI tests and additional real-clock server soak suites
(still run on `master`, `release-verify`, `cloud-readiness`, and
`PAPERCLIP_CI_FULL=1`), and add a permanent test-budget policy check.

**Expected Benefit**
Brings ordinary PR CI wall-clock down to ~3.1–3.8 minutes on 4-core
runners (and ~2.0–3.0 minutes on 8-core runners) with automated
guardrails against future test-time regressions.

## What Changed

- **Server soak triage & permanent test-budget guardrail
(`scripts/ci/nightly-only-suites.json`, `rules/test-budget.mdc`,
`.greptile/files.json`, `scripts/check-test-budget.mjs`,
`scripts/check-test-budget.test.mjs`,
`.github/workflows/pr-trusted.yml`):** Expanded the PR-excluded
soak/heavy-integration manifest to 568 genuine heavy suites (preserving
100% of company isolation, authz, checkout, approval, budget,
activity-log, security, telemetry, and serialized suites on every PR)
and wired `node scripts/check-test-budget.mjs` into the `policy` job.
- **Typecheck DAG overlap & CPU/RAM scaling
(`scripts/ci-typecheck-lane.mjs`, `scripts/typecheck-test-programs.mjs`,
`scripts/__tests__/ci-typecheck-lane.test.mjs`,
`scripts/typecheck-test-programs.test.mjs`):** Moved `build server
without type checks` and `check server runtime assets` out of serial
`prepare` into parallel DAG nodes behind `prepare runner vendor`, added
`computeResourceProfile` scaling across 2/4/8-core runners, and added
missing UI/Runner consumer routing inputs (`packages/paperclip-runner/`
for `@paperclipai/ui`, `packages/adapter-utils/` for Runner test
programs).
- **E2E fast boot, dynamic workers & 8-shard rebalance
(`tests/e2e/start-e2e-server.ts`, `tests/e2e/playwright.config.ts`,
`scripts/e2e-shard.mjs`, `scripts/e2e-shard-durations.json`,
`.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`):** Added direct throwaway
template-PG boot (`fsync=off`), unminified inline Vite fallback build,
dynamic parallel workers (`min(4, floor(cpus/2))`), empirical `1.5x`
parallel speedup weighting across 8 shards, targeted trims to slowest
E2E specs, and hashed workspace `package.json` manifests into the
`e2e-ui-dist-v2` cache key.
- **Dynamic Vitest workers, 2-shard `workspaces-b`, and pure-Node
preflight (`scripts/ci/vitest-workers.mjs`,
`scripts/ci/workspaces-b-shard.mjs`,
`scripts/ensure-workspace-package-links.mjs`,
`scripts/ci-dependency-cache.mjs`,
`packages/db/src/test-embedded-postgres.ts`,
`.github/ci-task-matrix.json`,
`.github/actions/setup-ci-dependencies/action.yml`, `package.json`):**
Scaled Vitest workers dynamically (`4→7` general, `3→5` serialized) with
`max_connections=300` before PostgreSQL start, split
`general-workspaces-b` into 2 duration-weighted shards
(backward-compatible unsharded for release workflows), replaced `tsx`
workspace-link preflight with pure Node (~29× faster), and parallelized
`ci-dependency-cache.mjs` child queries.
- **UI Vitest worker scaling, fake timers & E2E-duplicated suite pruning
(`ui/vitest.config.ts`, 4 `maps/` files, and UI test suites):** Scaled
UI `maxWorkers` dynamically, converted real-clock sleeps in kept suites
to fake timers, removed 34 E2E-duplicated mocked jsdom suites, and
updated corresponding `maps/` prose references.

## Verification

- `node --test .github/scripts/tests/ci-plan.test.mjs
.github/scripts/tests/ci-dependency-cache.test.mjs
.github/scripts/tests/pr-dependency-cache.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/typecheck-test-programs.test.mjs
scripts/__tests__/e2e-shard.test.mjs scripts/check-test-budget.test.mjs
scripts/ci/test-selection-pr-timings.test.mjs`: **160/160 PASS**
- `node scripts/check-test-budget.mjs`: **PASS** (`568` nightly suites
validated)
- `node scripts/check-maps.mjs`: **PASS** (`35 areas, 192 capability
IDs`)
- `pnpm --filter @paperclipai/ui typecheck` & `pnpm --filter
@paperclipai/db typecheck`: **PASS**
- Live CI verification runs on the new `pr-trusted.yml@master` (from
#22679) with `profile-ci` enabled to export the full job/step/file
waterfall to Honeycomb `paperclip-ci`.

## Risks

- Medium CI scope: touches workflow matrix partitioning, E2E startup,
and test runners; does not change production app runtime behavior.
- All PR-demoted soak suites continue to execute on `master`,
`release-verify`, `cloud-readiness`, local `pnpm test:run`, and
`PAPERCLIP_CI_FULL=1`.
- All new `policy` and `setup-ci-dependencies` commands keep
file-existence guards so reruns of older PR branches continue to work.

## Model Used

- Google Gemini (Antigravity swarm orchestrating specialized worker
agents with shell, file editing, and test execution tools) and Anthropic
Claude Opus (verification and optimization sub-agents).

## 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
2026-11-24 10:53:19 -06:00
DottaandClaude Opus 5.5 18aa2b353d feat(antigravity): /plan selects Plan mode and keeps Antigravity read-only while planning (#22727)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plan mode lets a person ask an agent for a plan, review it as the
task's Plan document, and accept it before any work starts
> - People who use Google Antigravity agents type `/plan <request>`, as
they do in other agent tools. Paperclip sent that text to the agent, and
#22701 correctly neutralised it, so nothing happened
> - An Antigravity run in Plan mode was also not read-only: the agent
could still edit files and run commands while it "planned"
> - This pull request makes a leading `/plan` in the composer select
Plan mode, and keeps an Antigravity Plan-mode run read-only at its
permission prompt
> - The benefit is that `/plan` with an Antigravity agent gives the
normal Paperclip plan flow (Plan document, accept, then execution on the
same task), and planning cannot change the workspace

## Linked Issues or Issue Description

Refs #22701

**What happened?**
A person wrote `/plan add greeting.txt` to a Google Antigravity agent.
The agent did not plan. In Plan mode the Antigravity agent could still
edit files and run commands.

**What did you expect?**
`/plan <request>` starts Plan mode. The agent researches and proposes a
plan in the task's Plan document. It does not change files until the
person accepts the plan.

**Steps to reproduce**
1. Assign a task to a Google Antigravity agent.
2. Write `/plan Add a file greeting.txt containing hello`.
3. See that the task stays in Auto mode, and that the agent creates the
file.

## What Changed

- Task composer: a leading `/plan` in a comment or in a new task selects
Plan mode and sends the rest of the message without the command. `/plan`
alone only switches the mode. The slash menu offers "Plan". A `/plan`
anywhere else in the message (quoted, pasted, fenced, mid-sentence)
stays ordinary text and does not change the mode. This is the typed form
of the existing Plan mode control, so it works the same for every agent.
- Antigravity runner (`antigravity-plan-mode.ts`, wired in
`acpx-runtime-adapter.ts` and `runtime-host.ts`): when Paperclip runs an
Antigravity task in Plan mode (the existing read-only task policy), the
permission prompt fails closed. It allows only (a) the 1.5.2 server's
built-in research tools (file read, search, directory listing, page
read), named by the exact `Run <tool>?` prompt title, when the reported
kind also matches that tool, and (b) the tools the runner's own
Paperclip bridge registered for this run, on the runner-owned server
named `paperclip`. The provider's reported kind alone never grants a
read, and no other MCP server is trusted, runner-owned or not. It
refuses file edits, terminal commands and everything else. Paperclip's
server applies its Plan-mode rules to its own tools, and the agent
writes the Plan document through them.
- Composer command parsing moved to
`ui/src/components/task-chat/composer-commands.ts`. `/goal` and `/plan`
both use the shared rule. Both submit paths use one `/plan` decision: a
bare `/plan` sends (in Plan mode) only when an attachment can be sent
without text; otherwise it only selects Plan mode. A composer without
Plan mode (the dashboard chat starter) keeps `/plan` as text.
- Follow-up, not in this PR: the Kimi read-only gate
(`kimiReadOnlyPermissionAllowed`) trusts every runner-owned MCP server
by title prefix. It should get the same binding to the Paperclip
bridge's registered tools.
- No change to the #22701 guard. Every `/plan`, `/logout` and `/usage`
that would reach the Antigravity server is still neutralised.
- No change to the Antigravity admission patch, profile or closure
digests. No shared contract change.

### Why not the native `/plan` of Antigravity 1.5.2

I checked the pinned 1.5.2 server and SDK sources and ran it live:

- The server has no plan session mode (only `default`, `auto_edit`,
`yolo`) and no plan config option. Its only route is the `/plan` text
command, which it turns into an SDK slash-command object.
- Live on 1.5.2 (Google sign-in, `gemini-3.8-flash-low`), a task with
`Please /plan this ...` reached the model as
`Please/BuiltinSlashCommandName.PLAN this ...`. The SDK sent the enum's
string form instead of `plan`, so the harness did not enter planning
mode. Over 61 native steps (about 5 minutes) the agent wrote no plan
artifact, ran terminal commands, and searched the file system for that
unknown name. I stopped the run.
- A working native path needs a change inside the runtime (for example
in the owned admission patch), which re-pins the closures for every
platform and needs re-qualification. This PR does not do that.
Paperclip's own Plan mode gives the user-visible result now, with no
re-pin.

### Source of trust for slash commands (reused by `/swarm`)

- `parseLeadingUserCommand(text, allowlist)` in
`packages/shared/src/leading-user-command.ts` is the one rule. It
returns `{ command, argument }` or `null`.
- Trusted text: only what the signed-in user typed and submitted in the
task composer. That is a comment body or the body of a new task.
Conversations (chat) do not use it for `/plan`.
- Never trusted: agent comments, chat or connector messages, API-posted
text, issue text written by someone else, quoted or pasted parts, and
every prompt Paperclip builds for an agent. These stay text, and the
#22701 guard still neutralises any native command in them.
- Inside trusted text, only a command at the very start counts: optional
whitespace, `/name`, then whitespace or the end. The name is exact and
lower-case and must be in the allowlist. Only `plan` is enabled.
Whitespace follows the Antigravity server's Python rules (U+001C-U+001F
count; U+FEFF does not).
- A recognised command becomes a structured action (here: Plan mode). It
never reaches an agent as command text.
- Tests cover: leading whitespace and newlines, a command not at the
start, quoted, fenced, forwarded and wrapped content, a neutralised
command, case, `/planning`, `/plans`, paths and URLs, Python vs
JavaScript whitespace, and the allowlist.

## Verification

- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/drivers/acpx/antigravity-plan-mode.test.ts
src/drivers/acpx/acpx-runtime-adapter.test.ts
src/drivers/acpx/antigravity-native-commands.test.ts
src/drivers/acpx/antigravity-admission.test.ts`: 250 passed.
- `pnpm --filter @paperclipai/shared exec vitest run
src/leading-user-command.test.ts`: 8 passed (red first: module missing).
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/task-chat/TaskChatComposer.test.tsx
src/components/MarkdownEditor.autocomplete.test.tsx`: all passed
(TaskChatComposer 155).
- Red before the fix: the adapter test showed an Antigravity Plan-mode
run approved a file write and a terminal command (`allow_once`), and the
four composer `/plan` tests failed. The negative test (a `/plan` inside
the message stays text) passed before and after.
- Runner and UI typecheck pass (`tsc --noEmit`; the UI's only errors are
the existing ungenerated Storybook catalog files).
- `pnpm verify` returned exit 2 (runner files outside the local test
graph), so required CI supplies the broad coverage.
- Live, on THIS branch: a local instance running this branch, Google
sign-in, `gemini-3.8-flash-low`, driven in the browser through the task
composer:
1. `/plan Create a file named plan-proof.txt containing the single line
OK` in a new task: the task was created in Plan mode with the command
removed. Plan run 3 min 34 s, terminal state **succeeded** (the agent
handed in through `paperclip_finish`; run result accepted, waiting for
plan approval). The Plan document and a Confirm / Request changes card
appeared. One `ls -la` was refused by the read-only gate. No file was
written.
2. Request changes ("Name the file plan-proof-2.txt instead."): revision
run 28 s, succeeded. Plan document revision 2 named the new file; a new
Confirm / Request changes card appeared. Still no file.
3. Confirm: execution run 55 s, succeeded; task Done; `plan-proof-2.txt`
contains exactly `OK` plus a newline.
4. Normal task whose text contains a pasted `"we usually /plan things
like this first"`: created in standard mode, text unchanged; run 68 s,
succeeded, Done; `negative-proof.txt` = `NEG`; no refused tool call.
5. Dashboard "Start a chat" box: NOT run live. The box renders only with
an experimental instance setting that is off on this instance, and I did
not change instance settings. A unit test covers it (a composer without
Plan mode keeps `/plan` as text).
6. Stop during a Plan-mode run: the run was cancelled about 1 s after
Stop and did not revive (no new run for over 3 min); no file. Killing
only the native Antigravity server process mid Plan-mode run: the run
failed with a provider error, showed "Continuing automatically", and a
continuation run started 36 s later and settled (succeeded, 3 min 17 s,
response wake). No duplicate comments; the Plan document has one
revision; no file written; the gate refused one shell command in each
run.
- Found live, NOT fixed here: in the recovered run of step 6 the model
settled with "waiting for plan review" but did not open the Confirm card
(in steps 1 and 2 it did). Paperclip creates that card automatically
only from a harness's own plan proposal (Codex, Claude). For Antigravity
it depends on the agent. Recommended follow-up: when a Plan-mode run
settles with a new plan revision and no pending plan confirmation, the
server opens the card itself.
- To be clear: this is not Antigravity's native plan mode. Native plan
mode on runtime 1.5.2 does not work (see above). This PR gives
Paperclip's Plan mode, started by a trusted `/plan`, with the
Antigravity run held read-only.

## Risks

- Low to medium. Plan mode for Antigravity now refuses terminal
commands, so the agent researches with its file read and search tools. A
planner that relied on shell reads must use those tools instead.
- Google Workspace accounts whose admin policy lets terminal commands
run in a sandbox without a prompt skip the permission prompt for
commands. That path cannot be blocked here. Personal Google accounts and
API keys always prompt.
- `/plan` as the first word of a message now selects Plan mode for every
agent. To send the literal text, write `\/plan` or put other text first.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell,
file edit, browser automation not used), 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>
2026-11-23 22:33:09 -06:00
DottaandClaude Opus 5.5 b908678ea3 fix(connections): leave no connection behind when a first sign-in is cancelled (#22714)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agents use apps through connections. Most app connections use an
OAuth sign-in.
> - Paperclip saves a draft connection before it opens the provider
sign-in page.
> - When the user cancels or abandons that sign-in, the draft stays. The
Apps list counts it as a connection that "needs attention".
> - The user did not ask for that connection, and the user must not
clean it up by hand.
> - This pull request hides drafts that never finished their first
sign-in and removes the draft when the user clicks Cancel.
> - The benefit is that a cancelled sign-in leaves no visible
connection, and a retry makes exactly one connection.

## Linked Issues or Issue Description

Refs #22634

**What happened?**

A workspace has one working "Google Workspace for the organization"
connection. The user clicks "Add account", chooses services, and clicks
Continue. The page shows "Opening Google Workspace…". The user clicks
Cancel before finishing at Google. The Apps page then shows "2
connections · 1 needs attention".

**What did you expect to happen?**

A cancelled sign-in leaves no visible connection. The same applies when
the user closes the page, reloads it, closes the Google tab, or refuses
consent at Google. A retry after a cancel makes exactly one connection.
A cancelled reconnect of a working connection does not change that
connection.

**Steps to reproduce**

1. Connect one Google Workspace account.
2. Open Apps, then Google Workspace, then "Add account".
3. Click "Continue to sign in", choose services, and click Continue.
4. On the "Opening Google Workspace" page, click Cancel.
5. Look at the Google Workspace card on the Apps page.

## What Changed

- Root cause: `connectApp` saves an OAuth draft (`status: "draft"`)
before sign-in (`server/src/services/tool-access.ts`, the connection
insert in the connect path). Cancel only navigated away. The Apps list
counted every draft as "needs attention"
(`ui/src/pages/apps/Browse.tsx`, `connectionState` and the attention
count).
- New module
`server/src/services/tool-access/connections/first-sign-in.ts`. It
decides if an OAuth draft never held a credential. It checks for OAuth
tokens on the connection and its grants, legacy inline tokens (the
removal module's list), a provider consent time, an external credential,
and the markers a real connection keeps when it needs a new sign-in. If
any check is not clear, the connection counts as real.
- The connection list endpoint sets `firstSignInPending: true` on those
drafts. The shared `ToolConnection` type has the new field.
- New route `POST /tool-connections/:connectionId/sign-in/cancel`. It
checks company access and configure permission. It removes the draft
with the normal removal teardown (grants, OAuth states, bindings) only
if the draft never held a credential. For any other connection it
changes nothing and returns `abandoned: false`. A removal writes the
activity entry `tool_connection.sign_in_cancelled`. The route is in the
OpenAPI registry.
- The Apps list does not show connections with `firstSignInPending`, and
it does not show an app whose only connections are such drafts. The
check is one pass with `Set` lookups.
- Cancel works in one transaction: it deletes the pending sign-in
states, locks the connection, checks it again, and parks it as
`disabled` with the marker `oauth_sign_in_cancelled`. If the connection
must stay, the transaction rolls back. Then the normal removal archives
the parked draft. Setup never reuses a parked draft, so a retry during
the removal gets its own row.
- One predicate, `connectionRemovedOrSignInCancelled`, guards
authorization start, access finish and machine sign-in. The direct,
Cloud and Vercel Connect callbacks and the access finish step lock the
connection before they write a grant or activate it, and return 409
`oauth_sign_in_cancelled` for a parked draft.
- `docs/api/tool-connections.md` documents the cancel route and the list
flag.
- The setup page calls the cancel route when the user clicks Cancel on
the sign-in screen. It does this only for a draft that this page made.
It does not do this for a resume, a reconnect, or a task-linked setup.
- Design for abandoned drafts (tab closed, reload, consent refused):
they are not listed, and the next attempt reuses them through the
existing draft reuse in setup. No background cleanup job is added.

## Verification

-
`server/src/__tests__/tool-access-cancelled-first-sign-in.integration.test.ts`
runs the real routes against embedded Postgres and a local OAuth
provider. It covers: a draft is marked and hidden; a provider token
exchange held open across Cancel ends in 409; Cancel and a retry at the
same time leave exactly one active connection; a parked draft is hidden
and refuses a new sign-in start; a legacy draft with an inline token is
not cancelled; Cancel removes it, deletes its OAuth state, logs
activity, and a late callback fails; a retry after Cancel gives exactly
one live connection (organization and personal); Cancel does not change
an active connection or a connection that needs a new sign-in; a draft
refused at the provider stays hidden and Cancel removes it; another
company cannot cancel the draft.
- `ui/src/pages/apps/Browse.test.tsx`: a pending draft is not listed and
does not add "needs attention".
- `ui/src/pages/apps/AppsConnect.test.tsx`: Google Workspace setup,
Continue, then Cancel calls the cancel route for the new draft.
- Red/green: the new Browse and setup tests fail without the UI change.
The server test fails on master because the route and flag do not exist.
- Local runs: the new server file, `openapi-routes.test.ts`,
`tool-access-oauth-protocol.integration.test.ts`, `Browse.test.tsx`,
`AppsConnect.test.tsx`, `activity-format.test.ts`, and
`src/features/connections` pass. Server typecheck passes. `pnpm verify`
exits 2 because of the pinned inputs file, so CI supplies broad
coverage.
- Not done: a real browser test against Google.

## Risks

- Low risk. The cancel route fails toward no change: it removes nothing
that shows any sign of a credential.
- Cancel and a late provider callback agree under the connection row
lock. If the callback commits first, Cancel changes nothing. If Cancel
commits first, the callback returns 409 and saves nothing. This covers
the direct, Cloud and Vercel Connect callbacks and the access finish
step.
- If the removal after Cancel fails, the draft stays parked and hidden,
and a second Cancel finishes it.
- A connection that was removed before and is now added again keeps its
old consent record. If that new sign-in is cancelled, it stays as a
visible draft, as it does today.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:16:28 -06:00
fe2db1c32b feat(ui): show the Cloud Slack invitation in the workspace sidebar (#22702)
## Thinking Path

> - Teams use Paperclip to manage agents and their work.
> - Hosted teams can have a private Slack channel with the Paperclip
team.
> - A workspace member needs to know whether they can open the channel
or still need the owner's invitation.
> - Cloud supplies that information for the selected organization.
> - This change puts a Slack button in the sidebar footer. It opens a
dialog with the next action.

## Linked Issues or Issue Description

**Subsystem affected**

Workspace sidebar and the Cloud onboarding browser journey.

**Problem or motivation**

After setup, a user can lose track of the invitation to their
organization's private feedback channel.

**Proposed solution**

Show the invitation status in a dialog. Offer a channel link when Cloud
confirms the connection.

**Roadmap alignment**

This extends the existing hosted workspace navigation. The roadmap has
no separate item for this shortcut.

## What Changed

- Both sidebar variants use the existing portfolio request to show the
Slack shortcut when Cloud supplies invitation details.
- The icon uses grayscale at rest and brand colors on hover or keyboard
focus. The button has an accessible name and a tooltip.
- The Cloud onboarding journey selects Codex and confirms feedback
intent when the first-account welcome appears.
- Storybook covers pending and connected channels.

## Verification

- The sidebar suite passed 36 tests. The Cloud onboarding journey suite
passed 10 tests covering both the current and previous gateway layouts.
- The Storybook catalog regenerated successfully.
- In a local browser run, a fresh user completed signup, connected a
test model, hired an agent, opened its chat, and opened and dismissed
the Slack invitation. The test used a local Slack fixture.
- The incremental verifier selected broad CI coverage for the runner
journey change.

All applicable checks passed on `ea9779abda`. A GitHub runner shut down
during a server test shard. The shard and final verification gate passed
on retry. [CI
run](https://github.com/paperclipai/paperclip/actions/runs/45276376121/attempts/2)
· [Greptile review
(5/5)](https://github.com/paperclipai/paperclip/pull/22702#issuecomment-7115303606)

## Risks

An older Cloud service can omit the optional feedback field. In that
case, the sidebar keeps the existing layout. Cloud controls the channel
destination and the invitation state.

## Model Used

OpenAI GPT-6 in Codex, with repository tools and browser verification.

## 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>
2026-11-23 14:38:55 -08:00
Devin FoleyandPaperclip 298026eadc fix(ai-connections): reconnect typed auth failures and stop quota retry countdowns (#22692)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Runs preserve typed provider failures so recovery can select the
right next action.
> - Authentication repair still recognized only older run error codes.
Native typed authentication failures could miss the reconnect request.
> - A typed exhausted quota with no reset also produced an estimated
one-hour admission hold. Waiting cannot repair that account.
> - This pull request uses the existing reconnect and validated adoption
flow for authentication. It asks for billing and usage repair for typed
quota exhaustion without a reset.
> - Rate limits and provider-reported resets keep their existing
automatic waits. Account authority, saved-work checks, pauses, and
approvals keep their existing gates.

## Linked Issues or Issue Description

Refs #15110. That open PR classifies the legacy Claude monthly-spend
message. This change does not duplicate its adapter parsing or change
older untyped quota recovery.

Refs #21351. That open PR changes legacy Claude edge-error
classification and repeated-failure latching. This change consumes the
typed provider category and retains the existing credential-generation
checks.

**What happened?**

A failed run with `providerFailure.category: authentication` and a
generic native error code did not create its reconnect request. A typed
`quota_exhausted` failure without a reset produced an estimated provider
cooldown, although the account needed attention. Recovery's narrow
PostgreSQL result projection also omitted typed native provider
failures.

**Expected behavior**

Ask the responsible person to repair the selected account or explicitly
adopt a compatible managed connection. Ask for billing and usage repair
when an exhausted allowance has no reported reset. Continue to wait
automatically for transient rate limits and reported allowance resets.

**Steps to reproduce**

Use a failed native run with a typed OpenAI authentication error and a
generic native error code. The existing reconnect controller should
create one card. Use typed `quota_exhausted` evidence with no reset. The
task should offer account review and manual Retry, with no invented
reset or automatic provider retry.

## What Changed

- Recognize typed authentication failures and the reported
`provider_invalid_credentials` run code. Reuse the existing
controller-only reconnect request, account freshness checks, durable
continuation, and explicit legacy adoption.
- Retain typed provider failures in the bounded PostgreSQL recovery
projection.
- Refresh the reviewed SDK public-source pin for the changed shared
interruption type with the repository generator.
- Keep typed quota exhaustion without a reset out of provider cooldown,
bounded retry, and periodic quota-recovery paths. A newer billing
refusal supersedes older reset evidence. Classify a startup billing
refusal before the remote exit-confirmed retry branch, and prevent the
startup planner from falling back to plain backoff.
- Add the derived `provider_billing` task action, an account-review
link, and a matching Inbox label. Preserve saved-work recovery and
current user gates.
- Update the connection documentation for these recovery decisions.

## Verification

- Red: five server regressions failed on current master for typed
authentication, the invalid-credential code, a false quota cooldown, and
the missing billing action. The new task notice regression also failed
before the repair.
- Green: the first focused set passed 241 tests. The final
quota/retry/UI set passed 281 tests. The database-backed reconnect set
passed seven selected cases for Claude, OpenAI, method switching, and
explicit legacy adoption. Sets overlap; these counts are not additive.
- Database tests check current account attribution, refreshed credential
generations, bounded result projection, and preservation of reported
resets. A quota without a reset must not schedule a successor. Two
additional startup regressions failed before the startup repair. The
repaired startup suites pass all 45 integration cases and 11 focused
classification cases. They check a blocked task, billing presentation,
no retry deadline, no resumable claim, and preserved retries for rate
limits and reported resets.
- `pnpm check:token-gates` and `git diff --check` passed.
- The earlier [Runner support
failure](https://github.com/paperclipai/paperclip/actions/runs/45263306284/job/138003893674)
came from a stale reviewed SDK source pin. The same three SDK evidence
files failed locally on `cacdb81`. Regenerating the pin from that
committed tree made all 59 tests in those files pass. Only the shared
`execution-projection.ts` source hash changed; lock and runtime pins
remain unchanged.
- `pnpm build` and repository-wide `pnpm -r typecheck` passed for the
initial change. The authentication/recovery policy set also passed 99
tests. Server typecheck and build also passed for the startup repair at
`cacdb81c26988394e11f934d05531bcbb121c7a2`. The full local `pnpm
test:run` stopped in chat shard 4/6 with 15 failures: fourteen
file/database-open failures during `ENFILE` file-table exhaustion and
one retry polling timeout. The failed run also reported an unhandled
`ENFILE` error. All 40 selected chat cases, including those 15 failures,
passed in a fresh process on `06c14a8`. This does not qualify the full
local suite. The complete CI workflow passed on the final head, as
recorded below.
- Local environment: isolated macOS arm64 checkout and disposable
PostgreSQL fixtures. The branch was replayed onto master at
`32375d302fbc3a233531674aedefa273adee2d97`; that base change touches an
unrelated migration test.
- Live provider account repair and the original reported credential
failure remain unverified. A read-only operational trace confirmed
retained runner checkpoint versions, but the reported runtime string was
absent from retained onboarding and run logs as well as current Core and
available Cloud source refs. Its producer remains unidentified.

- [Trusted PR CI, attempt
2](https://github.com/paperclipai/paperclip/actions/runs/45265943006/attempts/2)
completed successfully on `06c14a8cbcf2480eb9d2841bebda3337d4248bd6`,
including typecheck, build, Runner, serialized server, general test, and
browser suites. The previously cancelled serialized suite passed on that
attempt. All 59 commit checks are terminal: 56 succeeded and three
conditional checks were skipped. The Snyk commit status also passed.
- Greptile completed on `06c14a8cbcf2480eb9d2841bebda3337d4248bd6` with
5/5 and no new findings. Both earlier review threads are resolved.

## Risks

- A typed exhausted allowance without a reported reset now requires
account repair. Older untyped quota errors retain their existing
recovery policy; #15110 remains separate.
- Authentication repair must follow the recorded account rather than
infer an account from a proxy driver's upstream name. Existing
generation checks must still protect newer credentials.
- No schema migration or provider replay authority is added. Existing
stored runs keep their data. The new task action is derived at read
time.
- Live recovery of the originally reported incident remains unverified;
the operational trace did not locate the reported runtime code.

## Model Used

OpenAI `gpt-6.1-sol`, through the Codex harness in T3 Code, with xhigh
reasoning effort, tool use, code editing, and test execution. The
harness does not expose the context-window size.

## 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>
2026-11-23 14:37:16 -08:00
DottaandClaude Opus 5.5 8c6e5cbbb8 fix(connections): offer Paperclip's Google sign-in on Paperclip Cloud only (#22699)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use Google Workspace through a connection. A connection can
use Paperclip's own Google sign-in ("Connect with Paperclip") or the
customer's own Google OAuth client
> - Paperclip's own Google sign-in goes through the Paperclip Cloud
broker with Paperclip's verified Google client
> - Google's restricted-scope verification and security assessment cover
only the servers that Paperclip operates
> - The owner decided on 2026-11-23: Paperclip's own Google sign-in is
for Paperclip Cloud workspaces only. Self-hosted instances use their own
Google OAuth client
> - This pull request hides and refuses Paperclip's own Google sign-in
on self-hosted instances, keeps saved connections working, and gives
clear guidance
> - The benefit is that restricted-scope Google tokens stay on servers
that Paperclip operates, and self-hosted users always see a path that
works

## Linked Issues or Issue Description

Refs #22635

**What happened?**

A self-hosted Paperclip instance offered "Connect with Paperclip" for
Google Workspace and other Google apps. That sign-in uses Paperclip's
verified Google client. It sends restricted-scope Google tokens to a
server that Paperclip does not operate. A self-hosted instance also
offered Paperclip Cloud enrollment only to use that sign-in.

**What did you expect to happen?**

Paperclip's own Google sign-in is available only on Paperclip Cloud
workspaces. A self-hosted instance shows only "Use your own Google OAuth
app", with a short reason and a link to a setup guide. Saved Google
connections on a self-hosted instance keep working until a sunset date
that the owner sets on the Paperclip Cloud broker. After that date, the
connection tells the user to reconnect with their own Google client.
Paperclip Cloud workspaces do not change.

**Steps to reproduce**

1. Run Paperclip without Paperclip Cloud markers (self-hosted).
2. Turn on the Google Workspace connector in **Settings →
Experimental**.
3. Open **Apps** and choose **Google Workspace** or **Gmail**.
4. Before this change: setup offers "Connect with Paperclip" or asks to
connect the instance to Paperclip Cloud first.

## What Changed

- `packages/shared/src/google-sign-in-deployment.ts`: new
`appDefinitionForDeployment` and `isCloudOnlyConnectionMethod`. On a
self-hosted instance they remove every Paperclip-managed Google method.
Other providers do not change. New shared message
`GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE`.
- `server/src/services/google-sign-in-availability.ts`:
`paperclipGoogleSignInAvailable()` returns `isCloudManagedInstance()`.
This is the existing single Cloud check. No new environment variable.
- `appWithPaperclipCloudConnectorAvailability` (gallery and setup
validation) uses that check. A self-hosted gallery and setup do not show
managed Google methods.
- `authorization-start.ts`: a self-hosted instance refuses to start a
managed Google authorization before it calls Paperclip Cloud (`422`,
code `google_sign_in_cloud_only`). A broker refusal with
`PROVIDER_CLOUD_ONLY` maps to the same message, also on a Cloud
instance.
- `paperclip-cloud-connector.ts`: `PROVIDER_CLOUD_ONLY` is a known
broker reason.
- `grant-refresh.ts`: when the broker refuses a refresh with
`PROVIDER_CLOUD_ONLY` (after the sunset), the grant is marked for
reconnection. The error keeps code `oauth_reauthorization_required`,
adds reason `google_sign_in_cloud_only`, and tells the user to reconnect
with their own Google OAuth client.
- `ConnectionSetupFlow.tsx`: on a self-hosted instance (no `cloud` block
in health), Google setup uses the filtered definition. It never shows
Cloud enrollment for Google. The customer-owned Google client step shows
this note and a link to Google's client guide.
- Docs: `doc/connections/GOOGLE-WORKSPACE.md` ("Who can use Paperclip's
Google sign-in", "Self-hosted instances: use your own Google client")
and a dated decision row in `doc/memory/google-connector-memory.md`.
- `tests/runner-e2e/source-sdk-public-inputs.json`: pins the new shared
files (generated).

## Verification

- Red first, then green:
- `packages/shared/src/google-sign-in-deployment.test.ts` fails without
the new module and passes with it (4 tests).
- With the source files from `origin/master`, these new tests fail: 2 in
`server/src/__tests__/tool-access-service.test.ts` (self-hosted refusal,
refresh guidance and saved-connection refresh; broker refusal mapping),
3 in `server/src/services/paperclip-cloud-connector.test.ts`, and the
self-hosted test in `ui/src/pages/apps/AppsConnect.test.tsx`. With the
change they pass.
- Cloud path proof: "never shows the self-hosted Google notice on
Paperclip Cloud" (UI), "leaves every app unchanged on Paperclip Cloud"
(shared, identity check on every definition), "decides Cloud or
self-hosted from the instance's Cloud markers" (server). All existing
managed Google service tests (515) pass in a Cloud context.
- `npx vitest run src/__tests__/tool-access-service.test.ts` (server):
517 passed.
- `npx vitest run src/services/paperclip-cloud-connector.test.ts`
(server): 71 passed.
- `npx vitest run src/pages/apps/AppsConnect.test.tsx
src/features/connections` (ui): all passed.
- `npx vitest run` for `agent-connection-catalog.integration`,
`tool-gateway-service`, `google-access-removal`,
`connection-management.integration`, `generic-mcp-connection`,
`remote-mcp-connectors` and `plugin-connectors-circleback-parity`
(server): 446 passed, 1 skipped.
- `npx vitest run` in `packages/shared`: 1383 passed.
- `pnpm verify` exits 2 because `doc/connections/GOOGLE-WORKSPACE.md` is
a global CI input. Required CI supplies the broad coverage.
- Not run: no requests to staging, production, or Google. The reconnect
of a saved managed Google connection on a self-hosted instance after the
sunset was not run end to end in a browser.

## Risks

- Behavior change for self-hosted instances: new Paperclip-managed
Google connections stop. Saved ones keep refreshing until the broker
sunset (not set yet).
- The decision uses `isCloudManagedInstance()`. If a Cloud workspace
does not have its Cloud markers, it shows the self-hosted path. Cloud
stacks always have the tenant token, so the risk is low.
- Works with old and new brokers. An old broker does not refuse. The app
check still hides and refuses the method. A new broker refuses
self-hosted instances, and the app maps the refusal to the same
guidance.
- Deploy order: the broker change (paperclip-cloud) and this change can
deploy in any order.

> 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 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>
2026-11-23 16:19:01 -06:00
a00e31967b feat(connections): live setup progress from the person's own agent (#22626)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Several setup screens offer "Set it up with your agent": a prompt
the person pastes into their own agent (Claude Code, Codex) to do the
setup on their computer. AWS role setup is the newest
> - Once the prompt is copied, the setup page goes quiet: the person
cannot see what their agent is doing or when it is done, and has to
switch windows to find out
> - The agent already runs commands, so it can report its progress back
if we give it a safe place to send it
> - This pull request adds a live checklist the agent fills in: the page
creates it, the prompt gives the agent curl commands with a token, and
the page shows every update as it happens
> - The benefit is a setup that shows its own progress, and a reusable
piece any "Set it up with your agent" screen can use

## Linked Issues or Issue Description

Refs #22233 (the AWS setup screen this extends).

**Subsystem affected**
Connections (agent-guided setup), live updates, a new public agent API,
UI.

**Problem or motivation**
After a person copies a setup prompt into their own agent, Paperclip
shows nothing until they come back and paste a result. There is no way
for the agent to say what it is doing.

**Proposed solution**
A setup checklist a person's own agent writes to, shown live on the
setup page. The agent's requests need no Paperclip sign-in, so they
carry a narrow, expiring bearer token. Paperclip Cloud needs no
front-door change: it already forwards `/api` requests that carry an
`Authorization` header to the workspace without Cloud identity (its
machine-request lane), and these always do.

**Alternatives considered**
- Polling the page instead of live events: slower and adds load to every
open setup page. The page uses the existing live-event channel, with a
20-second backup refresh while the agent works.
- Putting the token in the URL: URLs end up in logs. The token goes in
the `Authorization` header.
- Letting the agent set the role ARN itself: the person still pastes it
(as decided for #22233). The agent's finish summary shows the ARN to
copy.

## What Changed

- `packages/db`: new `agent_setup_progress` table (company-scoped,
purpose and subject, token hash, items, status, summary, update count,
expiry). Migration `0501` is idempotent.
- `packages/shared`: `agent-setup-progress` types, limits and
validators; new live event type `agent_setup_progress.updated`.
- `server`:
- `agentSetupProgressService`: create (random `pcsp_` token, only its
SHA-256 kept), read, and the agent's set-checklist, update-item and
finish. Tokens are compared in constant time; a write is refused after
expiry (6 hours) or 300 updates, and concurrent writes are guarded by
the update counter. Finishing `done` ticks off open steps.
- Routes: board-only `POST
/api/companies/{companyId}/agent-setup-progress` and `GET
/api/agent-setup-progress/{id}`; agent routes `PUT …/checklist`, `POST
…/items/{key}` and `POST …/finish` mounted with the other public routes.
Activity entries for created, started and finished.
- Each agent write publishes `agent_setup_progress.updated`; the
live-events socket forwards it with only the checklist ID.
  - OpenAPI entries for all five routes.
- `ui`:
- Reusable `ui/src/components/AgentSetupProgress.tsx`:
`useAgentSetupProgress` (creates one checklist per setup and follows
it), `agentSetupProgressInstructions` (the prompt section with the
agent's curl commands) and `AgentSetupProgressPanel` (waiting, working,
done and failed states, using the task status glyphs).
  - `LiveUpdatesProvider` refreshes the checklist on its live event.
- AWS role step: one step (no numbering) with the prompt, the live
checklist and the Role ARN field. The prompt starts with the progress
instructions and asks the agent to put the role ARN in its finish
summary.
- Docs: `docs/api/agent-setup-progress.md` (API and how to add it to
another page) and the AWS setup section.
- Storybook: AWS step in waiting, working, done and failed states, and
the panel on its own.

## Verification

- `server/src/__tests__/agent-setup-progress.test.ts` (real routes,
embedded Postgres): set, update and finish with the prompt's token; only
the hash is stored; four live events carry the checklist ID; activity
entries. Refusals: missing token, wrong token, another checklist's token
(401), bad key (400), unknown item (404), update limit (429), expired
(410). Company boundary: another company's member gets 403 on read and
create.
- `live-events-toast.test.ts`: the socket delivers the event with only
`{ progressId }`. It failed before the socket fix (red/green), which an
end-to-end run found.
- `AgentSetupProgress.test.tsx`: the prompt section's exact commands;
the hook creates one checklist and the panel follows waiting → working →
done on live refreshes.
- `AwsRoleSetup.test.tsx`: the step creates the checklist for its
connection, waits for the agent, and the prompt leads with progress
reporting.
- Totals: shared 1362, server (new, OpenAPI, live events, AWS) 101, UI
(components, connections, apps, live updates) 1469. Typecheck clean for
db, shared, server and UI (except Storybook's generated catalog, not
built in this worktree).
- End to end on a local instance: Playwright opened the real AWS setup
step, read the prompt, sent the agent's requests with its token, and the
page showed each update within 1.5 seconds (inside the 20-second backup
refresh, so from live events) through "Your agent set up AWS" with the
role ARN summary. No page errors.
- Not run yet: Paperclip Cloud staging (after deploy) and an agent
running the prompt on its own.

## Risks

- New anonymous routes. The token is the only credential: 32 random
bytes, stored as a hash, scoped to one checklist, six hours, 300
updates. Text from the agent is shown as plain text (no links or
markup), so the worst a leaked token can do is change one checklist's
wording until it expires.
- One new table and migration (idempotent).
- Live delivery is per server process, like every other live event; the
20-second refresh covers a missed event.

> 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, Storybook and Playwright screenshots, the in-app
browser against a local dev server).

## 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>
2026-11-23 15:44:44 -06:00
DottaandClaude Opus 5.5 0aaf946227 fix(connections): keep retrying when Google does not confirm a revoked grant (#22669)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip Cloud can manage the Google sign-in for a Google Workspace
connection. The app keeps the refresh token. Cloud keeps no token.
> - When a user removes the connection, the app asks Cloud to end the
access at Google (#22065).
> - Before this change, the app deleted the token after that call,
whatever Cloud answered. If Google or Cloud could not be reached, the
access stayed open at Google, and no retry was possible.
> - The owner decided on 2026-11-23: the app keeps the token in a
pending record and retries until Google answers. Cloud still never
stores a provider token.
> - This pull request adds that pending record and a background retry.
It also covers company deletion and a Cloud-removed instance.
> - The benefit is that a removed Google connection does not keep access
at Google because of a short outage, and the user does not need to do
anything.

## Linked Issues or Issue Description

Refs #22065

**What happened?**
A managed Google connection was removed while Paperclip Cloud or Google
was unavailable. The removal result was `not_ended`, and the refresh
token was deleted. Paperclip could not try again, so Google access
stayed open.

**What did you expect?**
Paperclip keeps the token only for the retry, and retries automatically
until Google confirms or gives a final answer. The user sees that
Paperclip keeps trying, and does not need to act.

**Steps to reproduce**
1. Connect Gmail through Paperclip Cloud.
2. Make the broker revoke fail (Cloud unavailable, or Google 5xx).
3. Remove the connection. The token is deleted and nothing retries.

## What Changed

- New table `google_pending_revocations` (migration `0502`, additive,
`CREATE TABLE` only). It has `company_id` with no foreign key, so a row
outlives a deleted company. It stores the token as the same
`local_encrypted` material as the connection secret version. It never
stores plaintext. It is not a company secret: it is not listed, an agent
cannot bind it, and no route reads it.
- `google-access-removal.ts`: before the broker call, the app copies the
sent token version into a pending row (lease 2 minutes, so a restart
during the call resumes). A final outcome deletes the row. A retryable
outcome (`provider_revocation_failed`, `revocation_in_progress`,
`broker_unavailable`, `broker_error`, `unexpected_error`) keeps it, and
the result is the new `retrying`. If the connection secret is still live
after the conditional delete (for example, the user signed in again
during the call), the row is deleted.
- New worker on the `google-pending-revocation` delivery queue
(`registerDeadlineWork`; it registers the real next deadline and has no
deadline when the table is empty). Each attempt takes a lease on the row
and calls the broker with a 15-second timeout. Backoff is 1, 2, 4 ...
minutes, up to 6 hours. The hard stop is 30 days. The worker stops
without a call if a live company secret holds the same token.
- When a retry ends, the worker writes a
`connection.google_access_retry` audit event and a
`tool_connection.google_access_ended` or
`tool_connection.google_access_not_ended` activity entry (labels added
to the activity feed). For a deleted company, it writes only a log line.
- Company deletion queues every managed Google token of the company
inside the delete transaction, before the secrets are deleted (`reason =
company_deleted`).
- When the Cloud connection status check finds the instance `removed`,
the app queues every managed Google token (`reason = instance_removed`),
then deletes each connection secret.
- `ManagedGoogleAccessRemoval.result` gets `retrying` (shared type and
OpenAPI schema). The removal message for `retrying`: "Google didn't
confirm that Paperclip's access has ended yet. Paperclip will keep
trying automatically." It has no link and asks for no action.
- Docs: `doc/connections/GOOGLE-WORKSPACE.md` ("Pending revocation"),
`docs/api/tool-connections.md`, the help page
`docs/guides/board-operator/deleting-connection-data.md`, and a dated
decision row in `doc/memory/google-connector-memory.md`.
- `tests/runner-e2e/source-sdk-public-inputs.json` refreshed for the
changed shared type, as `pnpm verify` asks.

## Verification

- `npx vitest run
src/__tests__/google-managed-connection-removal.test.ts` (embedded
Postgres): 46 pass. Without the fix, 15 fail (red), with the fix all
pass (green). New cases:
- an unconfirmed token is kept only in the pending row, encrypted, not
in the secrets list; the worker retries and deletes the row when Google
confirms; audit and activity are written;
- the row exists during the broker call, so a fresh worker after a
restart revokes it;
- `binding_not_known`, `other_connections_remain` and
`provider_revocation_disabled` stop the retry;
- backoff 1 minute to 6 hours, and give-up at 30 days with a final audit
and activity entry;
  - a live secret with the same token stops the retry without a call;
  - an older broker's `403 INSTANCE_SUSPENDED` is retried;
- company deletion queues the token and the worker revokes it after the
company is gone;
- a removed instance queues every token, drops the secrets, does not
queue again, and the worker revokes.
- `npx vitest run
src/__tests__/paperclip-cloud-connector-status.test.ts`: the
removed-instance hook runs only for `removed`, and a failure does not
change the status.
- `ui`: `npx vitest run
src/features/connections/googleAccessRemoval.test.ts` (7 pass, the new
`retrying` case is red without the change).
- Also passed: `tool-connection-content-deletion`, its canary,
`delivery-work-coordinator`, `idle-local-work`, `packages/db` tests;
`server` `tsc --noEmit`.
- `pnpm verify` exits 2 (global doc input changed), so required CI
supplies the broad coverage.
- Not verified: any call to a real broker or to Google. No request was
sent to staging, production or Google.

## Risks

- Migration is additive (`CREATE TABLE` and indexes on the new table):
`online_compatible`.
- Paperclip now holds an encrypted token for at most 30 days after
removal when Google did not confirm. The token is never usable for tool
calls: no grant or connection refers to the row.
- Instance removal deletes the managed Google connection secrets. Those
connections then need a reconnect after a new enrollment. They could not
refresh anyway, because Cloud refuses a removed instance.
- Deploy order: either order is safe. With the current production
broker, a removed instance's revoke gets `403` and the app retries until
the hard stop. The Cloud broker change that accepts it is a separate PR
in the private Cloud repository.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code, with tool use
(shell, file edits, embedded Postgres tests), standard 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:28:07 -06:00
DottaandClaude Opus 5.5 7906db1ac9 fix(apps): title the Google AI connector "Google Antigravity and Gemini" (#22673)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Connectors page lists the services and model providers that a
company can connect
> - The Google model-provider connector has the title "Google"
> - That title does not tell people that this connector is for Google
Antigravity sign-in and Gemini API keys. It is easy to confuse with the
Google Workspace connectors
> - This pull request changes the connector title to "Google Antigravity
and Gemini"
> - The benefit is that people can find the correct connector for their
Google AI accounts

## Linked Issues or Issue Description

**What existing behavior does this improve?**
The title of the Google model-provider connector on the Connectors page.

**Subsystem affected**
UI: the Connectors page (`/<company>/apps`) and the shared app
definition for `google`.

**Current behavior**
The connector title is "Google". The title does not name the products
that it connects, and people can confuse it with the Google Workspace
connectors.

**Proposed behavior**
The connector title is "Google Antigravity and Gemini".

**Reason and benefit**
People can find the correct connector for Google Antigravity sign-in and
Gemini API keys.

**Breaking changes**
None. The provider id, the app slug, and all stored values stay the
same.

## What Changed

- Change the `name` of the `google` app definition
(`packages/shared/src/app-definitions/google.json`).
  - Before: `Google`
  - After: `Google Antigravity and Gemini`
- These texts read the name, so they also change:
  - Card heading: `Google` -> `Google Antigravity and Gemini`
- Card button accessible name: `Connect Google` -> `Connect Google
Antigravity and Gemini`. The visible button text stays `Connect`.
- Setup screen heading: `Connect Google` -> `Connect Google Antigravity
and Gemini`
- The service name that new connection requests show to agents and in
chat cards.
- Add a Connectors page test that checks the new card title,
description, and button name.
- Resync `tests/runner-e2e/source-sdk-public-inputs.json`, because the
app definition is a pinned input.

Not changed, on purpose:
- The provider id `google`, the app slug `google`, and all stored
values. Existing application rows are found by their
`app-gallery:google` key, not by name.
- The short provider name `Google` in
`ui/src/components/ai-connections/model.ts` and
`packages/shared/src/ai-connections.ts`. Sentences such as "Your Google
default" and default account names such as "My Google API account" use
this name. Account names are stored when people create them, and the
long title makes these sentences awkward.
- The `Google` choice in the model provider picker, next to `OpenAI`,
`Anthropic`, and `xAI`. Its description already says "Antigravity
sign-in or Gemini API key".
- The Google Workspace and Search Console connectors.

## Verification

- Red/green: `cd ui && npx vitest run src/pages/apps/Browse.test.tsx -t
"Antigravity and Gemini"` fails with the old name and passes with the
new name.
- `cd ui && npx vitest run src/pages/apps/Browse.test.tsx` passes (119
tests).
- `cd ui && npx vitest run src/components/ai-connections
src/pages/apps/AppsConnect.test.tsx` passes (362 tests).
- `cd packages/shared && npx vitest run src/app-definitions` passes (50
tests).
- `pnpm verify` exits 2 because the pinned-input registry changed.
Required CI supplies the broad coverage.

## Risks

- Low risk. This is a display text change.
- Old chat cards keep the service name that they stored when they were
created ("Google"). This is only display text.
- The Connectors page matches aggregator apps by slug and name. The slug
`google` does not change, so the match does not change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:18:19 -06:00
Devin Foley 7f343549db fix(ai-connections): tell people why an API key could not be verified (#22666)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - During onboarding, a person can connect a model with a provider API
key. Paperclip checks the key with one request to the provider before it
stores it
> - `validateAiApiKey` returns "The provider rejected this API key."
only for 401 and 403. Every other answer, and every network error,
returns "The provider could not verify this account. Try again."
> - The server does not log the upstream status, so nobody can tell
later what the provider said
> - A person whose key is valid but whose account has no credit, is
rate-limited, or hits a provider outage cannot know what to fix
> - This pull request gives each case its own code and message, and logs
the status and the provider's error type without the key
> - The benefit is that people can fix the real problem, and support can
see the provider's answer in the logs

## Linked Issues or Issue Description

**What happened?**

During onboarding, a person entered a Claude API key and saw "Could not
store the API key: The provider could not verify this account. Try
again." They then switched to a Claude subscription. The server log did
not show which status the provider returned.

**Expected behavior**

The person learns whether the key is wrong, the account has no credit,
the provider is limiting requests, or the provider is down. The server
logs the upstream status.

**Steps to reproduce**

1. Call `validateAiApiKey("anthropic", key, request)` with a `request`
stub that returns 400, 402, 429 or 500.
2. Observe that all four throw `ai_connection_verification_failed` with
the same message.

**Paperclip version or commit**

`master` at `5f5ac154368`.

**Deployment mode**

Hosted onboarding. Self-hosted installs use the same check.

Refs #12675 (related: server-owned user-secret definitions for
onboarding API keys).

## What Changed

- `ai-api-key-failures.ts` (new): one code and message for each result.
The codes are `ai_connection_api_key_rejected` (unchanged),
`ai_connection_billing_required`, `ai_connection_rate_limited`,
`ai_connection_provider_unavailable`,
`ai_connection_verification_timeout`,
`ai_connection_provider_unreachable`, and
`ai_connection_verification_failed` (unchanged, for all other answers).
- `ai-api-key-test.ts`: map 401/403 to rejected (unchanged); 402, or the
error type `billing_error`, `insufficient_quota` or
`insufficient_credits`, to billing; 429 to rate limited; 5xx (including
Anthropic's 529) to provider unavailable. A `TimeoutError` maps to
timeout, and other network errors map to unreachable.
- Log the provider, the HTTP status, the provider's error type and the
result code. The error type comes from `error.type`, `error.code` or
`error.status` in at most 8 KiB of the error body. It is used and logged
only when it is on a closed list of documented provider error types
(Anthropic, OpenAI and xAI, Google, OpenRouter). Any other value is
ignored. The key and the response text are never logged. 401/403 bodies
are not read.
- `adapters/registry.ts` and `agent-environment-test.ts`: keep the
specific code in the environment check instead of collapsing it to
rejected or failed.
- The billing check looks at `error.type`, `error.code` and
`error.status` together, so a 429 with `type: invalid_request_error` and
`code: insufficient_quota` is a billing problem, not a rate limit.
- `tests/runner-e2e`: the connection harness keeps every new code in
`creationFailure` instead of saving it as `connection_request_rejected`.
One shared list feeds `connection-flow.ts`, `connection-evidence.ts` and
`result-validation.ts`, and a test keeps it equal to the server's codes.
- Tests: `ai-api-key-test.test.ts` (17 tests) and
`connection-support.test.ts`.

**The user-facing text needs a person's review.** The new messages are a
first draft. They read after the onboarding prefix "Could not store the
API key:":

| Code | Message |
|---|---|
| `ai_connection_billing_required` | The provider account for this API
key has no credit or billing set up. Add credit with the provider, then
try again. |
| `ai_connection_rate_limited` | The provider is limiting requests for
this account right now. Wait a minute, then try again. |
| `ai_connection_provider_unavailable` | The provider is having problems
right now. Try again in a few minutes. |
| `ai_connection_verification_timeout` | The provider did not answer in
time. Try again. |
| `ai_connection_provider_unreachable` | Paperclip could not reach the
provider. Check this server's network connection, then try again. |

## Verification

- `pnpm exec vitest run server/src/services/ai-api-key-test.test.ts`: 17
passed. On `master`, 11 of the original 15 fail.
- Callers: `ai-connections.test.ts`, `adapters/registry.test.ts`,
`agent-environment-test-status.test.ts` and
`agent-test-environment-routes.test.ts` with the new file: 5 files, 331
tests passed.
- `pnpm --filter @paperclipai/server typecheck` passes.
- Not run: a live check against each provider. The billing mapping uses
the documented error types (`billing_error` for Anthropic,
`insufficient_quota` for OpenAI, 402 for OpenRouter). The models
endpoint may not report a billing problem for every provider.

## Risks

- Low risk. The HTTP status of the store request stays 422, and 401/403
behavior does not change.
- An answer that does not match a known case still returns
`ai_connection_verification_failed`, as before.
- A code that consumers compare by value can now be one of five new
values. No UI code compares these codes, and the server callers now pass
them through.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with shell, file
edit, and code execution tools.

## 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
2026-11-23 11:52:56 -08:00
DottaandClaude Opus 5.5 d28becf0f5 fix(server): run person-opened gateway sessions as their opener for personal connection grants (#22643)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The tool gateway lets an agent run call connected apps through a
short-lived session
> - A person on the board can also open a gateway session for a running
agent
> - Such a session resolved credentials for the run's responsible
person, not for the person who opened it
> - A member could therefore use another member's personal connection
grant through that member's running agent
> - This pull request limits personal grants in a person-opened session
to the grant owner and requires permission to act on the agent
> - The benefit is that a personal connection is used only by its owner
or by the owner's own agent runs

## Linked Issues or Issue Description

Refs #22635

**What happened?**
`POST /api/tool-gateway/sessions` let any non-viewer member open a
session for any running agent in the company. Tool calls in that session
used the personal grant of the run's responsible person.

**What did you expect to happen?**
A person who opens a session can use a personal (user-owned) grant only
when they own it. The person needs permission to act on the agent.
Company-shared connections and agent-opened sessions work as before.

**Steps to reproduce**
Two members are in one company. Member A has a personal grant on a
connection that agent X uses. While a run of X is active, member B opens
a gateway session for that run and calls a tool on that connection. The
new route test covers this case.

**Impact**
Access-control hardening for personal connection grants.

## What Changed

- Add the nullable column `tool_gateway_sessions.created_by_user_id`
(migration `0502`, which also adds `tool_mcp_tasks.created_by_user_id`).
The route sets it when a person (not a local implicit board) opens a
session.
- Grant resolution for such a session acts as the person who opened it.
That person's own personal grant is used, or a connect card is addressed
to that person. Another member's personal grant is never selected, and
that member gets no card.
- The opener is recorded on the tool invocation (server-written
`policyExplanation.sessionOpenedByUserId`) and restored when an approved
action runs. An approved call from that session therefore uses the same
person's grant.
- A guard after grant resolution refuses a user-owned grant of another
person with `403` and `reasonCode: personal_grant_owner_required`, as
defense in depth.
- Saved-call replay is scoped to the opener: idempotency keys get an
opener suffix for such sessions, and approval replay matches only
invocations recorded with the same opener. The lookup of keys saved
before this change still runs: a saved call that can be attributed to
the same person replays, one attributed to another person does not, and
one that cannot be attributed returns the existing
`legacy_tool_idempotency_unverifiable` conflict instead of running the
write again.
- Long-running provider tasks (`tool_mcp_tasks`) record the opener in a
new `created_by_user_id` column (same migration) and restore it on each
background poll, so the task keeps the opener's grant and is attributed
to the opener.
- Managed GitHub identity selection uses the opener, in the first and
the fallback selection.
- A call attaches to an existing long-running provider task only when
the task uses the same grant the call resolves to. On a personal grant
it must also be the same person (an agent session matches only tasks
with no opener; the grant owner may also collect a legacy task with no
opener). On a shared grant any person may collect. The wake for a
finished task now carries the task id, so the agent's continuation
resolves the opener's grant and collects the result instead of calling
the provider again.
- `POST /api/tool-gateway/sessions` checks the existing `agent:wake`
permission for a board caller, the same check as invoking the agent.
- Agent-opened sessions do not set the column, so agent runs and the
recovery of interrupted runs do not change.
- Document the rule in `doc/MCP-ACCESS-GOVERNANCE.md`.
- I checked the sibling routes. Named gateway tokens minted by a person
need `tools:admin` and carry no responsible person. Board test calls and
MCP app view calls already run as the caller. Stored MCP task
continuations stay pinned to the grant they started with.

## Verification

- New route tests in `server/src/__tests__/tool-gateway.test.ts`:
- Three members, two with personal grants, on a run that belongs to the
first. A session opened by the second member uses only that member's
credential. The run owner's session and an agent-opened session use the
run owner's credential. A member with no grant gets `409
user_authorization_required`, the card is addressed to that member, and
the remote server gets no request. A reviewed call from the second
member's session, once approved, runs with that member's credential. The
same write from two people's sessions runs once for each person, and
only the same person's retry replays.
- A pre-upgrade saved write retried by the same person replays (or
conflicts when it cannot be attributed) and never reaches the provider
twice; another person's identical write runs.
- `mcp-tasks.test.ts`: a person-started task keeps the opener's grant
through a background poll; an agent retry never receives that task's
result and keeps its own task; the continuation after a wake collects
once with no new provider call; on a shared grant another person
collects the task, including a task started before openers were
recorded.
- `tool-gateway-service.test.ts`: an opener with their own managed
GitHub grant uses it; an opener without one is refused and the run
owner's grant is never used.
  - A viewer cannot open a session for the agent.
- Before the fix, the second member's session used the run owner's
credential, and the viewer got `201`. Both tests pass now.
- `npx vitest run src/__tests__/tool-gateway.test.ts
src/__tests__/connection-management.integration.test.ts
src/__tests__/mcp-tasks.test.ts`: with `tool-access-service.test.ts` and
the policy tests, 833 tests pass.
- `tsc --noEmit` for `server` passes.
- `pnpm verify` exits 2 because a global CI input (a doc) changed.
Required CI gives the broad coverage.

## Risks

- A person who opened a session for another member's run used that
member's personal grants before. Now the session uses the opener's own
grants. This was not an intended flow. Shared connections and agent runs
do not change.
- A person-opened session that repeats exactly the same side-effecting
call an agent session already made in the same run gets a `409` conflict
instead of a second write, because that earlier call has no recorded
opener. Use a new explicit idempotency key for an intentional repeat.
- The migration only adds nullable columns. Sessions and review requests
created before this change have no opener record and keep the previous
behavior until they expire (15 to 60 minutes).

- Follow-up, out of scope: in the experimental MCP Tasks path, a call
with a new explicit idempotency key and the same arguments still
attaches to the same person's open task under the same grant. That is
the existing de-duplication for every caller and does not depend on the
opener rule.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, 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>
2026-11-23 19:16:22 +00:00