@mcoda/codali 0.1.134 → 0.1.135-codali.11

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 (254) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/ORCHESTRATION.md +462 -0
  3. package/README.md +112 -1
  4. package/config/alternate-local.example.json +49 -0
  5. package/config/docdex-runtime.json +21 -0
  6. package/config/orchestration.schema.json +548 -0
  7. package/config/raijin-suku.example.json +172 -0
  8. package/config/terminal-long-scenarios.v1.json +71 -0
  9. package/dist/agents/RoleResolution.d.ts.map +1 -1
  10. package/dist/agents/RoleResolution.js +4 -4
  11. package/dist/api/CodaliApi.d.ts +16 -0
  12. package/dist/api/CodaliApi.d.ts.map +1 -1
  13. package/dist/api/CodaliApi.js +39 -10
  14. package/dist/cli/AskCommand.d.ts +3 -0
  15. package/dist/cli/AskCommand.d.ts.map +1 -1
  16. package/dist/cli/AskCommand.js +76 -13
  17. package/dist/cli/RunCommand.d.ts +4 -0
  18. package/dist/cli/RunCommand.d.ts.map +1 -1
  19. package/dist/cli/RunCommand.js +110 -24
  20. package/dist/cli/TerminalCommand.d.ts +35 -0
  21. package/dist/cli/TerminalCommand.d.ts.map +1 -0
  22. package/dist/cli/TerminalCommand.js +618 -0
  23. package/dist/cli/TerminalCredentials.d.ts +3 -0
  24. package/dist/cli/TerminalCredentials.d.ts.map +1 -0
  25. package/dist/cli/TerminalCredentials.js +89 -0
  26. package/dist/cli/TerminalInput.d.ts +24 -0
  27. package/dist/cli/TerminalInput.d.ts.map +1 -0
  28. package/dist/cli/TerminalInput.js +98 -0
  29. package/dist/cli/TerminalText.d.ts +10 -0
  30. package/dist/cli/TerminalText.d.ts.map +1 -0
  31. package/dist/cli/TerminalText.js +53 -0
  32. package/dist/cli.d.ts.map +1 -1
  33. package/dist/cli.js +33 -4
  34. package/dist/cognitive/ConfiguredPipeline.d.ts +34 -0
  35. package/dist/cognitive/ConfiguredPipeline.d.ts.map +1 -0
  36. package/dist/cognitive/ConfiguredPipeline.js +50 -0
  37. package/dist/cognitive/ValidationRunner.d.ts +4 -0
  38. package/dist/cognitive/ValidationRunner.d.ts.map +1 -1
  39. package/dist/cognitive/ValidationRunner.js +18 -41
  40. package/dist/config/NodeOrchestration.d.ts +21 -0
  41. package/dist/config/NodeOrchestration.d.ts.map +1 -0
  42. package/dist/config/NodeOrchestration.js +54 -0
  43. package/dist/config/OrchestrationConfig.d.ts +100 -0
  44. package/dist/config/OrchestrationConfig.d.ts.map +1 -0
  45. package/dist/config/OrchestrationConfig.js +245 -0
  46. package/dist/connectors/mcp/McpClient.d.ts +3 -1
  47. package/dist/connectors/mcp/McpClient.d.ts.map +1 -1
  48. package/dist/connectors/mcp/McpClient.js +3 -2
  49. package/dist/connectors/mcp/McpServerRegistry.d.ts +2 -2
  50. package/dist/connectors/mcp/McpServerRegistry.d.ts.map +1 -1
  51. package/dist/connectors/mcp/McpServerRegistry.js +39 -16
  52. package/dist/connectors/mcp/McpToolAdapter.js +2 -2
  53. package/dist/connectors/media/ConfiguredMediaTools.d.ts +6 -0
  54. package/dist/connectors/media/ConfiguredMediaTools.d.ts.map +1 -0
  55. package/dist/connectors/media/ConfiguredMediaTools.js +41 -0
  56. package/dist/connectors/media/ImageGenerationTool.js +3 -3
  57. package/dist/connectors/media/MediaArtifactReceipt.d.ts +5 -0
  58. package/dist/connectors/media/MediaArtifactReceipt.d.ts.map +1 -0
  59. package/dist/connectors/media/MediaArtifactReceipt.js +65 -0
  60. package/dist/connectors/media/MediaJobStore.d.ts +68 -0
  61. package/dist/connectors/media/MediaJobStore.d.ts.map +1 -0
  62. package/dist/connectors/media/MediaJobStore.js +199 -0
  63. package/dist/connectors/media/MediaJobWorker.d.ts +2 -0
  64. package/dist/connectors/media/MediaJobWorker.d.ts.map +1 -0
  65. package/dist/connectors/media/MediaJobWorker.js +65 -0
  66. package/dist/connectors/media/RemoteMediaJob.d.ts +6 -0
  67. package/dist/connectors/media/RemoteMediaJob.d.ts.map +1 -0
  68. package/dist/connectors/media/RemoteMediaJob.js +80 -0
  69. package/dist/docdex/DocdexClient.d.ts +18 -1
  70. package/dist/docdex/DocdexClient.d.ts.map +1 -1
  71. package/dist/docdex/DocdexClient.js +135 -19
  72. package/dist/docdex/ManagedDocdex.d.ts +29 -0
  73. package/dist/docdex/ManagedDocdex.d.ts.map +1 -0
  74. package/dist/docdex/ManagedDocdex.js +215 -0
  75. package/dist/docdex/ManagedRuntime.d.ts +28 -0
  76. package/dist/docdex/ManagedRuntime.d.ts.map +1 -0
  77. package/dist/docdex/ManagedRuntime.js +212 -0
  78. package/dist/eval/EvaluationProcess.d.ts +13 -0
  79. package/dist/eval/EvaluationProcess.d.ts.map +1 -0
  80. package/dist/eval/EvaluationProcess.js +76 -0
  81. package/dist/eval/LongWorkflowJourney.d.ts +34 -0
  82. package/dist/eval/LongWorkflowJourney.d.ts.map +1 -0
  83. package/dist/eval/LongWorkflowJourney.js +243 -0
  84. package/dist/eval/PlanningCorpus.d.ts +45 -0
  85. package/dist/eval/PlanningCorpus.d.ts.map +1 -0
  86. package/dist/eval/PlanningCorpus.js +189 -0
  87. package/dist/eval/PlanningCorpusRunner.d.ts +13 -0
  88. package/dist/eval/PlanningCorpusRunner.d.ts.map +1 -0
  89. package/dist/eval/PlanningCorpusRunner.js +89 -0
  90. package/dist/eval/TerminalCorpusRunner.d.ts +36 -0
  91. package/dist/eval/TerminalCorpusRunner.d.ts.map +1 -0
  92. package/dist/eval/TerminalCorpusRunner.js +222 -0
  93. package/dist/eval/TerminalTaskCorpus.d.ts +26 -0
  94. package/dist/eval/TerminalTaskCorpus.d.ts.map +1 -0
  95. package/dist/eval/TerminalTaskCorpus.js +105 -0
  96. package/dist/eval/TerminalWorkflowCorpus.d.ts +11 -0
  97. package/dist/eval/TerminalWorkflowCorpus.d.ts.map +1 -0
  98. package/dist/eval/TerminalWorkflowCorpus.js +119 -0
  99. package/dist/eval/fixtures/ContractReviewProvider.d.ts +4 -0
  100. package/dist/eval/fixtures/ContractReviewProvider.d.ts.map +1 -0
  101. package/dist/eval/fixtures/ContractReviewProvider.js +10 -0
  102. package/dist/eval/fixtures/MixedMediaRecoveryJourney.d.ts +6 -0
  103. package/dist/eval/fixtures/MixedMediaRecoveryJourney.d.ts.map +1 -0
  104. package/dist/eval/fixtures/MixedMediaRecoveryJourney.js +145 -0
  105. package/dist/eval/fixtures/TerminalRecoveryJourney.d.ts +4 -0
  106. package/dist/eval/fixtures/TerminalRecoveryJourney.d.ts.map +1 -0
  107. package/dist/eval/fixtures/TerminalRecoveryJourney.js +136 -0
  108. package/dist/gateway/CodaliGateway.d.ts +2 -0
  109. package/dist/gateway/CodaliGateway.d.ts.map +1 -1
  110. package/dist/gateway/CodaliGateway.js +11 -1
  111. package/dist/gateway/ConfiguredGateway.d.ts +23 -0
  112. package/dist/gateway/ConfiguredGateway.d.ts.map +1 -0
  113. package/dist/gateway/ConfiguredGateway.js +44 -0
  114. package/dist/gateway/GatewayTracer.d.ts +1 -1
  115. package/dist/gateway/GatewayTracer.d.ts.map +1 -1
  116. package/dist/gateway/GatewayTracer.js +2 -27
  117. package/dist/index.d.ts +24 -0
  118. package/dist/index.d.ts.map +1 -1
  119. package/dist/index.js +13 -0
  120. package/dist/permissions/PermissionGate.d.ts +44 -0
  121. package/dist/permissions/PermissionGate.d.ts.map +1 -0
  122. package/dist/permissions/PermissionGate.js +97 -0
  123. package/dist/providers/ConfiguredEmbeddings.d.ts +43 -0
  124. package/dist/providers/ConfiguredEmbeddings.d.ts.map +1 -0
  125. package/dist/providers/ConfiguredEmbeddings.js +87 -0
  126. package/dist/providers/ConfiguredModelScope.d.ts +70 -0
  127. package/dist/providers/ConfiguredModelScope.d.ts.map +1 -0
  128. package/dist/providers/ConfiguredModelScope.js +129 -0
  129. package/dist/providers/ConfiguredProvider.d.ts +84 -0
  130. package/dist/providers/ConfiguredProvider.d.ts.map +1 -0
  131. package/dist/providers/ConfiguredProvider.js +271 -0
  132. package/dist/providers/ModelServiceError.d.ts +15 -0
  133. package/dist/providers/ModelServiceError.d.ts.map +1 -0
  134. package/dist/providers/ModelServiceError.js +69 -0
  135. package/dist/providers/MswarmWorkerProvider.d.ts.map +1 -1
  136. package/dist/providers/MswarmWorkerProvider.js +4 -0
  137. package/dist/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  138. package/dist/providers/OpenAiCompatibleProvider.js +97 -50
  139. package/dist/providers/ProviderTypes.d.ts +14 -0
  140. package/dist/providers/ProviderTypes.d.ts.map +1 -1
  141. package/dist/providers/RequestUsage.d.ts +11 -0
  142. package/dist/providers/RequestUsage.d.ts.map +1 -0
  143. package/dist/providers/RequestUsage.js +33 -0
  144. package/dist/runtime/CodaliJobRuntime.d.ts +6 -0
  145. package/dist/runtime/CodaliJobRuntime.d.ts.map +1 -1
  146. package/dist/runtime/CodaliJobRuntime.js +36 -1
  147. package/dist/runtime/CodaliRuntime.d.ts +29 -0
  148. package/dist/runtime/CodaliRuntime.d.ts.map +1 -1
  149. package/dist/runtime/CodaliRuntime.js +70 -1
  150. package/dist/runtime/CompletionReport.d.ts +5 -0
  151. package/dist/runtime/CompletionReport.d.ts.map +1 -0
  152. package/dist/runtime/CompletionReport.js +12 -0
  153. package/dist/runtime/ProgressTracker.d.ts +17 -0
  154. package/dist/runtime/ProgressTracker.d.ts.map +1 -0
  155. package/dist/runtime/ProgressTracker.js +27 -0
  156. package/dist/runtime/RequestedTestEvidence.d.ts +12 -0
  157. package/dist/runtime/RequestedTestEvidence.d.ts.map +1 -0
  158. package/dist/runtime/RequestedTestEvidence.js +16 -0
  159. package/dist/runtime/RequiredRetrieval.d.ts +13 -0
  160. package/dist/runtime/RequiredRetrieval.d.ts.map +1 -0
  161. package/dist/runtime/RequiredRetrieval.js +25 -0
  162. package/dist/runtime/ReviewContract.d.ts +35 -0
  163. package/dist/runtime/ReviewContract.d.ts.map +1 -0
  164. package/dist/runtime/ReviewContract.js +132 -0
  165. package/dist/runtime/ReviewCoordinator.d.ts +41 -0
  166. package/dist/runtime/ReviewCoordinator.d.ts.map +1 -0
  167. package/dist/runtime/ReviewCoordinator.js +126 -0
  168. package/dist/runtime/ReviewSource.d.ts +9 -0
  169. package/dist/runtime/ReviewSource.d.ts.map +1 -0
  170. package/dist/runtime/ReviewSource.js +54 -0
  171. package/dist/runtime/Runner.d.ts +7 -0
  172. package/dist/runtime/Runner.d.ts.map +1 -1
  173. package/dist/runtime/Runner.js +220 -171
  174. package/dist/runtime/SecretRedaction.d.ts +11 -0
  175. package/dist/runtime/SecretRedaction.d.ts.map +1 -0
  176. package/dist/runtime/SecretRedaction.js +85 -0
  177. package/dist/runtime/SessionController.d.ts +150 -0
  178. package/dist/runtime/SessionController.d.ts.map +1 -0
  179. package/dist/runtime/SessionController.js +1487 -0
  180. package/dist/runtime/StructuralEvidence.d.ts +22 -0
  181. package/dist/runtime/StructuralEvidence.d.ts.map +1 -0
  182. package/dist/runtime/StructuralEvidence.js +87 -0
  183. package/dist/runtime/TaskReview.d.ts +25 -0
  184. package/dist/runtime/TaskReview.d.ts.map +1 -0
  185. package/dist/runtime/TaskReview.js +84 -0
  186. package/dist/runtime/TaskReviewContext.d.ts +71 -0
  187. package/dist/runtime/TaskReviewContext.d.ts.map +1 -0
  188. package/dist/runtime/TaskReviewContext.js +50 -0
  189. package/dist/runtime/UsageReconciliation.d.ts +28 -0
  190. package/dist/runtime/UsageReconciliation.d.ts.map +1 -0
  191. package/dist/runtime/UsageReconciliation.js +68 -0
  192. package/dist/runtime/ValidationOutput.d.ts +5 -0
  193. package/dist/runtime/ValidationOutput.d.ts.map +1 -0
  194. package/dist/runtime/ValidationOutput.js +32 -0
  195. package/dist/runtime/VerificationCommand.d.ts +5 -0
  196. package/dist/runtime/VerificationCommand.d.ts.map +1 -0
  197. package/dist/runtime/VerificationCommand.js +76 -0
  198. package/dist/runtime/VerificationReceiptSelection.d.ts +15 -0
  199. package/dist/runtime/VerificationReceiptSelection.d.ts.map +1 -0
  200. package/dist/runtime/VerificationReceiptSelection.js +30 -0
  201. package/dist/runtime/WorkStatusPage.d.ts +15 -0
  202. package/dist/runtime/WorkStatusPage.d.ts.map +1 -0
  203. package/dist/runtime/WorkStatusPage.js +58 -0
  204. package/dist/runtime/WorkspaceLedger.d.ts +13 -0
  205. package/dist/runtime/WorkspaceLedger.d.ts.map +1 -0
  206. package/dist/runtime/WorkspaceLedger.js +145 -0
  207. package/dist/runtime/WorkspaceLock.d.ts.map +1 -1
  208. package/dist/runtime/WorkspaceLock.js +20 -17
  209. package/dist/runtime/WorkspaceSnapshot.d.ts +13 -0
  210. package/dist/runtime/WorkspaceSnapshot.d.ts.map +1 -0
  211. package/dist/runtime/WorkspaceSnapshot.js +88 -0
  212. package/dist/session/AtomicState.d.ts +13 -0
  213. package/dist/session/AtomicState.d.ts.map +1 -0
  214. package/dist/session/AtomicState.js +123 -0
  215. package/dist/session/SessionStoragePath.d.ts +15 -0
  216. package/dist/session/SessionStoragePath.d.ts.map +1 -0
  217. package/dist/session/SessionStoragePath.js +101 -0
  218. package/dist/session/SessionStore.d.ts +9 -0
  219. package/dist/session/SessionStore.d.ts.map +1 -1
  220. package/dist/session/SessionStore.js +181 -47
  221. package/dist/session/WorkState.d.ts +32 -0
  222. package/dist/session/WorkState.d.ts.map +1 -0
  223. package/dist/session/WorkState.js +399 -0
  224. package/dist/session/WorkTypes.d.ts +102 -0
  225. package/dist/session/WorkTypes.d.ts.map +1 -0
  226. package/dist/session/WorkTypes.js +1 -0
  227. package/dist/tools/ToolRegistry.d.ts +2 -0
  228. package/dist/tools/ToolRegistry.d.ts.map +1 -1
  229. package/dist/tools/ToolRegistry.js +12 -2
  230. package/dist/tools/ToolTypes.d.ts +16 -0
  231. package/dist/tools/ToolTypes.d.ts.map +1 -1
  232. package/dist/tools/docdex/DocdexTools.d.ts +2 -0
  233. package/dist/tools/docdex/DocdexTools.d.ts.map +1 -1
  234. package/dist/tools/docdex/DocdexTools.js +17 -2
  235. package/dist/tools/filesystem/FileTools.d.ts.map +1 -1
  236. package/dist/tools/filesystem/FileTools.js +30 -10
  237. package/dist/tools/shell/AsyncProcess.d.ts +19 -0
  238. package/dist/tools/shell/AsyncProcess.d.ts.map +1 -0
  239. package/dist/tools/shell/AsyncProcess.js +94 -0
  240. package/dist/tools/shell/DarwinRuntimeLibraries.d.ts +13 -0
  241. package/dist/tools/shell/DarwinRuntimeLibraries.d.ts.map +1 -0
  242. package/dist/tools/shell/DarwinRuntimeLibraries.js +130 -0
  243. package/dist/tools/shell/HostToolchain.d.ts +19 -0
  244. package/dist/tools/shell/HostToolchain.d.ts.map +1 -0
  245. package/dist/tools/shell/HostToolchain.js +266 -0
  246. package/dist/tools/shell/IsolatedExecutor.d.ts +15 -0
  247. package/dist/tools/shell/IsolatedExecutor.d.ts.map +1 -0
  248. package/dist/tools/shell/IsolatedExecutor.js +138 -0
  249. package/dist/tools/shell/ShellTool.d.ts.map +1 -1
  250. package/dist/tools/shell/ShellTool.js +9 -29
  251. package/dist/tools/shell/ShellWorkingDirectory.d.ts +3 -0
  252. package/dist/tools/shell/ShellWorkingDirectory.d.ts.map +1 -0
  253. package/dist/tools/shell/ShellWorkingDirectory.js +30 -0
  254. package/package.json +27 -24
@@ -0,0 +1,15 @@
1
+ import type { WorkState } from "../session/WorkTypes.js";
2
+ export interface WorkStatusQuery {
3
+ offset?: number;
4
+ limit?: number;
5
+ taskIds?: string[];
6
+ requirementIds?: string[];
7
+ record?: "goal" | "task" | "requirement" | "decision" | "phase" | "constraints";
8
+ recordId?: string;
9
+ textOffset?: number;
10
+ textLimit?: number;
11
+ }
12
+ /** Inspection must remain available even when the whole goal cannot fit in a
13
+ * model context. Previews are explicit; record chunks retrieve the exact JSON. */
14
+ export declare function workStatusPage(state: WorkState, query: WorkStatusQuery): Record<string, unknown>;
15
+ //# sourceMappingURL=WorkStatusPage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WorkStatusPage.d.ts","sourceRoot":"","sources":["../../src/runtime/WorkStatusPage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEzD,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,aAAa,GAAG,UAAU,GAAG,OAAO,GAAG,aAAa,CAAC;IAChF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;kFACkF;AAClF,wBAAgB,cAAc,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CA8ChG"}
@@ -0,0 +1,58 @@
1
+ /** Inspection must remain available even when the whole goal cannot fit in a
2
+ * model context. Previews are explicit; record chunks retrieve the exact JSON. */
3
+ export function workStatusPage(state, query) {
4
+ const offset = query.offset ?? 0, limit = query.limit ?? 20;
5
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 50)
6
+ throw new Error("Invalid status page");
7
+ if (query.record) {
8
+ const record = query.record === "goal" ? { goalId: state.goalId, goalRevision: state.goalRevision, originalObjective: state.originalObjective, objective: state.objective }
9
+ : query.record === "constraints" ? { constraints: state.constraints, nonGoals: state.nonGoals }
10
+ : (() => {
11
+ const records = query.record === "task" ? state.tasks : query.record === "requirement" ? state.requirements : query.record === "decision" ? state.decisions : state.phases ?? [];
12
+ return query.recordId ? records.find(item => item.id === query.recordId) : records;
13
+ })();
14
+ if (!record)
15
+ throw new Error("Unknown status record; supply its exact recordId");
16
+ const encoded = JSON.stringify(record), start = query.textOffset ?? 0, size = query.textLimit ?? 6000;
17
+ if (!Number.isSafeInteger(start) || start < 0 || start > encoded.length || !Number.isSafeInteger(size) || size < 1 || size > 6000)
18
+ throw new Error("Invalid status record text range");
19
+ const content = encoded.slice(start, start + size);
20
+ return { record: query.record, recordId: query.recordId, encoding: "json", content, textOffset: start,
21
+ totalChars: encoded.length, nextTextOffset: start + content.length < encoded.length ? start + content.length : null };
22
+ }
23
+ const tasks = state.tasks.filter(task => !query.taskIds || query.taskIds.includes(task.id));
24
+ const candidates = tasks.slice(offset, offset + limit);
25
+ const ids = new Set(query.requirementIds ?? candidates.flatMap(task => task.requirementIds));
26
+ const requirements = state.requirements.filter(requirement => ids.has(requirement.id));
27
+ const view = {
28
+ goalId: state.goalId, goalRevision: state.goalRevision, planRevision: state.planRevision ?? 1, status: state.status,
29
+ originalObjective: state.originalObjective.slice(0, 1200), originalObjectiveTruncated: state.originalObjective.length > 1200,
30
+ objective: state.objective.slice(0, 1200), objectiveTruncated: state.objective.length > 1200,
31
+ tasks: [], requirements: [],
32
+ totalTasks: tasks.length, totalRequirements: state.requirements.length,
33
+ totalDecisions: state.decisions.length, totalPhases: state.phases?.length ?? 0,
34
+ totalConstraints: state.constraints.length, totalNonGoals: state.nonGoals.length,
35
+ nextOffset: null, omittedRequirements: 0,
36
+ continuation: "This is a bounded inspection page, not the complete contract. Use offset/limit or taskIds/requirementIds for records. Use record:goal|constraints|task|requirement|decision|phase, recordId and textOffset to retrieve exact JSON in chunks. Every canonical requirement remains mandatory.",
37
+ };
38
+ const preview = (item) => JSON.stringify(item).length <= 2500 ? item
39
+ : { id: item.id, status: item.status, title: typeof item.title === "string" ? item.title.slice(0, 240) : undefined,
40
+ description: typeof item.description === "string" ? item.description.slice(0, 600) : undefined, recordTruncated: true };
41
+ for (const task of candidates) {
42
+ view.tasks.push(preview({ ...task }));
43
+ if (JSON.stringify(view).length > 9000) {
44
+ view.tasks.pop();
45
+ break;
46
+ }
47
+ }
48
+ view.nextOffset = offset + view.tasks.length < tasks.length ? offset + view.tasks.length : null;
49
+ for (const requirement of requirements) {
50
+ view.requirements.push(preview({ ...requirement }));
51
+ if (JSON.stringify(view).length > 12000) {
52
+ view.requirements.pop();
53
+ break;
54
+ }
55
+ }
56
+ view.omittedRequirements = requirements.length - view.requirements.length;
57
+ return view;
58
+ }
@@ -0,0 +1,13 @@
1
+ import { type WorkspaceSnapshot } from "./WorkspaceSnapshot.js";
2
+ /** Private original contents separate the agent's diff from a dirty checkout. */
3
+ export declare class WorkspaceLedger {
4
+ readonly root: string;
5
+ readonly workspaceRoot: string;
6
+ constructor(root: string, workspaceRoot: string);
7
+ private get manifest();
8
+ private read;
9
+ private readWorkspaceContent;
10
+ capture(snapshot: WorkspaceSnapshot, scopes: string[], explicitPaths?: string[]): Promise<void>;
11
+ diff(files: string[], limit?: number): Promise<string>;
12
+ }
13
+ //# sourceMappingURL=WorkspaceLedger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WorkspaceLedger.d.ts","sourceRoot":"","sources":["../../src/runtime/WorkspaceLedger.ts"],"names":[],"mappings":"AAIA,OAAO,EAAoC,KAAK,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAOlG,iFAAiF;AACjF,qBAAa,eAAe;IACd,QAAQ,CAAC,IAAI,EAAE,MAAM;IAAE,QAAQ,CAAC,aAAa,EAAE,MAAM;gBAA5C,IAAI,EAAE,MAAM,EAAW,aAAa,EAAE,MAAM;IAGjE,OAAO,KAAK,QAAQ,GAA6D;YACnE,IAAI;YAUJ,oBAAoB;IAoB5B,OAAO,CAAC,QAAQ,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,aAAa,GAAE,MAAM,EAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IA2BnG,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,KAAK,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC;CA+B7D"}
@@ -0,0 +1,145 @@
1
+ import { constants, promises as fs, realpathSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { execFile } from "node:child_process";
4
+ import { atomicWriteJson, withStateLock } from "../session/AtomicState.js";
5
+ import { hashWorkspacePath, workspaceHash } from "./WorkspaceSnapshot.js";
6
+ const MAX_FILE_BYTES = 8 * 1024 * 1024;
7
+ const inScope = (file, scopes) => scopes.some(scope => scope === "." || file === scope || file.startsWith(`${scope}/`));
8
+ /** Private original contents separate the agent's diff from a dirty checkout. */
9
+ export class WorkspaceLedger {
10
+ constructor(root, workspaceRoot) {
11
+ this.root = root;
12
+ this.workspaceRoot = workspaceRoot;
13
+ this.workspaceRoot = realpathSync.native(workspaceRoot);
14
+ }
15
+ get manifest() { return path.join(this.root, "ownership.json"); }
16
+ async read() {
17
+ try {
18
+ const value = JSON.parse(await fs.readFile(this.manifest, "utf8"));
19
+ if (value.schemaVersion !== 1 || !value.files)
20
+ throw new Error("Invalid workspace ownership ledger");
21
+ if (value.knownPaths !== undefined && (!Array.isArray(value.knownPaths) || value.knownPaths.some(file => typeof file !== "string" || path.isAbsolute(file) || file.split(/[\\/]/).includes(".."))))
22
+ throw new Error("Invalid workspace baseline inventory");
23
+ for (const [file, entry] of Object.entries(value.files))
24
+ if (path.isAbsolute(file) || file.split(/[\\/]/).includes("..") || !entry || typeof entry.hash !== "string" || entry.blob && !/^[a-f0-9]{64}$/.test(entry.blob))
25
+ throw new Error("Invalid workspace preimage reference");
26
+ return value;
27
+ }
28
+ catch (error) {
29
+ if (error.code === "ENOENT")
30
+ return { schemaVersion: 1, files: {} };
31
+ throw error;
32
+ }
33
+ }
34
+ async readWorkspaceContent(file, expectedHash) {
35
+ const target = path.resolve(this.workspaceRoot, file);
36
+ const parent = await fs.realpath(path.dirname(target));
37
+ if (!target.startsWith(`${this.workspaceRoot}${path.sep}`) || parent !== this.workspaceRoot && !parent.startsWith(`${this.workspaceRoot}${path.sep}`))
38
+ throw new Error("Workspace preimage path escapes the repository");
39
+ const handle = await fs.open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
40
+ try {
41
+ const before = await handle.stat();
42
+ if (!before.isFile() || before.size > MAX_FILE_BYTES)
43
+ throw new Error("Workspace content exceeds the 8 MiB file limit");
44
+ const chunks = [];
45
+ let bytes = 0;
46
+ for await (const chunk of handle.createReadStream({ autoClose: false })) {
47
+ bytes += chunk.length;
48
+ if (bytes > MAX_FILE_BYTES)
49
+ throw new Error("Workspace content exceeds the 8 MiB file limit");
50
+ chunks.push(Buffer.from(chunk));
51
+ }
52
+ const after = await handle.stat();
53
+ const content = Buffer.concat(chunks);
54
+ if (before.size !== after.size || before.ctimeMs !== after.ctimeMs || workspaceHash(content) !== expectedHash)
55
+ throw new Error(`File changed while preparing the edit or diff: ${file}`);
56
+ return content;
57
+ }
58
+ finally {
59
+ await handle.close();
60
+ }
61
+ }
62
+ async capture(snapshot, scopes, explicitPaths = []) {
63
+ await withStateLock(this.manifest, async () => {
64
+ const record = await this.read();
65
+ record.knownPaths ?? (record.knownPaths = Object.keys(snapshot.hashes));
66
+ const candidates = new Set([...Object.keys(snapshot.hashes).filter(file => inScope(file, scopes)), ...explicitPaths]);
67
+ let bytes = Object.values(record.files).reduce((sum, entry) => sum + (entry.bytes ?? 0), 0);
68
+ for (const file of candidates) {
69
+ if (record.files[file])
70
+ continue;
71
+ const hash = snapshot.hashes[file] ?? await hashWorkspacePath(this.workspaceRoot, file);
72
+ const entry = { hash };
73
+ if (/^[a-f0-9]{64}$/.test(hash)) {
74
+ const stat = await fs.lstat(path.join(this.workspaceRoot, file));
75
+ if (stat.size > 8 * 1024 * 1024 || bytes + stat.size > 64 * 1024 * 1024)
76
+ throw new Error("Task preimages exceed the 64 MiB ledger or 8 MiB file limit; narrow the task scope");
77
+ const content = await this.readWorkspaceContent(file, hash);
78
+ if (workspaceHash(content) !== hash || await hashWorkspacePath(this.workspaceRoot, file) !== hash)
79
+ throw new Error(`File changed while preparing the edit: ${file}`);
80
+ const blob = path.join(this.root, "blobs", hash);
81
+ await fs.mkdir(path.dirname(blob), { recursive: true, mode: 0o700 });
82
+ try {
83
+ await fs.writeFile(blob, content, { flag: "wx", mode: 0o600 });
84
+ }
85
+ catch (error) {
86
+ if (error.code !== "EEXIST")
87
+ throw error;
88
+ }
89
+ entry.blob = hash;
90
+ entry.bytes = content.length;
91
+ bytes += content.length;
92
+ }
93
+ record.files[file] = entry;
94
+ }
95
+ await atomicWriteJson(this.manifest, record);
96
+ });
97
+ }
98
+ async diff(files, limit = 60000) {
99
+ const record = await this.read();
100
+ const sections = [];
101
+ let length = 0;
102
+ await fs.mkdir(this.root, { recursive: true, mode: 0o700 });
103
+ for (const file of files) {
104
+ if (length >= limit)
105
+ break;
106
+ const entry = record.files[file] ?? (record.knownPaths && !record.knownPaths.includes(file) ? { hash: "missing" } : undefined);
107
+ if (!entry)
108
+ throw new Error(`No saved preimage for ${file}; session ownership cannot be established`);
109
+ const currentHash = await hashWorkspacePath(this.workspaceRoot, file);
110
+ if (currentHash === entry.hash)
111
+ continue;
112
+ if ((!entry.blob && entry.hash !== "missing") || currentHash.startsWith("symlink:") || currentHash.startsWith("directory:")) {
113
+ const summary = `${file}: ${entry.hash} -> ${currentHash}\n`;
114
+ sections.push(summary);
115
+ length += summary.length;
116
+ continue;
117
+ }
118
+ if (currentHash !== "missing" && (await fs.lstat(path.join(this.workspaceRoot, file))).size > MAX_FILE_BYTES) {
119
+ const summary = `${file}: ${entry.hash} -> ${currentHash} (content diff omitted above 8 MiB; validate the artifact separately)\n`;
120
+ sections.push(summary);
121
+ length += summary.length;
122
+ continue;
123
+ }
124
+ const directory = await fs.mkdtemp(path.join(this.root, "diff-"));
125
+ try {
126
+ const before = entry.blob ? await fs.readFile(path.join(this.root, "blobs", entry.blob)) : Buffer.alloc(0);
127
+ const after = currentHash === "missing" ? Buffer.alloc(0) : await this.readWorkspaceContent(file, currentHash);
128
+ if (entry.blob && workspaceHash(before) !== entry.hash)
129
+ throw new Error("Workspace preimage checksum mismatch");
130
+ if (after.length && workspaceHash(after) !== currentHash)
131
+ throw new Error(`File changed during diff: ${file}`);
132
+ await fs.writeFile(path.join(directory, "before"), before, { mode: 0o600 });
133
+ await fs.writeFile(path.join(directory, "after"), after, { mode: 0o600 });
134
+ const diff = await new Promise((resolve, reject) => execFile("git", ["--no-pager", "diff", "--no-index", "--no-ext-diff", "--no-textconv", "--", "before", "after"], { cwd: directory, timeout: 10000, maxBuffer: 32 * 1024 * 1024, env: { PATH: process.env.PATH, LANG: "C", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null" } }, (error, stdout) => error && error.code !== 1 ? reject(error) : resolve(stdout)));
135
+ const section = `Session changes: ${JSON.stringify(file)}\n${diff}`.slice(0, limit - length);
136
+ sections.push(section);
137
+ length += section.length;
138
+ }
139
+ finally {
140
+ await fs.rm(directory, { recursive: true, force: true });
141
+ }
142
+ }
143
+ return sections.join("\n");
144
+ }
145
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"WorkspaceLock.d.ts","sourceRoot":"","sources":["../../src/runtime/WorkspaceLock.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,0BAA0B;IACzC,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,OAAO,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5D,iBAAiB,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,OAAO,KAAK,MAAM,CAAC;CACxD;AAED,qBAAa,aAAa;IAMtB,OAAO,CAAC,aAAa;IACrB,OAAO,CAAC,KAAK;IACb,OAAO,CAAC,QAAQ;IAPlB,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAiB;gBAGhC,aAAa,EAAE,MAAM,EACrB,KAAK,EAAE,MAAM,EACb,QAAQ,GAAE,MAAuB;YAK7B,QAAQ;IAStB,OAAO,CAAC,OAAO;IAIf,OAAO,CAAC,UAAU;IAIlB,OAAO,CAAC,cAAc;YAcR,iBAAiB;YAuBjB,mBAAmB;IAQ3B,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAmBxB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAU9B,sBAAsB,CAAC,OAAO,GAAE,0BAA+B,GAAG,MAAM,IAAI;CAmC7E"}
1
+ {"version":3,"file":"WorkspaceLock.d.ts","sourceRoot":"","sources":["../../src/runtime/WorkspaceLock.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,0BAA0B;IACzC,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,OAAO,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5D,iBAAiB,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,OAAO,KAAK,MAAM,CAAC;CACxD;AAED,qBAAa,aAAa;IAMtB,OAAO,CAAC,aAAa;IACrB,OAAO,CAAC,KAAK;IACb,OAAO,CAAC,QAAQ;IAPlB,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAiB;gBAGhC,aAAa,EAAE,MAAM,EACrB,KAAK,EAAE,MAAM,EACb,QAAQ,GAAE,MAAuB;YAK7B,QAAQ;IAStB,OAAO,CAAC,OAAO;IAIf,OAAO,CAAC,UAAU;IAIlB,OAAO,CAAC,cAAc;YAcR,iBAAiB;YAuBjB,mBAAmB;IAQ3B,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAqBxB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAU9B,sBAAsB,CAAC,OAAO,GAAE,0BAA+B,GAAG,MAAM,IAAI;CAmC7E"}
@@ -1,6 +1,7 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
+ import { withStateLock } from "../session/AtomicState.js";
4
5
  export class WorkspaceLock {
5
6
  constructor(workspaceRoot, runId, maxAgeMs = 60 * 60 * 1000) {
6
7
  this.workspaceRoot = workspaceRoot;
@@ -69,32 +70,34 @@ export class WorkspaceLock {
69
70
  return false;
70
71
  }
71
72
  async shouldClearExisting(info) {
72
- if (this.isStale(info))
73
- return true;
74
73
  const processAlive = this.isProcessAlive(info);
75
74
  if (processAlive === false)
76
75
  return true;
77
76
  if (processAlive === true)
78
77
  return false;
78
+ if (this.isStale(info) && this.isSameHost(info))
79
+ return this.hasTerminalRunLog(info.runId);
79
80
  return this.hasTerminalRunLog(info.runId);
80
81
  }
81
82
  async acquire() {
82
83
  await fs.mkdir(path.dirname(this.lockPath), { recursive: true });
83
- const existing = await this.readLock();
84
- if (existing && !(await this.shouldClearExisting(existing))) {
85
- throw new Error(`Workspace is locked by run ${existing.runId}`);
86
- }
87
- if (existing) {
88
- await fs.unlink(this.lockPath).catch(() => undefined);
89
- }
90
- const payload = {
91
- runId: this.runId,
92
- acquiredAt: Date.now(),
93
- pid: process.pid,
94
- hostname: this.hostname,
95
- };
96
- await fs.writeFile(this.lockPath, JSON.stringify(payload, null, 2), "utf8");
97
- this.acquired = true;
84
+ await withStateLock(`${this.lockPath}.transaction`, async () => {
85
+ const existing = await this.readLock();
86
+ if (existing && !(await this.shouldClearExisting(existing))) {
87
+ throw new Error(`Workspace is locked by run ${existing.runId}`);
88
+ }
89
+ if (existing) {
90
+ await fs.unlink(this.lockPath).catch(() => undefined);
91
+ }
92
+ const payload = {
93
+ runId: this.runId,
94
+ acquiredAt: Date.now(),
95
+ pid: process.pid,
96
+ hostname: this.hostname,
97
+ };
98
+ await fs.writeFile(this.lockPath, JSON.stringify(payload, null, 2), { encoding: "utf8", flag: "wx", mode: 0o600 });
99
+ this.acquired = true;
100
+ });
98
101
  }
99
102
  async release() {
100
103
  if (!this.acquired)
@@ -0,0 +1,13 @@
1
+ export interface WorkspaceSnapshot {
2
+ git: boolean;
3
+ head?: string;
4
+ hashes: Record<string, string>;
5
+ dirtyPaths: string[];
6
+ }
7
+ export declare const workspaceGit: (root: string, args: string[]) => Promise<string>;
8
+ export declare const workspaceHash: (value: string | Buffer) => string;
9
+ /** The same content identity is used by baselines, validation and completion. */
10
+ export declare const hashWorkspacePath: (root: string, relative: string) => Promise<string>;
11
+ export declare const captureWorkspace: (root: string) => Promise<WorkspaceSnapshot>;
12
+ export declare const changedWorkspacePaths: (before: WorkspaceSnapshot, after: WorkspaceSnapshot) => string[];
13
+ //# sourceMappingURL=WorkspaceSnapshot.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WorkspaceSnapshot.d.ts","sourceRoot":"","sources":["../../src/runtime/WorkspaceSnapshot.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,iBAAiB;IAAG,GAAG,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,UAAU,EAAE,MAAM,EAAE,CAAC;CAAE;AACzH,eAAO,MAAM,YAAY,GAAI,MAAM,MAAM,EAAE,MAAM,MAAM,EAAE,KAAG,OAAO,CAAC,MAAM,CAKxE,CAAC;AACH,eAAO,MAAM,aAAa,GAAI,OAAO,MAAM,GAAG,MAAM,KAAG,MAA0D,CAAC;AAClH,iFAAiF;AACjF,eAAO,MAAM,iBAAiB,GAAU,MAAM,MAAM,EAAE,UAAU,MAAM,KAAG,OAAO,CAAC,MAAM,CAuBtF,CAAC;AACF,eAAO,MAAM,gBAAgB,GAAU,MAAM,MAAM,KAAG,OAAO,CAAC,iBAAiB,CA+B9E,CAAC;AACF,eAAO,MAAM,qBAAqB,GAAI,QAAQ,iBAAiB,EAAE,OAAO,iBAAiB,KAAG,MAAM,EACsC,CAAC"}
@@ -0,0 +1,88 @@
1
+ import { createHash } from "node:crypto";
2
+ import { constants, promises as fs } from "node:fs";
3
+ import path from "node:path";
4
+ import { execFile } from "node:child_process";
5
+ export const workspaceGit = (root, args) => new Promise((resolve, reject) => {
6
+ execFile("git", ["--no-optional-locks", "-c", "core.fsmonitor=false", ...args], {
7
+ cwd: root, timeout: 15000, maxBuffer: 8 * 1024 * 1024,
8
+ env: { PATH: process.env.PATH, LANG: "C", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_TERMINAL_PROMPT: "0" },
9
+ }, (error, output) => error ? reject(new Error(`Git inspection failed (${error.code ?? "unknown"})`)) : resolve(output));
10
+ });
11
+ export const workspaceHash = (value) => createHash("sha256").update(value).digest("hex");
12
+ /** The same content identity is used by baselines, validation and completion. */
13
+ export const hashWorkspacePath = async (root, relative) => {
14
+ root = await fs.realpath(root);
15
+ const file = path.resolve(root, relative);
16
+ if (!file.startsWith(`${root}${path.sep}`))
17
+ throw new Error("Unsafe workspace inventory path");
18
+ try {
19
+ const parent = await fs.realpath(path.dirname(file));
20
+ if (parent !== root && !parent.startsWith(`${root}${path.sep}`))
21
+ throw new Error("Workspace parent symlink escapes the repository");
22
+ const stat = await fs.lstat(file);
23
+ if (stat.isSymbolicLink())
24
+ return `symlink:${await fs.readlink(file)}`;
25
+ if (!stat.isFile())
26
+ return `directory:${stat.ino}`;
27
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
28
+ try {
29
+ const before = await handle.stat();
30
+ const digest = createHash("sha256");
31
+ for await (const chunk of handle.createReadStream({ autoClose: false }))
32
+ digest.update(chunk);
33
+ const after = await handle.stat();
34
+ if (before.ino !== stat.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs)
35
+ throw new Error(`Workspace file changed during inspection: ${relative}`);
36
+ return digest.digest("hex");
37
+ }
38
+ finally {
39
+ await handle.close();
40
+ }
41
+ }
42
+ catch (error) {
43
+ if (error.code === "ENOENT")
44
+ return "missing";
45
+ throw error;
46
+ }
47
+ };
48
+ export const captureWorkspace = async (root) => {
49
+ root = await fs.realpath(root);
50
+ const snapshot = { git: true, hashes: {}, dirtyPaths: [] };
51
+ let files;
52
+ try {
53
+ files = (await workspaceGit(root, ["ls-files", "-z", "--cached", "--others", "--exclude-standard"])).split("\0").filter(Boolean);
54
+ snapshot.head = await workspaceGit(root, ["rev-parse", "HEAD"]).then(v => v.trim()).catch(() => "unborn");
55
+ const dirty = await Promise.all([
56
+ workspaceGit(root, ["diff", "--relative", "--no-ext-diff", "--no-textconv", "--name-only", "-z"]),
57
+ workspaceGit(root, ["diff", "--cached", "--relative", "--no-ext-diff", "--no-textconv", "--name-only", "-z"]),
58
+ workspaceGit(root, ["ls-files", "--others", "--exclude-standard", "-z"]),
59
+ ]);
60
+ snapshot.dirtyPaths = [...new Set(dirty.flatMap(value => value.split("\0").filter(Boolean)))].sort();
61
+ }
62
+ catch {
63
+ snapshot.git = false;
64
+ files = [];
65
+ const walk = async (directory) => {
66
+ for (const entry of await fs.readdir(path.join(root, directory), { withFileTypes: true })) {
67
+ if ([".git", "node_modules", ".docdex", ".mcoda", ".codali", "dist", "build"].includes(entry.name))
68
+ continue;
69
+ const relative = path.join(directory, entry.name);
70
+ if (entry.isDirectory())
71
+ await walk(relative);
72
+ else
73
+ files.push(relative);
74
+ if (files.length > 20000)
75
+ throw new Error("Workspace inventory exceeds 20000 files; narrow the workspace");
76
+ }
77
+ };
78
+ await walk("");
79
+ }
80
+ files = [...new Set(files)].filter(file => !/^(?:\.docdex|\.mcoda|\.codali)\//.test(file));
81
+ if (files.length > 20000)
82
+ throw new Error("Workspace inventory exceeds 20000 files; narrow the workspace");
83
+ for (const relative of files) {
84
+ snapshot.hashes[relative] = await hashWorkspacePath(root, relative);
85
+ }
86
+ return snapshot;
87
+ };
88
+ export const changedWorkspacePaths = (before, after) => [...new Set([...Object.keys(before.hashes), ...Object.keys(after.hashes)])].filter(file => before.hashes[file] !== after.hashes[file]);
@@ -0,0 +1,13 @@
1
+ /** Windows cannot flush a directory handle through Node's fsync. File contents
2
+ * are still flushed before publication; POSIX directory durability is retained. */
3
+ export declare const syncStateDirectory: (directory: string) => Promise<void>;
4
+ export declare const atomicWriteJson: (file: string, value: unknown) => Promise<void>;
5
+ /** Probe an execution lock without relying on process IDs or waiting behind a live owner. */
6
+ export declare const tryStateLock: <T>(file: string, operation: () => Promise<T>) => Promise<{
7
+ acquired: false;
8
+ } | {
9
+ acquired: true;
10
+ value: T;
11
+ }>;
12
+ export declare const withStateLock: <T>(file: string, operation: () => Promise<T>, timeoutMs?: number) => Promise<T>;
13
+ //# sourceMappingURL=AtomicState.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AtomicState.d.ts","sourceRoot":"","sources":["../../src/session/AtomicState.ts"],"names":[],"mappings":"AAMA;mFACmF;AACnF,eAAO,MAAM,kBAAkB,GAAU,WAAW,MAAM,KAAG,OAAO,CAAC,IAAI,CAOxE,CAAC;AAEF,eAAO,MAAM,eAAe,GAAU,MAAM,MAAM,EAAE,OAAO,OAAO,KAAG,OAAO,CAAC,IAAI,CAyBhF,CAAC;AAIF,6FAA6F;AAC7F,eAAO,MAAM,YAAY,GAAU,CAAC,EAAE,MAAM,MAAM,EAAE,WAAW,MAAM,OAAO,CAAC,CAAC,CAAC,KAAG,OAAO,CAAC;IAAE,QAAQ,EAAE,KAAK,CAAA;CAAE,GAAG;IAAE,QAAQ,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,CAK3I,CAAC;AACF,eAAO,MAAM,aAAa,GAAU,CAAC,EAAE,MAAM,MAAM,EAAE,WAAW,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,kBAAkB,KAAG,OAAO,CAAC,CAAC,CAS/G,CAAC"}
@@ -0,0 +1,123 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { promises as fs } from "node:fs";
3
+ import path from "node:path";
4
+ import { Connection } from "@mcoda/db";
5
+ import { assertRegularStateFile } from "./SessionStoragePath.js";
6
+ /** Windows cannot flush a directory handle through Node's fsync. File contents
7
+ * are still flushed before publication; POSIX directory durability is retained. */
8
+ export const syncStateDirectory = async (directory) => {
9
+ const handle = await fs.open(directory, "r");
10
+ try {
11
+ await handle.sync();
12
+ }
13
+ catch (error) {
14
+ const code = error.code ?? "";
15
+ if (!["EINVAL", "ENOTSUP"].includes(code) && !(process.platform === "win32" && code === "EPERM"))
16
+ throw error;
17
+ }
18
+ finally {
19
+ await handle.close();
20
+ }
21
+ };
22
+ export const atomicWriteJson = async (file, value) => {
23
+ await assertRegularStateFile(file);
24
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
25
+ const temporary = `${file}.${randomUUID()}.tmp`;
26
+ const handle = await fs.open(temporary, "wx", 0o600);
27
+ try {
28
+ await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`, "utf8");
29
+ await handle.sync();
30
+ await handle.close();
31
+ // A concurrent Windows reader or scanner can briefly deny replacement.
32
+ // Retry the same atomic rename; never remove the previous durable state.
33
+ for (let attempt = 0;; attempt++) {
34
+ try {
35
+ await fs.rename(temporary, file);
36
+ break;
37
+ }
38
+ catch (error) {
39
+ const code = error.code ?? "";
40
+ if (process.platform !== "win32" || !["EPERM", "EACCES", "EBUSY"].includes(code) || attempt >= 7)
41
+ throw error;
42
+ await assertRegularStateFile(file);
43
+ await new Promise(resolve => setTimeout(resolve, Math.min(20 * 2 ** attempt, 160)));
44
+ }
45
+ }
46
+ await syncStateDirectory(path.dirname(file));
47
+ }
48
+ finally {
49
+ await handle.close().catch(() => undefined);
50
+ await fs.unlink(temporary).catch(() => undefined);
51
+ }
52
+ };
53
+ /** Short storage transaction lock. Never hold across inference or tool execution. */
54
+ const localTransactions = new Map();
55
+ /** Probe an execution lock without relying on process IDs or waiting behind a live owner. */
56
+ export const tryStateLock = async (file, operation) => {
57
+ if (localTransactions.has(file))
58
+ return { acquired: false };
59
+ let entered = false;
60
+ try {
61
+ return { acquired: true, value: await withStateLock(file, async () => { entered = true; return operation(); }, 0) };
62
+ }
63
+ catch (error) {
64
+ if (!entered && error.code === "SQLITE_BUSY")
65
+ return { acquired: false };
66
+ throw error;
67
+ }
68
+ };
69
+ export const withStateLock = async (file, operation, timeoutMs = 10000) => {
70
+ const previous = localTransactions.get(file) ?? Promise.resolve();
71
+ let release;
72
+ const next = new Promise(resolve => { release = resolve; });
73
+ const tail = previous.then(() => next);
74
+ localTransactions.set(file, tail);
75
+ await previous;
76
+ try {
77
+ return await transact(file, operation, timeoutMs);
78
+ }
79
+ finally {
80
+ release();
81
+ if (localTransactions.get(file) === tail)
82
+ localTransactions.delete(file);
83
+ }
84
+ };
85
+ const transact = async (file, operation, timeoutMs) => {
86
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
87
+ // Reuse mcoda's SQLite dependency for an OS-owned transaction lock. A killed
88
+ // process releases it automatically, without PID reuse or stale recovery files.
89
+ const databasePath = `${file}.transactions.sqlite`;
90
+ for (const suffix of ["", "-wal", "-shm", "-journal"])
91
+ await assertRegularStateFile(databasePath + suffix);
92
+ const connection = await Connection.open(databasePath);
93
+ try {
94
+ await fs.chmod(databasePath, 0o600);
95
+ // Do not park SQLite busy handlers on libuv threads needed by the owner to
96
+ // finish its filesystem transaction. Retry asynchronously across processes.
97
+ await connection.db.exec("PRAGMA busy_timeout = 0;");
98
+ const deadline = Date.now() + timeoutMs;
99
+ while (true) {
100
+ try {
101
+ await connection.db.exec("BEGIN IMMEDIATE;");
102
+ break;
103
+ }
104
+ catch (error) {
105
+ if (error.code !== "SQLITE_BUSY" || Date.now() >= deadline)
106
+ throw error;
107
+ await new Promise(resolve => setTimeout(resolve, 20));
108
+ }
109
+ }
110
+ try {
111
+ const result = await operation();
112
+ await connection.db.exec("COMMIT;");
113
+ return result;
114
+ }
115
+ catch (error) {
116
+ await connection.db.exec("ROLLBACK;").catch(() => undefined);
117
+ throw error;
118
+ }
119
+ }
120
+ finally {
121
+ await connection.close();
122
+ }
123
+ };
@@ -0,0 +1,15 @@
1
+ /** Existing state files must not alias another file or an external endpoint. */
2
+ export declare function assertRegularStateFile(file: string): Promise<void>;
3
+ /** Resolve trusted outer aliases (e.g. macOS /var) once, then reject symlinks
4
+ * beneath the storage boundary. The terminal sandbox prevents model processes
5
+ * from replacing these parents; this is not isolation from a hostile OS user. */
6
+ export declare function sessionStoragePath(options: {
7
+ workspaceRoot: string;
8
+ storageRoot: string;
9
+ file: string;
10
+ allowExternal: boolean;
11
+ createParents?: boolean;
12
+ directory?: boolean;
13
+ }): Promise<string>;
14
+ export declare function readStateFile(file: string): Promise<string>;
15
+ //# sourceMappingURL=SessionStoragePath.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SessionStoragePath.d.ts","sourceRoot":"","sources":["../../src/session/SessionStoragePath.ts"],"names":[],"mappings":"AAGA,gFAAgF;AAChF,wBAAsB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAWxE;AAED;;iFAEiF;AACjF,wBAAsB,kBAAkB,CAAC,OAAO,EAAE;IAChD,aAAa,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,aAAa,EAAE,OAAO,CAAC;IAAC,aAAa,CAAC,EAAE,OAAO,CAAC;IAAC,SAAS,CAAC,EAAE,OAAO,CAAC;CAChI,GAAG,OAAO,CAAC,MAAM,CAAC,CAuClB;AAED,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAUjE"}