@linxiraos/pi-messenger 1.1.1 → 1.3.0

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.
Files changed (66) hide show
  1. package/CHANGELOG.md +741 -676
  2. package/LICENSE +45 -0
  3. package/README.md +424 -424
  4. package/THIRD-PARTY-NOTICES.txt +22951 -0
  5. package/config-overlay.ts +175 -171
  6. package/config.ts +221 -209
  7. package/crew/agents/crew-plan-sync.md +66 -64
  8. package/crew/agents/crew-planner.md +173 -172
  9. package/crew/agents/crew-reviewer.md +58 -58
  10. package/crew/agents/crew-worker.md +130 -129
  11. package/crew/agents.ts +507 -434
  12. package/crew/handlers/coordination.ts +350 -332
  13. package/crew/handlers/plan.ts +988 -906
  14. package/crew/handlers/review.ts +354 -333
  15. package/crew/handlers/revise.ts +400 -376
  16. package/crew/handlers/status.ts +303 -295
  17. package/crew/handlers/sync.ts +237 -233
  18. package/crew/handlers/task.ts +820 -792
  19. package/crew/handlers/team.ts +294 -235
  20. package/crew/handlers/work.ts +467 -425
  21. package/crew/id-allocator.ts +30 -30
  22. package/crew/index.ts +297 -257
  23. package/crew/live-progress.ts +58 -58
  24. package/crew/lobby.ts +504 -473
  25. package/crew/prompt.ts +262 -252
  26. package/crew/registry.ts +114 -114
  27. package/crew/spawn.ts +135 -111
  28. package/crew/state-autonomous.ts +163 -164
  29. package/crew/state-planning.ts +264 -263
  30. package/crew/state.ts +20 -20
  31. package/crew/store.ts +646 -642
  32. package/crew/task-actions.ts +162 -131
  33. package/crew/team/store.ts +572 -479
  34. package/crew/team/subagent-roles.ts +105 -87
  35. package/crew/team/types.ts +50 -50
  36. package/crew/types.ts +194 -194
  37. package/crew/utils/artifacts.ts +57 -62
  38. package/crew/utils/config.ts +158 -156
  39. package/crew/utils/discover.ts +221 -219
  40. package/crew/utils/install.ts +94 -85
  41. package/crew/utils/migrations.ts +126 -0
  42. package/crew/utils/progress.ts +191 -187
  43. package/crew/utils/result.ts +16 -16
  44. package/crew/utils/risk-labels.ts +5 -7
  45. package/crew/utils/task-format.ts +14 -14
  46. package/crew/utils/team-roles.ts +44 -28
  47. package/crew/utils/truncate.ts +76 -79
  48. package/crew/utils/verdict.ts +55 -55
  49. package/editor-binary.ts +150 -0
  50. package/editor-command.ts +107 -0
  51. package/editor-target.ts +40 -0
  52. package/feed.ts +321 -268
  53. package/handlers.ts +1041 -1107
  54. package/index.ts +1314 -1206
  55. package/install.mjs +187 -189
  56. package/lib.ts +587 -467
  57. package/overlay-actions.ts +519 -511
  58. package/overlay-coordinator.ts +150 -150
  59. package/overlay-render.ts +770 -676
  60. package/overlay.ts +872 -830
  61. package/package.json +64 -60
  62. package/paths.ts +60 -0
  63. package/skills/pi-messenger-crew/SKILL.md +375 -347
  64. package/store.ts +1147 -1139
  65. package/teamagent-command.ts +321 -0
  66. package/vitest.config.ts +10 -10
@@ -1,479 +1,572 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
- import { homedir } from "node:os";
4
- import type { Task } from "../types.ts";
5
- import { getTasks } from "../store.ts";
6
- import { discoverSubagentRoles } from "./subagent-roles.ts";
7
- import { normalizeRiskLabels } from "../utils/risk-labels.ts";
8
- import { canonicalPackagedTeamRole, isNonEditingTeamRole, isValidTeamName } from "../utils/team-roles.ts";
9
- import { TEAM_MEMORY_TYPES, type TeamMemoryEntry, type TeamMemoryType, type TeamProfile, type TeamPromptContext, type TeamRoleDefinition, type TeamState } from "./types.ts";
10
-
11
- const DEFAULT_APPROVAL_LABELS = ["security", "database", "api-contract", "destructive", "migration", "auth", "payment"];
12
- const MEMORY_FILES: Record<TeamMemoryType, string> = {
13
- decision: "decisions.md",
14
- interface: "interfaces.md",
15
- risk: "risks.md",
16
- handoff: "handoffs.md",
17
- };
18
-
19
- const BUILTIN_ROLES: Record<string, TeamRoleDefinition> = {
20
- "context-builder": { name: "context-builder", description: "Analyzes requirements and codebase, generates context and meta-prompt", thinking: "medium", skills: [] },
21
- delegate: { name: "delegate", description: "Lightweight subagent that inherits the parent model with no default reads", skills: [] },
22
- oracle: { name: "oracle", description: "High-context decision-consistency oracle that protects inherited state and prevents drift", thinking: "high", skills: [] },
23
- planner: { name: "planner", description: "Creates implementation plans from context and requirements", thinking: "high", skills: [] },
24
- researcher: { name: "researcher", description: "Autonomous web researcher — searches, evaluates, and synthesizes a focused research brief", thinking: "medium", skills: [] },
25
- reviewer: { name: "reviewer", description: "Versatile review specialist for code diffs, plans, proposed solutions, codebase health, and PR/issue validation", thinking: "high", skills: [] },
26
- scout: { name: "scout", description: "Fast codebase recon that returns compressed context for handoff", thinking: "low", skills: [] },
27
- worker: { name: "worker", description: "Implementation agent for normal tasks and approved oracle handoffs", thinking: "high", skills: [] },
28
- };
29
-
30
- const SAMPLE_PROFILES: Record<string, TeamProfile> = {
31
- "migration-squad": {
32
- name: "migration-squad",
33
- description: "Scout, implement, and review high-risk migrations with lead approval gates",
34
- roles: {
35
- scout: { description: "Map affected schemas, APIs, and rollback paths before implementation" },
36
- worker: {
37
- description: "Implement the approved migration in small, reversible steps",
38
- prompt: "Before editing, confirm the migration plan, rollback path, and affected interfaces are clear. Keep changes narrow and record risky decisions in Team memory.",
39
- },
40
- reviewer: { description: "Review migration safety, compatibility, rollback, and tests" },
41
- oracle: { description: "Resolve ambiguous migration strategy or data-safety questions" },
42
- },
43
- approval: { mode: "risk-labels", labels: ["database", "migration", "destructive", "api-contract", "auth", "payment"] },
44
- memory: { inject: ["decision", "interface", "risk", "handoff"], maxCharsPerType: 4000 },
45
- },
46
- "review-squad": {
47
- name: "review-squad",
48
- description: "Review and safely polish a change before handoff",
49
- roles: {
50
- scout: { description: "Inspect the changed surface and summarize relevant local patterns" },
51
- reviewer: { description: "Check correctness, integration risks, and missing tests" },
52
- worker: { description: "Apply approved simplification or polish edits while preserving behavior" },
53
- oracle: { description: "Resolve ambiguous review findings or tradeoffs before edits" },
54
- },
55
- approval: { mode: "risk-labels", labels: ["security", "auth", "payment", "destructive"] },
56
- memory: { inject: ["decision", "risk", "handoff"], maxCharsPerType: 3000 },
57
- },
58
- "research-squad": {
59
- name: "research-squad",
60
- description: "Research uncertain areas before planning or implementation",
61
- roles: {
62
- researcher: { description: "Gather external references and summarize tradeoffs" },
63
- scout: { description: "Map the local codebase and existing decisions" },
64
- planner: { description: "Convert research into dependency-aware Crew tasks" },
65
- reviewer: { description: "Check that the plan follows the research and project constraints" },
66
- },
67
- approval: { mode: "off" },
68
- memory: { inject: ["decision", "interface", "handoff"], maxCharsPerType: 5000 },
69
- },
70
- };
71
-
72
- function ensureDir(dir: string): void {
73
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
74
- }
75
-
76
- function readJson<T>(filePath: string): T | null {
77
- if (!fs.existsSync(filePath)) return null;
78
- try {
79
- return JSON.parse(fs.readFileSync(filePath, "utf-8")) as T;
80
- } catch (error) {
81
- throw new Error(`Failed to read Team JSON at ${filePath}`, { cause: error });
82
- }
83
- }
84
-
85
- function writeJson(filePath: string, data: unknown): void {
86
- ensureDir(path.dirname(filePath));
87
- const temp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
88
- fs.writeFileSync(temp, JSON.stringify(data, null, 2));
89
- fs.renameSync(temp, filePath);
90
- }
91
-
92
- function readText(filePath: string): string | null {
93
- if (!fs.existsSync(filePath)) return null;
94
- return fs.readFileSync(filePath, "utf-8");
95
- }
96
-
97
- function writeText(filePath: string, content: string): void {
98
- ensureDir(path.dirname(filePath));
99
- const temp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
100
- fs.writeFileSync(temp, content);
101
- fs.renameSync(temp, filePath);
102
- }
103
-
104
- export function getTeamDir(cwd: string): string {
105
- return path.join(cwd, ".pi", "messenger", "team");
106
- }
107
-
108
- export function getProfileDir(homeDir = homedir()): string {
109
- if (homeDir === homedir() && process.env.PI_MESSENGER_TEAM_PROFILE_DIR) return process.env.PI_MESSENGER_TEAM_PROFILE_DIR;
110
- return path.join(homeDir, ".pi", "agent", "messenger", "team-profiles");
111
- }
112
-
113
- function teamPath(cwd: string, file: string): string {
114
- return path.join(getTeamDir(cwd), file);
115
- }
116
-
117
- export function isValidProfileName(name: string): boolean {
118
- return isValidTeamName(name);
119
- }
120
-
121
- function profilePath(name: string, homeDir?: string): string {
122
- if (!isValidProfileName(name)) throw new Error(`Invalid team profile name: ${name}`);
123
- return path.join(getProfileDir(homeDir), `${name}.json`);
124
- }
125
-
126
- function isRecord(value: unknown): value is Record<string, unknown> {
127
- return !!value && typeof value === "object" && !Array.isArray(value);
128
- }
129
-
130
- function isTeamMemoryType(value: unknown): value is TeamMemoryType {
131
- return typeof value === "string" && TEAM_MEMORY_TYPES.includes(value as TeamMemoryType);
132
- }
133
-
134
- function normalizeProfile(raw: unknown, filePath: string, expectedName?: string): TeamProfile {
135
- if (!isRecord(raw) || typeof raw.name !== "string" || !isValidProfileName(raw.name)) {
136
- throw new Error(`Invalid Team profile JSON at ${filePath}: profile name must be filename-safe`);
137
- }
138
- if (expectedName && raw.name !== expectedName) {
139
- throw new Error(`Invalid Team profile JSON at ${filePath}: profile name must match file name`);
140
- }
141
-
142
- const profile: TeamProfile = { name: raw.name };
143
- if (typeof raw.description === "string") profile.description = raw.description;
144
-
145
- if (raw.roles !== undefined) {
146
- if (!isRecord(raw.roles)) throw new Error(`Invalid Team profile JSON at ${filePath}: roles must be an object`);
147
- const roles: Record<string, Partial<TeamRoleDefinition>> = {};
148
- for (const [name, value] of Object.entries(raw.roles)) {
149
- const roleName = canonicalPackagedTeamRole(name) ?? name;
150
- if (!isValidProfileName(name) || !isRecord(value)) {
151
- throw new Error(`Invalid Team profile JSON at ${filePath}: role ${name} must be an object with a filename-safe name`);
152
- }
153
- if (value.skills !== undefined && !Array.isArray(value.skills)) {
154
- throw new Error(`Invalid Team profile JSON at ${filePath}: role ${name}.skills must be an array`);
155
- }
156
- roles[roleName] = {
157
- ...(typeof value.description === "string" ? { description: value.description } : {}),
158
- ...(typeof value.model === "string" ? { model: value.model } : {}),
159
- ...(typeof value.thinking === "string" ? { thinking: value.thinking } : {}),
160
- ...(Array.isArray(value.skills) ? { skills: value.skills.filter((skill): skill is string => typeof skill === "string") } : {}),
161
- ...(typeof value.prompt === "string" ? { prompt: value.prompt } : {}),
162
- ...(typeof value.promptSource === "string" ? { promptSource: value.promptSource } : {}),
163
- };
164
- }
165
- profile.roles = roles;
166
- }
167
-
168
- if (raw.approval !== undefined) {
169
- if (!isRecord(raw.approval)) throw new Error(`Invalid Team profile JSON at ${filePath}: approval must be an object`);
170
- const mode = raw.approval.mode ?? "risk-labels";
171
- if (mode !== "off" && mode !== "risk-labels") throw new Error(`Invalid Team profile JSON at ${filePath}: approval.mode is invalid`);
172
- if (raw.approval.labels !== undefined && !Array.isArray(raw.approval.labels)) {
173
- throw new Error(`Invalid Team profile JSON at ${filePath}: approval.labels must be an array`);
174
- }
175
- if (Array.isArray(raw.approval.labels)) {
176
- for (const label of raw.approval.labels) {
177
- if (typeof label !== "string" || label.trim().length === 0) {
178
- throw new Error(`Invalid Team profile JSON at ${filePath}: approval.labels entries must be non-empty strings`);
179
- }
180
- }
181
- }
182
- profile.approval = {
183
- mode,
184
- ...(Array.isArray(raw.approval.labels) ? { labels: normalizeRiskLabels(raw.approval.labels) } : {}),
185
- };
186
- }
187
-
188
- if (raw.memory !== undefined) {
189
- if (!isRecord(raw.memory)) throw new Error(`Invalid Team profile JSON at ${filePath}: memory must be an object`);
190
- if (raw.memory.inject !== undefined && !Array.isArray(raw.memory.inject)) {
191
- throw new Error(`Invalid Team profile JSON at ${filePath}: memory.inject must be an array`);
192
- }
193
- if (Array.isArray(raw.memory.inject)) {
194
- for (const type of raw.memory.inject) {
195
- if (!isTeamMemoryType(type)) {
196
- throw new Error(`Invalid Team profile JSON at ${filePath}: memory.inject entries must be one of ${TEAM_MEMORY_TYPES.join(", ")}`);
197
- }
198
- }
199
- }
200
- profile.memory = {
201
- ...(Array.isArray(raw.memory.inject) ? { inject: raw.memory.inject } : {}),
202
- ...(typeof raw.memory.maxCharsPerType === "number" && Number.isFinite(raw.memory.maxCharsPerType) ? { maxCharsPerType: raw.memory.maxCharsPerType } : {}),
203
- };
204
- }
205
-
206
- return profile;
207
- }
208
-
209
- function readProfileFile(filePath: string, expectedName?: string): TeamProfile | null {
210
- const raw = readJson<unknown>(filePath);
211
- return raw === null ? null : normalizeProfile(raw, filePath, expectedName);
212
- }
213
-
214
- export function sampleTeamProfile(name: string): TeamProfile | null {
215
- const profile = SAMPLE_PROFILES[name];
216
- return profile ? structuredClone(profile) : null;
217
- }
218
-
219
- export function defaultTeamProfile(name: string): TeamProfile {
220
- if (!isValidProfileName(name)) throw new Error(`Invalid team profile name: ${name}`);
221
- return {
222
- name,
223
- description: `Team profile ${name}`,
224
- roles: {
225
- scout: {},
226
- worker: {},
227
- reviewer: {},
228
- oracle: {},
229
- },
230
- approval: { mode: "risk-labels", labels: DEFAULT_APPROVAL_LABELS },
231
- memory: { inject: ["decision", "interface", "risk"], maxCharsPerType: 4000 },
232
- };
233
- }
234
-
235
- export function getActiveTeam(cwd: string): TeamState | null {
236
- return readJson<TeamState>(teamPath(cwd, "team.json"));
237
- }
238
-
239
- export function setActiveTeam(cwd: string, name: string, profile?: string): TeamState {
240
- const now = new Date().toISOString();
241
- const existing = getActiveTeam(cwd);
242
- const state: TeamState = {
243
- name,
244
- ...(profile ? { profile } : {}),
245
- created_at: existing?.created_at ?? now,
246
- updated_at: now,
247
- };
248
- writeJson(teamPath(cwd, "team.json"), state);
249
- return state;
250
- }
251
-
252
- export function listProfiles(homeDir?: string): TeamProfile[] {
253
- const profiles = new Map<string, TeamProfile>();
254
- for (const profile of Object.values(SAMPLE_PROFILES)) profiles.set(profile.name, structuredClone(profile));
255
-
256
- const dir = getProfileDir(homeDir);
257
- if (fs.existsSync(dir)) {
258
- for (const file of fs.readdirSync(dir).filter(file => file.endsWith(".json")).sort()) {
259
- const name = path.basename(file, ".json");
260
- const profile = readProfileFile(path.join(dir, file), name);
261
- if (profile) profiles.set(profile.name, profile);
262
- }
263
- }
264
-
265
- return Array.from(profiles.values()).sort((a, b) => a.name.localeCompare(b.name));
266
- }
267
-
268
- export function loadProfile(name: string, homeDir?: string): TeamProfile | null {
269
- return readProfileFile(profilePath(name, homeDir), name) ?? sampleTeamProfile(name);
270
- }
271
-
272
- export function saveProfile(profile: TeamProfile, homeDir?: string): TeamProfile {
273
- writeJson(profilePath(profile.name, homeDir), profile);
274
- return profile;
275
- }
276
-
277
- export function useProfile(cwd: string, name: string, homeDir?: string): { team: TeamState; profile: TeamProfile; created: boolean } {
278
- if (!isValidProfileName(name)) throw new Error(`Invalid team profile name: ${name}`);
279
- let profile = readProfileFile(profilePath(name, homeDir), name);
280
- let created = false;
281
- if (!profile) {
282
- profile = sampleTeamProfile(name) ?? defaultTeamProfile(name);
283
- saveProfile(profile, homeDir);
284
- created = true;
285
- }
286
- const team = setActiveTeam(cwd, profile.name, profile.name);
287
- return { team, profile, created };
288
- }
289
-
290
- export function loadActiveProfile(cwd: string, homeDir?: string): TeamProfile | null {
291
- const team = getActiveTeam(cwd);
292
- if (!team?.profile) return null;
293
- return loadProfile(team.profile, homeDir);
294
- }
295
-
296
- export function readCharter(cwd: string): string | null {
297
- return readText(teamPath(cwd, "charter.md"));
298
- }
299
-
300
- export function writeCharter(cwd: string, teamName: string, message: string): string {
301
- const content = `# ${teamName} Charter\n\n${message.trim()}\n`;
302
- writeText(teamPath(cwd, "charter.md"), content);
303
- const active = getActiveTeam(cwd);
304
- setActiveTeam(cwd, teamName, active?.profile);
305
- return content;
306
- }
307
-
308
- export function updateCharter(cwd: string, message: string): string {
309
- const existing = readCharter(cwd);
310
- const team = getActiveTeam(cwd);
311
- const content = existing
312
- ? `${existing.trimEnd()}\n\n## Update ${new Date().toISOString()}\n\n${message.trim()}\n`
313
- : `# ${team?.name ?? "Team"} Charter\n\n${message.trim()}\n`;
314
- writeText(teamPath(cwd, "charter.md"), content);
315
- if (team) setActiveTeam(cwd, team.name, team.profile);
316
- return content;
317
- }
318
-
319
- function parseMemoryEntry(raw: unknown): TeamMemoryEntry | null {
320
- if (!isRecord(raw)) return null;
321
- if (typeof raw.ts !== "string") return null;
322
- if (typeof raw.agent !== "string") return null;
323
- if (typeof raw.message !== "string") return null;
324
- if (!isTeamMemoryType(raw.type)) return null;
325
- if (raw.taskId !== undefined && typeof raw.taskId !== "string") return null;
326
- const taskId = typeof raw.taskId === "string" ? raw.taskId : undefined;
327
- return {
328
- ts: raw.ts,
329
- agent: raw.agent,
330
- type: raw.type,
331
- message: raw.message,
332
- ...(taskId ? { taskId } : {}),
333
- };
334
- }
335
-
336
- export function noteMemory(cwd: string, type: TeamMemoryType, message: string, agent: string, taskId?: string): TeamMemoryEntry {
337
- const entry: TeamMemoryEntry = {
338
- ts: new Date().toISOString(),
339
- agent,
340
- type,
341
- message,
342
- ...(taskId ? { taskId } : {}),
343
- };
344
- ensureDir(getTeamDir(cwd));
345
- fs.appendFileSync(teamPath(cwd, "memory.jsonl"), `${JSON.stringify(entry)}\n`);
346
- fs.appendFileSync(teamPath(cwd, MEMORY_FILES[type]), `- ${entry.ts} (${agent}${taskId ? `, ${taskId}` : ""}): ${message}\n`);
347
- return entry;
348
- }
349
-
350
- export function listMemory(cwd: string, type?: TeamMemoryType, limit?: number): TeamMemoryEntry[] {
351
- const file = teamPath(cwd, "memory.jsonl");
352
- if (!fs.existsSync(file)) return [];
353
- const entries: TeamMemoryEntry[] = [];
354
- for (const line of fs.readFileSync(file, "utf-8").split("\n")) {
355
- if (!line.trim()) continue;
356
- try {
357
- const parsed = parseMemoryEntry(JSON.parse(line));
358
- if (parsed && (!type || parsed.type === type)) entries.push(parsed);
359
- } catch {
360
- // Keep valid memory usable even if a hand-edited JSONL line is malformed.
361
- }
362
- }
363
- return typeof limit === "number" && limit > 0 ? entries.slice(-limit) : entries;
364
- }
365
-
366
- export function memoryCounts(cwd: string): Record<TeamMemoryType, number> {
367
- const counts = Object.fromEntries(TEAM_MEMORY_TYPES.map(type => [type, 0])) as Record<TeamMemoryType, number>;
368
- for (const entry of listMemory(cwd)) counts[entry.type]++;
369
- return counts;
370
- }
371
-
372
- export function resolveRoles(cwd: string, options?: { homeDir?: string }): Record<string, TeamRoleDefinition> {
373
- const roles: Record<string, TeamRoleDefinition> = {};
374
- for (const [name, role] of Object.entries(BUILTIN_ROLES)) roles[name] = { ...role };
375
-
376
- const discovered = discoverSubagentRoles(cwd, { homeDir: options?.homeDir });
377
- for (const [name, role] of Object.entries(discovered)) {
378
- roles[name] = { ...(roles[name] ?? { name }), ...role, name };
379
- }
380
-
381
- const profile = loadActiveProfile(cwd, options?.homeDir);
382
- for (const [name, role] of Object.entries(profile?.roles ?? {})) {
383
- roles[name] = { ...(roles[name] ?? { name }), ...role, name };
384
- }
385
-
386
- return roles;
387
- }
388
-
389
- export { normalizeRiskLabels };
390
-
391
- export function resolveRoleName(cwd: string, role: string | undefined): string | undefined {
392
- const trimmed = role?.trim();
393
- if (!trimmed) return undefined;
394
-
395
- const roles = resolveRoles(cwd);
396
- const packaged = canonicalPackagedTeamRole(trimmed);
397
- if (packaged && roles[packaged]) return packaged;
398
- if (roles[trimmed]) return trimmed;
399
-
400
- const lower = trimmed.toLowerCase();
401
- return Object.keys(roles).find(name => name.toLowerCase() === lower);
402
- }
403
-
404
- export function canonicalRoleForTask(cwd: string, role: string | undefined): string | undefined {
405
- const trimmed = role?.trim();
406
- if (!trimmed) return undefined;
407
- return resolveRoleName(cwd, trimmed) ?? (getActiveTeam(cwd) ? undefined : trimmed);
408
- }
409
-
410
- export function isNonEditingRole(cwd: string, role: string | undefined): boolean {
411
- return isNonEditingTeamRole(resolveRoleName(cwd, role) ?? role);
412
- }
413
-
414
- export function activeApprovalLabels(cwd: string): string[] {
415
- const profile = loadActiveProfile(cwd);
416
- if (!getActiveTeam(cwd)) return [];
417
- if (profile?.approval?.mode === "off") return [];
418
- return normalizeRiskLabels(profile?.approval?.labels ?? DEFAULT_APPROVAL_LABELS) ?? [];
419
- }
420
-
421
- export function approvalForTask(cwd: string, role: string | undefined, riskLabels: string[] | undefined): Task["approval"] | undefined {
422
- const labels = activeApprovalLabels(cwd);
423
- const taskLabels = normalizeRiskLabels(riskLabels);
424
- if (labels.length === 0 || !taskLabels || taskLabels.length === 0) return undefined;
425
- if (isNonEditingRole(cwd, role)) return undefined;
426
- const configured = new Set(labels);
427
- const matching = taskLabels.filter(label => configured.has(label));
428
- if (matching.length === 0) return undefined;
429
- return { required: true, status: "pending" };
430
- }
431
-
432
- export function taskNeedsApproval(task: Task): boolean {
433
- return task.approval?.required === true && task.approval.status !== "approved";
434
- }
435
-
436
- export function taskPendingApproval(task: Task): boolean {
437
- return task.approval?.required === true && task.approval.status === "pending";
438
- }
439
-
440
- export function taskNeedsRevision(task: Task): boolean {
441
- return task.approval?.required === true && task.approval.status === "rejected";
442
- }
443
-
444
- export function needsLeadTasks(cwd: string): Task[] {
445
- return getTasks(cwd).filter(taskPendingApproval);
446
- }
447
-
448
- export function rejectedTasks(cwd: string): Task[] {
449
- return getTasks(cwd).filter(taskNeedsRevision);
450
- }
451
-
452
- export function buildTeamPromptContext(cwd: string, task: Task): TeamPromptContext | undefined {
453
- const team = getActiveTeam(cwd);
454
- if (!team) return undefined;
455
-
456
- const profile = loadActiveProfile(cwd) ?? undefined;
457
- const roles = resolveRoles(cwd);
458
- const roleName = resolveRoleName(cwd, task.role);
459
- const role = roleName ? roles[roleName] : undefined;
460
- const charter = readCharter(cwd) ?? undefined;
461
- const inject = profile?.memory?.inject ?? ["decision", "interface", "risk"];
462
- const maxChars = profile?.memory?.maxCharsPerType ?? 4000;
463
- const memory: TeamPromptContext["memory"] = {};
464
-
465
- for (const type of inject) {
466
- const recent = listMemory(cwd, type, 20);
467
- const selected: TeamMemoryEntry[] = [];
468
- let used = 0;
469
- for (const entry of recent.reverse()) {
470
- const cost = entry.message.length + 80;
471
- if (selected.length > 0 && used + cost > maxChars) break;
472
- selected.unshift(entry);
473
- used += cost;
474
- }
475
- if (selected.length > 0) memory[type] = selected;
476
- }
477
-
478
- return { team, profile, role, charter, memory };
479
- }
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { homedir } from "node:os";
4
+ import type { Task } from "../types.ts";
5
+ import { getTasks } from "../store.ts";
6
+ import { discoverSubagentRoles } from "./subagent-roles.ts";
7
+ import { normalizeRiskLabels } from "../utils/risk-labels.ts";
8
+ import { canonicalPackagedTeamRole, isNonEditingTeamRole, isValidTeamName } from "../utils/team-roles.ts";
9
+ import { getAgentDir } from "@linxiraos/pi-utils/dirs";
10
+ import { getProjectMessengerDir } from "../../paths.ts";
11
+ import { ensureProjectStateMigrated } from "../utils/migrations.ts";
12
+ import {
13
+ TEAM_MEMORY_TYPES,
14
+ type TeamMemoryEntry,
15
+ type TeamMemoryType,
16
+ type TeamProfile,
17
+ type TeamPromptContext,
18
+ type TeamRoleDefinition,
19
+ type TeamState,
20
+ } from "./types.ts";
21
+
22
+ const DEFAULT_APPROVAL_LABELS = ["security", "database", "api-contract", "destructive", "migration", "auth", "payment"];
23
+ const MEMORY_FILES: Record<TeamMemoryType, string> = {
24
+ decision: "decisions.md",
25
+ interface: "interfaces.md",
26
+ risk: "risks.md",
27
+ handoff: "handoffs.md",
28
+ };
29
+
30
+ const BUILTIN_ROLES: Record<string, TeamRoleDefinition> = {
31
+ "context-builder": {
32
+ name: "context-builder",
33
+ description: "Analyzes requirements and codebase, generates context and meta-prompt",
34
+ thinking: "medium",
35
+ skills: [],
36
+ },
37
+ delegate: {
38
+ name: "delegate",
39
+ description: "Lightweight subagent that inherits the parent model with no default reads",
40
+ skills: [],
41
+ },
42
+ oracle: {
43
+ name: "oracle",
44
+ description: "High-context decision-consistency oracle that protects inherited state and prevents drift",
45
+ thinking: "high",
46
+ skills: [],
47
+ },
48
+ planner: {
49
+ name: "planner",
50
+ description: "Creates implementation plans from context and requirements",
51
+ thinking: "high",
52
+ skills: [],
53
+ },
54
+ researcher: {
55
+ name: "researcher",
56
+ description: "Autonomous web researcher — searches, evaluates, and synthesizes a focused research brief",
57
+ thinking: "medium",
58
+ skills: [],
59
+ },
60
+ reviewer: {
61
+ name: "reviewer",
62
+ description:
63
+ "Versatile review specialist for code diffs, plans, proposed solutions, codebase health, and PR/issue validation",
64
+ thinking: "high",
65
+ skills: [],
66
+ },
67
+ scout: {
68
+ name: "scout",
69
+ description: "Fast codebase recon that returns compressed context for handoff",
70
+ thinking: "low",
71
+ skills: [],
72
+ },
73
+ worker: {
74
+ name: "worker",
75
+ description: "Implementation agent for normal tasks and approved oracle handoffs",
76
+ thinking: "high",
77
+ skills: [],
78
+ },
79
+ };
80
+
81
+ const SAMPLE_PROFILES: Record<string, TeamProfile> = {
82
+ "migration-squad": {
83
+ name: "migration-squad",
84
+ description: "Scout, implement, and review high-risk migrations with lead approval gates",
85
+ roles: {
86
+ scout: { description: "Map affected schemas, APIs, and rollback paths before implementation" },
87
+ worker: {
88
+ description: "Implement the approved migration in small, reversible steps",
89
+ prompt:
90
+ "Before editing, confirm the migration plan, rollback path, and affected interfaces are clear. Keep changes narrow and record risky decisions in Team memory.",
91
+ },
92
+ reviewer: { description: "Review migration safety, compatibility, rollback, and tests" },
93
+ oracle: { description: "Resolve ambiguous migration strategy or data-safety questions" },
94
+ },
95
+ approval: {
96
+ mode: "risk-labels",
97
+ labels: ["database", "migration", "destructive", "api-contract", "auth", "payment"],
98
+ },
99
+ memory: { inject: ["decision", "interface", "risk", "handoff"], maxCharsPerType: 4000 },
100
+ },
101
+ "review-squad": {
102
+ name: "review-squad",
103
+ description: "Review and safely polish a change before handoff",
104
+ roles: {
105
+ scout: { description: "Inspect the changed surface and summarize relevant local patterns" },
106
+ reviewer: { description: "Check correctness, integration risks, and missing tests" },
107
+ worker: { description: "Apply approved simplification or polish edits while preserving behavior" },
108
+ oracle: { description: "Resolve ambiguous review findings or tradeoffs before edits" },
109
+ },
110
+ approval: { mode: "risk-labels", labels: ["security", "auth", "payment", "destructive"] },
111
+ memory: { inject: ["decision", "risk", "handoff"], maxCharsPerType: 3000 },
112
+ },
113
+ "research-squad": {
114
+ name: "research-squad",
115
+ description: "Research uncertain areas before planning or implementation",
116
+ roles: {
117
+ researcher: { description: "Gather external references and summarize tradeoffs" },
118
+ scout: { description: "Map the local codebase and existing decisions" },
119
+ planner: { description: "Convert research into dependency-aware Crew tasks" },
120
+ reviewer: { description: "Check that the plan follows the research and project constraints" },
121
+ },
122
+ approval: { mode: "off" },
123
+ memory: { inject: ["decision", "interface", "handoff"], maxCharsPerType: 5000 },
124
+ },
125
+ };
126
+
127
+ function ensureDir(dir: string): void {
128
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
129
+ }
130
+
131
+ function readJson<T>(filePath: string): T | null {
132
+ if (!fs.existsSync(filePath)) return null;
133
+ try {
134
+ return JSON.parse(fs.readFileSync(filePath, "utf-8")) as T;
135
+ } catch (error) {
136
+ throw new Error(`Failed to read Team JSON at ${filePath}`, { cause: error });
137
+ }
138
+ }
139
+
140
+ function writeJson(filePath: string, data: unknown): void {
141
+ ensureDir(path.dirname(filePath));
142
+ const temp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
143
+ fs.writeFileSync(temp, JSON.stringify(data, null, 2));
144
+ fs.renameSync(temp, filePath);
145
+ }
146
+
147
+ function readText(filePath: string): string | null {
148
+ if (!fs.existsSync(filePath)) return null;
149
+ return fs.readFileSync(filePath, "utf-8");
150
+ }
151
+
152
+ function writeText(filePath: string, content: string): void {
153
+ ensureDir(path.dirname(filePath));
154
+ const temp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
155
+ fs.writeFileSync(temp, content);
156
+ fs.renameSync(temp, filePath);
157
+ }
158
+
159
+ export function getTeamDir(cwd: string): string {
160
+ ensureProjectStateMigrated(cwd);
161
+ return path.join(getProjectMessengerDir(cwd), "team");
162
+ }
163
+
164
+ export function getProfileDir(homeDir = homedir()): string {
165
+ if (homeDir === homedir() && process.env.PI_MESSENGER_TEAM_PROFILE_DIR)
166
+ return process.env.PI_MESSENGER_TEAM_PROFILE_DIR;
167
+ if (homeDir !== homedir()) {
168
+ // Test isolation: mirror the default layout under the given root.
169
+ return path.join(homeDir, ".zeta", "agent", "messenger", "team-profiles");
170
+ }
171
+ return path.join(getAgentDir(), "messenger", "team-profiles");
172
+ }
173
+
174
+ function teamPath(cwd: string, file: string): string {
175
+ return path.join(getTeamDir(cwd), file);
176
+ }
177
+
178
+ export function isValidProfileName(name: string): boolean {
179
+ return isValidTeamName(name);
180
+ }
181
+
182
+ function profilePath(name: string, homeDir?: string): string {
183
+ if (!isValidProfileName(name)) throw new Error(`Invalid team profile name: ${name}`);
184
+ return path.join(getProfileDir(homeDir), `${name}.json`);
185
+ }
186
+
187
+ function isRecord(value: unknown): value is Record<string, unknown> {
188
+ return !!value && typeof value === "object" && !Array.isArray(value);
189
+ }
190
+
191
+ function isTeamMemoryType(value: unknown): value is TeamMemoryType {
192
+ return typeof value === "string" && TEAM_MEMORY_TYPES.includes(value as TeamMemoryType);
193
+ }
194
+
195
+ function normalizeProfile(raw: unknown, filePath: string, expectedName?: string): TeamProfile {
196
+ if (!isRecord(raw) || typeof raw.name !== "string" || !isValidProfileName(raw.name)) {
197
+ throw new Error(`Invalid Team profile JSON at ${filePath}: profile name must be filename-safe`);
198
+ }
199
+ if (expectedName && raw.name !== expectedName) {
200
+ throw new Error(`Invalid Team profile JSON at ${filePath}: profile name must match file name`);
201
+ }
202
+
203
+ const profile: TeamProfile = { name: raw.name };
204
+ if (typeof raw.description === "string") profile.description = raw.description;
205
+
206
+ if (raw.roles !== undefined) {
207
+ if (!isRecord(raw.roles)) throw new Error(`Invalid Team profile JSON at ${filePath}: roles must be an object`);
208
+ const roles: Record<string, Partial<TeamRoleDefinition>> = {};
209
+ for (const [name, value] of Object.entries(raw.roles)) {
210
+ const roleName = canonicalPackagedTeamRole(name) ?? name;
211
+ if (!isValidProfileName(name) || !isRecord(value)) {
212
+ throw new Error(
213
+ `Invalid Team profile JSON at ${filePath}: role ${name} must be an object with a filename-safe name`,
214
+ );
215
+ }
216
+ if (value.skills !== undefined && !Array.isArray(value.skills)) {
217
+ throw new Error(`Invalid Team profile JSON at ${filePath}: role ${name}.skills must be an array`);
218
+ }
219
+ roles[roleName] = {
220
+ ...(typeof value.description === "string" ? { description: value.description } : {}),
221
+ ...(typeof value.model === "string" ? { model: value.model } : {}),
222
+ ...(typeof value.thinking === "string" ? { thinking: value.thinking } : {}),
223
+ ...(Array.isArray(value.skills)
224
+ ? { skills: value.skills.filter((skill): skill is string => typeof skill === "string") }
225
+ : {}),
226
+ ...(typeof value.prompt === "string" ? { prompt: value.prompt } : {}),
227
+ ...(typeof value.promptSource === "string" ? { promptSource: value.promptSource } : {}),
228
+ };
229
+ }
230
+ profile.roles = roles;
231
+ }
232
+
233
+ if (raw.approval !== undefined) {
234
+ if (!isRecord(raw.approval))
235
+ throw new Error(`Invalid Team profile JSON at ${filePath}: approval must be an object`);
236
+ const mode = raw.approval.mode ?? "risk-labels";
237
+ if (mode !== "off" && mode !== "risk-labels")
238
+ throw new Error(`Invalid Team profile JSON at ${filePath}: approval.mode is invalid`);
239
+ if (raw.approval.labels !== undefined && !Array.isArray(raw.approval.labels)) {
240
+ throw new Error(`Invalid Team profile JSON at ${filePath}: approval.labels must be an array`);
241
+ }
242
+ if (Array.isArray(raw.approval.labels)) {
243
+ for (const label of raw.approval.labels) {
244
+ if (typeof label !== "string" || label.trim().length === 0) {
245
+ throw new Error(
246
+ `Invalid Team profile JSON at ${filePath}: approval.labels entries must be non-empty strings`,
247
+ );
248
+ }
249
+ }
250
+ }
251
+ profile.approval = {
252
+ mode,
253
+ ...(Array.isArray(raw.approval.labels) ? { labels: normalizeRiskLabels(raw.approval.labels) } : {}),
254
+ };
255
+ }
256
+
257
+ if (raw.memory !== undefined) {
258
+ if (!isRecord(raw.memory)) throw new Error(`Invalid Team profile JSON at ${filePath}: memory must be an object`);
259
+ if (raw.memory.inject !== undefined && !Array.isArray(raw.memory.inject)) {
260
+ throw new Error(`Invalid Team profile JSON at ${filePath}: memory.inject must be an array`);
261
+ }
262
+ if (Array.isArray(raw.memory.inject)) {
263
+ for (const type of raw.memory.inject) {
264
+ if (!isTeamMemoryType(type)) {
265
+ throw new Error(
266
+ `Invalid Team profile JSON at ${filePath}: memory.inject entries must be one of ${TEAM_MEMORY_TYPES.join(", ")}`,
267
+ );
268
+ }
269
+ }
270
+ }
271
+ profile.memory = {
272
+ ...(Array.isArray(raw.memory.inject) ? { inject: raw.memory.inject } : {}),
273
+ ...(typeof raw.memory.maxCharsPerType === "number" && Number.isFinite(raw.memory.maxCharsPerType)
274
+ ? { maxCharsPerType: raw.memory.maxCharsPerType }
275
+ : {}),
276
+ };
277
+ }
278
+
279
+ return profile;
280
+ }
281
+
282
+ function readProfileFile(filePath: string, expectedName?: string): TeamProfile | null {
283
+ const raw = readJson<unknown>(filePath);
284
+ return raw === null ? null : normalizeProfile(raw, filePath, expectedName);
285
+ }
286
+
287
+ export function sampleTeamProfile(name: string): TeamProfile | null {
288
+ const profile = SAMPLE_PROFILES[name];
289
+ return profile ? structuredClone(profile) : null;
290
+ }
291
+
292
+ export function defaultTeamProfile(name: string): TeamProfile {
293
+ if (!isValidProfileName(name)) throw new Error(`Invalid team profile name: ${name}`);
294
+ return {
295
+ name,
296
+ description: `Team profile ${name}`,
297
+ roles: {
298
+ scout: {},
299
+ worker: {},
300
+ reviewer: {},
301
+ oracle: {},
302
+ },
303
+ approval: { mode: "risk-labels", labels: DEFAULT_APPROVAL_LABELS },
304
+ memory: { inject: ["decision", "interface", "risk"], maxCharsPerType: 4000 },
305
+ };
306
+ }
307
+
308
+ export function getActiveTeam(cwd: string): TeamState | null {
309
+ return readJson<TeamState>(teamPath(cwd, "team.json"));
310
+ }
311
+
312
+ export function setActiveTeam(cwd: string, name: string, profile?: string): TeamState {
313
+ const now = new Date().toISOString();
314
+ const existing = getActiveTeam(cwd);
315
+ const state: TeamState = {
316
+ name,
317
+ ...(profile ? { profile } : {}),
318
+ created_at: existing?.created_at ?? now,
319
+ updated_at: now,
320
+ };
321
+ writeJson(teamPath(cwd, "team.json"), state);
322
+ return state;
323
+ }
324
+
325
+ export function listProfiles(homeDir?: string): TeamProfile[] {
326
+ const profiles = new Map<string, TeamProfile>();
327
+ for (const profile of Object.values(SAMPLE_PROFILES)) profiles.set(profile.name, structuredClone(profile));
328
+
329
+ const dir = getProfileDir(homeDir);
330
+ if (fs.existsSync(dir)) {
331
+ for (const file of fs
332
+ .readdirSync(dir)
333
+ .filter(file => file.endsWith(".json"))
334
+ .sort()) {
335
+ const name = path.basename(file, ".json");
336
+ const profile = readProfileFile(path.join(dir, file), name);
337
+ if (profile) profiles.set(profile.name, profile);
338
+ }
339
+ }
340
+
341
+ return Array.from(profiles.values()).sort((a, b) => a.name.localeCompare(b.name));
342
+ }
343
+
344
+ export function loadProfile(name: string, homeDir?: string): TeamProfile | null {
345
+ return readProfileFile(profilePath(name, homeDir), name) ?? sampleTeamProfile(name);
346
+ }
347
+
348
+ export function saveProfile(profile: TeamProfile, homeDir?: string): TeamProfile {
349
+ writeJson(profilePath(profile.name, homeDir), profile);
350
+ return profile;
351
+ }
352
+
353
+ export function useProfile(
354
+ cwd: string,
355
+ name: string,
356
+ homeDir?: string,
357
+ ): { team: TeamState; profile: TeamProfile; created: boolean } {
358
+ if (!isValidProfileName(name)) throw new Error(`Invalid team profile name: ${name}`);
359
+ let profile = readProfileFile(profilePath(name, homeDir), name);
360
+ let created = false;
361
+ if (!profile) {
362
+ profile = sampleTeamProfile(name) ?? defaultTeamProfile(name);
363
+ saveProfile(profile, homeDir);
364
+ created = true;
365
+ }
366
+ const team = setActiveTeam(cwd, profile.name, profile.name);
367
+ return { team, profile, created };
368
+ }
369
+
370
+ export function loadActiveProfile(cwd: string, homeDir?: string): TeamProfile | null {
371
+ const team = getActiveTeam(cwd);
372
+ if (!team?.profile) return null;
373
+ return loadProfile(team.profile, homeDir);
374
+ }
375
+
376
+ export function readCharter(cwd: string): string | null {
377
+ return readText(teamPath(cwd, "charter.md"));
378
+ }
379
+
380
+ export function writeCharter(cwd: string, teamName: string, message: string): string {
381
+ const content = `# ${teamName} Charter\n\n${message.trim()}\n`;
382
+ writeText(teamPath(cwd, "charter.md"), content);
383
+ const active = getActiveTeam(cwd);
384
+ setActiveTeam(cwd, teamName, active?.profile);
385
+ return content;
386
+ }
387
+
388
+ export function updateCharter(cwd: string, message: string): string {
389
+ const existing = readCharter(cwd);
390
+ const team = getActiveTeam(cwd);
391
+ const content = existing
392
+ ? `${existing.trimEnd()}\n\n## Update ${new Date().toISOString()}\n\n${message.trim()}\n`
393
+ : `# ${team?.name ?? "Team"} Charter\n\n${message.trim()}\n`;
394
+ writeText(teamPath(cwd, "charter.md"), content);
395
+ if (team) setActiveTeam(cwd, team.name, team.profile);
396
+ return content;
397
+ }
398
+
399
+ function parseMemoryEntry(raw: unknown): TeamMemoryEntry | null {
400
+ if (!isRecord(raw)) return null;
401
+ if (typeof raw.ts !== "string") return null;
402
+ if (typeof raw.agent !== "string") return null;
403
+ if (typeof raw.message !== "string") return null;
404
+ if (!isTeamMemoryType(raw.type)) return null;
405
+ if (raw.taskId !== undefined && typeof raw.taskId !== "string") return null;
406
+ const taskId = typeof raw.taskId === "string" ? raw.taskId : undefined;
407
+ return {
408
+ ts: raw.ts,
409
+ agent: raw.agent,
410
+ type: raw.type,
411
+ message: raw.message,
412
+ ...(taskId ? { taskId } : {}),
413
+ };
414
+ }
415
+
416
+ export function noteMemory(
417
+ cwd: string,
418
+ type: TeamMemoryType,
419
+ message: string,
420
+ agent: string,
421
+ taskId?: string,
422
+ ): TeamMemoryEntry {
423
+ const entry: TeamMemoryEntry = {
424
+ ts: new Date().toISOString(),
425
+ agent,
426
+ type,
427
+ message,
428
+ ...(taskId ? { taskId } : {}),
429
+ };
430
+ ensureDir(getTeamDir(cwd));
431
+ fs.appendFileSync(teamPath(cwd, "memory.jsonl"), `${JSON.stringify(entry)}\n`);
432
+ fs.appendFileSync(
433
+ teamPath(cwd, MEMORY_FILES[type]),
434
+ `- ${entry.ts} (${agent}${taskId ? `, ${taskId}` : ""}): ${message}\n`,
435
+ );
436
+ return entry;
437
+ }
438
+
439
+ export function listMemory(cwd: string, type?: TeamMemoryType, limit?: number): TeamMemoryEntry[] {
440
+ const file = teamPath(cwd, "memory.jsonl");
441
+ if (!fs.existsSync(file)) return [];
442
+ const entries: TeamMemoryEntry[] = [];
443
+ for (const line of fs.readFileSync(file, "utf-8").split("\n")) {
444
+ if (!line.trim()) continue;
445
+ try {
446
+ const parsed = parseMemoryEntry(JSON.parse(line));
447
+ if (parsed && (!type || parsed.type === type)) entries.push(parsed);
448
+ } catch {
449
+ // Keep valid memory usable even if a hand-edited JSONL line is malformed.
450
+ }
451
+ }
452
+ return typeof limit === "number" && limit > 0 ? entries.slice(-limit) : entries;
453
+ }
454
+
455
+ export function memoryCounts(cwd: string): Record<TeamMemoryType, number> {
456
+ const counts = Object.fromEntries(TEAM_MEMORY_TYPES.map(type => [type, 0])) as Record<TeamMemoryType, number>;
457
+ for (const entry of listMemory(cwd)) counts[entry.type]++;
458
+ return counts;
459
+ }
460
+
461
+ export function resolveRoles(cwd: string, options?: { homeDir?: string }): Record<string, TeamRoleDefinition> {
462
+ const roles: Record<string, TeamRoleDefinition> = {};
463
+ for (const [name, role] of Object.entries(BUILTIN_ROLES)) roles[name] = { ...role };
464
+
465
+ const discovered = discoverSubagentRoles(cwd, { homeDir: options?.homeDir });
466
+ for (const [name, role] of Object.entries(discovered)) {
467
+ roles[name] = { ...(roles[name] ?? { name }), ...role, name };
468
+ }
469
+
470
+ const profile = loadActiveProfile(cwd, options?.homeDir);
471
+ for (const [name, role] of Object.entries(profile?.roles ?? {})) {
472
+ roles[name] = { ...(roles[name] ?? { name }), ...role, name };
473
+ }
474
+
475
+ return roles;
476
+ }
477
+
478
+ export { normalizeRiskLabels };
479
+
480
+ export function resolveRoleName(cwd: string, role: string | undefined): string | undefined {
481
+ const trimmed = role?.trim();
482
+ if (!trimmed) return undefined;
483
+
484
+ const roles = resolveRoles(cwd);
485
+ const packaged = canonicalPackagedTeamRole(trimmed);
486
+ if (packaged && roles[packaged]) return packaged;
487
+ if (roles[trimmed]) return trimmed;
488
+
489
+ const lower = trimmed.toLowerCase();
490
+ return Object.keys(roles).find(name => name.toLowerCase() === lower);
491
+ }
492
+
493
+ export function canonicalRoleForTask(cwd: string, role: string | undefined): string | undefined {
494
+ const trimmed = role?.trim();
495
+ if (!trimmed) return undefined;
496
+ return resolveRoleName(cwd, trimmed) ?? (getActiveTeam(cwd) ? undefined : trimmed);
497
+ }
498
+
499
+ export function isNonEditingRole(cwd: string, role: string | undefined): boolean {
500
+ return isNonEditingTeamRole(resolveRoleName(cwd, role) ?? role);
501
+ }
502
+
503
+ export function activeApprovalLabels(cwd: string): string[] {
504
+ const profile = loadActiveProfile(cwd);
505
+ if (!getActiveTeam(cwd)) return [];
506
+ if (profile?.approval?.mode === "off") return [];
507
+ return normalizeRiskLabels(profile?.approval?.labels ?? DEFAULT_APPROVAL_LABELS) ?? [];
508
+ }
509
+
510
+ export function approvalForTask(
511
+ cwd: string,
512
+ role: string | undefined,
513
+ riskLabels: string[] | undefined,
514
+ ): Task["approval"] | undefined {
515
+ const labels = activeApprovalLabels(cwd);
516
+ const taskLabels = normalizeRiskLabels(riskLabels);
517
+ if (labels.length === 0 || !taskLabels || taskLabels.length === 0) return undefined;
518
+ if (isNonEditingRole(cwd, role)) return undefined;
519
+ const configured = new Set(labels);
520
+ const matching = taskLabels.filter(label => configured.has(label));
521
+ if (matching.length === 0) return undefined;
522
+ return { required: true, status: "pending" };
523
+ }
524
+
525
+ export function taskNeedsApproval(task: Task): boolean {
526
+ return task.approval?.required === true && task.approval.status !== "approved";
527
+ }
528
+
529
+ export function taskPendingApproval(task: Task): boolean {
530
+ return task.approval?.required === true && task.approval.status === "pending";
531
+ }
532
+
533
+ export function taskNeedsRevision(task: Task): boolean {
534
+ return task.approval?.required === true && task.approval.status === "rejected";
535
+ }
536
+
537
+ export function needsLeadTasks(cwd: string): Task[] {
538
+ return getTasks(cwd).filter(taskPendingApproval);
539
+ }
540
+
541
+ export function rejectedTasks(cwd: string): Task[] {
542
+ return getTasks(cwd).filter(taskNeedsRevision);
543
+ }
544
+
545
+ export function buildTeamPromptContext(cwd: string, task: Task): TeamPromptContext | undefined {
546
+ const team = getActiveTeam(cwd);
547
+ if (!team) return undefined;
548
+
549
+ const profile = loadActiveProfile(cwd) ?? undefined;
550
+ const roles = resolveRoles(cwd);
551
+ const roleName = resolveRoleName(cwd, task.role);
552
+ const role = roleName ? roles[roleName] : undefined;
553
+ const charter = readCharter(cwd) ?? undefined;
554
+ const inject = profile?.memory?.inject ?? ["decision", "interface", "risk"];
555
+ const maxChars = profile?.memory?.maxCharsPerType ?? 4000;
556
+ const memory: TeamPromptContext["memory"] = {};
557
+
558
+ for (const type of inject) {
559
+ const recent = listMemory(cwd, type, 20);
560
+ const selected: TeamMemoryEntry[] = [];
561
+ let used = 0;
562
+ for (const entry of recent.reverse()) {
563
+ const cost = entry.message.length + 80;
564
+ if (selected.length > 0 && used + cost > maxChars) break;
565
+ selected.unshift(entry);
566
+ used += cost;
567
+ }
568
+ if (selected.length > 0) memory[type] = selected;
569
+ }
570
+
571
+ return { team, profile, role, charter, memory };
572
+ }