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,115 +0,0 @@
1
- import * as fs from "node:fs";
2
- import { logInternalError } from "../../utils/internal-error.ts";
3
- import { redactJsonLine } from "../../utils/redaction.ts";
4
-
5
- export interface DrainableSource {
6
- pause(): void;
7
- resume(): void;
8
- }
9
-
10
- export interface JsonlWriteStream {
11
- write(chunk: string): boolean;
12
- once(event: "drain", listener: () => void): JsonlWriteStream;
13
- end(callback?: () => void): void;
14
- }
15
-
16
- const DEFAULT_MAX_JSONL_BYTES = 50 * 1024 * 1024;
17
- // FIX (Round 21, per-line cap): A single huge line could exhaust memory during
18
- // redactJsonLine if an upstream caller constructs an enormous string. Cap each
19
- // line at 1MB by default — large enough for any legitimate event payload, small
20
- // enough to prevent memory blow-up. Mirrors the upstream oh-my-pi pattern of
21
- // bounding chunk boundaries in Bun.file().writer().
22
- const DEFAULT_MAX_LINE_BYTES = 1 * 1024 * 1024;
23
-
24
- export interface JsonlWriterDeps {
25
- createWriteStream?: (filePath: string) => JsonlWriteStream;
26
- maxBytes?: number;
27
- maxLineBytes?: number;
28
- }
29
-
30
- export interface JsonlWriter {
31
- writeLine(line: string): void;
32
- close(): Promise<void>;
33
- }
34
-
35
- export function createJsonlWriter(filePath: string | undefined, source: DrainableSource, deps: JsonlWriterDeps = {}): JsonlWriter {
36
- if (!filePath) {
37
- return {
38
- writeLine() {
39
- /* no-op: null writer */
40
- },
41
- async close() {
42
- /* no-op: null writer */
43
- },
44
- };
45
- }
46
-
47
- const createWriteStream = deps.createWriteStream ?? ((targetPath: string) => fs.createWriteStream(targetPath, { flags: "a" }));
48
- let stream: JsonlWriteStream | undefined;
49
- try {
50
- stream = createWriteStream(filePath);
51
- } catch {
52
- return {
53
- writeLine() {
54
- /* no-op: stream creation failed */
55
- },
56
- async close() {
57
- /* no-op: stream creation failed */
58
- },
59
- };
60
- }
61
-
62
- let backpressured = false;
63
- let closed = false;
64
- let bytesWritten = 0;
65
- let linesDroppedForSize = 0;
66
- const maxBytes = deps.maxBytes ?? DEFAULT_MAX_JSONL_BYTES;
67
- const maxLineBytes = deps.maxLineBytes ?? DEFAULT_MAX_LINE_BYTES;
68
-
69
- return {
70
- writeLine(line: string) {
71
- if (!stream || closed || !line.trim()) return;
72
- const safeLine = redactJsonLine(line);
73
- const chunk = `${safeLine}\n`;
74
- const chunkBytes = Buffer.byteLength(chunk, "utf-8");
75
- // FIX (Round 21, per-line cap): Drop oversize lines. Without this, a
76
- // single huge payload (e.g. a 100MB base64-encoded transcript) would
77
- // be buffered in memory by redactJsonLine AND queued in the write
78
- // stream. We log the drop so silent loss is visible.
79
- if (chunkBytes > maxLineBytes) {
80
- linesDroppedForSize++;
81
- if (linesDroppedForSize === 1 || linesDroppedForSize % 100 === 0) {
82
- logInternalError(
83
- "jsonl-writer.lineTooLarge",
84
- new Error(`line size ${chunkBytes} exceeds maxLineBytes ${maxLineBytes}`),
85
- `file=${filePath} dropped=${linesDroppedForSize}`,
86
- );
87
- }
88
- return;
89
- }
90
- if (bytesWritten + chunkBytes > maxBytes) return;
91
- try {
92
- const ok = stream.write(chunk);
93
- bytesWritten += chunkBytes;
94
- if (!ok && !backpressured) {
95
- backpressured = true;
96
- source.pause();
97
- stream.once("drain", () => {
98
- backpressured = false;
99
- if (!closed) source.resume();
100
- });
101
- }
102
- } catch (writeError) {
103
- // Log the error — silently dropping events is dangerous.
104
- logInternalError("jsonl-writer.write", writeError, `file=${filePath}`);
105
- }
106
- },
107
- async close() {
108
- if (!stream || closed) return;
109
- closed = true;
110
- const current = stream;
111
- stream = undefined;
112
- await new Promise<void>((resolve) => current.end(() => resolve()));
113
- },
114
- };
115
- }
@@ -1,94 +0,0 @@
1
- /**
2
- * Hook-to-instinct bridge - connects crewHooks events to instinct formation.
3
- * Auto-initializes when imported.
4
- */
5
-
6
- import { crewHooks } from "../runtime/crew-hooks.ts";
7
-
8
- // Lazy-initialized store and paths
9
- let storeInstance: import("./stores/instinct-store.js").InstinctStore | null = null;
10
- let pathsInstance: typeof import("../utils/paths.js") | null = null;
11
-
12
- async function getStore() {
13
- if (!storeInstance) {
14
- // LAZY: defer dynamic import of ./instinct-store.js to its call site.
15
- const { InstinctStore } = await import("./stores/instinct-store.js");
16
- // LAZY: defer dynamic import of ../utils/paths.js to its call site.
17
- const paths = await import("../utils/paths.js");
18
- storeInstance = new InstinctStore(paths.projectCrewRoot(process.cwd()));
19
- }
20
- return storeInstance;
21
- }
22
-
23
- async function getPaths() {
24
- if (!pathsInstance) {
25
- // LAZY: defer dynamic import of ../utils/paths.js to its call site.
26
- pathsInstance = await import("../utils/paths.js");
27
- }
28
- return pathsInstance;
29
- }
30
-
31
- // Subscribe to events
32
- crewHooks.register("task_completed", async (event) => {
33
- try {
34
- const store = await getStore();
35
- if (event.data?.role) {
36
- store.saveInstinct({
37
- trigger: `role:${event.data.role}`,
38
- action: "prefer",
39
- confidence: 0.6,
40
- scope: "global",
41
- evidence: [`task:${event.taskId} completed`],
42
- });
43
- }
44
- } catch {
45
- // Best-effort - don't crash on instinct formation failures
46
- }
47
- });
48
-
49
- crewHooks.register("task_failed", async (event) => {
50
- try {
51
- const store = await getStore();
52
- if (event.data?.role) {
53
- store.saveInstinct({
54
- trigger: `role:${event.data.role}`,
55
- action: "avoid",
56
- confidence: 0.3,
57
- scope: "global",
58
- evidence: [`task:${event.taskId} failed`],
59
- });
60
- }
61
- } catch {
62
- // Best-effort
63
- }
64
- });
65
-
66
- crewHooks.register("run_completed", async (event) => {
67
- try {
68
- const store = await getStore();
69
- if (event.data?.taskCount) {
70
- store.saveInstinct({
71
- trigger: "run_completed",
72
- action: `completed:${event.data.taskCount}tasks`,
73
- confidence: 0.6,
74
- scope: "global",
75
- evidence: [`run:${event.runId}`],
76
- });
77
- }
78
- } catch {
79
- // Best-effort
80
- }
81
- });
82
-
83
- /**
84
- * Get instinct-based recommendations.
85
- */
86
- /** @internal */
87
- async function getInstinctRecommendations() {
88
- try {
89
- const store = await getStore();
90
- return store.getInstincts().filter((i: { confidence: number }) => i.confidence >= 0.6);
91
- } catch {
92
- return [];
93
- }
94
- }
@@ -1,51 +0,0 @@
1
- /**
2
- * Hook integrations - subscribes to crewHooks and provides observability.
3
- * Auto-initializes when imported.
4
- */
5
-
6
- import { crewHooks } from "../runtime/crew-hooks.ts";
7
-
8
- // Statistics
9
- let tasksCompleted = 0;
10
- let tasksFailed = 0;
11
- let runsCompleted = 0;
12
- let runsFailed = 0;
13
-
14
- // Subscribe to events (fire-and-forget)
15
- crewHooks.register("task_completed", () => {
16
- tasksCompleted++;
17
- });
18
-
19
- crewHooks.register("task_failed", () => {
20
- tasksFailed++;
21
- });
22
-
23
- crewHooks.register("run_completed", () => {
24
- runsCompleted++;
25
- });
26
-
27
- crewHooks.register("run_failed", () => {
28
- runsFailed++;
29
- });
30
-
31
- /**
32
- * Get current hook statistics.
33
- */
34
- export function getHookStats(): {
35
- tasksCompleted: number;
36
- tasksFailed: number;
37
- runsCompleted: number;
38
- runsFailed: number;
39
- } {
40
- return { tasksCompleted, tasksFailed, runsCompleted, runsFailed };
41
- }
42
-
43
- /**
44
- * Reset statistics (useful for testing).
45
- */
46
- export function resetHookStats(): void {
47
- tasksCompleted = 0;
48
- tasksFailed = 0;
49
- runsCompleted = 0;
50
- runsFailed = 0;
51
- }
@@ -1,51 +0,0 @@
1
- /**
2
- * Session-scoped state container.
3
- *
4
- * Generic Map keyed by session ID. Used by widget, dashboard, and
5
- * live-agent-manager to store per-session state without polluting globals.
6
- *
7
- * Inspired by @ayulab/pi-checkpoint SessionStateMap.
8
- */
9
- export class SessionStateMap<T> {
10
- private readonly map = new Map<string, T>();
11
-
12
- getOrUndefined(sessionId: string): T | undefined {
13
- return this.map.get(sessionId);
14
- }
15
-
16
- get(sessionId: string): T | undefined {
17
- return this.map.get(sessionId);
18
- }
19
-
20
- set(sessionId: string, value: T): void {
21
- this.map.set(sessionId, value);
22
- }
23
-
24
- has(sessionId: string): boolean {
25
- return this.map.has(sessionId);
26
- }
27
-
28
- delete(sessionId: string): boolean {
29
- return this.map.delete(sessionId);
30
- }
31
-
32
- clear(): void {
33
- this.map.clear();
34
- }
35
-
36
- get size(): number {
37
- return this.map.size;
38
- }
39
-
40
- entries(): IterableIterator<[string, T]> {
41
- return this.map.entries();
42
- }
43
-
44
- values(): IterableIterator<T> {
45
- return this.map.values();
46
- }
47
-
48
- keys(): IterableIterator<string> {
49
- return this.map.keys();
50
- }
51
- }
@@ -1,308 +0,0 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import * as fs from "node:fs";
3
- import * as path from "node:path";
4
- import { resolveRealContainedPath } from "../../utils/safe-paths.ts";
5
- import { atomicWriteFile, renameWithRetry } from "../atomic-write.ts";
6
- import { withFileLockSync } from "../coordination/locks.ts";
7
-
8
- const SHA256_HEX = /^[a-f0-9]{64}$/i;
9
-
10
- function validateBlobHash(hash: string, algorithm?: string): void {
11
- if (!SHA256_HEX.test(hash)) throw new Error(`Invalid blob hash: ${hash}`);
12
- if (algorithm !== undefined && algorithm !== SHA256_PREFIX) {
13
- throw new Error(`Invalid blob algorithm: ${algorithm} (expected ${SHA256_PREFIX})`);
14
- }
15
- }
16
-
17
- /**
18
- * Atomically write a Buffer to a file using temp-file + rename pattern.
19
- * Prevents partial writes on crash and handles concurrent writes safely.
20
- */
21
- function atomicWriteBuffer(filePath: string, content: Buffer): void {
22
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
23
- const tempPath = `${filePath}.${randomUUID()}.tmp`;
24
- const O_NOFOLLOW = typeof fs.constants.O_NOFOLLOW === "number" ? fs.constants.O_NOFOLLOW : 0;
25
- const fd = fs.openSync(tempPath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | O_NOFOLLOW, 0o600);
26
- try {
27
- const openedStat = fs.fstatSync(fd);
28
- if (!openedStat.isFile()) {
29
- throw new Error(`Refusing to write: opened path is not a regular file: ${tempPath}`);
30
- }
31
- fs.writeSync(fd, content, 0, content.length);
32
- renameWithRetry(tempPath, filePath);
33
- } catch (error) {
34
- try {
35
- fs.rmSync(tempPath, { force: true });
36
- } catch {
37
- /* best-effort */
38
- }
39
- throw error;
40
- } finally {
41
- // Always close fd; closeSync is safe to call even if fd was already closed
42
- try {
43
- fs.closeSync(fd);
44
- } catch {
45
- /* best-effort */
46
- }
47
- }
48
- }
49
-
50
- const BLOBS_DIR = "blobs";
51
- const BLOB_META_DIR = "blob-metadata";
52
- const SHA256_PREFIX = "sha256";
53
-
54
- /**
55
- * File-based lock for cross-process metadata write protection.
56
- * Uses withFileLockSync which provides O_EXCL atomic create + token-guarded release.
57
- */
58
- function withMetadataLock<T>(metadataPath: string, fn: () => T): T {
59
- return withFileLockSync(metadataPath, fn);
60
- }
61
-
62
- export interface BlobMetadata {
63
- blobHash: string;
64
- blobAlgorithm: string;
65
- runId: string;
66
- taskId?: string;
67
- mime: string;
68
- producer: string;
69
- originalPath: string;
70
- sizeBytes: number;
71
- redacted: boolean;
72
- retention: "run" | "project" | "temporary";
73
- createdAt: string;
74
- }
75
-
76
- export interface BlobWriteResult {
77
- hash: string;
78
- algorithm: string;
79
- blobPath: string;
80
- metadataPath: string;
81
- sizeBytes: number;
82
- }
83
-
84
- function sha256Of(content: string | Buffer): string {
85
- return createHash("sha256")
86
- .update(typeof content === "string" ? content : content)
87
- .digest("hex");
88
- }
89
-
90
- /**
91
- * Write content-addressed blob to the blobs directory under artifactsRoot.
92
- * Content is deduplicated by hash; metadata sidecar is always written.
93
- * FIX: Both content and metadata writes now use atomicWriteFile to prevent
94
- * partial writes on crash. The deduplication check is now advisory (the atomic
95
- * write handles concurrent writes correctly via O_EXCL temp file pattern).
96
- */
97
- export function writeBlob(
98
- artifactsRoot: string,
99
- input: {
100
- content: string | Buffer;
101
- runId: string;
102
- taskId?: string;
103
- mime?: string;
104
- producer: string;
105
- originalPath: string;
106
- redacted?: boolean;
107
- retention?: BlobMetadata["retention"];
108
- },
109
- ): BlobWriteResult {
110
- const content = input.content;
111
- const hash = sha256Of(content);
112
- const algorithm = SHA256_PREFIX;
113
- const blobDir = path.join(artifactsRoot, BLOBS_DIR, algorithm);
114
- const metaDir = path.join(artifactsRoot, BLOB_META_DIR);
115
- // Issue 2 fix: Validate parent directories are not symlinks before mkdirSync.
116
- // An attacker could plant a symlink before we create the directory, causing
117
- // blob content to be written to an attacker-controlled location.
118
- resolveRealContainedPath(artifactsRoot, blobDir);
119
- resolveRealContainedPath(artifactsRoot, metaDir);
120
- fs.mkdirSync(blobDir, { recursive: true });
121
- fs.mkdirSync(metaDir, { recursive: true });
122
-
123
- const blobPath = path.join(blobDir, hash);
124
- // Issue 6 fix: Validate blobPath BEFORE writing to ensure the path is safe.
125
- // If resolveRealContainedPath throws after the write, the blob may already
126
- // exist at an unexpected location. Validate first to prevent this.
127
- resolveRealContainedPath(artifactsRoot, blobPath);
128
- const metadata: BlobMetadata = {
129
- blobHash: hash,
130
- blobAlgorithm: algorithm,
131
- runId: input.runId,
132
- taskId: input.taskId,
133
- mime: input.mime ?? "text/plain",
134
- producer: input.producer,
135
- originalPath: input.originalPath,
136
- sizeBytes: Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content, "utf-8"),
137
- redacted: input.redacted ?? false,
138
- retention: input.retention ?? "run",
139
- createdAt: new Date().toISOString(),
140
- };
141
- const metadataPath = path.join(metaDir, `${hash}.json`);
142
-
143
- // Both content and metadata use atomic writes to prevent partial writes on crash.
144
- // Content is immutable and content-addressed (same hash = same content), so
145
- // concurrent writes to the same hash are safe. Metadata (mime, retention, etc.)
146
- // is protected by a per-hash lock to make the check-then-write atomic, preventing
147
- // concurrent writers from racing to write different metadata for the same hash.
148
- // Issue 3 fix: wrap metadata check-and-write in a lock to make it atomic.
149
- // Without the lock, two processes could read the same metadata concurrently,
150
- // both pass the check, and the second write would silently overwrite the first.
151
- // FIX: Write blob content FIRST, then metadata. If blob write fails, no orphan metadata.
152
- // Previous order was metadata first, then blob - causing orphan metadata on blob failure.
153
- let blobContentWritten = false;
154
- // Write blob content first (immutable, content-addressed)
155
- atomicWriteBuffer(blobPath, Buffer.isBuffer(content) ? content : Buffer.from(content, "utf-8"));
156
- blobContentWritten = true;
157
-
158
- // Metadata only after blob content is successfully written
159
- // Issue 3 fix: Use two-phase commit for metadata - write to temp file first,
160
- // then atomically rename to final location. This prevents orphan blobs if
161
- // the process crashes after blob write but before metadata rename.
162
- let metadataWritten = false;
163
- try {
164
- withMetadataLock(metadataPath, () => {
165
- try {
166
- const existingMeta = JSON.parse(fs.readFileSync(metadataPath, "utf-8")) as BlobMetadata;
167
- // Compare fields that indicate concurrent write with different metadata.
168
- // Note: taskId is intentionally NOT part of the conflict check because
169
- // it represents which task produced the blob and may legitimately differ
170
- // across processes (last-write-wins for taskId). If concurrent writes
171
- // have identical mime/retention/producer/originalPath but different
172
- // taskId, the conflict check passes and both writes succeed — the
173
- // final taskId reflects whichever write completed last.
174
- // Callers should not rely on taskId for correctness-critical decisions.
175
- if (
176
- existingMeta.mime !== metadata.mime ||
177
- existingMeta.retention !== metadata.retention ||
178
- existingMeta.producer !== metadata.producer ||
179
- existingMeta.originalPath !== metadata.originalPath
180
- ) {
181
- throw new Error(
182
- `Concurrent metadata write conflict for blob ${hash}: different metadata values detected. Existing: ${JSON.stringify(existingMeta)}, New: ${JSON.stringify(metadata)}`,
183
- );
184
- }
185
- } catch (err) {
186
- if (err instanceof Error && err.message.includes("ENOENT")) {
187
- // OK - metadata doesn't exist yet, proceed to write
188
- } else {
189
- // Re-throw non-ENOENT errors (e.g., permission denied, corrupt file)
190
- throw err;
191
- }
192
- }
193
- // Issue 3 fix: Two-phase commit for metadata
194
- // Write to temp file first, then atomically rename to final location.
195
- // Issue 1 fix: Use atomicWriteFile instead of plain writeSync for the temp file
196
- // to prevent partial writes on crash. atomicWriteFile uses O_EXCL + write + rename
197
- // pattern which is consistent with how blob content is written.
198
- const tempMetaPath = `${metadataPath}.${randomUUID()}.tmp`;
199
- atomicWriteFile(tempMetaPath, JSON.stringify(metadata, null, 2));
200
- renameWithRetry(tempMetaPath, metadataPath);
201
- metadataWritten = true;
202
- });
203
- } catch (error) {
204
- // Round 24 (BUG 4 note): the catch block previously checked
205
- // `if (!blobContentWritten)` — the WRONG variable (the local comment said
206
- // `metadataWritten === false`). For a CONTENT-ADDRESSED store the blob path
207
- // is the content hash, so the blob may be referenced by another process's
208
- // metadata even when OUR metadata write failed (e.g. a concurrent conflict
209
- // where the peer already wrote metadata for the same hash). Deleting it
210
- // would orphan their metadata. The safe behavior is therefore to NEVER
211
- // delete on a metadata write failure and let the periodic
212
- // cleanupOrphanedBlobs() reclaim genuinely-orphaned blobs. The guard below
213
- // only removes a blob when its CONTENT was never written (a stray/partial
214
- // file from a failed content write) — which is the only unambiguously-safe
215
- // case to clean up here.
216
- if (!blobContentWritten) {
217
- try {
218
- fs.rmSync(blobPath, { force: true });
219
- } catch {
220
- /* best-effort */
221
- }
222
- }
223
- throw error;
224
- }
225
-
226
- // Issue 2 fix: resolve paths before writes and return cached values
227
- const resolvedBlobPath = resolveRealContainedPath(artifactsRoot, blobPath);
228
- const resolvedMetadataPath = resolveRealContainedPath(artifactsRoot, metadataPath);
229
- return {
230
- hash,
231
- algorithm,
232
- blobPath: resolvedBlobPath,
233
- metadataPath: resolvedMetadataPath,
234
- sizeBytes: metadata.sizeBytes,
235
- };
236
- }
237
-
238
- /**
239
- * Read a content-addressed blob by hash.
240
- * Validates hash format and enforces path containment.
241
- */
242
- export function readBlob(artifactsRoot: string, hash: string): Buffer | undefined {
243
- validateBlobHash(hash);
244
- try {
245
- const blobDir = path.join(artifactsRoot, BLOBS_DIR, SHA256_PREFIX);
246
- const blobPath = resolveRealContainedPath(blobDir, hash);
247
- return fs.readFileSync(blobPath);
248
- } catch {
249
- return undefined;
250
- }
251
- }
252
-
253
- /**
254
- * Read blob metadata by hash.
255
- * Validates hash format and enforces path containment.
256
- */
257
- export function readBlobMetadata(artifactsRoot: string, hash: string): BlobMetadata | undefined {
258
- validateBlobHash(hash);
259
- try {
260
- const metaDir = path.join(artifactsRoot, BLOB_META_DIR);
261
- const metaPath = resolveRealContainedPath(metaDir, `${hash}.json`);
262
- return JSON.parse(fs.readFileSync(metaPath, "utf-8")) as BlobMetadata;
263
- } catch {
264
- return undefined;
265
- }
266
- }
267
- /**
268
- * Cleanup orphaned blobs - blobs without corresponding metadata entries.
269
- * Called periodically to reclaim storage from blobs that were written but whose
270
- * metadata write failed (e.g., crash between content and metadata write).
271
- * Returns the number of orphaned blobs cleaned up.
272
- */
273
- export function cleanupOrphanedBlobs(artifactsRoot: string): number {
274
- const blobDir = path.join(artifactsRoot, BLOBS_DIR, SHA256_PREFIX);
275
- const metaDir = path.join(artifactsRoot, BLOB_META_DIR);
276
-
277
- let cleaned = 0;
278
- try {
279
- const blobFiles = fs.readdirSync(blobDir);
280
- for (const blobFile of blobFiles) {
281
- // Skip non-hash files (e.g., temp files from atomicWriteBuffer)
282
- if (!SHA256_HEX.test(blobFile)) continue;
283
-
284
- const metaPath = path.join(metaDir, `${blobFile}.json`);
285
- // Issue 4 fix: Use lock to prevent race between stat and delete.
286
- // A concurrent process could write metadata between stat and delete,
287
- // causing valid blob to be deleted while metadata remains.
288
- withMetadataLock(metaPath, () => {
289
- try {
290
- fs.statSync(metaPath);
291
- // Metadata exists - blob is not orphaned
292
- } catch {
293
- // Metadata does not exist - blob is orphaned, delete it
294
- const blobPath = path.join(blobDir, blobFile);
295
- try {
296
- fs.rmSync(blobPath, { force: true });
297
- cleaned++;
298
- } catch {
299
- // Best-effort cleanup - continue to next blob
300
- }
301
- }
302
- });
303
- }
304
- } catch {
305
- // Blobs directory doesn't exist or inaccessible - nothing to clean
306
- }
307
- return cleaned;
308
- }