dsh-coding-enhanced 0.0.0-stage → 0.5.15

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/lib/index.js ADDED
@@ -0,0 +1,1771 @@
1
+ /**
2
+ * dsh-coding-enhanced — host half.
3
+ *
4
+ * Codex-style "undo last turn" for DeepSeek Harness:
5
+ *
6
+ * - Before every top-level turn starts, a shadow git repository (kept under
7
+ * `$DSH_HOME/coding-enhanced/repos`, never inside the workspace) records a
8
+ * tree of the whole working directory. The first tool call of the turn
9
+ * waits for that snapshot, so no mutation can precede it.
10
+ * - Withdrawing a turn restores the working directory to that tree (modified,
11
+ * created, and deleted files alike), appends a model-only surface
12
+ * replacement that hides the turn from the AI's context, and records the
13
+ * withdrawal so the client can grey the transcript.
14
+ *
15
+ * The browser half talks to this file through the authenticated Connection
16
+ * `/api` bridge: `POST /api/coding-enhanced` with `{ endpoint, payload }`.
17
+ */
18
+ import { execFile } from 'node:child_process'
19
+ import { defineTool } from '@deepseek-ai/dsh-tools'
20
+ import { createHash } from 'node:crypto'
21
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs'
22
+ import fs from 'node:fs/promises'
23
+ import os from 'node:os'
24
+ import path from 'node:path'
25
+
26
+ export const name = 'coding-enhanced'
27
+ export const inject = ['sessions', 'connection', 'tools', 'systemPrompt']
28
+
29
+ const SURFACE_TYPES = new Set([
30
+ 'system/message',
31
+ 'developer/message',
32
+ 'user/message',
33
+ 'assistant/message',
34
+ 'tool/result',
35
+ ])
36
+
37
+ const DEFAULT_EXCLUDES = ['.git/', 'node_modules/', '.DS_Store', '.dsh-coding-enhanced/']
38
+ const GIT_TIMEOUT_MS = 5 * 60 * 1000
39
+ const MAX_BUFFER = 512 * 1024 * 1024
40
+
41
+ /** Resolve a usable git executable once. */
42
+ function resolveGit() {
43
+ const candidates = [
44
+ '/opt/homebrew/bin/git',
45
+ '/usr/local/bin/git',
46
+ '/usr/bin/git',
47
+ 'git',
48
+ ]
49
+ for (const candidate of candidates) {
50
+ if (candidate !== 'git' && !existsSync(candidate)) continue
51
+ return candidate
52
+ }
53
+ return 'git'
54
+ }
55
+
56
+ const GIT = resolveGit()
57
+
58
+ function runGit(args, { gitDir, workTree, encoding = 'utf8' } = {}) {
59
+ const full = ['--git-dir', gitDir]
60
+ if (workTree !== undefined) full.push('--work-tree', workTree)
61
+ full.push(...args)
62
+ return new Promise((resolve, reject) => {
63
+ execFile(
64
+ GIT,
65
+ full,
66
+ {
67
+ ...(workTree === undefined ? {} : { cwd: workTree }),
68
+ env: {
69
+ ...process.env,
70
+ GIT_TERMINAL_PROMPT: '0',
71
+ GIT_OPTIONAL_LOCKS: '0',
72
+ GIT_CONFIG_NOSYSTEM: '1',
73
+ GIT_INDEX_FILE: path.join(gitDir, 'index'),
74
+ },
75
+ maxBuffer: MAX_BUFFER,
76
+ timeout: GIT_TIMEOUT_MS,
77
+ encoding,
78
+ },
79
+ (error, stdout, stderr) => {
80
+ if (error !== null) {
81
+ const message = typeof stderr === 'string' && stderr.trim() !== ''
82
+ ? stderr.trim()
83
+ : error.message
84
+ reject(new Error(`git ${args[0]} failed: ${message}`))
85
+ return
86
+ }
87
+ resolve(stdout)
88
+ },
89
+ )
90
+ })
91
+ }
92
+
93
+ function isSubagent(session) {
94
+ const header = session.header ?? {}
95
+ return header.origin === 'subagent' || (header.delegationDepth ?? 0) > 0
96
+ }
97
+
98
+ function shadowRepoPath(root, cwd) {
99
+ const key = createHash('sha1').update(cwd).digest('hex').slice(0, 20)
100
+ return path.join(root, 'repos', `${key}.git`)
101
+ }
102
+
103
+ function assertSafeRelative(rel) {
104
+ if (typeof rel !== 'string' || rel === '' || path.isAbsolute(rel)) {
105
+ throw new Error(`unsafe restorable path: ${JSON.stringify(rel)}`)
106
+ }
107
+ const parts = rel.split(/[\\/]/)
108
+ if (parts.some((part) => part === '..' || part === '.')) {
109
+ throw new Error(`unsafe restorable path: ${JSON.stringify(rel)}`)
110
+ }
111
+ return rel
112
+ }
113
+
114
+ function posixJoin(cwd, rel) {
115
+ return path.join(cwd, ...rel.split('/'))
116
+ }
117
+
118
+ /** Whether `child` is inside `parent` (or equal to it). */
119
+ function insideDir(parent, child) {
120
+ const relative = path.relative(parent, child)
121
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
122
+ }
123
+
124
+ /** Count non-overlapping literal occurrences. */
125
+ function countOccurrences(haystack, needle) {
126
+ if (needle === '') return 0
127
+ let count = 0
128
+ let from = 0
129
+ while (true) {
130
+ const index = haystack.indexOf(needle, from)
131
+ if (index < 0) return count
132
+ count += 1
133
+ from = index + needle.length
134
+ }
135
+ }
136
+
137
+ /** Replace the first literal occurrence. */
138
+ function replaceFirst(haystack, needle, replacement) {
139
+ const index = haystack.indexOf(needle)
140
+ if (index < 0) return haystack
141
+ return haystack.slice(0, index) + replacement + haystack.slice(index + needle.length)
142
+ }
143
+
144
+ /** Split text into lines without the trailing newline artifact. */
145
+ function splitLines(text) {
146
+ const normalized = String(text ?? '').replace(/\r\n/g, '\n')
147
+ if (normalized === '') return []
148
+ const lines = normalized.split('\n')
149
+ if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop()
150
+ return lines
151
+ }
152
+
153
+ /** Line diff (LCS) with a bounded middle; large middles degrade to replace-all. */
154
+ function lcsOps(a, b) {
155
+ const n = a.length
156
+ const m = b.length
157
+ if (n === 0) return b.map((text) => ({ type: 'add', text }))
158
+ if (m === 0) return a.map((text) => ({ type: 'del', text }))
159
+ if (n > 1500 || m > 1500 || n * m > 4_000_000) {
160
+ return [...a.map((text) => ({ type: 'del', text })), ...b.map((text) => ({ type: 'add', text }))]
161
+ }
162
+ const width = m + 1
163
+ const table = new Int32Array((n + 1) * width)
164
+ for (let i = n - 1; i >= 0; i -= 1) {
165
+ for (let j = m - 1; j >= 0; j -= 1) {
166
+ table[i * width + j] = a[i] === b[j]
167
+ ? table[(i + 1) * width + j + 1] + 1
168
+ : Math.max(table[(i + 1) * width + j], table[i * width + j + 1])
169
+ }
170
+ }
171
+ const ops = []
172
+ let i = 0
173
+ let j = 0
174
+ while (i < n && j < m) {
175
+ if (a[i] === b[j]) {
176
+ ops.push({ type: 'context', text: a[i] })
177
+ i += 1
178
+ j += 1
179
+ } else if (table[(i + 1) * width + j] >= table[i * width + j + 1]) {
180
+ ops.push({ type: 'del', text: a[i] })
181
+ i += 1
182
+ } else {
183
+ ops.push({ type: 'add', text: b[j] })
184
+ j += 1
185
+ }
186
+ }
187
+ while (i < n) ops.push({ type: 'del', text: a[i++] })
188
+ while (j < m) ops.push({ type: 'add', text: b[j++] })
189
+ return ops
190
+ }
191
+
192
+ /** Unified-diff hunks with line numbers and three context lines. */
193
+ function computeDiff(beforeText, afterText) {
194
+ const before = splitLines(beforeText)
195
+ const after = splitLines(afterText)
196
+ let start = 0
197
+ while (start < before.length && start < after.length && before[start] === after[start]) start += 1
198
+ let endBefore = before.length - 1
199
+ let endAfter = after.length - 1
200
+ while (endBefore >= start && endAfter >= start && before[endBefore] === after[endAfter]) {
201
+ endBefore -= 1
202
+ endAfter -= 1
203
+ }
204
+ const ops = [
205
+ ...before.slice(0, start).map((text) => ({ type: 'context', text })),
206
+ ...lcsOps(before.slice(start, endBefore + 1), after.slice(start, endAfter + 1)),
207
+ ...before.slice(endBefore + 1).map((text) => ({ type: 'context', text })),
208
+ ]
209
+
210
+ let added = 0
211
+ let removed = 0
212
+ for (const op of ops) {
213
+ if (op.type === 'add') added += 1
214
+ else if (op.type === 'del') removed += 1
215
+ }
216
+ if (added === 0 && removed === 0) return { hunks: [], added: 0, removed: 0, truncated: false }
217
+
218
+ let truncated = false
219
+ let visible = ops
220
+ if (visible.length > 5000) {
221
+ visible = visible.slice(0, 5000)
222
+ truncated = true
223
+ }
224
+
225
+ let oldNo = 1
226
+ let newNo = 1
227
+ for (const op of ops) {
228
+ op.oldNo = op.type === 'add' ? null : oldNo
229
+ op.newNo = op.type === 'del' ? null : newNo
230
+ if (op.type !== 'add') oldNo += 1
231
+ if (op.type !== 'del') newNo += 1
232
+ }
233
+
234
+ const context = 3
235
+ const changes = []
236
+ for (let index = 0; index < visible.length; index += 1) {
237
+ if (visible[index].type !== 'context') changes.push(index)
238
+ }
239
+ if (changes.length === 0) return { hunks: [], added, removed, truncated }
240
+ const ranges = []
241
+ for (const index of changes) {
242
+ const from = Math.max(0, index - context)
243
+ const to = Math.min(visible.length - 1, index + context)
244
+ const last = ranges[ranges.length - 1]
245
+ if (last !== undefined && from <= last.to + 1) last.to = Math.max(last.to, to)
246
+ else ranges.push({ from, to })
247
+ }
248
+ const hunks = ranges.map(({ from, to }) => {
249
+ const lines = visible.slice(from, to + 1).map((op) => ({
250
+ type: op.type,
251
+ oldNo: op.oldNo,
252
+ newNo: op.newNo,
253
+ text: op.text,
254
+ }))
255
+ const oldStart = lines.find((line) => line.oldNo !== null)?.oldNo ?? 0
256
+ const newStart = lines.find((line) => line.newNo !== null)?.newNo ?? 0
257
+ const oldCount = lines.filter((line) => line.oldNo !== null).length
258
+ const newCount = lines.filter((line) => line.newNo !== null).length
259
+ return {
260
+ header: `@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`,
261
+ lines,
262
+ }
263
+ })
264
+ return { hunks, added, removed, truncated }
265
+ }
266
+
267
+ export function apply(ctx) {
268
+ const home = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh')
269
+ const root = path.join(home, 'coding-enhanced')
270
+ const legacyRoot = path.join(home, 'withdraw-round')
271
+ if (!existsSync(root) && existsSync(legacyRoot)) {
272
+ try {
273
+ renameSync(legacyRoot, root)
274
+ } catch {}
275
+ }
276
+ const statePath = path.join(root, 'state.json')
277
+ const settingsPath = path.join(root, 'settings.json')
278
+ mkdirSync(root, { recursive: true })
279
+
280
+ const featureFlags = { review: true, withdraw: true, autoReview: true, keepTurns: 10, nestedSnapshots: true, autoGc: true }
281
+ try {
282
+ const parsed = JSON.parse(readFileSync(settingsPath, 'utf8'))
283
+ if (typeof parsed.review === 'boolean') featureFlags.review = parsed.review
284
+ if (typeof parsed.withdraw === 'boolean') featureFlags.withdraw = parsed.withdraw
285
+ if (typeof parsed.autoReview === 'boolean') featureFlags.autoReview = parsed.autoReview
286
+ if (Number.isSafeInteger(parsed.keepTurns)) {
287
+ featureFlags.keepTurns = Math.min(50, Math.max(1, parsed.keepTurns))
288
+ }
289
+ if (typeof parsed.nestedSnapshots === 'boolean') featureFlags.nestedSnapshots = parsed.nestedSnapshots
290
+ if (typeof parsed.autoGc === 'boolean') featureFlags.autoGc = parsed.autoGc
291
+ } catch {}
292
+
293
+ const saveFeatureFlags = () => {
294
+ try {
295
+ mkdirSync(root, { recursive: true })
296
+ const tmp = `${settingsPath}.tmp`
297
+ writeFileSync(tmp, JSON.stringify(featureFlags))
298
+ renameSync(tmp, settingsPath)
299
+ } catch (error) {
300
+ ctx.logger?.warn?.(`coding-enhanced: cannot persist settings: ${String(error)}`)
301
+ }
302
+ }
303
+
304
+ ctx.logger?.info?.(`coding-enhanced: state at ${root}`)
305
+
306
+ // ---------------------------------------------------------------- state ---
307
+ let state = { sessions: {}, snapshots: {} }
308
+ try {
309
+ const parsed = JSON.parse(readFileSync(statePath, 'utf8'))
310
+ if (parsed && typeof parsed === 'object') {
311
+ if (parsed.sessions) state.sessions = parsed.sessions
312
+ if (parsed.snapshots && typeof parsed.snapshots === 'object') state.snapshots = parsed.snapshots
313
+ }
314
+ } catch {}
315
+
316
+ const saveState = () => {
317
+ try {
318
+ const sessions = Object.entries(state.sessions)
319
+ if (sessions.length > 200) {
320
+ sessions.sort((a, b) => (a[1].updatedAt ?? 0) - (b[1].updatedAt ?? 0))
321
+ for (const [id] of sessions.slice(0, sessions.length - 200)) {
322
+ delete state.sessions[id]
323
+ delete state.snapshots[id]
324
+ }
325
+ }
326
+ mkdirSync(root, { recursive: true })
327
+ const tmp = `${statePath}.tmp`
328
+ writeFileSync(tmp, JSON.stringify(state))
329
+ renameSync(tmp, statePath)
330
+ } catch (error) {
331
+ ctx.logger?.warn?.(`coding-enhanced: cannot persist state: ${String(error)}`)
332
+ }
333
+ }
334
+
335
+ const withdrawnOf = (sessionId) => state.sessions[sessionId]?.withdrawn ?? {}
336
+
337
+ // ------------------------------------------------------------ snapshots ---
338
+ /** sessionId -> Map<turn, { sessionId, turn, tree, cwd, gitDir, endSeq, createdAt }> */
339
+ const snapshots = new Map()
340
+
341
+ const snapshotRef = (sessionId, turn) =>
342
+ `refs/coding-enhanced/${createHash('sha256').update(sessionId).digest('hex').slice(0, 16)}/${turn}`
343
+
344
+ const writeSnapshotRefs = async (snapshot) => {
345
+ const ref = snapshotRef(snapshot.sessionId, snapshot.turn)
346
+ try {
347
+ await runGit(['update-ref', ref, snapshot.tree], { gitDir: snapshot.gitDir })
348
+ } catch (error) {
349
+ ctx.logger?.warn?.(`coding-enhanced: cannot create snapshot ref: ${String(error)}`)
350
+ }
351
+ for (const nested of Array.isArray(snapshot.nested) ? snapshot.nested : []) {
352
+ try {
353
+ await runGit(['update-ref', ref, nested.tree], { gitDir: nested.gitDir })
354
+ } catch (error) {
355
+ ctx.logger?.warn?.(`coding-enhanced: cannot create nested snapshot ref: ${String(error)}`)
356
+ }
357
+ }
358
+ }
359
+
360
+ const deleteSnapshotRefs = async (snapshot) => {
361
+ const ref = snapshotRef(snapshot.sessionId, snapshot.turn)
362
+ try {
363
+ await runGit(['update-ref', '-d', ref], { gitDir: snapshot.gitDir })
364
+ } catch {}
365
+ for (const nested of Array.isArray(snapshot.nested) ? snapshot.nested : []) {
366
+ try {
367
+ await runGit(['update-ref', '-d', ref], { gitDir: nested.gitDir })
368
+ } catch {}
369
+ }
370
+ }
371
+
372
+ for (const [sessionId, turns] of Object.entries(state.snapshots)) {
373
+ if (turns === null || typeof turns !== 'object') continue
374
+ const map = new Map()
375
+ for (const [turnRaw, value] of Object.entries(turns)) {
376
+ const turn = Number(turnRaw)
377
+ if (!Number.isSafeInteger(turn) || value === null || typeof value !== 'object') continue
378
+ if (typeof value.tree !== 'string' || typeof value.cwd !== 'string' || typeof value.gitDir !== 'string') continue
379
+ const snapshot = {
380
+ sessionId,
381
+ turn,
382
+ tree: value.tree,
383
+ cwd: value.cwd,
384
+ gitDir: value.gitDir,
385
+ endSeq: Number.isSafeInteger(value.endSeq) ? value.endSeq : undefined,
386
+ createdAt: Number.isSafeInteger(value.createdAt) ? value.createdAt : Date.now(),
387
+ nested: Array.isArray(value.nested)
388
+ ? value.nested.filter((nested) =>
389
+ nested !== null && typeof nested === 'object'
390
+ && typeof nested.cwd === 'string' && typeof nested.tree === 'string' && typeof nested.gitDir === 'string')
391
+ .map((nested) => ({ cwd: nested.cwd, tree: nested.tree, gitDir: nested.gitDir }))
392
+ : [],
393
+ }
394
+ map.set(turn, snapshot)
395
+ void writeSnapshotRefs(snapshot)
396
+ }
397
+ if (map.size > 0) snapshots.set(sessionId, map)
398
+ }
399
+
400
+ const latestSnapshot = (sessionId) => {
401
+ const map = snapshots.get(sessionId)
402
+ if (map === undefined || map.size === 0) return undefined
403
+ let latest
404
+ for (const snapshot of map.values()) {
405
+ if (latest === undefined || snapshot.turn > latest.turn) latest = snapshot
406
+ }
407
+ return latest
408
+ }
409
+
410
+ const snapshotOf = (sessionId, turn) => snapshots.get(sessionId)?.get(turn)
411
+
412
+ const persistSnapshots = (sessionId) => {
413
+ const map = snapshots.get(sessionId)
414
+ if (map === undefined || map.size === 0) {
415
+ delete state.snapshots[sessionId]
416
+ saveState()
417
+ return
418
+ }
419
+ const record = {}
420
+ for (const [turn, snapshot] of map.entries()) {
421
+ record[String(turn)] = {
422
+ tree: snapshot.tree,
423
+ cwd: snapshot.cwd,
424
+ gitDir: snapshot.gitDir,
425
+ endSeq: Number.isSafeInteger(snapshot.endSeq) ? snapshot.endSeq : null,
426
+ createdAt: snapshot.createdAt ?? Date.now(),
427
+ nested: Array.isArray(snapshot.nested) ? snapshot.nested : [],
428
+ }
429
+ }
430
+ state.snapshots[sessionId] = record
431
+ saveState()
432
+ }
433
+
434
+ const setSnapshot = (snapshot) => {
435
+ let map = snapshots.get(snapshot.sessionId)
436
+ if (map === undefined) {
437
+ map = new Map()
438
+ snapshots.set(snapshot.sessionId, map)
439
+ }
440
+ map.set(snapshot.turn, snapshot)
441
+ persistSnapshots(snapshot.sessionId)
442
+ }
443
+ /** gitDir -> worktree for repos whose snapshots were dropped */
444
+ const dirtyRepos = new Map()
445
+ const gcTimestamps = new Map()
446
+
447
+ const markSnapshotDirty = (snapshot) => {
448
+ if (snapshot === undefined || snapshot === null) return
449
+ if (typeof snapshot.gitDir === 'string' && typeof snapshot.cwd === 'string') {
450
+ dirtyRepos.set(snapshot.gitDir, snapshot.cwd)
451
+ }
452
+ for (const nested of Array.isArray(snapshot.nested) ? snapshot.nested : []) {
453
+ if (typeof nested.gitDir === 'string' && typeof nested.cwd === 'string') {
454
+ dirtyRepos.set(nested.gitDir, nested.cwd)
455
+ }
456
+ }
457
+ }
458
+
459
+ const gcRepo = async (gitDir, cwd, force = false) => {
460
+ const now = Date.now()
461
+ if (!force && (gcTimestamps.get(gitDir) ?? 0) > now - 10 * 60 * 1000) return false
462
+ gcTimestamps.set(gitDir, now)
463
+ try {
464
+ await serialized(`snapshot:${cwd}`, () =>
465
+ runGit(['gc', '--prune=now', '--quiet'], { gitDir }))
466
+ return true
467
+ } catch (error) {
468
+ ctx.logger?.warn?.(`coding-enhanced: git gc failed for ${gitDir}: ${String(error)}`)
469
+ return false
470
+ }
471
+ }
472
+
473
+ const flushGc = async (force = false) => {
474
+ const entries = [...dirtyRepos.entries()]
475
+ dirtyRepos.clear()
476
+ let count = 0
477
+ for (const [gitDir, cwd] of entries) {
478
+ if (await gcRepo(gitDir, cwd, force)) count += 1
479
+ }
480
+ return count
481
+ }
482
+
483
+ const cleanupSnapshots = async () => {
484
+ let pruned = 0
485
+ for (const sessionId of [...snapshots.keys()]) {
486
+ const map = snapshots.get(sessionId)
487
+ if (map === undefined) continue
488
+ const turns = [...map.keys()].sort((left, right) => left - right)
489
+ while (turns.length > featureFlags.keepTurns) {
490
+ const turn = turns.shift()
491
+ const snapshot = map.get(turn)
492
+ if (snapshot !== undefined) {
493
+ await deleteSnapshotRefs(snapshot)
494
+ markSnapshotDirty(snapshot)
495
+ map.delete(turn)
496
+ pruned += 1
497
+ }
498
+ }
499
+ if (map.size === 0) snapshots.delete(sessionId)
500
+ persistSnapshots(sessionId)
501
+ }
502
+ try {
503
+ const entries = await fs.readdir(path.join(root, 'repos'), { withFileTypes: true })
504
+ for (const entry of entries) {
505
+ if (!entry.isDirectory() || !entry.name.endsWith('.git')) continue
506
+ const gitDir = path.join(root, 'repos', entry.name)
507
+ try {
508
+ const cwd = (await runGit(['config', 'core.worktree'], { gitDir })).trim()
509
+ if (cwd !== '') dirtyRepos.set(gitDir, cwd)
510
+ } catch {}
511
+ }
512
+ } catch {}
513
+ const repos = await flushGc(true)
514
+ return { pruned, repos }
515
+ }
516
+
517
+ const pruneSnapshots = (sessionId) => {
518
+ const map = snapshots.get(sessionId)
519
+ if (map === undefined) return
520
+ const turns = [...map.keys()].sort((left, right) => left - right)
521
+ if (turns.length <= featureFlags.keepTurns) return
522
+ let removed = 0
523
+ while (turns.length > featureFlags.keepTurns) {
524
+ const snapshot = map.get(turns.shift())
525
+ if (snapshot !== undefined) {
526
+ void deleteSnapshotRefs(snapshot)
527
+ markSnapshotDirty(snapshot)
528
+ map.delete(snapshot.turn)
529
+ removed += 1
530
+ }
531
+ }
532
+ if (map.size === 0) snapshots.delete(sessionId)
533
+ persistSnapshots(sessionId)
534
+ if (removed > 0 && featureFlags.autoGc === true) void flushGc()
535
+ }
536
+
537
+ const pruneAllSnapshots = () => {
538
+ for (const sessionId of [...snapshots.keys()]) pruneSnapshots(sessionId)
539
+ }
540
+ /** sessionId -> turn number while a turn is running */
541
+ const activeTurns = new Map()
542
+ /** sessionId -> Promise of the in-flight snapshot */
543
+ const pendingSnapshots = new Map()
544
+ /** gitDir -> serialized git queue so concurrent sessions never race the index */
545
+ const gitQueues = new Map()
546
+
547
+ const serialized = (key, work) => {
548
+ const previous = gitQueues.get(key) ?? Promise.resolve()
549
+ const next = previous.catch(() => {}).then(work)
550
+ gitQueues.set(key, next.catch(() => {}))
551
+ return next
552
+ }
553
+
554
+ const ensureRepo = async (cwd) => {
555
+ const gitDir = shadowRepoPath(root, cwd)
556
+ if (existsSync(path.join(gitDir, 'HEAD'))) return gitDir
557
+ mkdirSync(path.dirname(gitDir), { recursive: true })
558
+ await runGit(['init', '--quiet', '--bare', gitDir], { gitDir })
559
+ await runGit(['config', 'core.bare', 'false'], { gitDir })
560
+ await runGit(['config', 'core.worktree', cwd], { gitDir })
561
+ await runGit(['config', 'core.autocrlf', 'false'], { gitDir })
562
+ await runGit(['config', 'core.quotepath', 'false'], { gitDir })
563
+ mkdirSync(path.join(gitDir, 'info'), { recursive: true })
564
+ writeFileSync(path.join(gitDir, 'info', 'exclude'), `${DEFAULT_EXCLUDES.join('\n')}\n`)
565
+ return gitDir
566
+ }
567
+
568
+ const addAll = async (gitDir, cwd) => {
569
+ try {
570
+ await runGit(['add', '-A', '--ignore-errors'], { gitDir, workTree: cwd })
571
+ return
572
+ } catch (error) {
573
+ const message = String(error?.message ?? error)
574
+ const offenders = [...message.matchAll(/'([^']+)'/g)]
575
+ .map((match) => match[1].replace(/\/+$/, ''))
576
+ .filter((value) => value !== '' && !value.startsWith('/') && !value.split('/').includes('..'))
577
+ if (offenders.length === 0) throw error
578
+ const excludePath = path.join(gitDir, 'info', 'exclude')
579
+ let current = ''
580
+ try {
581
+ current = readFileSync(excludePath, 'utf8')
582
+ } catch {}
583
+ const lines = new Set(current.split('\n').filter((line) => line !== ''))
584
+ for (const offender of offenders) {
585
+ lines.add(`/${offender}/`)
586
+ lines.add(`/${offender}`)
587
+ }
588
+ mkdirSync(path.dirname(excludePath), { recursive: true })
589
+ writeFileSync(excludePath, `${[...lines].join('\n')}\n`)
590
+ ctx.logger?.warn?.(`coding-enhanced: excluded nested repositories from the snapshot: ${offenders.join(', ')}`)
591
+ await runGit(['add', '-A', '--ignore-errors'], { gitDir, workTree: cwd })
592
+ }
593
+ }
594
+
595
+ const findNestedRepos = async (cwd) => {
596
+ const found = []
597
+ const walk = async (dir, depth) => {
598
+ if (depth > 12) return
599
+ let entries
600
+ try {
601
+ entries = await fs.readdir(dir, { withFileTypes: true })
602
+ } catch {
603
+ return
604
+ }
605
+ for (const entry of entries) {
606
+ if (!entry.isDirectory()) continue
607
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === '.dsh-coding-enhanced') continue
608
+ const absolute = path.join(dir, entry.name)
609
+ if (existsSync(path.join(absolute, '.git'))) {
610
+ found.push(absolute)
611
+ continue
612
+ }
613
+ await walk(absolute, depth + 1)
614
+ }
615
+ }
616
+ await walk(cwd, 0)
617
+ return found
618
+ }
619
+
620
+ const captureSnapshot = (sessionId, cwd, turn) => {
621
+ const work = (async () => {
622
+ const gitDir = await ensureRepo(cwd)
623
+ // `--ignore-errors` keeps unreadable files from failing the whole turn.
624
+ try {
625
+ await addAll(gitDir, cwd)
626
+ } catch (error) {
627
+ ctx.logger?.warn?.(`coding-enhanced: snapshot add failed for ${cwd}: ${String(error)}`)
628
+ return
629
+ }
630
+ const tree = (await runGit(['write-tree'], { gitDir, workTree: cwd })).trim()
631
+ if (tree === '') return
632
+ const nested = []
633
+ if (featureFlags.nestedSnapshots === true) {
634
+ let candidates = []
635
+ try {
636
+ candidates = await findNestedRepos(cwd)
637
+ } catch (error) {
638
+ ctx.logger?.warn?.(`coding-enhanced: cannot scan nested repositories in ${cwd}: ${String(error)}`)
639
+ }
640
+ for (const nestedCwd of candidates) {
641
+ try {
642
+ const nestedGitDir = await ensureRepo(nestedCwd)
643
+ await serialized(`snapshot:${nestedCwd}`, async () => {
644
+ await addAll(nestedGitDir, nestedCwd)
645
+ const nestedTree = (await runGit(['write-tree'], { gitDir: nestedGitDir, workTree: nestedCwd })).trim()
646
+ if (nestedTree !== '') nested.push({ cwd: nestedCwd, tree: nestedTree, gitDir: nestedGitDir })
647
+ })
648
+ } catch (error) {
649
+ ctx.logger?.warn?.(`coding-enhanced: cannot snapshot nested repository ${nestedCwd}: ${String(error)}`)
650
+ }
651
+ }
652
+ }
653
+ const snapshot = {
654
+ sessionId,
655
+ turn,
656
+ tree,
657
+ cwd,
658
+ gitDir,
659
+ endSeq: undefined,
660
+ createdAt: Date.now(),
661
+ nested,
662
+ }
663
+ await writeSnapshotRefs(snapshot)
664
+ setSnapshot(snapshot)
665
+ pruneSnapshots(sessionId)
666
+ })()
667
+ return serialized(`snapshot:${cwd}`, () => work)
668
+ }
669
+
670
+
671
+ // ------------------------------------------------------- review gate ---
672
+ const REVIEW_TOOLS = new Set(['write', 'edit', 'apply_patch'])
673
+ const MAX_REVIEW_FILE_BYTES = 2 * 1024 * 1024
674
+ const MAX_EDITABLE_BYTES = 200 * 1024
675
+ /** sessionId -> review { id, sessionId, entries, virtual, submitted, finished, canceled, waiters } */
676
+ const reviews = new Map()
677
+ let reviewVersion = 0
678
+
679
+ const bumpReview = () => {
680
+ reviewVersion += 1
681
+ }
682
+
683
+ const ensureReview = (sessionId) => {
684
+ let review = reviews.get(sessionId)
685
+ if (review === undefined || review.finished) {
686
+ review = {
687
+ id: `review-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
688
+ sessionId,
689
+ createdAt: Date.now(),
690
+ entries: new Map(),
691
+ virtual: new Map(),
692
+ submitted: false,
693
+ finished: false,
694
+ canceled: false,
695
+ waiters: [],
696
+ }
697
+ reviews.set(sessionId, review)
698
+ }
699
+ return review
700
+ }
701
+
702
+ const cleanupReview = (sessionId) => {
703
+ const review = reviews.get(sessionId)
704
+ if (review === undefined) return
705
+ for (const waiter of review.waiters) waiter()
706
+ review.waiters = []
707
+ review.entries.clear()
708
+ reviews.delete(sessionId)
709
+ bumpReview()
710
+ }
711
+
712
+ const stageFileChange = async (session, call) => {
713
+ if (call === null || typeof call !== 'object' || typeof call.id !== 'string' || call.id === '') {
714
+ throw new Error('Invalid review change.')
715
+ }
716
+ let args
717
+ try {
718
+ args = typeof call.arguments === 'string' ? JSON.parse(call.arguments) : call.arguments
719
+ } catch {
720
+ throw new Error('Invalid review arguments.')
721
+ }
722
+ if (args === null || typeof args !== 'object') throw new Error('Invalid review arguments.')
723
+ const filePath = typeof args.file_path === 'string' ? args.file_path : ''
724
+ if (filePath === '') throw new Error('file_path is required.')
725
+
726
+ const cwd = typeof session.header?.cwd === 'string' && session.header.cwd !== '' ? session.header.cwd : process.cwd()
727
+ const absolute = path.isAbsolute(filePath) ? path.normalize(filePath) : path.resolve(cwd, filePath)
728
+ const display = insideDir(cwd, absolute) ? path.relative(cwd, absolute) : absolute
729
+
730
+ const review = ensureReview(session.id)
731
+ let entry = review.entries.get(absolute)
732
+ if (entry === undefined) {
733
+ let before = ''
734
+ let exists = false
735
+ let warning
736
+ let tooLarge = false
737
+ try {
738
+ const info = await fs.stat(absolute)
739
+ if (info.isFile()) {
740
+ exists = true
741
+ if (info.size > MAX_REVIEW_FILE_BYTES) {
742
+ tooLarge = true
743
+ warning = 'This file is too large to preview; its change is reviewed without a diff.'
744
+ } else {
745
+ before = await fs.readFile(absolute, 'utf8')
746
+ }
747
+ }
748
+ } catch (error) {
749
+ if (error.code !== 'ENOENT') warning = `Cannot read the current file: ${String(error)}`
750
+ }
751
+ entry = {
752
+ id: absolute,
753
+ callId: call.id,
754
+ tool: call.name,
755
+ path: absolute,
756
+ display,
757
+ isNew: !exists,
758
+ tooLarge,
759
+ before,
760
+ after: before,
761
+ warning,
762
+ added: 0,
763
+ removed: 0,
764
+ truncated: false,
765
+ hunks: [],
766
+ editable: false,
767
+ canApply: true,
768
+ updatedAt: Date.now(),
769
+ decision: null,
770
+ callIds: [call.id],
771
+ }
772
+ review.entries.set(absolute, entry)
773
+ } else if (Array.isArray(entry.callIds)) {
774
+ entry.callIds.push(call.id)
775
+ }
776
+
777
+ if (call.name === 'edit') {
778
+ if (entry.isNew) {
779
+ throw new Error(`Cannot queue the edit to "${display}": the file does not exist. Use review_write with the full content.`)
780
+ }
781
+ if (entry.tooLarge === true) {
782
+ throw new Error(`Cannot queue the edit to "${display}": the file is too large to edit through the review gate. Use review_write with the full content.`)
783
+ }
784
+ }
785
+
786
+ if (call.name === 'write') {
787
+ entry.after = typeof args.content === 'string' ? args.content : ''
788
+ } else if (call.name === 'edit') {
789
+ const oldString = typeof args.old_string === 'string' ? args.old_string : ''
790
+ const newString = typeof args.new_string === 'string' ? args.new_string : ''
791
+ if (oldString === '') throw new Error(`Cannot queue the edit to "${display}": old_string is empty.`)
792
+ const matches = countOccurrences(entry.after, oldString)
793
+ if (matches === 0) {
794
+ throw new Error(`Cannot queue the edit to "${display}": old_string was not found in the current queued content. Read the file and try again.`)
795
+ }
796
+ if (matches > 1 && args.replace_all !== true) {
797
+ throw new Error(`Cannot queue the edit to "${display}": old_string matches ${matches} places; set replace_all or use a more specific old_string.`)
798
+ }
799
+ entry.after = args.replace_all === true
800
+ ? entry.after.split(oldString).join(newString)
801
+ : replaceFirst(entry.after, oldString, newString)
802
+ } else {
803
+ throw new Error(`Unsupported review change: ${String(call.name)}`)
804
+ }
805
+
806
+ entry.tool = call.name
807
+ entry.updatedAt = Date.now()
808
+ entry.decision = null
809
+ const binary = entry.before.includes('\u0000') || entry.after.includes('\u0000')
810
+ if (binary || entry.after.length > MAX_REVIEW_FILE_BYTES) {
811
+ entry.warning = entry.warning ?? (binary
812
+ ? 'Binary file: preview unavailable.'
813
+ : 'The resulting file is too large to preview.')
814
+ entry.added = 0
815
+ entry.removed = 0
816
+ entry.truncated = false
817
+ entry.hunks = []
818
+ entry.editable = false
819
+ } else {
820
+ const diff = computeDiff(entry.before, entry.after)
821
+ entry.added = diff.added
822
+ entry.removed = diff.removed
823
+ entry.truncated = diff.truncated
824
+ entry.hunks = diff.hunks
825
+ entry.editable = entry.before.length <= MAX_EDITABLE_BYTES && entry.after.length <= MAX_EDITABLE_BYTES
826
+ }
827
+ bumpReview()
828
+ return { review, entry }
829
+ }
830
+
831
+ const reviewResults = (review) => {
832
+ if (review.canceled === true) return { status: 'canceled', files: [] }
833
+ if (review.finished !== true) return { status: 'open', files: [] }
834
+ const files = []
835
+ for (const entry of review.entries.values()) {
836
+ if (entry.applyError !== undefined) {
837
+ files.push({ path: entry.display, outcome: 'failed', error: entry.applyError })
838
+ } else if (entry.outcome === 'rejected') {
839
+ files.push({
840
+ path: entry.display,
841
+ outcome: 'rejected',
842
+ comment: entry.decision?.comment ?? '',
843
+ })
844
+ } else if (entry.outcome === 'edited') {
845
+ files.push({ path: entry.display, outcome: 'edited' })
846
+ } else {
847
+ files.push({ path: entry.display, outcome: 'applied' })
848
+ }
849
+ }
850
+ return { status: 'finished', files }
851
+ }
852
+
853
+ const applyReview = async (review) => {
854
+ for (const entry of review.entries.values()) {
855
+ if (entry.outcome === 'rejected') continue
856
+ const content = typeof entry.editedAfter === 'string' ? entry.editedAfter : entry.after
857
+ try {
858
+ await fs.mkdir(path.dirname(entry.path), { recursive: true })
859
+ await fs.writeFile(entry.path, content, 'utf8')
860
+ entry.applied = true
861
+ } catch (error) {
862
+ entry.applyError = String(error)
863
+ }
864
+ }
865
+ }
866
+
867
+ const waitForReviewFinish = (review, signal) => {
868
+ if (review.finished === true) return Promise.resolve()
869
+ return new Promise((resolve) => {
870
+ let settled = false
871
+ const done = () => {
872
+ if (settled) return
873
+ settled = true
874
+ signal?.removeEventListener('abort', done)
875
+ resolve()
876
+ }
877
+ review.waiters.push(done)
878
+ signal?.addEventListener('abort', done, { once: true })
879
+ })
880
+ }
881
+
882
+ const serializeReview = (review) => ({
883
+ id: review.id,
884
+ sessionId: review.sessionId,
885
+ createdAt: review.createdAt,
886
+ submitted: review.submitted === true,
887
+ applying: review.applying === true,
888
+ finished: review.finished === true,
889
+ canceled: review.canceled === true,
890
+ entries: [...review.entries.values()].map((entry) => ({
891
+ id: entry.id,
892
+ callId: entry.callId,
893
+ updatedAt: entry.updatedAt,
894
+ tool: entry.tool,
895
+ path: entry.path,
896
+ display: entry.display,
897
+ isNew: entry.isNew,
898
+ warning: entry.warning ?? null,
899
+ added: entry.added,
900
+ removed: entry.removed,
901
+ truncated: entry.truncated,
902
+ hunks: entry.hunks,
903
+ editable: entry.editable === true,
904
+ canApply: entry.canApply !== false,
905
+ beforeText: entry.editable === true ? entry.before : null,
906
+ afterText: entry.editable === true ? entry.after : null,
907
+ decision: entry.decision,
908
+ })),
909
+ })
910
+
911
+ const decideReview = (id, decisions) => {
912
+ const review = [...reviews.values()].find((candidate) => candidate.id === id)
913
+ if (review === undefined) return fail('review-not-found', 'This review is no longer open')
914
+ if (review.finished) return fail('review-finished', 'This review was already finished')
915
+ if (review.submitted !== true) return fail('not-submitted', 'The agent has not submitted this review yet')
916
+ const byEntry = new Map()
917
+ for (const decision of Array.isArray(decisions) ? decisions : []) {
918
+ if (decision !== null && typeof decision === 'object' && typeof decision.entryId === 'string') {
919
+ byEntry.set(decision.entryId, decision)
920
+ }
921
+ }
922
+ const entries = [...review.entries.values()]
923
+ const missing = []
924
+ const tooLarge = []
925
+ const normalized = new Map()
926
+ for (const entry of entries) {
927
+ const decision = byEntry.get(entry.id)
928
+ if (decision !== undefined && decision.outcome === 'edited') {
929
+ const text = decision.editedAfter
930
+ if (entry.editable !== true || typeof text !== 'string' || text === entry.after) {
931
+ missing.push(entry.display)
932
+ continue
933
+ }
934
+ if (text.length > MAX_EDITABLE_BYTES * 2) {
935
+ tooLarge.push(entry.display)
936
+ continue
937
+ }
938
+ normalized.set(entry.id, { outcome: 'edited', editedAfter: text, comment: '' })
939
+ continue
940
+ }
941
+ if (decision === undefined || typeof decision.approved !== 'boolean') {
942
+ missing.push(entry.display)
943
+ continue
944
+ }
945
+ normalized.set(entry.id, {
946
+ outcome: decision.approved === true ? 'approved' : 'rejected',
947
+ comment: typeof decision.comment === 'string' ? decision.comment.slice(0, 4000) : '',
948
+ })
949
+ }
950
+ if (missing.length > 0) return fail('incomplete', `No decision for: ${missing.join(', ')}`)
951
+ if (tooLarge.length > 0) return fail('edit-too-large', `The edited content is too large for: ${tooLarge.join(', ')}`)
952
+
953
+ for (const entry of entries) {
954
+ const decision = normalized.get(entry.id)
955
+ entry.outcome = decision.outcome
956
+ entry.decision = {
957
+ outcome: decision.outcome,
958
+ approved: decision.outcome === 'approved',
959
+ edited: decision.outcome === 'edited',
960
+ comment: decision.comment,
961
+ }
962
+ if (decision.outcome === 'edited') entry.editedAfter = decision.editedAfter
963
+ }
964
+ review.applying = true
965
+ bumpReview()
966
+ void applyReview(review).then(() => {
967
+ review.applying = false
968
+ review.finished = true
969
+ for (const waiter of review.waiters) waiter()
970
+ review.waiters = []
971
+ bumpReview()
972
+ }).catch((error) => {
973
+ review.applying = false
974
+ review.finished = true
975
+ review.applyError = String(error)
976
+ for (const waiter of review.waiters) waiter()
977
+ review.waiters = []
978
+ bumpReview()
979
+ })
980
+ return ok({ reviewId: review.id, applying: true })
981
+ }
982
+
983
+ const parsePatchHeaderPath = (line) => {
984
+ let rest = line.slice(4).trim()
985
+ if (rest.startsWith('"')) {
986
+ let out = ''
987
+ let index = 1
988
+ for (; index < rest.length; index += 1) {
989
+ const char = rest[index]
990
+ if (char === '\\' && index + 1 < rest.length) {
991
+ out += rest[index + 1]
992
+ index += 1
993
+ continue
994
+ }
995
+ if (char === '"') break
996
+ out += char
997
+ }
998
+ return out
999
+ }
1000
+ const tab = rest.indexOf('\t')
1001
+ if (tab >= 0) rest = rest.slice(0, tab)
1002
+ return rest.trim()
1003
+ }
1004
+
1005
+ const stagePatch = async (session, exec, patch) => {
1006
+ if (typeof patch !== 'string' || patch.trim() === '') throw new Error('patch is required.')
1007
+ if (patch.length > MAX_REVIEW_FILE_BYTES) throw new Error('The patch is too large for the review gate.')
1008
+ const cwd = typeof session.header?.cwd === 'string' && session.header.cwd !== '' ? session.header.cwd : process.cwd()
1009
+ const lines = patch.split(/\r?\n/)
1010
+ const pairs = []
1011
+ let pendingOld
1012
+ for (const line of lines) {
1013
+ if (line.startsWith('GIT binary patch') || line.startsWith('Binary files ')) {
1014
+ throw new Error('Binary patches are not supported; use review_write.')
1015
+ }
1016
+ if (line.startsWith('rename from ') || line.startsWith('rename to ') || line.startsWith('copy from ') || line.startsWith('copy to ')) {
1017
+ throw new Error('Renames and copies are not supported; use review_write for the new path.')
1018
+ }
1019
+ if (line.startsWith('--- ')) {
1020
+ pendingOld = parsePatchHeaderPath(line)
1021
+ } else if (line.startsWith('+++ ')) {
1022
+ if (pendingOld === undefined) throw new Error('Malformed patch: "+++" without a preceding "---".')
1023
+ pairs.push({ oldPath: pendingOld, newPath: parsePatchHeaderPath(line) })
1024
+ pendingOld = undefined
1025
+ }
1026
+ }
1027
+ if (pairs.length === 0) throw new Error('The patch has no file headers (---/+++).')
1028
+
1029
+ const prefixed = pairs.every((pair) =>
1030
+ (pair.oldPath === '/dev/null' || /^[ab]\//.test(pair.oldPath))
1031
+ && (pair.newPath === '/dev/null' || /^[ab]\//.test(pair.newPath)))
1032
+ const anyPrefixed = pairs.some((pair) =>
1033
+ (pair.oldPath !== '/dev/null' && /^[ab]\//.test(pair.oldPath))
1034
+ || (pair.newPath !== '/dev/null' && /^[ab]\//.test(pair.newPath)))
1035
+ if (anyPrefixed && !prefixed) {
1036
+ throw new Error('Use a/ and b/ prefixes on every path or omit them everywhere.')
1037
+ }
1038
+ const strip = prefixed ? 1 : 0
1039
+ const normalize = (raw) => {
1040
+ if (raw === '/dev/null') return null
1041
+ let value = raw
1042
+ if (strip === 1) value = value.replace(/^[ab]\//, '')
1043
+ if (value === '' || value.startsWith('/')) throw new Error(`Unsupported patch path: ${raw}`)
1044
+ const absolute = path.resolve(cwd, value)
1045
+ if (!insideDir(cwd, absolute)) throw new Error(`Patch path escapes the working directory: ${raw}`)
1046
+ return { absolute, relative: path.relative(cwd, absolute).split(path.sep).join('/') }
1047
+ }
1048
+
1049
+ const targets = new Map()
1050
+ for (const pair of pairs) {
1051
+ const oldTarget = normalize(pair.oldPath)
1052
+ const newTarget = normalize(pair.newPath)
1053
+ if (newTarget === null) {
1054
+ throw new Error('Deleting files is not supported in review_patch; reject the change or use review_write for the new content.')
1055
+ }
1056
+ if (oldTarget !== null && oldTarget.relative !== newTarget.relative) {
1057
+ throw new Error('Renaming files is not supported in review_patch; use review_write for the new path.')
1058
+ }
1059
+ targets.set(newTarget.relative, { ...newTarget, newFile: oldTarget === null })
1060
+ }
1061
+
1062
+ const review = ensureReview(session.id)
1063
+ const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-ce-patch-'))
1064
+ try {
1065
+ for (const target of targets.values()) {
1066
+ if (target.newFile) continue
1067
+ const filePath = path.join(tmp, target.relative)
1068
+ await fs.mkdir(path.dirname(filePath), { recursive: true })
1069
+ const existing = review.entries.get(target.absolute)
1070
+ let content
1071
+ if (existing !== undefined) {
1072
+ content = existing.after
1073
+ } else {
1074
+ try {
1075
+ content = await fs.readFile(target.absolute, 'utf8')
1076
+ } catch (error) {
1077
+ if (error.code === 'ENOENT') throw new Error(`The patch targets a file that does not exist: ${target.relative}`)
1078
+ throw error
1079
+ }
1080
+ }
1081
+ await fs.writeFile(filePath, content, 'utf8')
1082
+ }
1083
+ const diffStarts = []
1084
+ for (let index = 0; index < lines.length; index += 1) {
1085
+ if (lines[index].startsWith('diff --git ')) diffStarts.push(index)
1086
+ }
1087
+ let sections
1088
+ if (diffStarts.length > 0) {
1089
+ sections = diffStarts.map((start, index) => lines.slice(start, diffStarts[index + 1] ?? lines.length).join('\n').replace(/\n+$/, '') + '\n')
1090
+ } else {
1091
+ const starts = []
1092
+ for (let index = 0; index < lines.length - 1; index += 1) {
1093
+ if (lines[index].startsWith('--- ') && lines[index + 1].startsWith('+++ ')) starts.push(index)
1094
+ }
1095
+ sections = starts.map((start, index) => lines.slice(start, starts[index + 1] ?? lines.length).join('\n').replace(/\n+$/, '') + '\n')
1096
+ }
1097
+ if (sections.length === 0) throw new Error('The patch has no hunks to apply.')
1098
+ const gitDir = path.join(tmp, '.git')
1099
+ await runGit(['init', '-q'], { gitDir, workTree: tmp })
1100
+ for (let index = 0; index < sections.length; index += 1) {
1101
+ const sectionPath = path.join(tmp, `.dsh-review-${index}.patch`)
1102
+ await fs.writeFile(sectionPath, sections[index], 'utf8')
1103
+ await runGit(['apply', `-p${strip}`, '--recount', '--whitespace=nowarn', sectionPath], { gitDir, workTree: tmp })
1104
+ }
1105
+ const staged = []
1106
+ for (const target of targets.values()) {
1107
+ staged.push({
1108
+ target,
1109
+ content: await fs.readFile(path.join(tmp, target.relative), 'utf8'),
1110
+ })
1111
+ }
1112
+ const files = []
1113
+ for (const { target, content } of staged) {
1114
+ const queued = await stageFileChange(session, {
1115
+ id: exec.callId,
1116
+ name: 'write',
1117
+ arguments: { file_path: target.absolute, content },
1118
+ })
1119
+ files.push(queued.entry.display)
1120
+ }
1121
+ return { files, review }
1122
+ } finally {
1123
+ await fs.rm(tmp, { recursive: true, force: true }).catch(() => {})
1124
+ }
1125
+ }
1126
+
1127
+ const registerReviewTools = () => {
1128
+ ctx.tools.register(defineTool({
1129
+ name: 'review_write',
1130
+ description: 'Queue a new file or a full-file rewrite for the user\'s review. This does not write the file: the change is held in the Code review tab until the user finishes. Use review_patch for edits to existing files. After queueing every change for this turn, call review_wait.',
1131
+ parameters: {
1132
+ file_path: { type: 'string', required: true, description: 'Path to write, resolved like the write tool.' },
1133
+ content: { type: 'string', required: true, description: 'Full UTF-8 text content to write.' },
1134
+ },
1135
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
1136
+ async execute(args, exec) {
1137
+ const session = exec.agent?.session
1138
+ if (session === undefined) return 'No active session.'
1139
+ if (featureFlags.review !== true) return 'The review gate is off. Use the write tool instead.'
1140
+ const queued = await stageFileChange(session, { id: exec.callId, name: 'write', arguments: { file_path: args.file_path, content: args.content } })
1141
+ if (queued === undefined) return 'Could not queue this change (missing or invalid file_path).'
1142
+ return `Queued for review: ${queued.entry.display} (${queued.review.entries.size} file(s) queued). Nothing is written until the user finishes. After all changes, call review_wait.`
1143
+ },
1144
+ }), { when: () => featureFlags.review === true && featureFlags.autoReview === true })
1145
+
1146
+ ctx.tools.register(defineTool({
1147
+ name: 'review_patch',
1148
+ description: 'Queue a unified diff for the user\'s review. The patch must use ---/+++ headers and @@ hunks with paths relative to the working directory; a/ and b/ prefixes and diff --git headers are accepted. Use one patch per file when possible; multiple files are allowed. This does not modify the workspace: the change is held in the Code review tab until the user finishes. Example:\n--- a/src/app.ts\n+++ b/src/app.ts\n@@ -10,7 +10,9 @@\n const app = createApp()\n- app.use(oldRouter)\n+ app.use(newRouter)\n+ app.use(logger)\n app.listen(3000)\nAfter queueing every change for this turn, call review_wait.',
1149
+ parameters: {
1150
+ patch: { type: 'string', required: true, description: 'A unified diff (---/+++/@@) to queue for review.' },
1151
+ },
1152
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
1153
+ async execute(args, exec) {
1154
+ const session = exec.agent?.session
1155
+ if (session === undefined) return 'No active session.'
1156
+ if (featureFlags.review !== true) return 'The review gate is off. Use apply_patch or edit instead.'
1157
+ const queued = await stagePatch(session, exec, args.patch)
1158
+ return `Queued for review: ${queued.files.join(', ')} (${queued.review.entries.size} file(s) in this review). Nothing is written until the user finishes. After all changes, call review_wait.`
1159
+ },
1160
+ }), { when: () => featureFlags.review === true && featureFlags.autoReview === true })
1161
+
1162
+ ctx.tools.register(defineTool({
1163
+ name: 'review_wait',
1164
+ description: 'Wait for the user to finish reviewing every change queued in this turn. Call this exactly once after queueing all changes with review_write/review_patch. Returns one structured result per file: applied, rejected (with the user\'s comment), edited, or failed.',
1165
+ parameters: {},
1166
+ output: {
1167
+ schema: {
1168
+ type: 'object',
1169
+ additionalProperties: false,
1170
+ properties: {
1171
+ status: { type: 'string' },
1172
+ files: {
1173
+ type: 'array',
1174
+ items: {
1175
+ type: 'object',
1176
+ additionalProperties: false,
1177
+ properties: {
1178
+ path: { type: 'string' },
1179
+ outcome: { type: 'string' },
1180
+ comment: { type: 'string' },
1181
+ error: { type: 'string' },
1182
+ },
1183
+ },
1184
+ },
1185
+ },
1186
+ },
1187
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
1188
+ },
1189
+ async execute(_args, exec) {
1190
+ const session = exec.agent?.session
1191
+ if (session === undefined) return { status: 'open', files: [] }
1192
+ const review = reviews.get(session.id)
1193
+ if (review === undefined || review.entries.size === 0) return { status: 'empty', files: [] }
1194
+ if (review.submitted !== true) {
1195
+ review.submitted = true
1196
+ bumpReview()
1197
+ }
1198
+ await waitForReviewFinish(review, exec.signal)
1199
+ return reviewResults(review)
1200
+ },
1201
+ }), { when: () => featureFlags.review === true && featureFlags.autoReview === true })
1202
+ }
1203
+
1204
+
1205
+ registerReviewTools()
1206
+
1207
+ const nativeGate = async (exec, next) => {
1208
+ if (featureFlags.review !== true || featureFlags.autoReview !== true) return next()
1209
+ if (!REVIEW_TOOLS.has(exec.name)) return next()
1210
+ return {
1211
+ kind: 'deny',
1212
+ reason: 'File changes must go through the review gate while Auto review is on. Use review_write (new file / full file) or review_patch (unified diff); after queueing all changes call review_wait. Shell commands are outside the review.',
1213
+ }
1214
+ }
1215
+
1216
+ ctx.on('tools/pre-execute', nativeGate, { prepend: true })
1217
+
1218
+ ctx.inject(['systemPrompt'], (promptCtx) => {
1219
+ promptCtx.effect(() => promptCtx.systemPrompt.section({
1220
+ name: 'tool:review-gate',
1221
+ order: 110,
1222
+ text: () => featureFlags.review === true && featureFlags.autoReview === true
1223
+ ? '🎟️ FILE-EDIT VELVET ROPE: The human personally reviews every file change, and you do not have a backstage pass. Queue every change with review_write (new file / full file) or review_patch (unified diff); when you have queued everything, ring review_wait once and wait for the verdict. Do not use write/edit/apply_patch — that is the staff-only door, and the bouncer has a long memory. If a file is rejected, read the comment, say "fair enough", and revise. This is house rules, not a suggestion. 💅'
1224
+ : '',
1225
+ }), 'coding-enhanced: review prompt')
1226
+ })
1227
+
1228
+ ctx.on('session/event', (session, event) => {
1229
+ if (event.type === 'turn/start') {
1230
+ const cwd = session.header?.cwd
1231
+ if (typeof cwd !== 'string' || cwd === '' || isSubagent(session)) return
1232
+ const turn = event.data?.turn
1233
+ activeTurns.set(session.id, turn)
1234
+ if (featureFlags.withdraw === true) {
1235
+ const promise = captureSnapshot(session.id, cwd, turn).catch((error) => {
1236
+ ctx.logger?.warn?.(`coding-enhanced: cannot snapshot ${cwd}: ${String(error)}`)
1237
+ })
1238
+ pendingSnapshots.set(session.id, promise)
1239
+ void promise.finally(() => {
1240
+ if (pendingSnapshots.get(session.id) === promise) pendingSnapshots.delete(session.id)
1241
+ })
1242
+ }
1243
+ return
1244
+ }
1245
+ if (event.type === 'turn/end') {
1246
+ const turn = event.data?.turn
1247
+ activeTurns.delete(session.id)
1248
+ const review = reviews.get(session.id)
1249
+ if (review !== undefined) {
1250
+ if (review.finished === true) cleanupReview(session.id)
1251
+ else if (review.entries.size > 0 && review.submitted !== true) {
1252
+ review.submitted = true
1253
+ bumpReview()
1254
+ }
1255
+ }
1256
+ const snapshot = snapshotOf(session.id, turn)
1257
+ if (snapshot !== undefined) {
1258
+ snapshot.endSeq = event.seq
1259
+ persistSnapshots(session.id)
1260
+ }
1261
+ }
1262
+ })
1263
+
1264
+ // The first tool of a turn must never mutate files before the snapshot is written.
1265
+ ctx.on(
1266
+ 'tools/pre-execute',
1267
+ async (exec, next) => {
1268
+ const sessionId = exec.agent?.session?.id
1269
+ const pending = sessionId === undefined ? undefined : pendingSnapshots.get(sessionId)
1270
+ if (pending !== undefined) await pending
1271
+ return next()
1272
+ },
1273
+ { prepend: true },
1274
+ )
1275
+
1276
+ ctx.on('session/disposed', (session) => {
1277
+ activeTurns.delete(session.id)
1278
+ pendingSnapshots.delete(session.id)
1279
+ cleanupReview(session.id)
1280
+ })
1281
+
1282
+ // ------------------------------------------------------------- inspect ---
1283
+ const inspectSession = (session) => {
1284
+ const events = session.snapshotEvents()
1285
+ let endIndex = -1
1286
+ for (let index = events.length - 1; index >= 0; index -= 1) {
1287
+ if (events[index].type === 'turn/end') {
1288
+ endIndex = index
1289
+ break
1290
+ }
1291
+ }
1292
+ if (endIndex < 0) return { latestTurn: undefined, latestMessageIds: [], events }
1293
+ const turn = events[endIndex].data.turn
1294
+ let startIndex = -1
1295
+ for (let index = endIndex; index >= 0; index -= 1) {
1296
+ const event = events[index]
1297
+ if (event.type === 'turn/start' && event.data.turn === turn) {
1298
+ startIndex = index
1299
+ break
1300
+ }
1301
+ }
1302
+ if (startIndex < 0) return { latestTurn: turn, latestMessageIds: [], events }
1303
+ const ids = new Set()
1304
+ for (let index = startIndex + 1; index < endIndex; index += 1) {
1305
+ const event = events[index]
1306
+ if (event.surfaceOp !== 'append' || !SURFACE_TYPES.has(event.type)) continue
1307
+ const message = event.type === 'user/message' ? event.data : event.data?.message
1308
+ if (typeof message?.id === 'string' && message.id !== '') ids.add(message.id)
1309
+ }
1310
+ return { latestTurn: turn, latestMessageIds: [...ids], startIndex, endIndex, events }
1311
+ }
1312
+
1313
+ const surfaceRange = (session, turn) => {
1314
+ const events = session.snapshotEvents()
1315
+ // Everything already shadowed by an earlier replacement is not on the surface.
1316
+ const shadowed = new Set()
1317
+ for (const event of events) {
1318
+ const op = event.surfaceOp
1319
+ if (op === undefined || typeof op !== 'object' || op.op !== 'replace') continue
1320
+ const from = Math.min(op.startSeq, op.endSeq)
1321
+ const to = Math.max(op.startSeq, op.endSeq)
1322
+ for (let seq = from; seq <= to; seq += 1) shadowed.add(seq)
1323
+ }
1324
+ let startSeq
1325
+ let endSeq
1326
+ const seqs = []
1327
+ let inside = false
1328
+ for (const event of events) {
1329
+ if (event.type === 'turn/start' && event.data.turn === turn) {
1330
+ inside = true
1331
+ continue
1332
+ }
1333
+ if (event.type === 'turn/end' && event.data.turn === turn) break
1334
+ if (!inside) continue
1335
+ if (event.surfaceOp !== 'append' || !SURFACE_TYPES.has(event.type)) continue
1336
+ if (shadowed.has(event.seq)) continue
1337
+ if (startSeq === undefined) startSeq = event.seq
1338
+ endSeq = event.seq
1339
+ seqs.push(event.seq)
1340
+ }
1341
+ if (startSeq === undefined || endSeq === undefined) return undefined
1342
+ return { startSeq, endSeq, seqs }
1343
+ }
1344
+
1345
+ const turnMessageIds = (session, turn) => {
1346
+ const events = session.snapshotEvents()
1347
+ let inside = false
1348
+ const ids = []
1349
+ for (const event of events) {
1350
+ if (event.type === 'turn/start' && event.data?.turn === turn) {
1351
+ inside = true
1352
+ continue
1353
+ }
1354
+ if (event.type === 'turn/end' && event.data?.turn === turn) break
1355
+ if (!inside) continue
1356
+ if (event.surfaceOp !== 'append' || !SURFACE_TYPES.has(event.type)) continue
1357
+ const message = event.type === 'user/message' ? event.data : event.data?.message
1358
+ if (typeof message?.id === 'string' && message.id !== '') ids.push(message.id)
1359
+ }
1360
+ return ids
1361
+ }
1362
+
1363
+ const turnEndSeq = (session, turn) => {
1364
+ for (const event of session.snapshotEvents()) {
1365
+ if (event.type === 'turn/end' && event.data?.turn === turn) return event.seq
1366
+ }
1367
+ return undefined
1368
+ }
1369
+
1370
+ // ------------------------------------------------------------- restore ---
1371
+ const restoreWorktree = (gitDir, cwd, tree) => serialized(`snapshot:${cwd}`, async () => {
1372
+ await addAll(gitDir, cwd)
1373
+ const current = (await runGit(['write-tree'], { gitDir, workTree: cwd })).trim()
1374
+ if (current === tree) return { count: 0, files: [], skipped: [] }
1375
+
1376
+ const raw = await runGit(['diff-tree', '-r', '--name-status', '-z', tree, current], {
1377
+ gitDir,
1378
+ workTree: cwd,
1379
+ })
1380
+ const tokens = raw.split('\0')
1381
+ const entries = []
1382
+ for (let index = 0; index + 1 < tokens.length; index += 2) {
1383
+ const status = tokens[index]
1384
+ const rel = tokens[index + 1]
1385
+ if (status === '' || rel === '') continue
1386
+ entries.push({ status: status[0], rel: assertSafeRelative(rel) })
1387
+ }
1388
+
1389
+ const modes = new Map()
1390
+ const listing = await runGit(['ls-tree', '-r', '-z', tree], { gitDir, workTree: cwd })
1391
+ for (const record of listing.split('\0')) {
1392
+ if (record === '') continue
1393
+ const tab = record.indexOf('\t')
1394
+ if (tab < 0) continue
1395
+ const meta = record.slice(0, tab).split(' ')
1396
+ const rel = record.slice(tab + 1)
1397
+ modes.set(rel, meta[0])
1398
+ }
1399
+
1400
+ const skipped = []
1401
+ const restoredFiles = []
1402
+ for (const entry of entries) {
1403
+ const absolute = posixJoin(cwd, entry.rel)
1404
+ const mode = modes.get(entry.rel)
1405
+ // A nested git repository is recorded as a gitlink commit (160000), not
1406
+ // as blobs. Its contents are not in this snapshot, so restoring (or
1407
+ // deleting) it would fail or destroy the user's repository.
1408
+ if (mode === '160000' || existsSync(path.join(absolute, '.git'))) {
1409
+ skipped.push(entry.rel)
1410
+ continue
1411
+ }
1412
+ if (entry.status === 'A') {
1413
+ await fs.rm(absolute, { recursive: true, force: true })
1414
+ restoredFiles.push(entry.rel)
1415
+ continue
1416
+ }
1417
+ const blob = await runGit(['cat-file', 'blob', `${tree}:${entry.rel}`], {
1418
+ gitDir,
1419
+ workTree: cwd,
1420
+ encoding: 'buffer',
1421
+ })
1422
+ await fs.mkdir(path.dirname(absolute), { recursive: true })
1423
+ await fs.rm(absolute, { recursive: true, force: true })
1424
+ if (mode === '120000') {
1425
+ await fs.symlink(blob.toString('utf8'), absolute)
1426
+ } else {
1427
+ await fs.writeFile(absolute, blob, { mode: mode === '100755' ? 0o755 : 0o644 })
1428
+ }
1429
+ restoredFiles.push(entry.rel)
1430
+ }
1431
+
1432
+ if (skipped.length > 0) {
1433
+ ctx.logger?.warn?.(`coding-enhanced: withdraw left nested git repositories untouched: ${skipped.join(', ')}`)
1434
+ }
1435
+
1436
+ // Leave the shared index at the restored tree so the next turn diffs cleanly.
1437
+ await runGit(['read-tree', tree], { gitDir, workTree: cwd })
1438
+ return { count: restoredFiles.length, files: restoredFiles, skipped }
1439
+ })
1440
+
1441
+ const restoreTree = async (snapshot) => {
1442
+ const main = await restoreWorktree(snapshot.gitDir, snapshot.cwd, snapshot.tree)
1443
+ const nestedSnapshots = Array.isArray(snapshot.nested) ? snapshot.nested : []
1444
+ const nestedPaths = new Set(nestedSnapshots.map((nested) =>
1445
+ path.relative(snapshot.cwd, nested.cwd).split(path.sep).join('/')))
1446
+ let count = main.count
1447
+ const files = [...main.files]
1448
+ const skipped = main.skipped.filter((rel) => !nestedPaths.has(rel))
1449
+ for (const nested of nestedSnapshots) {
1450
+ const rel = path.relative(snapshot.cwd, nested.cwd).split(path.sep).join('/')
1451
+ try {
1452
+ await fs.mkdir(nested.cwd, { recursive: true })
1453
+ const result = await restoreWorktree(nested.gitDir, nested.cwd, nested.tree)
1454
+ count += result.count
1455
+ for (const file of result.files) files.push(rel === '' ? file : `${rel}/${file}`)
1456
+ for (const skip of result.skipped) skipped.push(rel === '' ? skip : `${rel}/${skip}`)
1457
+ } catch (error) {
1458
+ ctx.logger?.warn?.(`coding-enhanced: cannot restore nested repository ${nested.cwd}: ${String(error)}`)
1459
+ skipped.push(rel)
1460
+ }
1461
+ }
1462
+ try {
1463
+ for (const nestedCwd of await findNestedRepos(snapshot.cwd)) {
1464
+ const rel = path.relative(snapshot.cwd, nestedCwd).split(path.sep).join('/')
1465
+ if (!nestedPaths.has(rel)) skipped.push(rel)
1466
+ }
1467
+ } catch {}
1468
+ return { count, files, skipped: [...new Set(skipped)] }
1469
+ }
1470
+
1471
+ // ---------------------------------------------------------------- rpc ---
1472
+ const ok = (value) => ({ ok: true, value })
1473
+ const fail = (code, message) => ({
1474
+ ok: false,
1475
+ error: { code: `coding-enhanced/${code}`, message },
1476
+ })
1477
+
1478
+ const handleStatus = (sessionId) => {
1479
+ const session = ctx.sessions.get(sessionId)
1480
+ if (session === undefined) return fail('session-not-live', 'Session is not active in this Host')
1481
+ const info = inspectSession(session)
1482
+ const latestTurn = info.latestTurn
1483
+ const withdrawn = withdrawnOf(sessionId)
1484
+ const anchors = {}
1485
+ const withdrawable = {}
1486
+ if (featureFlags.withdraw === true && !activeTurns.has(sessionId)) {
1487
+ const map = snapshots.get(sessionId)
1488
+ if (map !== undefined) {
1489
+ let changed = false
1490
+ for (const [turn, snapshot] of map.entries()) {
1491
+ if (snapshot.endSeq !== undefined) continue
1492
+ const endSeq = turnEndSeq(session, turn)
1493
+ if (endSeq !== undefined) {
1494
+ snapshot.endSeq = endSeq
1495
+ changed = true
1496
+ }
1497
+ }
1498
+ if (changed) persistSnapshots(sessionId)
1499
+ for (const [turn, snapshot] of map.entries()) {
1500
+ if (snapshot.endSeq === undefined) continue
1501
+ if (withdrawn[turn] !== undefined) continue
1502
+ if (surfaceRange(session, turn) === undefined) continue
1503
+ for (const id of turnMessageIds(session, turn)) anchors[id] = turn
1504
+ withdrawable[turn] = true
1505
+ }
1506
+ }
1507
+ }
1508
+ if (latestTurn !== undefined && withdrawable[latestTurn] === undefined && withdrawn[latestTurn] === undefined) {
1509
+ for (const id of info.latestMessageIds) anchors[id] = latestTurn
1510
+ }
1511
+ for (const key of Object.keys(withdrawn)) {
1512
+ const withdrawnTurn = Number(key)
1513
+ if (!Number.isSafeInteger(withdrawnTurn)) continue
1514
+ if (anchors[withdrawnTurn] !== undefined) continue
1515
+ for (const id of turnMessageIds(session, withdrawnTurn)) anchors[id] = withdrawnTurn
1516
+ }
1517
+ let reason = null
1518
+ if (featureFlags.withdraw !== true) reason = 'disabled'
1519
+ else if (latestTurn === undefined) reason = 'no-turn'
1520
+ else if (withdrawn[latestTurn] !== undefined) reason = 'already'
1521
+ else if (activeTurns.has(sessionId)) reason = 'active'
1522
+ else if (snapshotOf(sessionId, latestTurn) === undefined) reason = 'no-snapshot'
1523
+ else if (snapshotOf(sessionId, latestTurn).endSeq === undefined) reason = 'incomplete'
1524
+ return ok({
1525
+ latestTurn: latestTurn ?? null,
1526
+ active: activeTurns.has(sessionId),
1527
+ canWithdraw: withdrawable[latestTurn] === true,
1528
+ reason,
1529
+ turns: withdrawn,
1530
+ anchors,
1531
+ withdrawable,
1532
+ })
1533
+ }
1534
+
1535
+ const handleWithdraw = async (payload) => {
1536
+ const sessionId = payload?.sessionId
1537
+ const turn = payload?.turn
1538
+ if (typeof sessionId !== 'string' || !Number.isSafeInteger(turn)) {
1539
+ return fail('bad-request', 'sessionId and turn are required')
1540
+ }
1541
+ const session = ctx.sessions.get(sessionId)
1542
+ if (session === undefined) return fail('session-not-live', 'Session is not active in this Host')
1543
+ if (featureFlags.withdraw !== true) return fail('withdraw-disabled', 'Turn withdraw is turned off in Settings')
1544
+ if (activeTurns.has(sessionId)) return fail('turn-active', 'A turn is still running')
1545
+ const withdrawn = withdrawnOf(sessionId)
1546
+ if (withdrawn[turn] !== undefined) return fail('already-withdrawn', 'This turn was already withdrawn')
1547
+ const snapshot = snapshotOf(sessionId, turn)
1548
+ if (snapshot === undefined) {
1549
+ return fail('no-snapshot', 'No workspace snapshot exists for this turn (it was pruned or started before the plugin loaded)')
1550
+ }
1551
+ if (snapshot.endSeq === undefined) {
1552
+ const endSeq = turnEndSeq(session, turn)
1553
+ if (endSeq !== undefined) {
1554
+ snapshot.endSeq = endSeq
1555
+ persistSnapshots(sessionId)
1556
+ }
1557
+ }
1558
+ if (snapshot.endSeq === undefined) return fail('turn-active', 'This turn has not finished yet')
1559
+ const info = inspectSession(session)
1560
+ if (info.latestTurn === undefined) return fail('no-turn', 'This session has no completed turn')
1561
+ if (turn > info.latestTurn) return fail('not-latest', 'This turn is newer than the latest completed turn')
1562
+ const target = surfaceRange(session, turn)
1563
+ if (target === undefined) {
1564
+ return fail('no-surface', 'This turn has no model-visible messages to cancel')
1565
+ }
1566
+
1567
+ const events = session.snapshotEvents()
1568
+ const shadowed = new Set()
1569
+ for (const event of events) {
1570
+ const op = event.surfaceOp
1571
+ if (op === undefined || typeof op !== 'object' || op.op !== 'replace') continue
1572
+ const from = Math.min(op.startSeq, op.endSeq)
1573
+ const to = Math.max(op.startSeq, op.endSeq)
1574
+ for (let seq = from; seq <= to; seq += 1) shadowed.add(seq)
1575
+ }
1576
+ const seqs = []
1577
+ for (const event of events) {
1578
+ if (event.seq < target.startSeq) continue
1579
+ if (event.surfaceOp !== 'append' || !SURFACE_TYPES.has(event.type)) continue
1580
+ if (shadowed.has(event.seq)) continue
1581
+ seqs.push(event.seq)
1582
+ }
1583
+ if (seqs.length === 0) return fail('no-surface', 'This turn has no model-visible messages to cancel')
1584
+ // End on a model-visible surface event; tool results and turn/end are not
1585
+ // part of the surface and would be rejected by session.append.
1586
+ const endSeq = seqs[seqs.length - 1]
1587
+ const affected = new Set([turn])
1588
+ for (const event of events) {
1589
+ if (event.type === 'turn/start' && event.seq >= target.startSeq && Number.isSafeInteger(event.data?.turn) && event.data.turn >= turn) {
1590
+ affected.add(event.data.turn)
1591
+ }
1592
+ }
1593
+
1594
+ let restored
1595
+ try {
1596
+ restored = await restoreTree(snapshot)
1597
+ } catch (error) {
1598
+ ctx.logger?.error?.(`coding-enhanced: restore failed: ${String(error)}`)
1599
+ return fail('restore-failed', String(error))
1600
+ }
1601
+
1602
+ // A withdrawal lands after turn/end, so there is no open turn and step to
1603
+ // join. A developer/message there is accepted by the live append but the
1604
+ // session format rejects it when the log is replayed, corrupting the
1605
+ // session. A user/message replacement is valid outside a turn (compaction
1606
+ // checkpoints use the same shape), and an empty user message projects to no
1607
+ // wire message, so the cancelled turn stays hidden without a synthetic turn.
1608
+ try {
1609
+ session.append(
1610
+ 'user/message',
1611
+ {
1612
+ id: `coding-enhanced-withdraw-${turn}-${Date.now().toString(36)}`,
1613
+ role: 'user',
1614
+ source: { kind: 'coding-enhanced-withdraw' },
1615
+ content: [],
1616
+ },
1617
+ {
1618
+ surfaceOp: { op: 'replace', startSeq: target.startSeq, endSeq },
1619
+ sourceEventSeqs: seqs,
1620
+ },
1621
+ )
1622
+ } catch (error) {
1623
+ ctx.logger?.error?.(`coding-enhanced: cancel append failed: ${String(error)}`)
1624
+ return fail(
1625
+ 'cancel-failed',
1626
+ `Files were restored, but hiding the turn from the model failed: ${String(error)}`,
1627
+ )
1628
+ }
1629
+
1630
+ const restoredAt = Date.now()
1631
+ const record = state.sessions[sessionId] ?? { withdrawn: {} }
1632
+ for (const affectedTurn of affected) {
1633
+ record.withdrawn[affectedTurn] = {
1634
+ at: restoredAt,
1635
+ files: affectedTurn === turn ? restored.count : 0,
1636
+ }
1637
+ }
1638
+ record.updatedAt = restoredAt
1639
+ state.sessions[sessionId] = record
1640
+
1641
+ const map = snapshots.get(sessionId)
1642
+ if (map !== undefined) {
1643
+ for (const affectedTurn of affected) {
1644
+ const dropped = map.get(affectedTurn)
1645
+ if (dropped !== undefined) {
1646
+ void deleteSnapshotRefs(dropped)
1647
+ markSnapshotDirty(dropped)
1648
+ }
1649
+ map.delete(affectedTurn)
1650
+ }
1651
+ if (map.size === 0) snapshots.delete(sessionId)
1652
+ }
1653
+ persistSnapshots(sessionId)
1654
+ saveState()
1655
+ if (featureFlags.autoGc === true) void flushGc()
1656
+
1657
+ return ok({
1658
+ turn,
1659
+ files: restored.count,
1660
+ paths: restored.files,
1661
+ skipped: restored.skipped,
1662
+ withdrawn: [...affected].sort((left, right) => left - right),
1663
+ })
1664
+ }
1665
+
1666
+ const cancelReview = (id, reasonFor) => {
1667
+ const review = [...reviews.values()].find((candidate) => candidate.id === id)
1668
+ if (review === undefined) return ok({ reviewId: id, canceled: true })
1669
+ if (review.finished) return ok({ reviewId: id, canceled: true })
1670
+ review.finished = true
1671
+ review.canceled = true
1672
+ for (const entry of review.entries.values()) {
1673
+ entry.canceled = true
1674
+ const reason = typeof reasonFor === 'function' ? reasonFor(entry) : reasonFor
1675
+ if (typeof reason === 'string' && reason !== '') entry.cancelReason = reason
1676
+ }
1677
+ for (const waiter of review.waiters) waiter()
1678
+ review.waiters = []
1679
+ bumpReview()
1680
+ return ok({ reviewId: id, canceled: true })
1681
+ }
1682
+
1683
+ const updateSettings = (patch) => {
1684
+ if (patch === null || typeof patch !== 'object') {
1685
+ return fail('bad-request', 'settings patch must be an object')
1686
+ }
1687
+ let changed = false
1688
+ if (typeof patch.review === 'boolean' && patch.review !== featureFlags.review) {
1689
+ featureFlags.review = patch.review
1690
+ changed = true
1691
+ }
1692
+ if (typeof patch.withdraw === 'boolean' && patch.withdraw !== featureFlags.withdraw) {
1693
+ featureFlags.withdraw = patch.withdraw
1694
+ changed = true
1695
+ }
1696
+ if (typeof patch.autoReview === 'boolean' && patch.autoReview !== featureFlags.autoReview) {
1697
+ featureFlags.autoReview = patch.autoReview
1698
+ changed = true
1699
+ }
1700
+ if (Number.isSafeInteger(patch.keepTurns)) {
1701
+ const next = Math.min(50, Math.max(1, patch.keepTurns))
1702
+ if (next !== featureFlags.keepTurns) {
1703
+ featureFlags.keepTurns = next
1704
+ changed = true
1705
+ pruneAllSnapshots()
1706
+ }
1707
+ }
1708
+ if (typeof patch.nestedSnapshots === 'boolean' && patch.nestedSnapshots !== featureFlags.nestedSnapshots) {
1709
+ featureFlags.nestedSnapshots = patch.nestedSnapshots
1710
+ changed = true
1711
+ }
1712
+ if (typeof patch.autoGc === 'boolean' && patch.autoGc !== featureFlags.autoGc) {
1713
+ featureFlags.autoGc = patch.autoGc
1714
+ changed = true
1715
+ }
1716
+ if (changed) saveFeatureFlags()
1717
+ if (featureFlags.review !== true) {
1718
+ for (const review of [...reviews.values()]) {
1719
+ if (review.finished) continue
1720
+ cancelReview(review.id, (entry) => `The review gate was turned off in Settings. Nothing was written for "${entry.display}". Do not retry immediately; wait for the user.`)
1721
+ }
1722
+ }
1723
+ return ok({ review: featureFlags.review, withdraw: featureFlags.withdraw, autoReview: featureFlags.autoReview, keepTurns: featureFlags.keepTurns, nestedSnapshots: featureFlags.nestedSnapshots, autoGc: featureFlags.autoGc })
1724
+ }
1725
+
1726
+ const dispatch = async (endpoint, payload) => {
1727
+ try {
1728
+ if (endpoint === 'status') return handleStatus(payload?.sessionId)
1729
+ if (endpoint === 'settings') return ok({ review: featureFlags.review, withdraw: featureFlags.withdraw, autoReview: featureFlags.autoReview, keepTurns: featureFlags.keepTurns, nestedSnapshots: featureFlags.nestedSnapshots, autoGc: featureFlags.autoGc })
1730
+ if (endpoint === 'setSettings') return updateSettings(payload)
1731
+ if (endpoint === 'cleanup') return ok(await cleanupSnapshots())
1732
+ if (endpoint === 'withdraw') return await handleWithdraw(payload)
1733
+ if (endpoint === 'reviews') {
1734
+ const since = payload?.since
1735
+ if (Number.isSafeInteger(since) && since === reviewVersion) {
1736
+ return ok({ version: reviewVersion, unchanged: true })
1737
+ }
1738
+ return ok({
1739
+ version: reviewVersion,
1740
+ unchanged: false,
1741
+ reviews: [...reviews.values()].map(serializeReview),
1742
+ })
1743
+ }
1744
+ if (endpoint === 'decide') return decideReview(payload?.reviewId, payload?.decisions)
1745
+ if (endpoint === 'cancel') return cancelReview(payload?.reviewId)
1746
+ return fail('not-found', `Unknown endpoint ${JSON.stringify(endpoint)}`)
1747
+ } catch (error) {
1748
+ ctx.logger?.error?.(`coding-enhanced: ${String(error)}`)
1749
+ return fail('internal', String(error))
1750
+ }
1751
+ }
1752
+
1753
+ // The shared `/api` bridge admits the request (browser trust, cookie auth and
1754
+ // the owner-Peer check) before an exact route sees it.
1755
+ ctx.connection.fetch.register({
1756
+ path: '/api/coding-enhanced',
1757
+ methods: ['POST'],
1758
+ requestBody: 'buffered',
1759
+ fetch: async (request) => {
1760
+ let body
1761
+ try {
1762
+ body = await request.json()
1763
+ } catch {
1764
+ return Response.json(fail('bad-request', 'Body must be JSON'), { status: 400 })
1765
+ }
1766
+ const result = await dispatch(body?.endpoint, body?.payload)
1767
+ return Response.json(result)
1768
+ },
1769
+ })
1770
+
1771
+ }