pi-crew 0.9.68 → 0.10.2

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 (253) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/NOTICE.md +21 -0
  3. package/README.md +44 -2
  4. package/agents/analyst.md +1 -1
  5. package/agents/cold-verifier.md +3 -1
  6. package/agents/critic.md +1 -1
  7. package/agents/executor.md +1 -1
  8. package/agents/explorer.md +1 -1
  9. package/agents/planner.md +1 -1
  10. package/agents/reviewer.md +1 -1
  11. package/agents/security-reviewer.md +1 -1
  12. package/agents/test-engineer.md +1 -1
  13. package/agents/verifier.md +1 -1
  14. package/agents/writer.md +1 -1
  15. package/dist/index.mjs +68113 -60774
  16. package/docs/README.md +2 -0
  17. package/docs/actions-reference.md +31 -0
  18. package/docs/commands-reference.md +17 -6
  19. package/docs/resource-formats.md +13 -0
  20. package/package.json +4 -2
  21. package/schema.json +503 -91
  22. package/scripts/resource-sampler.mjs +36 -2
  23. package/skills/requirements-to-task-packet/SKILL.md +26 -0
  24. package/skills/widget-rendering/SKILL.md +7 -7
  25. package/src/agents/agent-config.ts +2 -1
  26. package/src/agents/discover-agents.ts +23 -14
  27. package/src/config/config-merge.ts +183 -0
  28. package/src/config/config-validation.ts +687 -0
  29. package/src/config/config.ts +22 -864
  30. package/src/config/defaults.ts +43 -2
  31. package/src/config/drift-detector.ts +1 -1
  32. package/src/config/env-vars.ts +691 -0
  33. package/src/config/role-tools.ts +11 -9
  34. package/src/config/sanitize-project-config.ts +172 -0
  35. package/src/config/types.ts +49 -1
  36. package/src/extension/async-notifier.ts +25 -2
  37. package/src/extension/crew-cleanup.ts +13 -0
  38. package/src/extension/crew-vibes/config.ts +2 -1
  39. package/src/extension/crew-vibes/footer.ts +19 -0
  40. package/src/extension/crew-vibes/index.ts +11 -1
  41. package/src/extension/plan-orchestrate.ts +132 -0
  42. package/src/extension/register.ts +8 -0
  43. package/src/extension/registration/command-registration.ts +1 -0
  44. package/src/extension/registration/commands/dashboard.ts +158 -0
  45. package/src/extension/registration/commands/index.ts +35 -0
  46. package/src/extension/registration/commands/manage.ts +303 -0
  47. package/src/extension/registration/commands/run.ts +228 -0
  48. package/src/extension/registration/commands/shared.ts +639 -0
  49. package/src/extension/registration/commands/status.ts +60 -0
  50. package/src/extension/registration/commands.ts +13 -1224
  51. package/src/extension/registration/foreground-run-controller.ts +10 -2
  52. package/src/extension/registration/lifecycle-handlers.ts +178 -17
  53. package/src/extension/registration/runtime-cleanup.ts +23 -5
  54. package/src/extension/registration/subagent-tools.ts +218 -9
  55. package/src/extension/registration/team-tool.ts +5 -1
  56. package/src/extension/registration/ui.ts +5 -4
  57. package/src/extension/rpc-hmac.ts +5 -3
  58. package/src/extension/team-tool/api/heartbeat.ts +47 -10
  59. package/src/extension/team-tool/api/plan-approval.ts +9 -0
  60. package/src/extension/team-tool/api/task-claims.ts +109 -40
  61. package/src/extension/team-tool/cancel.ts +84 -50
  62. package/src/extension/team-tool/dispatch/index.ts +1 -0
  63. package/src/extension/team-tool/dispatch/run.ts +4 -1
  64. package/src/extension/team-tool/doctor.ts +103 -1
  65. package/src/extension/team-tool/orchestrate.ts +66 -1
  66. package/src/extension/team-tool/plans.ts +192 -0
  67. package/src/extension/team-tool/respond.ts +197 -65
  68. package/src/extension/team-tool/run-deadline.ts +35 -3
  69. package/src/extension/team-tool/run-intent.ts +63 -0
  70. package/src/extension/team-tool/run.ts +74 -20
  71. package/src/extension/team-tool/status.ts +84 -26
  72. package/src/extension/team-tool.ts +11 -2
  73. package/src/hooks/registry.ts +1 -6
  74. package/src/i18n.ts +9 -0
  75. package/src/prompt/prompt-runtime.ts +521 -2
  76. package/src/prompt/worker-events-channel.ts +173 -0
  77. package/src/runtime/README.md +8 -8
  78. package/src/runtime/async-runner.ts +7 -3
  79. package/src/runtime/background-runner.ts +42 -14
  80. package/src/runtime/broker/broker-issuer.ts +9 -2
  81. package/src/runtime/broker/crew-broker-tokens.ts +43 -6
  82. package/src/runtime/broker/crew-broker.ts +838 -10
  83. package/src/runtime/broker/wait-status-cache.ts +157 -0
  84. package/src/runtime/budget-enforcement.ts +281 -0
  85. package/src/runtime/child-pi/child-pi-constants.ts +8 -0
  86. package/src/runtime/child-pi/child-pi-spawn.ts +60 -14
  87. package/src/runtime/child-pi/child-pi-streams.ts +21 -1
  88. package/src/runtime/child-pi/child-pi-timers.ts +324 -0
  89. package/src/runtime/child-pi/child-pi.ts +97 -201
  90. package/src/runtime/child-pi/mock-fixtures.ts +16 -2
  91. package/src/runtime/crew-agent-records.ts +259 -14
  92. package/src/runtime/delegate-spawn.ts +148 -0
  93. package/src/runtime/detached-run-results.ts +90 -0
  94. package/src/runtime/deterministic-ast.ts +2 -1
  95. package/src/runtime/dispatch-batch.ts +945 -0
  96. package/src/runtime/finalize-run.ts +557 -0
  97. package/src/runtime/goal-workflow/adaptive-plan.ts +116 -15
  98. package/src/runtime/goal-workflow/dynamic-workflow-runner.ts +8 -3
  99. package/src/runtime/goal-workflow/goal-state-store.ts +1 -1
  100. package/src/runtime/group-join.ts +11 -125
  101. package/src/runtime/live-session/live-session-runtime.ts +26 -1
  102. package/src/runtime/merge-gate.ts +32 -10
  103. package/src/runtime/merge-loop.ts +130 -0
  104. package/src/runtime/model/model-budget-summary.ts +53 -0
  105. package/src/runtime/model/model-fallback.ts +36 -2
  106. package/src/runtime/model/pi-args.ts +10 -0
  107. package/src/runtime/model/provider-extensions.ts +10 -0
  108. package/src/runtime/orphan-worker-registry.ts +1 -1
  109. package/src/runtime/output/output-validator.ts +45 -0
  110. package/src/runtime/parent-guard.ts +3 -1
  111. package/src/runtime/peer-dep.ts +2 -1
  112. package/src/runtime/per-write-validator.ts +0 -5
  113. package/src/runtime/pi-spawn.ts +61 -15
  114. package/src/runtime/plan-approval.ts +125 -0
  115. package/src/runtime/plan-replan.ts +151 -0
  116. package/src/runtime/process-status.ts +16 -1
  117. package/src/runtime/recovery/checkpoint.ts +0 -18
  118. package/src/runtime/recovery/crash-recovery.ts +111 -46
  119. package/src/runtime/run-tracker.ts +77 -10
  120. package/src/runtime/scheduler-context.ts +98 -0
  121. package/src/runtime/scheduling/coalesce-tasks.ts +5 -0
  122. package/src/runtime/scheduling/global-worker-cap.ts +2 -1
  123. package/src/runtime/scheduling/nested-slots.ts +70 -0
  124. package/src/runtime/scheduling/run-coalesced-task-group.ts +64 -13
  125. package/src/runtime/scheduling/task-graph-scheduler.ts +0 -10
  126. package/src/runtime/settings-store.ts +219 -0
  127. package/src/runtime/spawn-policy.ts +217 -0
  128. package/src/runtime/stale-reconciler.ts +87 -6
  129. package/src/runtime/subagent-manager.ts +25 -1
  130. package/src/runtime/task-output-context.ts +230 -9
  131. package/src/runtime/task-packet.ts +23 -1
  132. package/src/runtime/task-runner/child-executor.ts +106 -7
  133. package/src/runtime/task-runner/post-execution.ts +125 -1
  134. package/src/runtime/task-runner/pre-execution.ts +39 -1
  135. package/src/runtime/task-runner/prompt-builder.ts +51 -1
  136. package/src/runtime/task-runner/retrieval-orchestrator.ts +72 -18
  137. package/src/runtime/task-runner/spec-evidence.ts +403 -0
  138. package/src/runtime/task-runner/state-helpers.ts +26 -24
  139. package/src/runtime/task-runner.ts +11 -0
  140. package/src/runtime/team-runner.ts +132 -1673
  141. package/src/runtime/verification/spec-sandbox.ts +255 -0
  142. package/src/runtime/verification/verification-gates.ts +3 -2
  143. package/src/runtime/verification/verification-worktree.ts +2 -1
  144. package/src/runtime/workflow-phase-advance.ts +100 -0
  145. package/src/runtime/workspace-tree.ts +9 -0
  146. package/src/schema/config-schema.ts +66 -26
  147. package/src/schema/sensitive-config-paths.ts +64 -0
  148. package/src/schema/team-tool-schema.ts +13 -3
  149. package/src/state/README.md +4 -10
  150. package/src/state/atomic-write.ts +20 -3
  151. package/src/state/contracts.ts +38 -0
  152. package/src/state/coordination/mailbox.ts +12 -2
  153. package/src/state/event-log/cursor.ts +223 -0
  154. package/src/state/event-log/event-log-rotation.ts +12 -4
  155. package/src/state/event-log/event-log.ts +152 -369
  156. package/src/state/event-log/sequence-cache.ts +373 -0
  157. package/src/state/event-log/worker-atomic-writer.ts +2 -1
  158. package/src/state/stores/active-run-registry.ts +3 -2
  159. package/src/state/stores/manifest-io.ts +237 -0
  160. package/src/state/stores/ownership-map.ts +162 -0
  161. package/src/state/stores/plan-store.ts +241 -0
  162. package/src/state/stores/run-cache.ts +0 -90
  163. package/src/state/stores/spec-store.ts +189 -0
  164. package/src/state/stores/state-store.ts +139 -232
  165. package/src/state/types.ts +199 -0
  166. package/src/ui/dashboard-panes/plan-pane.ts +136 -0
  167. package/src/ui/dashboard-panes/progress-pane.ts +6 -0
  168. package/src/ui/dashboard-panes/transcript-pane.ts +31 -0
  169. package/src/ui/dock-footer.ts +49 -0
  170. package/src/ui/heartbeat-aggregator.ts +9 -1
  171. package/src/ui/inline-panel/agent-pane.ts +375 -0
  172. package/src/ui/inline-panel/agent-transcript.ts +338 -0
  173. package/src/ui/inline-panel/agent-view-overlay.ts +225 -0
  174. package/src/ui/inline-panel/crew-editor.ts +192 -0
  175. package/src/ui/inline-panel/index.ts +290 -0
  176. package/src/ui/inline-panel/panel-rows.ts +37 -0
  177. package/src/ui/inline-panel/panel-selection.ts +157 -0
  178. package/src/ui/inline-panel/panel-store.ts +111 -0
  179. package/src/ui/inline-panel/view-session-store.ts +36 -0
  180. package/src/ui/keybinding-map.ts +54 -13
  181. package/src/ui/pi-ui-compat.ts +9 -0
  182. package/src/ui/powerbar-publisher.ts +52 -1
  183. package/src/ui/run-dashboard.ts +31 -5
  184. package/src/ui/run-snapshot-cache.ts +57 -30
  185. package/src/ui/snapshot-types.ts +6 -1
  186. package/src/ui/widget/index.ts +176 -22
  187. package/src/ui/widget/task-list.ts +198 -0
  188. package/src/ui/widget/widget-formatters.ts +240 -4
  189. package/src/ui/widget/widget-renderer.ts +243 -38
  190. package/src/ui/widget/widget-types.ts +11 -0
  191. package/src/utils/child-process-shield.ts +106 -0
  192. package/src/utils/file-coalescer.ts +0 -4
  193. package/src/utils/fs-errno.ts +66 -0
  194. package/src/utils/fs-watch.ts +1 -1
  195. package/src/utils/internal-error.ts +3 -1
  196. package/src/utils/paths.ts +11 -3
  197. package/src/utils/redaction.ts +7 -0
  198. package/src/utils/safe-abort.ts +45 -0
  199. package/src/utils/task-name-generator.ts +1 -8
  200. package/src/workflows/discover-workflows.ts +20 -2
  201. package/src/workflows/validate-workflow.ts +7 -1
  202. package/src/workflows/workflow-config.ts +17 -0
  203. package/src/workflows/workflow-serializer.ts +3 -0
  204. package/src/worktree/worktree-manager.ts +22 -0
  205. package/workflows/default.workflow.md +36 -26
  206. package/workflows/strict-fast-fix.workflow.md +26 -0
  207. package/src/agents/agent-search.ts +0 -98
  208. package/src/benchmark/benchmark-runner.ts +0 -313
  209. package/src/benchmark/feedback-loop.ts +0 -73
  210. package/src/config/resilient-parser.ts +0 -117
  211. package/src/extension/crew-vibes/cat-frames.ts +0 -18
  212. package/src/extension/result-watcher.ts +0 -139
  213. package/src/observability/exporters/prometheus-exporter.ts +0 -54
  214. package/src/observability/metric-retention.ts +0 -64
  215. package/src/runtime/compaction/compaction-summary.ts +0 -278
  216. package/src/runtime/errors/crew-errors.ts +0 -162
  217. package/src/runtime/live-session/intercom-bridge.ts +0 -187
  218. package/src/runtime/loop-gates.ts +0 -128
  219. package/src/runtime/metric-parser.ts +0 -36
  220. package/src/runtime/output/stream-preview.ts +0 -184
  221. package/src/runtime/output/tool-progress.ts +0 -278
  222. package/src/runtime/phase-tracker.ts +0 -385
  223. package/src/runtime/pipeline-runner.ts +0 -523
  224. package/src/runtime/process/process-lifecycle.ts +0 -491
  225. package/src/runtime/recovery/retry-runner.ts +0 -330
  226. package/src/runtime/run-drift.ts +0 -219
  227. package/src/runtime/task-quality.ts +0 -199
  228. package/src/runtime/task-runner/run-projection.ts +0 -128
  229. package/src/runtime/verification/post-checks.ts +0 -142
  230. package/src/state/coordination/schedule.ts +0 -166
  231. package/src/state/event-log/jsonl-writer.ts +0 -115
  232. package/src/state/hook-instinct-bridge.ts +0 -94
  233. package/src/state/hook-integrations.ts +0 -51
  234. package/src/state/session-state-map.ts +0 -51
  235. package/src/state/stores/blob-store.ts +0 -308
  236. package/src/state/stores/instinct-store.ts +0 -275
  237. package/src/state/stores/observation-store.ts +0 -176
  238. package/src/state/tiered-eval.ts +0 -480
  239. package/src/state/types-eval.ts +0 -58
  240. package/src/tools/safe-bash-extension.ts +0 -54
  241. package/src/tools/safe-bash.ts +0 -505
  242. package/src/ui/agent-management-overlay.ts +0 -160
  243. package/src/ui/crew-footer.ts +0 -102
  244. package/src/ui/crew-select-list.ts +0 -114
  245. package/src/ui/dashboard-panes/capability-pane.ts +0 -77
  246. package/src/ui/transcript-entries.ts +0 -256
  247. package/src/utils/conflict-detect.ts +0 -721
  248. package/src/utils/fingerprint.ts +0 -180
  249. package/src/utils/gh-protocol.ts +0 -556
  250. package/src/utils/project-detector.ts +0 -160
  251. package/src/utils/sse-parser.ts +0 -131
  252. package/src/workflows/cost-estimator.ts +0 -34
  253. package/src/workflows/intermediate-store.ts +0 -166
@@ -1,313 +0,0 @@
1
- /**
2
- * Benchmark runner - agent-eval inspired benchmarking system.
3
- * Provides tiered evaluation for workflow tasks.
4
- */
5
-
6
- import { execFileSync } from "node:child_process";
7
-
8
- export interface BenchmarkJudge {
9
- type: "pytest" | "grep" | "command";
10
- command?: string;
11
- pattern?: string;
12
- description: string;
13
- }
14
-
15
- export interface BenchmarkTask {
16
- id: string;
17
- name: string;
18
- prompt: string;
19
- judges: BenchmarkJudge[];
20
- /** Optional task-type label used for aggregate metrics grouping. */
21
- taskType?: string;
22
- }
23
-
24
- export interface BenchmarkResult {
25
- taskId: string;
26
- /** Task-type label for aggregation grouping. */
27
- taskType?: string;
28
- passed: boolean;
29
- judgeResults: { description: string; passed: boolean; output?: string }[];
30
- durationMs: number;
31
- /** Estimated cost in dollars (0 if not tracked). */
32
- cost: number;
33
- }
34
-
35
- /**
36
- * Validate command against allowlist to prevent shell injection.
37
- * Only allows specific safe commands with arguments.
38
- */
39
- /**
40
- * Validate command against allowlist to prevent shell injection.
41
- * Uses comprehensive shell metacharacter blocking similar to safe-bash.ts.
42
- */
43
- function validateCommand(command: string): void {
44
- // Basic allowlist - must start with an allowed command.
45
- // SECURITY (H-7): `npx`/`node` were removed because they enable arbitrary code
46
- // execution without any shell metacharacter (e.g. `npx --yes evil-package`
47
- // or `node -e "require('fs')…"`). Use `npm test`/`npm run …` instead of raw
48
- // `node`/`npx` in benchmark task definitions.
49
- // `echo` is allowed because the metachar blocker (validateGateCommand) rejects
50
- // command substitution (`$(...)`, backticks), so `echo $(evil)` cannot run;
51
- // bare `echo …` only prints. It's the canonical exit-0 command used in
52
- // benchmark fixtures across Linux/macOS/Windows(sh).
53
- const allowlist = /^(pytest|grep|npm test|cargo test|cargo clippy|echo) /;
54
- if (!allowlist.test(command)) {
55
- throw new Error(`Command not allowed: ${command}. Only pytest, grep, npm test, cargo test/clippy, echo allowed.`);
56
- }
57
-
58
- // Block shell metacharacters after command name
59
- const afterCommand = command.substring(command.indexOf(" ") + 1);
60
-
61
- // Block dangerous shell metacharacters
62
- const dangerousPatterns = [
63
- /[;&|`$(){}[\]<>\\]/, // Shell metacharacters
64
- /\$\([^)]*\)/, // Command substitution $(...)
65
- /`[^`]*`/, // Backtick command substitution
66
- /\|/, // Pipe
67
- /&&/, // And
68
- /\|\|/, // Or
69
- />>/, // Append redirect
70
- /2>&1/, // stderr redirect
71
- />/, // Output redirect
72
- /</, // Input redirect
73
- ];
74
-
75
- for (const pattern of dangerousPatterns) {
76
- if (pattern.test(afterCommand)) {
77
- throw new Error(`Shell metacharacters not allowed in command arguments`);
78
- }
79
- }
80
- }
81
-
82
- /**
83
- * Run a single benchmark task with tiered judges.
84
- * Tier 1: pytest (fast, deterministic)
85
- * Tier 2: grep pattern matching
86
- * Tier 3: command execution
87
- * Fails fast on first tier failure.
88
- */
89
- function splitCommand(command: string): { program: string; args: string[] } {
90
- // Naive split on whitespace. validateCommand already rejects shell
91
- // metacharacters, so a simple split is safe.
92
- const parts = command.trim().split(/\s+/);
93
- if (parts.length === 0) {
94
- throw new Error("Empty command");
95
- }
96
- return { program: parts[0]!, args: parts.slice(1) };
97
- }
98
-
99
- export async function runBenchmark(task: BenchmarkTask): Promise<BenchmarkResult> {
100
- const startTime = Date.now();
101
- const judgeResults: BenchmarkResult["judgeResults"] = [];
102
-
103
- for (const judge of task.judges) {
104
- try {
105
- let passed = false;
106
- let output: string | undefined;
107
-
108
- if (judge.type === "pytest" && judge.command) {
109
- // Validate command before execution (defense-in-depth)
110
- validateCommand(judge.command);
111
- // Use execFileSync to avoid shell parsing. validateCommand
112
- // already rejects metacharacters, so a simple split is safe.
113
- const { program, args } = splitCommand(judge.command);
114
- // Tier 1: pytest - fast deterministic check
115
- output = execFileSync(program, args, {
116
- timeout: 5000,
117
- encoding: "utf-8",
118
- cwd: process.cwd(),
119
- });
120
- // Look for pytest summary line with passed count
121
- passed = output.includes("passed");
122
- } else if (judge.type === "grep" && judge.pattern && judge.command) {
123
- // Validate command before execution (defense-in-depth)
124
- validateCommand(judge.command);
125
- const { program, args } = splitCommand(judge.command);
126
- // Tier 2: grep pattern matching
127
- output = execFileSync(program, args, {
128
- timeout: 5000,
129
- encoding: "utf-8",
130
- cwd: process.cwd(),
131
- });
132
- passed = output.includes(judge.pattern);
133
- } else if (judge.type === "command" && judge.command) {
134
- // Validate command before execution (defense-in-depth)
135
- validateCommand(judge.command);
136
- const { program, args } = splitCommand(judge.command);
137
- // Tier 3: command execution
138
- output = execFileSync(program, args, {
139
- timeout: 10000,
140
- encoding: "utf-8",
141
- cwd: process.cwd(),
142
- });
143
- passed = true; // Command succeeded = pass
144
- }
145
-
146
- judgeResults.push({
147
- description: judge.description,
148
- passed: passed ?? false,
149
- output,
150
- });
151
- } catch (e: unknown) {
152
- const error = e as { message?: string };
153
- judgeResults.push({
154
- description: judge.description,
155
- passed: false,
156
- output: error.message ?? String(e),
157
- });
158
- }
159
- }
160
-
161
- return {
162
- taskId: task.id,
163
- passed: judgeResults.every((j) => j.passed),
164
- judgeResults,
165
- durationMs: Date.now() - startTime,
166
- cost: 0,
167
- taskType: task.taskType,
168
- };
169
- }
170
-
171
- /**
172
- * Aggregate metrics computed over a group of benchmark results for a single task type.
173
- */
174
- export interface BenchmarkMetrics {
175
- taskType: string;
176
- totalTasks: number;
177
- passedTasks: number;
178
- /** Ratio of passed/total (0–1). */
179
- passRate: number;
180
- /** Mean execution duration in milliseconds. */
181
- avgTimeMs: number;
182
- /** Total estimated cost in dollars across all tasks. */
183
- totalCost: number;
184
- /** Mean cost in dollars per task. */
185
- avgCost: number;
186
- }
187
-
188
- /**
189
- * Per-task-type aggregate metrics map.
190
- * Keys are task-type labels; "__default__" is used when a task has no label.
191
- */
192
- export type AggregateMetrics = Record<string, BenchmarkMetrics>;
193
-
194
- /**
195
- * Run multiple benchmark tasks and aggregate results.
196
- *
197
- * @param tasks - Benchmark tasks to execute. Each task may carry a `taskType` label.
198
- * @param taskTypes - Optional subset of task-type labels to run. If provided, only tasks
199
- * whose `taskType` is in this set will be executed. If omitted, all tasks run.
200
- */
201
- export async function runBenchmarkSuite(
202
- tasks: BenchmarkTask[],
203
- taskTypes?: string[],
204
- ): Promise<{
205
- results: BenchmarkResult[];
206
- totalPassed: number;
207
- totalFailed: number;
208
- totalDurationMs: number;
209
- totalCost: number;
210
- }> {
211
- const filtered = taskTypes ? tasks.filter((t) => t.taskType && taskTypes.includes(t.taskType)) : tasks;
212
-
213
- const results: BenchmarkResult[] = [];
214
-
215
- for (const task of filtered) {
216
- const result = await runBenchmark(task);
217
- results.push(result);
218
- }
219
-
220
- const totalPassed = results.filter((r) => r.passed).length;
221
- const totalFailed = results.length - totalPassed;
222
- const totalDurationMs = results.reduce((a, b) => a + b.durationMs, 0);
223
- const totalCost = results.reduce((a, b) => a + b.cost, 0);
224
-
225
- return { results, totalPassed, totalFailed, totalDurationMs, totalCost };
226
- }
227
-
228
- /**
229
- * Aggregate benchmark results into per-task-type metrics.
230
- *
231
- * @param results - Raw benchmark results (may include any task-type mix).
232
- * @returns A map from task-type label to `BenchmarkMetrics`. Tasks with no label
233
- * are grouped under `"__default__"`.
234
- */
235
- export function aggregateBenchmarkMetrics(results: BenchmarkResult[]): AggregateMetrics {
236
- const buckets: Record<string, BenchmarkResult[]> = {};
237
-
238
- for (const result of results) {
239
- const key = result.taskType ?? "__default__";
240
- if (!buckets[key]) buckets[key] = [];
241
- buckets[key].push(result);
242
- }
243
-
244
- const metrics: AggregateMetrics = {};
245
-
246
- for (const [taskType, group] of Object.entries(buckets)) {
247
- const totalTasks = group.length;
248
- const passedTasks = group.filter((r) => r.passed).length;
249
- const passRate = totalTasks > 0 ? passedTasks / totalTasks : 0;
250
- const avgTimeMs = totalTasks > 0 ? group.reduce((s, r) => s + r.durationMs, 0) / totalTasks : 0;
251
- const totalCost = group.reduce((s, r) => s + r.cost, 0);
252
- const avgCost = totalTasks > 0 ? totalCost / totalTasks : 0;
253
-
254
- metrics[taskType] = {
255
- taskType,
256
- totalTasks,
257
- passedTasks,
258
- passRate: Math.round(passRate * 1000) / 1000,
259
- avgTimeMs: Math.round(avgTimeMs),
260
- totalCost: Math.round(totalCost * 1e6) / 1e6,
261
- avgCost: Math.round(avgCost * 1e6) / 1e6,
262
- };
263
- }
264
-
265
- return metrics;
266
- }
267
-
268
- /**
269
- * Generate a markdown comparison table for benchmark results including per-type aggregates.
270
- *
271
- * @param results - Benchmark results to report.
272
- * @param includeTaskTypeComparison - When true (default), appends a per-task-type aggregate table.
273
- */
274
- export function generateBenchmarkReport(results: BenchmarkResult[], includeTaskTypeComparison = true): string {
275
- const lines: string[] = ["# Benchmark Results", ""];
276
-
277
- lines.push("| Task | Type | Status | Duration | Cost |");
278
- lines.push("|------|------|--------|---------|------|");
279
-
280
- for (const r of results) {
281
- const status = r.passed ? "✅ PASS" : "❌ FAIL";
282
- const type = r.taskType ?? "—";
283
- const cost = r.cost > 0 ? `$${r.cost.toFixed(4)}` : "—";
284
- lines.push(`| ${r.taskId} | ${type} | ${status} | ${r.durationMs}ms | ${cost} |`);
285
- }
286
-
287
- lines.push("");
288
-
289
- // Per-type aggregate table.
290
- if (includeTaskTypeComparison && results.length > 0) {
291
- const metrics = aggregateBenchmarkMetrics(results);
292
- const types = Object.keys(metrics).sort();
293
-
294
- if (types.length > 0) {
295
- lines.push("## Per-Task-Type Comparison", "");
296
- lines.push("| Task Type | Total | Passed | Pass Rate | Avg Time | Avg Cost |");
297
- lines.push("|-----------|-------|--------|-----------|----------|---------|");
298
-
299
- for (const t of types) {
300
- const m = metrics[t];
301
- const passRatePct = `${(m.passRate * 100).toFixed(1)}%`;
302
- const avgCostStr = m.avgCost > 0 ? `$${m.avgCost.toFixed(4)}` : "—";
303
- lines.push(`| ${m.taskType} | ${m.totalTasks} | ${m.passedTasks} | ${passRatePct} | ${m.avgTimeMs}ms | ${avgCostStr} |`);
304
- }
305
- }
306
- }
307
-
308
- const passed = results.filter((r) => r.passed).length;
309
- lines.push("");
310
- lines.push(`**Total: ${passed}/${results.length} passed**`);
311
-
312
- return lines.join("\n");
313
- }
@@ -1,73 +0,0 @@
1
- /**
2
- * Feedback loop - continuous improvement cycle: evaluate → learn → apply → re-evaluate
3
- */
4
-
5
- import type { RunMetrics } from "../state/stores/run-metrics.ts";
6
-
7
- /** @internal */
8
- interface FeedbackLoopStats {
9
- runsObserved: number;
10
- avgSuccessRate: number;
11
- recommendations: string[];
12
- }
13
-
14
- /** @internal */
15
- class FeedbackLoop {
16
- private runs: RunMetrics[] = [];
17
- private static readonly MAX_RUNS = 1000;
18
-
19
- /**
20
- * Record a run's metrics for learning.
21
- */
22
- recordRun(metrics: RunMetrics): void {
23
- this.runs.push(metrics);
24
- // Trim to MAX_RUNS to prevent unbounded memory growth
25
- if (this.runs.length > FeedbackLoop.MAX_RUNS) {
26
- this.runs = this.runs.slice(-FeedbackLoop.MAX_RUNS);
27
- }
28
- }
29
-
30
- /**
31
- * Get current statistics and recommendations.
32
- */
33
- getStats(): FeedbackLoopStats {
34
- if (this.runs.length === 0) {
35
- return {
36
- runsObserved: 0,
37
- avgSuccessRate: 0,
38
- recommendations: ["No runs observed yet. Run some workflows to gather data."],
39
- };
40
- }
41
-
42
- const successRates = this.runs.map((r) => (r.taskCount > 0 ? r.completedCount / r.taskCount : 0));
43
- const avg = successRates.reduce((a, b) => a + b, 0) / successRates.length;
44
-
45
- const recommendations: string[] = [];
46
- if (avg >= 0.9) {
47
- recommendations.push(`High success rate (${(avg * 100).toFixed(0)}%). Current configuration is working well.`);
48
- } else if (avg >= 0.7) {
49
- recommendations.push(`Moderate success rate (${(avg * 100).toFixed(0)}%). Consider reviewing failed tasks for patterns.`);
50
- } else {
51
- recommendations.push(`Low success rate (${(avg * 100).toFixed(0)}%). Investigate failure patterns.`);
52
- }
53
-
54
- // Cost awareness
55
- const avgCost = this.runs.reduce((a, b) => a + b.totalCost, 0) / this.runs.length;
56
- if (avgCost > 10) {
57
- recommendations.push(`Average cost per run: $${avgCost.toFixed(2)}. Consider optimization.`);
58
- }
59
-
60
- return {
61
- runsObserved: this.runs.length,
62
- avgSuccessRate: avg,
63
- recommendations,
64
- };
65
- }
66
-
67
- /**
68
- * Clear recorded runs.
69
- */
70
- clear(): void {
71
- this.runs = [];
72
- }
73
- }
@@ -1,117 +0,0 @@
1
- /**
2
- * Per-field resilient config parsing — continues on error, collects all field-level issues.
3
- */
4
-
5
- import type { TSchema } from "@sinclair/typebox";
6
- import { Value } from "@sinclair/typebox/value";
7
- import { PiTeamsConfigSchema } from "../schema/config-schema.ts";
8
- import { type PiTeamsConfig, parseConfig } from "./config.ts";
9
- import { suggestConfigKey } from "./suggestions.ts";
10
-
11
- // ---------------------------------------------------------------------------
12
- // Types
13
- // ---------------------------------------------------------------------------
14
-
15
- export interface FieldError {
16
- field: string;
17
- message: string;
18
- value: unknown;
19
- suggestion?: string;
20
- }
21
-
22
- export interface ResilientParseResult {
23
- config: Record<string, unknown>;
24
- errors: FieldError[];
25
- warnings: string[];
26
- valid: boolean;
27
- }
28
-
29
- // ---------------------------------------------------------------------------
30
- // Helpers
31
- // ---------------------------------------------------------------------------
32
-
33
- const KNOWN_TOP_LEVEL_KEYS: readonly string[] = Object.keys(PiTeamsConfigSchema.properties ?? {});
34
-
35
- function isObject(value: unknown): value is Record<string, unknown> {
36
- return value !== null && typeof value === "object" && !Array.isArray(value);
37
- }
38
-
39
- // ---------------------------------------------------------------------------
40
- // Implementation
41
- // ---------------------------------------------------------------------------
42
-
43
- /**
44
- * Parse a raw config value field-by-field.
45
- *
46
- * - Each top-level key is validated independently via TypeBox sub-schemas.
47
- * - Fields that fail are recorded as errors but do not block others.
48
- * - Unknown keys get a fuzzy suggestion via Levenshtein distance.
49
- * - The returned `config` contains only successfully-parsed fields (via `parseConfig`).
50
- */
51
- export function parseConfigResilient(raw: unknown): ResilientParseResult {
52
- const errors: FieldError[] = [];
53
- const warnings: string[] = [];
54
-
55
- if (!isObject(raw)) {
56
- return {
57
- config: {},
58
- errors: [
59
- {
60
- field: "config",
61
- message: "config must be an object",
62
- value: raw,
63
- },
64
- ],
65
- warnings,
66
- valid: false,
67
- };
68
- }
69
-
70
- // Collect unknown top-level keys with suggestions
71
- for (const key of Object.keys(raw)) {
72
- if (!KNOWN_TOP_LEVEL_KEYS.includes(key)) {
73
- const suggestion = suggestConfigKey(key, KNOWN_TOP_LEVEL_KEYS);
74
- errors.push({
75
- field: key,
76
- message: `unknown config key '${key}'`,
77
- value: raw[key],
78
- suggestion: suggestion ?? undefined,
79
- });
80
- }
81
- }
82
-
83
- // Use TypeBox per-field validation for known keys
84
- for (const key of KNOWN_TOP_LEVEL_KEYS) {
85
- if (!(key in raw)) continue;
86
- const value = raw[key];
87
- const subSchema = (PiTeamsConfigSchema.properties as Record<string, unknown>)[key];
88
- if (subSchema && !Value.Check(subSchema as TSchema, value)) {
89
- // Collect ALL errors for this field
90
- const fieldErrors = [...Value.Errors(subSchema as TSchema, value)];
91
- for (const err of fieldErrors) {
92
- const errObj = err as unknown as Record<string, unknown>;
93
- const msg = typeof errObj.message === "string" ? errObj.message : "invalid value";
94
- errors.push({
95
- field: key,
96
- message: msg,
97
- value,
98
- });
99
- }
100
- }
101
- }
102
-
103
- // Build the valid subset using existing parseConfig (which silently drops invalid fields)
104
- const parsed: PiTeamsConfig = parseConfig(raw);
105
- const config: Record<string, unknown> = {};
106
- for (const key of Object.keys(parsed)) {
107
- const val = (parsed as Record<string, unknown>)[key];
108
- if (val !== undefined) config[key] = val;
109
- }
110
-
111
- return {
112
- config,
113
- errors,
114
- warnings,
115
- valid: errors.length === 0,
116
- };
117
- }
@@ -1,18 +0,0 @@
1
- /**
2
- * ANSI art cat animation frames extracted from runner-spritesheet.png.
3
- * Used when PUA font glyphs are not available (web terminals like gotty).
4
- * Each frame is an array of strings (one per line).
5
- */
6
- export const CAT_FRAMES: readonly string[][] = [
7
- // Frame 0 — standing
8
- ["▄▄ ███▄ ", "▀▀█████▄", " ██▀██ ", " ▀▀ ▀▀"],
9
- // Frame 1 — step 1
10
- [" ████ ", " █████▄", "▄██████▀", " ██ ▀█▄"],
11
- // Frame 2 — step 2
12
- [" ▄██████", " █████▀ ", "███████ ", "▀██████ "],
13
- // Frame 3 — step 3
14
- [" ████ ", "▄█████▄ ", "▀██████▄", "▄█▀ ██ "],
15
- ] as const;
16
-
17
- /** Number of animation frames. */
18
- export const CAT_FRAME_COUNT = CAT_FRAMES.length;
@@ -1,139 +0,0 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
- import { buildCompletionKey, getGlobalSeenMap, markSeenWithTtl } from "../utils/completion-dedupe.ts";
4
- import { createFileCoalescer } from "../utils/file-coalescer.ts";
5
- import { closeWatcher, watchWithErrorHandler } from "../utils/fs-watch.ts";
6
- import { logInternalError } from "../utils/internal-error.ts";
7
-
8
- export interface ResultWatcherEvents {
9
- emit(event: string, data: unknown): void;
10
- }
11
-
12
- export interface ResultWatcherHandle {
13
- start(): void;
14
- prime(): void;
15
- stop(): void;
16
- }
17
-
18
- interface ResultWatcherDependencies {
19
- watch?: typeof watchWithErrorHandler;
20
- }
21
-
22
- export interface ResultWatcherOptions extends ResultWatcherDependencies {
23
- eventName?: string;
24
- completionTtlMs?: number;
25
- isCurrent?: () => boolean;
26
- }
27
-
28
- const RESULT_WATCHER_RESTART_MS = 3000;
29
- const RESULT_WATCHER_POLL_MS = 1000;
30
-
31
- function shouldFallBackToPolling(error: unknown): boolean {
32
- const code = error && typeof error === "object" ? (error as { code?: unknown }).code : undefined;
33
- return code === "EMFILE" || code === "ENOSPC" || code === "EPERM";
34
- }
35
-
36
- function readJson(filePath: string): unknown | undefined {
37
- try {
38
- return JSON.parse(fs.readFileSync(filePath, "utf-8")) as unknown;
39
- } catch (error) {
40
- logInternalError("result-watcher.parse", error, `filePath=${filePath}`);
41
- return undefined;
42
- }
43
- }
44
-
45
- export function createResultWatcher(
46
- events: ResultWatcherEvents,
47
- resultsDir: string,
48
- eventNameOrOptions: string | ResultWatcherOptions = "pi-crew:run-result",
49
- ): ResultWatcherHandle {
50
- const options: ResultWatcherOptions = typeof eventNameOrOptions === "string" ? { eventName: eventNameOrOptions } : eventNameOrOptions;
51
- const eventName = options.eventName ?? "pi-crew:run-result";
52
- const completionTtlMs = options.completionTtlMs ?? 5 * 60_000;
53
- const watch = options.watch ?? watchWithErrorHandler;
54
- const isCurrent = options.isCurrent ?? (() => true);
55
- const seen = getGlobalSeenMap("pi-crew.result-watcher");
56
- let watcher: fs.FSWatcher | null | undefined;
57
- let restartTimer: ReturnType<typeof setTimeout> | undefined;
58
- let pollTimer: ReturnType<typeof setInterval> | undefined;
59
- const coalescer = createFileCoalescer((file) => {
60
- if (!isCurrent()) return;
61
- const filePath = path.join(resultsDir, file);
62
- if (!file.endsWith(".json") || !fs.existsSync(filePath)) return;
63
- const payload = readJson(filePath);
64
- if (payload === undefined) {
65
- coalescer.schedule(file, RESULT_WATCHER_POLL_MS);
66
- return;
67
- }
68
- const key = buildCompletionKey(
69
- payload && typeof payload === "object" && !Array.isArray(payload) ? (payload as Record<string, unknown>) : {},
70
- `file:${file}`,
71
- );
72
- if (!markSeenWithTtl(seen, key, Date.now(), completionTtlMs)) {
73
- events.emit(eventName, payload);
74
- }
75
- try {
76
- fs.unlinkSync(filePath);
77
- } catch (error) {
78
- logInternalError("result-watcher.unlink", error, `filePath=${filePath}`);
79
- }
80
- }, 50);
81
- const poll = () => {
82
- if (!isCurrent() || !fs.existsSync(resultsDir)) return;
83
- for (const file of fs.readdirSync(resultsDir).filter((entry) => entry.endsWith(".json"))) coalescer.schedule(file, 0);
84
- };
85
- const startPolling = () => {
86
- if (pollTimer) return;
87
- pollTimer = setInterval(poll, RESULT_WATCHER_POLL_MS);
88
- pollTimer.unref();
89
- poll();
90
- };
91
- const stopPolling = () => {
92
- if (pollTimer) clearInterval(pollTimer);
93
- pollTimer = undefined;
94
- };
95
- const scheduleRestart = (error?: unknown) => {
96
- if (shouldFallBackToPolling(error)) startPolling();
97
- if (restartTimer) clearTimeout(restartTimer);
98
- restartTimer = setTimeout(() => {
99
- restartTimer = undefined;
100
- try {
101
- if (!isCurrent()) return;
102
- fs.mkdirSync(resultsDir, { recursive: true });
103
- handle.start();
104
- } catch (error) {
105
- logInternalError("result-watcher.restart", error, `resultsDir=${resultsDir}`);
106
- }
107
- }, RESULT_WATCHER_RESTART_MS);
108
- restartTimer.unref();
109
- };
110
- const handle: ResultWatcherHandle = {
111
- start() {
112
- if (!isCurrent()) return;
113
- fs.mkdirSync(resultsDir, { recursive: true });
114
- if (watcher) closeWatcher(watcher);
115
- watcher = watch(
116
- resultsDir,
117
- (event, fileName) => {
118
- if (event !== "rename" || !fileName) return;
119
- coalescer.schedule(fileName.toString());
120
- },
121
- scheduleRestart,
122
- );
123
- if (watcher) stopPolling();
124
- watcher?.unref();
125
- },
126
- prime() {
127
- poll();
128
- },
129
- stop() {
130
- if (restartTimer) clearTimeout(restartTimer);
131
- restartTimer = undefined;
132
- closeWatcher(watcher);
133
- watcher = undefined;
134
- stopPolling();
135
- coalescer.clear();
136
- },
137
- };
138
- return handle;
139
- }