@nexum-hub/agent 0.0.0-stage → 0.0.1

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 (343) hide show
  1. package/README.md +129 -2
  2. package/contracts/v2/common.schema.json +262 -0
  3. package/contracts/v2/fixtures/inputs.json +244 -0
  4. package/contracts/v2/fixtures/wire.json +6493 -0
  5. package/contracts/v2/model/agent.close.input.schema.json +14 -0
  6. package/contracts/v2/model/agent.close.output.schema.json +101 -0
  7. package/contracts/v2/model/agent.list.input.schema.json +57 -0
  8. package/contracts/v2/model/agent.list.output.schema.json +220 -0
  9. package/contracts/v2/model/agent.open.input.schema.json +35 -0
  10. package/contracts/v2/model/agent.open.output.schema.json +41 -0
  11. package/contracts/v2/model/agent.run.cancel.input.schema.json +18 -0
  12. package/contracts/v2/model/agent.run.cancel.output.schema.json +100 -0
  13. package/contracts/v2/model/agent.run.get.input.schema.json +41 -0
  14. package/contracts/v2/model/agent.run.get.output.schema.json +100 -0
  15. package/contracts/v2/model/agent.run.input.input.schema.json +30 -0
  16. package/contracts/v2/model/agent.run.input.output.schema.json +100 -0
  17. package/contracts/v2/model/agent.run.list.input.schema.json +47 -0
  18. package/contracts/v2/model/agent.run.list.output.schema.json +41 -0
  19. package/contracts/v2/model/agent.run.start.input.schema.json +73 -0
  20. package/contracts/v2/model/agent.run.start.output.schema.json +100 -0
  21. package/contracts/v2/wire/bodies.schema.json +383 -0
  22. package/contracts/v2/wire/envelope.schema.json +2280 -0
  23. package/contracts/v2/wire/events.schema.json +242 -0
  24. package/contracts/v2/wire/maintenance.schema.json +308 -0
  25. package/contracts/v2/wire/operations.schema.json +1791 -0
  26. package/contracts/v2/wire/stream.schema.json +74 -0
  27. package/contracts/v2/wire/types.schema.json +2616 -0
  28. package/dist/adapters/mcp-http.d.ts +22 -0
  29. package/dist/adapters/mcp-http.js +472 -0
  30. package/dist/adapters/mcp-http.js.map +1 -0
  31. package/dist/adapters/mcp-oauth.d.ts +29 -0
  32. package/dist/adapters/mcp-oauth.js +653 -0
  33. package/dist/adapters/mcp-oauth.js.map +1 -0
  34. package/dist/adapters/mcp-wire.d.ts +21 -0
  35. package/dist/adapters/mcp-wire.js +307 -0
  36. package/dist/adapters/mcp-wire.js.map +1 -0
  37. package/dist/adapters/mcp.d.ts +56 -0
  38. package/dist/adapters/mcp.js +1989 -0
  39. package/dist/adapters/mcp.js.map +1 -0
  40. package/dist/adapters/openapi-http.d.ts +29 -0
  41. package/dist/adapters/openapi-http.js +504 -0
  42. package/dist/adapters/openapi-http.js.map +1 -0
  43. package/dist/adapters/openapi-request.d.ts +26 -0
  44. package/dist/adapters/openapi-request.js +597 -0
  45. package/dist/adapters/openapi-request.js.map +1 -0
  46. package/dist/adapters/openapi-schema.d.ts +22 -0
  47. package/dist/adapters/openapi-schema.js +471 -0
  48. package/dist/adapters/openapi-schema.js.map +1 -0
  49. package/dist/adapters/openapi-typegen.d.ts +11 -0
  50. package/dist/adapters/openapi-typegen.js +185 -0
  51. package/dist/adapters/openapi-typegen.js.map +1 -0
  52. package/dist/adapters/openapi-types.d.ts +99 -0
  53. package/dist/adapters/openapi-types.js +2 -0
  54. package/dist/adapters/openapi-types.js.map +1 -0
  55. package/dist/adapters/openapi.d.ts +7 -0
  56. package/dist/adapters/openapi.js +768 -0
  57. package/dist/adapters/openapi.js.map +1 -0
  58. package/dist/application/activation.d.ts +28 -0
  59. package/dist/application/activation.js +289 -0
  60. package/dist/application/activation.js.map +1 -0
  61. package/dist/application/attachments.d.ts +24 -0
  62. package/dist/application/attachments.js +87 -0
  63. package/dist/application/attachments.js.map +1 -0
  64. package/dist/application/authority.d.ts +32 -0
  65. package/dist/application/authority.js +213 -0
  66. package/dist/application/authority.js.map +1 -0
  67. package/dist/application/catalog.d.ts +11 -0
  68. package/dist/application/catalog.js +177 -0
  69. package/dist/application/catalog.js.map +1 -0
  70. package/dist/application/config.d.ts +24 -0
  71. package/dist/application/config.js +140 -0
  72. package/dist/application/config.js.map +1 -0
  73. package/dist/application/connection.d.ts +35 -0
  74. package/dist/application/connection.js +465 -0
  75. package/dist/application/connection.js.map +1 -0
  76. package/dist/application/data-plane.d.ts +35 -0
  77. package/dist/application/data-plane.js +437 -0
  78. package/dist/application/data-plane.js.map +1 -0
  79. package/dist/application/diagnostics.d.ts +4 -0
  80. package/dist/application/diagnostics.js +65 -0
  81. package/dist/application/diagnostics.js.map +1 -0
  82. package/dist/application/dispatcher.d.ts +4 -0
  83. package/dist/application/dispatcher.js +16 -0
  84. package/dist/application/dispatcher.js.map +1 -0
  85. package/dist/application/main.d.ts +12 -0
  86. package/dist/application/main.js +167 -0
  87. package/dist/application/main.js.map +1 -0
  88. package/dist/application/maintenance.d.ts +27 -0
  89. package/dist/application/maintenance.js +244 -0
  90. package/dist/application/maintenance.js.map +1 -0
  91. package/dist/application/packages.d.ts +25 -0
  92. package/dist/application/packages.js +208 -0
  93. package/dist/application/packages.js.map +1 -0
  94. package/dist/application/processes.d.ts +49 -0
  95. package/dist/application/processes.js +180 -0
  96. package/dist/application/processes.js.map +1 -0
  97. package/dist/application/run-view.d.ts +17 -0
  98. package/dist/application/run-view.js +286 -0
  99. package/dist/application/run-view.js.map +1 -0
  100. package/dist/application/runtime.d.ts +78 -0
  101. package/dist/application/runtime.js +1747 -0
  102. package/dist/application/runtime.js.map +1 -0
  103. package/dist/application/tasks.d.ts +38 -0
  104. package/dist/application/tasks.js +23 -0
  105. package/dist/application/tasks.js.map +1 -0
  106. package/dist/application/user-state.d.ts +20 -0
  107. package/dist/application/user-state.js +52 -0
  108. package/dist/application/user-state.js.map +1 -0
  109. package/dist/application/work-git.d.ts +14 -0
  110. package/dist/application/work-git.js +67 -0
  111. package/dist/application/work-git.js.map +1 -0
  112. package/dist/cli.d.ts +2 -0
  113. package/dist/cli.js +40 -0
  114. package/dist/cli.js.map +1 -0
  115. package/dist/contracts/caller.d.ts +51 -0
  116. package/dist/contracts/caller.js +95 -0
  117. package/dist/contracts/caller.js.map +1 -0
  118. package/dist/contracts/error-data.d.ts +6 -0
  119. package/dist/contracts/error-data.js +51 -0
  120. package/dist/contracts/error-data.js.map +1 -0
  121. package/dist/contracts/errors.d.ts +10 -0
  122. package/dist/contracts/errors.js +28 -0
  123. package/dist/contracts/errors.js.map +1 -0
  124. package/dist/contracts/json.d.ts +9 -0
  125. package/dist/contracts/json.js +104 -0
  126. package/dist/contracts/json.js.map +1 -0
  127. package/dist/contracts/types.d.ts +122 -0
  128. package/dist/contracts/types.js +19 -0
  129. package/dist/contracts/types.js.map +1 -0
  130. package/dist/contracts/validation.d.ts +4 -0
  131. package/dist/contracts/validation.js +157 -0
  132. package/dist/contracts/validation.js.map +1 -0
  133. package/dist/contracts/wire-validation.d.ts +9 -0
  134. package/dist/contracts/wire-validation.js +399 -0
  135. package/dist/contracts/wire-validation.js.map +1 -0
  136. package/dist/contracts/wire.d.ts +1083 -0
  137. package/dist/contracts/wire.js +62 -0
  138. package/dist/contracts/wire.js.map +1 -0
  139. package/dist/extension-api.d.ts +12 -0
  140. package/dist/extension-api.js +2 -0
  141. package/dist/extension-api.js.map +1 -0
  142. package/dist/extensions/api.d.ts +72 -0
  143. package/dist/extensions/api.js +2 -0
  144. package/dist/extensions/api.js.map +1 -0
  145. package/dist/extensions/host-requests.d.ts +23 -0
  146. package/dist/extensions/host-requests.js +60 -0
  147. package/dist/extensions/host-requests.js.map +1 -0
  148. package/dist/extensions/materials.d.ts +37 -0
  149. package/dist/extensions/materials.js +691 -0
  150. package/dist/extensions/materials.js.map +1 -0
  151. package/dist/extensions/package-loader.d.ts +28 -0
  152. package/dist/extensions/package-loader.js +177 -0
  153. package/dist/extensions/package-loader.js.map +1 -0
  154. package/dist/extensions/packages.d.ts +73 -0
  155. package/dist/extensions/packages.js +441 -0
  156. package/dist/extensions/packages.js.map +1 -0
  157. package/dist/extensions/registry.d.ts +92 -0
  158. package/dist/extensions/registry.js +1540 -0
  159. package/dist/extensions/registry.js.map +1 -0
  160. package/dist/extensions/resources.d.ts +105 -0
  161. package/dist/extensions/resources.js +595 -0
  162. package/dist/extensions/resources.js.map +1 -0
  163. package/dist/extensions/state.d.ts +25 -0
  164. package/dist/extensions/state.js +10 -0
  165. package/dist/extensions/state.js.map +1 -0
  166. package/dist/extensions/transfer.d.ts +81 -0
  167. package/dist/extensions/transfer.js +16 -0
  168. package/dist/extensions/transfer.js.map +1 -0
  169. package/dist/index.d.ts +7 -0
  170. package/dist/index.js +25 -0
  171. package/dist/index.js.map +1 -0
  172. package/dist/maintenance/configuration.d.ts +79 -0
  173. package/dist/maintenance/configuration.js +1503 -0
  174. package/dist/maintenance/configuration.js.map +1 -0
  175. package/dist/maintenance/credentials.d.ts +23 -0
  176. package/dist/maintenance/credentials.js +177 -0
  177. package/dist/maintenance/credentials.js.map +1 -0
  178. package/dist/maintenance/files.d.ts +2 -0
  179. package/dist/maintenance/files.js +40 -0
  180. package/dist/maintenance/files.js.map +1 -0
  181. package/dist/maintenance/npm.d.ts +71 -0
  182. package/dist/maintenance/npm.js +1013 -0
  183. package/dist/maintenance/npm.js.map +1 -0
  184. package/dist/maintenance/oauth.d.ts +45 -0
  185. package/dist/maintenance/oauth.js +686 -0
  186. package/dist/maintenance/oauth.js.map +1 -0
  187. package/dist/maintenance/requests.d.ts +347 -0
  188. package/dist/maintenance/requests.js +959 -0
  189. package/dist/maintenance/requests.js.map +1 -0
  190. package/dist/maintenance/work-git.d.ts +29 -0
  191. package/dist/maintenance/work-git.js +776 -0
  192. package/dist/maintenance/work-git.js.map +1 -0
  193. package/dist/process/backend.d.ts +54 -0
  194. package/dist/process/backend.js +39 -0
  195. package/dist/process/backend.js.map +1 -0
  196. package/dist/process/environment-windows.d.ts +15 -0
  197. package/dist/process/environment-windows.js +151 -0
  198. package/dist/process/environment-windows.js.map +1 -0
  199. package/dist/process/environment.d.ts +28 -0
  200. package/dist/process/environment.js +410 -0
  201. package/dist/process/environment.js.map +1 -0
  202. package/dist/process/launch.d.ts +31 -0
  203. package/dist/process/launch.js +281 -0
  204. package/dist/process/launch.js.map +1 -0
  205. package/dist/process/managed.d.ts +36 -0
  206. package/dist/process/managed.js +459 -0
  207. package/dist/process/managed.js.map +1 -0
  208. package/dist/process/output-log.d.ts +50 -0
  209. package/dist/process/output-log.js +552 -0
  210. package/dist/process/output-log.js.map +1 -0
  211. package/dist/process/pipes.d.ts +16 -0
  212. package/dist/process/pipes.js +588 -0
  213. package/dist/process/pipes.js.map +1 -0
  214. package/dist/process/pty.d.ts +22 -0
  215. package/dist/process/pty.js +512 -0
  216. package/dist/process/pty.js.map +1 -0
  217. package/dist/process/windows-conout-worker.d.ts +1 -0
  218. package/dist/process/windows-conout-worker.js +90 -0
  219. package/dist/process/windows-conout-worker.js.map +1 -0
  220. package/dist/process/windows-conout.d.ts +46 -0
  221. package/dist/process/windows-conout.js +140 -0
  222. package/dist/process/windows-conout.js.map +1 -0
  223. package/dist/process/windows-helper.d.ts +43 -0
  224. package/dist/process/windows-helper.js +255 -0
  225. package/dist/process/windows-helper.js.map +1 -0
  226. package/dist/process/windows-job.d.ts +39 -0
  227. package/dist/process/windows-job.js +224 -0
  228. package/dist/process/windows-job.js.map +1 -0
  229. package/dist/process/windows-pipes.d.ts +16 -0
  230. package/dist/process/windows-pipes.js +475 -0
  231. package/dist/process/windows-pipes.js.map +1 -0
  232. package/dist/results/artifacts.d.ts +118 -0
  233. package/dist/results/artifacts.js +873 -0
  234. package/dist/results/artifacts.js.map +1 -0
  235. package/dist/results/encoder.d.ts +57 -0
  236. package/dist/results/encoder.js +1179 -0
  237. package/dist/results/encoder.js.map +1 -0
  238. package/dist/results/mcp.d.ts +95 -0
  239. package/dist/results/mcp.js +656 -0
  240. package/dist/results/mcp.js.map +1 -0
  241. package/dist/results/media.d.ts +19 -0
  242. package/dist/results/media.js +301 -0
  243. package/dist/results/media.js.map +1 -0
  244. package/dist/results/normalize.d.ts +29 -0
  245. package/dist/results/normalize.js +464 -0
  246. package/dist/results/normalize.js.map +1 -0
  247. package/dist/runtime/control-scripts.d.ts +23 -0
  248. package/dist/runtime/control-scripts.js +242 -0
  249. package/dist/runtime/control-scripts.js.map +1 -0
  250. package/dist/runtime/engine.d.ts +177 -0
  251. package/dist/runtime/engine.js +1159 -0
  252. package/dist/runtime/engine.js.map +1 -0
  253. package/dist/runtime/globals.d.ts +1 -0
  254. package/dist/runtime/globals.js +31 -0
  255. package/dist/runtime/globals.js.map +1 -0
  256. package/dist/runtime/material-retention.d.ts +34 -0
  257. package/dist/runtime/material-retention.js +671 -0
  258. package/dist/runtime/material-retention.js.map +1 -0
  259. package/dist/runtime/modules.d.ts +50 -0
  260. package/dist/runtime/modules.js +320 -0
  261. package/dist/runtime/modules.js.map +1 -0
  262. package/dist/runtime/names.d.ts +2 -0
  263. package/dist/runtime/names.js +22 -0
  264. package/dist/runtime/names.js.map +1 -0
  265. package/dist/runtime/operations.d.ts +20 -0
  266. package/dist/runtime/operations.js +137 -0
  267. package/dist/runtime/operations.js.map +1 -0
  268. package/dist/runtime/paths.d.ts +3 -0
  269. package/dist/runtime/paths.js +38 -0
  270. package/dist/runtime/paths.js.map +1 -0
  271. package/dist/runtime/promises.d.ts +9 -0
  272. package/dist/runtime/promises.js +78 -0
  273. package/dist/runtime/promises.js.map +1 -0
  274. package/dist/runtime/retention.d.ts +88 -0
  275. package/dist/runtime/retention.js +735 -0
  276. package/dist/runtime/retention.js.map +1 -0
  277. package/dist/runtime/run-log.d.ts +30 -0
  278. package/dist/runtime/run-log.js +207 -0
  279. package/dist/runtime/run-log.js.map +1 -0
  280. package/dist/runtime/scripts.d.ts +84 -0
  281. package/dist/runtime/scripts.js +387 -0
  282. package/dist/runtime/scripts.js.map +1 -0
  283. package/dist/runtime/tasks.d.ts +54 -0
  284. package/dist/runtime/tasks.js +290 -0
  285. package/dist/runtime/tasks.js.map +1 -0
  286. package/dist/sdk/maintenance.d.ts +3 -0
  287. package/dist/sdk/maintenance.js +80 -0
  288. package/dist/sdk/maintenance.js.map +1 -0
  289. package/dist/sdk/output-extension.d.ts +3 -0
  290. package/dist/sdk/output-extension.js +44 -0
  291. package/dist/sdk/output-extension.js.map +1 -0
  292. package/dist/sdk/output.d.ts +52 -0
  293. package/dist/sdk/output.js +350 -0
  294. package/dist/sdk/output.js.map +1 -0
  295. package/dist/sdk/runtime.d.ts +3 -0
  296. package/dist/sdk/runtime.js +26 -0
  297. package/dist/sdk/runtime.js.map +1 -0
  298. package/dist/sdk/sh.d.ts +3 -0
  299. package/dist/sdk/sh.js +384 -0
  300. package/dist/sdk/sh.js.map +1 -0
  301. package/dist/sdk/state.d.ts +2 -0
  302. package/dist/sdk/state.js +69 -0
  303. package/dist/sdk/state.js.map +1 -0
  304. package/dist/sdk/transfer.d.ts +3 -0
  305. package/dist/sdk/transfer.js +141 -0
  306. package/dist/sdk/transfer.js.map +1 -0
  307. package/dist/services/extensions.d.ts +19 -0
  308. package/dist/services/extensions.js +183 -0
  309. package/dist/services/extensions.js.map +1 -0
  310. package/dist/services/state.d.ts +37 -0
  311. package/dist/services/state.js +125 -0
  312. package/dist/services/state.js.map +1 -0
  313. package/dist/services/transfer.d.ts +86 -0
  314. package/dist/services/transfer.js +948 -0
  315. package/dist/services/transfer.js.map +1 -0
  316. package/dist/storage/schema.d.ts +8 -0
  317. package/dist/storage/schema.js +241 -0
  318. package/dist/storage/schema.js.map +1 -0
  319. package/dist/storage/sqlite.d.ts +241 -0
  320. package/dist/storage/sqlite.js +1855 -0
  321. package/dist/storage/sqlite.js.map +1 -0
  322. package/dist/storage/transfers.d.ts +90 -0
  323. package/dist/storage/transfers.js +2 -0
  324. package/dist/storage/transfers.js.map +1 -0
  325. package/dist/transfer/io.d.ts +74 -0
  326. package/dist/transfer/io.js +425 -0
  327. package/dist/transfer/io.js.map +1 -0
  328. package/dist/transfer/offers.d.ts +72 -0
  329. package/dist/transfer/offers.js +380 -0
  330. package/dist/transfer/offers.js.map +1 -0
  331. package/dist/transfer/stream-slots.d.ts +12 -0
  332. package/dist/transfer/stream-slots.js +28 -0
  333. package/dist/transfer/stream-slots.js.map +1 -0
  334. package/dist/work/catalog.d.ts +43 -0
  335. package/dist/work/catalog.js +198 -0
  336. package/dist/work/catalog.js.map +1 -0
  337. package/dist/work/discovery.d.ts +70 -0
  338. package/dist/work/discovery.js +465 -0
  339. package/dist/work/discovery.js.map +1 -0
  340. package/dist/work/service.d.ts +83 -0
  341. package/dist/work/service.js +703 -0
  342. package/dist/work/service.js.map +1 -0
  343. package/package.json +66 -4
@@ -0,0 +1,776 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import { lstat, mkdir, mkdtemp, open, opendir, readFile, realpath, rm, } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { AgentError, requireCondition } from "../contracts/errors.js";
7
+ import { canonicalJson, isPlainRecord } from "../contracts/json.js";
8
+ import { mergeChildEnvironment, whichExecutable, } from "../process/environment.js";
9
+ import { atomicText, contains, privateDirectory } from "../runtime/paths.js";
10
+ const day = 24 * 60 * 60_000;
11
+ const maximumOutput = 4 * 1024 * 1024;
12
+ // Git documents /dev/null for disabled config; Git for Windows maps it to NUL.
13
+ // Node's Windows device-path spelling is not accepted by Git.
14
+ const gitNullPath = "/dev/null";
15
+ const roots = [
16
+ ".gitignore",
17
+ "package.json",
18
+ "package-lock.json",
19
+ "scripts",
20
+ "modules",
21
+ "docs",
22
+ ];
23
+ const running = new Set();
24
+ const ignoreBlock = [
25
+ "# Nexum Agent work snapshots",
26
+ "/mcp.json",
27
+ "/api/",
28
+ "/api.json",
29
+ "node_modules/",
30
+ "resources/",
31
+ "tmp/",
32
+ ".env",
33
+ ".env.*",
34
+ ".npmrc",
35
+ "",
36
+ ].join("\n");
37
+ class Skip extends Error {
38
+ reason;
39
+ constructor(reason) {
40
+ super(reason);
41
+ this.reason = reason;
42
+ }
43
+ }
44
+ class GitFailure extends Error {
45
+ reason;
46
+ constructor(reason) {
47
+ super(reason);
48
+ this.reason = reason;
49
+ }
50
+ }
51
+ function missing(cause) {
52
+ return ["ENOENT", "ENOTDIR"].includes(cause?.code ?? "");
53
+ }
54
+ async function exists(filename) {
55
+ try {
56
+ await lstat(filename);
57
+ return true;
58
+ }
59
+ catch (cause) {
60
+ if (missing(cause))
61
+ return false;
62
+ throw cause;
63
+ }
64
+ }
65
+ function forbidden(filename) {
66
+ const parts = filename.split("/");
67
+ return (["mcp.json", "api", "api.json"].includes(parts[0].toLowerCase()) ||
68
+ parts.some((part) => ["node_modules", "resources", "tmp", ".npmrc", ".env", ".git"].includes(part.toLowerCase()) || /^\.env\./i.test(part)));
69
+ }
70
+ function selected(filename) {
71
+ return (!forbidden(filename) &&
72
+ (roots.includes(filename) ||
73
+ ["scripts/", "modules/", "docs/"].some((prefix) => filename.startsWith(prefix))));
74
+ }
75
+ function names(bytes) {
76
+ if (!bytes.length)
77
+ return [];
78
+ requireCondition(bytes.at(-1) === 0, "invalid_git_output", "Git returned incomplete path records.");
79
+ return new TextDecoder("utf-8", { fatal: true })
80
+ .decode(bytes.subarray(0, -1))
81
+ .split("\0");
82
+ }
83
+ function gitEnvironment(snapshot) {
84
+ const result = mergeChildEnvironment(snapshot);
85
+ for (const name of Object.keys(result)) {
86
+ if (/^GIT_/i.test(name) ||
87
+ [
88
+ "NODE_OPTIONS",
89
+ "NODE_PATH",
90
+ "PAGER",
91
+ "EDITOR",
92
+ "VISUAL",
93
+ "SSH_ASKPASS",
94
+ ].includes(name.toUpperCase()))
95
+ delete result[name];
96
+ }
97
+ Object.assign(result, {
98
+ GIT_CONFIG_NOSYSTEM: "1",
99
+ GIT_CONFIG_SYSTEM: gitNullPath,
100
+ GIT_CONFIG_GLOBAL: gitNullPath,
101
+ GIT_TERMINAL_PROMPT: "0",
102
+ GIT_OPTIONAL_LOCKS: "0",
103
+ GIT_NO_LAZY_FETCH: "1",
104
+ GIT_LITERAL_PATHSPECS: "1",
105
+ LC_ALL: "C",
106
+ LANG: "C",
107
+ });
108
+ return result;
109
+ }
110
+ function safeOptions(attempt) {
111
+ return [
112
+ "--no-pager",
113
+ "--literal-pathspecs",
114
+ "-c",
115
+ `core.hooksPath=${attempt.empty}`,
116
+ "-c",
117
+ "core.fsmonitor=false",
118
+ "-c",
119
+ `core.attributesFile=${gitNullPath}`,
120
+ "-c",
121
+ "commit.gpgSign=false",
122
+ "-c",
123
+ "tag.gpgSign=false",
124
+ "-c",
125
+ "gc.auto=0",
126
+ "-c",
127
+ "maintenance.auto=false",
128
+ "-c",
129
+ "core.pager=",
130
+ "-c",
131
+ "user.name=Nexum Agent",
132
+ "-c",
133
+ "user.email=nexum@localhost",
134
+ ];
135
+ }
136
+ /** Cold, due-aware local maintenance. Application startup/resume calls these explicitly. */
137
+ export class WorkGitMaintenance {
138
+ root;
139
+ #options;
140
+ #now;
141
+ constructor(agentRoot, options) {
142
+ requireCondition(path.isAbsolute(agentRoot) && !agentRoot.includes("\0"), "invalid_work_git_root", "Work Git requires the current absolute Agent profile root.");
143
+ requireCondition(options.environment.platform === process.platform &&
144
+ Number.isSafeInteger(options.timeoutMs ?? 10_000) &&
145
+ (options.timeoutMs ?? 10_000) > 0 &&
146
+ (options.timeoutMs ?? 10_000) <= 30_000, "invalid_work_git_options", "Work Git requires a user environment and bounded native command deadline.");
147
+ this.root = path.resolve(agentRoot);
148
+ this.#options = options;
149
+ this.#now = options.now ?? Date.now;
150
+ }
151
+ /** Includes first repository initialization/snapshot, but never forces a second daily attempt. */
152
+ initialize() {
153
+ return this.#check();
154
+ }
155
+ /** No catch-up loop: a late startup/resume attempts only the current snapshot once. */
156
+ checkDue() {
157
+ return this.#check();
158
+ }
159
+ #result(status, reason, now, commit = null) {
160
+ return {
161
+ status,
162
+ reason,
163
+ checkedAt: new Date(now).toISOString(),
164
+ nextCheckAt: new Date(now + day).toISOString(),
165
+ commit,
166
+ stateSaved: false,
167
+ };
168
+ }
169
+ async #boundary() {
170
+ const stat = await lstat(this.root);
171
+ if (!stat.isDirectory() || (await realpath(this.root)) !== this.root)
172
+ throw new Skip("unsafe_profile_root");
173
+ let work, state;
174
+ try {
175
+ work = privateDirectory(this.root, "work");
176
+ }
177
+ catch (cause) {
178
+ if (cause instanceof AgentError && cause.code === "storage_path_escape")
179
+ throw new Skip("unsafe_work_root");
180
+ throw cause;
181
+ }
182
+ try {
183
+ state = privateDirectory(this.root, "state");
184
+ }
185
+ catch (cause) {
186
+ if (cause instanceof AgentError && cause.code === "storage_path_escape")
187
+ throw new Skip("unsafe_maintenance_state");
188
+ throw cause;
189
+ }
190
+ return { root: this.root, work, state };
191
+ }
192
+ async #stored(filename) {
193
+ try {
194
+ const stat = await lstat(filename);
195
+ if (!stat.isFile() || stat.size > 16384)
196
+ throw new Skip("unsafe_maintenance_state");
197
+ const value = JSON.parse(await readFile(filename, "utf8"));
198
+ if (!isPlainRecord(value) ||
199
+ value.schemaVersion !== 1 ||
200
+ !isPlainRecord(value.result))
201
+ return null;
202
+ const result = value.result;
203
+ if (typeof result.checkedAt !== "string" ||
204
+ typeof result.nextCheckAt !== "string" ||
205
+ !Number.isFinite(Date.parse(result.checkedAt)) ||
206
+ Date.parse(result.nextCheckAt) !== Date.parse(result.checkedAt) + day)
207
+ return null;
208
+ if (![
209
+ "committed",
210
+ "unchanged",
211
+ "skipped",
212
+ "unavailable",
213
+ "failed",
214
+ ].includes(result.status) ||
215
+ !(result.reason === null ||
216
+ (typeof result.reason === "string" &&
217
+ /^[a-z][a-z0-9_]{0,95}$/.test(result.reason))) ||
218
+ !(result.commit === null ||
219
+ (typeof result.commit === "string" &&
220
+ /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(result.commit))) ||
221
+ typeof result.stateSaved !== "boolean")
222
+ return null;
223
+ return result;
224
+ }
225
+ catch (cause) {
226
+ if (missing(cause) || cause instanceof SyntaxError)
227
+ return null;
228
+ throw cause;
229
+ }
230
+ }
231
+ async #check() {
232
+ const key = path.join(this.root, "work"), now = this.#now();
233
+ if (running.has(key))
234
+ return this.#result("skipped", "maintenance_busy", now);
235
+ running.add(key);
236
+ try {
237
+ return await this.#attempt(now);
238
+ }
239
+ finally {
240
+ running.delete(key);
241
+ }
242
+ }
243
+ async #attempt(now) {
244
+ let state, empty;
245
+ let reservation;
246
+ let result;
247
+ try {
248
+ try {
249
+ const boundary = await this.#boundary();
250
+ state = path.join(boundary.state, "work-git.json");
251
+ const stored = await this.#stored(state);
252
+ if (stored && now < Date.parse(stored.nextCheckAt))
253
+ return { ...stored, status: "not_due" };
254
+ const budget = await this.#snapshotBudget(boundary.work);
255
+ reservation = await this.#options.reserve?.(budget.bytes);
256
+ const environment = gitEnvironment(this.#options.environment);
257
+ const executable = await whichExecutable(process.platform === "win32" ? "git.exe" : "git", { ...this.#options.environment, variables: environment }, boundary.root);
258
+ if (executable.kind !== "native" ||
259
+ contains(boundary.work, executable.launchPath) ||
260
+ contains(boundary.work, executable.path))
261
+ throw new Skip("unsafe_git_executable");
262
+ empty = await mkdtemp(path.join(boundary.state, "work-git-"));
263
+ const attempt = {
264
+ ...boundary,
265
+ gitDir: path.join(boundary.work, ".git"),
266
+ empty,
267
+ executable: executable.path,
268
+ environment,
269
+ timeoutMs: this.#options.timeoutMs ?? 10_000,
270
+ inputBytes: budget.inputBytes,
271
+ };
272
+ result = await this.#snapshot(attempt, now);
273
+ }
274
+ catch (cause) {
275
+ const unavailable = cause instanceof AgentError &&
276
+ ["command_not_found", "command_access_denied"].includes(cause.code);
277
+ result = this.#result(unavailable
278
+ ? "unavailable"
279
+ : cause instanceof Skip
280
+ ? "skipped"
281
+ : "failed", cause instanceof AgentError && cause.code === "storage_quota_exceeded"
282
+ ? "storage_quota_exceeded"
283
+ : unavailable
284
+ ? "git_unavailable"
285
+ : cause instanceof Skip || cause instanceof GitFailure
286
+ ? cause.reason
287
+ : "maintenance_failed", now);
288
+ }
289
+ finally {
290
+ if (empty)
291
+ await rm(empty, { recursive: true, force: true }).catch(() => { });
292
+ }
293
+ if (state && (!this.#options.reserve || reservation)) {
294
+ try {
295
+ if ((await exists(state)) && !(await lstat(state)).isFile())
296
+ return { ...result, stateSaved: false };
297
+ const saved = { ...result, stateSaved: true };
298
+ atomicText(state, canonicalJson({ schemaVersion: 1, result: saved }, 16384) + "\n");
299
+ return saved;
300
+ }
301
+ catch {
302
+ /* A maintenance record failure cannot invalidate a real commit. */
303
+ }
304
+ }
305
+ return result;
306
+ }
307
+ finally {
308
+ reservation?.release();
309
+ }
310
+ }
311
+ async #git(attempt, args, input, repository = true) {
312
+ // Recheck the actual current directories before every child; this is not an
313
+ // OS-level dirfd isolation promise against arbitrary hostile concurrent FS writes.
314
+ if ((await realpath(attempt.root)) !== attempt.root ||
315
+ (await realpath(attempt.work)) !== attempt.work ||
316
+ !(await lstat(attempt.work)).isDirectory())
317
+ throw new Skip("unsafe_work_root");
318
+ const prefix = [
319
+ ...safeOptions(attempt),
320
+ ...(repository
321
+ ? [`--git-dir=${attempt.gitDir}`, `--work-tree=${attempt.work}`]
322
+ : []),
323
+ ];
324
+ return await new Promise((resolve, reject) => {
325
+ const child = spawn(attempt.executable, [...prefix, ...args], {
326
+ cwd: attempt.work,
327
+ env: attempt.environment,
328
+ shell: false,
329
+ windowsHide: true,
330
+ stdio: ["pipe", "pipe", "pipe"],
331
+ });
332
+ let failure, uncertain = false, bytes = 0, force;
333
+ const stdout = [], stderr = [];
334
+ const stop = (reason) => {
335
+ if (uncertain)
336
+ return;
337
+ uncertain = true;
338
+ failure = new GitFailure(reason);
339
+ child.kill("SIGTERM");
340
+ force = setTimeout(() => child.kill("SIGKILL"), 100);
341
+ };
342
+ const timer = setTimeout(() => stop("git_command_timeout"), attempt.timeoutMs);
343
+ const collect = (chunks, chunk) => {
344
+ bytes += chunk.length;
345
+ if (bytes > maximumOutput)
346
+ stop("git_output_exceeded");
347
+ else
348
+ chunks.push(Buffer.from(chunk));
349
+ };
350
+ child.stdout.on("data", (chunk) => collect(stdout, chunk));
351
+ child.stderr.on("data", (chunk) => collect(stderr, chunk));
352
+ child.once("error", (cause) => {
353
+ failure = cause;
354
+ });
355
+ child.stdin.on("error", () => { }); // EPIPE is reported by the real child outcome.
356
+ child.once("close", (code) => {
357
+ clearTimeout(timer);
358
+ if (force)
359
+ clearTimeout(force);
360
+ if (failure && !uncertain)
361
+ reject(failure);
362
+ else
363
+ resolve({
364
+ code,
365
+ stdout: Buffer.concat(stdout),
366
+ stderr: Buffer.concat(stderr),
367
+ uncertain,
368
+ });
369
+ });
370
+ child.stdin.end(input);
371
+ });
372
+ }
373
+ #ok(result) {
374
+ if (result.uncertain)
375
+ throw new GitFailure("git_result_unknown");
376
+ if (result.code !== 0) {
377
+ if (/index\.lock|cannot lock ref|another git process/i.test(result.stderr.toString("utf8")))
378
+ throw new Skip("git_busy");
379
+ throw new GitFailure("git_command_failed");
380
+ }
381
+ return result.stdout;
382
+ }
383
+ async #repository(attempt) {
384
+ const git = await lstat(attempt.gitDir);
385
+ if (!git.isDirectory() ||
386
+ (await realpath(attempt.gitDir)) !== attempt.gitDir)
387
+ throw new Skip("repository_mismatch");
388
+ for (const part of ["config", "index", "HEAD", "objects", "refs"]) {
389
+ const filename = path.join(attempt.gitDir, part);
390
+ if ((await exists(filename)) && (await lstat(filename)).isSymbolicLink())
391
+ throw new Skip("repository_mismatch");
392
+ }
393
+ for (const part of [
394
+ "commondir",
395
+ "config.worktree",
396
+ "objects/info/alternates",
397
+ ])
398
+ if (await exists(path.join(attempt.gitDir, part)))
399
+ throw new Skip("repository_mismatch");
400
+ let entries = 0;
401
+ const inspect = async (directory) => {
402
+ if (!(await exists(directory)))
403
+ return;
404
+ const children = await opendir(directory);
405
+ for await (const child of children) {
406
+ if (++entries > 100_000)
407
+ throw new Skip("git_metadata_exceeded");
408
+ if (child.isSymbolicLink())
409
+ throw new Skip("repository_mismatch");
410
+ if (child.name.endsWith(".lock"))
411
+ throw new Skip("git_busy");
412
+ // Git can overwrite COMMIT_EDITMSG or append reflogs in place. A
413
+ // second hard-link name must not make those writes escape the profile.
414
+ if (child.isFile() &&
415
+ !contains(path.join(attempt.gitDir, "objects"), path.join(directory, child.name)) &&
416
+ (await lstat(path.join(directory, child.name))).nlink > 1)
417
+ throw new Skip("repository_mismatch");
418
+ if (child.isDirectory())
419
+ await inspect(path.join(directory, child.name));
420
+ }
421
+ };
422
+ await inspect(attempt.gitDir);
423
+ const config = await this.#git(attempt, [
424
+ "config",
425
+ "--no-includes",
426
+ "--local",
427
+ "--name-only",
428
+ "--get-regexp",
429
+ "^(include|includeif|filter|hook)\\.|^core\\.worktree$|^extensions\\.(worktreeconfig|partialclone)$|^remote\\..*\\.promisor$",
430
+ ]);
431
+ if (config.uncertain || ![0, 1].includes(config.code ?? -1))
432
+ throw new GitFailure("git_config_unavailable");
433
+ if (config.stdout.length)
434
+ throw new Skip("unsafe_git_config");
435
+ const actual = this.#ok(await this.#git(attempt, [
436
+ "rev-parse",
437
+ "--show-toplevel",
438
+ "--absolute-git-dir",
439
+ "--git-common-dir",
440
+ "--is-bare-repository",
441
+ ]))
442
+ .toString("utf8")
443
+ .trimEnd()
444
+ .split("\n");
445
+ if (actual.length !== 4 ||
446
+ path.resolve(actual[0]) !== attempt.work ||
447
+ path.resolve(actual[1]) !== attempt.gitDir ||
448
+ path.resolve(attempt.work, actual[2]) !== attempt.gitDir ||
449
+ actual[3] !== "false")
450
+ throw new Skip("repository_mismatch");
451
+ }
452
+ async #admission(attempt) {
453
+ for (const item of [
454
+ "index.lock",
455
+ "HEAD.lock",
456
+ "config.lock",
457
+ "packed-refs.lock",
458
+ ])
459
+ if (await exists(path.join(attempt.gitDir, item)))
460
+ throw new Skip("git_busy");
461
+ for (const item of [
462
+ "MERGE_HEAD",
463
+ "REBASE_HEAD",
464
+ "CHERRY_PICK_HEAD",
465
+ "REVERT_HEAD",
466
+ "rebase-apply",
467
+ "rebase-merge",
468
+ "sequencer",
469
+ "BISECT_LOG",
470
+ ])
471
+ if (await exists(path.join(attempt.gitDir, item)))
472
+ throw new Skip("repository_operation");
473
+ const conflicts = this.#ok(await this.#git(attempt, ["ls-files", "--unmerged", "-z"]));
474
+ if (conflicts.length)
475
+ throw new Skip("unresolved_conflicts");
476
+ const staged = await this.#git(attempt, [
477
+ "diff",
478
+ "--cached",
479
+ "--quiet",
480
+ "--exit-code",
481
+ "--no-ext-diff",
482
+ "--no-textconv",
483
+ ]);
484
+ if (staged.code === 1 && !staged.uncertain)
485
+ throw new Skip("existing_staged");
486
+ this.#ok(staged);
487
+ const tracked = names(this.#ok(await this.#git(attempt, ["ls-files", "-z"])));
488
+ if (tracked.some(forbidden))
489
+ throw new Skip("forbidden_tracked");
490
+ return tracked;
491
+ }
492
+ async #ignore(attempt) {
493
+ const filename = path.join(attempt.work, ".gitignore");
494
+ if ((await exists(filename)) && !(await lstat(filename)).isFile())
495
+ throw new Skip("unsafe_snapshot_path");
496
+ const handle = await open(filename, constants.O_RDWR |
497
+ constants.O_APPEND |
498
+ constants.O_CREAT |
499
+ constants.O_NOFOLLOW, 0o600);
500
+ try {
501
+ const stat = await handle.stat();
502
+ if (!stat.isFile() || stat.nlink > 1 || stat.size > 64 * 1024)
503
+ throw new Skip("unsafe_snapshot_path");
504
+ const content = await handle.readFile("utf8");
505
+ if (!content.includes(ignoreBlock))
506
+ await handle.writeFile((content && !content.endsWith("\n") ? "\n" : "") + ignoreBlock);
507
+ }
508
+ finally {
509
+ await handle.close();
510
+ }
511
+ }
512
+ async #paths(attempt) {
513
+ const candidates = names(this.#ok(await this.#git(attempt, [
514
+ "ls-files",
515
+ "--cached",
516
+ "--others",
517
+ "--exclude-standard",
518
+ "-z",
519
+ "--",
520
+ ...roots,
521
+ ]))).filter(selected);
522
+ for (const filename of candidates) {
523
+ const parts = filename.split("/");
524
+ if (parts.some((part) => !part || part === "." || part === ".." || part === ".git") ||
525
+ !contains(attempt.work, path.resolve(attempt.work, ...parts)))
526
+ throw new Skip("unsafe_snapshot_path");
527
+ let current = attempt.work;
528
+ for (let index = 0; index < parts.length; index++) {
529
+ current = path.join(current, parts[index]);
530
+ try {
531
+ const stat = await lstat(current);
532
+ if (stat.isSymbolicLink() ||
533
+ (index === parts.length - 1 ? !stat.isFile() : !stat.isDirectory()))
534
+ throw new Skip("unsafe_snapshot_path");
535
+ }
536
+ catch (cause) {
537
+ if (missing(cause))
538
+ break;
539
+ throw cause;
540
+ }
541
+ }
542
+ }
543
+ return [...new Set(candidates)];
544
+ }
545
+ async #head(attempt) {
546
+ const result = await this.#git(attempt, [
547
+ "rev-parse",
548
+ "--verify",
549
+ "--quiet",
550
+ "HEAD",
551
+ ]);
552
+ if (result.code === 1 && !result.uncertain)
553
+ return null;
554
+ const hash = this.#ok(result).toString("utf8").trim();
555
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(hash))
556
+ throw new GitFailure("invalid_git_head");
557
+ return hash;
558
+ }
559
+ async #snapshotBudget(work) {
560
+ let entries = 0, inputBytes = 4096, pathBytes = 0;
561
+ const walk = async (relative) => {
562
+ if (forbidden(relative))
563
+ return;
564
+ if (++entries > 20000)
565
+ throw new Skip("snapshot_too_large");
566
+ const file = path.join(work, ...relative.split("/"));
567
+ let info;
568
+ try {
569
+ info = await lstat(file);
570
+ }
571
+ catch (cause) {
572
+ if (missing(cause))
573
+ return;
574
+ throw cause;
575
+ }
576
+ if (info.isSymbolicLink())
577
+ throw new Skip("unsafe_snapshot_path");
578
+ if (info.isDirectory()) {
579
+ const directory = await opendir(file);
580
+ for await (const child of directory)
581
+ await walk(`${relative}/${child.name}`);
582
+ }
583
+ else if (info.isFile() && selected(relative)) {
584
+ inputBytes += info.size;
585
+ pathBytes += Buffer.byteLength(relative) + 128;
586
+ if (!Number.isSafeInteger(inputBytes))
587
+ throw new Skip("snapshot_too_large");
588
+ }
589
+ else
590
+ throw new Skip("unsafe_snapshot_path");
591
+ };
592
+ for (const root of roots)
593
+ await walk(root);
594
+ const index = path.join(work, ".git", "index");
595
+ const indexBytes = await lstat(index).then((value) => (value.isFile() ? value.size : 0), (cause) => {
596
+ if (missing(cause) ||
597
+ cause.code === "ENOTDIR")
598
+ return 0;
599
+ throw cause;
600
+ });
601
+ const bytes = 2 * inputBytes + 8 * pathBytes + 2 * indexBytes + 2 * 1024 * 1024;
602
+ requireCondition(Number.isSafeInteger(bytes), "storage_quota_exceeded", "The work snapshot exceeds the bounded managed-storage budget.");
603
+ return { bytes, inputBytes };
604
+ }
605
+ async #fixedSnapshot(attempt, paths) {
606
+ const directory = path.join(attempt.empty, "snapshot");
607
+ await mkdir(directory, { mode: 0o700 });
608
+ let copied = 0;
609
+ const deadline = Date.now() + attempt.timeoutMs;
610
+ for (const relative of paths) {
611
+ const source = path.join(attempt.work, ...relative.split("/")), target = path.join(directory, ...relative.split("/"));
612
+ let input, output;
613
+ try {
614
+ try {
615
+ input = await open(source, constants.O_RDONLY |
616
+ constants.O_NOFOLLOW |
617
+ (constants.O_NONBLOCK ?? 0));
618
+ }
619
+ catch (cause) {
620
+ if (missing(cause))
621
+ continue;
622
+ throw cause;
623
+ }
624
+ const before = await input.stat();
625
+ const linked = await lstat(source);
626
+ if (!before.isFile() ||
627
+ linked.isSymbolicLink() ||
628
+ linked.dev !== before.dev ||
629
+ linked.ino !== before.ino ||
630
+ (await realpath(source)) !== source ||
631
+ !contains(attempt.work, source))
632
+ throw new Skip("unsafe_snapshot_path");
633
+ if (before.size > attempt.inputBytes - copied)
634
+ throw new Skip("snapshot_source_changed");
635
+ let parent = directory;
636
+ for (const part of relative.split("/").slice(0, -1)) {
637
+ parent = path.join(parent, part);
638
+ if (!(await exists(parent)))
639
+ await mkdir(parent, { mode: 0o700 });
640
+ if (!(await lstat(parent)).isDirectory() ||
641
+ (await realpath(parent)) !== parent)
642
+ throw new Skip("unsafe_snapshot_path");
643
+ }
644
+ output = await open(target, constants.O_WRONLY |
645
+ constants.O_CREAT |
646
+ constants.O_EXCL |
647
+ constants.O_NOFOLLOW, before.mode & 0o100 ? 0o700 : 0o600);
648
+ let size = 0;
649
+ while (true) {
650
+ if (Date.now() > deadline)
651
+ throw new Skip("snapshot_copy_timeout");
652
+ const chunk = Buffer.allocUnsafe(65536), read = await input.read(chunk, 0, chunk.length, null);
653
+ if (!read.bytesRead)
654
+ break;
655
+ copied += read.bytesRead;
656
+ size += read.bytesRead;
657
+ if (copied > attempt.inputBytes || size > before.size)
658
+ throw new Skip("snapshot_source_changed");
659
+ await output.writeFile(chunk.subarray(0, read.bytesRead));
660
+ }
661
+ const after = await input.stat();
662
+ if (size !== before.size ||
663
+ before.size !== after.size ||
664
+ before.ino !== after.ino ||
665
+ before.dev !== after.dev ||
666
+ before.mtimeMs !== after.mtimeMs ||
667
+ before.ctimeMs !== after.ctimeMs ||
668
+ (await realpath(source)) !== source)
669
+ throw new Skip("snapshot_source_changed");
670
+ }
671
+ finally {
672
+ const closed = await Promise.allSettled([
673
+ input?.close(),
674
+ output?.close(),
675
+ ]);
676
+ const failed = closed.find((item) => item.status === "rejected");
677
+ if (failed?.status === "rejected")
678
+ throw failed.reason;
679
+ }
680
+ }
681
+ return directory;
682
+ }
683
+ async #snapshot(attempt, now) {
684
+ const version = this.#ok(await this.#git(attempt, ["--version"], undefined, false))
685
+ .toString("utf8")
686
+ .match(/git version (\d+)\.(\d+)/);
687
+ if (!version ||
688
+ Number(version[1]) < 2 ||
689
+ (Number(version[1]) === 2 && Number(version[2]) < 36))
690
+ return this.#result("unavailable", "git_version_unsupported", now);
691
+ if (!(await exists(attempt.gitDir)))
692
+ this.#ok(await this.#git(attempt, [
693
+ "init",
694
+ `--template=${attempt.empty}`,
695
+ attempt.work,
696
+ ]));
697
+ await this.#repository(attempt);
698
+ await this.#admission(attempt);
699
+ await this.#ignore(attempt);
700
+ const paths = await this.#paths(attempt);
701
+ if (!paths.length)
702
+ return this.#result("unchanged", null, now);
703
+ const snapshot = await this.#fixedSnapshot(attempt, paths);
704
+ // Recheck immediately before writing the index, then commit only these
705
+ // literal paths. Concurrent unrelated user staging cannot enter this commit.
706
+ await this.#admission(attempt);
707
+ await this.#repository(attempt);
708
+ const before = await this.#head(attempt), input = Buffer.from(paths.join("\0") + "\0");
709
+ this.#ok(await this.#git(attempt, [
710
+ `--work-tree=${snapshot}`,
711
+ "add",
712
+ "-A",
713
+ "--pathspec-from-file=-",
714
+ "--pathspec-file-nul",
715
+ ], input));
716
+ const changed = await this.#git(attempt, [
717
+ "diff",
718
+ "--cached",
719
+ "--quiet",
720
+ "--exit-code",
721
+ "--no-ext-diff",
722
+ "--no-textconv",
723
+ ]);
724
+ if (!changed.uncertain && changed.code === 0)
725
+ return this.#result("unchanged", null, now);
726
+ if (changed.uncertain || changed.code !== 1)
727
+ this.#ok(changed);
728
+ const staged = names(this.#ok(await this.#git(attempt, [
729
+ "diff",
730
+ "--cached",
731
+ "--name-only",
732
+ "--no-ext-diff",
733
+ "--no-textconv",
734
+ "-z",
735
+ ])));
736
+ if (staged.some((filename) => !paths.includes(filename)) ||
737
+ (await this.#head(attempt)) !== before)
738
+ throw new Skip("git_state_changed");
739
+ await this.#repository(attempt);
740
+ const message = `Nexum Agent 自动快照 ${new Date(this.#now()).toISOString()} [${randomUUID()}]`;
741
+ const committed = await this.#git(attempt, [
742
+ `--work-tree=${snapshot}`,
743
+ "commit",
744
+ "--only",
745
+ "--no-gpg-sign",
746
+ "--no-verify",
747
+ "--cleanup=verbatim",
748
+ "-m",
749
+ message,
750
+ "--pathspec-from-file=-",
751
+ "--pathspec-file-nul",
752
+ ], input);
753
+ // A timeout/nonzero result can occur after HEAD changed. Inspect the actual
754
+ // commit once; never replay a potentially successful mutation.
755
+ const after = await this.#head(attempt);
756
+ if (after && after !== before) {
757
+ const proof = this.#ok(await this.#git(attempt, [
758
+ "show",
759
+ "--no-patch",
760
+ "--format=%P%n%B",
761
+ after,
762
+ ])).toString("utf8");
763
+ const newline = proof.indexOf("\n");
764
+ if (proof.slice(0, newline) === (before ?? "") &&
765
+ proof.slice(newline + 1).trimEnd() === message)
766
+ return this.#result("committed", committed.uncertain || committed.code !== 0
767
+ ? "commit_confirmed_after_error"
768
+ : null, now, after);
769
+ }
770
+ if (committed.uncertain || committed.code === 0)
771
+ return this.#result("failed", "commit_outcome_unknown", now);
772
+ this.#ok(committed);
773
+ throw new GitFailure("commit_failed");
774
+ }
775
+ }
776
+ //# sourceMappingURL=work-git.js.map