feat(FN-4253): close linked GitHub issues on task deletion

Implements automatic closing of linked GitHub issues when a task is deleted (FN-4253), adding deletion logic to the GitHub tracking state module with corresponding tests for both state management and deletion behavior, plus a patch changeset for the `@runfusion/fusion` CLI.

Fusion-Task-Id: FN-4253
This commit is contained in:
Fusion
2026-05-12 21:08:00 -07:00
committed by gsxdsm
parent 7428c4fd86
commit d0c9e47f66
6 changed files with 214 additions and 4 deletions

View File

@@ -0,0 +1,5 @@
---
"@runfusion/fusion": minor
---
Close the linked GitHub tracking issue (with state_reason "not_planned") when a tracked Fusion task is deleted.

View File

@@ -1332,7 +1332,7 @@ When Fusion does create a tracking issue, it formats the title as `[FN-XXXX] Tas
When a tracked task later moves to `in-progress` or `done`, Fusion posts one short lifecycle comment on the linked tracking issue. These comments always include the Fusion task ID as plain text (`Fusion task: FN-XXXX`) and never link back to the Fusion app. The `in-progress` comment stays plain-text; the `done` comment can additionally include GitHub commit/PR markdown links plus branch, file-change, and merge-timestamp details when that merge context is available on the task. No comment is posted for any other transition.
When a tracked task transitions into `done`, Fusion closes the linked GitHub issue with `state_reason: completed`. When a task transitions out of `done` into any active column (`triage`, `todo`, `in-progress`, `in-review`), Fusion reopens it with `state_reason: reopened`. Moves from `done` to `archived` leave the issue closed. Tasks without `githubTracking.enabled` or without a linked issue are unaffected, and GitHub failures are logged to task activity without blocking the move.
When a tracked task transitions into `done`, Fusion closes the linked GitHub issue with `state_reason: completed`. When a task transitions out of `done` into any active column (`triage`, `todo`, `in-progress`, `in-review`), Fusion reopens it with `state_reason: reopened`. When a tracked task is permanently deleted, Fusion closes the linked GitHub issue with `state_reason: not_planned`. Moves from `done` to `archived` leave the issue closed. Tasks without `githubTracking.enabled` or without a linked issue are unaffected, and GitHub failures are logged to task activity without blocking the move.
### Worktree model
- Each active task runs in isolated worktree under `.worktrees/*`

View File

@@ -493,6 +493,8 @@ When Fusion creates a tracking issue, it uses:
When tracked tasks later move to `in-progress` or `done`, Fusion also posts a short lifecycle comment on the linked tracking issue. The `in-progress` comment stays plain-text and capped, while the `done` comment can include the merge commit SHA/subject, task branch, PR link, file-change stats, and merge timestamp when those fields are available.
When a tracked task moves into `done`, Fusion closes the linked GitHub issue with `state_reason: completed`; when it leaves `done` for an active column, Fusion reopens the issue with `state_reason: reopened`; and when the Fusion task is permanently deleted, Fusion closes the linked issue with `state_reason: not_planned`.
GitHub authentication/settings are configured in [Settings Reference](./settings-reference.md) via `githubAuthMode` (`gh-cli` or `token`) and `githubAuthToken`.
## Completion Modes (`mergeStrategy`)

View File

@@ -0,0 +1,101 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mkdtempSync } from "node:fs";
import { rm } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { TaskStore } from "@fusion/core";
import { GitHubTrackingStateService } from "../github-tracking-state.js";
const { mockSetIssueState, mockResolveGithubTrackingAuth } = vi.hoisted(() => ({
mockSetIssueState: vi.fn(),
mockResolveGithubTrackingAuth: vi.fn(),
}));
vi.mock("../github.js", () => ({
GitHubClient: vi.fn().mockImplementation(() => ({
setIssueState: (...args: unknown[]) => mockSetIssueState(...args),
})),
}));
vi.mock("../github-auth.js", () => ({
resolveGithubTrackingAuth: (...args: unknown[]) => mockResolveGithubTrackingAuth(...args),
}));
function makeTmpDir(): string {
return mkdtempSync(join(tmpdir(), "kb-dashboard-github-tracking-delete-test-"));
}
async function flushAsync(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0));
}
describe("github tracking delete flow", () => {
let rootDir: string;
let globalDir: string;
let store: TaskStore;
let stateService: GitHubTrackingStateService;
beforeEach(async () => {
vi.clearAllMocks();
mockResolveGithubTrackingAuth.mockReturnValue({ ok: true, auth: { mode: "token", token: "token" } });
rootDir = makeTmpDir();
globalDir = makeTmpDir();
store = new TaskStore(rootDir, globalDir, { inMemoryDb: true });
await store.init();
stateService = new GitHubTrackingStateService(store);
stateService.start();
});
afterEach(async () => {
stateService.stop();
await flushAsync();
store.close();
await rm(rootDir, { recursive: true, force: true });
await rm(globalDir, { recursive: true, force: true });
});
it("closes the linked issue as not_planned when a tracked task is deleted", async () => {
const task = await store.createTask({
description: "delete tracked task",
githubTracking: { enabled: true },
});
await store.linkGithubIssue(task.id, {
owner: "octocat",
repo: "hello-world",
number: 7,
url: "https://github.com/octocat/hello-world/issues/7",
createdAt: new Date().toISOString(),
});
await store.deleteTask(task.id);
await flushAsync();
expect(mockSetIssueState).toHaveBeenCalledTimes(1);
expect(mockSetIssueState).toHaveBeenCalledWith("octocat", "hello-world", 7, "closed", "not_planned");
});
it("does not call GitHub when deleting a task with tracking disabled", async () => {
const task = await store.createTask({
description: "delete untracked task",
githubTracking: { enabled: false },
});
await store.deleteTask(task.id);
await flushAsync();
expect(mockSetIssueState).not.toHaveBeenCalled();
});
it("does not call GitHub when deleting a tracked task without a linked issue", async () => {
const task = await store.createTask({
description: "delete tracked task without issue",
githubTracking: { enabled: true },
});
await store.deleteTask(task.id);
await flushAsync();
expect(mockSetIssueState).not.toHaveBeenCalled();
});
});

View File

@@ -98,15 +98,17 @@ describe("GitHubTrackingStateService", () => {
service.start();
store.emit("task:moved", { task: createTask(), from: "triage", to: "done" });
store.emit("task:deleted", createTask({ id: "FN-2" }));
await flushAsync();
expect(mockSetIssueState).toHaveBeenCalledTimes(1);
expect(mockSetIssueState).toHaveBeenCalledTimes(2);
service.stop();
service.stop();
store.emit("task:moved", { task: createTask(), from: "done", to: "todo" });
store.emit("task:deleted", createTask({ id: "FN-3" }));
await flushAsync();
expect(mockSetIssueState).toHaveBeenCalledTimes(1);
expect(mockSetIssueState).toHaveBeenCalledTimes(2);
});
it("closes on triage -> done and logs success", async () => {
@@ -262,4 +264,64 @@ describe("GitHubTrackingStateService", () => {
expect(mockSetIssueState).toHaveBeenNthCalledWith(1, "owner", "repo", 42, "closed", "completed");
expect(mockSetIssueState).toHaveBeenNthCalledWith(2, "owner", "repo", 42, "open", "reopened");
});
describe("on task:deleted", () => {
it("closes the linked issue with not_planned and does not log to the store", async () => {
service.start();
store.emit("task:deleted", createTask());
await flushAsync();
expect(mockSetIssueState).toHaveBeenCalledWith("owner", "repo", 42, "closed", "not_planned");
expect(store.logEntry).not.toHaveBeenCalled();
});
it.each([
{
label: "tracking disabled",
task: createTask({ githubTracking: { enabled: false } }),
},
{
label: "missing issue",
task: createTask({ githubTracking: { enabled: true } }),
},
{
label: "missing owner",
task: createTask({ githubTracking: { enabled: true, issue: { owner: "", repo: "repo", number: 42 } } }),
},
{
label: "missing repo",
task: createTask({ githubTracking: { enabled: true, issue: { owner: "owner", repo: "", number: 42 } } }),
},
{
label: "missing number",
task: createTask({ githubTracking: { enabled: true, issue: { owner: "owner", repo: "repo" } } }),
},
])("does nothing when $label", async ({ task }) => {
service.start();
store.emit("task:deleted", task);
await flushAsync();
expect(mockSetIssueState).not.toHaveBeenCalled();
expect(store.logEntry).not.toHaveBeenCalled();
});
it("swallows network failures without throwing and does not log to the store", async () => {
service.start();
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
mockSetIssueState.mockRejectedValueOnce(new Error("delete close failed"));
expect(() => {
store.emit("task:deleted", createTask());
}).not.toThrow();
await flushAsync();
expect(warnSpy).toHaveBeenCalledWith(
"[github-tracking-state] Failed to close linked GitHub tracking issue for deleted task FN-1: delete close failed",
);
expect(store.logEntry).not.toHaveBeenCalled();
warnSpy.mockRestore();
});
});
});

View File

@@ -1,4 +1,4 @@
import type { GlobalSettings, ProjectSettings, TaskStore } from "@fusion/core";
import type { GlobalSettings, ProjectSettings, Task, TaskStore } from "@fusion/core";
import { GitHubClient } from "./github.js";
import { resolveGithubTrackingAuth } from "./github-auth.js";
@@ -43,6 +43,9 @@ export class GitHubTrackingStateService {
private readonly onTaskMoved = (event: TaskMovedEvent): void => {
void this.handleTaskMoved(event);
};
private readonly onTaskDeleted = (task: Task): void => {
void this.handleTaskDeleted(task);
};
private started = false;
constructor(store: TaskStore) {
@@ -53,12 +56,14 @@ export class GitHubTrackingStateService {
if (this.started) return;
this.started = true;
this.store.on("task:moved", this.onTaskMoved);
this.store.on("task:deleted", this.onTaskDeleted);
}
stop(): void {
if (!this.started) return;
this.started = false;
this.store.off("task:moved", this.onTaskMoved);
this.store.off("task:deleted", this.onTaskDeleted);
}
private async handleTaskMoved(event: TaskMovedEvent): Promise<void> {
@@ -123,4 +128,39 @@ export class GitHubTrackingStateService {
);
}
}
private async handleTaskDeleted(task: Task): Promise<void> {
if (task.githubTracking?.enabled !== true) {
return;
}
const issue = task.githubTracking.issue;
if (!issue) {
return;
}
const { owner, repo, number } = issue;
if (!owner || !repo || !number) {
return;
}
const projectSettings = await this.store.getSettings() as Pick<ProjectSettings, "githubAuthMode" | "githubAuthToken">;
const globalSettings = (await this.store.getGlobalSettingsStore?.()?.getSettings?.() ?? {}) as Pick<GlobalSettings, never>;
const resolution = resolveGithubTrackingAuth({ projectSettings, globalSettings });
if (!resolution.ok) {
return;
}
const client = resolution.auth.mode === "token"
? new GitHubClient({ token: resolution.auth.token, forceMode: "token" })
: new GitHubClient({ forceMode: "gh-cli" });
try {
await client.setIssueState(owner, repo, number, "closed", "not_planned");
} catch (err) {
console.warn(
`[github-tracking-state] Failed to close linked GitHub tracking issue for deleted task ${task.id}: ${err instanceof Error ? err.message : String(err)}`,
);
}
}
}