@suifei/dsh-ai-team 0.3.56 → 0.3.60

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/index.js CHANGED
@@ -11,6 +11,7 @@
11
11
  import { homedir } from 'node:os';
12
12
  import { join } from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
+ import { readFileSync, writeFileSync } from 'node:fs';
14
15
  import z from '@deepseek-ai/schemastery';
15
16
  import { ProjectRuntime } from './lib/host/project-runtime.js';
16
17
  import { ProjectRegistry } from './lib/host/project-registry.js';
@@ -29,6 +30,10 @@ import { installFaultAdapter } from './lib/host/fault-adapter.js';
29
30
  import { buildModelCatalog } from './lib/host/model-catalog.js';
30
31
  import { createTeamTool } from './lib/host/member-tools.js';
31
32
  import { describeWake, planWakes } from './lib/host/waker.js';
33
+ import { aggregatePeople } from './lib/host/people-view.js';
34
+ import { riskView } from './lib/host/risk-view.js';
35
+ import { weeklyView } from './lib/host/weekly-view.js';
36
+ import { isInformationalThreadMention } from './lib/domain/inbox.js';
32
37
  import { createDiagLogger, defaultDiagDir } from './lib/diaglog.js';
33
38
 
34
39
  export const name = 'ai-team';
@@ -36,7 +41,7 @@ export const name = 'ai-team';
36
41
  /** The workbench only makes sense where the Web carrier exists. */
37
42
  export const inject = ['webServer', 'permissionPresets', 'sandboxPolicy'];
38
43
 
39
- const VERSION = '0.3.56';
44
+ const VERSION = '0.3.60';
40
45
  const PROJECT_ID = 'prj_main';
41
46
  const HUMAN_ID = 'mem_human';
42
47
 
@@ -95,12 +100,6 @@ function profileName() {
95
100
  return process.env.DSH_PROFILE || 'default';
96
101
  }
97
102
 
98
- function errorResponse(res, error) {
99
- const code = typeof error?.code === 'string' ? error.code : 'INTERNAL';
100
- const status = typeof error?.status === 'number' ? error.status : (code === 'E_STORAGE' ? 503 : 409);
101
- send(res, { error: { code, message: error?.message ?? 'command failed', details: error?.details ?? null } }, status);
102
- }
103
-
104
103
  /**
105
104
  * Open the default Project ledger and seed the Human + Project skeleton once.
106
105
  * A torn tail is repaired by the writer; the repair is recorded as a system
@@ -151,6 +150,17 @@ export function apply(ctx, config = {}) {
151
150
  maxBytes: config.diagLogMaxBytes ?? 1048576,
152
151
  level: config.diagLevel ?? 'errors',
153
152
  });
153
+ // HTTP 层失败/拒绝的统一落点(route.reject 在 errors 白名单内)。
154
+ const errorResponse = (res, error) => {
155
+ diag.append({
156
+ ev: 'route.reject',
157
+ code: typeof error?.code === 'string' ? error.code : 'INTERNAL',
158
+ message: error?.message ?? String(error ?? 'command failed'),
159
+ });
160
+ const code = typeof error?.code === 'string' ? error.code : 'INTERNAL';
161
+ const status = typeof error?.status === 'number' ? error.status : (code === 'E_STORAGE' ? 503 : 409);
162
+ send(res, { error: { code, message: error?.message ?? 'command failed', details: error?.details ?? null } }, status);
163
+ };
154
164
  ctx.effect(() => {
155
165
  const webServer = ctx.get('webServer');
156
166
  if (webServer === undefined) return () => {};
@@ -362,13 +372,15 @@ export function apply(ctx, config = {}) {
362
372
  const pmoLastEscalate = new Map();
363
373
  const pmoLastReview = new Map();
364
374
  // Members resumed from cold sessions produce AgentHandles nobody stored;
365
- // track them so teardown can dispose every owned activation.
366
- const resumedHandles = new Set();
375
+ // track them by session id so teardown — and session reseat — can
376
+ // dispose exactly the handle they own.
377
+ const resumedHandles = new Map();
367
378
  let pmoTimer = null;
368
- const projectCwd = (projectRuntime, member) => member?.workspace
379
+ // 项目工作目录(显式,无兜底):null 表示尚未设置。历史版本在此处用
380
+ // runtime.dir(账本目录)兜底,曾把成员会话 cwd 钉进插件数据目录。
381
+ const projectWorkspace = (projectRuntime, member) => member?.workspace
369
382
  || projectRuntime?.service?.state?.projects?.[projectRuntime.id]?.workspacePath
370
- || projectRuntime?.dir
371
- || undefined;
383
+ || null;
372
384
  const wakeFromResult = async (projectRuntime, result, actor = {}) => {
373
385
  if (projectRuntime === null || projectRuntime === undefined) return;
374
386
  const plans = planWakes(projectRuntime.service.state, result, actor);
@@ -398,7 +410,14 @@ export function apply(ctx, config = {}) {
398
410
  // Reserve before the async delivery: the HTTP result and the ledger
399
411
  // event both schedule the same plan, and only one may deliver it.
400
412
  wakeKeys.set(plan.key, result?.event?.seq ?? head);
401
- const cwd = projectCwd(projectRuntime, member);
413
+ // 无工作目录的项目不 wake(与 activate 的 fail-closed 同一不变量):
414
+ // 冷恢复/直连唤醒都会在会话原 cwd 里干活,不该落到插件数据目录。
415
+ const projectWorkspacePath = projectWorkspace(projectRuntime, member);
416
+ if (projectWorkspacePath === null || projectWorkspacePath.trim?.() === '') {
417
+ diag?.append({ ev: 'wake.skip', projectId: projectRuntime.id, memberId: plan.memberId, reason: 'E_WORKSPACE_REQUIRED' });
418
+ continue;
419
+ }
420
+ const cwd = projectWorkspacePath;
402
421
  try {
403
422
  // Idle default members have no Agent session yet. A wake must
404
423
  // activate them first; otherwise the first Human message is
@@ -432,7 +451,7 @@ export function apply(ctx, config = {}) {
432
451
  provider: providers[0],
433
452
  preset: 'standard',
434
453
  cwd,
435
- trackHandle: (handle) => resumedHandles.add(handle),
454
+ trackHandle: (sessionId, handle) => resumedHandles.set(sessionId, handle),
436
455
  });
437
456
  const delivered = await runtime.wake(member, { prompt: await wakePrompt(plan, member) });
438
457
  messageId = delivered.messageId ?? null;
@@ -723,15 +742,51 @@ export function apply(ctx, config = {}) {
723
742
  if (member === undefined) return { error: { code: 'E_NOT_FOUND', message: 'member not found' }, status: 404 };
724
743
  if (member.status === 'retired') return { error: { code: 'E_INVALID_STATE', message: 'member is retired' }, status: 409 };
725
744
  if (member.status === 'running' && body.payload?.force !== true) return { error: { code: 'E_INVALID_STATE', message: 'member is already running' }, status: 409 };
745
+ // 无目录项目 fail-closed:成员绝不落到宿主默认目录或插件数据目录
746
+ // (projectCwd 的 dir 兜底)里执行。显式判工作目录,不吃兜底。
747
+ // 先于 reseat 释放旧句柄——否则无目录的 force 会先杀句柄再 409。
748
+ const workspacePath = projectRuntime?.service?.state?.projects?.[projectRuntime.id]?.workspacePath;
749
+ const effectiveDir = member?.workspace || (typeof workspacePath === 'string' ? workspacePath.trim() : '');
750
+ if (effectiveDir === '') {
751
+ diag?.append({ ev: 'activate.reject', projectId: projectRuntime.id, memberId: member.id, code: 'E_WORKSPACE_REQUIRED' });
752
+ return {
753
+ error: {
754
+ code: 'E_WORKSPACE_REQUIRED',
755
+ message: 'this Project has no workspace yet; set a workspace directory before activating members',
756
+ },
757
+ status: 409,
758
+ };
759
+ }
760
+ // 会话重建(reseat):成员已有会话且本次为 force 时,先释放旧会话的
761
+ // 运行时句柄(activation / resume handle),旧 DSH 会话本体由宿主持
762
+ // 久管理,插件不再持有或唤醒它;新会话落在当前项目工作目录。这是
763
+ // 修复历史"账本目录兜底 cwd"游离会话的唯一路径(会话 cwd 创建时
764
+ // 钉死,resume 不覆盖,DSH 不提供原地改 cwd 的 API)。
765
+ if (typeof member.sessionId === 'string' && member.sessionId !== '' && body.payload?.force === true) {
766
+ const staleId = member.sessionId;
767
+ const staleActivation = activations.get(staleId);
768
+ if (staleActivation !== undefined) {
769
+ activations.delete(staleId);
770
+ try { await staleActivation.dispose?.(); } catch { /* already gone */ }
771
+ }
772
+ const staleHandle = resumedHandles.get(staleId);
773
+ if (staleHandle !== undefined) {
774
+ resumedHandles.delete(staleId);
775
+ try { await staleHandle.dispose?.(); } catch { /* already gone */ }
776
+ }
777
+ diag?.append({ ev: 'member.reseat', memberId: member.id, oldSessionId: staleId, projectId: projectRuntime.id });
778
+ }
726
779
  const subagents = ctx.get('subagents');
727
780
  const sessions = ctx.get('sessions');
728
781
  const permissionPresets = ctx.get('permissionPresets');
729
782
  const sandboxPolicy = ctx.get('sandboxPolicy');
730
783
  if (subagents === undefined || sessions === undefined || permissionPresets === undefined || sandboxPolicy === undefined) {
784
+ diag?.append({ ev: 'activate.reject', projectId: projectRuntime.id, memberId: member.id, code: 'E_RUNTIME_UNAVAILABLE' });
731
785
  return { error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'member runtime services are unavailable' }, status: 503 };
732
786
  }
733
787
  const providers = typeof subagents.list === 'function' ? subagents.list() : [];
734
788
  if (providers.length === 0) {
789
+ diag?.append({ ev: 'activate.reject', projectId: projectRuntime.id, memberId: member.id, code: 'E_RUNTIME_UNAVAILABLE', detail: 'no provider' });
735
790
  return { error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'no subagent provider is registered' }, status: 503 };
736
791
  }
737
792
  try {
@@ -761,13 +816,13 @@ export function apply(ctx, config = {}) {
761
816
  parent: parentInfo.agent,
762
817
  provider: providers[0],
763
818
  preset: 'standard',
764
- cwd: projectCwd(projectRuntime, member),
765
- trackHandle: (handle) => resumedHandles.add(handle),
819
+ cwd: effectiveDir,
820
+ trackHandle: (sessionId, handle) => resumedHandles.set(sessionId, handle),
766
821
  });
767
822
  const result = await runtime.activate(activationMember, {
768
823
  prompt: `${memberIdentity(activationMember)}\n\n${typeof body.payload?.prompt === 'string'
769
824
  ? body.payload.prompt
770
- : '你被加入 AI Team。先读取项目简报与收件箱,再处理分配给你的任务。'}${await formatSkillCatalog(skillsService, { cwd: projectCwd(projectRuntime, activationMember) })}${await loadSkillContext(activationMember, projectRuntime.dir)}`,
825
+ : '你被加入 AI Team。先读取项目简报与收件箱,再处理分配给你的任务。'}${await formatSkillCatalog(skillsService, { cwd: effectiveDir })}${await loadSkillContext(activationMember, projectRuntime.dir)}`,
771
826
  });
772
827
  let bound;
773
828
  try {
@@ -900,6 +955,7 @@ export function apply(ctx, config = {}) {
900
955
  projectName,
901
956
  projectGoal,
902
957
  workspacePath,
958
+ diag,
903
959
  });
904
960
  booted.runtimes.set(nextProjectId, next);
905
961
  attachRuntime(next);
@@ -956,8 +1012,102 @@ export function apply(ctx, config = {}) {
956
1012
  const catalog = await buildModelCatalog(ctx.get('llm'), ctx.get('agentDefaultModel'));
957
1013
  return send(res, catalog);
958
1014
  }
959
- if (req.method === 'GET' && url.pathname === '/ai-team/api/health') {
960
- const head = booted.ledger.head;
1015
+ // R-17 person 别名:视图层绑定(name → personId),文件存策略数据
1016
+ // 目录;聚合时别名生效,未绑定回落同名聚合(可回退路径)。
1017
+ const aliasesPath = join(booted.dataDir, 'people-aliases.json');
1018
+ const readAliases = () => {
1019
+ try {
1020
+ const parsed = JSON.parse(readFileSync(aliasesPath, 'utf8'));
1021
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
1022
+ } catch {
1023
+ return null;
1024
+ }
1025
+ };
1026
+ // 人员池:按"人"聚合各项目账本的成员身份/状态/失败/任务数
1027
+ //(11-管理视角与信息架构 §2;只读,复用既有投影,不建新数据)。
1028
+ if (req.method === 'GET' && url.pathname === '/ai-team/api/people') {
1029
+ const registryEntries = booted.registry.list();
1030
+ const people = aggregatePeople(registryEntries, [...booted.runtimes.values()], { aliases: readAliases() });
1031
+ return send(res, { ok: true, people });
1032
+ }
1033
+ // R-17 绑定:把一个名字并到某个 personId(Human 在人员池显式确认)。
1034
+ if (req.method === 'POST' && url.pathname === '/ai-team/api/people-aliases') {
1035
+ const body = await readJson(req);
1036
+ const memberName = typeof body?.name === 'string' ? body.name.trim() : '';
1037
+ const personId = typeof body?.personId === 'string' ? body.personId.trim() : '';
1038
+ if (memberName === '' || personId === '') {
1039
+ return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: 'name and personId are required' } }, 400);
1040
+ }
1041
+ const aliases = readAliases() ?? {};
1042
+ aliases[memberName] = personId;
1043
+ writeFileSync(aliasesPath, JSON.stringify(aliases, null, 2) + '\n', 'utf8');
1044
+ diag?.append({ ev: 'people.alias', name: memberName, personId });
1045
+ return send(res, { ok: true, aliases });
1046
+ }
1047
+ // 待验收跨项目队列(R-09):各项目 q1 中需要 Human 验收的任务
1048
+ //(review/irreversible 类目,复用 quadrantsView 既有投影)。
1049
+ if (req.method === 'GET' && url.pathname === '/ai-team/api/pending-acceptance') {
1050
+ const registryEntries = booted.registry.list();
1051
+ const rows = [];
1052
+ for (const runtime of booted.runtimes.values()) {
1053
+ const projectName = registryEntries.find((project) => project.id === runtime.id)?.name ?? runtime.id;
1054
+ const q1 = runtime.service.quadrants(runtime.id).q1;
1055
+ for (const item of q1.items ?? []) {
1056
+ if (item.kind !== 'task' || (item.category !== 'review' && item.category !== 'irreversible')) continue;
1057
+ rows.push({ ...item, projectId: runtime.id, projectName });
1058
+ }
1059
+ }
1060
+ return send(res, { ok: true, rows });
1061
+ }
1062
+ // 风险清单(R-07):当前项目账本的三类风险只读投影(受阻/失败/待决超时)。
1063
+ if (req.method === 'GET' && url.pathname === '/ai-team/api/risks') {
1064
+ const requested = url.searchParams.get('project');
1065
+ const runtime = (requested === null ? null : projectRuntime(requested)) ?? currentRuntime();
1066
+ if (runtime === null || runtime === undefined) {
1067
+ return send(res, { ok: true, risks: { rev: 0, generatedAt: Date.now(), blocked: [], failures: [], staleDecisions: [], counts: { blocked: 0, failures: 0, staleDecisions: 0 } } });
1068
+ }
1069
+ const staleHours = Number.parseFloat(url.searchParams.get('staleHours') ?? '');
1070
+ const risks = riskView(runtime.service.state, {
1071
+ now: Date.now(),
1072
+ staleHours: Number.isFinite(staleHours) && staleHours > 0 ? staleHours : 24,
1073
+ });
1074
+ return send(res, { ok: true, projectId: runtime.id, risks });
1075
+ }
1076
+ // 项目周报(R-11):同一投影的正向/负向双解读数据面。
1077
+ const weekly = url.pathname.match(/^\/ai-team\/api\/projects\/([^/]+)\/weekly$/);
1078
+ if (req.method === 'GET' && weekly !== null) {
1079
+ const runtime = projectRuntime(decodeURIComponent(weekly[1]));
1080
+ if (runtime === null) return send(res, { error: { code: 'NOT_FOUND', message: 'project not found' } }, 404);
1081
+ const weeks = Number.parseInt(url.searchParams.get('weeks') ?? '', 10);
1082
+ return send(res, {
1083
+ ok: true,
1084
+ projectId: runtime.id,
1085
+ weekly: weeklyView(runtime.service.state, {
1086
+ now: Date.now(),
1087
+ weeks: Number.isSafeInteger(weeks) && weeks > 0 ? Math.min(weeks, 12) : 1,
1088
+ }),
1089
+ });
1090
+ }
1091
+ // 任务事件历史(R-18):Human 侧可追溯入口的只读数据面。
1092
+ const taskEvents = url.pathname.match(/^\/ai-team\/api\/projects\/([^/]+)\/tasks\/([^/]+)\/events$/);
1093
+ if (req.method === 'GET' && taskEvents !== null) {
1094
+ const runtime = projectRuntime(decodeURIComponent(taskEvents[1]));
1095
+ const taskId = decodeURIComponent(taskEvents[2]);
1096
+ if (runtime === null || runtime === undefined) return send(res, { error: { code: 'NOT_FOUND', message: 'project not found' } }, 404);
1097
+ const events = runtime.ledger.events.filter((event) => {
1098
+ const pid = event.payload?.taskId ?? event.payload?.id ?? null;
1099
+ return typeof pid === 'string' && pid === taskId;
1100
+ });
1101
+ return send(res, {
1102
+ ok: true,
1103
+ taskId,
1104
+ events: events.map((event) => ({
1105
+ seq: event.seq, type: event.type, at: event.at,
1106
+ actor: event.actor ?? null,
1107
+ })),
1108
+ });
1109
+ }
1110
+ if (req.method === 'GET' && url.pathname === '/ai-team/api/health') { const head = booted.ledger.head;
961
1111
  return send(res, {
962
1112
  ok: true,
963
1113
  plugin: name,
@@ -1029,11 +1179,22 @@ export function apply(ctx, config = {}) {
1029
1179
  const requestedRuntime = requested === null ? null : projectRuntime(requested);
1030
1180
  const bootstrapRuntime = requestedRuntime ?? currentRuntime();
1031
1181
  const bootstrap = bootstrapRuntime.service.bootstrap(bootstrapRuntime.id);
1182
+ // 跨项目收件箱聚合:其它项目只读 state.inbox 过滤(此前对每个
1183
+ // 项目整调 bootstrap——board+quadrants+threads 全算,O(项目数×
1184
+ // 全视图)/请求)。
1032
1185
  const inbox = [];
1033
1186
  for (const runtime of booted.runtimes.values()) {
1034
1187
  const projectName = booted.registry.list().find((project) => project.id === runtime.id)?.name ?? runtime.id;
1035
- const view = runtime.id === bootstrapRuntime.id ? bootstrap : runtime.service.bootstrap(runtime.id);
1036
- for (const item of view.inbox ?? []) {
1188
+ if (runtime.id === bootstrapRuntime.id) {
1189
+ for (const item of bootstrap.inbox ?? []) {
1190
+ inbox.push({ ...item, projectId: runtime.id, projectName });
1191
+ }
1192
+ continue;
1193
+ }
1194
+ const humanId = runtime.service.humanId();
1195
+ for (const item of Object.values(runtime.service.state.inbox ?? {})) {
1196
+ if (humanId === null || item.memberId !== humanId) continue;
1197
+ if (isInformationalThreadMention(item)) continue;
1037
1198
  inbox.push({ ...item, projectId: runtime.id, projectName });
1038
1199
  }
1039
1200
  }
@@ -1191,7 +1352,8 @@ export function apply(ctx, config = {}) {
1191
1352
  const goal = typeof body.payload?.goal === 'string' ? body.payload.goal.trim() : '';
1192
1353
  const workspacePath = typeof body.payload?.workspacePath === 'string' ? body.payload.workspacePath.trim() : '';
1193
1354
  if (name === '') return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: 'project name is required' } }, 400);
1194
- if (workspacePath === '') return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: 'project workspacePath is required' } }, 400);
1355
+ // 工作目录可空(稍后设置):讨论与建卡不受限;成员激活在
1356
+ // activateMember 处 fail-closed,绝不落到宿主默认目录执行。
1195
1357
  const id = ids.project();
1196
1358
  booted.registry.add({ id, name, goal, workspacePath });
1197
1359
  const next = await activateProject(id, name, goal, workspacePath);
@@ -1258,7 +1420,7 @@ export function apply(ctx, config = {}) {
1258
1420
  }));
1259
1421
  }
1260
1422
  activations.clear();
1261
- for (const handle of resumedHandles) {
1423
+ for (const handle of resumedHandles.values()) {
1262
1424
  cleanup.push(Promise.resolve().then(async () => {
1263
1425
  try { await handle?.dispose?.(); } catch { /* already gone */ }
1264
1426
  }));
package/lib/diaglog.js CHANGED
@@ -10,7 +10,7 @@ import { appendFile, mkdir, readFile, rename, stat } from 'node:fs/promises';
10
10
  import { homedir } from 'node:os';
11
11
  import { join } from 'node:path';
12
12
 
13
- /** The date-stamped file name carries the project id and the day (naming rule). */
13
+ /** The date-stamped file name carries the day; rows carry projectId/projectName. */
14
14
  export function diagFileName(date = new Date()) {
15
15
  return `aiteam-diag-${date.toISOString().slice(0, 10)}.jsonl`;
16
16
  }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * 人员池只读聚合(11-管理视角与信息架构 §2):遍历各 Project 账本的
3
+ * members/tasks,按姓名把"同一个人在各项目的身份"聚成一行。
4
+ * 不产生任何新数据——输入是既有账本投影,输出是纯视图。
5
+ *
6
+ * 同名即同一人:默认花名册同名同人;自建成员重名视为同一团队身份(文档化
7
+ * 于 docs/11 §5)。可选 `aliases`(name → personId 视图层绑定,R-17)在
8
+ * 同名聚合之上生效。
9
+ */
10
+
11
+ import { isTaskBlocked } from '../ledger/fold.js';
12
+
13
+ const ACTIVE_TASK_STATUSES = new Set(['pending', 'in_progress', 'pending_acceptance']);
14
+
15
+ /**
16
+ * @param {Array<{id:string,name:string}>} registryEntries
17
+ * @param {Array<{id:string,service:{state:any}}>} runtimes
18
+ * @param {{ aliases?: Record<string,string> }} [options]
19
+ * @returns {Array<{name:string,role:string,projects:Array,failures:number,activeTasks:number}>}
20
+ */
21
+ export function aggregatePeople(registryEntries, runtimes, options = {}) {
22
+ const aliases = options.aliases ?? null;
23
+ const people = new Map();
24
+ const bucketOf = (name) => {
25
+ const personId = aliases !== null && Object.prototype.hasOwnProperty.call(aliases, name) ? aliases[name] : null;
26
+ return personId !== null ? `person:${personId}` : `name:${name}`;
27
+ };
28
+ for (const runtime of runtimes) {
29
+ const projectName = registryEntries.find((project) => project.id === runtime.id)?.name ?? runtime.id;
30
+ const state = runtime.service?.state;
31
+ if (state === undefined || state === null) continue;
32
+ // 本项目的活跃任务计数:按 owner/assignee 两个责任位累计,并按状态
33
+ // 分解(R-10 成员负载:进行中/待验收/受阻)。
34
+ const loadByMember = new Map();
35
+ for (const task of Object.values(state.tasks ?? {})) {
36
+ if (task.tombstone === true || !ACTIVE_TASK_STATUSES.has(task.status)) continue;
37
+ const bucketKey = task.status === 'in_progress' ? 'inProgress'
38
+ : task.status === 'pending_acceptance' ? 'pendingAcceptance'
39
+ : 'pending';
40
+ for (const memberId of [task.ownerId, task.assigneeId]) {
41
+ if (typeof memberId !== 'string' || memberId === '') continue;
42
+ const load = loadByMember.get(memberId) ?? { activeTasks: 0, inProgress: 0, pendingAcceptance: 0, pending: 0, blocked: 0 };
43
+ load.activeTasks += 1;
44
+ if (bucketKey === 'inProgress') load.inProgress += 1;
45
+ else if (bucketKey === 'pendingAcceptance') load.pendingAcceptance += 1;
46
+ else load.pending += 1;
47
+ if (isTaskBlocked(state, task) === true) load.blocked += 1;
48
+ loadByMember.set(memberId, load);
49
+ }
50
+ }
51
+ for (const member of Object.values(state.members ?? {})) {
52
+ if (member.kind === 'human') continue;
53
+ // 空串名不吃 ?? 兜底(fold 允许空名成员;空名各自按 id 独立成行)。
54
+ const memberName = member.name || member.id;
55
+ const bucket = bucketOf(memberName);
56
+ const entry = people.get(bucket) ?? {
57
+ name: memberName,
58
+ role: member.role ?? '',
59
+ projects: [],
60
+ failures: 0,
61
+ activeTasks: 0,
62
+ };
63
+ if (entry.role === '' && member.role) entry.role = member.role;
64
+ const load = loadByMember.get(member.id) ?? { activeTasks: 0, inProgress: 0, pendingAcceptance: 0, pending: 0, blocked: 0 };
65
+ // 同人同项目出现多个 memberId(如离职后重入职的新会话 id):合并为
66
+ // 一行负载,memberIds 保留全部身份 id(兼容字段 memberId 取首个)。
67
+ const existingProjectRow = entry.projects.find((row) => row.projectId === runtime.id);
68
+ if (existingProjectRow !== undefined) {
69
+ for (const key of ['activeTasks', 'inProgress', 'pendingAcceptance', 'pending', 'blocked']) {
70
+ existingProjectRow[key] = (existingProjectRow[key] ?? 0) + load[key];
71
+ }
72
+ existingProjectRow.status = member.status ?? existingProjectRow.status;
73
+ existingProjectRow.sessionId = member.sessionId ?? existingProjectRow.sessionId;
74
+ existingProjectRow.memberIds = [...new Set([...(existingProjectRow.memberIds ?? [existingProjectRow.memberId].filter(Boolean)), member.id])];
75
+ entry.failures += member.lastFailure !== undefined && member.lastFailure !== null ? 1 : 0;
76
+ entry.activeTasks += load.activeTasks;
77
+ people.set(bucket, entry);
78
+ continue;
79
+ }
80
+ entry.projects.push({
81
+ projectId: runtime.id,
82
+ projectName,
83
+ status: member.status ?? 'idle',
84
+ sessionId: member.sessionId ?? null,
85
+ memberIds: [member.id],
86
+ talentPool: member.talentPool === true,
87
+ attempts: member.attempts ?? 0,
88
+ lastFailure: member.lastFailure ?? null,
89
+ activeTasks: load.activeTasks,
90
+ inProgress: load.inProgress,
91
+ pendingAcceptance: load.pendingAcceptance,
92
+ pending: load.pending,
93
+ blocked: load.blocked,
94
+ });
95
+ if (member.lastFailure !== undefined && member.lastFailure !== null) entry.failures += 1;
96
+ entry.activeTasks += load.activeTasks;
97
+ people.set(bucket, entry);
98
+ }
99
+ }
100
+ return [...people.values()].sort((left, right) => left.name.localeCompare(right.name));
101
+ }
102
+ // 语义备注:failures 计的是"当前仍带 lastFailure 的项目数"——member/recovered
103
+ // 不清 lastFailure(保留最近一次失败供展示),康复成员会继续计入;这是展示
104
+ // 口径而非存活判定(存活以 status 为准)。
@@ -0,0 +1,94 @@
1
+ /**
2
+ * 风险清单投影(R-07 / 视图组合纪律 V1):三类需要 Human 注意的风险,
3
+ * 全部从既有账本投影只读聚合,零新事件、零新数据结构——
4
+ * 1. 受阻任务:pending 且依赖未完成(isTaskBlocked);
5
+ * 2. 失败成员:agent 带未清除的 lastFailure(或 status=failed);
6
+ * 3. 待决超时:Human 收件箱中 unread 的 decision_required,超过 staleHours。
7
+ *
8
+ * 输出行复用 quadrantItem 的形状约定(kind/taskId/taskNumber/title/...),
9
+ * 前端零新交互模式即可渲染。
10
+ */
11
+
12
+ import { isTaskBlocked } from '../ledger/fold.js';
13
+
14
+ const RISK_KINDS = Object.freeze({
15
+ BLOCKED_TASK: 'blocked_task',
16
+ FAILED_MEMBER: 'failed_member',
17
+ STALE_DECISION: 'stale_decision',
18
+ });
19
+
20
+ export function riskView(state, { now = Date.now(), staleHours = 24 } = {}) {
21
+ const humanId = state.humanMemberId
22
+ ?? Object.values(state.members ?? {}).find((member) => member.kind === 'human')?.id
23
+ ?? null;
24
+ const cutoff = now - staleHours * 60 * 60 * 1000;
25
+
26
+ const blocked = [];
27
+ for (const task of Object.values(state.tasks ?? {})) {
28
+ if (task.tombstone === true) continue;
29
+ if (task.status !== 'pending') continue;
30
+ if (!isTaskBlocked(state, task)) continue;
31
+ blocked.push({
32
+ kind: RISK_KINDS.BLOCKED_TASK,
33
+ taskId: task.id,
34
+ taskNumber: task.number ?? null,
35
+ title: task.title ?? '',
36
+ ownerId: task.ownerId ?? null,
37
+ ownerName: state.members?.[task.ownerId]?.name ?? task.ownerId ?? null,
38
+ blockedBy: Array.isArray(task.blockedBy) ? [...task.blockedBy] : [],
39
+ waitingSince: task.updatedAt ?? null,
40
+ });
41
+ }
42
+
43
+ const failures = [];
44
+ for (const member of Object.values(state.members ?? {})) {
45
+ if (member.kind !== 'agent') continue;
46
+ const failure = member.lastFailure;
47
+ if (member.status !== 'failed' && (failure === undefined || failure === null)) continue;
48
+ failures.push({
49
+ kind: RISK_KINDS.FAILED_MEMBER,
50
+ memberId: member.id,
51
+ name: member.name ?? member.id,
52
+ role: member.role ?? '',
53
+ status: member.status ?? 'idle',
54
+ category: failure?.category ?? null,
55
+ attempt: failure?.attempt ?? (member.attempts ?? 0),
56
+ message: failure?.message ?? member.failure ?? null,
57
+ });
58
+ }
59
+
60
+ const staleDecisions = [];
61
+ for (const item of Object.values(state.inbox ?? {})) {
62
+ if (humanId !== null && item.memberId !== humanId) continue;
63
+ if (item.type !== 'decision_required' || item.requiresDecision !== true) continue;
64
+ if (item.state !== 'unread') continue;
65
+ const createdAt = item.createdAt ?? null;
66
+ const waitingHours = createdAt !== null && Number.isFinite(createdAt)
67
+ ? Math.max(0, Math.round((now - createdAt) / (60 * 60 * 1000)))
68
+ : null;
69
+ if (createdAt === null || now - createdAt < staleHours * 60 * 60 * 1000) continue;
70
+ staleDecisions.push({
71
+ kind: RISK_KINDS.STALE_DECISION,
72
+ itemId: item.id,
73
+ title: item.ref?.title ?? item.type ?? 'decision_required',
74
+ taskId: item.ref?.taskId ?? null,
75
+ waitingHours,
76
+ });
77
+ }
78
+ staleDecisions.sort((left, right) => (right.waitingHours ?? 0) - (left.waitingHours ?? 0));
79
+
80
+ return {
81
+ rev: state.lastSeq ?? 0,
82
+ generatedAt: now,
83
+ blocked,
84
+ failures,
85
+ staleDecisions,
86
+ counts: {
87
+ blocked: blocked.length,
88
+ failures: failures.length,
89
+ staleDecisions: staleDecisions.length,
90
+ },
91
+ };
92
+ }
93
+
94
+ export { RISK_KINDS };