返回 CodeWhale
snapshot.js
根目录 / crates / plugins / assets / agent-teams / lib / snapshot.js
1 /**
2 * Team activity snapshot assembly for the activity panel.
3 *
4 * Server-side assembly mirrors the Claude Code desktop teamWatcher: read the
5 * durable team files (the truth source) and enrich with live subagent
6 * activity, so the panel always reflects the on-disk state even when a model
7 * skipped a tool "ritual" (e.g. not calling update_task on completion).
8 * @module dsh-agent-teams/snapshot
9 */
10 import { readdir } from 'node:fs/promises';
11 import { join } from 'node:path';
12 import { memberActivity } from "./members.js";
13 import { canDeclareDelivery, describeQualityLoop, verdictAuditNotes } from "./quality-gates.js";
14 import { workspaceAuditor } from "./workspace-audit-service.js";
15 import { CAPTAIN_KEY, listArchivedTeamIds, readArchivedTeam, readUnreadMailbox, readTeam, taskDepthsById, taskVisualState, } from "./state.js";
16 /** The current task of a member: its first unfinished owned task. */
17 function currentTaskOf(memberName, tasks) {
18 for (const task of tasks) {
19 if (task.status === 'in_progress' && task.assignee === memberName)
20 return task.id;
21 }
22 return '';
23 }
24 /** Compact `provider/model` route for the activity panel, or just the model. */
25 export function memberModelRoute(member) {
26 if (member === undefined)
27 return '';
28 const provider = member.provider?.trim() ?? '';
29 const model = member.model?.trim() ?? '';
30 if (provider !== '' && model !== '')
31 return `${provider}/${model}`;
32 return model;
33 }
34 /**
35 * Assemble one team snapshot from its durable files plus live activity.
36 * @param ctx - the plugin context (injects `subagents`, used for activity).
37 * @param stateRoot - resolved absolute state root of the owning workspace.
38 * @param workspace - display name of the owning workspace.
39 * @param state - the durable team record.
40 * @returns the panel snapshot.
41 */
42 export async function assembleTeamSnapshot(ctx, stateRoot, workspace, state, options = {}) {
43 const tasks = state.tasks;
44 const includePlanText = options.summary !== true || state.phase === 'staged' || options.historic === true;
45 const depths = taskDepthsById(tasks);
46 const roster = options.includeRemoved === true
47 ? state.members
48 : state.members.filter((member) => member.status !== 'removed');
49 const activity = options.historic === true
50 ? new Map()
51 : memberActivity(ctx, roster.map((member) => member.id));
52 const unreadByMember = new Map();
53 for (const member of roster) {
54 try {
55 unreadByMember.set(member.name, (await readUnreadMailbox(stateRoot, state.id, member.name)).length);
56 }
57 catch (error) {
58 ctx.logger.warn(`agent-teams: mailbox read failed for ${member.name}: ${String(error)}`);
59 unreadByMember.set(member.name, 0);
60 }
61 }
62 const members = roster.map((member) => {
63 const owned = tasks.filter((task) => task.assignee === member.name);
64 const done = owned.filter((task) => task.status === 'completed').length;
65 return {
66 id: member.id,
67 name: member.name,
68 role: member.role ?? '',
69 provider: member.provider?.trim() ?? '',
70 model: member.model?.trim() ?? '',
71 reasoningEffort: member.reasoningEffort?.trim() ?? '',
72 ...includePlanText ? { executionPrompt: member.executionPrompt ?? '' } : {},
73 status: member.status,
74 activity: options.historic === true
75 ? 'idle'
76 : member.id !== ''
77 ? (activity.get(member.id) === 'running'
78 ? 'working'
79 : activity.get(member.id) === 'idle' || activity.get(member.id) === 'ready'
80 ? 'idle'
81 : 'unknown')
82 : 'idle',
83 progress: owned.length === 0 ? 0 : Math.round((done / owned.length) * 100),
84 done,
85 total: owned.length,
86 currentTask: currentTaskOf(member.name, tasks),
87 unread: unreadByMember.get(member.name) ?? 0,
88 };
89 });
90 const captainInbox = await readUnreadMailbox(stateRoot, state.id, CAPTAIN_KEY);
91 // The panel must reach the same delivery conclusion as the status tool, so
92 // it reads the same current bytes instead of trusting task records alone.
93 const audit = options.workspacePath === undefined ? undefined : await workspaceAuditor(ctx).audit(options.workspacePath, state, stateRoot);
94 const deliveryCheck = audit === undefined ? canDeclareDelivery(state) : canDeclareDelivery(state, audit);
95 const loop = audit === undefined ? describeQualityLoop(state) : describeQualityLoop(state, audit);
96 const staleById = new Map();
97 if (audit !== undefined) {
98 for (const note of verdictAuditNotes(state, audit)) {
99 staleById.set(note.taskId, [...staleById.get(note.taskId) ?? [], note.message]);
100 }
101 }
102 return {
103 workspace,
104 teamId: state.id,
105 name: state.name,
106 ...state.description !== undefined ? { description: state.description } : {},
107 captainSessionId: state.captainSessionId,
108 phase: state.phase ?? 'running',
109 ...state.phase === 'staged'
110 ? { planReviewState: state.planReviewState ?? 'awaiting_review' }
111 : {},
112 ...state.halted === true ? { halted: true } : {},
113 ...audit === undefined ? {} : {
114 loopState: loop.state,
115 deliverable: loop.deliverable,
116 delivery: { ok: deliveryCheck.ok, blockers: [...deliveryCheck.blockers], warnings: [...deliveryCheck.warnings] },
117 },
118 members,
119 tasks: tasks.map((task) => ({
120 id: task.id,
121 subject: task.subject,
122 ...includePlanText ? { description: task.description ?? '' } : {},
123 status: task.status,
124 state: taskVisualState(task.status, task.dependencies, tasks),
125 assignee: task.assignee ?? '',
126 model: memberModelRoute(roster.find((member) => member.name === task.assignee)),
127 dependencies: task.dependencies,
128 depth: depths.get(task.id) ?? 0,
129 ...task.kind === undefined ? {} : { kind: task.kind },
130 ...task.round === undefined ? {} : { round: task.round },
131 ...task.verdict === undefined ? {} : { verdict: task.verdict },
132 ...staleById.get(task.id) === undefined ? {} : { verdictStale: staleById.get(task.id).join('; ') },
133 updatedAt: task.updatedAt,
134 })),
135 messageCount: captainInbox.length
136 + members.reduce((count, member) => count + member.unread, 0),
137 captainInbox: captainInbox.slice(-5).map((message) => ({
138 from: message.from,
139 content: message.content,
140 })),
141 };
142 }
143 /**
144 * Collect live teams under the given workspace state roots.
145 * @param ctx - the plugin context.
146 * @param roots - `{ workspace, stateRoot }` pairs (resolved absolute roots).
147 * @param captainSessionId - when present, assemble only the requested captain's teams.
148 * @param summary - omit editor-only text from running teams.
149 * @returns the snapshots in stable order (workspace, then team id).
150 */
151 export async function collectTeamsActivity(ctx, roots, captainSessionId, summary = false) {
152 const snapshots = [];
153 for (const root of roots) {
154 let entries;
155 try {
156 entries = await readdir(root.stateRoot, { withFileTypes: true });
157 }
158 catch (error) {
159 if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
160 continue;
161 }
162 throw error;
163 }
164 for (const entry of entries) {
165 if (!entry.isDirectory())
166 continue;
167 try {
168 const state = await readTeam(root.stateRoot, entry.name);
169 if (state === undefined || (captainSessionId !== undefined && state.captainSessionId !== captainSessionId))
170 continue;
171 snapshots.push(await assembleTeamSnapshot(ctx, root.stateRoot, root.workspace, state, {
172 summary,
173 ...root.workspacePath === undefined ? {} : { workspacePath: root.workspacePath },
174 }));
175 }
176 catch {
177 ctx.logger.warn(`agent-teams: skipped unreadable team state "${entry.name}" in workspace "${root.workspace}"`);
178 }
179 }
180 }
181 return snapshots;
182 }
183 /**
184 * Collect archived teams under the given workspace state roots (the
185 * `archive/` subdirectory of each state root). Used by the historic panel
186 * path to restore full team detail after deletion.
187 * @param ctx - the plugin context.
188 * @param roots - `{ workspace, stateRoot }` pairs.
189 * @param captainSessionId - when present, assemble only the requested captain's teams.
190 * @returns the archived snapshots in stable order.
191 */
192 export async function collectArchivedTeamsActivity(ctx, roots, captainSessionId) {
193 const snapshots = [];
194 for (const root of roots) {
195 for (const teamId of await listArchivedTeamIds(root.stateRoot)) {
196 try {
197 const state = await readArchivedTeam(root.stateRoot, teamId);
198 if (state === undefined || (captainSessionId !== undefined && state.captainSessionId !== captainSessionId))
199 continue;
200 snapshots.push(await assembleTeamSnapshot(ctx, join(root.stateRoot, 'archive'), root.workspace, state, { includeRemoved: true, historic: true }));
201 }
202 catch {
203 ctx.logger.warn(`agent-teams: skipped unreadable archived team "${teamId}" in workspace "${root.workspace}"`);
204 }
205 }
206 }
207 return snapshots;
208 }
209
209 lines JAVASCRIPT