@tea-agent/loop-agent 0.39.3 → 0.40.0-beta.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 (223) hide show
  1. package/CHANGELOG.md +135 -92
  2. package/dist/adapters/context-transfer/optional-pi-handoff.js +31 -0
  3. package/dist/adapters/context-transfer/pi-session.js +61 -0
  4. package/dist/build-stamp.json +3 -3
  5. package/dist/cli/command-definitions.js +12 -0
  6. package/dist/cli/program.js +23 -1
  7. package/dist/commands/dag-artifact.js +284 -0
  8. package/dist/commands/dag-context.js +184 -0
  9. package/dist/commands/dag-rerun.js +206 -1
  10. package/dist/executors/dag-pi-executor.js +108 -19
  11. package/dist/executors/pi-executor.js +4 -2
  12. package/dist/executors/pi-sdk-executor.js +49 -1
  13. package/dist/executors/pi-writer-tool-policy.js +57 -1
  14. package/dist/executors/shell-executor.js +42 -2
  15. package/dist/executors/workspace-write-snapshot.js +68 -0
  16. package/dist/{worker → infrastructure}/console/app-data.js +4 -0
  17. package/dist/infrastructure/console/artifact-revision-store.js +430 -0
  18. package/dist/infrastructure/console/context-export-store.js +160 -0
  19. package/dist/infrastructure/console/dir-lock.js +132 -0
  20. package/dist/infrastructure/harness/artifact-store.js +10 -1
  21. package/dist/infrastructure/harness/atomic-write.js +35 -2
  22. package/dist/shared/context-transfer/artifact-revision.js +172 -0
  23. package/dist/shared/context-transfer.js +418 -0
  24. package/dist/shared/operator/capabilities.js +14 -0
  25. package/dist/shared/operator/safe-run-summary.js +1 -0
  26. package/dist/shared/path-safety.js +93 -0
  27. package/dist/shared/preview.js +28 -4
  28. package/dist/task/config-types.js +12 -1
  29. package/dist/task/source-prepare/fragment-inventory.js +1 -14
  30. package/dist/task/task-demand-routing.js +3 -0
  31. package/dist/worker/console/chat/chat-event-store.js +77 -7
  32. package/dist/worker/console/chat/context-panel.js +7 -0
  33. package/dist/worker/console/chat/deferred-turn.js +12 -0
  34. package/dist/worker/console/chat/pi-runtime.js +331 -18
  35. package/dist/worker/console/chat/provider-error.js +98 -0
  36. package/dist/worker/console/chat/resource-preferences-store.js +1 -1
  37. package/dist/worker/console/chat/routes.js +389 -56
  38. package/dist/worker/console/chat/session-stats.js +179 -0
  39. package/dist/worker/console/chat/session-store.js +94 -64
  40. package/dist/worker/console/chat/todos.js +115 -0
  41. package/dist/worker/console/chat/tool-preview.js +42 -0
  42. package/dist/worker/console/chat/turn-process.js +20 -55
  43. package/dist/worker/console/chat/user-questions.js +266 -0
  44. package/dist/worker/console/chat/workspace-landing.js +79 -0
  45. package/dist/worker/console/console-update-runtime.js +1 -1
  46. package/dist/worker/console/context-transfer-diagnostics.js +198 -0
  47. package/dist/worker/console/dag-confirmation.js +1 -1
  48. package/dist/worker/console/dag-execution-receipt.js +1 -1
  49. package/dist/worker/console/doctor.js +1 -1
  50. package/dist/worker/console/draft-store.js +1 -1
  51. package/dist/worker/console/human-gate-token.js +1 -1
  52. package/dist/worker/console/index.js +3 -3
  53. package/dist/worker/console/interview/assessment.js +1 -1
  54. package/dist/worker/console/interview/session.js +1 -1
  55. package/dist/worker/console/native-directory-picker.js +13 -0
  56. package/dist/worker/console/operation-runner.js +45 -4
  57. package/dist/worker/console/operation-sse.js +1 -1
  58. package/dist/worker/console/operation-wait.js +1 -1
  59. package/dist/worker/console/operator-actions.js +104 -3
  60. package/dist/worker/console/operator-surface-health.js +1 -1
  61. package/dist/worker/console/operator-user-error.js +128 -0
  62. package/dist/worker/console/routes.js +927 -8
  63. package/dist/worker/console/security.js +39 -4
  64. package/dist/worker/console/server.js +532 -187
  65. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-CTx1TrNa.js → abnfDiagram-N423BO3Z-CpWvwARc.js} +1 -1
  66. package/dist/worker/console/static/assets/{arc-B4i9cVxX.js → arc-DctXgO-g.js} +1 -1
  67. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-BAXE8_Rl.js → architectureDiagram-T3A2C74G-D4mIkoQl.js} +1 -1
  68. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-C5Xh59at.js → blockDiagram-VBNYF7ZC-ClG0--KO.js} +1 -1
  69. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-B_asOzAu.js → c4Diagram-5PPSVZJV-CwdLk78T.js} +1 -1
  70. package/dist/worker/console/static/assets/channel-C9VQZ-ru.js +1 -0
  71. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-wRO_iRNc.js → chunk-2GRJ4B5K-DKczcu-O.js} +1 -1
  72. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-ByOaSh_G.js → chunk-2Q5K7J3B-BV6F-vBI.js} +1 -1
  73. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-DjLzudan.js → chunk-5RXB4S5H-DtojVnvA.js} +1 -1
  74. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-JCNGkXYT.js → chunk-5VM5RSS4-BjDQRGnO.js} +1 -1
  75. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-BhrPXXMZ.js → chunk-6Q2QTUOP-I0fV6ngU.js} +1 -1
  76. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-TJ5JuEBT.js → chunk-GF5L2VYU-BM8C-mmC.js} +1 -1
  77. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-VVthn_mD.js → chunk-JWPE2WC7-BEK-a15e.js} +1 -1
  78. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-D60-Mny4.js → chunk-KBJHAD2P-CQsg_fSR.js} +1 -1
  79. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-zXv7aVye.js → chunk-RYQCIY6F-B-BcaUm3.js} +1 -1
  80. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-By9VQoi1.js → chunk-XXDRQBXY-D1Bu08fg.js} +1 -1
  81. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BsCkw5MF.js +1 -0
  82. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BsCkw5MF.js +1 -0
  83. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-C4zQLe-M.js → cose-bilkent-JH36ORCC-q8nwtxBR.js} +1 -1
  84. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-wh5N2ReN.js → cynefin-VYW2F7L2-CruhpURw.js} +1 -1
  85. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-Dlu5wIqs.js → cynefinDiagram-MW4NZA55-CJne6iYF.js} +1 -1
  86. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-CrDgthc6.js → dagre-VZM6K2ZE-CbeLvBU5.js} +1 -1
  87. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-zN1clg27.js → diagram-7IWD3JNH-DmCxH1Pe.js} +1 -1
  88. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-BN-o7J7-.js → diagram-B4RE2ZJO-DJ5OYhtC.js} +1 -1
  89. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-C8SuPt0d.js → diagram-LBJQPF4R-B-UN-hln.js} +1 -1
  90. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BoizuHbZ.js → diagram-Q27KOJAE-CcEro8Ey.js} +1 -1
  91. package/dist/worker/console/static/assets/{diagram-UB23O5K3-BzUzXixG.js → diagram-UB23O5K3-BBBzDden.js} +1 -1
  92. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-Ev3lA4Cf.js → ebnfDiagram-BXEA7PRR-xKEyH-oo.js} +1 -1
  93. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-GALUzRbs.js → erDiagram-JOGREHBK-C7xl63VC.js} +1 -1
  94. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-CZJN65Sb.js → flowDiagram-UKHOOZJN-nthQQ9nR.js} +1 -1
  95. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-JLB9OESl.js → ganttDiagram-PKOTCBZU-CWN5mE33.js} +1 -1
  96. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-CcvCr4GD.js → gitGraphDiagram-DS77QQ5N-Wn86tQ6N.js} +1 -1
  97. package/dist/worker/console/static/assets/index-D-0NVyMk.css +1 -0
  98. package/dist/worker/console/static/assets/index-gwyOxQiS.js +407 -0
  99. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-HG5z7aVg.js → infoDiagram-6WML65LV-_WQymGtW.js} +1 -1
  100. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-BHEu9chR.js → ishikawaDiagram-WSZJBQD7-COBeivBm.js} +1 -1
  101. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-Cp_Up8-a.js → journeyDiagram-NVQOT4AX-CwGOJl3Q.js} +1 -1
  102. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-DvVeY-em.js → kanban-definition-27J2QSJJ-Ci0CJ5Vi.js} +1 -1
  103. package/dist/worker/console/static/assets/{linear-aGmcjgTn.js → linear-CPjMq6vN.js} +1 -1
  104. package/dist/worker/console/static/assets/{mermaid.core-Biyo-tqA.js → mermaid.core-Z0wGoe0b.js} +5 -5
  105. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-DyxY2pIb.js → mindmap-definition-FAOFIHXS-dISked0d.js} +1 -1
  106. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-CkdGuc50.js → pegDiagram-VL7TDLO6-BJxgof7Y.js} +1 -1
  107. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-NNQI9xVR.js → pieDiagram-7S7Q4E2Y-CIblU8eW.js} +1 -1
  108. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-PAJkuz_G.js → quadrantDiagram-CIZ2JOQS-vwYiqh8E.js} +1 -1
  109. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-ZwrQod0O.js → railroadDiagram-AXF67PYL-_iOsVeFm.js} +1 -1
  110. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-D3ZfrzM2.js → requirementDiagram-LRYGKXZP-Dk0MLxO_.js} +1 -1
  111. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-DDGFmWk5.js → sankeyDiagram-W5VNT64P-Dx7HtLVW.js} +1 -1
  112. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-DO6mmXTA.js → sequenceDiagram-SI44F4Z6-DRuWjlpL.js} +1 -1
  113. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-DMbCQiJt.js → sizeCapture-X5ZJPWSS-Bhy9DQAA.js} +1 -1
  114. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-Di_YUEfC.js → stateDiagram-OKZ733FA-DAx9twnU.js} +1 -1
  115. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Dmdf8cGy.js +1 -0
  116. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-Bn2PphNJ.js → swimlanes-SLNWSIFB-okMlvVrM.js} +2 -2
  117. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-W1IcAFff.js +8 -0
  118. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-DPh8pRsp.js → timeline-definition-Z64GVDOM-DXqCKe37.js} +1 -1
  119. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-GMfl26pW.js → vennDiagram-T6HMQDX7-CeIUkwBh.js} +1 -1
  120. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-DTlmVrmF.js → wardleyDiagram-T6FBY63Y-BP76BKTN.js} +1 -1
  121. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-YGBjKAS5.js → xychartDiagram-ELKLHX3M-BpVI0OpF.js} +1 -1
  122. package/dist/worker/console/static/index.html +7 -2
  123. package/dist/worker/console/static-src/app/console-types.js +29 -4
  124. package/dist/worker/console/static-src/app/useConsoleShell.js +30 -12
  125. package/dist/worker/console/static-src/app/useOperatorActions.js +36 -6
  126. package/dist/worker/console/static-src/app/useRecoveryConsole.js +10 -11
  127. package/dist/worker/console/static-src/app/useRunProgress.js +2 -1
  128. package/dist/worker/console/static-src/app/useTaskWizard.js +2 -2
  129. package/dist/worker/console/static-src/night/useNightBoard.js +8 -5
  130. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +141 -8
  131. package/dist/worker/console/static-src/operator-chat/compaction-message.js +79 -0
  132. package/dist/worker/console/static-src/operator-chat/details-dag-actions.js +122 -0
  133. package/dist/worker/console/static-src/operator-chat/refs.js +3 -0
  134. package/dist/worker/console/static-src/operator-chat/runtime-selection-labels.js +27 -0
  135. package/dist/worker/console/static-src/operator-chat/spatial-overlay.js +1 -2
  136. package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +25 -0
  137. package/dist/worker/console/static-src/operator-chat/turn-submission.js +3 -2
  138. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +181 -87
  139. package/dist/worker/console/static-src/operator-chat/useChatStream.js +159 -44
  140. package/dist/worker/console/static-src/operator-chat/useChatThread.js +177 -8
  141. package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +63 -9
  142. package/dist/worker/console/static-src/operator-chat/useWorkspaceBrowserGate.js +4 -0
  143. package/dist/worker/console/static-src/operator-chat/workspace-layout-mode.js +3 -3
  144. package/dist/worker/console/static-src/shell/useWorkspaces.js +299 -0
  145. package/dist/worker/console/static-src/shell/workspace-route.js +339 -0
  146. package/dist/worker/console/workspace-context.js +260 -0
  147. package/dist/worker/console/workspace-registry.js +214 -0
  148. package/dist/worker/continuation/worker-continuation.js +278 -0
  149. package/dist/worker/observe/health.js +1 -1
  150. package/dist/worker/observe/node-transparency.js +572 -0
  151. package/dist/worker/observe/routes.js +51 -1
  152. package/dist/worker/observe/server.js +4 -0
  153. package/dist/worker/observe/static/api.js +94 -10
  154. package/dist/worker/observe/static/app.js +18 -70
  155. package/dist/worker/observe/static/dag-context-reason-labels.d.ts +9 -0
  156. package/dist/worker/observe/static/dag-context-reason-labels.js +120 -0
  157. package/dist/worker/observe/static/index.html +1 -1
  158. package/dist/worker/observe/static/inspect-workspace.js +307 -0
  159. package/dist/worker/observe/static/operator-chrome.css +145 -20
  160. package/dist/worker/observe/static/operator-chrome.d.ts +20 -3
  161. package/dist/worker/observe/static/operator-chrome.js +330 -100
  162. package/dist/worker/observe/static/router.d.ts +46 -0
  163. package/dist/worker/observe/static/router.js +25 -1
  164. package/dist/worker/observe/static/state.d.ts +50 -0
  165. package/dist/worker/observe/static/state.js +175 -1
  166. package/dist/worker/observe/static/styles.css +1039 -128
  167. package/dist/worker/observe/static/views/dag-inspector.js +1218 -60
  168. package/dist/worker/observe/static/views/dag.js +2 -1
  169. package/dist/worker/observe/static/views/dashboard.js +6 -4
  170. package/dist/worker/observe/static/views/night.js +2 -2
  171. package/dist/worker/observe/static/views/pool.js +1 -0
  172. package/dist/worker/observe/static/views/run.js +3 -1
  173. package/dist/worker/observe/static/views/session-timeline.js +75 -10
  174. package/dist/worker/observe/static/views/task.js +1 -1
  175. package/dist/worker/outcomes/adapters.js +19 -0
  176. package/dist/worker/outcomes/types.js +1 -0
  177. package/dist/worker/pool/attempt-lease.js +97 -66
  178. package/dist/worker/pool/begin-attempt-with-lease.js +1 -0
  179. package/dist/worker/pool/reconcile.js +46 -1
  180. package/dist/worker/pool/run-store.js +2 -0
  181. package/dist/worker/pool/state-projection.js +2 -0
  182. package/dist/worker/task-spec/workflow-routing.js +8 -3
  183. package/dist/workflows/dag/artifact-bindings.js +149 -0
  184. package/dist/workflows/dag/artifact-revision-schema-registry.js +31 -0
  185. package/dist/workflows/dag/backend-test-pytest-collection.js +11 -10
  186. package/dist/workflows/dag/backend-test-writer-completeness.js +7 -12
  187. package/dist/workflows/dag/context-receipt.js +305 -0
  188. package/dist/workflows/dag/context-transfer/context-bundle.js +423 -0
  189. package/dist/workflows/dag/context-transfer/operator-actions.js +61 -0
  190. package/dist/workflows/dag/context-transfer/renderers.js +93 -0
  191. package/dist/workflows/dag/dynamic-runtime/map.js +1 -0
  192. package/dist/workflows/dag/frontend-implementation-contract.js +1 -89
  193. package/dist/workflows/dag/init-hybrid.js +259 -47
  194. package/dist/workflows/dag/interrupt-request.js +3 -3
  195. package/dist/workflows/dag/lifecycle.js +3 -3
  196. package/dist/workflows/dag/node-execution.js +112 -27
  197. package/dist/workflows/dag/path-safety.js +1 -0
  198. package/dist/workflows/dag/prompt.js +29 -4
  199. package/dist/workflows/dag/rerun-plan.js +272 -0
  200. package/dist/workflows/dag/rerun-run.js +390 -12
  201. package/dist/workflows/dag/skill-snapshot.js +1 -0
  202. package/dist/workflows/dag/types.js +203 -8
  203. package/docs/README.md +1 -0
  204. package/docs/architecture/runtime-boundaries.md +6 -6
  205. package/docs/architecture/worker-and-feature.md +1 -1
  206. package/docs/operations/local-development-environment.md +21 -0
  207. package/docs/templates/agent-dag.schema.json +50 -0
  208. package/docs/templates/backend-test-dag.json +265 -237
  209. package/docs/templates/product-line/task.yaml +1 -1
  210. package/harness.json +3 -3
  211. package/package.json +5 -1
  212. package/skills/loop-agent/references/command-reference.md +6 -0
  213. package/dist/worker/console/static/assets/channel-Dj_4Moei.js +0 -1
  214. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-C0YYAyCa.js +0 -1
  215. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-C0YYAyCa.js +0 -1
  216. package/dist/worker/console/static/assets/index-CW88Fjbw.js +0 -406
  217. package/dist/worker/console/static/assets/index-DP0ZJl39.css +0 -1
  218. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DrdDvela.js +0 -1
  219. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DPkEAULl.js +0 -8
  220. package/dist/worker/console/static-src/operator-chat/activity-rail-presentation.js +0 -73
  221. package/dist/worker/console/static-src/operator-chat/useActivityRailTransition.js +0 -59
  222. /package/dist/{worker → infrastructure}/console/operation-store.js +0 -0
  223. /package/dist/{worker → infrastructure}/console/repo-fingerprint.js +0 -0
@@ -0,0 +1,132 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { lstat, mkdir, readFile, rename, rm, utimes, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { ensureSecureDir } from "./app-data.js";
5
+ const OWNER_FILE = "owner";
6
+ const DEFAULT_STALE_MS = 30_000;
7
+ function delay(ms) {
8
+ return new Promise((resolve) => setTimeout(resolve, ms));
9
+ }
10
+ function freshToken() {
11
+ return randomBytes(16).toString("hex");
12
+ }
13
+ function ownerPath(lockDir) {
14
+ return path.join(lockDir, OWNER_FILE);
15
+ }
16
+ /**
17
+ * A lock's freshness is the owner-file heartbeat, not the containing
18
+ * directory mtime. Creating or editing a file does not refresh the directory
19
+ * mtime, so using the latter could make a healthy long-running lock appear
20
+ * stale and permit a second holder into its critical section.
21
+ */
22
+ async function lockTimestamp(lockDir) {
23
+ const ownerStat = await lstat(ownerPath(lockDir)).catch(() => undefined);
24
+ if (ownerStat?.isFile())
25
+ return ownerStat.mtimeMs;
26
+ return (await lstat(lockDir).catch(() => undefined))?.mtimeMs;
27
+ }
28
+ export async function isDirLockStale(lockDir, staleMs, nowMs = Date.now()) {
29
+ const timestamp = await lockTimestamp(lockDir);
30
+ return timestamp === undefined || nowMs - timestamp > staleMs;
31
+ }
32
+ async function refreshDirLock(lockDir, token) {
33
+ const owner = await readFile(ownerPath(lockDir), "utf-8").catch(() => undefined);
34
+ if (owner !== token)
35
+ return;
36
+ const now = new Date();
37
+ await utimes(ownerPath(lockDir), now, now).catch(() => { });
38
+ }
39
+ /**
40
+ * Cross-process exclusive directory lock (mkdir-based). Ownership is
41
+ * token-guarded: each holder writes a unique owner file inside the lock
42
+ * directory and only ever removes a lock whose owner token matches its own.
43
+ *
44
+ * Release protocol (B2): verify owner AND freshness BEFORE touching the lock
45
+ * path. Takeover only ever targets a stale lock, so a holder that releases a
46
+ * lock it still owns (fresh) cannot have been taken over between the verify
47
+ * and the rename — it moves its own lock, never a successor's. A stale lock is
48
+ * deliberately left alone (a takeover may be in flight); only the post-rename
49
+ * tombstone check restores a lock moved by an unexpected race, never deletes a
50
+ * successor's live lock.
51
+ */
52
+ export async function acquireDirLock(lockDir, options) {
53
+ const token = options?.token ?? freshToken();
54
+ const staleMs = options?.staleMs ?? DEFAULT_STALE_MS;
55
+ ensureSecureDir(path.dirname(lockDir));
56
+ for (;;) {
57
+ try {
58
+ await mkdir(lockDir);
59
+ }
60
+ catch (error) {
61
+ const code = error?.code;
62
+ if (code !== "EEXIST")
63
+ throw error;
64
+ const stat = await lstat(lockDir).catch(() => undefined);
65
+ if (stat?.isDirectory() && await isDirLockStale(lockDir, staleMs)) {
66
+ const tombstone = `${lockDir}.${freshToken()}.tomb`;
67
+ try {
68
+ await rename(lockDir, tombstone);
69
+ await rm(tombstone, { recursive: true, force: true });
70
+ }
71
+ catch {
72
+ // another process won the takeover; retry the loop
73
+ }
74
+ continue;
75
+ }
76
+ await delay(20);
77
+ continue;
78
+ }
79
+ try {
80
+ await writeFile(ownerPath(lockDir), token, {
81
+ flag: "wx",
82
+ mode: 0o600,
83
+ });
84
+ }
85
+ catch {
86
+ await rm(lockDir, { recursive: true, force: true });
87
+ continue;
88
+ }
89
+ break;
90
+ }
91
+ const heartbeat = setInterval(() => { void refreshDirLock(lockDir, token); }, Math.max(10, Math.floor(staleMs / 3)));
92
+ heartbeat.unref();
93
+ let released = false;
94
+ const release = async () => {
95
+ if (released)
96
+ return;
97
+ released = true;
98
+ clearInterval(heartbeat);
99
+ // Verify the lock is still ours AND fresh before renaming it away. If the
100
+ // owner no longer matches, a successor holds the lock — never touch it.
101
+ const stat = await lstat(lockDir).catch(() => undefined);
102
+ if (!stat?.isDirectory())
103
+ return;
104
+ if (await isDirLockStale(lockDir, staleMs)) {
105
+ // Our lock went stale: a takeover may be in flight or imminent. Leave
106
+ // it alone — removing it now could delete a successor's live lock.
107
+ return;
108
+ }
109
+ const owner = await readFile(ownerPath(lockDir), "utf-8").catch(() => undefined);
110
+ if (owner !== token)
111
+ return;
112
+ const tombstone = `${lockDir}.${token}.release`;
113
+ try {
114
+ await rename(lockDir, tombstone);
115
+ }
116
+ catch {
117
+ // lock path already gone (a takeover removed it); nothing of ours.
118
+ return;
119
+ }
120
+ const movedOwner = await readFile(path.join(tombstone, OWNER_FILE), "utf-8").catch(() => undefined);
121
+ if (movedOwner !== token) {
122
+ // Raced with a takeover in the microsecond window between the fresh
123
+ // verify and the rename: restore the moved lock if the path is still
124
+ // free; otherwise leave the tombstone for reconcile — never delete a
125
+ // successor's live lock.
126
+ await rename(tombstone, lockDir).catch(() => { });
127
+ return;
128
+ }
129
+ await rm(tombstone, { recursive: true, force: true }).catch(() => { });
130
+ };
131
+ return { token, release };
132
+ }
@@ -1,6 +1,6 @@
1
1
  import { mkdir } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { writeJsonAtomic, writeTextAtomic, } from "./atomic-write.js";
3
+ import { writeJsonAtomic, writeBufferAtomic, writeTextAtomic, } from "./atomic-write.js";
4
4
  function resolveRepoRootFromDagRunDir(runDir) {
5
5
  const normalized = path.resolve(runDir);
6
6
  const lifecycleDir = path.dirname(normalized);
@@ -26,12 +26,16 @@ function dagWriteOptions(runDir, options) {
26
26
  return {
27
27
  repoRoot: options?.repoRoot ?? resolveRepoRootFromDagRunDir(runDir),
28
28
  allowCompletedFactsWrite: options?.allowCompletedFactsWrite,
29
+ mode: options?.mode,
30
+ directoryMode: options?.directoryMode,
29
31
  };
30
32
  }
31
33
  function pathWriteOptions(targetPath, options) {
32
34
  return {
33
35
  repoRoot: options?.repoRoot ?? resolveRepoRootFromHarnessPath(targetPath),
34
36
  allowCompletedFactsWrite: options?.allowCompletedFactsWrite,
37
+ mode: options?.mode,
38
+ directoryMode: options?.directoryMode,
35
39
  };
36
40
  }
37
41
  function completedRelocationWriteOptions(runDir) {
@@ -48,6 +52,11 @@ export async function writeDagNodeTextArtifact(runDir, nodeId, fileName, content
48
52
  await writeTextAtomic(targetPath, content, dagWriteOptions(runDir, options));
49
53
  return targetPath;
50
54
  }
55
+ export async function writeDagNodeBufferArtifact(runDir, nodeId, fileName, bytes, options) {
56
+ const targetPath = path.join(runDir, nodeId, fileName);
57
+ await writeBufferAtomic(targetPath, bytes, dagWriteOptions(runDir, options));
58
+ return targetPath;
59
+ }
51
60
  export async function writeDagNodeJsonArtifact(runDir, nodeId, fileName, value, options) {
52
61
  const targetPath = path.join(runDir, nodeId, fileName);
53
62
  await writeJsonAtomic(targetPath, value, dagWriteOptions(runDir, options));
@@ -2,15 +2,45 @@ import { copyFile, mkdir, readFile, rename, unlink, writeFile } from "node:fs/pr
2
2
  import path from "node:path";
3
3
  import { assertHarnessWriteAllowed, } from "./completed-facts-guard.js";
4
4
  let atomicWriteSequence = 0;
5
+ function isTransientJsonReadError(error) {
6
+ if (error instanceof SyntaxError)
7
+ return true;
8
+ if (!error || typeof error !== "object" || !("code" in error))
9
+ return false;
10
+ const code = String(error.code ?? "");
11
+ return code === "EBUSY" || code === "EPERM" || code === "EACCES";
12
+ }
13
+ export async function readJsonWithTransientRetry(targetPath, options = {}) {
14
+ const attempts = Math.max(1, Math.floor(options.attempts ?? 6));
15
+ const delayMs = Math.max(0, Math.floor(options.delayMs ?? 20));
16
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
17
+ try {
18
+ return JSON.parse(await readFile(targetPath, "utf-8"));
19
+ }
20
+ catch (error) {
21
+ if (attempt === attempts || !isTransientJsonReadError(error))
22
+ throw error;
23
+ await new Promise((resolve) => setTimeout(resolve, delayMs * attempt));
24
+ }
25
+ }
26
+ throw new Error("unreachable transient JSON read state");
27
+ }
5
28
  async function writeAtomic(targetPath, content, options) {
6
29
  assertHarnessWriteAllowed(targetPath, options);
7
30
  const resolved = options?.repoRoot && !path.isAbsolute(targetPath)
8
31
  ? path.resolve(options.repoRoot, targetPath)
9
32
  : path.resolve(targetPath);
10
- await mkdir(path.dirname(resolved), { recursive: true });
33
+ await mkdir(path.dirname(resolved), {
34
+ recursive: true,
35
+ ...(options?.directoryMode !== undefined
36
+ ? { mode: options.directoryMode }
37
+ : {}),
38
+ });
11
39
  const tempPath = `${resolved}.${process.pid}.${(atomicWriteSequence += 1)}.tmp`;
12
40
  try {
13
- await writeFile(tempPath, content, "utf-8");
41
+ await writeFile(tempPath, content, {
42
+ ...(options?.mode !== undefined ? { mode: options.mode } : {}),
43
+ });
14
44
  try {
15
45
  await rename(tempPath, resolved);
16
46
  }
@@ -31,6 +61,9 @@ export async function writeJsonAtomic(targetPath, value, options) {
31
61
  export async function writeTextAtomic(targetPath, text, options) {
32
62
  await writeAtomic(targetPath, text, options);
33
63
  }
64
+ export async function writeBufferAtomic(targetPath, bytes, options) {
65
+ await writeAtomic(targetPath, bytes, options);
66
+ }
34
67
  export function serializeJsonl(entries) {
35
68
  if (entries.length === 0)
36
69
  return "";
@@ -0,0 +1,172 @@
1
+ import { createHash } from "node:crypto";
2
+ import { artifactRevisionV1Schema } from "../context-transfer.js";
3
+ import { redactSecretsWithFindings } from "../preview.js";
4
+ export const ARTIFACT_REVISION_LIMITS = Object.freeze({
5
+ singleFileBytes: 10 * 1024 * 1024,
6
+ diffPreviewBytes: 64 * 1024,
7
+ });
8
+ function sha256(bytes) {
9
+ return createHash("sha256").update(bytes).digest("hex");
10
+ }
11
+ function isTextMedia(mediaType) {
12
+ return mediaType.startsWith("text/") || mediaType.includes("json") || mediaType.includes("xml");
13
+ }
14
+ function stableJson(bytes) {
15
+ try {
16
+ const value = JSON.parse(bytes.toString("utf8"));
17
+ const sort = (input) => {
18
+ if (Array.isArray(input))
19
+ return input.map(sort);
20
+ if (input && typeof input === "object") {
21
+ return Object.fromEntries(Object.entries(input)
22
+ .sort(([a], [b]) => a.localeCompare(b))
23
+ .map(([key, child]) => [key, sort(child)]));
24
+ }
25
+ return input;
26
+ };
27
+ return `${JSON.stringify(sort(value), null, 2)}\n`;
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ }
33
+ function boundedLineDiff(before, after) {
34
+ const beforeLines = before.split(/\r?\n/);
35
+ const afterLines = after.split(/\r?\n/);
36
+ const rows = [];
37
+ const limit = Math.max(beforeLines.length, afterLines.length);
38
+ for (let index = 0; index < limit; index += 1) {
39
+ if (beforeLines[index] === afterLines[index])
40
+ continue;
41
+ if (beforeLines[index] !== undefined)
42
+ rows.push(`- ${beforeLines[index]}`);
43
+ if (afterLines[index] !== undefined)
44
+ rows.push(`+ ${afterLines[index]}`);
45
+ }
46
+ const complete = rows.join("\n");
47
+ const preview = Buffer.from(complete, "utf8");
48
+ if (preview.byteLength <= ARTIFACT_REVISION_LIMITS.diffPreviewBytes) {
49
+ return { summary: complete, truncated: false };
50
+ }
51
+ return {
52
+ summary: preview.subarray(0, ARTIFACT_REVISION_LIMITS.diffPreviewBytes).toString("utf8") + "\n[diff truncated]",
53
+ truncated: true,
54
+ };
55
+ }
56
+ export function validateAndDescribeArtifactRevision(input) {
57
+ if (input.declaration.revisionPolicy !== "replace-file") {
58
+ throw new Error("ARTIFACT_NOT_REVISION_ELIGIBLE");
59
+ }
60
+ if (input.candidateBytes.byteLength > ARTIFACT_REVISION_LIMITS.singleFileBytes) {
61
+ throw new Error("ARTIFACT_REVISION_SCHEMA_INVALID: candidate exceeds size limit");
62
+ }
63
+ if (sha256(input.parentBytes) !== input.parentSha256) {
64
+ throw new Error("ARTIFACT_REVISION_DRIFT: parent artifact hash mismatch");
65
+ }
66
+ if (input.mediaType !== input.declaration.mediaType) {
67
+ throw new Error("ARTIFACT_REVISION_SCHEMA_INVALID: media type mismatch");
68
+ }
69
+ const textCandidate = isTextMedia(input.mediaType);
70
+ if (textCandidate &&
71
+ redactSecretsWithFindings(input.candidateBytes.toString("utf8"))
72
+ .findingCount > 0) {
73
+ throw new Error("SECRET_SCAN_CONFIRMATION_REQUIRED");
74
+ }
75
+ const candidateSha256 = sha256(input.candidateBytes);
76
+ if (candidateSha256 === input.parentSha256) {
77
+ throw new Error("ARTIFACT_REVISION_SCHEMA_INVALID: replacement is unchanged");
78
+ }
79
+ let kind = "binary";
80
+ let summary = `binary ${input.parentBytes.byteLength} -> ${input.candidateBytes.byteLength} bytes; ${input.parentSha256} -> ${candidateSha256}`;
81
+ let truncated = false;
82
+ let diffPreview;
83
+ const schemaChecks = [];
84
+ if (input.declaration.schemaId || input.mediaType.includes("json")) {
85
+ const before = stableJson(input.parentBytes);
86
+ const after = stableJson(input.candidateBytes);
87
+ if (!before || !after) {
88
+ throw new Error("ARTIFACT_REVISION_SCHEMA_INVALID: expected valid JSON");
89
+ }
90
+ kind = "json";
91
+ const declaredSchemaId = input.declaration.schemaId;
92
+ if (declaredSchemaId) {
93
+ const validator = input.artifactSchemaResolver?.(declaredSchemaId);
94
+ if (!validator) {
95
+ // Fail closed (W4.3): a declared schema without a registered
96
+ // validator must not pass as "JSON syntax only" — revision
97
+ // eligibility would silently outrun actual verification.
98
+ throw new Error(`ARTIFACT_REVISION_SCHEMA_INVALID: no registered revision validator for ${declaredSchemaId}; artifact cannot be staged until its schema is registered`);
99
+ }
100
+ const parsed = JSON.parse(after);
101
+ const result = validator.safeParse(parsed);
102
+ if (!result.success) {
103
+ const issue = result.error.issues[0];
104
+ const issuePath = issue
105
+ ? issue.path.map((part) => String(part)).join(".")
106
+ : "(root)";
107
+ throw new Error(`ARTIFACT_REVISION_SCHEMA_INVALID: candidate does not satisfy ${declaredSchemaId} at ${issuePath}: ${issue?.message ?? "schema violation"}`);
108
+ }
109
+ schemaChecks.push({
110
+ id: "artifact-schema",
111
+ status: "pass",
112
+ detail: declaredSchemaId,
113
+ });
114
+ }
115
+ const diff = boundedLineDiff(before, after);
116
+ summary = diff.summary;
117
+ truncated = diff.truncated;
118
+ diffPreview = Buffer.from(diff.summary, "utf8");
119
+ }
120
+ else if (isTextMedia(input.mediaType)) {
121
+ kind = "text";
122
+ const diff = boundedLineDiff(input.parentBytes.toString("utf8"), input.candidateBytes.toString("utf8"));
123
+ summary = diff.summary;
124
+ truncated = diff.truncated;
125
+ diffPreview = Buffer.from(diff.summary, "utf8");
126
+ }
127
+ const revision = artifactRevisionV1Schema.parse({
128
+ schemaVersion: 1,
129
+ revisionId: input.revisionId,
130
+ state: "validated",
131
+ parent: {
132
+ runId: input.parentRunId,
133
+ nodeId: input.producerNodeId,
134
+ artifactPath: input.declaration.path,
135
+ artifactSha256: input.parentSha256,
136
+ ...(input.declaration.schemaId ? { artifactSchemaId: input.declaration.schemaId } : {}),
137
+ },
138
+ candidate: {
139
+ stagingPath: input.stagingPath,
140
+ sha256: candidateSha256,
141
+ bytes: input.candidateBytes.byteLength,
142
+ mediaType: input.mediaType,
143
+ uploadedAt: input.uploadedAt,
144
+ uploadedBy: "operator",
145
+ },
146
+ validation: {
147
+ status: "pass",
148
+ checks: [
149
+ { id: "parent-hash", status: "pass" },
150
+ { id: "declared-path", status: "pass" },
151
+ { id: "media-type", status: "pass" },
152
+ textCandidate
153
+ ? { id: "secret-scan", status: "pass" }
154
+ : {
155
+ id: "secret-scan",
156
+ status: "warning",
157
+ detail: "binary candidate was not decoded for text secret scanning",
158
+ },
159
+ ...(kind === "json" ? [{ id: "json-syntax", status: "pass" }] : []),
160
+ ...schemaChecks,
161
+ ],
162
+ },
163
+ diff: {
164
+ kind,
165
+ summary,
166
+ ...(diffPreview ? { previewPath: `artifact-revisions/${input.revisionId}/diff.txt` } : {}),
167
+ truncated,
168
+ },
169
+ expiresAt: input.expiresAt,
170
+ });
171
+ return { revision, ...(diffPreview ? { diffPreview } : {}) };
172
+ }