pi-crew 0.1.41 → 0.1.43

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 (176) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +51 -0
  3. package/agents/analyst.md +11 -11
  4. package/agents/critic.md +11 -11
  5. package/agents/executor.md +11 -11
  6. package/agents/explorer.md +11 -11
  7. package/agents/planner.md +11 -11
  8. package/agents/reviewer.md +11 -11
  9. package/agents/security-reviewer.md +11 -11
  10. package/agents/test-engineer.md +11 -11
  11. package/agents/verifier.md +11 -11
  12. package/agents/writer.md +11 -11
  13. package/docs/refactor-tasks-phase3.md +394 -394
  14. package/docs/refactor-tasks-phase4.md +564 -564
  15. package/docs/refactor-tasks-phase5.md +402 -402
  16. package/docs/refactor-tasks-phase6.md +662 -662
  17. package/docs/research-extension-examples.md +297 -297
  18. package/docs/research-extension-system.md +324 -324
  19. package/docs/research-optimization-plan.md +548 -548
  20. package/docs/research-pi-coding-agent.md +357 -357
  21. package/docs/research-source-pi-crew-reference.md +174 -174
  22. package/docs/runtime-flow.md +148 -148
  23. package/docs/source-runtime-refactor-map.md +83 -83
  24. package/index.ts +6 -6
  25. package/package.json +1 -1
  26. package/src/agents/agent-serializer.ts +34 -34
  27. package/src/agents/discover-agents.ts +4 -4
  28. package/src/config/config.ts +9 -4
  29. package/src/extension/cross-extension-rpc.ts +82 -82
  30. package/src/extension/management.ts +37 -8
  31. package/src/extension/notification-router.ts +2 -2
  32. package/src/extension/register.ts +3 -0
  33. package/src/extension/registration/commands.ts +11 -9
  34. package/src/extension/registration/compaction-guard.ts +125 -125
  35. package/src/extension/registration/subagent-tools.ts +28 -19
  36. package/src/extension/result-watcher.ts +4 -4
  37. package/src/extension/run-bundle-schema.ts +8 -4
  38. package/src/extension/run-import.ts +4 -0
  39. package/src/extension/run-index.ts +4 -1
  40. package/src/extension/run-maintenance.ts +43 -24
  41. package/src/extension/team-tool/api.ts +1 -1
  42. package/src/extension/team-tool/cancel.ts +31 -31
  43. package/src/extension/team-tool/doctor.ts +8 -1
  44. package/src/extension/team-tool/handle-settings.ts +188 -0
  45. package/src/extension/team-tool/inspect.ts +41 -41
  46. package/src/extension/team-tool/lifecycle-actions.ts +79 -79
  47. package/src/extension/team-tool/plan.ts +19 -19
  48. package/src/extension/team-tool/run.ts +4 -2
  49. package/src/extension/team-tool/status.ts +93 -93
  50. package/src/extension/team-tool.ts +3 -1
  51. package/src/i18n.ts +184 -0
  52. package/src/observability/correlation.ts +2 -2
  53. package/src/observability/event-to-metric.ts +4 -3
  54. package/src/observability/exporters/adapter.ts +7 -1
  55. package/src/observability/exporters/otlp-exporter.ts +14 -2
  56. package/src/observability/exporters/prometheus-exporter.ts +9 -2
  57. package/src/observability/metric-registry.ts +18 -3
  58. package/src/observability/metric-retention.ts +11 -3
  59. package/src/observability/metric-sink.ts +9 -4
  60. package/src/observability/metrics-primitives.ts +4 -3
  61. package/src/prompt/prompt-runtime.ts +72 -68
  62. package/src/runtime/agent-control.ts +63 -63
  63. package/src/runtime/agent-memory.ts +72 -72
  64. package/src/runtime/agent-observability.ts +114 -114
  65. package/src/runtime/async-marker.ts +26 -26
  66. package/src/runtime/attention-events.ts +28 -23
  67. package/src/runtime/background-runner.ts +53 -53
  68. package/src/runtime/child-pi.ts +4 -4
  69. package/src/runtime/completion-guard.ts +103 -99
  70. package/src/runtime/concurrency.ts +1 -1
  71. package/src/runtime/crash-recovery.ts +2 -1
  72. package/src/runtime/crew-agent-runtime.ts +58 -58
  73. package/src/runtime/deadletter.ts +14 -4
  74. package/src/runtime/direct-run.ts +35 -35
  75. package/src/runtime/foreground-control.ts +82 -82
  76. package/src/runtime/green-contract.ts +46 -46
  77. package/src/runtime/group-join.ts +106 -106
  78. package/src/runtime/heartbeat-gradient.ts +28 -28
  79. package/src/runtime/heartbeat-watcher.ts +48 -4
  80. package/src/runtime/live-agent-control.ts +87 -87
  81. package/src/runtime/live-agent-manager.ts +85 -85
  82. package/src/runtime/live-control-realtime.ts +36 -36
  83. package/src/runtime/live-session-runtime.ts +305 -305
  84. package/src/runtime/manifest-cache.ts +2 -2
  85. package/src/runtime/model-fallback.ts +269 -261
  86. package/src/runtime/parallel-research.ts +44 -44
  87. package/src/runtime/parallel-utils.ts +1 -1
  88. package/src/runtime/pi-json-output.ts +111 -111
  89. package/src/runtime/policy-engine.ts +79 -78
  90. package/src/runtime/post-exit-stdio-guard.ts +2 -2
  91. package/src/runtime/process-status.ts +56 -56
  92. package/src/runtime/progress-event-coalescer.ts +43 -43
  93. package/src/runtime/recovery-recipes.ts +74 -74
  94. package/src/runtime/retry-executor.ts +5 -0
  95. package/src/runtime/role-permission.ts +39 -39
  96. package/src/runtime/runtime-resolver.ts +1 -1
  97. package/src/runtime/session-usage.ts +79 -79
  98. package/src/runtime/sidechain-output.ts +29 -29
  99. package/src/runtime/subagent-manager.ts +3 -3
  100. package/src/runtime/task-display.ts +38 -38
  101. package/src/runtime/task-output-context.ts +127 -127
  102. package/src/runtime/task-runner/live-executor.ts +101 -101
  103. package/src/runtime/task-runner/progress.ts +119 -111
  104. package/src/runtime/task-runner/result-utils.ts +14 -14
  105. package/src/runtime/task-runner/state-helpers.ts +22 -22
  106. package/src/runtime/team-runner.ts +3 -6
  107. package/src/runtime/worker-heartbeat.ts +21 -21
  108. package/src/runtime/worker-startup.ts +57 -57
  109. package/src/schema/config-schema.ts +1 -1
  110. package/src/schema/team-tool-schema.ts +110 -109
  111. package/src/state/artifact-store.ts +4 -2
  112. package/src/state/atomic-write.ts +12 -4
  113. package/src/state/contracts.ts +105 -105
  114. package/src/state/event-log.ts +3 -4
  115. package/src/state/jsonl-writer.ts +4 -1
  116. package/src/state/locks.ts +9 -1
  117. package/src/state/task-claims.ts +44 -42
  118. package/src/state/usage.ts +29 -29
  119. package/src/subagents/async-entry.ts +1 -1
  120. package/src/subagents/index.ts +3 -3
  121. package/src/subagents/live/control.ts +1 -1
  122. package/src/subagents/live/manager.ts +1 -1
  123. package/src/subagents/live/realtime.ts +1 -1
  124. package/src/subagents/live/session-runtime.ts +1 -1
  125. package/src/subagents/manager.ts +1 -1
  126. package/src/subagents/spawn.ts +1 -1
  127. package/src/teams/discover-teams.ts +2 -2
  128. package/src/teams/team-serializer.ts +38 -38
  129. package/src/types/diff.d.ts +18 -18
  130. package/src/ui/crew-footer.ts +101 -101
  131. package/src/ui/crew-select-list.ts +111 -111
  132. package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
  133. package/src/ui/dynamic-border.ts +25 -25
  134. package/src/ui/layout-primitives.ts +106 -106
  135. package/src/ui/live-run-sidebar.ts +1 -1
  136. package/src/ui/loaders.ts +158 -158
  137. package/src/ui/mascot.ts +3 -2
  138. package/src/ui/powerbar-publisher.ts +4 -3
  139. package/src/ui/render-diff.ts +119 -119
  140. package/src/ui/render-scheduler.ts +54 -14
  141. package/src/ui/run-dashboard.ts +39 -11
  142. package/src/ui/run-snapshot-cache.ts +63 -37
  143. package/src/ui/spinner.ts +17 -17
  144. package/src/ui/status-colors.ts +54 -54
  145. package/src/ui/syntax-highlight.ts +116 -116
  146. package/src/ui/theme-adapter.ts +1 -1
  147. package/src/ui/transcript-viewer.ts +7 -2
  148. package/src/utils/completion-dedupe.ts +63 -63
  149. package/src/utils/file-coalescer.ts +5 -3
  150. package/src/utils/frontmatter.ts +68 -36
  151. package/src/utils/git.ts +262 -262
  152. package/src/utils/ids.ts +12 -12
  153. package/src/utils/internal-error.ts +1 -1
  154. package/src/utils/names.ts +27 -26
  155. package/src/utils/paths.ts +1 -1
  156. package/src/utils/redaction.ts +44 -41
  157. package/src/utils/safe-paths.ts +47 -34
  158. package/src/utils/sleep.ts +2 -2
  159. package/src/utils/timings.ts +2 -0
  160. package/src/utils/visual.ts +9 -1
  161. package/src/workflows/discover-workflows.ts +4 -1
  162. package/src/workflows/validate-workflow.ts +40 -40
  163. package/src/worktree/branch-freshness.ts +45 -45
  164. package/src/worktree/worktree-manager.ts +6 -1
  165. package/teams/default.team.md +12 -12
  166. package/teams/fast-fix.team.md +11 -11
  167. package/teams/implementation.team.md +18 -18
  168. package/teams/parallel-research.team.md +14 -14
  169. package/teams/research.team.md +11 -11
  170. package/teams/review.team.md +12 -12
  171. package/workflows/default.workflow.md +29 -29
  172. package/workflows/fast-fix.workflow.md +22 -22
  173. package/workflows/implementation.workflow.md +38 -38
  174. package/workflows/parallel-research.workflow.md +46 -46
  175. package/workflows/research.workflow.md +22 -22
  176. package/workflows/review.workflow.md +30 -30
@@ -1,53 +1,53 @@
1
- import { allAgents, discoverAgents } from "../agents/discover-agents.ts";
2
- import { allTeams, discoverTeams } from "../teams/discover-teams.ts";
3
- import { appendEvent } from "../state/event-log.ts";
4
- import { loadRunManifestById, updateRunStatus } from "../state/state-store.ts";
5
- import { allWorkflows, discoverWorkflows } from "../workflows/discover-workflows.ts";
6
- import { loadConfig } from "../config/config.ts";
7
- import { executeTeamRun } from "./team-runner.ts";
8
- import { resolveCrewRuntime } from "./runtime-resolver.ts";
9
- import { directTeamAndWorkflowFromRun } from "./direct-run.ts";
10
- import { expandParallelResearchWorkflow } from "./parallel-research.ts";
11
- import { writeAsyncStartMarker } from "./async-marker.ts";
12
-
13
- function argValue(name: string): string | undefined {
14
- const index = process.argv.indexOf(name);
15
- if (index === -1) return undefined;
16
- return process.argv[index + 1];
17
- }
18
-
19
- async function main(): Promise<void> {
20
- const cwd = argValue("--cwd");
21
- const runId = argValue("--run-id");
22
- if (!cwd || !runId) throw new Error("Usage: background-runner.ts --cwd <cwd> --run-id <runId>");
23
-
24
- const loaded = loadRunManifestById(cwd, runId);
25
- if (!loaded) throw new Error(`Run '${runId}' not found.`);
26
- let { manifest, tasks } = loaded;
27
- appendEvent(manifest.eventsPath, { type: "async.started", runId: manifest.runId, data: { pid: process.pid } });
28
- writeAsyncStartMarker(manifest, { pid: process.pid, startedAt: new Date().toISOString() });
29
-
30
- try {
31
- const agents = allAgents(discoverAgents(cwd));
32
- const direct = directTeamAndWorkflowFromRun(manifest, tasks, agents);
33
- const team = direct?.team ?? allTeams(discoverTeams(cwd)).find((candidate) => candidate.name === manifest.team);
34
- if (!team) throw new Error(`Team '${manifest.team}' not found.`);
35
- const baseWorkflow = direct?.workflow ?? allWorkflows(discoverWorkflows(cwd)).find((candidate) => candidate.name === manifest.workflow);
36
- if (!baseWorkflow) throw new Error(`Workflow '${manifest.workflow ?? ""}' not found.`);
37
- const workflow = expandParallelResearchWorkflow(baseWorkflow, cwd);
38
- const loadedConfig = loadConfig(cwd);
39
- const runtime = await resolveCrewRuntime(loadedConfig.config);
40
- const executeWorkers = runtime.kind !== "scaffold";
41
- const result = await executeTeamRun({ manifest, tasks, team, workflow, agents, executeWorkers, limits: loadedConfig.config.limits, runtime, runtimeConfig: loadedConfig.config.runtime });
42
- manifest = result.manifest;
43
- tasks = result.tasks;
44
- appendEvent(manifest.eventsPath, { type: "async.completed", runId: manifest.runId, data: { status: manifest.status, tasks: tasks.length } });
45
- } catch (error) {
46
- const message = error instanceof Error ? error.message : String(error);
47
- manifest = updateRunStatus(manifest, "failed", message);
48
- appendEvent(manifest.eventsPath, { type: "async.failed", runId: manifest.runId, message });
49
- process.exitCode = 1;
50
- }
51
- }
52
-
53
- await main();
1
+ import { allAgents, discoverAgents } from "../agents/discover-agents.ts";
2
+ import { allTeams, discoverTeams } from "../teams/discover-teams.ts";
3
+ import { appendEvent } from "../state/event-log.ts";
4
+ import { loadRunManifestById, updateRunStatus } from "../state/state-store.ts";
5
+ import { allWorkflows, discoverWorkflows } from "../workflows/discover-workflows.ts";
6
+ import { loadConfig } from "../config/config.ts";
7
+ import { executeTeamRun } from "./team-runner.ts";
8
+ import { resolveCrewRuntime } from "./runtime-resolver.ts";
9
+ import { directTeamAndWorkflowFromRun } from "./direct-run.ts";
10
+ import { expandParallelResearchWorkflow } from "./parallel-research.ts";
11
+ import { writeAsyncStartMarker } from "./async-marker.ts";
12
+
13
+ function argValue(name: string): string | undefined {
14
+ const index = process.argv.indexOf(name);
15
+ if (index === -1) return undefined;
16
+ return process.argv[index + 1];
17
+ }
18
+
19
+ async function main(): Promise<void> {
20
+ const cwd = argValue("--cwd");
21
+ const runId = argValue("--run-id");
22
+ if (!cwd || !runId) throw new Error("Usage: background-runner.ts --cwd <cwd> --run-id <runId>");
23
+
24
+ const loaded = loadRunManifestById(cwd, runId);
25
+ if (!loaded) throw new Error(`Run '${runId}' not found.`);
26
+ let { manifest, tasks } = loaded;
27
+ appendEvent(manifest.eventsPath, { type: "async.started", runId: manifest.runId, data: { pid: process.pid } });
28
+ writeAsyncStartMarker(manifest, { pid: process.pid, startedAt: new Date().toISOString() });
29
+
30
+ try {
31
+ const agents = allAgents(discoverAgents(cwd));
32
+ const direct = directTeamAndWorkflowFromRun(manifest, tasks, agents);
33
+ const team = direct?.team ?? allTeams(discoverTeams(cwd)).find((candidate) => candidate.name === manifest.team);
34
+ if (!team) throw new Error(`Team '${manifest.team}' not found.`);
35
+ const baseWorkflow = direct?.workflow ?? allWorkflows(discoverWorkflows(cwd)).find((candidate) => candidate.name === manifest.workflow);
36
+ if (!baseWorkflow) throw new Error(`Workflow '${manifest.workflow ?? ""}' not found.`);
37
+ const workflow = expandParallelResearchWorkflow(baseWorkflow, cwd);
38
+ const loadedConfig = loadConfig(cwd);
39
+ const runtime = await resolveCrewRuntime(loadedConfig.config);
40
+ const executeWorkers = runtime.kind !== "scaffold";
41
+ const result = await executeTeamRun({ manifest, tasks, team, workflow, agents, executeWorkers, limits: loadedConfig.config.limits, runtime, runtimeConfig: loadedConfig.config.runtime });
42
+ manifest = result.manifest;
43
+ tasks = result.tasks;
44
+ appendEvent(manifest.eventsPath, { type: "async.completed", runId: manifest.runId, data: { status: manifest.status, tasks: tasks.length } });
45
+ } catch (error) {
46
+ const message = error instanceof Error ? error.message : String(error);
47
+ manifest = updateRunStatus(manifest, "failed", message);
48
+ appendEvent(manifest.eventsPath, { type: "async.failed", runId: manifest.runId, message });
49
+ process.exitCode = 1;
50
+ }
51
+ }
52
+
53
+ await main();
@@ -69,7 +69,7 @@ function killProcessTree(pid: number | undefined, child?: ChildProcess): void {
69
69
  }
70
70
  childHardKillTimers.delete(pid);
71
71
  }, HARD_KILL_MS);
72
- hardKillTimer.unref?.();
72
+ hardKillTimer.unref();
73
73
  child?.once("exit", () => clearHardKillTimer(pid));
74
74
  childHardKillTimers.set(pid, hardKillTimer);
75
75
  } catch (error) {
@@ -318,7 +318,7 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
318
318
  logInternalError("child-pi.response-timeout-term", error, `pid=${child.pid}`);
319
319
  }
320
320
  }, responseTimeoutMs);
321
- noResponseTimer.unref?.();
321
+ noResponseTimer.unref();
322
322
  };
323
323
  const clearNoResponseTimer = (): void => {
324
324
  if (noResponseTimer) clearTimeout(noResponseTimer);
@@ -352,9 +352,9 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
352
352
  logInternalError("child-pi.final-drain-kill", error, `pid=${child.pid}`);
353
353
  }
354
354
  }, hardKillMs);
355
- hardKillTimer.unref?.();
355
+ hardKillTimer.unref();
356
356
  }, finalDrainMs);
357
- finalDrainTimer.unref?.();
357
+ finalDrainTimer.unref();
358
358
  },
359
359
  });
360
360
 
@@ -1,99 +1,103 @@
1
- import * as fs from "node:fs";
2
-
3
- export interface CompletionMutationGuardInput {
4
- role: string;
5
- taskText?: string;
6
- transcriptPath?: string;
7
- stdout?: string;
8
- }
9
-
10
- export interface CompletionMutationGuardResult {
11
- expectedMutation: boolean;
12
- observedMutation: boolean;
13
- reason?: "no_mutation_observed";
14
- observedTools: string[];
15
- }
16
-
17
- const MUTATING_ROLES = new Set(["executor", "test-engineer"]);
18
- const MUTATING_TOOLS = new Set(["edit", "write", "multi_edit", "apply_patch"]);
19
- const READ_ONLY_COMMANDS = /^(pwd|ls|dir|cat|type|sed|grep|rg|find|git\s+(status|diff|log|show|branch|remote|rev-parse|ls-files)|npm\s+(test|run\s+(typecheck|check|lint|test|ci))|node\s+--test)\b/i;
20
- const MUTATING_COMMANDS = /\b(rm\s+-|del\s+|erase\s+|mv\s+|move\s+|cp\s+|copy\s+|mkdir\b|touch\b|git\s+(add|commit|push|reset|clean|checkout|switch|merge|rebase|stash)|npm\s+(install|i|uninstall|publish|version)|pnpm\s+(add|install|remove)|yarn\s+(add|install|remove)|python\b.*>|node\b.*>|echo\b.*>|Set-Content|Out-File)\b/i;
21
- const READ_ONLY_HINTS = /\b(read-only|no edits?|do not edit|không sửa|khong sua|chỉ đọc|chi doc|plan only|chỉ lập plan|review only|audit only)\b/i;
22
-
23
- function asRecord(value: unknown): Record<string, unknown> | undefined {
24
- return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
25
- }
26
-
27
- function commandText(value: unknown): string {
28
- const record = asRecord(value);
29
- if (!record) return typeof value === "string" ? value : "";
30
- for (const key of ["command", "cmd", "script", "input"]) {
31
- const raw = record[key];
32
- if (typeof raw === "string") return raw;
33
- }
34
- return JSON.stringify(record);
35
- }
36
-
37
- function isMutatingTool(tool: string, args: unknown): boolean {
38
- const normalized = tool.toLowerCase();
39
- if (MUTATING_TOOLS.has(normalized)) return true;
40
- if (normalized === "bash" || normalized === "shell" || normalized === "powershell") {
41
- const command = commandText(args).trim();
42
- if (!command || READ_ONLY_COMMANDS.test(command)) return false;
43
- return MUTATING_COMMANDS.test(command);
44
- }
45
- return false;
46
- }
47
-
48
- function collectToolCallsFromEvent(event: unknown): Array<{ tool: string; args?: unknown }> {
49
- const record = asRecord(event);
50
- if (!record) return [];
51
- const calls: Array<{ tool: string; args?: unknown }> = [];
52
- const directTool = record.toolName ?? record.name ?? record.tool;
53
- if (typeof directTool === "string" && (record.type === "tool_execution_start" || record.type === "toolCall" || record.type === "tool_call")) {
54
- calls.push({ tool: directTool, args: record.args ?? record.input });
55
- }
56
- const content = Array.isArray(record.content) ? record.content : asRecord(record.message)?.content;
57
- if (Array.isArray(content)) {
58
- for (const part of content) {
59
- const item = asRecord(part);
60
- if (!item) continue;
61
- const tool = item.name ?? item.toolName ?? item.tool;
62
- if (typeof tool === "string" && (item.type === "toolCall" || item.type === "tool_call" || item.type === "tool_execution_start")) calls.push({ tool, args: item.input ?? item.args });
63
- }
64
- }
65
- return calls;
66
- }
67
-
68
- function transcriptText(input: CompletionMutationGuardInput): string {
69
- if (input.transcriptPath && fs.existsSync(input.transcriptPath)) return fs.readFileSync(input.transcriptPath, "utf-8");
70
- return input.stdout ?? "";
71
- }
72
-
73
- export function expectsImplementationMutation(input: Pick<CompletionMutationGuardInput, "role" | "taskText">): boolean {
74
- if (!MUTATING_ROLES.has(input.role)) return false;
75
- return !READ_ONLY_HINTS.test(input.taskText ?? "");
76
- }
77
-
78
- export function evaluateCompletionMutationGuard(input: CompletionMutationGuardInput): CompletionMutationGuardResult {
79
- const expectedMutation = expectsImplementationMutation(input);
80
- const observedTools: string[] = [];
81
- let observedMutation = false;
82
- const text = transcriptText(input);
83
- for (const line of text.split("\n")) {
84
- const trimmed = line.trim();
85
- if (!trimmed) continue;
86
- let event: unknown;
87
- try { event = JSON.parse(trimmed); } catch { continue; }
88
- for (const call of collectToolCallsFromEvent(event)) {
89
- observedTools.push(call.tool);
90
- if (isMutatingTool(call.tool, call.args)) observedMutation = true;
91
- }
92
- }
93
- return {
94
- expectedMutation,
95
- observedMutation,
96
- observedTools,
97
- ...(expectedMutation && !observedMutation ? { reason: "no_mutation_observed" as const } : {}),
98
- };
99
- }
1
+ import * as fs from "node:fs";
2
+
3
+ export interface CompletionMutationGuardInput {
4
+ role: string;
5
+ taskText?: string;
6
+ transcriptPath?: string;
7
+ stdout?: string;
8
+ }
9
+
10
+ export interface CompletionMutationGuardResult {
11
+ expectedMutation: boolean;
12
+ observedMutation: boolean;
13
+ reason?: "no_mutation_observed";
14
+ observedTools: string[];
15
+ }
16
+
17
+ const MUTATING_ROLES = new Set(["executor", "test-engineer"]);
18
+ const MUTATING_TOOLS = new Set(["edit", "write", "multi_edit", "apply_patch", "replace_in_file", "insert", "delete_files", "create_file", "overwrite", "patch"]);
19
+ const READ_ONLY_COMMANDS = /^(pwd|ls|dir|cat|type|sed|grep|rg|find|git\s+(status|diff|log|show|branch|remote|rev-parse|ls-files)|npm\s+(test|run\s+(typecheck|check|lint|test|ci))|node\s+--test)\b/i;
20
+ const MUTATING_COMMANDS = /\b(rm\s+-|del\s+|erase\s+|mv\s+|move\s+|cp\s+|copy\s+|mkdir\b|touch\b|git\s+(add|commit|push|reset|clean|checkout|switch|merge|rebase|stash)|npm\s+(install|i|uninstall|publish|version)|pnpm\s+(add|install|remove)|yarn\s+(add|install|remove)|python\b.*>|node\b.*>|echo\b.*>|Set-Content|Out-File|sed\s+-i|tee\b|dd\b.*of=|wget\b.*-O|curl\b.*-o)\b/i;
21
+ const READ_ONLY_HINTS = /\b(read-only|no edits?|do not edit|không sửa|khong sua|chỉ đọc|chi doc|plan only|chỉ lập plan|review only|audit only)\b/i;
22
+
23
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
24
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
25
+ }
26
+
27
+ function commandText(value: unknown): string {
28
+ const record = asRecord(value);
29
+ if (!record) return typeof value === "string" ? value : "";
30
+ for (const key of ["command", "cmd", "script", "input"]) {
31
+ const raw = record[key];
32
+ if (typeof raw === "string") return raw;
33
+ }
34
+ return JSON.stringify(record);
35
+ }
36
+
37
+ function isMutatingTool(tool: string, args: unknown): boolean {
38
+ const normalized = tool.toLowerCase();
39
+ if (MUTATING_TOOLS.has(normalized)) return true;
40
+ if (normalized === "bash" || normalized === "shell" || normalized === "powershell") {
41
+ const command = commandText(args).trim();
42
+ if (!command) return false;
43
+ // Check mutating patterns first: sed -i is mutating even though plain sed is read-only.
44
+ if (MUTATING_COMMANDS.test(command)) return true;
45
+ if (READ_ONLY_COMMANDS.test(command)) return false;
46
+ // If the command doesn't match either list, treat unknown bash calls as potentially mutating.
47
+ return true;
48
+ }
49
+ return false;
50
+ }
51
+
52
+ function collectToolCallsFromEvent(event: unknown): Array<{ tool: string; args?: unknown }> {
53
+ const record = asRecord(event);
54
+ if (!record) return [];
55
+ const calls: Array<{ tool: string; args?: unknown }> = [];
56
+ const directTool = record.toolName ?? record.name ?? record.tool;
57
+ if (typeof directTool === "string" && (record.type === "tool_execution_start" || record.type === "toolCall" || record.type === "tool_call")) {
58
+ calls.push({ tool: directTool, args: record.args ?? record.input });
59
+ }
60
+ const content = Array.isArray(record.content) ? record.content : asRecord(record.message)?.content;
61
+ if (Array.isArray(content)) {
62
+ for (const part of content) {
63
+ const item = asRecord(part);
64
+ if (!item) continue;
65
+ const tool = item.name ?? item.toolName ?? item.tool;
66
+ if (typeof tool === "string" && (item.type === "toolCall" || item.type === "tool_call" || item.type === "tool_execution_start")) calls.push({ tool, args: item.input ?? item.args });
67
+ }
68
+ }
69
+ return calls;
70
+ }
71
+
72
+ function transcriptText(input: CompletionMutationGuardInput): string {
73
+ if (input.transcriptPath && fs.existsSync(input.transcriptPath)) return fs.readFileSync(input.transcriptPath, "utf-8");
74
+ return input.stdout ?? "";
75
+ }
76
+
77
+ export function expectsImplementationMutation(input: Pick<CompletionMutationGuardInput, "role" | "taskText">): boolean {
78
+ if (!MUTATING_ROLES.has(input.role)) return false;
79
+ return !READ_ONLY_HINTS.test(input.taskText ?? "");
80
+ }
81
+
82
+ export function evaluateCompletionMutationGuard(input: CompletionMutationGuardInput): CompletionMutationGuardResult {
83
+ const expectedMutation = expectsImplementationMutation(input);
84
+ const observedTools: string[] = [];
85
+ let observedMutation = false;
86
+ const text = transcriptText(input);
87
+ for (const line of text.split("\n")) {
88
+ const trimmed = line.trim();
89
+ if (!trimmed) continue;
90
+ let event: unknown;
91
+ try { event = JSON.parse(trimmed); } catch { continue; }
92
+ for (const call of collectToolCallsFromEvent(event)) {
93
+ observedTools.push(call.tool);
94
+ if (isMutatingTool(call.tool, call.args)) observedMutation = true;
95
+ }
96
+ }
97
+ return {
98
+ expectedMutation,
99
+ observedMutation,
100
+ observedTools,
101
+ ...(expectedMutation && !observedMutation ? { reason: "no_mutation_observed" as const } : {}),
102
+ };
103
+ }
@@ -44,7 +44,7 @@ export function resolveBatchConcurrency(input: ResolveBatchConcurrencyInput): Ba
44
44
  else source = "workflow";
45
45
  const hardCap = positiveInteger(input.hardCap) ?? DEFAULT_CONCURRENCY.hardCap;
46
46
  const maxConcurrent = input.allowUnboundedConcurrency ? requested : Math.min(requested, hardCap);
47
- const readyCount = Math.max(0, Math.trunc(input.readyCount));
47
+ const readyCount = Math.max(0, Math.trunc(Number.isFinite(input.readyCount) ? input.readyCount : 0));
48
48
  const cappedReason = maxConcurrent < requested ? `;capped:${hardCap}` : "";
49
49
  const unboundedReason = input.allowUnboundedConcurrency && requested > hardCap ? `;unbounded:${hardCap}` : "";
50
50
  return {
@@ -51,6 +51,7 @@ export async function applyRecoveryPlan(plan: RecoveryPlan, ctx: Pick<ExtensionC
51
51
  export function declineRecoveryPlan(plan: RecoveryPlan, ctx: Pick<ExtensionContext, "cwd">): void {
52
52
  const loaded = loadRunManifestById(ctx.cwd, plan.runId);
53
53
  if (!loaded) throw new Error(`Run '${plan.runId}' not found.`);
54
- updateRunStatus(loaded.manifest, "cancelled", "interrupted-not-resumed");
54
+ // Log the event first — if appendEvent fails, state remains consistent.
55
55
  appendEvent(loaded.manifest.eventsPath, { type: "crew.run.recovery_declined", runId: plan.runId, message: "Interrupted run was not resumed.", data: { recoveredFromSeq: plan.lastEventSeq } });
56
+ updateRunStatus(loaded.manifest, "cancelled", "interrupted-not-resumed");
56
57
  }
@@ -1,58 +1,58 @@
1
- import type { TeamTaskStatus } from "../state/contracts.ts";
2
- import type { CrewActivityState, ModelRoutingState, UsageState } from "../state/types.ts";
3
-
4
- export type CrewRuntimeKind = "scaffold" | "child-process" | "live-session";
5
- export type CrewAgentStatus = "queued" | "running" | "completed" | "failed" | "cancelled" | "stopped";
6
-
7
- export interface CrewAgentRecentTool {
8
- tool: string;
9
- args?: string;
10
- endedAt: string;
11
- }
12
-
13
- export interface CrewAgentProgress {
14
- currentTool?: string;
15
- currentToolArgs?: string;
16
- currentToolStartedAt?: string;
17
- recentTools: CrewAgentRecentTool[];
18
- recentOutput: string[];
19
- toolCount: number;
20
- tokens?: number;
21
- turns?: number;
22
- durationMs?: number;
23
- lastActivityAt?: string;
24
- activityState?: CrewActivityState;
25
- failedTool?: string;
26
- }
27
-
28
- export interface CrewAgentRecord {
29
- id: string;
30
- runId: string;
31
- taskId: string;
32
- agent: string;
33
- role: string;
34
- runtime: CrewRuntimeKind;
35
- status: CrewAgentStatus;
36
- startedAt: string;
37
- completedAt?: string;
38
- resultArtifactPath?: string;
39
- transcriptPath?: string;
40
- statusPath?: string;
41
- eventsPath?: string;
42
- outputPath?: string;
43
- toolUses?: number;
44
- jsonEvents?: number;
45
- model?: string;
46
- routing?: ModelRoutingState;
47
- usage?: UsageState;
48
- progress?: CrewAgentProgress;
49
- error?: string;
50
- }
51
-
52
- export function taskStatusToAgentStatus(status: TeamTaskStatus): CrewAgentStatus {
53
- if (status === "completed") return "completed";
54
- if (status === "failed") return "failed";
55
- if (status === "cancelled" || status === "skipped") return "cancelled";
56
- if (status === "running") return "running";
57
- return "queued";
58
- }
1
+ import type { TeamTaskStatus } from "../state/contracts.ts";
2
+ import type { CrewActivityState, ModelRoutingState, UsageState } from "../state/types.ts";
3
+
4
+ export type CrewRuntimeKind = "scaffold" | "child-process" | "live-session";
5
+ export type CrewAgentStatus = "queued" | "running" | "completed" | "failed" | "cancelled" | "stopped";
6
+
7
+ export interface CrewAgentRecentTool {
8
+ tool: string;
9
+ args?: string;
10
+ endedAt: string;
11
+ }
12
+
13
+ export interface CrewAgentProgress {
14
+ currentTool?: string;
15
+ currentToolArgs?: string;
16
+ currentToolStartedAt?: string;
17
+ recentTools: CrewAgentRecentTool[];
18
+ recentOutput: string[];
19
+ toolCount: number;
20
+ tokens?: number;
21
+ turns?: number;
22
+ durationMs?: number;
23
+ lastActivityAt?: string;
24
+ activityState?: CrewActivityState;
25
+ failedTool?: string;
26
+ }
27
+
28
+ export interface CrewAgentRecord {
29
+ id: string;
30
+ runId: string;
31
+ taskId: string;
32
+ agent: string;
33
+ role: string;
34
+ runtime: CrewRuntimeKind;
35
+ status: CrewAgentStatus;
36
+ startedAt: string;
37
+ completedAt?: string;
38
+ resultArtifactPath?: string;
39
+ transcriptPath?: string;
40
+ statusPath?: string;
41
+ eventsPath?: string;
42
+ outputPath?: string;
43
+ toolUses?: number;
44
+ jsonEvents?: number;
45
+ model?: string;
46
+ routing?: ModelRoutingState;
47
+ usage?: UsageState;
48
+ progress?: CrewAgentProgress;
49
+ error?: string;
50
+ }
51
+
52
+ export function taskStatusToAgentStatus(status: TeamTaskStatus): CrewAgentStatus {
53
+ if (status === "completed") return "completed";
54
+ if (status === "failed") return "failed";
55
+ if (status === "cancelled" || status === "skipped") return "cancelled";
56
+ if (status === "running") return "running";
57
+ return "queued";
58
+ }
@@ -2,6 +2,8 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { TeamRunManifest } from "../state/types.ts";
4
4
 
5
+ import { logInternalError } from "../utils/internal-error.ts";
6
+
5
7
  export type DeadletterReason = "max-retries" | "heartbeat-dead" | "manual";
6
8
 
7
9
  export interface DeadletterEntry {
@@ -18,14 +20,22 @@ export function deadletterPath(manifest: TeamRunManifest): string {
18
20
  }
19
21
 
20
22
  export function appendDeadletter(manifest: TeamRunManifest, entry: DeadletterEntry): void {
21
- fs.mkdirSync(manifest.stateRoot, { recursive: true });
22
- fs.appendFileSync(deadletterPath(manifest), `${JSON.stringify(entry)}\n`, "utf-8");
23
+ try {
24
+ fs.mkdirSync(manifest.stateRoot, { recursive: true });
25
+ fs.appendFileSync(deadletterPath(manifest), `${JSON.stringify(entry)}\n`, "utf-8");
26
+ } catch (error) {
27
+ logInternalError("deadletter.append", error, `taskId=${entry.taskId}`);
28
+ }
23
29
  }
24
30
 
25
- export function readDeadletter(manifest: TeamRunManifest): DeadletterEntry[] {
31
+ export function readDeadletter(manifest: TeamRunManifest, maxEntries = 1000): DeadletterEntry[] {
26
32
  const filePath = deadletterPath(manifest);
27
33
  if (!fs.existsSync(filePath)) return [];
28
- return fs.readFileSync(filePath, "utf-8").split(/\r?\n/).filter(Boolean).flatMap((line) => {
34
+ // Read last maxEntries lines only to limit memory.
35
+ const raw = fs.readFileSync(filePath, "utf-8");
36
+ const lines = raw.split(/\r?\n/).filter(Boolean);
37
+ const tail = lines.slice(-maxEntries);
38
+ return tail.flatMap((line) => {
29
39
  try {
30
40
  const parsed = JSON.parse(line) as DeadletterEntry;
31
41
  return parsed && typeof parsed.taskId === "string" && typeof parsed.runId === "string" ? [parsed] : [];
@@ -1,35 +1,35 @@
1
- import type { AgentConfig } from "../agents/agent-config.ts";
2
- import type { TeamRunManifest, TeamTaskState } from "../state/types.ts";
3
- import type { TeamConfig } from "../teams/team-config.ts";
4
- import type { WorkflowConfig } from "../workflows/workflow-config.ts";
5
-
6
- export function isDirectRun(manifest: Pick<TeamRunManifest, "team" | "workflow">): boolean {
7
- return manifest.workflow === "direct-agent";
8
- }
9
-
10
- export function directTeamAndWorkflowFromRun(manifest: TeamRunManifest, tasks: TeamTaskState[], agents: AgentConfig[]): { team: TeamConfig; workflow: WorkflowConfig } | undefined {
11
- if (!isDirectRun(manifest)) return undefined;
12
- const firstTask = tasks[0];
13
- const agentName = firstTask?.agent ?? (manifest.team.replace(/^direct-/, "") || "executor");
14
- const agent = agents.find((candidate) => candidate.name === agentName);
15
- const role = firstTask?.role ?? "agent";
16
- const stepId = firstTask?.stepId ?? "01_agent";
17
- return {
18
- team: {
19
- name: manifest.team,
20
- description: `Direct subagent run for ${agentName}`,
21
- source: "builtin",
22
- filePath: "<generated>",
23
- roles: [{ name: role, agent: agentName, description: agent?.description }],
24
- defaultWorkflow: "direct-agent",
25
- workspaceMode: manifest.workspaceMode,
26
- },
27
- workflow: {
28
- name: manifest.workflow ?? "direct-agent",
29
- description: `Direct task for ${agentName}`,
30
- source: "builtin",
31
- filePath: "<generated>",
32
- steps: [{ id: stepId, role, task: "{goal}", model: firstTask?.model }],
33
- },
34
- };
35
- }
1
+ import type { AgentConfig } from "../agents/agent-config.ts";
2
+ import type { TeamRunManifest, TeamTaskState } from "../state/types.ts";
3
+ import type { TeamConfig } from "../teams/team-config.ts";
4
+ import type { WorkflowConfig } from "../workflows/workflow-config.ts";
5
+
6
+ export function isDirectRun(manifest: Pick<TeamRunManifest, "team" | "workflow">): boolean {
7
+ return manifest.workflow === "direct-agent";
8
+ }
9
+
10
+ export function directTeamAndWorkflowFromRun(manifest: TeamRunManifest, tasks: TeamTaskState[], agents: AgentConfig[]): { team: TeamConfig; workflow: WorkflowConfig } | undefined {
11
+ if (!isDirectRun(manifest)) return undefined;
12
+ const firstTask = tasks[0];
13
+ const agentName = firstTask?.agent ?? (manifest.team.replace(/^direct-/, "") || "executor");
14
+ const agent = agents.find((candidate) => candidate.name === agentName);
15
+ const role = firstTask?.role ?? "agent";
16
+ const stepId = firstTask?.stepId ?? "01_agent";
17
+ return {
18
+ team: {
19
+ name: manifest.team,
20
+ description: `Direct subagent run for ${agentName}`,
21
+ source: "builtin",
22
+ filePath: "<generated>",
23
+ roles: [{ name: role, agent: agentName, description: agent?.description }],
24
+ defaultWorkflow: "direct-agent",
25
+ workspaceMode: manifest.workspaceMode,
26
+ },
27
+ workflow: {
28
+ name: manifest.workflow ?? "direct-agent",
29
+ description: `Direct task for ${agentName}`,
30
+ source: "builtin",
31
+ filePath: "<generated>",
32
+ steps: [{ id: stepId, role, task: "{goal}", model: firstTask?.model }],
33
+ },
34
+ };
35
+ }