The earlier sweep cleaned the hot path (worker/runtime/automation/api-
server/ipc core — 59 sites). This pass finishes the deferred long tail:
main/* services, database/* CRUD modules, api-server/* routes, ipc-*
handlers, thread-integration, automation helpers, browser, skills.
Default strategy: catch (error) { logger.warn("[module] context:", ...) }
— preserve current behavior, make the failure visible instead of
silently hidden. Widened 3 logger interface signatures to include warn
where callers only passed info/error previously (thread-helpers,
host-environment-service, ipc-domain-common).
Legitimate boundaries left intact: JSON.parse on untrusted input, DNS
resolver no-records paths, explicit safe* helpers (safeJson, parseJson,
parseTriggerDetail), URL-parse predicates, and `<unserialisable>`
fallbacks inside the prompt-builder summarisers. Each kept catch now
either has a reason in context or is a documented safe* helper.
Tests adjusted only where test-constructed no-op loggers needed a warn
stub (message-dispatch, company-mode-switch, ipc-agent-graph-handlers).
With the earlier pass, AgentCompany no longer has silently-swallowing
catch blocks in main-process or renderer business code.
212 lines
8.2 KiB
TypeScript
212 lines
8.2 KiB
TypeScript
import {
|
|
IPC_CHANNELS,
|
|
deleteEntitySchema,
|
|
goalInputSchema,
|
|
projectInputSchema,
|
|
taskInputSchema,
|
|
} from "@shared/contracts";
|
|
import { fail, ok, type RegisterCoreHandlersDependencies } from "./ipc-core-common";
|
|
import { validateTaskCreation, checkCapabilityMatch } from "./task-quality-gates";
|
|
|
|
export function registerCoreTaskGraphHandlers({
|
|
registerHandle,
|
|
db,
|
|
ensureCompanyExists,
|
|
findInvalidReference,
|
|
publishDomainChanged,
|
|
emitEvent,
|
|
wakeAgentIfPossible,
|
|
handleTaskCreated,
|
|
handleTaskStatusChange,
|
|
logger,
|
|
}: Pick<
|
|
RegisterCoreHandlersDependencies,
|
|
| "registerHandle"
|
|
| "db"
|
|
| "ensureCompanyExists"
|
|
| "findInvalidReference"
|
|
| "publishDomainChanged"
|
|
| "emitEvent"
|
|
| "wakeAgentIfPossible"
|
|
| "handleTaskCreated"
|
|
| "handleTaskStatusChange"
|
|
| "logger"
|
|
>) {
|
|
registerHandle(IPC_CHANNELS.saveGoal, async (_event, payload) => {
|
|
const parsed = goalInputSchema.parse(payload);
|
|
const companyError = ensureCompanyExists(parsed.companyId);
|
|
if (companyError) return companyError;
|
|
const invalidReference = findInvalidReference(parsed.companyId, [
|
|
{ id: parsed.parentId, table: "goals", label: "parent goal" },
|
|
{ id: parsed.ownerAgentId, table: "agents", label: "owner agent" },
|
|
]);
|
|
if (invalidReference) {
|
|
return fail("INVALID_COMPANY_REFERENCE", `The selected ${invalidReference.label} does not belong to the current company.`);
|
|
}
|
|
const id = db.saveGoal(parsed);
|
|
db.addActivity({
|
|
companyId: parsed.companyId,
|
|
actor: "board",
|
|
action: parsed.id ? "goal.updated" : "goal.created",
|
|
entityType: "goal",
|
|
entityId: id,
|
|
detail: parsed.title,
|
|
});
|
|
publishDomainChanged();
|
|
if (parsed.status === "active" && parsed.ownerAgentId) {
|
|
wakeAgentIfPossible(parsed.ownerAgentId, parsed.companyId, "goal_activated");
|
|
}
|
|
return ok(id);
|
|
});
|
|
|
|
registerHandle(IPC_CHANNELS.saveProject, async (_event, payload) => {
|
|
const parsed = projectInputSchema.parse(payload);
|
|
const companyError = ensureCompanyExists(parsed.companyId);
|
|
if (companyError) return companyError;
|
|
const invalidReference = findInvalidReference(parsed.companyId, [
|
|
{ id: parsed.goalId, table: "goals", label: "goal" },
|
|
{ id: parsed.leadAgentId, table: "agents", label: "lead agent" },
|
|
]);
|
|
if (invalidReference) {
|
|
return fail("INVALID_COMPANY_REFERENCE", `The selected ${invalidReference.label} does not belong to the current company.`);
|
|
}
|
|
const id = db.saveProject(parsed);
|
|
db.addActivity({
|
|
companyId: parsed.companyId,
|
|
actor: "board",
|
|
action: parsed.id ? "project.updated" : "project.created",
|
|
entityType: "project",
|
|
entityId: id,
|
|
detail: parsed.name,
|
|
});
|
|
if (parsed.leadAgentId) {
|
|
wakeAgentIfPossible(parsed.leadAgentId, parsed.companyId, "assignment");
|
|
}
|
|
publishDomainChanged();
|
|
return ok(id);
|
|
});
|
|
|
|
registerHandle(IPC_CHANNELS.saveTask, async (_event, payload) => {
|
|
const parsed = taskInputSchema.parse(payload);
|
|
const companyError = ensureCompanyExists(parsed.companyId);
|
|
if (companyError) return companyError;
|
|
const invalidReference = findInvalidReference(parsed.companyId, [
|
|
{ id: parsed.projectId, table: "projects", label: "project" },
|
|
{ id: parsed.goalId, table: "goals", label: "goal" },
|
|
{ id: parsed.parentId, table: "tasks", label: "parent task" },
|
|
{ id: parsed.assigneeAgentId, table: "agents", label: "assignee agent" },
|
|
{ id: parsed.workspaceId, table: "workspaces", label: "workspace" },
|
|
]);
|
|
if (invalidReference) {
|
|
return fail("INVALID_COMPANY_REFERENCE", `The selected ${invalidReference.label} does not belong to the current company.`);
|
|
}
|
|
const isNew = !parsed.id;
|
|
if (isNew) {
|
|
// User-created tasks are never heartbeat tasks; the is_heartbeat flag
|
|
// is set only by acquireHeartbeatTask in the orchestrator.
|
|
const validation = validateTaskCreation(parsed, false);
|
|
if (!validation.valid) {
|
|
return fail("TASK_VALIDATION_FAILED", validation.errors.join("; "));
|
|
}
|
|
}
|
|
let previousStatus: string | null = null;
|
|
let previousAssigneeAgentId: string | null = null;
|
|
if (!isNew) {
|
|
const taskId = parsed.id;
|
|
if (!taskId) return fail("INVALID_TASK_STATE", "Task ID required for updates.");
|
|
try {
|
|
const existingTask = db.getTask(taskId);
|
|
previousStatus = existingTask.status;
|
|
previousAssigneeAgentId = existingTask.assigneeAgentId;
|
|
} catch (err) {
|
|
logger.warn(`[ipc/task-graph] getTask failed for ${taskId}; treating as new task:`, err instanceof Error ? err.message : String(err));
|
|
previousStatus = null;
|
|
previousAssigneeAgentId = null;
|
|
}
|
|
}
|
|
let id: string;
|
|
try {
|
|
id = db.saveTask(parsed);
|
|
} catch (error) {
|
|
return fail("INVALID_TASK_STATE", error instanceof Error ? error.message : "Task could not be saved.");
|
|
}
|
|
db.addActivity({
|
|
companyId: parsed.companyId,
|
|
actor: "board",
|
|
action: isNew ? "task.created" : "task.updated",
|
|
entityType: "task",
|
|
entityId: id,
|
|
detail: parsed.title,
|
|
});
|
|
if (isNew) {
|
|
handleTaskCreated(id, parsed.companyId);
|
|
} else {
|
|
if (previousStatus && previousStatus !== parsed.status) {
|
|
handleTaskStatusChange(id, parsed.companyId, previousStatus, parsed.status);
|
|
}
|
|
// User (board) manually advancing a flagged task to done: clear the review flag
|
|
if (parsed.status === "done") {
|
|
try {
|
|
db.setTaskRequiresUserReview(id, false);
|
|
} catch (error) {
|
|
logger.warn(
|
|
`[ipc-task] setTaskRequiresUserReview(false) failed for task ${id}: ${error instanceof Error ? error.message : String(error)}`,
|
|
);
|
|
}
|
|
}
|
|
// Wake new assignee when task is reassigned (matches api-server.ts behavior)
|
|
if (parsed.assigneeAgentId && parsed.assigneeAgentId !== previousAssigneeAgentId) {
|
|
wakeAgentIfPossible(parsed.assigneeAgentId, parsed.companyId, "assignment");
|
|
}
|
|
}
|
|
let capabilityWarning: string | undefined;
|
|
if (isNew && parsed.assigneeAgentId) {
|
|
try {
|
|
const match = checkCapabilityMatch(db, parsed.assigneeAgentId, parsed.description, parsed.companyId);
|
|
if (!match.matched) {
|
|
capabilityWarning = match.warning;
|
|
}
|
|
} catch (error) {
|
|
logger.warn(
|
|
`[ipc-task] capability check failed for new task ${id} (advisory, not blocking): ${error instanceof Error ? error.message : String(error)}`,
|
|
);
|
|
}
|
|
}
|
|
emitEvent({ type: "task-updated", taskId: id, action: isNew ? "created" : "updated" });
|
|
return ok({ id, capabilityWarning });
|
|
});
|
|
|
|
const deleteHandlers = [
|
|
{ channel: IPC_CHANNELS.deleteTask, table: "tasks", entity: "task", deleteFn: (id: string, companyId: string) => db.deleteTask(id, companyId) },
|
|
{ channel: IPC_CHANNELS.deleteGoal, table: "goals", entity: "goal", deleteFn: (id: string, companyId: string) => db.deleteGoal(id, companyId) },
|
|
{ channel: IPC_CHANNELS.deleteProject, table: "projects", entity: "project", deleteFn: (id: string, companyId: string) => db.deleteProject(id, companyId) },
|
|
{ channel: IPC_CHANNELS.deleteWorkspace, table: "workspaces", entity: "workspace", deleteFn: (id: string, companyId: string) => db.deleteWorkspace(id, companyId) },
|
|
] as const;
|
|
|
|
for (const { channel, table, entity, deleteFn } of deleteHandlers) {
|
|
registerHandle(channel, async (_event, payload) => {
|
|
const parsed = deleteEntitySchema.parse(payload);
|
|
const companyError = ensureCompanyExists(parsed.companyId);
|
|
if (companyError) return companyError;
|
|
if (!db.belongsToCompany(table, parsed.id, parsed.companyId)) {
|
|
return fail(`${entity.toUpperCase()}_NOT_FOUND`, `${entity.charAt(0).toUpperCase() + entity.slice(1)} not found in the current company.`);
|
|
}
|
|
deleteFn(parsed.id, parsed.companyId);
|
|
db.addActivity({
|
|
companyId: parsed.companyId,
|
|
actor: "board",
|
|
action: `${entity}.deleted`,
|
|
entityType: entity,
|
|
entityId: parsed.id,
|
|
detail: "",
|
|
});
|
|
if (entity === "task") {
|
|
emitEvent({ type: "task-updated", taskId: parsed.id, action: "deleted" });
|
|
} else {
|
|
publishDomainChanged();
|
|
}
|
|
return ok(true);
|
|
});
|
|
}
|
|
}
|