⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(integrations): revalidate provider confirmation snapshots
Tinc2c3bcff48a0
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts b/apps/api/src/plugins/gitea/webhooks/issue-closed.tsindex c8d128875..c2c9ec083 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts@@ -87,7 +87,7 @@ export async function handleGiteaIssueClosed(};await withEchoConfirmation(readCurrent,- (current) =>+ (current, confirmation) =>withIntegrationLink(externalLink,integration,@@ -119,6 +119,7 @@ export async function handleGiteaIssueClosed(linkId: externalLink.id,field: "state",localValue: task.status === "done" ? "closed" : "open",+ confirmation,},))diff --git a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts b/apps/api/src/plugins/gitea/webhooks/issue-edited.tsindex 9266c5abe..4f31962bf 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-edited.ts@@ -83,7 +83,7 @@ export async function handleGiteaIssueEdited(};await withEchoConfirmation(readCurrent,- (current) =>+ (current, confirmation) =>withIntegrationLink(externalLink,integration,@@ -125,6 +125,7 @@ export async function handleGiteaIssueEdited(linkId: externalLink.id,field: "title",localValue: task.title,+ confirmation,},)) {@@ -168,6 +169,7 @@ export async function handleGiteaIssueEdited(linkId: externalLink.id,field: "description",localValue: task.description || "",+ confirmation,},)) {diff --git a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts b/apps/api/src/plugins/gitea/webhooks/issue-reopened.tsindex 3ab480731..224a93a80 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts@@ -89,7 +89,7 @@ export async function handleGiteaIssueReopened(};await withEchoConfirmation(readCurrent,- (current) =>+ (current, confirmation) =>withIntegrationLink(externalLink,integration,@@ -120,6 +120,7 @@ export async function handleGiteaIssueReopened(linkId: externalLink.id,field: "state",localValue: task.status === "done" ? "closed" : "open",+ confirmation,},))diff --git a/apps/api/src/plugins/github/utils/inbound-echo.ts b/apps/api/src/plugins/github/utils/inbound-echo.tsindex f6e3adca2..e18bd187d 100644--- a/apps/api/src/plugins/github/utils/inbound-echo.ts+++ b/apps/api/src/plugins/github/utils/inbound-echo.ts@@ -1,3 +1,4 @@+import { createHash } from "node:crypto";import { updateExternalLink } from "../services/link-manager";import {ambiguousOutboundEcho,@@ -7,7 +8,19 @@ import {inboundOccurredAfterIntent,type SyncStamp,} from "./sync-echo";-class ConfirmationRequired extends Error {}+type ConfirmationSnapshot = {+ fingerprint: string;+ localValueHash: string;+};+type EchoConfirmation = ReadonlyMap<string, ConfirmationSnapshot>;+class ConfirmationRequired extends Error {+ constructor(+ public key?: string,+ public snapshot?: ConfirmationSnapshot,+ ) {+ super("Current provider confirmation is required");+ }+}class RepairRequired extends Error {}export class PendingResponseTimeout extends Error {}export class PendingEcho extends Error {@@ -32,8 +45,39 @@ export function inboundEcho(linkId: string;field: "title" | "description" | "state";localValue?: string;+ confirmation?: EchoConfirmation;},) {+ const confirmedValue = () => {+ const key = context ? `${context.linkId}:${context.field}` : undefined;+ const localValueHash = createHash("sha256")+ .update(context?.localValue ?? stamp?.value ?? "")+ .digest("hex");+ const snapshot = key+ ? {+ fingerprint: createHash("sha256")+ .update(JSON.stringify({ stamp, localValueHash }))+ .digest("hex"),+ localValueHash,+ }+ : undefined;+ const previous = key ? context?.confirmation?.get(key) : undefined;+ // A newer local or provider edit owns reconciliation after the read began.+ if (+ providerValue !== undefined &&+ previous &&+ previous.localValueHash !== localValueHash+ )+ return undefined;+ if (+ providerValue === undefined ||+ (key &&+ context?.confirmation &&+ previous?.fingerprint !== snapshot?.fingerprint)+ )+ throw new ConfirmationRequired(key, snapshot);+ return providerValue;+ };const version = Date.parse(updatedAt ?? "");const inboundVersion = Date.parse(stamp?.inboundUpdatedAt ?? "");const knownVersions = [@@ -52,8 +96,7 @@ export function inboundEcho(version === inboundVersion &&stamp?.inboundValue !== value) {- if (providerValue === undefined) throw new ConfirmationRequired();- if (providerValue !== value) return true;+ if (confirmedValue() !== value) return true;}const uncertain = uncertainOutboundIntent(stamp, value);const localValue = context?.localValue ?? stamp?.value;@@ -66,8 +109,7 @@ export function inboundEcho(inboundOccurredAfterIntent(stamp, uncertain))) {- if (providerValue === undefined) throw new ConfirmationRequired();- if (providerValue !== value) return true;+ if (confirmedValue() !== value) return true;throw new RepairRequired();}const pending = pendingOutboundIntent(stamp, value);@@ -79,28 +121,30 @@ export function inboundEcho((entry) => !entry.cancelled && entry.updatedAt === updatedAt,);if (!colliding) return false;- if (providerValue === undefined) throw new ConfirmationRequired();- return providerValue !== value;+ return confirmedValue() !== value;}if (stamp?.value === value && !ambiguousOutboundEcho(stamp, value, updatedAt))return true;- if (providerValue === undefined) throw new ConfirmationRequired();- return providerValue !== value;+ return confirmedValue() !== value;}// Every retry releases the transaction first. Persist observed provider versions// so an outbound completion cannot repair over a newer edit waiting for it.export async function withEchoConfirmation<Provider, Result>(read: () => Promise<Provider>,- apply: (current?: Provider) => Promise<Result>,+ apply: (+ current?: Provider,+ confirmation?: EchoConfirmation,+ ) => Promise<Result>,defer?: () => Promise<void>,): Promise<Result | undefined> {const recorded = new Set<string>();+ const confirmation = new Map<string, ConfirmationSnapshot>();let current: Provider | undefined;let delay = 50;const deadline = Date.now() + 5000;for (;;) {try {- const result = await apply(current);+ const result = await apply(current, confirmation);if (result instanceof PendingEcho) throw result;return result;} catch (error) {@@ -154,10 +198,33 @@ export async function withEchoConfirmation<Provider, Result>();delay = Math.min(delay * 2, 1000);current = undefined;- } else if (- error instanceof ConfirmationRequired &&- current === undefined- ) {+ } else if (error instanceof ConfirmationRequired) {+ if (current !== undefined) {+ await new Promise((resolve) =>+ setTimeout(+ resolve,+ Math.min(delay, Math.max(0, deadline - Date.now())),+ ),+ );+ delay = Math.min(delay * 2, 1000);+ }+ if (Date.now() >= deadline) {+ if (!defer)+ throw new PendingResponseTimeout(+ "Provider confirmation changed; retry this webhook delivery",+ );+ try {+ await defer();+ return;+ } catch (cause) {+ throw new PendingResponseTimeout(+ "Could not persist deferred webhook delivery",+ { cause },+ );+ }+ }+ if (error.key && error.snapshot)+ confirmation.set(error.key, error.snapshot);try {current = await read();} catch (error) {diff --git a/apps/api/src/plugins/github/webhooks/issue-closed.ts b/apps/api/src/plugins/github/webhooks/issue-closed.tsindex 485b62f13..5d292003a 100644--- a/apps/api/src/plugins/github/webhooks/issue-closed.ts+++ b/apps/api/src/plugins/github/webhooks/issue-closed.ts@@ -66,7 +66,7 @@ export async function handleIssueClosed(payload: IssueClosedPayload) {};await withEchoConfirmation(readCurrent,- (current) =>+ (current, confirmation) =>withIntegrationLink(externalLink,integration,@@ -103,6 +103,7 @@ export async function handleIssueClosed(payload: IssueClosedPayload) {linkId: externalLink.id,field: "state",localValue: task.status === "done" ? "closed" : "open",+ confirmation,},))diff --git a/apps/api/src/plugins/github/webhooks/issue-edited.ts b/apps/api/src/plugins/github/webhooks/issue-edited.tsindex 4848b68f1..4752ab476 100644--- a/apps/api/src/plugins/github/webhooks/issue-edited.ts+++ b/apps/api/src/plugins/github/webhooks/issue-edited.ts@@ -85,7 +85,7 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {};await withEchoConfirmation(readCurrent,- (current) =>+ (current, confirmation) =>withIntegrationLink(externalLink,integration,@@ -132,6 +132,7 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {linkId: externalLink.id,field: "title",localValue: task.title,+ confirmation,},)) {@@ -181,6 +182,7 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {linkId: externalLink.id,field: "description",localValue: task.description || "",+ confirmation,},)) {diff --git a/apps/api/src/plugins/github/webhooks/issue-reopened.ts b/apps/api/src/plugins/github/webhooks/issue-reopened.tsindex e08cac429..091e7c97f 100644--- a/apps/api/src/plugins/github/webhooks/issue-reopened.ts+++ b/apps/api/src/plugins/github/webhooks/issue-reopened.ts@@ -66,7 +66,7 @@ export async function handleIssueReopened(payload: IssueReopenedPayload) {};await withEchoConfirmation(readCurrent,- (current) =>+ (current, confirmation) =>withIntegrationLink(externalLink,integration,@@ -106,6 +106,7 @@ export async function handleIssueReopened(payload: IssueReopenedPayload) {linkId: externalLink.id,field: "state",localValue: task.status === "done" ? "closed" : "open",+ confirmation,},))diff --git a/tests/api-integration/deferred-issue-edits.test.ts b/tests/api-integration/deferred-issue-edits.test.tsindex a818836a8..664ba0d52 100644--- a/tests/api-integration/deferred-issue-edits.test.ts+++ b/tests/api-integration/deferred-issue-edits.test.ts@@ -890,3 +890,140 @@ it("retains the uncertain intent and job when corrective provider HTTP fails", aexpect((await current(task.id))?.title).toBe("B");expect((await metadata(link.id)).deferredIssueEdit).toBeUndefined();});++it.each(providerFields)(+ "rechecks a stale $provider $field confirmation after a newer colliding webhook",+ async ({ provider, field }) => {+ const { task, integration, link } = await seed(provider);+ const version = "2026-09-30T00:00:03Z";+ const initial = field === "state" ? "closed" : "A";+ const stale = field === "state" ? "open" : "B";+ const latest = field === "state" ? "closed" : "C";+ await db+ .update(schema.taskTable)+ .set({+ [field === "state" ? "status" : field]:+ field === "state" ? "done" : initial,+ })+ .where(eq(schema.taskTable.id, task.id));+ await db+ .update(schema.externalLinkTable)+ .set({+ metadata: JSON.stringify({+ lastSync: {+ [field]: inboundStamp(undefined, initial, provider, version),+ },+ }),+ })+ .where(eq(schema.externalLinkTable.id, link.id));+ m.read.mockResolvedValue({+ title: latest,+ body: latest,+ state: "closed",+ updated_at: version,+ });+ m.read.mockImplementationOnce(async () => {+ await deliverField(provider, field, latest, version, integration.id);+ return { title: stale, body: stale, state: "open", updated_at: version };+ });+ await deliverField(provider, field, stale, version, integration.id);+ const row = await current(task.id);+ expect(field === "state" ? row?.status : row?.[field]).toBe(+ field === "state" ? "done" : latest,+ );+ expect((await metadata(link.id)).lastSync[field].inboundValue).toBe(latest);+ expect(m.read.mock.calls.length).toBeGreaterThanOrEqual(2);+ },+);+it.each(["github", "gitea"])(+ "validates each changed %s field when a shared confirmation GET becomes stale",+ async (provider) => {+ const { task, integration, link } = await seed(provider);+ const version = "2026-09-30T00:00:03Z";+ await db+ .update(schema.taskTable)+ .set({ title: "A", description: "A" })+ .where(eq(schema.taskTable.id, task.id));+ await db+ .update(schema.externalLinkTable)+ .set({+ metadata: JSON.stringify({+ lastSync: {+ title: inboundStamp(undefined, "A", provider, version),+ description: inboundStamp(undefined, "A", provider, version),+ },+ }),+ })+ .where(eq(schema.externalLinkTable.id, link.id));+ m.read.mockResolvedValue({+ title: "B",+ body: "C",+ state: "open",+ updated_at: version,+ });+ m.read.mockImplementationOnce(async () => {+ await deliverField(provider, "description", "C", version, integration.id);+ return { title: "B", body: "B", state: "open", updated_at: version };+ });+ const payload = {+ action: "edited",+ issue: {+ number: 1,+ title: "B",+ body: "B",+ updated_at: version,+ html_url: link.url,+ },+ changes: { title: { from: "A" }, body: { from: "A" } },+ repository: {+ id: 20,+ name: "repo",+ full_name: "owner/repo",+ owner: { login: "owner" },+ html_url: "https://git.example/owner/repo",+ },+ };+ if (provider === "github") await handleIssueEdited(payload);+ else await handleGiteaIssueEdited(payload, integration.id);+ expect(await current(task.id)).toMatchObject({+ title: "B",+ description: "C",+ });+ },+);++it.each(["github", "gitea"])(+ "preserves a newer local edit committed during %s provider confirmation",+ async (provider) => {+ const { task, integration, link } = await seed(provider);+ const version = "2026-09-30T00:00:03Z";+ await db+ .update(schema.taskTable)+ .set({ title: "A" })+ .where(eq(schema.taskTable.id, task.id));+ await db+ .update(schema.externalLinkTable)+ .set({+ metadata: JSON.stringify({+ lastSync: { title: inboundStamp(undefined, "A", provider, version) },+ }),+ })+ .where(eq(schema.externalLinkTable.id, link.id));+ m.read.mockResolvedValue({+ title: "B",+ body: "body",+ state: "open",+ updated_at: version,+ });+ m.read.mockImplementationOnce(async () => {+ await db+ .update(schema.taskTable)+ .set({ title: "C" })+ .where(eq(schema.taskTable.id, task.id));+ return { title: "B", body: "body", state: "open", updated_at: version };+ });+ await deliverField(provider, "title", "B", version, integration.id);+ expect((await current(task.id))?.title).toBe("C");+ expect(publishEvent).not.toHaveBeenCalled();+ },+);diff --git a/tests/api/plugins/gitea/rapid-text-sync.test.ts b/tests/api/plugins/gitea/rapid-text-sync.test.tsindex 5caf5fd4c..d4c5ba0b3 100644--- a/tests/api/plugins/gitea/rapid-text-sync.test.ts+++ b/tests/api/plugins/gitea/rapid-text-sync.test.ts@@ -298,7 +298,8 @@ it("accepts a legitimate remote edit matching a historical outbound value withintitle: "Earlier title",description: "Earlier body",});- expect(m.getIssue).toHaveBeenCalledTimes(1);+ // Each ambiguous field needs a confirmation tied to its locked sync state.+ expect(m.getIssue).toHaveBeenCalledTimes(2);});it("ignores the linked task footer when detecting a description echo", async () => {diff --git a/tests/api/plugins/github/outbound-intent.test.ts b/tests/api/plugins/github/outbound-intent.test.tsindex a8ee95e1a..d9ef0b981 100644--- a/tests/api/plugins/github/outbound-intent.test.ts+++ b/tests/api/plugins/github/outbound-intent.test.ts@@ -445,3 +445,56 @@ it("confirms different inbound values sharing a provider version", async () => {expect(read).toHaveBeenCalledOnce();expect(inboundEcho(stamp, "A", version, "A")).toBe(false);});++it("rereads a provider confirmation after the locked sync state changes", async () => {+ const version = "2026-09-30T00:00:03Z";+ let stamp = inboundStamp(undefined, "C", "github", version);+ const read = vi.fn(async () => {+ if (read.mock.calls.length === 1) {+ stamp = inboundStamp(stamp, "C", "github", version);+ return "B";+ }+ return "C";+ });+ const result = await withEchoConfirmation(+ read,+ async (current, confirmation) =>+ inboundEcho(stamp, "B", version, current, {+ linkId: "link",+ field: "title",+ localValue: stamp.value,+ confirmation,+ }),+ );+ expect(result).toBe(true);+ expect(read).toHaveBeenCalledTimes(2);+});+it("bounds confirmation retries and durably defers continuous sync changes", async () => {+ vi.useFakeTimers();+ try {+ const version = "2026-09-30T00:00:03Z";+ let stamp = inboundStamp(undefined, "C", "github", version);+ const read = vi.fn(async () => {+ stamp = inboundStamp(stamp, "C", "github", version);+ return "B";+ });+ const defer = vi.fn(async () => undefined);+ const run = withEchoConfirmation(+ read,+ async (current, confirmation) =>+ inboundEcho(stamp, "B", version, current, {+ linkId: "link",+ field: "title",+ localValue: stamp.value,+ confirmation,+ }),+ defer,+ );+ await vi.advanceTimersByTimeAsync(5000);+ await run;+ expect(defer).toHaveBeenCalledOnce();+ expect(read.mock.calls.length).toBeLessThanOrEqual(11);+ } finally {+ vi.useRealTimers();+ }+});