fix(FN-2107): normalize task ID handling for task creation tools

- Return the created task ID directly from runTaskPlan and propagate it through fn_task_plan
- Remove hardcoded FN-### log parsing so CLI extension supports structured IDs like PROJ-042
- Add heartbeat fallback parsing from task_create text output when details.taskId is absent
- Expand engine and CLI tests to cover structured task IDs and updated task-plan return behavior
This commit is contained in:
Fusion
2026-04-19 03:21:26 -07:00
committed by gsxdsm
parent a901975ed8
commit 2f611ce489
7 changed files with 106 additions and 33 deletions

View File

@@ -10,9 +10,14 @@ vi.mock("@fusion/core/gh-cli", () => ({
getGhErrorMessage: vi.fn((error: unknown) => (error instanceof Error ? error.message : String(error))),
}));
vi.mock("../commands/task.js", () => ({
runTaskPlan: vi.fn(),
}));
import kbExtension from "../extension.js";
import { TaskStore } from "@fusion/core";
import { isGhAvailable, isGhAuthenticated, runGhJsonAsync } from "@fusion/core/gh-cli";
import { runTaskPlan } from "../commands/task.js";
// ── Mock ExtensionAPI that captures registrations ──────────────────
@@ -73,6 +78,7 @@ describe("fn pi extension", () => {
vi.mocked(isGhAvailable).mockReturnValue(true);
vi.mocked(isGhAuthenticated).mockReturnValue(true);
vi.mocked(runGhJsonAsync).mockReset();
vi.mocked(runTaskPlan).mockReset();
tmpDir = await mkdtemp(join(tmpdir(), "kb-ext-test-"));
api = createMockAPI();
@@ -144,6 +150,25 @@ describe("fn pi extension", () => {
});
});
describe("fn_task_plan", () => {
it("uses runTaskPlan return value for taskId regardless of prefix", async () => {
vi.mocked(runTaskPlan).mockResolvedValueOnce("PROJ-042");
const tool = api.tools.get("fn_task_plan")!;
const result = await tool.execute(
"plan-1",
{ description: "Plan a project task" },
undefined,
undefined,
makeCtx(tmpDir),
);
expect(runTaskPlan).toHaveBeenCalledWith("Plan a project task", true);
expect(result.details.taskId).toBe("PROJ-042");
expect(result.content[0].text).toContain("Task PROJ-042");
});
});
describe("fn_task_create", () => {
it("creates a task and returns its ID", async () => {
const tool = api.tools.get("fn_task_create")!;

View File

@@ -405,24 +405,15 @@ describe("runTaskPlan", () => {
mockQuestion.mockResolvedValueOnce("y");
const exitSpy = vi.spyOn(process, "exit").mockImplementation(() => {
throw new Error("Process.exit called");
});
try {
await runTaskPlan("Build something", true);
} catch {
// expected
}
const taskId = await runTaskPlan("Build something", true);
expect(taskId).toBe("FN-042");
expect(mockCreateTask).toHaveBeenCalledWith({
title: "Planned Task",
description: "A well-planned task",
column: "triage",
dependencies: ["FN-001"],
});
exitSpy.mockRestore();
});
it("prompts for confirmation without --yes flag", async () => {
@@ -575,22 +566,13 @@ describe("runTaskPlan", () => {
.mockResolvedValueOnce("y")
.mockResolvedValueOnce("n");
const exitSpy = vi.spyOn(process, "exit").mockImplementation(() => {
throw new Error("Process.exit called");
});
try {
await runTaskPlan("Build something", false);
} catch {
// expected
}
const taskId = await runTaskPlan("Build something", false);
expect(taskId).toBeUndefined();
expect(mockCreateTask).not.toHaveBeenCalled();
expect(mockConsoleLog).toHaveBeenCalledWith(
expect.stringContaining("Task creation cancelled")
);
exitSpy.mockRestore();
});
it("validates single_select input and retries on invalid", async () => {

View File

@@ -1392,7 +1392,7 @@ function wrapText(text: string, width: number): string[] {
}
/** Run the planning mode */
export async function runTaskPlan(initialPlanArg?: string, yesFlag = false, projectName?: string): Promise<void> {
export async function runTaskPlan(initialPlanArg?: string, yesFlag = false, projectName?: string): Promise<string | undefined> {
let initialPlan = initialPlanArg;
// If no initial plan, prompt interactively
@@ -1481,7 +1481,7 @@ export async function runTaskPlan(initialPlanArg?: string, yesFlag = false, proj
} catch (promptErr) {
// Prompt was cancelled (Ctrl+C handled above)
if (cancelled) {
return;
return undefined;
}
throw promptErr;
}
@@ -1540,11 +1540,12 @@ export async function runTaskPlan(initialPlanArg?: string, yesFlag = false, proj
}
console.log(` Path: .fusion/tasks/${task.id}/`);
console.log();
} else {
console.log("\n Task creation cancelled.\n");
return task.id;
}
break;
console.log("\n Task creation cancelled.\n");
return undefined;
}
// Next question

View File

@@ -1038,8 +1038,9 @@ export default function kbExtension(pi: ExtensionAPI) {
originalError.apply(console, args);
};
let taskId: string | undefined;
try {
await runTaskPlan(params.description, true); // Use --yes flag for non-interactive
taskId = await runTaskPlan(params.description, true); // Use --yes flag for non-interactive
} catch (err: any) {
console.error = originalError;
console.log = originalLog;
@@ -1049,10 +1050,6 @@ export default function kbExtension(pi: ExtensionAPI) {
console.log = originalLog;
}
// Parse created task ID from logs
const createdMatch = logs.find((l) => l.match(/Created (FN-\d+):/));
const taskId = createdMatch ? createdMatch.match(/Created (FN-\d+):/)?.[1] : undefined;
// Get summary line
const summaryLine = logs.find((l) => l.includes("✓ Created")) || "Task created";

View File

@@ -9,6 +9,7 @@ import {
HEARTBEAT_SYSTEM_PROMPT_NO_TASK,
} from "./agent-heartbeat.js";
import { AgentLogger } from "./agent-logger.js";
import * as agentTools from "./agent-tools.js";
import type { AgentStore, AgentHeartbeatRun, TaskStore, TaskDetail, Agent, MessageStore, Message, AgentBudgetStatus } from "@fusion/core";
// Mock logger to suppress noise in test output
@@ -3290,6 +3291,35 @@ describe("HeartbeatMonitor", () => {
);
});
it("task_create tracking falls back to parsing text when details.taskId is missing", async () => {
const store = createMockStore();
const createTaskCreateToolSpy = vi.spyOn(agentTools, "createTaskCreateTool").mockReturnValue({
name: "task_create",
label: "Create Task",
description: "Create a task",
parameters: {} as any,
execute: vi.fn().mockResolvedValue({
content: [{ type: "text", text: "Created PROJ-777: Follow-up task" }],
details: {},
}),
} as any);
const monitor = new HeartbeatMonitor({ store, taskStore: mockTaskStore, rootDir: "/tmp" });
try {
const tools = monitor.createHeartbeatTools("agent-001", mockTaskStore, "FN-001");
await tools[0]!.execute("call-1", { description: "Follow-up task" }, undefined as any, undefined as any, undefined as any);
expect(mockTaskStore.logEntry).toHaveBeenCalledWith(
"PROJ-777",
"Created by agent agent-001 during heartbeat run",
undefined,
undefined,
);
} finally {
createTaskCreateToolSpy.mockRestore();
}
});
it("task_create tracking handles missing details gracefully", async () => {
const store = createMockStore();
const missingDetailsTaskStore = createMockTaskStoreForTools({

View File

@@ -1432,7 +1432,9 @@ export class HeartbeatMonitor {
execute: async (id: string, params: Static<typeof taskCreateParams>, signal, onUpdate, ctx) => {
const result = await baseCreateTool.execute(id, params, signal, onUpdate, ctx);
const createdTaskId = (result.details as { taskId?: string })?.taskId ?? "unknown";
const textResponse = result.content.find((item) => item.type === "text")?.text;
const taskIdMatch = textResponse?.match(/(?:Created|created) (\w+-\d+):/);
const createdTaskId = (result.details as { taskId?: string } | undefined)?.taskId ?? taskIdMatch?.[1] ?? "unknown";
// Log agent link on the created task with run context for correlation
try {

View File

@@ -6,6 +6,7 @@ import {
buildQmdAgentMemoryCollectionAddArgs,
buildQmdAgentMemorySearchArgs,
createMemoryTools,
createTaskCreateTool,
createSendMessageTool,
createReadMessagesTool,
qmdAgentMemoryCollectionName,
@@ -54,6 +55,41 @@ vi.mock("node:child_process", async () => {
};
});
describe("createTaskCreateTool", () => {
it("returns details.taskId and keeps Created <id> response text", async () => {
const store = {
createTask: vi.fn().mockResolvedValue({
id: "PROJ-042",
description: "Follow-up task",
dependencies: ["PROJ-001"],
column: "triage",
}),
};
const tool = createTaskCreateTool(store as any);
const result = await tool.execute(
"call-1",
{
description: "Follow-up task",
dependencies: ["PROJ-001"],
} as any,
undefined,
undefined,
{} as any,
);
expect(store.createTask).toHaveBeenCalledWith({
description: "Follow-up task",
dependencies: ["PROJ-001"],
column: "triage",
});
expect(result.details).toEqual({ taskId: "PROJ-042" });
const responseText = result.content[0]?.type === "text" ? result.content[0].text : "";
expect(responseText).toContain("Created PROJ-042: Follow-up task");
expect(responseText).toContain("(depends on: PROJ-001)");
});
});
describe("createMemoryTools", () => {
let tempDir: string;