feat(roundtable): 圆桌 Step2 分层 DAG 编排(并行/沙箱双模式 + 流程图 + 按需取全文)
数据模型/编辑器:链条加 stages 分层(前后端 + alembic 20260607_03);BusinessChainEditorPage 竖列 Stage 编辑 + 底部只读流程图预览;lib/dag-types + chain-stages 纯逻辑(含单测)。 调度(runDagOrchestration,方案 A 总控驱动):每个 stage 由总控经 agent_orchestration 派活给计划钉死的席位,批内 Promise.all 并行、批间 barrier 串行;末尾交回 runOrchestration 收口。抑制 leader 预广播 + 干净席位任务,根治『席位模仿派活』。 执行子模式:快速(双列·产物走正文·禁写文件 seat_parallel)/ 沙箱(单列·写 .md·沙箱跟随预览 seat);统一禁 bash(防 .py 脚本),提示词禁 .py。 显示:头像条 + 两列/单列 + ref 全量累积 + 节流 flush(仅选中渲染);DAG 流程图弹窗(按 stage 分列,节点随执行点亮,只到共识);沙箱跟随当前席位(防错位 + 修第一个席位自动开沙箱)。 按需取全文:新增 harness 只读工具 read_peer_delivery(从 run context 取网关注入的前序席位完整交付),席位默认看摘要、需要时取全文。 修:宽表溢出、并行自动下滑、data-lov-id Fragment 警告等。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
5164fd362c
commit
7b8c11852e
26 files changed
+3719
-216
No files matched your search
@@ -27,21 +27,43 @@ export interface BusinessChain {
|
||||
description?: string;
|
||||
/** 有序席位列表。 */
|
||||
seats: ChainSeat[];
|
||||
/**
|
||||
* 可选「分层编排」:把 `seats` 分成若干阶段(stage),每个阶段内的 agent_id
|
||||
* 并行、阶段之间串行。如 `[["a","b"],["c"]]` = (a‖b) → c。缺省 / null = 线性链
|
||||
* (每席位独立一层)。有分层时,选入 Step 2 走 `dag` 编排(见 `lib/dag-types.ts`)。
|
||||
*/
|
||||
stages?: string[][] | null;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 推荐弹窗(席位来源选择器)确认后回传给主页面的统一结果。
|
||||
* 两种模式(智能推荐 / 业务链条)最终都产出**有序**的 `agents` + 一个 `mode`。
|
||||
* 三种模式(智能推荐 / 业务链条线性 / 业务链条分层 DAG)最终都产出**有序**的
|
||||
* `agents` + 一个 `mode`。
|
||||
*/
|
||||
export interface SeatSelectionResult {
|
||||
/** 有序席位 —— 与现有 `handleConfirmAgents` 入参兼容。 */
|
||||
/** 有序席位 —— 与现有 `handleConfirmAgents` 入参兼容。dag 模式下按 stage 展平排序。 */
|
||||
agents: Array<{ agent_id: string; name: string }>;
|
||||
/** 决定 Step 2 走哪种编排:自由派活 vs 按链条顺序派活。 */
|
||||
mode: "recommend" | "chain";
|
||||
/** chain 模式带上来源链条(用于草稿快照 / Step 2 展示链名)。 */
|
||||
/**
|
||||
* 决定 Step 2 走哪种编排:
|
||||
* - `recommend` 总控自由派活;
|
||||
* - `chain` 按链条顺序逐位派活;
|
||||
* - `dag` 分层并行(来源链条带 `stages` 时)。
|
||||
*/
|
||||
mode: "recommend" | "chain" | "dag";
|
||||
/** chain / dag 模式带上来源链条(用于草稿快照 / Step 2 展示链名)。 */
|
||||
chain?: Pick<BusinessChain, "id" | "title">;
|
||||
/** dag 模式带上由链条 `stages` 构造的执行计划(见 `lib/dag-types.ts`)。 */
|
||||
plan?: import("./dag-types").OrchestrationPlan;
|
||||
/**
|
||||
* dag 模式的执行子模式(仅 `mode === "dag"` 有意义):
|
||||
* - `fast`(快速):同 stage 席位**并行**、主区**双列**显示、**禁写文件**(seat_parallel);
|
||||
* - `sandbox`(沙箱):同 stage 席位仍**并行**,但主区**单列**显示、**允许写文件**(seat),
|
||||
* 沙箱跟随当前显示的席位(点头像切换,沙箱内容随之切换/关闭)。
|
||||
* 缺省 `fast`。
|
||||
*/
|
||||
dagExecMode?: "fast" | "sandbox";
|
||||
}
|
||||
|
||||
/** 链条席位数硬约束,与圆桌推荐弹窗的 `MIN_SELECTED`/`MAX_SELECTED` 对齐。 */
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
addEmptyStage,
|
||||
addSeatAsNewStage,
|
||||
addSeatToStage,
|
||||
chainToStageGroups,
|
||||
countSeats,
|
||||
deleteStage,
|
||||
findStageIndexOfSeat,
|
||||
moveSeatToStage,
|
||||
moveStage,
|
||||
removeSeat,
|
||||
splitSeatToNewStage,
|
||||
stageGroupsToSeats,
|
||||
stageGroupsToStagePayload,
|
||||
type StageGroups,
|
||||
} from "./chain-stages";
|
||||
|
||||
const seat = (id: string) => ({ agent_id: id, name: id.toUpperCase(), description: "" });
|
||||
const ids = (groups: StageGroups) => groups.map((g) => g.map((s) => s.agent_id));
|
||||
|
||||
// ── chainToStageGroups ────────────────────────────────────────────────────────
|
||||
|
||||
test("chainToStageGroups: linear chain (no stages) → one seat per stage", () => {
|
||||
const groups = chainToStageGroups({ seats: [seat("a"), seat("b"), seat("c")] });
|
||||
assert.deepEqual(ids(groups), [["a"], ["b"], ["c"]]);
|
||||
});
|
||||
|
||||
test("chainToStageGroups: with stages → grouped, mapping ids to seats", () => {
|
||||
const groups = chainToStageGroups({
|
||||
seats: [seat("a"), seat("b"), seat("c")],
|
||||
stages: [["a", "b"], ["c"]],
|
||||
});
|
||||
assert.deepEqual(ids(groups), [["a", "b"], ["c"]]);
|
||||
});
|
||||
|
||||
test("chainToStageGroups: drops stage ids with no matching seat, and empty groups", () => {
|
||||
const groups = chainToStageGroups({
|
||||
seats: [seat("a"), seat("c")],
|
||||
stages: [["a", "ghost"], ["c"], ["onlyghost"]],
|
||||
});
|
||||
assert.deepEqual(ids(groups), [["a"], ["c"]]);
|
||||
});
|
||||
|
||||
test("chainToStageGroups: stages that resolve to nothing → linear fallback", () => {
|
||||
const groups = chainToStageGroups({ seats: [seat("a"), seat("b")], stages: [["ghost"]] });
|
||||
assert.deepEqual(ids(groups), [["a"], ["b"]]);
|
||||
});
|
||||
|
||||
// ── serialization ─────────────────────────────────────────────────────────────
|
||||
|
||||
test("stageGroupsToSeats flattens in order", () => {
|
||||
const groups: StageGroups = [[seat("a"), seat("b")], [seat("c")]];
|
||||
assert.deepEqual(
|
||||
stageGroupsToSeats(groups).map((s) => s.agent_id),
|
||||
["a", "b", "c"],
|
||||
);
|
||||
});
|
||||
|
||||
test("stageGroupsToStagePayload returns null when all singletons (linear)", () => {
|
||||
const groups: StageGroups = [[seat("a")], [seat("b")]];
|
||||
assert.equal(stageGroupsToStagePayload(groups), null);
|
||||
});
|
||||
|
||||
test("stageGroupsToStagePayload returns groups when any stage is parallel", () => {
|
||||
const groups: StageGroups = [[seat("a"), seat("b")], [seat("c")]];
|
||||
assert.deepEqual(stageGroupsToStagePayload(groups), [["a", "b"], ["c"]]);
|
||||
});
|
||||
|
||||
test("stageGroupsToStagePayload ignores empty stages", () => {
|
||||
const groups: StageGroups = [[seat("a"), seat("b")], []];
|
||||
assert.deepEqual(stageGroupsToStagePayload(groups), [["a", "b"]]);
|
||||
});
|
||||
|
||||
// ── lookups ───────────────────────────────────────────────────────────────────
|
||||
|
||||
test("findStageIndexOfSeat / countSeats", () => {
|
||||
const groups: StageGroups = [[seat("a"), seat("b")], [seat("c")]];
|
||||
assert.equal(findStageIndexOfSeat(groups, "c"), 1);
|
||||
assert.equal(findStageIndexOfSeat(groups, "zzz"), -1);
|
||||
assert.equal(countSeats(groups), 3);
|
||||
});
|
||||
|
||||
// ── mutations ─────────────────────────────────────────────────────────────────
|
||||
|
||||
test("addSeatAsNewStage appends a singleton stage, dedupes", () => {
|
||||
let g: StageGroups = [[seat("a")]];
|
||||
g = addSeatAsNewStage(g, seat("b"));
|
||||
assert.deepEqual(ids(g), [["a"], ["b"]]);
|
||||
g = addSeatAsNewStage(g, seat("a")); // dup → no-op
|
||||
assert.deepEqual(ids(g), [["a"], ["b"]]);
|
||||
});
|
||||
|
||||
test("addSeatToStage inserts into a stage at index", () => {
|
||||
const g = addSeatToStage([[seat("a")], [seat("c")]], seat("b"), 0, 0);
|
||||
assert.deepEqual(ids(g), [["b", "a"], ["c"]]);
|
||||
});
|
||||
|
||||
test("removeSeat drops the seat and prunes an emptied stage", () => {
|
||||
const g = removeSeat([[seat("a")], [seat("b"), seat("c")]], "a");
|
||||
assert.deepEqual(ids(g), [["b", "c"]]);
|
||||
});
|
||||
|
||||
test("moveSeatToStage merges across stages and prunes empty source", () => {
|
||||
const g = moveSeatToStage([[seat("a")], [seat("b")]], "a", 1);
|
||||
assert.deepEqual(ids(g), [["b", "a"]]);
|
||||
});
|
||||
|
||||
test("moveSeatToStage within same stage reorders", () => {
|
||||
const g = moveSeatToStage([[seat("a"), seat("b"), seat("c")]], "c", 0, 0);
|
||||
assert.deepEqual(ids(g), [["c", "a", "b"]]);
|
||||
});
|
||||
|
||||
test("splitSeatToNewStage pulls a seat out into a new following stage", () => {
|
||||
const g = splitSeatToNewStage([[seat("a"), seat("b")], [seat("c")]], "b");
|
||||
assert.deepEqual(ids(g), [["a"], ["b"], ["c"]]);
|
||||
});
|
||||
|
||||
test("splitSeatToNewStage on an already-solo seat is a no-op", () => {
|
||||
const g = splitSeatToNewStage([[seat("a")], [seat("b")]], "a");
|
||||
assert.deepEqual(ids(g), [["a"], ["b"]]);
|
||||
});
|
||||
|
||||
test("moveStage reorders serial stages", () => {
|
||||
const g = moveStage([[seat("a")], [seat("b")], [seat("c")]], 2, -1);
|
||||
assert.deepEqual(ids(g), [["a"], ["c"], ["b"]]);
|
||||
});
|
||||
|
||||
test("addEmptyStage / deleteStage", () => {
|
||||
let g = addEmptyStage([[seat("a")]]);
|
||||
assert.deepEqual(ids(g), [["a"], []]);
|
||||
g = deleteStage(g, 1);
|
||||
assert.deepEqual(ids(g), [["a"]]);
|
||||
});
|
||||
|
||||
// round-trip: editor groups → payload → reload preserves structure
|
||||
test("round-trip: groups → {seats, stages} → chainToStageGroups", () => {
|
||||
const groups: StageGroups = [[seat("a"), seat("b")], [seat("c")]];
|
||||
const seats = stageGroupsToSeats(groups);
|
||||
const stages = stageGroupsToStagePayload(groups);
|
||||
const restored = chainToStageGroups({ seats, stages });
|
||||
assert.deepEqual(ids(restored), [["a", "b"], ["c"]]);
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* 业务链条「分层编排」编辑器的纯数据操作。
|
||||
*
|
||||
* 编辑器内部用 `StageGroups`(`ChainSeat[][]`,每个内层数组 = 一个 stage,stage 内
|
||||
* 并行、stage 间串行)作为**单一数据源**:
|
||||
* - 展平得到落库的有序 `seats`({@link stageGroupsToSeats});
|
||||
* - 折叠得到落库的 `stages`({@link stageGroupsToStagePayload})。
|
||||
*
|
||||
* 这里只放纯函数(无 React / 无副作用),便于单测;组件只做渲染 + 调用这些函数。
|
||||
* 对应需求文档 `docs/roundtable-dag-orchestration.md` §2(分层编辑器,竖列分组)。
|
||||
*/
|
||||
import type { BusinessChain, ChainSeat } from "@/roundtable-planning/lib/business-chain";
|
||||
|
||||
/** 编辑器内部的分层结构:每个内层数组是一个并行 stage,外层顺序即串行顺序。 */
|
||||
export type StageGroups = ChainSeat[][];
|
||||
|
||||
/**
|
||||
* 从一条业务链条还原分层结构。
|
||||
* - 链条带 `stages`:按分层分组(agent_id → 对应 seat),丢弃找不到 seat 的 id 与空组;
|
||||
* 分层全空时回退到线性。
|
||||
* - 无 `stages`(老链条):线性 —— 每个 seat 独立成一层。
|
||||
*/
|
||||
export function chainToStageGroups(chain: Pick<BusinessChain, "seats" | "stages">): StageGroups {
|
||||
const seats = chain.seats ?? [];
|
||||
const byId = new Map(seats.map((s) => [s.agent_id, s]));
|
||||
if (chain.stages && chain.stages.length > 0) {
|
||||
const groups: StageGroups = [];
|
||||
for (const group of chain.stages) {
|
||||
const mapped = group.map((id) => byId.get(id)).filter((s): s is ChainSeat => Boolean(s));
|
||||
if (mapped.length > 0) groups.push(mapped);
|
||||
}
|
||||
if (groups.length > 0) return groups;
|
||||
}
|
||||
return seats.map((s) => [s]);
|
||||
}
|
||||
|
||||
/** 展平成落库 / 校验用的有序席位列表(stage 顺序 → stage 内顺序)。 */
|
||||
export function stageGroupsToSeats(groups: StageGroups): ChainSeat[] {
|
||||
return groups.flat();
|
||||
}
|
||||
|
||||
/**
|
||||
* 折叠成落库的 `stages`。**全是单元素 stage(无并行)时返回 null** —— 语义上就是线性
|
||||
* 链,落库为 null 以便老行为不变(Step 2 仍走 chain 模式);只要有一个 stage ≥2 席位
|
||||
* 就返回显式分层(Step 2 走 dag 模式)。空 stage 已被忽略。
|
||||
*/
|
||||
export function stageGroupsToStagePayload(groups: StageGroups): string[][] | null {
|
||||
const nonEmpty = groups.filter((g) => g.length > 0);
|
||||
const hasParallel = nonEmpty.some((g) => g.length > 1);
|
||||
if (!hasParallel) return null;
|
||||
return nonEmpty.map((g) => g.map((s) => s.agent_id));
|
||||
}
|
||||
|
||||
/** 该席位所在 stage 下标;不存在返回 -1。 */
|
||||
export function findStageIndexOfSeat(groups: StageGroups, agentId: string): number {
|
||||
return groups.findIndex((g) => g.some((s) => s.agent_id === agentId));
|
||||
}
|
||||
|
||||
/** 席位是否已在任意 stage 中。 */
|
||||
export function seatExistsInGroups(groups: StageGroups, agentId: string): boolean {
|
||||
return findStageIndexOfSeat(groups, agentId) >= 0;
|
||||
}
|
||||
|
||||
/** 总席位数(用于 2–8 约束)。 */
|
||||
export function countSeats(groups: StageGroups): number {
|
||||
return groups.reduce((n, g) => n + g.length, 0);
|
||||
}
|
||||
|
||||
// ── 变换(均返回新结构,不可变)──────────────────────────────────────────────
|
||||
|
||||
/** 末尾追加一个**新单席位 stage**(线性追加,pool 点击加入默认行为)。 */
|
||||
export function addSeatAsNewStage(groups: StageGroups, seat: ChainSeat): StageGroups {
|
||||
if (seatExistsInGroups(groups, seat.agent_id)) return groups;
|
||||
return [...groups, [seat]];
|
||||
}
|
||||
|
||||
/** 把席位加入指定 stage(可选插入位置);席位已存在则不动。 */
|
||||
export function addSeatToStage(
|
||||
groups: StageGroups,
|
||||
seat: ChainSeat,
|
||||
stageIdx: number,
|
||||
atIndex?: number,
|
||||
): StageGroups {
|
||||
if (seatExistsInGroups(groups, seat.agent_id)) return groups;
|
||||
if (stageIdx < 0 || stageIdx >= groups.length) return groups;
|
||||
return groups.map((g, i) => {
|
||||
if (i !== stageIdx) return g;
|
||||
const next = [...g];
|
||||
const at = atIndex == null ? next.length : Math.max(0, Math.min(atIndex, next.length));
|
||||
next.splice(at, 0, seat);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
/** 移除一个席位;该 stage 因此变空则连 stage 一起删掉。 */
|
||||
export function removeSeat(groups: StageGroups, agentId: string): StageGroups {
|
||||
return groups
|
||||
.map((g) => g.filter((s) => s.agent_id !== agentId))
|
||||
.filter((g) => g.length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把席位移动到目标 stage(跨 stage 合并 / stage 内移动)。
|
||||
* 源 stage 变空则删除;删除会改变下标,这里用 agent_id 与目标 stage 的**身份**而非下标
|
||||
* 重新定位,保证语义稳定。`atIndex` 为目标 stage 内插入位置。
|
||||
*/
|
||||
export function moveSeatToStage(
|
||||
groups: StageGroups,
|
||||
agentId: string,
|
||||
targetStageIdx: number,
|
||||
atIndex?: number,
|
||||
): StageGroups {
|
||||
const from = findStageIndexOfSeat(groups, agentId);
|
||||
if (from < 0 || targetStageIdx < 0 || targetStageIdx >= groups.length) return groups;
|
||||
const seat = groups[from].find((s) => s.agent_id === agentId);
|
||||
if (!seat) return groups;
|
||||
// 先按身份记下目标 stage 引用,避免删空源 stage 后下标错位。
|
||||
const targetRef = groups[targetStageIdx];
|
||||
let next: StageGroups = groups.map((g) =>
|
||||
g === targetRef ? g : g.filter((s) => s.agent_id !== agentId),
|
||||
);
|
||||
next = next.map((g) => {
|
||||
if (g !== targetRef) return g;
|
||||
if (g.some((s) => s.agent_id === agentId)) {
|
||||
// stage 内移动:先抽出再按 atIndex 插回。
|
||||
const without = g.filter((s) => s.agent_id !== agentId);
|
||||
const at = atIndex == null ? without.length : Math.max(0, Math.min(atIndex, without.length));
|
||||
without.splice(at, 0, seat);
|
||||
return without;
|
||||
}
|
||||
const merged = [...g];
|
||||
const at = atIndex == null ? merged.length : Math.max(0, Math.min(atIndex, merged.length));
|
||||
merged.splice(at, 0, seat);
|
||||
return merged;
|
||||
});
|
||||
return next.filter((g) => g.length > 0);
|
||||
}
|
||||
|
||||
/** 把席位从当前 stage 抽出,独立成一个**新 stage**(插在原 stage 之后)。 */
|
||||
export function splitSeatToNewStage(groups: StageGroups, agentId: string): StageGroups {
|
||||
const from = findStageIndexOfSeat(groups, agentId);
|
||||
if (from < 0) return groups;
|
||||
const seat = groups[from].find((s) => s.agent_id === agentId);
|
||||
if (!seat) return groups;
|
||||
if (groups[from].length === 1) return groups; // 已经独占一层,无需拆
|
||||
const out: StageGroups = [];
|
||||
groups.forEach((g, i) => {
|
||||
if (i === from) {
|
||||
out.push(g.filter((s) => s.agent_id !== agentId));
|
||||
out.push([seat]);
|
||||
} else {
|
||||
out.push(g);
|
||||
}
|
||||
});
|
||||
return out.filter((g) => g.length > 0);
|
||||
}
|
||||
|
||||
/** 整段 stage 上移 / 下移(改串行顺序)。 */
|
||||
export function moveStage(groups: StageGroups, stageIdx: number, dir: -1 | 1): StageGroups {
|
||||
const target = stageIdx + dir;
|
||||
if (stageIdx < 0 || stageIdx >= groups.length || target < 0 || target >= groups.length) {
|
||||
return groups;
|
||||
}
|
||||
const next = [...groups];
|
||||
[next[stageIdx], next[target]] = [next[target], next[stageIdx]];
|
||||
return next;
|
||||
}
|
||||
|
||||
/** 末尾追加一个空 stage(用户「新建 Stage」后再拖 / 加席位进去)。 */
|
||||
export function addEmptyStage(groups: StageGroups): StageGroups {
|
||||
return [...groups, []];
|
||||
}
|
||||
|
||||
/** 删除整个 stage(含其席位)。 */
|
||||
export function deleteStage(groups: StageGroups, stageIdx: number): StageGroups {
|
||||
if (stageIdx < 0 || stageIdx >= groups.length) return groups;
|
||||
return groups.filter((_, i) => i !== stageIdx);
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
buildDagStageLeaderTask,
|
||||
buildDagTransitTask,
|
||||
buildDependencySummary,
|
||||
buildPlanFromStages,
|
||||
buildStageTask,
|
||||
chainToDagPlan,
|
||||
emptyPlan,
|
||||
isParallelStage,
|
||||
PARALLEL_DEGREE_WARN_THRESHOLD,
|
||||
pickDagSeatTask,
|
||||
validatePlan,
|
||||
type OrchestrationPlan,
|
||||
} from "./dag-types";
|
||||
|
||||
// ── chainToDagPlan:链条 → 单节点-stage DAG(§1.3 兼容转换)────────────────────
|
||||
|
||||
test("chainToDagPlan turns a linear chain into one-node-per-stage DAG", () => {
|
||||
const plan = chainToDagPlan(["a", "b", "c"]);
|
||||
assert.equal(plan.mode, "dag");
|
||||
assert.equal(plan.finalSynthesis, true);
|
||||
assert.deepEqual(
|
||||
plan.stages.map((s) => s.agentIds),
|
||||
[["a"], ["b"], ["c"]],
|
||||
);
|
||||
// stage id 稳定且唯一(diff / 拖拽重排用)。
|
||||
assert.deepEqual(
|
||||
plan.stages.map((s) => s.id),
|
||||
["stage-0", "stage-1", "stage-2"],
|
||||
);
|
||||
});
|
||||
|
||||
test("chainToDagPlan preserves order and respects finalSynthesis=false", () => {
|
||||
const plan = chainToDagPlan(["x", "y"], false);
|
||||
assert.equal(plan.finalSynthesis, false);
|
||||
assert.deepEqual(
|
||||
plan.stages.map((s) => s.agentIds[0]),
|
||||
["x", "y"],
|
||||
);
|
||||
});
|
||||
|
||||
test("chainToDagPlan on empty chain yields an empty plan", () => {
|
||||
const plan = chainToDagPlan([]);
|
||||
assert.deepEqual(plan.stages, []);
|
||||
});
|
||||
|
||||
test("emptyPlan is a valid empty dag plan", () => {
|
||||
assert.deepEqual(emptyPlan(), { mode: "dag", stages: [], finalSynthesis: true });
|
||||
});
|
||||
|
||||
// ── isParallelStage ──────────────────────────────────────────────────────────
|
||||
|
||||
test("isParallelStage is true only for ≥2 seats", () => {
|
||||
assert.equal(isParallelStage({ id: "s", agentIds: ["a"] }), false);
|
||||
assert.equal(isParallelStage({ id: "s", agentIds: ["a", "b"] }), true);
|
||||
});
|
||||
|
||||
// ── validatePlan ──────────────────────────────────────────────────────────────
|
||||
|
||||
const roster = ["a", "b", "c", "d"];
|
||||
|
||||
test("validatePlan accepts a valid mixed serial/parallel plan", () => {
|
||||
const plan: OrchestrationPlan = {
|
||||
mode: "dag",
|
||||
finalSynthesis: true,
|
||||
stages: [
|
||||
{ id: "s0", agentIds: ["a"] },
|
||||
{ id: "s1", agentIds: ["b", "c"] },
|
||||
{ id: "s2", agentIds: ["d"] },
|
||||
],
|
||||
};
|
||||
const res = validatePlan(plan, roster);
|
||||
assert.equal(res.ok, true);
|
||||
assert.deepEqual(res.errors, []);
|
||||
assert.deepEqual(res.warnings, []);
|
||||
});
|
||||
|
||||
test("validatePlan rejects an empty plan", () => {
|
||||
const res = validatePlan(emptyPlan(), roster);
|
||||
assert.equal(res.ok, false);
|
||||
assert.equal(res.errors.length, 1);
|
||||
});
|
||||
|
||||
test("validatePlan rejects an empty stage", () => {
|
||||
const plan: OrchestrationPlan = {
|
||||
mode: "dag",
|
||||
finalSynthesis: true,
|
||||
stages: [{ id: "s0", agentIds: ["a"] }, { id: "s1", agentIds: [] }],
|
||||
};
|
||||
const res = validatePlan(plan, roster);
|
||||
assert.equal(res.ok, false);
|
||||
assert.match(res.errors[0], /第 2 阶段为空/);
|
||||
});
|
||||
|
||||
test("validatePlan rejects a seat not in the roster", () => {
|
||||
const plan: OrchestrationPlan = {
|
||||
mode: "dag",
|
||||
finalSynthesis: true,
|
||||
stages: [{ id: "s0", agentIds: ["a", "zzz"] }],
|
||||
};
|
||||
const res = validatePlan(plan, roster);
|
||||
assert.equal(res.ok, false);
|
||||
assert.match(res.errors[0], /未选定的席位/);
|
||||
});
|
||||
|
||||
test("validatePlan rejects the same seat across two stages", () => {
|
||||
const plan: OrchestrationPlan = {
|
||||
mode: "dag",
|
||||
finalSynthesis: true,
|
||||
stages: [
|
||||
{ id: "s0", agentIds: ["a"] },
|
||||
{ id: "s1", agentIds: ["a"] },
|
||||
],
|
||||
};
|
||||
const res = validatePlan(plan, roster);
|
||||
assert.equal(res.ok, false);
|
||||
assert.match(res.errors[0], /只能跑一次/);
|
||||
});
|
||||
|
||||
test("validatePlan rejects a duplicate seat within one stage", () => {
|
||||
const plan: OrchestrationPlan = {
|
||||
mode: "dag",
|
||||
finalSynthesis: true,
|
||||
stages: [{ id: "s0", agentIds: ["a", "a"] }],
|
||||
};
|
||||
const res = validatePlan(plan, roster);
|
||||
assert.equal(res.ok, false);
|
||||
assert.match(res.errors[0], /重复/);
|
||||
});
|
||||
|
||||
test("validatePlan warns (but allows) when parallel degree exceeds the threshold", () => {
|
||||
const big = Array.from({ length: PARALLEL_DEGREE_WARN_THRESHOLD + 1 }, (_, i) => `p${i}`);
|
||||
const plan: OrchestrationPlan = {
|
||||
mode: "dag",
|
||||
finalSynthesis: true,
|
||||
stages: [{ id: "s0", agentIds: big }],
|
||||
};
|
||||
const res = validatePlan(plan, big);
|
||||
assert.equal(res.ok, true);
|
||||
assert.equal(res.errors.length, 0);
|
||||
assert.equal(res.warnings.length, 1);
|
||||
assert.match(res.warnings[0], /并发限流/);
|
||||
});
|
||||
|
||||
// chain→dag round-trip is always valid against its own roster.
|
||||
test("a chainToDagPlan validates clean against its own roster", () => {
|
||||
const chain = ["alpha", "beta", "gamma"];
|
||||
const res = validatePlan(chainToDagPlan(chain), chain);
|
||||
assert.equal(res.ok, true);
|
||||
});
|
||||
|
||||
// ── buildPlanFromStages (链条 stages → 执行计划) ──────────────────────────────
|
||||
|
||||
test("buildPlanFromStages maps groups to stages with stable ids", () => {
|
||||
const plan = buildPlanFromStages([["a", "b"], ["c"]]);
|
||||
assert.equal(plan.mode, "dag");
|
||||
assert.equal(plan.finalSynthesis, true);
|
||||
assert.deepEqual(
|
||||
plan.stages.map((s) => s.agentIds),
|
||||
[["a", "b"], ["c"]],
|
||||
);
|
||||
assert.deepEqual(
|
||||
plan.stages.map((s) => s.id),
|
||||
["stage-0", "stage-1"],
|
||||
);
|
||||
});
|
||||
|
||||
test("buildPlanFromStages filters out non-surviving ids and drops emptied stages", () => {
|
||||
// "b" deleted; stage that becomes empty is dropped.
|
||||
const plan = buildPlanFromStages([["a", "b"], ["x"]], ["a", "c"]);
|
||||
assert.deepEqual(
|
||||
plan.stages.map((s) => s.agentIds),
|
||||
[["a"]],
|
||||
);
|
||||
});
|
||||
|
||||
test("buildPlanFromStages on all-filtered yields empty stages (caller falls back)", () => {
|
||||
const plan = buildPlanFromStages([["x"], ["y"]], ["a"]);
|
||||
assert.deepEqual(plan.stages, []);
|
||||
});
|
||||
|
||||
test("a chain plan validates clean against its surviving roster", () => {
|
||||
const plan = buildPlanFromStages([["a", "b"], ["c"]], ["a", "b", "c"]);
|
||||
const res = validatePlan(plan, ["a", "b", "c"]);
|
||||
assert.equal(res.ok, true);
|
||||
});
|
||||
|
||||
// ── buildDependencySummary (§3.1 依赖摘要注入) ─────────────────────────────────
|
||||
|
||||
test("buildDependencySummary is empty for no deliveries (first stage)", () => {
|
||||
assert.equal(buildDependencySummary([]), "");
|
||||
});
|
||||
|
||||
test("buildDependencySummary lists each seat's delivery with its name", () => {
|
||||
const out = buildDependencySummary([
|
||||
{ seatName: "情报收集", content: "情报正文" },
|
||||
{ seatName: "环境评估", content: "评估正文" },
|
||||
]);
|
||||
assert.match(out, /【情报收集】/);
|
||||
assert.match(out, /情报正文/);
|
||||
assert.match(out, /【环境评估】/);
|
||||
assert.match(out, /评估正文/);
|
||||
});
|
||||
|
||||
test("buildDependencySummary truncates long content", () => {
|
||||
const long = "x".repeat(3000);
|
||||
const out = buildDependencySummary([{ seatName: "A", content: long }], 100);
|
||||
assert.match(out, /…(已截断)/);
|
||||
assert.ok(out.length < 3000);
|
||||
});
|
||||
|
||||
test("buildDependencySummary handles empty content gracefully", () => {
|
||||
const out = buildDependencySummary([{ seatName: "A", content: " " }]);
|
||||
assert.match(out, /(无文本输出)/);
|
||||
});
|
||||
|
||||
// ── buildStageTask (§3.2 直派提示) ────────────────────────────────────────────
|
||||
|
||||
test("buildStageTask for first stage embeds the task background", () => {
|
||||
const task = buildStageTask({
|
||||
seedMessage: "做一个容灾方案",
|
||||
seatName: "情报收集",
|
||||
priorSummary: "",
|
||||
isParallel: false,
|
||||
});
|
||||
assert.match(task, /任务背景/);
|
||||
assert.match(task, /做一个容灾方案/);
|
||||
assert.match(task, /情报收集/);
|
||||
// serial node — no parallel no-file warning.
|
||||
assert.doesNotMatch(task, /并行研讨/);
|
||||
});
|
||||
|
||||
test("buildStageTask for a later stage embeds the prior summary, not the seed", () => {
|
||||
const task = buildStageTask({
|
||||
seedMessage: "原始任务",
|
||||
seatName: "方案设计",
|
||||
priorSummary: "【情报收集】的交付:\n情报正文",
|
||||
isParallel: false,
|
||||
});
|
||||
assert.match(task, /此前各阶段已完成席位的交付摘要/);
|
||||
assert.match(task, /情报正文/);
|
||||
assert.doesNotMatch(task, /原始任务/);
|
||||
});
|
||||
|
||||
test("buildStageTask in a parallel stage forbids writing files", () => {
|
||||
const task = buildStageTask({
|
||||
seedMessage: "原始任务",
|
||||
seatName: "方案设计",
|
||||
priorSummary: "",
|
||||
isParallel: true,
|
||||
});
|
||||
assert.match(task, /并行研讨/);
|
||||
assert.match(task, /不要写文件/);
|
||||
});
|
||||
|
||||
test("buildStageTask with priorIsBridge frames prior context as the leader's bridge", () => {
|
||||
const bridge = "总控综合:情报已收集,下一步聚焦架构设计";
|
||||
const task = buildStageTask({
|
||||
seedMessage: "原始任务",
|
||||
seatName: "方案设计",
|
||||
priorSummary: bridge,
|
||||
isParallel: false,
|
||||
priorIsBridge: true,
|
||||
});
|
||||
// 措辞切换到「承上启下」综合说明,而非机械「交付摘要」。
|
||||
assert.match(task, /承上启下/);
|
||||
assert.match(task, /综合说明/);
|
||||
assert.match(task, /总控综合/);
|
||||
assert.doesNotMatch(task, /已完成席位的交付摘要/);
|
||||
});
|
||||
|
||||
// ── buildDagTransitTask (§12.3 Stage 间总控中转 + 广播) ─────────────────────────
|
||||
|
||||
test("buildDagTransitTask names completed + next seats and forbids dispatch/closeout", () => {
|
||||
const task = buildDagTransitTask({
|
||||
completedSeatNames: ["情报收集", "环境评估"],
|
||||
nextSeatNames: ["方案设计", "风险审查"],
|
||||
});
|
||||
assert.match(task, /中转轮/);
|
||||
assert.match(task, /情报收集、环境评估/);
|
||||
assert.match(task, /方案设计、风险审查/);
|
||||
assert.match(task, /承上启下/);
|
||||
// 计划钉死下一批 → 总控不自由派活、不收口。
|
||||
assert.match(task, /不要.*派活/);
|
||||
assert.match(task, /不要现在收口/);
|
||||
});
|
||||
|
||||
test("buildDagTransitTask falls back gracefully when seat name lists are empty", () => {
|
||||
const task = buildDagTransitTask({ completedSeatNames: [], nextSeatNames: [] });
|
||||
assert.match(task, /本批席位/);
|
||||
assert.match(task, /下一阶段席位/);
|
||||
});
|
||||
|
||||
// ── buildDagStageLeaderTask (§3.2 方案 A:总控驱动每 stage 派活) ─────────────────
|
||||
|
||||
test("buildDagStageLeaderTask first stage embeds task background + pins seats", () => {
|
||||
const task = buildDagStageLeaderTask({
|
||||
seedMessage: "做一个容灾方案",
|
||||
stageIndex: 0,
|
||||
totalStages: 3,
|
||||
seats: [
|
||||
{ agentId: "intel", name: "情报收集" },
|
||||
{ agentId: "env", name: "环境评估" },
|
||||
],
|
||||
isFirst: true,
|
||||
});
|
||||
assert.match(task, /任务背景/);
|
||||
assert.match(task, /做一个容灾方案/);
|
||||
assert.match(task, /第 1\/3 个阶段/);
|
||||
// 每个钉死席位都要带 agent_name 让总控逐字派活。
|
||||
assert.match(task, /agent_name: intel/);
|
||||
assert.match(task, /agent_name: env/);
|
||||
assert.match(task, /情报收集/);
|
||||
assert.match(task, /环境评估/);
|
||||
// 约束:只派给清单内、不收口。
|
||||
assert.match(task, /不要派给清单外/);
|
||||
assert.match(task, /不要.*给出最终结论/);
|
||||
// 多席位 → 并行提示。
|
||||
assert.match(task, /并行/);
|
||||
});
|
||||
|
||||
test("buildDagStageLeaderTask later stage relies on injected prior deliveries, not seed", () => {
|
||||
const task = buildDagStageLeaderTask({
|
||||
seedMessage: "原始任务",
|
||||
stageIndex: 1,
|
||||
totalStages: 2,
|
||||
seats: [{ agentId: "plan", name: "方案设计" }],
|
||||
isFirst: false,
|
||||
});
|
||||
assert.match(task, /承上启下/);
|
||||
assert.match(task, /第 2\/2 个阶段/);
|
||||
assert.doesNotMatch(task, /原始任务/);
|
||||
// 单席位 stage → 不加并行提示。
|
||||
assert.doesNotMatch(task, /会\*\*并行\*\*执行/);
|
||||
});
|
||||
|
||||
// ── pickDagSeatTask (§3.2 方案 A:取总控派给某席位的 task,多席位不张冠李戴) ────────
|
||||
|
||||
test("pickDagSeatTask returns the exact dispatch matched by agent_name (+ role guard)", () => {
|
||||
const dispatched: [string, string][] = [
|
||||
["plan", "设计架构"],
|
||||
["risk", "审查风险"],
|
||||
];
|
||||
const riskTask = pickDagSeatTask(dispatched, "risk", "风险审查");
|
||||
assert.match(riskTask, /审查风险/);
|
||||
assert.doesNotMatch(riskTask, /设计架构/);
|
||||
const planTask = pickDagSeatTask(dispatched, "plan", "方案设计");
|
||||
assert.match(planTask, /设计架构/);
|
||||
// 角色边界护栏:禁止席位派活/调度。
|
||||
assert.match(riskTask, /执行席位/);
|
||||
assert.match(riskTask, /严禁.*派活|严禁.*调度/);
|
||||
});
|
||||
|
||||
test("pickDagSeatTask gives a CLEAN own-role task on miss — never injects the dispatch narrative", () => {
|
||||
const dispatched: [string, string][] = [["plan", "设计架构"]];
|
||||
// risk 没被派到 → 既不借 plan 的「设计架构」,也**不**注入总控派活叙述(防模仿派活)。
|
||||
const task = pickDagSeatTask(dispatched, "risk", "风险审查");
|
||||
assert.doesNotMatch(task, /设计架构/);
|
||||
assert.match(task, /风险审查/);
|
||||
assert.match(task, /独立完成/);
|
||||
// 角色边界护栏:禁止席位派活/调度/绕道脚本。
|
||||
assert.match(task, /执行席位/);
|
||||
assert.match(task, /严禁/);
|
||||
assert.match(task, /bash|脚本|内部接口/);
|
||||
});
|
||||
|
||||
test("pickDagSeatTask with empty dispatched falls back to clean own-role task", () => {
|
||||
const task = pickDagSeatTask([], "risk", "风险审查");
|
||||
assert.match(task, /风险审查/);
|
||||
assert.match(task, /本阶段/);
|
||||
assert.match(task, /执行席位/);
|
||||
});
|
||||
|
||||
test("pickDagSeatTask embeds the seed message as task background when provided", () => {
|
||||
const task = pickDagSeatTask([], "risk", "风险审查", "做一个容灾方案");
|
||||
assert.match(task, /任务背景/);
|
||||
assert.match(task, /做一个容灾方案/);
|
||||
// exact-match 分支也带背景。
|
||||
const exactTask = pickDagSeatTask([["risk", "审查风险"]], "risk", "风险审查", "做一个容灾方案");
|
||||
assert.match(exactTask, /做一个容灾方案/);
|
||||
assert.match(exactTask, /审查风险/);
|
||||
});
|
||||
|
||||
test("pickDagSeatTask mentions read_peer_delivery only when peers exist (§12.9)", () => {
|
||||
const noPeers = pickDagSeatTask([], "risk", "风险审查", "种子", false);
|
||||
assert.doesNotMatch(noPeers, /read_peer_delivery/);
|
||||
const withPeers = pickDagSeatTask([], "risk", "风险审查", "种子", true);
|
||||
assert.match(withPeers, /read_peer_delivery/);
|
||||
assert.match(withPeers, /按需取全文|完整交付/);
|
||||
});
|
||||
|
||||
test("pickDagSeatTask (sandbox mode, allowFiles) asks for .md and forbids .py (§12.8)", () => {
|
||||
// allowFiles=true(沙箱模式):产出 md、禁 .py。
|
||||
const miss = pickDagSeatTask([], "risk", "风险审查", "", false, true);
|
||||
const hit = pickDagSeatTask([["risk", "审查风险"]], "risk", "风险审查", "", false, true);
|
||||
for (const t of [miss, hit]) {
|
||||
assert.match(t, /Markdown(\.md)文件|\.md/);
|
||||
assert.match(t, /不要写 \.py|不要 \.py/);
|
||||
assert.match(t, /产物要求/);
|
||||
}
|
||||
});
|
||||
|
||||
test("pickDagSeatTask (fast mode, default) keeps output in the message body — no file (§12.10)", () => {
|
||||
// allowFiles 默认 false(快速模式):产物走正文,不写文件、不写 md。
|
||||
const t = pickDagSeatTask([], "risk", "风险审查");
|
||||
assert.match(t, /直接写在回复正文|产物走正文|不要写文件/);
|
||||
assert.doesNotMatch(t, /Markdown(\.md)文件/);
|
||||
});
|
||||
|
||||
test("buildDagStageLeaderTask insists on actually calling the tool (not narrating)", () => {
|
||||
const task = buildDagStageLeaderTask({
|
||||
seedMessage: "x",
|
||||
stageIndex: 0,
|
||||
totalStages: 2,
|
||||
seats: [
|
||||
{ agentId: "a", name: "甲" },
|
||||
{ agentId: "b", name: "乙" },
|
||||
],
|
||||
isFirst: true,
|
||||
});
|
||||
assert.match(task, /真正调用 agent_orchestration 工具/);
|
||||
assert.match(task, /不要.*只用文字/);
|
||||
});
|
||||
@@ -0,0 +1,418 @@
|
||||
/**
|
||||
* 圆桌 DAG 编排(分层 Stage 模型)共享类型 + 纯函数。
|
||||
*
|
||||
* 对应 `docs/roundtable-dag-orchestration.md` §1「数据模型」。本文件只放纯类型 +
|
||||
* 可单测的纯函数(校验 / chain→dag 兼容转换),不含任何 React / 网络副作用,
|
||||
* 后续 Phase 2(编辑器)/ Phase 3(`runDagOrchestration`)会引用这些类型。
|
||||
*
|
||||
* 设计要点(§0.3 / §1.1):
|
||||
* - DAG 用「有序的 stage 列表」表示:stage 内并行、stage 间串行。
|
||||
* - 线性链是 DAG 的特例(每层 1 个节点),见 {@link chainToDagPlan}。
|
||||
* - 自由连线画布本期不做,仅在数据模型上预留 {@link DagGraph}(§1.2)避免返工。
|
||||
*/
|
||||
|
||||
// ── 分层(Stage)表示:本期主模型(§1.1)──────────────────────────────────────
|
||||
|
||||
/** 一个并行批次:stage 内所有席位并行执行。 */
|
||||
export interface OrchestrationStage {
|
||||
/** stage 稳定 id(拖拽重排 / diff 用)。 */
|
||||
id: string;
|
||||
/** 本 stage 并行执行的席位(agent_id 列表)。1 个 = 退化为串行节点。 */
|
||||
agentIds: string[];
|
||||
}
|
||||
|
||||
/** 用户编排出的执行计划。stages 顺序即串行顺序。 */
|
||||
export interface OrchestrationPlan {
|
||||
/** 编排模式标识,持久化进 step2。 */
|
||||
mode: "dag";
|
||||
/** 串行执行的批次;每批内并行。 */
|
||||
stages: OrchestrationStage[];
|
||||
/** 收口:是否在所有 stage 完成后由总控综合(默认 true)。 */
|
||||
finalSynthesis: boolean;
|
||||
}
|
||||
|
||||
// ── 通用 DAG 表示:自由连线时才需要(§1.2,本期仅预留)───────────────────────
|
||||
|
||||
/** from 完成后才能跑 to。 */
|
||||
export interface DagEdge {
|
||||
from: string;
|
||||
to: string;
|
||||
}
|
||||
|
||||
/** 自由连线画布的图表示。执行前需 toposort → 分层落回 {@link OrchestrationStage}。 */
|
||||
export interface DagGraph {
|
||||
nodes: string[];
|
||||
edges: DagEdge[];
|
||||
}
|
||||
|
||||
// ── 常量 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 单 stage 并行度软上限:超过给 warning(远程模型并发限流 + 沙箱压力,§1.4 / §9)。
|
||||
* 仅提示,不阻断保存。
|
||||
*/
|
||||
export const PARALLEL_DEGREE_WARN_THRESHOLD = 6;
|
||||
|
||||
// ── 校验(纯函数,可单测,§1.4)──────────────────────────────────────────────
|
||||
|
||||
/** {@link validatePlan} 的返回。`errors` 阻断保存,`warnings` 仅提示。 */
|
||||
export interface PlanValidation {
|
||||
ok: boolean;
|
||||
/** 面向用户的中文错误(非空 = 无法保存)。 */
|
||||
errors: string[];
|
||||
/** 面向用户的中文提示(不阻断保存)。 */
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验一份编排计划是否可执行 / 可保存。
|
||||
*
|
||||
* 校验项(§1.4):
|
||||
* - 至少 1 个 stage。
|
||||
* - 不允许空 stage。
|
||||
* - 每个席位必须在本次选定席位 `selectedAgentIds` 内(防编排不存在的席位)。
|
||||
* - 同一席位不允许出现在多个 stage(一个席位只跑一次);同一 stage 内也不允许重复。
|
||||
* - (warning)单 stage 并行度 > {@link PARALLEL_DEGREE_WARN_THRESHOLD}。
|
||||
*
|
||||
* @param plan 待校验的计划。
|
||||
* @param selectedAgentIds 本次选定的席位 agent_id 全集(roster)。
|
||||
*/
|
||||
export function validatePlan(
|
||||
plan: OrchestrationPlan,
|
||||
selectedAgentIds: string[],
|
||||
): PlanValidation {
|
||||
const errors: string[] = [];
|
||||
const warnings: string[] = [];
|
||||
const roster = new Set(selectedAgentIds);
|
||||
|
||||
if (!plan.stages || plan.stages.length === 0) {
|
||||
errors.push("编排为空:请至少添加一个阶段(Stage)。");
|
||||
return { ok: false, errors, warnings };
|
||||
}
|
||||
|
||||
// 记录每个席位首次出现的 stage 序号,用来检测跨 stage 重复。
|
||||
const seenInStage = new Map<string, number>();
|
||||
|
||||
plan.stages.forEach((stage, idx) => {
|
||||
const human = idx + 1;
|
||||
|
||||
if (!stage.agentIds || stage.agentIds.length === 0) {
|
||||
errors.push(`第 ${human} 阶段为空:请至少放入一个席位,或删除该阶段。`);
|
||||
return;
|
||||
}
|
||||
|
||||
const seenInThisStage = new Set<string>();
|
||||
for (const agentId of stage.agentIds) {
|
||||
if (!roster.has(agentId)) {
|
||||
errors.push(`第 ${human} 阶段包含未选定的席位「${agentId}」,请先把它加入参与角色。`);
|
||||
continue;
|
||||
}
|
||||
if (seenInThisStage.has(agentId)) {
|
||||
errors.push(`第 ${human} 阶段内席位「${agentId}」重复,一个席位每阶段只能出现一次。`);
|
||||
continue;
|
||||
}
|
||||
seenInThisStage.add(agentId);
|
||||
|
||||
const firstStage = seenInStage.get(agentId);
|
||||
if (firstStage !== undefined) {
|
||||
errors.push(
|
||||
`席位「${agentId}」同时出现在第 ${firstStage + 1} 与第 ${human} 阶段,一个席位只能跑一次。`,
|
||||
);
|
||||
} else {
|
||||
seenInStage.set(agentId, idx);
|
||||
}
|
||||
}
|
||||
|
||||
if (stage.agentIds.length > PARALLEL_DEGREE_WARN_THRESHOLD) {
|
||||
warnings.push(
|
||||
`第 ${human} 阶段并行 ${stage.agentIds.length} 个席位,可能触发远程模型并发限流或沙箱压力,建议拆分。`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return { ok: errors.length === 0, errors, warnings };
|
||||
}
|
||||
|
||||
// ── 链条 → DAG 兼容转换(§1.3)───────────────────────────────────────────────
|
||||
|
||||
/** 生成稳定的 stage id。不依赖随机数,便于单测与 diff(用序号即可,stages 不重排前唯一)。 */
|
||||
function stageId(index: number): string {
|
||||
return `stage-${index}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把线性链条(有序席位数组)转换成「每层 1 个节点」的 DAG 计划。
|
||||
*
|
||||
* 老 `chain` 模式的数据只是有序的 `selectedAgents`(线性),读取时即时转换为
|
||||
* 单节点-stage 的 dag,不破坏老 draft(§1.3 兼容层)。
|
||||
*
|
||||
* @param orderedAgentIds 链条顺序的席位 agent_id。
|
||||
* @param finalSynthesis 是否收口综合,默认 true。
|
||||
*/
|
||||
export function chainToDagPlan(
|
||||
orderedAgentIds: string[],
|
||||
finalSynthesis = true,
|
||||
): OrchestrationPlan {
|
||||
return {
|
||||
mode: "dag",
|
||||
stages: orderedAgentIds.map((agentId, idx) => ({
|
||||
id: stageId(idx),
|
||||
agentIds: [agentId],
|
||||
})),
|
||||
finalSynthesis,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造一个空计划(编辑器初始态 / 兜底)。
|
||||
*/
|
||||
export function emptyPlan(finalSynthesis = true): OrchestrationPlan {
|
||||
return { mode: "dag", stages: [], finalSynthesis };
|
||||
}
|
||||
|
||||
/**
|
||||
* 把业务链条的 `stages`(agent_id 分组的 string[][])转成执行计划。
|
||||
*
|
||||
* - `allowedIds` 提供时,过滤掉不在其中的 agent_id(如链条里有席位被删除),
|
||||
* 并丢弃过滤后变空的 stage —— 保证选入 Step 2 的计划只含存活席位。
|
||||
* - 全部为空时返回空 stages(调用方据此判断退回 chain / recommend)。
|
||||
*
|
||||
* @param stages 链条分层(每组并行、组间串行)。
|
||||
* @param allowedIds 仅保留这些 agent_id(存活席位);省略则全保留。
|
||||
* @param finalSynthesis 是否收口综合,默认 true。
|
||||
*/
|
||||
export function buildPlanFromStages(
|
||||
stages: string[][],
|
||||
allowedIds?: Iterable<string>,
|
||||
finalSynthesis = true,
|
||||
): OrchestrationPlan {
|
||||
const allow = allowedIds ? new Set(allowedIds) : null;
|
||||
const cleaned: OrchestrationStage[] = [];
|
||||
stages.forEach((group, idx) => {
|
||||
const ids = allow ? group.filter((id) => allow.has(id)) : group.slice();
|
||||
if (ids.length > 0) cleaned.push({ id: stageId(idx), agentIds: ids });
|
||||
});
|
||||
return { mode: "dag", stages: cleaned, finalSynthesis };
|
||||
}
|
||||
|
||||
/** 该 stage 是否真并行(≥2 席位)—— Phase 3 决定是否禁写文件 / Phase 5 决定显示。 */
|
||||
export function isParallelStage(stage: OrchestrationStage): boolean {
|
||||
return stage.agentIds.length > 1;
|
||||
}
|
||||
|
||||
// ── 派活提示构造(纯函数,Phase 3 调度用,可单测,§3.1 依赖摘要注入)──────────────
|
||||
|
||||
/** 已完成席位的一条交付(喂给后续 stage 当依赖上下文)。 */
|
||||
export interface StageDelivery {
|
||||
/** 席位显示名(中文优先)。 */
|
||||
seatName: string;
|
||||
/** 该席位本轮交付正文。 */
|
||||
content: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把前面所有 stage 已交付席位的正文拼成「依赖摘要」,注入下一 stage 的派活提示。
|
||||
* 每条按 `maxCharsPerSeat` 截断,避免后续席位上下文过长(§3.1:stage 边界拉一次摘要)。
|
||||
* 无交付(首 stage)返回空串。
|
||||
*/
|
||||
export function buildDependencySummary(
|
||||
deliveries: StageDelivery[],
|
||||
maxCharsPerSeat = 1200,
|
||||
): string {
|
||||
if (deliveries.length === 0) return "";
|
||||
return deliveries
|
||||
.map((d) => {
|
||||
const body = (d.content ?? "").trim();
|
||||
const clipped =
|
||||
body.length > maxCharsPerSeat ? `${body.slice(0, maxCharsPerSeat)}…(已截断)` : body;
|
||||
return `【${d.seatName}】的交付:\n${clipped || "(无文本输出)"}`;
|
||||
})
|
||||
.join("\n\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* 为某 stage 内一个席位构造 special 派活提示(DAG 直派,无 leader,§3.2 方案 B)。
|
||||
*
|
||||
* - 首 stage(`priorSummary` 为空):带任务背景。
|
||||
* - 后续 stage:带前序交付摘要让其承接(§3.1 依赖可见性)。
|
||||
* - 并行 stage(`isParallel`):明确要求**产出写在正文、禁止写文件 / 沙箱命令**
|
||||
* (§4.3 / §9:并行禁写文件,降低模型困惑,与后端 `seat_parallel` policy 呼应)。
|
||||
*/
|
||||
export function buildStageTask(args: {
|
||||
seedMessage: string;
|
||||
seatName: string;
|
||||
/**
|
||||
* 上一阶段的上下文:
|
||||
* - 默认(`priorIsBridge` 假):{@link buildDependencySummary} 拼出的机械交付摘要;
|
||||
* - `priorIsBridge` 真:总控「承上启下」中转轮({@link buildDagTransitTask})的综合说明。
|
||||
* 首 stage 传空串。
|
||||
*/
|
||||
priorSummary: string;
|
||||
isParallel: boolean;
|
||||
/**
|
||||
* `priorSummary` 是否为总控中转轮(§12.3)产出的「承上启下」说明(而非机械交付摘要)。
|
||||
* 真时改用对应措辞,让席位知道这是总控综合后的指引。缺省 false(机械摘要)。
|
||||
*/
|
||||
priorIsBridge?: boolean;
|
||||
}): string {
|
||||
const { seedMessage, seatName, priorSummary, isParallel, priorIsBridge } = args;
|
||||
const lines: string[] = [];
|
||||
if (!priorSummary) {
|
||||
lines.push("这是一次【分层 DAG 编排】的多智能体圆桌研讨。任务背景如下:", seedMessage, "");
|
||||
} else if (priorIsBridge) {
|
||||
lines.push("分层研讨继续。以下是总控对此前各阶段的【承上启下】综合说明,请据此承接:", "", priorSummary, "");
|
||||
} else {
|
||||
lines.push("分层研讨继续。以下是此前各阶段已完成席位的交付摘要,供你承接:", "", priorSummary, "");
|
||||
}
|
||||
lines.push(`请你作为「${seatName}」,从你的专业职责出发,完成本阶段的分析与交付。`);
|
||||
if (isParallel) {
|
||||
lines.push(
|
||||
"⚠️ 本阶段为并行研讨:请把你的产出**直接写在回复正文里**,不要写文件、不要执行沙箱命令——并行期间禁止文件写入,以免与同批其他席位互相打架。需要落文件的产物会留到后续串行 / 收口阶段单独处理。",
|
||||
);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* 总控「中转轮」派活提示(§12.3 Stage 间经总控中转 + 广播)。
|
||||
*
|
||||
* DAG 各 stage 之间插入一轮 leader:综合上一批并行席位的交付,产出一段「承上启下」
|
||||
* 说明,再作为下一 stage 席位 task 的上下文(见 {@link buildStageTask} 的
|
||||
* `priorIsBridge`)。下一批席位由编排计划**钉死**(已在 `nextSeatNames` 列出),
|
||||
* 故提示明确要求总控**不要自己派活、不要收口**——只做综合(前端照计划直派下一批)。
|
||||
*
|
||||
* 「传摘要按需传全文」:各席位真实交付由后端 `_collect_delivery_status`(轻量
|
||||
* `GET /last-ai-message?max_chars=N` 接口)实读后注入总控输入——中转轮默认只注入
|
||||
* 每席位 ~600 字**摘要**,完整交付正文留到最终收口的 synthesis 轮才按需读取。
|
||||
* 本提示因此不重复塞交付正文,保持总控上下文精简、响应快。
|
||||
*/
|
||||
export function buildDagTransitTask(args: {
|
||||
/** 刚完成的本批席位显示名(仅用于提示文案,真实交付由后端核对注入)。 */
|
||||
completedSeatNames: string[];
|
||||
/** 下一阶段由计划钉死、即将执行的席位显示名。 */
|
||||
nextSeatNames: string[];
|
||||
}): string {
|
||||
const { completedSeatNames, nextSeatNames } = args;
|
||||
const done = completedSeatNames.join("、") || "本批席位";
|
||||
const next = nextSeatNames.join("、") || "下一阶段席位";
|
||||
return [
|
||||
"【分层 DAG · 总控中转轮】本阶段并行席位已全部完成交付。",
|
||||
`已完成席位:${done}。系统已把各席位的真实交付(摘要)客观核对后注入到你本轮输入里,以此为准。`,
|
||||
"请你作为总控,综合这一批的交付,产出一段【承上启下】说明:提炼关键结论与未决问题,并给出对下一阶段的指引。",
|
||||
`下一阶段将由编排计划**钉死**执行的席位是:${next}。这些席位由系统按计划直接派活,` +
|
||||
"**你不需要、也不要**通过 agent_orchestration 自行派活,更不要现在收口或输出最终方案。",
|
||||
"只输出这段承上启下的综合说明即可——它会作为下一阶段席位承接前序结论的上下文。",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
// ── 总控驱动的「每 stage 派活轮」(§3.2 方案 A + 批内并行,2026-06-07 改)─────────
|
||||
//
|
||||
// 把 DAG 执行从「前端直派」改成「总控驱动」:每个 stage 由总控**真正派活**给该 stage
|
||||
// 计划钉死的席位(约束总控只派给这些席位、且每个都派到),席位并行执行、完成后交付经
|
||||
// 后端广播 + `_collect_delivery_status` 回到总控,总控下一 stage 继续派活。与 chain 模式
|
||||
// 同构(`buildChainLeaderTask` 单席位),区别是一次钉死**一批**席位、批内并行。
|
||||
|
||||
/**
|
||||
* 总控「每 stage 派活轮」提示:约束总控只对本 stage 钉死的若干席位派活(§3.2 方案 A)。
|
||||
*
|
||||
* - 首 stage(`isFirst`):带任务背景;后续 stage:靠后端注入的此前交付摘要承上。
|
||||
* - `seats` 是本 stage 计划钉死的席位(≥2 即并行批次),要求总控对**每个**席位都
|
||||
* 通过 agent_orchestration 派一个聚焦其职责的 task,不要派给清单外席位、不要自答 / 收口。
|
||||
*
|
||||
* 「传摘要按需传全文」:此处不塞各席位交付正文——后端 `_build_seat_status_block` 已把
|
||||
* 此前各席位的真实交付(摘要)注入总控本轮输入;完整正文留到末尾收口的 synthesis 轮。
|
||||
*/
|
||||
export function buildDagStageLeaderTask(args: {
|
||||
seedMessage: string;
|
||||
/** 0-based stage 序号。 */
|
||||
stageIndex: number;
|
||||
totalStages: number;
|
||||
/** 本 stage 计划钉死的席位。 */
|
||||
seats: Array<{ agentId: string; name: string }>;
|
||||
isFirst: boolean;
|
||||
}): string {
|
||||
const { seedMessage, stageIndex, totalStages, seats, isFirst } = args;
|
||||
const ordinal = `${stageIndex + 1}/${totalStages}`;
|
||||
const seatList = seats
|
||||
.map((s) => `「${s.name}」(agent_name: ${s.agentId})`)
|
||||
.join("、");
|
||||
const isParallel = seats.length > 1;
|
||||
const lines: string[] = [];
|
||||
if (isFirst) {
|
||||
lines.push("这是一次【分层 DAG 编排】的多智能体圆桌研讨。任务背景如下:", seedMessage, "");
|
||||
} else {
|
||||
lines.push(
|
||||
"分层研讨继续。系统已把此前各阶段席位的真实交付(摘要)客观核对后注入到你本轮输入里,请据此承上启下。",
|
||||
"",
|
||||
);
|
||||
}
|
||||
lines.push(
|
||||
`本研讨严格按预设分层顺序进行,共 ${totalStages} 个阶段,现在是第 ${ordinal} 个阶段。`,
|
||||
`本阶段需要执行的席位(已由编排计划钉死)是:${seatList}。`,
|
||||
`请你作为总控,通过 agent_orchestration 技能**分别**向上述${isParallel ? `这 ${seats.length} 个席位` : "席位"}派活,结合任务背景与此前交付,为每个席位分配聚焦其职责的本阶段任务。`,
|
||||
"只派给上述席位、且每个都必须派到;不要派给清单外的任何席位,也不要自己直接作答或给出最终结论。",
|
||||
"⚠️ 必须**真正调用 agent_orchestration 工具**来派活(每个席位对应一次工具调用);**不要**只用文字罗列「席位1:…席位2:…」这样的任务清单——只写文字而不调用工具,系统无法把任务下发给席位。",
|
||||
);
|
||||
if (isParallel) {
|
||||
lines.push(
|
||||
`注意:本阶段这 ${seats.length} 个席位会**并行**执行,请确保给每个席位的 task 都能独立完成,不要让它们互相等待。`,
|
||||
);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* 从总控「每 stage 派活轮」的终态里,取出派给**某个**钉死席位的 task 文本:
|
||||
* 1) 命中 agent_name === seatAgentId 的结构化派活(总控真调了 agent_orchestration 工具)
|
||||
* → 用它的 task(正常路径);
|
||||
* 2) 总控**没用工具、只写了文字**(弱模型常见,dispatched 为空 / 没命中该席位)→ **绝不**把
|
||||
* 总控的整段派活叙述喂给席位 —— 否则席位会把「我来调度…席位1/2/3」当成自己的任务照抄、
|
||||
* 模仿派活,甚至绕道 bash/python 调内部接口去派活(已在生产观测到)。改给一个**干净的本职
|
||||
* 任务**:任务背景与此前各阶段交付已由后端广播进席位线程上下文,席位据此承接即可。
|
||||
*
|
||||
* 所有分支都追加「角色边界护栏」,明确席位**不是总控、不许派活**(席位本就被 run policy 禁了
|
||||
* agent_orchestration,但弱模型会空转叙述 / 绕道,故再从提示层钉死)。
|
||||
*/
|
||||
export function pickDagSeatTask(
|
||||
dispatched: ReadonlyArray<readonly [string, string]>,
|
||||
seatAgentId: string,
|
||||
seatName: string,
|
||||
seedMessage = "",
|
||||
/** 是否已有前序席位交付(决定是否提示 read_peer_delivery 工具按需取全文,§12.9)。 */
|
||||
hasPeers = false,
|
||||
/**
|
||||
* 是否允许写文件(§12.10):
|
||||
* - `true`(**沙箱模式**):要求把交付**写成 .md 文件** + 正文摘要,禁 .py;
|
||||
* - `false`(**快速模式**,默认):产物**直接写在正文**,不写文件(fast 模式产物走正文)。
|
||||
*/
|
||||
allowFiles = false,
|
||||
): string {
|
||||
const guard =
|
||||
`\n\n【角色边界·必读】你是**执行席位**「${seatName}」,不是总控协调者,本轮**只**对你自己的交付负责。**严禁**任何形式的派活 / 调度:不要调用 agent_orchestration 或 skill_list,不要用 python / 脚本去访问内部接口(如 /api/agents、agent_orchestration)来调度,不要罗列或给其他席位分配任务清单、不要复述「我来调度各智能体」这类总控口吻。`;
|
||||
// 产物要求(§12.8 / §12.10):沙箱模式产出 .md 文件(禁 .py);快速模式产物走正文、不写文件。
|
||||
const fileRule = allowFiles
|
||||
? `\n\n【产物要求】请把你的**完整交付写成一个 Markdown(.md)文件**(用 write_file 写到 outputs 目录,文件名体现你的职责),并在回复正文里给出要点摘要。**不要写 .py 或任何可执行脚本文件**(不要写脚本去生成产物);直接产出成品文档,.md / .html / .txt 等其它格式都可以,唯独不要 .py。`
|
||||
: `\n\n【产物要求】本轮为**快速并行**模式:请把你的产物**直接写在回复正文里**,**不要写文件、不要执行脚本/命令**(需要落文件的产物留给沙箱模式或后续阶段)。`;
|
||||
// 任务背景:DAG 派活轮抑制了 leader 预广播(防席位模仿派活),所以席位 thread 里可能没有
|
||||
// 用户原始消息 —— 把任务背景直接写进席位 task,确保它有上下文(此前各阶段交付仍由后端
|
||||
// 席位间 detached 广播注入,故只补背景)。
|
||||
const bg = seedMessage.trim() ? `本次研讨的任务背景:\n${seedMessage.trim()}\n\n` : "";
|
||||
// §12.9:此前各阶段席位的交付,你默认只看到**摘要**(广播进来的);若某个前序席位的摘要不够、
|
||||
// 你需要它的**完整交付**,调用 read_peer_delivery('<席位名>') 按需取全文(平时不必调,优先用摘要)。
|
||||
const peerRule = hasPeers
|
||||
? `\n\n【按需取全文】此前各阶段席位的交付你默认只看到**摘要**;若需要某个前序席位的**完整交付**,调用工具 read_peer_delivery('<该席位名称>') 取回全文(摘要够用就不必调)。`
|
||||
: "";
|
||||
const wanted = seatAgentId.toLowerCase();
|
||||
const exact = dispatched.find(([name]) => name.toLowerCase() === wanted);
|
||||
if (exact && exact[1]?.trim()) {
|
||||
return `${bg}请你作为「${seatName}」,完成总控派给你的本阶段任务:\n${exact[1].trim()}${fileRule}${peerRule}${guard}`;
|
||||
}
|
||||
// dispatched 为空 / 未命中 → 干净本职任务,**不**注入总控派活叙述(根治「席位模仿派活」)。
|
||||
return (
|
||||
`${bg}请你作为「${seatName}」,从你的专业职责出发,独立完成本阶段属于你的分析与交付。` +
|
||||
`此前各阶段席位的交付已在你的会话上下文里,请据此承接。` +
|
||||
fileRule +
|
||||
peerRule +
|
||||
guard
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user