@chroxy/server 0.10.0 → 0.11.0
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.
- package/CONFIG.md +411 -14
- package/hooks/permission-hook.sh +253 -3
- package/package.json +8 -15
- package/sidecar/node_modules/.package-lock.json +29 -0
- package/sidecar/node_modules/ws/LICENSE +20 -0
- package/sidecar/node_modules/ws/README.md +548 -0
- package/sidecar/node_modules/ws/browser.js +8 -0
- package/sidecar/node_modules/ws/index.js +22 -0
- package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
- package/sidecar/node_modules/ws/lib/constants.js +19 -0
- package/sidecar/node_modules/ws/lib/event-target.js +292 -0
- package/sidecar/node_modules/ws/lib/extension.js +203 -0
- package/sidecar/node_modules/ws/lib/limiter.js +55 -0
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
- package/sidecar/node_modules/ws/lib/receiver.js +706 -0
- package/sidecar/node_modules/ws/lib/sender.js +602 -0
- package/sidecar/node_modules/ws/lib/stream.js +161 -0
- package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
- package/sidecar/node_modules/ws/lib/validation.js +152 -0
- package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
- package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
- package/sidecar/node_modules/ws/package.json +70 -0
- package/sidecar/node_modules/ws/wrapper.mjs +21 -0
- package/src/base-session.js +151 -6
- package/src/billing-budget.js +5 -1
- package/src/binary-provenance-trust.js +95 -0
- package/src/built-in-tools/file-ops.js +5 -4
- package/src/byok-mcp-client.js +1061 -13
- package/src/byok-mcp-config.js +1201 -4
- package/src/byok-mcp-fleet.js +374 -29
- package/src/byok-mcp-oauth-store.js +327 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +254 -37
- package/src/byok-session.js +789 -13
- package/src/byok-tool-executor.js +20 -13
- package/src/checkpoint-manager.js +33 -6
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-stream-parser.js +56 -0
- package/src/claude-tui/pty-driver.js +54 -14
- package/src/claude-tui-session.js +106 -7
- package/src/cli/config-cmd.js +2 -2
- package/src/cli/deploy-cmd.js +1 -1
- package/src/cli/init-cmd.js +1 -1
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +775 -0
- package/src/cli/server-cmd.js +16 -1
- package/src/cli/service-cmd.js +39 -19
- package/src/cli/shared.js +7 -4
- package/src/cli/tokens-cmd.js +213 -0
- package/src/cli/tunnel-cmd.js +1 -1
- package/src/cli-session.js +66 -10
- package/src/cli.js +4 -0
- package/src/codex-app-server-session.js +671 -39
- package/src/codex-session.js +121 -18
- package/src/config.js +453 -27
- package/src/control-room/integrations.js +16 -10
- package/src/control-room/skills-inventory.js +6 -1
- package/src/control-room/survey.js +32 -0
- package/src/credential-store.js +256 -10
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
- package/src/diagnostics.js +3 -0
- package/src/docker-sdk-session.js +16 -1
- package/src/docker-session.js +9 -0
- package/src/doctor.js +19 -8
- package/src/environments/backends/docker.js +8 -0
- package/src/environments/backends/k8s.js +9 -0
- package/src/event-ingest.js +19 -1
- package/src/event-normalizer.js +354 -19
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +19 -2
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +42 -8
- package/src/handlers/checkpoint-handlers.js +126 -19
- package/src/handlers/control-room-handlers.js +48 -18
- package/src/handlers/conversation-handlers.js +127 -2
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/file-handlers.js +47 -3
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +4 -0
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +510 -0
- package/src/handlers/session-handlers.js +10 -2
- package/src/handlers/settings-handlers.js +510 -11
- package/src/handlers/token-handlers.js +11 -2
- package/src/http-routes.js +159 -0
- package/src/jsonl-reader.js +60 -6
- package/src/jsonl-subprocess-session.js +35 -6
- package/src/keychain.js +159 -12
- package/src/logger.js +182 -19
- package/src/notification-prefs.js +88 -6
- package/src/notifications/discord-webhook-sink.js +30 -1
- package/src/orchestration/build-manager.js +56 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +347 -0
- package/src/orchestration/orchestration-manager.js +1295 -0
- package/src/orchestration/permission-gate.js +109 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +205 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +398 -0
- package/src/pairing.js +146 -1
- package/src/permission-audit.js +79 -3
- package/src/permission-floor.js +455 -0
- package/src/permission-manager.js +492 -40
- package/src/permission-resolver.js +55 -7
- package/src/permission-rule-store.js +411 -0
- package/src/platform.js +367 -23
- package/src/providers.js +21 -2
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +653 -0
- package/src/scheduler.js +1029 -0
- package/src/sdk-session.js +338 -5
- package/src/server-cli/server-orchestrator.js +23 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli.js +238 -26
- package/src/server-identity.js +28 -4
- package/src/service.js +291 -33
- package/src/session-manager.js +417 -25
- package/src/session-message-history.js +27 -21
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +60 -35
- package/src/skills-usage.js +20 -2
- package/src/statusline.js +584 -0
- package/src/subagent-counter.js +9 -1
- package/src/supervisor.js +77 -27
- package/src/token-manager.js +39 -9
- package/src/transcript-tasks.js +41 -6
- package/src/tunnel/cloudflare.js +115 -8
- package/src/tunnel/index.js +4 -1
- package/src/tunnel-check.js +1 -1
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +118 -0
- package/src/user-shell-session.js +98 -32
- package/src/utils/componentwise-resolver.js +205 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/preflight.js +140 -28
- package/src/utils/spawn-env.js +8 -2
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +241 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/worktree-gc.js +4 -1
- package/src/ws-file-ops/browser.js +42 -11
- package/src/ws-file-ops/common.js +68 -1
- package/src/ws-file-ops/git.js +221 -3
- package/src/ws-file-ops/index.js +5 -0
- package/src/ws-file-ops/memory.js +358 -0
- package/src/ws-file-ops/reader.js +124 -0
- package/src/ws-forwarding.js +44 -16
- package/src/ws-handler-context.js +19 -0
- package/src/ws-history.js +84 -11
- package/src/ws-message-handlers.js +6 -0
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +285 -4
- package/src/ws-schemas.js +1 -0
- package/src/ws-server.js +301 -17
|
@@ -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,347 @@
|
|
|
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 { homedir } from 'node:os'
|
|
31
|
+
import { rmSync, mkdirSync, existsSync } from 'node:fs'
|
|
32
|
+
import { GIT } from '../git.js'
|
|
33
|
+
|
|
34
|
+
const execFileAsync = promisify(execFileCb)
|
|
35
|
+
|
|
36
|
+
const DEFAULT_TIMEOUT_MS = 30_000
|
|
37
|
+
const DEFAULT_MAX_BUFFER = 8 * 1024 * 1024
|
|
38
|
+
// A raw `git diff`/`status` can be far larger than what we KEEP; buffer
|
|
39
|
+
// generously so a big real change is never misread as empty (we cap the KEPT
|
|
40
|
+
// bytes separately in computeCappedDiff).
|
|
41
|
+
const DIFF_MAX_BUFFER = 64 * 1024 * 1024
|
|
42
|
+
|
|
43
|
+
// Reject a ref/path that git would parse as an OPTION (leading '-') or that
|
|
44
|
+
// carries a NUL/newline — defense-in-depth so a caller can never turn a branch
|
|
45
|
+
// name into a git flag. execFile already blocks SHELL injection; this blocks
|
|
46
|
+
// ARGUMENT injection.
|
|
47
|
+
function assertSafeRef(name, kind = 'ref') {
|
|
48
|
+
if (typeof name !== 'string' || name.length === 0) throw new GitOpsError(`empty ${kind}`)
|
|
49
|
+
if (name.startsWith('-') || /[\0\n\r]/.test(name)) throw new GitOpsError(`unsafe ${kind}: ${JSON.stringify(name)}`)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Byte-accurate UTF-8 truncation that drops an incomplete trailing multibyte
|
|
53
|
+
// char (String.slice counts UTF-16 code units, so it can overshoot a byte
|
|
54
|
+
// budget ~3x on CJK content and split surrogate pairs into U+FFFD).
|
|
55
|
+
function byteSliceUtf8(str, maxBytes) {
|
|
56
|
+
const buf = Buffer.from(str, 'utf8')
|
|
57
|
+
if (buf.length <= maxBytes) return str
|
|
58
|
+
// stream:true holds back an incomplete trailing sequence instead of emitting U+FFFD.
|
|
59
|
+
return new TextDecoder('utf-8').decode(buf.subarray(0, maxBytes), { stream: true })
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Orchestrator commit identity — the daemon env has no configured git identity,
|
|
63
|
+
// so a bare `git commit` would fail. Passed per-invocation via `-c`, never
|
|
64
|
+
// written to any user config.
|
|
65
|
+
const ORCH_IDENTITY = { name: 'chroxy-orch', email: 'orch@chroxy.local' }
|
|
66
|
+
|
|
67
|
+
/** ~/.chroxy (honoring CHROXY_CONFIG_DIR), matching the rest of the daemon. */
|
|
68
|
+
export function configDir() {
|
|
69
|
+
return process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The root the orphan sweep and the provisioner MUST agree on. Never `runs/`. */
|
|
73
|
+
export function defaultWorktreesRoot() {
|
|
74
|
+
return join(configDir(), 'orchestration', 'worktrees')
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export class GitOpsError extends Error {
|
|
78
|
+
constructor(message, { args = null, stderr = null } = {}) {
|
|
79
|
+
super(message)
|
|
80
|
+
this.name = 'GitOpsError'
|
|
81
|
+
this.code = 'GIT_OP_FAILED'
|
|
82
|
+
this.args = args
|
|
83
|
+
this.stderr = stderr
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function createGitOps({ git = GIT, now = () => Date.now(), worktreesRoot = null, identity = ORCH_IDENTITY, fs = { rmSync, mkdirSync, existsSync } } = {}) {
|
|
88
|
+
const gitBin = () => git
|
|
89
|
+
const rootDir = () => worktreesRoot || defaultWorktreesRoot()
|
|
90
|
+
|
|
91
|
+
const errText = (err) => (err?.stderr?.trim?.() || err?.message || String(err))
|
|
92
|
+
|
|
93
|
+
// Run git; resolve { stdout, stderr } on success. On failure, resolve a
|
|
94
|
+
// structured { failed:true, stderr, code } so callers can branch on expected
|
|
95
|
+
// failure modes instead of try/catch everywhere.
|
|
96
|
+
const run = async (args, { timeout = DEFAULT_TIMEOUT_MS, maxBuffer = DEFAULT_MAX_BUFFER } = {}) => {
|
|
97
|
+
try {
|
|
98
|
+
const { stdout, stderr } = await execFileAsync(gitBin(), args, { timeout, maxBuffer })
|
|
99
|
+
return { ok: true, stdout: stdout ?? '', stderr: stderr ?? '' }
|
|
100
|
+
} catch (err) {
|
|
101
|
+
return { ok: false, stdout: err?.stdout ?? '', stderr: errText(err), code: err?.code ?? null }
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// Run git; THROW on failure. For ops where a failure is genuinely unexpected.
|
|
105
|
+
const runOrThrow = async (args, opts) => {
|
|
106
|
+
const r = await run(args, opts)
|
|
107
|
+
if (!r.ok) throw new GitOpsError(`git ${args.join(' ')} failed: ${r.stderr}`, { args, stderr: r.stderr })
|
|
108
|
+
return r
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// --- path single-source-of-truth ----------------------------------------
|
|
112
|
+
|
|
113
|
+
const orchestrationWorktreesRoot = () => rootDir()
|
|
114
|
+
const runWorktreesDir = (runId) => join(rootDir(), String(runId))
|
|
115
|
+
const integrationWorktreePath = (runId) => join(rootDir(), String(runId), 'integration')
|
|
116
|
+
|
|
117
|
+
// --- branch + HEAD -------------------------------------------------------
|
|
118
|
+
|
|
119
|
+
const captureHead = async (dir) => {
|
|
120
|
+
const r = await runOrThrow(['-C', dir, 'rev-parse', 'HEAD'])
|
|
121
|
+
return { sha: r.stdout.trim() }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// A worker worktree is created DETACHED at HEAD; put it on a named branch.
|
|
125
|
+
const createBranch = async (worktreePath, branchName) => {
|
|
126
|
+
assertSafeRef(branchName, 'branch')
|
|
127
|
+
const base = await captureHead(worktreePath)
|
|
128
|
+
await runOrThrow(['-C', worktreePath, 'switch', '-c', branchName])
|
|
129
|
+
return { branch: branchName, baseSha: base.sha }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const branchExists = async (repoDir, branchName) => {
|
|
133
|
+
assertSafeRef(branchName, 'branch')
|
|
134
|
+
const r = await run(['-C', repoDir, 'rev-parse', '--verify', '--quiet', `refs/heads/${branchName}`])
|
|
135
|
+
return { exists: r.ok }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const deleteBranch = async (repoDir, branchName) => {
|
|
139
|
+
assertSafeRef(branchName, 'branch')
|
|
140
|
+
const r = await run(['-C', repoDir, 'branch', '-D', '--', branchName])
|
|
141
|
+
return { deleted: r.ok }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// --- capped diff ---------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
// A reproducible, size-bounded review artifact: baseSha..headRef, per-file
|
|
147
|
+
// and total byte caps with explicit truncation markers so a small worker
|
|
148
|
+
// model isn't handed a 2MB patch.
|
|
149
|
+
const computeCappedDiff = async ({ repoDir, baseSha, headRef = 'HEAD', maxBytes = 65_536, maxFileBytes = 8_192 }) => {
|
|
150
|
+
const statR = await run(['-C', repoDir, 'diff', '--stat', `${baseSha}..${headRef}`], { maxBuffer: DIFF_MAX_BUFFER })
|
|
151
|
+
const patchR = await run(['-C', repoDir, 'diff', `${baseSha}..${headRef}`], { maxBuffer: DIFF_MAX_BUFFER })
|
|
152
|
+
const stat = statR.ok ? statR.stdout : ''
|
|
153
|
+
// If the raw diff couldn't be produced/buffered, NEVER return an empty patch
|
|
154
|
+
// as if clean — that would let a huge unreviewed change look like no change.
|
|
155
|
+
// Report it honestly as truncated with an explicit marker.
|
|
156
|
+
if (!patchR.ok) {
|
|
157
|
+
return {
|
|
158
|
+
stat,
|
|
159
|
+
patch: `// diff unavailable (${patchR.stderr || 'exceeded buffer'})\n`,
|
|
160
|
+
truncated: true,
|
|
161
|
+
omittedFiles: [],
|
|
162
|
+
includedFiles: [],
|
|
163
|
+
error: patchR.stderr || 'diff_unavailable',
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const fullPatch = patchR.stdout
|
|
167
|
+
|
|
168
|
+
// Split into per-file sections on the `diff --git` boundary.
|
|
169
|
+
const sections = []
|
|
170
|
+
const re = /(^|\n)(diff --git [^\n]*\n)/g
|
|
171
|
+
const indices = []
|
|
172
|
+
let m
|
|
173
|
+
while ((m = re.exec(fullPatch)) !== null) indices.push(m.index + (m[1] ? 1 : 0))
|
|
174
|
+
if (indices.length === 0 && fullPatch) sections.push(fullPatch)
|
|
175
|
+
for (let i = 0; i < indices.length; i += 1) {
|
|
176
|
+
const start = indices[i]
|
|
177
|
+
const end = i + 1 < indices.length ? indices[i + 1] : fullPatch.length
|
|
178
|
+
sections.push(fullPatch.slice(start, end))
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const fileNameOf = (section) => {
|
|
182
|
+
const fm = section.match(/^diff --git a\/(.+?) b\/(.+?)\n/)
|
|
183
|
+
return fm ? fm[2] : (section.split('\n', 1)[0] || 'unknown').slice(0, 200)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
let out = ''
|
|
187
|
+
let truncated = false
|
|
188
|
+
const includedFiles = []
|
|
189
|
+
const omittedFiles = []
|
|
190
|
+
for (const section of sections) {
|
|
191
|
+
const name = fileNameOf(section)
|
|
192
|
+
// Whole-file omission once the total budget is exhausted.
|
|
193
|
+
if (Buffer.byteLength(out, 'utf8') >= maxBytes) {
|
|
194
|
+
truncated = true
|
|
195
|
+
omittedFiles.push(name)
|
|
196
|
+
continue
|
|
197
|
+
}
|
|
198
|
+
let piece = section
|
|
199
|
+
if (Buffer.byteLength(piece, 'utf8') > maxFileBytes) {
|
|
200
|
+
// Byte-accurate truncation (not String.slice, which counts UTF-16 units
|
|
201
|
+
// and overshoots the byte budget on multibyte content).
|
|
202
|
+
const kept = byteSliceUtf8(piece, maxFileBytes)
|
|
203
|
+
const omittedBytes = Buffer.byteLength(section, 'utf8') - Buffer.byteLength(kept, 'utf8')
|
|
204
|
+
piece = `${kept}\n// … ${omittedBytes} bytes omitted (file diff truncated)\n`
|
|
205
|
+
truncated = true
|
|
206
|
+
}
|
|
207
|
+
// Total-budget check after per-file truncation.
|
|
208
|
+
if (Buffer.byteLength(out + piece, 'utf8') > maxBytes) {
|
|
209
|
+
truncated = true
|
|
210
|
+
omittedFiles.push(name)
|
|
211
|
+
continue
|
|
212
|
+
}
|
|
213
|
+
out += piece
|
|
214
|
+
includedFiles.push(name)
|
|
215
|
+
}
|
|
216
|
+
if (omittedFiles.length) out += `\n// omitted files (diff too large): ${omittedFiles.join(', ')}\n`
|
|
217
|
+
|
|
218
|
+
return { stat, patch: out, truncated, omittedFiles, includedFiles }
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// --- auto-commit (the load-bearing safety primitive) ---------------------
|
|
222
|
+
|
|
223
|
+
// THROWS on a git-status failure rather than reporting clean — a false "clean"
|
|
224
|
+
// would make autoCommit a no-op and let teardown delete uncommitted work. A
|
|
225
|
+
// caller must treat an indeterminate tree as "do not destroy".
|
|
226
|
+
const isDirty = async (worktreePath) => {
|
|
227
|
+
const r = await runOrThrow(['-C', worktreePath, 'status', '--porcelain'], { maxBuffer: DIFF_MAX_BUFFER })
|
|
228
|
+
return { dirty: r.stdout.trim().length > 0 }
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// Commit everything in a worker worktree. Called ALWAYS before destroying an
|
|
232
|
+
// implement worker (destroySession removes the worktree, deleting uncommitted
|
|
233
|
+
// work). A clean tree is a no-op, not an error. --no-verify / --no-gpg-sign:
|
|
234
|
+
// these are the daemon's OWN bookkeeping commits — they must not run the
|
|
235
|
+
// user's pre-commit/commit-msg hooks (a rejecting hook would throw here and
|
|
236
|
+
// lose the worker's output) or require a GPG key the daemon doesn't have.
|
|
237
|
+
const autoCommit = async ({ worktreePath, subtaskId, message = null, identity: id = identity }) => {
|
|
238
|
+
const { dirty } = await isDirty(worktreePath)
|
|
239
|
+
if (!dirty) return { committed: false }
|
|
240
|
+
await runOrThrow(['-C', worktreePath, 'add', '-A'])
|
|
241
|
+
const msg = message || `chroxy-orch(${subtaskId}): auto-commit`
|
|
242
|
+
await runOrThrow(['-C', worktreePath, '-c', `user.name=${id.name}`, '-c', `user.email=${id.email}`,
|
|
243
|
+
'commit', '--no-verify', '--no-gpg-sign', '-m', msg])
|
|
244
|
+
const head = await captureHead(worktreePath)
|
|
245
|
+
return { committed: true, sha: head.sha }
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// --- integration worktree + sequential merge -----------------------------
|
|
249
|
+
|
|
250
|
+
const createIntegrationWorktree = async ({ repoDir, runId, branchName, baseSha }) => {
|
|
251
|
+
assertSafeRef(branchName, 'branch')
|
|
252
|
+
const worktreePath = integrationWorktreePath(runId)
|
|
253
|
+
fs.mkdirSync(runWorktreesDir(runId), { recursive: true })
|
|
254
|
+
await runOrThrow(['-C', repoDir, 'worktree', 'add', '-b', branchName, worktreePath, baseSha])
|
|
255
|
+
return { worktreePath, branch: branchName }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const conflictFiles = async (integrationWorktree) => {
|
|
259
|
+
const r = await run(['-C', integrationWorktree, 'diff', '--name-only', '--diff-filter=U'])
|
|
260
|
+
return r.ok ? r.stdout.split('\n').map((s) => s.trim()).filter(Boolean) : []
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const mergeNoFf = async ({ integrationWorktree, branch, subtaskId, identity: id = identity }) => {
|
|
264
|
+
assertSafeRef(branch, 'branch')
|
|
265
|
+
// --no-verify / --no-gpg-sign for the same reason as autoCommit: the merge
|
|
266
|
+
// commit is the daemon's bookkeeping, so a user commit-msg/pre-merge-commit
|
|
267
|
+
// hook must not be able to reject it (that would look like a non-conflict
|
|
268
|
+
// failure and wedge the integration worktree with MERGE_HEAD set).
|
|
269
|
+
const r = await run(['-C', integrationWorktree, '-c', `user.name=${id.name}`, '-c', `user.email=${id.email}`,
|
|
270
|
+
'merge', '--no-ff', '--no-verify', '--no-gpg-sign', '-m', `chroxy-orch: merge ${subtaskId}`, branch])
|
|
271
|
+
if (r.ok) return { ok: true }
|
|
272
|
+
const files = await conflictFiles(integrationWorktree)
|
|
273
|
+
if (files.length > 0 || /conflict/i.test(r.stderr) || /conflict/i.test(r.stdout)) {
|
|
274
|
+
return { ok: false, conflict: true, conflictFiles: files, stderr: r.stderr }
|
|
275
|
+
}
|
|
276
|
+
// A non-conflict merge failure is genuinely unexpected.
|
|
277
|
+
throw new GitOpsError(`merge ${branch} failed: ${r.stderr}`, { stderr: r.stderr })
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const abortMerge = async (integrationWorktree) => {
|
|
281
|
+
const r = await run(['-C', integrationWorktree, 'merge', '--abort'])
|
|
282
|
+
return { aborted: r.ok }
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// --- teardown + reconcile ------------------------------------------------
|
|
286
|
+
|
|
287
|
+
// Remove an ORCHESTRATOR-OWNED worktree. --force + the rm fallback are safe
|
|
288
|
+
// ONLY under the worktrees root — this guard ENFORCES that invariant so a
|
|
289
|
+
// corrupted ledger record or a buggy caller can never `rm -rf` the user's
|
|
290
|
+
// repo, the ledger's runs/ dir, or any path outside the root. The root itself
|
|
291
|
+
// is also refused (we only ever remove `<root>/<runId>/…`).
|
|
292
|
+
const removeWorktree = async ({ repoDir, worktreePath }) => {
|
|
293
|
+
const base = resolve(rootDir())
|
|
294
|
+
const target = resolve(String(worktreePath || ''))
|
|
295
|
+
if (target === base || !target.startsWith(base + sep)) {
|
|
296
|
+
throw new GitOpsError(`refusing to remove a path outside the worktrees root: ${worktreePath}`)
|
|
297
|
+
}
|
|
298
|
+
const r = await run(['-C', repoDir, 'worktree', 'remove', '--force', target])
|
|
299
|
+
if (r.ok) return { removed: true, method: 'git' }
|
|
300
|
+
if (fs.existsSync(target)) {
|
|
301
|
+
try { fs.rmSync(target, { recursive: true, force: true }) } catch { /* best-effort */ }
|
|
302
|
+
}
|
|
303
|
+
return { removed: true, method: 'rm' }
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const pruneWorktrees = async (repoDir) => {
|
|
307
|
+
const r = await run(['-C', repoDir, 'worktree', 'prune'])
|
|
308
|
+
return { pruned: r.ok }
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// Parse `worktree list --porcelain` into { path, head, branch, detached }.
|
|
312
|
+
const listWorktrees = async (repoDir) => {
|
|
313
|
+
const r = await run(['-C', repoDir, 'worktree', 'list', '--porcelain'])
|
|
314
|
+
if (!r.ok) return []
|
|
315
|
+
const entries = []
|
|
316
|
+
let cur = null
|
|
317
|
+
for (const line of r.stdout.split('\n')) {
|
|
318
|
+
if (line.startsWith('worktree ')) { cur = { path: line.slice('worktree '.length).trim(), head: null, branch: null, detached: false }; entries.push(cur) }
|
|
319
|
+
else if (cur && line.startsWith('HEAD ')) cur.head = line.slice('HEAD '.length).trim()
|
|
320
|
+
else if (cur && line.startsWith('branch ')) cur.branch = line.slice('branch '.length).trim()
|
|
321
|
+
else if (cur && line.trim() === 'detached') cur.detached = true
|
|
322
|
+
}
|
|
323
|
+
return entries
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
return {
|
|
327
|
+
now,
|
|
328
|
+
identity,
|
|
329
|
+
configDir,
|
|
330
|
+
orchestrationWorktreesRoot,
|
|
331
|
+
runWorktreesDir,
|
|
332
|
+
integrationWorktreePath,
|
|
333
|
+
captureHead,
|
|
334
|
+
createBranch,
|
|
335
|
+
branchExists,
|
|
336
|
+
deleteBranch,
|
|
337
|
+
computeCappedDiff,
|
|
338
|
+
isDirty,
|
|
339
|
+
autoCommit,
|
|
340
|
+
createIntegrationWorktree,
|
|
341
|
+
mergeNoFf,
|
|
342
|
+
abortMerge,
|
|
343
|
+
removeWorktree,
|
|
344
|
+
pruneWorktrees,
|
|
345
|
+
listWorktrees,
|
|
346
|
+
}
|
|
347
|
+
}
|