@linxiraos/pi-messenger 1.1.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 (58) hide show
  1. package/CHANGELOG.md +676 -0
  2. package/README.md +424 -0
  3. package/config-overlay.ts +171 -0
  4. package/config.ts +209 -0
  5. package/crew/agents/crew-plan-sync.md +64 -0
  6. package/crew/agents/crew-planner.md +172 -0
  7. package/crew/agents/crew-reviewer.md +58 -0
  8. package/crew/agents/crew-worker.md +129 -0
  9. package/crew/agents.ts +434 -0
  10. package/crew/handlers/coordination.ts +332 -0
  11. package/crew/handlers/plan.ts +906 -0
  12. package/crew/handlers/review.ts +333 -0
  13. package/crew/handlers/revise.ts +376 -0
  14. package/crew/handlers/status.ts +295 -0
  15. package/crew/handlers/sync.ts +233 -0
  16. package/crew/handlers/task.ts +792 -0
  17. package/crew/handlers/team.ts +235 -0
  18. package/crew/handlers/work.ts +425 -0
  19. package/crew/id-allocator.ts +30 -0
  20. package/crew/index.ts +257 -0
  21. package/crew/live-progress.ts +58 -0
  22. package/crew/lobby.ts +473 -0
  23. package/crew/prompt.ts +252 -0
  24. package/crew/registry.ts +114 -0
  25. package/crew/spawn.ts +111 -0
  26. package/crew/state-autonomous.ts +164 -0
  27. package/crew/state-planning.ts +263 -0
  28. package/crew/state.ts +20 -0
  29. package/crew/store.ts +642 -0
  30. package/crew/task-actions.ts +131 -0
  31. package/crew/team/store.ts +479 -0
  32. package/crew/team/subagent-roles.ts +87 -0
  33. package/crew/team/types.ts +50 -0
  34. package/crew/types.ts +194 -0
  35. package/crew/utils/artifacts.ts +62 -0
  36. package/crew/utils/config.ts +156 -0
  37. package/crew/utils/discover.ts +219 -0
  38. package/crew/utils/install.ts +85 -0
  39. package/crew/utils/progress.ts +187 -0
  40. package/crew/utils/result.ts +16 -0
  41. package/crew/utils/risk-labels.ts +7 -0
  42. package/crew/utils/task-format.ts +14 -0
  43. package/crew/utils/team-roles.ts +28 -0
  44. package/crew/utils/truncate.ts +79 -0
  45. package/crew/utils/verdict.ts +55 -0
  46. package/feed.ts +268 -0
  47. package/handlers.ts +1107 -0
  48. package/index.ts +1206 -0
  49. package/install.mjs +189 -0
  50. package/lib.ts +467 -0
  51. package/overlay-actions.ts +511 -0
  52. package/overlay-coordinator.ts +150 -0
  53. package/overlay-render.ts +676 -0
  54. package/overlay.ts +830 -0
  55. package/package.json +62 -0
  56. package/skills/pi-messenger-crew/SKILL.md +347 -0
  57. package/store.ts +1139 -0
  58. package/vitest.config.ts +10 -0
@@ -0,0 +1,131 @@
1
+ import { logFeedEvent } from "../feed.ts";
2
+ import * as store from "./store.ts";
3
+ import { loadCrewConfig } from "./utils/config.ts";
4
+ import { killWorkerByTask } from "./registry.ts";
5
+ import type { Task } from "./types.ts";
6
+
7
+ export type TaskAction = "start" | "block" | "unblock" | "reset" | "cascade-reset" | "delete" | "stop";
8
+
9
+ export interface TaskActionOptions {
10
+ isWorkerActive?: (taskId: string) => boolean;
11
+ }
12
+
13
+ export interface TaskActionResult {
14
+ success: boolean;
15
+ message: string;
16
+ error?: string;
17
+ task?: Task;
18
+ resetTasks?: Task[];
19
+ unmetDependencies?: string[];
20
+ }
21
+
22
+ export function executeTaskAction(
23
+ cwd: string,
24
+ action: TaskAction,
25
+ taskId: string,
26
+ agentName: string,
27
+ reason?: string,
28
+ options?: TaskActionOptions,
29
+ ): TaskActionResult {
30
+ const task = store.getTask(cwd, taskId);
31
+ if (!task) return { success: false, error: "not_found", message: `Task ${taskId} not found` };
32
+
33
+ switch (action) {
34
+ case "start": {
35
+ if (task.milestone) {
36
+ return { success: false, error: "milestone_not_startable", message: `Task ${taskId} is a milestone and cannot be started manually` };
37
+ }
38
+ if (task.status === "in_progress" && task.assigned_to === agentName) {
39
+ return { success: true, message: `Already started ${taskId}`, task };
40
+ }
41
+ if (task.status !== "todo") {
42
+ return { success: false, error: "invalid_status", message: `Task ${taskId} is ${task.status}, not todo` };
43
+ }
44
+ const config = loadCrewConfig(store.getCrewDir(cwd));
45
+ if (config.dependencies !== "advisory") {
46
+ const unmetDependencies = task.depends_on.filter(depId => store.getTask(cwd, depId)?.status !== "done");
47
+ if (unmetDependencies.length > 0) {
48
+ return {
49
+ success: false,
50
+ error: "unmet_dependencies",
51
+ message: `Unmet dependencies: ${unmetDependencies.join(", ")}`,
52
+ unmetDependencies,
53
+ };
54
+ }
55
+ }
56
+ const started = store.startTask(cwd, taskId, agentName);
57
+ if (!started) return { success: false, error: "start_failed", message: `Failed to start ${taskId}` };
58
+ logFeedEvent(cwd, agentName, "task.start", taskId, started.title);
59
+ return { success: true, message: `Started ${taskId}`, task: started };
60
+ }
61
+
62
+ case "block": {
63
+ if (task.status !== "in_progress") {
64
+ return { success: false, error: "invalid_status", message: `Task ${taskId} must be in_progress to block` };
65
+ }
66
+ if (!reason) {
67
+ return { success: false, error: "missing_reason", message: `Reason required to block ${taskId}` };
68
+ }
69
+ const blocked = store.blockTask(cwd, taskId, reason);
70
+ if (!blocked) return { success: false, error: "block_failed", message: `Failed to block ${taskId}` };
71
+ logFeedEvent(cwd, agentName, "task.block", taskId, reason);
72
+ return { success: true, message: `Blocked ${taskId}`, task: blocked };
73
+ }
74
+
75
+ case "unblock": {
76
+ if (task.status !== "blocked") {
77
+ return { success: false, error: "invalid_status", message: `Task ${taskId} is ${task.status}, not blocked` };
78
+ }
79
+ const unblocked = store.unblockTask(cwd, taskId);
80
+ if (!unblocked) return { success: false, error: "unblock_failed", message: `Failed to unblock ${taskId}` };
81
+ logFeedEvent(cwd, agentName, "task.unblock", taskId, unblocked.title);
82
+ return { success: true, message: `Unblocked ${taskId}`, task: unblocked };
83
+ }
84
+
85
+ case "reset": {
86
+ if (options?.isWorkerActive?.(taskId)) {
87
+ return { success: false, error: "active_worker", message: `Cannot reset ${taskId} while its worker is active` };
88
+ }
89
+ const resetTasks = store.resetTask(cwd, taskId, false);
90
+ if (resetTasks.length === 0) return { success: false, error: "reset_failed", message: `Failed to reset ${taskId}` };
91
+ logFeedEvent(cwd, agentName, "task.reset", taskId, task.title);
92
+ return { success: true, message: `Reset ${taskId}`, resetTasks };
93
+ }
94
+
95
+ case "cascade-reset": {
96
+ const subtree = [task, ...store.getTransitiveDependents(cwd, taskId)];
97
+ const activeTask = subtree.find(t => options?.isWorkerActive?.(t.id));
98
+ if (activeTask) {
99
+ return { success: false, error: "active_worker", message: `Cannot reset ${activeTask.id} while its worker is active` };
100
+ }
101
+ const resetTasks = store.resetTask(cwd, taskId, true);
102
+ if (resetTasks.length === 0) return { success: false, error: "reset_failed", message: `Failed to reset ${taskId}` };
103
+ logFeedEvent(cwd, agentName, "task.reset", taskId, `cascade (${resetTasks.length} tasks)`);
104
+ return { success: true, message: `Reset ${taskId} + ${Math.max(0, resetTasks.length - 1)} dependents`, resetTasks };
105
+ }
106
+
107
+ case "delete": {
108
+ if (task.status === "in_progress" && options?.isWorkerActive?.(taskId)) {
109
+ return { success: false, error: "active_worker", message: `Cannot delete ${taskId} while its worker is active` };
110
+ }
111
+ if (!store.deleteTask(cwd, taskId)) return { success: false, error: "delete_failed", message: `Failed to delete ${taskId}` };
112
+ logFeedEvent(cwd, agentName, "task.delete", taskId, task.title);
113
+ return { success: true, message: `Deleted ${taskId}` };
114
+ }
115
+
116
+ case "stop": {
117
+ if (task.status !== "in_progress") {
118
+ return { success: false, error: "invalid_status", message: `Task ${taskId} is ${task.status}, not in_progress` };
119
+ }
120
+ if (options?.isWorkerActive?.(taskId)) {
121
+ killWorkerByTask(cwd, taskId);
122
+ store.appendTaskProgress(cwd, taskId, agentName, "Worker stopped by user");
123
+ } else {
124
+ store.appendTaskProgress(cwd, taskId, agentName, "Task unassigned (no active worker)");
125
+ }
126
+ store.updateTask(cwd, taskId, { status: "todo", assigned_to: undefined });
127
+ logFeedEvent(cwd, agentName, "task.reset", taskId, "stopped");
128
+ return { success: true, message: `Stopped ${taskId}` };
129
+ }
130
+ }
131
+ }
@@ -0,0 +1,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 { 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
+ }