From 3a5ee878cf00af9a7de27dbc9b6daf24457fe896 Mon Sep 17 00:00:00 2001 From: Tanner Polley <42780259+tannerpolley@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:23:01 -0700 Subject: [PATCH 1/2] feat(issues): move thread issue links onto thread.issues A managed claim now writes its thread.issues[] link in the event that creates the claimed thread, and unmanaged delegated children link through upstream's thread link command. A one-time startup backfill moves the issue_thread_links rows, and claims made before claims carried links, onto thread.issues[] with commands keyed by thread and issue. The table reads, issues.unlink and the table's refresh stream are gone; linkedIssue stays the claim record and still counts as live work after its link is removed. Closes #455. Part of #451. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/ForkWsRpc.ts | 3 - apps/server/src/auth/RpcAuthorization.test.ts | 3 +- .../src/issues/IssueLinkBackfill.test.ts | 204 ++++++++++++++++++ apps/server/src/issues/IssueLinkBackfill.ts | 156 ++++++++++++++ apps/server/src/issues/IssueLinks.test.ts | 148 ++++--------- apps/server/src/issues/IssueLinks.ts | 86 +------- apps/server/src/issues/IssueRoadmap.test.ts | 4 +- apps/server/src/issues/IssueRoadmap.ts | 134 ++++++------ apps/server/src/issues/IssueRpcTables.ts | 1 - apps/server/src/issues/IssueService.test.ts | 1 - .../src/issues/IssueWorkProjection.test.ts | 22 +- .../mcp/IssueReviewDelegation.fork.test.ts | 66 ++++-- apps/server/src/mcp/ManagedIssueDelegation.ts | 61 ++++-- apps/server/src/mcp/OrchestratorMcpService.ts | 2 +- .../ForkHistoryMaintenance.ts | 1 - .../src/orchestration-v2/IssueWorkCommands.ts | 42 +++- .../src/orchestration-v2/Orchestrator.ts | 10 +- ...adLaunchService.readOnlyLimit.fork.test.ts | 21 +- apps/server/src/server.ts | 2 + .../components/issues/IssueDetailActions.tsx | 52 +---- .../components/issues/IssueWorkSection.tsx | 3 - .../issues/issueDetailActions.logic.test.ts | 34 --- .../issues/issueDetailActions.logic.ts | 15 -- docs/operations/fork.md | 6 +- .../src/state/commandPermissions.test.ts | 5 +- .../src/state/repositoryIssues.ts | 4 - packages/contracts/src/issueLinks.ts | 27 +-- packages/contracts/src/issueRpc.ts | 10 - packages/contracts/src/repositoryIssue.ts | 2 - scripts/fork-dev/seed.py | 17 +- 30 files changed, 669 insertions(+), 473 deletions(-) create mode 100644 apps/server/src/issues/IssueLinkBackfill.test.ts create mode 100644 apps/server/src/issues/IssueLinkBackfill.ts diff --git a/apps/server/src/ForkWsRpc.ts b/apps/server/src/ForkWsRpc.ts index 99047783917c7..196b6cf3e397c 100644 --- a/apps/server/src/ForkWsRpc.ts +++ b/apps/server/src/ForkWsRpc.ts @@ -22,7 +22,6 @@ import type * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; import * as OwnerDecisions from "./issues/OwnerDecisions.ts"; import * as IssueCleanup from "./issues/IssueCleanup.ts"; import * as IssueChangeService from "./issues/IssueChangeService.ts"; -import * as IssueLinks from "./issues/IssueLinks.ts"; import * as IssueInbox from "./issues/IssueInbox.ts"; import * as IssueRoadmap from "./issues/IssueRoadmap.ts"; import * as IssueService from "./issues/IssueService.ts"; @@ -50,7 +49,6 @@ const layerForkWsRpc = (currentSession: EnvironmentAuth.AuthenticatedSession) => const inlineShell = yield* InlineShellRuns; const workspace = yield* ThreadWorkspaceService.ThreadWorkspaceService; const issues = yield* IssueService.IssueService; - const issueLinks = yield* IssueLinks.IssueLinks; const cleanup = yield* IssueCleanup.IssueCleanup; const roadmap = yield* IssueRoadmap.IssueRoadmap; const issueWork = yield* IssueWorkService.IssueWorkService; @@ -134,7 +132,6 @@ const layerForkWsRpc = (currentSession: EnvironmentAuth.AuthenticatedSession) => [WS_METHODS.issueWorkRoadmap]: (input) => roadmap.list(input), [WS_METHODS.issuesCleanup]: (input) => cleanup.cleanup(input), [WS_METHODS.issueWorkSetState]: (input) => issues.setState(input), - [WS_METHODS.issuesUnlink]: (input) => issueLinks.link(input, undefined, true), [WS_METHODS.issueWorkDetail]: (input) => roadmap.detail(input), [WS_METHODS.issuesStatusBatch]: (input) => roadmap.statusBatch(input), [WS_METHODS.issuesSubscribeLinkRefreshes]: () => roadmap.linkRefreshes, diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index a52a4d1bb6749..2232c6a168ed4 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -77,12 +77,11 @@ it.effect( ); describe("RPC authorization scopes", () => { - it("guards issue state writes and unlink separately", () => { + it("guards issue state writes and repository limits", () => { expect(requiredScopeForRpcMethod(WS_METHODS.issuesCleanup)).toBe(AuthSourceControlWriteScope); expect(requiredScopeForRpcMethod(WS_METHODS.issueWorkSetState)).toBe( AuthSourceControlWriteScope, ); - expect(requiredScopeForRpcMethod(WS_METHODS.issuesUnlink)).toBe(AuthOrchestrationOperateScope); expect(requiredScopeForRpcMethod(WS_METHODS.issuesSetReadOnlyLimit)).toBe( AuthOrchestrationOperateScope, ); diff --git a/apps/server/src/issues/IssueLinkBackfill.test.ts b/apps/server/src/issues/IssueLinkBackfill.test.ts new file mode 100644 index 0000000000000..6779da00890c5 --- /dev/null +++ b/apps/server/src/issues/IssueLinkBackfill.test.ts @@ -0,0 +1,204 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { + CommandId, + IssueOperationError, + IssueTrackerKind, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as TrackerIssueService from "../issue/IssueService.ts"; +import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import * as EventSink from "../orchestration-v2/EventSink.ts"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as IssueLinkBackfill from "./IssueLinkBackfill.ts"; + +const instanceId = ProviderInstanceId.make("codex"); +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + openSession: () => Effect.die("No provider runs in a link backfill"), +} as unknown as ProviderAdapter.ProviderAdapterV2["Service"]; +const projectId = ProjectId.make("project:backfill"); +const claim = (number: number, title: string) => ({ + host: "github.com", + repository: "Owner/Repo", + repositoryId: "repo", + id: String(number), + nodeId: `I_${number}`, + number, + url: `https://github.com/Owner/Repo/issues/${number}`, + title, +}); + +function setup() { + const reads: string[] = []; + let titleReadsFail = true; + const database = SqlitePersistence.layerMemory; + const layer = Layer.mergeAll( + database, + ProviderReplayHarness.layerWithRegistry( + { name: "issue-link-backfill" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: database, runEffectWorker: false }, + ), + Layer.mock(TrackerIssueService.IssueService)({ + detail: (ref) => { + reads.push(ref.key); + return ref.key === "14" && titleReadsFail + ? Effect.fail(new IssueOperationError({ operation: "detail", detail: "offline" })) + : Effect.succeed({ title: `Issue ${ref.key}` } as never); + }, + }), + ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); + return { + layer, + reads, + restoreTitleReads: () => { + titleReadsFail = false; + }, + }; +} + +const create = (id: string, linkedIssue?: ReturnType) => + Effect.flatMap(Orchestrator.OrchestratorV2, (orchestrator) => + orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`create:${id}`), + threadId: ThreadId.make(id), + projectId, + title: id, + ...(linkedIssue === undefined ? {} : { linkedIssue }), + modelSelection: { instanceId, model: "gpt-6" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }), + ); +const links = (id: string) => + Effect.flatMap(Orchestrator.OrchestratorV2, (orchestrator) => + orchestrator + .getThreadShell(ThreadId.make(id)) + .pipe(Effect.map((shell) => (shell?.issues ?? []).map(({ key, title }) => [key, title]))), + ); + +it.effect( + "moves table rows and old claims onto thread links once, and keeps a row whose title read failed", + () => { + const h = setup(); + return Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + yield* create("ordinary"); + yield* create("old-claim", claim(15, "Claimed title")); + yield* create("removed-claim", claim(16, "Removed")); + yield* create("deleted"); + // A claim made now carries its link; an old claim's projection has none. + assert.deepEqual(yield* links("old-claim"), [["15", "Claimed title"]]); + yield* sql`UPDATE orchestration_v2_projection_threads + SET payload_json = json_remove(payload_json, '$.issues') WHERE thread_id = 'old-claim'`; + yield* orchestrator.dispatch({ + type: "thread.issue.unlink", + commandId: CommandId.make("user-unlinks-claim"), + threadId: ThreadId.make("removed-claim"), + tracker: IssueTrackerKind.make("github"), + host: "github.com", + scope: "owner/repo", + key: "16", + }); + yield* sql`UPDATE orchestration_v2_projection_threads + SET deleted_at = '2026-11-17T00:00:00.000Z' WHERE thread_id = 'deleted'`; + for (const [number, thread] of [ + [13, "ordinary"], + [14, "ordinary"], + [15, "old-claim"], + [13, "deleted"], + [13, "missing"], + ] as const) + yield* sql`INSERT INTO issue_thread_links(host, repository, issue_number, thread_id) + VALUES ('github.com', 'owner/repo', ${number}, ${thread})`; + const rows = sql<{ + thread_id: string; + issue_number: number; + }>`SELECT thread_id, issue_number FROM issue_thread_links ORDER BY thread_id, issue_number`; + + yield* IssueLinkBackfill.run(); + assert.deepEqual(yield* links("ordinary"), [["13", "Issue 13"]]); + assert.deepEqual(yield* links("old-claim"), [["15", "Claimed title"]]); + assert.deepEqual(yield* links("removed-claim"), []); + // A claim's own title names it; each other issue is read once. + assert.deepEqual(h.reads, ["13", "14"]); + assert.deepEqual(yield* rows, [{ thread_id: "ordinary", issue_number: 14 }]); + const shell = yield* orchestrator.getThreadShell(ThreadId.make("ordinary")); + assert.deepEqual( + shell?.issues?.map(({ tracker, host, scope, projectId, url, displayKey, source }) => ({ + tracker, + host, + scope, + projectId, + url, + displayKey, + source, + })), + [ + { + tracker: "github", + host: "github.com", + scope: "owner/repo", + projectId, + url: "https://github.com/owner/repo/issues/13", + displayKey: "#13", + source: "agent", + }, + ], + ); + + h.restoreTitleReads(); + yield* IssueLinkBackfill.run(); + assert.deepEqual(yield* links("ordinary"), [ + ["13", "Issue 13"], + ["14", "Issue 14"], + ]); + assert.deepEqual(yield* rows, []); + + const settled = yield* sink.latestSequence(); + yield* IssueLinkBackfill.run(); + assert.equal(yield* sink.latestSequence(), settled); + + // A row left behind by a crash after its link committed replays its receipt, even after + // the user removed that link. + yield* orchestrator.dispatch({ + type: "thread.issue.unlink", + commandId: CommandId.make("user-unlinks-13"), + threadId: ThreadId.make("ordinary"), + tracker: IssueTrackerKind.make("github"), + host: "github.com", + scope: "owner/repo", + key: "13", + }); + yield* sql`INSERT INTO issue_thread_links(host, repository, issue_number, thread_id) + VALUES ('github.com', 'owner/repo', 13, 'ordinary')`; + const unlinked = yield* sink.latestSequence(); + yield* IssueLinkBackfill.run(); + assert.deepEqual(yield* links("ordinary"), [["14", "Issue 14"]]); + assert.equal(yield* sink.latestSequence(), unlinked); + assert.deepEqual(yield* rows, []); + }).pipe(Effect.provide(h.layer)); + }, +); diff --git a/apps/server/src/issues/IssueLinkBackfill.ts b/apps/server/src/issues/IssueLinkBackfill.ts new file mode 100644 index 0000000000000..2afa477d80507 --- /dev/null +++ b/apps/server/src/issues/IssueLinkBackfill.ts @@ -0,0 +1,156 @@ +import { + CommandId, + IssueTrackerKind, + ProjectId, + ThreadId, + ThreadLinkedIssue, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as TrackerIssueService from "../issue/IssueService.ts"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import { forkParked } from "../serverActivation.ts"; + +type Row = { + readonly from_table: number; + readonly host: string; + readonly repository: string; + readonly number: number; + readonly thread_id: string; + readonly project_id: string | null; + readonly live: number; + readonly linked: number; + readonly claim_json: string | null; +}; + +const decodeClaim = Schema.decodeUnknownOption(Schema.fromJsonString(ThreadLinkedIssue)); +const issueKey = (row: Pick) => + `${row.host.toLowerCase()}/${row.repository.toLowerCase()}#${row.number}`; + +/** + * Moves the retired `issue_thread_links` rows, and claims written before claims carried their + * link, onto `thread.issues[]` as commands, so the links survive a projection rebuild. A claim + * whose thread has had any link change is not an old claim: someone removed its link. The command + * id names the thread and the issue, so a rerun replays its receipt and changes nothing. + */ +export const run = Effect.fn("IssueLinkBackfill.run")(function* () { + const sql = yield* SqlClient.SqlClient; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const issues = yield* TrackerIssueService.IssueService; + const linkedSql = (thread: string, host: string, repository: string, number: string) => sql` + EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(${sql.unsafe(thread)}.payload_json) + THEN ${sql.unsafe(thread)}.payload_json ELSE '{}' END, '$.issues') link + WHERE json_extract(link.value, '$.tracker') = 'github' + AND lower(json_extract(link.value, '$.host')) = lower(${sql.unsafe(host)}) + AND lower(json_extract(link.value, '$.scope')) = lower(${sql.unsafe(repository)}) + AND json_extract(link.value, '$.key') = CAST(${sql.unsafe(number)} AS TEXT))`; + const rows = yield* sql` + SELECT 1 AS from_table, row.host, row.repository, row.issue_number AS number, row.thread_id, + thread.project_id, thread.thread_id IS NOT NULL AND thread.deleted_at IS NULL AS live, + COALESCE(${linkedSql("thread", "row.host", "row.repository", "row.issue_number")}, 0) AS linked, + CASE WHEN json_valid(thread.payload_json) + THEN json_extract(thread.payload_json, '$.linkedIssue') END AS claim_json + FROM issue_thread_links row + LEFT JOIN orchestration_v2_projection_threads thread ON thread.thread_id = row.thread_id + UNION ALL + SELECT 0, json_extract(claimed.payload_json, '$.linkedIssue.host'), + json_extract(claimed.payload_json, '$.linkedIssue.repository'), + json_extract(claimed.payload_json, '$.linkedIssue.number'), claimed.thread_id, + claimed.project_id, 1, 0, json_extract(claimed.payload_json, '$.linkedIssue') + FROM orchestration_v2_projection_threads claimed + WHERE claimed.deleted_at IS NULL + AND lower(CASE WHEN json_valid(claimed.payload_json) THEN json_extract(claimed.payload_json, '$.linkedIssue.host') END) > '' + AND NOT EXISTS (SELECT 1 FROM orchestration_events event + WHERE event.aggregate_kind = 'thread' AND event.stream_id = claimed.thread_id + AND event.event_type = 'thread.issue-synced') + AND NOT ${linkedSql( + "claimed", + "json_extract(claimed.payload_json, '$.linkedIssue.host')", + "json_extract(claimed.payload_json, '$.linkedIssue.repository')", + "json_extract(claimed.payload_json, '$.linkedIssue.number')", + )} + `; + const removeRow = (row: Row) => + sql`DELETE FROM issue_thread_links WHERE host = ${row.host} AND repository = ${row.repository} + AND issue_number = ${row.number} AND thread_id = ${row.thread_id}`; + const pending: Array = []; + for (const row of rows) { + if (row.live === 1 && row.linked === 0 && row.project_id !== null) + pending.push({ ...row, projectId: ProjectId.make(row.project_id) }); + else if (row.from_table === 1) yield* removeRow(row); + } + const titles = new Map(); + const unnamed = new Map(); + for (const row of pending) { + const claim = Option.getOrUndefined(decodeClaim(row.claim_json)); + const title = claim?.title.trim(); + if (claim !== undefined && title && issueKey(claim) === issueKey(row)) + titles.set(issueKey(row), title); + } + for (const row of pending) if (!titles.has(issueKey(row))) unnamed.set(issueKey(row), row); + yield* Effect.forEach( + unnamed, + ([key, row]) => + issues + .detail({ + projectId: row.projectId, + tracker: IssueTrackerKind.make("github"), + host: row.host.toLowerCase(), + scope: row.repository, + key: String(row.number), + }) + .pipe( + Effect.map((detail) => void titles.set(key, detail.title)), + // The row stays for the next start. + Effect.catch((error) => + Effect.logWarning("issue link backfill could not read an issue title", { + issue: key, + reason: error.message, + }), + ), + ), + { concurrency: 4, discard: true }, + ); + for (const row of pending) { + const title = titles.get(issueKey(row)); + if (title === undefined) continue; + const host = row.host.toLowerCase(); + yield* orchestrator + .dispatch({ + type: "thread.issue.link", + commandId: CommandId.make(`fork:issue-link-backfill:${row.thread_id}:${issueKey(row)}`), + threadId: ThreadId.make(row.thread_id), + tracker: IssueTrackerKind.make("github"), + host, + scope: row.repository, + key: String(row.number), + projectId: row.projectId, + url: `https://${host}/${row.repository}/issues/${row.number}`, + displayKey: `#${row.number}`, + title, + source: "agent", + }) + .pipe( + Effect.andThen(row.from_table === 1 ? removeRow(row) : Effect.void), + Effect.catch((error) => + Effect.logWarning("issue link backfill could not link a thread", { + thread: row.thread_id, + issue: issueKey(row), + reason: error.message, + }), + ), + ); + } +}); + +export const layer = Layer.effectDiscard( + forkParked( + run().pipe( + Effect.catchCause((cause) => Effect.logWarning("issue link backfill failed", { cause })), + ), + ), +); diff --git a/apps/server/src/issues/IssueLinks.test.ts b/apps/server/src/issues/IssueLinks.test.ts index cdd3db371cf79..00b381a0a0b7d 100644 --- a/apps/server/src/issues/IssueLinks.test.ts +++ b/apps/server/src/issues/IssueLinks.test.ts @@ -16,8 +16,6 @@ import { import * as Effect from "effect/Effect"; import * as DateTime from "effect/DateTime"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Result from "effect/Result"; import * as Tracer from "effect/Tracer"; import * as SqlClient from "effect/sql/SqlClient"; import * as Statement from "effect/sql/Statement"; @@ -32,6 +30,22 @@ import { issueWorkThreadIds } from "./IssueWorkQuery.ts"; const ref = { host: "github.com", repository: "owner/repo", number: 13 }; const threadId = ThreadId.make("ordinary-builder"); +const issueLink = { + tracker: IssueTrackerKind.make("github"), + host: "github.com", + scope: "owner/repo", + key: "13", + projectId: ProjectId.make("project"), + url: "https://github.com/owner/repo/issues/13", + source: "agent" as const, + linkedAt: "2026-11-17T00:00:00.000Z", + displayKey: "#13", + title: "Roadmap", +}; +const linked = (shell: T) => ({ + ...shell, + issues: [issueLink], +}); function harness(initial: OrchestrationV2ThreadShell[]) { let shells = initial; let revision = 0; @@ -123,75 +137,21 @@ function list(): RepositoryIssueListResult { }; } -it.effect( - "ordinary threads link multiple issues durably and idempotently, without a repository owner; unlink is scoped", - () => { - const h = harness([liveThreadShell(threadId), liveThreadShell(ThreadId.make("another"))]); - return Effect.gen(function* () { - const links = yield* IssueLinks.IssueLinks; - const sql = yield* SqlClient.SqlClient; - assert.equal( - (yield* links.link({ url: "https://github.com/Owner/Repo/issues/13" }, threadId)).changed, - true, - ); - assert.equal((yield* links.link(ref, threadId)).changed, false); - assert.equal((yield* links.link({ ...ref, number: 14 }, threadId)).changed, true); - assert.equal( - (yield* links.link({ ...ref, threadId: ThreadId.make("another") }, threadId)).changed, - true, - ); - assert.equal((yield* sql`SELECT * FROM issue_thread_links`).length, 3); - assert.isTrue( - (yield* links.enrich(list())).issues[0]?.liveWork?.find( - (work) => work.threadId === threadId, - )?.canUnlink, - ); - assert.equal((yield* links.link(ref, threadId, true)).changed, true); - assert.equal((yield* links.link(ref, threadId, true)).changed, false); - assert.equal(yield* Stream.runHead(links.refreshes).pipe(Effect.map(Option.getOrThrow)), 4); - assert.deepEqual( - (yield* links.enrich(list())).issues[0]?.liveWork?.map((work) => work.threadId), - ["another"], - ); - assert.deepEqual( - yield* sql`SELECT issue_number, thread_id FROM issue_thread_links ORDER BY issue_number`, - [ - { issue_number: 13, thread_id: "another" }, - { issue_number: 14, thread_id: threadId }, - ], - ); - }).pipe(Effect.provide(h.layer)); - }, -); - -it.effect("counts an upstream thread.issues link as live work it cannot unlink", () => { +it.effect("counts an upstream thread.issues link as live work, matching host and scope", () => { const linkedThread = { ...liveThreadShell(threadId), - issues: [ - { - tracker: IssueTrackerKind.make("github"), - host: "GitHub.com", - scope: "Owner/Repo", - key: "13", - projectId: ProjectId.make("project"), - url: "https://github.com/owner/repo/issues/13", - source: "agent" as const, - linkedAt: "2026-11-17T00:00:00.000Z", - displayKey: "#13", - title: "Roadmap", - }, - ], + issues: [{ ...issueLink, host: "GitHub.com", scope: "Owner/Repo" }], }; const other = { ...liveThreadShell(ThreadId.make("other-repo")), - issues: [{ ...linkedThread.issues[0]!, scope: "owner/other" }], + issues: [{ ...issueLink, scope: "owner/other" }], }; const h = harness([linkedThread, other]); return Effect.gen(function* () { const enriched = yield* (yield* IssueLinks.IssueLinks).enrich(list()); assert.deepEqual( - enriched.issues[0]!.liveWork!.map(({ threadId, canUnlink }) => ({ threadId, canUnlink })), - [{ threadId, canUnlink: false }], + enriched.issues[0]!.liveWork!.map((work) => work.threadId), + [threadId], ); }).pipe(Effect.provide(h.layer)); }); @@ -211,7 +171,7 @@ it.effect( url: "https://github.com/owner/repo/issues/13", }, }; - const ordinary = liveThreadShell(threadId); + const ordinary = linked(liveThreadShell(threadId)); const h = harness([managed, ordinary]); const layer = IssueRoadmap.layer.pipe( Layer.provide(Layer.mock(Orchestrator.OrchestratorV2)({ streamDomainEvents: Stream.empty })), @@ -235,7 +195,6 @@ it.effect( ), ); return Effect.gen(function* () { - yield* (yield* IssueLinks.IssueLinks).link(ref, ordinary.id); const roadmap = yield* IssueRoadmap.IssueRoadmap; const pane = yield* roadmap.list({ ...ref, roadmap: true }); const badge = yield* roadmap.statusBatch({ issues: [{ host: ref.host, nodeId: "I_13" }] }); @@ -332,39 +291,13 @@ it.effect("acquires the reader once for a multi-repository status batch", () => }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -it.effect( - "rejects malformed or conflicting targets and unavailable threads before saving a link", - () => { - const h = harness([liveThreadShell(threadId)]); - return Effect.gen(function* () { - const links = yield* IssueLinks.IssueLinks; - for (const input of [ - {}, - { repository: "owner/repo", number: 0 }, - { url: "https://github.com/owner/repo/pull/13" }, - { url: "https://github.com/owner/repo/issues/13", number: 14 }, - { url: "http://github.com/owner/repo/issues/13" }, - ]) { - const result = yield* links.link(input, threadId).pipe(Effect.result); - assert.isTrue(Result.isFailure(result)); - if (Result.isFailure(result)) assert.equal(result.failure.code, "invalid-request"); - } - const missing = yield* links.link(ref, ThreadId.make("missing")).pipe(Effect.result); - assert.isTrue(Result.isFailure(missing)); - if (Result.isFailure(missing)) assert.equal(missing.failure.code, "thread-not-found"); - const sql = yield* SqlClient.SqlClient; - assert.deepEqual(yield* sql`SELECT * FROM issue_thread_links`, []); - }).pipe(Effect.provide(h.layer)); - }, -); - it.effect( "loads only explicitly linked, managed, closing-PR and descendant work, and refreshes live state", () => { - const root = { + const root = linked({ ...liveThreadShell(threadId, { activeRunId: null }), status: "completed" as const, - }; + }); const child = { ...liveThreadShell(ThreadId.make("delegated")), role: "investigator" as const, @@ -376,8 +309,9 @@ it.effect( relationshipToParent: "subagent" as const, }, }; + // A claim and its own link for one thread must not duplicate its indicator. const managed = { - ...liveThreadShell(ThreadId.make("managed")), + ...linked(liveThreadShell(ThreadId.make("managed"))), linkedIssue: { ...ref, repositoryId: "repo-id", @@ -435,6 +369,7 @@ it.effect( ...managed, id: ThreadId.make("other-repo"), linkedIssue: { ...managed.linkedIssue, repository: "other/repo" }, + issues: [], }; const modern = { ...pr, @@ -488,8 +423,6 @@ it.effect( ]); return Effect.gen(function* () { const links = yield* IssueLinks.IssueLinks; - yield* links.link(ref, threadId); - yield* links.link(ref, managed.id); // Two sources for one thread must not duplicate its indicator. const input = list(); const withPr = { ...input, @@ -524,10 +457,6 @@ it.effect( ], ); const work = first.issues[0]!.liveWork!; - assert.deepEqual( - work.filter((item) => item.canUnlink).map((item) => item.threadId), - [managed.id, threadId], - ); assert.deepEqual( work.map((item) => [item.threadId, item.status]), [ @@ -571,7 +500,11 @@ it.effect( (yield* links.enrich(withPr)).issues[0]!.liveWork?.map((item) => item.status), ["idle", "idle"], ); - yield* links.link(ref, threadId, true); + const { issues: _issues, ...unlinked } = root; + yield* (yield* SqlClient.SqlClient)` + UPDATE orchestration_v2_projection_threads SET payload_json = ${JSON.stringify(unlinked)} + WHERE thread_id = ${root.id}`; + h.setShells([unlinked, { ...child, status: "completed", activeRunId: null }]); assert.deepEqual((yield* links.enrich(withPr)).issues[0]!.liveWork, []); }).pipe(Effect.provide(h.layer)); }, @@ -580,7 +513,7 @@ it.effect( it.effect("bounds cyclic descendant lineage without loading unrelated threads", () => { const childId = ThreadId.make("cycle-child"); const root = { - ...liveThreadShell(threadId), + ...linked(liveThreadShell(threadId)), lineage: { rootThreadId: threadId, parentThreadId: childId, @@ -598,7 +531,6 @@ it.effect("bounds cyclic descendant lineage without loading unrelated threads", const h = harness([root, child, liveThreadShell(ThreadId.make("unrelated"))]); return Effect.gen(function* () { const links = yield* IssueLinks.IssueLinks; - yield* links.link(ref, threadId); h.lookups.length = 0; const result = yield* links.enrich(list()); assert.deepEqual(h.lookups, [childId, threadId]); @@ -754,7 +686,7 @@ it.effect("returns closing and linked-thread PRs with state, deduplicating the s }, }; const thread = { - ...liveThreadShell(threadId), + ...linked(liveThreadShell(threadId)), pullRequests: [ pr, { @@ -769,7 +701,6 @@ it.effect("returns closing and linked-thread PRs with state, deduplicating the s const h = harness([thread]); return Effect.gen(function* () { const links = yield* IssueLinks.IssueLinks; - yield* links.link(ref, threadId); const input = list(); const result = yield* links.enrich({ ...input, @@ -866,17 +797,15 @@ it.effect( const links = yield* IssueLinks.IssueLinks; yield* sql`CREATE TABLE contention_probe (value INTEGER)`; for (let index = 0; index < 100; index++) { - const thread = idleThreadProjection( - liveThreadShell(ThreadId.make(`batch-${index}`)), - ).thread; + const thread = linked( + idleThreadProjection(liveThreadShell(ThreadId.make(`batch-${index}`))).thread, + ); yield* sql` INSERT INTO orchestration_v2_projection_threads( thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, created_at, updated_at, archived_at, deleted_at, payload_json ) VALUES (${thread.id}, ${thread.projectId}, ${thread.title}, 'codex', 'full-access', 'default', '2026-10-13', '2026-10-13', NULL, NULL, ${JSON.stringify(thread)})`; - yield* sql`INSERT INTO issue_thread_links(host, repository, issue_number, thread_id) - VALUES (${ref.host}, ${ref.repository}, ${ref.number}, ${thread.id})`; } const other = yield* Effect.acquireRelease( Effect.sync(() => new NodeSqlite.DatabaseSync(filename)), @@ -956,11 +885,10 @@ it.effect( ); it.effect("memoizes unchanged work and invalidates it on the next projected thread change", () => { - const thread = liveThreadShell(threadId); + const thread = linked(liveThreadShell(threadId)); const h = harness([thread]); return Effect.gen(function* () { const links = yield* IssueLinks.IssueLinks; - yield* links.link(ref, threadId); h.lookups.length = 0; const first = yield* links.enrich(list()); const reads = h.lookups.length; diff --git a/apps/server/src/issues/IssueLinks.ts b/apps/server/src/issues/IssueLinks.ts index 90c7d1f70b17e..efba86231e799 100644 --- a/apps/server/src/issues/IssueLinks.ts +++ b/apps/server/src/issues/IssueLinks.ts @@ -3,8 +3,6 @@ import { IssueLinkError, RepositoryOrchestration, RepositoryIssueRef, - type IssueLinkInput, - type IssueLinkResult, type IssueRepositoryRef, type IssuePullRequestStatus, type RepositoryIssueSummary, @@ -26,13 +24,10 @@ import { } from "../sourceControl/threadPullRequests.ts"; import { issuePullRequests } from "@t3tools/source-control-definitions/issuePullRequests"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; -import * as Stream from "effect/Stream"; -import * as SubscriptionRef from "effect/SubscriptionRef"; import { issueWorkThreadIds } from "./IssueWorkQuery.ts"; const key = (issue: RepositoryIssueRef) => `${issue.host.toLowerCase()}/${issue.repository.toLowerCase()}#${issue.number}`; -const isIssueRef = Schema.is(RepositoryIssueRef); const encodeMemoKey = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); const encodePrRefs = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(RepositoryIssueRef))); const decodeOrchestration = Schema.decodeEffect(Schema.fromJsonString(RepositoryOrchestration)); @@ -47,45 +42,10 @@ type WorkList = { })[]; }; -function target(input: IssueLinkInput): RepositoryIssueRef | null { - let ref = { - host: input.host ?? "github.com", - repository: input.repository, - number: input.number, - }; - if (input.url !== undefined) { - try { - const url = new URL(input.url); - const match = /^\/([^/]+\/[^/]+)\/issues\/(\d+)\/?$/.exec(url.pathname); - if (url.protocol !== "https:" || url.username || url.password || url.port || match === null) - return null; - ref = { host: url.hostname, repository: match[1], number: Number(match[2]) }; - if ( - (input.host !== undefined && input.host.toLowerCase() !== ref.host.toLowerCase()) || - (input.repository !== undefined && - input.repository.toLowerCase() !== ref.repository?.toLowerCase()) || - (input.number !== undefined && input.number !== ref.number) - ) - return null; - } catch { - return null; - } - } - return isIssueRef(ref) - ? { ...ref, host: ref.host.toLowerCase(), repository: ref.repository.toLowerCase() } - : null; -} - -/** Ordinary thread associations, independent of repository orchestration ownership. */ +/** Live work per issue: claims, `thread.issues[]` links, owned pull requests and descendants. */ export class IssueLinks extends Context.Service< IssueLinks, { - readonly link: ( - input: IssueLinkInput, - callerThreadId?: ThreadId, - remove?: boolean, - ) => Effect.Effect; - readonly refreshes: Stream.Stream; readonly enrich: ( list: T, ) => Effect.Effect< @@ -104,7 +64,6 @@ const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const fs = yield* FileSystem.FileSystem; const projections = yield* ProjectionStore.ProjectionStoreV2; - const refreshes = yield* SubscriptionRef.make(0); const workByRepository = new Map< string, { @@ -113,38 +72,11 @@ const make = Effect.gen(function* () { threadLinks: Effect.Effect, IssueLinkError>; } >(); - const link: IssueLinks["Service"]["link"] = Effect.fn("IssueLinks.link")(function* ( - input, - callerThreadId, - remove = false, - ) { - const issue = target(input); - const threadId = input.threadId ?? callerThreadId; - if (issue === null || threadId === undefined) - return yield* new IssueLinkError({ code: "invalid-request" }); - const thread = yield* projections.getThreadShell(threadId).pipe(Effect.mapError(storageError)); - if (thread === null || thread.deletedAt !== null) - return yield* new IssueLinkError({ code: "thread-not-found" }); - const rows = yield* ( - remove - ? sql`DELETE FROM issue_thread_links WHERE host = ${issue.host} AND repository = ${issue.repository} - AND issue_number = ${issue.number} AND thread_id = ${threadId} RETURNING thread_id` - : sql`INSERT INTO issue_thread_links(host, repository, issue_number, thread_id) - VALUES (${issue.host}, ${issue.repository}, ${issue.number}, ${threadId}) - ON CONFLICT DO NOTHING RETURNING thread_id` - ).pipe(Effect.mapError(storageError)); - if (rows.length > 0) yield* SubscriptionRef.update(refreshes, (revision) => revision + 1); - return { issue, threadId, changed: rows.length > 0 }; - }); const enrich: IssueLinks["Service"]["enrich"] = Effect.fn("IssueLinks.enrich")(function* < T extends WorkList, >(list: T) { const host = list.repository.host.toLowerCase(); const repository = list.repository.repository.toLowerCase(); - const tableRows = yield* sql` - SELECT issue_number, thread_id FROM issue_thread_links - WHERE host = ${host} AND repository = ${repository} - `.pipe(NodeSqliteClient.readOnly, Effect.mapError(storageError)); const issueNumbers = list.issues.map((issue) => issue.number); const prRefs = list.issues.flatMap((issue) => issue.pullRequestRefs ?? []); const prRefsJson = yield* encodePrRefs(prRefs).pipe(Effect.mapError(storageError)); @@ -155,8 +87,8 @@ const make = Effect.gen(function* () { memo = { revision, queries: new Map(), - // ponytail: scans every thread's links once per event revision; read links per issue - // once the old table is retired. + // ponytail: scans every thread's links once per event revision, shared by every page; + // a projected link table indexed by issue if this shows up in profiles. threadLinks: yield* Effect.cached( sql` SELECT CAST(json_extract(link.value, '$.key') AS INTEGER) AS issue_number, thread.thread_id @@ -171,15 +103,13 @@ const make = Effect.gen(function* () { }; workByRepository.set(repositoryKey, memo); } - // Upstream's thread.issues[] links sit beside the old table until the table is retired. - const rows = [...tableRows, ...(yield* memo.threadLinks)]; - // Link rows are outside the event projection. Include them and the GitHub candidate set so - // explicit unlinking, paging and newly discovered closing PRs invalidate their own reads. + const rows = yield* memo.threadLinks; + // The GitHub candidate set is outside the event projection, so paging and newly discovered + // closing PRs invalidate their own reads. const queryKey = encodeMemoKey([ issueNumbers, prRefsJson, list.issues.some((issue) => issue.state === "closed"), - rows, ]); const queries = memo.queries; let read = queries.get(queryKey); @@ -222,7 +152,6 @@ const make = Effect.gen(function* () { refs.add(number); refsByThread.set(threadId, refs); }; - const removableLinks = new Set(tableRows.map((row) => `${row.thread_id}:${row.issue_number}`)); for (const row of rows) add(row.thread_id, row.issue_number); const issuesByPr = new Map>(); for (const issue of list.issues) @@ -332,7 +261,6 @@ const make = Effect.gen(function* () { linked.push({ ...item, inherited, - canUnlink: removableLinks.has(`${thread.id}:${number}`), status: inherited && state === "working" ? "idle" : state, }); work.set(number, linked); @@ -374,7 +302,7 @@ const make = Effect.gen(function* () { }), }; }); - return IssueLinks.of({ link, enrich, refreshes: SubscriptionRef.changes(refreshes) }); + return IssueLinks.of({ enrich }); }); function workState( diff --git a/apps/server/src/issues/IssueRoadmap.test.ts b/apps/server/src/issues/IssueRoadmap.test.ts index 95f0981967610..d076f9fe2716f 100644 --- a/apps/server/src/issues/IssueRoadmap.test.ts +++ b/apps/server/src/issues/IssueRoadmap.test.ts @@ -203,7 +203,7 @@ it.effect( Layer.provide( Layer.mergeAll( Layer.mock(IssueService.IssueService)({ refreshes: Stream.empty }), - Layer.mock(IssueLinks.IssueLinks)({ refreshes: Stream.make(0) }), + Layer.mock(IssueLinks.IssueLinks)({}), Layer.mock(Orchestrator.OrchestratorV2)({ streamDomainEvents: Stream.fromQueue(changes), }), @@ -512,7 +512,7 @@ it.effect( Layer.mock(IssueService.IssueService)({ refreshes: SubscriptionRef.changes(revisions), }), - Layer.mock(IssueLinks.IssueLinks)({ refreshes: Stream.make(0) }), + Layer.mock(IssueLinks.IssueLinks)({}), Layer.mock(Orchestrator.OrchestratorV2)({ streamDomainEvents: Stream.empty }), ), ), diff --git a/apps/server/src/issues/IssueRoadmap.ts b/apps/server/src/issues/IssueRoadmap.ts index 37d45fd11a8da..0f337e540f2c6 100644 --- a/apps/server/src/issues/IssueRoadmap.ts +++ b/apps/server/src/issues/IssueRoadmap.ts @@ -47,83 +47,79 @@ export const layer = Layer.effect( const orchestrator = yield* Orchestrator.OrchestratorV2; const sql = yield* SqlClient.SqlClient; return IssueRoadmap.of({ - linkRefreshes: Stream.merge( - links.refreshes.pipe(Stream.drop(1)), - Stream.suspend(() => { - const workStates = new Map(); - return orchestrator.streamDomainEvents.pipe( - Stream.filter((event) => { - const state: readonly [string, string] | undefined = - event.type === "provider-thread.updated" + linkRefreshes: Stream.suspend(() => { + const workStates = new Map(); + return orchestrator.streamDomainEvents.pipe( + Stream.filter((event) => { + const state: readonly [string, string] | undefined = + event.type === "provider-thread.updated" + ? [ + `provider:${event.payload.id}`, + String( + backgroundWorkHoldsCompletion(event.payload.pendingBackgroundTasks ?? []), + ), + ] + : event.type === "subagent.updated" ? [ - `provider:${event.payload.id}`, - String( - backgroundWorkHoldsCompletion(event.payload.pendingBackgroundTasks ?? []), - ), + `subagent:${event.payload.id}`, + `${event.payload.status}:${event.payload.childThreadId ?? ""}`, ] - : event.type === "subagent.updated" + : event.type === "runtime-request.updated" ? [ - `subagent:${event.payload.id}`, - `${event.payload.status}:${event.payload.childThreadId ?? ""}`, + `request:${event.payload.id}`, + `${event.payload.kind}:${event.payload.status}:${event.payload.responseCapability.type}`, ] - : event.type === "runtime-request.updated" + : event.type === "run.created" || event.type === "run.updated" ? [ - `request:${event.payload.id}`, - `${event.payload.kind}:${event.payload.status}:${event.payload.responseCapability.type}`, + `run:${event.payload.id}`, + `${event.payload.status}:${event.payload.queueHeld === true}`, ] - : event.type === "run.created" || event.type === "run.updated" + : event.type === "turn-item.updated" && + isBackgroundTurnItemType(event.payload.type) ? [ - `run:${event.payload.id}`, - `${event.payload.status}:${event.payload.queueHeld === true}`, + `item:${event.payload.id}`, + String( + pendingBackgroundTurnItems({ turnItems: [event.payload] }).length > 0, + ), ] - : event.type === "turn-item.updated" && - isBackgroundTurnItemType(event.payload.type) - ? [ - `item:${event.payload.id}`, - String( - pendingBackgroundTurnItems({ turnItems: [event.payload] }).length > - 0, - ), - ] - : undefined; - if (state !== undefined) { - const [key, value] = state; - if (workStates.get(key) === value) return false; - workStates.set(key, value); - } - return ( - event.type === "thread.created" || - event.type === "thread.metadata-updated" || - event.type === "thread.archived" || - event.type === "thread.unarchived" || - event.type === "thread.deleted" || - event.type === "thread.pull-request-synced" || - event.type === "thread.issue-synced" || - event.type === "thread.pull-request-link-updated" || - event.type === "issue.work.requested" || - event.type === "issue.work.cancelled" || - event.type === "issue.queue.updated" || - event.type === "repository.work.restored" || - event.type === "runtime-request.updated" || - event.type === "provider-thread.updated" || - event.type === "subagent.updated" || - (event.type === "turn-item.updated" && - (event.payload.type === "secret_request" || - isBackgroundTurnItemType(event.payload.type))) || - event.type === "run.created" || - event.type === "run.updated" - ); - }), - Stream.mapError( - () => - new IssueWorkError({ - code: "orchestration-error", - message: "Could not follow issue work changes.", - }), - ), - ); - }), - ).pipe( + : undefined; + if (state !== undefined) { + const [key, value] = state; + if (workStates.get(key) === value) return false; + workStates.set(key, value); + } + return ( + event.type === "thread.created" || + event.type === "thread.metadata-updated" || + event.type === "thread.archived" || + event.type === "thread.unarchived" || + event.type === "thread.deleted" || + event.type === "thread.pull-request-synced" || + event.type === "thread.issue-synced" || + event.type === "thread.pull-request-link-updated" || + event.type === "issue.work.requested" || + event.type === "issue.work.cancelled" || + event.type === "issue.queue.updated" || + event.type === "repository.work.restored" || + event.type === "runtime-request.updated" || + event.type === "provider-thread.updated" || + event.type === "subagent.updated" || + (event.type === "turn-item.updated" && + (event.payload.type === "secret_request" || + isBackgroundTurnItemType(event.payload.type))) || + event.type === "run.created" || + event.type === "run.updated" + ); + }), + Stream.mapError( + () => + new IssueWorkError({ + code: "orchestration-error", + message: "Could not follow issue work changes.", + }), + ), + ); + }).pipe( Stream.merge(issues.refreshes.pipe(Stream.drop(1))), // One command often commits ownership, thread and run events together. Stream.groupedWithin(128, "250 millis"), diff --git a/apps/server/src/issues/IssueRpcTables.ts b/apps/server/src/issues/IssueRpcTables.ts index 0dacbec237d3a..eafe83bb88f12 100644 --- a/apps/server/src/issues/IssueRpcTables.ts +++ b/apps/server/src/issues/IssueRpcTables.ts @@ -40,7 +40,6 @@ export const ISSUE_RPC_AGGREGATES = { [WS_METHODS.issuesStatusBatch]: "issues", [WS_METHODS.issueWorkSetState]: "issues", [WS_METHODS.issuesCleanup]: "issues", - [WS_METHODS.issuesUnlink]: "issues", [WS_METHODS.issuesSubscribeLinkRefreshes]: "issues", [WS_METHODS.issuesStart]: "issues", [WS_METHODS.issuesQueue]: "issues", diff --git a/apps/server/src/issues/IssueService.test.ts b/apps/server/src/issues/IssueService.test.ts index c34a0a37290e2..a5e7fbaa0189f 100644 --- a/apps/server/src/issues/IssueService.test.ts +++ b/apps/server/src/issues/IssueService.test.ts @@ -245,7 +245,6 @@ it.effect( Layer.mock(Orchestrator.OrchestratorV2)({ streamDomainEvents: Stream.empty }), SqlitePersistence.layerMemory, Layer.mock(IssueLinks.IssueLinks)({ - refreshes: Stream.empty, enrich: (list) => Effect.sync(() => { enrichments++; diff --git a/apps/server/src/issues/IssueWorkProjection.test.ts b/apps/server/src/issues/IssueWorkProjection.test.ts index 53be9bdbb579b..917caa647e5de 100644 --- a/apps/server/src/issues/IssueWorkProjection.test.ts +++ b/apps/server/src/issues/IssueWorkProjection.test.ts @@ -1,6 +1,7 @@ import { assert, it } from "@effect/vitest"; import { EventId, + IssueTrackerKind, MessageId, NodeId, RunId, @@ -90,6 +91,24 @@ it.effect( }, }), ...(name === "archived" ? { archivedAt: now } : {}), + ...(name === "explicit" + ? { + issues: [ + { + tracker: IssueTrackerKind.make("github"), + host: "github.com", + scope: "owner/repo", + key: "13", + projectId: liveThreadShell(id).projectId, + url: "https://github.com/owner/repo/issues/13", + source: "agent" as const, + linkedAt: "2026-10-20T00:00:00Z", + displayKey: "#13", + title: "Issue", + }, + ], + } + : {}), ...(name === "inherited" ? { lineage: { @@ -277,7 +296,6 @@ it.effect( }); } const links = yield* IssueLinks.IssueLinks; - yield* links.link(reference, ThreadId.make("explicit")); const input = { repository: reference, issues: [ @@ -310,7 +328,7 @@ it.effect( assert.deepEqual(first, expected); const work = first.issues[0]!.liveWork!; assert.equal(work.find((item) => item.threadId === "inherited")?.inherited, true); - assert.equal(work.find((item) => item.threadId === "explicit")?.canUnlink, true); + assert.equal(work.find((item) => item.threadId === "explicit")?.inherited, false); assert.equal(work.find((item) => item.threadId === "archived")?.status, "idle"); assert.deepEqual(work.find((item) => item.threadId === "legacy")?.pullRequests, [pr.url]); assert.equal(first.issues[0]!.pullRequestCount, 1); diff --git a/apps/server/src/mcp/IssueReviewDelegation.fork.test.ts b/apps/server/src/mcp/IssueReviewDelegation.fork.test.ts index 82f2ae3648e1d..351d1c3ce209d 100644 --- a/apps/server/src/mcp/IssueReviewDelegation.fork.test.ts +++ b/apps/server/src/mcp/IssueReviewDelegation.fork.test.ts @@ -14,9 +14,8 @@ import * as DateTime from "effect/DateTime"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; -import * as SqlClient from "effect/sql/SqlClient"; -import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; -import * as IssueLinks from "../issues/IssueLinks.ts"; +import * as TrackerIssueService from "../issue/IssueService.ts"; +import * as ThreadIssueService from "../orchestration-v2/ThreadIssueService.ts"; import * as IssueWorkService from "../issues/IssueWorkService.ts"; import * as IssueWorkStore from "../issues/IssueWorkStore.ts"; import * as EventSink from "../orchestration-v2/EventSink.ts"; @@ -52,15 +51,15 @@ function setup() { const dependencies = Layer.mergeAll( harness.layer, Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), - IssueLinks.layer.pipe( - Layer.provide( - Layer.mergeAll( - harness.layer, - Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), - ProjectionStore.layer.pipe(Layer.provide(harness.layer)), - ), - ), - ), + ThreadIssueService.layer.pipe(Layer.provide(Layer.mergeAll(harness.layer, NodeCrypto.layer))), + Layer.mock(TrackerIssueService.IssueService)({ + detail: (ref) => + Effect.succeed({ + url: `https://github.com/${ref.scope}/issues/${ref.key}`, + displayKey: `#${ref.key}`, + title: `Issue ${ref.key}`, + } as never), + }), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), Layer.mock(SecretRequests.SecretRequests)({}), Layer.mock(GitVcsDriver.GitVcsDriver)({ @@ -107,7 +106,6 @@ it.effect( const work = yield* IssueWorkService.IssueWorkService; const store = yield* IssueWorkStore.IssueWorkStore; const mcp = yield* OrchestratorMcpService.OrchestratorMcpService; - const sql = yield* SqlClient.SqlClient; const root = yield* createReviewRoot(); const repository = { host: "github.com", repository: "tannerpolley/t3code" }; yield* work.setWorkerLimit({ @@ -116,7 +114,33 @@ it.effect( expectedRevision: 1, clientRequestId: CommandId.make("limit"), }); - yield* delegateReviewIssue(root, reviewIssue(1), "occupy-slot"); + const claimed = yield* delegateReviewIssue(root, reviewIssue(1), "occupy-slot"); + // The claim and its thread link commit in the one event that creates the worker. + const created = claimed.storedEvents.find((stored) => stored.event.type === "thread.created"); + assert.equal(created?.event.type, "thread.created"); + if (created?.event.type === "thread.created") { + assert.equal(created.event.payload.linkedIssue?.number, 1); + assert.deepEqual( + created.event.payload.issues?.map(({ tracker, host, scope, key, title, source }) => ({ + tracker, + host, + scope, + key, + title, + source, + })), + [ + { + tracker: "github", + host: "github.com", + scope: "tannerpolley/t3code", + key: "1", + title: "Issue 1", + source: "agent", + }, + ], + ); + } assert.equal(yield* store.slotsInUse(root), 1); const originalOwner = yield* store.issueOwner(reviewIssue(1)); const scope = scopeFor(root); @@ -142,9 +166,10 @@ it.effect( assert.isUndefined(child.runs[0]!.workspacePreparation); assert.equal(yield* store.slotsInUse(root), 1); assert.equal(yield* store.issueOwner(reviewIssue(1)), originalOwner); - const links = - yield* sql`SELECT thread_id FROM issue_thread_links WHERE thread_id = ${result.childThreadId}`; - assert.lengthOf(links, issue === undefined ? 0 : 1); + assert.deepEqual( + child.thread.issues?.map((link) => link.key) ?? [], + issue === undefined ? [] : ["1"], + ); } } for (const issue of [undefined, reviewIssue(1)]) { @@ -171,9 +196,10 @@ it.effect( assert.equal(yield* store.slotsInUse(root), 1); assert.equal(yield* store.readOnlySlotsInUse(root), 4); assert.equal(yield* store.issueOwner(reviewIssue(1)), originalOwner); - const links = - yield* sql`SELECT thread_id FROM issue_thread_links WHERE thread_id = ${result.childThreadId}`; - assert.lengthOf(links, issue === undefined ? 0 : 1); + assert.deepEqual( + child.thread.issues?.map((link) => link.key) ?? [], + issue === undefined ? [] : ["1"], + ); } yield* work.queueIssue({ ...repository, diff --git a/apps/server/src/mcp/ManagedIssueDelegation.ts b/apps/server/src/mcp/ManagedIssueDelegation.ts index bb0f3a12b6fdb..024ccc4eac687 100644 --- a/apps/server/src/mcp/ManagedIssueDelegation.ts +++ b/apps/server/src/mcp/ManagedIssueDelegation.ts @@ -1,4 +1,5 @@ import { + IssueTrackerKind, OrchestratorMcpFailure, type OrchestratorMcpDelegateTaskInput, type OrchestratorMcpDelegateTaskResult, @@ -9,7 +10,8 @@ import { import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as IssueWorkService from "../issues/IssueWorkService.ts"; -import * as IssueLinks from "../issues/IssueLinks.ts"; +import * as TrackerIssueService from "../issue/IssueService.ts"; +import * as ThreadIssueService from "../orchestration-v2/ThreadIssueService.ts"; import * as IssueService from "../issues/IssueService.ts"; import * as IssueWorkStore from "../issues/IssueWorkStore.ts"; import { @@ -20,7 +22,8 @@ import { export const makeManagedIssueDelegation = Effect.gen(function* () { const issueWork = yield* Effect.serviceOption(IssueWorkService.IssueWorkService); - const issueLinks = yield* Effect.serviceOption(IssueLinks.IssueLinks); + const trackerIssues = yield* Effect.serviceOption(TrackerIssueService.IssueService); + const threadIssues = yield* Effect.serviceOption(ThreadIssueService.ThreadIssueService); const issueService = yield* Effect.serviceOption(IssueService.IssueService); const issueWorkStore = yield* Effect.serviceOption(IssueWorkStore.IssueWorkStore); const failure = (code: OrchestratorMcpFailure["code"], message: string) => @@ -37,7 +40,11 @@ export const makeManagedIssueDelegation = Effect.gen(function* () { ? parent.thread : yield* loadRoot(parent.thread.lineage.rootThreadId); const managed = requiresManagedIssueAdmission(input.role, parent.thread, root); - if (unmanaged && input.issue !== undefined && Option.isNone(issueLinks)) + if ( + unmanaged && + input.issue !== undefined && + (Option.isNone(trackerIssues) || Option.isNone(threadIssues)) + ) return yield* failure("orchestration_error", "Issue linking is unavailable on this server."); if (managed && input.issue === undefined) return yield* failure( @@ -101,18 +108,42 @@ export const makeManagedIssueDelegation = Effect.gen(function* () { ), ); }); - // Linking happens after the task projection is committed, as in the caller. - const linkUnmanaged = Effect.fnUntraced(function* ( - unmanaged: boolean, - issue: OrchestratorMcpDelegateTaskInput["issue"], - childThreadId: ThreadId | null, - parentThreadId: ThreadId, - ) { - if (unmanaged && issue !== undefined && childThreadId !== null && Option.isSome(issueLinks)) - yield* issueLinks.value - .link({ ...issue, threadId: childThreadId }, parentThreadId) - .pipe(Effect.mapError((error) => failure("orchestration_error", error.message))); - }); + // Linking happens after the task projection is committed, as in the caller. Reading the issue + // names it for the thread's row, as upstream's link_issue does. + const linkUnmanaged = Effect.fnUntraced( + function* ( + unmanaged: boolean, + issue: OrchestratorMcpDelegateTaskInput["issue"], + childThreadId: ThreadId | null, + parent: OrchestrationV2AppThread, + ) { + if ( + !unmanaged || + issue === undefined || + childThreadId === null || + Option.isNone(trackerIssues) || + Option.isNone(threadIssues) + ) + return; + const ref = { + projectId: parent.projectId, + tracker: IssueTrackerKind.make("github"), + host: (issue.host ?? "github.com").toLowerCase(), + scope: issue.repository, + key: String(issue.number), + }; + const detail = yield* trackerIssues.value.detail(ref); + yield* threadIssues.value.link({ + threadId: childThreadId, + ref, + url: detail.url, + displayKey: detail.displayKey, + title: detail.title, + source: "agent", + }); + }, + Effect.mapError((error) => failure("orchestration_error", error.message)), + ); // The delegateTask span owns the response; pool policy belongs with admission. const withQueueNote = Effect.fnUntraced(function* ( taskResult: OrchestratorMcpDelegateTaskResult, diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 28c072b934092..690aa5bc1960d 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2948,7 +2948,7 @@ const make = Effect.gen(function* () { unmanaged, input.issue, childThreadId, - parent.thread.id, + parent.thread, ); const childRunEvent = result.storedEvents.find( (stored) => stored.event.type === "run.created" && stored.event.threadId === childThreadId, diff --git a/apps/server/src/orchestration-v2/ForkHistoryMaintenance.ts b/apps/server/src/orchestration-v2/ForkHistoryMaintenance.ts index 8c701ac026f94..5033bc209a0a0 100644 --- a/apps/server/src/orchestration-v2/ForkHistoryMaintenance.ts +++ b/apps/server/src/orchestration-v2/ForkHistoryMaintenance.ts @@ -85,7 +85,6 @@ export const maintainForkHistory = Effect.fn("ForkHistoryMaintenance.run")(funct ["projection_threads", "thread_id"], ["projection_thread_pull_requests", "thread_id"], ["projection_thread_sessions", "thread_id"], - ["issue_thread_links", "thread_id"], ] as const; const drainBatches = diff --git a/apps/server/src/orchestration-v2/IssueWorkCommands.ts b/apps/server/src/orchestration-v2/IssueWorkCommands.ts index c0a431fbb0d1f..9fd2cfadeb639 100644 --- a/apps/server/src/orchestration-v2/IssueWorkCommands.ts +++ b/apps/server/src/orchestration-v2/IssueWorkCommands.ts @@ -1,7 +1,8 @@ import { keepIssueWorktree } from "../issues/issueThreadRetention.ts"; -import { MessageId } from "@t3tools/contracts"; +import { IssueTrackerKind, MessageId } from "@t3tools/contracts"; import type { NodeId, + ProjectId, ProviderDriverKind, OrchestrationV2AppThread, OrchestrationV2Command, @@ -10,6 +11,7 @@ import type { OrchestrationV2StoredEvent, RunId, ThreadId, + ThreadIssueLink, ThreadLinkedIssue, } from "@t3tools/contracts"; import { delegatedTaskProgress } from "@t3tools/provider-core/server/subagentProjection"; @@ -79,6 +81,35 @@ interface IssueWorkCommandHooks extends ForkCommandHooks { ) => Effect.Effect; } +/** + * The claim and its `thread.issues[]` link, written by the one event that creates the claimed + * thread, so screens and tools see the claim like any other link. + */ +export const claimFields = ( + issue: ThreadLinkedIssue | undefined, + projectId: ProjectId, + now: DateTime.Utc, +): { linkedIssue?: ThreadLinkedIssue; issues?: ThreadIssueLink[] } => + issue === undefined + ? {} + : { + linkedIssue: issue, + issues: [ + { + tracker: IssueTrackerKind.make("github"), + host: issue.host.toLowerCase(), + scope: issue.repository, + key: String(issue.number), + projectId, + url: issue.url, + source: "agent", + linkedAt: DateTime.formatIso(now), + displayKey: `#${issue.number}`, + title: issue.title.trim() || "Untitled issue", + }, + ], + }; + // Decisions use the supplied committed reads and collector; dispatch owns locks and commit. export function makeIssueWorkCommands({ issueWorkStore, @@ -513,10 +544,15 @@ export function makeIssueWorkCommands({ }); }); - const childIssueFields = (request: DelegatedTaskRequest) => ({ + // The claim's link replaces links the child inherited from its parent's thread. + const childIssueFields = ( + request: DelegatedTaskRequest, + projectId: ProjectId, + now: DateTime.Utc, + ) => ({ ...(request.issue === undefined || isUnmanagedIssueRole(request.role) ? {} - : { linkedIssue: request.issue, titleSource: "generated" as const }), + : { ...claimFields(request.issue, projectId, now), titleSource: "generated" as const }), ...(request.role === undefined ? {} : { role: request.role }), }); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 327de90008830..212b3bf4f3ef4 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -177,7 +177,11 @@ import { makeIssueWorkDispatch, } from "./IssueWorkDispatch.ts"; import { makeIssueWorkRecovery } from "./IssueWorkRecovery.ts"; -import { makeIssueWorkCommands, type DelegatedTaskRequest } from "./IssueWorkCommands.ts"; +import { + claimFields, + makeIssueWorkCommands, + type DelegatedTaskRequest, +} from "./IssueWorkCommands.ts"; import { makeRepositoryWorkCommands } from "./RepositoryWorkCommands.ts"; import { DispatchModeLimit, @@ -3937,7 +3941,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projectId: command.projectId, title: command.linkedIssue === undefined ? command.title : issueThreadTitle(command.linkedIssue), - ...(command.linkedIssue === undefined ? {} : { linkedIssue: command.linkedIssue }), + ...claimFields(command.linkedIssue, command.projectId, now), ...(command.repositoryOrchestration === undefined ? {} : { repositoryOrchestration: command.repositoryOrchestration }), @@ -9965,7 +9969,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio createdBy: request.createdBy, creationSource: request.creationSource, }), - ...issueWork.childIssueFields(request), + ...issueWork.childIssueFields(request, parentProjection.thread.projectId, now), runtimeMode: request.runtimeMode, interactionMode: request.interactionMode, ...issueWork.childWorkspaceFields(request), diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.readOnlyLimit.fork.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.readOnlyLimit.fork.test.ts index 41ec8632a030a..c23a536cdbdb7 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.readOnlyLimit.fork.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.readOnlyLimit.fork.test.ts @@ -3,7 +3,8 @@ import * as OrchestratorMcp from "../mcp/OrchestratorMcpService.ts"; import * as ScheduledTasks from "../scheduledTasks/ScheduledTaskService.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; -import * as IssueLinks from "../issues/IssueLinks.ts"; +import * as TrackerIssueService from "../issue/IssueService.ts"; +import * as ThreadIssueService from "./ThreadIssueService.ts"; import { assert, it, vi } from "@effect/vitest"; import { CommandId, @@ -458,15 +459,19 @@ it.effect( Layer.mock(GitVcsDriver.GitVcsDriver)({}), Layer.mock(ScheduledTasks.ScheduledTaskService)({}), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(IssueLinks.IssueLinks)({ + Layer.mock(TrackerIssueService.IssueService)({ + detail: (ref) => + Effect.succeed({ + url: `https://github.com/${ref.scope}/issues/${ref.key}`, + displayKey: `#${ref.key}`, + title: "Issue", + } as never), + }), + Layer.mock(ThreadIssueService.ThreadIssueService)({ link: (input) => Effect.sync(() => { - links.push(input.threadId!); - return { - issue: { ...reference, number: input.number! }, - threadId: input.threadId!, - changed: true, - }; + links.push(input.threadId); + return { alreadyLinked: false }; }), }), ), diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index dc0f6cb5613c4..f4bcd2d6cc0f9 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -60,6 +60,7 @@ import { speechHttpApiLayer } from "./speech/http.ts"; import { speechStreamRouteLayer } from "./speech/stream.ts"; import * as PullRequestProviderRegistry from "./pullRequest/PullRequestProviderRegistry.ts"; import * as PullRequestService from "./pullRequest/PullRequestService.ts"; +import * as IssueLinkBackfill from "./issues/IssueLinkBackfill.ts"; import * as IssueServerLayers from "./issues/IssueServerLayers.ts"; import * as IssueService from "./issue/IssueService.ts"; import * as IssueTrackerConnections from "./issue/IssueTrackerConnections.ts"; @@ -919,6 +920,7 @@ const layerMakeRoutes = Layer.mergeAll( Layer.effectDiscard( RemoteDelegation.RemoteDelegation.pipe(Effect.flatMap((remote) => remote.start())), ), + IssueLinkBackfill.layer, ).pipe( Layer.provide( PullRequestReviewGuideService.layer.pipe(Layer.provide(PullRequestReviewGuides.layer)), diff --git a/apps/web/src/components/issues/IssueDetailActions.tsx b/apps/web/src/components/issues/IssueDetailActions.tsx index 06178fe5bd0d0..e679b942881b1 100644 --- a/apps/web/src/components/issues/IssueDetailActions.tsx +++ b/apps/web/src/components/issues/IssueDetailActions.tsx @@ -1,67 +1,29 @@ -import { useAtomValue } from "@effect/atom-react"; -import type { - EnvironmentId, - RepositoryIssueRef, - RepositoryIssueSummary, - ScopedThreadRef, -} from "@t3tools/contracts"; -import { CopyIcon, MoreHorizontalIcon, RefreshCwIcon, UnlinkIcon } from "lucide-react"; -import { useState } from "react"; +import type { RepositoryIssueSummary } from "@t3tools/contracts"; +import { CopyIcon, MoreHorizontalIcon, RefreshCwIcon } from "lucide-react"; import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; -import { repositoryIssueEnvironment } from "~/state/repositoryIssues"; -import { formatEnvironmentQueryError } from "~/state/query"; -import { useAtomCommand } from "~/state/use-atom-command"; import { Button } from "../ui/button"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; import { toastManager } from "../ui/toast"; -import { canUnlinkIssue } from "./issueDetailActions.logic"; /** - * The fork's issue actions upstream's panel lacks: removing an old `link_issue` link, refreshing - * the work data, and copying the number. Upstream's panel owns state, links and opening. + * The fork's issue actions upstream's panel lacks: refreshing the work data and copying the + * number. Upstream's panel owns state, links and opening. */ export function IssueDetailActions({ - environmentId, - reference, issue, - threadRef, refreshing, onRefresh, }: { - environmentId: EnvironmentId; - reference: RepositoryIssueRef; issue: RepositoryIssueSummary; - threadRef: ScopedThreadRef | null; refreshing: boolean; onRefresh: () => void; }) { - const unlink = useAtomCommand(repositoryIssueEnvironment.unlink, { reportFailure: false }); - const canUnlink = useAtomValue(repositoryIssueEnvironment.unlink.permissionAtom(environmentId)); - const [writing, setWriting] = useState(false); const { copyToClipboard } = useCopyToClipboard({ target: "issue reference", onCopy: (label) => toastManager.add({ type: "success", title: `${label} copied` }), onError: (error) => toastManager.add({ type: "error", title: error.message }), }); - const removeLink = async () => { - if (threadRef === null) return; - setWriting(true); - const result = await unlink({ - environmentId, - input: { ...reference, threadId: threadRef.threadId }, - }); - setWriting(false); - if (result._tag === "Failure") { - toastManager.add({ - type: "error", - title: "Could not unlink issue", - description: formatEnvironmentQueryError(result.cause), - }); - return; - } - onRefresh(); - }; return ( - {canUnlink && canUnlinkIssue(issue, environmentId, threadRef) ? ( - void removeLink()}> - - Unlink from this thread - - ) : null} Refresh diff --git a/apps/web/src/components/issues/IssueWorkSection.tsx b/apps/web/src/components/issues/IssueWorkSection.tsx index 349226a322a3a..2da47c6a91d84 100644 --- a/apps/web/src/components/issues/IssueWorkSection.tsx +++ b/apps/web/src/components/issues/IssueWorkSection.tsx @@ -221,10 +221,7 @@ function IssueWorkSection({ threadRef={threadRef} /> diff --git a/apps/web/src/components/issues/issueDetailActions.logic.test.ts b/apps/web/src/components/issues/issueDetailActions.logic.test.ts index 5dfc2fffe3858..ef01b26c85866 100644 --- a/apps/web/src/components/issues/issueDetailActions.logic.test.ts +++ b/apps/web/src/components/issues/issueDetailActions.logic.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { - canUnlinkIssue, issueReferenceCopyTarget, filterIssueComments, issueComposerPrompt, @@ -17,39 +16,6 @@ const issue = { }; describe("issue menu", () => { - it("unlinks only ordinary links belonging to this thread on this environment", () => { - const summary = { - liveWork: [ - { - threadId: threadRef.threadId, - title: "Thread", - branch: null, - worktreePath: null, - pullRequests: [], - status: "idle" as const, - canUnlink: true, - }, - ], - }; - expect(canUnlinkIssue(summary, "host", threadRef)).toBe(true); - expect(canUnlinkIssue(summary, "another-host", threadRef)).toBe(false); - expect(canUnlinkIssue(summary, "host", null)).toBe(false); - expect( - canUnlinkIssue( - { ...summary, liveWork: [{ ...summary.liveWork![0]!, canUnlink: false }] }, - "host", - threadRef, - ), - ).toBe(false); - expect( - canUnlinkIssue( - { ...summary, liveWork: [{ ...summary.liveWork![0]!, threadId: ThreadId.make("other") }] }, - "host", - threadRef, - ), - ).toBe(false); - }); - it("adds issue context for a question and preserves existing composer text", () => { const prompt = issueComposerPrompt("ask", issue); expect(prompt).toBe("#44: Match PR panes\n\nhttps://github.com/owner/repo/issues/44"); diff --git a/apps/web/src/components/issues/issueDetailActions.logic.ts b/apps/web/src/components/issues/issueDetailActions.logic.ts index 9843d79db2a6b..e61be7c7274b9 100644 --- a/apps/web/src/components/issues/issueDetailActions.logic.ts +++ b/apps/web/src/components/issues/issueDetailActions.logic.ts @@ -3,7 +3,6 @@ import type { EnvironmentId, RepositoryIssueComment, RepositoryIssueSummary, - ScopedThreadRef, ThreadId, } from "@t3tools/contracts"; @@ -39,20 +38,6 @@ export function issueImplementDestination(input: { }; } -/** Only ordinary associations can be removed; managed work and PR references keep their owners. */ -export function canUnlinkIssue( - issue: Pick, - environmentId: string, - threadRef: ScopedThreadRef | null, -) { - return ( - threadRef?.environmentId === environmentId && - issue.liveWork?.some( - (work) => work.threadId === threadRef.threadId && work.canUnlink === true, - ) === true - ); -} - export function issueComposerPrompt( action: IssueComposerAction, issue: Pick, diff --git a/docs/operations/fork.md b/docs/operations/fork.md index 1777d6a869be3..04727666994f3 100644 --- a/docs/operations/fork.md +++ b/docs/operations/fork.md @@ -35,8 +35,10 @@ content: its `/issues` page, its detail panel and its agent tools (`list_issues` The fork adds the work on top: the roadmap at `/roadmap` and in the per-repository Issues panel beside a thread, with Ready / Paused / Queued / In progress / Done, and a work section inside upstream's issue panel. Until #451 is finished, the roadmap still lists issues through the fork's -own GitHub reads, and live work reads both upstream's thread links and the old -`issue_thread_links` table. +own GitHub reads. Thread links live only in upstream's `thread.issues[]`: a managed claim +(`linkedIssue`) writes its link in the same event, and a claim still counts as live work after +its link is removed. A one-time backfill at server start moves the retired `issue_thread_links` +rows onto `thread.issues[]`. ## Branches and worktrees diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 1ee84b53f2e0f..ca357a1734e0e 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -1086,22 +1086,19 @@ it.effect("guards inline shell launch and input against the destination terminal ), ); -it.effect("issue state and unlink writes check the destination's exact grant", () => +it.effect("issue state writes check the destination's exact grant", () => Effect.scoped( Effect.gen(function* () { const registry = yield* setup; const issues = createRepositoryIssueEnvironmentAtoms(runtime, () => Atom.make(null)); const statePermission = issues.setState.permissionAtom(env); - const unlinkPermission = issues.unlink.permissionAtom(env); registry.set( sessions(env), AsyncResult.success({ ...grant(true), permissions: [AuthSourceControlWriteScope] }), ); expect(registry.get(statePermission)).toBe(true); - expect(registry.get(unlinkPermission)).toBe(false); registry.set(sessions(env), AsyncResult.success(grant(true))); expect(registry.get(statePermission)).toBe(false); - expect(registry.get(unlinkPermission)).toBe(true); const failed = yield* Effect.promise(() => issues.setState.run(registry, { environmentId: env, diff --git a/packages/client-runtime/src/state/repositoryIssues.ts b/packages/client-runtime/src/state/repositoryIssues.ts index 829197cb5fc5d..dd123fde101d2 100644 --- a/packages/client-runtime/src/state/repositoryIssues.ts +++ b/packages/client-runtime/src/state/repositoryIssues.ts @@ -275,10 +275,6 @@ export function createRepositoryIssueEnvironmentAtoms( onSuccess: ({ environmentId }, registry) => Effect.sync(() => registry.update(localChanges(environmentId), (revision) => revision + 1)), }), - unlink: createEnvironmentRpcCommand(runtime, { - label: "environment-data:issues:unlink", - tag: WS_METHODS.issuesUnlink, - }), decideChange: createEnvironmentRpcCommand(runtime, { label: "environment-data:issues:decide-change", tag: WS_METHODS.issueChangesDecide, diff --git a/packages/contracts/src/issueLinks.ts b/packages/contracts/src/issueLinks.ts index 29c8619f22f24..5a3f74e75c823 100644 --- a/packages/contracts/src/issueLinks.ts +++ b/packages/contracts/src/issueLinks.ts @@ -1,33 +1,10 @@ import * as Schema from "effect/Schema"; -import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; -import { RepositoryIssueRef } from "./repositoryIssue.ts"; -export const IssueLinkInput = Schema.Struct({ - threadId: Schema.optional(ThreadId), - url: Schema.optional(TrimmedNonEmptyString), - host: Schema.optional(RepositoryIssueRef.fields.host), - repository: Schema.optional(RepositoryIssueRef.fields.repository), - number: Schema.optional(RepositoryIssueRef.fields.number), -}); -export type IssueLinkInput = typeof IssueLinkInput.Type; -export const IssueLinkResult = Schema.Struct({ - threadId: ThreadId, - issue: RepositoryIssueRef, - changed: Schema.Boolean, -}); -export type IssueLinkResult = typeof IssueLinkResult.Type; export class IssueLinkError extends Schema.TaggedError()("IssueLinkError", { - code: Schema.Literals(["invalid-request", "thread-not-found", "storage"]), + code: Schema.Literals(["storage"]), cause: Schema.optional(Schema.Defect()), }) { override get message() { - switch (this.code) { - case "invalid-request": - return "Pass a thread and an issue URL, or repository and positive issue number."; - case "thread-not-found": - return "The thread is unavailable."; - case "storage": - return "Issue links could not be read or saved."; - } + return "Issue links could not be read."; } } diff --git a/packages/contracts/src/issueRpc.ts b/packages/contracts/src/issueRpc.ts index 40da49765e06f..859f373d67390 100644 --- a/packages/contracts/src/issueRpc.ts +++ b/packages/contracts/src/issueRpc.ts @@ -5,7 +5,6 @@ import { AuthOrchestrationOperateScope, AuthSourceControlWriteScope, } from "./auth.ts"; -import { ThreadId } from "./baseSchemas.ts"; import { OwnerDecision, OwnerDecisionsListInput, @@ -25,7 +24,6 @@ import { IssueInboxUnread, } from "./issueInbox.ts"; import { IssueCleanupInput, IssueCleanupError, IssueCleanupResult } from "./issueCleanup.ts"; -import { IssueLinkInput, IssueLinkResult, IssueLinkError } from "./issueLinks.ts"; import { RepositoryIssueRef, IssueRepositoryRef, @@ -67,7 +65,6 @@ export const ISSUE_WS_METHODS = { issuesStatusBatch: "issues.statusBatch", issueWorkSetState: "issueWork.setState", issuesCleanup: "issues.cleanup", - issuesUnlink: "issues.unlink", issuesSubscribeLinkRefreshes: "issues.subscribeLinkRefreshes", issuesStart: "issues.start", issuesQueue: "issues.queue", @@ -147,11 +144,6 @@ const WsIssuesCleanupRpc = Rpc.make(ISSUE_WS_METHODS.issuesCleanup, { success: IssueCleanupResult, error: Schema.Union([IssueCleanupError, EnvironmentAuthorizationError]), }); -const WsIssuesUnlinkRpc = Rpc.make(ISSUE_WS_METHODS.issuesUnlink, { - payload: Schema.Struct({ ...IssueLinkInput.fields, threadId: ThreadId }), - success: IssueLinkResult, - error: Schema.Union([IssueLinkError, EnvironmentAuthorizationError]), -}); const WsIssuesQueueRpc = Rpc.make(ISSUE_WS_METHODS.issuesQueue, { payload: IssueQueueInput, @@ -293,7 +285,6 @@ export const issueRpcs = [ WsIssuesStatusBatchRpc, WsIssuesSetStateRpc, WsIssuesCleanupRpc, - WsIssuesUnlinkRpc, WsIssuesSubscribeLinkRefreshesRpc, WsIssuesStartRpc, WsIssuesQueueRpc, @@ -326,7 +317,6 @@ export const ISSUE_CLIENT_GUARDED_RPC_SCOPES = { [ISSUE_WS_METHODS.issuesEndRepository]: AuthOrchestrationOperateScope, [ISSUE_WS_METHODS.issueWorkSetState]: AuthSourceControlWriteScope, [ISSUE_WS_METHODS.issuesCleanup]: AuthSourceControlWriteScope, - [ISSUE_WS_METHODS.issuesUnlink]: AuthOrchestrationOperateScope, [ISSUE_WS_METHODS.issuesCloseOut]: AuthOrchestrationOperateScope, [ISSUE_WS_METHODS.issuesSetUsageSprint]: AuthOrchestrationOperateScope, [ISSUE_WS_METHODS.issuesCancelRequest]: AuthOrchestrationOperateScope, diff --git a/packages/contracts/src/repositoryIssue.ts b/packages/contracts/src/repositoryIssue.ts index 144bee0419118..ba3deec1a3b75 100644 --- a/packages/contracts/src/repositoryIssue.ts +++ b/packages/contracts/src/repositoryIssue.ts @@ -126,8 +126,6 @@ export const RepositoryIssueSummary = Schema.Struct({ Schema.Array( Schema.Struct({ ...IssueWorkStatus.fields, - /** An ordinary issue link, removable without altering managed work or PRs. */ - canUnlink: Schema.optional(Schema.Boolean), title: Schema.String, /** Absent from older servers and threads without an assigned role. */ role: Schema.optional(ThreadRole), diff --git a/scripts/fork-dev/seed.py b/scripts/fork-dev/seed.py index c8b1223a183e0..0fef3de46a554 100755 --- a/scripts/fork-dev/seed.py +++ b/scripts/fork-dev/seed.py @@ -385,6 +385,15 @@ def finished_runs(spec): for n in range(1, run_count(spec) + 1)] +def claim_link(spec, linked_at): + """A claim's thread.issues[] entry, as the server writes it with the claim.""" + issue = spec["linked_issue"] + return {"tracker": "github", "host": issue["host"], "scope": issue["repository"], + "key": str(issue["number"]), "projectId": PID[spec["project"]], "url": issue["url"], + "source": "agent", "linkedAt": linked_at, "displayKey": f"#{issue['number']}", + "title": issue["title"] or "Untitled issue"} + + def thread_row(spec): tid = thread_id(spec) if "gh_issue" in spec: @@ -410,7 +419,8 @@ def thread_row(spec): "providerInstanceId": spec["provider"], "modelSelection": model_selection(spec), "runtimeMode": "full-access", "interactionMode": "plan" if spec.get("plan") else "default", "branch": spec.get("branch", "main"), "worktreePath": spec.get("worktree"), - **({"linkedIssue": spec["linked_issue"]} if "linked_issue" in spec else {}), + **({"linkedIssue": spec["linked_issue"], "issues": [claim_link(spec, created)]} + if "linked_issue" in spec else {}), **({"repositoryOrchestration": repository_orchestration()} if spec.get("orchestrates") else {}), "linkedPullRequest": None, "pullRequests": spec.get("prs", []), "activeProviderThreadId": None, @@ -1143,11 +1153,6 @@ def base(db): db.executemany(RUN_SQL, [row for spec in THREADS for row in finished_runs(spec)]) write_timelines(db, phase_live=False) write_checkpoints(db) - db.executemany( - "INSERT INTO issue_thread_links (host, repository, issue_number, thread_id) VALUES (?, ?, ?, ?)", - [("github.com", SANDBOX_REPO.lower(), spec["gh_issue"], thread_id(spec)) - for spec in THREADS if "gh_issue" in spec], - ) owner = repository_orchestration() db.execute( "INSERT INTO orchestration_v2_projection_repository_orchestration VALUES " From d5f0a745e1004394fa31b929f664a1b3e642eb03 Mon Sep 17 00:00:00 2001 From: Tanner Polley <42780259+tannerpolley@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:10:42 -0700 Subject: [PATCH 2/2] fix(issues): cheap startup backfill, GitHub-only links, never fail a started delegation The backfill checks "already linked" first and reads a claim's event history only when the claim is unlinked, on the reader connection. Only github.com claims and rows are linked; other-host rows are dropped and their claims stay claims. A claim is skipped only when its own key once appeared in the thread's link history, and a claim's own URL is kept. Rows whose issue is not found are dropped; transient failures keep the row. An unmanaged delegated child whose issue read fails is linked by its number instead of failing a delegation that started. Co-Authored-By: Claude Opus 5.5 --- .../src/issues/IssueLinkBackfill.test.ts | 85 +++++++-- apps/server/src/issues/IssueLinkBackfill.ts | 169 ++++++++++++------ .../mcp/IssueReviewDelegation.fork.test.ts | 29 ++- apps/server/src/mcp/ManagedIssueDelegation.ts | 79 ++++---- docs/operations/fork.md | 6 +- 5 files changed, 256 insertions(+), 112 deletions(-) diff --git a/apps/server/src/issues/IssueLinkBackfill.test.ts b/apps/server/src/issues/IssueLinkBackfill.test.ts index 6779da00890c5..7be4c0d880763 100644 --- a/apps/server/src/issues/IssueLinkBackfill.test.ts +++ b/apps/server/src/issues/IssueLinkBackfill.test.ts @@ -57,9 +57,16 @@ function setup() { Layer.mock(TrackerIssueService.IssueService)({ detail: (ref) => { reads.push(ref.key); + if (ref.key === "17") + return Effect.fail( + new IssueOperationError({ operation: "detail", detail: "gone", reason: "not-found" }), + ); return ref.key === "14" && titleReadsFail ? Effect.fail(new IssueOperationError({ operation: "detail", detail: "offline" })) - : Effect.succeed({ title: `Issue ${ref.key}` } as never); + : Effect.succeed({ + title: `Issue ${ref.key}`, + url: `https://github.com/${ref.scope}/issues/${ref.key}`, + } as never); }, }), ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); @@ -90,6 +97,15 @@ const create = (id: string, linkedIssue?: ReturnType) => creationSource: "web", }), ); +// A claim from before claims carried links: its projection has one, its history never did. +const oldClaim = (id: string, linkedIssue: ReturnType) => + Effect.gen(function* () { + yield* create(id); + yield* (yield* SqlClient.SqlClient)`UPDATE orchestration_v2_projection_threads + SET payload_json = json_set(payload_json, '$.linkedIssue', json(${JSON.stringify(linkedIssue)})) + WHERE thread_id = ${id}`; + }); +const forgejo = "tnnrpolley21-ms-7c95.taila72856.ts.net:3000"; const links = (id: string) => Effect.flatMap(Orchestrator.OrchestratorV2, (orchestrator) => orchestrator @@ -98,7 +114,7 @@ const links = (id: string) => ); it.effect( - "moves table rows and old claims onto thread links once, and keeps a row whose title read failed", + "moves GitHub table rows and old claims onto thread links, keeping only rows worth retrying", () => { const h = setup(); return Effect.gen(function* () { @@ -106,13 +122,10 @@ it.effect( const orchestrator = yield* Orchestrator.OrchestratorV2; const sink = yield* EventSink.EventSinkV2; yield* create("ordinary"); - yield* create("old-claim", claim(15, "Claimed title")); - yield* create("removed-claim", claim(16, "Removed")); yield* create("deleted"); - // A claim made now carries its link; an old claim's projection has none. - assert.deepEqual(yield* links("old-claim"), [["15", "Claimed title"]]); - yield* sql`UPDATE orchestration_v2_projection_threads - SET payload_json = json_remove(payload_json, '$.issues') WHERE thread_id = 'old-claim'`; + // A claim made now carries its link from creation, so a later unlink stays. + yield* create("removed-claim", claim(16, "Removed")); + assert.deepEqual(yield* links("removed-claim"), [["16", "Removed"]]); yield* orchestrator.dispatch({ type: "thread.issue.unlink", commandId: CommandId.make("user-unlinks-claim"), @@ -122,29 +135,63 @@ it.effect( scope: "owner/repo", key: "16", }); + // An old claim on #15 whose thread later linked #99 still gets its own link. + yield* oldClaim("old-claim", claim(15, "Claimed title")); + yield* orchestrator.dispatch({ + type: "thread.issue.link", + commandId: CommandId.make("upstream-links-99"), + threadId: ThreadId.make("old-claim"), + tracker: IssueTrackerKind.make("github"), + host: "github.com", + scope: "owner/repo", + key: "99", + projectId, + url: "https://github.com/owner/repo/issues/99", + displayKey: "#99", + title: "Issue 99", + source: "agent", + }); + yield* oldClaim("forgejo-claim", { ...claim(5, "Archived"), host: forgejo }); yield* sql`UPDATE orchestration_v2_projection_threads SET deleted_at = '2026-11-17T00:00:00.000Z' WHERE thread_id = 'deleted'`; - for (const [number, thread] of [ - [13, "ordinary"], - [14, "ordinary"], - [15, "old-claim"], - [13, "deleted"], - [13, "missing"], + for (const [host, number, thread] of [ + ["github.com", 13, "ordinary"], + ["github.com", 14, "ordinary"], + ["github.com", 17, "ordinary"], + ["github.com", 15, "old-claim"], + ["github.com", 13, "deleted"], + ["github.com", 13, "missing"], + [forgejo, 5, "ordinary"], ] as const) yield* sql`INSERT INTO issue_thread_links(host, repository, issue_number, thread_id) - VALUES ('github.com', 'owner/repo', ${number}, ${thread})`; + VALUES (${host}, 'owner/repo', ${number}, ${thread})`; const rows = sql<{ thread_id: string; issue_number: number; }>`SELECT thread_id, issue_number FROM issue_thread_links ORDER BY thread_id, issue_number`; - yield* IssueLinkBackfill.run(); + assert.deepEqual(yield* IssueLinkBackfill.run(), { + linked: 2, + rowsDone: 2, + rowsDropped: 3, + rowsKept: 1, + otherHostRows: 1, + otherHostClaims: 1, + }); assert.deepEqual(yield* links("ordinary"), [["13", "Issue 13"]]); - assert.deepEqual(yield* links("old-claim"), [["15", "Claimed title"]]); + assert.deepEqual(yield* links("old-claim"), [ + ["99", "Issue 99"], + ["15", "Claimed title"], + ]); assert.deepEqual(yield* links("removed-claim"), []); - // A claim's own title names it; each other issue is read once. - assert.deepEqual(h.reads, ["13", "14"]); + assert.deepEqual(yield* links("forgejo-claim"), []); + // A claim's own title names it; each other GitHub issue is read once. + assert.sameMembers(h.reads, ["13", "14", "17"]); + // Only the transient failure is retried; the missing issue and other hosts are dropped. assert.deepEqual(yield* rows, [{ thread_id: "ordinary", issue_number: 14 }]); + const oldClaimLink = (yield* orchestrator.getThreadShell(ThreadId.make("old-claim"))) + ?.issues?.[1]; + assert.equal(oldClaimLink?.url, "https://github.com/Owner/Repo/issues/15"); const shell = yield* orchestrator.getThreadShell(ThreadId.make("ordinary")); assert.deepEqual( shell?.issues?.map(({ tracker, host, scope, projectId, url, displayKey, source }) => ({ diff --git a/apps/server/src/issues/IssueLinkBackfill.ts b/apps/server/src/issues/IssueLinkBackfill.ts index 2afa477d80507..a23e37c9675a4 100644 --- a/apps/server/src/issues/IssueLinkBackfill.ts +++ b/apps/server/src/issues/IssueLinkBackfill.ts @@ -5,6 +5,7 @@ import { ThreadId, ThreadLinkedIssue, } from "@t3tools/contracts"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -15,6 +16,9 @@ import * as TrackerIssueService from "../issue/IssueService.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; import { forkParked } from "../serverActivation.ts"; +/** GitHub is the fork's only issue host; claims on other hosts stay claims without a link. */ +const GITHUB = "github.com"; + type Row = { readonly from_table: number; readonly host: string; @@ -24,6 +28,8 @@ type Row = { readonly project_id: string | null; readonly live: number; readonly linked: number; + /** A claim's own link once existed in the thread's link history, so someone removed it. */ + readonly removed: number; readonly claim_json: string | null; }; @@ -32,66 +38,104 @@ const issueKey = (row: Pick) => `${row.host.toLowerCase()}/${row.repository.toLowerCase()}#${row.number}`; /** - * Moves the retired `issue_thread_links` rows, and claims written before claims carried their - * link, onto `thread.issues[]` as commands, so the links survive a projection rebuild. A claim - * whose thread has had any link change is not an old claim: someone removed its link. The command - * id names the thread and the issue, so a rerun replays its receipt and changes nothing. + * Moves `issue_thread_links` rows and older GitHub claims onto `thread.issues[]` as commands, so + * links survive a projection rebuild. Runs at each start until nothing is left; the command id + * names the thread and issue, so a rerun replays its receipt. */ export const run = Effect.fn("IssueLinkBackfill.run")(function* () { const sql = yield* SqlClient.SqlClient; const orchestrator = yield* Orchestrator.OrchestratorV2; const issues = yield* TrackerIssueService.IssueService; - const linkedSql = (thread: string, host: string, repository: string, number: string) => sql` - EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(${sql.unsafe(thread)}.payload_json) - THEN ${sql.unsafe(thread)}.payload_json ELSE '{}' END, '$.issues') link + // `links` is a JSON array of thread.issues[] entries; the issue names columns in scope. + const matches = (links: string, host: string, repository: string, number: string) => sql` + EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(${sql.unsafe(links)}) + THEN ${sql.unsafe(links)} ELSE '{}' END, '$.issues') link WHERE json_extract(link.value, '$.tracker') = 'github' AND lower(json_extract(link.value, '$.host')) = lower(${sql.unsafe(host)}) AND lower(json_extract(link.value, '$.scope')) = lower(${sql.unsafe(repository)}) AND json_extract(link.value, '$.key') = CAST(${sql.unsafe(number)} AS TEXT))`; - const rows = yield* sql` + const tableRows = yield* sql` SELECT 1 AS from_table, row.host, row.repository, row.issue_number AS number, row.thread_id, thread.project_id, thread.thread_id IS NOT NULL AND thread.deleted_at IS NULL AS live, - COALESCE(${linkedSql("thread", "row.host", "row.repository", "row.issue_number")}, 0) AS linked, + COALESCE(${matches("thread.payload_json", "row.host", "row.repository", "row.issue_number")}, 0) AS linked, + 0 AS removed, CASE WHEN json_valid(thread.payload_json) THEN json_extract(thread.payload_json, '$.linkedIssue') END AS claim_json FROM issue_thread_links row LEFT JOIN orchestration_v2_projection_threads thread ON thread.thread_id = row.thread_id - UNION ALL - SELECT 0, json_extract(claimed.payload_json, '$.linkedIssue.host'), - json_extract(claimed.payload_json, '$.linkedIssue.repository'), - json_extract(claimed.payload_json, '$.linkedIssue.number'), claimed.thread_id, - claimed.project_id, 1, 0, json_extract(claimed.payload_json, '$.linkedIssue') - FROM orchestration_v2_projection_threads claimed - WHERE claimed.deleted_at IS NULL - AND lower(CASE WHEN json_valid(claimed.payload_json) THEN json_extract(claimed.payload_json, '$.linkedIssue.host') END) > '' - AND NOT EXISTS (SELECT 1 FROM orchestration_events event - WHERE event.aggregate_kind = 'thread' AND event.stream_id = claimed.thread_id - AND event.event_type = 'thread.issue-synced') - AND NOT ${linkedSql( - "claimed", - "json_extract(claimed.payload_json, '$.linkedIssue.host')", - "json_extract(claimed.payload_json, '$.linkedIssue.repository')", - "json_extract(claimed.payload_json, '$.linkedIssue.number')", - )} - `; + `.pipe(NodeSqliteClient.readOnly); + // The cheap payload check runs first; only unlinked GitHub claims read their event history. + const claims = yield* sql` + WITH unlinked AS MATERIALIZED ( + SELECT claimed.thread_id, claimed.project_id, + json_extract(claimed.payload_json, '$.linkedIssue.host') AS host, + json_extract(claimed.payload_json, '$.linkedIssue.repository') AS repository, + json_extract(claimed.payload_json, '$.linkedIssue.number') AS number, + json_extract(claimed.payload_json, '$.linkedIssue') AS claim_json + FROM orchestration_v2_projection_threads claimed + WHERE claimed.deleted_at IS NULL + AND lower(CASE WHEN json_valid(claimed.payload_json) THEN json_extract(claimed.payload_json, '$.linkedIssue.host') END) > '' + AND NOT ${matches( + "claimed.payload_json", + "json_extract(claimed.payload_json, '$.linkedIssue.host')", + "json_extract(claimed.payload_json, '$.linkedIssue.repository')", + "json_extract(claimed.payload_json, '$.linkedIssue.number')", + )} + ) + SELECT 0 AS from_table, host, repository, number, thread_id, project_id, 1 AS live, 0 AS linked, + CASE WHEN lower(host) <> ${GITHUB} THEN 0 ELSE EXISTS ( + SELECT 1 FROM orchestration_events event + WHERE event.aggregate_kind = 'thread' AND event.stream_id = unlinked.thread_id + AND event.event_type IN ('thread.created', 'thread.issue-synced') + AND ${matches("event.payload_json", "unlinked.host", "unlinked.repository", "unlinked.number")} + ) END AS removed, + claim_json + FROM unlinked + `.pipe(NodeSqliteClient.readOnly); const removeRow = (row: Row) => sql`DELETE FROM issue_thread_links WHERE host = ${row.host} AND repository = ${row.repository} AND issue_number = ${row.number} AND thread_id = ${row.thread_id}`; + const counts = { + linked: 0, + rowsDone: 0, + rowsDropped: 0, + rowsKept: 0, + otherHostRows: 0, + otherHostClaims: 0, + }; const pending: Array = []; - for (const row of rows) { - if (row.live === 1 && row.linked === 0 && row.project_id !== null) + for (const row of tableRows) { + if (row.live === 0 || row.project_id === null) { + yield* removeRow(row); + counts.rowsDropped++; + } else if (row.linked === 1) { + yield* removeRow(row); + counts.rowsDone++; + } else if (row.host.toLowerCase() !== GITHUB) { + yield* removeRow(row); + counts.otherHostRows++; + } else pending.push({ ...row, projectId: ProjectId.make(row.project_id) }); + } + const fromTable = new Set(pending.map((row) => `${row.thread_id}:${issueKey(row)}`)); + for (const row of claims) { + if (row.host.toLowerCase() !== GITHUB) counts.otherHostClaims++; + else if ( + row.removed === 0 && + row.project_id !== null && + !fromTable.has(`${row.thread_id}:${issueKey(row)}`) + ) pending.push({ ...row, projectId: ProjectId.make(row.project_id) }); - else if (row.from_table === 1) yield* removeRow(row); } - const titles = new Map(); - const unnamed = new Map(); + const named = new Map(); for (const row of pending) { const claim = Option.getOrUndefined(decodeClaim(row.claim_json)); const title = claim?.title.trim(); if (claim !== undefined && title && issueKey(claim) === issueKey(row)) - titles.set(issueKey(row), title); + named.set(issueKey(row), { title, url: claim.url }); } - for (const row of pending) if (!titles.has(issueKey(row))) unnamed.set(issueKey(row), row); + const unnamed = new Map(); + for (const row of pending) if (!named.has(issueKey(row))) unnamed.set(issueKey(row), row); + const missing = new Set(); yield* Effect.forEach( unnamed, ([key, row]) => @@ -99,52 +143,73 @@ export const run = Effect.fn("IssueLinkBackfill.run")(function* () { .detail({ projectId: row.projectId, tracker: IssueTrackerKind.make("github"), - host: row.host.toLowerCase(), + host: GITHUB, scope: row.repository, key: String(row.number), }) .pipe( - Effect.map((detail) => void titles.set(key, detail.title)), - // The row stays for the next start. - Effect.catch((error) => - Effect.logWarning("issue link backfill could not read an issue title", { + Effect.map((detail) => void named.set(key, { title: detail.title, url: detail.url })), + Effect.catch((error) => { + // A missing issue never appears; anything else may pass by the next start. + if (error._tag === "IssueOperationError" && error.reason === "not-found") + missing.add(key); + return Effect.logWarning("issue link backfill could not read an issue title", { issue: key, reason: error.message, - }), - ), + }); + }), ), { concurrency: 4, discard: true }, ); for (const row of pending) { - const title = titles.get(issueKey(row)); - if (title === undefined) continue; - const host = row.host.toLowerCase(); - yield* orchestrator + const key = issueKey(row); + const issue = named.get(key); + if (issue === undefined) { + if (row.from_table === 0) continue; + if (missing.has(key)) { + yield* removeRow(row); + counts.rowsDropped++; + } else counts.rowsKept++; + continue; + } + const linked = yield* orchestrator .dispatch({ type: "thread.issue.link", - commandId: CommandId.make(`fork:issue-link-backfill:${row.thread_id}:${issueKey(row)}`), + commandId: CommandId.make(`fork:issue-link-backfill:${row.thread_id}:${key}`), threadId: ThreadId.make(row.thread_id), tracker: IssueTrackerKind.make("github"), - host, + host: GITHUB, scope: row.repository, key: String(row.number), projectId: row.projectId, - url: `https://${host}/${row.repository}/issues/${row.number}`, + url: issue.url, displayKey: `#${row.number}`, - title, + title: issue.title, source: "agent", }) .pipe( - Effect.andThen(row.from_table === 1 ? removeRow(row) : Effect.void), + Effect.as(true), Effect.catch((error) => Effect.logWarning("issue link backfill could not link a thread", { thread: row.thread_id, - issue: issueKey(row), + issue: key, reason: error.message, - }), + }).pipe(Effect.as(false)), ), ); + if (!linked) { + if (row.from_table === 1) counts.rowsKept++; + continue; + } + counts.linked++; + if (row.from_table === 1) { + yield* removeRow(row); + counts.rowsDone++; + } } + if (Object.entries(counts).some(([name, count]) => name !== "otherHostClaims" && count > 0)) + yield* Effect.logInfo("issue link backfill", counts); + return counts; }); export const layer = Layer.effectDiscard( diff --git a/apps/server/src/mcp/IssueReviewDelegation.fork.test.ts b/apps/server/src/mcp/IssueReviewDelegation.fork.test.ts index 351d1c3ce209d..0d2cc5731a39a 100644 --- a/apps/server/src/mcp/IssueReviewDelegation.fork.test.ts +++ b/apps/server/src/mcp/IssueReviewDelegation.fork.test.ts @@ -4,6 +4,7 @@ import { assert, it, vi } from "@effect/vitest"; import { CommandId, EnvironmentId, + IssueOperationError, EventId, ProviderSessionId, resolveThreadRole, @@ -54,11 +55,13 @@ function setup() { ThreadIssueService.layer.pipe(Layer.provide(Layer.mergeAll(harness.layer, NodeCrypto.layer))), Layer.mock(TrackerIssueService.IssueService)({ detail: (ref) => - Effect.succeed({ - url: `https://github.com/${ref.scope}/issues/${ref.key}`, - displayKey: `#${ref.key}`, - title: `Issue ${ref.key}`, - } as never), + ref.key === "3" + ? Effect.fail(new IssueOperationError({ operation: "detail", detail: "offline" })) + : Effect.succeed({ + url: `https://github.com/${ref.scope}/issues/${ref.key}`, + displayKey: `#${ref.key}`, + title: `Issue ${ref.key}`, + } as never), }), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), Layer.mock(SecretRequests.SecretRequests)({}), @@ -66,10 +69,8 @@ function setup() { resolveCommit: () => Effect.succeed({ commitSha: "abc" } as never), }), ); - const launch = Layer.mock(ThreadLaunch.ThreadLaunchService)({ - readDefaultBranch, - prepareRun: () => Effect.void, - }); + const prepareRun = vi.fn((_input: { readonly threadId: ThreadId }) => Effect.void); + const launch = Layer.mock(ThreadLaunch.ThreadLaunchService)({ readDefaultBranch, prepareRun }); const services = Layer.mergeAll( dependencies, IssueWorkService.layer.pipe(Layer.provide(Layer.mergeAll(dependencies, launch))), @@ -78,6 +79,7 @@ function setup() { return { ...harness, readDefaultBranch, + prepareRun, close: () => { closed = true; }, @@ -215,6 +217,15 @@ it.effect( }); const separate = yield* threads.getThreadRecords(isolated.childThreadId!, ["runs"]); assert.equal(separate.runs[0]!.workspacePreparation?.type, "worktree"); + // Issue #3's read fails after the child started: the delegation still succeeds, names the + // link by number, and prepares the child's worktree. + assert.deepEqual( + separate.thread.issues?.map(({ key, title }) => [key, title]), + [["3", "#3"]], + ); + assert.isTrue( + harness.prepareRun.mock.calls.some(([input]) => input.threadId === isolated.childThreadId), + ); assert.isNull(yield* store.issueOwner(reviewIssue(3))); assert.equal((yield* store.queue(repository))[0]!.issue.id, reviewIssue(3).id); assert.equal(yield* store.slotsInUse(root), 1); diff --git a/apps/server/src/mcp/ManagedIssueDelegation.ts b/apps/server/src/mcp/ManagedIssueDelegation.ts index 024ccc4eac687..8d4654fc35cfd 100644 --- a/apps/server/src/mcp/ManagedIssueDelegation.ts +++ b/apps/server/src/mcp/ManagedIssueDelegation.ts @@ -108,42 +108,61 @@ export const makeManagedIssueDelegation = Effect.gen(function* () { ), ); }); - // Linking happens after the task projection is committed, as in the caller. Reading the issue - // names it for the thread's row, as upstream's link_issue does. - const linkUnmanaged = Effect.fnUntraced( - function* ( - unmanaged: boolean, - issue: OrchestratorMcpDelegateTaskInput["issue"], - childThreadId: ThreadId | null, - parent: OrchestrationV2AppThread, - ) { - if ( - !unmanaged || - issue === undefined || - childThreadId === null || - Option.isNone(trackerIssues) || - Option.isNone(threadIssues) - ) - return; - const ref = { - projectId: parent.projectId, - tracker: IssueTrackerKind.make("github"), - host: (issue.host ?? "github.com").toLowerCase(), - scope: issue.repository, - key: String(issue.number), - }; - const detail = yield* trackerIssues.value.detail(ref); - yield* threadIssues.value.link({ + // The child already exists and runs, so a failure here must not fail the delegation: a retry + // would start a second child. A failed read names the link by its number. + const linkUnmanaged = Effect.fnUntraced(function* ( + unmanaged: boolean, + issue: OrchestratorMcpDelegateTaskInput["issue"], + childThreadId: ThreadId | null, + parent: OrchestrationV2AppThread, + ) { + if ( + !unmanaged || + issue === undefined || + childThreadId === null || + Option.isNone(trackerIssues) || + Option.isNone(threadIssues) + ) + return; + const host = (issue.host ?? "github.com").toLowerCase(); + const ref = { + projectId: parent.projectId, + tracker: IssueTrackerKind.make("github"), + host, + scope: issue.repository, + key: String(issue.number), + }; + const detail = yield* trackerIssues.value.detail(ref).pipe( + Effect.tapError((error) => + Effect.logWarning("delegated child linked without reading its issue", { + thread: childThreadId, + reason: error.message, + }), + ), + Effect.orElseSucceed(() => ({ + url: `https://${host}/${issue.repository}/issues/${issue.number}`, + displayKey: `#${issue.number}`, + title: `#${issue.number}`, + })), + ); + yield* threadIssues.value + .link({ threadId: childThreadId, ref, url: detail.url, displayKey: detail.displayKey, title: detail.title, source: "agent", - }); - }, - Effect.mapError((error) => failure("orchestration_error", error.message)), - ); + }) + .pipe( + Effect.catch((error) => + Effect.logWarning("delegated child could not be linked to its issue", { + thread: childThreadId, + reason: error.message, + }), + ), + ); + }); // The delegateTask span owns the response; pool policy belongs with admission. const withQueueNote = Effect.fnUntraced(function* ( taskResult: OrchestratorMcpDelegateTaskResult, diff --git a/docs/operations/fork.md b/docs/operations/fork.md index 04727666994f3..47943c7c11f9b 100644 --- a/docs/operations/fork.md +++ b/docs/operations/fork.md @@ -37,8 +37,10 @@ beside a thread, with Ready / Paused / Queued / In progress / Done, and a work s upstream's issue panel. Until #451 is finished, the roadmap still lists issues through the fork's own GitHub reads. Thread links live only in upstream's `thread.issues[]`: a managed claim (`linkedIssue`) writes its link in the same event, and a claim still counts as live work after -its link is removed. A one-time backfill at server start moves the retired `issue_thread_links` -rows onto `thread.issues[]`. +its link is removed. At each start, a backfill moves the retired `issue_thread_links` rows and +older GitHub claims onto `thread.issues[]`, until the table is empty and every GitHub claim is +linked; after that it finds nothing to do. Rows and claims on other hosts, such as the archived +Forgejo, are not linked: their rows are dropped and their claims stay claims. ## Branches and worktrees