@chroxy/server 0.10.0 → 0.11.10

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 (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Committee decision contract (engine foundations, epic #6691, step E-1) — the
3
+ * highest-risk piece. Models end each committee turn with a fenced JSON block
4
+ * (```chroxy-decision); this module extracts and validates it. Fail-closed:
5
+ * absence of a valid block is NEVER an approval — extractDecision throws, and
6
+ * the engine's policy (repair re-prompt → architect salvage → escalate) decides
7
+ * what to do. It never guesses a verdict.
8
+ *
9
+ * Pure — no I/O, no clock, no session. zod (server package ^4.3.6) validates
10
+ * per-kind; unknown keys are stripped, not fatal.
11
+ */
12
+
13
+ import { z } from 'zod'
14
+
15
+ export const DECISION_KINDS = [
16
+ 'epic_plan', 'plan_of_attack', 'poa_review', 'work_result', 'result_review', 'synthesis',
17
+ ]
18
+
19
+ const VERDICT = z.enum(['approve', 'revise', 'redelegate', 'escalate'])
20
+
21
+ // Per-kind schemas. `kind` is a z.literal discriminator; unknown keys stripped.
22
+ const SubtaskSpec = z.object({
23
+ title: z.string().min(1).max(300),
24
+ goal: z.string().min(1).max(8000),
25
+ role: z.enum(['audit', 'implement']),
26
+ dependsOn: z.array(z.string().max(128)).max(50).optional(),
27
+ successCriteria: z.string().max(4000).optional(),
28
+ filesHint: z.array(z.string().max(1024)).max(200).optional(),
29
+ })
30
+
31
+ export const DECISION_SCHEMAS = {
32
+ epic_plan: z.object({
33
+ kind: z.literal('epic_plan'),
34
+ summary: z.string().max(8000).optional(),
35
+ subtasks: z.array(SubtaskSpec).min(1).max(100),
36
+ }),
37
+ plan_of_attack: z.object({
38
+ kind: z.literal('plan_of_attack'),
39
+ plan: z.string().min(1).max(20000),
40
+ summary: z.string().min(1).max(4000),
41
+ }),
42
+ poa_review: z.object({
43
+ kind: z.literal('poa_review'),
44
+ verdict: VERDICT,
45
+ feedback: z.string().max(8000).optional(),
46
+ }),
47
+ work_result: z.object({
48
+ kind: z.literal('work_result'),
49
+ summary: z.string().min(1).max(20000),
50
+ filesChanged: z.array(z.string().max(1024)).max(500).optional(),
51
+ notes: z.string().max(8000).optional(),
52
+ }),
53
+ result_review: z.object({
54
+ kind: z.literal('result_review'),
55
+ verdict: VERDICT,
56
+ feedback: z.string().max(8000).optional(),
57
+ }),
58
+ synthesis: z.object({
59
+ kind: z.literal('synthesis'),
60
+ reportMarkdown: z.string().min(1).max(200000),
61
+ summary: z.string().max(8000).optional(),
62
+ }),
63
+ }
64
+
65
+ export class DecisionParseError extends Error {
66
+ constructor(stage, detail) {
67
+ super(`decision parse failed at ${stage}: ${detail}`)
68
+ this.name = 'DecisionParseError'
69
+ this.code = 'DECISION_PARSE_ERROR'
70
+ this.stage = stage // 'no_block' | 'parse' | 'kind' | 'schema'
71
+ this.detail = detail
72
+ }
73
+ }
74
+
75
+ const TAIL_SCAN_LIMIT = 32 * 1024
76
+
77
+ function findFencedBlocks(text) {
78
+ // ```tag\n ... ``` — capture tag + body. Tolerates a trailing space after the
79
+ // tag and CRLF. Non-greedy body so adjacent fences don't merge.
80
+ const re = /```([a-zA-Z0-9_-]*)[ \t]*\r?\n([\s\S]*?)```/g
81
+ const blocks = []
82
+ let m
83
+ while ((m = re.exec(text)) !== null) blocks.push({ tag: m[1].toLowerCase(), body: m[2].trim() })
84
+ return blocks
85
+ }
86
+
87
+ // Last balanced {...} object in the final TAIL_SCAN_LIMIT chars, string-aware so
88
+ // braces inside JSON strings don't confuse the depth count.
89
+ function braceScanFromTail(text) {
90
+ const tail = text.length > TAIL_SCAN_LIMIT ? text.slice(text.length - TAIL_SCAN_LIMIT) : text
91
+ const end = tail.lastIndexOf('}')
92
+ if (end === -1) return null
93
+ let depth = 0
94
+ let inStr = false
95
+ for (let i = end; i >= 0; i--) {
96
+ const ch = tail[i]
97
+ if (inStr) {
98
+ // walking backwards: a quote closes the string unless it's escaped. We
99
+ // approximate escape handling by checking the preceding backslash run.
100
+ if (ch === '"') {
101
+ let bs = 0
102
+ let j = i - 1
103
+ while (j >= 0 && tail[j] === '\\') { bs++; j-- }
104
+ if (bs % 2 === 0) inStr = false
105
+ }
106
+ continue
107
+ }
108
+ if (ch === '"') { inStr = true; continue }
109
+ if (ch === '}') depth++
110
+ else if (ch === '{') {
111
+ depth--
112
+ if (depth === 0) return tail.slice(i, end + 1)
113
+ }
114
+ }
115
+ return null
116
+ }
117
+
118
+ /** Pick the decision block text from model output, scanning from the end. */
119
+ function extractBlockText(text) {
120
+ const blocks = findFencedBlocks(text)
121
+ const byTag = (tag) => {
122
+ for (let i = blocks.length - 1; i >= 0; i--) if (blocks[i].tag === tag) return blocks[i].body
123
+ return null
124
+ }
125
+ return (
126
+ byTag('chroxy-decision')
127
+ || byTag('json')
128
+ || (blocks.length ? blocks[blocks.length - 1].body : null)
129
+ || braceScanFromTail(text)
130
+ )
131
+ }
132
+
133
+ // Strip //, /* */ comments and trailing commas that are OUTSIDE JSON strings,
134
+ // so a `//` (e.g. a URL) or a `, }` inside a string value is never mangled.
135
+ // Smart quotes are normalized everywhere (they only ever appear as a typo for
136
+ // real quotes, and a smart quote inside a value is still not valid JSON).
137
+ function stripNoise(s) {
138
+ let out = ''
139
+ let inStr = false
140
+ let esc = false
141
+ for (let i = 0; i < s.length; i++) {
142
+ const ch = s[i]
143
+ if (inStr) {
144
+ out += ch
145
+ if (esc) esc = false
146
+ else if (ch === '\\') esc = true
147
+ else if (ch === '"') inStr = false
148
+ continue
149
+ }
150
+ if (ch === '"') { inStr = true; out += ch; continue }
151
+ // line comment
152
+ if (ch === '/' && s[i + 1] === '/') { while (i < s.length && s[i] !== '\n' && s[i] !== '\r') i++; i--; continue }
153
+ // block comment
154
+ if (ch === '/' && s[i + 1] === '*') { i += 2; while (i < s.length && !(s[i] === '*' && s[i + 1] === '/')) i++; i++; continue }
155
+ // trailing comma: a comma followed (after whitespace) by } or ]
156
+ if (ch === ',') {
157
+ let j = i + 1
158
+ while (j < s.length && /\s/.test(s[j])) j++
159
+ if (s[j] === '}' || s[j] === ']') continue // drop the comma
160
+ }
161
+ out += ch
162
+ }
163
+ return out
164
+ }
165
+
166
+ function tolerantParse(raw) {
167
+ try { return JSON.parse(raw) } catch { /* fall through to tolerant pass */ }
168
+ const normalized = raw.replace(/[“”]/g, '"').replace(/[‘’]/g, "'")
169
+ return JSON.parse(stripNoise(normalized)) // may throw — caller wraps
170
+ }
171
+
172
+ function zodErrorSummary(error) {
173
+ return error.issues
174
+ .slice(0, 8)
175
+ .map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`)
176
+ .join('; ')
177
+ }
178
+
179
+ /**
180
+ * Extract + validate the committee decision of `expectedKind` from model text.
181
+ * @returns {{ decision: object, warnings: string[] }}
182
+ * @throws {DecisionParseError}
183
+ */
184
+ export function extractDecision(text, expectedKind) {
185
+ const schema = DECISION_SCHEMAS[expectedKind]
186
+ if (!schema) throw new DecisionParseError('kind', `unknown expectedKind '${expectedKind}'`)
187
+ const warnings = []
188
+ const raw = typeof text === 'string' ? extractBlockText(text) : null
189
+ if (raw == null || raw.length === 0) {
190
+ throw new DecisionParseError('no_block', 'no fenced chroxy-decision block, json block, or JSON object found')
191
+ }
192
+
193
+ let obj
194
+ try {
195
+ obj = tolerantParse(raw)
196
+ } catch (err) {
197
+ throw new DecisionParseError('parse', (err && err.message) || 'invalid JSON')
198
+ }
199
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
200
+ throw new DecisionParseError('parse', 'decision is not a JSON object')
201
+ }
202
+ // Distinguish a kind mismatch from a schema failure for clearer repair prompts.
203
+ if (obj.kind !== expectedKind) {
204
+ throw new DecisionParseError('kind', `expected kind '${expectedKind}', got '${obj.kind ?? '(absent)'}'`)
205
+ }
206
+ const parsed = schema.safeParse(obj)
207
+ if (!parsed.success) {
208
+ throw new DecisionParseError('schema', zodErrorSummary(parsed.error))
209
+ }
210
+ return { decision: parsed.data, warnings }
211
+ }
212
+
213
+ const EXAMPLES = {
214
+ epic_plan: '{ "kind": "epic_plan", "subtasks": [ { "title": "...", "goal": "...", "role": "audit" } ] }',
215
+ plan_of_attack: '{ "kind": "plan_of_attack", "plan": "...", "summary": "..." }',
216
+ poa_review: '{ "kind": "poa_review", "verdict": "approve", "feedback": "..." }',
217
+ work_result: '{ "kind": "work_result", "summary": "..." }',
218
+ result_review: '{ "kind": "result_review", "verdict": "approve" }',
219
+ synthesis: '{ "kind": "synthesis", "reportMarkdown": "# ..." }',
220
+ }
221
+
222
+ /** The per-turn instruction appended to a role prompt (NOT the capped preamble). */
223
+ export function decisionInstruction(expectedKind) {
224
+ return [
225
+ `End your reply with exactly one fenced code block tagged \`chroxy-decision\` containing ONLY`,
226
+ `JSON of kind "${expectedKind}", matching:`,
227
+ '```chroxy-decision',
228
+ EXAMPLES[expectedKind] ?? '{ "kind": "..." }',
229
+ '```',
230
+ 'The block must be the last thing in your message. Do not wrap it in prose.',
231
+ ].join('\n')
232
+ }
233
+
234
+ /** The corrective re-prompt sent to the same session on a parse failure. */
235
+ export function buildRepairPrompt(expectedKind, parseError) {
236
+ const stage = parseError instanceof DecisionParseError ? parseError.stage : 'unknown'
237
+ const detail = parseError instanceof DecisionParseError ? parseError.detail : String(parseError)
238
+ return [
239
+ `Your previous reply's chroxy-decision block could not be used (${stage}: ${detail}).`,
240
+ `Reply with ONLY the corrected block — nothing else:`,
241
+ '```chroxy-decision',
242
+ EXAMPLES[expectedKind] ?? '{ "kind": "..." }',
243
+ '```',
244
+ ].join('\n')
245
+ }
@@ -0,0 +1,381 @@
1
+ /**
2
+ * Git operations for the orchestration write path (epic #6691, step E-3).
3
+ *
4
+ * The safety primitives behind write-capable workers: create a per-subtask
5
+ * branch in a worker's worktree, compute a capped review diff, auto-commit
6
+ * before any teardown (so uncommitted work is never lost), and merge accepted
7
+ * branches sequentially into a run-owned integration worktree. Landing the
8
+ * result (into the user's branch, or a push) is ALWAYS a human action — this
9
+ * module never touches the user's working tree, never checks out or merges into
10
+ * the user's branch, and never contacts a remote.
11
+ *
12
+ * Hard rules baked in here:
13
+ * - Every git call is `execFile(GIT, [...args])` — never a shell string, so a
14
+ * branch name / path / conflict-file list can never inject a command.
15
+ * - `GIT` is the resolved binary (a bare 'git' is ENOENT under launchd's
16
+ * minimal PATH).
17
+ * - `worktree remove --force` + an rm fallback are used ONLY on orchestrator-
18
+ * owned worktrees under the injected worktrees root; user-adjacent
19
+ * reclamation is the GC reaper's job, not this module's.
20
+ * - Expected git failure modes (a merge conflict, a clean tree, a missing
21
+ * branch) are returned as structured results, not thrown.
22
+ *
23
+ * All collaborators (git binary, clock, fs, worktrees root) are injected via
24
+ * `createGitOps(...)` so the suite can drive it against temp repos.
25
+ */
26
+
27
+ import { execFile as execFileCb } from 'node:child_process'
28
+ import { promisify } from 'node:util'
29
+ import { join, resolve, sep } from 'node:path'
30
+ import { rmSync, mkdirSync, existsSync } from 'node:fs'
31
+ import { GIT } from '../git.js'
32
+ import { configDir } from '../config-dir.js'
33
+ import { assertSafeArgvValue } from '../utils/argv-safety.js'
34
+
35
+ const execFileAsync = promisify(execFileCb)
36
+
37
+ const DEFAULT_TIMEOUT_MS = 30_000
38
+ const DEFAULT_MAX_BUFFER = 8 * 1024 * 1024
39
+ // A raw `git diff`/`status` can be far larger than what we KEEP; buffer
40
+ // generously so a big real change is never misread as empty (we cap the KEPT
41
+ // bytes separately in computeCappedDiff).
42
+ const DIFF_MAX_BUFFER = 64 * 1024 * 1024
43
+
44
+ // Reject a ref/path that git would parse as an OPTION (leading '-') or that
45
+ // carries a NUL/newline — defense-in-depth so a caller can never turn a branch
46
+ // name into a git flag. execFile already blocks SHELL injection; this blocks
47
+ // ARGUMENT injection.
48
+ //
49
+ // #7290: the CHECK now lives in utils/argv-safety.js and is shared with
50
+ // ws-file-ops/reader.js. This wrapper exists only to translate its Error into
51
+ // a GitOpsError; both messages (`empty <kind>` / `unsafe <kind>: <json>`) are
52
+ // produced there, and orchestration-git-ops.test.js pins the `unsafe` half.
53
+ // Do not re-inline the check here — #7290 was filed because a SECOND, weaker
54
+ // spelling had grown in reader.js. A THIRD spelling — `rejectGitOptionLike`
55
+ // in environments/backends/k8s.js, scoped to gitRepo fields — was folded
56
+ // into the shared guard by #7869.
57
+ function assertSafeRef(name, kind = 'ref') {
58
+ try {
59
+ assertSafeArgvValue(name, kind)
60
+ } catch (err) {
61
+ // Only validation errors are expected here. Anything else would be a bug
62
+ // inside the shared guard, so keep the original rather than silently
63
+ // relabelling it as an unsafe ref. GitOpsError's constructor takes
64
+ // { args, stderr } and does not forward `cause` to super(), so it is set
65
+ // here rather than passed in — passing it would be dropped on the floor.
66
+ const wrapped = new GitOpsError(err.message)
67
+ wrapped.cause = err
68
+ throw wrapped
69
+ }
70
+ }
71
+
72
+ // Byte-accurate UTF-8 truncation that drops an incomplete trailing multibyte
73
+ // char (String.slice counts UTF-16 code units, so it can overshoot a byte
74
+ // budget ~3x on CJK content and split surrogate pairs into U+FFFD).
75
+ function byteSliceUtf8(str, maxBytes) {
76
+ const buf = Buffer.from(str, 'utf8')
77
+ if (buf.length <= maxBytes) return str
78
+ // stream:true holds back an incomplete trailing sequence instead of emitting U+FFFD.
79
+ return new TextDecoder('utf-8').decode(buf.subarray(0, maxBytes), { stream: true })
80
+ }
81
+
82
+ // Orchestrator commit identity — the daemon env has no configured git identity,
83
+ // so a bare `git commit` would fail. Passed per-invocation via `-c`, never
84
+ // written to any user config.
85
+ const ORCH_IDENTITY = { name: 'chroxy-orch', email: 'orch@chroxy.local' }
86
+
87
+ // Re-exported for the orchestration tests, which resolve the root the same way
88
+ // the provisioner does. The resolver itself lives in config-dir.js (#7052) —
89
+ // this module used to carry its own copy.
90
+ export { configDir }
91
+
92
+ /** The root the orphan sweep and the provisioner MUST agree on. Never `runs/`. */
93
+ export function defaultWorktreesRoot() {
94
+ return join(configDir(), 'orchestration', 'worktrees')
95
+ }
96
+
97
+ export class GitOpsError extends Error {
98
+ constructor(message, { args = null, stderr = null } = {}) {
99
+ super(message)
100
+ this.name = 'GitOpsError'
101
+ this.code = 'GIT_OP_FAILED'
102
+ this.args = args
103
+ this.stderr = stderr
104
+ }
105
+ }
106
+
107
+ export function createGitOps({ git = GIT, now = () => Date.now(), worktreesRoot = null, identity = ORCH_IDENTITY, fs = { rmSync, mkdirSync, existsSync } } = {}) {
108
+ const gitBin = () => git
109
+ const rootDir = () => worktreesRoot || defaultWorktreesRoot()
110
+
111
+ const errText = (err) => (err?.stderr?.trim?.() || err?.message || String(err))
112
+
113
+ // Run git; resolve { stdout, stderr } on success. On failure, resolve a
114
+ // structured { failed:true, stderr, code } so callers can branch on expected
115
+ // failure modes instead of try/catch everywhere.
116
+ const run = async (args, { timeout = DEFAULT_TIMEOUT_MS, maxBuffer = DEFAULT_MAX_BUFFER } = {}) => {
117
+ try {
118
+ const { stdout, stderr } = await execFileAsync(gitBin(), args, { timeout, maxBuffer })
119
+ return { ok: true, stdout: stdout ?? '', stderr: stderr ?? '' }
120
+ } catch (err) {
121
+ return { ok: false, stdout: err?.stdout ?? '', stderr: errText(err), code: err?.code ?? null }
122
+ }
123
+ }
124
+ // Run git; THROW on failure. For ops where a failure is genuinely unexpected.
125
+ const runOrThrow = async (args, opts) => {
126
+ const r = await run(args, opts)
127
+ if (!r.ok) throw new GitOpsError(`git ${args.join(' ')} failed: ${r.stderr}`, { args, stderr: r.stderr })
128
+ return r
129
+ }
130
+
131
+ // --- path single-source-of-truth ----------------------------------------
132
+
133
+ const orchestrationWorktreesRoot = () => rootDir()
134
+ const runWorktreesDir = (runId) => join(rootDir(), String(runId))
135
+ const integrationWorktreePath = (runId) => join(rootDir(), String(runId), 'integration')
136
+
137
+ // --- branch + HEAD -------------------------------------------------------
138
+
139
+ const captureHead = async (dir) => {
140
+ const r = await runOrThrow(['-C', dir, 'rev-parse', 'HEAD'])
141
+ return { sha: r.stdout.trim() }
142
+ }
143
+
144
+ // A worker worktree is created DETACHED at HEAD; put it on a named branch.
145
+ const createBranch = async (worktreePath, branchName) => {
146
+ assertSafeRef(branchName, 'branch')
147
+ const base = await captureHead(worktreePath)
148
+ await runOrThrow(['-C', worktreePath, 'switch', '-c', branchName])
149
+ return { branch: branchName, baseSha: base.sha }
150
+ }
151
+
152
+ const branchExists = async (repoDir, branchName) => {
153
+ assertSafeRef(branchName, 'branch')
154
+ const r = await run(['-C', repoDir, 'rev-parse', '--verify', '--quiet', `refs/heads/${branchName}`])
155
+ return { exists: r.ok }
156
+ }
157
+
158
+ const deleteBranch = async (repoDir, branchName) => {
159
+ assertSafeRef(branchName, 'branch')
160
+ const r = await run(['-C', repoDir, 'branch', '-D', '--', branchName])
161
+ return { deleted: r.ok }
162
+ }
163
+
164
+ // --- capped diff ---------------------------------------------------------
165
+
166
+ // A reproducible, size-bounded review artifact: baseSha..headRef, per-file
167
+ // and total byte caps with explicit truncation markers so a small worker
168
+ // model isn't handed a 2MB patch.
169
+ const computeCappedDiff = async ({ repoDir, baseSha, headRef = 'HEAD', maxBytes = 65_536, maxFileBytes = 8_192 }) => {
170
+ // #7342: these were the only ref slots in this module that skipped the
171
+ // guard every neighbour applies. `<base>..<head>` is a positional REVISION,
172
+ // and a `--` separator does NOT protect one (measured in
173
+ // utils/argv-safety.js: `git diff -O/etc/nope --` still reads the
174
+ // orderfile), so rejection is the only correct shape. Both values come
175
+ // from captureHead()'s rev-parse output today — this closes the gap before
176
+ // a caller wires a client-supplied ref in. Unlike a git failure (returned
177
+ // as a structured result below), an unsafe ref is a programming error and
178
+ // throws.
179
+ assertSafeRef(baseSha, 'base ref')
180
+ assertSafeRef(headRef, 'head ref')
181
+ const statR = await run(['-C', repoDir, 'diff', '--stat', `${baseSha}..${headRef}`], { maxBuffer: DIFF_MAX_BUFFER })
182
+ const patchR = await run(['-C', repoDir, 'diff', `${baseSha}..${headRef}`], { maxBuffer: DIFF_MAX_BUFFER })
183
+ const stat = statR.ok ? statR.stdout : ''
184
+ // If the raw diff couldn't be produced/buffered, NEVER return an empty patch
185
+ // as if clean — that would let a huge unreviewed change look like no change.
186
+ // Report it honestly as truncated with an explicit marker.
187
+ if (!patchR.ok) {
188
+ return {
189
+ stat,
190
+ patch: `// diff unavailable (${patchR.stderr || 'exceeded buffer'})\n`,
191
+ truncated: true,
192
+ omittedFiles: [],
193
+ includedFiles: [],
194
+ error: patchR.stderr || 'diff_unavailable',
195
+ }
196
+ }
197
+ const fullPatch = patchR.stdout
198
+
199
+ // Split into per-file sections on the `diff --git` boundary.
200
+ const sections = []
201
+ const re = /(^|\n)(diff --git [^\n]*\n)/g
202
+ const indices = []
203
+ let m
204
+ while ((m = re.exec(fullPatch)) !== null) indices.push(m.index + (m[1] ? 1 : 0))
205
+ if (indices.length === 0 && fullPatch) sections.push(fullPatch)
206
+ for (let i = 0; i < indices.length; i += 1) {
207
+ const start = indices[i]
208
+ const end = i + 1 < indices.length ? indices[i + 1] : fullPatch.length
209
+ sections.push(fullPatch.slice(start, end))
210
+ }
211
+
212
+ const fileNameOf = (section) => {
213
+ const fm = section.match(/^diff --git a\/(.+?) b\/(.+?)\n/)
214
+ return fm ? fm[2] : (section.split('\n', 1)[0] || 'unknown').slice(0, 200)
215
+ }
216
+
217
+ let out = ''
218
+ let truncated = false
219
+ const includedFiles = []
220
+ const omittedFiles = []
221
+ for (const section of sections) {
222
+ const name = fileNameOf(section)
223
+ // Whole-file omission once the total budget is exhausted.
224
+ if (Buffer.byteLength(out, 'utf8') >= maxBytes) {
225
+ truncated = true
226
+ omittedFiles.push(name)
227
+ continue
228
+ }
229
+ let piece = section
230
+ if (Buffer.byteLength(piece, 'utf8') > maxFileBytes) {
231
+ // Byte-accurate truncation (not String.slice, which counts UTF-16 units
232
+ // and overshoots the byte budget on multibyte content).
233
+ const kept = byteSliceUtf8(piece, maxFileBytes)
234
+ const omittedBytes = Buffer.byteLength(section, 'utf8') - Buffer.byteLength(kept, 'utf8')
235
+ piece = `${kept}\n// … ${omittedBytes} bytes omitted (file diff truncated)\n`
236
+ truncated = true
237
+ }
238
+ // Total-budget check after per-file truncation.
239
+ if (Buffer.byteLength(out + piece, 'utf8') > maxBytes) {
240
+ truncated = true
241
+ omittedFiles.push(name)
242
+ continue
243
+ }
244
+ out += piece
245
+ includedFiles.push(name)
246
+ }
247
+ if (omittedFiles.length) out += `\n// omitted files (diff too large): ${omittedFiles.join(', ')}\n`
248
+
249
+ return { stat, patch: out, truncated, omittedFiles, includedFiles }
250
+ }
251
+
252
+ // --- auto-commit (the load-bearing safety primitive) ---------------------
253
+
254
+ // THROWS on a git-status failure rather than reporting clean — a false "clean"
255
+ // would make autoCommit a no-op and let teardown delete uncommitted work. A
256
+ // caller must treat an indeterminate tree as "do not destroy".
257
+ const isDirty = async (worktreePath) => {
258
+ const r = await runOrThrow(['-C', worktreePath, 'status', '--porcelain'], { maxBuffer: DIFF_MAX_BUFFER })
259
+ return { dirty: r.stdout.trim().length > 0 }
260
+ }
261
+
262
+ // Commit everything in a worker worktree. Called ALWAYS before destroying an
263
+ // implement worker (destroySession removes the worktree, deleting uncommitted
264
+ // work). A clean tree is a no-op, not an error. --no-verify / --no-gpg-sign:
265
+ // these are the daemon's OWN bookkeeping commits — they must not run the
266
+ // user's pre-commit/commit-msg hooks (a rejecting hook would throw here and
267
+ // lose the worker's output) or require a GPG key the daemon doesn't have.
268
+ const autoCommit = async ({ worktreePath, subtaskId, message = null, identity: id = identity }) => {
269
+ const { dirty } = await isDirty(worktreePath)
270
+ if (!dirty) return { committed: false }
271
+ await runOrThrow(['-C', worktreePath, 'add', '-A'])
272
+ const msg = message || `chroxy-orch(${subtaskId}): auto-commit`
273
+ await runOrThrow(['-C', worktreePath, '-c', `user.name=${id.name}`, '-c', `user.email=${id.email}`,
274
+ 'commit', '--no-verify', '--no-gpg-sign', '-m', msg])
275
+ const head = await captureHead(worktreePath)
276
+ return { committed: true, sha: head.sha }
277
+ }
278
+
279
+ // --- integration worktree + sequential merge -----------------------------
280
+
281
+ const createIntegrationWorktree = async ({ repoDir, runId, branchName, baseSha }) => {
282
+ assertSafeRef(branchName, 'branch')
283
+ // #7342: `baseSha` is the final positional operand of `worktree add`, so a
284
+ // dash-leading value would be read as an option there too.
285
+ assertSafeRef(baseSha, 'base ref')
286
+ const worktreePath = integrationWorktreePath(runId)
287
+ fs.mkdirSync(runWorktreesDir(runId), { recursive: true })
288
+ await runOrThrow(['-C', repoDir, 'worktree', 'add', '-b', branchName, worktreePath, baseSha])
289
+ return { worktreePath, branch: branchName }
290
+ }
291
+
292
+ const conflictFiles = async (integrationWorktree) => {
293
+ const r = await run(['-C', integrationWorktree, 'diff', '--name-only', '--diff-filter=U'])
294
+ return r.ok ? r.stdout.split('\n').map((s) => s.trim()).filter(Boolean) : []
295
+ }
296
+
297
+ const mergeNoFf = async ({ integrationWorktree, branch, subtaskId, identity: id = identity }) => {
298
+ assertSafeRef(branch, 'branch')
299
+ // --no-verify / --no-gpg-sign for the same reason as autoCommit: the merge
300
+ // commit is the daemon's bookkeeping, so a user commit-msg/pre-merge-commit
301
+ // hook must not be able to reject it (that would look like a non-conflict
302
+ // failure and wedge the integration worktree with MERGE_HEAD set).
303
+ const r = await run(['-C', integrationWorktree, '-c', `user.name=${id.name}`, '-c', `user.email=${id.email}`,
304
+ 'merge', '--no-ff', '--no-verify', '--no-gpg-sign', '-m', `chroxy-orch: merge ${subtaskId}`, branch])
305
+ if (r.ok) return { ok: true }
306
+ const files = await conflictFiles(integrationWorktree)
307
+ if (files.length > 0 || /conflict/i.test(r.stderr) || /conflict/i.test(r.stdout)) {
308
+ return { ok: false, conflict: true, conflictFiles: files, stderr: r.stderr }
309
+ }
310
+ // A non-conflict merge failure is genuinely unexpected.
311
+ throw new GitOpsError(`merge ${branch} failed: ${r.stderr}`, { stderr: r.stderr })
312
+ }
313
+
314
+ const abortMerge = async (integrationWorktree) => {
315
+ const r = await run(['-C', integrationWorktree, 'merge', '--abort'])
316
+ return { aborted: r.ok }
317
+ }
318
+
319
+ // --- teardown + reconcile ------------------------------------------------
320
+
321
+ // Remove an ORCHESTRATOR-OWNED worktree. --force + the rm fallback are safe
322
+ // ONLY under the worktrees root — this guard ENFORCES that invariant so a
323
+ // corrupted ledger record or a buggy caller can never `rm -rf` the user's
324
+ // repo, the ledger's runs/ dir, or any path outside the root. The root itself
325
+ // is also refused (we only ever remove `<root>/<runId>/…`).
326
+ const removeWorktree = async ({ repoDir, worktreePath }) => {
327
+ const base = resolve(rootDir())
328
+ const target = resolve(String(worktreePath || ''))
329
+ if (target === base || !target.startsWith(base + sep)) {
330
+ throw new GitOpsError(`refusing to remove a path outside the worktrees root: ${worktreePath}`)
331
+ }
332
+ const r = await run(['-C', repoDir, 'worktree', 'remove', '--force', target])
333
+ if (r.ok) return { removed: true, method: 'git' }
334
+ if (fs.existsSync(target)) {
335
+ try { fs.rmSync(target, { recursive: true, force: true }) } catch { /* best-effort */ }
336
+ }
337
+ return { removed: true, method: 'rm' }
338
+ }
339
+
340
+ const pruneWorktrees = async (repoDir) => {
341
+ const r = await run(['-C', repoDir, 'worktree', 'prune'])
342
+ return { pruned: r.ok }
343
+ }
344
+
345
+ // Parse `worktree list --porcelain` into { path, head, branch, detached }.
346
+ const listWorktrees = async (repoDir) => {
347
+ const r = await run(['-C', repoDir, 'worktree', 'list', '--porcelain'])
348
+ if (!r.ok) return []
349
+ const entries = []
350
+ let cur = null
351
+ for (const line of r.stdout.split('\n')) {
352
+ if (line.startsWith('worktree ')) { cur = { path: line.slice('worktree '.length).trim(), head: null, branch: null, detached: false }; entries.push(cur) }
353
+ else if (cur && line.startsWith('HEAD ')) cur.head = line.slice('HEAD '.length).trim()
354
+ else if (cur && line.startsWith('branch ')) cur.branch = line.slice('branch '.length).trim()
355
+ else if (cur && line.trim() === 'detached') cur.detached = true
356
+ }
357
+ return entries
358
+ }
359
+
360
+ return {
361
+ now,
362
+ identity,
363
+ configDir,
364
+ orchestrationWorktreesRoot,
365
+ runWorktreesDir,
366
+ integrationWorktreePath,
367
+ captureHead,
368
+ createBranch,
369
+ branchExists,
370
+ deleteBranch,
371
+ computeCappedDiff,
372
+ isDirty,
373
+ autoCommit,
374
+ createIntegrationWorktree,
375
+ mergeNoFf,
376
+ abortMerge,
377
+ removeWorktree,
378
+ pruneWorktrees,
379
+ listWorktrees,
380
+ }
381
+ }