org-graph-service.js
18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
/**
* Org Graph Service — 公司级 workflow 图的读写与合法性校验(P2 / T2)
*
* 设计见 docs/todo/system-design/27-p2-org-graph.md §3.3(四项校验)+ §4.3(API)。
*
* 模型要点(v0.4):org_graph 是**执行流图**,不是汇报结构。
* - 节点 = 公司对某个 system_agent 的引用(role_name 在同一公司内唯一,仅约束 active 行)
* - 边 = condition ∈ {success, fail} 的执行流转,edge_kind ∈ {forward, backward}
* - 删除一律软删除(status='removed'),从不物理删行,保留审计轨迹
*
* 对外的 roleName / id 约定(容易踩坑,先看这里):
* - writeGraph / patchGraph / validateGraph 的入参边用 **roleName** 表达 from/to
* (规划 agent 手里只有角色名,拿不到数据库自增 id)
* - getGraph 返回的边用 **节点数字 id** 表达 from/to(前端画布/执行引擎按 id 索引)
*/
const { getDb } = require('./graph-db');
const { upsertOrgGraphNode } = require('./graph-service');
const CONDITIONS = ['success', 'fail'];
const EDGE_KINDS = ['forward', 'backward'];
// 用于在事务里主动回滚(better-sqlite3 的 transaction() 靠抛异常回滚)
class GraphRollback extends Error {
constructor(errors) {
super('org graph validation failed');
this.errors = errors;
}
}
// ────────────────────────────────────────────────────────────────
// 入参归一化
// ────────────────────────────────────────────────────────────────
/** 节点入参既接受 'code-coder' 字符串,也接受 {roleName, systemAgentId?} */
function normalizeNodes(nodes) {
return (nodes || []).map((n) => {
const roleName = typeof n === 'string' ? n : n && n.roleName;
const systemAgentId = (typeof n === 'object' && n && n.systemAgentId) || roleName;
return { roleName, systemAgentId };
});
}
/** 边入参:condition 缺省按 'success',edgeKind 缺省按 'forward'(也认下划线写法 edge_kind) */
function normalizeEdges(edges) {
return (edges || []).map((e) => ({
from: e.from,
to: e.to,
condition: e.condition || 'success',
edgeKind: e.edgeKind || e.edge_kind || 'forward',
}));
}
// ────────────────────────────────────────────────────────────────
// §3.3 四项校验
// ────────────────────────────────────────────────────────────────
/**
* 校验一张图是否结构合法。
*
* 四条规则(rule 字段取值):
* 'acyclic' 仅看 forward 边,三色 DFS 判环
* 'single-entry' forward 边意义下入度为 0 的节点必须恰好一个
* 'reachable' 所有节点都要从入口沿 forward 边可达
* 'backward-labeled' 真正的回退边必须标 edge_kind='backward',标注由本函数独立复核
* 另有两条前置的形态检查:'schema'(缺字段/重名/枚举越界)、'reference'(边引用了不存在的节点)。
*
* @param {Array} nodes [{roleName, systemAgentId?}] 或 ['roleName', ...]
* @param {Array} edges [{from, to, condition, edgeKind?}],from/to 是 roleName
* @returns {{ok: boolean, errors: Array<{rule: string, detail: string}>}}
*/
function validateGraph(nodes, edges) {
const errors = [];
const ns = normalizeNodes(nodes);
const es = normalizeEdges(edges);
// ── 前置:形态与引用完整性(不通过就没法做后面的图论校验,直接返回)
const names = [];
const nameSet = new Set();
for (const n of ns) {
if (!n.roleName || typeof n.roleName !== 'string') {
errors.push({ rule: 'schema', detail: `节点缺少 roleName: ${JSON.stringify(n)}` });
continue;
}
if (nameSet.has(n.roleName)) {
errors.push({ rule: 'schema', detail: `节点 roleName 重复: ${n.roleName}` });
continue;
}
nameSet.add(n.roleName);
names.push(n.roleName);
}
for (const e of es) {
const label = `${e.from} -> ${e.to}`;
if (!nameSet.has(e.from) || !nameSet.has(e.to)) {
errors.push({ rule: 'reference', detail: `边 ${label} 引用了图中不存在的节点` });
}
if (!CONDITIONS.includes(e.condition)) {
errors.push({ rule: 'schema', detail: `边 ${label} 的 condition 非法: ${e.condition}` });
}
if (!EDGE_KINDS.includes(e.edgeKind)) {
errors.push({ rule: 'schema', detail: `边 ${label} 的 edgeKind 非法: ${e.edgeKind}` });
}
}
if (errors.length > 0) return { ok: false, errors };
// 空图合法:允许 patchGraph 把一张图清空(否则"删掉最后一个节点"永远做不到)
if (names.length === 0) return { ok: true, errors: [] };
const idx = new Map(names.map((name, i) => [name, i]));
const forward = es.filter((e) => e.edgeKind === 'forward');
const fwdAdj = names.map(() => []);
for (const e of forward) fwdAdj[idx.get(e.from)].push(idx.get(e.to));
// ── 规则 1:无环(三色 DFS,思路同 devloop/doc-store.js 的 hasCycle)
const color = new Array(names.length).fill(0); // 0=white 1=gray 2=black
let cycleEdge = null;
const visit = (i) => {
if (cycleEdge || color[i] === 2) return;
color[i] = 1;
for (const j of fwdAdj[i]) {
if (color[j] === 1) {
cycleEdge = `${names[i]} -> ${names[j]}`;
return;
}
if (color[j] === 0) visit(j);
if (cycleEdge) return;
}
color[i] = 2;
};
for (let i = 0; i < names.length && !cycleEdge; i++) if (color[i] === 0) visit(i);
if (cycleEdge) {
errors.push({ rule: 'acyclic', detail: `forward 边构成环,闭合于 ${cycleEdge}` });
}
// ── 规则 2:单一入口(forward 边意义下入度为 0 的节点恰好一个)
const indeg = new Array(names.length).fill(0);
for (const e of forward) indeg[idx.get(e.to)] += 1;
const entries = names.filter((_, i) => indeg[i] === 0);
if (entries.length !== 1) {
errors.push({
rule: 'single-entry',
detail:
entries.length === 0
? '没有入度为 0 的节点(forward 边构成环时会出现),任务无法确定从哪进入'
: `入度为 0 的节点有 ${entries.length} 个:${entries.join(', ')},必须恰好一个`,
});
}
// ── 规则 3:可达性(从入口沿 forward 边 BFS;多入口时取声明序第一个,保证报错可复现)
if (entries.length > 0) {
const seen = new Set([idx.get(entries[0])]);
const queue = [idx.get(entries[0])];
while (queue.length > 0) {
for (const j of fwdAdj[queue.shift()]) {
if (!seen.has(j)) {
seen.add(j);
queue.push(j);
}
}
}
const orphans = names.filter((_, i) => !seen.has(i));
if (orphans.length > 0) {
errors.push({
rule: 'reachable',
detail: `节点从入口 ${entries[0]} 不可达:${orphans.join(', ')}`,
});
}
}
// ── 规则 4:回退边必须显式标注(不信任调用方的 edgeKind,按图结构独立复核)
// 判据:边 u→v 是回退边 ⟺ u===v(自环),或去掉这条边之后 v 仍能沿 forward 边回到 u
// (即这条边闭合了一个循环)。用可达性而不是某一个具体拓扑序,是因为拓扑序不唯一,
// 用它判"更早"会让同一张图的校验结果依赖节点声明顺序。
// ponytail: 每条边一次 DFS,O(E·(V+E))。org graph 是十几个节点的量级,不值得建支配树/SCC。
const reachesWithout = (startIdx, targetIdx, skipEdge) => {
const seen = new Set([startIdx]);
const stack = [startIdx];
while (stack.length > 0) {
const cur = stack.pop();
if (cur === targetIdx && cur !== startIdx) return true;
for (const e of forward) {
if (e === skipEdge) continue;
if (idx.get(e.from) !== cur) continue;
const nxt = idx.get(e.to);
if (nxt === targetIdx) return true;
if (!seen.has(nxt)) {
seen.add(nxt);
stack.push(nxt);
}
}
}
return false;
};
for (const e of es) {
const isLoopClosing = e.from === e.to || reachesWithout(idx.get(e.to), idx.get(e.from), e);
if (isLoopClosing && e.edgeKind !== 'backward') {
errors.push({
rule: 'backward-labeled',
detail: `边 ${e.from} -> ${e.to} 指向了拓扑序更早的节点(构成回路),edge_kind 必须是 'backward'`,
});
} else if (!isLoopClosing && e.edgeKind === 'backward') {
errors.push({
rule: 'backward-labeled',
detail: `边 ${e.from} -> ${e.to} 并不构成回路,不应标注为 'backward'`,
});
}
}
return { ok: errors.length === 0, errors };
}
// ────────────────────────────────────────────────────────────────
// 落库
// ────────────────────────────────────────────────────────────────
/** 该公司当前 active 节点:roleName -> id */
function activeNodeIds(db, companyId) {
const rows = db
.prepare(`SELECT id, role_name FROM org_graph_nodes WHERE company_id = ? AND status = 'active'`)
.all(companyId);
return new Map(rows.map((r) => [r.role_name, r.id]));
}
/** 插入一个 active 节点并返回它的 id(复用 P1 的 upsert,顺带补 system_agents 缺失行) */
function insertNode(db, companyId, node) {
upsertOrgGraphNode(companyId, node.systemAgentId || node.roleName, node.roleName);
const row = db
.prepare(
`SELECT id FROM org_graph_nodes WHERE company_id = ? AND role_name = ? AND status = 'active'`
)
.get(companyId, node.roleName);
return row ? row.id : null;
}
function insertEdge(db, companyId, fromId, toId, edge, now) {
db.prepare(`
INSERT INTO org_graph_edges (company_id, from_node_id, to_node_id, condition, edge_kind, status, created_at)
VALUES (@company_id, @from_node_id, @to_node_id, @condition, @edge_kind, 'active', @created_at)
ON CONFLICT(company_id, from_node_id, to_node_id, condition) WHERE status = 'active' DO NOTHING
`).run({
company_id: companyId,
from_node_id: fromId,
to_node_id: toId,
condition: edge.condition,
edge_kind: edge.edgeKind,
created_at: now,
});
}
/**
* 整体写入:先过 §3.3 四项校验,通过后在一个事务里把该公司已有的 active 图整体作废,
* 再写入新的 nodes / edges。校验不通过一行都不落库。
*
* @param {string} companyId
* @param {{nodes: Array, edges: Array}} graph 边的 from/to 是 roleName
* @returns {{ok: boolean, errors?: Array, nodeCount?: number, edgeCount?: number}}
*/
function writeGraph(companyId, { nodes = [], edges = [] } = {}) {
const ns = normalizeNodes(nodes);
const es = normalizeEdges(edges);
const verdict = validateGraph(ns, es);
if (!verdict.ok) return { ok: false, errors: verdict.errors };
const db = getDb();
const now = new Date().toISOString();
db.transaction(() => {
db.prepare(
`UPDATE org_graph_edges SET status = 'removed' WHERE company_id = ? AND status = 'active'`
).run(companyId);
db.prepare(
`UPDATE org_graph_nodes SET status = 'removed' WHERE company_id = ? AND status = 'active'`
).run(companyId);
const ids = new Map();
for (const n of ns) ids.set(n.roleName, insertNode(db, companyId, n));
for (const e of es) insertEdge(db, companyId, ids.get(e.from), ids.get(e.to), e, now);
})();
return { ok: true, nodeCount: ns.length, edgeCount: es.length };
}
/**
* 增量修改。所有改动落在一个事务里,改完之后整张图重新过一遍 §3.3 校验,
* 不合法则整体回滚并返回 errors(调用方看到的库还是改动前的样子)。
*
* @param {string} companyId
* @param {{addNodes?: Array, removeNodes?: string[], addEdges?: Array, removeEdges?: Array}} patch
* addNodes [{roleName, systemAgentId?}]
* removeNodes ['roleName', ...](连带级联失效相关边)
* addEdges [{from, to, condition, edgeKind?}],from/to 是 roleName
* removeEdges [{from, to, condition?}],condition 缺省时删掉这对节点之间所有 active 边
* @returns {{ok: boolean, errors?: Array}}
*/
function patchGraph(companyId, patch = {}) {
const db = getDb();
const now = new Date().toISOString();
const addNodes = normalizeNodes(patch.addNodes);
const addEdges = normalizeEdges(patch.addEdges);
const removeNodes = (patch.removeNodes || []).map((n) => (typeof n === 'string' ? n : n.roleName));
const removeEdges = patch.removeEdges || [];
try {
db.transaction(() => {
// 1. 加节点(幂等:同名 active 节点已存在时 upsert 不产生第二行)
for (const n of addNodes) insertNode(db, companyId, n);
// 2. 删边
let ids = activeNodeIds(db, companyId);
for (const e of removeEdges) {
const fromId = ids.get(e.from);
const toId = ids.get(e.to);
if (fromId == null || toId == null) continue;
db.prepare(`
UPDATE org_graph_edges SET status = 'removed'
WHERE company_id = ? AND from_node_id = ? AND to_node_id = ? AND status = 'active'
AND (? IS NULL OR condition = ?)
`).run(companyId, fromId, toId, e.condition || null, e.condition || null);
}
// 3. 删节点(级联失效它的进出边,避免留下悬边)
for (const roleName of removeNodes) removeNodeIn(db, companyId, roleName);
// 4. 加边
ids = activeNodeIds(db, companyId);
for (const e of addEdges) {
const fromId = ids.get(e.from);
const toId = ids.get(e.to);
if (fromId == null || toId == null) {
throw new GraphRollback([
{ rule: 'reference', detail: `边 ${e.from} -> ${e.to} 引用了不存在的 active 节点` },
]);
}
insertEdge(db, companyId, fromId, toId, e, now);
}
// 5. 改完的整张图必须仍然合法
const graph = readGraph(db, companyId);
const verdict = validateGraph(
graph.nodes.map((n) => ({ roleName: n.roleName, systemAgentId: n.systemAgentId })),
graph.edges.map((e) => ({
from: graph.nameById.get(e.from),
to: graph.nameById.get(e.to),
condition: e.condition,
edgeKind: e.edgeKind,
}))
);
if (!verdict.ok) throw new GraphRollback(verdict.errors);
})();
} catch (err) {
if (err instanceof GraphRollback) return { ok: false, errors: err.errors };
throw err;
}
return { ok: true };
}
/** 内部读:多返回一个 nameById,供 patchGraph 把 id 边翻回 roleName 边 */
function readGraph(db, companyId) {
const nodeRows = db
.prepare(`
SELECT id, role_name, system_agent_id, status FROM org_graph_nodes
WHERE company_id = ? AND status = 'active' ORDER BY id
`)
.all(companyId);
const nameById = new Map(nodeRows.map((r) => [r.id, r.role_name]));
const edgeRows = db
.prepare(`
SELECT from_node_id, to_node_id, condition, edge_kind FROM org_graph_edges
WHERE company_id = ? AND status = 'active' ORDER BY id
`)
.all(companyId)
// 防御:节点被物理清理/异常状态时不返回悬边
.filter((r) => nameById.has(r.from_node_id) && nameById.has(r.to_node_id));
return {
nodes: nodeRows.map((r) => ({
id: r.id,
roleName: r.role_name,
systemAgentId: r.system_agent_id,
status: r.status,
})),
edges: edgeRows.map((r) => ({
from: r.from_node_id,
to: r.to_node_id,
condition: r.condition,
edgeKind: r.edge_kind,
})),
nameById,
};
}
/**
* 只读查询。边的 from/to 是节点数字 id(§4.3 的 GET 返回形状)。
* 公司不存在 / 没有图时返回空图,不抛错。
*
* @param {string} companyId
* @returns {{nodes: Array<{id, roleName, systemAgentId, status}>, edges: Array<{from, to, condition, edgeKind}>}}
*/
function getGraph(companyId) {
const { nodes, edges } = readGraph(getDb(), companyId);
return { nodes, edges };
}
/** removeNode 的事务内实现(patchGraph 复用),返回失效掉的边数;节点不存在返回 null */
function removeNodeIn(db, companyId, roleName) {
const row = db
.prepare(
`SELECT id FROM org_graph_nodes WHERE company_id = ? AND role_name = ? AND status = 'active'`
)
.get(companyId, roleName);
if (!row) return null;
const res = db
.prepare(`
UPDATE org_graph_edges SET status = 'removed'
WHERE company_id = ? AND status = 'active' AND (from_node_id = ? OR to_node_id = ?)
`)
.run(companyId, row.id, row.id);
db.prepare(`UPDATE org_graph_nodes SET status = 'removed' WHERE id = ?`).run(row.id);
return res.changes;
}
/**
* 软删除一个节点,并级联把它的进出 active 边一并置 'removed'(否则 getGraph 会返回悬边)。
*
* 刻意**不**做 §3.3 校验:fire 是既成事实,不能因为"删完图不合法"而拒绝解雇。
* 删完的图可能是多入口/有孤立节点的,由后续 patchGraph 或重跑 orggraph-planning 修复。
*
* @returns {{ok: boolean, nodeId?: number, removedEdges?: number, errors?: Array}}
*/
function removeNode(companyId, roleName) {
const db = getDb();
let nodeId = null;
let removedEdges = null;
db.transaction(() => {
const before = db
.prepare(
`SELECT id FROM org_graph_nodes WHERE company_id = ? AND role_name = ? AND status = 'active'`
)
.get(companyId, roleName);
if (!before) return;
nodeId = before.id;
removedEdges = removeNodeIn(db, companyId, roleName);
})();
if (nodeId == null) {
return {
ok: false,
errors: [{ rule: 'reference', detail: `公司 ${companyId} 没有 active 节点 ${roleName}` }],
};
}
return { ok: true, nodeId, removedEdges };
}
module.exports = {
validateGraph,
writeGraph,
patchGraph,
getGraph,
removeNode,
};