feat(FN-1096): add task agent assignment persistence and API
- Add assignedAgentId to core task types, database schema migration, and TaskStore persistence flows - Implement dashboard assignment API routes for setting and clearing task-to-agent assignments - Expand core and dashboard test coverage for persistence, migration behavior, and assignment route handling - Add a changeset for the published CLI package to document the assignment core update
This commit is contained in:
@@ -93,7 +93,7 @@ describe("Database", () => {
|
||||
});
|
||||
|
||||
it("seeds schema version", () => {
|
||||
expect(db.getSchemaVersion()).toBe(12);
|
||||
expect(db.getSchemaVersion()).toBe(13);
|
||||
});
|
||||
|
||||
it("seeds lastModified", () => {
|
||||
@@ -116,7 +116,7 @@ describe("Database", () => {
|
||||
|
||||
it("is idempotent - calling init() twice does not fail", () => {
|
||||
expect(() => db.init()).not.toThrow();
|
||||
expect(db.getSchemaVersion()).toBe(12);
|
||||
expect(db.getSchemaVersion()).toBe(13);
|
||||
});
|
||||
|
||||
it("does not overwrite existing config on re-init", () => {
|
||||
@@ -723,7 +723,7 @@ describe("schema migrations", () => {
|
||||
db.init();
|
||||
|
||||
// Verify version bumped to 5 (includes v1→v2, v2→v3, v3→v4, and v4→v5 migrations)
|
||||
expect(db.getSchemaVersion()).toBe(12);
|
||||
expect(db.getSchemaVersion()).toBe(13);
|
||||
|
||||
// Verify new columns exist and existing data is intact
|
||||
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
|
||||
@@ -748,11 +748,11 @@ describe("schema migrations", () => {
|
||||
const db = new Database(kbDir);
|
||||
db.init();
|
||||
|
||||
expect(db.getSchemaVersion()).toBe(12);
|
||||
expect(db.getSchemaVersion()).toBe(13);
|
||||
|
||||
// Re-init should not fail
|
||||
db.init();
|
||||
expect(db.getSchemaVersion()).toBe(12);
|
||||
expect(db.getSchemaVersion()).toBe(13);
|
||||
|
||||
db.close();
|
||||
});
|
||||
@@ -847,7 +847,7 @@ describe("schema migrations", () => {
|
||||
db.init();
|
||||
|
||||
// Verify version bumped to 5
|
||||
expect(db.getSchemaVersion()).toBe(12);
|
||||
expect(db.getSchemaVersion()).toBe(13);
|
||||
|
||||
// Verify new columns exist and existing data is intact
|
||||
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
|
||||
@@ -1057,7 +1057,7 @@ describe("createDatabase factory", () => {
|
||||
const db = createDatabase(kbDir);
|
||||
db.init();
|
||||
|
||||
expect(db.getSchemaVersion()).toBe(12);
|
||||
expect(db.getSchemaVersion()).toBe(13);
|
||||
expect(db.getLastModified()).toBeGreaterThan(0);
|
||||
|
||||
db.close();
|
||||
|
||||
@@ -59,7 +59,7 @@ export function fromJson<T>(json: string | null | undefined): T | undefined {
|
||||
|
||||
// ── Schema Definition ────────────────────────────────────────────────
|
||||
|
||||
const SCHEMA_VERSION = 12;
|
||||
const SCHEMA_VERSION = 13;
|
||||
|
||||
function normalizeTaskComments(
|
||||
steeringComments: SteeringComment[] | undefined,
|
||||
@@ -167,7 +167,8 @@ CREATE TABLE IF NOT EXISTS tasks (
|
||||
enabledWorkflowSteps TEXT DEFAULT '[]',
|
||||
modifiedFiles TEXT DEFAULT '[]',
|
||||
missionId TEXT,
|
||||
sliceId TEXT
|
||||
sliceId TEXT,
|
||||
assignedAgentId TEXT
|
||||
);
|
||||
|
||||
-- Config table (single row with project settings)
|
||||
@@ -451,7 +452,7 @@ export class Database {
|
||||
}
|
||||
|
||||
// Future migrations go here:
|
||||
// if (version < 13) { this.applyMigration(13, () => { ... }); }
|
||||
// if (version < 14) { this.applyMigration(14, () => { ... }); }
|
||||
|
||||
if (version < 10) {
|
||||
this.applyMigration(10, () => {
|
||||
@@ -490,6 +491,13 @@ export class Database {
|
||||
this.db.exec(`CREATE INDEX IF NOT EXISTS idxMessagesCreatedAt ON messages(createdAt)`);
|
||||
});
|
||||
}
|
||||
|
||||
if (version < 13) {
|
||||
this.applyMigration(13, () => {
|
||||
this.addColumnIfMissing("tasks", "assignedAgentId", "TEXT");
|
||||
this.db.exec(`CREATE INDEX IF NOT EXISTS idxTasksAssignedAgentId ON tasks(assignedAgentId)`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -166,6 +166,56 @@ describe("TaskStore", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("assignedAgentId persistence", () => {
|
||||
it("creates a task with assignedAgentId when provided", async () => {
|
||||
const task = await store.createTask({
|
||||
description: "Assigned task",
|
||||
assignedAgentId: "agent-123",
|
||||
});
|
||||
|
||||
expect(task.assignedAgentId).toBe("agent-123");
|
||||
|
||||
const detail = await store.getTask(task.id);
|
||||
expect(detail.assignedAgentId).toBe("agent-123");
|
||||
});
|
||||
|
||||
it("updates a task to set assignedAgentId", async () => {
|
||||
const task = await store.createTask({ description: "Unassigned task" });
|
||||
|
||||
const updated = await store.updateTask(task.id, { assignedAgentId: "agent-456" });
|
||||
expect(updated.assignedAgentId).toBe("agent-456");
|
||||
|
||||
const detail = await store.getTask(task.id);
|
||||
expect(detail.assignedAgentId).toBe("agent-456");
|
||||
});
|
||||
|
||||
it("updates a task to clear assignedAgentId with null", async () => {
|
||||
const task = await store.createTask({
|
||||
description: "Assigned then cleared",
|
||||
assignedAgentId: "agent-789",
|
||||
});
|
||||
|
||||
const cleared = await store.updateTask(task.id, { assignedAgentId: null });
|
||||
expect(cleared.assignedAgentId).toBeUndefined();
|
||||
|
||||
const detail = await store.getTask(task.id);
|
||||
expect(detail.assignedAgentId).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns assignedAgentId values from listTasks", async () => {
|
||||
const assigned = await store.createTask({
|
||||
description: "Assigned task in list",
|
||||
assignedAgentId: "agent-list",
|
||||
});
|
||||
await store.createTask({ description: "Unassigned task in list" });
|
||||
|
||||
const tasks = await store.listTasks();
|
||||
const listedAssigned = tasks.find((t) => t.id === assigned.id);
|
||||
|
||||
expect(listedAssigned?.assignedAgentId).toBe("agent-list");
|
||||
});
|
||||
});
|
||||
|
||||
// ── Lock serialization test ──────────────────────────────────────
|
||||
|
||||
describe("write lock serialization", () => {
|
||||
|
||||
@@ -228,6 +228,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
|
||||
modifiedFiles: (() => { const m = fromJson<string[]>(row.modifiedFiles); return m && m.length > 0 ? m : undefined; })(),
|
||||
missionId: row.missionId || undefined,
|
||||
sliceId: row.sliceId || undefined,
|
||||
assignedAgentId: row.assignedAgentId || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -244,10 +245,10 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
|
||||
summary, thinkingLevel, createdAt, updatedAt, columnMovedAt,
|
||||
dependencies, steps, log, attachments, steeringComments,
|
||||
comments, workflowStepResults, prInfo, issueInfo, mergeDetails,
|
||||
breakIntoSubtasks, enabledWorkflowSteps, modifiedFiles, missionId, sliceId
|
||||
breakIntoSubtasks, enabledWorkflowSteps, modifiedFiles, missionId, sliceId, assignedAgentId
|
||||
) VALUES (
|
||||
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
|
||||
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
|
||||
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
|
||||
)
|
||||
`).run(
|
||||
task.id,
|
||||
@@ -296,6 +297,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
|
||||
toJson(task.modifiedFiles || []),
|
||||
task.missionId ?? null,
|
||||
task.sliceId ?? null,
|
||||
task.assignedAgentId ?? null,
|
||||
);
|
||||
this.db.bumpLastModified();
|
||||
}
|
||||
@@ -830,6 +832,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
|
||||
breakIntoSubtasks: input.breakIntoSubtasks === true ? true : undefined,
|
||||
enabledWorkflowSteps: resolvedWorkflowSteps,
|
||||
modelPresetId: input.modelPresetId,
|
||||
assignedAgentId: input.assignedAgentId,
|
||||
modelProvider: input.modelProvider,
|
||||
modelId: input.modelId,
|
||||
validatorModelProvider: input.validatorModelProvider,
|
||||
@@ -1124,7 +1127,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
|
||||
|
||||
async updateTask(
|
||||
id: string,
|
||||
updates: { title?: string; description?: string; prompt?: string; worktree?: string | null; status?: string | null; dependencies?: string[]; blockedBy?: string | null; paused?: boolean; baseBranch?: string | null; branch?: string | null; baseCommitSha?: string | null; size?: "S" | "M" | "L"; reviewLevel?: number; mergeRetries?: number; stuckKillCount?: number | null; recoveryRetryCount?: number | null; nextRecoveryAt?: string | null; enabledWorkflowSteps?: string[]; modelProvider?: string | null; modelId?: string | null; validatorModelProvider?: string | null; validatorModelId?: string | null; planningModelProvider?: string | null; planningModelId?: string | null; thinkingLevel?: string | null; error?: string | null; summary?: string | null; sessionFile?: string | null; workflowStepResults?: import("./types.js").WorkflowStepResult[] | null; mergeDetails?: import("./types.js").MergeDetails | null; modifiedFiles?: string[] | null; missionId?: string | null; sliceId?: string | null },
|
||||
updates: { title?: string; description?: string; prompt?: string; worktree?: string | null; status?: string | null; dependencies?: string[]; blockedBy?: string | null; assignedAgentId?: string | null; paused?: boolean; baseBranch?: string | null; branch?: string | null; baseCommitSha?: string | null; size?: "S" | "M" | "L"; reviewLevel?: number; mergeRetries?: number; stuckKillCount?: number | null; recoveryRetryCount?: number | null; nextRecoveryAt?: string | null; enabledWorkflowSteps?: string[]; modelProvider?: string | null; modelId?: string | null; validatorModelProvider?: string | null; validatorModelId?: string | null; planningModelProvider?: string | null; planningModelId?: string | null; thinkingLevel?: string | null; error?: string | null; summary?: string | null; sessionFile?: string | null; workflowStepResults?: import("./types.js").WorkflowStepResult[] | null; mergeDetails?: import("./types.js").MergeDetails | null; modifiedFiles?: string[] | null; missionId?: string | null; sliceId?: string | null },
|
||||
): Promise<Task> {
|
||||
return this.withTaskLock(id, async () => {
|
||||
// Validate that task doesn't depend on itself
|
||||
@@ -1175,6 +1178,11 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
|
||||
} else if (updates.blockedBy !== undefined) {
|
||||
task.blockedBy = updates.blockedBy;
|
||||
}
|
||||
if (updates.assignedAgentId === null) {
|
||||
task.assignedAgentId = undefined;
|
||||
} else if (updates.assignedAgentId !== undefined) {
|
||||
task.assignedAgentId = updates.assignedAgentId;
|
||||
}
|
||||
if (updates.paused !== undefined) task.paused = updates.paused || undefined;
|
||||
if (updates.baseBranch === null) {
|
||||
task.baseBranch = undefined;
|
||||
|
||||
@@ -571,6 +571,8 @@ export interface Task {
|
||||
nextRecoveryAt?: string;
|
||||
/** Thinking level for AI agent sessions — controls reasoning effort (off/minimal/low/medium/high) */
|
||||
thinkingLevel?: ThinkingLevel;
|
||||
/** Explicitly assigned agent ID for task-agent linking. Distinct from Agent.taskId active execution state. */
|
||||
assignedAgentId?: string;
|
||||
/** Path to the persisted agent session file, enabling pause/resume without
|
||||
* losing conversation context. Set when execution starts; cleared on
|
||||
* completion or terminal failure. */
|
||||
@@ -632,6 +634,8 @@ export interface TaskCreateInput {
|
||||
missionId?: string;
|
||||
/** Slice ID to link this task to (for mission hierarchy) */
|
||||
sliceId?: string;
|
||||
/** Optional explicit agent assignment for this task */
|
||||
assignedAgentId?: string;
|
||||
}
|
||||
|
||||
// ── Settings Scope Types ────────────────────────────────────────────────
|
||||
|
||||
@@ -1874,6 +1874,116 @@ describe("PATCH /tasks/:id", () => {
|
||||
});
|
||||
|
||||
|
||||
describe("PATCH /tasks/:id/assign and GET /agents/:id/tasks", () => {
|
||||
let tempDir: string;
|
||||
let fusionDir: string;
|
||||
let agentId: string;
|
||||
let store: TaskStore;
|
||||
|
||||
beforeEach(async () => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "kb-routes-task-assign-"));
|
||||
fusionDir = join(tempDir, ".fusion");
|
||||
mkdirSync(fusionDir, { recursive: true });
|
||||
|
||||
const { AgentStore } = await import("@fusion/core");
|
||||
const agentStore = new AgentStore({ rootDir: fusionDir });
|
||||
await agentStore.init();
|
||||
const agent = await agentStore.createAgent({
|
||||
name: "Assignment test agent",
|
||||
role: "executor",
|
||||
});
|
||||
agentId = agent.id;
|
||||
|
||||
store = createMockStore({
|
||||
getFusionDir: vi.fn().mockReturnValue(fusionDir),
|
||||
updateTask: vi.fn(),
|
||||
listTasks: vi.fn().mockResolvedValue([]),
|
||||
} as any);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function buildApp() {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use("/api", createApiRoutes(store));
|
||||
return app;
|
||||
}
|
||||
|
||||
it("assigns a task to an existing agent", async () => {
|
||||
(store.updateTask as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
...FAKE_TASK_DETAIL,
|
||||
id: "FN-200",
|
||||
assignedAgentId: agentId,
|
||||
});
|
||||
|
||||
const res = await REQUEST(buildApp(), "PATCH", "/api/tasks/FN-200/assign", JSON.stringify({ agentId }), {
|
||||
"Content-Type": "application/json",
|
||||
});
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(store.updateTask).toHaveBeenCalledWith("FN-200", { assignedAgentId: agentId });
|
||||
expect(res.body.assignedAgentId).toBe(agentId);
|
||||
});
|
||||
|
||||
it("returns 404 when assigning to a non-existent agent", async () => {
|
||||
const res = await REQUEST(
|
||||
buildApp(),
|
||||
"PATCH",
|
||||
"/api/tasks/FN-200/assign",
|
||||
JSON.stringify({ agentId: "agent-missing" }),
|
||||
{ "Content-Type": "application/json" },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body.error).toBe("Agent not found");
|
||||
expect(store.updateTask).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("unassigns a task when agentId is null", async () => {
|
||||
(store.updateTask as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
...FAKE_TASK_DETAIL,
|
||||
id: "FN-200",
|
||||
assignedAgentId: undefined,
|
||||
});
|
||||
|
||||
const res = await REQUEST(
|
||||
buildApp(),
|
||||
"PATCH",
|
||||
"/api/tasks/FN-200/assign",
|
||||
JSON.stringify({ agentId: null }),
|
||||
{ "Content-Type": "application/json" },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(store.updateTask).toHaveBeenCalledWith("FN-200", { assignedAgentId: null });
|
||||
expect(res.body.assignedAgentId).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns tasks assigned to the specified agent", async () => {
|
||||
(store.listTasks as ReturnType<typeof vi.fn>).mockResolvedValue([
|
||||
{ ...FAKE_TASK_DETAIL, id: "FN-001", assignedAgentId: agentId },
|
||||
{ ...FAKE_TASK_DETAIL, id: "FN-002", assignedAgentId: "agent-other" },
|
||||
{ ...FAKE_TASK_DETAIL, id: "FN-003" },
|
||||
]);
|
||||
|
||||
const res = await GET(buildApp(), `/api/agents/${agentId}/tasks`);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.map((task: { id: string }) => task.id)).toEqual(["FN-001"]);
|
||||
});
|
||||
|
||||
it("returns 404 for /api/agents/:id/tasks when agent does not exist", async () => {
|
||||
const res = await GET(buildApp(), "/api/agents/agent-missing/tasks");
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body.error).toBe("Agent not found");
|
||||
expect(store.listTasks).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Attachment routes", () => {
|
||||
const FAKE_ATTACHMENT: TaskAttachment = {
|
||||
filename: "1234-screenshot.png",
|
||||
|
||||
@@ -2626,6 +2626,45 @@ export function createApiRoutes(store: TaskStore, options?: ServerOptions): Rout
|
||||
}
|
||||
});
|
||||
|
||||
// Assign or unassign a task to an explicit agent
|
||||
router.patch("/tasks/:id/assign", async (req, res) => {
|
||||
try {
|
||||
const { agentId } = req.body as { agentId?: string | null };
|
||||
if (agentId !== null && typeof agentId !== "string") {
|
||||
res.status(400).json({ error: "agentId must be a string or null" });
|
||||
return;
|
||||
}
|
||||
if (typeof agentId === "string" && agentId.trim().length === 0) {
|
||||
res.status(400).json({ error: "agentId must be a non-empty string or null" });
|
||||
return;
|
||||
}
|
||||
|
||||
const scopedStore = await getScopedStore(req);
|
||||
const { AgentStore } = await import("@fusion/core");
|
||||
const agentStore = new AgentStore({ rootDir: scopedStore.getFusionDir() });
|
||||
await agentStore.init();
|
||||
|
||||
if (typeof agentId === "string") {
|
||||
const agent = await agentStore.getAgent(agentId);
|
||||
if (!agent) {
|
||||
res.status(404).json({ error: "Agent not found" });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const task = await scopedStore.updateTask(req.params.id, {
|
||||
assignedAgentId: agentId === null ? null : agentId,
|
||||
});
|
||||
res.json(task);
|
||||
} catch (err: any) {
|
||||
if (err?.code === "ENOENT" || err?.message?.includes("not found")) {
|
||||
res.status(404).json({ error: err.message ?? "Task not found" });
|
||||
} else {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Delete task
|
||||
router.delete("/tasks/:id", async (req, res) => {
|
||||
try {
|
||||
@@ -7168,6 +7207,30 @@ Output ONLY the prompt text (no markdown, no explanations).`;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/agents/:id/tasks
|
||||
* List tasks explicitly assigned to the given agent.
|
||||
*/
|
||||
router.get("/agents/:id/tasks", async (req, res) => {
|
||||
try {
|
||||
const scopedStore = await getScopedStore(req);
|
||||
const { AgentStore } = await import("@fusion/core");
|
||||
const agentStore = new AgentStore({ rootDir: scopedStore.getFusionDir() });
|
||||
await agentStore.init();
|
||||
|
||||
const agent = await agentStore.getAgent(req.params.id);
|
||||
if (!agent) {
|
||||
res.status(404).json({ error: "Agent not found" });
|
||||
return;
|
||||
}
|
||||
|
||||
const tasks = await scopedStore.listTasks();
|
||||
res.json(tasks.filter((task) => task.assignedAgentId === req.params.id));
|
||||
} catch (err: any) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/agents/:id/heartbeat
|
||||
* Record a heartbeat for an agent.
|
||||
|
||||
Reference in New Issue
Block a user