Commit Graph
2794 Commits
Author SHA1 Message Date
DottaandPaperclip 8252974141 fix(server): schedule stopped instruction collection (#17674)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Runs can stop while their private instruction edits still need
collection.
> - Existing copy rows and stop evidence describe that unfinished work.
> - The orphan reaper still queries for it on every maintenance pass.
> - This PR activates collection from committed copy and run
transitions.
> - It uses saved retry deadlines when stop proof or collection remains
pending.
> - Active copies and completed history no longer cause collection
polling.

## Linked Issues or Issue Description

Refs #17671 and #17670. Both prerequisites are merged into master.
Captured saves and post-save release remain separate reasons with their
own workers.

**What needs to be improved?**

`recoverStopped` queries instruction copies on every orphan-reaper pass,
even when no terminal run owes collection. A run can become terminal
without changing its copy row, so copy-only notifications would miss
real work.

**Why is this improvement important?**

Repeated empty queries prevent idle tenant instances from becoming
quiet. Removing them must preserve edits, stop proof, current ownership,
and recovery after restart.

**Proposed solution**

Use the existing transaction signals, scoped deadline worker, and
scheduler. Reconstruct eligible copies at startup, signal supported copy
and terminal-run writers, and retain saved retry deadlines for
unresolved work. Preserve the existing collection and directory owners.

Related PR search found the warm agent-file ownership work (#14695),
verified stop boundary (#14311), and task-workspace cleanup (#16464).
This PR does not replace those contracts. ROADMAP.md has no duplicate
migration.

## What Changed

- Add scoped stopped-instruction collection with keyset reconstruction
and fair batches of 20.
- Signal before copy preparation, mutation and adoption writes, and
before terminal run writes in their existing transactions.
- Cover heartbeat, native finalization/restart/session recovery,
execution-control, queue and dispatch producers.
- Signal settings changes and company/agent deletion. Preserve drain,
standby, restart and shutdown ownership.
- Recheck terminal-run eligibility in the due-time claim. Keep terminal
status separate from process-stop proof.
- Retain existing stop checks, attempt limits, saved candidate bytes and
remote-resource fencing.
- Skip only this lane in periodic orphan recovery. Preserve
manual/startup recovery.
- Add concurrent, replay-safe partial index 0408 and retain the five
newest snapshots. Add no table.
- Record the owner and producer audit in
`doc/plans/2026-10-25-stopped-instruction-collection-sleep-audit.md`.

## Verification

- Source `cb2818a8f46ef961f744977a258f0e9042e31a42`: all 1469 cases
across 14 complete files pass without skips in 141.69 seconds. This
includes all 968 native-session cases, filesystem saves, startup,
terminal-run producers, dispatch, queue, execution-control, finalization
and lifecycle.
- Eleven separate fresh PostgreSQL 17 databases migrated through 0408.
The embedded-only lifecycle fixture temporarily used its own external
database on this IPC-exhausted host and was restored byte for byte.
Assertions and timing limits stayed unchanged. This qualifies
external-database behavior; it does not claim an unmodified embedded CI
run.
- Database build, server typecheck/build, module boundaries and
exact-current migration order pass. The original concurrent index SQL is
unchanged. All prior executable migration history, journal entries and
retained snapshot bytes are preserved; the five newest snapshots are
0404 through 0408.
- A populated 0407-to0408 upgrade preserves all 406 prior migration
receipts and 38 companies. It appends exactly one receipt. Replay adds
none. The collection index is valid and ready on fresh and upgraded
databases.
- The normal merge of actual parent
`267842fc3c6e6542deed8a1bcc2c78bec8df7862` preserves both complete
patches, all independent sidebar changes from #18117, and the full
accepted server/package/test trees. The complete sidebar test file
passes all 36 cases on the combined tree. React act warnings remain.
- Prior failures and fixture qualifications remain in the audit.
Published head `d176d731f083c7edd2ede688cb901d1e66d8f1d8` has Greptile
5/5, all 57 checks passing or skipped, and no unresolved review threads.
No Ponytail review is present. These local tests do not establish
deployed host/database suspension or Cloud alarm delivery.

## Risks

- Process-local signals cover instrumented writers. Independent SQL
writers and additional replicas still need integration.
- Terminal-run signals can cause one scoped inspection even if no
instruction copy exists. They do not create a recurring scan.
- Reconstruction and memory scale with actual pending candidates; active
candidates are filtered by the run join.
- Admitted file/provider operations can outlive a later drain request.
Shutdown joins them. Uncertain ownership remains pending rather than
being discarded.
- The partial index adds storage and write cost. Its concurrent
migration uses the existing interrupted-index repair path.
- Cloud alarms, sleep eligibility and provider suspension are unchanged.
Worker quiet is not a claim of deployed host/database sleep or measured
savings.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning, shell tools, and
PostgreSQL/filesystem tests. The runtime does not expose a more precise
model ID or context-window size for this turn.

## 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-10-28 22:13:57 -05:00
DottaandPaperclip 267842fc3c fix(server): schedule owed agent directory cleanup (#17671)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent runs can save their directory before temporary-file cleanup
finishes.
> - The existing receipt records stop proof and unfinished cleanup.
> - The orphan reaper still searches for this debt on every maintenance
pass.
> - This PR activates cleanup from committed changes and saved retry
deadlines.
> - The directory owner keeps its resource checks and file lock.
> - Settled directory history no longer causes recurring cleanup
queries.

## Linked Issues or Issue Description

Refs #17670, the merged captured-instruction commit slice. This PR
targets master. It does not include stopped instruction collection or
change the saved-file contract from #14695.

**What needs to be improved?**

The post-save part of `recoverCaptured` queries directory copies on each
orphan-reaper pass, even after all temporary directories have been
released.

**Why is this improvement important?**

Empty database work prevents idle tenant instances from becoming quiet.
Cleanup must still survive a crash after a save and preserve files when
stop or resource ownership is uncertain.

**Proposed solution**

Use existing copy receipts as the source of truth. Notify the shared
coordinator inside relevant copy-write transactions. Reconstruct pending
work at startup and register each saved retry deadline. Keep physical
cleanup in the directory owner. Add a partial index over unfinished
cleanup rather than a new queue table.

Related-PR search found workspace archive and SSH task-workspace cleanup
changes (#17175 and #16464). They own different resources and do not
replace this stopped agent-directory receipt recovery. ROADMAP.md has no
duplicate migration.

## What Changed

- Add a scoped directory cleanup worker with keyset discovery and
batches of 20.
- Signal relevant copy transitions, company/agent deletion, and worktree
execution policy changes.
- Preserve the due-time claim, current receipt read, directory lock,
stop proof, and exact remote-resource checks.
- Read the receipt after release; a returned promise does not establish
cleanup completion.
- Keep unresolved cleanup on its saved retry or shared failure backoff.
Final receipts disarm the worker.
- Register the worker during startup and skip only this lane in periodic
recovery. Keep manual recovery compatible.
- Add concurrent, replay-safe partial index migration
`0407_greedy_star_brand.sql`. Retain the five newest schema snapshots.
- Add the producer audit and lifecycle evidence in
`doc/plans/2026-10-25-directory-cleanup-sleep-audit.md`.

## Verification

Published head: `210fcb1215a3b5e5ed84e420ddb73ab5952d9365`. Source
acceptance: `70a6800eea874bdb87685bf6eea66de79c48b577`. Parent #17670
landed as `b294de546bf9cd3a8578a7a66d7e8ec0eb939799`; normal
squash-ancestry reconciliation preserves the entire accepted descendant
tree. Final follow-ups change audits only.

- All 284 cases in six complete filesystem, startup and heartbeat owner
files pass, without skips, in 48.88 seconds. Four unused fresh
PostgreSQL 17 databases migrated through 0407 isolate destructive
fixtures.
- Three fixtures use supported external database paths. The
embedded-only lifecycle fixture temporarily uses its own external
database on this IPC-exhausted host, then is restored byte for byte. All
assertions and original timing limits remain unchanged. This qualifies
the local result; CI must still pass with the original embedded fixture.
- Actual database build, server typecheck/build, module boundaries and
exact-current migration order pass. The original concurrent idempotent
index SQL bytes are unchanged. All prior executable migration history,
journal entries and retained snapshots stay intact. The five snapshots
are 0403 through 0407.
- Populated 0406-to0407 upgrade preserves all 405 old receipts and all
38 companies, adds exactly one receipt and adds none on replay. The
cleanup index is valid and ready on fresh and upgraded databases. The
entire current database tree equals the source used for this proof.
- Both complete original and upstream patches are preserved. The actual
parent squash tree equals the already-adopted reviewed parent; resolving
eleven duplicate-ancestry text conflicts leaves the whole accepted tree
unchanged, not just selected files. Complete server, package, UI and
test trees still match the 284-case source acceptance.
- The audit retains earlier ownership, stopped-resource, receipt,
fixture and local-runner failures. The no-projects build filter was not
counted as a build pass; corrected actual build and complete reruns
passed before publication. Old draft review scores do not count for this
new head.
- Current-head Greptile gives 5/5 with no actionable findings, and all
57 checks pass. These checks establish worker behavior, not deployed
host/database suspension or measured savings.

## Risks

- Signals cover the existing single-process writer model. Independent
SQL writers and replicas need separate integration.
- The worker retains identifiers for actual pending work. Its index
excludes completed history but does not make large pending backlogs
free.
- File/provider cleanup can outlive an admission change once started.
Shutdown joins admitted operations. Unknown remote ownership remains
pending and no replacement environment is acquired for cleanup.
- The partial index adds storage and write cost. Its concurrent
migration uses the existing interrupted-index repair path.
- Cloud alarm coverage and host-sleep safety remain unchanged. This
establishes worker quiet, not deployed host/database suspension or
measured savings.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning, shell tools, and
PostgreSQL/filesystem tests. The runtime does not expose a more precise
model ID or context-window size for this turn.

## 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-10-28 21:51:47 -05:00
DottaandPaperclip b294de546b fix(server): recover captured instruction saves from committed deadlines (#17670)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A stopped run can leave captured instruction edits waiting for a
persistent save.
> - Existing working-copy records retain the candidate bytes, attempt
count, and retry deadline.
> - The orphan reaper scans those records on every heartbeat, even when
no save is due.
> - This PR wakes the existing save owner after committed changes and at
saved deadlines.
> - The worker preserves permissions, conflicts, and bounded retries,
then becomes quiet.

## Linked Issues or Issue Description

Refs #17667, the merged preceding PR in this recurring-server-work
stack. This PR targets master. Related warm-file ownership work: #14695.
Its process-stop and retained-directory guarantees remain with their
existing owner. The dedup search found no equivalent captured-save
scheduling migration.

**What happened?**

The commit portion of `recoverCaptured` runs inside the periodic orphan
sweep. Prepared copies, completed history, conflicts, and exhausted
candidates do not need repeated save discovery. A saved candidate does
need recovery after restart or a failed foreground save.

**Expected behavior**

Committed candidate changes reactivate recovery. The worker honors the
saved deadline and existing three-attempt bound. It stops querying after
settlement or deliberate conflict/exhaustion. Permission checks and
canonical save semantics remain in the revision service.

**Steps to reproduce**

1. Start a server with heartbeat scheduling enabled and no captured save
pending.
2. Observe repeated pending-commit queries from the orphan reaper.
3. Capture edited instructions and fail their first canonical file
replacement. The durable candidate must be saved after its retry
deadline without starting a provider.

**Paperclip version or commit**

Reviewed parent `405e533394b26215e22d0452e9b0207d3f784a79`. Actual
parent squash and current master baseline
`27270e9bf8b7a294cf03f8b84f4857f1b1ff05c7`.

**Deployment mode**

Self-hosted server with the existing single-process transaction signal
model. Local verification uses PostgreSQL 17 and actual managed
instruction files.

## What Changed

- Preserve foreground instruction-save ownership and its failure
deadline before recovery spends another attempt.

- Add a bounded captured-commit worker inside the instruction-copy
owner. Existing rows and deadlines supply its state. No new table,
migration, or external scheduler is added.
- Signal writes entering or leaving pending commit from the existing
copy mutation boundary. Only these writes gain a short transaction. File
collection, file replacement, and provider operations stay outside that
new transaction.
- Signal company/agent deletion and worktree execution setting changes.
Preserve drain, standby, startup reconstruction, shutdown join, and
uncertain-transaction handling through the shared coordinator.
- Guard attempt claims with current copy ownership and a still-due
deadline. A concurrent writer that postpones the retry wins without
consuming an attempt. Manual/startup recovery uses the same guarded
owner.
- Remove only captured commits from periodic reaping. Stopped collection
and the separate post-save directory cleanup sweep remain for later
slices.
- Add real producer, file, transaction, concurrency, and lifecycle
tests. Add guarded external test databases to the two filesystem suites
so they can run where embedded PostgreSQL is unavailable.

## Verification

Published head: `915ef6f20a68fffe89711cc97a6196521ea9885d`. Source
acceptance: `9fb75e508f06b05b740099403ce021a61e7c6603`. The actual
#17667 squash ancestry is recorded by a normal merge. Its entire result
tree equals the prior accepted descendant tree; the final commit changes
the audit only.

- All 268 cases in six complete files pass, without skips, in 41.89
seconds on the updated parent. Coverage includes captured saves,
directory consumers, startup, instruction-copy lifecycle boundaries,
recovery and run lifecycle.
- Four unused fresh PostgreSQL 17 databases migrated through parent 0406
isolate the destructive fixtures. Three use supported external URL
paths. The embedded-only lifecycle fixture temporarily uses its own
external database on this IPC-exhausted host, then is restored byte for
byte. Assertions and original timing limits are unchanged. CI must still
pass with the original embedded fixture.
- Actual database build, server typecheck/build, module boundaries and
exact-current migration order pass. Commands select each operation by
name. The earlier local no-projects filter error remains recorded and is
not treated as a build pass.
- The normal parent merge preserves both complete added/removed patches
and every unrelated upstream blob. The entire database subtree is
parent-identical, with no owned schema or migration changes. New parent
worker behavior has current consumer/startup acceptance here and
separate owner acceptance in #17667.
- Earlier foreground ownership, postponed deadline, attempt cap, drain
hold, fixture and skipped-test findings remain in the audit. The prior
head's Greptile 5/5, Ponytail 5/5 and green CI are historical after this
new publication.
- Current-head Greptile and Ponytail both give 5/5. All 58 checks pass.
Prior stacked-head scores are historical; the new published SHA requires
fresh gates. These checks do not establish deployed host/database
suspension or external wake delivery.

## Risks

- Signals cover supported in-process writers. Independent SQL writers
and other replicas require a separate ingress contract. Startup
reconstructs persisted obligations.
- Exhausted candidates stay preserved under the existing policy; the
worker does not increase retry limits or silently discard saved edits.
Database reconstruction failures retain shared backoff.
- Inventory pages scalar fields but retains candidate identifiers in
memory. The query-plan result covers completed history, not a
constant-cost promise for arbitrary exhausted-pending history.
- File saves can outlive a stop request once admitted. Shutdown joins
them. Exact-byte replay and current authorization remain with the
revision owner.
- Other instruction recovery duties and other stack blockers remain.
This PR does not prove host suspension, database suspension, or external
wake delivery. An ordinary protected merge is authorized only after
current review and CI gates pass.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning, shell tools, and local
PostgreSQL/filesystem tests. The runtime does not expose a more precise
model identifier or context-window size for this turn.

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


Review follow-up: remove seven newly added comment lines to satisfy
CONTRIBUTING.md, preserving the explanations in the owning audit. Both
changed files retain the exact non-comment TypeScript token stream;
other source bytes are unchanged. The original cffe server-shard-9 run
ended after a runner shutdown signal and cancellation, without a final
assertion verdict; that failure is retained and not counted as a pass.
No old-head retry is requested. Fresh current-head CI and Greptile are
required.

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-28 21:29:02 -05:00
DottaandPaperclip 27270e9bf8 fix(server): wake interrupted retry cancellation from committed intent (#17667)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A parked scheduled retry has no executor to finish an interrupted
Stop request.
> - Its saved cancellation fence already records the work that remains.
> - The orphan reaper currently scans for that work on every heartbeat,
including idle periods.
> - This PR registers the existing records with the shared delivery
scheduler and wakes recovery after committed writes.
> - Recovery keeps the existing cancellation guards and settlement
behavior, then becomes quiet.

## Linked Issues or Issue Description

Refs #17666, the merged preceding PR in the recurring-server-work
migration stack. This PR targets master. Related cancellation work found
in the dedup search: #12301 and #7340. This PR changes the trigger for
interrupted parked-retry cancellation; it does not replace their
cancellation or retry policies.

**What happened?**

The periodic orphan reaper queries scheduled retries with cancellation
fences even when no cancellation needs recovery. Its first-20-row scan
can also stop behind malformed evidence.

**Expected behavior**

Committed cancellation intent wakes bounded recovery. Failed work
retains a retry. Startup reconstructs durable work. Empty or settled
work performs no recurring SQL for this duty.

**Steps to reproduce**

1. Start a server with heartbeat scheduling enabled and no interrupted
retry cancellations.
2. Observe the orphan reaper repeatedly query for cancellation fences.
3. Cancel a scheduled retry and fail the final status write after its
fence commits. Recovery must complete the existing Stop request without
running a provider or dropping its metadata.

**Paperclip version or commit**

Current parent squash `7afee8f0622e273d10506b0febfb68f143d168b1`. Source
acceptance `66107ae0a7ad85fd0476f91c4f8f98ae74a7a048`.

**Deployment mode**

Self-hosted server with the existing single-process transaction signal
model. Local evidence uses PostgreSQL 17.

## What Changed

- Add one domain-owned recovery worker over existing heartbeat run rows.
No new table. It delegates to run control and preserves original
cancellation, budget, and operator metadata.
- Signal cancellation fences, lifecycle transitions, dispatch
deferral/promotion/suppression, relevant settings changes, and deletion
within their owning transactions. Wrap only the ordinary database fence
in a short transaction; provider calls stay outside it.
- Keep startup/manual recovery compatible and remove this duty from the
periodic orphan sweep. Other reaper duties remain for separate PRs.
- Extend the shared scoped worker to retain pending work with a
memory-only admission retry while its owner is paused. Without pending
work, it schedules nothing. Existing GitHub consumers retain their
behavior.
- Add a concurrent idempotent partial index and lifecycle/producer
tests. Enable guarded disposable PostgreSQL URLs in affected test
harnesses.
- Reconstruct one hundred candidates per scope per scheduler pass.
Resume from the saved scope cursor and retain fair twenty-item execution
batches. Manual recovery starts cancellation before reading the full
backlog.
- Require the recovered browser reply to be saved before testing reload.
Keep all original assertions and time limits.
- Record the full producer audit, lifecycle limits, and failed attempts
in `doc/plans/2026-10-25-scheduled-retry-cancellation-sleep-audit.md`.

## Verification

Published head: `405e533394b26215e22d0452e9b0207d3f784a79`. Source
acceptance: `a35fa43b98e2bd378d4a920d2775ce243654838b`. The final commit
changes the audit only.

- All 363 backend cases in ten complete owner and consumer files pass
without skips. This includes actual Stop/retry producers, transaction
settlement, interrupted-write recovery, pause/resume, shutdown, fair
backlog processing and quiet after settlement. Seven separate fresh
PostgreSQL 17 databases prevent fixture interference.
- The two embedded-only backend fixtures temporarily use separate
external databases on this IPC-exhausted host. Their fixture imports and
native client teardown are restored byte for byte afterward. Assertions
and timing limits are unchanged. CI must still pass with the original
embedded fixtures.
- Two paging regressions fail on the prior worker and pass on the fix.
They cover cancellation before full reconstruction, a malformed first
page, fair batches, a newly committed intent behind the cursor, and no
later idle SQL. Per-candidate admission reads remain deliberate safety
checks.
- The repeated CI reload failure is reproduced with a temporary
twelve-second fixture settlement delay. The trace retains the same
five-second missing-reply assertion, even though a cleanup race masked
it in the top-level error. Requiring exactly one saved reply from the
resumed run passes under the identical delay. The fault is removed. All
six browser journeys pass on the final source in 40.5 seconds, with zero
retries and the original 120-second case and five-second reload limits.
- Browser acceptance uses the canonical CLI/server/static-UI path and a
fresh external database. Only fixture database-URI setup is temporarily
adapted and then restored. This is not an unmodified embedded
CI-environment reproduction. The six cases include the controlled case;
repeated runs are not added to the distinct count.
- Actual database build, server typecheck/build, module boundaries and
exact-current migration order pass. The database source tree is
unchanged from the verified 0405-to0406 upgrade: all 404 prior receipts
and 300 companies stay intact, exactly one receipt is added, replay adds
none, and the index is valid on upgraded and fresh databases. The five
snapshots remain 0402 through 0406.
- All earlier failures remain recorded in the audit. Prior head
`48b3fcb83f305616df02a4337a42ec0867bb4b80` had exact-head Greptile 5/5
but failed the repeated browser assertion. It was not retried blindly.
Its completed Ponytail review's backlog concern and old migration
paragraph are addressed here. Old scores do not satisfy new-head gates.
- Current-head CI passes. Exact-head Greptile and Ponytail both give
5/5, with no remaining actionable findings. These checks do not prove
deployed instance or database suspension.

## Risks

- Only supported in-process writers produce local transaction signals.
Independent SQL writers or other replicas need a separate ingress
contract. Startup reconstructs saved obligations.
- A real failure retains bounded retries. Unknown commit outcomes retain
the shared intent hold. Neither is discarded to report quiet.
- Per-owner drain uses a memory-only admission recheck. The shared
helper change affects existing consumers, which have focused regression
coverage.
- The partial index is concurrent and idempotent; it adds index storage.
Each scoped load reads at most one hundred rows. The shared helper
retains discovered pending IDs between passes, so a large unresolved
backlog still uses memory.
- Cloud alarms, idle-safety exemptions, and other reaper duties remain
separate. Merge requires passing current-head CI and review gates.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning, shell tools, and local
PostgreSQL tests. The runtime does not expose a more precise model
identifier or context-window size for this turn.

## 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-10-28 21:07:55 -05:00
DottaandPaperclip 7afee8f062 fix(server): schedule direct GitHub webhook recovery from saved deadlines (#17666)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/218/changes/paperclip/218
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - GitHub callbacks can fail before the app records an inbox row.
> - Direct GitHub integrations need bounded recovery from provider
delivery history.
> - The chat timer checks for due recovery every second, even without an
eligible integration.
> - Existing recovery checkpoints already store the next scan time and
runtime epoch.
> - This pull request schedules those saved obligations and wakes on
committed configuration changes.
> - It removes the final chat maintenance interval while preserving
authenticated recovery.

## Linked Issues or Issue Description

**What happened?**

The app queries due GitHub recovery endpoints every second. This still
runs when no direct GitHub integration needs recovery. Other chat
maintenance duties already have independent workers in the preceding
stack.

**What did you expect?**

Reconstruct existing recovery deadlines at startup and after committed
changes. Run only when an eligible endpoint reaches its saved deadline.
Make no recurring SQL or HTTP calls for unconfigured, disabled, or
Cloud-relayed integrations.

**Steps to reproduce**

Start an instance without an active direct GitHub integration. Leave it
idle. The chat maintenance interval continues to call
processFailedGitHubWebhookDeliveries each second.

Follows merged #17664. Related #15981 owns the original GitHub webhook
ingress/recovery separation. #17662 preserves review-check recovery,
which is a separate obligation. No duplicate scheduling migration was
found in the related-PR search.

## What Changed

- Put deadline reconstruction, scopes, and registration in the GitHub
provider owner. Read existing recovery checkpoints in pages of 100.
Reload current eligibility before each dispatch.
- Dispatch batches of five through the existing shared helper. Preserve
company fairness and the default limit of 25 for other consumers.
- Notify inside configuration, credential, checkpoint,
installation-lifecycle, and Cloud-registration transactions. A signed
installation deletion reproduced a missing wake before the fix.
- Detect credential-only epoch changes during a future backoff. Preserve
the existing floor reset without adopting old events into new
credentials.
- Gate every new recovery HTTP call on dispatch admission and shutdown.
Join in-flight work and retain its existing outcome/uncertainty
settlement. Other queues remain independent.
- Remove the final chat reconciliation interval and its unused
coordinator. Update the old coordinator fixtures; preserve the voice
retention worker acceptance.
- Restore known-unsent redelivery claims after drain/shutdown, guarded
by exact attempt identity. Preserve uncertain outcomes after transport
starts and never overwrite a newer receipt.
- Keep all existing redelivery, source, authority, lease, receipt, and
callback checks. Add no table, migration, or external wake contract.

## Verification

Current source: `ab00fc5b30d51d6c85891536599e7bdfd0c822fe`.

- **751 distinct cases pass** at
`3d7f163bc5259b60f9bd19b7fc90b402f0a6e925`: 274 complete GitHub review
cases, 294 other GitHub-named cases, 30 publication cases, 145
voice/retention cases, and eight startup cases.
- All 19 new recovery worker cases and all six stop-before-transport
variants pass. Coverage includes configured eligibility, callback-only
admission, committed configuration changes, outer transaction
settlement, restart/drain/standby, saved deadlines, fair batches,
independent queues, held HTTP, joined shutdown, known-unsent
restoration, and newer-receipt fencing.
- The first workflow filter omitted the separate recovery group. The
saved case list exposed the gap. The second selection ran the remaining
GitHub cases in a new database. Passed-name sets are disjoint. The two
commands filtered 1,504 and 1,484 unrelated cases respectively. No full
chat or repository-suite claim is made.
- Database build, server typecheck/build, module boundaries, and
migration order pass. Five fresh PostgreSQL fixtures receive the
unchanged parent migration history through 0403. This slice adds no
database migration or table.
- The parent browser-fixture repair is carried with both complete
patches preserved. At predecessor
`836acef0370d42323fdfdbd6d62a805b2469f1d4`, entire server, package and
UI source trees and owned hashes match the 751-case acceptance. The
current follow-up adds three test cases and audit evidence; production
source remains unchanged. The parent has merged.
- [The owning
audit](https://github.com/paperclipai/paperclip/blob/ab00fc5b30d51d6c85891536599e7bdfd0c822fe/doc/plans/2026-10-25-github-webhook-recovery-sleep-audit.md)
preserves earlier failures and exact acceptance scope. Fresh exact-head
Greptile and all CI gates remain required.

## Risks

- Direct GitHub endpoints still require the existing one-minute external
history cadence, with five-minute failure/claim backoff and provider
backoff up to one day. Cloud relay endpoints are excluded. This does not
promise network-idle direct integrations.
- The existing history, envelope, attempt, and lease limits remain.
Provider history never substitutes for a genuine authenticated callback.
- Supported producers share the current database owner's process-local
signals. Independent SQL writers and other server processes need their
own integration. Unknown transaction outcomes remain held by the
existing reconciliation protocol.
- Already-started HTTP keeps its existing timeout and is joined during
shutdown. No later request starts after drain or stop; durable attempt
uncertainty is preserved.
- Host-sleep eligibility and Cloud alarm coverage stay unchanged. Local
worker tests do not prove host/database suspension or fleet savings.
- Each remaining sleep slice needs its own current review and CI checks
before merge.

## Model Used

OpenAI Codex (GPT-6), with reasoning and code execution. The exact
serving model ID and context-window size were not exposed.

## Checklist

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


Parent startup-test correction: #17664 fixes its legacy coordinator
boundary marker. This slice removes that coordinator and timer entirely,
so its existing absence assertions supersede that obsolete inspection.
All other parent and upstream changes are preserved. At predecessor
`836acef0370d42323fdfdbd6d62a805b2469f1d4`, complete server, package and
UI trees match the 751-case acceptance; all eight startup cases also
pass after the explicit conflict resolution. Fresh review and CI are
required for this new head.


## Required review finding: orphan assignment investigation

The reported orphan endpoint cannot be committed through the existing
schema: assigned_agent_id is NOT NULL, its agent FK is ON DELETE
RESTRICT, and a validated nondeferrable composite FK enforces the same
company. A first reproduction failed at fixture mutation with PostgreSQL
23502 before reaching the worker; that failure remains recorded. Three
new real-PostgreSQL cases verify NULL/missing/deleted assignments are
rejected, then prove the preserved valid endpoint recovers once, saves
its next deadline, and makes no SQL reads during a 15-second
pre-deadline interval. All 22 recovery-scheduling cases pass (19
previous plus three new); unselected cases are not counted. The
preceding style-only commit preserved production behavior and
non-comment tokens, and the prior 751-case evidence retains its original
scope (754 distinct cases across both selections). A new review must
assess this evidence before merge; the old conditional verdict is not
waived. Actual parent squash ancestry is carried with whole-tree
identity before this test-only follow-up.


Repository style follow-up removes seven new code-comment lines from the
recovery ingress owner and constraint tests. Their explanations remain
in the audit. Both files retain identical non-comment TypeScript token
streams, preserving all guards, assertions and deadlines. Production
eligibility SQL is unchanged. Fresh current-head CI and reviews remain
required.


## CI test corrections

The original strict deletion assertion reproduced CI's PostgreSQL-18
failure locally: the forbidden delete reports 23001 (restrict
violation), versus 23503 on PostgreSQL 17. The corrected assertion
accepts only these integrity codes for deletion, retains exact codes for
NULL/missing assignments, and verifies the original agent and assignment
remain. All 22 recovery cases pass on embedded PostgreSQL 18; the same
three integrity probes pass on PostgreSQL 17.

A delayed real announcement response reproduced the attachment E2E's
filechooser timeout: the dismiss handler tried to click outside an
already-open modal menu. It now closes the menu, dismisses through the
UI, and restores that menu so the original action resumes. Controlled
late-announcement acceptance passes; the temporary fault is removed. All
11 complete attachment receipt journeys pass, retries zero and original
assertions/budgets unchanged, using a fresh supported external
PostgreSQL-17 database with canonical isolated
onboarding/server/UI/storage. An earlier embedded-cluster startup
failure occurred before tests and remains recorded. Production server
typecheck passes; production source and schema are unchanged. Fresh
current-head CI and review are required.

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-28 20:05:31 -05:00
scotttongandPaperclip 71f0c0c99e feat: add opt-in Coordinator workspace for chat, tasks, and decisions (#17983)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/147/changes/paperclip/147
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People coordinate work through conversations, tasks, and requests
for input.
> - These surfaces must share task state and preserve the context of
each decision.
> - The existing workspace makes people switch surfaces to follow that
context.
> - This pull request adds an optional Coordinator workspace with linked
conversations, tasks, documents, and decisions.
> - Each person can enable it in Settings > Experimental and return to
the classic workspace.
> - The benefit is a coherent path from a request to an assigned task
and reviewed work.

## Linked Issues or Issue Description

**Subsystem affected**
UI, server, shared contracts, and database.

**Problem or motivation**
People need a consistent way to start tasks from agent conversations,
answer questions, review work, and return to the source context.
Decisions and task state must agree across these surfaces.

**Proposed solution**
Add a personal, default-off workspace experiment. Keep one conversation
per agent. Add task proposals, compact task and decision cards,
contextual document panels, and a Needs You queue with search, filters,
sorting, grouping, and history.

**Alternatives considered**
Replacing the classic workspace for everyone would remove the opt-out
path. Keeping separate decision state in each surface would create
conflicting answers. This change uses the existing canonical task and
interaction records instead.

**Roadmap alignment**
This supports the existing agent chat, task management, and human review
capabilities. It is an experimental presentation choice. The user
requested this isolated implementation after design review. No Discord
discussion is claimed.

## What Changed

- Add per-person workspace preferences, a default-off setting, and an
additive migration.
- Add Coordinator navigation, pinned destinations, task lists, agent
switching, and contextual panels.
- Link task suggestions and creation to the source conversation. Default
new task ownership to the current agent unless the user specifies
another owner.
- Share pending questions, decision receipts, exact review targets, and
history across tasks, chat, and Needs You.
- Preserve task access, assignment authorization, revision binding, and
required output review gates.
- Add compact document links, relative timestamps, composer controls,
and reduced-motion support for task and decision transitions.
- Add component stories, regression coverage, and capability-map
documentation.

## Verification

- Final head: `4b839aae1e314bd7e8635a766f1d205ff1c03ba6`, based on
master `8bc051245f77a47bee0f8ba45896b8bfa5922e0a`. Verified October 29,
2026 at 00:10 UTC: **MERGEABLE, 56 checks passed, four conditional
skips, no pending or failed checks**. [Current CI
run](https://github.com/paperclipai/paperclip/actions/runs/40790639688)
passed without a rerun on this head.
- Fresh Greptile **5/5**, zero new comments and zero open review
threads; Superagent passed with no suspicious changes.
[Checks](https://github.com/paperclipai/paperclip/pull/17983/checks).
- Local workspace typecheck/build passed after the latest rebase. The
final account-read patch passed UI typecheck/build and all 12 related
preference/settings tests, including a delayed real-client request
across account changes. Earlier scoped checks cover review
deduplication/replay, decision deep links, cross-surface state, access
boundaries, and migration replay.
- Local database/browser rechecks after the latest rebase were limited
by exhausted macOS shared-memory IDs: `initdb` failed before database
creation. The local run passed 31 UI/snapshot tests and skipped 24
database tests; those skips and the blocked local browser start are not
claimed as passes. The independent Linux CI database and browser checks
passed. No running dev database or host setting was changed.
- Upstream migration 0403 is preserved. Preferences and durable review
retry aliases are generated as replay-safe migrations
`0404_tense_silver_sable.sql` and `0405_harsh_avengers.sql`; five newest
snapshots are retained. Every detected conflict was rebased and pushed
before waiting for CI/review, as requested.
- The PR is unmerged. The active master ruleset still requires
code-owner approval for the changed Paperclip skill; no approval or rule
change was performed.

<details>
<summary>Earlier verification failures, integration history, and
evidence</summary>

These entries preserve prior checkpoints and failures; the current
acceptance result is above.

- Focused UI and server checks from the isolated build are recorded in
the implementation plan.
- Browser checks covered the opt-in shell, navigation, task/document
links, and decision card states. No new live provider trial is claimed
for this handoff.
- Current acceptance head: `4b839aae1e314bd7e8635a766f1d205ff1c03ba6`,
rebased onto master `8bc051245` immediately after its GitHub
review-repair migration took 0403. Preferences are generated as
idempotent `0404_tense_silver_sable.sql`, preserving upstream
SQL/journal/snapshot history and five newest snapshots. GitHub reports
MERGEABLE after the immediate lease-protected push. Scott's updated
instruction is to rebase and push every conflict resolution first,
without waiting for CI or Greptile; verification follows the push.
- The final reviewed feature tree was consolidated for repeatable
single-commit rebases. The complete previous commit history remains
reachable through local recovery ref
`codex/coordinator-recovery-before-rebase-20261028` (resolved snapshot
`0e1bbdf4e`). The actual rebase completed, and its tree hash exactly
matches that resolved snapshot. The force-with-lease required the known
remote head `0e6ef7c44`, protecting against concurrent branch changes.
No PR merge or permission/runner setting change occurred. Fresh
CI/review are in progress for the current head.
- `2001132fa` received Greptile 5/5 with one nonblocking account-switch
read finding. Current head detaches path-coalesced preference GETs and
disables HTTP caching, retaining React Query's account-scoped sharing. A
delayed real-client GET regression proves account B can load its saved
choice before account A responds, and A's late response only updates A's
cache. Preference/settings tests 12/12 and UI typecheck passed; its
review thread is resolved. Fresh current-head CI/reviews are pending.
The prior CI chat shard 3 ended with “The operation was canceled” and no
assertion failure ([job
123171595631](https://github.com/paperclipai/paperclip/actions/runs/40789688333/job/123171595631),
`/tmp/pr17983-2001132-chat3.log`); no code/timeout change is attributed
to that cancellation.
- `843e823b4` reached fresh Greptile 5/5 with zero comments/open threads
and Superagent pass. All browser tests including the repaired YAML shard
passed, and 54 checks passed. General server shard 9 ended with “The
operation was canceled” and no failed assertion; its test step was
marked cancelled (job
[123164350893](https://github.com/paperclipai/paperclip/actions/runs/40787501761/job/123164350893),
log `/tmp/pr17983-843e-server9.log`). A single unchanged-head rerun was
started after the workflow completed, but master moved while it ran. A
local nested-clone check timed out in its 30-second database-startup
hook and then failed cleanup before the 20 database cases ran; this is
retained as a local verification limit
(`/tmp/pr17983-843e-nested-clone-check.log`), not claimed as a pass or
proof of the CI cancellation cause.
- Following Scott's instruction, the new conflict was rebased and pushed
immediately without waiting for that rerun. Upstream's
`0403_natural_cerise.sql` is preserved; regenerated preferences and
retry-alias migrations are `0404_tense_silver_sable.sql` and
`0405_harsh_avengers.sql`, replay-safe with five newest snapshots
retained. The YAML helper conflict combines upstream's click and header
behavior with the editor-selection guard and injected regression.
Recovery ref `codex/coordinator-recovery-843e823b4` preserves pre-rebase
work. Current head is MERGEABLE. Full workspace typecheck/build passed;
UI and snapshot checks passed 31 tests, but 24 database tests were
skipped by the local support probe, and the local browser server could
not initialize PostgreSQL. A direct disposable `initdb` diagnostic
established the host limitation: `could not create shared memory
segment: No space left on device` (`shmget`, shared-memory IDs
exhausted, not disk space). No dev database or host setting was changed.
Diagnostics: `/tmp/pr17983-2001132-initdb-probe.log`,
`/tmp/pr17983-2001132-db-probe.log`; checks:
`/tmp/pr17983-2001132-tests.log`, `/tmp/pr17983-2001132-browser.log`,
`/tmp/pr17983-2001132-types.log`, `/tmp/pr17983-2001132-build.log`.
These local skipped/blocked checks are not claimed as passes; fresh CI
on independent runners is in progress.
- `d18f683cd` reached fresh Greptile 5/5 with zero comments/open threads
and Superagent pass, but [E2E shard
7](https://github.com/paperclipai/paperclip/actions/runs/40785966243/job/123159719925)
failed parsing an Advanced YAML clipboard read beginning with “Skip to
Main Content.” The log is retained at `/tmp/pr17983-d18f-e2e7.log`.
Current head hardens the test helper to verify editor focus and
selection, clear stale clipboard content, and require the YAML header at
the start of a fresh copy before parsing. Saved-state assertions and
timeouts are unchanged. All six Advanced YAML browser journeys passed on
a disposable local instance (41.0s); the exact lost-response journey
also passed with a one-time injected surrounding-page copy, verifying
rejection/reacquisition (17.6s). The precise browser focus/clipboard
timing in CI remains unproven; the observed invalid-read path is now
guarded and deterministically exercised. Logs:
`/tmp/pr17983-yaml-clipboard-scope-browser.log`,
`/tmp/pr17983-yaml-clipboard-injected-browser.log`. Fresh current-head
CI and reviews are pending.
- `19e6dcb0b` passed Superagent and Greptile 5/5, with one nonblocking
deep-link finding. Current head preserves attention links using
`?decisionId=`: the requested pending decision is rendered even beyond
the first 40 cards, focused and scrolled into view, then only that
parameter is consumed so later refreshes do not refocus. Other URL
parameters remain. Needs You tests 10/10 and UI typecheck passed; its
review thread is resolved. The preceding post-rebase regression run
passed 45/45 tests. Fresh current-head CI/reviews are pending.
- `6d772b7cc` reached Greptile 5/5 with zero comments/open threads and
Superagent pass. While 32 checks had passed, master moved and caused a
documentation conflict in `maps/feature-map/onboarding.md`. Rebased
immediately, preserving both onboarding paragraphs. The complete
four-commit branch was pushed as `19e6dcb0b` before waiting on
CI/review, per Scott's instruction. A transient Git index lock
interrupted the first continue; the command sequence briefly pushed
intermediate `34e298c07`, then the completed rebase was immediately
pushed. All feature and security/retry fixes are present; local recovery
ref `codex/coordinator-recovery-6d772b7cc` preserves the pre-rebase
history. The only tree differences from that ref are upstream's two
smoke-test files and the combined documentation paragraph. GitHub
reports MERGEABLE. Fresh current-head verification is in progress;
prior-head review results are not current acceptance.
- `21efa3120` passed Superagent but Greptile scored 4/5 for a valid
retry-key persistence bug: an acknowledged duplicate key could reopen a
resolved review. Current head adds an additive, replay-safe
`0404_light_swarm.sql` migration for indexed, task-scoped aliases from
acknowledged retry keys to the canonical interaction. Alias registration
and retry lookup occur under the existing task lock; payload/actor
mismatch still conflicts, and each canonical review permits at most 100
aliases. Original and acknowledged keys replay the terminal result
rather than creating a new gate. Five newest migration snapshots are
retained. Service/routes tests 165/165 passed; final quality review plus
migration replay/snapshot checks 25/25 passed; server typecheck passed.
The P1 thread is resolved in code; fresh current-head reviews and CI are
pending.
- `69c2c7543` passed 55 checks and Greptile 5/5 with no open Greptile
findings, but Superagent check
[123140675812](https://github.com/paperclipai/paperclip/pull/17983/checks?check_run_id=123140675812)
correctly flagged unbounded pending quality-card creation. Current head
fixes that under the existing task-row lock: equivalent requests with
fresh idempotency keys reuse the pending card; conflicting requests for
an unresolved deliverable return the existing interaction ID; pending
cards are capped at ten per task across all reviewers. Distinct outputs
remain independent, and already-answered items in a partially pending
batch can receive a fresh review. Added real-database concurrency,
cross-card duplicate, partial-answer, and hard-cap regressions. Quality
review 22/22 tests and final server typecheck passed; earlier
service/routes 163/163 tests passed before the final partial-answer
refinement. One added assertion initially expected a service HTTP error,
but duplicate keys are rejected earlier by the existing shared schema;
the assertion now verifies that validation. Fresh current-head
CI/reviews are pending; the action-required security result is not
treated as passed.
- `c9c575e5f` completed all 56 checks successfully with four conditional
skips, Greptile 5/5, and Superagent pass. Its two P2 review findings are
fixed in the current head: independently bound quality approvals now
each remain visible in attention; changing/clearing URL-backed
assignee/status filters updates the URL and survives task navigation.
Both review threads are resolved. Regression evidence: attention service
34/34 tests passed, CoordinatorTasks 20/20 passed, UI and server
typechecks and the full workspace build passed on `69c2c7543`. The first
new UI test run caught an assertion racing React Router's transition;
waiting for the navigation before asserting passes without weakening the
navigation/remount checks. These older-head green checks are not claimed
for the new fix commit.
- Preceding `0e6ef7c44` completed all 56 checks successfully with four
conditional skips, fresh Greptile 5/5 and no open findings, and passed
Superagent. A fifth migration-metadata collision arrived before the
final Runner job finished. Those green results are preserved as
prior-head evidence, not current acceptance.
- Previous fully verified migration head:
`0e6ef7c44696a377f35e69521b93587576374bd0`, integrating master
`f8226b051` after the fourth migration-number collision. Master added
terminal GitHub-response migration 0401 while the final native check
ran; upstream 0401 SQL/journal/snapshot is preserved unchanged, and
preferences are generated as idempotent `0402_yielding_blink.sql` on
top. Exactly the five newest snapshots remain. GitHub reports MERGEABLE
after the push. All 1,155 relevant
migration/review/interaction/native-execution/remote-assets tests,
workspace typecheck/build, migration guards and whitespace checks pass.
Fresh exact-head CI/Greptile/Superagent are pending.
- Immediately preceding head `36c67cf03` completed all 56 checks
successfully with four conditional skips, fresh Greptile 5/5 and no open
findings, plus passed Superagent security. No retry was needed for that
head's CI. Master advanced and introduced only a migration-metadata
conflict while its final native check ran, so that green result does not
establish acceptance of the current integration. Four consecutive
collisions (0398, 0399, 0400, 0401) during verification are retained as
concrete integration churn; a brief pause of competing migration merges
was requested, without assuming it happened or changing any repo
setting. The PR has not been merged.
- Prior fully verified head: `36c67cf03`, on the clean `30059c0ed`
integration of master `efd65c112`. The last Greptile P2 is fixed: Needs
attention retains the participant-agent scope through authoritative
server membership queries for each pending task, including historical
participation when another agent currently owns the task. It does not
approximate participation with current assignment or enumerate every
company task. The actual view-switch regression and all 31 focused
task/routing/collection tests, UI typecheck/build, token gates and
whitespace checks pass. Greptile completed a fresh 5/5 review on this
exact head (review 19) with zero new comments and no open review
threads. CI and Superagent remain in progress; no current-head CI
failure has been reported.
- Head `30059c0ed` received Greptile 5/5 with that one nonblocking
participant finding, now fixed. Superagent passed that head.
Current-base integration restored the ephemeral RunsOn fleet after a
superseded workflow retained queued aggregate jobs: normal cancellation
was insufficient; the single force-cancel request was interrupted but
readback confirmed that obsolete run cancelled and current CI began on
the trusted fleet. No cancellation retry or runner/security/workflow
changes were made. Its partial CI was superseded by the necessary
participant fix and is not current acceptance.
- Previous compatibility/base-sync head:
`30059c0ededc0eab4e04e8299a884f36db8b292f`, integrating master
`efd65c112` and the Inbox/workspace compatibility fixes. GitHub reports
MERGEABLE after the push. Coordinator keeps Inbox standalone under More
without rewriting the instance's Combined Inbox preference; opting out
restores that preference. Saved merged-Inbox URLs resolve to their
original owner, task status presets remain usable, and canonical
repeated `workspace` parameters retain scoped, deduplicated pagination
(including Needs attention). All 192 broader
routing/Inbox/sidebar/privacy/review tests and the final 16 task-page
tests pass, as do workspace typecheck/build, token gates and whitespace
checks. The two review threads are resolved. Fresh exact-head CI,
Greptile and Superagent results are pending.
- The preceding `d5b9be5bd` remained mergeable but its CI routing gate
intentionally fell back to GitHub-hosted runners: “stacked base merge
commit does not contain the current base branch.” All 45 downstream jobs
stayed queued. Current master was merged cleanly to refresh the pinned
base; no runner/security settings or workflow logic were changed.
Greptile scored that preceding head 4/5 with the two compatibility
findings fixed here. Its automatic Superagent scan was inconclusive at
checkout; the documented retry was still pending when superseded. Those
results do not establish acceptance of this current head.
- Previous approval/migration head:
`d5b9be5bd3b8d6b0437e42bf48138377f34fa67d`, integrating master
`ba5bba86d` and the stale-output approval correction. GitHub reports
MERGEABLE after the push. The fresh P1 finding is fixed: every submitted
item now validates and locks its bound output inside the resolution
transaction, whether or not it carries a required-quality-review
binding. Real database regressions verify that an advanced document
revision or deleted attachment refuses the entire batch without
recording approvals, and current ordinary output reviews still resolve.
All 272 combined migration/review/interaction tests pass; workspace
typecheck/build passed. Fresh exact-head Greptile and CI are pending.
The automatic Superagent scan ended inconclusive at checkout; one
documented on-demand retry is pending. These are explicit verification
limits, not passed security results. The P1 thread is resolved.
- Master consumed the next migration slot three times during this
verification pass: confirmation recovery took 0398, continuation
recovery took 0399, and GitHub acknowledgement recovery took 0400. Each
upstream SQL/journal/snapshot is preserved unchanged. Preferences are
now generated as idempotent `0401_white_lenny_balinger.sql` from
upstream 0400; exactly five snapshots remain, and replay coverage
locates this migration by table content. This is recorded concurrent
integration churn, not a claim that older green results apply to the
latest base.
- Head `ed3b68da9` fixed the two history/URL findings with 26 focused
regression tests, server/UI typechecks, workspace build and token gates
passing. Greptile then scored that head 4/5 with the stale-output P1
corrected in the current head. Its partial CI is superseded, not counted
as current acceptance.
- Previous filter-fix head: `ed3b68da9`, based on the `8458d39d9` merge
of master `063cfd438`. The two fresh Greptile findings are fixed:
history outcome filters now match recorded per-item verdicts in SQL
before pagination (mixed reviews remain in both applicable outcomes),
and same-page URL assignee changes/back/forward navigation update that
filter without clearing independent filters. All 26 focused
database/navigation/collection tests, server/UI typechecks, workspace
build, token gates and whitespace checks pass. The two review threads
are resolved. Fresh exact-head CI, Greptile and Superagent results are
pending.
- The `8458d39d9` migration integration also passed all 328 targeted
migration/interaction/confirmation tests, workspace typecheck/build and
Superagent security scan. Greptile scored that head 4/5 with the two
functional gaps fixed in the current head; those prior-head checks are
not current acceptance.
- Migration integration head:
`8458d39d9721f4cb312c2390070a0609f8cddd1a`, integrating master
`063cfd43813cabf18417605fb9eefb9aacf95c8d`. GitHub reports MERGEABLE
after the push. Master advanced twice during this conflict-resolution
pass: first its confirmation-recovery migration took 0398, then its
continuation-recovery migration took 0399. Both upstream migrations and
journal entries remain unchanged; Coordinator preferences are now
generated as idempotent `0400_sad_guardian.sql` from upstream's latest
snapshot. Exactly the five newest snapshots remain. The replay
regression now locates the table migration by content instead of
hardcoding a renumbered filename.
- All 328 targeted question/review/confirmation/migration tests passed
again after the second merge. Workspace typecheck/build and fresh
exact-head CI/reviews are in progress. The preceding `0c46f46d6` passed
workspace typecheck/build and Superagent security scan, but was
superseded because master consumed migration 0399 while those checks
ran. That prior-head result is not acceptance of the current head. No
production settings or runner/security permissions were changed, and the
PR has not been merged.
- Previous integration head: `0c46f46d6f2b23417ab872ce3cb6ff2673647287`,
integrating master `287b04d72f1b9fca1412e05435c75b8302ba0710`. GitHub
reports MERGEABLE after the push. The renewed conflicts were
`0398_snapshot.json`, `_journal.json`, and the top imports in
`issue-thread-interactions.ts`. Upstream's `0398` confirmation-recovery
index and journal history are preserved unchanged; Coordinator
preferences were regenerated as idempotent `0399_bouncy_miek.sql`, with
replay coverage updated and exactly the five newest snapshots retained.
Both terminal confirmation notifications and Coordinator task
assignment/required review behavior are preserved.
- All 328 targeted interaction/review/confirmation/migration tests pass,
as do workspace typecheck, map validation and whitespace checks. The
workspace build and fresh exact-head CI/Greptile/Superagent checks are
pending. The first migration-generation attempt hit the sandbox's local
IPC restriction before generating files; the unchanged authorized local
generation completed successfully. Prior-head green checks below do not
establish acceptance of this merge.
- Previous acceptance head: `8b7dcf739ed15afc51351fdfa0e0e5fbc75ab788`,
with master `1aa3a21ac` integrated and GitHub reporting MERGEABLE.
Greptile completed a fresh 5/5 review on this exact head with zero new
actionable findings and no open review threads. The [fresh CI
workflow](https://github.com/paperclipai/paperclip/actions/runs/40752864319)
completed SUCCESS on attempt 2 at 19:40:08 UTC, including all eight E2E
shards. Final completed check set: 55 succeeded, four conditional checks
skipped, zero pending/queued/running checks, and one
neutral/inconclusive Superagent scan. The auxiliary commitperclip review
and isolated native Runner compilation/cache-reuse check both passed.
This is not a claim that Superagent produced a passed security verdict.
GitHub still reports MERGEABLE against current master
`60b8089a44b4eaa37e627adbfdf2f130bda13335`.
- Current-head E2E: all eight shards and the aggregate passed, including
the previously failing YAML browser journey. Serialized server shard 9/9
failed: the protected YAML projection test exceeded its original
15-second timeout; its late update request then reached the next test's
reset mock (the captured payload is the prior test's model/label
update). All 88 tests in that exact unchanged file passed locally in
38.03 seconds, with no timeout or assertion changes. The original
slow-request cause remains unproven. CI failure log:
`/tmp/pr17983-8b7-serialized9.log`; local recovery:
`/tmp/pr17983-adapter-yaml-repro.log`. The single bounded unchanged
shard rerun passed, and the workflow completed SUCCESS. Rerun log:
`/tmp/pr17983-8b7-serialized9-rerun.log`. The initial failure is
retained; a passing retry does not establish its original slow-request
cause.
- Greptile scored preceding head `4873704be` 5/5 with one valid P2:
opened task decision records missed company-scoped live invalidation.
The current head uses the existing company decision prefix for
resolution and effect-completion events, and resets private record
payloads on access changes. Its thread is resolved. All 107 focused
record/live-update tests, UI typecheck/build, token checks and
whitespace checks pass.
- CI on `4873704be` failed E2E shard 7/8 in the Advanced YAML
lost-creation-response journey: its clipboard helper selected page text
starting with “Skip to Main Content” instead of YAML. The exact
unchanged journey passed in a disposable local browser instance (1 test,
17.1 seconds). No assertion, timeout or production behavior was
weakened; the original failure cause remains unproven. Failure log:
`/tmp/pr17983-487-e2e7.log`; local check:
`/tmp/pr17983-agent-yaml-repro.log`. The full unchanged Advanced YAML
browser suite also passed locally (6 tests, 37.8 seconds). Fresh
current-head CI subsequently passed this journey and all other E2E
shards.
- Both the automatic and one supported on-demand Superagent scan on
`4873704be` ended neutral/inconclusive: “Pinned PR scan merge-base
checkout failed or timed out.” These do not count as a passed security
verdict. The current head's automatic scan and one documented on-demand
retry also returned the identical neutral checkout failure, with zero
annotations or further diagnostics. This is an external scanner blocker,
not a passed security verdict. No security settings or permissions were
changed.
- Recorded decision links now render and focus the full source-task
record in both Classic and Coordinator, including recorded choice,
submitted inputs, and the existing effect-result resolver. Fresh
terminal records take precedence over older open-decision cache entries.
Context and account checks keep mismatched or inaccessible records out
of the DOM; no decision-history tab was added to tasks or chat. The
shared company live-run feed now drives live-only filtering, including
ended runs and terminal tasks with stale run entries. All 213 focused
tests, UI typecheck/build, token and whitespace checks pass; the final
focus follow-up passed all 188 task-detail tests and UI typecheck. The
first new navigation test failed because its test host omitted company
context; the host was corrected before the passing run.
- Previous integration head: `375c5e89516705050d94bab99336212841b2e6e1`
merges master `1aa3a21ac` after four additional upstream commits. The
sole conflict was competing imports in `server/src/services/issues.ts`;
both quality-review policy and inbound wake-notice notifications are
preserved. The PR-specific review import now sits beside
execution-policy imports instead of the frequently changing first line.
GitHub mergeability is rechecked after the push.
- On the combined master tree, workspace typecheck/build, all 153
affected UI tests, map validation, and whitespace checks pass. Four
server suites passed 77 tests; the fifth suite's module-import hook
timed out while broad verification was running. Its unchanged isolated
run passed all 41 tests in 7.2 seconds with the original timeout. This
records recovery without claiming the original import-timeout cause is
proven. CI on `375c5e895` passed every substantive job, including all
eight E2E shards and Superagent; Greptile found the two functional gaps
fixed in the current head. A short-lived `669d90876` commit added the
main fixes before the focused navigation follow-up.
- Immediately preceding head `9d9737b49` completed all 56 checks
successfully with four conditional skips, Greptile 5/5 and no open
findings, plus a successful Superagent scan. The signoff E2E shard
passed on its single accepted rerun; its initial cancellation/timing
failure is retained below. Master moved again while those checks ran,
requiring this final integration rather than treating the prior head's
green result as current acceptance.
- Previous head `9d9737b496911a6054d0ea22d1b42b28b115e9ab` includes
master `d30c8f42b842327ee1c18c41a2efd6ba623da5cd`; that head was
subsequently conflicted by moving master. The master merge preserved
durable account-bound writes and Coordinator UX. Workspace
typecheck/build, 416 focused UI tests, and 142 affected comment-route
tests passed. A stable full UI run on preceding head `938ad1665` passed
all 9,833 tests across 836 files; its final full workspace build also
passed.
- Greptile found nested proposal project inheritance and Classic
bound-revision links on `91be74952`. Both were fixed with 142
interaction-route tests, 113 focused UI tests, and UI/server typechecks.
Its next review identified a valid draft-preservation bug in the new
Classic loading UI. Head `9d9737b49` keeps loading/error notices outside
editors and annotations while preserving dirty drafts; 115 focused
review UI tests pass, including pending/failed revision loads and
continued draft editing. All related threads are resolved. Greptile
completed a fresh 5/5 review of
`9d9737b496911a6054d0ea22d1b42b28b115e9ab` with no open findings.
- CI on `938ad1665` exposed an integration regression with the newly
merged durable startup saves: the personal preference gate blocked the
task page before its first session lookup. The guarded title editor now
mounts while that lookup is pending, with presentation-specific tools
still gated. All 216 affected component tests pass. The unchanged
five-test `disconnect-write-recovery.spec.ts` browser suite passes
against a newly launched disposable local-trusted PostgreSQL instance on
port 33219, including the exact failed startup-save journey. No live
provider, hosted authentication or production proof is claimed. The
helper-owned test server exited and the port has no listener. UI
typecheck, built-browser assets, token and whitespace checks pass.
- Initial durable-write merge tests found duplicate imports and unscoped
draft fixtures, fixed before 416 focused tests passed. A sandbox
typecheck could not create its IPC socket; the supported rerun passed.
The first revision-link test used a wrong Return to latest button
assertion, corrected before the 113-test pass. The startup E2E
reproduction initially still failed because an outer shell gate also
blocked the page; the subsequent fix passed all five cases without
changing the test or its timeouts. A focused loading-header assertion
initially used an incorrect fixture title; correcting it preceded the
216-test pass. These failures remain recorded.
- Earlier routing gates fell back to GitHub-hosted runners while master
was moving or conflicted. Superseded queued runs were cancelled, then
the `938ad1665` routing gate explicitly selected the ephemeral RunsOn
fleet. Its CI actively executed and completed most tests; only the
diagnosed startup E2E shard and aggregate failed, alongside the valid
Greptile finding. Auxiliary GitHub-hosted workflows also completed
successfully on earlier heads, so queueing alone is not an
administrative blocker. Fresh [CI on
`9d9737b49`](https://github.com/paperclipai/paperclip/actions/runs/40744012678)
is the acceptance target; the previously failing startup E2E shard now
passes. A different signoff E2E shard failed during executor
resubmission when its fixture run was cancelled as
`issue_continuation_waiting_on_review`. The exact unchanged journey
passed locally (1 test, 46 seconds), and the preceding head with
identical server/signoff code passed that CI shard. This supports a
bounded rerun but does not establish the timing failure's root cause.
After the workflow finished, GitHub accepted one rerun of that failed
shard and its dependent aggregate; both passed, completing all checks on
that head. The failure log is retained at `/tmp/pr17983-9d9737-e2e7.log`
and the local reproduction at `/tmp/pr17983-signoff-repro.log`. No
assertion or timeout was weakened.
- On the first merge, full workspace typecheck/build, all 9,622 UI
tests, 267 tests across seven affected server suites, two migration
checks, map validation, token gates, and the PR diff whitespace check
passed. Greptile then found duplicate local task-search filtering and
lost completed item-review detail. Both are fixed, with 42 passing
focused UI tests and passing UI typecheck/build.
- A subsequent Greptile review found attachment confirmations without
working links and mobile history without a visible host. Confirmation
layouts now derive the authenticated immutable-content endpoint from the
attachment ID, and Needs You uses the existing full-screen mobile sheet.
All 119 focused tests pass, including missing/stale display URLs, both
review layouts, and both mobile history entry buttons. UI
typecheck/build and token checks pass. Full workspace typecheck/build
also pass after the second master merge.
- Greptile gave head 22f69c304 a 5/5 score with one non-blocking
desktop-history reopening finding. Head 6dd52b6d3 fixed it, passed all
nine history tests, UI typecheck/build, token gates, and the full
9,679-test UI suite, then received a fresh 5/5 review with zero open
findings. These are prior-head results; review on the master-sync commit
is pending.
- The chat and workspace CI jobs on head 22f69c304 were interrupted by
runner shutdown signals and cancellation before completing their tests.
Their logs do not report failing assertions. Those interrupted jobs are
not claimed as passes. The new head starts fresh runs.
- The first merge CI had a Slack session-sync idle assertion fail after
an unexpected database read. Its exact isolated reproduction passes, and
the chat CI shard passed on head 618c5a2a3. The original failure's cause
remains undetermined. The broader local reproduction, run concurrently
with full verification, instead encountered 21 timeout failures across
its two test chunks; it is not claimed as a passing full local server
run. A concurrent local UI run had eight failures (seven timeouts and
one delayed autosave assertion). The complete UI run on the final head
passed all 9,679 tests across 830 files with two workers; no test
timeout or assertion was weakened. This establishes recovery without
claiming that every earlier timeout's cause has been proved. An earlier
intermediate UI run also overlapped the second master merge and failed
the newly added Advanced-sidebar expectation, so it is not treated as
stable-tree evidence. The newly merged UI dependencies initially
required refreshing the local install from the upstream package
manifest; the generated local lockfile update is not committed, per
repository policy.
- Superagent returned neutral/inconclusive scans on the preceding heads
because its pinned merge-base checkout failed or timed out. The
available retry endpoint returned 404. These are not successful security
verdicts. The fresh scan on `91be74952` passed (PR scan passed; no
suspicious PR changes detected). The `938ad1665` scan again returned
neutral/inconclusive with the same pinned merge-base checkout error; the
check-suite rerun endpoint returned 404. The fresh `9d9737b49` scan
completed successfully at 18:22 UTC with no suspicious changes detected.
Earlier neutral scans are not counted as successful security verdicts.
- Prior head `57902152ac3218096fca669d33ff18400a2a86ae` passed 9,618 UI
tests across 826 files, received Greptile 5/5 with no open findings, and
completed CI with 56 passes and four conditional skips. These are
historical results, not acceptance of the latest merge commit.
- The first full build found generated capability-contract drift. The
generated outputs were refreshed. Initial sandbox runs could not open
local IPC sockets; verification was rerun with local test access.
- Current master was merged. The workspace preference migration was
regenerated after the existing migration history.
- The UI run first found two outdated expectations: early custom-answer
validation and the document access error copy. Both were corrected, and
the full UI suite then passed.
- The local server run found three failures in unchanged tests. The Muse
test passes with Python 3.13 instead of the host's Python 3.9. The two
workspace tests pass when their test process uses the expected master
default branch. These environment settings do not change application
behavior or global machine settings. The unsharded server run was
stopped after those reproductions; CI supplies the full sharded server
result. No successful full local server run is claimed.
- Skill inventory generation needs an external eval checkout, which is
absent locally. The existing generator functions refreshed only the live
skill inventory and its derived files. The checked-in eval inventory was
preserved. The inventory validation gate passes.
- Greptile found a dropped MCP review requirement, missing per-item
output links, generic item-review summaries, and a history-refresh
failure. The fixes have 32 passing database-backed server tests and
focused rendered-card tests. A follow-up partial-review finding was
corrected by forwarding the canonical mutation status before settling
the card. Attachments open through the authenticated immutable-content
route in both card layouts. The final focused UI set has 117 passing
tests, including these regressions.
- Both browser shards that first failed expected a disabled-chat
message. The copy was restored, and those shards passed in CI on the
next commit. The two journeys also passed locally. One local attempt
first timed out before feature disable while waiting for the provider's
initial message; its isolated reproduction passed. That earlier timing
failure remains recorded and is not presented as an explained
infrastructure failure.
- Serialized server shard 9 first failed during pnpm setup with
ECONNRESET, before dependencies or tests ran. Its single rerun passed
setup and all tests. The build and production runtime boot passed on the
first attempt, but that run's public-install step timed out during Pi
setup. The single build-job rerun passed compilation, runtime boot, and
clean public-install verification. Those setup scripts are unchanged by
this PR. The successful retry establishes recovery; the earlier Pi
timeout's underlying cause remains undetermined. The aggregate CI gate
is green: [workflow
run](https://github.com/paperclipai/paperclip/actions/runs/40637789695).

</details>

## Risks

- This touches shared task, interaction, and completion paths.
Regression tests must cover classic and experimental behavior,
authorization, duplicate answers, and stale review targets.
- The additive preference table must migrate before the setting is used.
The setting defaults off.
- The experiment changes navigation and message presentation. Canonical
task and document records remain the source of truth.
- The initial task brief and saved plan can repeat information. This
change fixes chronology; a broader redundancy policy remains a design
decision.

## Model Used

OpenAI GPT-6 Codex with reasoning and tool-assisted code editing, tests,
and browser verification. Earlier iterations used Codex models in this
task; their exact model IDs are not available in the current context.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used
- [x] I have checked ROADMAP.md
- [x] I have searched GitHub for duplicate or related PRs
- [x] I have described the issue in-PR following the relevant issue
template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change
- [x] I have run relevant tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation
- [x] I have documented risks
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open recommendations or follow-ups
- [x] I will address review comments before requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-28 17:20:01 -07:00
Nicky LeachandPaperclip c57af3c564 Reuse prepared Runner storage and installed skill selections (#18089)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/207/changes/paperclip/207
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip manages AI agents and their work.
> - The native Runner prepares selected skills, instructions, and
provider storage.
> - Repeated preparation imports the company skill inventory and
rebuilds Claude storage.
> - Execution environments can already maintain prepared resources.
> - This pull request lets them reuse account storage while Core keeps
execution policy.
> - New retry runs resolve current skills and keep the failed attempt's
history.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Native Runner preparation and retry skill selection.

**Current behavior**

Explicit installed selections still trigger company inventory
reconciliation. Plugin preparation receives account identity only on
warm transitions. Claude's isolated mode requires a session-specific
configuration directory.

**Proposed behavior**

Skip inventory imports when explicit selections are installed, while
retaining current authorization and version resolution. Send account
identity on initial preparation. Allow an execution environment to
provide persistent Claude storage without enabling preconfigured
permission behavior. A new retry resolves current skill assignments.

**Reason and benefit**

Remove repeated preparation work without adding environment-specific
policy to Core. Related: #13984 describes a similar storage-lifetime
problem in the separate claude_local adapter; this PR does not change
that adapter.

## What Changed

- Derive Claude’s configuration path from the single authoritative
prepared-storage input; separately supplied CLAUDE_CONFIG_DIR values are
overridden.
- Add an explicit prepared Claude storage binding, forward it to the
sidecar, and retain recovery and provider lifetime fencing.
- Refresh Core-owned Claude settings after acquiring the lifetime lease.
Reuse environment-prepared skills.
- Reuse installed explicit skill selections and preserve
missing-selection initialization and current access checks.
- Reserve the prepared-home marker for environment provisioning; task
overrides are rejected and configured bindings are stripped before
native launch.
- Clear inherited skill selection snapshots on new retries. Keep
admitted execution recovery and failed attempt metadata.

## Verification

- Current single-input follow-up `8dbc2f6ec`: 154 focused Runner checks
pass with one existing skip; four Grok identity checks and four Pi
packaged-probe checks pass. Shared immutable source identities advance
to Grok10/Pi32/Copilot74. All56 current-head CI checks pass (four
intentionally skipped); standard and enhanced reviews are both5/5 with
no unresolved threads.
- Focused Runner sandbox tests: 29 passed. Focused environment tests: 16
passed.
- company-skills-empty-runtime: 10 passed.
- Plugin Runner and runtime selection database tests were attempted.
Local execution is blocked because embedded PostgreSQL cannot load
libzstd.1.dylib; these checks remain for CI.
- New database regressions cover installed-selection reuse, initial
account preparation, and retry snapshot removal.
- Prepared-home trust-boundary regressions: 4 targeted checks passed
(task schema, all env binding scopes, native executor).
- Focused Pi public-install probe checks: 4 passed. The build smoke
probe now asserts the current Pi 32 profile and exact digest.
- CI found and fixed retry-context TypeScript inference, stale Pi
identity fixtures, Docker source identity inputs, and the
skill-observability test’s old assumption that every selection imports
inventory. Cold and reused selection coverage remain.
- CI chat shard 2 initially failed three GitHub/Discord idle-database
assertions. An unchanged-head rerun passed; the original cause remains
unexplained.
- Runtime head `f5b53679a` passes all 56 current CI checks (four jobs
intentionally skipped), including the full build/public-install probe,
TypeScript, Rust, Runner and server matrices. Greptile is 5/5 with no
unresolved review threads.
- The requested enhanced review scored 5/5 on `f5b53679a`, with one
nonblocking documentation request. Documentation follow-up `1ac5d26a8`
adds only the documented existing ownership/0700 requirement; the thread
is resolved and all 56 current-head checks pass (four intentionally
skipped). The subsequent single-input runtime follow-up8dbc2f6ec
repeated the complete CI → standard5/5 → enhanced5/5 cycle successfully.
- Broader verification is delegated to GitHub CI as requested. The
initial policy check rejected a generated lockfile repair; that change
was removed because Core CI already resolves stale importer entries.

## Risks

Prepared storage must be provisioned by the execution environment before
launch. It is not credential isolation. Core replaces managed Claude
settings under the existing provider lease. No new per-run harness homes
are created by this option. New retries may select a newer skill
version; recovery of an already admitted provider execution keeps its
saved input.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning and tool use. The exact model
revision is not exposed in this session.

## 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
related context above
- [x] I have described the issue in-PR following the relevant issue
template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change
- [x] I have run focused local tests; database and full verification
remain for CI as explained above
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation
- [x] I have considered and documented risks
- [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-10-28 17:09:24 -07:00
DottaandPaperclip 8bc051245f fix(server): wake stale GitHub review repair from committed changes (#17664)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/215/changes/paperclip/215
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - GitHub checks and task admission can finish in either order.
> - A check can reject an old head before admission creates its review
row.
> - The chat maintenance loop repeatedly scans for that late review.
> - Existing cancellation and delivery receipts already identify the
repair.
> - This pull request wakes repair from committed changes and leaves
settled history quiet.

## Linked Issues or Issue Description

**What happened?**

GitHub chat maintenance repeatedly scans all review projections. Empty
instances and retained history incur database work even when no repair
is owed.

**What did you expect?**

A committed stale-head cancellation or admitted review should wake
repair. Only the exact delivery's unassessed queued/running review
should become superseded. When no repair remains, this duty should stop
making database calls.

**Steps to reproduce**

Configure a GitHub chat endpoint and leave it idle after all reviews
settle. The previous maintenance callback continues to call
repairSupersededReviews. A rapid push can also cancel a check before
admission inserts its review, which explains why recovery must remain.

Refs #17662, the merged review-check publication parent. Related #17661
and #17656 migrate terminal responses and acknowledgements. This slice
owns only late stale-head projection repair.

## What Changed

- Move the repair predicate and execution into the GitHub provider
owner. Match the original admitted delivery and cancellation receipt.
Recheck state and assessment in the update.
- Register a scoped worker with the existing coordinator. Use keyset
pages and fair bounded dispatch. Keep retries only for unresolved repair
or failed reconstruction.
- Signal before cancellation, automatic receipt insertion,
automatic-review binding, and check-driven review-state writes. Preserve
existing transaction ownership and outer commit behavior.
- Remove the periodic provider wrapper and publication-maintenance
callback. Preserve explicit manual recovery and independent
missed-webhook recovery.
- Add two concurrent, idempotent partial indexes. Use a guarded delivery
UUID lookup and a bounded exact-receipt lookup. Add no tables.
- Add ten real-database lifecycle and producer cases. Document the
producer audit, failure history, and remaining limits.

- Keep YAML browser reads scoped to the editor after focus changes, with
the original journey assertions and deadlines.

## Verification

Current source: `0886a0229b1c4f68d2f582da86aa1f248e9124f3`.

- At `dd6bca0485c3444d6e3d0ee10ec4aa651e801392`, **287 distinct cases
pass**: 274 complete GitHub workflow cases and 13 startup cases. The
GitHub command filters out 1,485 unrelated cases. The workflow suite
uses a new, pre-migrated PostgreSQL database.
- Coverage includes both orders of cancellation and admission, outer
commit and rollback, restart, drain, standby, failed-update retry,
concurrent assessment under an observed row lock, shutdown during that
wait, more than one candidate page, manual history, and settled-history
quiet.
- Database build, server typecheck/build, module boundaries, and target
migration order pass.
- Canonical migration `0403_natural_cerise.sql` preserves both original
index definitions and concurrent idempotent creation. All 401 parent
migration receipts remain unchanged during upgrade. One new receipt is
added. Replay adds none. Both indexes are ready and valid on fresh and
upgraded databases. The five newest snapshots remain.
- The normal parent merge preserved the prepared tree. The later browser
fixture repair changes only its central read helper and verification
note. Entire server, package, and UI trees remain identical to the
accepted source.
- [The owning
audit](https://github.com/paperclipai/paperclip/blob/0886a0229b1c4f68d2f582da86aa1f248e9124f3/doc/plans/2026-10-25-github-review-projection-sleep-audit.md)
records the exact evidence and earlier failures. Earlier query-plan
measurements retain their historical revision scope.
- Fresh current-head CI and Greptile review remain required. No deployed
sleep, full repository-suite, or fleet-savings claim is made.

Failure accounting: browser shard 7 failed twice on
`1453a4447c0d4d33f713ae3e00734c7950f95426` because the YAML helper read
whole-page clipboard text while main was focused. Three isolated
unchanged local passes did not resolve that failure. A controlled native
focus-loss probe reproduced the same error before the repair and passed
after it. The helper now clears stale clipboard data, focuses the
editor, and waits within the existing expectation budget for a fresh
YAML copy. All six complete YAML journeys pass with zero retries in 50.9
seconds. Journey assertions and deadlines are unchanged. The temporary
fault is removed. The exact CI focus-change trigger remains unknown.
[Both CI
attempts](https://github.com/paperclipai/paperclip/actions/runs/40777754306)
remain part of the verification record. Fresh new-head checks are
required.

Ponytail follow-up: the 4/5 review of `b3c81ba` was conditional on
fixing a stale startup-test slice marker, so the merge was held.
Boundary assertions reproduced the invalid -1 end index. The test now
uses the existing timer declaration and checks both bounds; all 13
startup/hostname cases pass. The optional no-op coordinator cleanup is
already in #17666. The six YAML journeys and all production code remain
unchanged. Fresh review and CI are required for this corrected head.

## Risks

- Missing a future producer signal could delay discovery until restart.
Supported writers share the current database owner's process-local
notification scope. Independent SQL writers and other server processes
need their own integration.
- The migration builds indexes concurrently. The existing migration
runner handles interruption and invalid index recovery.
- Direct GitHub missed-webhook discovery remains periodic. This change
does not make the whole chat service idle.
- Existing Cloud wake coverage and sleep blockers remain unchanged.
These tests do not prove deployed host or database suspension.
- Each remaining sleep slice needs its own review and CI checks before
merge.

## Model Used

OpenAI Codex (GPT-6), with reasoning and code execution. The exact
serving model ID and context-window size were not exposed.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] 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-10-28 18:42:54 -05:00
DottaandPaperclip 65fa1cd617 fix(server): schedule GitHub review checks from committed changes (#17662)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/213/changes/paperclip/213
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - GitHub review checks report the state of admitted agent work.
> - The chat maintenance loop searches for check work even when none
remains.
> - Existing action rows already record unfinished publication and retry
deadlines.
> - Committed changes can wake those rows through the shared
coordinator.
> - An unresolved check must still detect a remote head change when a
webhook is missed.
> - This pull request schedules only outstanding checks and leaves
settled history quiet.

## Linked Issues or Issue Description

**What happened?**

The GitHub chat maintenance callback repeatedly queries review-check
actions. Empty queues and completed history still incur database reads.
Local state changes wait for the maintenance callback.

**Expected behavior**

Committed check creation, review binding, run changes, and
publication-lease release wake the worker. Existing retry and
remote-head deadlines apply only to unfinished checks. A settled worker
makes no recurring database or provider calls.

**Steps to reproduce**

Configure a GitHub bot with no outstanding checks, or finish all of its
checks. Leave the instance idle. The old maintenance callback continues
to call the check service.

Refs #17661, the merged terminal-response parent. Related #17656
migrates response acknowledgements. Related #16385 changes branch-policy
admission; this PR preserves that separate policy boundary. Late
stale-head projection repair remains a separate follow-up slice.

## What Changed

- Move the existing check-state reader into the GitHub provider owner.
Preserve current authority, run selection, assessment ownership, and
check replacement behavior.
- Register a scoped worker with the existing coordinator and scheduler.
Existing received and retryable-failed actions remain durable truth. No
new table is added.
- Signal check enqueue, task review receipts, manual review
insertion/binding, run lifecycle changes, and publication-lease release
through existing transaction ownership.
- Preserve the saved failure backoff, eight-attempt policy, and
competing lease expiry. Keep five-second remote-head reconciliation only
while a received check remains unresolved.
- Check admission before each HTTP request. Shutdown leaves durable work
recoverable without spending a provider failure attempt.
- Remove check dispatch from the periodic GitHub callback. Keep the
separate late-projection repair and the manual combined recovery method
compatible.
- Add an idempotent concurrent partial index for unfinished check
selection. Retain the newest five generated snapshots.
- Add eleven real-database worker cases and startup wiring coverage.
Document producer coverage and the external reconciliation limit.

## Verification

Current reviewed source: `2bba08403b195bf646eda48992b46d6f5cebf756`.

- Normal merges preserve the complete review-check patch, the landed
terminal-response parent, and current master changes. No landed SQL
migration or journal entry changes.
- At `6995f84b240a14a7b8660e1cf095b3aa1e1e3168`, **331 distinct tests
pass**: 264 complete GitHub workflow cases, 30 completion cases, eight
issue-tree producer cases, 16 login-cleanup cases, and 13 startup cases.
The GitHub command filters out 1,485 unrelated cases. Login cleanup uses
its real embedded PostgreSQL fixture.
- Combined-master acceptance: **277 distinct tests pass** at
`9c538aed1251fd7f7cecb829a0ecbce6110fb1ed`: 264 complete GitHub workflow
cases and 13 startup cases. The GitHub command filters out 1,485
unrelated cases. A new PostgreSQL database receives all migrations
through 0402..
- Migration `0402_ancient_malice.sql` preserves the original partial
index definition and concurrent idempotent creation. All 400 prior
migration receipts stay unchanged during upgrade. One new receipt is
added. Replay adds no receipt. The index is ready and valid on fresh and
upgraded PostgreSQL databases. The five newest snapshots are retained.
- A rollback-only query probe adds 10,000 processed actions and one
pending action. The actual parameterized candidate predicate selects the
one pending row through the partial index, with two shared buffers and
0.007 ms execution time. This measures candidate discovery, not all
lease or provenance reads.
- Database build, server typecheck and build, module boundaries,
migration safety and migration order pass. Audit: [GitHub review-check
scheduling](https://github.com/paperclipai/paperclip/blob/2bba08403b195bf646eda48992b46d6f5cebf756/doc/plans/2026-10-25-github-review-check-sleep-audit.md).
- Fresh checks and Greptile review are required for this head. Prior
scores do not count. These checks do not prove deployed host suspension
or fleet savings.

## Risks

- Unresolved queued/running checks still make remote-head requests at
the existing five-second deadline. GitHub webhook receipt does not prove
future pushes cannot be missed. This PR does not claim active reviews
become network-idle.
- Run and configuration hints rebuild outstanding checks for the
affected company. Enqueue, review, and lease hints narrow to the
affected endpoint/repository/PR. Startup and scope reconstruction read
existing pending rows; they are not constant-cost operations.
- Delivery admission failures remain discoverable through the unresolved
check's external reconciliation deadline. Not every shared delivery
mutation gains a new immediate signal.
- Notifications use the existing process-local database ownership
contract. Independent SQL writers and other replicas need their own
supported integration.
- Provider markers, publication leases, and saved actions preserve
recovery after uncertainty. This change does not expand Cloud alarm
coverage or prove deployed host/database suspension.
- Each remaining sleep slice needs its own review and CI checks before
merge.

## Model Used

OpenAI Codex (GPT-6), with reasoning and code execution. The exact
serving model ID and context-window size were not exposed.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] 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-10-28 17:08:27 -05:00
DottaandPaperclip f8226b0515 fix(server): wake GitHub terminal responses from committed changes (#17661)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/210/changes/paperclip/210
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip coordinates agent work and presents results in chat.
> - GitHub acknowledgements already persist the response action and
provider receipt.
> - A terminal run can still owe a final response after acknowledgement.
> - Periodic maintenance searches those rows even when no relevant state
changed.
> - Committed run, issue, presentation, lease and publication changes
identify when recovery can advance.
> - The owner should recover from those events and real deadlines, then
become quiet.

## Linked Issues or Issue Description

Refs #17656, which is merged. This existing terminal-response slice
targets master.

**Problem:** A saved GitHub response can remain nonfinal while its run,
native presentation, publication or source is unresolved. Removing
maintenance without covering those producers loses recovery. Polling
settled history keeps the tenant active.

**Expected behavior:** Committed supported changes wake the terminal
owner. It reconstructs existing actions, preserves provider authority
and pending publication ownership, waits at saved deadlines where
needed, and becomes quiet after settlement.

## What Changed

- Register terminal GitHub response work with the shared scoped deadline
coordinator, using existing action/delivery/publication/run rows.
- Notify response availability from supported run milestones, native
identity, recovery resolution, issue updates and tree/workspace
restoration writes. Preserve outer transaction commit/rollback.
- Keep GitHub response interpretation in its platform owner. Use the
bounded run projection for both direct authorization and scheduling,
including native presentation guards and deliberate passive outcomes.
- Retain the existing publication lease, markers, source/principal
checks and final receipt precedence. A publication owner or uncertain
outcome keeps its existing authority; the worker does not replay it.
- Remove only recurring terminal-response recovery, preserving the
manual path and neighbouring duties. Add no table or scheduler service.
- Regenerate the original sparse terminal-work index as
`0401_yummy_ultimates.sql`, concurrently and idempotently through the
existing top-level migration runner. Preserve all prior SQL/journal
entries and the five newest snapshots.

## Verification

Published head: `88a209e28b969b5229e9a621aeddfd3cbae9b0cd`, integrated
with landed #17656 (`ba5bba86dcdde32b14d4d7dec1b51898e5f6f22d`) and
master `52b86c2032a189b0ea259c5b0cb7158b07ef788c`.

- **74 distinct current cases pass:** 17 terminal-response
lifecycle/producer cases (1,721 other chat cases skipped), all six
queued-comment consumption regressions for the new upstream query
optimization, all 30 heartbeat completion cases, all eight real/unit
issue-tree control cases and all 13 startup cases. Database build,
server typecheck/build, module boundaries and four fresh migrations
through 0401 pass.
- The earlier **304-case** prepared-parent matrix passes at
`aa72f32641b2e2c680342cd49477272349aca9db`: all 253 GitHub workflow
cases, 30 completion cases, eight issue-tree cases and 13 startup cases.
It retains that revision scope. Repeated cases are not added to the
current 74.
- The terminal matrix covers finalized-history quiet, deleted Board
sources, pending presentation/passive outcomes, outer rollback/commit,
paused/new runs, restart/drain/standby, committed native identity, lease
waits, full-page unrelated history, uncertain publication ownership and
tree/workspace/exhausted-recovery producers.
- A populated 0400 database upgrades to 0401 with all 399 prior
migration receipts identical, exactly one added, and none added on
replay. The terminal index is valid/ready on fresh and upgraded
databases. Its SQL matches the original draft after whitespace
normalization; generation keeps snapshots 0397–0401.
- Normal integration `3c8339a541bf68bc9957b9d5a8df80d3a7c3452d`
preserves the complete 24-path owned binary patch and all five new
master paths. The landed parent tree also equals the previously
published parent tree byte for byte. Both normal merge parents and the
exact composition tree are checked. No force push or rebase occurs.
- [The owner
audit](https://github.com/paperclipai/paperclip/blob/88a209e28b969b5229e9a621aeddfd3cbae9b0cd/doc/plans/2026-10-25-github-terminal-response-sleep-audit.md#acceptance-on-the-landed-github-parent-and-current-master)
preserves the original producer, quietness, failure-isolation,
skipped-suite and presentation-wait results with their scopes. Current
passes do not erase earlier failures or turn skips into passes.
- The audit-only follow-up leaves all owned source/test/migration hashes
unchanged. **Fresh exact-head CI and Greptile 5/5 with no actionable
findings remain required.** No full local repository suite, live GitHub
tenant or deployed sleep result is claimed.

## Risks

- Process-local notifications cover supported application writers and
shared pools. Independent SQL writers and other replicas gain no new
wake guarantee.
- Native terminal status alone does not authorize fallback publication.
Pending presentation and existing publication ownership remain separate
obligations.
- Stop can leave an in-flight provider request settling; admission
fences stop a subsequent request. Unknown outcomes retain their existing
recovery rules.
- Index creation can take time on large histories. Concurrent/idempotent
migration and existing replay recovery remain in charge.
- Worker quiet does not establish host/database suspension. Cloud alarm
coverage and sleep admission remain unchanged.

## Model Used

OpenAI Codex, using reasoning, repository inspection, code execution and
real PostgreSQL tests. The exact model identifier and context-window
size are not exposed in this session.

## 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-10-28 16:51:57 -05:00
DottaandPaperclip f8484a9f8d fix(native): deliver selected skills to remote Codex homes (#18080)
## Thinking Path

> - Paperclip coordinates company agents and preserves their assigned
instructions and approval rules.
> - Native runs pin an immutable skill inventory for each execution.
> - Built-in remote Codex launches prepare that inventory on the
controller, but transfer only authentication, configuration, and the
separate context assets.
> - Codex needs the selected skills under its isolated home. An explicit
skill path does not load a skill outside its registered discovery roots.
> - This pull request transfers the sealed selected inventory to the
path already used by explicit skill inputs.
> - Each launch replaces stale assignments inside the authorized
workspace while preserving provider history.

## Linked Issues or Issue Description

Refs #18025. The corrected first-task instructions exist in the selected
bundle, but remote Codex must receive those bytes before it can follow
them. The legacy skill resolver work in #16646 and #9323 uses different
paths and does not repair native remote launch staging.

**What happened?**

A fresh remote native Codex run could not read its assigned first-task
skill. It produced an approval question instead of the required
confirmation. The Product E2E journey correctly rejected that question
before child creation.

**Expected behavior**

Codex receives the selected immutable skill at the same provider-local
discovery path used by explicit skill input. Removed or unassigned
skills do not remain available after a new launch.

**Steps to reproduce**

1. Prepare an isolated Codex home with one assigned skill.
2. Run the built-in remote launch staging path against a fresh remote
filesystem.
3. Resolve an explicit invocation of that skill. Before the repair, its
provider-local file is missing.

## What Changed

- Transfer only the prepared selected skill inventory into the isolated
remote Codex home before other launch writes.
- Reject writable files, symlinks, missing entries, and extra unassigned
packages in the controller projection.
- Validate each provider-home path component below the authorized
workspace. Reject redirected retained paths before deleting stale
skills.
- Create the private discovery root before native sandbox transfers,
which omit the source-root metadata and can ignore the requested
directory mode.
- Replace stale or empty inventories without changing provider
conversation history, preconfigured homes, other providers, or
plugin-provided launch preparation.
- Exercise the real home materializer and turn resolver through the
existing test-only Runner surface. Document the remote discovery
contract.
- Synchronize an existing Telegram attachment-failure test with the
durable provider-effect commit, preserving its required final states.
This CI repair is a separate test-only commit.

## Verification

- The new production-staging regression failed before the repair because
the resolved skill file was absent.
- All 23 focused staging checks pass. They cover delivery, file modes,
empty/revoked inventories, history retention, extra packages, writable
files, source symlinks, target symlinks, redirected ancestors on
sandbox/SSH, and an authorized workspace alias. The filesystem fixture
packs and extracts actual tar bytes without applying the requested root
mode; it preserves exact projected-file digests and executable bits.
- The unchanged materializer and prepared-launch contracts passed 26
tests. Eight selected native caller checks passed; other cases in that
filtered run were not selected.
- Independent probes used official Codex 0.160.0, the real materializer,
production staging, the real resolver, and a local model endpoint. The
original staging supplied no skill message. The final staging supplied
the complete selected skill body with its exact SHA-256. A final probe
also ran production Daytona `performSyncIn`, backing only its SDK
exec/upload/chmod edge with the local filesystem under umask `022`: the
pre-review source reproduced root `0755`, and the final source retained
root `0700`, package `0555`, file `0444`, and the exact selected digest.
All model requests returned local 403; there were no upstream requests
or credentials.
- Full local `pnpm -r typecheck` and `pnpm build` passed on verification
commit `e7d4e7a9`, based on `60b8089a`. The full local `pnpm test:run`
on that frozen tree was not completed: later embedded PostgreSQL startup
failed because the host could not allocate semaphore sets (`semget`,
SEMMNI/SEMMNS), and the owned attempt was stopped with its log
preserved. Its earlier four caller-fixture failures and one
workspace-conflict failure are recorded separately below; the later
resource error is not an explanation for them. Delivery commit
`567d838d` replayed the initial six-file patch onto `ee67d2ec`;
production was last changed in `23456f51`, followed by test-only commits
`002fa4a7` and `6e8fa595`. All 24 staging checks, all 26
materializer/prepared-launch checks, and the complete native executor
file (968 tests, zero skipped) pass locally. Server typecheck also
passed after these test edits. The complete CI matrix passed on
`002fa4a7`; current-head CI is tracked separately.
- Initial-head CI exposed four caller fixtures that manually wrote
auth/config without preparing the skills inventory. The same four
failures reproduced locally. Those fixtures now use the real home
preparer for their existing empty inventory and assert its transfer; all
34 retained/replacement scenarios and the complete 966-test caller file
pass. A sandboxed full-file attempt could not bind local PostgreSQL
(`EPERM`); it was stopped with its log preserved, then the identical
command passed with local fixture access. Initial-head CI also recorded
timeouts in workspace recovery, approval-queue backoff, and heartbeat
attribution. Their three complete files pass unchanged locally (102
tests); the next CI head also passed those cases. The original slowdown
remains unexplained. The consequent approval cleanup foreign-key failure
is a timeout teardown race already recorded in the owning worker
documentation.
- The frozen full local run also observed an existing workspace-conflict
test fail. The test and owning workspace code are unchanged between the
verification and delivery trees, and the isolated delivery case passes.
The original failure remains unresolved: stopping the later
resource-blocked run prevented the final assertion detail from being
emitted. That isolated pass does not replace the earlier result.
- CI on `23456f51` caught a Telegram test reading
`provider_effect=processing` after observing the provider mock call.
Production commits `processed` later, so the test now waits for the
unchanged complete durable-state assertion. All 18 selected Telegram
attachment/media cases pass (the other 1,670 cases were not selected).
The same CI attempt also recorded an E2E runner shutdown followed by
cancellation, without a failed Playwright assertion; the necessary new
test-only head reruns the matrix. Earlier failures remain preserved and
are not reported as passes.
- Review requested an executor-level preconfigured-home negative test.
Retained and replacement workspace cases now drive the actual launcher,
assert successful context staging, and exclude the isolated home's
skills/auth/config transfers. A counterfactual that removes only the
executor exclusion makes both tests fail; the exact production bytes
were restored before the complete 968-test pass. Flat and nested
selected package delivery is also covered. Optional arbitrary
remote-stderr expansion is deferred; the repair keeps the existing
closed error code and report surface.
- Final head `6e8fa595` passes the complete CI matrix, including
typecheck, build, Runner, browser, and aggregate gates. Two
first-attempt jobs were interrupted by runner shutdown/lost
communication; one unchanged-head rerun of those jobs and their
aggregates passed. The underlying host interruption cause remains
unknown. Both current-head automated reviews are 5/5 with the
implemented finding resolved.
- The original checked-in lockfile fails a fresh frozen install on the
baseline. The repository's maintained resolution-then-frozen sequence
passes. No lockfile change is included.
- Independent source review found and then verified the
retained-ancestor guard. This PR does not claim that the full live Cloud
onboarding campaign has passed. It changes no journey assertion or
approval gate.

## Risks

Launch preparation adds an asynchronous inventory walk, one bounded
remote cleanup command, and one transfer of the selected skill tree.
Those costs grow with selected files and bytes and occur only at
provider launch. A failed validation, cleanup, or transfer prevents
launch. Remote Node is already required by the shared SSH/sandbox
launcher. The selected packages remain read-only; the private discovery
root retains Codex's normal writable mode. No database, API,
credential-routing, or deployment change is included.

## Model Used

OpenAI Codex based on GPT-6, with reasoning, source inspection, tool
use, and code execution. The host does not expose the exact serving
model ID or 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-10-28 16:37:13 -05:00
DottaandPaperclip a30194e008 perf: avoid company scans in task privacy ancestry (#18024)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Task reads use one shared privacy predicate for detail, list, badge,
and derived access.
> - Its recursive parent join can scan all tasks for each frontier,
including tasks with no parent.
> - A 1,200-task local reproduction inspects 1,440,000 recursive task
rows without finding any parent.
> - Each task has at most one same-company parent, so the query can
probe that parent directly.
> - This pull request exposes that single-parent contract to the planner
and keeps the existing access rules.
> - The result removes repeated scans and avoids JIT in the measured
large callers.

## Linked Issues or Issue Description

Refs #14718 and #17973. I searched public issues and open/closed PRs for
privacy ancestry and privacy performance work. No competing open fix was
found.

**What happened?**

Task privacy checks repeat company task scans and private-project checks
during list and unread badge reads. The recursive join may do this work
even when every parent is NULL.

**Expected behavior**

Read each actual same-company parent through the existing unique task
index. Preserve current grants, project membership, user intersections,
cycle termination, and visibility before pagination.

**Steps to reproduce**

Run `authorization-privacy-query.test.ts` against the pre-fix query. The
semantic ID check passes. Its plan-work assertion fails at 1,440,000
rows against a 3,600-row bound. The same test passes after this change.

**Paperclip version or commit**

Measured baseline `8279c990080b15abdcd9981f5793290fab37f9ad`. The branch
was replayed onto `71b448b9cb841e6fa18fe883585430c5081245da`. Both have
identical pre-fix authorization, issue-service and participation-helper
sources. Treatment source SHA-256 is
`a99faf974070a35f2786c92407e023c668c1f7b99b6604f6281c89bce089b1a8`.

**Deployment mode**

Source checkout, isolated local PostgreSQL 17.11 on ARM64 Linux. No
hosted write, migration, merge, or deployment was performed.

## What Changed

- Skip NULL privacy parents. Use a lateral lookup for the exact
same-company parent through existing indexes.
- Keep `UNION` cycle detection and every existing principal, grant,
private-project and membership expression. Both `LIMIT 1` clauses are
redundant: one anchor and one unique parent give at most one row per
recursive generation. The query still follows a complete deep chain.
- Cover open ancestors inside private projects, including current
project visibility and ancestor grant revocation. Place the benchmark
under `server/scripts/` with ordinary package imports.
- Add real PostgreSQL regressions and a pinned-baseline benchmark for
complete badge/list calls. Keep all 36 measured cells, ranges, neutral
paths, failed experiments, and the single-chain proof in [the query
proof](https://github.com/paperclipai/paperclip/blob/codex/perf-task-privacy-ancestry/doc/plans/2026-10-28-task-privacy-query.md).

## Verification

Local warm full-service medians, with two warmups and five alternating
measured calls per arm:

| Scoped caller | Baseline | Treatment | Ratio |
| --- | --- | --- | --- |
| Dense badge, default JIT | 645.33 ms | 77.11 ms | 8.37x |
| Dense list, default JIT | 214.77 ms | 29.87 ms | 7.19x |
| Sparse list, default JIT | 117.92 ms | 13.22 ms | 8.92x |
| Dense list, JIT off | 55.69 ms | 30.62 ms | 1.82x |
| Sparse list, JIT off | 16.61 ms | 15.12 ms | 1.10x |

All 36 cases match every positional SQL field and row order across all
captured queries. Complete final badge IDs and list objects also match.
Both badge phases and ordinary list enrichment remain in the measured
caller. Dense/sparse fixtures have 1,200 tasks, 300,000 activity rows
and 24,000 comments, with wide random content. Small, unrestricted,
private fan-out, 64-level ancestry, cycle, and JIT on/off controls are
included.

The dense ranking plan reduces recursive task and project work from
720,000 visits each to zero. Its cost estimate falls from 103,000.61 to
20,458.73 and JIT disappears. Separate EXPLAIN execution falls from
524.04 to 34.34 ms. The dense JIT-off main list statement falls from
29.52 to 1.89 ms; remaining service work limits the full-call gain.

**Retained failed goals:** `--assert-performance --max-dense-ms=60`
exited 1. The original 60 ms dense badge goal remains unmet at 77.11 ms.
Four full-service cases also miss the exploratory blanket 2x goal. These
criteria remain in the harness and are not counted as green. The
delivered optimization is proved by the deterministic query-work
red/green test and complete result equality.

Small and unrestricted controls meet their original 25% or 2 ms
allowance. All 12 unrestricted cells use byte-identical SQL and
parameters in both arms; their overlapping timing variation is
neutral/inconclusive. Modest slower scoped controls are retained,
including small JIT-off list 16.18→18.78 ms and cycle JIT-off list
14.78→16.29 ms. There is no claim that all paths improve.

- Final head `328078f494d6ec585936fb75a9410ad39eefd099`: full CI passes
(55 success, 1 neutral, 2 skipped); fresh Greptile is 5/5 with zero
unresolved review threads. The optional Paperclip Review ended neutral
because its worker stopped; its earlier two specific recommendations are
both addressed below.
- Final-runtime focused Docker PostgreSQL run: **44/44 tests passed**
across ancestry work, production privacy, unread badge, and creation
visibility suites. Includes fresh revocation, private projects, grant
direction, three-principal agent intersections, cycles, deep
inheritance, foreign-company parents, and access before LIMIT.
- `pnpm -r typecheck` and `pnpm build`: passed before replay. The real
PostgreSQL ancestry suite passed after replay (5/5 tests, 17.44
seconds). The added private-project ancestor case then passed in the
six-test suite (43.04 seconds). Database and server typechecks and
builds passed after replay; review follow-ups change tests and benchmark
location only. A small relocated-command smoke preserves byte-identical
generated SQL and complete result comparisons.
- `pnpm test:run`: attempted, then stopped with exit 143 after 16 native
database bootstrap failures in 940 executor cases. An independent empty
native `initdb` fails with `semget` semaphore exhaustion before
application SQL. This local full suite is incomplete, not passed. All 16
affected cases then passed on real PostgreSQL 17 Docker in 155.04
seconds (924 other cases were intentionally filtered out).
- An earlier focused command passed 35 tests but skipped eight after a
20-second database setup timeout. The later 44/44 pass resolves that
coverage gap; the failed command is retained.
- The first CI e2e shard attempt completed functional split-handoff
assertions, then cleanup run cancellation hit a one-second row-lock
timeout. The unchanged local-trusted cleanup path does not use the
changed privacy predicate. A single same-head job retry passed. The
original failure is retained.
- The first lateral-only draft removed scans but raised estimated
ancestry rows from 11 to 101 and retained JIT. The per-generation fence
fixes that estimate. No failed attempt was discarded.

Reproduce the measured caller pair:

```sh
pnpm --filter @paperclipai/server exec tsx scripts/benchmark-task-privacy.ts \
  --baseline-ref=71b448b9cb841e6fa18fe883585430c5081245da \
  --evidence-dir=/tmp/task-privacy-proof
```

The full matrix takes about 107 seconds locally, including 8 seconds of
setup. Capture and EXPLAIN run outside ordinary timing samples. Only the
old authorization module changes between arms; caller source and all
relevant query helpers remain constant. Hosted request latency remains
unverified.

## Risks

- The per-generation bound depends on the single anchor and unique
scalar parent contract. A future multi-parent model must revise this
query and its deep/cycle tests.
- Tiny tables can still use a cheap sequential lookup for a real parent.
The guard prevents broad scans for absent parents; it does not force
index use everywhere.
- The 60 ms badge goal and blanket full-service 2x goal remain failed.
Unchanged enrichment, application work and local variation remain
visible in the measurements.
- This changes shared read authorization SQL. No permissions are cached,
no authorization moves after LIMIT, and no schema or startup change is
included.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning, local code execution and
real PostgreSQL profiling. The exact model ID and context-window size
are not exposed by this session. No more specific ID or window size is
claimed.

## 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-10-28 16:11:01 -05:00
DottaandPaperclip 52b86c2032 perf: avoid repeated run-context reads for queued comments (#18021)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Execution recovery shows how many saved user messages remain
unconsumed.
> - This read must preserve the rule that consumed input cannot be
replayed.
> - The current query reads a large run context again for each saved
comment.
> - PostgreSQL already scans the run relation once, but repeats the JSON
reads.
> - This pull request projects the two wake-comment fields before the
repeated comparison.
> - The query uses less database work and returns the same blocker
state.

## Linked Issues or Issue Description

**What happened?**

The eight-comment consumption query averaged 131.14 ms across 99 calls
in a recent hosted sample. Each call returned all eight comments. The
query used about 8,002 shared buffer hits per call. It used no JIT
compilation. The local plan showed repeated TOAST reads in the
anti-join, despite a single run scan.

**Expected behavior**

Count saved, undeleted user comments without reading each large context
again for each comment. Keep exact JSON issue bindings, JSON
containment, company scope, and cancellation rules. Consumed input must
remain excluded.

**Steps to reproduce**

Run the committed benchmark against disposable PostgreSQL with
repository migrations. Pass the pinned baseline below. Seed forty task
runs with 72 KiB random contexts, eight unconsumed comments, and 1,400
unrelated runs. Compare complete SQL rows and the full execution blocker
result.

**Paperclip version or commit**

Pre-fix baseline: `8279c990080b15abdcd9981f5793290fab37f9ad`. This
branch is based on current master. The intervening master changes do not
change the measured service or its SQL helpers.

**Deployment mode**

The report came from hosted PostgreSQL 17.11. The local proof uses
disposable PostgreSQL 17.11 on ARM64 Linux.

Related correctness work: #16528, #16664, and #18012. This query change
does not replace those fixes or resolve the replay report in #17782. The
duplicate search found no open performance fix for this query.

## What Changed

- Select only `wakeCommentId` as text and `wakeCommentIds` as JSON
before the anti-join.
- Use `OFFSET 0` as a PostgreSQL projection boundary. Keep lazy
first-match behavior and the existing company/JSON-issue index.
- Preserve the original singular text comparison and JSON containment
expression. Keep cancelled-before-start, deleted-comment, user-author,
and company filters unchanged.
- Add real PostgreSQL regression tests and a reproducible paired
benchmark. Compare every positional SQL column and the entire service
result.
- Record the rejected scan-count hypothesis, slower controls, full
samples, and acceptance limits in the [proof
document](doc/plans/2026-10-28-queued-comment-consumption-query.md).

## Verification

- Red before the source change: the eight-comment/300-run fixture used
35,711 shared buffer accesses and failed the selected 10,600-work
budget. Five semantic cases passed. The earlier single-scan guard passed
the original code and is not counted as red.
- Green: six new real PostgreSQL cases and 85 existing queued-comment
route cases pass together: **91/91**. Coverage includes
cancelled-before-start, started cancellation, no replay, conflicting
native IDs, noncanonical JSON IDs, cross-company data, deleted/agent
comments, and scalar/object/nested-array JSON.
- `pnpm -r typecheck` and `pnpm build`: passed. `pnpm test:run` was
attempted and stopped after 16 native PostgreSQL startup failures in an
unchanged executor suite; 924 other cases in that file passed. The full
local attempt is incomplete and is not counted as a pass. Those same 16
cases then passed with Docker PostgreSQL 17.11. Full Linux CI passed on
the final head.
- A standalone empty native `initdb` fails with `semget: No space left
on device` from the macOS semaphore limit. Native PostgreSQL startup is
unsupported on this host. Its focused attempt skipped six tests. The
91-case run used a private Docker PostgreSQL constructor substitute.
Repository database creation, migrations, clients, and cleanup were
retained. No test infrastructure change is committed.
- Final head `d2921d9220e22624f85f7057a577a6e2e98dc097`: all 58 check
contexts are terminal and clean (55 success, two expected skips, one
neutral). The full [PR
workflow](https://github.com/paperclipai/paperclip/actions/runs/40699607944)
passed. Greptile reviewed this exact head at 5/5. Paperclip Review
originally requested the deep first-consumed control; it now passes and
that thread is resolved. Its latest automated review attempt stopped
before completion and reported neutral, so no fresh Paperclip 5/5 is
claimed.

Two warmups and five alternating samples per arm, with capture, equality
checks, and plans outside the timers:

| Local fixture | SQL median before → after | Full blocker median before
→ after | Shared buffer accesses |
| --- | ---: | ---: | ---: |
| Representative: 40 runs, 72 KiB, 8 unconsumed comments | **11.47 →
3.82 ms (3.00×)** | **29.48 → 18.85 ms** | **7,686 → 966** |
| Same fixture, JIT disabled | 10.96 → 3.63 ms | 32.18 → 24.75 ms |
7,686 → 966 |
| 11 runs, 72 KiB | 8.35 → 5.05 ms | 37.60 → 35.13 ms | 2,116 → 268 |
| 8 comments consumed by the first wide run | 1.60 → 1.28 ms | 13.90 →
16.59 ms | 196 → 28 |
| 1,400-run stress, above observed task depth | 172.82 → 44.27 ms |
212.60 → 73.94 ms | 175,089 → 37,889 |
| 1,400 runs, first wide run consumes all 8 | 1.54 → 1.99 ms | 19.00 →
18.23 ms | 122 → 24 |

Representative SQL ranges: 10.36–12.33 ms before and 2.83–4.30 ms after.
Service ranges: 27.34–33.22 ms before and 18.58–21.81 ms after. All 24
final fixture/JIT cells return identical complete rows and service
objects. The follow-up widens the consuming run to the same payload size
as history and supersedes the initial thin-row consuming controls. All
final-matrix benchmark budgets pass. The deterministic buffer-work
budget was selected before the production change. The timing criteria
were selected after the initial exploratory projection trial and before
the final quiet matrices.

Small and empty-history service medians rose by 5.03 ms and 3.90 ms in
the JIT-on matrix. Small-case ranges overlap: 18.49–36.48 ms before and
17.29–41.89 ms after. These differences do not establish a causal
service regression. The JIT-off small and empty-history controls
improved slightly. The unchanged no-comment path runs no changed SQL.
The one-comment control is neutral. The widened immediately consumed
service median rose 2.69 ms (19 percent), inside the selected 25 percent
or 2 ms service budget. Its ranges overlap: 13.34–27.72 ms before and
13.18–18.10 ms after. This accepts a possible bounded small-path cost;
it does not claim every path gets faster. All controls and full
distributions remain in the proof.

The reviewer-requested deep first-consumed plan reads exactly **one**
underlying run row in each arm. Both materializations return one row,
revisited eight times. The remaining history is not read eagerly. JIT-on
SQL ranges overlap at 0.86–2.79 ms before and 0.77–4.38 ms after; this
proves early exit rather than a latency gain. With JIT disabled, SQL is
1.08 → 1.07 ms and service time is 11.36 → 11.53 ms, with the same 122 →
24 buffer accesses. Production source is unchanged by this proof update.

Reproduce:

```sh
QUEUED_COMMENT_BENCHMARK_DATABASE_URL="$DISPOSABLE_QUEUED_COMMENT_DATABASE_URL" \
  pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-queued-comment-consumption.ts \
  --baseline-ref=8279c990080b15abdcd9981f5793290fab37f9ad --require-budget
```

Use an isolated `queued_comments_` database. Repeat with `--jit-off`.
Without the URL, the script creates disposable embedded PostgreSQL. The
benchmark rejects changed runtime helpers and records source hashes,
settings, SQL/parameters, complete results, samples, and plans.

## Risks

- PostgreSQL planner changes can alter the materialization strategy. The
regression guard checks repeated context work on the supplied fixture.
- Small local service medians are noisy. Their ranges and slower medians
remain visible. A faster local query does not establish the same hosted
request saving.
- JSON authority and no-replay rules are sensitive. The query keeps the
original predicates and has real database tests for non-array and
conflicting-ID cases.
- There is no migration, index, cache, history cutoff, extra round trip,
deployment, or hosted write.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning and tool use. The exact model
ID and context window are not exposed by this session. They are not
inferred from a model alias.

## 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-10-28 16:10:43 -05:00
DottaandPaperclip ba5bba86dc fix(server): wake GitHub acknowledgements from committed changes (#17656)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/206/changes/paperclip/206
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip coordinates agent work and presents its progress in chat.
> - GitHub deliveries save acknowledgement actions and provider
receipts.
> - Periodic maintenance currently searches for unfinished
acknowledgements even when idle.
> - Committed delivery, lease, response and presentation changes
identify when work can advance.
> - The existing owner should wake on those changes and recover only at
saved deadlines.
> - Completed history should become quiet without losing unfinished
provider effects.

## Linked Issues or Issue Description

Refs #17653, which is merged. This existing GitHub acknowledgement slice
targets master.

**Problem:** A saved GitHub acknowledgement can wait for a publication
lease, fast-response result or native presentation decision. Polling
empty or unchanged work keeps the tenant active. Removing maintenance
without covering these producers can strand the acknowledgement.

**Expected behavior:** Committed changes wake the scoped owner. It
reconstructs existing actions on startup, retries at saved deadlines,
parks unchanged presentation waits and becomes quiet when settled.

## What Changed

- Register GitHub acknowledgement work with the shared scoped deadline
coordinator. Reuse existing action, delivery, lease and fast-response
rows.
- Add transaction-aware response-availability notifications at supported
writes. Keep GitHub protocol details in its platform owner and shared
notifications limited to IDs.
- Share the bounded latest-request/run projection between scheduling and
direct response authorization. An absent native presentation decision
parks the action until its real writer commits.
- Retain publication leases, source/principal authority, version
fencing, response markers and final receipt precedence. Check admission
before each new provider request; let in-flight work settle. Stop does
not consume the provider retry budget.
- Remove only recurring acknowledgement recovery and keep its manual
path. Add no work table or scheduler service.
- Regenerate the three original indexes as
`0400_absent_phantom_reporter.sql`: pending acknowledgement IDs,
fast-response delivery lookup and publication comment/destination
lookup. Each uses concurrent/idempotent creation and the existing
top-level migration runner. Preserve all landed SQL/journal entries and
the five newest snapshots.

## Verification

Published head: `09ca00b9f029838434ec042cda691345d67b493e`, on landed
continuation parent `063cfd43813cabf18417605fb9eefb9aacf95c8d`.

- **87 distinct current cases pass:** 18 real PostgreSQL acknowledgement
lifecycle/presentation cases, all 26 fast-response service cases, all 30
heartbeat completion cases and all 13 startup cases. Database build,
server typechecking/build, module boundaries and three fresh migrations
through 0400 pass. The current Runner bundle rebuild also passes after
upstream provider-event changes.
- The lifecycle matrix covers empty/history quiet, lease release,
restart, drain/standby, fast-response failure/expiry/publication/unknown
outcome, streaming quarantine, outer rollback/commit, saved provider
retry, stop between requests and receipt state. The real presentation
writer proves quiet while pending, rollback, committed reactivation and
final quiet.
- The earlier **305-case** matrix (236 full GitHub workflow cases, 26
fast-response service cases, 30 completion cases and 13 startup cases)
passes at `337f272853d4f8a51b5b9300900a46eb4e13f698`. It retains its
prepared-parent scope. Repeated cases are not added to current 87.
- A populated 0399 database upgrades to 0400 with all 398 prior
migration receipts unchanged, one new receipt and no additional receipt
on replay. All three indexes are valid/ready on fresh and upgraded
databases. Their SQL definitions match the original draft after
whitespace normalization; migration history and retained snapshot bytes
are preserved.
- Normal integration `9b3607e159153e00ccdfe538d52b591bd38d6499`
preserves the full 28-path owned binary patch and all 20 unrelated
master paths, including native retry, provider-event and evaluation
workflow changes. Both normal merge parents and the exact tree are
checked. No force push or rebase occurs.
- [The owner
audit](https://github.com/paperclipai/paperclip/blob/09ca00b9f029838434ec042cda691345d67b493e/doc/plans/2026-10-25-github-chat-maintenance-sleep-audit.md#acceptance-on-the-actual-landed-continuation-parent)
retains the original missing-notification, JSON precedence, receipt
lifecycle, external-database fixture and migration-registry failures.
Earlier 69/228/broad counts keep their original scope. Skips and failed
revisions are not relabelled as current passes.
- The final audit-only edit leaves all owned source/test/migration
hashes unchanged. **Fresh exact-head CI and Greptile 5/5 with no
actionable findings remain required.** No full local repository, live
GitHub tenant or deployed sleep result is claimed.

## Risks

- Process-local transaction hints cover supported application writers
and shared pools. Independent SQL writers and other replicas do not gain
a new wake guarantee.
- Provider effects remain guarded by the existing publication lease and
current source/principal authority. Unknown outcomes retain their
existing recovery semantics.
- Presentation waits depend on their supported milestone/transaction
producers. A missing producer can defer recovery until another supported
change or restart.
- Index creation can take time on large histories and runs concurrently
outside a transaction. Existing migration recovery handles replay; prior
SQL is unchanged.
- Worker quiet is distinct from host/database suspension. Cloud wake
coverage and sleep admission remain unchanged; later maintenance duties
are separate slices.

## Model Used

OpenAI Codex, using reasoning, repository inspection, code execution and
real PostgreSQL tests. The exact model identifier and context-window
size are not exposed in this session.

## 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-10-28 16:06:42 -05:00
DottaandPaperclip 063cfd4381 fix(server): wake interaction continuations from committed responses (#17653)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/204/changes/paperclip/204
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip coordinates agent work and human approvals.
> - Human decisions already persist the continuation action that resumes
an agent.
> - A response can commit before its callback or publication finishes.
> - Periodic maintenance repeatedly discovers those rows, including when
idle.
> - Committed writes should wake the existing owner; saved retries and
claims supply real deadlines.
> - Startup reconstructs durable work, and settled history becomes
quiet.

## Linked Issues or Issue Description

Refs #17651, which is merged. This existing continuation slice targets
master and removes its duty from periodic chat maintenance.

**Problem:** A saved `interaction_wakeup` action can survive a committed
human response whose callback crashes. Without producer coverage,
removing maintenance strands the continuation. Repeated empty
maintenance also keeps the database active.

**Expected behavior:** The outer transaction's settlement wakes the
continuation owner. It handles ready conversation publications,
dispatches under existing authority, preserves interrupted/retry work,
and becomes quiet after settlement.

## What Changed

- Register continuation recovery with the shared scoped deadline
coordinator. Reconstruct existing issued/processing actions and retain
the existing retry and stale-claim deadlines.
- Notify from both enqueue producers and owner-local claim/settlement
writes. Preserve outer commit/rollback and avoid moving provider or
heartbeat calls into database transactions.
- Give the existing publication queue an optional
company/endpoint/conversation scope. The continuation owner gives ready
cards in that conversation a bounded delivery opportunity before
claiming the action; FIFO, capacity, ambiguity and provider authority
remain with the queue.
- Carry admission/cancellation through publication preparation and check
before every new send. Join in-flight requests and retain pending
actions/publications through drain, standby, shutdown and resume.
- Remove only recurring continuation recovery; keep the manual API. Add
no table. A concurrent partial index on existing pending continuation
actions and matching company/id keyset paging prevent retained history
from being scanned. Parent #17651's indexed confirmation discovery and
current master are retained.

## Verification

Published head: `a1d16f84b3fae361d5d648670a5964486370c3a3`, on actual
landed terminal-confirmation parent
`ee67d2ece9bda157dfad9bdf25175b1d004ed341`.

- **75 distinct current cases pass:** 32 selected real PostgreSQL chat
cases (14 continuation lifecycle/producer/stop cases, one new
continuation query-cost case, and 17 parent confirmation/query-cost
cases; 1,671 skipped), and all 43 cases in complete
interaction-publication and app/startup suites. Database build, server
typecheck/build, module boundaries and fresh migrations through 0399
pass. The original landed-parent matrix passed 74 cases before the
additional query-cost repair; those are not added again.
- The new real-SQL regression seeds 20,000 completed/unrelated actions
and one pending processing claim. Before repair it examines 20,345 rows
and hits 20,421 buffers. The final startup and company-scoped queries
must examine at most two action rows and fewer than 20 action buffers;
empty scoped recovery must also stay below 20 buffers. Planner settings
are unchanged. Migration `0399_ambitious_onslaught.sql` is
concurrent/idempotent and uses the existing top-level migration runner;
prior SQL/journal entries and the five newest snapshots are preserved.
- The matrix covers callback recovery, concurrent responses, malformed
prefixes, more than one page, saved retries/stale claims, outer
rollback/commit, deferred/future/paused publication states, restart,
drain and stop before each new provider request. Quiet assertions
inspect real selects/transactions across virtual idle time.
- Normal integration `db5a84c0f8b73a0ce863f4d2fbaee0a115cf044f`
preserves the complete 12-path owned binary patch and all 12 unrelated
current-master paths, including managed Cloud sandbox changes. A
verified semantic base resolves squash-ancestry conflicts; both normal
parents and the exact tree are checked. The subsequent index/keyset
repair is a deliberate additional change, tested separately; the final
patch is not claimed identical to the original 12-file implementation.
No force push or rebase occurs.
- The same 74 pre-index cases passed on the earlier prepared and actual
landed parents. The new query-cost regression failed before its repair,
then passes on the repaired source. Earlier 57-case and broad acceptance
retain their original revision scopes; repeated cases are not added to
the current count. The audit-only follow-up leaves all owned server
source/test hashes unchanged.
- [The owner
audit](https://github.com/paperclipai/paperclip/blob/a1d16f84b3fae361d5d648670a5964486370c3a3/doc/plans/2026-10-25-interaction-continuation-sleep-audit.md#acceptance-on-the-actual-landed-terminal-confirmation-parent)
retains the original missing-signal regression, the skipped standalone
publication suite, and the review's stop-before-send failures with their
corrections. Skips and earlier failing revisions are not relabelled as
current passes.
- **Fresh exact-head CI and Greptile 5/5 without unresolved actionable
findings remain required.** The former remote head's reviews are stale.
No full local repository suite, live provider or deployed sleep result
is claimed.

## Risks

- Process-local transaction hints cover supported application writers
and shared pools. Independent SQL writers and other replicas do not gain
a new wake guarantee.
- The publication queue's existing FIFO, capacity, retry/ambiguity and
authorization contracts still govern effects. In-flight provider
requests can settle after Stop; the fence prevents a subsequent request
from starting.
- Missing a supported producer can defer recovery until another change
or startup. Producer and rollback tests cover this slice's supported
paths.
- Worker quiet is separate from host/database suspension. External alarm
coverage and Cloud sleep gates are unchanged.

## Model Used

OpenAI Codex, using repository inspection, code execution and real
PostgreSQL tests. The exact model identifier and context-window size are
not exposed in this session.

## 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-10-28 15:45:18 -05:00
DottaandPaperclip c74171d620 fix(recovery): retire superseded native workspace retries (#18077)
## Thinking Path

> - Paperclip coordinates agents while retaining their work and
execution authority.
> - A failed native run can schedule an exact-session retry and retain a
sandbox.
> - An explicit task Retry can already have completed successfully on a
successor.
> - Recovery correctly refuses the old run after its task execution lock
changes.
> - It nevertheless leaves that old retry scheduled and its workspace
without a preservation owner.
> - This change retires that proven superseded retry and registers
exact-source preservation together.
> - Existing stop receipts and saved-file verification still control
workspace switching.

## Linked Issues or Issue Description

**What happened?**

A native sandbox run failed before starting a provider turn. An explicit
Retry completed on a linked successor. The original coordinator remained
in `retryable_failure` with an active sandbox lease. Restart recovery
returned `issue_execution_lock_changed`, while the ordinary sweep kept
delaying it. A pending workspace selection then made every new task run
fail during setup.

**Expected behavior**

Stop replaying a failed retry after its linked explicit successor has
completed. Preserve the original files through the existing system
worker. Keep the current task, ownership, pending choice, and unresolved
action outcomes intact.

**Steps to reproduce**

1. Persist a failed, unowned native run with a prepared remote workspace
and `retryable_failure` coordinator.
2. Complete a same-company/task/agent explicit Retry linked to that run.
3. Release the task's old execution lock and schedule a workspace
selection.
4. Run startup or ordinary retry recovery. Observe the old retry remain
scheduled and the selection fail with an unfinished-recovery conflict.

**Paperclip version or commit**

Regression reproduced against `644937c931`. The current repair is based
on refreshed master `60b8089a44`.

**Deployment mode**

Native Runner with remote sandbox workspaces. The reported runtime used
ACPX Claude with per-turn lifecycle. The original provider
session-resume rejection is not independently reproduced or claimed
fixed here; this PR addresses the subsequent stranded recovery.

Related: #17839 records preservation when restart classification becomes
terminal. This change handles the earlier lock-mismatch return and
ordinary retry admission after a completed explicit successor. It uses
the same preservation service and does not require that PR.

## What Changed

- Share a narrow superseded-retry settlement between startup recovery
and the ordinary retry sweep.
- Require a failed source with no coordinator owner or process, its
exact prepared source lease, and a completed linked successor under the
same company, task and agent.
- Atomically retire replay and register preservation. Do not alter task
state or create another provider run.
- Add PostgreSQL lifecycle/safety regressions, a real-file preservation
and workspace-selection regression, and execution/map documentation.

## Verification

- Red: both startup and ordinary admission regressions left the old
coordinator in `retryable_failure` with no preservation obligation.
- Green: the same two cases retire the retry and retain the exact lease
without another run or task mutation.
- The assembled PostgreSQL/filesystem regression passes: workspace
selection remains blocked before preservation, the existing service
saves `saved.txt` and preserves newer local work, then the normal
selection guard applies the pending shared workspace.
- All 90 native retention/resumption cases pass. Three neighboring
startup-recovery cases pass, including the blocked-owner inventory. Full
recursive typecheck and full build pass at runtime head `23ddb213b4`;
final `19d7738ae3` only moves the function comment into execution
documentation. Map, module-boundary and diff checks pass. The duplicate
full local Vitest run was stopped after 20 minutes in its first long
general shard once the complete current-head hosted test gates passed;
no complete local-suite pass is claimed.
- Current-head CI has 53 passing checks and two intended Storybook
skips, including full typecheck, all test shards, build, Runner
verification, browser shards and both aggregate gates. The separate
`commitperclip PR Review` job is still queued on `ubuntu-latest` with no
assigned runner; its outcome remains pending. Greptile reviewed exact
head `19d7738ae3` at 5/5, with zero unresolved threads.
- Live acceptance passes on exact final source `19d7738ae3`: a
disposable Daytona Linux sandbox, the current immutable staging fleet
snapshot, SDK 0.203.0, a Darwin arm64 source host and Node 26.4.0. The
real native workspace preparation/export and provider stop/start paths
preserve an unpredictable report and newer host files. The ordinary
workspace-selection guard stays blocked until preservation commits, then
applies the pending shared workspace.
- The old workload's start count and side-effect marker each remain one.
Recovery creates no new run or native result. The sandbox finishes
stopped and is then deleted by the probe; a final provider read confirms
it is absent.
- A second live acceptance also passes on the original runtime's older
immutable snapshot with the source explicitly archived before recovery.
It verifies cold source reopening, the same report/newer-file checks,
one workload start and side effect, pending workspace application, and
confirmed deletion. Its initial probe attempt used immediate
archive/deletion reads and failed during asynchronous cleanup
observation; bounded provider-state polling fixed the probe without a
product change. The abandoned probe allocation is independently
confirmed absent.
- Scope: database fixtures represent the already-failed run and
completed explicit successor. The old workload is a persistent shell
process with observable file/side-effect markers, not a paid Claude
turn. This qualifies the repaired recovery handoff and real provider
preservation; it does not reproduce the initial ACPX session-resume
rejection.
- The original hosted task has only been inspected read-only. No rollout
or original-task recovery is claimed.

## Risks

- Incorrect successor classification could retire legitimate work.
Matching requires the server-persisted explicit Retry link, same
company/task/agent, later successful committed execution, no current
source execution lock, no recorded process, no coordinator owner, and no
workspace finalization owner.
- Retirement is not a stop receipt. The exact source remains retained,
unknown effects remain unknown, and workspace switching still waits for
the existing worker's stop and file-persistence proof.
- A failed preservation transaction rolls back retirement. No new scan,
retry budget, schema or public API is introduced.

## Model Used

OpenAI GPT-6 through Codex, with reasoning, tool use and code execution.
The host does not expose a more specific model ID or 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 — focused suites and live
acceptance; full-suite status above
- [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 — separate template-review job
still queued as noted above
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups —
exact head `19d7738ae3`
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-28 15:15:19 -05:00
DottaandPaperclip ee67d2ece9 fix(server): wake terminal confirmation recovery from committed changes (#17651)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/202/changes/paperclip/202
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip persists confirmation clicks and interaction decisions
before dispatch completes.
> - A crash after a decision commits can leave a processing confirmation
action.
> - Periodic publication maintenance repeatedly scans those actions even
when idle.
> - Saved decisions and the supported board/admin writers already
identify when settlement can change.
> - This owner reconstructs durable actions, reconciles real changes and
then becomes quiet.

## Linked Issues or Issue Description

This existing terminal-confirmation slice follows merged #17649. It
removes only terminal-confirmation recovery from periodic chat
maintenance while retaining the explicit manual API and existing durable
action/interaction/publication rows.

**Problem:** An accepted response can commit before its dispatch
settles. Removing periodic recovery without covering board decisions,
expiry and ownership changes would strand processing actions. Pending
human decisions must remain recoverable without polling indefinitely.

**Expected behavior:** Committed supported changes wake the scoped
owner. It reconciles terminal responses once, parks unresolved human
decisions, preserves concurrent commits/restart/drain and becomes quiet
when settled.

## What Changed

- Register terminal-confirmation work with the existing delivery
coordinator and scoped lifecycle. Reconstruct processing action IDs,
bound selection pages, preserve concurrent wakes and keep current
authorization in the existing interaction owner.
- Add the existing transaction-aware confirmation notification topic at
real resolution writes and callback settlement. Reuse milestone signals
instead of adding per-caller recovery wrappers.
- Cover ordinary and checkbox confirmations, suggestions and connection
intents through their owning service. Cover board accept/reject,
cancellation/withdrawal, opt-in comment supersession, expiry,
reassignment and already-satisfied connection resolution.
- Preserve task/actor authority, one-use callback tokens and immutable
provider publication semantics. Explicitly fail malformed missing
bindings instead of silently retaining unrecoverable processing actions.
- Remove only this duty from recurring publication maintenance. Add no
table or scheduler infrastructure. A concurrent partial index on
existing action rows prevents recovery discovery from scanning completed
history.

## Verification

Published repair head: `a35e78d076c1b618bc643391b7520fa6952fc996`,
targeting master after normal integration of
`644937c93150c423f12674992c7ea1e8b5dbc98c`. [Detailed acceptance and
preserved
failures](https://github.com/paperclipai/paperclip/blob/a35e78d076c1b618bc643391b7520fa6952fc996/doc/plans/2026-10-25-terminal-confirmation-sleep-audit.md#bound-retained-history-reads--october-28-review-repair).

- **New query-cost regression:** Capture the actual SQL emitted by
startup and company-scoped confirmation discovery. Seed 20,000
completed/unrelated action rows and one pending human decision. Before
the index, the regression fails because recovery examines 20,009 action
rows. After the partial index, startup and scoped discovery must examine
at most two action rows and fewer than 20 table/index buffers; the
no-pending scoped path must also stay below 20 buffers. Planner settings
are unchanged, and returned IDs remain correct.
- Match startup keyset ordering to `(company_id, id)`, the partial index
order. The index alone still let PostgreSQL choose the primary key and
scan 20,206 rows for `ORDER BY id`; the final query fixes this without
forcing a planner setting or adding a second index. Fixed kind/status
predicates stay literal for prepared-plan index eligibility.
- Add the generated `0398_yielding_random.sql` migration, using `CREATE
INDEX CONCURRENTLY IF NOT EXISTS` and the existing top-level migration
runner. Keep the five newest generated snapshots and preserve every
prior SQL/journal entry. No work table is introduced.
- **110 distinct cases pass:** 17 final confirmation
lifecycle/query-cost cases (1,671 skipped), seven real Runner descriptor
variants (295 skipped), and all 86
app/startup/bundled-plugin/plugin-database cases. Server/database
typechecking and builds, migration safety/numbering, module boundaries
and a fresh PostgreSQL migration through 0398 pass. The final test-only
vacuum precondition is followed by another 17-case confirmation pass and
server typecheck. Counts are not added across repeated runs. Normal
integration of master `644937c93150c423f12674992c7ea1e8b5dbc98c`
preserves the complete owned patch and all 18 unrelated master paths.
- Previous landed-parent acceptance: 29 distinct cases (16 confirmation
lifecycle/producer cases with 1,671 skipped, plus all 13 startup cases)
passed on `32e64a7e9ea5b457e54ca7b268be90e1e155b451`; the earlier
80-case matrix remains scoped to
`c1e8542b588a4fa59b62f9829541d3daea4f1ddc`. Counts are not added across
repeated runs.
- Actual producer cases prove parking/quiet, caller-owned outer
transaction rollback, commit-driven automatic settlement, restart/drain
and concurrent commits. Checkbox, suggestion, connection-intent and
Telegram/Slack callback paths retain existing authority and immutable
publication semantics.
- **Fresh exact-head CI and Greptile 5/5 with no unresolved actionable
findings are required.** The preceding head's Runner CI failed its
timeout-attachment durable-suspension case (1 failed/1,955 passed/4
skipped); that failure is retained and not counted as a pass. The new
head must pass this job. No full local repository, live provider or
physical suspension claim is made.

The owner audit retains the earlier missing-board-producer regressions
and their corrections, including the invalid supersession fixture that
assumed a new checkbox expires an older one. Existing behavior was
preserved by using the supported opt-in human-comment path. Prior
scheduler/backoff, route and plugin test failures remain at their
original revisions; no old pass is substituted for current remote gates.

## Risks

- Process-local notifications cover supported application writers and
their shared pools, not independent SQL writers or other replicas.
- Processing actions waiting on a human response are deliberately
parked. Supported interaction resolution/expiry writers must use the
notification boundary; a missing producer delays settlement until
restart.
- Invalid bindings have explicit failure evidence. Source, actor, task
and publication authority remain checked by their existing owners.
- Following continuation/GitHub duties remain separate. Cloud sleep
gates and external alarms are unchanged; local worker quiet does not
establish physical host/database suspension or fleet savings.

## Model Used

OpenAI GPT-6 / Codex, with reasoning, repository inspection, code
execution, and PostgreSQL tests. The exact runtime model identifier and
context-window size are not exposed in this session.

## 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-10-28 15:00:31 -05:00
DottaandPaperclip 60b8089a44 fix(runner): trust managed Cloud sandbox images (#18066)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Cloud selects and updates the sandbox image used by its agents.
> - Runner admission also required saved qualification for the exact
snapshot and configuration.
> - An image update left the old record stale and stopped work before
runtime startup.
> - This pull request trusts the image selected by Cloud and uses the
real runtime startup check.
> - Agents can continue after an image update without an operator
running a separate qualification test.

## Linked Issues or Issue Description

**What happened?**

A managed Cloud image update could cause
`sandbox_snapshot_qualification_required` before provider work began.
Runner discovery also fell back to Legacy when saved platform
qualification was absent. The agent Test action could require a separate
qualification request even when discovery already offered Paperclip
Runner.

**Expected behavior**

A managed Cloud image can start without a saved qualification record.
Runtime startup and the handshake report actual compatibility failures.
Custom images keep their existing qualification rules.

**Steps to reproduce**

1. Use Paperclip Runner on a Paperclip-managed Cloud sandbox.
2. Save qualification for its current snapshot.
3. Update the platform-selected snapshot and leave the old record in
place.
4. Start a task. Before this fix, admission rejects the stale record
before starting the provider.

Related work: Refs #17445, Refs #17724, Refs #17448. These changes cover
saved-computer qualification and setup tests. This fix removes the
qualification prerequisite only for managed Cloud images.

## What Changed

- Use one managed-image policy in runner selection and lease admission.
Require the active Cloud configuration to provision the provider. Active
captured custom images are excluded.
- Use the current Cloud image and ignore missing, stale, revoked or
valid saved qualification records for that image.
- Reuse the existing provisioned-runner selection path. Keep adapter
availability checks and the Legacy choice for managed sandboxes.
- Read custom-image metadata directly during discovery without resolving
provider credentials.
- Use the existing template-matching rule for captured images. Ignore
outdated captures, preserve qualification for matching custom captures,
and fall back to Legacy discovery for malformed saved capture config.
- Skip the separate qualification request when discovery already offers
Paperclip Runner as the default. Test checks the actual runtime.
- Add regressions for image updates, provider failures, custom images,
self-hosted environments and company access. Update the development and
verification guides.

## Verification

- Before the fix, managed-image discovery regressions returned Legacy,
and the rendered Test action called the separate qualification endpoint.
- The original runtime source fails four of the five managed-image
regression cases. The fixed runtime passes all five, including provider
startup error propagation. The baseline check uses the original module
source through a temporary Vitest transform and the same database-backed
tests.
- All 603 focused tests pass: 231 runner selection, 185 environment
runtime, 10 snapshot qualification, 168 rendered agent form and nine
form source controls. Discovery controls cover unavailable credentials,
stale managed markers without an active provisioner, outdated captures,
matching custom captures and malformed saved config. The
outdated-capture regression fails before the fix and passes afterward.
- `node scripts/check-maps.mjs` and `pnpm check:token-gates` pass.
- Full `pnpm -r typecheck` and `pnpm build` pass. All five focused files
passed together on `8275bbe72bb4d91fb3a02fb0658f0846b2abc966`
(`codex/simplify-managed-runner-readiness`, Node 24.19.0, macOS ARM64).
- The full local `pnpm test:run` suite is still in progress. Hosted CI
is waiting at `ci / gate / Select trusted runner`; the separate `review`
workflow is queued. Greptile is 5/5 on the current head, and both review
threads are resolved. This PR is not yet verified by full CI.
- Live fixed-source Daytona acceptance is not verified. This workspace
has no Daytona API key or image configuration. The earlier deployed
recovery is not evidence for this source change.

## Risks

- Managed Cloud now trusts its selected image. A bad image can fail at
real runtime startup instead of a saved qualification gate.
- Company access, credentials, runtime integrity and handshake checks
still apply. Self-hosted sandboxes, custom environments and active
captured custom images keep their qualification and immutable snapshot
binding.
- No schema change or data migration is required. Existing qualification
records can remain in place.

## Model Used

- OpenAI Codex, GPT-6 family, with reasoning, tool use and code
execution. The exact model ID and context window are not exposed in this
session.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-28 14:39:26 -05:00
MichielMAnalyticsandClaude Opus 5.5 644937c931 feat(sandbox-providers): add boxd sandbox provider (#17284)
<p align="center">
<img
src="https://raw.githubusercontent.com/MichielMAnalytics/paperclip/08f1cdda04443ed10fc43e7097ae0b2d14b5cc19/boxd-x-paperclip.png"
alt="boxd × Paperclip" width="700">
</p>

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agent work runs in sandboxes that provider plugins supply
> - An operator selects a provider for each environment, and a reused
lease keeps one sandbox for an issue across heartbeats
> - The time to resume a reused sandbox delays every heartbeat on that
issue (see #14684)
> - boxd runs each sandbox as an isolated microVM that suspends and
resumes in milliseconds, with disk, memory and processes kept
> - This pull request adds a boxd sandbox provider plugin
> - The benefit is that operators get one more provider, with fast
resume for reused leases

## Linked Issues or Issue Description

Refs #14684. That pull request keys the remote session identity on the
provider lease ID. This provider keeps the provider lease ID equal to
the boxd machine ID, so the ID stays the same across suspend and resume.

No issue exists for boxd. The request is described below with the fields
of `adapter_request.yml`.

**Agent or provider**

boxd (https://boxd.sh). boxd runs each sandbox as a KVM microVM. The
plugin uses the public TypeScript SDK, `@boxd-sh/sdk` 0.2.20 or later.

**Why this adapter is useful**

boxd suspends a machine in about 17 ms and resumes it in about 0.2 s,
with the disk, the memory and the running processes kept. This fits
`reuseLease`: the next heartbeat on an issue continues on the same
machine. Each machine is created with `isolated: true`. An isolated
machine has no metadata endpoint, no in-VM `boxd` CLI and no boxd
integrations, so sandbox code cannot reach the provider management
interface.

**How the agent is invoked**

Build and install the plugin by local path, as the package README
describes. Open Instance Settings, then Environments. Select the `boxd`
provider and supply a boxd API key. Agents that use the environment run
their adapter commands in a boxd machine.

**Are you willing to implement it?**

Yes. This pull request is the implementation.

## What Changed

- Adds the `boxd` sandbox provider under
`packages/plugins/sandbox-providers/boxd`. Its structure follows the E2B
and exe.dev plugins. The plugin has no code comments, to follow
`CONTRIBUTING.md`.
- Implements the validate, probe, acquire, resume, release, stop,
destroy, inspect, realize-workspace and execute hooks. The manifest
declares `sandboxCapabilities: { reusableLeases: true }`.
- With `reuseLease`, release suspends the machine and resume wakes it. A
suspended, hibernated or stopped machine is woken by the matching boxd
call. A release that cancels active work stops the machine and keeps its
disk.
- Release and destroy return a `destroyed` receipt only after boxd no
longer lists the machine. Stop returns a `stopped` receipt only after
boxd reports the `stopped` state.
- When the host sets `requestedExpiresAt`, the plugin sets a boxd delete
timer at or before that time and returns `expiresAt` on the lease. The
timer is set after the create call returns, so a failure while setting
it cannot lose the machine ID.
- Commands run through `sh` with quoted arguments and per-command
environment. Stdin is staged with boxd's file API in a temporary file
that only the machine user can read, and removed afterwards; the
workspace directory is created the same way. A machine whose boxd agent
predates that API, such as one restored from an older snapshot, falls
back to the older upload and `mkdir` calls. A command timeout ends the
remote process group and returns `timedOut: true`. A command on a
stopped machine starts the machine and runs one more time.
- A failed acquisition deletes its machine. If boxd cannot confirm the
deletion, the plugin throws `PluginEnvironmentCreationCleanupError` with
the machine ID, so the host records it and retries the teardown; the
destroy hook checks the account and the machine labels before it deletes
a failed creation. A probe whose machine cannot be deleted reports a
failure, and probe machines carry a 15-minute boxd delete timer.
- The plugin keeps one SDK client for each API key. This prevents a
session token exchange for each command.
- Machines carry the labels `paperclip-provider`,
`paperclip-environment` and `paperclip-run`, so an operator can find
them with `boxd machine list --label paperclip-provider=boxd`.
- Registers the optional bundled catalog key `boxd` and the trusted
`BOXD_API_KEY` host fallback, with tests that mirror the CreateOS cases.
- Adds the package to the release manifest with `publishFromCi: false`
until a maintainer bootstraps the first npm publish.
- Adds unit tests with a mocked SDK (40 tests) and opt-in live tests
(`BOXD_LIVE_TEST=1`, 9 tests) that run every hook against boxd.
- Adds a section to `doc/plugins/PLUGIN_AUTHORING_GUIDE.md` and adds
boxd to the README provider list.

## Verification

Provider package (`packages/plugins/sandbox-providers/boxd`):

- `pnpm install --ignore-workspace --no-lockfile && pnpm typecheck`:
passes.
- `pnpm test`: 40 passed, 9 live tests skipped.
- `BOXD_LIVE_TEST=1 BOXD_API_KEY=... pnpm test`: 49 passed against
production boxd on 2026-10-28 with `@boxd-sh/sdk` 0.2.20. The live tests
cover:
- validation, and a probe at 2 vCPU that deletes its machine (a bad key
returns a failed probe);
  - the labels, the isolation and the org of an acquired machine;
- stdin, env, argument quoting, the exit code and stderr, and the
removal of the staged stdin file;
- an empty stdin, and a staged stdin file that only the machine user can
read (mode 600);
- a 5 MiB round trip through the base64-over-exec path (the SHA-256
matches);
- a command timeout, which returns `timedOut` and ends the remote
processes;
- suspend and resume (a file and a running process stay), stop and
resume (the file stays), and inspect in each state;
  - a command on a stopped machine, which starts the machine and runs;
- resume and stop of a hibernated machine, stop of a suspended machine,
and release with `cancelActiveWork` and with `stop_and_retain`;
  - release without reuse, which deletes the machine;
- a `requestedExpiresAt` 45 s away, which boxd enforces by deleting the
machine;
- a run restored from a snapshot, and a fresh machine at 2 vCPU / 8 GiB;
- resume after destroy, which returns an expired lease, and a final
check that no test machines remain.
- Measured times: probe 1.5 s, acquire 1.4 s, release with suspend 17
ms, resume from suspend 0.13 s, resume from hibernate 0.18 s, stop 14
ms, resume from stop 3.2 s, acquire from snapshot 1.6 s, confirmed
destroy 30 ms.
- On a machine started before boxd's file API (the test host), the
plugin's hooks fell back to the older calls: the workspace was created,
stdin was staged (mode 644, the upload path), an empty stdin worked, and
no staged file was left.

Host:

- `npx vitest run src/__tests__/bundled-plugins.test.ts
src/__tests__/plugin-database.test.ts` in `server`: 73 passed, 6 of them
new (re-run on 2026-10-28).
- `npx vitest run src/__tests__/cli-invocation-safety.test.ts` in
`server`: 40 passed. The README install commands now use the direct-exec
CLI form.
- `npx tsc --noEmit` in `server`: passes.
- `node --test scripts/release-package-map.test.mjs
scripts/check-release-package-bootstrap.test.mjs`: 18 passed.

Full stack, on a Linux host with `pnpm dev:once` in `local_trusted`
mode:

- I installed the plugin with `POST /api/plugins/install` and a local
path, then created boxd environments with a secret reference for the API
key.
- Ephemeral environment: the environment probe passed. A `claude_local`
agent (`claude-sonnet-5-5`, legacy runner) ran a task in a boxd machine.
It reported Ubuntu 24.04.5 and the workspace
`/home/boxd/paperclip-workspace`, and it marked the task done. The lease
was released and the machine was deleted.
- Reused-lease environment: the first run wrote a file and started a
background loop. After release, the machine was in the `suspended`
state. A comment with `reopen: true` started a second run. That run used
the same machine, so the provider lease ID was the same on both lease
rows. The file was there and the background loop was still running.
- Validation: a config with `vcpu: 3`, and a config with both `vcpu` and
`snapshot`, return 422 with the plugin error. The unsaved-config probe
(`/environments/probe-config`) passed in 2.0 s and deleted its machine.
A saved probe with `vcpu: 4` created a 4 vCPU / 16 GiB isolated machine.
- Cancel: cancelling the first run on a reused lease marked the lease
`expired`, and the host destroyed the machine through the plugin about
12 s later.
- Delete: deleting an environment that holds a reused lease returns 409.
With `?destroyReusableSandboxLeases=true` it returns 200, and the host
destroys the suspended machine through the plugin.
- I re-ran this flow on 2026-10-26 and again on 2026-10-28 with
`@boxd-sh/sdk` 0.2.20, from a script, with each step checked. On
2026-10-28 the ephemeral run posted its proof and both of its machines
were deleted. The reused-lease follow-up ran on the same machine (both
lease rows have the same provider lease ID), and found the file and a
background loop that had kept running. The validation errors returned
422, the unsaved-config probe passed in 1.8 s, and deleting the
environments left no machines. Every check passed except the host gap
below.
- After the runs, `boxd machine list` showed no machines with the test
prefix.

Not run: `pnpm -r typecheck`, `pnpm test:run` and `pnpm build` at the
root. The test host has no Rust toolchain for the runner binary. On that
host, `scripts/check-forbidden-tokens.mjs` adds the local username
(`boxd`) as a token. It then flags every `boxd` substring, and it also
fails on `master` there (`InboxDismissal`). A CI runner uses a different
username.

## Risks

- Host gap, not in this plugin: when a run that **resumed** a reused
lease is cancelled, the host marks the run `cancelled` but does not stop
the agent in the sandbox. The adapter keeps polling the file bridge, and
the host calls no release, stop or destroy hook. The lease stays
`active` until the environment is deleted. A plugin-side trace showed
only bridge-polling `execute` calls after the cancel. boxd is the only
provider that declares `reusableLeases`, so this path may not have been
exercised before. A cancel on the first run of a lease works as
expected.

- Low risk to existing behavior. The plugin is opt-in and is not
installed by default. The host changes add one catalog entry, one
credential passthrough entry and their tests.
- boxd machine creation has no idempotency key. If a create response is
lost, a machine can stay behind. The labels above help an operator find
it.
- A suspended machine keeps its memory image until boxd hibernates it
after a period of idle time. An operator who keeps many reused leases
pays for that storage.
- boxd stops a non-PTY command that has no output for 30 minutes. Agent
CLIs write output during a run, so this does not affect normal runs.
- boxd has one region (EU), amd64 machines only, and no GPUs. Machine
sizes are 1/4 GB, 2/8 GB, 4/16 GB and 8/32 GB.
- The new `package.json` needs code-owner approval.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code, with tool use
and shell execution on a boxd machine. The session 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 (focused checks; the limits
are listed under Verification)
- [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)

https://claude.ai/code/session_01HNWtBYxLByQmmNKjuaou1P

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:34:21 -07:00
DottaandPaperclip f4f02880ca fix(server): wake failed retry notices from committed changes (#17649)
## Thinking Path

> - Paperclip keeps exact failed chat retries in durable action and wake
receipts.
> - Deferred and declined retries owe safe notices to their original
conversation.
> - Periodic publication maintenance repeatedly inspects those receipts
when idle.
> - Committing receipt, authority, lifecycle and lease changes already
identifies when eligibility can change.
> - A scoped owner reconstructs durable obligations, drains bounded
candidates, retains contention, then becomes quiet.

## Linked Issues or Issue Description

This existing failed-retry notice slice follows #17647. It removes the
failed-retry notice duty from periodic publication maintenance while
preserving the explicit manual API. Existing action, receipt,
publication and source rows remain authoritative; no new table or
scheduler is added.

**Problem:** Removing the scan alone loses notices after real admission,
cancellation, early refusal, requester or agent restoration, and
relevant lease settlement. Millisecond cursor truncation can also repeat
denied history.

**Expected behavior:** Committed supported writes wake the scoped notice
owner, which uses current authorization and precise cursors. Real
retries survive failure, contention, restart and drain; settled work has
no recurring SQL.

## What Changed

- Extract failed-retry projection under the existing authorization
owner. Preserve current receipt/source authority and provider transport
authorization.
- Register bounded scoped work using the existing delivery
coordinator/scheduler. Preserve exact PostgreSQL cursor precision,
contention and a wake arriving during reconciliation.
- Extend the shared transaction-aware notification boundary to
failed-retry notices. Cover admission, conditional denial, early
refusal, requester changes, and agent lifecycle transitions to an
invokable status. Two shared receipt hooks and their budget fixture
correction already landed in the preceding inbound slice; preserve them
once.
- Notify when relevant native lease cleanup completes or a reusable
lease is retired, preserving claim fencing and caller-owned
transactions.
- Avoid the discovery scan identified in #17647: known task scopes
require zero discovery SQL; company/startup discovery uses a single
DISTINCT projection from the same candidate predicate. Bounded current
authorization still runs afterward.
- Remove only this duty from periodic publication maintenance, retain
manual behavior and startup reconstruction, and add real
producer/lifecycle/query-budget regressions with an audit.

## Verification

Published head: `fa95a1f2fb9d546aa62dbd3b43aa714f5c88bd35`, targeting
master after #17647 merged at
`1aa3a21ac41f602977638cf0be875b01a243e69f`.

- **42 distinct current combined-master cases pass:** 21
retry-notice/native-lease/restored-input producer cases (1,651 skipped),
plus all 21 app/startup and task-drain admission-release cases. Server
typechecking, build and module boundaries pass. The final follow-up adds
acceptance documentation only; all 17 owned server source/test hashes
are unchanged.
- The prior **404-case** matrix passes at prepared revision
`c2c53b839497be6f5e28aa2cd5ba50cfd1d76d4a`: 259 across six complete
consumer/lifecycle/environment suites, 20 notice/lease cases, 53
ordinary-notice and 72 Retry/budget cases. Those chat selections skip
1,651/1,618/1,599 cases. A subsequent 21-case combined producer check
passes after the parent restoration repair. These earlier runs retain
their revision scope.
- The normal two-parent integration
`43d0f84ea56845b8fc4946a7533ecbf7f07b679a` preserves the complete
19-path owned binary patch and all 23 unrelated master paths/deletions.
The semantic merge base is the verified landed parent head
`41f7e2c9e351efa6cfa5ef699c0e69df7425012b`; squash ancestry otherwise
causes historical conflicts. Both parent commits and the exact resolved
tree are verified; no rebase or force push occurs.
- Three scope-discovery regressions fail before the fix. The first SQL
projection fails with PostgreSQL 42702 (ambiguous company column), then
passes after using a distinct company alias. Known task hints have zero
discovery SQL; company/startup discovery has one query returning only
distinct task scopes. Existing bounded projection/current authorization
remain intact.
- Current producer tests cover commit/rollback, parked authority
restoration, real agent resume, early refusal, requester changes, native
lease cleanup/replacement, drain/restart/shutdown, precise cursors and
contention. Parent shared admission/denial/restored-input notifications
are preserved once. No polling backstop or storage is added.
- [The owner
audit](https://github.com/paperclipai/paperclip/blob/fa95a1f2fb9d546aa62dbd3b43aa714f5c88bd35/doc/plans/2026-10-25-failed-retry-notices-sleep-audit.md#final-landed-parent-acceptance--october-28)
records current commands, fixtures, failure history and limits. Fresh
exact-head remote checks and Greptile 5/5 are pending; old-head reviews
do not count.

The owner audit preserves prior failures and their original revision
scope. The old remote head's Runner receipt timeout, cancelled gate, and
review error are not current passes; fresh exact-head checks and
Greptile 5/5 are required. No full local repository suite, live provider
tenant, external wake alarm, physical suspension or savings claim is
made.

### Final remote gates

Exact published head `fa95a1f2fb9d546aa62dbd3b43aa714f5c88bd35` has
Greptile 5/5 with no actionable findings, successful current main CI and
ready-triggered security scan. The final dependency/quality review
workflow `40747725096` passed after waiting for a GitHub-hosted runner.
No Ponytail verdict is present.

Two automatic main CI requests and two identical-head quality-review
requests were created one second apart. The older main run was
automatically cancelled; only the proven duplicate, unstarted quality
request was cancelled manually. Their same-head, same-workflow
replacements both finish successfully. The merge guard verifies these
replacements, all current checks and current required-status integration
rules before excluding the superseded cancellation contexts. No actual
failing review or current check is waived and no protection bypass is
used.

## Risks

- Process-local signals cover supported writers using this boundary, not
independent SQL or other replicas.
- Lease completion now reads/locks the exact row before updating.
Reusable lease retirement wakes company scope because its previous issue
can differ. Claims and transaction ownership remain enforced.
- Broad discovery can inspect history inside PostgreSQL; DISTINCT
reduces returned rows and round trips, without claiming constant
database cost. Task hints are wake requests, so bounded reconciliation
handles already exhausted scopes.
- Native filesystem activation belongs to execution authorization and is
not an eligibility input for this notice projection. Other
notice/maintenance duties and Cloud sleep gates remain separate.

## Model Used

OpenAI Codex, based on GPT-6, with reasoning, local code inspection,
shell execution, and PostgreSQL testing. The exact serving model
identifier and context-window size are not exposed in this session.

## 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-10-28 14:14:28 -05:00
DottaandPaperclip c4b6168e08 fix(server): disclose assigned tool search page bounds (#18056)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/187/changes/paperclip/187
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip is the control plane for AI agents at work.
> - Native agents find connected app tools through the assigned-tool
search tool.
> - Large catalogs require small pages and an offset for the next page.
> - The input schema enforces a maximum of 20 results, but its
descriptions omit that number.
> - Providers can render the integer field as a plain number and hide
its numeric bounds.
> - This pull request puts the existing range and default in both
descriptions.
> - Agents can choose a valid page size before they make a search call.

## Linked Issues or Issue Description

**What happened?**

An agent can request `limit: 50` for `paperclip_search_assigned_tools`.
The tool rejects the call with `invalid_tool_call` at
`/properties/limit/maximum`. Its model-visible description does not
state the accepted range.

**Expected behavior**

The tool description and the `limit` description must state the range of
1 to 20 and the default of 5. Agents can use `nextOffset` to read more
results.

**Steps to reproduce**

1. Inspect the assigned-tool search description in a provider tool list.
2. Render the integer schema as a TypeScript number field.
3. Request `limit: 50` without a visible page-size bound.
4. Observe the validation error. Retry with a valid size and offset.

### Hypothesis and thesis for a fix

The numeric schema is correct, but the descriptions omit the page limit.
Put the existing range and default in text that all providers can see.
Keep the strict validation in the assigned-tool discovery owner. This
should reduce avoidable retries. It does not guarantee that every model
call will be valid.

## What Changed

- State the accepted range and default in the search description and the
`limit` property. Add the existing default as schema metadata.
- Test the tool listing and calls through the real HTTP MCP bridge for
both compact delivery paths.
- Document the page size and offset procedure in the Runner README and
verification maps.

## Verification

- Red: the two new bridge tests fail against the unchanged
implementation because the listing omits the numeric guidance.
- Green: all 37 tests in
`server/src/services/native-runtime/assigned-mcp-tools.test.ts` pass
after the change. The tests cover default pages, a 20-result page,
offset continuation without duplicates, and rejection of 21 and 50.
Existing tests cover grants, revocation, modes, approvals, aliases, and
schema chunks.
- Current head `7d658d0c4e4d9db3feb53a5c508214440ff058c4`: 37/37 focused
tests pass locally. Greptile is 5/5 with no unresolved threads.
Current-head CI is green, including typecheck, build, unit tests, Runner
checks, and all browser shards ([CI run, attempt
2](https://github.com/paperclipai/paperclip/actions/runs/40733284523/attempts/2)).
Browser shard 7 initially failed in a newly merged agent YAML editor
test when its clipboard read included the whole page. The single retry
passed without a code change; the exact cause is unconfirmed. The
original failure remains in [the CI
log](https://github.com/paperclipai/paperclip/actions/runs/40733284523/job/122975224906).
- Run the focused suite from `server/`: `pnpm exec vitest run
src/services/native-runtime/assigned-mcp-tools.test.ts`.
- `node scripts/check-maps.mjs` and `git diff --check` pass.
- The bridge uses real local HTTP. The app gateway uses synthetic
descriptors. No deployed build or live model improvement is claimed.
- Full local verification is incomplete. Recursive typecheck and server
typecheck require `cargo`, which this workspace lacks. A direct server
TypeScript check was killed by the workspace. The full test suite had no
final verdict before the resource stop. CI must supply the remaining
verification.

## Risks

Low risk. This change describes existing limits and adds default
metadata. It does not change search execution, page caps, gateway
access, revocation, approvals, or audit. Models can still send invalid
calls. This change has not measured their future retry rate.

## Model Used

OpenAI Codex, GPT-6 family, with tool use and code execution. The exact
provider model ID and context window are not exposed to this session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used, its capabilities, and unavailable
model metadata
- [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
- [x] I have described the issue in-PR following the bug report fields
- [x] I have not referenced internal or instance-local Paperclip issues
or links
- [x] The public branch name describes the change and has no internal
task ID
- [x] I have run the focused tests locally and they pass
- [x] I have added tests for the reported failure
- [x] I have updated relevant documentation
- [x] I have considered and documented risks
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open recommendations or follow-ups
- [x] I will address reviewer comments before requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-28 13:55:48 -05:00
DottaandPaperclip 1aa3a21ac4 fix(server): wake inbound queue notices from committed changes (#17647)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Chat users receive a notice when accepted input waits for execution.
> - Periodic publication maintenance scans those receipts even when
nothing changes.
> - Admission, cancellation, source removal, and authority changes
already define when a notice can change.
> - Existing action, receipt, publication, and provider-link rows
preserve that work across restart.
> - This PR gives ordinary inbound queue notices a commit-driven owner
using the shared scheduler.
> - Settled notices stop querying while unfinished batches and
contention retain recovery.

## Linked Issues or Issue Description

This ordinary inbound-notice slice follows merged #17895 and now targets
master. Related extraction: #16187. Failed-run retry notice projection
remains a separate following slice (#17649); its two shared
receipt-writer notifications move forward here because ordinary input
can attach to those receipt owners.

**What happened?**

Publication maintenance scans accepted input to project queued,
not-started, and removed-source notices. Empty scans keep touching the
database. Its cursor also loses PostgreSQL timestamp precision, so a
full page of suppressed candidates can repeat.

**Expected behavior**

Committed changes should wake the notice owner. The worker should
reconstruct saved candidates after restart and stop scanning when
settled. It must retain a wake across drain, failed selection,
contention, and a commit during reconciliation.

**Steps to reproduce**

Start an otherwise idle instance with chat history. Observe the ordinary
inbound notice scan in periodic publication maintenance. For the cursor
defect, retain a full page of denied candidates with microsecond
timestamps before an eligible notice.

## What Changed

- Register an ordinary inbound-notice owner with the existing delivery
coordinator and scheduler. Bound each pass to 100 candidates, preserve
precise continuation cursors and earlier-page contention, and reset
scoped discovery after committed changes.
- Notify from real admission, failed action settlement, source removal,
task/tree/agent/budget/company cancellation, signed Slack Stop, and
deferred queue cancellation/failure. Preserve pending-status and
absent-run guards so concurrent promotion wins.
- Cover task privacy/grants, project membership/visibility and current
authority through their persistence owners. Keep receipt ownership,
current authorization, provider policy and closed notice text in the
existing chat service.
- Cover shared retry-owned receipts through the existing durable
authorization callback and a notifying transaction around conditional
denial retirement. These small producer fixes already exist in #17649;
no per-caller recovery wrappers are added. Retain its matching
budget-refusal fixture correction.
- Remove only ordinary notices from periodic maintenance. Preserve the
separate failed-retry pass at 50 and keep the explicit combined manual
API.
- Preserve timestamp precision, fairness, restart, drain/resume,
rollback and quiet behavior. Add two real producer transaction
regressions and update the audit. Add no storage or scheduler
infrastructure.

## Verification

Current publication head: `41f7e2c9e351efa6cfa5ef699c0e69df7425012b`,
after normal merge of master `d30c8f42b842327ee1c18c41a2efd6ba623da5cd`
(#17960). The integration preserves both complete added/removed patches,
all non-overlap upstream blobs/deletions, and task-before-comment lock
order before the notice source lock/intent. Full binary identity is not
claimed for the overlapping files. The final follow-up changes
acceptance documentation only.

- **202 distinct combined-master cases pass on
`1720b685d9d5fb9cb4377223fdaa0a9fae2aff9c`:** 148 across the real
PostgreSQL receipt concurrency and two comment route suites, plus 54
notice/FIFO/producer cases (1,598 skipped). Current server
typechecking/build and module boundaries pass; all 21 owned source/test
hashes are unchanged after the documentation follow-up.
- The earlier CI voice-reconstruction quiet assertion failed once after
105 fetches. All 15 voice lifecycle cases pass unchanged locally; no
assertions or production code were relaxed and no CI retry was used. The
original failure remains in the audit, and current-head full CI must
pass.
- **Earlier restoration repair (head
`28c898e93504318056d7a6ab2bbc5eafa6b639ae`): 126 distinct selected cases
pass (54 ordinary-notice/producer cases with 1,598 skipped, plus 72
separate Retry/budget cases with 1,580 skipped).** Fix the blocking
[restored input stays
silent](https://github.com/paperclipai/paperclip/pull/17647#discussion_r4404007181)
finding. A failed Retry's earlier receipt wake can drain before
`releaseUnadmittedTaskRetryInput` restores ordinary receipts in a later
transaction. The restoring transaction now awaits the existing
company/task notification before its guarded write.
- The new causal regression builds a durable unadmitted failed-Retry
owner, uses the real input-claim owner, consumes an earlier committed
wake, and proves two minutes of worker quiet with no notice. The real
release transaction then restores the ordinary row, emits intent/commit
settlement, and reactivates the coordinator to create its queued notice.
It fails before the hook with the restored row visible but no intent.
This is real PostgreSQL producer/consumer boundary proof with seeded
Retry-refusal state; the separate compatibility selection exercises
existing supported GitHub Retry flows. It is not a claimed complete
public-request failure walkthrough.

- **Earlier discovery-repair acceptance (revision
`4a713edfa06b9d3dcc0e81e900006fbdb973b2d9`): 267 distinct selected cases
pass:** 142 complete cancellation/app/admission consumer cases, 53
ordinary-notice cases, and 72 separate retry/budget cases. The
selections skip 1,598 and 1,579 other cases. The final master
integration leaves this complete patch byte-identical; the new master
paths concern provider workspace/session reuse and E2E reports.
- Fix the valid P2 [discovery rereads denied
history](https://github.com/paperclipai/paperclip/pull/17647#discussion_r4386889825),
despite the previous head's 5/5 summary. Task hints now need zero
discovery SQL; company/startup discovery returns DISTINCT company/task
identifiers with one query. Bounded projection still checks current
authority and candidates. Three real database regressions with 250
denied actions and a second company fail before the fix and pass
afterward, checking actual query and returned-row counts. Broad SQL may
still inspect candidate history; no constant database-cost claim is
made.
- Both new producer tests fail before their fixes and pass afterward.
One observes intent before a callback-owned receipt write and settlement
after outer commit. The other uses real heartbeat admission/recovery and
a PostgreSQL row lock to prove exact company/task intent exists before
conditional denial retirement; the outside connection still sees
deferred status until commit.
- The reader can select a retry-owned deferred receipt for later
ordinary input, and receipt resolution follows its owner. Disabling
coalescing on the retry's own request does not exclude that later path.
The two transferred notifications close the actual writer gaps; current
authorization remains enforced by existing consumers. This is
producer/transaction proof, not a claimed complete mixed-ingress
walkthrough.
- The moved callback exposes an old test mock that authorized against
the root DB. The existing #17649 fixture correction authorizes and
writes in one transaction; original requester, comment, skipped-status
and budget assertions remain. Both the initial invalid lock fixture and
the corrected missing-intent failures are preserved in the audit.
- Updated shared dependency build, server typechecking/build and
module-boundary checks pass. Because master also changed agent
configuration, upgrade admission and runner contracts, the same 264
cases were rerun on combined revision
`875a6ee8d211cba7f0499aace7fcea7f6880c4a2` with new isolated databases.
Repeated checks are not 528 different tests. Tests under `src/__tests__`
were executed separately from production typechecking.
- [Current acceptance and preserved failure
ledger](https://github.com/paperclipai/paperclip/blob/41f7e2c9e351efa6cfa5ef699c0e69df7425012b/doc/plans/2026-10-25-inbound-wake-notices-sleep-audit.md#shared-retry-receipt-producer-gap-resolved-october-28)
records current scope, exact commands, actual fixtures, source hashes
and remaining limits. Earlier baseline/full-suite counts retain their
original revision scope.
- Server typechecking/build and module boundaries pass after the current
restoration hook. The earlier combined-master compilation at
`661f2f6da8c6c22cdcc25edccd57502ee6fa8c4b` retains its original scope.
- **Current exact-head CI is green and Greptile is 5/5.** The old head's
review error is not a pass. No full local repository matrix, live
provider tenant, external alarm, physical suspension or savings claim is
made. Following notice duties retain their separate owners.

### Final merge verification

- Reviewed PR head remains `41f7e2c9e351efa6cfa5ef699c0e69df7425012b`:
exact-head Greptile 5/5, all 55 check contexts clean, no unresolved
review threads, and no Ponytail verdict present.
- One Runner shard initially failed descriptor suspension and a
five-second OpenCode fixture deadline. The same package passed on the
preceding head. The first local attempt was invalid because required
Rust fixture binaries were absent; after building them, all eight
relevant cases pass with unchanged timeouts. One failed-job retry then
passes 1,956 cases (four skipped). No source/assertion/time-budget
change or second CI retry was used.
- Current master `0e365768f032a472807b5720da8431f92d2f07ce` adds manual
monitor and task-drain fixes. Its routes file overlaps but merges
cleanly. Local normal-merge validation commit
`2720b79c769cb609ad4d392512331e67b910ff3f` preserves both complete
added/removed patches and every unrelated master blob/deletion. This is
not raw binary identity for overlapping files.
- **156 distinct cases pass on that exact combined tree:** all 102
monitor/drain/policy cases plus 54 notice cases (1,598 skipped). Types
and build pass. An initial competing-cold-check run failed setup hooks
(38 passed, two hook failures, 62 skipped); the same four suites pass
alone with all original hook/test timeouts and assertions intact. The
failed run remains recorded, not counted as full acceptance.
- This merge proof changes no published source or review head. The
protected pinned-head merge guard recomputes both patches and requires
the exact tested master/tree/head, successful validation receipts and
unchanged live merge gates. Previous acceptance counts retain their
original revision scope; no local full-repository or deployed-sleep
claim is made.

Master then advanced to `75754ffb7af2b7ee7dce1e915a145faa82a8fb2a` with
#17976 (five UI/e2e/map files only). The entire `server` and `packages`
trees are identical to the validated composition. Both complete patches
and all newly landed UI files are preserved in the final clean merge
tree; the protected gate checks these exact source-root hashes and
changed paths. No additional UI-test result is claimed.

## Risks

- Missing a supported producer could delay a notice until restart. Tests
cover real service and API producers; durable rows remain authoritative.
Notifications cover supported application writers in the owning process,
not arbitrary external SQL writers.
- Privacy invalidation can affect descendants, so those changes use
company scope. Ordinary admission and publication changes use task
scope. Settled history causes no recurring scan.
- Provider output remains subject to current authority and receipt
ownership. A cancelled request without a visible queued notice does not
acquire a new failure message.
- This establishes worker quiet, not host or database suspension. Cloud
alarms and conservative sleep gates do not change. Other maintenance
remains in place.
- Remaining stacked slices still need their own integration, review, and
CI. This slice merges only under the user’s explicit campaign
authorization after current-head gates pass.

## Model Used

OpenAI Codex, GPT-6 family, with repository inspection and code
execution tools. The exact serving variant and context-window size are
not exposed in this session.

## 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-10-28 13:34:38 -05:00
DottaandPaperclip 0e365768f0 fix(server): preserve sandbox workers when task drain resumes (#18065)
## Thinking Path

> - Paperclip coordinates agents and preserves queued work during
maintenance.
> - Stopping a task drain resumes that queued work.
> - Sandbox runs need the configured plugin worker manager to acquire
their environment.
> - The instance-settings route received that manager but omitted it
from its heartbeat service.
> - The route could claim queued work and then fail before provider
execution.
> - This PR forwards the existing manager and tests the actual dispatch
boundary.

## Linked Issues or Issue Description

Follow-up to #17967, which resumes queued work after maintenance. #18037
adds readiness reporting to the same route but does not repair this
dependency.

**What happened?**

After a task drain stopped, a queued Daytona task failed with
`setup_failed`: the provider was installed, but sandbox plugin workers
were unavailable in that server process. The application had supplied
the manager to `instanceSettingsRoutes`. That route constructed
`heartbeatService(db)` without it, then dispatched through that separate
service. The environment runtime therefore reached its missing-manager
guard before any provider work.

**Expected behavior**

Drain-release dispatch must use the manager supplied to the route. Queue
eligibility, scope and ownership checks must still apply.

**Steps to reproduce**

1. Configure a sandbox provider plugin and an agent that uses its
environment.
2. Start a task drain and queue work for that agent.
3. Stop the drain through `DELETE /api/instance/task-drain`.
4. Observe dispatch fail before it calls the configured plugin manager.

**Paperclip version or commit**

Observed at `2e5bbde8cc7eba0eacce00649f17c331203e56d9`. Reproduced
against `7f10cc058568e3c1ac133cf24f3b4000cbdfca0e`.

**Deployment mode**

Hosted Linux with a Daytona sandbox plugin. The local regression uses
real PostgreSQL 18 and the actual route, heartbeat, queue, orchestrator
and environment runtime.

## What Changed

- Pass the supplied plugin worker manager to the route's heartbeat
service.
- Add a database regression that releases genuinely queued sandbox work
through the real HTTP route and checks the scoped acquisition call.

## Verification

- Red: the new test executed the route and recorded zero manager calls.
The queued run failed with the same missing-manager error as the
incident.
- Green: the route reached exactly one `environmentAcquireLease` call
bound to the expected plugin, company, task, agent, environment and
queued run. The fixture then threw a unique sentinel before any external
allocation; that sentinel was persisted on the same run.
- All 8 database drain-release cases pass. All 101 existing
instance-settings and task-drain unit checks pass. `git diff --check`
passes.
- Local database verification used an owned PostgreSQL 18 container with
all 396 migrations. A temporary Vitest configuration replaced only
embedded database startup/cleanup. Database queries and dispatch
services remained real. The override and credentials are not in this PR.
The owned container stopped after the tests.
- Preserved setup failures include the initial temporary mock-bootstrap
import, an unbuilt SDK entry and a reused synthetic sponsor row. A first
fixed-path run also exposed an unnecessary expectation about an optional
RPC timeout. That assumption was removed; the run identity, exact call
count and scope assertions remain. These failures are not claimed as the
behavioral red.
- The initial frozen install found existing UI lockfile drift. Setup
used the repository's CI resolution fallback. The original lockfile was
restored and is unchanged in this PR.
- Full `pnpm -r typecheck` and `pnpm build` pass at
`be18d8ec1f84af20bad2b6bd97677b1e60c3626f`. Current-head CI passes: 53
successful checks and two intended Storybook skips, none pending or
failing. Greptile is 5/5 on that exact head with no open review threads.
CI ran the standard embedded PostgreSQL bootstrap and passed all 8
drain-release cases, including the new regression. The full standard
local `pnpm test:run` is still in progress; no local full-suite pass is
claimed. The earlier targeted database suite used the isolated external
fixture.
- No post-fix production drain cycle is claimed. The repair is not
deployed. An ordinary retry of the observed legacy preparation failure
was separately refused by the existing internal retry-safety classifier
before admission. This PR does not broaden that classifier or replay the
request.

The initial CI server-7 shard failed the unchanged decision-expiry
restart test: the global coordinator reported a wake at +30 seconds
rather than the decision expiry at +120 seconds. The test failed before
checking early expiration. A bounded probe of the real work signals,
coordinator and decision workers reproduces that earlier wake after a
failed transaction is reconciled during startup, without database or
provider calls. The captured CI log does not establish that exact
trigger. One diagnostic failed-job rerun passed all 1,625 shard tests
and the dependent verification gate on unchanged source. The original
failure, probe and retry receipts are retained; no scheduler fix or
infrastructure cause is claimed.

## Risks

The route can now reach the configured sandbox provider when it resumes
eligible work. Existing queue claims, company scope, pause and new-drain
gates remain in place. The change does not start a second manager, add a
wake loop or change the successful drain-release response. Installations
without a manager retain the existing missing-manager behavior. No
schema, provider binary, credential or retry-authorization contract
changes.

## Model Used

OpenAI GPT-6 through Codex, with reasoning, tool use, code execution and
collaborating agents. The session exposes GPT-6 as its model version; a
more specific model ID and context-window size are unavailable.

## 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-10-28 13:13:36 -05:00
DottaandPaperclip 21137db805 fix: make Check now work for retained monitors on blocked tasks (#18061)
## Thinking Path

> - Paperclip lets people manage agents and inspect their work.
> - Task monitors schedule checks of work that is still pending.
> - A task can retain a monitor after it becomes blocked.
> - The UI still offered Check now, but the server rejected the task
status.
> - The UI also claimed that an automatic check would run on the next
tick.
> - This change admits an explicit human check through the normal
execution gates and shows that automatic checks are paused.
> - People can request the check without changing task status, and
skipped checks no longer report success.

## Linked Issues or Issue Description

**What happened?**

A blocked task with a retained monitor showed Check now and an overdue
countdown. Clicking the button failed because manual checks required an
in-progress or in-review task. The endpoint also returned success when
admission skipped a check.

**Expected behavior**

A human can request one check through normal admission. Automatic checks
stay paused while the task is blocked. A check that cannot start reports
a conflict.

**Steps to reproduce**

1. Schedule a monitor on an agent-owned task.
2. Let the task become blocked while it retains the schedule.
3. Open the task and click Check now.

Related: #14909 addresses scheduled-retry promotion. This PR addresses
retained task monitors.

**Paperclip version or commit**

Base: 7f10cc0585.

## What Changed

- Allow a human to check a retained monitor on a blocked task. Keep
agent and automatic checks limited to active task statuses.
- Keep the existing admission path and status guard. Do not change task
status to start a check.
- Return 409 when admission skips the check. Preserve the schedule when
a dependency or recovery hold prevents dispatch. Keep a successful
result when a new schedule replaces the consumed schedule after
admission.
- Show Automatic checks paused in the banner, composer strip and
properties. Hide Check now on backlog and todo tasks. Provider-quota
recovery stays paused on blocked tasks because it uses a direct retry
path; its monitor is retained until the task resumes.
- Add database, process, route and UI regression coverage, a Storybook
state, API metadata, and behavior documentation.

## Verification

- `pnpm -r typecheck` passed.
- `pnpm build` passed.
- Server scheduling, process admission and route suites: 94 tests
passed.
- UI monitor, properties and time-formatting suites: 142 tests passed.
- Additional admission checks passed: an explicit check starts a process
on a blocked task; an unresolved dependency prevents dispatch and
preserves the monitor.
- Token gates, map checks, Storybook catalog checks and 30 map/catalog
tests passed.
- The full local `pnpm test:run` attempt reported 1 timeout among 1,621
chat integration tests: “keeps an ambiguous github text part blocked
across restart and retries only that part and its tail” exceeded 15
seconds. The exact case passed in isolation on the final head (1 passed,
1,620 skipped). The remaining full-run groups were stopped to isolate
that failure. This does not establish a full local pass or explain the
initial timeout. Final-head CI is green, including the full chat lanes
and the successful single server-shard retry.
- Browser inspection passed for the blocked-task banner, composer strip
and properties row. Clicking Check now set both visible buttons to
disabled Checking state. The preview uses isolated fixtures.
- CI server shard 7/12 failed one decision-expiry deadline assertion.
The entire unchanged decision-expiry suite passed locally on the final
head (20/20). The single retry of that shard passed after the first
workflow attempt completed. The initial failure remains recorded here.
Neither that test nor its production path changed before retry; the
cause is not established by a passing retry.
- Greptile reviewed final head ed936f7433
at 5/5. Both prior review threads are resolved.
- The first CI chat job stopped after its runner received a shutdown
signal. The final head completed a fresh CI run.
- The process fixture uses a local no-op adapter. It proves admission
and execution, not a live provider's response. The Storybook state
simulates dispatch.

## Risks

- An explicit human check can start work on a blocked task with no
unresolved execution gate. This is intentional. Dependencies, recovery,
native finalization, ownership, pause and budgets retain their existing
checks.
- Skipped manual checks now return 409 instead of 200. The UI already
displays API errors in context.
- No schema change or migration.

## Model Used

OpenAI Codex, based on GPT-6. The session does not expose a more
specific served model ID or context-window size. Used repository tools,
code execution, and browser inspection.

## 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-10-28 13:01:11 -05:00
d30c8f42b8 feat(ui): keep writes durable through temporary disconnects (#17960)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/123/changes/paperclip/123
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People save tasks, write documents, make decisions and send board
messages.
> - A disconnect can hide a response after the server accepts a write.
> - Recovery must keep the original account, task and request key.
> - The merged connection foundation in #15754 handles reads and shared
outage state.
> - This change adds bounded write recovery and explicit actions when
recovery stops.

## Linked Issues or Issue Description

**What happened?**

Temporary failures could lose edits, report accepted writes as failures,
or require people to copy and send input again. A retry could target a
newly selected task or account. Restoring attachments could create a
second task.

**Expected behavior**

Keep the draft, its owner and its target. Retry only operations with a
server contract that prevents duplicate writes. Verify uncertain
results. Show conflicts and permanent failures, with an explicit resend
or cancel action.

**Steps to reproduce**

1. Save a task title during an outage, then open another task before
recovery.
2. Restore a task creation that needs files, selecting those files in
another order.
3. Lose a document or decision response, then interrupt the verification
read.
4. Switch accounts while a create, upload or connected-channel
publication is pending.
5. Type and erase a new-task draft before the first account lookup
completes, then reopen it.

This PR carries the write layer from #15769 and its review fixes. It
targets master after #15754 merged. Related test cleanup #16952 already
covers the unchanged copy-link toast test; this PR does not duplicate
that work.

## What Changed

- Add bounded autosave and submit jobs for supported writes, with
pending, conflict and manual retry states. Retain admitted autosaves
after navigation and preserve newer task revisions.
- Keep each job with its original account, task and operation. First
account resolution adopts admitted startup work; a later account change
cancels old work. Remount inline and document editors when their owner
or document subject changes.
- Preserve task-creation keys and immutable request snapshots through
file reattachment. Restore generated document keys before comparing
reselected files. Reject changed requests instead of creating a second
task.
- Check the original account scope before creates and each upload. Save
successful upload receipts before stopping on an account change.
Identify attachments by content digest and metadata.
- Verify uncertain document and decision results. Replay only plain,
keyed comments automatically; combined reassignment, reopen and
run-setting changes require receipt reconciliation or cancel. Settle
each request once when a receipt races its retry.
- Scope drafts and connected-channel publication reads to their owner.
Keep unowned older records unread and unreplayed, with an explicit
confirmed discard action after Activity inspection. Preserve typing
through the first session lookup, keep erased text erased, and report
browser persistence only when storage succeeds.
- Wait for the first account lookup before sending startup status
changes or decisions. Retry failed required lookups with a fixed limit
and surface exhaustion to the original action. Preserve uncertain
comment keys on account cancellation. Check the account generation
before a comment retry calls its sender and again immediately before
POST after asynchronous preparation. Retire only that request’s
optimistic echo on completion.
- Return an ordinary comment’s accepted same-company, same-task,
same-user receipt before workspace reopening, task status changes or
wakeups. Reused keys with changed text still conflict. Complete
reference and activity records through the same finalizer for initial
sends and accepted retries. It locks the task before its comment,
matching task and company deletion, comment removal and tombstoning,
rejects removed or tombstoned comments, repairs references and inserts a
missing activity record in one transaction, and publishes after commit.
- Remove reader-only record and comment-body size caps so accepted
browser writes remain readable, including JSON-escaped comment requests
in local and session storage. Update four existing Storybook fixtures to
use owned draft keys.
- Document the write contracts and add regression and real browser
recovery coverage.

- Add the exact reviewed-save recovery regression for both composer
implementations and reloads. Align receipt completion, both comment
deletion methods and company deletion with task deletion by locking
tasks first. Cover real task and company deletion races.

## Verification

- The exact reviewed-unknown-save regression fails in all four cases on
original commit `1ed0af4186`. It passes with this PR for both composers,
before and after reload. Cancel keeps the text and uploaded receipt. The
retained draft sends, and the next message also sends. Run `pnpm exec
vitest run --project @paperclipai/ui
ui/src/components/composer-recovery.test.tsx`.
- The new real PostgreSQL task-deletion race fails with SQLSTATE `40P01`
on parent commit `f3253a00c4`. The company-deletion race also fails with
`40P01` on `e8cf0e02dd`. All six receipt tests pass after the final
lock-order fixes. They cover company deletion, task deletion, comment
removal, tombstoning, concurrent cross-task references and interrupted
reference repair. Run `pnpm exec vitest run --project
@paperclipai/server
server/src/__tests__/issue-comment-receipt-postgres.test.ts`.
- The full UI run passed 9,656 of 9,659 tests across 816 files. Three
cases failed under that run: two large-tree timeouts and one
plugin-panel assertion. All 67 tests in those two files passed in an
isolated rerun. These failures remain recorded; this does not claim a
clean full UI run.
- `pnpm -r typecheck`, `pnpm build`, token gates and map checks pass on
the final change. The local full repository test command was started,
then stopped when the delivery moved to this existing PR. Fresh PR CI
must provide the full-suite gate.
- A local Storybook walkthrough used the real rich editor. Cancel kept
the restored text, Send cleared it after the simulated save, and a new
draft enabled Send again. Storybook simulates submission; it is not
staging acceptance.
- Earlier verification on `f3253a00c4` recorded five browser journeys
for title saves, cached-task offline recovery, startup recovery,
accepted comment replay and session lookup failure. Those results remain
prior-head evidence. No new staging deployment is claimed.

- On `e8cf0e02dd`, all CI checks passed after one browser-shard rerun.
Its first failure copied page text instead of YAML in an unrelated
agent-configuration test. On final commit `35131d4380`, Greptile is 5/5
with no unresolved review threads. The first CI attempt has two failures
outside this diff: runner close-attachment suspension and
scheduled-retry teardown. The scheduled-retry file passes all 14 tests
in isolation; the isolated runner test still fails locally. The single
standard CI rerun passed both jobs, and the aggregate verification gate
passed. All CI checks are green on `35131d4380`; Apex is 5/5 on that
same commit with no unresolved findings.

## Risks

- Automatic replay requires server duplicate prevention or result
verification. Uncertain combined mutations require receipt observation
or cancel and a fresh intentional send.
- Old unowned form drafts remain stored but are not assigned to an
account. Unowned channel records can be retired after Activity
inspection; this never cancels an accepted remote update.
- Browser storage and hashing can be unavailable. Storage failure is
reported honestly. Without a digest, replay can duplicate an upload
rather than silently drop a selected file.
- Detached autosaves remain bounded and check account ownership on each
attempt. Conflicts or exhaustion retain the draft for explicit recovery.
- No schema, credential or agent permission change is included. This PR
does not claim staging deployment or original-task acceptance.

## Model Used

Anthropic Claude Opus 5.5 (`claude-opus-5-5`) produced the original
implementation with tool use. OpenAI Codex, GPT-6 family, assisted with
restoration, integration, verification and review fixes. This Codex
session does not expose its exact serving model ID or 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: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Amy (Opus) <claude@users.noreply.github.com>
Co-authored-by: Dotta <bippadotta@protonmail.com>
2026-10-28 10:52:06 -07:00
Nicky LeachandPaperclip a2fbce9305 Fix plugin session and directory reuse on follow-up turns (#18045)
## Thinking Path

> - Paperclip preserves task state when agents receive follow-up work.
> - Plugin computers keep their process state outside the controller.
> - A local receipt proves that a previous plugin run suspended.
> - A cold resume left that receipt in place after the session became
live.
> - The next warm follow-up rejected the stale receipt as an identity
mismatch.
> - A separate follow-up path also treated a fresh task directory as a
Git worktree.
> - This PR consumes the obsolete receipt after admission and preserves
the bound directory on follow-up.

## Linked Issues or Issue Description

Related: #17820. This change retains the controller restoration added by
#18018.

**What happened?**

A plugin session resumed from a suspended checkpoint and completed a
turn. Its next warm follow-up failed with
`runner_state_identity_mismatch:
prior_owner_terminal_state_indeterminate`. The journal had the completed
run's identity. The local suspension receipt still had the preceding
run's identity. Two separate task histories showed this sequence.

After a fresh retry completed in a repository-free plugin directory, an
ordinary follow-up could instead fail with `The selected plugin
environment does not support Core Git worktree preparation.` The saved
task settings contained only `mode: isolated_workspace`, which
introduced the default Git strategy on the next admission.

**Expected behavior**

Keep the same admitted provider session during warm follow-ups. Reuse
the saved plugin task directory without Core Git preparation. Retain
ownership checks and explicit strategy settings.

**Steps to reproduce**

1. Complete a warm plugin task and let its session suspend.
2. Resume the checkpoint and complete another turn.
3. Send a follow-up while that session remains warm.
4. Separately, complete a fresh retry in a repository-free plugin
directory and send an ordinary follow-up.

**Paperclip version or commit**

Both regressions reproduce against base `820c45846` with the added
tests.

**Deployment mode**

Hosted plugin execution. Local reproduction uses the real filesystem and
a disposable PostgreSQL 18 database, with synthetic provider execution.

## What Changed

- Remove the local plugin suspension receipt after provider recovery and
durable run admission publish a live session. Admission still checks the
receipt first. Normal suspension writes a new receipt.
- Recognize a saved fresh plugin directory through its company, task,
workspace, owner, attempt and path. Use the existing directory-selection
path. Explicit strategy settings still apply.
- Add cold-to-warm, database-backed workspace-selection and ownership
regressions. Update execution semantics and session verification
recipes.

## Verification

- Red: the cold-to-warm regression failed on unchanged executor code
with `prior_owner_terminal_state_indeterminate` on the follow-up.
- Red: the PostgreSQL regression selected a Git strategy on unchanged
environment-selection code. The explicit-strategy denial case already
passed.
- Green: all 95 tests in `workspace-preparation.test.ts` and
`provider-fresh-workspace.test.ts` pass against a disposable local
PostgreSQL 18 database, selected with the existing
`PAPERCLIP_WORKSPACE_PREPARATION_TEST_DATABASE_URL` test seam.
- Green: 92 focused executor cases pass, including plugin checkpoint
recovery, warm rotation and denial cases. The full
`plugin-runner-task.test.ts` suite also passed (38 tests).
- Green: direct server check, `node node_modules/typescript/bin/tsc -p
server/tsconfig.json --noEmit`.
- Green: `node scripts/check-maps.mjs`, `git diff --check`, and a local
diff scan for secrets, personal data and live identifiers.
- Full local native suites: 988 of 1,004 cases passed. Sixteen
integration cases could not start their bundled PostgreSQL cluster. The
failure persisted outside the sandbox. These cases are not claimed as
passing. An earlier sandboxed attempt also denied process and loopback
operations; those denials disappeared when run outside the sandbox.
- The first broad local commands could not locate Cargo on `PATH`. Rust
is installed under `~/.rustup`; its Cargo executable was verified. Per
the requested scope, subsequent local verification stays targeted to
changed TypeScript paths; no Rust source changed. CI Typecheck + Release
Registry and Rust verification passed on the initial commit. The
complete repository test suite was not run locally.
- Review regression: an explicit agent-level Git strategy reproduced the
incorrect directory fallback before correction. After including the raw
agent strategy in the existing check, all three targeted cases
(implicit, task-level explicit, agent-level explicit) pass. The server
TypeScript check passes after this correction.
- CI on `a81668c4b`: the first workspace-a 2/2 attempt failed in
unchanged UI `AgentActionButtons.test.tsx` (`calls clearError and
refreshes agent-related queries`, zero mock calls). [Original failed
job](https://github.com/paperclipai/paperclip/actions/runs/40717870938/job/122921463517).
That shard passed on `294c5dfc3`. The failure is retained here. The UI
shard passed on final commit `687000287`; no unrelated UI edits or local
UI suite runs were added.
- CI also exposed three existing local-directory recovery failures on
`a81668c4b`: the review correction applied the raw agent strategy guard
to local directories. [Original failed server
job](https://github.com/paperclipai/paperclip/actions/runs/40717870938/job/122921463229).
Narrowed that guard to adapter-managed directories, preserving local
recovery behavior. All 20 targeted cases (three plugin selection cases
and 17 local recovery scenarios) pass afterward, and server TypeScript
verification passes.
- Final commit `687000287d3339b7e15e35d95515b3c75c273d7a`: [hosted CI is
green](https://github.com/paperclipai/paperclip/actions/runs/40720169342),
including the corrected server shard, all other server/workspace shards,
Runner checks, typechecking and build. All 55 non-skipped PR checks
pass. Greptile scores this exact commit 5/5, with no unresolved review
threads. GitHub reports no merge conflicts.
- Pre-merge hosted acceptance was requested. The maintained deployment
CLI stopped during artifact discovery: no published private Cloud
composition exists for `687000287`. The current private build requires
canonical Core master readiness and standard-image provenance. The
Core-only branch preview omits the private computer plugin needed for
the journey. No campaign or tenant update was started; private-preview
deployment support is a separate prerequisite. No live deployment or
provider acceptance run is claimed.

## Risks

The receipt is removed only after the existing runtime publishes an
admitted session. Earlier admission failures keep their proof. A later
normal suspension creates a new receipt. The change preserves existing
identity, lifecycle and controller checks.

Directory selection remains limited to the exact bound, active,
repository-free plugin recovery directory. Foreign owners, changed
paths, wrong attempts and explicit Git strategies do not gain this
fallback. No schema, API, credential, permission or fleet-default change
is required.

Existing failed runs and recovery holds remain history. This PR does not
edit quarantined state or replay an interrupted task. Rollback restores
the previous code and can reintroduce the two admission failures.

## Model Used

OpenAI GPT-6 through Codex, with reasoning, tool use and code execution.
A more specific model ID and context-window size are not exposed in this
session.

## 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-10-28 10:26:12 -07:00
DottaandPaperclip b14e1ecaf8 feat: add a complete agent YAML configuration editor (#18036)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/175/changes/paperclip/175
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Operators configure each agent through several settings tabs.
> - Operators also need one complete, editable configuration document.
> - The document must retain each resource service's access and
validation rules.
> - This pull request defines the `paperclip/v1` Agent YAML format and
adds an Advanced editor.
> - The editor previews changes, rejects stale core writes, and explains
partial saves.
> - Operators can edit agent settings in one place and verify the saved
state after reload.

## Linked Issues or Issue Description

Refs #2219. Related settings work: #10974.

**Problem or motivation**

Agent configuration spans profile, runtime, instructions, skills, tools,
channels, permissions, secrets, keys, and revision history. Operators
cannot inspect and edit those settings as one versioned YAML document.

**Proposed solution**

Add an Advanced agent tab with a YAML editor. Define a shared document
schema. Read and write resources through their existing APIs. Separate
editable settings, explicit commands, and read-only observed state.

**Alternatives considered**

A raw agent-row editor would omit related resources. A generic database
update would bypass resource ownership. The editor therefore uses the
existing resource contracts and records partial results when a later
request fails.

**Roadmap alignment**

This extends the shipped agent configuration capability. It relates to
easy AGENTS.md configuration, multi-harness teams, governed tool access,
and secrets management. Stored credentials remain redacted. This format
is an editable settings view; it does not add company portability or
provider consent.

## What Changed

- Add the `paperclip/v1` Agent document schema and format documentation.
- Add the Advanced route, sidebar entry, YAML editor, validation, change
summary, save progress, and reload recovery.
- Cover core settings, instruction files, skill pins, tool
installs/profiles/policies, channels, permissions, secret operations,
API keys, and revision restore.
- Add private-keyed configuration revisions checked under the agent
write lock. Read the current key through its owner so file-based
rotation does not require restarting the server. Preserve unchanged
secret markers at their original paths.
- Retain drafts and returned credentials after partial saves. Require
reload before retrying commands. Prevent duplicate submissions. Keep new
key tokens visible through rename and disable saves with an empty change
plan.
- Send only changed channel settings. Require explicit intent for shared
profile edits. Load destination instruction files when changing their
location.
- Update Storybook fixtures, verification maps, and regression tests.
Add browser acceptance through real APIs and PostgreSQL.

## Verification

- `pnpm -r typecheck` passes.
- `pnpm build` passes.
- The focused UI suite passes all 50 tests. The API/revision helper
suites pass all 93 tests.
- All 65 lifecycle tests pass with a dedicated PostgreSQL database. They
exercise real row locks, redaction, revision history, audit, and company
access.
- All six browser acceptance cases pass. They check saved settings and
clears, secret redaction, key creation/revocation, stale drafts,
lost-response recovery, instruction relocation, revision restore, and
key-token retention through rename. The tests use real resource APIs and
storage. The MCP target uses the existing local provider fixture. No
model run or provider login is claimed.
- Signing-key regressions cover both environment changes and real
in-place key-file rotation. The protected database save/fencing cases
pass after removing the cache. A local measurement of 1,000 file-backed
revision calculations took 48 ms.
- `pnpm check:token-gates`, `node scripts/check-maps.mjs`, and Storybook
catalog checks pass.
- The full [PR CI
run](https://github.com/paperclipai/paperclip/actions/runs/40725425470)
passes on `34ed97bbf9`: all 48 jobs, including all eight browser shards.
Greptile is 5/5 on this commit, with no unresolved review threads. This
final commit refreshes CI after a runner-routing fallback; its source
tree matches `fb4cf488cf`.
- Paperclip Review and Superagent Security Scan ended neutral because
their external agents did not complete a valid assessment/receipt.
Superagent passed on `fb4cf488cf`, which has the identical source tree.
One request to retry the final scan returned HTTP 404. Neither check
reports a code finding.
- The local full-suite attempt was blocked by host System V semaphore
exhaustion. Acceptance and lifecycle verification used an isolated
PostgreSQL 18 container. Earlier CI runners were interrupted. A local
combined run hit hook/test timeouts; the full 88-test route file passed
after the builds finished. The final full CI run passes. Earlier failure
logs and browser traces remain retained outside the repository.

To run the browser regression:

```sh
pnpm exec playwright test --config tests/e2e/playwright.config.ts tests/e2e/agent-configuration.spec.ts
```

## Risks

- Multi-resource saves are sequential. Earlier operations can remain
saved if a later operation fails. The editor reports the completed steps
and requires reload.
- Core settings and managed instruction files have atomic revision/hash
checks. Other unversioned resource writes and external supporting files
retain a race window after preflight.
- Shared profile definitions affect other bindings. The editor requires
`updateSharedDefinition: true` for those edits.
- The editor follows native service normalization and experimental
settings. Canonical reload can add generated access profiles or mask
environment values.
- New editor dependencies require the repository's normal automated
lockfile update. This pull request does not edit the lockfile or add a
database migration.

## Model Used

OpenAI Codex, GPT-6 family. The exact current model version was not
exposed. The work used reasoning, repository tools, code execution, and
browser automation. Earlier work in this chat used the configured Codex
model before a model switch; its exact model ID and context window were
not exposed. The current context window size is also not exposed.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-28 11:49:24 -05:00
DottaandPaperclip 4808a3a2b1 fix(heartbeat): retry operator Stop after a transaction deadlock (#17895)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/69/changes/paperclip/69
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Operator Stop must revoke task authority before it stops provider
execution.
> - Its transaction locks the task and then the run. A concurrent writer
can hold the run while it waits for the task.
> - PostgreSQL can abort the Stop transaction with a confirmed deadlock.
The cancel API then returns 500.
> - This pull request retries only that aborted database transaction, at
most three times.
> - Provider Stop and activity publication stay after commit, so the
retry cannot repeat those effects.

## Linked Issues or Issue Description

Refs #17639. Its agent-chat project browser test completed the product
assertions, then failed during cleanup when the cancel API returned 500.
A real PostgreSQL lock-cycle test reproduces the same `40P01` error in
the Stop transaction.

Related: #13911 addresses audit foreign-key lock contention. This change
handles a different concurrent run-writer path without changing the
schema or task/run lock order.

Stack base: #17639. This is a separate correctness repair for the sleep
migration stack, not another polling migration.

## What Changed

- Control the runner timeout regression fixture's clock so it reaches
the pending append before expiry; retain production cancellation and
late-append assertions.

- Retry the Stop authority transaction only after PostgreSQL reports
`40P01`. Make at most three attempts, with short bounded backoff.
- Discard rolled-back local run state, claim flags, and queued activity
publications before each retry. Re-read current authority under fresh
locks.
- Keep provider cancellation and activity publication outside the
retried transaction. Preserve other errors and the existing native
lock-conflict response.
- Add a real two-transaction deadlock test. Add server-side failure
tests for retry exhaustion and errors that must not retry.
- Let run-control tests use a validated disposable PostgreSQL database
URL.

## Verification

Published head: `60ba892ae9fc5faaf8cd0833694b4a66c13323c3`, targeting
master after #17639 merged at
`1ed0af41867ba40fd1d23292d395588d18c2fcbe`. The normal ancestry merge
preserves the complete five-path tested cancellation patch
byte-for-byte, including the review repair, and all four unrelated
current master paths. The production retry logic remains unchanged from
this slice's reviewed implementation; the follow-up adds coverage and
its audit.

- **228 distinct complete cases pass:** all 48 run-control cases and all
180 native-session runtime cases. The two new targeted cases are
included in 48 and are not counted again. Server typechecking, build and
module-boundary checks also pass.
- The new real PostgreSQL cases reach a failed native run's correlated
Stop claim, cancellation fence, board handoff retirement and activity
write before raising `40P01`. One case preserves retry authority and
commits exactly one cancellation activity/live notice. The other changes
coordinator authority between attempts, returns 409, preserves the
failed run and handoff, and performs no provider/workspace cleanup.
- A negative control removes only the publication-list reset. It fails
with two live notices for one durable activity. Production was restored
byte-for-byte before final validation. The existing actual
two-connection deadlock, bounded attempts, non-deadlock rejection and
post-commit provider behavior remain covered.
- Preserve the initial new-assertion typecheck failure (optional
live-event payload) and the corrected final pass. Service-local test
files are typechecked; `src/__tests__` is excluded. The negative-control
harness initially expected an untruncated Vitest assertion line; the
actual named 1-versus-2 failure and restoration were inspected before
correcting its result matcher.
- [Current-parent acceptance and failure
ledger](https://github.com/paperclipai/paperclip/blob/60ba892ae9fc5faaf8cd0833694b4a66c13323c3/doc/plans/2026-10-28-cancellation-deadlock-acceptance.md)
records current scope, commands, isolated fixtures, mutation evidence
and limits. Earlier combined-stack counts retain their original revision
scope. The existing controlled runner timeout/late-append fixture is
retained and passes within the complete 180-case runtime suite.
- This addresses the prior Ponytail request to exercise native claimed
state before deadlock rollback and re-evaluate authority afterward. The
advisory loop-invariant snapshot/named-attempt-bound note remains a
maintainability suggestion, not a runtime defect. No production loop
refactor or new worker duty is introduced.
- **All 58 current checks are clean; Greptile and Ponytail both rate
this exact head 5/5.** Ponytail explicitly confirms that the
native-claim coverage request is resolved and says Ship. The formerly
queued dependency/quality review workflow has completed successfully.
Old `fffc`/parent checks and reviews are not current passes; the former
pending Snyk status is not called successful. Actual failing Ponytail
findings must be fixed. Missing/stopped/paused turns without a verdict
are authorized nonblockers. Active unfinished reviews retain their
original per-head timer, with a 25-minute monitor cutoff respecting the
30-minute maximum.
- No full local repository matrix, live provider execution, external
alarm, physical host/database suspension or savings claim is made. No
schema, dependency, workflow, shared scheduler contract or shared OS
resource changes are introduced.

## Risks

- Persistent contention still returns an error after the third attempt.
This change does not promise to eliminate every possible lock cycle.
- Retrying a write after an ambiguous connection failure would be
unsafe. The retry accepts only PostgreSQL's confirmed deadlock abort
code; it does not accept transport errors.
- No schema or public API contract changes. Current task/run authority
and cancellation eligibility are checked again on each attempt.

## Model Used

OpenAI GPT-6 via Codex, with shell, GitHub CLI, TypeScript, PostgreSQL,
and Playwright tools. The exact serving model ID and context window are
not exposed in this session.

## 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-10-28 11:46:58 -05:00
DottaandPaperclip 567c043b17 feat(server): expose bounded hot-upgrade readiness (#18037)
## Thinking Path

> - Paperclip coordinates agent work and keeps its authority in the
server.
> - Remote native runners can preserve execution through a server
replacement.
> - Deployment operators need evidence that current runs support that
recovery.
> - Process-local drain counters do not establish this fact.
> - This PR adds an optional, operator-only readiness observation from
existing records.
> - A deployment consumer can use that report while the existing runtime
retains recovery authority.

## Linked Issues or Issue Description

Refs #17439.

**What happened?**

A deployment cannot distinguish recoverable remote native executions
from runs that require a task drain. The existing status endpoint
reports only process-local counts.

**Expected behavior**

An instance operator can request a bounded readiness report without
stopping admission or exposing checkpoint material. Missing ownership or
persistence evidence must prevent readiness. Ordinary status reads must
keep their current cost.

**Steps to reproduce**

Run a remote native task. Read the task-drain status. It reports active
work but supplies no recovery eligibility. Deployment code therefore has
no affirmative signal to select an active-run handover.

## What Changed

- Add `GET /api/instance/task-drain?upgradeReadiness=1` for instance
administrators and existing Cloud control callers.
- Return aggregate eligibility from current run identities, controller
leases and bound opaque checkpoint headers. Unknown work, pending
admission and incomplete reads prevent a positive report.
- Bound the explicit read to 1,001 rows, encrypted headers of at most
256 KiB each and 8 MiB total, and a two-second SQL statement timeout in
a read-only transaction. Keep ordinary status reads in memory.
- Add PostgreSQL, count-transition and route authorization tests. Update
the API contract, operator docs and access maps.

## Verification

- All seven readiness cases pass against an isolated PostgreSQL 18
fixture. They cover missing checkpoints, legacy adapters, missing
process/session identities, foreign owners, expired leases, missing
lease tokens, failure state and in-flight work. The positive SQL fixture
uses the real Runner checkpoint writer and encryption. Regular sandbox
workspace identity and plugin environment-lease identity are tested with
independent IDs. Stopped/released/undispatched plugin tasks and every
mismatched identity field are rejected. Local/legacy/malformed/oversized
or mismatched headers are rejected. A held PostgreSQL table lock proves
the two-second cancellation budget, rollback/connection release and
unrelated query responsiveness.
- All 123 focused readiness, instance-settings and Cloud control
assertion tests pass, including operator-only access and no readiness
read on ordinary status requests. Runner’s 168 checkpoint tests pass.
Runner and server typechecks pass after review fixes.
- Workspace typecheck, full build, module-boundary and map checks passed
locally before the master rebase. Current-head GitHub CI is now green,
including typecheck, build, all grouped/serialized server and Runner
tests, browser shards, policy and review-dispatch checks. Greptile
completed cleanly at 5/5 for `f15fb0c7e9dfb975090cd5d791a1c8e6701275f8`;
all actionable threads are resolved.
- The broad local test run was stopped after the macOS embedded
PostgreSQL fixture failed to bootstrap. The SQL test was then run on the
isolated PostgreSQL fixture. No assertion or timeout was weakened. One
unrelated existing route test exceeded its 15-second limit under
concurrent local builds; it passed on one isolated retry and the
subsequent whole route suite passed.
- Hosted active-run upgrade acceptance has not run. This PR supplies an
observation; it does not change rollout policy or establish live
continuity by itself.

## Risks

This is an instance-wide observation, so company members and agent keys
must not receive it. A readiness snapshot can age as work changes;
shutdown and startup retain their existing execution authority and
fencing. The report does not validate a replacement artifact or
authorize a schema migration. It decrypts only bounded headers through
the checkpoint owner and delegates format/identity inspection to Runner;
full journal restoration and physical sandbox authentication remain with
recovery. No migration, recurring query, new checkpoint write or wire
protocol change is included. The additive Runner header inspection
contract reuses its existing parser.

## Model Used

OpenAI Codex, based on GPT-6, with reasoning, source inspection, tool
use and code execution. The host does not expose the exact serving model
ID or 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 and contains no internal
Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass for the affected contracts;
the broad-run limitation is recorded above
- [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-10-28 11:28:15 -05:00
DottaandPaperclip 1ed0af4186 fix(server): wake native chat progress from committed changes (#17639)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Chat users receive coarse progress updates while native runs
execute.
> - A recurring chat pass scans saved run events even when no progress
changes.
> - This traffic prevents an idle database from staying idle.
> - Events, lineage changes, and publication state already identify when
projection can change.
> - This PR gives native progress its own commit-driven worker and
schedules only unfinished work.
> - Idle progress stops scanning while restart and recovery preserve
delivery.

## Linked Issues or Issue Description

Refs #17606. This is slice 29 of the recurring-server-work stack, based
on `codex/sleep-28-chat-run-milestones`. It owns native chat progress
only. Related historical optimization: #16845. The parent and this PR
must land in stack order.

**What happened?**

Native chat progress is still called by the one-second chat
reconciliation loop. It repeatedly selects run events with no new work.
Its cursor also truncates PostgreSQL timestamp precision, which can
repeat a rejected full page forever.

**Expected behavior**

Committed events and eligibility changes should wake the projection
owner. Existing rows should reconstruct work after restart. A settled
worker should have no recurring database activity. Full batches, lock
contention, and errors must retain recovery.

**Steps to reproduce**

Start an otherwise idle instance with chat history. Observe the native
progress lane in the recurring chat coordinator. For the cursor defect,
create a full page of suppressed candidates sharing a microsecond
timestamp and one eligible later candidate. The old cursor fails to
advance.

## What Changed

- Extract native progress from lifecycle milestones into its owning
service. Keep the public combined API and budget compatible.
- Register a scoped worker with the existing delivery coordinator and
scheduler. Remove native progress from the recurring chat coordinator.
- Notify before allowlisted event writes in both persistence owners.
Preserve outer commit, rollback, duplicate detection, and the ordinary
non-progress log fast path.
- Extend the existing lineage/authority notification boundary once.
Failed-publication replay and operator retry carry their issue scope.
First working publications signal progress so commit ordering cannot
strand an already-inspected event.
- Limit notification payloads to company/task IDs so wider caller inputs
never serialize database handles or private fields. Load task-binding
fields only for progress event kinds; other native/recovery events
retain their narrow lock query.
- Preserve current safe phrases, cadence, phase deduplication, provider
policy, authorization, and final-output precedence.
- Retry concrete issue/run lock contention. Disarm deleted or terminal
candidates. Preserve scoped dirty work across batches, failures, drain
and shutdown.
- Preserve PostgreSQL timestamp precision in pagination. Add a bounded
regression for the former infinite rejected-page scan.
- Document the producer audit, lifecycle contract, failures, and
remaining limits in
`doc/plans/2026-10-25-native-chat-progress-sleep-audit.md`.

## Verification

Published head: `b7ee820e49fd06c780b36b79d9b1c0883557fb73`, targeting
master after #17606 merged at
`5f0da562dbfdf3229f3cd4bb3dc742ab541986b4`. A normal ancestry merge
preserves the complete 18-path native-progress patch byte-for-byte
relative to its verified parent, with all six unrelated current master
paths intact. No new production change was introduced during final
reconciliation.

- **163 distinct selected cases pass on the verified unchanged patch:**
137 across eight complete suites (native progress, atomic event append,
all five milestone worker suites, and app admission wiring), plus 26
real chat integration cases selected by `native progress`. The other
1,595 chat integration cases were skipped, not passed.
- The full worker suites cover restart, committed events, trace
reprojection, duplicate/no-progress events, first-working publication
ordering, concrete lock contention, issue scope, backlog, drain/resume,
failures and shutdown. Settled history leaves no recurring SQL. The real
chat cases verify operator retry and replay, microsecond pagination,
authority, cadence, phase deduplication, final/question precedence and
redaction.
- The sole earlier parent conflict preserves both this slice's
issue-scoped retry wake and the exact voice conversation scope. The
current parent's milestone producers, onboarding completion guard,
identity query/read-scope coverage, migration 0397 and voice
cleanup/retention repairs remain present.
- Server production typechecking, build and module-boundary checks pass.
The selected server tests live under the excluded `src/__tests__` path
and were executed separately. Each database owner uses a new isolated
app-migrated PostgreSQL fixture.
- [Current-parent acceptance and failure
ledger](https://github.com/paperclipai/paperclip/blob/b7ee820e49fd06c780b36b79d9b1c0883557fb73/doc/plans/2026-10-25-native-chat-progress-sleep-audit.md#current-milestone-parent-acceptance-october-28)
records current counts and scope. Older combined checks and failures
retain their original revision scope and are not added to 163. No new
table, dependency, workflow, migration, or scheduler contract is
introduced.
- **Exact-head Greptile is 5/5 and all 55 current checks are clean.** No
Ponytail review is present, which is an explicitly authorized
nonblocker; no failing verdict is waived. Older head/parent reviews are
not current passes. Actual failing Ponytail findings must be fixed.
Missing/stopped/paused turns without a verdict are authorized
nonblockers; active unfinished reviews retain the original per-head
timer with a 25-minute monitor cutoff respecting the 30-minute maximum.
- No complete local repository matrix, live provider tenant, external
wake, physical host/database suspension or savings claim is made.
Following stack duties remain separate.

## Risks

- Signals are process-local under the existing single active writer
contract. Independent SQL writers or another active process need an
explicit wake integration.
- Allowlisted direct log writes now use a transaction. Native bound runs
register transaction intent; unrelated direct event types retain their
atomic-statement path.
- The shared eligibility boundary wakes both lifecycle and native
projection. It does not decide provider policy or copy event payloads.
- The existing 24-hour selection window, event-time cadence and
authority checks remain. A suppressed event is not retried just because
wall-clock time passes.
- This establishes worker quiet, not whole-instance suspension. Cloud
alarm coverage and conservative sleep gates do not change. Other chat
maintenance remains on its existing cadence.
- This actual-master reconciliation still requires fresh exact-head
review and CI before protected merge. Subsequent slices retain their own
gates.

## Model Used

OpenAI Codex, GPT-6 family, with repository inspection, code execution
and browser-test tools. The exact serving variant and context-window
size are not exposed in this session.

## 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-10-28 11:22:29 -05:00
DottaandPaperclip 0791da0cc5 fix(server): synchronize routine history during native status commit (#18033)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/173/changes/paperclip/173
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip manages work assigned to AI agents.
> - A routine stores each invocation and its execution task.
> - Native completion commits task status without using the public issue
route.
> - That route synchronizes routine history, but the native status
transaction did not.
> - A successful task could remain listed as an unfinished routine
invocation on a local instance.
> - This pull request uses the existing database projection in the
native status transaction.
> - Task status and routine history now commit or roll back together.

## Linked Issues or Issue Description

**What happened?**

A real routine execution completed successfully. Its task had status
`done` and retained its routine origin and invocation identity. Public
routine history still returned `issue_created`, with `completedAt: null`
and a linked task whose status was `done`. The existing five-minute
reconciliation runs only on cloud-managed instances. It does not close
this path for a local instance.

**Expected behavior**

An authoritative native task status change must update the matching
routine invocation through the existing routine status rules. It must
not update another task, routine or company.

**Steps to reproduce**

1. Create a routine on a local instance and run it through the public
routine API.
2. Let its native execution finish and commit the task as done.
3. Read the routine run history. Before this change, the invocation can
remain `issue_created` while its linked task is done.

**Paperclip version or commit**

The retained failure used merged production `39e811c9c5`. The missing
hook is also present on this branch's base, `8049fbf51d`.

Related: #16633 contains the existing cloud-only reconciliation. A
bounded search found no duplicate native synchronization fix.

## What Changed

- Synchronize routine history inside the native status transaction after
the task status projection.
- Require matching company, invocation and linked task before
synchronization. Preserve supported custom display origins.
- Add database-backed tests for terminal and active states, replay,
invalid custody, rollback and a real plugin-managed routine dispatch
with a custom origin.
- Keep the routine status projection in a database-only helper. Both the
routine service and native status committer use it without loading
heartbeat execution from the committer.

## Verification

- Own-source server TypeScript check passed after the helper extraction.
It includes the new test source and production dependencies. Local
package exports point at another checkout, so the check used explicit
paths to this checkout's source and disabled declaration emit.
- Existing pure `status-arbiter.test.ts`: 20 tests passed. `git diff
--check` passed.
- Initial required CI run 40711603938 built and typechecked
successfully. It executed all ten new database tests: nine passed; the
public-dispatch fixture failed because it assumed status version zero.
The fixture now reads the saved version and decision binding.
- That CI run also exposed a heartbeat mock dependency cycle. The
database-only helper removes the
committer-to-routine-service-to-heartbeat import. Required CI on the new
head must confirm both repairs.
- Initial browser shard 3/8 failed during cleanup: legacy run
cancellation waited for a heartbeat row lock. Its cause is under
investigation; the failure remains recorded.
- A local runtime-execution check failed during module import from stale
package exports, before any tests or database setup ran. It is not
passing evidence. No local database, provider or live eval was run.
- Latest-head required CI run 40717315212 executed all ten new database
tests successfully in server shard 5/12 (2,163 passed; three unrelated
skips). The heartbeat runtime suite executed 23 tests successfully in
server shard 9/12 (1,704 passed).
- Latest-head browser shard 3/8 passed all 33 tests. This does not
establish the cause of the preserved earlier cleanup lock timeout.
- Required CI run 40717315212 completed successfully on head
`2d77f4302b36303741abad07266bbe9e376ba6a5`. All 48 workflow jobs are
green after one failed-jobs-only infrastructure retry. The first attempt
had seven explicit runner shutdowns and three lost-runner communication
failures. The exact chat shard host was independently confirmed as an
AWS Spot termination. Original logs and annotations remain retained.
- Greptile completed at 5/5 on this exact head, with no outstanding
findings. All review threads are resolved. The independent follow-up
review found no issues.
- No live qualification or corrected eval pass is claimed. The PR
remains open and unmerged, with auto-merge off.

## Risks

- Matching routine executions perform the existing bounded status
synchronization queries inside the status transaction. A database
failure rolls back both projections.
- Inconsistent invocation or linked-task metadata now prevents
synchronization. No unrelated invocation is inferred or repaired.
- The existing scheduled repair remains unchanged. This PR does not
change accounting, provider behavior or eval budgets.

## Model Used

- OpenAI `gpt-6.1-sol`, with reasoning and tool-assisted source
inspection and coding. The session did not supply a 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 references)
- [x] My branch name describes the change and contains no internal
ticket id or instance-derived details
- [x] I have run relevant credential-free tests locally and they pass;
database coverage is pending CI
- [x] I have added or updated tests where applicable
- [x] I have checked documentation; the existing routine status contract
is unchanged
- [x] I have considered and documented 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-10-28 11:09:49 -05:00
DottaandPaperclip 5f0da562db fix(server): wake chat lifecycle milestones from committed changes (#17606)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Connected chats show safe notices when a run starts, waits,
finishes, or fails.
> - A recurring scan projected these notices even when no eligible work
existed.
> - Eligibility depends on committed run state, conversation lineage,
and current authority.
> - Existing database rows can reconstruct that work after restart.
> - This PR wakes a scoped worker from those writes and removes
lifecycle polling.
> - Native progress events keep their separate existing owner until the
next migration.

## Linked Issues or Issue Description

**What happened?**

The chat maintenance timer repeatedly scanned run lifecycle state. Empty
and settled instances still queried the database. A run-status event
alone cannot replace the scan: prompt receipts, continuation receipts,
identity changes, and restored authority can make a run eligible later.

**What did you expect?**

Committed changes wake projection. Startup reconstructs eligible work. A
completed pass stops until another relevant change arrives. Failed work
retains recovery without scanning settled history forever.

**Steps to reproduce**

Configure an automatic chat endpoint. Finish its work, or leave it
unused. Observe recurring lifecycle projection queries from the chat
maintenance callback.

Stacked on #17592. Related foundation: #15625. This PR owns lifecycle
milestones only.

## What Changed

- Preserve upstream coalesced Cloud membership writes together with
locked membership restoration and its committed chat notification.

- Signal milestone eligibility from the real Slack account-link
transaction.

- Register the lifecycle worker with the existing delivery coordinator.
Remove lifecycle projection from the periodic chat callback. Keep native
progress in a separately named lane and preserve the explicit combined
API.
- Reconstruct company/issue scopes from the existing selector. Drain
bounded batches with company fairness. Retry failures, retain writes
through drain/resume, and disarm settled work.
- Signal from supported run, presentation, interaction, receipt,
lineage, conversation, recovery, and authority writers. Preserve their
transaction ownership, including nested savepoints and uncertain
settlement. No new table is added.
- Preserve provider authorization, authored-final suppression,
responsible-user continuity, deduplication, the 24-hour selection
window, and raw-output restrictions. Keep provider interpretation in its
owner.
- Preserve PostgreSQL timestamp precision in lifecycle pagination.
Rejected submillisecond candidates must not repeat the same page and
starve later notices.
- Document producer coverage and alternate-writer dispositions in
`doc/plans/2026-10-25-chat-run-milestone-sleep-audit.md`.

## Verification

Published head: `1d056f68c5b1005933b9e12de8745bf1c4cbeeca`, targeting
master after #17592 merged at
`7d75ae0569e41786640cf09647ae8849411d2f22`. A normal merge integrates
the actual landed parent. The entire 77-path milestone patch is
binary-identical to the locally verified preparation across that
ancestry reconciliation; both unrelated master paths are preserved. The
four earlier producer/test integration conflicts retain scoped milestone
and voice notices, current onboarding completion admission, and expanded
identity query/read-scope coverage.

- **330 distinct selected cases pass on the verified unchanged patch:**
305 across 14 complete suites (all five milestone worker suites, run
identity, board claim, Cloud provisioning, auth session routes, Cloud
actor authentication, stale-lock recovery, GitHub credentials, project
Git authorization, and app admission wiring), plus 25 selected real chat
producer cases. The remaining 1,590 chat integration cases were skipped,
not passed.
- The real producer cases cover saved milestone discovery, GitHub and
Slack identity changes, account-link rollback/reconfirmation, ordinary
ingress reactivation, post-close action/delivery receipt settlement, all
ten authority-restoration paths including Cloud synchronization, and
changed native review metadata.
- Worker coverage verifies outer commit, rollback, uncertain-write
recovery, restart, bounded batching/fairness, timestamp precision,
retries, drain/resume, and settled SQL quiet. Authorization and existing
publication deduplication remain with their owning services.
- Server production typechecking, build, and module-boundary checks
pass. The tests above were executed separately. Production typechecking
excludes `src/__tests__` and does not replace those runs. Each database
owner uses its own newly created and app-migrated PostgreSQL fixture.
- [Current-parent acceptance and preserved failure
ledger](https://github.com/paperclipai/paperclip/blob/1d056f68c5b1005933b9e12de8745bf1c4cbeeca/doc/plans/2026-10-25-chat-run-milestone-sleep-audit.md#current-parent-integration-and-acceptance-october-28)
records commands, counts, producer scope, conflict dispositions, and
limits. Earlier combined-stack counts and failures keep their original
revision scope; local acceptance does not erase old CI failures.
- No new migration, queue table, dependency, workflow, or shared
scheduler contract is introduced. Parent migration 0397, bounded consent
recovery, voice cleanup/retention repairs, and runner checkpoint
restoration remain present.
- **Exact-head Greptile is 5/5 and all 55 current checks are clean.** No
Ponytail review is present, which is an explicitly authorized
nonblocker; no failing review is waived. Older reviews and parent checks
are not current passes. Actual failing Ponytail findings must be fixed;
an absent/stopped/paused turn without a verdict is an authorized
nonblocker. Active unfinished Ponytail uses its original request/start
timer, with a 25-minute monitor cutoff respecting the user's 30-minute
maximum.
- No complete local repository matrix, live provider tenant, external
alarm, physical host/database suspension, or fleet savings claim is
made. Native progress remains a separate following slice.

## Risks

- A future eligibility writer must notify the existing projection
boundary. Independent SQL writers or another active server process are
outside this process-local signal contract.
- Authority and lineage remain sensitive. The worker uses the existing
selectors and publication policy; it does not grant execution or
disclosure authority.
- Native progress and other publication maintenance still have recurring
work. This PR removes one reason, not the entire chat maintenance timer.
- Worker quiet does not prove database suspension, host sleep, or
external alarm coverage. Cloud sleep blockers remain unchanged.
- Merge eligibility requires passing current-head CI and Greptile 5/5
after this actual-master reconciliation. Subsequent stack slices retain
their own gates.

## Model Used

OpenAI Codex, GPT-6 family. The exact serving model ID and
context-window size are not exposed. Used repository inspection,
reasoning, shell execution, PostgreSQL tests, browser E2Es and GitHub
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 available in this session)
- [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 the documented focused 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-10-28 11:07:54 -05:00
DottaandPaperclip 143d20e466 fix(server): retain native Codex Plan write boundaries (#18034)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Native Codex task chat keeps a saved Plan inside the turn that wrote
it.
> - The compact conversation API omits ordinary tool history.
> - That omission also removes the write receipt needed to place the
Plan.
> - This pull request retains a small successful write receipt in
conversation reads.
> - The UI can then keep the saved Plan at its write boundary after
readback.

## Linked Issues or Issue Description

**What happened?**

A real native Codex Product E2E attempt saved its Plan and displayed it
inside a settled turn. The Plan used the fallback position. The
browser's final conversation-only API response contained no
`write_document` receipt. The full event snapshot retained the
successful write. The native placement assertion failed and remains
failed in the original report.

**Expected behavior**

Conversation readback must retain enough evidence to place the saved
Plan at its successful write boundary. It must keep arbitrary tool
bodies and ordinary tool history out of the compact response.

**Steps to reproduce**

1. Save a canonical Plan through a native `write_document` call.
2. Read the run with `view=conversation`.
3. Before this fix, the response omits the write receipt and the UI
places the Plan at the end-of-turn fallback.

Related eval evidence repair: Refs #18026. This is a separate product
readback fix. It does not resolve the failed human-input call or the
Claude tool-availability failure from those attempts.

## What Changed

- Include only successful canonical `plan` document results, matched to
a native `write_document` call in the same run, turn, session and source
instance. Ordinary document writes stay excluded.
- Build the small receipt inside PostgreSQL before its body crosses the
database connection. Preserve only fixed event metadata, tool identity,
the `plan` key and mutation disposition. Keep the existing payload
decoder for ordinary conversation events.
- Keep cursor paging, run scope, ordinary-tool exclusion, and full event
reads unchanged.
- Document the compact read contract in OpenAPI.
- Scope this fix to the canonical native dynamic-tool call/result pair
used by Codex. The retained Claude sample proves compatibility with that
captured shape. It does not qualify every current ACPX Claude producer.
Provider-activity-only paths and OpenCode keep the explicit fallback.

## Verification

- Real PostgreSQL red: the new boundary test fails because the first
selected event is assistant text rather than the saved write. The six
existing tests pass.
- Real PostgreSQL/API green: 36 tests pass across task cold-open and
OpenAPI routes on an isolated Linux current-master checkout.
- UI: 104 transcript tests pass, including completed native placement
from the body-free receipt.
- Review regression red: a later notes write incorrectly enters
conversation readback (one failure, six passes). After the fix, the
PostgreSQL/API suite passes all 36 tests.
- Fixed the new UI fixture's string-to-Date type mismatch found by
hosted CI. Original failed CI remains visible; fresh exact-head checks
are pending.
- Existing token/style gates pass.
- Retained native Codex and Claude fixture shapes both pass. Each
fixture includes the canonical item pair and parallel provider
`tool.execution.*` activity. All identifiers and document bodies in the
fixtures are synthetic. This captured-shape test is historical readback
compatibility, not fresh current-source Claude acceptance. The Codex
canonical pair is emitted by
`packages/paperclip-runner/src/drivers/codex/codex-session-server-requests.ts`
in the admitted dynamic-tool handler.
- Projection-collision regression red: a non-Plan result selected by
conversation identity was relabeled as a Plan. The SQL projection now
uses the same full Plan predicate as selection. The regression and both
native fixtures pass.
- The database test checks cursor paging, a Plan followed by notes,
failed/read/control-plane/unrelated-turn exclusion, schema and ID
bounds, omission of a large tool body, unchanged full-history reads, and
ordinary conversation payloads containing NUL.
- Local server typecheck fails on 80 installed workspace export
mismatches outside changed paths. No changed-path type error or local
full build pass is claimed. Clean hosted checks must pass before merge.
- Current-head hosted CI and legacy status pass. One failed-check retry
followed recorded runner shutdowns and an unrelated native-distribution
timeout; that test passed all 33 cases locally. Original failed logs
remain retained.
- Zero provider calls or paid attempt retries. Original failures and
accounting journals remain unchanged. This is not a new live
qualification result.

## Risks

- Conversation pages include matching Plan results within the existing
1,000-row page limit. The query adds a run-scoped match against
canonical tool calls and projects results inside SQL. PostgreSQL still
reads the stored JSON to select receipts; private bodies are not
transferred to the application. It adds no separate database round trip
or background work.
- Matching requires the existing canonical call/result identities.
Missing or malformed historical receipts keep the explicit fallback.
This fixes compact conversation readback; it does not redesign placement
in an unrelated full-history multi-document UI flow.
- This restores the existing UI write-boundary mechanism. It does not
change Plan acceptance, permissions, or completion rules.

## Model Used

- OpenAI Codex, GPT-6, with reasoning and code execution tools. The
exact serving variant and context window are not exposed in this
session.

## 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-10-28 11:06:05 -05:00
DottaandPaperclip 7d75ae0569 fix(server): recover Teams attempts from saved claim deadlines (#17592)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Teams file delivery saves a claim before each provider operation.
> - A crashed operation can leave that claim unfinished.
> - Periodic maintenance scans for abandoned claims even when none
exist.
> - This PR wakes recovery from committed changes and the saved claim
deadline.
> - Empty work becomes quiet while unknown effects remain safe to
review.

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Teams abandoned file-transfer recovery. This is slice 27, stacked on
consent expiry #17590.

**Current behavior**
The remaining Teams maintenance callback scans every 30 seconds for
expired transport claims. It runs from shared publication maintenance.

**Proposed behavior**
The Teams owner reconstructs existing claim deadlines at startup and
reloads a transfer after its committed update. At expiry it clears the
claim and preserves the existing unknown-outcome or conflict state.
Normal receipt settlement removes the deadline.

**Reason and benefit**
Remove the last periodic Teams maintenance scan without resending a
possibly delivered card or file.

**Breaking changes**
No schema or public API change. Explicit diagnostic recovery methods
remain compatible. Consent expiry stays with its separate parent worker.

## What Changed

- Add a Teams-owned worker for consent_sending, uploading,
file_info_sending and conflict rows with a saved attempt expiry.
- Notify from the existing versioned update before writes. Preserve
transaction ownership and shared uncertain-write reconciliation.
- Expose a narrow per-transfer recovery method that uses the existing
lock order, integrity checks and atomic projection.
- Remove the periodic Teams maintenance callback and its
publication-maintenance invocation.
- Add real claim, receipt, conflict, backlog, restart, precision,
failure, drain and shutdown tests. Wire the owner through existing app
admission gates.
- Retain the existing signoff cancelled-run selection test and GitHub
inline retry-window race assertion.
- Document supported writers, remaining sleep limits and the failure
ledger in `doc/idle-teams-attempt-recovery.md` and its linked audit.

## Verification

Published head: `24c54399909105984e2a10f5869064984f69c472`, targeting
master after consent #17590 merged at
`4a89456bb3f9aef87cfe0e922e8b9d1a777a6c7e`. A normal ancestry merge
reconciles the landed squash with the previously verified child. The
complete 13-path binary patch is identical before and after
reconciliation, and all 30 unrelated master paths are preserved. This
adds no new worker behavior; the 239-case local evidence below belongs
to the verified unchanged patch. All 58 current-head checks are now
clean, including the complete required CI run. Greptile is 5/5 at this
exact head. The current Ponytail turn is paused without a verdict, which
is an explicitly authorized nonblocker; no failing review is waived.

The complete 13-path slice preserves the reviewed attempt implementation
and inherits the parent's report migration 0397, bounded consent worker
and retention CI test repair. No new schema, queue table, shared
scheduler contract, workflow or lockfile change is added by this duty.

- **239 distinct selected cases pass:** 221 across five complete
transfer/publication/consent/runtime/app-wiring suites, 16 selected real
Board/Teams-authority/GitHub-retry integration cases, and two delegated
Slack policy cases. Other chat integration cases (1,579) and
connection-management cases (81) were skipped, not passed. Each database
owner uses a new isolated PostgreSQL database.
- Real Board publication saves an active attempt deadline; its confirmed
receipt retires recovery, and SQL stays quiet afterward. The inherited
consent producer and authority cases still pass. Lifecycle coverage
exercises claim stages, unknown-outcome quarantine without repeating
provider I/O, conflicts, rollback, restart, precision, backlog/fairness,
failure recovery, drain and shutdown. The changed GitHub metadata/retry
race passes without duplicate assessments.
- The old server10 CI failure, run `40557802358` job `122390238707`, was
a delegated Slack invitation rate-window assertion (2,122 passed/one
failed/15 skipped in that shard). The verified parent already contains
its Date-only fixture fix. Both linked and invitation cases now pass
their full caller/target/shared-policy scenarios on a fresh server
fixture; no duplicate policy change or new owned file was added. That
old failure is preserved rather than called a pass.
- Server production typecheck, build and module-boundary checks pass.
Test files were executed; production typechecking does not statically
check them. The existing test-only signoff cancelled-run selection fix
is retained but was not executed locally in this acceptance; fresh
remote E2E gates remain required.
- [Current-parent acceptance and preserved failure
ledger](https://github.com/paperclipai/paperclip/blob/24c54399909105984e2a10f5869064984f69c472/doc/plans/2026-10-25-teams-attempt-recovery-sleep-audit.md#current-consent-parent-preparation-and-acceptance-october-28)
records current scope, commands, counts and limits. Earlier 235-case and
combined-stack counts belong to their stated revisions and are not added
to 239. The [stack
ledger](https://github.com/paperclipai/paperclip/blob/24c54399909105984e2a10f5869064984f69c472/doc/plans/2026-10-24-recurring-server-sleep-stack.md)
retains inherited failure history. No complete local repository suite,
live Teams/Slack tenant, external wake, physical suspension or savings
claim is made.
- **Exact-head Greptile 5/5 and all 58 checks are clean.** Actual
failing Ponytail findings must be repaired; a missing/stopped/paused
turn without a verdict is an authorized nonblocker. An active no-verdict
turn waits at most 30 minutes from its original request/start (25-minute
monitor cutoff). Older reviews and parent checks are not treated as
current passes.

## Risks

- Recovery must not infer that an expired claim means a provider effect
did not happen. It retains unknown outcomes and does not resend.
- Late receipts must still match current claim identity. Current-state
rechecks and existing protocol tests preserve this fence.
- Supported deployment uses one active writer process through its owning
DB client. Independent SQL and additional processes need a separate wake
contract.
- Cloud external alarm coverage and sleep eligibility are unchanged.
Other chat duties still run periodically until their own migrations.
- Voice-report parent review repairs are propagated: explicit
single-active-writer scope and an indexed report window. Thirty
report-worker/startup tests pass on the combined child. Fresh remote
checks, older stack findings and final master reconciliation remain
required.

## Model Used

OpenAI GPT-6 through Codex, with repository inspection, tool use and
code execution. The exact serving model ID and context-window size are
not exposed in this session.

## 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 linked existing issues or described the issue in-PR
following the relevant issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change 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-10-28 10:51:16 -05:00
DottaandPaperclip 4a89456bb3 fix(server): schedule Teams consent expiry from saved deadlines (#17590)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Teams file delivery saves consent and transfer state in the
database.
> - Unused consent must expire even when no new message arrives.
> - The maintenance loop currently checks this state every 30 seconds.
> - This PR schedules each existing consent deadline and wakes on
committed changes.
> - Empty or settled consent work stops querying while expiry remains
recoverable.

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Teams unused file-consent expiry. This is slice 26 of the
recurring-server migration stack, following merged #17586 and targeting
master.

**Current behavior**
The Teams maintenance callback scans for expired unused consent and
abandoned transport attempts together, even when consent work is empty.

**Proposed behavior**
The Teams owner reconstructs unused consent at startup and reloads one
transfer after a committed write. The shared scheduler runs its saved
expiry. Abandoned attempts keep their current recovery until a separate
slice migrates them.

**Reason and benefit**
Remove unnecessary consent queries without losing expiry, atomic
publication projection, or recovery after restart.

**Breaking changes**
No schema or API change. The explicit combined recovery method remains
available. Cloud sleep eligibility and external alarms remain unchanged.

## What Changed

- Add a Teams-owned scoped deadline worker for the three unused consent
phases. Registered reconstruction yields after one 100-row page per
scope refresh and resets cursors on registration; the explicit
diagnostic inventory still returns every eligible row.
- Signal before insertion and the existing versioned update inside the
owning transaction. Nested writes wait for outer settlement.
- Extract the existing locked per-transfer recovery operation. Preserve
authority checks, atomic projection, bounded lock waits and
unknown-outcome quarantine.
- Remove unused consent from periodic maintenance selection and
execution. Keep abandoned attempts as a separate obligation.
- Register the worker through existing app lifecycle gates. Add
lifecycle, producer, production wiring and precision regressions.
- Document supported writers, remaining sleep limits and the failure
ledger in `doc/idle-teams-consent-expiry.md` and its linked audit.

## Verification

Published head: `9e84cfab1f795279c8cec413a946631f1d781bd2`. This
follow-up changes only the inherited voice-retention test and its CI
failure ledger; all production behavior is unchanged from `36f43922`. It
normally merges actual landed master/report parent
`8049fbf51d0701ca6b242e4b1198e5449f7661b2`. The verified 12-path Teams
patch was byte-identical across the actual-parent ancestry integration.
This test-only CI follow-up adds one existing retention test path,
bringing the final scope to 13 paths. Every unrelated master change,
report documentation fix, and migration 0397 is preserved. No database,
shared-worker, workflow or lockfile change belongs to this slice.

- **223 distinct selected cases pass:** 209 across five complete
transfer/publication/consent/runtime/app-wiring suites, plus 14 selected
real Board-producer and Teams-authority integration cases. The other
1,580 integration cases were skipped, not passed. The protocol and
production consumers use separate new PostgreSQL databases migrated
through the application migrator.
- A real 105-transfer regression failed against the original worker
because one registered startup pass selected 105 rows instead of
yielding at 100. The corrected worker uses the existing paged shared
contract. Restarting the same service midway through discovery selects
the first 100 again, restores all 105 saved deadlines and expires them
at the original deadline. SQL is quiet before the deadline and after
settlement, with no consent-card or upload requests. The one-shot
inventory still returns all 105 rows.
- A guarded mutation removing only cursor reset fails at five rows
instead of 100 after restart. The original production source was
restored before the complete suites. The initial regression fixture
incorrectly faked network timers before its first SQL connection and
timed out; that setup failure is retained separately from the corrected
105-versus-100 regression. No assertion or timeout was weakened.
- The real Board producer registers the worker before publication,
commits the transfer wake, preserves the saved expiry, remains SQL-quiet
until due and atomically projects expiry to a cancelled publication
without another provider request. Existing authority and consent
transitions remain covered.
- Complete lifecycle coverage retains all three consent phases,
precision rounding, rollback and held outer commit, exact-row hints,
expiry recheck, failed projection retry, corrupt-row fairness,
drain/resume, shutdown and separation from abandoned-attempt
maintenance. Production server typecheck, build and module boundaries
pass. Server production typechecking does not statically check test
files; those files were executed.
- [Current bounded reconstruction and failure
ledger](https://github.com/paperclipai/paperclip/blob/36f43922b0a408f76adb7de31280812e9b752019/doc/plans/2026-10-25-teams-consent-expiry-sleep-audit.md#bounded-reconstruction-and-current-parent-acceptance-october-28)
records exact scope, counts, guarded mutation, corrected timer setup,
earlier fixture failures and limitations. Earlier 222-case and
combined-stack results belong to their stated historical heads; they are
not added to 223 or claimed rerun here. The [stack
ledger](https://github.com/paperclipai/paperclip/blob/36f43922b0a408f76adb7de31280812e9b752019/doc/plans/2026-10-24-recurring-server-sleep-stack.md)
retains inherited failure history. No complete local repository-suite,
live Teams tenant, Cloud wake, host/database suspension or savings claim
is made.
- **Fresh exact-head Greptile 5/5 and all CI are required.** Actual
failing Ponytail findings must be repaired. A missing/stopped/paused
turn without a verdict is an authorized nonblocker; an active no-verdict
review waits at most 30 minutes from its original request/start
(25-minute monitor cutoff). Older scores and parent checks are not
accepted as current passes.

- **Preserved inherited CI failure:** prior head `36f43922` had
exact-head Greptile/Ponytail 5/5 but CI run `40708566195` server6 job
`122887395220` failed the retention fairness assertion (2,291 passed/one
failed/one skipped in that shard). A fixed final UUID reproduces the
wrong expectation that an undiscovered page-two row is already deleted.
The corrected test controls time, expects that row to remain before
discovery and requires its deletion in the next fair batch, then all
remaining history and idle SQL. The existing five-second wait budget and
global timeout are unchanged. All 13 retention lifecycle cases pass;
bypassing company rotation fails the corrected assertion, and the
original shared helper is restored byte-for-byte. Earlier 223-case Teams
acceptance remains valid for unchanged Teams source and is not relabeled
as a new complete repository run. [Full CI repair
ledger](https://github.com/paperclipai/paperclip/blob/9e84cfab1f795279c8cec413a946631f1d781bd2/doc/plans/2026-10-25-teams-consent-expiry-sleep-audit.md#inherited-retention-ci-fairness-repair-october-28).
Fresh CI and exact-head reviews are required for this test-only
follow-up; old scores are stale.

- **Current merge gates:** all 58 checks are now clean for this exact
head and Greptile is 5/5 with no actionable findings. The current
Ponytail turn is paused without a verdict, an authorized nonblocking
state. Workflow `40712464720` attempt 1 independently hit npm
`ECONNRESET` during the serialized8 job's tool self-installer, before
its tests ran. Exactly one targeted job retry was requested after the
original workflow finished; attempt 2 completed successfully on the
unchanged head. No code, dependencies, workflow, timeout or review timer
changed for that retry. The original setup failure is retained in its
[job
log](https://github.com/paperclipai/paperclip/actions/runs/40712464720/job/122901243926);
the successful replacement is [job
122910350074](https://github.com/paperclipai/paperclip/actions/runs/40712464720/job/122910350074).

## Risks

- Missed supported producer signals could delay expiry until restart.
Real insertion, cancellation, consent transitions, caller-owned
transactions and Board publication are covered.
- Corrupt or locked rows must retain retry without starving healthy
work. Paging, fairness, atomic rollback, redaction, drain/resume and
shutdown tests cover these paths.
- Independent SQL writers and other processes need their own
notification contract. No persistent DB listener is added.
- Attempt recovery still scans periodically until the next slice. A
local deadline is not a durable Cloud alarm. This PR does not claim
whole-instance sleep.
- This slice is reconciled with its landed parent; current-head remote
checks/review and live-master composition proof still gate merge. Later
stack duties remain separate PRs.

## Model Used

OpenAI GPT-6 through Codex, with repository inspection, tool use and
code execution. The exact serving model ID and context-window size are
not exposed in this session.

## 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 linked existing issues or described the issue in-PR
following the relevant issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change 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-10-28 10:32:30 -05:00
DottaandPaperclip 820c458465 fix(runner): restore per-turn controller checkpoints before resume (#18018)
## Thinking Path

> - Paperclip coordinates agents and preserves their work between turns.
> - Remote native sessions save controller checkpoints in the database.
> - External persistence leaves a small identity marker on local disk.
> - A later `per_turn` continuation must restore that checkpoint before
it reads the controller identity.
> - The restore path handled warm sessions only, so valid per-turn
continuations failed before provider execution.
> - This PR restores the referenced checkpoint and retains the existing
ownership and lifecycle checks.

## Linked Issues or Issue Description

Related: #17439 added external controller persistence and the warm
restore path. #18011 repairs warm preparation and fresh bootstrap
checks; it does not cover ordinary per-turn continuation.

**What happened?**

A remote OpenCode run completed with `per_turn` lifecycle and saved its
controller checkpoint in the database. Its next turn reused the
normalized session. Admission read the remaining external-persistence
marker as a full controller file and failed with
`runner_state_identity_mismatch: durable_identity_unreadable`. The prior
run's complete checkpoint and harness backup still existed. The failure
occurred before provider work started.

**Expected behavior**

Restore the exact prior controller checkpoint before identity
inspection. Then apply the existing company, task, session, prior-owner
and suspended-state checks before a provider can start.

**Steps to reproduce**

1. Complete a remote native OpenCode task with `per_turn` lifecycle and
external controller persistence.
2. Send a follow-up that resumes the same saved session without a
session reset.
3. Observe admission reject the valid external controller marker before
provider execution.

**Paperclip version or commit**

Observed at `40c1ab36cdac70c85dc8fe5e912431834fdb691b`. The same
warm-only restore remains on current master.

**Deployment mode**

Hosted Linux with Daytona and native OpenCode. The original model was
`openrouter/deepseek/deepseek-v4.1-flash-1017`.

## What Changed

- Restore external controller state for ordinary remote per-turn
continuations through the existing checkpoint loader.
- Bind that read to the current company and task, the marker's run, and
the expected normalized session.
- Keep local, warm and restart-recovery paths, prior-owner checks and
harness backup checks intact.
- Refresh a prior-run projection from the latest checkpoint after a
rejected active-owner attempt. Keep current-run full state and the
existing legacy file-backed fallback intact.
- Add restoration and denial regressions, execution documentation and
session verification recipes.

## Verification

- Red: the real controller generated an external marker; a valid
per-turn OpenCode continuation failed with the exact
`durable_identity_unreadable` error before tool-authority construction.
The repair passed the same case and its ownership guards.
- Review regression red/green: a real controller advanced its checkpoint
after an active-owner rejection. Before the follow-up fix, a later valid
continuation retained a null attach seed. After the fix, it restored the
newer attach template and prepare command. Legacy full-file roots with
no database checkpoint retain their existing behavior.
- At current head `1f6589233e6121d082a0c0c4444ea895b6e8cd7c`, 86 focused
executor cases and all 14 execution-driver cases pass. Coverage includes
checkpoint restoration, direct/backup suspension, Codex, legacy files,
warm admission and canonical bootstrap, missing or malformed evidence,
wrong bindings, active/foreign owners and unsuspended runners. Tests
stop before provider launch.
- The real PostgreSQL encrypted-checkpoint integration passes, including
normalized-session refusal before write and stale-writer fencing.
Independent source review found no actionable safety defect.
- `node scripts/check-maps.mjs`, `git diff --check`, full `pnpm -r
typecheck` and `pnpm build` pass on current head.
- The local full suite did not complete: native PostgreSQL startup
failed under the host sandbox, an initial Docker rerun lacked
migrations, and the migrated retry crossed the review-fix revision
change. Logs are retained; that mixed-revision run was stopped and its
owned database removed. Full test evidence comes from current-head CI.
- Current-head CI passes: 53 successful checks, two intended Storybook
skips, none pending or failing. Greptile is 5/5 on that exact head with
no open review threads. The only manual merge conflict with #18011 was
in the verification recipes; both recipes and the unchanged per-turn
restore helper are preserved.

**Live continuation acceptance remains unverified, so this PR stays
draft.** Two disposable OpenCode/Daytona attempts never reached turns
two and three:

- At `72b49208b1`, the first turn executed tools and produced the exact
33-byte workspace note, but exceeded its four-minute settlement
deadline. The first completion lacked a registered attachment; the
second decorated a typed attachment reference with filename/size/hash
text. The strict UUID parser rejected that reference before checking a
valid criterion reference. The scoped attachment, asset and publication
receipt exist. Replaying the actual guard rejects the original input
before a database lookup; correcting only that reference passes against
the recovered row and receipt. This did not show a
publication-persistence or controller defect. The task remained
unsettled.
- At `1f6589233e`, a separately approved replacement used a temporary
prompt-only fixture change requiring exact `deliverable:<attachmentId>`
references, with metadata in `verification.detail`. Production code,
grading and deadlines were unchanged; the fixture patch was removed
afterward. This attempt had no recorded provider authentication,
harness-ready, model, tool or result event. Ingress acquisition took
84.072 seconds; transport connection took 205.835 seconds within the
239.832-second failed native execution. A local settlement GET also
timed out after 30 seconds. The underlying startup stall is unresolved;
these observations do not establish a remote provider outage. Final
recovery was blocked with `ambiguous_remote_recovery_evidence`; no
successful settlement or continuation is claimed.

Both attempts used a Darwin arm64 source host with Node 26.4.0, isolated
PostgreSQL 18, a Linux x64 runner and OpenCode 1.18.34. The
representative qualified model was
`openrouter/deepseek/deepseek-v4-flash-0731`; the original incident used
`openrouter/deepseek/deepseek-v4.1-flash-1017`. The controller defect
occurs before provider work. Runtime artifacts came from immutable build
`e7ea2e2961`, whose Runner package source is identical to the candidate.
The current-source manifest, artifact, distribution, asset and all 110
archive-hash checks passed. Each attempt had $10 company/agent model
budgets and zero automatic workflow/task retries. Accounting was
incomplete; zero recorded spend is not proof of zero cost.

Earlier setup failures are also retained: host PostgreSQL bootstrap
denial, cached-pack compatibility admission before provider work, and an
[official artifact
build](https://github.com/paperclipai/paperclip/actions/runs/40696838122)
that stopped during an unrelated Pi npm install at its 300-second bound.
No manifest or integrity guard was weakened. Owned local processes and
databases are stopped, and the temporary fixture patch is removed.
Standard fixture cleanup had left one replacement sandbox started; it
was stopped and deleted through the SDK. Every owned sandbox was then
verified absent with a final 404 readback. Resource cleanup does not
establish successful task finalization.

An earlier head retained one [voice-recovery timing
failure](https://github.com/paperclipai/paperclip/actions/runs/40695892339/job/122843005098):
a deadline test observed two failed-provider inspections instead of one.
A single isolated shard rerun passed all 1,579 tests without a source
change. Its timing explanation remains an inference. The current
reconciled head passed without a retry.

## Risks

Restoration writes a local projection before the existing admission
checks. The encrypted checkpoint loader validates company/task/run and
normalized session before writing. A later ordinary continuation
refreshes a prior-run projection so rejected admission cannot freeze an
active owner's older checkpoint. Active, foreign or unsuspended prior
owners still cannot start a successor. Missing or malformed evidence
remains blocked. The change adds no retry, credential, provider binary
or lifecycle-policy change; it preserves the existing legacy fallback.

This PR does not deploy the repair or recover the original hosted tasks.

## Model Used

OpenAI GPT-6 through Codex, with reasoning, tool use, code execution and
collaborating agents. The session exposes GPT-6 as its model version; a
more specific model ID and context-window size are unavailable.

## 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-10-28 09:49:32 -05:00
Dotta b25f3e2af8 fix(onboarding): show native proposal confirmation recipes (#18025)
## Thinking Path

> - Paperclip lets people manage agent work through tasks.
> - First-task onboarding asks a new agent to propose work before it
starts.
> - The user must accept a saved proposal before the agent can create
its child task.
> - A native agent can ask for approval in a question card, which does
not record proposal acceptance.
> - The skill names confirmation cards but does not show their native
tool arguments.
> - This change adds executable native proposal recipes and checks their
real approval path.
> - The task admission rules and Product E2E assertions stay in place.

## Linked Issues or Issue Description

**What happened?**

A fresh onboarding agent asked the user to approve a child task through
an Approve/Revise question. The question looked like a decision, but its
answer cannot authorize child creation. The first-task skill teaches
native question calls for interviews and names proposal confirmation
cards without showing the native mapping.

**Expected behavior**

The agent should create a confirmation card for a single-task proposal,
or a checkbox card bound to the saved plan revision. Only the saved
human acceptance should admit the child task.

**Steps to reproduce**

1. Start first-task onboarding with a native agent.
2. Choose one task and ask the agent to propose a child before it starts
work.
3. Have the agent use a question card with Approve/Revise options.
4. Answer Approve. Child creation remains blocked because no proposal
confirmation was accepted.

Related public context: #17940, #13517.

## What Changed

- Show the native `request_human_input` arguments for confirmation and
plan-bound checkbox proposals.
- Explain that question answers supply scope and cannot grant proposal
authority.
- Resume the agent after either acceptance or rejection, and use new
proposal keys for revisions.
- Parse the shipped recipes and execute them through the real native
tool authority and interaction service.
- Verify that pending proposals, agent-only acceptance, and an answered
Approve/Revise question cannot admit child work.
- Use the existing isolated PostgreSQL test helper when a local test
database is supplied.
- Fix the required clean Grok npm-install check to prefix synthetic
revision identifiers with `g`. The former all-numeric, leading-zero
identifier was invalid SemVer and caused a reproduced `ETARGET` failure.
Customer release versions are unchanged.

## Verification

- Red: both new executable recipe checks fail against the preceding
skill.
- Green: 44 focused tests pass with zero skips against a task-owned
PostgreSQL server. The actual tool authority and approval service are
exercised.
- Human acceptance of either recipe admits the child. Agent-only
acceptance does not. Answering the question leaves the issue set
unchanged.
- Red/green real HTTP checks prove rejection saves the assignee
continuation, starts no extra model run, and still denies child
creation.
- `git diff --check` passes.
- Full repository `pnpm -r typecheck` and `pnpm build` passed on the
final approval-guidance revision.
- The first full local test attempt used an unmigrated external fixture
and was stopped after the cause was confirmed. A new migrated fixture
resolved that setup error; the second full attempt reached its explicit
10-minute limit before finishing. Both attempts are preserved and are
not claimed as passing. The temporary owned PostgreSQL container was
removed. The complete Linux CI workflow passed on the final PR head.
- The exact synthetic-version failure was reproduced with real npm and
an empty local packed registry. The new maintained regression keeps the
invalid-version negative control and installs corrected numeric-hash and
normal-hash controls. All 27 existing Grok helper tests and three
offline registry-boundary checks pass.
- Final head `52d0b92a00dcb0653b6fb48415cfaea979b8f21f`: [CI
40706933035, attempt
1](https://github.com/paperclipai/paperclip/actions/runs/40706933035)
passed; 55 successful checks, two skipped and one neutral. Greptile is
5/5 for this exact head with no unresolved threads. The original failed
build remains preserved.
- Live fresh-workspace acceptance has not passed yet. It follows the
reviewed testing rollout; this source test does not prove model
compliance.

## Risks

The change guides model tool selection. An agent can still ignore the
skill. Product admission remains the authority, and the live journey
must still verify human approval, native child execution, downloaded
artifact bytes, context reuse, and cleanup. There is no schema or API
change. The CI helper changes only temporary verifier versions and
preserves the existing registry integrity, install, lifecycle, and
isolation checks.

## Model Used

OpenAI Codex `gpt-6.1-sol`, with reasoning, source inspection, tool use,
and code execution. The host does not expose its configured
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
2026-10-28 09:47:55 -05:00
DottaandPaperclip 8049fbf51d fix(server): schedule voice call reports from saved deadlines (#17586)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Voice calls retain reports and project guest transcripts into intake
tasks.
> - Chat maintenance repeatedly scans recent calls even when no report
is due.
> - Empty scans keep the tenant database active.
> - Existing session and report rows already contain the work and its
deadlines.
> - This pull request moves report refresh to the shared coordinator and
removes the final voice maintenance lane.
> - Idle voice configuration and old call history no longer cause report
scans.

## Linked Issues or Issue Description

Refs #17583, #17580, #17578, #17576. This is slice 25 of the
recurring-server sleep stack. It now follows merged #17583 and targets
master.

**What existing behavior does this improve?**

Voice call-report refresh and guest transcript projection.

**Current behavior**

The chat interval scans terminal calls for reports. It repeats the scan
even when there are no eligible calls or all saved deadlines are in the
future.

**Proposed behavior**

Committed session transitions and signed callbacks wake a scoped worker.
Startup reconstructs existing rows. Later refreshes use saved deadlines.
The worker becomes quiet after all eligible windows expire.

**Reason and benefit**

Stop empty database scans without losing late transcript and billing
updates. Keep the existing 24-hour refresh policy, provider response
ordering, and guest-task trust restrictions.

## What Changed

- Add a voice-owned report worker using the existing scoped deadline
helper. No queue table or field is added; the existing session table
receives a report-window index.
- Save each attempt and its retry before provider I/O. Compare that
ownership on settlement so an older response cannot overwrite a later
callback or claim.
- Preserve available reports when a response is incomplete or stale.
Preserve their finite refresh window.
- Route voice-change and reply call-ended writes through
transaction-aware report signals.
- Preserve guest transcript locks and use the observed document revision
when updating an existing transcript.
- Register the worker in app startup. Remove voice reconciliation from
the chat interval. Keep explicit one-shot diagnostics.
- Document producer scope, lifecycle behavior, tests, and external wake
limits.

## Verification

Published head: `758cfe15c3e6283d38ba512c8416ccce4d200862`. The
follow-up after `c28de398` changes only two documentation files; the
verified production, migration and test source is unchanged. It normally
merges landed retention/master
`980775e0e956eecdc28c73c9b4aca0407ad45e1a`. The 20 owned paths remain
the complete slice, including officially regenerated migration 0397, its
snapshot and required pruning of snapshot 0392. The non-database
reviewed patch was preserved during ancestry integration; the only
subsequent source edit makes one existing report test’s provider
responses call-specific. All production report behavior and unrelated
master changes are preserved. No shared worker, workflow or lockfile
change belongs to reports. All 58 current-head checks are now clean,
including the previously failing approval shard; exact-head Greptile is
5/5 with no new actionable issues. Ponytail’s current turn stopped
without a verdict, an authorized nonblocking state. The prior
conditional documentation requirement was fixed; old CI failures remain
recorded below.

- **Prior-head evidence at `9bf20467df`: 303 distinct targeted cases
passed**, not rerun wholesale for this integration: all 132 voice
integration cases; 170 cases across 11 complete report, retention,
cleanup, recovery, company-removal, shared-worker and startup/hostname
suites; and one complete snapshot/schema drift case. This includes 15
report, 13 retention and 14 cleanup lifecycle cases. Voice integration
and the four other database owners use separate initially empty
databases and migrate themselves. Report cases use their dedicated
database after the setup repair.
- Five real connection saves over 205 sessions with saved future report
deadlines selected 1,025 session rows before the notification repair.
They now select zero and preserve the original deadline. The report
notification helper accepts only exact session scopes. Configuration,
authority and connection hints retain their existing live
recovery/reply/cleanup behavior but do not rebuild report history. Real
session terminal writes, callback hints, report claims and receipts
still reactivate reports.
- Database/server typechecks and builds, migration numbering/safety, and
module-boundary checks pass. Final server types/build also pass after
integrating the retention review repairs. The parent 205-admission,
five-configuration-save test still observes zero retained-history rows
and preserves its deadline.
- The old eager reader selected all 105 saved-report headers before
yielding and failed the 100-row budget. Registered reconstruction now
uses the existing paged contract and yields at 100 rows per scope
refresh. A partial scan can restart on the same owner and reconstruct
every saved deadline. At due time all 105 report IDs are fetched exactly
once. Future deadlines remain quiet between actual retries.
- The company-fairness case places a small company deterministically on
page two and requires it in the next 25-work batch after discovery, with
all 105 reports processed before the failed provider's retry. Guarded
mutations catch a missing cursor reset and bypassed company rotation.
Original source was restored before final acceptance.
- At prior head `9bf20467df`, migration 0396 was generated with `pnpm
db:generate` on the parent 0395 lineage. It creates the partial
`(ended_at, id)` report-window index concurrently and replayably through
the existing migration runner. All 394 historical SQL files and the
journal prefix are unchanged; snapshots 0392 through 0396 remain. Fresh
application migration and two replay invocations succeed with a valid
index. The real plan case retains 20,001 old sessions, 205 recent
sessions, precision-safe keysets, and fewer than 1,000 rows removed by
filtering on each page.
- Existing real hangup/callback/reply-error producers, callback
ownership fencing, monotonic report results, saved retry before provider
contact, guest transcript projection after a document lock, transaction
rollback/nesting, drain and shutdown remain covered. No table, field or
provider protocol is added. Available reports retain the existing finite
24-hour refresh policy.
- [Current-parent acceptance and failure
ledger](https://github.com/paperclipai/paperclip/blob/9bf20467dfd50b81848e1c8dd7ddc905d206418f/doc/plans/2026-10-25-voice-call-report-sleep-audit.md#current-parent-reconstruction-and-migration-acceptance-october-28)
records the failed fresh fixture, eager read, fairness-clock attempts,
guards, commands, counts and limits. Older 174/138-case and
workspace-wide results belong to their stated heads. No new complete
local repository suite, live provider, Cloud wake, host/database
suspension or savings claim is made.
- [Report configuration-scope
repair](https://github.com/paperclipai/paperclip/blob/9bf20467dfd50b81848e1c8dd7ddc905d206418f/doc/plans/2026-10-25-voice-call-report-sleep-audit.md#configuration-scope-review-repair-october-28)
records the current 303 cases and measured rescan repair. The prior
`80207ba6bb` head had Ponytail 5/5; that review is stale after this
change. Fresh exact-head Greptile 5/5 and all CI remain required. Actual
failing Ponytail findings must be fixed; a stopped or paused turn
without a verdict is an authorized nonblocker. Active no-verdict review
waits are capped at 30 minutes from the original request/start
(25-minute monitor cutoff). Older scores and parent checks are not
inferred as current passes.

- **Current-master verification: 185 distinct cases pass**: final
complete voice integration 132, complete report/cleanup/retention
15+24+13, and snapshot/schema drift 1. Each database owner used its own
empty fixture database. The first combined run had 183 passing cases and
one report-test failure; it is preserved in the audit. A deliberately
earlier-ended competing call reproduces the old one-shot mock consuming
the intended response. The corrected test selects responses by provider
session ID, verifies independent costs for both calls, then rejects
stale target data. The isolated repair and full 132-case suite pass;
production behavior and timeouts are unchanged. These 185 cases are not
added to the older 303 count.
- **Current migration lineage:** official `pnpm db:generate` after
actual master creates `0397_known_madrox.sql`; the reviewed
concurrent/idempotent report-index SQL is retained byte-for-byte. All
395 existing SQL files and journal entries are unchanged; snapshots
0393–0397 remain and the new snapshot links parent 0396. The application
migrator boots a fresh database, repairs a deliberately invalid index
during two concurrent replay invocations, records one history row, and
replays again successfully. Database build, server build/typecheck,
migration checks and module boundaries pass. [Full current-master
acceptance and failure
ledger](https://github.com/paperclipai/paperclip/blob/c28de398fef074f650eff532952ab6f5563739a8/doc/plans/2026-10-25-voice-call-report-sleep-audit.md#landed-master-migration-and-acceptance-october-28).

- **Review follow-up and preserved CI timeout:** Ponytail’s prior
`c28de398` review was 4/5 advisory, with no must-fix production defect
and a request to fix the stale design-doc migration reference before
shipping. That document now names migration 0397 and links current
185-case acceptance; older 302/303-case evidence is explicitly
historical. The optional suggestions about one-shot diagnostic inventory
cost and inherited test-clock helpers remain disclosed. CI run
`40703490340` failed the unchanged approval-queue backoff test on its
existing 15-second timeout and then an activity-log FK in teardown
(2,097 pass/one fail/one skip in that shard). The complete unchanged
28-case approval suite passes on a new isolated database; the exact CI
timing cause remains unproven. No timeout, workflow or production logic
was changed, and no old-head rerun or failure waiver is claimed. This
documentation head requires fresh CI and exact-head Greptile. [Review
and timeout
ledger](https://github.com/paperclipai/paperclip/blob/758cfe15c3e6283d38ba512c8416ccce4d200862/doc/plans/2026-10-25-voice-call-report-sleep-audit.md#review-documentation-and-preserved-remote-timeout-october-28).

## Risks

- Process-local commit signals do not observe independent SQL writers or
another server process.
- Available reports still refresh for 24 hours. The provider's complete
flag does not promise immutable final data.
- Transcript projection retries remain within the existing report
window. This change does not add indefinite projection repair.
- One-shot diagnostic `reconcile(limit)` inventories the eligible window
before slicing; it remains a manual diagnostic cost, not recurring idle
work. Some inherited test helpers advance fake time during assertion
retries, an optional reliability follow-up noted by review.
- A local deadline cannot wake a stopped host. Cloud alarms and sleep
eligibility remain unchanged. No deployed sleep or cost saving is
claimed.
- This PR depends on the preceding stack. Final master reconciliation
and remote review gates remain required.

## Model Used

OpenAI GPT-6 through Codex, with repository inspection, code editing,
and local test execution. The exact serving model ID and context window
are not exposed in this session.

## 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-10-28 09:41:15 -05:00
DottaandPaperclip 25f1070fbd fix(runner): preserve checkpoint proof across warm preparation (#18011)
## Thinking Path

> - Paperclip coordinates agent work and preserves its execution state.
> - Native Runner checkpoints preserve authority across controller
changes.
> - Warm sessions also need checkpoint writes while their successor
prepares.
> - External persistence replaces the local state file with a marker.
> - Two existing checks treated those valid states as lost ownership or
prior activity.
> - This PR uses the existing preparation lease and canonical controller
state to keep those checks accurate.
> - The result is safe warm-session retirement and fresh-session startup
on reused sandboxes.

## Linked Issues or Issue Description

Related: #17439 and #17320. The open #17401 changes the recovery welcome
window and does not cover these paths.

**What happened?**

A configuration change could fail before the next provider turn with
`runner did not durably suspend before checkpoint`. The task already
pointed to its preparing successor, but that successor did not yet have
a native coordinator. The old completed runner's maintenance checkpoint
was rejected.

A separate fresh session on a reused sandbox could fail with
`resumed_unavailable`. Checkpoint registration had replaced the full
local state file with an external-persistence marker. The bootstrap
check still required the old full-file format. Process supervision then
reported unconfirmed termination before launch.

**Expected behavior**

Retire the completed warm runner under the same process's live
preparation lease. Admit a fresh remote session only when the registered
controller proves exact identity, no prior activity and pending
bootstrap commands, and the remote session directory can be claimed
atomically.

**Steps to reproduce**

1. Complete a native warm turn with external checkpoint persistence.
2. Change configuration so instruction preparation must retire that
session, then submit a follow-up.
3. Separately, admit a fresh native session on a reused sandbox lease
after external checkpoint registration.

**Paperclip version or commit**

Reproduced in the checkpoint implementation introduced by #17439. Fixed
against current master.

**Deployment mode**

Source checkout tests and a hosted Docker/Daytona incident. No
deployment or original-task retry is part of this PR.

## What Changed

- Accept completed-run maintenance under the exact successor's live,
same-process preparation lease only before a native coordinator exists.
- Preserve original controller generation, accepted-result, no-new-work,
company and task checks.
- Pass the registered controller through the existing connection
callback and read its current canonical state for untouched-session
proof.
- Keep marker-only, identity, activity, backup and atomic
remote-directory guards.
- Add regressions and update execution semantics and session
verification recipes.

## Verification

- Warm retirement red: the real Postgres writer rejected the preparing
successor's `runner.suspend` checkpoint with
`native_runner_checkpoint_owner_lost`.
- Warm retirement green: 14 Postgres ownership cases pass, including
stale/foreign/expired owners, conflicting native authority and new
provider work.
- Bootstrap red: real controller registration and external persistence
caused the resumed and replacement positives to fail. Six external
negative cases passed.
- Bootstrap green: all 34 bootstrap cases, the bootstrap-state predicate
and 13 connection-driver cases pass (48 total).
- `node scripts/check-maps.mjs` and `git diff --check` pass.
- Full `pnpm -r typecheck` and `pnpm build` pass.
- Full local `pnpm test:run` remains partial/interrupted. The default
attempt could not initialize embedded Postgres on this Mac. A dedicated
Postgres 18 attempt ran for 17 minutes without a completed file result
before interruption; the generic helper separately confirmed unsupported
embedded Postgres (`initdb` failed after five attempts) and ignores the
external database URL. The generic probe skipped one test. Setup and
interrupted-run logs are retained; neither is claimed as a behavioral
red or a full local pass.
- Real source-hosted Codex/Daytona acceptance was attempted at
`6ce7fcacc4` with `gpt-6.1-sol`, `xhigh`. The actual task stopped before
provider work at `runner_ingress_auth_failed`, with zero authenticated
connections and zero source events. A separate environment-qualification
handshake reached challenge/response; that does not prove task
authentication. The three-turn warm reuse, configuration retirement,
useful output and reload workflow remains unverified, so this PR stays
draft.
- The live attempt used the cached Linux amd64 Runner binary
`7437a4e32a099180889be534fcfb2a086046514490c1448aba46c55848983ed8` from
the immutable Daytona image. The current staging binary could not be
copied because SSH timed out, and the configured current EXE image
returned registry 403. No compatible current local or CI-downloadable
artifact was available. Earlier setup failures and cleanup receipts are
retained; no provider success is claimed. Disposable test resources were
cleaned up.
- Exact-head Greptile completed at 5/5 with no open feedback:
https://github.com/paperclipai/paperclip/pull/18011#issuecomment-6469515952.
All current-head CI checks pass: 53 successful checks and two intended
Storybook skips.

## Risks

The preparation fallback affects maintenance checkpoints only after an
accepted result. An existing native coordinator prevents that fallback.
Stale controller generations, expired or foreign preparation leases,
wrong tasks and new provider work remain denied.

The bootstrap check retains the live controller object and reads current
state each time. It does not trust a marker or restore local state
beneath a live controller. Pending turns, prior events/connections,
backups and existing remote directories retain recovery gates. No
schema, provider binary, credential, permission or lifecycle-policy
change is required.

## Model Used

OpenAI GPT-6 through Codex, with reasoning, tool use, code execution and
collaborating agents. This session does not expose a more specific model
ID or 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-10-28 09:09:09 -05:00
DottaandPaperclip c08da3e0a7 perf(server): narrow skill list reconciliation reads (#18023)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The skill library lists current company skills and their agent
attachments.
> - Each list request also reconciles bundled skills, folders, and local
files.
> - These reads return full agent records and large metadata that their
callers do not use.
> - Conditional requests do this work before they return an unchanged
response.
> - This pull request selects the fields each caller needs and avoids
unused folder lookups.
> - The result is less database transfer and fewer round trips while
reconciliation stays current.

## Linked Issues or Issue Description

Refs #17941. That change reuses bundled categories within an import.
This change removes other repeated work in the same list path.

**What happened?**

Warm skill-list requests still made 119 SQL calls in a local HTTP
fixture. The folder pass returned full skill metadata. The local-source
pass also returned remote skills. Attachment counts loaded full agent
configurations and monthly spend. Bundled reconciliation resolved folder
paths that its release check did not use.

**Expected behavior**

The list must preserve its current result, attachment counts, access
rules, local-file reconciliation, and bundled release checks. Internal
reads should return only the data their callers need.

**Steps to reproduce**

1. Use a company with many remote skills and agents with large saved
configurations.
2. Read its skill list, then repeat the read with its ETag.
3. Measure the queries and response values before the server returns
`200` or `304`.
4. Run `pnpm --filter @paperclipai/server exec tsx
scripts/benchmark-skill-list.ts --samples=5 --network-delay-ms=3.5` for
a synthetic reproduction.

**Paperclip version or commit**

Baseline service: `e1ba77f06771a27114b3999004b0ca5e3c172dd4`. The branch
is based on current master. The paired mode changes only the
skill-service module; both versions use the same imported helpers.

**Deployment mode**

Built from source. Local HTTP server and disposable PostgreSQL 17. No
hosted deployment is part of this PR's local proof.

## What Changed

- Read only the desired-skill selections of nonterminated company agents
for attachment counts. Resolve each agent's references once against the
full visible skill list. Preserve IDs, keys, aliases, duplicate
handling, and ambiguous slugs.
- Read only `sourceKind` from metadata for bundled folder
classification.
- Limit local-source reconciliation to local-path rows.
- Skip folder-path enrichment only for bundled reconciliation. Normal
imports and list responses keep their folder paths.
- Add real-database byte regressions and a local HTTP benchmark. The
benchmark can alternate the old and new services against one database,
actor, and process. It checks complete response equality and conditional
responses.

The company-skill service owns these reads. The query predicates and
freshness checks remain at their existing owners. This change adds no
cache, schema change, or new background work.

## Verification

- The attachment byte regression failed before the fix: 601,418 captured
response-value bytes exceeded its 2,000-byte bound. The same case passed
after the fix. It checks fresh configuration edits, IDs and keys,
duplicate aliases, ambiguous slugs, paused agents, terminated agents,
and company scope.
- 111 focused service and authorization tests passed against isolated
real PostgreSQL 17 databases. They include full result equality,
retained stored Markdown and metadata, local-file updates, release
checks, project visibility, and import authorization.
- The default embedded PostgreSQL probe skipped the first local attempt
on this Mac. The completed run used a local-only bootstrap adapter for
disposable databases. Queries, migrations, services, authorization, and
filesystem work used their real implementations. The adapter is not part
of this PR.
- In repeated synthetic HTTP byte runs, calls fell from 119 to 98 per
request. Result-value bytes fell from about 7.75 MB to 1.64 MB per
request, about 79%. These values are measured before Drizzle decoding.
They exclude protocol framing and do not measure provider billing.
- A separate-process run without the byte observer did not show a
latency gain. The paired experiment removes that comparison gap: it
alternates both services against the same database and checks identical
complete responses. On final commit
`3076fe1402085f7286ff58e642d7caca892a5f80`, five observer-free pairs had
median times of 2.582 s before and 1.850 s after (28.3% lower). The
candidate was faster in all five pairs. Its range was 1.802–2.199 s; the
baseline range was 2.327–2.725 s. Every normal response had the same
complete body hash, and both versions returned the expected unchanged
conditional responses. These are local service/HTTP timings with
synthetic data and 3.5 ms delay per network direction. They are not
hosted acceptance.
- Final-head workspace typecheck and build passed. The full local test
command did not complete because embedded PostgreSQL bootstrap failed on
this Mac; I stopped that owned runner after 16 native-runtime cases
failed. All 16 cases then passed when rerun alone against disposable
PostgreSQL 17 using their existing external-database path. The 111
focused PostgreSQL 17 tests above also completed successfully. This does
not constitute a completed full local suite; all current-head remote CI
gates passed (55 successful checks and 2 skipped). Module-boundary and
whitespace checks pass. An initial nested package command used the
global pnpm; subsequent commands were pinned to pnpm 9.15.4.
- The first canary dry run failed while installing an unrelated
standalone package: npm returned 404 for the newly published Rollup
4.66.0 tarball. The exact download subsequently returned HTTP 200. The
one retry passed without code changes.
- Benchmark commands: add `--capture-values=false` for observer-free
timings. Add `--baseline-ref=e1ba77f06771a27114b3999004b0ca5e3c172dd4
--capture-values=false` for paired service acceptance. The normal mode
uses the production router. The paired mode uses equivalent default-list
HTTP handlers and a synthetic authenticated board actor; it does not
test login.

## Risks

The SQL selection must stay in sync if the desired-skill format or
folder classifier needs new fields. Existing parsing and reference
resolution still interpret the selected data.

The synthetic fixture has large unused payloads. It proves the mechanism
and preserves required content. Its percentage is not a projection of
whole-instance transfer or billed savings. Hosted latency still needs
verification after merge and deployment.

## Model Used

OpenAI GPT-6 through Codex, with repository inspection, shell execution,
real PostgreSQL, and local HTTP testing. The host does not expose a
precise backend revision or 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-10-28 09:07:17 -05:00
Jamie Buchanan 3339582810 fix(adapter-utils): stop asking the GitHub broker on every local git call (#17886)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent runs use `git` and `gh` through the managed GitHub launcher.
> - The launcher asks the broker for credentials before every `git` and
`gh` call. It also asks for local commands that do not use the network,
such as `git status`.
> - Each request runs a transaction and an UPDATE in the database. On a
busy install this gives hundreds of thousands of writes each day and
long COMMIT waits.
> - This pull request stops the request for local `git` commands and
writes the identity summary only when it changes.
> - The benefit is fewer broker requests and fewer database writes. The
credential rules do not change.

## Linked Issues or Issue Description

- Fixes #17879

## What Changed

- The managed `git` launcher does not ask the broker for local
subcommands (`status`, `diff`, `log`, `rev-parse`, `add`, `config`,
`branch`, `checkout` and others). It reads past global options such as
`-C` and `-c`. An unknown subcommand or option still asks. `commit` and
`var` still ask, because the managed author comes from the broker
answer.
- The launcher keeps no broker answer between invocations, so no GitHub
credential is written to a file. The suggestion in the issue to reuse
one answer per run is not part of this pull request, because the reused
answer would have to rest on disk.
- `resolveGitHubOperationCredentials` writes
`run_identity_contexts.github` only when the summary changes.
- `doc/execution-github-identity.md` describes the behavior.

## Verification

- New launcher tests run real `git` against a fake broker that counts
POSTs. A 12-command sequence (init, status, config, rev-parse, add,
diff, commit, log, branch, show, status, diff) made 12 POSTs before and
1 POST after. The one POST is `commit`.
- The same tests check that `var`, `remote`, `fetch`, an alias, and an
unknown option still ask, and that `git var GIT_AUTHOR_IDENT` returns
the managed author.
- A new test covers the unchanged-summary write.
- `vitest run` on the launcher, launcher environment, callback bridge,
github-operation-credentials, run-identity, heartbeat-github-launchers,
native-github-access, openapi-routes, run-trust-preset,
http-log-redaction, skill-source-github-access and chat-channels tests:
12 files, 1901 passed, 1 skipped.
- `vitest run --project @paperclipai/adapter-utils` on `src`: 1903
passed, 12 skipped, 1 failed. The failure is
`sandbox-callback-bridge.test.ts`, a file this PR does not change. It
passes alone (89 of 89, three runs).
- `tsc --noEmit` passes in `packages/adapter-utils` and in `server`.
- Three deliberate breakages each made a test fail: `var` back in the
local list, the broker always asked, and the summary write skip removed.
- Not run: the full server suite and `pnpm build` (the local machine has
no `cargo` for the runner binary).

## Risks

- In a partial clone or an LFS repository, a local command that must
fetch a missing object runs without a token.
- A `git` command that is not local (`commit`, `fetch`, `push`) and
every `gh` command still asks the broker once.
- No migration. No credential is stored at rest.

## Model Used

- Claude Sonnet 5.5 (`claude-sonnet-5-5`, Anthropic) through Claude
Code, with tool use (shell, file edits, test runs), wrote the code and
tests.
- Claude Opus 5.5 (`claude-opus-5-5`, Anthropic) through Claude Code
wrote the issue text and this description.
- A person asked for the change and submits it.

## 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-10-28 09:06:14 -05:00
DottaandPaperclip 980775e0e9 fix(server): schedule inbound voice history retention by deadline (#17583)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Incoming voice calls leave history after provider cleanup is
confirmed.
> - The chat maintenance tick repeatedly deletes old admission history.
> - Each eligible row already contains the dates needed for its
retention deadline.
> - This pull request schedules that deadline and wakes on committed
changes.
> - Idle retention stops querying while the existing seven-day policy
remains enforced.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Inbound voice history retention. This PR follows merged #17580, which
owns physical call cleanup, and now targets master. Call reports remain
a separate migration.

**Current behavior**

Voice maintenance scans admission history repeatedly. It deletes
confirmed, terminal, unbound admissions when both expiry and last update
are at least seven days old.

**Proposed behavior**

Load existing retention deadlines at startup. Wake from the existing
admission transaction notifications. Delete at the later timestamp plus
seven days. Lock and recheck current eligibility before deletion.

**Reason and benefit**

Configured idle endpoints and future history do not cause recurring
retention SQL. Failed deletion retains a retry. Restart reconstructs the
same saved deadlines.

## What Changed

- Add a voice-owned retention worker using the existing scoped deadline
helper and coordinator. Yield after 100 history rows per scope refresh
and reset reconstruction on registration. Keep complete one-shot
inventory reads. No table, field, or migration is added.
- Extend `notifyVoiceInbound` to notify retention before the same
committed writes that already notify cleanup. Callers need no new
recovery wrapper.
- Preserve confirmation, terminal-state, session, task, and seven-day
eligibility conditions. Round PostgreSQL submillisecond deadlines up.
- Lock and recheck the current row before deletion. New bindings or
moved dates invalidate stale candidates.
- Remove history pruning from recurring voice maintenance. Keep the
explicit one-shot diagnostic path. Leave call reports for their own
slice.
- Document producer ownership, retry/drain behavior, tests, and external
wake limitations.

## Verification

Published head: `53f2fafcb64d104887eb4455c292b48e6dd10253`. It includes
the normal merge of actual landed master
`71b448b9cb841e6fa18fe883585430c5081245da` after cleanup #17580. That
ancestry integration at `768c650365` preserved the complete binary diff
of all 13 reviewed retention paths. This follow-up changes only the
existing cleanup fairness test and its failure ledger, bringing the
final scope to 14 paths; all production source is unchanged from that
integration. All unrelated master changes, cleanup repair, migration
`0396_tan_paladin.sql`, and gateway clock repair are preserved. Database
files, shared worker, workflows and lockfile match actual master. The
earlier 282-case/type/build evidence below belongs to unchanged
retention source at its stated head; current repair acceptance is 37
distinct complete cleanup and retention lifecycle cases. All 58
current-head checks are now clean, including the Canary Dry Run;
Greptile is exact-head 5/5 with no new actionable issues. The current
Ponytail turn stopped without a verdict, which is an authorized
nonblocking state. The earlier failing CI remains preserved below.

- **282 distinct targeted cases pass**: all 127 voice integration cases
and all 155 cases in ten complete retention, cleanup, recovery,
company-removal, shared-worker, startup and hostname suites. These
include 13 retention and 14 cleanup lifecycle cases. Voice integration,
parent recovery and company removal start on separate empty databases
and migrate themselves. Retention uses its dedicated database after the
setup repair; cleanup uses its already-migrated dedicated database.
- Ponytail's prior exact-head 4/5 review found configuration-driven
history rescans. Five real connection saves selected 1,025 rows over 205
future admissions before repair. Retention now receives only admission
hints and startup reconstruction; the same saves select zero admission
rows and retain the original deadline. Cleanup still receives its full
configuration and authority scopes. Restrictive binding foreign keys
prevent implicit unbinding outside the admission-write boundary.
- Successful deletion now returns its confirmed result without reloading
the deleted row. A real SQL-count case and a guarded negative probe
cover that path. Changed or not-yet-due history still reloads current
eligibility and its deadline.
- Server typecheck, build and module-boundary checks pass. No schema,
driver, shared scheduler contract or provider protocol changes are added
by this slice.
- A real 105-row future-history case failed before the reader repair
because startup selected 105 rows rather than yielding at 100. The
existing paged shared-worker contract now bounds each scope refresh. The
same-owner restart case reconstructs every deadline and deletes all 105
eligible rows at the original deadline. It verifies SQL quiet before
that deadline and after settlement. Removing only cursor reset fails at
five rows instead of 100 after restart; guarded source was restored
before final acceptance.
- Existing cases retain the later-of-two-timestamps seven-day policy,
submillisecond rounding, current-state confirmation and binding checks,
concurrent binding lock, rollback/outer commit, first write during
drain, failure retry and shutdown. Real signed ingress, cleanup
confirmation and maintenance-lane removal remain covered by the complete
voice suite.
- The fresh retention fixture first failed on missing schema and now
applies the application migrator. The initial parent merge duplicated a
test import and failed to parse before any voice case ran. Both failures
are retained in the audit; the corrected complete suites pass.
- Prior head `daca270a99` had a failed server (4/12) check, run
40557790710/job 122386307340. Its actual log reports a runner shutdown
and cancellation before completion. This is incomplete acceptance, not a
pass or a proven product flake. New-head CI must pass independently.
- [Current-parent acceptance and failure
ledger](https://github.com/paperclipai/paperclip/blob/68b62b6d13f28ac5f17f35b98adf5488752f9b97/doc/plans/2026-10-25-voice-inbound-retention-sleep-audit.md#current-parent-paging-and-restart-acceptance-october-28)
records the exact scope, commands, counts and preserved failures.
Earlier 218/133/134-case and full-workspace results belong to their
stated heads. No new full local repository suite, live provider, Cloud
wake, host/database suspension or savings claim is made.
- [Notification review repair and current 282-case
evidence](https://github.com/paperclipai/paperclip/blob/68b62b6d13f28ac5f17f35b98adf5488752f9b97/doc/plans/2026-10-25-voice-inbound-retention-sleep-audit.md#configuration-rescan-review-repair-october-28)
records the new source. The prior head had green CI and a 4/5 Ponytail
review; neither is accepted for this new commit. Fresh exact-head
Greptile 5/5 and all CI remain required. Completed actual failing
Ponytail findings must be repaired; a stopped or paused turn without a
verdict is not a merge blocker under the user’s authorization. An active
Ponytail review waits at most 30 minutes from its original request
(25-minute monitor cutoff).

- **Preserved current-master CI failures:** run `40697141057` failed
server shard 7/12 in cleanup’s fairness test and Canary Dry Run on an
npm `rollup-4.66.0.tgz` 404. A fixed final admission UUID reproduces the
same fairness assertion: the second company was sometimes beyond the
first 100-row page, so expecting it among the first 25 calls was
invalid. The corrected test controls time and proves service within the
next 25-call batch after discovery, all 105 successful calls before the
failed provider’s saved retry, exactly one retry at its deadline, and
idle SQL after settlement. Bypassing company rotation fails the
corrected assertion; the shared helper was restored byte-for-byte. Both
complete cleanup (24) and retention (13) suites pass after restoration.
An intermediate 23/24 run incorrectly demanded idle before
reconstruction finished; the audit preserves that failure and its
corrected pending-intent wait. No production behavior, timeouts,
dependencies or workflow gates changed. The exact npm metadata and
tarball now return 200; new-head canary CI must pass independently.
Prior Greptile/Ponytail 5/5 on `768c650365` are stale for this new head.
[Full CI repair
ledger](https://github.com/paperclipai/paperclip/blob/53f2fafcb64d104887eb4455c292b48e6dd10253/doc/plans/2026-10-25-voice-inbound-retention-sleep-audit.md#current-master-ci-repair-october-28).

## Risks

- Supported admission writers must use the existing transaction
notification boundary. Independent SQL writers and additional processes
need a separate wake contract.
- Retention never deletes unconfirmed cleanup or session/task-bound
history. Those records remain with their owners.
- The in-process deadline does not wake stopped compute. This PR does
not extend Cloud alarms or relax sleep eligibility, and does not claim
deployed host/database suspension.
- Call-report reconciliation and other chat maintenance still need
separate migrations.

## Model Used

OpenAI Codex with reasoning, shell, and code-editing tools. The exact
model version and context-window size are not exposed in this session.

## 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 for this new head
- [x] Greptile is 5/5 on this new head with no unresolved actionable
findings
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-28 08:57:58 -05:00
DottaandPaperclip 71b448b9cb fix(server): schedule inbound voice cleanup from durable obligations (#17580)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Incoming voice calls need approval, expiry, and safe provider
cleanup.
> - The remaining voice maintenance tick scans admissions every second,
including idle endpoints.
> - Admission status does not prove that the provider call has ended.
> - Existing admission rows can retain the cleanup owner, confirmation,
and retry deadline.
> - This pull request replaces the cleanup scan with committed changes
and actual deadlines.
> - Idle cleanup stops querying while unfinished calls keep a
recoverable path to termination.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Inbound voice admission cleanup. Its reply-delivery parent #17578 has
landed; this PR targets master. Live-session recovery is in #17576. It
preserves separate ownership for those services.

**Current behavior**

The voice maintenance tick scans expired admissions even when no cleanup
is due. A session can commit before the separate approved-admission
write. Expiry can then terminate that authorized call. A rejected guest
call can be labeled ended before provider termination succeeds.
Seven-day retention can delete that unfinished cleanup.

**Proposed behavior**

Wake cleanup from committed admission and session changes. Schedule the
original expiry or saved retry. Claim current state under the admission
lock before provider I/O. Commit approval with session reservation. Keep
unconfirmed termination durable and transfer bound calls to live-session
recovery.

**Reason and benefit**

Configured idle endpoints and confirmed history cause no recurring
admission cleanup SQL or provider requests. Approval, retries, crash
recovery, and cleanup remain supported. History retention and call
reports stay separate migration items.

## What Changed

- Recover terminal and rejected legacy admissions whose session binding
was lost. Copy known termination or bind a proven matching live session
for cleanup without granting approval.
- Register inbound cleanup with the shared coordinator and scoped
deadline worker. Yield after each 100-row scope page and reset cursors
on registration. Remove only cleanup from periodic voice maintenance.
Keep complete manual reconciliation.
- Add commit-aware notifications at admission, approval, rejection,
guest binding, pending-tool expiry, lifecycle confirmation, and session
termination writes.
- Commit authorized session binding and admission approval together.
Recheck cleanup ownership under the same admission lock. Recover older
interrupted bindings only from matching session evidence.
- Add nullable cleanup confirmation, next-attempt, and provider-account
fields to the existing admission table. No new queue table is added.
Generated migration 0396 backfills only provable historical termination
in committed 1,000-row keyset batches and adds a concurrent partial
index.
- Save the retry before provider contact. An unconfirmed end receipt
retains cleanup. Bound calls remain owned by live-session recovery.
- Verify the signed provider account before using a rotated key for
unbound cleanup. A different account cannot inspect or end the saved
call. Legacy admissions require their original credential fingerprint.
- Prevent history pruning and company deletion from erasing unfinished
cleanup. Company deletion locks endpoints before the voice owner's
check, matching ingress serialization.
- Document producer coverage, ownership, deadlines, verification, and
remaining sleep limits.

## Verification

Published head: `a4e7ccf976fc5793a8914e4e4861aa080d43a4da`. The reply
parent #17578 has landed. A normal merge integrates actual master
`e7ea2e2961863171956e70fb05d3d1f3790f7909`, preserves its unrelated
changes, and regenerates this slice’s migration after landed migration
0395. Fresh exact-head reviews and CI are required.

- The previous Ponytail 3/5 finding is repaired: legacy terminal
admissions no longer enter approval-only repair, and rejected admissions
with valid matching live sessions retain their rejection and persist the
binding needed for session-scoped cleanup confirmation. Five regressions
failed with ownership conflicts before the repair. Five
conflicting-session regressions prevent an unrelated leg from being
claimed. No cleanup operation grants approval or starts a provider call.
- **24 complete cleanup lifecycle cases and 122 complete voice-store
integration cases pass** on the repair. After actual-master integration
and migration regeneration, the complete 24-case cleanup suite passes
again on a new empty PostgreSQL 17 database, and the database migration
integration test passes separately. The cleanup owner, voice-store test
and admission schema are byte-identical to that tested repair; the
cleanup fixture only changes the migration filename. Migration
numbering/safety, database build, production server typecheck and build
pass.
- Migration `0396_tan_paladin.sql` was generated with `pnpm
db:generate`. Every landed SQL migration and the complete parent journal
prefix are unchanged. Generated snapshots retain exactly 0392–0396,
pruning 0391. The reviewed cleanup SQL, concurrent idempotent index and
committed 1,000-row historical backfill are retained byte for byte under
the new generated filename, registered for top-level execution. The real
application migrator boots a fresh database, repairs an interrupted
concurrent index, serializes replays and verifies eligible-history
backfill across actual transactions.
- The preceding published head
`48d8356e73308579470c182e759eead6e83173d2` received Greptile 5/5 but
failed CI server shard 9/12: one existing connected MCP rate-limit test
expected two real-clock calls to share a fixed 60-second bucket. A
controlled window rollover reproduced its exact failure. That existing
fixture now freezes only `Date` around the same-window 429 assertion,
verifies acceptance after advancing one window, and restores the real
clock in `finally`. All 92 gateway acceptance cases pass. Production
rate limiting, timeouts and assertions are unchanged. This adds one
existing CI fixture to the slice; the original failed run remains
recorded.
- The first regression invocation skipped the suite because it used the
wrong database variable; that is not a pass. The corrected invocation
reproduced five ownership conflicts. The first fixed cleanup run passed
22 and failed two new low-level deletion test calls on a
retained-session foreign key; the regressions now check the cleanup
deletion guard at its owning boundary, with production deletion ordering
unchanged. The final full suite passes all 24.
- The first complete voice-store invocation passed 121 and timed out on
one transcript case at the unchanged 15-second limit. That case passed
in isolation on a fresh database. One subsequent complete invocation,
with builds finished, passed all 122 without source, assertion or
timeout changes. The underlying timeout cause is unproven; the original
failure remains recorded. A new PostgreSQL startup also failed from
exhausted host semaphore capacity; fresh databases on the already-owned
server were used without removing shared IPC resources.
- Prior source `b8b12199b9` passed 266 distinct cases and carried three
guarded mutation proofs; those older results are not added to this
repair’s case count. Its CI run 40641168596 failed E2E shard 3 when
legacy cancellation hit a one-second PostgreSQL lock timeout. GitHub
initially rejected a retry while the run was active, then accepted one
targeted retry after completion; attempt 2 passed on that same old head.
The lock holder and underlying cause remain unproven. The unchanged Node
policy checker’s older failure on ignored generated Copilot manifests
and passing tracked-input mirror are also retained in the audit; no
workflow, checker, vendor manifest or ignore rule was modified.
- [Current repair and failure
record](https://github.com/paperclipai/paperclip/blob/a4e7ccf976fc5793a8914e4e4861aa080d43a4da/doc/plans/2026-10-25-voice-inbound-cleanup-sleep-audit.md#legacy-terminal-admissions-missing-their-session-binding--october-28).
Current-head CI and Greptile 5/5 gate merge. A completed failing
Ponytail verdict must be fixed; missing or interrupted reviews do not
block, and active pending review waits are capped at 30 minutes under
the maintainer’s explicit instruction. No new full local repository
suite, real provider, Cloud alarm, host/database suspension or savings
claim is made.

## Risks

- The migration distinguishes admission status from physical
termination. Legacy ended guest rejections without proof remain cleanup
obligations. Missing original credentials can keep those old obligations
unresolved.
- Future writers must use the existing notification boundary.
Independent SQL writers and multiple processes need their own wake
contract.
- Pending inbound cleanup now blocks company deletion instead of
allowing cascade deletion to lose the provider obligation. Existing
voice-history deletion restrictions remain. This deliberately includes
an active anonymous inbound ring and an old call whose termination
cannot be verified. An operator must stop ingress and settle the call
before deletion; this slice adds no abandonment override and never
treats missing credentials as proof of termination. This is the retained
cleanup ownership policy, not a claim that every deletion attempt can
complete immediately.
- History retention and report processing still run in the remaining
maintenance lane. This PR does not extend Cloud wake coverage or claim
measured host/database suspension.

## Model Used

OpenAI Codex (GPT-6), with reasoning and code execution. The exact
serving model ID and context window were not exposed.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] 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-10-28 08:30:15 -05:00
DottaandPaperclip 6ce0909db4 fix(agents): skip runtime probes for unchanged connections (#18016)
## Thinking Path

> - Paperclip manages AI agents and their runtime settings.
> - Operators save identity, model, connection, and run-policy settings
from the agent page.
> - PostgreSQL stores connection bindings as JSONB and can return keys
in a different order.
> - The save route compared JSON strings and treated an unchanged
binding as a new connection.
> - That false change started a remote runtime and credential probe
during ordinary saves.
> - This pull request compares binding values and checks real execution
selection changes separately.
> - Ordinary edits save without a probe. New connections and execution
selections retain validation.

## Linked Issues or Issue Description

Fixes #14518.

Related work: #17760 also addresses prospective environment resolution.
#14027 also adds explicit connection removal. This change is limited to
the save validation gate and its regressions.

**What happened?**

A title-only save took 9.8–16.0 seconds in a hosted reproduction. JSONB
key order made the unchanged AI connection look different. The route
then waited for a remote runtime probe.

**Expected behavior**

Identity, thinking-effort, and run-policy edits skip the probe when the
connection and execution selection stay the same. A changed connection,
harness, model, provider, engine, or environment still validates
adoption.

**Steps to reproduce**

1. Save an agent with a managed AI connection in PostgreSQL.
2. Edit its title or thinking effort without changing the connection or
execution selection.
3. Observe that the old route starts the adapter environment test. The
fixed route saves without that test.

## What Changed

- Use value equality for the stored and validated AI connection
bindings.
- Compare the effective execution selection separately. Preserve runtime
probes for real selection changes and existing Copilot checks.
- Add PostgreSQL route regressions for shared, delegated, default-user,
and pooled bindings. Cover failed connection, model, engine,
environment, and harness changes.
- Keep the existing credential rejection and reconnect tests. Document
the save behavior.

## Verification

- `pnpm -r typecheck` passed on the rebased implementation.
- Focused PostgreSQL 17 route selection: 21 passed, 58 excluded by the
name filter. This covers ordinary saves, selection-change rejection, and
credential health.
- Full PostgreSQL 17 connection suite: 79 passed, zero skipped. Final
`pnpm build` passed at `8fde75fa1a8fe63c71b05a3db149edf289295672`.
- Before the fix, the PostgreSQL regression reached the unintended probe
and failed for unchanged shared, delegated, and default-user bindings.
The pool control passed.
- An early controlled HTTP comparison of the binding fix used a
synthetic 500 ms provider probe: five measured saves had a median of 798
ms before and 56 ms after. Probe count fell from five to zero. This is
local supporting evidence, not a hosted latency result.
- Earlier adjacent-route run: 159 of 160 tests passed. One existing
roster-edit case exceeded its 15-second timeout. That case passed alone
with the normal timeout. The cause of the earlier timeout remains
unproven.
- Local full-repository tests were not run. Native PostgreSQL startup
fails because the host has exhausted System V semaphores. The focused
tests use an isolated PostgreSQL 17 Docker fixture.
- `git diff --check` passed. Hosted improvement remains unverified until
deployment.
- Greptile and Ponytail Paperclip Review both rated the exact head
`8fde75fa1a8fe63c71b05a3db149edf289295672` 5/5, with no actionable
defects.
- CI attempt 1 passed 51 checks. Three self-hosted runners lost
communication, interrupting the chat shard, serialized server shard, and
canary dry run. GitHub annotations identify the runner communication
failures; the serialized shard log also records a shutdown signal. Only
those failed jobs were retried, once, on the unchanged commit. The [full
CI
workflow](https://github.com/paperclipai/paperclip/actions/runs/40692641103/attempts/2)
then passed on attempt 2 at the same commit. All 55 passing checks and
the legacy Snyk status are green; no checks remain pending.

## Risks

This changes when connection adoption validation runs. Separate
selection checks preserve validation for real runtime changes.
Regression tests verify that rejected selections do not replace the
saved configuration. Company access, connection authorization, activity
records, and Copilot checks retain their existing paths. There is no
schema or migration change.

## Model Used

OpenAI Codex, configured model `gpt-6.1-sol` with ultra reasoning. Work
used source inspection, shell tools, browser network timing, and
PostgreSQL route tests. The context window size is not exposed by this
session.

## 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-10-28 08:25:27 -05:00
DottaandPaperclip e93732c3d4 fix(server): deliver voice replies from commits and saved deadlines (#17578)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Phone calls receive approved answers from the existing chat
publication queue.
> - The chat maintenance timer checks for voice replies every second,
including when no reply is ready.
> - A reply can be saved before its publication commits. An early wake
alone can miss that final transition.
> - Existing session, reply, publication, and action rows already record
delivery and recovery work.
> - This pull request uses committed changes and saved deadlines to
drive phone reply delivery.
> - Empty reply queues become quiet while authorization, ordering, and
uncertain-send protection remain in place.

## Linked Issues or Issue Description

Stacked on #17576. Related delivery infrastructure: #15625. Related
voice connection work: #11418.

**What existing behavior does this improve?**

Background phone reply delivery and recovery of abandoned dispatch
intents.

**Current behavior**

Chat maintenance calls voice reply delivery every second. It also scans
old dispatch intents. Publication transport starts a direct push before
the final publication commit. The timer masks that timing gap.

**Proposed behavior**

Committed publication, reply, session, and configuration changes wake
the shared coordinator. Ready replies drain in bounded passes. Saved
rate-limit and dispatch-expiry deadlines retain recovery. An empty queue
or a permanent delivery barrier has no recurring reply scan.

**Reason and benefit**

Remove recurring SQL from idle phone reply delivery without dropping
replies, replaying uncertain sends, or adding a queue table.

**Breaking changes**

No API or schema change. Explicit manual recovery remains available.
Inbound admission cleanup, history retention, and reports remain on
their current paths for separate migrations.

## What Changed

- Extract ordered reply state and multipart policy within the voice
owner. Retain current authorization and atomic dispatch claims.
- Register a scoped reply worker with startup reconstruction, fair work
batches, failure backoff, drain/resume handling and shutdown ownership.
- Extend the existing shared dispatcher with normalized partial-page
results to preserve the bounded parent recovery contract. Existing
complete-array consumers retain their calls.
- Signal before relevant writes in their existing transactions. Both
normal publication completion and operator resolution wake the actual
conversation after commit.
- Bound reply inventory to 100 total headers per refresh. Preserve
partial scans, concurrent changes and newer denied-call restoration
obligations across reconstruction.
- Track abandoned dispatch actions independently of live calls.
Quarantine expired intents without resending them.
- Use existing active-call authorization checks to reactivate replies
that were previously denied. Healthy call inspections do not rescan
empty reply queues.
- Remove the periodic reply scan and the early direct publication push.
Keep provider requests outside database transactions.

## Verification

Published head: `1435cab10be3f95c38ab6672d2a890ae49e9d300`. Voice
recovery #17576 has landed at master
`e1ba77f06771a27114b3999004b0ca5e3c172dd4`. A normal merge reconciles
squash ancestry while preserving the complete reviewed 31-file reply
patch byte for byte and all unrelated master changes. The PR now targets
master; fresh exact-head CI and Greptile are required. The prior
449-case/typecheck/build results below cover the identical owned source,
not a new full-suite run.

- **449 distinct targeted cases pass**: 111 complete voice-store/reply;
19 complete parent recovery; and 319 complete tool-gateway,
secret-proposal, shared dispatcher/coordinator/batching/startup/hostname
cases. Production server typecheck and build pass. The policy checker
and its Node tests pass. Later edits record evidence only.
- Two real normal-publication/operator-resolution tests seed 105
unrelated calls and 105 future dispatches. Five publications selected
**1,065/1,060 inventory rows before repair**; both paths now pass the
same **125-row total budget** and deliver every answer once. This counts
selected SQL results, not physical tuple visits or host savings.
- Publication commits now signal their actual conversation. The voice
reader returns at most 100 total session/action headers per refresh,
preserves phase/cursor state and retries, and resets on worker
registration. Current-state checks and dispatch claims still own
provider effects. The 105-action case measures the page cap, restarts
the same owner during reconstruction, waits at saved future deadlines
and quarantines every abandoned action without resending.
- A real 403 fixture proves that an older broad scan cannot erase a
denied call first observed behind its cursor. Its owner callback still
emits the committed restoration wake after scan completion. The existing
actual-service authority-restoration and final-publication timing tests
remain in the full suite. They are not replaced by direct helper calls.
- Guarded removal of conversation scoping, cursor reset or the denial
revision fence fails the intended budget, 100-versus-5 restart or
missing committed-wake assertion; source is restored. An initial
shadowed fixture name and an inadequate due-action reset probe are
retained as failed attempts in the [current
audit](https://github.com/paperclipai/paperclip/blob/d2c0a7de8c3e9cac8382b1268f3f5d883a2067b3/doc/plans/2026-10-25-voice-reply-delivery-sleep-audit.md#publication-inventory-and-paging-acceptance-october-28).
- Parent recovery still passes paging, restart, behind-cursor insertion,
feature changes, actual disablement, quiet health observations, current
authority, exact-scope failure fences and wildcard-failure isolation
through the shared worker. Four existing array-based worker consumers
retain their API and pass their full suites.
- The two voice fixtures self-migrate separate empty databases. Legacy
tool-review/secrets suites use separate migrated clones. Earlier
full-local attempts remain limited by embedded PostgreSQL setup and are
not passing full-matrix claims. Older counts apply only to their stated
revisions. Fresh exact-head Greptile, Ponytail if present, security and
all CI remain merge gates. No live-provider, multi-writer,
external-wake, deployed-sleep or savings claim is made.

## Risks

- Missing a supported producer can strand work. Tests cover real
enqueue, retrieval, normal publication, and operator publication paths.
Startup reconstructs existing records.
- Signals cover the process-local database owner. Independent SQL
writers or other replicas need their own wake contract.
- Authority restoration relies on the existing live-call recovery check.
This dependency must be preserved if that owner changes later.
- A provider acceptance receipt does not prove speech. Unknown outcomes
remain blocked from automatic resend.
- This change does not extend Cloud alarms, allow sleep during live
calls, or prove deployed suspension or cost savings.

## Model Used

OpenAI GPT-6 via Codex, with repository inspection, reasoning, code
execution and test tools. The runtime does not expose a more specific
deployment identifier or 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 the available 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 described the issue in-PR following the relevant issue
template
- [x] I have not referenced internal or instance-local Paperclip issues
or links
- [x] My branch name describes the change and contains no internal
ticket identifier
- [x] I have run the selected 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 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-10-28 07:50:27 -05:00
DottaandPaperclip e1ba77f067 fix(server): schedule live voice recovery from session changes and deadlines (#17576)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Voice calls retain durable session state and provider identities.
> - The chat maintenance timer scans live voice sessions even when no
call exists.
> - Session writes, saved expiry and active-call inspection deadlines
identify real work.
> - This pull request moves live-session recovery to the shared
coordinator.
> - Idle session recovery becomes quiet without losing exact-call
cleanup or current authorization checks.

## Linked Issues or Issue Description

Refs #17572. This PR is stacked on receiver discovery. It owns only live
voice session recovery. Reply delivery, inbound admission cleanup,
inbound history retention and call reports remain separate migration
slices.

**What happened?**
The one-second chat maintenance lane reads voice settings and scans live
sessions even when an instance has no calls or only terminal history.

**What did you expect?**
Reconstruct live calls on startup. Wake on committed session or
configuration changes. Inspect active calls and retry cleanup at actual
deadlines. Stop querying when no live obligation remains.

**Steps to reproduce**
Start an instance with no live voice sessions. Let startup settle. The
old maintenance method continues to read settings and session inventory
every chat maintenance pass.

## What Changed

- Add a voice-owned bounded deadline reader and scoped worker on the
existing coordinator. Retain concurrent writes across pages and reset
partial scans on restart. No tables or migrations are added.
- Separate generic connection health observations from configuration
changes. Existing receiver and command consumers retain their
notifications. Voice eligibility and provider operations remain in the
voice owner.
- Signal existing session transactions and configuration/feature
changes. Keep provider calls outside database transactions. Standalone
session writes use one small transaction helper.
- Preserve saved expiry, the two-minute unknown-creation grace,
active-call authorization and missed-hangup inspection, and
exact-provider cleanup. Recovery never creates a provider call.
- Retry transient authority lookup failures instead of treating them as
confirmed revocation.
- Fence expiration against a provider identity bound after discovery. A
late known call remains eligible for cleanup.
- Preserve work through rollback, drain, restart, concurrent refresh,
backoff and shutdown. Page inventory and rotate bounded batches across
companies.
- Leave the four other voice maintenance duties in the periodic lane.
- Document producer coverage and the supported writer contract in
`doc/idle-voice-session-recovery.md` and the dated audit.

## Verification

Published head: `f0b2e3cc22a18e7d08b10d4fc02aae4a19a52f30`. Receiver
#17572 has landed in master at
`dce004259394486f6361d0c0dd5a33a5272acc0a`. This normal merge reconciles
squash ancestry; the complete 22-file voice recovery patch is
byte-for-byte identical to the reviewed and tested `ad79c7e805` patch,
while all unrelated master changes are preserved. The PR now targets
master. Fresh exact-head CI and Greptile are running; interrupted
Ponytail turns are not completed verdicts under the maintainer’s
clarified merge policy, and an actual failing verdict still blocks.

- **210 distinct targeted cases pass on the current repair**: 19
complete recovery lifecycle cases and 191 complete voice-store,
coordinator, batching, startup and hostname cases. Production server
typecheck and build pass. Later edits record evidence only.
- CI `40633667141` on prior head `1b6323c164` failed the feature-change
assertion with `34050 < 25000`; its verification aggregate also failed.
The test now disables automatically advancing fake time, drives 20
controlled scheduler turns and requires all 205 calls to close before an
unrelated inspection deadline can mask a lost wake. Removing generation
replay fails with missing closures. The repair does not benchmark
database/host speed or raise the elapsed-time bound.
- A real committed exact-call regression reproduces wildcard-backoff
starvation. The worker keeps the broad retry but processes independent
exact hints and cached due calls. Each check reloads current state and
authority. Failed exact scopes remain fenced. Removing wildcard
isolation fails the intended assertion; a successful broad retry then
leaves the worker SQL-quiet. Full-row and lean queries now share the
state/scope/cursor predicate.
- Earlier acceptance on `712f3862b5` passed 725 distinct targeted cases.
Its measurements remain useful history: five real metadata writes and
one health check over 205 future calls selected 1,230 rows before the
inventory repair and zero afterward, without changing the saved
deadline. Those older test counts are not added to the current 210-case
count.
- Both external voice fixtures self-migrate; the current full
voice-store run uses a separate initially empty database. Earlier
fixture/method/observer failures, source mutations and partial edit
attempts remain in the [current
audit](https://github.com/paperclipai/paperclip/blob/ad79c7e805367fc7e2df3ea53c942ca6c7d27365/doc/plans/2026-10-25-voice-maintenance-sleep-audit.md#wildcard-failure-and-deterministic-generation-acceptance-october-28).
Source is restored after guarded mutations.
- Older CI `40632057899` failed because its trusted policy script was
absent from the checkout, while build separately received a runner
shutdown signal. E2E shards succeeded but their aggregate failed on
policy. The current checkout includes the landed policy tooling and its
checker/tests pass locally. The shutdown cause is unproven; neither old
failed run is counted as passing. Earlier full-local attempts stopped on
embedded PostgreSQL setup failures and did not pass.
- Fresh exact-head Greptile, security and all CI must pass before merge.
A completed failing Ponytail verdict blocks; an interrupted turn without
a verdict does not. No full current local repository matrix, live
provider acceptance, multi-writer support, Cloud wake, host suspension
or savings is claimed.

## Risks

- Process-local hints cover the existing active writer and shared
clients. Independent SQL writers or another replica need explicit wake
integration.
- Membership, task binding, phone preferences and other authority inputs
remain checked on the existing 30-second active-call inspection deadline
and on use. This is not an instant cleanup guarantee for every authority
mutation.
- Unknown creation retains its existing maximum-duration grace. Cleanup
failures retain retries. A provider request is never replayed merely
because its creation response is unknown.
- Genuine configuration changes retain bounded reconstruction. Metadata
writes can probe parent eligibility, while health-only observations
leave voice recovery quiet. Paging state is process-local and
reconstructs from durable rows after restart.
- Active calls, the other voice maintenance owners and connector
transports remain real obligations. This does not expand Cloud alarm
coverage, relax sleep eligibility or prove deployed suspension.
- The receiver and Discord parents have landed. Current-master
compatibility and exact-head CI and Greptile remain merge gates.

## Model Used

OpenAI GPT-6 via Codex, with repository inspection, reasoning, code
execution and test tools. The runtime does not expose a more specific
deployment identifier or 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 linked existing issues or described the issue in-PR
following the relevant issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
ticket identifier
- [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-10-28 07:38:48 -05:00
DottaandPaperclip dce0042593 fix(server): wake chat receiver discovery from configuration and lease deadlines (#17572)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Chat receivers own persistent provider connections and fenced
database leases.
> - The chat maintenance timer repeatedly queries all eligible
receivers, including when none exist.
> - Configuration changes and known lease deadlines already identify
when discovery is needed.
> - This pull request moves receiver discovery to the shared delivery
coordinator.
> - Empty or settled discovery stops querying, while ownership and
recovery remain explicit.

## Linked Issues or Issue Description

Refs #17557. This is the next stacked slice after Discord command
registration. The base is `codex/sleep-19-discord-command-registration`.

**What happened?**
The recurring chat maintenance lane scans receiver inventory and
reconciles Discord and Photon runtimes even when configuration has not
changed.

**Expected behavior**
Reconstruct receiver work at startup. React to committed configuration
changes and local listener retirement. Retry foreign ownership at the
saved lease expiry. Stop discovery when there is no remaining
obligation.

**Steps to reproduce**
Start an instance with no chat endpoints. Let startup finish. Observe
the recurring receiver inventory query from chat maintenance. With a
configured receiver, remove its ownership token while listener shutdown
is delayed and signal a configuration refresh: the old implementation
can replace the listener before shutdown completes.

## What Changed

- Preserve healthy receiver progress after a slow failed batch while
retaining per-receiver retry backoff.

- Register a receiver discovery worker with scoped refreshes, paged
startup inventory, fair batches, and per-receiver or scope failure
backoff.
- Keep owned receiver identities cached without a discovery deadline, so
deletion still stops their listeners.
- Use existing transaction signals for configuration, credentials,
health, access revocation, company deletion, and provider lifecycle
changes. Rename the generic command-only helper to describe its broader
configuration contract.
- Keep lease-key selection with the receiver owner. Shared scheduling
contains no provider protocol.
- Retain stopping ownership until listener shutdown and lease release
complete. Concurrent acquisition joins the existing stop promise.
- Remove receiver discovery from the periodic chat lane. Preserve voice
and the other unmigrated duties.
- Record producer coverage, failure evidence, limits, and remaining work
in `doc/plans/2026-10-25-chat-receiver-discovery-sleep-audit.md`.

## Verification

Published head: `ab39569250f4b699a0ab7a829e66dbe27c15020b`. Discord
#17557 has landed at master `5bf0142d45`. A normal merge reconciles its
squash ancestry by applying only the recorded 27-file receiver patch
from parent `547fdf2139`. Every other path matches that master. Every
server and package production/test file is byte-identical to the
published `6e88ca0201` source that passed the 131-case run, typecheck
and build. Unrelated upstream UI/eval/documentation changes are
preserved. This PR targets master. Fresh exact-head reviews and CI are
required.

- **131 distinct targeted cases pass.** Five complete receiver,
coordinator, batching, startup, and GitHub health error-projection
suites pass 99 cases. Twelve real Discord
automatic-registration/receiver and Slack held-transaction cases pass
separately, with 1,581 other chat integration cases deselected. The
complete Photon channel suite passes 20 cases.
- The standalone receiver and Photon fixtures each reproduced
missing-table failures on separate initially empty PostgreSQL 17
databases. Both now apply pending migrations before client use; their
complete 20-case files pass on those same databases. The large chat
producer suite uses a separate migrated clone.
- The old review concerns already have source fixes: discovery stops
suppress their own completion wake at `1604a9fcba`; slow failed batches
supply `nextRunAtOnError` at `ab56393acc`. Guarded mutations prove the
existing regressions: reenabling the stop wake yields two inventory
reads instead of one, and removing the error deadline fails the 1,100 ms
provider-delay next-wake assertion. Both original source files are
restored byte for byte. Normal full worker and real producer suites pass
with those fixes.
- All 131 distinct targeted cases, production server typecheck and build
pass on source `6e88ca0201`. Exact source comparison carries that
evidence to this normal merge; the unchanged suites were not rerun just
for unrelated upstream changes. Receiver and Photon fixtures
self-migrate separate initially empty databases; the large producer
fixture uses its own migrated clone. Source is unchanged after these
checks. Recorded listener-count warnings and controlled provider failure
logs remain; no assertion was weakened. An initial whole-file identity
check rejected expected parent queue additions; precise patch comparison
confirms those declarations are correctly preserved.
- Old server shard 12 failed because GitHub reports that its self-hosted
runner lost communication. The grouped-test step is cancelled, and the
retained log has no failing assertion or completed summary. The
underlying host/resource/network cause is unproven. That interrupted job
is not a pass; the updated parent and fixture source require a fresh
full CI run.
- [Current acceptance and failure
record](https://github.com/paperclipai/paperclip/blob/ab39569250f4b699a0ab7a829e66dbe27c15020b/doc/plans/2026-10-25-chat-receiver-discovery-sleep-audit.md#compatibility-after-discord-squash-merge-october-27).
Prior 218-case and full-workspace results describe earlier revisions. No
full local repository-suite, multi-writer deployment, Cloud wake, host
suspension, or fleet cost claim is made.

## Risks

- Process-local transaction hints cover the active database owner and
its shared clients. Arbitrary direct SQL or independent configuration
writers need explicit wake integration. Startup/resume reconstruction
and known foreign-lease takeover remain supported; this does not add
general multi-writer discovery.
- Active receiver sockets and lease renewals continue. This change does
not prove host suspension or extend Cloud alarm coverage.
- Configuration signals can arrive during drain, initialization, or
shutdown. The worker preserves dirty scopes and the owner joins listener
retirement before replacement.
- Voice, Teams, milestone projection, publication maintenance, GitHub
recovery, and the remaining stack inventory are separate work.
- The Discord parent has landed and the receiver child now targets
master. Fresh exact-head reviews and all CI must pass before merge.

## Model Used

OpenAI GPT-6 via Codex, with repository inspection, code execution, and
test tools. The runtime does not expose a more specific deployment
identifier or context-window limit.

## 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 linked existing issues or described the issue in-PR
following the relevant issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
ticket identifier
- [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-10-28 07:25:20 -05:00
DottaandPaperclip 7d8bab773d perf: avoid full JIT and activity scans in Mine unread badges (#17973)
## Thinking Path

> - Paperclip helps people manage AI agents and their work.
> - Mine includes tasks the person created, was assigned, or
participated in.
> - Its unread badge ranks the visible personal top 100 before checking
unread state.
> - Correlated participation and privacy predicates can trigger
expensive PostgreSQL JIT work.
> - This change joins native participant IDs before ranking a narrow
candidate projection.
> - A partial actor index avoids scanning company activity history for
each badge.
> - Local representative scoped reads improve while dense unrestricted
overhead remains explicit.

## Linked Issues or Issue Description

**What existing behavior does this improve?** The Mine unread badge in
the company sidebar.

**Current behavior:** A fresh five-minute window recorded 402 ranking
calls and 31.7 seconds of SQL time. Correlated predicates can spend more
time compiling than executing.

**Proposed behavior:** Build the same company-scoped participant set,
use native issue keys, apply fresh authority before the top-100 limit,
then retain the original canonical rank and second unread query.

**Reason and benefit:** Reduce full JIT compilation and avoid an
unindexed company-history activity scan. Realistic activity-only
participation is included in the measurement.

**Breaking changes:** No API or policy change. This PR adds one
concurrent partial index migration. Related Mine rules in #16356 and
#17756 are preserved.

## What Changed

- Join distinct native participant IDs; guard exact legacy text before
UUID conversion.
- Skip redundant activity participation already covered by
creation/assignment. Sort a narrow eligible candidate projection before
canonical activity ranking.
- Share existing pending-request and user-activity predicates with
ordinary Mine reads.
- Add partial `activity_log(company_id, actor_id, entity_id)` for
user-authored issue activity. Register its idempotent concurrent
migration with the existing top-level/invalid-index-repair runner.
- Add real PostgreSQL coverage for visible top 100,
unread/archive/source semantics, exact IDs, company scope and fresh
grant/private-project access.
- Add a pinned service benchmark with separate pre-index/indexed
databases, identical data, full positional equality, ordinary-call
timings, plans and real migration/cancellation proof.

## Verification

- Fourteen focused PostgreSQL 17 tests pass (16.37 s), including
assembled badge routes and grant revocation. Full workspace typecheck
and build pass on the final production sources.
- The earlier full local suite is incomplete: native PostgreSQL startup
exhausted system semaphores, independently reproduced with empty initdb.
All sixteen failed cases passed with task-owned Docker PostgreSQL 17.
This is not counted as a full local-suite pass. Full Linux CI passes on
final head `f44e46ce580e8345209d7165f57bd8bf696c517c`. Greptile and
Paperclip Review are both 5/5 with zero unresolved comments.
- Baseline `70c864633744cd96c0dc7394d631fc7119cd17d2`; source and DDL
hashes retained. Two warmups and five alternating samples per arm/cell.
Capture and EXPLAIN occur outside timed ordinary service calls.
- All twelve 300k-history cells match complete positional rows in both
SQL phases and final returned IDs. Half the personal tasks qualify
through activity alone; the actor index contains matching and
other-human rows.

| Local service case | Before median | After median | Before / after |
| --- | ---: | ---: | ---: |
| dense / unrestricted / JIT on | 18.33 ms | 25.06 ms | 0.73x |
| dense / scoped / JIT on | 909.30 ms | 221.10 ms | 4.11x |
| sparse / unrestricted / JIT on | 13.64 ms | 5.84 ms | 2.34x |
| sparse / scoped / JIT on | 719.07 ms | 10.79 ms | 66.64x |

Small paths add at most 0.6 ms at the median. Dense unrestricted paths
regress by 6.7–7.7 ms; dense scoped JIT-off is approximately neutral
(218.34→223.24 ms). Sparse JIT-off paths improve too. This is not a
uniform speedup.

The actual baseline fails the compiler-work assertion. The final query
avoids full JIT optimization/inlining and exceeds 1.5x where the old
plan triggers those passes. Small/sparse controls meet the 25% or 2 ms
allowance. Dense no-JIT cases are explicit diagnostics. The optional 60
ms absolute goal still fails at 221.10 ms on dense scoped reads:
substantial privacy-predicate execution remains after compilation is
removed. The failure is retained rather than counted as green.

The actual normal migration runner upgraded 300k activity rows in 668.79
ms including inspection, index build/validation and journal work. Rerun
took 21.83 ms; a deliberately cancelled build left an invalid index, and
retry repaired it in 187.71 ms. Concurrent reads/writes completed; the
final index was 188416 bytes. No migration was run on the hosted
database.

The million-row mixed-participation sparse control also passes all four
visibility/JIT pairs with complete equality: unrestricted JIT-on
13.44→5.76 ms; scoped JIT-on 807.76→11.59 ms. The actor branch visits 36
indexed rows rather than scanning company history. Actual
migration+runner took 255.06 ms; rerun 20.32 ms; cancellation
repair/retry 241.73 ms. Concurrent reads and writes completed without
failures.

Reproduce:

```sh
pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-mine-unread-badge.ts --baseline-ref=70c864633744cd96c0dc7394d631fc7119cd17d2 --history-decoys=240000 --verify-migration --assert-performance --evidence-dir=<directory>
```

Add `--fixture=sparse --history-decoys=940000` for the million-row
control. The default harness starts disposable embedded PostgreSQL and
ignores DATABASE_URL. Recorded evidence used PostgreSQL 17.11 through a
scratch constructor provider because the host native runtime has
semaphore limits. All normal database allocation/migration/client paths
are retained.

Source-only EXISTS/lateral alternatives were measured and rejected after
company scans or sparse regressions. A time bound would lose historical
participation, and existing indexes cannot select a user's activity.
This justifies the exceptional partial index migration. The exact sample
ranges, plans, failures, source hashes, migration footprint and
feedback-loop timing are in
`doc/plans/2026-10-27-mine-unread-badge-query.md`.

## Risks

- Dense unrestricted reads are slightly slower, and dense scoped reads
retain substantial authority work. The PR removes a compilation/lookup
bottleneck rather than all badge latency.
- The concurrent build scans activity history and can wait for
long-lived transactions. Local build/cancellation timings do not
guarantee the duration on larger or slower hosted databases.
User-authored issue activity gains one narrow index to maintain.
- Participation, visibility, ranking and legacy ID semantics must remain
exact; the real database regressions exercise those boundaries.
- Hosted improvement is unverified. The affected ranking SQL averaged
78.8 ms while HTTP badge requests averaged 752 ms without correlated
traces. No merge or deployment is included.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning, tool use and local code
execution. The runtime does not expose the exact model ID or context
window to this agent.

## 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-10-28 07:20:08 -05:00
DottaandPaperclip a91f78e7e0 perf(chat): reduce inbound queue discovery cost (#17971)
## Thinking Path

> - Paperclip helps people manage companies of AI agents.
> - External chat messages enter a durable delivery queue.
> - Queue reads must preserve pending wake ownership and conversation
order.
> - Retained processed history increases the estimated cost of a
correlated pending-action test.
> - PostgreSQL 17 enables JIT for these small selectors and reads extra
JSON in deadline discovery.
> - This pull request uses a scoped pending-action set for open-work
discovery.
> - The benefit is less database work with the same selected deliveries
and deadlines.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Inbound delivery deadline discovery and conversation-head selection.

**Subsystem affected**

Server chat queue discovery.

**Current behavior**

A correlated `EXISTS` inside an `OR` has a high cost estimate on
retained completed history. PostgreSQL 17 already hashes its
pending-action read, but the estimate still enables JIT. Deadline
discovery also reads JSON from completed deliveries that have no pending
wake.

**Proposed behavior**

Use `(company_id, endpoint_id, delivery_id)` membership in the
pending-action set for the two open-work selectors. Keep ready-only
evaluation on its original scoped `EXISTS`. Keep retry, lease, ordering,
lifecycle and endpoint rules.

**Reason and benefit**

The local retained-history fixture reduces deadline selection time. The
small control and the final head selection are neutral. Ready-only
selection remains an unchanged control.

**Breaking changes**

None. No API, schema, migration, stored history, worker, timer or
notification changes.

Related work: #17647 and #15927 change inbound wake-notice scheduling
and selection. This PR changes the separate conversation queue ownership
predicate.

## What Changed

- Use a fully scoped pending-action set for open-work discovery. Exclude
null delivery IDs to preserve exact boolean results. Keep duplicate
actions from multiplying deliveries.
- Preserve the original ready-only query.
- Add five real PostgreSQL tests and a reproducible baseline/treatment
benchmark. Capture the complete real service SQL, parameters, positional
rows and execution plans.
- Document the query cause, rejected hypotheses, test results and limits
in `doc/plans/2026-10-27-inbound-queue-query-proof.md`.

## Verification

Pinned pre-fix baseline: `09ad9adce2cf4742944353a3707a2f908e9bb35e`.

Local fixture: Linux ARM64 PostgreSQL 17.11, Node 26.4.0. It has 1500
completed deliveries and actions, two open deliveries, and 32 KiB of
synthetic incompressible JSON per historical delivery. A separate
control has 20 completed rows. The normal settings use JIT on with a
100000 cost threshold, 128 MiB shared buffers and 4 MiB work_mem.

The final quiet retained-history pair measured these local SQL medians.
Each
arm has two warmups and five alternating samples. The small control is
neutral.

| Actual selector | Baseline | Treatment | Complete positional output |
| --- | ---: | ---: | --- |
| Next inbound deadline | 18.78 ms | 1.58 ms | Equal |
| Conversation head | 5.71 ms | 6.18 ms | Equal |
| Ordinary ready control | 9.23 ms | 8.33 ms | Equal ; unchanged |

The deadline plan uses fewer shared buffers. Head physical reads remain
unchanged. Deadline discovery avoids JIT on this fixture. The pristine
head estimate is below the JIT threshold in both arms, and its timing is
neutral. With JIT disabled, deadline discovery still improves; head and
ready timings overlap.

- Red: the unchanged baseline fails the explicit local fixture work
budget for JIT and deadline buffer reads. Green: the treatment passes.
There is no timing threshold in ordinary CI.
- Five new PostgreSQL tests and six existing assembled chat tests pass.
They cover scoped/null/duplicate pending actions, boolean results,
payloads, head barriers, reactions, paused/attention/AgentMail
exclusions, retry/processing deadlines, provider ordering, lease loss,
lifecycle retry and edit/admission races.
- Actual old/new ready selectors have equal error outcomes for unrelated
malformed retry timestamps. An initial AND-only oracle comparison was
inconclusive and is not defect evidence.
- `pnpm -r typecheck` passes.
- `pnpm build` passes.
- Final head `f3cac298d8a8a5377127b0db7057c52019bbe426` passes the
complete [CI
workflow](https://github.com/paperclipai/paperclip/actions/runs/40625611887).
Greptile is 5/5 on that head with no unresolved review threads. The
earlier end-to-end cleanup lock-timeout failure passed on this revision.
- The complete local suite was not run. The host's known native
PostgreSQL startup failure exhausts SysV semaphores. Focused integration
tests use a disposable Docker PostgreSQL constructor through the
existing test seam. Complete final-head CI is required.

Reproduce the real SQL comparison:

```sh
pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-inbound-queue-discovery.ts --baseline-ref=09ad9adce2cf4742944353a3707a2f908e9bb35e --require-work-budget --retained-only
```

Use `--jit-off` for the diagnostic control. The default command uses the
repository's bundled PostgreSQL version and records it in output. The
reported 17.11 run used the existing test constructor seam with a
disposable `postgres:17` container. Raw samples, complete queries,
parameters and plans are emitted as JSON. The benchmark uses disposable
synthetic data and does not read a live database URL.

## Risks

- Query plans depend on data and PostgreSQL settings. These local
measurements do not prove deployed speed or request latency.
- Head selection still reads historical JSON. Action history remains
stored and scanned. This is not a constant-time queue implementation.
- The changed false branch has no retry timestamp cast. Ready-only
parsing, claims and retries stay on their existing query.
- Background SQL totals can overlap. Do not add these savings into an
HTTP latency claim. The largest possible saving for an affected
selection is bounded by its observed SQL time, about 49–53 ms on average
in discovery.

## Model Used

OpenAI Codex, GPT-6 family, with tool use and code execution. The
runtime does not expose the exact model ID or context-window size. Three
parallel agents own separate performance fixes; this PR contains only
the inbound queue fix.

## 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-10-28 07:19:22 -05:00
DottaandPaperclip f69dfc0e23 perf: use indexed latest-run probes for task interruption lists (#17969)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Task lists show the latest run's interruption state for each visible
task.
> - The old lookup applies a coalesced text expression to company run
history.
> - That lookup cannot use the separate binding indexes for a small task
page.
> - This pull request selects the newest run through those existing
indexes.
> - The benefit is less database work with the same interruption result.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

The latest-run lookup used by task-list interruption enrichment.

**Current behavior**

The query scans company history for a coalesced native, first-class, or
legacy task ID. A local two-task fixture inspects 1,506 runs to select
six candidates. A recent hosted sample recorded about 110 ms per
latest-run lookup. This is one part of the list handler, not its whole
latency.

**Proposed behavior**

Probe each existing binding index for the newest candidate. Pick the
newest candidate across the three binding branches. Read the same
evidence fields in the same SQL statement. Preserve native precedence,
first-class precedence, legacy text matching, company scope, and
ordering ties.

**Reason and benefit**

The representative local 100-task page improves from 17.17 ms to 3.00 ms
(5.72×). A modern 100-task page with 40 runs per task improves from
26.78 ms to 3.82 ms (7.02×). All positional SQL fields, row order, and
full service results match.

**Breaking changes**

None. Stored history, API fields, visibility filtering, execution
authority, and external-conversation state are unchanged.

Related behavior: #16965, #17509, #17552. The duplicate search found no
open PR for this query rewrite. ROADMAP.md has no duplicate planned
feature.

## What Changed

- Use three disjoint indexed candidate branches with a lateral
newest-run selection.
- Guard UUID parameters to preserve the old text matching for
noncanonical input.
- Keep final evidence projection in the same database snapshot.
- Add real PostgreSQL work and contract regressions, a pinned-source
benchmark, and a verification note.
- Require the plan regression to find real run-table nodes. Record the
deep-native-history follow-up without adding indexes or DDL.

## Verification

- Baseline red: the real two-task lookup inspects 1,506 run rows and
fails the work bound. The unchanged semantic oracle passes.
- Treatment green: both PostgreSQL query regressions pass. They cover
conflicting bindings, malformed JSON, empty values, noncanonical IDs,
duplicates, foreign companies, missing runs, and timestamp ties across
branches.
- Seven paired PostgreSQL 17.11 cases pass complete positional SQL and
full service equality. Each arm has two warmups and five alternating
measured samples. Fixture payload sizes are random input bytes before
Base64 encoding: 24 KiB becomes 32 KiB of stored text per noise field.
- Representative 100 × 12 history: 17.17 ms (16.79–17.48) → 3.00 ms
(2.64–4.28). Shared buffer hits: 30,033 → 3,400.
- Modern 100 × 40 history: 26.78 ms (25.79–27.40) → 3.82 ms (3.47–4.78).
- The benchmark command, all cases, plans, fixture limits, and
feedback-loop timing are described in [the verification
note](doc/plans/2026-10-27-task-interruption-query-performance.md).
- Reproduce with `pnpm --filter @paperclipai/server exec tsx
../scripts/benchmark-task-interruption.ts
--baseline-ref=09ad9adce2cf4742944353a3707a2f908e9bb35e`.
- `pnpm -r typecheck` and `pnpm build` passed at
`20d46e3a16d10cf3c5399fc1211b17db6a4afdc6`. The current head has the
identical production runtime; it adds one test assertion and
documentation.
- The focused query, real project-access repair/retry, and presentation
suites pass: 19 tests across three files. The earlier plugin-sdk loading
failure is resolved by normal build setup.
- `pnpm test:run` was attempted, then stopped after repeated native
embedded PostgreSQL bootstrap failures. The full local suite is
incomplete. All 16 affected real-DB executor cases pass when rerun with
disposable PostgreSQL 17 in Docker.
- Linux CI passes the full server suites on this head. One unchanged
Runner close fixture failed on the first CI attempt; its source tree is
identical to the passing upstream #17439 baseline. One targeted job
retry passed on the original head. Fresh checks run again for the
test/documentation review fix. A separate macOS diagnostic fails the
unchanged close variants too; that close issue is not diagnosed or
counted as a local pass here.
- The original head passed 55 checks with one neutral result and two
expected Storybook skips. Greptile gave 5/5. The current head adds one
nonempty-plan assertion and documents the deep-history follow-up. Its
focused PostgreSQL suite passes 2/2. Final head
`c1db106d7ab56b530af82d2bb0556feb0eda290b` is mergeable with all CI
checks complete and passing, Greptile 5/5, and no unresolved review
findings; the documented per-task history limitation remains an explicit
follow-up.

## Risks

- More index probes add about 0.43 ms to the one-run tiny control. The
maximum 1,000-task page with one modern run per task is 9.99 → 14.11 ms,
a 4.12 ms regression. Dense history pages save substantially more in the
local fixture.
- Each branch can still walk one task's own history. The first-class and
legacy probes can discard native-bound rows after index lookup. The plan
note specifies a 10,000-run follow-up, migration-free alternatives, and
a measured index-build budget if indexes prove necessary. This PR does
not make work independent of history depth.
- Local SQL results do not prove deployed HTTP gains. The affected query
averaged about 110 ms in the hosted sample; its critical-path
contribution can be smaller because other enrichment reads run
concurrently.
- The main issue-list SQL and external-conversation gates remain
separate work. This PR has no migration or startup job.

## Model Used

OpenAI Codex, GPT-6 family, with code execution and repository tool use.
The runtime does not expose the exact model ID or 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-10-28 07:18:17 -05:00