@suifei/dsh-ai-team 0.4.87 → 0.4.88
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/index.js +1 -34
- package/lib/host/service.js +1596 -1596
- package/lib/ledger/fold.js +1117 -1117
- package/lib/runtime/member-runtime.js +190 -318
- package/package.json +1 -1
package/lib/host/service.js
CHANGED
|
@@ -1,1596 +1,1596 @@
|
|
|
1
|
-
import { checkWorkspacePath } from './workspace-path.js';
|
|
2
|
-
import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
|
3
|
-
import pathDefault from 'node:path';
|
|
4
|
-
import { ERRORS, fail } from '../domain/errors.js';
|
|
5
|
-
import { findReportPath, parseDecisionQuestions } from './decision-report.js';
|
|
6
|
-
import { ids } from '../domain/ids.js';
|
|
7
|
-
import { ackInboxItem, createInboxItem, isInformationalThreadMention } from '../domain/inbox.js';
|
|
8
|
-
import { chooseDecisionAnswers } from './pmo.js';
|
|
9
|
-
import {
|
|
10
|
-
acceptTask,
|
|
11
|
-
assignTask,
|
|
12
|
-
cancelTask,
|
|
13
|
-
claimTask,
|
|
14
|
-
createTask,
|
|
15
|
-
deleteTask,
|
|
16
|
-
reassignTask,
|
|
17
|
-
releaseTask,
|
|
18
|
-
reopenTask,
|
|
19
|
-
requestChangesTask,
|
|
20
|
-
submitTask,
|
|
21
|
-
} from '../domain/task.js';
|
|
22
|
-
import { appendReply, createThread } from '../domain/thread.js';
|
|
23
|
-
import { boardView, quadrantsView, taskCard } from './views.js';
|
|
24
|
-
import { applyMemberConfigPatch, normalizeMemberConfig } from '../domain/member-config.js';
|
|
25
|
-
import { MEMBER_STATUS } from '../ledger/fold.js';
|
|
26
|
-
|
|
27
|
-
const MEMBER_STATUS_VALUES = new Set(Object.values(MEMBER_STATUS));
|
|
28
|
-
import { isQaMember, unfinishedTasksFor } from '../domain/member-profile.js';
|
|
29
|
-
|
|
30
|
-
function mentionsHuman(body) {
|
|
31
|
-
return typeof body === 'string'
|
|
32
|
-
&& /(^|[^A-Za-z])(human|@你|待你|需要你|请你|等你|你拍板)([^A-Za-z]|$)/i.test(body);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Team domain service on top of a Project ledger.
|
|
37
|
-
*
|
|
38
|
-
* The ledger is the single writer and owns `state`; this service only:
|
|
39
|
-
* 1. reads the current view from `ledger.state`,
|
|
40
|
-
* 2. validates the command with the pure domain rules,
|
|
41
|
-
* 3. appends one event and returns the committed result.
|
|
42
|
-
*
|
|
43
|
-
* `ledger.append` must update `ledger.state` before resolving (or provide a
|
|
44
|
-
* synchronous state read after an awaited append).
|
|
45
|
-
*/
|
|
46
|
-
/**
|
|
47
|
-
* P6 交接文档:按时序拼接 Human 指令与全部任务关键信息,写入项目工作
|
|
48
|
-
* 目录(交付给别的工具继续开发);账本留痕记录路径。
|
|
49
|
-
*/
|
|
50
|
-
// P6 交接文档生成:Human 指令时序 + 任务全量关键信息,Markdown 落盘。
|
|
51
|
-
function handoffMarkdown(state, project, nowMs) {
|
|
52
|
-
const line = (text) => String(text ?? '').replace(/\r?\n/g, '\n ');
|
|
53
|
-
const out = [];
|
|
54
|
-
out.push(`# 项目交接文档 — ${project.name}`);
|
|
55
|
-
out.push('');
|
|
56
|
-
out.push(`- 生成时间:${new Date(nowMs).toISOString()}`);
|
|
57
|
-
out.push(`- 项目 id:${project.id}`);
|
|
58
|
-
out.push(`- 目标:${project.goal ?? '(未填写)'}`);
|
|
59
|
-
out.push(`- 工作目录:${project.workspacePath}`);
|
|
60
|
-
out.push(`- 运行态:${project.runState === 'stopped' ? '已停止(交接前)' : '运行中'}`);
|
|
61
|
-
out.push('');
|
|
62
|
-
out.push('## 一、Human 指令时序(按账本顺序)');
|
|
63
|
-
out.push('');
|
|
64
|
-
const humanMessages = (state.stream ?? []).filter((entry) => entry.kind === 'human_message');
|
|
65
|
-
if (humanMessages.length === 0) out.push('(无 Human 指令记录)');
|
|
66
|
-
for (const entry of humanMessages) {
|
|
67
|
-
out.push(`- ${new Date(entry.at ?? 0).toISOString()} — ${line(entry.body)}`);
|
|
68
|
-
}
|
|
69
|
-
out.push('');
|
|
70
|
-
out.push('## 二、任务清单(含状态与验收要点)');
|
|
71
|
-
out.push('');
|
|
72
|
-
const tasks = Object.values(state.tasks ?? {}).filter((task) => task.tombstone !== true)
|
|
73
|
-
.sort((left, right) => (left.createdAt ?? 0) - (right.createdAt ?? 0));
|
|
74
|
-
if (tasks.length === 0) out.push('(无任务)');
|
|
75
|
-
for (const task of tasks) {
|
|
76
|
-
out.push(`### #${task.number ?? task.id} ${task.title} — ${task.status}`);
|
|
77
|
-
out.push(`- 结果定义:${line(task.resultDefinition)}`);
|
|
78
|
-
if (task.summary) out.push(`- 提交摘要:${line(task.summary)}`);
|
|
79
|
-
for (const ev of task.evidence ?? []) out.push(`- 证据(${ev.kind}):${line(ev.value)}`);
|
|
80
|
-
if (task.qaChecks?.length) out.push(`- QA 检查:${task.qaChecks.map((c) => `${c.passed ? '✔' : '✘'} ${line(c.text ?? '')}`).join(';')}`);
|
|
81
|
-
if (task.reason) out.push(`- 最近理由:${line(task.reason)}`);
|
|
82
|
-
out.push(`- 责任位:owner=${task.ownerId ?? '—'};assignee=${task.assigneeId ?? '—'};更新于 ${new Date(task.updatedAt ?? 0).toISOString()}`);
|
|
83
|
-
out.push('');
|
|
84
|
-
}
|
|
85
|
-
out.push('## 三、Thread 关键讨论(按任务)');
|
|
86
|
-
out.push('');
|
|
87
|
-
for (const [taskId, thread] of Object.entries(state.threads ?? {})) {
|
|
88
|
-
const entries = thread.entries ?? [];
|
|
89
|
-
if (entries.length === 0) continue;
|
|
90
|
-
out.push(`### Task ${taskId}`);
|
|
91
|
-
for (const entry of entries.slice(-20)) {
|
|
92
|
-
out.push(`- ${new Date(entry.at ?? 0).toISOString()} ${entry.author ?? entry.authorId ?? '—'}:${line(entry.body)}`);
|
|
93
|
-
}
|
|
94
|
-
out.push('');
|
|
95
|
-
}
|
|
96
|
-
out.push('## 四、接手提示');
|
|
97
|
-
out.push('');
|
|
98
|
-
out.push('- 以上内容来自插件账本投影(append-only,时序可信);接手工具可直接在工作目录继续开发。');
|
|
99
|
-
out.push('- 成员的 DSH 会话仍在,如需复用团队请保持项目 runState;如改用其他工具,可停止本项目。');
|
|
100
|
-
return out.join('\n') + '\n';
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* 成员引用的统一校验:幽灵 id 写进投影后没有修复命令,卡片会永久挂在不存在的人名下。
|
|
105
|
-
* `agentOnly` 用于只能由 Agent 担任的字段(assignee)。
|
|
106
|
-
*/
|
|
107
|
-
export function requireMemberRef(state, memberId, field, { agentOnly = false } = {}) {
|
|
108
|
-
if (typeof memberId !== 'string' || memberId === '') return;
|
|
109
|
-
const candidate = state?.members?.[memberId];
|
|
110
|
-
if (candidate === undefined) fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} is not a Team member`);
|
|
111
|
-
if (agentOnly && candidate.kind !== 'agent') fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} is not an agent member`);
|
|
112
|
-
if (candidate.status === 'retired') fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} has left the team`);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
export class TeamService {
|
|
116
|
-
/**
|
|
117
|
-
* @param {{ ledger: { state: any, append: (input: any) => Promise<any> }, now?: () => number, diag?: { append: (row: any) => any } }} options
|
|
118
|
-
*/
|
|
119
|
-
constructor(options) {
|
|
120
|
-
this.ledger = options.ledger;
|
|
121
|
-
this.now = options.now ?? (() => Date.now());
|
|
122
|
-
this.memberConfigPolicy = options.memberConfigPolicy ?? {};
|
|
123
|
-
/** Diagnostic sink ({ append(row) }); optional so tests run without it. */
|
|
124
|
-
this.diag = options.diag ?? null;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
get state() {
|
|
128
|
-
return this.ledger.state;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/**
|
|
132
|
-
* Serialize a mutation that must observe a fresh projection across an await.
|
|
133
|
-
* `ledger.append` is async, so two concurrent dispatches can both read the
|
|
134
|
-
* same pre-append projection. A rejected run never poisons the chain.
|
|
135
|
-
*/
|
|
136
|
-
runExclusive(work) {
|
|
137
|
-
const run = this.exclusive ?? Promise.resolve();
|
|
138
|
-
const result = run.then(work, work);
|
|
139
|
-
this.exclusive = result.then(() => undefined, () => undefined);
|
|
140
|
-
return result;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
/** The Human member id, derived once per call from the folded state. */
|
|
144
|
-
humanId() {
|
|
145
|
-
return this.state.humanMemberId
|
|
146
|
-
?? Object.values(this.state.members ?? {}).find((member) => member.kind === 'human')?.id
|
|
147
|
-
?? null;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/** Four-column board derived from the same ledger state. */
|
|
151
|
-
board(projectId, options = {}) {
|
|
152
|
-
if (projectId !== undefined && this.state.projects?.[projectId] === undefined) {
|
|
153
|
-
fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
154
|
-
}
|
|
155
|
-
return boardView(this.state, options);
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/** Four-quadrant situation view; Human is the only attention target. */
|
|
159
|
-
quadrants(projectId, options = {}) {
|
|
160
|
-
if (projectId !== undefined && this.state.projects?.[projectId] === undefined) {
|
|
161
|
-
fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
162
|
-
}
|
|
163
|
-
const human = options.humanMemberId ?? this.humanId() ?? 'mem_human';
|
|
164
|
-
return quadrantsView(this.state, { ...options, humanMemberId: human });
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
/** One page of workbench state; the UI reads this instead of the ledger. */
|
|
168
|
-
bootstrap(projectId, threadTaskId) {
|
|
169
|
-
const state = this.state;
|
|
170
|
-
// 归档项目仍要被「看见」:列表里过滤掉它们,但存在性判定必须用未过滤的
|
|
171
|
-
// 记录——否则归归档项目会被报成 E_NOT_FOUND,与 board()/quadrants() 的口径
|
|
172
|
-
// 打架,且客户端把归档项目渲染成可点的只读行,选中即失败。
|
|
173
|
-
const allProjectRecords = Object.values(state.projects ?? {});
|
|
174
|
-
const projects = allProjectRecords
|
|
175
|
-
.filter((p) => p.status !== 'archived')
|
|
176
|
-
.map((p) => ({
|
|
177
|
-
id: p.id, name: p.name, goal: p.goal ?? '', owner: p.ownerName ?? p.ownerMemberId ?? p.ownerId, workspacePath: p.workspacePath ?? '', pmoAuto: p.pmoAuto !== false, active: p.status !== 'archived',
|
|
178
|
-
runState: p.runState === 'stopped' ? 'stopped' : 'running',
|
|
179
|
-
}));
|
|
180
|
-
const members = Object.values(state.members ?? {}).map((m) => ({
|
|
181
|
-
id: m.id,
|
|
182
|
-
name: m.name,
|
|
183
|
-
role: m.role ?? '',
|
|
184
|
-
status: m.status ?? 'idle',
|
|
185
|
-
kind: m.kind ?? 'agent',
|
|
186
|
-
sessionId: m.sessionId ?? null,
|
|
187
|
-
preset: m.config?.preset ?? m.preset ?? 'standard',
|
|
188
|
-
personality: m.personality ?? '',
|
|
189
|
-
notes: m.notes ?? [],
|
|
190
|
-
skills: m.skills ?? [],
|
|
191
|
-
profileVersion: m.profileVersion ?? 1,
|
|
192
|
-
distillVersion: m.distillVersion ?? 0,
|
|
193
|
-
distilledAt: m.distilledAt ?? null,
|
|
194
|
-
talentPool: m.talentPool === true,
|
|
195
|
-
leftTeamAt: m.leftTeamAt ?? null,
|
|
196
|
-
qa: isQaMember(m),
|
|
197
|
-
config: m.config ?? null,
|
|
198
|
-
configVersion: m.configVersion ?? 0,
|
|
199
|
-
lastFailure: m.lastFailure ?? null,
|
|
200
|
-
attempts: m.attempts ?? 0,
|
|
201
|
-
lastRecoveredAt: m.lastRecoveredAt ?? null,
|
|
202
|
-
}));
|
|
203
|
-
const agents = members.filter((m) => m.kind !== 'human');
|
|
204
|
-
// One Task card shape for board, quadrants and bootstrap; bootstrap only
|
|
205
|
-
// adds the submission bookkeeping the panel needs.
|
|
206
|
-
const tasks = Object.values(state.tasks ?? {})
|
|
207
|
-
.filter((task) => task.tombstone !== true && task.status !== 'deleted')
|
|
208
|
-
.map((task) => ({ ...taskCard(state, task), qaChecks: task.qaChecks ?? [] }));
|
|
209
|
-
const project = projectId === undefined ? projects[0] : projects.find((p) => p.id === projectId);
|
|
210
|
-
// 与 board/quadrants 同口径:显式给了**不存在**的 projectId 必须报错,不能返回
|
|
211
|
-
// 一个 project:null 的空壳让调用方分不清「项目不存在」和「空项目」。
|
|
212
|
-
// 存在性按未过滤记录判定:归档项目是「已归档」,不是「不存在」。
|
|
213
|
-
if (projectId !== undefined && state.projects?.[projectId] === undefined) {
|
|
214
|
-
fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
215
|
-
}
|
|
216
|
-
// 归档项目:仍返回它的只读视图(列表里不出现,但请求它时可用)。
|
|
217
|
-
const archivedProject = projectId !== undefined && project === undefined
|
|
218
|
-
? {
|
|
219
|
-
id: projectId,
|
|
220
|
-
name: state.projects[projectId].name ?? projectId,
|
|
221
|
-
goal: state.projects[projectId].goal ?? '',
|
|
222
|
-
owner: state.projects[projectId].ownerName ?? state.projects[projectId].ownerMemberId ?? null,
|
|
223
|
-
workspacePath: state.projects[projectId].workspacePath ?? '',
|
|
224
|
-
pmoAuto: state.projects[projectId].pmoAuto !== false,
|
|
225
|
-
active: false,
|
|
226
|
-
archived: true,
|
|
227
|
-
runState: state.projects[projectId].runState === 'stopped' ? 'stopped' : 'running',
|
|
228
|
-
}
|
|
229
|
-
: null;
|
|
230
|
-
const selectedProject = project ?? archivedProject ?? undefined;
|
|
231
|
-
// 大规模/长迭代裁剪:面板只需要最近的窗口,全史在账本里按需取。
|
|
232
|
-
// stream 投影本身已封顶(≤500),bootstrap 再按窗口切尾。
|
|
233
|
-
const stream = selectedProject === undefined
|
|
234
|
-
? []
|
|
235
|
-
: (state.stream ?? [])
|
|
236
|
-
.filter((entry) => entry.projectId === selectedProject.id)
|
|
237
|
-
.slice(-200)
|
|
238
|
-
// 客户端按对象读作者(`item.author.kind` / `.name`),账本只有 authorId:
|
|
239
|
-
// 在这里补成 { id, kind, name },否则主对话与 Thread 的作者恒为「—」,
|
|
240
|
-
// human 判定也永远是 false。
|
|
241
|
-
.map((entry) => {
|
|
242
|
-
const member = state.members?.[entry.authorId];
|
|
243
|
-
return {
|
|
244
|
-
...entry,
|
|
245
|
-
author: {
|
|
246
|
-
id: entry.authorId ?? null,
|
|
247
|
-
kind: member?.kind ?? entry.authorKind ?? 'agent',
|
|
248
|
-
name: member?.name ?? entry.authorId ?? '',
|
|
249
|
-
},
|
|
250
|
-
};
|
|
251
|
-
});
|
|
252
|
-
const selected = threadTaskId ?? tasks.find((task) => task.status === 'in_progress')?.id ?? tasks[0]?.id;
|
|
253
|
-
const threadOf = (taskId) => {
|
|
254
|
-
const full = taskId === undefined || taskId === null ? undefined : state.threads?.[taskId];
|
|
255
|
-
if (full === undefined) return { taskId, headSeq: 0, entries: [], entryTotal: 0 };
|
|
256
|
-
const entries = Array.isArray(full.entries) ? full.entries : [];
|
|
257
|
-
return { ...full, entries: entries.slice(-50), entryTotal: full.headSeq ?? entries.length };
|
|
258
|
-
};
|
|
259
|
-
const thread = selected === undefined ? null : threadOf(selected);
|
|
260
|
-
const threads = Object.fromEntries(tasks.map((task) => [task.id, threadOf(task.id)]));
|
|
261
|
-
const inbox = Object.values(state.inbox ?? {}).filter((item) =>
|
|
262
|
-
(item.memberId === this.humanId())
|
|
263
|
-
&& !isInformationalThreadMention(item));
|
|
264
|
-
return {
|
|
265
|
-
project: selectedProject ?? null,
|
|
266
|
-
projects,
|
|
267
|
-
agents,
|
|
268
|
-
members,
|
|
269
|
-
tasks,
|
|
270
|
-
stream,
|
|
271
|
-
thread,
|
|
272
|
-
threads,
|
|
273
|
-
inbox,
|
|
274
|
-
board: selectedProject === undefined ? null : this.board(selectedProject.id),
|
|
275
|
-
quadrants: selectedProject === undefined ? null : this.quadrants(selectedProject.id),
|
|
276
|
-
};
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
/**
|
|
280
|
-
* Create missing Human decision items for existing Agent Thread messages
|
|
281
|
-
* that explicitly asked Human to decide. Runs on Project open once; the
|
|
282
|
-
* per-entry dedupe makes it idempotent.
|
|
283
|
-
*/
|
|
284
|
-
async backfillHumanMentions(workspacePath = '') {
|
|
285
|
-
const humanId = this.humanId();
|
|
286
|
-
if (humanId === null) return 0;
|
|
287
|
-
const projectId = Object.keys(this.state.projects ?? {})[0];
|
|
288
|
-
// 路径包含性:Thread 正文由 agent 写,正文里的绝对路径不能变成
|
|
289
|
-
// 「读主机任意文件」的通道——只接受项目工作目录内的 .md。
|
|
290
|
-
// 必须按 **realpath** 比较:工作区内的 junction/symlink 指向外部时,
|
|
291
|
-
// 纯词法比较会把它当成「在工作区内」,等于放行任意路径。
|
|
292
|
-
const realOrNull = (value) => {
|
|
293
|
-
try { return realpathSync(value); } catch { return null; }
|
|
294
|
-
};
|
|
295
|
-
const allowedRoot = typeof workspacePath === 'string' && workspacePath !== ''
|
|
296
|
-
? realOrNull(workspacePath) ?? pathDefault.resolve(workspacePath)
|
|
297
|
-
: null;
|
|
298
|
-
const insideWorkspace = (candidate) => {
|
|
299
|
-
if (allowedRoot === null) return false;
|
|
300
|
-
const resolved = realOrNull(candidate) ?? pathDefault.resolve(candidate);
|
|
301
|
-
const relative = pathDefault.relative(allowedRoot, resolved);
|
|
302
|
-
return relative !== '' && !relative.startsWith('..') && !pathDefault.isAbsolute(relative);
|
|
303
|
-
};
|
|
304
|
-
let reportPath = null;
|
|
305
|
-
for (const task of Object.values(this.state.tasks ?? {})) {
|
|
306
|
-
for (const entry of this.state.threads?.[task.id]?.entries ?? []) {
|
|
307
|
-
const found = findReportPath(entry.body);
|
|
308
|
-
if (found !== null && insideWorkspace(found) && existsSync(found)) { reportPath = found; break; }
|
|
309
|
-
}
|
|
310
|
-
if (reportPath !== null) break;
|
|
311
|
-
}
|
|
312
|
-
let reportQuestions = [];
|
|
313
|
-
if (reportPath !== null) {
|
|
314
|
-
try {
|
|
315
|
-
// An agent-authored path drives a server-side read here; cap the
|
|
316
|
-
// read so a giant or adversarial report cannot flood memory.
|
|
317
|
-
if (statSync(reportPath).size > 256 * 1024) reportPath = null;
|
|
318
|
-
} catch { reportPath = null; }
|
|
319
|
-
}
|
|
320
|
-
if (reportPath !== null) {
|
|
321
|
-
try {
|
|
322
|
-
reportQuestions = parseDecisionQuestions(readFileSync(reportPath, 'utf8'));
|
|
323
|
-
} catch { /* report may be unavailable; keep the Thread fallback */ }
|
|
324
|
-
}
|
|
325
|
-
if (reportQuestions.length === 0) return 0;
|
|
326
|
-
const candidates = [];
|
|
327
|
-
for (const task of Object.values(this.state.tasks ?? {})) {
|
|
328
|
-
if (task.tombstone === true) continue;
|
|
329
|
-
for (const entry of this.state.threads?.[task.id]?.entries ?? []) {
|
|
330
|
-
const author = this.state.members?.[entry.authorId];
|
|
331
|
-
if (author?.kind !== 'agent' || !mentionsHuman(entry.body)) continue;
|
|
332
|
-
candidates.push({ task, entry, key: `${task.id}:${entry.seq}` });
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
if (candidates.length > 0) {
|
|
336
|
-
const alreadyStructured = Object.values(this.state.inbox ?? {}).some((item) =>
|
|
337
|
-
item.memberId === humanId
|
|
338
|
-
&& item.ref?.source === reportPath
|
|
339
|
-
&& Array.isArray(item.ref?.questions)
|
|
340
|
-
&& item.ref.questions.length > 0);
|
|
341
|
-
if (alreadyStructured) return 0;
|
|
342
|
-
const chosen = candidates.find((candidate) => /§6|六问/.test(candidate.entry.body))
|
|
343
|
-
?? candidates.sort((left, right) => (right.entry.seq ?? 0) - (left.entry.seq ?? 0))[0];
|
|
344
|
-
const item = createInboxItem({
|
|
345
|
-
memberId: humanId,
|
|
346
|
-
type: 'decision_required',
|
|
347
|
-
ref: {
|
|
348
|
-
taskId: chosen.task.id,
|
|
349
|
-
entrySeq: chosen.entry.seq,
|
|
350
|
-
memberId: chosen.entry.authorId,
|
|
351
|
-
memberName: this.state.members?.[chosen.entry.authorId]?.name ?? chosen.entry.authorId,
|
|
352
|
-
category: 'thread_mention',
|
|
353
|
-
title: `需 Human 决策 · ${reportQuestions.length} 问`,
|
|
354
|
-
questions: reportQuestions,
|
|
355
|
-
source: reportPath,
|
|
356
|
-
},
|
|
357
|
-
requiresDecision: true,
|
|
358
|
-
}, { at: this.now() });
|
|
359
|
-
await this.ledger.append({
|
|
360
|
-
type: 'inbox/item-created',
|
|
361
|
-
payload: { itemId: item.id, ...item },
|
|
362
|
-
actor: { kind: 'system' },
|
|
363
|
-
projectId,
|
|
364
|
-
at: this.now(),
|
|
365
|
-
});
|
|
366
|
-
return 1;
|
|
367
|
-
}
|
|
368
|
-
return 0;
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
/**
|
|
372
|
-
* Dispatch one command. The caller is an exact Team member (or Human) and
|
|
373
|
-
* the ledger serializes commands per Project.
|
|
374
|
-
* @param {{ type: string, payload?: any, actor: { kind: string, memberId?: string }, correlationId?: string, projectId?: string }} command
|
|
375
|
-
*/
|
|
376
|
-
async dispatch(command) {
|
|
377
|
-
const payload = command.payload ?? {};
|
|
378
|
-
const actor = command.actor;
|
|
379
|
-
// Diagnostic trail: one entry row per command, one failure row on throw,
|
|
380
|
-
// one done row with the duration in every case. 前置校验失败也必须留痕
|
|
381
|
-
// (errors 档只留 .fail 行,校验抛出必须发生在 try 内才能落行)。
|
|
382
|
-
const startedAt = Date.now();
|
|
383
|
-
const failRow = (code, message) => {
|
|
384
|
-
this.diag?.append({
|
|
385
|
-
ev: 'dispatch.fail',
|
|
386
|
-
type: command.type,
|
|
387
|
-
code,
|
|
388
|
-
projectId: command.projectId ?? null,
|
|
389
|
-
message,
|
|
390
|
-
elapsedMs: Date.now() - startedAt,
|
|
391
|
-
});
|
|
392
|
-
};
|
|
393
|
-
this.diag?.append({
|
|
394
|
-
ev: 'dispatch.start',
|
|
395
|
-
type: command.type,
|
|
396
|
-
actor: actor?.kind ?? null,
|
|
397
|
-
memberId: actor?.memberId ?? null,
|
|
398
|
-
projectId: command.projectId ?? null,
|
|
399
|
-
});
|
|
400
|
-
try {
|
|
401
|
-
if (actor === undefined || (actor.kind !== 'human' && actor.kind !== 'agent')) {
|
|
402
|
-
failRow(ERRORS.UNAUTHORIZED, 'an exact Team member is required');
|
|
403
|
-
fail(ERRORS.UNAUTHORIZED, 'an exact Team member is required');
|
|
404
|
-
}
|
|
405
|
-
// An agent actor must resolve to a live, non-retired member: otherwise a
|
|
406
|
-
// forged or stale memberId would bypass owner/QA checks downstream.
|
|
407
|
-
if (actor.kind === 'agent') {
|
|
408
|
-
const actingMember = this.state.members?.[actor.memberId];
|
|
409
|
-
if (actingMember === undefined || actingMember.kind !== 'agent') {
|
|
410
|
-
failRow(ERRORS.UNAUTHORIZED, `agent actor ${String(actor.memberId ?? '?')} is not a Team member`);
|
|
411
|
-
fail(ERRORS.UNAUTHORIZED, `agent actor ${String(actor.memberId ?? '?')} is not a Team member`);
|
|
412
|
-
}
|
|
413
|
-
if (actingMember.status === 'retired') {
|
|
414
|
-
failRow(ERRORS.INVALID_STATE, `agent ${actingMember.name ?? actingMember.id} is retired`);
|
|
415
|
-
fail(ERRORS.INVALID_STATE, `agent ${actingMember.name ?? actingMember.id} is retired`);
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
switch (command.type) {
|
|
419
|
-
case 'project.create': return await this.createProject(command, payload);
|
|
420
|
-
case 'project.owner.update': return await this.changeProjectOwner(command, payload);
|
|
421
|
-
case 'project.workspace.update': return await this.changeProjectWorkspace(command, payload);
|
|
422
|
-
case 'project.repair': return await this.runExclusive(() => this.repairLedger(command));
|
|
423
|
-
case 'project.pmo.update': return await this.setProjectPmo(command, payload);
|
|
424
|
-
case 'project.archive': return await this.setProjectArchive(command, payload);
|
|
425
|
-
case 'project.runState': return await this.setProjectRunState(command, payload);
|
|
426
|
-
case 'project.handoff': return await this.handoffProject(command, payload);
|
|
427
|
-
case 'stream.post': return await this.postStream(command, payload);
|
|
428
|
-
case 'member.add': return await this.addMember(command, payload);
|
|
429
|
-
case 'member.bind': return await this.bindMemberSession(command, payload);
|
|
430
|
-
case 'member.fail': return await this.failMember(command, payload);
|
|
431
|
-
case 'member.retire': return await this.retireMember(command, payload);
|
|
432
|
-
case 'member.profile.update': return await this.updateMemberProfile(command, payload);
|
|
433
|
-
case 'member.evolve': return await this.evolveMember(command, payload);
|
|
434
|
-
case 'member.distill': return await this.distillMember(command, payload);
|
|
435
|
-
case 'member.leave': return await this.leaveMember(command, payload);
|
|
436
|
-
case 'member.rejoin': return await this.rejoinMember(command, payload);
|
|
437
|
-
case 'member.takeover': return await this.takeoverMember(command, payload);
|
|
438
|
-
case 'member.message': return await this.messageMember(command, payload);
|
|
439
|
-
case 'member.note': return await this.addMemberNote(command, payload);
|
|
440
|
-
case 'member.skill': return await this.addMemberSkill(command, payload);
|
|
441
|
-
case 'member.config.update': return await this.updateMemberConfig(command, payload);
|
|
442
|
-
case 'member.retry': return await this.retryMember(command, payload);
|
|
443
|
-
case 'task.create': return await this.runExclusive(() => this.createTask(command, payload));
|
|
444
|
-
case 'task.claim': return await this.runExclusive(() => this.taskCommand(command, 'claim'));
|
|
445
|
-
case 'task.release': return await this.runExclusive(() => this.taskCommand(command, 'release'));
|
|
446
|
-
case 'task.assign': return await this.runExclusive(() => this.taskCommand(command, 'assign'));
|
|
447
|
-
case 'task.submit': return await this.runExclusive(() => this.taskCommand(command, 'submit'));
|
|
448
|
-
case 'task.accept': return await this.runExclusive(() => this.taskCommand(command, 'accept'));
|
|
449
|
-
case 'task.request_changes': return await this.runExclusive(() => this.taskCommand(command, 'request_changes'));
|
|
450
|
-
case 'task.cancel': return await this.runExclusive(() => this.taskCommand(command, 'cancel'));
|
|
451
|
-
case 'task.reopen': return await this.runExclusive(() => this.taskCommand(command, 'reopen'));
|
|
452
|
-
case 'task.reassign': return await this.runExclusive(() => this.taskCommand(command, 'reassign'));
|
|
453
|
-
case 'task.delete': return await this.runExclusive(() => this.taskCommand(command, 'delete'));
|
|
454
|
-
case 'task.convert': return await this.runExclusive(() => this.convert(command, payload));
|
|
455
|
-
case 'task.follow': return await this.follow(command, payload);
|
|
456
|
-
case 'thread.post': return await this.postThread(command, payload);
|
|
457
|
-
case 'inbox.ack': return await this.ack(command, payload);
|
|
458
|
-
case 'decision.request': return await this.runExclusive(() => this.requestDecision(command, payload));
|
|
459
|
-
case 'decision.answer': return await this.runExclusive(() => this.answerDecision(command, payload));
|
|
460
|
-
default: fail(ERRORS.INVALID_ARGUMENT, `unknown command: ${String(command.type)}`);
|
|
461
|
-
}
|
|
462
|
-
} catch (error) {
|
|
463
|
-
this.diag?.append({
|
|
464
|
-
ev: 'dispatch.fail',
|
|
465
|
-
type: command.type,
|
|
466
|
-
code: error?.code ?? 'INTERNAL',
|
|
467
|
-
projectId: command.projectId ?? null,
|
|
468
|
-
message: error?.message ?? String(error),
|
|
469
|
-
elapsedMs: Date.now() - startedAt,
|
|
470
|
-
});
|
|
471
|
-
throw error;
|
|
472
|
-
} finally {
|
|
473
|
-
this.diag?.append({
|
|
474
|
-
ev: 'dispatch.done',
|
|
475
|
-
type: command.type,
|
|
476
|
-
projectId: command.projectId ?? null,
|
|
477
|
-
elapsedMs: Date.now() - startedAt,
|
|
478
|
-
});
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
async append(command, type, payload) {
|
|
483
|
-
const event = await this.ledger.append({
|
|
484
|
-
type,
|
|
485
|
-
payload,
|
|
486
|
-
actor: command.actor,
|
|
487
|
-
correlationId: command.correlationId,
|
|
488
|
-
at: this.now(),
|
|
489
|
-
});
|
|
490
|
-
return { event, result: payload };
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
async createProject(command, payload) {
|
|
494
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may create a Project');
|
|
495
|
-
if (typeof payload.name !== 'string' || payload.name.trim() === '') fail(ERRORS.INVALID_ARGUMENT, 'project name is required');
|
|
496
|
-
const id = this.ledger.projectId ?? payload.id ?? ids.project();
|
|
497
|
-
// 重复 id 会覆盖既有项目的 name/goal/owner/status(fold 按 id 合并),
|
|
498
|
-
// 静默丢掉原项目。create 必须是「新建」。
|
|
499
|
-
if (this.state.projects?.[id] !== undefined) {
|
|
500
|
-
fail(ERRORS.CONFLICT, `project ${id} already exists`);
|
|
501
|
-
}
|
|
502
|
-
// 工作目录**必需**(用户裁定:每个项目都必须指定目录):没有目录的项目里
|
|
503
|
-
// 成员无法激活、PMO 也无从派发,等于建了个用不了的项目。
|
|
504
|
-
// 例外只有内部播种(payload.seed):它先建出「待设定目录」的默认项目,
|
|
505
|
-
// 由首次使用引导补上目录,否则 boot 自己就会被这条校验挡住。
|
|
506
|
-
const rawWorkspace = typeof payload.workspacePath === 'string' ? payload.workspacePath.trim() : '';
|
|
507
|
-
if (rawWorkspace !== '') {
|
|
508
|
-
const shape = checkWorkspacePath(rawWorkspace);
|
|
509
|
-
if (shape.ok !== true) fail(ERRORS.INVALID_ARGUMENT, shape.message, { suggestion: shape.suggestion ?? null });
|
|
510
|
-
}
|
|
511
|
-
if (rawWorkspace === '' && payload.seed !== true) {
|
|
512
|
-
fail(ERRORS.INVALID_ARGUMENT, '工作目录是必填项:请选择一个已存在的目录作为项目工作区');
|
|
513
|
-
}
|
|
514
|
-
if (rawWorkspace !== '') {
|
|
515
|
-
let stat = null;
|
|
516
|
-
try { stat = statSync(rawWorkspace); } catch { stat = null; }
|
|
517
|
-
if (stat === null) fail(ERRORS.INVALID_ARGUMENT, `工作目录不存在:${rawWorkspace};请先创建该目录,或选择已存在的目录`);
|
|
518
|
-
if (typeof stat.isDirectory === 'function' && stat.isDirectory() !== true) {
|
|
519
|
-
fail(ERRORS.INVALID_ARGUMENT, `工作目录不是目录:${rawWorkspace}`);
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
const ownerMemberId = payload.ownerId ?? command.actor.memberId ?? this.humanId();
|
|
523
|
-
const project = {
|
|
524
|
-
id,
|
|
525
|
-
name: payload.name.trim(),
|
|
526
|
-
goal: payload.goal ?? '',
|
|
527
|
-
ownerMemberId,
|
|
528
|
-
workspacePath: rawWorkspace,
|
|
529
|
-
status: 'active',
|
|
530
|
-
createdAt: this.now(),
|
|
531
|
-
};
|
|
532
|
-
await this.append({ ...command, projectId: id }, 'project/created', {
|
|
533
|
-
name: project.name,
|
|
534
|
-
goal: project.goal,
|
|
535
|
-
ownerMemberId,
|
|
536
|
-
workspacePath: project.workspacePath,
|
|
537
|
-
pmoAuto: payload.pmoAuto !== false,
|
|
538
|
-
status: project.status,
|
|
539
|
-
});
|
|
540
|
-
return { project };
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
/**
|
|
544
|
-
* 账本自检/修复入口(仅 Human)。`ledger.repair()` 此前没有任何生产调用点:
|
|
545
|
-
* 回滚失败被置为 poisoned 之后,除了重启宿主没有任何恢复路径。
|
|
546
|
-
*/
|
|
547
|
-
async repairLedger(command) {
|
|
548
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may repair the ledger');
|
|
549
|
-
const result = this.ledger.repair();
|
|
550
|
-
this.diag?.append({
|
|
551
|
-
ev: 'ledger.repaired',
|
|
552
|
-
projectId: command.projectId ?? null,
|
|
553
|
-
repair: result?.repair ?? null,
|
|
554
|
-
events: result?.events ?? null,
|
|
555
|
-
stateLastSeq: result?.stateLastSeq ?? null,
|
|
556
|
-
});
|
|
557
|
-
return {
|
|
558
|
-
repaired: result?.repair ?? null,
|
|
559
|
-
repairs: Array.isArray(result?.repairs) ? result.repairs : [],
|
|
560
|
-
events: result?.events ?? null,
|
|
561
|
-
stateLastSeq: result?.stateLastSeq ?? null,
|
|
562
|
-
// 恢复区间与缺口:一次失败的批次可能把前缀留在盘上,调用方要能看出来。
|
|
563
|
-
acceptedRange: result?.acceptedRange ?? null,
|
|
564
|
-
seqGaps: Array.isArray(result?.seqGaps) ? result.seqGaps : [],
|
|
565
|
-
};
|
|
566
|
-
}
|
|
567
|
-
async changeProjectWorkspace(command, payload) {
|
|
568
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may change the Project workspace');
|
|
569
|
-
const projectId = command.projectId;
|
|
570
|
-
const project = this.state.projects?.[projectId];
|
|
571
|
-
if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
572
|
-
if (typeof payload.workspacePath !== 'string' || payload.workspacePath.trim() === '') {
|
|
573
|
-
fail(ERRORS.INVALID_ARGUMENT, 'workspacePath is required');
|
|
574
|
-
}
|
|
575
|
-
const workspacePath = payload.workspacePath.trim();
|
|
576
|
-
// 平台形态先判:WSL/Linux 宿主上 `D:\works\x` 只是带反斜杠的相对文件名,
|
|
577
|
-
// 直接做 statSync 只会得到「不存在」,完全指不出该怎么改。
|
|
578
|
-
const shape = checkWorkspacePath(workspacePath);
|
|
579
|
-
if (shape.ok !== true) fail(ERRORS.INVALID_ARGUMENT, shape.message, { suggestion: shape.suggestion ?? null });
|
|
580
|
-
// P5b:目录必须真实存在且是目录——配置不存在的目录会让成员会话 cwd
|
|
581
|
-
// 无效、回合直接失败(用户实证:working-directory: directory does not exist)。
|
|
582
|
-
let stat = null;
|
|
583
|
-
try {
|
|
584
|
-
stat = statSync(workspacePath);
|
|
585
|
-
} catch {
|
|
586
|
-
fail(ERRORS.INVALID_ARGUMENT, `工作目录不存在:${workspacePath};请先创建该目录,或选择已存在的目录`);
|
|
587
|
-
}
|
|
588
|
-
if (stat !== null && typeof stat.isDirectory === 'function' && stat.isDirectory() !== true) {
|
|
589
|
-
fail(ERRORS.INVALID_ARGUMENT, `工作目录不是目录:${workspacePath}`);
|
|
590
|
-
}
|
|
591
|
-
await this.append(command, 'project/workspace-changed', {
|
|
592
|
-
projectId,
|
|
593
|
-
workspacePath,
|
|
594
|
-
reason: payload.reason ?? '',
|
|
595
|
-
});
|
|
596
|
-
return { project: { ...project, workspacePath } };
|
|
597
|
-
}
|
|
598
|
-
|
|
599
|
-
// P4:项目归档(软删)——账本 append-only 纪律下不可物理删除;archived
|
|
600
|
-
// 项目从工作台消失(bootstrap 过滤),成员的 DSH 会话不受影响。
|
|
601
|
-
// P6:项目运行态(启动/停止/交接)—— Human 的全局掌控面。
|
|
602
|
-
// 'stopped':PMO tick 停止派发(补派/心跳/升级/continue 全停),正在执行
|
|
603
|
-
// 的回合自然完成;'running'(默认):正常驱动。start 时 explicitStart=true
|
|
604
|
-
// 解除空项目的 P1a 等待门(Human 显式启动即指令)。
|
|
605
|
-
async setProjectRunState(command, payload) {
|
|
606
|
-
const projectId = command.projectId;
|
|
607
|
-
const project = this.state.projects?.[projectId];
|
|
608
|
-
if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
609
|
-
const runState = payload.runState;
|
|
610
|
-
if (runState !== 'running' && runState !== 'stopped') fail(ERRORS.INVALID_ARGUMENT, 'runState must be running or stopped');
|
|
611
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may change the project run state');
|
|
612
|
-
await this.append(command, 'project/run-state', { projectId, runState, reason: payload.reason ?? '' });
|
|
613
|
-
return { project: { ...project, runState, explicitStart: runState === 'running' ? true : project.explicitStart === true } };
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
async handoffProject(command, payload) {
|
|
618
|
-
const projectId = command.projectId;
|
|
619
|
-
const project = this.state.projects?.[projectId];
|
|
620
|
-
if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
621
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may request a handoff');
|
|
622
|
-
if (typeof project.workspacePath !== 'string' || project.workspacePath.trim() === '') {
|
|
623
|
-
fail(ERRORS.INVALID_STATE, '项目未配置工作目录,无法落盘交接文档');
|
|
624
|
-
}
|
|
625
|
-
const nowMs = this.now();
|
|
626
|
-
const markdown = handoffMarkdown(this.state, project, nowMs);
|
|
627
|
-
const docsDir = pathDefault.join(project.workspacePath, 'docs');
|
|
628
|
-
mkdirSync(docsDir, { recursive: true });
|
|
629
|
-
const stamp = new Date(nowMs).toISOString().replace(/[:T]/g, '-').slice(0, 19);
|
|
630
|
-
const filePath = pathDefault.join(docsDir, `HANDOFF-${stamp}.md`);
|
|
631
|
-
writeFileSync(filePath, markdown, 'utf8');
|
|
632
|
-
await this.append(command, 'project/handoff', { projectId, filePath, reason: payload.reason ?? '' });
|
|
633
|
-
return { project, filePath };
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
async setProjectArchive(command, payload) {
|
|
637
|
-
const projectId = command.projectId;
|
|
638
|
-
const project = this.state.projects?.[projectId];
|
|
639
|
-
if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
640
|
-
const archived = payload.archived !== false;
|
|
641
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may archive a project');
|
|
642
|
-
if (archived === false && project.status === 'archived') fail(ERRORS.INVALID_STATE, 'archived projects cannot be un-archived in this version');
|
|
643
|
-
// 归档许可由 Host 层判定(registry 是全局项目清单;本 service 只持有
|
|
644
|
-
// 自己项目的账本,无法看到其它项目——旧实现的「最后 active 项目」检查
|
|
645
|
-
// 在本账本里恒为 1,导致所有归档都被误拒 409)。
|
|
646
|
-
await this.append(command, 'project/archived', { projectId, archived, reason: payload.reason ?? '' });
|
|
647
|
-
return { project: { ...project, status: archived ? 'archived' : 'active' } };
|
|
648
|
-
}
|
|
649
|
-
|
|
650
|
-
async setProjectPmo(command, payload) { const projectId = command.projectId;
|
|
651
|
-
const project = this.state.projects?.[projectId];
|
|
652
|
-
if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
653
|
-
if (typeof payload.pmoAuto !== 'boolean') fail(ERRORS.INVALID_ARGUMENT, 'pmoAuto must be boolean');
|
|
654
|
-
const isOwner = command.actor.kind === 'agent' && command.actor.memberId === project.ownerMemberId;
|
|
655
|
-
if (command.actor.kind !== 'human' && !isOwner) fail(ERRORS.UNAUTHORIZED, 'only Human or the Project owner may change PMO mode');
|
|
656
|
-
await this.append(command, 'project/pmo-updated', { projectId, pmoAuto: payload.pmoAuto, reason: payload.reason ?? '' });
|
|
657
|
-
return { project: { ...project, pmoAuto: payload.pmoAuto } };
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
async changeProjectOwner(command, payload) {
|
|
661
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may change the Project owner');
|
|
662
|
-
const projectId = command.projectId;
|
|
663
|
-
const project = this.state.projects?.[projectId];
|
|
664
|
-
if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
665
|
-
const ownerMemberId = payload.ownerMemberId;
|
|
666
|
-
if (typeof ownerMemberId !== 'string' || this.state.members?.[ownerMemberId] === undefined) {
|
|
667
|
-
fail(ERRORS.INVALID_ARGUMENT, 'ownerMemberId must name an existing member');
|
|
668
|
-
}
|
|
669
|
-
await this.append(command, 'project/owner-changed', { projectId, ownerMemberId, reason: payload.reason ?? '' });
|
|
670
|
-
return { project: { ...project, ownerMemberId } };
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
async postStream(command, payload) {
|
|
674
|
-
const body = typeof payload.body === 'string' ? payload.body.trim() : '';
|
|
675
|
-
if (body === '') fail(ERRORS.INVALID_ARGUMENT, 'stream message body is required');
|
|
676
|
-
const author = this.state.members?.[command.actor.memberId];
|
|
677
|
-
if (author === undefined) fail(ERRORS.UNAUTHORIZED, 'actor must be a Team member');
|
|
678
|
-
// seq 由账本事件定(fold 用 event.seq;payload 里的幻影计数会被忽略,
|
|
679
|
-
// 并发下还会重复——曾造成 API 返回值与投影不一致)。
|
|
680
|
-
// kind 必须反映真实作者:`human_message` 是 Waker 判定「Human 下了指令」的
|
|
681
|
-
// 唯一依据(会触发建卡唤醒),agent 发言若也标成它,等于让 agent 冒充 Human。
|
|
682
|
-
const entry = {
|
|
683
|
-
kind: command.actor.kind === 'human' ? 'human_message' : 'milestone',
|
|
684
|
-
authorId: author.id,
|
|
685
|
-
body,
|
|
686
|
-
at: this.now(),
|
|
687
|
-
};
|
|
688
|
-
const event = await this.ledger.append({
|
|
689
|
-
type: 'stream/posted',
|
|
690
|
-
payload: entry,
|
|
691
|
-
actor: command.actor,
|
|
692
|
-
projectId: command.projectId,
|
|
693
|
-
at: this.now(),
|
|
694
|
-
});
|
|
695
|
-
return { entry: { ...entry, seq: event.seq }, event };
|
|
696
|
-
}
|
|
697
|
-
|
|
698
|
-
async addMember(command, payload) {
|
|
699
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may create a member');
|
|
700
|
-
if (typeof payload.name !== 'string' || payload.name.trim() === '') fail(ERRORS.INVALID_ARGUMENT, 'member name is required');
|
|
701
|
-
// id 由调用方给出时必须是非空字符串且未被占用:否则会覆盖既有成员
|
|
702
|
-
// (fold 按 id 合并,sessionId/config 一起丢失),或写入非字符串 id 被
|
|
703
|
-
// fold 丢弃却仍返回成功。
|
|
704
|
-
if (payload.id !== undefined) {
|
|
705
|
-
if (typeof payload.id !== 'string' || payload.id.trim() === '') {
|
|
706
|
-
fail(ERRORS.INVALID_ARGUMENT, 'member id must be a non-empty string');
|
|
707
|
-
}
|
|
708
|
-
if (this.state.members?.[payload.id] !== undefined) {
|
|
709
|
-
fail(ERRORS.CONFLICT, `member ${payload.id} already exists`);
|
|
710
|
-
}
|
|
711
|
-
}
|
|
712
|
-
const status = payload.status === undefined ? MEMBER_STATUS.IDLE : payload.status;
|
|
713
|
-
if (!MEMBER_STATUS_VALUES.has(status)) {
|
|
714
|
-
fail(ERRORS.INVALID_ARGUMENT, `member status must be one of ${[...MEMBER_STATUS_VALUES].join(', ')}`);
|
|
715
|
-
}
|
|
716
|
-
const member = {
|
|
717
|
-
id: payload.id ?? ids.member(),
|
|
718
|
-
name: payload.name.trim(),
|
|
719
|
-
kind: payload.kind === 'human' ? 'human' : 'agent',
|
|
720
|
-
role: payload.role ?? '',
|
|
721
|
-
personality: typeof payload.personality === 'string' ? payload.personality : '',
|
|
722
|
-
status,
|
|
723
|
-
createdAt: this.now(),
|
|
724
|
-
};
|
|
725
|
-
await this.append(command, 'project/member-added', {
|
|
726
|
-
memberId: member.id,
|
|
727
|
-
name: member.name,
|
|
728
|
-
kind: member.kind,
|
|
729
|
-
role: member.role,
|
|
730
|
-
personality: member.personality,
|
|
731
|
-
status: member.status,
|
|
732
|
-
projectId: payload.projectId,
|
|
733
|
-
});
|
|
734
|
-
return { member };
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
async recordWake(memberId, info, projectId = Object.keys(this.state.projects ?? {})[0]) {
|
|
738
|
-
const event = {
|
|
739
|
-
type: info.ok === true ? 'wake/delivered' : 'wake/failed',
|
|
740
|
-
payload: { memberId, taskId: info.taskId ?? null, reason: info.reason ?? null, messageId: info.messageId ?? null, error: info.error ?? null },
|
|
741
|
-
actor: { kind: 'system' },
|
|
742
|
-
projectId,
|
|
743
|
-
at: this.now(),
|
|
744
|
-
};
|
|
745
|
-
await this.ledger.append(event);
|
|
746
|
-
return event;
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
async bindHostSession(sessionId, projectId = Object.keys(this.state.projects ?? {})[0]) {
|
|
750
|
-
if (typeof sessionId !== 'string' || sessionId === '') fail(ERRORS.INVALID_ARGUMENT, 'host sessionId is required');
|
|
751
|
-
await this.ledger.append({
|
|
752
|
-
type: 'team/host-bound',
|
|
753
|
-
payload: { sessionId },
|
|
754
|
-
actor: { kind: 'system' },
|
|
755
|
-
projectId,
|
|
756
|
-
at: this.now(),
|
|
757
|
-
});
|
|
758
|
-
return { sessionId };
|
|
759
|
-
}
|
|
760
|
-
|
|
761
|
-
async bindMemberSession(command, payload) {
|
|
762
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may bind a member session');
|
|
763
|
-
const member = this.state.members?.[payload.memberId];
|
|
764
|
-
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.memberId)} not found`);
|
|
765
|
-
// 退役成员不得经 bind 复活;重新入队必须走 member.rejoin(清 talentPool)。
|
|
766
|
-
if (member.status === 'retired') fail(ERRORS.INVALID_STATE, `member ${member.name ?? member.id} is retired`);
|
|
767
|
-
if (typeof payload.sessionId !== 'string' || payload.sessionId === '') fail(ERRORS.INVALID_ARGUMENT, 'sessionId is required');
|
|
768
|
-
await this.append(command, 'member/session-bound', {
|
|
769
|
-
memberId: member.id,
|
|
770
|
-
sessionId: payload.sessionId,
|
|
771
|
-
status: 'running',
|
|
772
|
-
});
|
|
773
|
-
return { member: { ...member, sessionId: payload.sessionId, status: 'running' } };
|
|
774
|
-
}
|
|
775
|
-
|
|
776
|
-
async failMember(command, payload) {
|
|
777
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may mark a member failed');
|
|
778
|
-
const member = this.state.members?.[payload.memberId];
|
|
779
|
-
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.memberId)} not found`);
|
|
780
|
-
// 退役是终态:把 retired 改成 failed 会让 member.bind 之后把 ta 复活。
|
|
781
|
-
if (member.status === 'retired') fail(ERRORS.INVALID_STATE, `member ${member.id} is retired`);
|
|
782
|
-
await this.append(command, 'member/failed', { memberId: member.id, reason: payload.reason ?? '' });
|
|
783
|
-
return { member: { ...member, status: 'failed', failure: payload.reason ?? '' } };
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
async retireMember(command, payload) {
|
|
787
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may retire a member');
|
|
788
|
-
const member = this.state.members?.[payload.memberId];
|
|
789
|
-
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.memberId)} not found`);
|
|
790
|
-
await this.append(command, 'project/member-retired', { memberId: member.id });
|
|
791
|
-
return { member: { ...member, status: 'retired' } };
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
async updateMemberProfile(command, payload) {
|
|
795
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may change name, role or personality');
|
|
796
|
-
const member = this.state.members?.[payload.memberId];
|
|
797
|
-
if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId)} not found`);
|
|
798
|
-
const text = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);
|
|
799
|
-
const name = text(payload.name);
|
|
800
|
-
const role = text(payload.role);
|
|
801
|
-
// An empty personality means "leave it unchanged", not "clear it".
|
|
802
|
-
const personality = text(payload.personality);
|
|
803
|
-
if (name === undefined && role === undefined && personality === undefined) {
|
|
804
|
-
fail(ERRORS.INVALID_ARGUMENT, 'name, role or personality is required');
|
|
805
|
-
}
|
|
806
|
-
await this.append(command, 'member/profile-updated', {
|
|
807
|
-
memberId: member.id,
|
|
808
|
-
...(name === undefined ? {} : { name }),
|
|
809
|
-
...(role === undefined ? {} : { role }),
|
|
810
|
-
...(personality === undefined ? {} : { personality }),
|
|
811
|
-
updatedBy: command.actor.memberId,
|
|
812
|
-
reason: payload.reason ?? '',
|
|
813
|
-
});
|
|
814
|
-
return { member: this.state.members[member.id] };
|
|
815
|
-
}
|
|
816
|
-
|
|
817
|
-
/** An Agent may evolve its own working personality, never its name/role. */
|
|
818
|
-
async evolveMember(command, payload) {
|
|
819
|
-
if (command.actor.kind !== 'agent') fail(ERRORS.UNAUTHORIZED, 'only an Agent may evolve its personality');
|
|
820
|
-
const member = this.state.members?.[command.actor.memberId];
|
|
821
|
-
if (member === undefined) fail(ERRORS.NOT_FOUND, 'actor member not found');
|
|
822
|
-
if (payload.memberId !== undefined && payload.memberId !== member.id) {
|
|
823
|
-
fail(ERRORS.UNAUTHORIZED, 'an Agent may only evolve itself');
|
|
824
|
-
}
|
|
825
|
-
const personality = typeof payload.personality === 'string' ? payload.personality.trim() : '';
|
|
826
|
-
if (personality === '') fail(ERRORS.INVALID_ARGUMENT, 'personality is required');
|
|
827
|
-
await this.append(command, 'member/distilled', {
|
|
828
|
-
memberId: member.id,
|
|
829
|
-
personality,
|
|
830
|
-
updatedBy: member.id,
|
|
831
|
-
reason: payload.reason ?? 'self-evolution',
|
|
832
|
-
});
|
|
833
|
-
return { member: this.state.members[member.id] };
|
|
834
|
-
}
|
|
835
|
-
|
|
836
|
-
/** Human/Lead-triggered distillation snapshot; model quality is a later step. */
|
|
837
|
-
async distillMember(command, payload) {
|
|
838
|
-
if (command.actor.kind !== 'human' && command.actor.kind !== 'agent') fail(ERRORS.UNAUTHORIZED, 'a member is required');
|
|
839
|
-
const member = this.state.members?.[payload.memberId];
|
|
840
|
-
if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId)} not found`);
|
|
841
|
-
const lead = this.state.projects?.[command.projectId]?.ownerMemberId === command.actor.memberId;
|
|
842
|
-
if (command.actor.kind !== 'human' && !lead && command.actor.memberId !== member.id) {
|
|
843
|
-
fail(ERRORS.UNAUTHORIZED, 'only Human, the Project owner or the member may distill');
|
|
844
|
-
}
|
|
845
|
-
const personality = typeof payload.personality === 'string' && payload.personality.trim() !== ''
|
|
846
|
-
? payload.personality.trim()
|
|
847
|
-
: member.personality ?? '';
|
|
848
|
-
if (personality === '') fail(ERRORS.INVALID_ARGUMENT, 'personality is required for distillation');
|
|
849
|
-
await this.append(command, 'member/distilled', {
|
|
850
|
-
memberId: member.id,
|
|
851
|
-
personality,
|
|
852
|
-
updatedBy: command.actor.memberId,
|
|
853
|
-
reason: payload.reason ?? 're-distill',
|
|
854
|
-
});
|
|
855
|
-
return { member: this.state.members[member.id] };
|
|
856
|
-
}
|
|
857
|
-
|
|
858
|
-
async messageMember(command, payload) {
|
|
859
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may message a member');
|
|
860
|
-
const member = this.state.members?.[payload.memberId];
|
|
861
|
-
if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId)} not found`);
|
|
862
|
-
const body = typeof payload.body === 'string' ? payload.body.trim() : '';
|
|
863
|
-
if (body === '') fail(ERRORS.INVALID_ARGUMENT, 'message body is required');
|
|
864
|
-
const event = await this.ledger.append({
|
|
865
|
-
type: 'member/message',
|
|
866
|
-
payload: { memberId: member.id, authorId: command.actor.memberId, body, at: this.now() },
|
|
867
|
-
actor: command.actor,
|
|
868
|
-
correlationId: command.correlationId,
|
|
869
|
-
projectId: command.projectId,
|
|
870
|
-
at: this.now(),
|
|
871
|
-
});
|
|
872
|
-
return { event, memberId: member.id };
|
|
873
|
-
}
|
|
874
|
-
|
|
875
|
-
async addMemberNote(command, payload) {
|
|
876
|
-
const member = this.state.members?.[payload.memberId ?? command.actor.memberId];
|
|
877
|
-
if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId ?? command.actor.memberId)} not found`);
|
|
878
|
-
if (command.actor.kind === 'agent' && command.actor.memberId !== member.id) {
|
|
879
|
-
fail(ERRORS.UNAUTHORIZED, 'an Agent may only note itself');
|
|
880
|
-
}
|
|
881
|
-
const text = typeof payload.text === 'string' ? payload.text.trim() : '';
|
|
882
|
-
if (text === '') fail(ERRORS.INVALID_ARGUMENT, 'note text is required');
|
|
883
|
-
await this.append(command, 'member/note-added', {
|
|
884
|
-
memberId: member.id,
|
|
885
|
-
text,
|
|
886
|
-
addedBy: command.actor.memberId,
|
|
887
|
-
});
|
|
888
|
-
return { member: this.state.members[member.id] };
|
|
889
|
-
}
|
|
890
|
-
|
|
891
|
-
async addMemberSkill(command, payload) {
|
|
892
|
-
const member = this.state.members?.[payload.memberId ?? command.actor.memberId];
|
|
893
|
-
if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId ?? command.actor.memberId)} not found`);
|
|
894
|
-
if (command.actor.kind === 'agent' && command.actor.memberId !== member.id) {
|
|
895
|
-
fail(ERRORS.UNAUTHORIZED, 'an Agent may only add its own skill');
|
|
896
|
-
}
|
|
897
|
-
const name = typeof payload.name === 'string' ? payload.name.trim() : '';
|
|
898
|
-
if (name === '') fail(ERRORS.INVALID_ARGUMENT, 'skill name is required');
|
|
899
|
-
await this.append(command, 'member/skill-added', {
|
|
900
|
-
memberId: member.id,
|
|
901
|
-
name,
|
|
902
|
-
addedBy: command.actor.memberId,
|
|
903
|
-
});
|
|
904
|
-
return { member: this.state.members[member.id] };
|
|
905
|
-
}
|
|
906
|
-
|
|
907
|
-
async leaveMember(command, payload) {
|
|
908
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may move a member to the talent pool');
|
|
909
|
-
const member = this.state.members?.[payload.memberId];
|
|
910
|
-
if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId)} not found`);
|
|
911
|
-
const unfinished = unfinishedTasksFor(this.state, member.id);
|
|
912
|
-
await this.append(command, 'member/left-team', { memberId: member.id, reason: payload.reason ?? '' });
|
|
913
|
-
return {
|
|
914
|
-
member: this.state.members[member.id],
|
|
915
|
-
unfinishedTasks: unfinished.map((task) => ({ id: task.id, number: task.number, title: task.title, status: task.status })),
|
|
916
|
-
};
|
|
917
|
-
}
|
|
918
|
-
|
|
919
|
-
async rejoinMember(command, payload) {
|
|
920
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may recruit from the talent pool');
|
|
921
|
-
const member = this.state.members?.[payload.memberId];
|
|
922
|
-
if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId)} not found`);
|
|
923
|
-
if (member.status !== 'retired') fail(ERRORS.INVALID_STATE, 'member is already in the team');
|
|
924
|
-
await this.append(command, 'member/rejoined', { memberId: member.id, reason: payload.reason ?? '' });
|
|
925
|
-
return { member: this.state.members[member.id] };
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
async takeoverMember(command, payload) {
|
|
929
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may assign a successor');
|
|
930
|
-
const from = this.state.members?.[payload.fromMemberId];
|
|
931
|
-
const to = this.state.members?.[payload.toMemberId];
|
|
932
|
-
if (from === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.fromMemberId)} not found`);
|
|
933
|
-
if (to === undefined || to.kind !== 'agent' || to.status === 'retired') {
|
|
934
|
-
fail(ERRORS.INVALID_ARGUMENT, 'successor must be an active Agent');
|
|
935
|
-
}
|
|
936
|
-
const unfinished = unfinishedTasksFor(this.state, from.id);
|
|
937
|
-
const taken = [];
|
|
938
|
-
for (const task of unfinished) {
|
|
939
|
-
await this.append(command, 'task/taken-over', {
|
|
940
|
-
taskId: task.id,
|
|
941
|
-
revision: task.revision + 1,
|
|
942
|
-
fromMemberId: from.id,
|
|
943
|
-
toMemberId: to.id,
|
|
944
|
-
reason: payload.reason ?? `takeover from ${from.name}`,
|
|
945
|
-
});
|
|
946
|
-
taken.push(this.state.tasks[task.id]);
|
|
947
|
-
}
|
|
948
|
-
return { from: from.id, to: to.id, tasks: taken };
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
/** Lead (Project owner) or Human may update another member's config. */
|
|
952
|
-
async updateMemberConfig(command, payload) {
|
|
953
|
-
const member = this.state.members?.[payload.memberId];
|
|
954
|
-
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.memberId)} not found`);
|
|
955
|
-
const project = this.state.projects?.[command.projectId];
|
|
956
|
-
const isHuman = command.actor.kind === 'human';
|
|
957
|
-
const isLead = project?.ownerMemberId === command.actor.memberId || project?.ownerId === command.actor.memberId;
|
|
958
|
-
if (!isHuman && !isLead) fail(ERRORS.UNAUTHORIZED, 'only the Project owner or Human may update member config');
|
|
959
|
-
if (command.actor.memberId === member.id) {
|
|
960
|
-
fail(ERRORS.UNAUTHORIZED, 'a member cannot update its own config; Lead self-config is Human-only');
|
|
961
|
-
}
|
|
962
|
-
if (Number.isSafeInteger(payload.expectedConfigVersion) && payload.expectedConfigVersion !== (member.configVersion ?? 0)) {
|
|
963
|
-
fail(ERRORS.REVISION, 'member config changed since you read it', {
|
|
964
|
-
details: { expected: payload.expectedConfigVersion, current: member.configVersion ?? 0 },
|
|
965
|
-
});
|
|
966
|
-
}
|
|
967
|
-
const current = normalizeMemberConfig(member.config ?? {});
|
|
968
|
-
const result = applyMemberConfigPatch(current, payload.patch ?? {}, {
|
|
969
|
-
// policy 只能来自服务端注入:允许命令 payload 覆盖等于让调用方自己定义
|
|
970
|
-
// 授权边界(实测可把 allowedModels 扩到未授权模型)。
|
|
971
|
-
policy: { ...this.memberConfigPolicy },
|
|
972
|
-
configVersion: member.configVersion ?? 0,
|
|
973
|
-
});
|
|
974
|
-
if (!result.changed) return { member, config: current, changed: false };
|
|
975
|
-
const nextConfig = {
|
|
976
|
-
...result.config,
|
|
977
|
-
updatedBy: command.actor.memberId ?? command.actor.kind,
|
|
978
|
-
updatedAt: this.now(),
|
|
979
|
-
reason: typeof payload.reason === 'string' ? payload.reason : '',
|
|
980
|
-
};
|
|
981
|
-
// 路由字段(provider/model)变化必须单独标记:已存活会话的 provider 在创建时
|
|
982
|
-
// 就固定了,只追加 model/selection 改不了路由(实机:模型换成 Qwen,provider
|
|
983
|
-
// 仍是 deepseek-official,于是报缺 DEEPSEEK_API_KEY 且一直不恢复)。
|
|
984
|
-
const routeChanged = (current.provider ?? '') !== (nextConfig.provider ?? '')
|
|
985
|
-
|| (current.model ?? '') !== (nextConfig.model ?? '');
|
|
986
|
-
await this.append(command, 'member/config-updated', {
|
|
987
|
-
memberId: member.id,
|
|
988
|
-
config: nextConfig,
|
|
989
|
-
configVersion: nextConfig.configVersion,
|
|
990
|
-
before: result.before,
|
|
991
|
-
reason: nextConfig.reason,
|
|
992
|
-
routeChanged,
|
|
993
|
-
});
|
|
994
|
-
return {
|
|
995
|
-
member: { ...member, config: nextConfig, configVersion: nextConfig.configVersion, routeStale: routeChanged ? true : member.routeStale === true },
|
|
996
|
-
config: nextConfig,
|
|
997
|
-
changed: true,
|
|
998
|
-
routeChanged,
|
|
999
|
-
};
|
|
1000
|
-
}
|
|
1001
|
-
|
|
1002
|
-
async retryMember(command, payload) {
|
|
1003
|
-
const member = this.state.members?.[payload.memberId];
|
|
1004
|
-
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.memberId)} not found`);
|
|
1005
|
-
// 退役成员的重启必须走 member.rejoin(清 talentPool/leftTeamAt)。
|
|
1006
|
-
if (member.status === 'retired') fail(ERRORS.INVALID_STATE, `member ${member.name ?? member.id} is retired; use member.rejoin`);
|
|
1007
|
-
const project = this.state.projects?.[command.projectId];
|
|
1008
|
-
const isHuman = command.actor.kind === 'human';
|
|
1009
|
-
const isLead = project?.ownerMemberId === command.actor.memberId || project?.ownerId === command.actor.memberId;
|
|
1010
|
-
if (!isHuman && !isLead) fail(ERRORS.UNAUTHORIZED, 'only the Project owner or Human may retry a member');
|
|
1011
|
-
await this.append(command, 'member/retry-requested', {
|
|
1012
|
-
memberId: member.id,
|
|
1013
|
-
reason: typeof payload.reason === 'string' ? payload.reason : '',
|
|
1014
|
-
});
|
|
1015
|
-
return { member: { ...member, status: 'provisioning' } };
|
|
1016
|
-
}
|
|
1017
|
-
|
|
1018
|
-
/** Host/Waker calls these; actor is system, never a Human decision. */
|
|
1019
|
-
async recordMemberFailure(memberId, failure, projectId = Object.keys(this.state.projects ?? {})[0]) {
|
|
1020
|
-
const member = this.state.members?.[memberId];
|
|
1021
|
-
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(memberId)} not found`);
|
|
1022
|
-
// 退役成员不该被迟到的 LLM 失败改成 failed(fold 对这条事件没有 retired 守卫,
|
|
1023
|
-
// 之后 member.bind 就能把 ta 复活)。直接忽略,不写事件。
|
|
1024
|
-
if (member.status === 'retired') return null;
|
|
1025
|
-
const attempt = Number.isSafeInteger(failure.attempt) ? failure.attempt : (member.lastFailure?.attempt ?? 0) + 1;
|
|
1026
|
-
const fatal = failure.category === 'auth' || failure.category === 'billing' || failure.category === 'policy' || failure.category === 'unknown';
|
|
1027
|
-
// Tool-argument and provider dumps can run to kilobytes; the ledger and
|
|
1028
|
-
// the risk list only ever need a human-readable first act of the error.
|
|
1029
|
-
const message = typeof failure.message === 'string' && failure.message.length > 400
|
|
1030
|
-
? failure.message.slice(0, 400) + '…'
|
|
1031
|
-
: failure.message;
|
|
1032
|
-
const recorded = { ...failure, message, attempt };
|
|
1033
|
-
await this.ledger.append({
|
|
1034
|
-
type: 'member/llm-failed',
|
|
1035
|
-
payload: { ...recorded, memberId, fatal },
|
|
1036
|
-
actor: { kind: 'system' },
|
|
1037
|
-
projectId,
|
|
1038
|
-
at: this.now(),
|
|
1039
|
-
});
|
|
1040
|
-
this.diag?.append({
|
|
1041
|
-
ev: fatal ? 'member.fail' : 'member.llm-failed',
|
|
1042
|
-
memberId,
|
|
1043
|
-
category: recorded.category,
|
|
1044
|
-
attempt,
|
|
1045
|
-
provider: recorded.provider ?? null,
|
|
1046
|
-
model: recorded.model ?? null,
|
|
1047
|
-
projectId,
|
|
1048
|
-
});
|
|
1049
|
-
let inboxItem = null;
|
|
1050
|
-
if (fatal) {
|
|
1051
|
-
const humanId = this.humanId();
|
|
1052
|
-
// 去重必须用自己的判别字段:`ref.memberId` 在 requestDecision 里表示
|
|
1053
|
-
// 「申请人」,与这里「失败的成员」同名不同义——成员只要有一条自己提的
|
|
1054
|
-
// 未决决策,ta 的致命失败就再也不会生成升级项。
|
|
1055
|
-
const duplicate = humanId === null ? undefined : Object.values(this.state.inbox ?? {}).find((item) =>
|
|
1056
|
-
item.memberId === humanId
|
|
1057
|
-
&& item.requiresDecision === true
|
|
1058
|
-
&& (item.ref?.kind === 'member_failure'
|
|
1059
|
-
? item.ref?.failedMemberId === memberId
|
|
1060
|
-
: item.ref?.kind === undefined && item.ref?.memberId === memberId && item.ref?.category !== undefined)
|
|
1061
|
-
&& !['resolved', 'dismissed', 'superseded'].includes(item.state));
|
|
1062
|
-
if (humanId !== null && duplicate === undefined) {
|
|
1063
|
-
const activeTask = Object.values(this.state.tasks ?? {}).find((task) =>
|
|
1064
|
-
task.tombstone !== true
|
|
1065
|
-
&& ['pending', 'in_progress', 'pending_acceptance'].includes(task.status)
|
|
1066
|
-
&& (task.ownerId === memberId || task.assigneeId === memberId));
|
|
1067
|
-
const taskId = recorded.taskId ?? activeTask?.id ?? null;
|
|
1068
|
-
inboxItem = createInboxItem({
|
|
1069
|
-
memberId: humanId,
|
|
1070
|
-
type: 'decision_required',
|
|
1071
|
-
ref: { kind: 'member_failure', failedMemberId: memberId, memberId, category: recorded.category, taskId },
|
|
1072
|
-
requiresDecision: true,
|
|
1073
|
-
}, { at: this.now() });
|
|
1074
|
-
await this.ledger.append({
|
|
1075
|
-
type: 'inbox/item-created',
|
|
1076
|
-
payload: { itemId: inboxItem.id, ...inboxItem },
|
|
1077
|
-
actor: { kind: 'system' },
|
|
1078
|
-
projectId,
|
|
1079
|
-
at: this.now(),
|
|
1080
|
-
});
|
|
1081
|
-
}
|
|
1082
|
-
}
|
|
1083
|
-
return {
|
|
1084
|
-
member: { ...member, lastFailure: recorded, attempts: attempt, status: fatal ? 'failed' : member.status },
|
|
1085
|
-
inboxItem,
|
|
1086
|
-
};
|
|
1087
|
-
}
|
|
1088
|
-
|
|
1089
|
-
/** Fallback changes are system-authored config events, rollback-able by Human. */
|
|
1090
|
-
async applySystemFallback(memberId, patch, reason = 'llm-fallback', projectId = Object.keys(this.state.projects ?? {})[0]) {
|
|
1091
|
-
const member = this.state.members?.[memberId];
|
|
1092
|
-
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(memberId)} not found`);
|
|
1093
|
-
const current = normalizeMemberConfig(member.config ?? {});
|
|
1094
|
-
const result = applyMemberConfigPatch(current, patch, {
|
|
1095
|
-
policy: this.memberConfigPolicy,
|
|
1096
|
-
configVersion: member.configVersion ?? 0,
|
|
1097
|
-
});
|
|
1098
|
-
if (!result.changed) return { member, config: current, changed: false };
|
|
1099
|
-
this.diag?.append({
|
|
1100
|
-
ev: 'member.fallback',
|
|
1101
|
-
memberId,
|
|
1102
|
-
reason,
|
|
1103
|
-
patch,
|
|
1104
|
-
projectId,
|
|
1105
|
-
});
|
|
1106
|
-
const nextConfig = {
|
|
1107
|
-
...result.config,
|
|
1108
|
-
updatedBy: 'system',
|
|
1109
|
-
updatedAt: this.now(),
|
|
1110
|
-
reason,
|
|
1111
|
-
};
|
|
1112
|
-
await this.ledger.append({
|
|
1113
|
-
type: 'member/config-updated',
|
|
1114
|
-
payload: {
|
|
1115
|
-
memberId,
|
|
1116
|
-
config: nextConfig,
|
|
1117
|
-
configVersion: nextConfig.configVersion,
|
|
1118
|
-
before: result.before,
|
|
1119
|
-
reason,
|
|
1120
|
-
},
|
|
1121
|
-
actor: { kind: 'system' },
|
|
1122
|
-
projectId,
|
|
1123
|
-
at: this.now(),
|
|
1124
|
-
});
|
|
1125
|
-
return { member: { ...member, config: nextConfig, configVersion: nextConfig.configVersion }, config: nextConfig, changed: true };
|
|
1126
|
-
}
|
|
1127
|
-
|
|
1128
|
-
async recordMemberRecovery(memberId, attempt, effectiveConfig, projectId = Object.keys(this.state.projects ?? {})[0]) {
|
|
1129
|
-
const member = this.state.members?.[memberId];
|
|
1130
|
-
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(memberId)} not found`);
|
|
1131
|
-
await this.ledger.append({
|
|
1132
|
-
type: 'member/recovered',
|
|
1133
|
-
payload: { memberId, attempt, effectiveConfig: effectiveConfig ?? member.config ?? null },
|
|
1134
|
-
actor: { kind: 'system' },
|
|
1135
|
-
projectId,
|
|
1136
|
-
at: this.now(),
|
|
1137
|
-
});
|
|
1138
|
-
this.diag?.append({ ev: 'member.recovered', memberId, attempt, projectId });
|
|
1139
|
-
return { member: { ...member, status: 'running', lastRecoveredAt: this.now() } };
|
|
1140
|
-
}
|
|
1141
|
-
|
|
1142
|
-
async createTask(command, payload) {
|
|
1143
|
-
const state = this.state;
|
|
1144
|
-
const projectId = command.projectId;
|
|
1145
|
-
const project = state.projects?.[projectId];
|
|
1146
|
-
if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
1147
|
-
const number = Math.max(0, ...Object.values(state.tasks ?? {}).map((task) => task.number ?? 0)) + 1;
|
|
1148
|
-
const ownerId = payload.ownerId ?? project.ownerMemberId ?? project.ownerId;
|
|
1149
|
-
const qaRequired = payload.qaRequired === true;
|
|
1150
|
-
const qaChecklist = Array.isArray(payload.qaChecklist) ? payload.qaChecklist.filter((item) => typeof item === 'string' && item.trim() !== '') : [];
|
|
1151
|
-
if (qaRequired && qaChecklist.length === 0) {
|
|
1152
|
-
fail(ERRORS.INVALID_ARGUMENT, 'qaRequired needs at least one qaChecklist item');
|
|
1153
|
-
}
|
|
1154
|
-
// 幽灵成员 id / 不存在的依赖会被直接写进投影,且没有修复命令:卡的 owner 永远
|
|
1155
|
-
// 不对,或被一个不存在的依赖永久 blocked。
|
|
1156
|
-
// 只校验**显式传入**的 ownerId:默认值来自 project.ownerMemberId,若该成员已退役,
|
|
1157
|
-
// 校验会把工作台的建卡入口整个封死(退役不转移所有权)。
|
|
1158
|
-
if (typeof payload.ownerId === 'string' && payload.ownerId !== '') requireMemberRef(state, payload.ownerId, 'ownerId');
|
|
1159
|
-
requireMemberRef(state, payload.assigneeId, 'assigneeId', { agentOnly: true });
|
|
1160
|
-
if (Array.isArray(payload.blockedBy)) {
|
|
1161
|
-
for (const dependency of payload.blockedBy) {
|
|
1162
|
-
if (typeof dependency !== 'string' || Object.hasOwn(state.tasks ?? {}, dependency) !== true) {
|
|
1163
|
-
fail(ERRORS.INVALID_ARGUMENT, `blockedBy ${String(dependency)} is not a Task of this project`);
|
|
1164
|
-
}
|
|
1165
|
-
// 删除是 tombstone 而不是物理移除,而依赖判定只认 status === 'done':
|
|
1166
|
-
// 指向一张已删除的卡会让新卡**永久** blocked,且没有修复命令。
|
|
1167
|
-
const dependencyTask = state.tasks[dependency];
|
|
1168
|
-
if (dependencyTask?.tombstone === true || dependencyTask?.status === 'deleted' || dependencyTask?.status === 'cancelled') {
|
|
1169
|
-
fail(ERRORS.INVALID_ARGUMENT, `blockedBy ${String(dependency)} can never complete (it is ${dependencyTask?.tombstone === true ? 'deleted' : String(dependencyTask?.status)})`);
|
|
1170
|
-
}
|
|
1171
|
-
}
|
|
1172
|
-
}
|
|
1173
|
-
const title = typeof payload.title === 'string' ? payload.title.trim() : '';
|
|
1174
|
-
const resultDefinition = typeof payload.resultDefinition === 'string' ? payload.resultDefinition.trim() : '';
|
|
1175
|
-
const duplicate = Object.values(state.tasks ?? {}).find((candidate) =>
|
|
1176
|
-
candidate.tombstone !== true
|
|
1177
|
-
&& ['pending', 'in_progress', 'pending_acceptance'].includes(candidate.status)
|
|
1178
|
-
&& candidate.ownerId === ownerId
|
|
1179
|
-
&& candidate.title === title
|
|
1180
|
-
&& candidate.resultDefinition === resultDefinition);
|
|
1181
|
-
if (duplicate !== undefined && payload.allowDuplicate !== true) {
|
|
1182
|
-
fail(ERRORS.CONFLICT, 'an active Task with the same title, result definition and owner already exists', {
|
|
1183
|
-
details: { taskId: duplicate.id, number: duplicate.number, title: duplicate.title },
|
|
1184
|
-
});
|
|
1185
|
-
}
|
|
1186
|
-
const { task, event } = createTask({
|
|
1187
|
-
number,
|
|
1188
|
-
title,
|
|
1189
|
-
resultDefinition,
|
|
1190
|
-
ownerId,
|
|
1191
|
-
assigneeId: payload.assigneeId,
|
|
1192
|
-
blockedBy: payload.blockedBy,
|
|
1193
|
-
writeScopes: payload.writeScopes,
|
|
1194
|
-
irreversible: payload.irreversible,
|
|
1195
|
-
qaRequired,
|
|
1196
|
-
qaChecklist,
|
|
1197
|
-
originRefs: payload.originRefs,
|
|
1198
|
-
at: this.now(),
|
|
1199
|
-
});
|
|
1200
|
-
await this.ledger.append({ ...event, actor: command.actor, correlationId: command.correlationId, at: this.now(), projectId });
|
|
1201
|
-
return { task };
|
|
1202
|
-
}
|
|
1203
|
-
|
|
1204
|
-
async taskCommand(command, action) {
|
|
1205
|
-
const state = this.state;
|
|
1206
|
-
const taskId = command.payload?.taskId;
|
|
1207
|
-
const task = state.tasks?.[taskId];
|
|
1208
|
-
if (task === undefined) fail(ERRORS.NOT_FOUND, `task ${String(taskId)} not found`);
|
|
1209
|
-
const expectedRevision = command.payload?.expectedRevision;
|
|
1210
|
-
// 目标成员必须真实存在且可用:幽灵 id 写进投影后,真实成员 claim 会一直
|
|
1211
|
-
// 撞 E_ALREADY_CLAIMED,只能由 owner/Human 重新指派才能解锁。
|
|
1212
|
-
const requireAgentMember = (memberId, field) => requireMemberRef(this.state, memberId, field, { agentOnly: true });
|
|
1213
|
-
let outcome;
|
|
1214
|
-
switch (action) {
|
|
1215
|
-
case 'claim': outcome = claimTask(task, command.actor, state.tasks ?? {}, { expectedRevision, at: this.now() }); break;
|
|
1216
|
-
case 'release': outcome = releaseTask(task, command.actor, { expectedRevision, reason: command.payload?.reason, at: this.now() }); break;
|
|
1217
|
-
case 'assign':
|
|
1218
|
-
requireAgentMember(command.payload?.assigneeId, 'assigneeId');
|
|
1219
|
-
outcome = assignTask(task, command.actor, command.payload?.assigneeId, { expectedRevision, at: this.now() });
|
|
1220
|
-
break;
|
|
1221
|
-
case 'submit': outcome = submitTask(task, command.actor, { summary: command.payload?.summary, evidence: command.payload?.evidence }, { expectedRevision, at: this.now() }); break;
|
|
1222
|
-
case 'accept': {
|
|
1223
|
-
// Agent actors are pre-resolved by dispatch; resolve defensively here
|
|
1224
|
-
// so an unknown memberId fails closed instead of skipping the QA gate.
|
|
1225
|
-
const reviewer = command.actor.kind === 'agent'
|
|
1226
|
-
? this.state.members?.[command.actor.memberId] ?? undefined
|
|
1227
|
-
: null;
|
|
1228
|
-
if (command.actor.kind === 'agent' && reviewer === undefined) {
|
|
1229
|
-
fail(ERRORS.UNAUTHORIZED, `agent actor ${String(command.actor.memberId ?? '?')} is not a Team member`);
|
|
1230
|
-
}
|
|
1231
|
-
if (task.qaRequired === true && reviewer !== null && !isQaMember(reviewer)) {
|
|
1232
|
-
fail(ERRORS.INVALID_STATE, 'this task requires a QA reviewer');
|
|
1233
|
-
}
|
|
1234
|
-
const checklist = Array.isArray(task.qaChecklist) ? task.qaChecklist : [];
|
|
1235
|
-
const checks = Array.isArray(command.payload?.checks) ? command.payload.checks : [];
|
|
1236
|
-
// 门禁对**所有**验收人都生效:Human 是 UI 上唯一的验收人,之前把它
|
|
1237
|
-
// 排除在 `reviewer !== null` 之外,等于让 qaRequired 的卡零勾选通过,
|
|
1238
|
-
// 未校验的 checks 还会原样写进 task.qaChecks。
|
|
1239
|
-
if (checklist.length > 0) {
|
|
1240
|
-
// QA 门禁必须逐项对应 task.qaChecklist:只比较条数 + passed 会让
|
|
1241
|
-
// 任意 item 文本(含伪造/无关条目)通过门禁,与 tool schema 契约
|
|
1242
|
-
// "Exact qaChecklist item" 不一致。
|
|
1243
|
-
const pending = checklist.map((item) => String(item));
|
|
1244
|
-
for (const check of checks) {
|
|
1245
|
-
if (check?.passed !== true) fail(ERRORS.INVALID_STATE, 'every QA checklist item must pass before acceptance');
|
|
1246
|
-
const text = typeof check?.item === 'string' ? check.item : '';
|
|
1247
|
-
const at = pending.indexOf(text);
|
|
1248
|
-
if (at === -1) {
|
|
1249
|
-
fail(ERRORS.INVALID_ARGUMENT, `unknown QA checklist item: ${text === '' ? '(empty)' : text}`);
|
|
1250
|
-
}
|
|
1251
|
-
pending.splice(at, 1);
|
|
1252
|
-
}
|
|
1253
|
-
if (pending.length > 0) {
|
|
1254
|
-
fail(ERRORS.INVALID_STATE, `QA checklist item not verified: ${pending[0]}`);
|
|
1255
|
-
}
|
|
1256
|
-
} else if (checks.length > 0) {
|
|
1257
|
-
// 没有清单却提交了勾选:不接受未知证据,避免写进投影后无从核对。
|
|
1258
|
-
fail(ERRORS.INVALID_ARGUMENT, 'this task has no QA checklist; do not submit checks');
|
|
1259
|
-
}
|
|
1260
|
-
outcome = acceptTask(task, command.actor, {
|
|
1261
|
-
note: command.payload?.note,
|
|
1262
|
-
confirmed: command.payload?.confirmed,
|
|
1263
|
-
qaChecks: checks,
|
|
1264
|
-
}, { expectedRevision, at: this.now() });
|
|
1265
|
-
break;
|
|
1266
|
-
}
|
|
1267
|
-
case 'request_changes': outcome = requestChangesTask(task, command.actor, { note: command.payload?.note }, { expectedRevision, at: this.now() }); break;
|
|
1268
|
-
case 'cancel': outcome = cancelTask(task, command.actor, { reason: command.payload?.reason, expectedRevision, at: this.now() }); break;
|
|
1269
|
-
case 'reopen': outcome = reopenTask(task, command.actor, { reason: command.payload?.reason, expectedRevision, members: state.members, at: this.now() }); break;
|
|
1270
|
-
case 'reassign':
|
|
1271
|
-
requireAgentMember(command.payload?.ownerId, 'ownerId');
|
|
1272
|
-
outcome = reassignTask(task, command.actor, command.payload?.ownerId, { expectedRevision, reason: command.payload?.reason, at: this.now() });
|
|
1273
|
-
break;
|
|
1274
|
-
case 'delete': outcome = deleteTask(task, command.actor, { expectedRevision, at: this.now() }); break;
|
|
1275
|
-
default: fail(ERRORS.INVALID_ARGUMENT, `unknown task action: ${action}`);
|
|
1276
|
-
}
|
|
1277
|
-
await this.ledger.append({ ...outcome.event, actor: command.actor, correlationId: command.correlationId, projectId: command.projectId, at: this.now() });
|
|
1278
|
-
// fold 会丢弃陈旧 revision 的事件(revision <= 当前),务必返回已提交的投影,
|
|
1279
|
-
// 否则并发 claim/accept 的失败方会收到“成功”并发出错误的 follower 通知。
|
|
1280
|
-
const committed = this.state.tasks?.[outcome.task.id] ?? outcome.task;
|
|
1281
|
-
if (action === 'accept') await this.notifyTaskFollowers(committed, command);
|
|
1282
|
-
return { task: committed, event: outcome.event };
|
|
1283
|
-
}
|
|
1284
|
-
|
|
1285
|
-
async convert(command, payload) {
|
|
1286
|
-
const sourceEventIds = payload.sourceEventIds;
|
|
1287
|
-
if (!Array.isArray(sourceEventIds) || sourceEventIds.length === 0) fail(ERRORS.INVALID_ARGUMENT, 'sourceEventIds is required');
|
|
1288
|
-
const state = this.state;
|
|
1289
|
-
const existing = Object.values(state.tasks ?? {}).find((task) =>
|
|
1290
|
-
(task.originRefs ?? []).some((ref) => sourceEventIds.includes(ref)));
|
|
1291
|
-
if (existing !== undefined) {
|
|
1292
|
-
fail(ERRORS.CONFLICT, `already converted to ${existing.id}`, { details: { taskId: existing.id } });
|
|
1293
|
-
}
|
|
1294
|
-
const result = await this.createTask(command, {
|
|
1295
|
-
title: payload.title,
|
|
1296
|
-
resultDefinition: payload.doneCriteria ?? payload.resultDefinition,
|
|
1297
|
-
ownerId: payload.ownerId,
|
|
1298
|
-
assigneeId: payload.assigneeId,
|
|
1299
|
-
writeScopes: payload.writeScopes,
|
|
1300
|
-
originRefs: sourceEventIds,
|
|
1301
|
-
});
|
|
1302
|
-
return result;
|
|
1303
|
-
}
|
|
1304
|
-
|
|
1305
|
-
/** Followers get one report when a Task is accepted; unfollow removes future reports. */
|
|
1306
|
-
async notifyTaskFollowers(task, command) {
|
|
1307
|
-
const followers = Array.isArray(this.state.followers?.[task.id]) ? this.state.followers[task.id] : [];
|
|
1308
|
-
for (const followerId of followers) {
|
|
1309
|
-
if (followerId === command.actor.memberId) continue;
|
|
1310
|
-
const duplicate = Object.values(this.state.inbox ?? {}).find((item) =>
|
|
1311
|
-
item.memberId === followerId
|
|
1312
|
-
&& item.type === 'followed_task_update'
|
|
1313
|
-
&& item.ref?.taskId === task.id
|
|
1314
|
-
&& item.ref?.kind === 'completed'
|
|
1315
|
-
&& item.state === 'unread');
|
|
1316
|
-
if (duplicate !== undefined) continue;
|
|
1317
|
-
const item = createInboxItem({
|
|
1318
|
-
memberId: followerId,
|
|
1319
|
-
type: 'followed_task_update',
|
|
1320
|
-
ref: { taskId: task.id, title: task.title, kind: 'completed' },
|
|
1321
|
-
requiresDecision: false,
|
|
1322
|
-
}, { at: this.now() });
|
|
1323
|
-
await this.ledger.append({
|
|
1324
|
-
type: 'inbox/item-created',
|
|
1325
|
-
payload: { itemId: item.id, ...item },
|
|
1326
|
-
actor: { kind: 'system' },
|
|
1327
|
-
projectId: command.projectId,
|
|
1328
|
-
at: this.now(),
|
|
1329
|
-
});
|
|
1330
|
-
}
|
|
1331
|
-
}
|
|
1332
|
-
|
|
1333
|
-
async follow(command, payload) {
|
|
1334
|
-
if (typeof payload.taskId !== 'string') fail(ERRORS.INVALID_ARGUMENT, 'taskId is required');
|
|
1335
|
-
const following = payload.following === true;
|
|
1336
|
-
await this.ledger.append({
|
|
1337
|
-
type: following ? 'task/followed' : 'task/unfollowed',
|
|
1338
|
-
payload: { taskId: payload.taskId, memberId: command.actor.memberId ?? this.humanId() },
|
|
1339
|
-
actor: command.actor,
|
|
1340
|
-
correlationId: command.correlationId,
|
|
1341
|
-
projectId: command.projectId,
|
|
1342
|
-
at: this.now(),
|
|
1343
|
-
});
|
|
1344
|
-
return { following };
|
|
1345
|
-
}
|
|
1346
|
-
|
|
1347
|
-
async postThread(command, payload) {
|
|
1348
|
-
const taskId = payload.taskId;
|
|
1349
|
-
if (this.state.tasks?.[taskId] === undefined) fail(ERRORS.NOT_FOUND, `task ${String(taskId)} not found`);
|
|
1350
|
-
// headSeq 的读取与 ledger.append 之间有一次 await:两个并发 reply 会读到同一个
|
|
1351
|
-
// headSeq、各自生成 seq=headSeq+1,fold 按 seq 去重后第二条被永久丢弃,而两次
|
|
1352
|
-
// 调用都返回成功。用 runExclusive 让「读头 + 分配 seq + 提交」串行。
|
|
1353
|
-
return this.runExclusive(async () => {
|
|
1354
|
-
if (this.state.tasks?.[taskId] === undefined) fail(ERRORS.NOT_FOUND, `task ${String(taskId)} not found`);
|
|
1355
|
-
const thread = this.state.threads?.[taskId] ?? createThread(taskId);
|
|
1356
|
-
const actorKind = command.actor.kind;
|
|
1357
|
-
const authorId = command.actor.memberId ?? this.humanId();
|
|
1358
|
-
const outcome = appendReply(thread, { authorId, actorKind, baseSeq: payload.baseSeq, body: payload.body, refs: payload.refs }, { at: this.now() });
|
|
1359
|
-
await this.ledger.append({
|
|
1360
|
-
type: 'thread/posted',
|
|
1361
|
-
payload: { taskId, ...outcome.entry },
|
|
1362
|
-
actor: command.actor,
|
|
1363
|
-
correlationId: command.correlationId,
|
|
1364
|
-
projectId: command.projectId,
|
|
1365
|
-
at: this.now(),
|
|
1366
|
-
});
|
|
1367
|
-
return { thread: this.state.threads?.[taskId] ?? outcome.thread, entry: outcome.entry };
|
|
1368
|
-
});
|
|
1369
|
-
}
|
|
1370
|
-
|
|
1371
|
-
/** PMO: answer all pending structured questions with the max-value policy. */
|
|
1372
|
-
async autoAnswerDecisions(projectId = Object.keys(this.state.projects ?? {})[0]) {
|
|
1373
|
-
const humanId = this.humanId();
|
|
1374
|
-
// 合同是「返回回答列表」:这里曾返回数字 0,调用方按数组迭代时抛 TypeError,
|
|
1375
|
-
// 整个 PMO tick 被打断且每个 tick 都重复失败。
|
|
1376
|
-
if (humanId === null || humanId === undefined) return [];
|
|
1377
|
-
// 只自动回答**有结构化问题**的决策项。成员致命失败生成的升级项没有 questions,
|
|
1378
|
-
// 自动作答会用一句通用话术把它 resolved,Human 再也看不到真正的失败。
|
|
1379
|
-
const items = Object.values(this.state.inbox ?? {}).filter((item) =>
|
|
1380
|
-
item.memberId === humanId
|
|
1381
|
-
&& item.type === 'decision_required'
|
|
1382
|
-
&& item.state === 'unread'
|
|
1383
|
-
&& Array.isArray(item.ref?.questions)
|
|
1384
|
-
&& item.ref.questions.length > 0);
|
|
1385
|
-
const results = [];
|
|
1386
|
-
for (const item of items) {
|
|
1387
|
-
const questions = Array.isArray(item.ref?.questions) ? item.ref.questions : [];
|
|
1388
|
-
const answers = chooseDecisionAnswers(questions);
|
|
1389
|
-
// 自动作答也要在锁内:它与 thread.post 一样是「读 head → 分配 seq → append」,
|
|
1390
|
-
// 并发时同 seq 会被 fold 静默丢弃,而 Human 的明确决策可能被自动决策替换。
|
|
1391
|
-
results.push(await this.runExclusive(() => this.autoAnswerDecision(item, answers, projectId)));
|
|
1392
|
-
}
|
|
1393
|
-
return results;
|
|
1394
|
-
}
|
|
1395
|
-
|
|
1396
|
-
async autoAnswerDecision(item, answers, projectId = Object.keys(this.state.projects ?? {})[0]) {
|
|
1397
|
-
const taskId = typeof item.ref?.taskId === 'string' ? item.ref.taskId : null;
|
|
1398
|
-
const task = taskId === null ? undefined : this.state.tasks?.[taskId];
|
|
1399
|
-
const questionById = new Map((item.ref?.questions ?? []).map((question) => [question.id, question.text]));
|
|
1400
|
-
const lines = answers.length > 0
|
|
1401
|
-
? answers.map((answer) => `- ${questionById.get(answer.id) ?? answer.id}: ${answer.value}`)
|
|
1402
|
-
: ['- 无结构化问题:按当前 Task/Thread 的最高价值路径推进,不等待 Human。'];
|
|
1403
|
-
const body = `【PMO 自动决策】按最高价值建议执行,不需要 Human 再确认:\n${lines.join('\n')}`;
|
|
1404
|
-
let entry = null;
|
|
1405
|
-
if (task !== undefined) {
|
|
1406
|
-
const thread = this.state.threads?.[task.id] ?? createThread(task.id);
|
|
1407
|
-
const outcome = appendReply(thread, {
|
|
1408
|
-
authorId: 'mem_pmo',
|
|
1409
|
-
actorKind: 'system',
|
|
1410
|
-
baseSeq: thread.headSeq,
|
|
1411
|
-
body,
|
|
1412
|
-
}, { at: this.now() });
|
|
1413
|
-
await this.ledger.append({
|
|
1414
|
-
type: 'thread/posted',
|
|
1415
|
-
payload: { taskId: task.id, ...outcome.entry },
|
|
1416
|
-
actor: { kind: 'system', memberId: 'mem_pmo' },
|
|
1417
|
-
projectId,
|
|
1418
|
-
at: this.now(),
|
|
1419
|
-
});
|
|
1420
|
-
entry = outcome.entry;
|
|
1421
|
-
}
|
|
1422
|
-
const next = ackInboxItem(item, {
|
|
1423
|
-
disposition: 'done',
|
|
1424
|
-
decision: { answers, auto: true, by: 'mem_pmo', body },
|
|
1425
|
-
}, { at: this.now() });
|
|
1426
|
-
this.diag?.append({
|
|
1427
|
-
ev: 'pmo.auto-answer',
|
|
1428
|
-
itemId: item.id,
|
|
1429
|
-
taskId,
|
|
1430
|
-
answers: answers.length,
|
|
1431
|
-
projectId,
|
|
1432
|
-
});
|
|
1433
|
-
await this.ledger.append({
|
|
1434
|
-
type: 'inbox/acked',
|
|
1435
|
-
payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, decision: next.decision ?? null, at: next.ackedAt },
|
|
1436
|
-
actor: { kind: 'system', memberId: 'mem_pmo' },
|
|
1437
|
-
projectId,
|
|
1438
|
-
at: this.now(),
|
|
1439
|
-
});
|
|
1440
|
-
return { item: next, entry };
|
|
1441
|
-
}
|
|
1442
|
-
|
|
1443
|
-
/** Surface an explicit Human decision request with all questions inline. */
|
|
1444
|
-
async requestDecision(command, payload) {
|
|
1445
|
-
const humanId = this.humanId();
|
|
1446
|
-
if (humanId === null) fail(ERRORS.NOT_FOUND, 'Human member not found');
|
|
1447
|
-
const raw = Array.isArray(payload.questions) ? payload.questions : [];
|
|
1448
|
-
if (raw.length === 0 || raw.length > 20) fail(ERRORS.INVALID_ARGUMENT, 'questions must contain 1..20 items');
|
|
1449
|
-
const questions = raw.map((question, index) => {
|
|
1450
|
-
if (typeof question === 'string') return { id: `q${index + 1}`, text: question.trim() };
|
|
1451
|
-
if (question === null || typeof question !== 'object') fail(ERRORS.INVALID_ARGUMENT, `questions[${index}] must be a string or object`);
|
|
1452
|
-
const text = typeof question.text === 'string' ? question.text.trim() : '';
|
|
1453
|
-
if (text === '') fail(ERRORS.INVALID_ARGUMENT, `questions[${index}].text is required`);
|
|
1454
|
-
const options = Array.isArray(question.options) ? question.options.filter((option) => typeof option === 'string' && option.trim() !== '').slice(0, 12) : [];
|
|
1455
|
-
return {
|
|
1456
|
-
id: typeof question.id === 'string' && question.id !== '' ? question.id : `q${index + 1}`,
|
|
1457
|
-
text,
|
|
1458
|
-
...(options.length ? { options } : {}),
|
|
1459
|
-
...(typeof question.recommendation === 'string' && question.recommendation !== '' ? { recommendation: question.recommendation } : {}),
|
|
1460
|
-
...(typeof question.blocking === 'string' && question.blocking !== '' ? { blocking: question.blocking } : {}),
|
|
1461
|
-
};
|
|
1462
|
-
});
|
|
1463
|
-
const title = typeof payload.title === 'string' && payload.title.trim() !== '' ? payload.title.trim() : '需要你决策';
|
|
1464
|
-
const taskId = typeof payload.taskId === 'string' ? payload.taskId : null;
|
|
1465
|
-
const duplicate = Object.values(this.state.inbox ?? {}).find((item) =>
|
|
1466
|
-
item.memberId === humanId
|
|
1467
|
-
&& item.type === 'decision_required'
|
|
1468
|
-
&& item.ref?.title === title
|
|
1469
|
-
&& item.ref?.taskId === taskId
|
|
1470
|
-
&& !['resolved', 'dismissed', 'superseded'].includes(item.state));
|
|
1471
|
-
if (duplicate !== undefined) return { item: duplicate, duplicate: true };
|
|
1472
|
-
const item = createInboxItem({
|
|
1473
|
-
memberId: humanId,
|
|
1474
|
-
type: 'decision_required',
|
|
1475
|
-
ref: {
|
|
1476
|
-
taskId,
|
|
1477
|
-
title,
|
|
1478
|
-
memberId: command.actor.memberId ?? null,
|
|
1479
|
-
memberName: this.state.members?.[command.actor.memberId]?.name ?? command.actor.memberId ?? null,
|
|
1480
|
-
questions,
|
|
1481
|
-
...(typeof payload.source === 'string' && payload.source !== '' ? { source: payload.source } : {}),
|
|
1482
|
-
},
|
|
1483
|
-
requiresDecision: true,
|
|
1484
|
-
}, { at: this.now() });
|
|
1485
|
-
await this.ledger.append({
|
|
1486
|
-
type: 'inbox/item-created',
|
|
1487
|
-
payload: { itemId: item.id, ...item },
|
|
1488
|
-
actor: command.actor,
|
|
1489
|
-
correlationId: command.correlationId,
|
|
1490
|
-
projectId: command.projectId,
|
|
1491
|
-
at: this.now(),
|
|
1492
|
-
});
|
|
1493
|
-
return { item, duplicate: false };
|
|
1494
|
-
}
|
|
1495
|
-
|
|
1496
|
-
async answerDecision(command, payload) {
|
|
1497
|
-
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may answer a decision');
|
|
1498
|
-
const item = this.state.inbox?.[payload.itemId];
|
|
1499
|
-
if (item === undefined) fail(ERRORS.NOT_FOUND, `inbox item ${String(payload.itemId)} not found`);
|
|
1500
|
-
if (item.type !== 'decision_required' || item.requiresDecision !== true) {
|
|
1501
|
-
fail(ERRORS.INVALID_STATE, 'this inbox item is not a Human decision');
|
|
1502
|
-
}
|
|
1503
|
-
const humanId = command.actor.memberId;
|
|
1504
|
-
if (item.memberId !== humanId) fail(ERRORS.UNAUTHORIZED, 'decision belongs to another member');
|
|
1505
|
-
// 终态前置:已 resolved/dismissed/superseded 的决策项再次提交过去会被接受,
|
|
1506
|
-
// 于是同一决策重复写 Thread 回复,ack 回来的 item 还是旧答案。
|
|
1507
|
-
if (['resolved', 'dismissed', 'superseded', 'done'].includes(item.state)) {
|
|
1508
|
-
fail(ERRORS.INVALID_STATE, `decision ${String(item.id)} is already ${String(item.state)}`);
|
|
1509
|
-
}
|
|
1510
|
-
const answers = (Array.isArray(payload.answers) ? payload.answers : [])
|
|
1511
|
-
.map((answer, index) => ({
|
|
1512
|
-
id: typeof answer?.id === 'string' && answer.id !== '' ? answer.id : `q${index + 1}`,
|
|
1513
|
-
value: typeof answer?.value === 'string' ? answer.value.trim() : '',
|
|
1514
|
-
}))
|
|
1515
|
-
.filter((answer) => answer.value !== '');
|
|
1516
|
-
if (answers.length === 0) fail(ERRORS.INVALID_ARGUMENT, 'at least one answer is required');
|
|
1517
|
-
const questions = Array.isArray(item.ref?.questions) ? item.ref.questions : [];
|
|
1518
|
-
// 决策必须覆盖全部问题:只答一半就把 item 置为 resolved,会让未答的问题
|
|
1519
|
-
// 从待决策表单里消失(UI 有 complete 校验,命令层也必须一致)。
|
|
1520
|
-
if (questions.length > 0) {
|
|
1521
|
-
const known = new Set(questions.map((question) => question.id));
|
|
1522
|
-
const unknown = answers.filter((answer) => !known.has(answer.id)).map((answer) => answer.id);
|
|
1523
|
-
if (unknown.length > 0) fail(ERRORS.INVALID_ARGUMENT, `unknown question id(s): ${unknown.join(', ')}`);
|
|
1524
|
-
const missing = questions.filter((question) => !answers.some((answer) => answer.id === question.id)).map((question) => question.id);
|
|
1525
|
-
if (missing.length > 0) fail(ERRORS.INVALID_ARGUMENT, `every question must be answered; missing: ${missing.join(', ')}`);
|
|
1526
|
-
}
|
|
1527
|
-
const lines = answers.map((answer) => {
|
|
1528
|
-
const question = questions.find((candidate) => candidate.id === answer.id);
|
|
1529
|
-
return `- ${question?.text ?? answer.id}: ${answer.value}`;
|
|
1530
|
-
});
|
|
1531
|
-
const body = `Human 决策:\n${lines.join('\n')}${typeof payload.note === 'string' && payload.note.trim() !== '' ? `\n备注:${payload.note.trim()}` : ''}`;
|
|
1532
|
-
let entry = null;
|
|
1533
|
-
if (typeof item.ref?.taskId === 'string' && this.state.tasks?.[item.ref.taskId] !== undefined) {
|
|
1534
|
-
const taskId = item.ref.taskId;
|
|
1535
|
-
const thread = this.state.threads?.[taskId] ?? createThread(taskId);
|
|
1536
|
-
const outcome = appendReply(thread, {
|
|
1537
|
-
authorId: humanId,
|
|
1538
|
-
actorKind: 'human',
|
|
1539
|
-
baseSeq: thread.headSeq,
|
|
1540
|
-
body,
|
|
1541
|
-
}, { at: this.now() });
|
|
1542
|
-
await this.ledger.append({
|
|
1543
|
-
type: 'thread/posted',
|
|
1544
|
-
payload: { taskId, ...outcome.entry },
|
|
1545
|
-
actor: command.actor,
|
|
1546
|
-
projectId: command.projectId,
|
|
1547
|
-
at: this.now(),
|
|
1548
|
-
});
|
|
1549
|
-
entry = outcome.entry;
|
|
1550
|
-
}
|
|
1551
|
-
const next = ackInboxItem(item, { disposition: 'done', decision: { answers, note: payload.note ?? '', body } }, { at: this.now() });
|
|
1552
|
-
await this.ledger.append({
|
|
1553
|
-
type: 'inbox/acked',
|
|
1554
|
-
payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, decision: next.decision ?? null, at: next.ackedAt },
|
|
1555
|
-
actor: command.actor,
|
|
1556
|
-
projectId: command.projectId,
|
|
1557
|
-
at: this.now(),
|
|
1558
|
-
});
|
|
1559
|
-
return { item: next, entry };
|
|
1560
|
-
}
|
|
1561
|
-
|
|
1562
|
-
async ack(command, payload) {
|
|
1563
|
-
const state = this.state;
|
|
1564
|
-
const item = state.inbox?.[payload.itemId];
|
|
1565
|
-
if (item === undefined) fail(ERRORS.NOT_FOUND, `inbox item ${String(payload.itemId)} not found`);
|
|
1566
|
-
// 归属校验:成员只能处理自己的收件项。缺了这条,任意 agent 可用一个
|
|
1567
|
-
// itemId 把别人的(含 Human 的)决策项标成 resolved。
|
|
1568
|
-
const actorMemberId = command.actor.memberId ?? this.humanId();
|
|
1569
|
-
if (command.actor.kind !== 'human' && item.memberId !== actorMemberId) {
|
|
1570
|
-
fail(ERRORS.UNAUTHORIZED, 'inbox item belongs to another member');
|
|
1571
|
-
}
|
|
1572
|
-
const next = ackInboxItem(item, { disposition: payload.disposition, decision: payload.decision }, { at: this.now() });
|
|
1573
|
-
await this.ledger.append({
|
|
1574
|
-
type: 'inbox/acked',
|
|
1575
|
-
payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, decision: next.decision ?? null, at: next.ackedAt },
|
|
1576
|
-
actor: command.actor,
|
|
1577
|
-
correlationId: command.correlationId,
|
|
1578
|
-
projectId: command.projectId,
|
|
1579
|
-
at: this.now(),
|
|
1580
|
-
});
|
|
1581
|
-
return { item: next };
|
|
1582
|
-
}
|
|
1583
|
-
|
|
1584
|
-
/** Create an inbox item and append it; used by the Waker/observer. */
|
|
1585
|
-
async notify(input, command = { actor: { kind: 'system' } }) {
|
|
1586
|
-
const item = createInboxItem(input, { at: this.now() });
|
|
1587
|
-
await this.ledger.append({
|
|
1588
|
-
type: 'inbox/item-created',
|
|
1589
|
-
payload: { itemId: item.id, ...item },
|
|
1590
|
-
actor: command.actor ?? { kind: 'system' },
|
|
1591
|
-
projectId: command.projectId,
|
|
1592
|
-
at: this.now(),
|
|
1593
|
-
});
|
|
1594
|
-
return item;
|
|
1595
|
-
}
|
|
1596
|
-
}
|
|
1
|
+
import { checkWorkspacePath } from './workspace-path.js';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import pathDefault from 'node:path';
|
|
4
|
+
import { ERRORS, fail } from '../domain/errors.js';
|
|
5
|
+
import { findReportPath, parseDecisionQuestions } from './decision-report.js';
|
|
6
|
+
import { ids } from '../domain/ids.js';
|
|
7
|
+
import { ackInboxItem, createInboxItem, isInformationalThreadMention } from '../domain/inbox.js';
|
|
8
|
+
import { chooseDecisionAnswers } from './pmo.js';
|
|
9
|
+
import {
|
|
10
|
+
acceptTask,
|
|
11
|
+
assignTask,
|
|
12
|
+
cancelTask,
|
|
13
|
+
claimTask,
|
|
14
|
+
createTask,
|
|
15
|
+
deleteTask,
|
|
16
|
+
reassignTask,
|
|
17
|
+
releaseTask,
|
|
18
|
+
reopenTask,
|
|
19
|
+
requestChangesTask,
|
|
20
|
+
submitTask,
|
|
21
|
+
} from '../domain/task.js';
|
|
22
|
+
import { appendReply, createThread } from '../domain/thread.js';
|
|
23
|
+
import { boardView, quadrantsView, taskCard } from './views.js';
|
|
24
|
+
import { applyMemberConfigPatch, normalizeMemberConfig } from '../domain/member-config.js';
|
|
25
|
+
import { MEMBER_STATUS } from '../ledger/fold.js';
|
|
26
|
+
|
|
27
|
+
const MEMBER_STATUS_VALUES = new Set(Object.values(MEMBER_STATUS));
|
|
28
|
+
import { isQaMember, unfinishedTasksFor } from '../domain/member-profile.js';
|
|
29
|
+
|
|
30
|
+
function mentionsHuman(body) {
|
|
31
|
+
return typeof body === 'string'
|
|
32
|
+
&& /(^|[^A-Za-z])(human|@你|待你|需要你|请你|等你|你拍板)([^A-Za-z]|$)/i.test(body);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Team domain service on top of a Project ledger.
|
|
37
|
+
*
|
|
38
|
+
* The ledger is the single writer and owns `state`; this service only:
|
|
39
|
+
* 1. reads the current view from `ledger.state`,
|
|
40
|
+
* 2. validates the command with the pure domain rules,
|
|
41
|
+
* 3. appends one event and returns the committed result.
|
|
42
|
+
*
|
|
43
|
+
* `ledger.append` must update `ledger.state` before resolving (or provide a
|
|
44
|
+
* synchronous state read after an awaited append).
|
|
45
|
+
*/
|
|
46
|
+
/**
|
|
47
|
+
* P6 交接文档:按时序拼接 Human 指令与全部任务关键信息,写入项目工作
|
|
48
|
+
* 目录(交付给别的工具继续开发);账本留痕记录路径。
|
|
49
|
+
*/
|
|
50
|
+
// P6 交接文档生成:Human 指令时序 + 任务全量关键信息,Markdown 落盘。
|
|
51
|
+
function handoffMarkdown(state, project, nowMs) {
|
|
52
|
+
const line = (text) => String(text ?? '').replace(/\r?\n/g, '\n ');
|
|
53
|
+
const out = [];
|
|
54
|
+
out.push(`# 项目交接文档 — ${project.name}`);
|
|
55
|
+
out.push('');
|
|
56
|
+
out.push(`- 生成时间:${new Date(nowMs).toISOString()}`);
|
|
57
|
+
out.push(`- 项目 id:${project.id}`);
|
|
58
|
+
out.push(`- 目标:${project.goal ?? '(未填写)'}`);
|
|
59
|
+
out.push(`- 工作目录:${project.workspacePath}`);
|
|
60
|
+
out.push(`- 运行态:${project.runState === 'stopped' ? '已停止(交接前)' : '运行中'}`);
|
|
61
|
+
out.push('');
|
|
62
|
+
out.push('## 一、Human 指令时序(按账本顺序)');
|
|
63
|
+
out.push('');
|
|
64
|
+
const humanMessages = (state.stream ?? []).filter((entry) => entry.kind === 'human_message');
|
|
65
|
+
if (humanMessages.length === 0) out.push('(无 Human 指令记录)');
|
|
66
|
+
for (const entry of humanMessages) {
|
|
67
|
+
out.push(`- ${new Date(entry.at ?? 0).toISOString()} — ${line(entry.body)}`);
|
|
68
|
+
}
|
|
69
|
+
out.push('');
|
|
70
|
+
out.push('## 二、任务清单(含状态与验收要点)');
|
|
71
|
+
out.push('');
|
|
72
|
+
const tasks = Object.values(state.tasks ?? {}).filter((task) => task.tombstone !== true)
|
|
73
|
+
.sort((left, right) => (left.createdAt ?? 0) - (right.createdAt ?? 0));
|
|
74
|
+
if (tasks.length === 0) out.push('(无任务)');
|
|
75
|
+
for (const task of tasks) {
|
|
76
|
+
out.push(`### #${task.number ?? task.id} ${task.title} — ${task.status}`);
|
|
77
|
+
out.push(`- 结果定义:${line(task.resultDefinition)}`);
|
|
78
|
+
if (task.summary) out.push(`- 提交摘要:${line(task.summary)}`);
|
|
79
|
+
for (const ev of task.evidence ?? []) out.push(`- 证据(${ev.kind}):${line(ev.value)}`);
|
|
80
|
+
if (task.qaChecks?.length) out.push(`- QA 检查:${task.qaChecks.map((c) => `${c.passed ? '✔' : '✘'} ${line(c.text ?? '')}`).join(';')}`);
|
|
81
|
+
if (task.reason) out.push(`- 最近理由:${line(task.reason)}`);
|
|
82
|
+
out.push(`- 责任位:owner=${task.ownerId ?? '—'};assignee=${task.assigneeId ?? '—'};更新于 ${new Date(task.updatedAt ?? 0).toISOString()}`);
|
|
83
|
+
out.push('');
|
|
84
|
+
}
|
|
85
|
+
out.push('## 三、Thread 关键讨论(按任务)');
|
|
86
|
+
out.push('');
|
|
87
|
+
for (const [taskId, thread] of Object.entries(state.threads ?? {})) {
|
|
88
|
+
const entries = thread.entries ?? [];
|
|
89
|
+
if (entries.length === 0) continue;
|
|
90
|
+
out.push(`### Task ${taskId}`);
|
|
91
|
+
for (const entry of entries.slice(-20)) {
|
|
92
|
+
out.push(`- ${new Date(entry.at ?? 0).toISOString()} ${entry.author ?? entry.authorId ?? '—'}:${line(entry.body)}`);
|
|
93
|
+
}
|
|
94
|
+
out.push('');
|
|
95
|
+
}
|
|
96
|
+
out.push('## 四、接手提示');
|
|
97
|
+
out.push('');
|
|
98
|
+
out.push('- 以上内容来自插件账本投影(append-only,时序可信);接手工具可直接在工作目录继续开发。');
|
|
99
|
+
out.push('- 成员的 DSH 会话仍在,如需复用团队请保持项目 runState;如改用其他工具,可停止本项目。');
|
|
100
|
+
return out.join('\n') + '\n';
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 成员引用的统一校验:幽灵 id 写进投影后没有修复命令,卡片会永久挂在不存在的人名下。
|
|
105
|
+
* `agentOnly` 用于只能由 Agent 担任的字段(assignee)。
|
|
106
|
+
*/
|
|
107
|
+
export function requireMemberRef(state, memberId, field, { agentOnly = false } = {}) {
|
|
108
|
+
if (typeof memberId !== 'string' || memberId === '') return;
|
|
109
|
+
const candidate = state?.members?.[memberId];
|
|
110
|
+
if (candidate === undefined) fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} is not a Team member`);
|
|
111
|
+
if (agentOnly && candidate.kind !== 'agent') fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} is not an agent member`);
|
|
112
|
+
if (candidate.status === 'retired') fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} has left the team`);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export class TeamService {
|
|
116
|
+
/**
|
|
117
|
+
* @param {{ ledger: { state: any, append: (input: any) => Promise<any> }, now?: () => number, diag?: { append: (row: any) => any } }} options
|
|
118
|
+
*/
|
|
119
|
+
constructor(options) {
|
|
120
|
+
this.ledger = options.ledger;
|
|
121
|
+
this.now = options.now ?? (() => Date.now());
|
|
122
|
+
this.memberConfigPolicy = options.memberConfigPolicy ?? {};
|
|
123
|
+
/** Diagnostic sink ({ append(row) }); optional so tests run without it. */
|
|
124
|
+
this.diag = options.diag ?? null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
get state() {
|
|
128
|
+
return this.ledger.state;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Serialize a mutation that must observe a fresh projection across an await.
|
|
133
|
+
* `ledger.append` is async, so two concurrent dispatches can both read the
|
|
134
|
+
* same pre-append projection. A rejected run never poisons the chain.
|
|
135
|
+
*/
|
|
136
|
+
runExclusive(work) {
|
|
137
|
+
const run = this.exclusive ?? Promise.resolve();
|
|
138
|
+
const result = run.then(work, work);
|
|
139
|
+
this.exclusive = result.then(() => undefined, () => undefined);
|
|
140
|
+
return result;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The Human member id, derived once per call from the folded state. */
|
|
144
|
+
humanId() {
|
|
145
|
+
return this.state.humanMemberId
|
|
146
|
+
?? Object.values(this.state.members ?? {}).find((member) => member.kind === 'human')?.id
|
|
147
|
+
?? null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Four-column board derived from the same ledger state. */
|
|
151
|
+
board(projectId, options = {}) {
|
|
152
|
+
if (projectId !== undefined && this.state.projects?.[projectId] === undefined) {
|
|
153
|
+
fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
154
|
+
}
|
|
155
|
+
return boardView(this.state, options);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Four-quadrant situation view; Human is the only attention target. */
|
|
159
|
+
quadrants(projectId, options = {}) {
|
|
160
|
+
if (projectId !== undefined && this.state.projects?.[projectId] === undefined) {
|
|
161
|
+
fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
162
|
+
}
|
|
163
|
+
const human = options.humanMemberId ?? this.humanId() ?? 'mem_human';
|
|
164
|
+
return quadrantsView(this.state, { ...options, humanMemberId: human });
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** One page of workbench state; the UI reads this instead of the ledger. */
|
|
168
|
+
bootstrap(projectId, threadTaskId) {
|
|
169
|
+
const state = this.state;
|
|
170
|
+
// 归档项目仍要被「看见」:列表里过滤掉它们,但存在性判定必须用未过滤的
|
|
171
|
+
// 记录——否则归归档项目会被报成 E_NOT_FOUND,与 board()/quadrants() 的口径
|
|
172
|
+
// 打架,且客户端把归档项目渲染成可点的只读行,选中即失败。
|
|
173
|
+
const allProjectRecords = Object.values(state.projects ?? {});
|
|
174
|
+
const projects = allProjectRecords
|
|
175
|
+
.filter((p) => p.status !== 'archived')
|
|
176
|
+
.map((p) => ({
|
|
177
|
+
id: p.id, name: p.name, goal: p.goal ?? '', owner: p.ownerName ?? p.ownerMemberId ?? p.ownerId, workspacePath: p.workspacePath ?? '', pmoAuto: p.pmoAuto !== false, active: p.status !== 'archived',
|
|
178
|
+
runState: p.runState === 'stopped' ? 'stopped' : 'running',
|
|
179
|
+
}));
|
|
180
|
+
const members = Object.values(state.members ?? {}).map((m) => ({
|
|
181
|
+
id: m.id,
|
|
182
|
+
name: m.name,
|
|
183
|
+
role: m.role ?? '',
|
|
184
|
+
status: m.status ?? 'idle',
|
|
185
|
+
kind: m.kind ?? 'agent',
|
|
186
|
+
sessionId: m.sessionId ?? null,
|
|
187
|
+
preset: m.config?.preset ?? m.preset ?? 'standard',
|
|
188
|
+
personality: m.personality ?? '',
|
|
189
|
+
notes: m.notes ?? [],
|
|
190
|
+
skills: m.skills ?? [],
|
|
191
|
+
profileVersion: m.profileVersion ?? 1,
|
|
192
|
+
distillVersion: m.distillVersion ?? 0,
|
|
193
|
+
distilledAt: m.distilledAt ?? null,
|
|
194
|
+
talentPool: m.talentPool === true,
|
|
195
|
+
leftTeamAt: m.leftTeamAt ?? null,
|
|
196
|
+
qa: isQaMember(m),
|
|
197
|
+
config: m.config ?? null,
|
|
198
|
+
configVersion: m.configVersion ?? 0,
|
|
199
|
+
lastFailure: m.lastFailure ?? null,
|
|
200
|
+
attempts: m.attempts ?? 0,
|
|
201
|
+
lastRecoveredAt: m.lastRecoveredAt ?? null,
|
|
202
|
+
}));
|
|
203
|
+
const agents = members.filter((m) => m.kind !== 'human');
|
|
204
|
+
// One Task card shape for board, quadrants and bootstrap; bootstrap only
|
|
205
|
+
// adds the submission bookkeeping the panel needs.
|
|
206
|
+
const tasks = Object.values(state.tasks ?? {})
|
|
207
|
+
.filter((task) => task.tombstone !== true && task.status !== 'deleted')
|
|
208
|
+
.map((task) => ({ ...taskCard(state, task), qaChecks: task.qaChecks ?? [] }));
|
|
209
|
+
const project = projectId === undefined ? projects[0] : projects.find((p) => p.id === projectId);
|
|
210
|
+
// 与 board/quadrants 同口径:显式给了**不存在**的 projectId 必须报错,不能返回
|
|
211
|
+
// 一个 project:null 的空壳让调用方分不清「项目不存在」和「空项目」。
|
|
212
|
+
// 存在性按未过滤记录判定:归档项目是「已归档」,不是「不存在」。
|
|
213
|
+
if (projectId !== undefined && state.projects?.[projectId] === undefined) {
|
|
214
|
+
fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
215
|
+
}
|
|
216
|
+
// 归档项目:仍返回它的只读视图(列表里不出现,但请求它时可用)。
|
|
217
|
+
const archivedProject = projectId !== undefined && project === undefined
|
|
218
|
+
? {
|
|
219
|
+
id: projectId,
|
|
220
|
+
name: state.projects[projectId].name ?? projectId,
|
|
221
|
+
goal: state.projects[projectId].goal ?? '',
|
|
222
|
+
owner: state.projects[projectId].ownerName ?? state.projects[projectId].ownerMemberId ?? null,
|
|
223
|
+
workspacePath: state.projects[projectId].workspacePath ?? '',
|
|
224
|
+
pmoAuto: state.projects[projectId].pmoAuto !== false,
|
|
225
|
+
active: false,
|
|
226
|
+
archived: true,
|
|
227
|
+
runState: state.projects[projectId].runState === 'stopped' ? 'stopped' : 'running',
|
|
228
|
+
}
|
|
229
|
+
: null;
|
|
230
|
+
const selectedProject = project ?? archivedProject ?? undefined;
|
|
231
|
+
// 大规模/长迭代裁剪:面板只需要最近的窗口,全史在账本里按需取。
|
|
232
|
+
// stream 投影本身已封顶(≤500),bootstrap 再按窗口切尾。
|
|
233
|
+
const stream = selectedProject === undefined
|
|
234
|
+
? []
|
|
235
|
+
: (state.stream ?? [])
|
|
236
|
+
.filter((entry) => entry.projectId === selectedProject.id)
|
|
237
|
+
.slice(-200)
|
|
238
|
+
// 客户端按对象读作者(`item.author.kind` / `.name`),账本只有 authorId:
|
|
239
|
+
// 在这里补成 { id, kind, name },否则主对话与 Thread 的作者恒为「—」,
|
|
240
|
+
// human 判定也永远是 false。
|
|
241
|
+
.map((entry) => {
|
|
242
|
+
const member = state.members?.[entry.authorId];
|
|
243
|
+
return {
|
|
244
|
+
...entry,
|
|
245
|
+
author: {
|
|
246
|
+
id: entry.authorId ?? null,
|
|
247
|
+
kind: member?.kind ?? entry.authorKind ?? 'agent',
|
|
248
|
+
name: member?.name ?? entry.authorId ?? '',
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
});
|
|
252
|
+
const selected = threadTaskId ?? tasks.find((task) => task.status === 'in_progress')?.id ?? tasks[0]?.id;
|
|
253
|
+
const threadOf = (taskId) => {
|
|
254
|
+
const full = taskId === undefined || taskId === null ? undefined : state.threads?.[taskId];
|
|
255
|
+
if (full === undefined) return { taskId, headSeq: 0, entries: [], entryTotal: 0 };
|
|
256
|
+
const entries = Array.isArray(full.entries) ? full.entries : [];
|
|
257
|
+
return { ...full, entries: entries.slice(-50), entryTotal: full.headSeq ?? entries.length };
|
|
258
|
+
};
|
|
259
|
+
const thread = selected === undefined ? null : threadOf(selected);
|
|
260
|
+
const threads = Object.fromEntries(tasks.map((task) => [task.id, threadOf(task.id)]));
|
|
261
|
+
const inbox = Object.values(state.inbox ?? {}).filter((item) =>
|
|
262
|
+
(item.memberId === this.humanId())
|
|
263
|
+
&& !isInformationalThreadMention(item));
|
|
264
|
+
return {
|
|
265
|
+
project: selectedProject ?? null,
|
|
266
|
+
projects,
|
|
267
|
+
agents,
|
|
268
|
+
members,
|
|
269
|
+
tasks,
|
|
270
|
+
stream,
|
|
271
|
+
thread,
|
|
272
|
+
threads,
|
|
273
|
+
inbox,
|
|
274
|
+
board: selectedProject === undefined ? null : this.board(selectedProject.id),
|
|
275
|
+
quadrants: selectedProject === undefined ? null : this.quadrants(selectedProject.id),
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Create missing Human decision items for existing Agent Thread messages
|
|
281
|
+
* that explicitly asked Human to decide. Runs on Project open once; the
|
|
282
|
+
* per-entry dedupe makes it idempotent.
|
|
283
|
+
*/
|
|
284
|
+
async backfillHumanMentions(workspacePath = '') {
|
|
285
|
+
const humanId = this.humanId();
|
|
286
|
+
if (humanId === null) return 0;
|
|
287
|
+
const projectId = Object.keys(this.state.projects ?? {})[0];
|
|
288
|
+
// 路径包含性:Thread 正文由 agent 写,正文里的绝对路径不能变成
|
|
289
|
+
// 「读主机任意文件」的通道——只接受项目工作目录内的 .md。
|
|
290
|
+
// 必须按 **realpath** 比较:工作区内的 junction/symlink 指向外部时,
|
|
291
|
+
// 纯词法比较会把它当成「在工作区内」,等于放行任意路径。
|
|
292
|
+
const realOrNull = (value) => {
|
|
293
|
+
try { return realpathSync(value); } catch { return null; }
|
|
294
|
+
};
|
|
295
|
+
const allowedRoot = typeof workspacePath === 'string' && workspacePath !== ''
|
|
296
|
+
? realOrNull(workspacePath) ?? pathDefault.resolve(workspacePath)
|
|
297
|
+
: null;
|
|
298
|
+
const insideWorkspace = (candidate) => {
|
|
299
|
+
if (allowedRoot === null) return false;
|
|
300
|
+
const resolved = realOrNull(candidate) ?? pathDefault.resolve(candidate);
|
|
301
|
+
const relative = pathDefault.relative(allowedRoot, resolved);
|
|
302
|
+
return relative !== '' && !relative.startsWith('..') && !pathDefault.isAbsolute(relative);
|
|
303
|
+
};
|
|
304
|
+
let reportPath = null;
|
|
305
|
+
for (const task of Object.values(this.state.tasks ?? {})) {
|
|
306
|
+
for (const entry of this.state.threads?.[task.id]?.entries ?? []) {
|
|
307
|
+
const found = findReportPath(entry.body);
|
|
308
|
+
if (found !== null && insideWorkspace(found) && existsSync(found)) { reportPath = found; break; }
|
|
309
|
+
}
|
|
310
|
+
if (reportPath !== null) break;
|
|
311
|
+
}
|
|
312
|
+
let reportQuestions = [];
|
|
313
|
+
if (reportPath !== null) {
|
|
314
|
+
try {
|
|
315
|
+
// An agent-authored path drives a server-side read here; cap the
|
|
316
|
+
// read so a giant or adversarial report cannot flood memory.
|
|
317
|
+
if (statSync(reportPath).size > 256 * 1024) reportPath = null;
|
|
318
|
+
} catch { reportPath = null; }
|
|
319
|
+
}
|
|
320
|
+
if (reportPath !== null) {
|
|
321
|
+
try {
|
|
322
|
+
reportQuestions = parseDecisionQuestions(readFileSync(reportPath, 'utf8'));
|
|
323
|
+
} catch { /* report may be unavailable; keep the Thread fallback */ }
|
|
324
|
+
}
|
|
325
|
+
if (reportQuestions.length === 0) return 0;
|
|
326
|
+
const candidates = [];
|
|
327
|
+
for (const task of Object.values(this.state.tasks ?? {})) {
|
|
328
|
+
if (task.tombstone === true) continue;
|
|
329
|
+
for (const entry of this.state.threads?.[task.id]?.entries ?? []) {
|
|
330
|
+
const author = this.state.members?.[entry.authorId];
|
|
331
|
+
if (author?.kind !== 'agent' || !mentionsHuman(entry.body)) continue;
|
|
332
|
+
candidates.push({ task, entry, key: `${task.id}:${entry.seq}` });
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
if (candidates.length > 0) {
|
|
336
|
+
const alreadyStructured = Object.values(this.state.inbox ?? {}).some((item) =>
|
|
337
|
+
item.memberId === humanId
|
|
338
|
+
&& item.ref?.source === reportPath
|
|
339
|
+
&& Array.isArray(item.ref?.questions)
|
|
340
|
+
&& item.ref.questions.length > 0);
|
|
341
|
+
if (alreadyStructured) return 0;
|
|
342
|
+
const chosen = candidates.find((candidate) => /§6|六问/.test(candidate.entry.body))
|
|
343
|
+
?? candidates.sort((left, right) => (right.entry.seq ?? 0) - (left.entry.seq ?? 0))[0];
|
|
344
|
+
const item = createInboxItem({
|
|
345
|
+
memberId: humanId,
|
|
346
|
+
type: 'decision_required',
|
|
347
|
+
ref: {
|
|
348
|
+
taskId: chosen.task.id,
|
|
349
|
+
entrySeq: chosen.entry.seq,
|
|
350
|
+
memberId: chosen.entry.authorId,
|
|
351
|
+
memberName: this.state.members?.[chosen.entry.authorId]?.name ?? chosen.entry.authorId,
|
|
352
|
+
category: 'thread_mention',
|
|
353
|
+
title: `需 Human 决策 · ${reportQuestions.length} 问`,
|
|
354
|
+
questions: reportQuestions,
|
|
355
|
+
source: reportPath,
|
|
356
|
+
},
|
|
357
|
+
requiresDecision: true,
|
|
358
|
+
}, { at: this.now() });
|
|
359
|
+
await this.ledger.append({
|
|
360
|
+
type: 'inbox/item-created',
|
|
361
|
+
payload: { itemId: item.id, ...item },
|
|
362
|
+
actor: { kind: 'system' },
|
|
363
|
+
projectId,
|
|
364
|
+
at: this.now(),
|
|
365
|
+
});
|
|
366
|
+
return 1;
|
|
367
|
+
}
|
|
368
|
+
return 0;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Dispatch one command. The caller is an exact Team member (or Human) and
|
|
373
|
+
* the ledger serializes commands per Project.
|
|
374
|
+
* @param {{ type: string, payload?: any, actor: { kind: string, memberId?: string }, correlationId?: string, projectId?: string }} command
|
|
375
|
+
*/
|
|
376
|
+
async dispatch(command) {
|
|
377
|
+
const payload = command.payload ?? {};
|
|
378
|
+
const actor = command.actor;
|
|
379
|
+
// Diagnostic trail: one entry row per command, one failure row on throw,
|
|
380
|
+
// one done row with the duration in every case. 前置校验失败也必须留痕
|
|
381
|
+
// (errors 档只留 .fail 行,校验抛出必须发生在 try 内才能落行)。
|
|
382
|
+
const startedAt = Date.now();
|
|
383
|
+
const failRow = (code, message) => {
|
|
384
|
+
this.diag?.append({
|
|
385
|
+
ev: 'dispatch.fail',
|
|
386
|
+
type: command.type,
|
|
387
|
+
code,
|
|
388
|
+
projectId: command.projectId ?? null,
|
|
389
|
+
message,
|
|
390
|
+
elapsedMs: Date.now() - startedAt,
|
|
391
|
+
});
|
|
392
|
+
};
|
|
393
|
+
this.diag?.append({
|
|
394
|
+
ev: 'dispatch.start',
|
|
395
|
+
type: command.type,
|
|
396
|
+
actor: actor?.kind ?? null,
|
|
397
|
+
memberId: actor?.memberId ?? null,
|
|
398
|
+
projectId: command.projectId ?? null,
|
|
399
|
+
});
|
|
400
|
+
try {
|
|
401
|
+
if (actor === undefined || (actor.kind !== 'human' && actor.kind !== 'agent')) {
|
|
402
|
+
failRow(ERRORS.UNAUTHORIZED, 'an exact Team member is required');
|
|
403
|
+
fail(ERRORS.UNAUTHORIZED, 'an exact Team member is required');
|
|
404
|
+
}
|
|
405
|
+
// An agent actor must resolve to a live, non-retired member: otherwise a
|
|
406
|
+
// forged or stale memberId would bypass owner/QA checks downstream.
|
|
407
|
+
if (actor.kind === 'agent') {
|
|
408
|
+
const actingMember = this.state.members?.[actor.memberId];
|
|
409
|
+
if (actingMember === undefined || actingMember.kind !== 'agent') {
|
|
410
|
+
failRow(ERRORS.UNAUTHORIZED, `agent actor ${String(actor.memberId ?? '?')} is not a Team member`);
|
|
411
|
+
fail(ERRORS.UNAUTHORIZED, `agent actor ${String(actor.memberId ?? '?')} is not a Team member`);
|
|
412
|
+
}
|
|
413
|
+
if (actingMember.status === 'retired') {
|
|
414
|
+
failRow(ERRORS.INVALID_STATE, `agent ${actingMember.name ?? actingMember.id} is retired`);
|
|
415
|
+
fail(ERRORS.INVALID_STATE, `agent ${actingMember.name ?? actingMember.id} is retired`);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
switch (command.type) {
|
|
419
|
+
case 'project.create': return await this.createProject(command, payload);
|
|
420
|
+
case 'project.owner.update': return await this.changeProjectOwner(command, payload);
|
|
421
|
+
case 'project.workspace.update': return await this.changeProjectWorkspace(command, payload);
|
|
422
|
+
case 'project.repair': return await this.runExclusive(() => this.repairLedger(command));
|
|
423
|
+
case 'project.pmo.update': return await this.setProjectPmo(command, payload);
|
|
424
|
+
case 'project.archive': return await this.setProjectArchive(command, payload);
|
|
425
|
+
case 'project.runState': return await this.setProjectRunState(command, payload);
|
|
426
|
+
case 'project.handoff': return await this.handoffProject(command, payload);
|
|
427
|
+
case 'stream.post': return await this.postStream(command, payload);
|
|
428
|
+
case 'member.add': return await this.addMember(command, payload);
|
|
429
|
+
case 'member.bind': return await this.bindMemberSession(command, payload);
|
|
430
|
+
case 'member.fail': return await this.failMember(command, payload);
|
|
431
|
+
case 'member.retire': return await this.retireMember(command, payload);
|
|
432
|
+
case 'member.profile.update': return await this.updateMemberProfile(command, payload);
|
|
433
|
+
case 'member.evolve': return await this.evolveMember(command, payload);
|
|
434
|
+
case 'member.distill': return await this.distillMember(command, payload);
|
|
435
|
+
case 'member.leave': return await this.leaveMember(command, payload);
|
|
436
|
+
case 'member.rejoin': return await this.rejoinMember(command, payload);
|
|
437
|
+
case 'member.takeover': return await this.takeoverMember(command, payload);
|
|
438
|
+
case 'member.message': return await this.messageMember(command, payload);
|
|
439
|
+
case 'member.note': return await this.addMemberNote(command, payload);
|
|
440
|
+
case 'member.skill': return await this.addMemberSkill(command, payload);
|
|
441
|
+
case 'member.config.update': return await this.updateMemberConfig(command, payload);
|
|
442
|
+
case 'member.retry': return await this.retryMember(command, payload);
|
|
443
|
+
case 'task.create': return await this.runExclusive(() => this.createTask(command, payload));
|
|
444
|
+
case 'task.claim': return await this.runExclusive(() => this.taskCommand(command, 'claim'));
|
|
445
|
+
case 'task.release': return await this.runExclusive(() => this.taskCommand(command, 'release'));
|
|
446
|
+
case 'task.assign': return await this.runExclusive(() => this.taskCommand(command, 'assign'));
|
|
447
|
+
case 'task.submit': return await this.runExclusive(() => this.taskCommand(command, 'submit'));
|
|
448
|
+
case 'task.accept': return await this.runExclusive(() => this.taskCommand(command, 'accept'));
|
|
449
|
+
case 'task.request_changes': return await this.runExclusive(() => this.taskCommand(command, 'request_changes'));
|
|
450
|
+
case 'task.cancel': return await this.runExclusive(() => this.taskCommand(command, 'cancel'));
|
|
451
|
+
case 'task.reopen': return await this.runExclusive(() => this.taskCommand(command, 'reopen'));
|
|
452
|
+
case 'task.reassign': return await this.runExclusive(() => this.taskCommand(command, 'reassign'));
|
|
453
|
+
case 'task.delete': return await this.runExclusive(() => this.taskCommand(command, 'delete'));
|
|
454
|
+
case 'task.convert': return await this.runExclusive(() => this.convert(command, payload));
|
|
455
|
+
case 'task.follow': return await this.follow(command, payload);
|
|
456
|
+
case 'thread.post': return await this.postThread(command, payload);
|
|
457
|
+
case 'inbox.ack': return await this.ack(command, payload);
|
|
458
|
+
case 'decision.request': return await this.runExclusive(() => this.requestDecision(command, payload));
|
|
459
|
+
case 'decision.answer': return await this.runExclusive(() => this.answerDecision(command, payload));
|
|
460
|
+
default: fail(ERRORS.INVALID_ARGUMENT, `unknown command: ${String(command.type)}`);
|
|
461
|
+
}
|
|
462
|
+
} catch (error) {
|
|
463
|
+
this.diag?.append({
|
|
464
|
+
ev: 'dispatch.fail',
|
|
465
|
+
type: command.type,
|
|
466
|
+
code: error?.code ?? 'INTERNAL',
|
|
467
|
+
projectId: command.projectId ?? null,
|
|
468
|
+
message: error?.message ?? String(error),
|
|
469
|
+
elapsedMs: Date.now() - startedAt,
|
|
470
|
+
});
|
|
471
|
+
throw error;
|
|
472
|
+
} finally {
|
|
473
|
+
this.diag?.append({
|
|
474
|
+
ev: 'dispatch.done',
|
|
475
|
+
type: command.type,
|
|
476
|
+
projectId: command.projectId ?? null,
|
|
477
|
+
elapsedMs: Date.now() - startedAt,
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
async append(command, type, payload) {
|
|
483
|
+
const event = await this.ledger.append({
|
|
484
|
+
type,
|
|
485
|
+
payload,
|
|
486
|
+
actor: command.actor,
|
|
487
|
+
correlationId: command.correlationId,
|
|
488
|
+
at: this.now(),
|
|
489
|
+
});
|
|
490
|
+
return { event, result: payload };
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
async createProject(command, payload) {
|
|
494
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may create a Project');
|
|
495
|
+
if (typeof payload.name !== 'string' || payload.name.trim() === '') fail(ERRORS.INVALID_ARGUMENT, 'project name is required');
|
|
496
|
+
const id = this.ledger.projectId ?? payload.id ?? ids.project();
|
|
497
|
+
// 重复 id 会覆盖既有项目的 name/goal/owner/status(fold 按 id 合并),
|
|
498
|
+
// 静默丢掉原项目。create 必须是「新建」。
|
|
499
|
+
if (this.state.projects?.[id] !== undefined) {
|
|
500
|
+
fail(ERRORS.CONFLICT, `project ${id} already exists`);
|
|
501
|
+
}
|
|
502
|
+
// 工作目录**必需**(用户裁定:每个项目都必须指定目录):没有目录的项目里
|
|
503
|
+
// 成员无法激活、PMO 也无从派发,等于建了个用不了的项目。
|
|
504
|
+
// 例外只有内部播种(payload.seed):它先建出「待设定目录」的默认项目,
|
|
505
|
+
// 由首次使用引导补上目录,否则 boot 自己就会被这条校验挡住。
|
|
506
|
+
const rawWorkspace = typeof payload.workspacePath === 'string' ? payload.workspacePath.trim() : '';
|
|
507
|
+
if (rawWorkspace !== '') {
|
|
508
|
+
const shape = checkWorkspacePath(rawWorkspace);
|
|
509
|
+
if (shape.ok !== true) fail(ERRORS.INVALID_ARGUMENT, shape.message, { suggestion: shape.suggestion ?? null });
|
|
510
|
+
}
|
|
511
|
+
if (rawWorkspace === '' && payload.seed !== true) {
|
|
512
|
+
fail(ERRORS.INVALID_ARGUMENT, '工作目录是必填项:请选择一个已存在的目录作为项目工作区');
|
|
513
|
+
}
|
|
514
|
+
if (rawWorkspace !== '') {
|
|
515
|
+
let stat = null;
|
|
516
|
+
try { stat = statSync(rawWorkspace); } catch { stat = null; }
|
|
517
|
+
if (stat === null) fail(ERRORS.INVALID_ARGUMENT, `工作目录不存在:${rawWorkspace};请先创建该目录,或选择已存在的目录`);
|
|
518
|
+
if (typeof stat.isDirectory === 'function' && stat.isDirectory() !== true) {
|
|
519
|
+
fail(ERRORS.INVALID_ARGUMENT, `工作目录不是目录:${rawWorkspace}`);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
const ownerMemberId = payload.ownerId ?? command.actor.memberId ?? this.humanId();
|
|
523
|
+
const project = {
|
|
524
|
+
id,
|
|
525
|
+
name: payload.name.trim(),
|
|
526
|
+
goal: payload.goal ?? '',
|
|
527
|
+
ownerMemberId,
|
|
528
|
+
workspacePath: rawWorkspace,
|
|
529
|
+
status: 'active',
|
|
530
|
+
createdAt: this.now(),
|
|
531
|
+
};
|
|
532
|
+
await this.append({ ...command, projectId: id }, 'project/created', {
|
|
533
|
+
name: project.name,
|
|
534
|
+
goal: project.goal,
|
|
535
|
+
ownerMemberId,
|
|
536
|
+
workspacePath: project.workspacePath,
|
|
537
|
+
pmoAuto: payload.pmoAuto !== false,
|
|
538
|
+
status: project.status,
|
|
539
|
+
});
|
|
540
|
+
return { project };
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* 账本自检/修复入口(仅 Human)。`ledger.repair()` 此前没有任何生产调用点:
|
|
545
|
+
* 回滚失败被置为 poisoned 之后,除了重启宿主没有任何恢复路径。
|
|
546
|
+
*/
|
|
547
|
+
async repairLedger(command) {
|
|
548
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may repair the ledger');
|
|
549
|
+
const result = this.ledger.repair();
|
|
550
|
+
this.diag?.append({
|
|
551
|
+
ev: 'ledger.repaired',
|
|
552
|
+
projectId: command.projectId ?? null,
|
|
553
|
+
repair: result?.repair ?? null,
|
|
554
|
+
events: result?.events ?? null,
|
|
555
|
+
stateLastSeq: result?.stateLastSeq ?? null,
|
|
556
|
+
});
|
|
557
|
+
return {
|
|
558
|
+
repaired: result?.repair ?? null,
|
|
559
|
+
repairs: Array.isArray(result?.repairs) ? result.repairs : [],
|
|
560
|
+
events: result?.events ?? null,
|
|
561
|
+
stateLastSeq: result?.stateLastSeq ?? null,
|
|
562
|
+
// 恢复区间与缺口:一次失败的批次可能把前缀留在盘上,调用方要能看出来。
|
|
563
|
+
acceptedRange: result?.acceptedRange ?? null,
|
|
564
|
+
seqGaps: Array.isArray(result?.seqGaps) ? result.seqGaps : [],
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
async changeProjectWorkspace(command, payload) {
|
|
568
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may change the Project workspace');
|
|
569
|
+
const projectId = command.projectId;
|
|
570
|
+
const project = this.state.projects?.[projectId];
|
|
571
|
+
if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
572
|
+
if (typeof payload.workspacePath !== 'string' || payload.workspacePath.trim() === '') {
|
|
573
|
+
fail(ERRORS.INVALID_ARGUMENT, 'workspacePath is required');
|
|
574
|
+
}
|
|
575
|
+
const workspacePath = payload.workspacePath.trim();
|
|
576
|
+
// 平台形态先判:WSL/Linux 宿主上 `D:\works\x` 只是带反斜杠的相对文件名,
|
|
577
|
+
// 直接做 statSync 只会得到「不存在」,完全指不出该怎么改。
|
|
578
|
+
const shape = checkWorkspacePath(workspacePath);
|
|
579
|
+
if (shape.ok !== true) fail(ERRORS.INVALID_ARGUMENT, shape.message, { suggestion: shape.suggestion ?? null });
|
|
580
|
+
// P5b:目录必须真实存在且是目录——配置不存在的目录会让成员会话 cwd
|
|
581
|
+
// 无效、回合直接失败(用户实证:working-directory: directory does not exist)。
|
|
582
|
+
let stat = null;
|
|
583
|
+
try {
|
|
584
|
+
stat = statSync(workspacePath);
|
|
585
|
+
} catch {
|
|
586
|
+
fail(ERRORS.INVALID_ARGUMENT, `工作目录不存在:${workspacePath};请先创建该目录,或选择已存在的目录`);
|
|
587
|
+
}
|
|
588
|
+
if (stat !== null && typeof stat.isDirectory === 'function' && stat.isDirectory() !== true) {
|
|
589
|
+
fail(ERRORS.INVALID_ARGUMENT, `工作目录不是目录:${workspacePath}`);
|
|
590
|
+
}
|
|
591
|
+
await this.append(command, 'project/workspace-changed', {
|
|
592
|
+
projectId,
|
|
593
|
+
workspacePath,
|
|
594
|
+
reason: payload.reason ?? '',
|
|
595
|
+
});
|
|
596
|
+
return { project: { ...project, workspacePath } };
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// P4:项目归档(软删)——账本 append-only 纪律下不可物理删除;archived
|
|
600
|
+
// 项目从工作台消失(bootstrap 过滤),成员的 DSH 会话不受影响。
|
|
601
|
+
// P6:项目运行态(启动/停止/交接)—— Human 的全局掌控面。
|
|
602
|
+
// 'stopped':PMO tick 停止派发(补派/心跳/升级/continue 全停),正在执行
|
|
603
|
+
// 的回合自然完成;'running'(默认):正常驱动。start 时 explicitStart=true
|
|
604
|
+
// 解除空项目的 P1a 等待门(Human 显式启动即指令)。
|
|
605
|
+
async setProjectRunState(command, payload) {
|
|
606
|
+
const projectId = command.projectId;
|
|
607
|
+
const project = this.state.projects?.[projectId];
|
|
608
|
+
if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
609
|
+
const runState = payload.runState;
|
|
610
|
+
if (runState !== 'running' && runState !== 'stopped') fail(ERRORS.INVALID_ARGUMENT, 'runState must be running or stopped');
|
|
611
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may change the project run state');
|
|
612
|
+
await this.append(command, 'project/run-state', { projectId, runState, reason: payload.reason ?? '' });
|
|
613
|
+
return { project: { ...project, runState, explicitStart: runState === 'running' ? true : project.explicitStart === true } };
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
async handoffProject(command, payload) {
|
|
618
|
+
const projectId = command.projectId;
|
|
619
|
+
const project = this.state.projects?.[projectId];
|
|
620
|
+
if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
621
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may request a handoff');
|
|
622
|
+
if (typeof project.workspacePath !== 'string' || project.workspacePath.trim() === '') {
|
|
623
|
+
fail(ERRORS.INVALID_STATE, '项目未配置工作目录,无法落盘交接文档');
|
|
624
|
+
}
|
|
625
|
+
const nowMs = this.now();
|
|
626
|
+
const markdown = handoffMarkdown(this.state, project, nowMs);
|
|
627
|
+
const docsDir = pathDefault.join(project.workspacePath, 'docs');
|
|
628
|
+
mkdirSync(docsDir, { recursive: true });
|
|
629
|
+
const stamp = new Date(nowMs).toISOString().replace(/[:T]/g, '-').slice(0, 19);
|
|
630
|
+
const filePath = pathDefault.join(docsDir, `HANDOFF-${stamp}.md`);
|
|
631
|
+
writeFileSync(filePath, markdown, 'utf8');
|
|
632
|
+
await this.append(command, 'project/handoff', { projectId, filePath, reason: payload.reason ?? '' });
|
|
633
|
+
return { project, filePath };
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
async setProjectArchive(command, payload) {
|
|
637
|
+
const projectId = command.projectId;
|
|
638
|
+
const project = this.state.projects?.[projectId];
|
|
639
|
+
if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
640
|
+
const archived = payload.archived !== false;
|
|
641
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may archive a project');
|
|
642
|
+
if (archived === false && project.status === 'archived') fail(ERRORS.INVALID_STATE, 'archived projects cannot be un-archived in this version');
|
|
643
|
+
// 归档许可由 Host 层判定(registry 是全局项目清单;本 service 只持有
|
|
644
|
+
// 自己项目的账本,无法看到其它项目——旧实现的「最后 active 项目」检查
|
|
645
|
+
// 在本账本里恒为 1,导致所有归档都被误拒 409)。
|
|
646
|
+
await this.append(command, 'project/archived', { projectId, archived, reason: payload.reason ?? '' });
|
|
647
|
+
return { project: { ...project, status: archived ? 'archived' : 'active' } };
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
async setProjectPmo(command, payload) { const projectId = command.projectId;
|
|
651
|
+
const project = this.state.projects?.[projectId];
|
|
652
|
+
if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
653
|
+
if (typeof payload.pmoAuto !== 'boolean') fail(ERRORS.INVALID_ARGUMENT, 'pmoAuto must be boolean');
|
|
654
|
+
const isOwner = command.actor.kind === 'agent' && command.actor.memberId === project.ownerMemberId;
|
|
655
|
+
if (command.actor.kind !== 'human' && !isOwner) fail(ERRORS.UNAUTHORIZED, 'only Human or the Project owner may change PMO mode');
|
|
656
|
+
await this.append(command, 'project/pmo-updated', { projectId, pmoAuto: payload.pmoAuto, reason: payload.reason ?? '' });
|
|
657
|
+
return { project: { ...project, pmoAuto: payload.pmoAuto } };
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
async changeProjectOwner(command, payload) {
|
|
661
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may change the Project owner');
|
|
662
|
+
const projectId = command.projectId;
|
|
663
|
+
const project = this.state.projects?.[projectId];
|
|
664
|
+
if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
665
|
+
const ownerMemberId = payload.ownerMemberId;
|
|
666
|
+
if (typeof ownerMemberId !== 'string' || this.state.members?.[ownerMemberId] === undefined) {
|
|
667
|
+
fail(ERRORS.INVALID_ARGUMENT, 'ownerMemberId must name an existing member');
|
|
668
|
+
}
|
|
669
|
+
await this.append(command, 'project/owner-changed', { projectId, ownerMemberId, reason: payload.reason ?? '' });
|
|
670
|
+
return { project: { ...project, ownerMemberId } };
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
async postStream(command, payload) {
|
|
674
|
+
const body = typeof payload.body === 'string' ? payload.body.trim() : '';
|
|
675
|
+
if (body === '') fail(ERRORS.INVALID_ARGUMENT, 'stream message body is required');
|
|
676
|
+
const author = this.state.members?.[command.actor.memberId];
|
|
677
|
+
if (author === undefined) fail(ERRORS.UNAUTHORIZED, 'actor must be a Team member');
|
|
678
|
+
// seq 由账本事件定(fold 用 event.seq;payload 里的幻影计数会被忽略,
|
|
679
|
+
// 并发下还会重复——曾造成 API 返回值与投影不一致)。
|
|
680
|
+
// kind 必须反映真实作者:`human_message` 是 Waker 判定「Human 下了指令」的
|
|
681
|
+
// 唯一依据(会触发建卡唤醒),agent 发言若也标成它,等于让 agent 冒充 Human。
|
|
682
|
+
const entry = {
|
|
683
|
+
kind: command.actor.kind === 'human' ? 'human_message' : 'milestone',
|
|
684
|
+
authorId: author.id,
|
|
685
|
+
body,
|
|
686
|
+
at: this.now(),
|
|
687
|
+
};
|
|
688
|
+
const event = await this.ledger.append({
|
|
689
|
+
type: 'stream/posted',
|
|
690
|
+
payload: entry,
|
|
691
|
+
actor: command.actor,
|
|
692
|
+
projectId: command.projectId,
|
|
693
|
+
at: this.now(),
|
|
694
|
+
});
|
|
695
|
+
return { entry: { ...entry, seq: event.seq }, event };
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
async addMember(command, payload) {
|
|
699
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may create a member');
|
|
700
|
+
if (typeof payload.name !== 'string' || payload.name.trim() === '') fail(ERRORS.INVALID_ARGUMENT, 'member name is required');
|
|
701
|
+
// id 由调用方给出时必须是非空字符串且未被占用:否则会覆盖既有成员
|
|
702
|
+
// (fold 按 id 合并,sessionId/config 一起丢失),或写入非字符串 id 被
|
|
703
|
+
// fold 丢弃却仍返回成功。
|
|
704
|
+
if (payload.id !== undefined) {
|
|
705
|
+
if (typeof payload.id !== 'string' || payload.id.trim() === '') {
|
|
706
|
+
fail(ERRORS.INVALID_ARGUMENT, 'member id must be a non-empty string');
|
|
707
|
+
}
|
|
708
|
+
if (this.state.members?.[payload.id] !== undefined) {
|
|
709
|
+
fail(ERRORS.CONFLICT, `member ${payload.id} already exists`);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
const status = payload.status === undefined ? MEMBER_STATUS.IDLE : payload.status;
|
|
713
|
+
if (!MEMBER_STATUS_VALUES.has(status)) {
|
|
714
|
+
fail(ERRORS.INVALID_ARGUMENT, `member status must be one of ${[...MEMBER_STATUS_VALUES].join(', ')}`);
|
|
715
|
+
}
|
|
716
|
+
const member = {
|
|
717
|
+
id: payload.id ?? ids.member(),
|
|
718
|
+
name: payload.name.trim(),
|
|
719
|
+
kind: payload.kind === 'human' ? 'human' : 'agent',
|
|
720
|
+
role: payload.role ?? '',
|
|
721
|
+
personality: typeof payload.personality === 'string' ? payload.personality : '',
|
|
722
|
+
status,
|
|
723
|
+
createdAt: this.now(),
|
|
724
|
+
};
|
|
725
|
+
await this.append(command, 'project/member-added', {
|
|
726
|
+
memberId: member.id,
|
|
727
|
+
name: member.name,
|
|
728
|
+
kind: member.kind,
|
|
729
|
+
role: member.role,
|
|
730
|
+
personality: member.personality,
|
|
731
|
+
status: member.status,
|
|
732
|
+
projectId: payload.projectId,
|
|
733
|
+
});
|
|
734
|
+
return { member };
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
async recordWake(memberId, info, projectId = Object.keys(this.state.projects ?? {})[0]) {
|
|
738
|
+
const event = {
|
|
739
|
+
type: info.ok === true ? 'wake/delivered' : 'wake/failed',
|
|
740
|
+
payload: { memberId, taskId: info.taskId ?? null, reason: info.reason ?? null, messageId: info.messageId ?? null, error: info.error ?? null },
|
|
741
|
+
actor: { kind: 'system' },
|
|
742
|
+
projectId,
|
|
743
|
+
at: this.now(),
|
|
744
|
+
};
|
|
745
|
+
await this.ledger.append(event);
|
|
746
|
+
return event;
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
async bindHostSession(sessionId, projectId = Object.keys(this.state.projects ?? {})[0]) {
|
|
750
|
+
if (typeof sessionId !== 'string' || sessionId === '') fail(ERRORS.INVALID_ARGUMENT, 'host sessionId is required');
|
|
751
|
+
await this.ledger.append({
|
|
752
|
+
type: 'team/host-bound',
|
|
753
|
+
payload: { sessionId },
|
|
754
|
+
actor: { kind: 'system' },
|
|
755
|
+
projectId,
|
|
756
|
+
at: this.now(),
|
|
757
|
+
});
|
|
758
|
+
return { sessionId };
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
async bindMemberSession(command, payload) {
|
|
762
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may bind a member session');
|
|
763
|
+
const member = this.state.members?.[payload.memberId];
|
|
764
|
+
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.memberId)} not found`);
|
|
765
|
+
// 退役成员不得经 bind 复活;重新入队必须走 member.rejoin(清 talentPool)。
|
|
766
|
+
if (member.status === 'retired') fail(ERRORS.INVALID_STATE, `member ${member.name ?? member.id} is retired`);
|
|
767
|
+
if (typeof payload.sessionId !== 'string' || payload.sessionId === '') fail(ERRORS.INVALID_ARGUMENT, 'sessionId is required');
|
|
768
|
+
await this.append(command, 'member/session-bound', {
|
|
769
|
+
memberId: member.id,
|
|
770
|
+
sessionId: payload.sessionId,
|
|
771
|
+
status: 'running',
|
|
772
|
+
});
|
|
773
|
+
return { member: { ...member, sessionId: payload.sessionId, status: 'running' } };
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
async failMember(command, payload) {
|
|
777
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may mark a member failed');
|
|
778
|
+
const member = this.state.members?.[payload.memberId];
|
|
779
|
+
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.memberId)} not found`);
|
|
780
|
+
// 退役是终态:把 retired 改成 failed 会让 member.bind 之后把 ta 复活。
|
|
781
|
+
if (member.status === 'retired') fail(ERRORS.INVALID_STATE, `member ${member.id} is retired`);
|
|
782
|
+
await this.append(command, 'member/failed', { memberId: member.id, reason: payload.reason ?? '' });
|
|
783
|
+
return { member: { ...member, status: 'failed', failure: payload.reason ?? '' } };
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
async retireMember(command, payload) {
|
|
787
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may retire a member');
|
|
788
|
+
const member = this.state.members?.[payload.memberId];
|
|
789
|
+
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.memberId)} not found`);
|
|
790
|
+
await this.append(command, 'project/member-retired', { memberId: member.id });
|
|
791
|
+
return { member: { ...member, status: 'retired' } };
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
async updateMemberProfile(command, payload) {
|
|
795
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may change name, role or personality');
|
|
796
|
+
const member = this.state.members?.[payload.memberId];
|
|
797
|
+
if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId)} not found`);
|
|
798
|
+
const text = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);
|
|
799
|
+
const name = text(payload.name);
|
|
800
|
+
const role = text(payload.role);
|
|
801
|
+
// An empty personality means "leave it unchanged", not "clear it".
|
|
802
|
+
const personality = text(payload.personality);
|
|
803
|
+
if (name === undefined && role === undefined && personality === undefined) {
|
|
804
|
+
fail(ERRORS.INVALID_ARGUMENT, 'name, role or personality is required');
|
|
805
|
+
}
|
|
806
|
+
await this.append(command, 'member/profile-updated', {
|
|
807
|
+
memberId: member.id,
|
|
808
|
+
...(name === undefined ? {} : { name }),
|
|
809
|
+
...(role === undefined ? {} : { role }),
|
|
810
|
+
...(personality === undefined ? {} : { personality }),
|
|
811
|
+
updatedBy: command.actor.memberId,
|
|
812
|
+
reason: payload.reason ?? '',
|
|
813
|
+
});
|
|
814
|
+
return { member: this.state.members[member.id] };
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
/** An Agent may evolve its own working personality, never its name/role. */
|
|
818
|
+
async evolveMember(command, payload) {
|
|
819
|
+
if (command.actor.kind !== 'agent') fail(ERRORS.UNAUTHORIZED, 'only an Agent may evolve its personality');
|
|
820
|
+
const member = this.state.members?.[command.actor.memberId];
|
|
821
|
+
if (member === undefined) fail(ERRORS.NOT_FOUND, 'actor member not found');
|
|
822
|
+
if (payload.memberId !== undefined && payload.memberId !== member.id) {
|
|
823
|
+
fail(ERRORS.UNAUTHORIZED, 'an Agent may only evolve itself');
|
|
824
|
+
}
|
|
825
|
+
const personality = typeof payload.personality === 'string' ? payload.personality.trim() : '';
|
|
826
|
+
if (personality === '') fail(ERRORS.INVALID_ARGUMENT, 'personality is required');
|
|
827
|
+
await this.append(command, 'member/distilled', {
|
|
828
|
+
memberId: member.id,
|
|
829
|
+
personality,
|
|
830
|
+
updatedBy: member.id,
|
|
831
|
+
reason: payload.reason ?? 'self-evolution',
|
|
832
|
+
});
|
|
833
|
+
return { member: this.state.members[member.id] };
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/** Human/Lead-triggered distillation snapshot; model quality is a later step. */
|
|
837
|
+
async distillMember(command, payload) {
|
|
838
|
+
if (command.actor.kind !== 'human' && command.actor.kind !== 'agent') fail(ERRORS.UNAUTHORIZED, 'a member is required');
|
|
839
|
+
const member = this.state.members?.[payload.memberId];
|
|
840
|
+
if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId)} not found`);
|
|
841
|
+
const lead = this.state.projects?.[command.projectId]?.ownerMemberId === command.actor.memberId;
|
|
842
|
+
if (command.actor.kind !== 'human' && !lead && command.actor.memberId !== member.id) {
|
|
843
|
+
fail(ERRORS.UNAUTHORIZED, 'only Human, the Project owner or the member may distill');
|
|
844
|
+
}
|
|
845
|
+
const personality = typeof payload.personality === 'string' && payload.personality.trim() !== ''
|
|
846
|
+
? payload.personality.trim()
|
|
847
|
+
: member.personality ?? '';
|
|
848
|
+
if (personality === '') fail(ERRORS.INVALID_ARGUMENT, 'personality is required for distillation');
|
|
849
|
+
await this.append(command, 'member/distilled', {
|
|
850
|
+
memberId: member.id,
|
|
851
|
+
personality,
|
|
852
|
+
updatedBy: command.actor.memberId,
|
|
853
|
+
reason: payload.reason ?? 're-distill',
|
|
854
|
+
});
|
|
855
|
+
return { member: this.state.members[member.id] };
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
async messageMember(command, payload) {
|
|
859
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may message a member');
|
|
860
|
+
const member = this.state.members?.[payload.memberId];
|
|
861
|
+
if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId)} not found`);
|
|
862
|
+
const body = typeof payload.body === 'string' ? payload.body.trim() : '';
|
|
863
|
+
if (body === '') fail(ERRORS.INVALID_ARGUMENT, 'message body is required');
|
|
864
|
+
const event = await this.ledger.append({
|
|
865
|
+
type: 'member/message',
|
|
866
|
+
payload: { memberId: member.id, authorId: command.actor.memberId, body, at: this.now() },
|
|
867
|
+
actor: command.actor,
|
|
868
|
+
correlationId: command.correlationId,
|
|
869
|
+
projectId: command.projectId,
|
|
870
|
+
at: this.now(),
|
|
871
|
+
});
|
|
872
|
+
return { event, memberId: member.id };
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
async addMemberNote(command, payload) {
|
|
876
|
+
const member = this.state.members?.[payload.memberId ?? command.actor.memberId];
|
|
877
|
+
if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId ?? command.actor.memberId)} not found`);
|
|
878
|
+
if (command.actor.kind === 'agent' && command.actor.memberId !== member.id) {
|
|
879
|
+
fail(ERRORS.UNAUTHORIZED, 'an Agent may only note itself');
|
|
880
|
+
}
|
|
881
|
+
const text = typeof payload.text === 'string' ? payload.text.trim() : '';
|
|
882
|
+
if (text === '') fail(ERRORS.INVALID_ARGUMENT, 'note text is required');
|
|
883
|
+
await this.append(command, 'member/note-added', {
|
|
884
|
+
memberId: member.id,
|
|
885
|
+
text,
|
|
886
|
+
addedBy: command.actor.memberId,
|
|
887
|
+
});
|
|
888
|
+
return { member: this.state.members[member.id] };
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
async addMemberSkill(command, payload) {
|
|
892
|
+
const member = this.state.members?.[payload.memberId ?? command.actor.memberId];
|
|
893
|
+
if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId ?? command.actor.memberId)} not found`);
|
|
894
|
+
if (command.actor.kind === 'agent' && command.actor.memberId !== member.id) {
|
|
895
|
+
fail(ERRORS.UNAUTHORIZED, 'an Agent may only add its own skill');
|
|
896
|
+
}
|
|
897
|
+
const name = typeof payload.name === 'string' ? payload.name.trim() : '';
|
|
898
|
+
if (name === '') fail(ERRORS.INVALID_ARGUMENT, 'skill name is required');
|
|
899
|
+
await this.append(command, 'member/skill-added', {
|
|
900
|
+
memberId: member.id,
|
|
901
|
+
name,
|
|
902
|
+
addedBy: command.actor.memberId,
|
|
903
|
+
});
|
|
904
|
+
return { member: this.state.members[member.id] };
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
async leaveMember(command, payload) {
|
|
908
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may move a member to the talent pool');
|
|
909
|
+
const member = this.state.members?.[payload.memberId];
|
|
910
|
+
if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId)} not found`);
|
|
911
|
+
const unfinished = unfinishedTasksFor(this.state, member.id);
|
|
912
|
+
await this.append(command, 'member/left-team', { memberId: member.id, reason: payload.reason ?? '' });
|
|
913
|
+
return {
|
|
914
|
+
member: this.state.members[member.id],
|
|
915
|
+
unfinishedTasks: unfinished.map((task) => ({ id: task.id, number: task.number, title: task.title, status: task.status })),
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
async rejoinMember(command, payload) {
|
|
920
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may recruit from the talent pool');
|
|
921
|
+
const member = this.state.members?.[payload.memberId];
|
|
922
|
+
if (member === undefined || member.kind !== 'agent') fail(ERRORS.NOT_FOUND, `agent ${String(payload.memberId)} not found`);
|
|
923
|
+
if (member.status !== 'retired') fail(ERRORS.INVALID_STATE, 'member is already in the team');
|
|
924
|
+
await this.append(command, 'member/rejoined', { memberId: member.id, reason: payload.reason ?? '' });
|
|
925
|
+
return { member: this.state.members[member.id] };
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
async takeoverMember(command, payload) {
|
|
929
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may assign a successor');
|
|
930
|
+
const from = this.state.members?.[payload.fromMemberId];
|
|
931
|
+
const to = this.state.members?.[payload.toMemberId];
|
|
932
|
+
if (from === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.fromMemberId)} not found`);
|
|
933
|
+
if (to === undefined || to.kind !== 'agent' || to.status === 'retired') {
|
|
934
|
+
fail(ERRORS.INVALID_ARGUMENT, 'successor must be an active Agent');
|
|
935
|
+
}
|
|
936
|
+
const unfinished = unfinishedTasksFor(this.state, from.id);
|
|
937
|
+
const taken = [];
|
|
938
|
+
for (const task of unfinished) {
|
|
939
|
+
await this.append(command, 'task/taken-over', {
|
|
940
|
+
taskId: task.id,
|
|
941
|
+
revision: task.revision + 1,
|
|
942
|
+
fromMemberId: from.id,
|
|
943
|
+
toMemberId: to.id,
|
|
944
|
+
reason: payload.reason ?? `takeover from ${from.name}`,
|
|
945
|
+
});
|
|
946
|
+
taken.push(this.state.tasks[task.id]);
|
|
947
|
+
}
|
|
948
|
+
return { from: from.id, to: to.id, tasks: taken };
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/** Lead (Project owner) or Human may update another member's config. */
|
|
952
|
+
async updateMemberConfig(command, payload) {
|
|
953
|
+
const member = this.state.members?.[payload.memberId];
|
|
954
|
+
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.memberId)} not found`);
|
|
955
|
+
const project = this.state.projects?.[command.projectId];
|
|
956
|
+
const isHuman = command.actor.kind === 'human';
|
|
957
|
+
const isLead = project?.ownerMemberId === command.actor.memberId || project?.ownerId === command.actor.memberId;
|
|
958
|
+
if (!isHuman && !isLead) fail(ERRORS.UNAUTHORIZED, 'only the Project owner or Human may update member config');
|
|
959
|
+
if (command.actor.memberId === member.id) {
|
|
960
|
+
fail(ERRORS.UNAUTHORIZED, 'a member cannot update its own config; Lead self-config is Human-only');
|
|
961
|
+
}
|
|
962
|
+
if (Number.isSafeInteger(payload.expectedConfigVersion) && payload.expectedConfigVersion !== (member.configVersion ?? 0)) {
|
|
963
|
+
fail(ERRORS.REVISION, 'member config changed since you read it', {
|
|
964
|
+
details: { expected: payload.expectedConfigVersion, current: member.configVersion ?? 0 },
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
const current = normalizeMemberConfig(member.config ?? {});
|
|
968
|
+
const result = applyMemberConfigPatch(current, payload.patch ?? {}, {
|
|
969
|
+
// policy 只能来自服务端注入:允许命令 payload 覆盖等于让调用方自己定义
|
|
970
|
+
// 授权边界(实测可把 allowedModels 扩到未授权模型)。
|
|
971
|
+
policy: { ...this.memberConfigPolicy },
|
|
972
|
+
configVersion: member.configVersion ?? 0,
|
|
973
|
+
});
|
|
974
|
+
if (!result.changed) return { member, config: current, changed: false };
|
|
975
|
+
const nextConfig = {
|
|
976
|
+
...result.config,
|
|
977
|
+
updatedBy: command.actor.memberId ?? command.actor.kind,
|
|
978
|
+
updatedAt: this.now(),
|
|
979
|
+
reason: typeof payload.reason === 'string' ? payload.reason : '',
|
|
980
|
+
};
|
|
981
|
+
// 路由字段(provider/model)变化必须单独标记:已存活会话的 provider 在创建时
|
|
982
|
+
// 就固定了,只追加 model/selection 改不了路由(实机:模型换成 Qwen,provider
|
|
983
|
+
// 仍是 deepseek-official,于是报缺 DEEPSEEK_API_KEY 且一直不恢复)。
|
|
984
|
+
const routeChanged = (current.provider ?? '') !== (nextConfig.provider ?? '')
|
|
985
|
+
|| (current.model ?? '') !== (nextConfig.model ?? '');
|
|
986
|
+
await this.append(command, 'member/config-updated', {
|
|
987
|
+
memberId: member.id,
|
|
988
|
+
config: nextConfig,
|
|
989
|
+
configVersion: nextConfig.configVersion,
|
|
990
|
+
before: result.before,
|
|
991
|
+
reason: nextConfig.reason,
|
|
992
|
+
routeChanged,
|
|
993
|
+
});
|
|
994
|
+
return {
|
|
995
|
+
member: { ...member, config: nextConfig, configVersion: nextConfig.configVersion, routeStale: routeChanged ? true : member.routeStale === true },
|
|
996
|
+
config: nextConfig,
|
|
997
|
+
changed: true,
|
|
998
|
+
routeChanged,
|
|
999
|
+
};
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
async retryMember(command, payload) {
|
|
1003
|
+
const member = this.state.members?.[payload.memberId];
|
|
1004
|
+
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.memberId)} not found`);
|
|
1005
|
+
// 退役成员的重启必须走 member.rejoin(清 talentPool/leftTeamAt)。
|
|
1006
|
+
if (member.status === 'retired') fail(ERRORS.INVALID_STATE, `member ${member.name ?? member.id} is retired; use member.rejoin`);
|
|
1007
|
+
const project = this.state.projects?.[command.projectId];
|
|
1008
|
+
const isHuman = command.actor.kind === 'human';
|
|
1009
|
+
const isLead = project?.ownerMemberId === command.actor.memberId || project?.ownerId === command.actor.memberId;
|
|
1010
|
+
if (!isHuman && !isLead) fail(ERRORS.UNAUTHORIZED, 'only the Project owner or Human may retry a member');
|
|
1011
|
+
await this.append(command, 'member/retry-requested', {
|
|
1012
|
+
memberId: member.id,
|
|
1013
|
+
reason: typeof payload.reason === 'string' ? payload.reason : '',
|
|
1014
|
+
});
|
|
1015
|
+
return { member: { ...member, status: 'provisioning' } };
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/** Host/Waker calls these; actor is system, never a Human decision. */
|
|
1019
|
+
async recordMemberFailure(memberId, failure, projectId = Object.keys(this.state.projects ?? {})[0]) {
|
|
1020
|
+
const member = this.state.members?.[memberId];
|
|
1021
|
+
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(memberId)} not found`);
|
|
1022
|
+
// 退役成员不该被迟到的 LLM 失败改成 failed(fold 对这条事件没有 retired 守卫,
|
|
1023
|
+
// 之后 member.bind 就能把 ta 复活)。直接忽略,不写事件。
|
|
1024
|
+
if (member.status === 'retired') return null;
|
|
1025
|
+
const attempt = Number.isSafeInteger(failure.attempt) ? failure.attempt : (member.lastFailure?.attempt ?? 0) + 1;
|
|
1026
|
+
const fatal = failure.category === 'auth' || failure.category === 'billing' || failure.category === 'policy' || failure.category === 'unknown';
|
|
1027
|
+
// Tool-argument and provider dumps can run to kilobytes; the ledger and
|
|
1028
|
+
// the risk list only ever need a human-readable first act of the error.
|
|
1029
|
+
const message = typeof failure.message === 'string' && failure.message.length > 400
|
|
1030
|
+
? failure.message.slice(0, 400) + '…'
|
|
1031
|
+
: failure.message;
|
|
1032
|
+
const recorded = { ...failure, message, attempt };
|
|
1033
|
+
await this.ledger.append({
|
|
1034
|
+
type: 'member/llm-failed',
|
|
1035
|
+
payload: { ...recorded, memberId, fatal },
|
|
1036
|
+
actor: { kind: 'system' },
|
|
1037
|
+
projectId,
|
|
1038
|
+
at: this.now(),
|
|
1039
|
+
});
|
|
1040
|
+
this.diag?.append({
|
|
1041
|
+
ev: fatal ? 'member.fail' : 'member.llm-failed',
|
|
1042
|
+
memberId,
|
|
1043
|
+
category: recorded.category,
|
|
1044
|
+
attempt,
|
|
1045
|
+
provider: recorded.provider ?? null,
|
|
1046
|
+
model: recorded.model ?? null,
|
|
1047
|
+
projectId,
|
|
1048
|
+
});
|
|
1049
|
+
let inboxItem = null;
|
|
1050
|
+
if (fatal) {
|
|
1051
|
+
const humanId = this.humanId();
|
|
1052
|
+
// 去重必须用自己的判别字段:`ref.memberId` 在 requestDecision 里表示
|
|
1053
|
+
// 「申请人」,与这里「失败的成员」同名不同义——成员只要有一条自己提的
|
|
1054
|
+
// 未决决策,ta 的致命失败就再也不会生成升级项。
|
|
1055
|
+
const duplicate = humanId === null ? undefined : Object.values(this.state.inbox ?? {}).find((item) =>
|
|
1056
|
+
item.memberId === humanId
|
|
1057
|
+
&& item.requiresDecision === true
|
|
1058
|
+
&& (item.ref?.kind === 'member_failure'
|
|
1059
|
+
? item.ref?.failedMemberId === memberId
|
|
1060
|
+
: item.ref?.kind === undefined && item.ref?.memberId === memberId && item.ref?.category !== undefined)
|
|
1061
|
+
&& !['resolved', 'dismissed', 'superseded'].includes(item.state));
|
|
1062
|
+
if (humanId !== null && duplicate === undefined) {
|
|
1063
|
+
const activeTask = Object.values(this.state.tasks ?? {}).find((task) =>
|
|
1064
|
+
task.tombstone !== true
|
|
1065
|
+
&& ['pending', 'in_progress', 'pending_acceptance'].includes(task.status)
|
|
1066
|
+
&& (task.ownerId === memberId || task.assigneeId === memberId));
|
|
1067
|
+
const taskId = recorded.taskId ?? activeTask?.id ?? null;
|
|
1068
|
+
inboxItem = createInboxItem({
|
|
1069
|
+
memberId: humanId,
|
|
1070
|
+
type: 'decision_required',
|
|
1071
|
+
ref: { kind: 'member_failure', failedMemberId: memberId, memberId, category: recorded.category, taskId },
|
|
1072
|
+
requiresDecision: true,
|
|
1073
|
+
}, { at: this.now() });
|
|
1074
|
+
await this.ledger.append({
|
|
1075
|
+
type: 'inbox/item-created',
|
|
1076
|
+
payload: { itemId: inboxItem.id, ...inboxItem },
|
|
1077
|
+
actor: { kind: 'system' },
|
|
1078
|
+
projectId,
|
|
1079
|
+
at: this.now(),
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
return {
|
|
1084
|
+
member: { ...member, lastFailure: recorded, attempts: attempt, status: fatal ? 'failed' : member.status },
|
|
1085
|
+
inboxItem,
|
|
1086
|
+
};
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
/** Fallback changes are system-authored config events, rollback-able by Human. */
|
|
1090
|
+
async applySystemFallback(memberId, patch, reason = 'llm-fallback', projectId = Object.keys(this.state.projects ?? {})[0]) {
|
|
1091
|
+
const member = this.state.members?.[memberId];
|
|
1092
|
+
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(memberId)} not found`);
|
|
1093
|
+
const current = normalizeMemberConfig(member.config ?? {});
|
|
1094
|
+
const result = applyMemberConfigPatch(current, patch, {
|
|
1095
|
+
policy: this.memberConfigPolicy,
|
|
1096
|
+
configVersion: member.configVersion ?? 0,
|
|
1097
|
+
});
|
|
1098
|
+
if (!result.changed) return { member, config: current, changed: false };
|
|
1099
|
+
this.diag?.append({
|
|
1100
|
+
ev: 'member.fallback',
|
|
1101
|
+
memberId,
|
|
1102
|
+
reason,
|
|
1103
|
+
patch,
|
|
1104
|
+
projectId,
|
|
1105
|
+
});
|
|
1106
|
+
const nextConfig = {
|
|
1107
|
+
...result.config,
|
|
1108
|
+
updatedBy: 'system',
|
|
1109
|
+
updatedAt: this.now(),
|
|
1110
|
+
reason,
|
|
1111
|
+
};
|
|
1112
|
+
await this.ledger.append({
|
|
1113
|
+
type: 'member/config-updated',
|
|
1114
|
+
payload: {
|
|
1115
|
+
memberId,
|
|
1116
|
+
config: nextConfig,
|
|
1117
|
+
configVersion: nextConfig.configVersion,
|
|
1118
|
+
before: result.before,
|
|
1119
|
+
reason,
|
|
1120
|
+
},
|
|
1121
|
+
actor: { kind: 'system' },
|
|
1122
|
+
projectId,
|
|
1123
|
+
at: this.now(),
|
|
1124
|
+
});
|
|
1125
|
+
return { member: { ...member, config: nextConfig, configVersion: nextConfig.configVersion }, config: nextConfig, changed: true };
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
async recordMemberRecovery(memberId, attempt, effectiveConfig, projectId = Object.keys(this.state.projects ?? {})[0]) {
|
|
1129
|
+
const member = this.state.members?.[memberId];
|
|
1130
|
+
if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(memberId)} not found`);
|
|
1131
|
+
await this.ledger.append({
|
|
1132
|
+
type: 'member/recovered',
|
|
1133
|
+
payload: { memberId, attempt, effectiveConfig: effectiveConfig ?? member.config ?? null },
|
|
1134
|
+
actor: { kind: 'system' },
|
|
1135
|
+
projectId,
|
|
1136
|
+
at: this.now(),
|
|
1137
|
+
});
|
|
1138
|
+
this.diag?.append({ ev: 'member.recovered', memberId, attempt, projectId });
|
|
1139
|
+
return { member: { ...member, status: 'running', lastRecoveredAt: this.now() } };
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
async createTask(command, payload) {
|
|
1143
|
+
const state = this.state;
|
|
1144
|
+
const projectId = command.projectId;
|
|
1145
|
+
const project = state.projects?.[projectId];
|
|
1146
|
+
if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
|
|
1147
|
+
const number = Math.max(0, ...Object.values(state.tasks ?? {}).map((task) => task.number ?? 0)) + 1;
|
|
1148
|
+
const ownerId = payload.ownerId ?? project.ownerMemberId ?? project.ownerId;
|
|
1149
|
+
const qaRequired = payload.qaRequired === true;
|
|
1150
|
+
const qaChecklist = Array.isArray(payload.qaChecklist) ? payload.qaChecklist.filter((item) => typeof item === 'string' && item.trim() !== '') : [];
|
|
1151
|
+
if (qaRequired && qaChecklist.length === 0) {
|
|
1152
|
+
fail(ERRORS.INVALID_ARGUMENT, 'qaRequired needs at least one qaChecklist item');
|
|
1153
|
+
}
|
|
1154
|
+
// 幽灵成员 id / 不存在的依赖会被直接写进投影,且没有修复命令:卡的 owner 永远
|
|
1155
|
+
// 不对,或被一个不存在的依赖永久 blocked。
|
|
1156
|
+
// 只校验**显式传入**的 ownerId:默认值来自 project.ownerMemberId,若该成员已退役,
|
|
1157
|
+
// 校验会把工作台的建卡入口整个封死(退役不转移所有权)。
|
|
1158
|
+
if (typeof payload.ownerId === 'string' && payload.ownerId !== '') requireMemberRef(state, payload.ownerId, 'ownerId');
|
|
1159
|
+
requireMemberRef(state, payload.assigneeId, 'assigneeId', { agentOnly: true });
|
|
1160
|
+
if (Array.isArray(payload.blockedBy)) {
|
|
1161
|
+
for (const dependency of payload.blockedBy) {
|
|
1162
|
+
if (typeof dependency !== 'string' || Object.hasOwn(state.tasks ?? {}, dependency) !== true) {
|
|
1163
|
+
fail(ERRORS.INVALID_ARGUMENT, `blockedBy ${String(dependency)} is not a Task of this project`);
|
|
1164
|
+
}
|
|
1165
|
+
// 删除是 tombstone 而不是物理移除,而依赖判定只认 status === 'done':
|
|
1166
|
+
// 指向一张已删除的卡会让新卡**永久** blocked,且没有修复命令。
|
|
1167
|
+
const dependencyTask = state.tasks[dependency];
|
|
1168
|
+
if (dependencyTask?.tombstone === true || dependencyTask?.status === 'deleted' || dependencyTask?.status === 'cancelled') {
|
|
1169
|
+
fail(ERRORS.INVALID_ARGUMENT, `blockedBy ${String(dependency)} can never complete (it is ${dependencyTask?.tombstone === true ? 'deleted' : String(dependencyTask?.status)})`);
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
const title = typeof payload.title === 'string' ? payload.title.trim() : '';
|
|
1174
|
+
const resultDefinition = typeof payload.resultDefinition === 'string' ? payload.resultDefinition.trim() : '';
|
|
1175
|
+
const duplicate = Object.values(state.tasks ?? {}).find((candidate) =>
|
|
1176
|
+
candidate.tombstone !== true
|
|
1177
|
+
&& ['pending', 'in_progress', 'pending_acceptance'].includes(candidate.status)
|
|
1178
|
+
&& candidate.ownerId === ownerId
|
|
1179
|
+
&& candidate.title === title
|
|
1180
|
+
&& candidate.resultDefinition === resultDefinition);
|
|
1181
|
+
if (duplicate !== undefined && payload.allowDuplicate !== true) {
|
|
1182
|
+
fail(ERRORS.CONFLICT, 'an active Task with the same title, result definition and owner already exists', {
|
|
1183
|
+
details: { taskId: duplicate.id, number: duplicate.number, title: duplicate.title },
|
|
1184
|
+
});
|
|
1185
|
+
}
|
|
1186
|
+
const { task, event } = createTask({
|
|
1187
|
+
number,
|
|
1188
|
+
title,
|
|
1189
|
+
resultDefinition,
|
|
1190
|
+
ownerId,
|
|
1191
|
+
assigneeId: payload.assigneeId,
|
|
1192
|
+
blockedBy: payload.blockedBy,
|
|
1193
|
+
writeScopes: payload.writeScopes,
|
|
1194
|
+
irreversible: payload.irreversible,
|
|
1195
|
+
qaRequired,
|
|
1196
|
+
qaChecklist,
|
|
1197
|
+
originRefs: payload.originRefs,
|
|
1198
|
+
at: this.now(),
|
|
1199
|
+
});
|
|
1200
|
+
await this.ledger.append({ ...event, actor: command.actor, correlationId: command.correlationId, at: this.now(), projectId });
|
|
1201
|
+
return { task };
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
async taskCommand(command, action) {
|
|
1205
|
+
const state = this.state;
|
|
1206
|
+
const taskId = command.payload?.taskId;
|
|
1207
|
+
const task = state.tasks?.[taskId];
|
|
1208
|
+
if (task === undefined) fail(ERRORS.NOT_FOUND, `task ${String(taskId)} not found`);
|
|
1209
|
+
const expectedRevision = command.payload?.expectedRevision;
|
|
1210
|
+
// 目标成员必须真实存在且可用:幽灵 id 写进投影后,真实成员 claim 会一直
|
|
1211
|
+
// 撞 E_ALREADY_CLAIMED,只能由 owner/Human 重新指派才能解锁。
|
|
1212
|
+
const requireAgentMember = (memberId, field) => requireMemberRef(this.state, memberId, field, { agentOnly: true });
|
|
1213
|
+
let outcome;
|
|
1214
|
+
switch (action) {
|
|
1215
|
+
case 'claim': outcome = claimTask(task, command.actor, state.tasks ?? {}, { expectedRevision, at: this.now() }); break;
|
|
1216
|
+
case 'release': outcome = releaseTask(task, command.actor, { expectedRevision, reason: command.payload?.reason, at: this.now() }); break;
|
|
1217
|
+
case 'assign':
|
|
1218
|
+
requireAgentMember(command.payload?.assigneeId, 'assigneeId');
|
|
1219
|
+
outcome = assignTask(task, command.actor, command.payload?.assigneeId, { expectedRevision, at: this.now() });
|
|
1220
|
+
break;
|
|
1221
|
+
case 'submit': outcome = submitTask(task, command.actor, { summary: command.payload?.summary, evidence: command.payload?.evidence }, { expectedRevision, at: this.now() }); break;
|
|
1222
|
+
case 'accept': {
|
|
1223
|
+
// Agent actors are pre-resolved by dispatch; resolve defensively here
|
|
1224
|
+
// so an unknown memberId fails closed instead of skipping the QA gate.
|
|
1225
|
+
const reviewer = command.actor.kind === 'agent'
|
|
1226
|
+
? this.state.members?.[command.actor.memberId] ?? undefined
|
|
1227
|
+
: null;
|
|
1228
|
+
if (command.actor.kind === 'agent' && reviewer === undefined) {
|
|
1229
|
+
fail(ERRORS.UNAUTHORIZED, `agent actor ${String(command.actor.memberId ?? '?')} is not a Team member`);
|
|
1230
|
+
}
|
|
1231
|
+
if (task.qaRequired === true && reviewer !== null && !isQaMember(reviewer)) {
|
|
1232
|
+
fail(ERRORS.INVALID_STATE, 'this task requires a QA reviewer');
|
|
1233
|
+
}
|
|
1234
|
+
const checklist = Array.isArray(task.qaChecklist) ? task.qaChecklist : [];
|
|
1235
|
+
const checks = Array.isArray(command.payload?.checks) ? command.payload.checks : [];
|
|
1236
|
+
// 门禁对**所有**验收人都生效:Human 是 UI 上唯一的验收人,之前把它
|
|
1237
|
+
// 排除在 `reviewer !== null` 之外,等于让 qaRequired 的卡零勾选通过,
|
|
1238
|
+
// 未校验的 checks 还会原样写进 task.qaChecks。
|
|
1239
|
+
if (checklist.length > 0) {
|
|
1240
|
+
// QA 门禁必须逐项对应 task.qaChecklist:只比较条数 + passed 会让
|
|
1241
|
+
// 任意 item 文本(含伪造/无关条目)通过门禁,与 tool schema 契约
|
|
1242
|
+
// "Exact qaChecklist item" 不一致。
|
|
1243
|
+
const pending = checklist.map((item) => String(item));
|
|
1244
|
+
for (const check of checks) {
|
|
1245
|
+
if (check?.passed !== true) fail(ERRORS.INVALID_STATE, 'every QA checklist item must pass before acceptance');
|
|
1246
|
+
const text = typeof check?.item === 'string' ? check.item : '';
|
|
1247
|
+
const at = pending.indexOf(text);
|
|
1248
|
+
if (at === -1) {
|
|
1249
|
+
fail(ERRORS.INVALID_ARGUMENT, `unknown QA checklist item: ${text === '' ? '(empty)' : text}`);
|
|
1250
|
+
}
|
|
1251
|
+
pending.splice(at, 1);
|
|
1252
|
+
}
|
|
1253
|
+
if (pending.length > 0) {
|
|
1254
|
+
fail(ERRORS.INVALID_STATE, `QA checklist item not verified: ${pending[0]}`);
|
|
1255
|
+
}
|
|
1256
|
+
} else if (checks.length > 0) {
|
|
1257
|
+
// 没有清单却提交了勾选:不接受未知证据,避免写进投影后无从核对。
|
|
1258
|
+
fail(ERRORS.INVALID_ARGUMENT, 'this task has no QA checklist; do not submit checks');
|
|
1259
|
+
}
|
|
1260
|
+
outcome = acceptTask(task, command.actor, {
|
|
1261
|
+
note: command.payload?.note,
|
|
1262
|
+
confirmed: command.payload?.confirmed,
|
|
1263
|
+
qaChecks: checks,
|
|
1264
|
+
}, { expectedRevision, at: this.now() });
|
|
1265
|
+
break;
|
|
1266
|
+
}
|
|
1267
|
+
case 'request_changes': outcome = requestChangesTask(task, command.actor, { note: command.payload?.note }, { expectedRevision, at: this.now() }); break;
|
|
1268
|
+
case 'cancel': outcome = cancelTask(task, command.actor, { reason: command.payload?.reason, expectedRevision, at: this.now() }); break;
|
|
1269
|
+
case 'reopen': outcome = reopenTask(task, command.actor, { reason: command.payload?.reason, expectedRevision, members: state.members, at: this.now() }); break;
|
|
1270
|
+
case 'reassign':
|
|
1271
|
+
requireAgentMember(command.payload?.ownerId, 'ownerId');
|
|
1272
|
+
outcome = reassignTask(task, command.actor, command.payload?.ownerId, { expectedRevision, reason: command.payload?.reason, at: this.now() });
|
|
1273
|
+
break;
|
|
1274
|
+
case 'delete': outcome = deleteTask(task, command.actor, { expectedRevision, at: this.now() }); break;
|
|
1275
|
+
default: fail(ERRORS.INVALID_ARGUMENT, `unknown task action: ${action}`);
|
|
1276
|
+
}
|
|
1277
|
+
await this.ledger.append({ ...outcome.event, actor: command.actor, correlationId: command.correlationId, projectId: command.projectId, at: this.now() });
|
|
1278
|
+
// fold 会丢弃陈旧 revision 的事件(revision <= 当前),务必返回已提交的投影,
|
|
1279
|
+
// 否则并发 claim/accept 的失败方会收到“成功”并发出错误的 follower 通知。
|
|
1280
|
+
const committed = this.state.tasks?.[outcome.task.id] ?? outcome.task;
|
|
1281
|
+
if (action === 'accept') await this.notifyTaskFollowers(committed, command);
|
|
1282
|
+
return { task: committed, event: outcome.event };
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
async convert(command, payload) {
|
|
1286
|
+
const sourceEventIds = payload.sourceEventIds;
|
|
1287
|
+
if (!Array.isArray(sourceEventIds) || sourceEventIds.length === 0) fail(ERRORS.INVALID_ARGUMENT, 'sourceEventIds is required');
|
|
1288
|
+
const state = this.state;
|
|
1289
|
+
const existing = Object.values(state.tasks ?? {}).find((task) =>
|
|
1290
|
+
(task.originRefs ?? []).some((ref) => sourceEventIds.includes(ref)));
|
|
1291
|
+
if (existing !== undefined) {
|
|
1292
|
+
fail(ERRORS.CONFLICT, `already converted to ${existing.id}`, { details: { taskId: existing.id } });
|
|
1293
|
+
}
|
|
1294
|
+
const result = await this.createTask(command, {
|
|
1295
|
+
title: payload.title,
|
|
1296
|
+
resultDefinition: payload.doneCriteria ?? payload.resultDefinition,
|
|
1297
|
+
ownerId: payload.ownerId,
|
|
1298
|
+
assigneeId: payload.assigneeId,
|
|
1299
|
+
writeScopes: payload.writeScopes,
|
|
1300
|
+
originRefs: sourceEventIds,
|
|
1301
|
+
});
|
|
1302
|
+
return result;
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
/** Followers get one report when a Task is accepted; unfollow removes future reports. */
|
|
1306
|
+
async notifyTaskFollowers(task, command) {
|
|
1307
|
+
const followers = Array.isArray(this.state.followers?.[task.id]) ? this.state.followers[task.id] : [];
|
|
1308
|
+
for (const followerId of followers) {
|
|
1309
|
+
if (followerId === command.actor.memberId) continue;
|
|
1310
|
+
const duplicate = Object.values(this.state.inbox ?? {}).find((item) =>
|
|
1311
|
+
item.memberId === followerId
|
|
1312
|
+
&& item.type === 'followed_task_update'
|
|
1313
|
+
&& item.ref?.taskId === task.id
|
|
1314
|
+
&& item.ref?.kind === 'completed'
|
|
1315
|
+
&& item.state === 'unread');
|
|
1316
|
+
if (duplicate !== undefined) continue;
|
|
1317
|
+
const item = createInboxItem({
|
|
1318
|
+
memberId: followerId,
|
|
1319
|
+
type: 'followed_task_update',
|
|
1320
|
+
ref: { taskId: task.id, title: task.title, kind: 'completed' },
|
|
1321
|
+
requiresDecision: false,
|
|
1322
|
+
}, { at: this.now() });
|
|
1323
|
+
await this.ledger.append({
|
|
1324
|
+
type: 'inbox/item-created',
|
|
1325
|
+
payload: { itemId: item.id, ...item },
|
|
1326
|
+
actor: { kind: 'system' },
|
|
1327
|
+
projectId: command.projectId,
|
|
1328
|
+
at: this.now(),
|
|
1329
|
+
});
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
async follow(command, payload) {
|
|
1334
|
+
if (typeof payload.taskId !== 'string') fail(ERRORS.INVALID_ARGUMENT, 'taskId is required');
|
|
1335
|
+
const following = payload.following === true;
|
|
1336
|
+
await this.ledger.append({
|
|
1337
|
+
type: following ? 'task/followed' : 'task/unfollowed',
|
|
1338
|
+
payload: { taskId: payload.taskId, memberId: command.actor.memberId ?? this.humanId() },
|
|
1339
|
+
actor: command.actor,
|
|
1340
|
+
correlationId: command.correlationId,
|
|
1341
|
+
projectId: command.projectId,
|
|
1342
|
+
at: this.now(),
|
|
1343
|
+
});
|
|
1344
|
+
return { following };
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
async postThread(command, payload) {
|
|
1348
|
+
const taskId = payload.taskId;
|
|
1349
|
+
if (this.state.tasks?.[taskId] === undefined) fail(ERRORS.NOT_FOUND, `task ${String(taskId)} not found`);
|
|
1350
|
+
// headSeq 的读取与 ledger.append 之间有一次 await:两个并发 reply 会读到同一个
|
|
1351
|
+
// headSeq、各自生成 seq=headSeq+1,fold 按 seq 去重后第二条被永久丢弃,而两次
|
|
1352
|
+
// 调用都返回成功。用 runExclusive 让「读头 + 分配 seq + 提交」串行。
|
|
1353
|
+
return this.runExclusive(async () => {
|
|
1354
|
+
if (this.state.tasks?.[taskId] === undefined) fail(ERRORS.NOT_FOUND, `task ${String(taskId)} not found`);
|
|
1355
|
+
const thread = this.state.threads?.[taskId] ?? createThread(taskId);
|
|
1356
|
+
const actorKind = command.actor.kind;
|
|
1357
|
+
const authorId = command.actor.memberId ?? this.humanId();
|
|
1358
|
+
const outcome = appendReply(thread, { authorId, actorKind, baseSeq: payload.baseSeq, body: payload.body, refs: payload.refs }, { at: this.now() });
|
|
1359
|
+
await this.ledger.append({
|
|
1360
|
+
type: 'thread/posted',
|
|
1361
|
+
payload: { taskId, ...outcome.entry },
|
|
1362
|
+
actor: command.actor,
|
|
1363
|
+
correlationId: command.correlationId,
|
|
1364
|
+
projectId: command.projectId,
|
|
1365
|
+
at: this.now(),
|
|
1366
|
+
});
|
|
1367
|
+
return { thread: this.state.threads?.[taskId] ?? outcome.thread, entry: outcome.entry };
|
|
1368
|
+
});
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
/** PMO: answer all pending structured questions with the max-value policy. */
|
|
1372
|
+
async autoAnswerDecisions(projectId = Object.keys(this.state.projects ?? {})[0]) {
|
|
1373
|
+
const humanId = this.humanId();
|
|
1374
|
+
// 合同是「返回回答列表」:这里曾返回数字 0,调用方按数组迭代时抛 TypeError,
|
|
1375
|
+
// 整个 PMO tick 被打断且每个 tick 都重复失败。
|
|
1376
|
+
if (humanId === null || humanId === undefined) return [];
|
|
1377
|
+
// 只自动回答**有结构化问题**的决策项。成员致命失败生成的升级项没有 questions,
|
|
1378
|
+
// 自动作答会用一句通用话术把它 resolved,Human 再也看不到真正的失败。
|
|
1379
|
+
const items = Object.values(this.state.inbox ?? {}).filter((item) =>
|
|
1380
|
+
item.memberId === humanId
|
|
1381
|
+
&& item.type === 'decision_required'
|
|
1382
|
+
&& item.state === 'unread'
|
|
1383
|
+
&& Array.isArray(item.ref?.questions)
|
|
1384
|
+
&& item.ref.questions.length > 0);
|
|
1385
|
+
const results = [];
|
|
1386
|
+
for (const item of items) {
|
|
1387
|
+
const questions = Array.isArray(item.ref?.questions) ? item.ref.questions : [];
|
|
1388
|
+
const answers = chooseDecisionAnswers(questions);
|
|
1389
|
+
// 自动作答也要在锁内:它与 thread.post 一样是「读 head → 分配 seq → append」,
|
|
1390
|
+
// 并发时同 seq 会被 fold 静默丢弃,而 Human 的明确决策可能被自动决策替换。
|
|
1391
|
+
results.push(await this.runExclusive(() => this.autoAnswerDecision(item, answers, projectId)));
|
|
1392
|
+
}
|
|
1393
|
+
return results;
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
async autoAnswerDecision(item, answers, projectId = Object.keys(this.state.projects ?? {})[0]) {
|
|
1397
|
+
const taskId = typeof item.ref?.taskId === 'string' ? item.ref.taskId : null;
|
|
1398
|
+
const task = taskId === null ? undefined : this.state.tasks?.[taskId];
|
|
1399
|
+
const questionById = new Map((item.ref?.questions ?? []).map((question) => [question.id, question.text]));
|
|
1400
|
+
const lines = answers.length > 0
|
|
1401
|
+
? answers.map((answer) => `- ${questionById.get(answer.id) ?? answer.id}: ${answer.value}`)
|
|
1402
|
+
: ['- 无结构化问题:按当前 Task/Thread 的最高价值路径推进,不等待 Human。'];
|
|
1403
|
+
const body = `【PMO 自动决策】按最高价值建议执行,不需要 Human 再确认:\n${lines.join('\n')}`;
|
|
1404
|
+
let entry = null;
|
|
1405
|
+
if (task !== undefined) {
|
|
1406
|
+
const thread = this.state.threads?.[task.id] ?? createThread(task.id);
|
|
1407
|
+
const outcome = appendReply(thread, {
|
|
1408
|
+
authorId: 'mem_pmo',
|
|
1409
|
+
actorKind: 'system',
|
|
1410
|
+
baseSeq: thread.headSeq,
|
|
1411
|
+
body,
|
|
1412
|
+
}, { at: this.now() });
|
|
1413
|
+
await this.ledger.append({
|
|
1414
|
+
type: 'thread/posted',
|
|
1415
|
+
payload: { taskId: task.id, ...outcome.entry },
|
|
1416
|
+
actor: { kind: 'system', memberId: 'mem_pmo' },
|
|
1417
|
+
projectId,
|
|
1418
|
+
at: this.now(),
|
|
1419
|
+
});
|
|
1420
|
+
entry = outcome.entry;
|
|
1421
|
+
}
|
|
1422
|
+
const next = ackInboxItem(item, {
|
|
1423
|
+
disposition: 'done',
|
|
1424
|
+
decision: { answers, auto: true, by: 'mem_pmo', body },
|
|
1425
|
+
}, { at: this.now() });
|
|
1426
|
+
this.diag?.append({
|
|
1427
|
+
ev: 'pmo.auto-answer',
|
|
1428
|
+
itemId: item.id,
|
|
1429
|
+
taskId,
|
|
1430
|
+
answers: answers.length,
|
|
1431
|
+
projectId,
|
|
1432
|
+
});
|
|
1433
|
+
await this.ledger.append({
|
|
1434
|
+
type: 'inbox/acked',
|
|
1435
|
+
payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, decision: next.decision ?? null, at: next.ackedAt },
|
|
1436
|
+
actor: { kind: 'system', memberId: 'mem_pmo' },
|
|
1437
|
+
projectId,
|
|
1438
|
+
at: this.now(),
|
|
1439
|
+
});
|
|
1440
|
+
return { item: next, entry };
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
/** Surface an explicit Human decision request with all questions inline. */
|
|
1444
|
+
async requestDecision(command, payload) {
|
|
1445
|
+
const humanId = this.humanId();
|
|
1446
|
+
if (humanId === null) fail(ERRORS.NOT_FOUND, 'Human member not found');
|
|
1447
|
+
const raw = Array.isArray(payload.questions) ? payload.questions : [];
|
|
1448
|
+
if (raw.length === 0 || raw.length > 20) fail(ERRORS.INVALID_ARGUMENT, 'questions must contain 1..20 items');
|
|
1449
|
+
const questions = raw.map((question, index) => {
|
|
1450
|
+
if (typeof question === 'string') return { id: `q${index + 1}`, text: question.trim() };
|
|
1451
|
+
if (question === null || typeof question !== 'object') fail(ERRORS.INVALID_ARGUMENT, `questions[${index}] must be a string or object`);
|
|
1452
|
+
const text = typeof question.text === 'string' ? question.text.trim() : '';
|
|
1453
|
+
if (text === '') fail(ERRORS.INVALID_ARGUMENT, `questions[${index}].text is required`);
|
|
1454
|
+
const options = Array.isArray(question.options) ? question.options.filter((option) => typeof option === 'string' && option.trim() !== '').slice(0, 12) : [];
|
|
1455
|
+
return {
|
|
1456
|
+
id: typeof question.id === 'string' && question.id !== '' ? question.id : `q${index + 1}`,
|
|
1457
|
+
text,
|
|
1458
|
+
...(options.length ? { options } : {}),
|
|
1459
|
+
...(typeof question.recommendation === 'string' && question.recommendation !== '' ? { recommendation: question.recommendation } : {}),
|
|
1460
|
+
...(typeof question.blocking === 'string' && question.blocking !== '' ? { blocking: question.blocking } : {}),
|
|
1461
|
+
};
|
|
1462
|
+
});
|
|
1463
|
+
const title = typeof payload.title === 'string' && payload.title.trim() !== '' ? payload.title.trim() : '需要你决策';
|
|
1464
|
+
const taskId = typeof payload.taskId === 'string' ? payload.taskId : null;
|
|
1465
|
+
const duplicate = Object.values(this.state.inbox ?? {}).find((item) =>
|
|
1466
|
+
item.memberId === humanId
|
|
1467
|
+
&& item.type === 'decision_required'
|
|
1468
|
+
&& item.ref?.title === title
|
|
1469
|
+
&& item.ref?.taskId === taskId
|
|
1470
|
+
&& !['resolved', 'dismissed', 'superseded'].includes(item.state));
|
|
1471
|
+
if (duplicate !== undefined) return { item: duplicate, duplicate: true };
|
|
1472
|
+
const item = createInboxItem({
|
|
1473
|
+
memberId: humanId,
|
|
1474
|
+
type: 'decision_required',
|
|
1475
|
+
ref: {
|
|
1476
|
+
taskId,
|
|
1477
|
+
title,
|
|
1478
|
+
memberId: command.actor.memberId ?? null,
|
|
1479
|
+
memberName: this.state.members?.[command.actor.memberId]?.name ?? command.actor.memberId ?? null,
|
|
1480
|
+
questions,
|
|
1481
|
+
...(typeof payload.source === 'string' && payload.source !== '' ? { source: payload.source } : {}),
|
|
1482
|
+
},
|
|
1483
|
+
requiresDecision: true,
|
|
1484
|
+
}, { at: this.now() });
|
|
1485
|
+
await this.ledger.append({
|
|
1486
|
+
type: 'inbox/item-created',
|
|
1487
|
+
payload: { itemId: item.id, ...item },
|
|
1488
|
+
actor: command.actor,
|
|
1489
|
+
correlationId: command.correlationId,
|
|
1490
|
+
projectId: command.projectId,
|
|
1491
|
+
at: this.now(),
|
|
1492
|
+
});
|
|
1493
|
+
return { item, duplicate: false };
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
async answerDecision(command, payload) {
|
|
1497
|
+
if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may answer a decision');
|
|
1498
|
+
const item = this.state.inbox?.[payload.itemId];
|
|
1499
|
+
if (item === undefined) fail(ERRORS.NOT_FOUND, `inbox item ${String(payload.itemId)} not found`);
|
|
1500
|
+
if (item.type !== 'decision_required' || item.requiresDecision !== true) {
|
|
1501
|
+
fail(ERRORS.INVALID_STATE, 'this inbox item is not a Human decision');
|
|
1502
|
+
}
|
|
1503
|
+
const humanId = command.actor.memberId;
|
|
1504
|
+
if (item.memberId !== humanId) fail(ERRORS.UNAUTHORIZED, 'decision belongs to another member');
|
|
1505
|
+
// 终态前置:已 resolved/dismissed/superseded 的决策项再次提交过去会被接受,
|
|
1506
|
+
// 于是同一决策重复写 Thread 回复,ack 回来的 item 还是旧答案。
|
|
1507
|
+
if (['resolved', 'dismissed', 'superseded', 'done'].includes(item.state)) {
|
|
1508
|
+
fail(ERRORS.INVALID_STATE, `decision ${String(item.id)} is already ${String(item.state)}`);
|
|
1509
|
+
}
|
|
1510
|
+
const answers = (Array.isArray(payload.answers) ? payload.answers : [])
|
|
1511
|
+
.map((answer, index) => ({
|
|
1512
|
+
id: typeof answer?.id === 'string' && answer.id !== '' ? answer.id : `q${index + 1}`,
|
|
1513
|
+
value: typeof answer?.value === 'string' ? answer.value.trim() : '',
|
|
1514
|
+
}))
|
|
1515
|
+
.filter((answer) => answer.value !== '');
|
|
1516
|
+
if (answers.length === 0) fail(ERRORS.INVALID_ARGUMENT, 'at least one answer is required');
|
|
1517
|
+
const questions = Array.isArray(item.ref?.questions) ? item.ref.questions : [];
|
|
1518
|
+
// 决策必须覆盖全部问题:只答一半就把 item 置为 resolved,会让未答的问题
|
|
1519
|
+
// 从待决策表单里消失(UI 有 complete 校验,命令层也必须一致)。
|
|
1520
|
+
if (questions.length > 0) {
|
|
1521
|
+
const known = new Set(questions.map((question) => question.id));
|
|
1522
|
+
const unknown = answers.filter((answer) => !known.has(answer.id)).map((answer) => answer.id);
|
|
1523
|
+
if (unknown.length > 0) fail(ERRORS.INVALID_ARGUMENT, `unknown question id(s): ${unknown.join(', ')}`);
|
|
1524
|
+
const missing = questions.filter((question) => !answers.some((answer) => answer.id === question.id)).map((question) => question.id);
|
|
1525
|
+
if (missing.length > 0) fail(ERRORS.INVALID_ARGUMENT, `every question must be answered; missing: ${missing.join(', ')}`);
|
|
1526
|
+
}
|
|
1527
|
+
const lines = answers.map((answer) => {
|
|
1528
|
+
const question = questions.find((candidate) => candidate.id === answer.id);
|
|
1529
|
+
return `- ${question?.text ?? answer.id}: ${answer.value}`;
|
|
1530
|
+
});
|
|
1531
|
+
const body = `Human 决策:\n${lines.join('\n')}${typeof payload.note === 'string' && payload.note.trim() !== '' ? `\n备注:${payload.note.trim()}` : ''}`;
|
|
1532
|
+
let entry = null;
|
|
1533
|
+
if (typeof item.ref?.taskId === 'string' && this.state.tasks?.[item.ref.taskId] !== undefined) {
|
|
1534
|
+
const taskId = item.ref.taskId;
|
|
1535
|
+
const thread = this.state.threads?.[taskId] ?? createThread(taskId);
|
|
1536
|
+
const outcome = appendReply(thread, {
|
|
1537
|
+
authorId: humanId,
|
|
1538
|
+
actorKind: 'human',
|
|
1539
|
+
baseSeq: thread.headSeq,
|
|
1540
|
+
body,
|
|
1541
|
+
}, { at: this.now() });
|
|
1542
|
+
await this.ledger.append({
|
|
1543
|
+
type: 'thread/posted',
|
|
1544
|
+
payload: { taskId, ...outcome.entry },
|
|
1545
|
+
actor: command.actor,
|
|
1546
|
+
projectId: command.projectId,
|
|
1547
|
+
at: this.now(),
|
|
1548
|
+
});
|
|
1549
|
+
entry = outcome.entry;
|
|
1550
|
+
}
|
|
1551
|
+
const next = ackInboxItem(item, { disposition: 'done', decision: { answers, note: payload.note ?? '', body } }, { at: this.now() });
|
|
1552
|
+
await this.ledger.append({
|
|
1553
|
+
type: 'inbox/acked',
|
|
1554
|
+
payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, decision: next.decision ?? null, at: next.ackedAt },
|
|
1555
|
+
actor: command.actor,
|
|
1556
|
+
projectId: command.projectId,
|
|
1557
|
+
at: this.now(),
|
|
1558
|
+
});
|
|
1559
|
+
return { item: next, entry };
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
async ack(command, payload) {
|
|
1563
|
+
const state = this.state;
|
|
1564
|
+
const item = state.inbox?.[payload.itemId];
|
|
1565
|
+
if (item === undefined) fail(ERRORS.NOT_FOUND, `inbox item ${String(payload.itemId)} not found`);
|
|
1566
|
+
// 归属校验:成员只能处理自己的收件项。缺了这条,任意 agent 可用一个
|
|
1567
|
+
// itemId 把别人的(含 Human 的)决策项标成 resolved。
|
|
1568
|
+
const actorMemberId = command.actor.memberId ?? this.humanId();
|
|
1569
|
+
if (command.actor.kind !== 'human' && item.memberId !== actorMemberId) {
|
|
1570
|
+
fail(ERRORS.UNAUTHORIZED, 'inbox item belongs to another member');
|
|
1571
|
+
}
|
|
1572
|
+
const next = ackInboxItem(item, { disposition: payload.disposition, decision: payload.decision }, { at: this.now() });
|
|
1573
|
+
await this.ledger.append({
|
|
1574
|
+
type: 'inbox/acked',
|
|
1575
|
+
payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, decision: next.decision ?? null, at: next.ackedAt },
|
|
1576
|
+
actor: command.actor,
|
|
1577
|
+
correlationId: command.correlationId,
|
|
1578
|
+
projectId: command.projectId,
|
|
1579
|
+
at: this.now(),
|
|
1580
|
+
});
|
|
1581
|
+
return { item: next };
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
/** Create an inbox item and append it; used by the Waker/observer. */
|
|
1585
|
+
async notify(input, command = { actor: { kind: 'system' } }) {
|
|
1586
|
+
const item = createInboxItem(input, { at: this.now() });
|
|
1587
|
+
await this.ledger.append({
|
|
1588
|
+
type: 'inbox/item-created',
|
|
1589
|
+
payload: { itemId: item.id, ...item },
|
|
1590
|
+
actor: command.actor ?? { kind: 'system' },
|
|
1591
|
+
projectId: command.projectId,
|
|
1592
|
+
at: this.now(),
|
|
1593
|
+
});
|
|
1594
|
+
return item;
|
|
1595
|
+
}
|
|
1596
|
+
}
|