吸收数字员工计划步骤依赖图

This commit is contained in:
baiyanyun
2026-06-09 10:21:12 +08:00
parent e4715bbabb
commit f35d945d9c
10 changed files with 641 additions and 74 deletions

View File

@@ -42,6 +42,24 @@ const DIGITAL_EMPLOYEE_SCHEMA_SQL = `
FOREIGN KEY(plan_id) REFERENCES digital_plans(id)
);
CREATE TABLE IF NOT EXISTS digital_plan_steps (
id TEXT PRIMARY KEY,
remote_id TEXT,
plan_id TEXT NOT NULL,
title TEXT NOT NULL,
status TEXT NOT NULL,
seq INTEGER NOT NULL,
depends_on TEXT NOT NULL DEFAULT '[]',
preferred_skill_ids TEXT NOT NULL DEFAULT '[]',
payload TEXT NOT NULL DEFAULT '{}',
sync_status TEXT NOT NULL DEFAULT 'pending',
last_synced_at TEXT,
sync_error TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(plan_id) REFERENCES digital_plans(id)
);
CREATE TABLE IF NOT EXISTS digital_runs (
id TEXT PRIMARY KEY,
remote_id TEXT,
@@ -140,6 +158,8 @@ const DIGITAL_EMPLOYEE_SCHEMA_SQL = `
);
CREATE INDEX IF NOT EXISTS idx_digital_plans_sync ON digital_plans(sync_status);
CREATE INDEX IF NOT EXISTS idx_digital_plan_steps_plan ON digital_plan_steps(plan_id, seq);
CREATE INDEX IF NOT EXISTS idx_digital_plan_steps_sync ON digital_plan_steps(sync_status);
CREATE INDEX IF NOT EXISTS idx_digital_tasks_plan ON digital_tasks(plan_id);
CREATE INDEX IF NOT EXISTS idx_digital_runs_task ON digital_runs(task_id);
CREATE INDEX IF NOT EXISTS idx_digital_events_plan ON digital_events(plan_id, occurred_at);

View File

@@ -255,6 +255,16 @@ describe("digital employee state service", () => {
status: "pending",
assigned_skill_id: "qimingclaw-mcp-tool-crm-crm-search",
});
expect(mockState.db?.planSteps.get("collect-crm")).toMatchObject({
plan_id: "plan-customer-followup",
title: "整理客户列表",
status: "pending",
seq: 1,
preferred_skill_ids: JSON.stringify(["qimingclaw-mcp-tool-crm-crm-search"]),
});
expect(JSON.parse(mockState.db?.tasks.get("task-collect-crm")?.payload ?? "{}")).toMatchObject({
stepId: "collect-crm",
});
expect(mockState.db?.runs.get("governance-run-command-1")).toMatchObject({
plan_id: "plan-customer-followup",
task_id: "governance-task-command-1",
@@ -270,9 +280,54 @@ describe("digital employee state service", () => {
entity_id: "plan-customer-followup",
status: "pending",
});
expect(mockState.db?.outbox.get("plan_step:upsert:collect-crm")).toMatchObject({
entity_type: "plan_step",
entity_id: "collect-crm",
status: "pending",
});
expect(mockState.ensureSchemaCalls).toBeGreaterThan(0);
});
it("creates a default plan step for top-level plan tasks", async () => {
const {
readDigitalEmployeeRuntimeRecords,
recordDigitalEmployeeGovernanceCommand,
} = await import("./stateService");
recordDigitalEmployeeGovernanceCommand({
commandKind: "create_plan",
commandId: "command-default-step",
accepted: true,
payload: {
title: "客户回访计划",
tasks: [{ task_id: "task-call", title: "拨打客户电话" }],
},
result: { plan_id: "plan-default-step", status: "draft" },
});
expect(mockState.db?.planSteps.get("plan-default-step:step:default")).toMatchObject({
plan_id: "plan-default-step",
title: "默认执行步骤",
seq: 1,
});
expect(JSON.parse(mockState.db?.tasks.get("task-call")?.payload ?? "{}")).toMatchObject({
stepId: "plan-default-step:step:default",
});
expect(mockState.db?.outbox.get("plan_step:upsert:plan-default-step:step:default")).toMatchObject({
entity_type: "plan_step",
entity_id: "plan-default-step:step:default",
});
expect(readDigitalEmployeeRuntimeRecords()).toMatchObject({
planSteps: [
expect.objectContaining({
id: "plan-default-step:step:default",
planId: "plan-default-step",
title: "默认执行步骤",
}),
],
});
});
it("preserves created plan title across follow-up governance commands", async () => {
const { recordDigitalEmployeeGovernanceCommand } = await import("./stateService");
@@ -324,6 +379,20 @@ interface TestTaskRow {
updated_at: string;
}
interface TestPlanStepRow {
id: string;
plan_id: string;
title: string;
status: string;
seq: number;
depends_on: string;
preferred_skill_ids: string;
payload: string;
sync_status: string;
created_at: string;
updated_at: string;
}
interface TestRunRow {
id: string;
plan_id: string;
@@ -391,6 +460,7 @@ interface TestOutboxRow {
class TestDb {
plans = new Map<string, TestPlanRow>();
planSteps = new Map<string, TestPlanStepRow>();
tasks = new Map<string, TestTaskRow>();
runs = new Map<string, TestRunRow>();
events = new Map<string, TestEventRow>();
@@ -409,12 +479,23 @@ class TestDb {
} {
const normalized = sql.replace(/\s+/g, " ").trim();
return {
all: () => [],
all: (...args: unknown[]) => this.all(normalized, args),
get: (...args: unknown[]) => this.get(normalized, args),
run: (...args: unknown[]) => this.run(normalized, args),
};
}
private all(sql: string, _args: unknown[]): unknown[] {
if (sql.includes("FROM digital_plans")) return Array.from(this.plans.values());
if (sql.includes("FROM digital_plan_steps")) return Array.from(this.planSteps.values());
if (sql.includes("FROM digital_tasks")) return Array.from(this.tasks.values());
if (sql.includes("FROM digital_runs")) return Array.from(this.runs.values());
if (sql.includes("FROM digital_events")) return Array.from(this.events.values());
if (sql.includes("FROM digital_artifacts")) return Array.from(this.artifacts.values());
if (sql.includes("FROM digital_approvals")) return Array.from(this.approvals.values());
return [];
}
private get(sql: string, args: unknown[]): unknown {
if (sql.startsWith("SELECT title, objective FROM digital_plans")) {
return this.plans.get(args[0] as string);
@@ -450,6 +531,36 @@ class TestDb {
return { changes: 1 };
}
if (sql.startsWith("INSERT INTO digital_plan_steps")) {
const [
id,
planId,
title,
status,
seq,
dependsOn,
preferredSkillIds,
payload,
createdAt,
updatedAt,
] = args as [string, string, string, string, number, string, string, string, string, string];
const previous = this.planSteps.get(id);
this.planSteps.set(id, {
id,
plan_id: planId,
title,
status,
seq,
depends_on: dependsOn,
preferred_skill_ids: preferredSkillIds,
payload,
sync_status: previous?.sync_status === "synced" ? "pending" : previous?.sync_status ?? "pending",
created_at: previous?.created_at ?? createdAt,
updated_at: updatedAt,
});
return { changes: 1 };
}
if (sql.startsWith("INSERT INTO digital_tasks")) {
const [id, planId, title, status, assignedSkillId, payload, createdAt, updatedAt] = args as [
string,

View File

@@ -88,6 +88,23 @@ export interface DigitalEmployeeTaskRecord {
updatedAt: string;
}
export interface DigitalEmployeePlanStepRecord {
id: string;
remoteId?: string | null;
planId: string;
title: string;
status: string;
seq: number;
dependsOn: string[];
preferredSkillIds: string[];
payload: unknown;
syncStatus: string;
lastSyncedAt?: string | null;
syncError?: string | null;
createdAt: string;
updatedAt: string;
}
export interface DigitalEmployeeRunRecord {
id: string;
remoteId?: string | null;
@@ -155,6 +172,7 @@ export interface DigitalEmployeeApprovalRecord {
export interface DigitalEmployeeRuntimeRecords {
generatedAt: string;
plans: DigitalEmployeePlanRecord[];
planSteps: DigitalEmployeePlanStepRecord[];
tasks: DigitalEmployeeTaskRecord[];
runs: DigitalEmployeeRunRecord[];
events: DigitalEmployeeEventRecord[];
@@ -479,6 +497,7 @@ export function readDigitalEmployeeRuntimeRecords(
return {
generatedAt: new Date().toISOString(),
plans: [],
planSteps: [],
tasks: [],
runs: [],
events: [],
@@ -494,6 +513,14 @@ export function readDigitalEmployeeRuntimeRecords(
ORDER BY updated_at DESC, created_at DESC
LIMIT ?
`).all(safeLimit) as Array<Record<string, unknown>>;
const planSteps = db.prepare(`
SELECT id, remote_id, plan_id, title, status, seq, depends_on,
preferred_skill_ids, payload, sync_status, last_synced_at,
sync_error, created_at, updated_at
FROM digital_plan_steps
ORDER BY plan_id ASC, seq ASC, created_at ASC
LIMIT ?
`).all(safeLimit) as Array<Record<string, unknown>>;
const tasks = db.prepare(`
SELECT id, remote_id, plan_id, title, status, assigned_skill_id, payload,
sync_status, last_synced_at, sync_error, created_at, updated_at
@@ -533,6 +560,7 @@ export function readDigitalEmployeeRuntimeRecords(
return {
generatedAt: new Date().toISOString(),
plans: plans.map(toPlanRecord),
planSteps: planSteps.map(toPlanStepRecord),
tasks: tasks.map(toTaskRecord),
runs: runs.map(toRunRecord),
events: events.map(toEventRecord),
@@ -802,6 +830,13 @@ export function recordDigitalEmployeeGovernanceCommand(
now,
});
if (command.commandKind === "create_plan") {
upsertCreatedPlanSteps({
planId: ids.planId,
payload,
status: "pending",
commandId,
now,
});
upsertCreatedPlanTasks({
planId: ids.planId,
payload,
@@ -878,6 +913,34 @@ function readExistingPlanSummary(planId: string): { title: string; objective: st
}
}
function upsertCreatedPlanSteps(input: {
planId: string;
payload: Record<string, unknown>;
status: string;
commandId: string;
now: string;
}): void {
extractPlanStepInputs(input.payload, input.planId).forEach((step) => {
upsertPlanStep({
id: step.id,
planId: input.planId,
title: step.title,
status: step.status || input.status,
seq: step.seq,
dependsOn: step.dependsOn,
preferredSkillIds: step.preferredSkillIds,
payload: {
source: "qimingclaw-create-plan",
commandId: input.commandId,
dependsOn: step.dependsOn,
preferredSkillIds: step.preferredSkillIds,
original: step.original,
},
now: input.now,
});
});
}
function upsertCreatedPlanTasks(input: {
planId: string;
payload: Record<string, unknown>;
@@ -885,7 +948,7 @@ function upsertCreatedPlanTasks(input: {
commandId: string;
now: string;
}): void {
extractPlanTaskInputs(input.payload).forEach((task, index) => {
extractPlanTaskInputs(input.payload, input.planId).forEach((task, index) => {
const title = task.title || `计划任务 ${index + 1}`;
const taskId = task.id || `${input.planId}:task:${safeId(`${index + 1}-${title}`)}`;
upsertTask({
@@ -908,7 +971,60 @@ function upsertCreatedPlanTasks(input: {
});
}
function extractPlanTaskInputs(payload: Record<string, unknown>): Array<{
function extractPlanStepInputs(
payload: Record<string, unknown>,
planId: string,
): Array<{
id: string;
title: string;
status: string;
seq: number;
dependsOn: string[];
preferredSkillIds: string[];
original: unknown;
}> {
const steps = unknownArray(payload.steps)
.map((step, index) => planStepInputFromRecord(objectRecord(step), index, planId))
.filter((step): step is NonNullable<typeof step> => Boolean(step));
if (steps.length > 0) return steps;
if (unknownArray(payload.tasks).length === 0) return [];
return [{
id: `${planId}:step:default`,
title: "默认执行步骤",
status: "pending",
seq: 1,
dependsOn: [],
preferredSkillIds: [],
original: { source: "default_step", task_count: unknownArray(payload.tasks).length },
}];
}
function planStepInputFromRecord(
record: Record<string, unknown> | null,
index: number,
planId: string,
): ReturnType<typeof extractPlanStepInputs>[number] | null {
if (!record) return null;
const title = stringValue(record.title ?? record.name ?? record.summary)
|| `计划步骤 ${index + 1}`;
const stepId = stringValue(record.step_id ?? record.stepId ?? record.id)
|| `${planId}:step:${index + 1}-${safeId(title)}`;
return {
id: stepId,
title,
status: stringValue(record.status) || "pending",
seq: typeof record.seq === "number" ? record.seq : Number(record.seq) || index + 1,
dependsOn: normalizeSkillIds(unknownArray(record.depends_on ?? record.dependsOn)),
preferredSkillIds: normalizeSkillIds([
...unknownArray(record.skills),
...unknownArray(record.preferred_skills),
...unknownArray(record.preferredSkills),
]),
original: record,
};
}
function extractPlanTaskInputs(payload: Record<string, unknown>, planId: string): Array<{
id: string;
stepId: string;
title: string;
@@ -918,9 +1034,11 @@ function extractPlanTaskInputs(payload: Record<string, unknown>): Array<{
skills: string[];
original: unknown;
}> {
const rawSteps = unknownArray(payload.steps);
const defaultStepId = rawSteps.length > 0 ? "" : `${planId}:step:default`;
const explicitTasks = unknownArray(payload.tasks)
.map((task, index) => planTaskInputFromRecord(objectRecord(task), index, ""));
const stepTasks = unknownArray(payload.steps).flatMap((step, stepIndex) => {
.map((task, index) => planTaskInputFromRecord(objectRecord(task), index, defaultStepId));
const stepTasks = rawSteps.flatMap((step, stepIndex) => {
const stepRecord = objectRecord(step);
if (!stepRecord) return [];
const nestedTasks = unknownArray(stepRecord.tasks);
@@ -1091,6 +1209,12 @@ function parseStoredPayload(value: unknown): unknown {
}
}
function parseStringArray(value: unknown): string[] {
const parsed = parseStoredPayload(value);
if (!Array.isArray(parsed)) return [];
return parsed.filter((item): item is string => typeof item === "string" && item.trim().length > 0);
}
function toPlanRecord(row: Record<string, unknown>): DigitalEmployeePlanRecord {
return {
id: stringField(row, "id"),
@@ -1125,6 +1249,25 @@ function toTaskRecord(row: Record<string, unknown>): DigitalEmployeeTaskRecord {
};
}
function toPlanStepRecord(row: Record<string, unknown>): DigitalEmployeePlanStepRecord {
return {
id: stringField(row, "id"),
remoteId: optionalStringField(row, "remote_id"),
planId: stringField(row, "plan_id"),
title: stringField(row, "title"),
status: stringField(row, "status"),
seq: typeof row.seq === "number" ? row.seq : Number(row.seq) || 0,
dependsOn: parseStringArray(row.depends_on),
preferredSkillIds: parseStringArray(row.preferred_skill_ids),
payload: parseStoredPayload(row.payload),
syncStatus: stringField(row, "sync_status"),
lastSyncedAt: optionalStringField(row, "last_synced_at"),
syncError: optionalStringField(row, "sync_error"),
createdAt: stringField(row, "created_at"),
updatedAt: stringField(row, "updated_at"),
};
}
function toRunRecord(row: Record<string, unknown>): DigitalEmployeeRunRecord {
return {
id: stringField(row, "id"),
@@ -1279,6 +1422,52 @@ function upsertPlan(input: {
markOutbox("plan", input.id, "upsert", input, input.now);
}
function upsertPlanStep(input: {
id: string;
planId: string;
title: string;
status: string;
seq: number;
dependsOn: string[];
preferredSkillIds: string[];
payload: unknown;
now: string;
}): void {
const db = getDigitalEmployeeDb();
if (!db) return;
db.prepare(`
INSERT INTO digital_plan_steps (
id, plan_id, title, status, seq, depends_on, preferred_skill_ids,
payload, sync_status, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)
ON CONFLICT(id) DO UPDATE SET
plan_id = excluded.plan_id,
title = excluded.title,
status = excluded.status,
seq = excluded.seq,
depends_on = excluded.depends_on,
preferred_skill_ids = excluded.preferred_skill_ids,
payload = excluded.payload,
sync_status = CASE
WHEN digital_plan_steps.sync_status = 'synced' THEN 'pending'
ELSE digital_plan_steps.sync_status
END,
updated_at = excluded.updated_at
`).run(
input.id,
input.planId,
input.title,
input.status,
input.seq,
stringify(input.dependsOn),
stringify(input.preferredSkillIds),
stringify(input.payload),
input.now,
input.now,
);
markOutbox("plan_step", input.id, "upsert", input, input.now);
}
function upsertTask(input: {
id: string;
planId: string;

View File

@@ -320,6 +320,80 @@ describe("digital employee sync service", () => {
sync_error: null,
});
});
it("syncs plan step business views and acknowledgements", async () => {
insertEntity("plan_step", "step-1");
insertOutbox(
"plan_step:upsert:step-1",
"plan_step",
"step-1",
JSON.stringify({
planId: "plan-1",
title: "整理客户列表",
status: "pending",
seq: 2,
dependsOn: ["step-0"],
preferredSkillIds: ["qimingclaw-mcp-tool-crm-crm-search"],
}),
);
mockState.fetch.mockResolvedValue(
jsonResponse({
success: true,
acked: [
{
entity_type: "plan_step",
entity_id: "step-1",
remote_id: "remote-step-1",
},
],
}),
);
const { flushDigitalEmployeeSyncOutbox } = await import("./syncService");
const status = await flushDigitalEmployeeSyncOutbox({ force: true });
expect(lastSyncRequestBody()).toMatchObject({
items: [
expect.objectContaining({
entity_type: "plan_step",
business_view: expect.objectContaining({
entity_type: "plan_step",
local_id: "step-1",
plan_id: "plan-1",
step_id: "step-1",
title: "整理客户列表",
status: "pending",
seq: 2,
depends_on: ["step-0"],
preferred_skill_ids: ["qimingclaw-mcp-tool-crm-crm-search"],
}),
}),
],
});
expect(status.failed).toBe(0);
expect(readEntity("plan_step", "step-1")).toMatchObject({
sync_status: "synced",
remote_id: "remote-step-1",
sync_error: null,
});
});
it("marks plan step business failures as failed", async () => {
insertEntity("plan_step", "step-rejected");
insertOutbox("plan_step:upsert:step-rejected", "plan_step", "step-rejected");
mockState.fetch.mockResolvedValue(
jsonResponse({ code: "0001", message: "步骤同步被拒绝", data: null }),
);
const { flushDigitalEmployeeSyncOutbox } = await import("./syncService");
const status = await flushDigitalEmployeeSyncOutbox({ force: true });
expect(status.failed).toBe(1);
expect(readEntity("plan_step", "step-rejected")).toMatchObject({
sync_status: "failed",
sync_error: "步骤同步被拒绝",
});
});
});
function insertPlan(id: string): void {
@@ -340,13 +414,18 @@ function insertEntity(entityType: string, id: string): void {
});
}
function insertOutbox(id: string, entityType: string, entityId: string): void {
function insertOutbox(
id: string,
entityType: string,
entityId: string,
payload = '{"ok":true}',
): void {
mockState.db?.outbox.set(id, {
id,
entity_type: entityType,
entity_id: entityId,
operation: "upsert",
payload: '{"ok":true}',
payload,
status: "pending",
attempts: 0,
last_attempt_at: null,
@@ -376,6 +455,7 @@ function entityMap(
): Map<string, TestSyncEntityRow> | undefined {
if (!mockState.db) return undefined;
if (entityType === "plan") return mockState.db.plans;
if (entityType === "plan_step") return mockState.db.planSteps;
if (entityType === "artifact") return mockState.db.artifacts;
if (entityType === "approval") return mockState.db.approvals;
return undefined;
@@ -441,6 +521,7 @@ interface TestAttemptRow {
class TestDb {
outbox = new Map<string, TestOutboxRow>();
plans = new Map<string, TestSyncEntityRow>();
planSteps = new Map<string, TestSyncEntityRow>();
artifacts = new Map<string, TestSyncEntityRow>();
approvals = new Map<string, TestSyncEntityRow>();
attempts: TestAttemptRow[] = [];
@@ -543,6 +624,11 @@ class TestDb {
return this.approvals.get(id);
}
if (sql.startsWith("SELECT title, status, NULL AS objective, payload FROM digital_plan_steps")) {
const [id] = args as [string];
return this.planSteps.get(id);
}
if (
sql.includes("COUNT(*) AS count FROM digital_sync_outbox WHERE status = ?")
) {
@@ -640,7 +726,7 @@ class TestDb {
return { changes: before - this.attempts.length };
}
if (/^UPDATE digital_(plans|artifacts|approvals) SET sync_status = 'synced'/.test(sql)) {
if (/^UPDATE digital_(plans|plan_steps|artifacts|approvals) SET sync_status = 'synced'/.test(sql)) {
const [remoteId, lastSyncedAt, id] = args as [string | null, string, string];
const row = this.entityRowsForUpdate(sql).get(id);
if (row) {
@@ -652,7 +738,7 @@ class TestDb {
return { changes: row ? 1 : 0 };
}
if (/^UPDATE digital_(plans|artifacts|approvals) SET sync_status = 'failed'/.test(sql)) {
if (/^UPDATE digital_(plans|plan_steps|artifacts|approvals) SET sync_status = 'failed'/.test(sql)) {
const [syncError, id] = args as [string, string];
const row = this.entityRowsForUpdate(sql).get(id);
if (row) {
@@ -668,6 +754,7 @@ class TestDb {
private entityRowsForUpdate(sql: string): Map<string, TestSyncEntityRow> {
if (sql.startsWith("UPDATE digital_artifacts")) return this.artifacts;
if (sql.startsWith("UPDATE digital_approvals")) return this.approvals;
if (sql.startsWith("UPDATE digital_plan_steps")) return this.planSteps;
return this.plans;
}
}

View File

@@ -447,6 +447,19 @@ function buildBusinessView(
plan_id: stringField(record.planId ?? record.plan_id) || null,
assigned_skill_id: stringField(record.assignedSkillId ?? record.assigned_skill_id) || null,
};
case "plan_step":
return {
...base,
plan_id: stringField(record.planId ?? record.plan_id) || null,
step_id: row.entity_id,
seq: typeof record.seq === "number" ? record.seq : null,
depends_on: Array.isArray(record.dependsOn ?? record.depends_on)
? record.dependsOn ?? record.depends_on
: [],
preferred_skill_ids: Array.isArray(record.preferredSkillIds ?? record.preferred_skill_ids)
? record.preferredSkillIds ?? record.preferred_skill_ids
: [],
};
case "run":
return {
...base,
@@ -747,6 +760,8 @@ function entitySummarySelect(entityType: string): string | null {
return "SELECT title, status, objective, payload FROM digital_plans WHERE id = ?";
case "task":
return "SELECT title, status, NULL AS objective, payload FROM digital_tasks WHERE id = ?";
case "plan_step":
return "SELECT title, status, NULL AS objective, payload FROM digital_plan_steps WHERE id = ?";
case "run":
return "SELECT id AS title, status, NULL AS objective, payload FROM digital_runs WHERE id = ?";
case "event":
@@ -843,6 +858,8 @@ function entityTable(entityType: string): string | null {
return "digital_plans";
case "task":
return "digital_tasks";
case "plan_step":
return "digital_plan_steps";
case "run":
return "digital_runs";
case "event":