From 94510d7b2643f817598fe27e8080897bbde39a05 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:36:30 -0600 Subject: [PATCH] fix(github): settle request comments after deliberate waits and refused replies (#22798) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Review agents answer GitHub pull request threads; each request's comment must end in a real reply or an honest final notice > - After #22672 and #22710, 13 of 85 new review-bot comments on staging still ended as status notices, and 10 old placeholders on merged PRs never settled > - Run data on staging shows two causes: runs that yield on purpose to wait for a response (`external_chat_response_waiting`), and runs whose final reply was refused (`responsePublication.state = failed`) > - The first marked inline threads "ended without publishing" while a later run posted the review; the second looked like presentation still pending, forever > - This pull request makes both settle: link the latest response, wait while the task is open, and use the honest notice only when nothing was published > - The benefit is that every request comment ends in a useful final state ## Linked Issues or Issue Description Refs #22672, #22710 **Describe the bug** - On #22732 the author replied on five review threads at once. Each reply woke its own run; those runs yielded with `external_chat_response_waiting`, and a later run posted the review. Four threads still ended with "This turn ended without publishing a final response." - On #22658 (and the other merged PRs with stuck "Working on this…"), the request's run finished `succeeded`/`committed` with no presentation decision because its final reply publication failed after 6 attempts (`publication_refused`). The settle logic treated that as presentation pending and never settled the thread. **Steps to reproduce** 1. An inline request's run yields with a response-wake continuation; a later run publishes a review. 2. Or: an inline request's run finishes with `responsePublication.state = "failed"` and no presentation decision. 3. The thread says "ended without publishing" (1) or stays "Working on this…" forever (2). **Expected behavior** The thread links the latest published response, waits while the task is still open, and otherwise ends with an honest notice. ## What Changed - `githubLatestTaskResponseUrl`: the latest processed GitHub publication (comment, formal review, assessment) for the task after the request arrived. - `githubResponseExecution`: when the request's run did not reply, link that latest response if any. An inline request whose run deliberately waits keeps waiting while the task is open. A run whose reply was refused says so. The main PR comment keeps its passive-wait cancellation (`mainPullResponse`). - `nativePresentationPending` is false when `responsePublication.state = failed`; new `responsePublicationFailed` column. - Terminal sweep decision version is now `v3`, so requests parked under v2 are read again once. ## Verification - New integration tests (red on master, green here): links a waited thread to a later response; settles a waited thread when the task finishes with no response; settles a thread whose run's reply could not be published. - Updated `keeps per-request fallback outside the main GitHub PR review wait`: waits while the task is open, then settles when done. - `keeps native presentation idle until its committed GitHub outcome` (main PR passive) still passes. - `server/src/services/chat-channels/github/` and response comment tests: 67 passed. GitHub integration group: 538 passed before the main-PR scoping fix; the two affected tests pass after it. - After deploy: re-measure the stuck rate on staging for comments created after the deploy. ## Risks - One extra indexed query per request that settles without its own reply (to find the latest response). Settled requests leave the backlog. - A waited inline thread stays "Working on this…" while its task is open and nothing was published yet; that is the honest state. - Separate, not fixed here: why the native finalizer refuses some final replies (`publication_refused`). ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- packages/db/src/client.ts | 1 + .../src/migrations/0505_nice_rawhide_kid.sql | 2 + ...{0500_snapshot.json => 0505_snapshot.json} | 625 +++++++++++++++++- packages/db/src/migrations/meta/_journal.json | 7 + packages/db/src/schema/chat_channels.ts | 4 + .../chat-channels.integration.test.ts | 92 ++- .../github/response-execution.ts | 38 +- .../github/response-run-state.ts | 2 + .../chat-channels/github/response-target.ts | 8 +- .../github/terminal-response-work.test.ts | 42 ++ .../github/terminal-response-work.ts | 11 +- .../services/chat-github-response-comments.ts | 2 +- server/src/services/chat-run-publications.ts | 51 +- 13 files changed, 857 insertions(+), 28 deletions(-) create mode 100644 packages/db/src/migrations/0505_nice_rawhide_kid.sql rename packages/db/src/migrations/meta/{0500_snapshot.json => 0505_snapshot.json} (99%) diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 17ab8ba4a45..a94414df070 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -920,6 +920,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0384_funny_adam_warlock.sql", "0383_tool_review_company_expiry.sql", + "0505_nice_rawhide_kid.sql", ]); async function applyPendingMigrationsManually( diff --git a/packages/db/src/migrations/0505_nice_rawhide_kid.sql b/packages/db/src/migrations/0505_nice_rawhide_kid.sql new file mode 100644 index 00000000000..31b4dfbe93e --- /dev/null +++ b/packages/db/src/migrations/0505_nice_rawhide_kid.sql @@ -0,0 +1,2 @@ +-- paperclip:migration-compat online_compatible: a new partial index built concurrently; no lock held long and the previous release ignores it +CREATE INDEX CONCURRENTLY IF NOT EXISTS "chat_actions_github_task_publications_idx" ON "chat_actions" USING btree ("company_id","endpoint_id",("payload"->'session'->>'issueId'),"updated_at") WHERE "chat_actions"."kind" = 'github_review_publication' and "chat_actions"."status" = 'processed'; \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0500_snapshot.json b/packages/db/src/migrations/meta/0505_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0500_snapshot.json rename to packages/db/src/migrations/meta/0505_snapshot.json index c63960459a8..c2723b7dd0e 100644 --- a/packages/db/src/migrations/meta/0500_snapshot.json +++ b/packages/db/src/migrations/meta/0505_snapshot.json @@ -1,6 +1,6 @@ { - "id": "51525362-c4bc-44be-b4a7-95cb4aae7748", - "prevId": "a80ac568-accd-4c40-b63a-82b870052e0a", + "id": "001ed6d5-4cc4-4f05-91ec-f3031c94bc98", + "prevId": "5d1d8cc7-e7f6-40ce-94c5-dc84dd4210b9", "version": "7", "dialect": "postgresql", "tables": { @@ -3313,6 +3313,153 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.agent_setup_progress": { + "name": "agent_setup_progress", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_id": { + "name": "subject_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'waiting'" + }, + "items": { + "name": "items", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "update_count": { + "name": "update_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "agent_setup_progress_company_idx": { + "name": "agent_setup_progress_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "agent_setup_progress_expires_idx": { + "name": "agent_setup_progress_expires_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "agent_setup_progress_company_id_companies_id_fk": { + "name": "agent_setup_progress_company_id_companies_id_fk", + "tableFrom": "agent_setup_progress", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "agent_setup_progress_status_check": { + "name": "agent_setup_progress_status_check", + "value": "\"agent_setup_progress\".\"status\" in ('waiting', 'in_progress', 'done', 'failed')" + } + }, + "isRLSEnabled": false + }, "public.agent_session_goal_actions": { "name": "agent_session_goal_actions", "schema": "", @@ -10448,6 +10595,40 @@ "method": "btree", "with": {} }, + "chat_actions_github_task_publications_idx": { + "name": "chat_actions_github_task_publications_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "endpoint_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "(\"payload\"->'session'->>'issueId')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"chat_actions\".\"kind\" = 'github_review_publication' and \"chat_actions\".\"status\" = 'processed'", + "concurrently": true, + "method": "btree", + "with": {} + }, "chat_actions_github_terminal_work_idx": { "name": "chat_actions_github_terminal_work_idx", "columns": [ @@ -34245,6 +34426,163 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.google_pending_revocations": { + "name": "google_pending_revocations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "grant_id": { + "name": "grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "source_secret_id": { + "name": "source_secret_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "profile": { + "name": "profile", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_material": { + "name": "token_material", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "token_sha256": { + "name": "token_sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_outcome": { + "name": "last_outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "give_up_at": { + "name": "give_up_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "google_pending_revocations_due_idx": { + "name": "google_pending_revocations_due_idx", + "columns": [ + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "google_pending_revocations_token_idx": { + "name": "google_pending_revocations_token_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "token_sha256", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.grok_bot_dispatches": { "name": "grok_bot_dispatches", "schema": "", @@ -39070,6 +39408,169 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.issue_connection_content_deletions": { + "name": "issue_connection_content_deletions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "requested_by_actor_type": { + "name": "requested_by_actor_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "requested_by_actor_id": { + "name": "requested_by_actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_at": { + "name": "requested_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "progress": { + "name": "progress", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "not_before": { + "name": "not_before", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "issue_connection_content_deletions_issue_idx": { + "name": "issue_connection_content_deletions_issue_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "issue_connection_content_deletions_pending_idx": { + "name": "issue_connection_content_deletions_pending_idx", + "columns": [ + { + "expression": "not_before", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"issue_connection_content_deletions\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "issue_connection_content_deletions_company_id_companies_id_fk": { + "name": "issue_connection_content_deletions_company_id_companies_id_fk", + "tableFrom": "issue_connection_content_deletions", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.issue_create_idempotency_keys": { "name": "issue_create_idempotency_keys", "schema": "", @@ -57788,6 +58289,114 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.stored_object_deletions": { + "name": "stored_object_deletions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "log_store": { + "name": "log_store", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "object_key": { + "name": "object_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "not_before": { + "name": "not_before", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "stored_object_deletions_due_idx": { + "name": "stored_object_deletions_due_idx", + "columns": [ + { + "expression": "not_before", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "stored_object_deletions_company_idx": { + "name": "stored_object_deletions_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.summary_slots": { "name": "summary_slots", "schema": "", @@ -61329,6 +61938,12 @@ "primaryKey": false, "notNull": false }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, "token_hash": { "name": "token_hash", "type": "text", @@ -63773,6 +64388,12 @@ "primaryKey": false, "notNull": false }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, "identity_context_id": { "name": "identity_context_id", "type": "uuid", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 2a863e13abf..39824040b7a 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3522,6 +3522,13 @@ "when": 1795469468402, "tag": "0504_lucky_pepper_potts", "breakpoints": true + }, + { + "idx": 505, + "version": "7", + "when": 1795544784796, + "tag": "0505_nice_rawhide_kid", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/chat_channels.ts b/packages/db/src/schema/chat_channels.ts index 49ecc309ea2..4e6015851e9 100644 --- a/packages/db/src/schema/chat_channels.ts +++ b/packages/db/src/schema/chat_channels.ts @@ -711,6 +711,10 @@ export const chatActions = pgTable( and ${table.status} = 'cancelled' and ${table.result}->>'code' = 'stale_head'`), index("chat_actions_github_check_work_idx").on(table.id).where(sql`${table.kind} = 'github_review_check' and (${table.status} = 'received' or (${table.status} = 'failed' and ${table.result}->>'retryable' = 'true'))`), + index("chat_actions_github_task_publications_idx") + .on(table.companyId, table.endpointId, sql`(${table.payload}->'session'->>'issueId')`, table.updatedAt) + .where(sql`${table.kind} = 'github_review_publication' and ${table.status} = 'processed'`) + .concurrently(), index("chat_actions_github_terminal_work_idx").on(table.id).where(sql`${table.kind} = 'github_response_comment' and ${table.status} = 'processed' and ${table.deliveryId} is not null and coalesce(${table.result}->>'final', 'false') <> 'true'`), diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index 3b43fae37df..08d7ad11389 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -3240,7 +3240,12 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { presentationDecision: { schema: "paperclip.run_presentation_decision.v1", chosenSource: "none", commentAction: "none", reasonCodes: ["yielded_control_plane_wait"] }, } }).where(eq(heartbeatRuns.id, f.run.id)); - await githubResponseCommentService(db, f.providerFetch).processPending(); + const responses = githubResponseCommentService(db, f.providerFetch); + await responses.processPending(); + // The run waits on purpose and the task is open: the request keeps waiting. + expect([...f.responseComments.values()][0].body).toContain("Working on this"); + await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.conversation.issueId!)); + await responses.processPending(); expect([...f.responseComments.values()][0].body).toContain("without publishing a final response"); }); it.each(["same_head", "new_head"] as const)("reuses one main GitHub PR comment across review requests: %s", async headCase => { @@ -3360,6 +3365,91 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { await responses.processPending(); expect(f.responseWrites).toHaveLength(writes); }); + const passiveWait = (key: string) => ({ status: "succeeded" as const, runtimeMode: "native" as const, nativePhase: "committed", resultJson: { + finalizationPhase: "committed", finalizationReasonCode: "external_chat_response_waiting", + nativeResult: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "yielded", + continuation: { kind: "response_wake", idempotencyKey: key } }, + presentationDecision: { schema: "paperclip.run_presentation_decision.v1", chosenSource: "none", + commentAction: "none", reasonCodes: ["yielded_control_plane_wait"] } } }); + it("links a GitHub thread whose run waited to the response a later run published", async () => { + const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100"); + const [firstId] = [...f.responseComments.keys()]; + await db.update(heartbeatRuns).set(passiveWait("first-wait")).where(eq(heartbeatRuns.id, f.run.id)); + const responses = githubResponseCommentService(db, f.providerFetch); + await responses.processPending(); + // The run waits on purpose and the task is still open, so the thread waits too. + expect(f.responseComments.get(firstId)?.body).toContain("Working on this"); + // A response on another pull request bound to the same task is not linked. + const [other] = await db.insert(chatConversations).values({ companyId: f.companyId, endpointId: f.endpoint.id, + issueId: f.conversation.issueId, externalConversationId: "github:paperclipai/paperclip", + externalLabel: "paperclipai/paperclip", externalThreadId: "github:paperclipai/paperclip:4180" }).returning(); + await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpoint.id, conversationId: other.id, + kind: "github_review_publication", providerActionId: `github_publication:${randomUUID()}`, status: "processed", + payload: { operation: "comment", session: { companyId: f.companyId, issueId: f.conversation.issueId, runId: f.run.id } }, + result: { id: "77", url: "https://github.com/paperclipai/paperclip/pull/4180#issuecomment-77" } }); + await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, f.conversation.issueId!)); + await responses.processPending(); + expect(f.responseComments.get(firstId)?.body).toContain("Working on this"); + const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread; + await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread, + trigger: "mention", message: makeMessage({ id: "41802", text: "Fixed this one too", userId: "42", userName: "octocat", mentioned: true }) }); + const [next] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId, + status: "running", runtimeMode: "native", contextSnapshot: await chatWakeContext({ + endpointId: f.endpoint.id, issueId: f.conversation.issueId, provider: "github", providerMessageId: "41802", + }) }).returning(); + await githubChatReviewService(db, f.providerFetch).execute({ ...f.session, runId: next.id }, "comment", + { body: "Re-reviewed both threads", idempotencyKey: "later-response" }); + await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, next.id)); + await responses.processPending(); + expect(f.responseComments.get(firstId)?.body).toMatch(/See the \[latest response\]\(https:\/\/github\.com\//); + }); + it("links a waiting GitHub thread to a later review published only as inline findings", async () => { + const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100"); + const [firstId] = [...f.responseComments.keys()]; + await db.update(heartbeatRuns).set(passiveWait("inline-only-wait")).where(eq(heartbeatRuns.id, f.run.id)); + const responses = githubResponseCommentService(db, f.providerFetch); + await responses.processPending(); + expect(f.responseComments.get(firstId)?.body).toContain("Working on this"); + const reviewId = randomUUID(); + await db.insert(chatGitHubReviews).values({ id: reviewId, companyId: f.companyId, endpointId: f.endpoint.id, + issueId: f.conversation.issueId!, repositoryId: "42", repository: "paperclipai/paperclip", pullNumber: 418, + headSha: "b".repeat(40), deliveryId: "inline-only", configurationRevision: 1, policySnapshot: {} as never, event: {} as never, + state: "completed", publicationReceipts: { "finding:1": { id: "88", + url: "https://github.com/paperclipai/paperclip/pull/418#discussion_r88", digest: "d" } } }); + await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpoint.id, conversationId: f.conversation.id, + kind: "github_review_publication", providerActionId: `github_publication:${randomUUID()}`, status: "processed", + payload: { operation: "assessment", reviewId, session: { companyId: f.companyId, issueId: f.conversation.issueId, runId: f.run.id } }, + result: { reviewId, summaryUrl: null } }); + await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.conversation.issueId!)); + await responses.processPending(); + // The outgoing-text projection drops URL fragments, so the link names the pull request. + expect(f.responseComments.get(firstId)?.body).toContain("See the [latest response](https://github.com/paperclipai/paperclip/pull/418)"); + expect(f.responseComments.get(firstId)?.body).not.toContain("ended without publishing"); + }); + it("settles a waiting GitHub thread once the task finishes without a later response", async () => { + const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100"); + const [firstId] = [...f.responseComments.keys()]; + await db.update(heartbeatRuns).set(passiveWait("only-wait")).where(eq(heartbeatRuns.id, f.run.id)); + const responses = githubResponseCommentService(db, f.providerFetch); + await responses.processPending(); + expect(f.responseComments.get(firstId)?.body).toContain("Working on this"); + await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.conversation.issueId!)); + await responses.processPending(); + expect(f.responseComments.get(firstId)?.body).toContain("ended without publishing a final response"); + }); + it("settles a GitHub thread whose run's final reply could not be published", async () => { + const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100"); + const [firstId] = [...f.responseComments.keys()]; + await db.update(heartbeatRuns).set({ status: "succeeded", runtimeMode: "native", nativePhase: "committed", resultJson: { + finalizationPhase: "committed", finalizationReasonCode: "governed_gate_pending", + responsePublication: { schema: "paperclip.native_response_publication.v1", state: "failed", attempts: 6, + reasonCode: "native_response_publication_failed", lastReason: "publication_refused", nextAttemptAt: null } } }) + .where(eq(heartbeatRuns.id, f.run.id)); + await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.conversation.issueId!)); + const responses = githubResponseCommentService(db, f.providerFetch); + for (let pass = 0; pass < 2; pass++) await responses.processPending(); + expect(f.responseComments.get(firstId)?.body).toContain("reply could not be published"); + }); it("ignores a review request addressed to an external GitHub bot", async () => { const f = await subscribedGitHubFixture("github:paperclipai/paperclip:419"); const wakeCount = f.wakeup.mock.calls.length; diff --git a/server/src/services/chat-channels/github/response-execution.ts b/server/src/services/chat-channels/github/response-execution.ts index 1be29f7fae5..8156dae9561 100644 --- a/server/src/services/chat-channels/github/response-execution.ts +++ b/server/src/services/chat-channels/github/response-execution.ts @@ -1,5 +1,6 @@ import type { Db } from "@paperclipai/db"; -import { githubRunReplyState } from "../../chat-run-publications.js"; +import { githubLatestTaskResponseUrl, githubRunReplyState } from "../../chat-run-publications.js"; +import { baseThreadId, isMainPullThread } from "./response-target.js"; import { FINISHED_RUN_STATUSES, readGitHubResponseRun, type GitHubResponseRunRead, type GitHubResponseRunState } from "./response-run-state.js"; export { responseRunColumns as githubResponseRunColumns } from "./response-run-state.js"; @@ -12,8 +13,18 @@ export type GitHubResponseExecutionInput = { sourceMessageId: string | null; issueStatus: string; deliveryCreatedAt: Date; + /** The request's conversation thread, such as `github:owner/repo:12` or `github:owner/repo:12:rc:34`. */ + threadId: string; }; +const STATUS_TEXT = { + handled: "This request has been handled. See the response in this conversation.", + paused: "Work is paused. Your request is saved. See the Paperclip task for details.", + publish_failed: "This turn's reply could not be published. See the Paperclip task for details.", + ended: "This turn ended without publishing a final response. See the Paperclip task for details.", + stopped: "This turn stopped before completing. See the Paperclip task for details.", +} as const; + const finished = (status: string | undefined) => (FINISHED_RUN_STATUSES as readonly string[]).includes(status ?? ""); /** Whether the task is idle and this request settles from the earlier run that @@ -43,13 +54,26 @@ export async function githubResponseExecution(db: Db, input: GitHubResponseExecu : input.issueStatus === "blocked" && latestRun?.status !== "running"; const presentationPending = !!run && answersRequest && run.nativePresentationPending && reply === "none"; const passiveResponseWait = !!run && answersRequest && run.passiveResponseWait && reply === "none"; - const body = presentationPending ? undefined : run ? reply === "confirmed" ? "This request has been handled. See the response in this conversation." - : paused ? "Work is paused. Your request is saved. See the Paperclip task for details." - : run.status === "succeeded" ? "This turn ended without publishing a final response. See the Paperclip task for details." - : "This turn stopped before completing. See the Paperclip task for details." - : paused ? "Work is paused. Your request is saved. See the Paperclip task for details." : undefined; + const unanswered = !!run && !presentationPending && reply === "none" && !paused; + const latestResponse = unanswered ? await githubLatestTaskResponseUrl(db, { companyId: input.companyId, + endpointId: input.endpointId, issueId: input.issueId, since: input.deliveryCreatedAt, baseThreadId: baseThreadId(input.threadId) }) + : null; + const taskFinished = ["done", "cancelled"].includes(input.issueStatus); + // Precedence: a later published response is more useful to the reader than + // any notice about this request's own run, including a refused reply. + const outcome: keyof typeof STATUS_TEXT | "link" | "waiting" | null = + presentationPending ? null + : !run ? paused ? "paused" : null + : reply === "confirmed" ? "handled" + : paused ? "paused" + : latestResponse ? "link" + : run.passiveResponseWait && !isMainPullThread(input.threadId) && !taskFinished ? "waiting" + : run.responsePublicationFailed ? "publish_failed" + : run.status === "succeeded" ? "ended" : "stopped"; + const body = outcome === null || outcome === "waiting" ? undefined + : outcome === "link" ? `See the [latest response](${latestResponse}).` : STATUS_TEXT[outcome]; return { - body, paused, reply, running: requestRunning, presentationPending, passiveResponseWait, + body, outcome, paused, reply, running: requestRunning, presentationPending, passiveResponseWait, versionAt: run ? new Date(Math.max(run.updatedAt.getTime(), input.deliveryCreatedAt.getTime())) : paused ? input.deliveryCreatedAt : undefined, version: JSON.stringify([latestRun?.id ?? null, latestRun?.status ?? null, diff --git a/server/src/services/chat-channels/github/response-run-state.ts b/server/src/services/chat-channels/github/response-run-state.ts index 71a34839ebb..0f023d3f3a6 100644 --- a/server/src/services/chat-channels/github/response-run-state.ts +++ b/server/src/services/chat-channels/github/response-run-state.ts @@ -24,6 +24,7 @@ export const responseRunColumns = { nativePresentationPending: sql`coalesce( ${heartbeatRuns.status} = 'succeeded' and ${heartbeatRuns.runtimeMode} = 'native' + and ${heartbeatRuns.resultJson} #>> '{responsePublication,state}' is distinct from 'failed' and (${heartbeatRuns.nativePhase} is distinct from 'committed' or ${heartbeatRuns.resultJson}->'presentationDecision'->>'schema' is distinct from 'paperclip.run_presentation_decision.v1' or coalesce(${heartbeatRuns.resultJson}->'presentationDecision'->>'commentAction', '') not in ('none', 'create', 'reuse')), @@ -31,6 +32,7 @@ export const responseRunColumns = { )`, // Project only the server-committed no-publication decision, never the // potentially large native result or model-authored summary. + responsePublicationFailed: sql`coalesce(${heartbeatRuns.resultJson} #>> '{responsePublication,state}' = 'failed', false)`, passiveResponseWait: sql`coalesce( ${heartbeatRuns.status} = 'succeeded' and ${heartbeatRuns.runtimeMode} = 'native' diff --git a/server/src/services/chat-channels/github/response-target.ts b/server/src/services/chat-channels/github/response-target.ts index b45ef3c8d81..f80b416ffe5 100644 --- a/server/src/services/chat-channels/github/response-target.ts +++ b/server/src/services/chat-channels/github/response-target.ts @@ -14,8 +14,14 @@ export type GitHubResponseSource = { repositoryId?: string; }; +/** A pull request's main conversation; inline review threads add `:rc:`. */ +const MAIN_PULL_THREAD = "^github:[^:]+:[1-9][0-9]*$"; +export const isMainPullThread = (threadId: string) => new RegExp(MAIN_PULL_THREAD).test(threadId); +/** The conversation thread the request's pull request or issue starts from. */ +export const baseThreadId = (threadId: string) => threadId.replace(/:rc:[1-9][0-9]*$/, ""); + export const isMainPullResponse = (source: GitHubResponseSource) => - !source.replyId && /^github:[^:]+:[1-9][0-9]*$/.test(source.conversation.externalThreadId); + !source.replyId && isMainPullThread(source.conversation.externalThreadId); export const requestResponseMarker = (source: GitHubResponseSource) => ``; diff --git a/server/src/services/chat-channels/github/terminal-response-work.test.ts b/server/src/services/chat-channels/github/terminal-response-work.test.ts index f5781c0daaf..ef4d8c9f33c 100644 --- a/server/src/services/chat-channels/github/terminal-response-work.test.ts +++ b/server/src/services/chat-channels/github/terminal-response-work.test.ts @@ -237,6 +237,48 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", () expect(new Set(acknowledged)).toEqual(new Set(f.stale.map(request => request.deliveryId))); }, 300_000); + it("reads a waiting inline request again once a reply is published, without a hint", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const f = await seed(); + const client = db.$client, issueId = f.runs[0]!.issueId; + const [{ main, resource }] = await client.unsafe(`select id as main, resource_id as resource from chat_conversations + where issue_id = $1 and external_thread_id = 'github:paperclipai/paperclip:1'`, [issueId]); + const [{ conversation }] = await client.unsafe(`insert into chat_conversations (company_id, endpoint_id, issue_id, resource_id, + external_conversation_id, external_label, external_thread_id) + values ($1, $2, $3, $4, 'github:paperclipai/paperclip:1:rc:5001', 'thread', 'github:paperclipai/paperclip:1:rc:5001') + returning id as conversation`, [f.companyId, f.endpointId, issueId, resource]); + const [{ delivery }] = await client.unsafe(`insert into chat_deliveries (company_id, endpoint_id, provider_event_id, + deduplication_key, event_kind, normalized_event, conversation_id, state) + values ($1, $2, 'inline-wait', 'inline-wait', 'message', '{}', $3, 'processed') returning id as delivery`, + [f.companyId, f.endpointId, conversation]); + const [{ comment }] = await client.unsafe(`insert into issue_comments (company_id, issue_id, body) + values ($1, $2, 'Fixed') returning id as comment`, [f.companyId, issueId]); + await client.unsafe(`insert into chat_message_links (company_id, endpoint_id, conversation_id, delivery_id, comment_id, + provider_message_id, direction) values ($1, $2, $3, $4, $5, 'inline-wait-in', 'inbound')`, + [f.companyId, f.endpointId, conversation, delivery, comment]); + await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpointId, conversationId: conversation, + deliveryId: delivery, kind: "github_response_comment", providerActionId: `github_response:${delivery}`, + payload: { agentId: f.agentId }, status: "processed", + result: { id: "9001", url: "https://github.com/paperclipai/paperclip/pull/1#discussion_r9001", final: false, + versionAt: new Date(Date.UTC(2026, 9, 28)).toISOString() } }); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, nativeIssueId: issueId, issueId, + scopeKind: "issue", status: "succeeded", runtimeMode: "native", nativePhase: "committed", + contextSnapshot: { issueId, wakeCommentId: comment }, createdAt: new Date(Date.UTC(2026, 9, 28) + 3_000_000), + resultJson: { finalizationPhase: "committed", finalizationReasonCode: "external_chat_response_waiting", + nativeResult: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "yielded", + continuation: { kind: "response_wake", idempotencyKey: "inline-wait" } }, + presentationDecision: { schema: "paperclip.run_presentation_decision.v1", chosenSource: "none", + commentAction: "none", reasonCodes: ["yielded_control_plane_wait"] } } }); + await start(); await advance(5_000); + expect(acknowledged).not.toContain(delivery); + await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpointId, conversationId: main, + kind: "github_review_publication", providerActionId: `github_publication:${randomUUID()}`, status: "processed", + payload: { operation: "comment", session: { companyId: f.companyId, issueId, runId: f.runs[0]!.runId } }, + result: { id: "9002", url: "https://github.com/paperclipai/paperclip/pull/1#issuecomment-9002" } }); + await companyHint(f.companyId); await advance(31_000); + expect(acknowledged).toContain(delivery); + }, 300_000); + it("acknowledges every owed request of a page when one run's requester provenance changed", async () => { vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); const f = await seed("received"); diff --git a/server/src/services/chat-channels/github/terminal-response-work.ts b/server/src/services/chat-channels/github/terminal-response-work.ts index 0915d04239f..5195a749c35 100644 --- a/server/src/services/chat-channels/github/terminal-response-work.ts +++ b/server/src/services/chat-channels/github/terminal-response-work.ts @@ -8,7 +8,7 @@ import { githubResponseExecution } from "./response-execution.js"; import { readGitHubResponseRuns, type GitHubResponseRunRead } from "./response-run-state.js"; import { githubResponseReconstructionIntervalMs, type GitHubResponseSweepScope as Scope } from "./response-sweep-scope.js"; import { HttpError } from "../../../errors.js"; -export const GITHUB_TERMINAL_RESPONSE_DECISION_VERSION = "v2"; +export const GITHUB_TERMINAL_RESPONSE_DECISION_VERSION = "v3"; type Entry = { id: string; companyId: string; endpointId: string; deliveryId: string; issueId: string; conversationId: string; repositoryId: string | null; number: number | null; dueAt: number }; @@ -49,14 +49,19 @@ export function registerGitHubTerminalResponseWork( // the request's own row changes. Such a request records this key, and a broad // rebuild skips it until one of them changes. A targeted load still reads it. const actionVersion = sql`extract(epoch from ${chatActions.updatedAt})::text`; + const latestPublication = sql`coalesce((select extract(epoch from max(p.updated_at))::text from ${chatActions} p + where p.company_id = ${chatActions.companyId} and p.endpoint_id = ${chatActions.endpointId} + and p.kind = 'github_review_publication' and p.status = 'processed' + and p.payload->'session'->>'issueId' = ${issues.id}::text), 'none')`; const waitKey = sql`${GITHUB_TERMINAL_RESPONSE_DECISION_VERSION} || '|' || coalesce(${latestIssueRun.version}, 'none') - || '|' || ${issues.status} || '|' || ${actionVersion}`; + || '|' || ${issues.status} || '|' || ${actionVersion} || '|' || ${latestPublication}`; async function page(scope?: Scope, cursor?: string, actionId?: string) { return db.select({ id: chatActions.id, companyId: chatActions.companyId, endpointId: chatActions.endpointId, deliveryId: chatActions.deliveryId, conversationId: chatConversations.id, issueId: issues.id, agentId: chatEndpoints.assignedAgentId, issueStatus: issues.status, - deliveryCreatedAt: chatDeliveries.createdAt, repositoryId, number, result: chatActions.result, actionVersion, waitKey, + deliveryCreatedAt: chatDeliveries.createdAt, repositoryId, number, + threadId: chatConversations.externalThreadId, result: chatActions.result, actionVersion, waitKey, sourceMessageId: sql`(select l.comment_id from ${chatMessageLinks} l where l.company_id = ${chatActions.companyId} and l.endpoint_id = ${chatActions.endpointId} and l.delivery_id = ${chatActions.deliveryId} and l.direction = 'inbound' limit 1)`, diff --git a/server/src/services/chat-github-response-comments.ts b/server/src/services/chat-github-response-comments.ts index b3f439f75c5..52fbcea3f4a 100644 --- a/server/src/services/chat-github-response-comments.ts +++ b/server/src/services/chat-github-response-comments.ts @@ -246,7 +246,7 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) { companyId: source.endpoint.companyId, endpointId: source.endpoint.id, agentId: source.endpoint.assignedAgentId!, issueId: source.conversation.issueId!, deliveryId, sourceMessageId: source.sourceMessageId, issueStatus: source.issueStatus, - deliveryCreatedAt: source.delivery.createdAt, + deliveryCreatedAt: source.delivery.createdAt, threadId: source.conversation.externalThreadId, }); if (execution.reply === "unsettled") { // An acknowledged request waits for its reply to settle without diff --git a/server/src/services/chat-run-publications.ts b/server/src/services/chat-run-publications.ts index 9dfae17c724..6ee49861800 100644 --- a/server/src/services/chat-run-publications.ts +++ b/server/src/services/chat-run-publications.ts @@ -4,19 +4,7 @@ import { enqueueSafeNativeChatProgress } from "./chat-native-progress.js"; export { enqueueSafeNativeChatProgress } from "./chat-native-progress.js"; import type { ChatRunMilestoneScope } from "./chat-run-milestone-notifications.js"; import { notifyChatPublicationWork } from "./chat-work-notifications.js"; -import { - and, - asc, - eq, - gt, - gte, - inArray, - isNull, - ne, - notExists, - or, - sql, -} from "drizzle-orm"; +import { and, asc, eq, gt, gte, inArray, isNull, ne, notExists, or, sql, desc } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { agents, @@ -117,6 +105,43 @@ export async function resolveChatRunPresentationAuthorizationReason( return CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON; } +/** The latest response the agent published on GitHub for the task after + * `since`, in a conversation of the same pull request or issue. A processed + * publication's updated time is when GitHub accepted it. */ +export async function githubLatestTaskResponseUrl( + db: Db, + input: { companyId: string; endpointId: string; issueId: string; since: Date; baseThreadId: string }, +): Promise { + // An assessment published only as inline findings has no summary URL; its + // finding receipts on the saved review hold the published comment URLs. + const url = sql`coalesce(${chatActions.result}->>'summaryUrl', ${chatActions.result}->>'url', + (select receipt.value->>'url' from ${chatGitHubReviews} review, jsonb_each(review.publication_receipts) receipt + where review.company_id = ${chatActions.companyId} and review.endpoint_id = ${chatActions.endpointId} + and review.issue_id = ${input.issueId}::uuid + and review.id = (case when coalesce(${chatActions.payload}->>'reviewId', ${chatActions.result}->>'reviewId') + ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + then coalesce(${chatActions.payload}->>'reviewId', ${chatActions.result}->>'reviewId')::uuid end) + and receipt.value->>'url' like 'https://github.com/%' + order by receipt.key limit 1))`; + const [latest] = await db.select({ url }).from(chatActions).innerJoin(chatConversations, and( + eq(chatConversations.id, chatActions.conversationId), eq(chatConversations.companyId, chatActions.companyId), + eq(chatConversations.endpointId, chatActions.endpointId), + sql`(${chatConversations.externalThreadId} = ${input.baseThreadId} + or ${chatConversations.externalThreadId} like ${input.baseThreadId.replace(/[\\%_]/g, "\\$&") + ":rc:%"})`, + )).where(and( + eq(chatActions.companyId, input.companyId), + eq(chatActions.endpointId, input.endpointId), + eq(chatActions.kind, "github_review_publication"), + eq(chatActions.status, "processed"), + sql`${chatActions.payload}->'session'->>'companyId' = ${input.companyId}`, + sql`${chatActions.payload}->'session'->>'issueId' = ${input.issueId}`, + sql`${chatActions.payload}->>'operation' in ('comment', 'formal_review', 'assessment')`, + sql`${url} like 'https://github.com/%'`, + sql`${chatActions.updatedAt} > ${input.since.toISOString()}::timestamptz`, + )).orderBy(desc(chatActions.updatedAt)).limit(1); + return latest?.url ?? null; +} + /** A missing receipt is not proof that a provider write never arrived. */ export async function githubRunReplyState( db: Db,