@lincyaw/workspace 1.0.0-rc.15 → 1.0.0-rc.151

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +6 -4
  2. package/package.json +12 -6
  3. package/src/domain/paths.ts +0 -15
  4. package/src/node/agent-activity.ts +46 -0
  5. package/src/node/archive.ts +33 -0
  6. package/src/node/authoring-clients.ts +73 -20
  7. package/src/node/authoring-windows.ts +165 -0
  8. package/src/node/build.ts +16 -6
  9. package/src/node/capture.ts +383 -0
  10. package/src/node/config.ts +135 -50
  11. package/src/node/document-assets.ts +2 -2
  12. package/src/node/document-audio.ts +66 -47
  13. package/src/node/document-authoring.ts +30 -15
  14. package/src/node/document-check.ts +36 -0
  15. package/src/node/document-history.ts +32 -5
  16. package/src/node/document-images.ts +24 -14
  17. package/src/node/document-import.ts +123 -0
  18. package/src/node/document-index.ts +654 -0
  19. package/src/node/document-materials.ts +80 -0
  20. package/src/node/document-operations.ts +4 -2
  21. package/src/node/document-transcription.ts +2 -1
  22. package/src/node/document-voice.ts +121 -13
  23. package/src/node/git-runner.mjs +19 -0
  24. package/src/node/git.ts +141 -22
  25. package/src/node/host-activity.ts +17 -0
  26. package/src/node/host-upgrade.ts +28 -0
  27. package/src/node/jobs.ts +40 -8
  28. package/src/node/local-history.ts +85 -0
  29. package/src/node/locks.ts +12 -0
  30. package/src/node/mcp-settings.ts +68 -0
  31. package/src/node/media-upload-messages.ts +4 -0
  32. package/src/node/media-upload-page.ts +57 -0
  33. package/src/node/media-upload.css +4 -0
  34. package/src/node/media-uploads.ts +116 -0
  35. package/src/node/page-delete.ts +0 -1
  36. package/src/node/project-files.ts +2 -2
  37. package/src/node/projects.ts +20 -5
  38. package/src/node/review/agent-session-reviews.ts +211 -68
  39. package/src/node/review/agent-workspace.ts +151 -0
  40. package/src/node/review/git-review.ts +72 -29
  41. package/src/node/review/record.ts +41 -9
  42. package/src/node/review/routes.ts +9 -1
  43. package/src/node/review/windows-dependencies.ts +163 -0
  44. package/src/node/review/workspace-review.ts +87 -0
  45. package/src/node/revision-files.ts +54 -0
  46. package/src/node/revisions.ts +318 -80
  47. package/src/node/routes.ts +52 -59
  48. package/src/node/serve.ts +267 -52
  49. package/src/node/site.ts +5 -5
  50. package/src/node/source-editor.ts +66 -26
  51. package/src/node/speech-settings.ts +6 -8
  52. package/src/node/templates.ts +2 -2
  53. package/src/node/tree-operations.ts +425 -0
  54. package/src/node/tree-routes.ts +107 -0
  55. package/src/node/workbench-api.ts +14 -3
  56. package/src/node/workspace-changes.ts +130 -0
  57. package/src/node/workspace-migrate.ts +54 -0
  58. package/src/node/workspace-source.ts +133 -0
  59. package/src/node/writer.ts +21 -8
  60. package/templates/document/default/{lecture.json → index.pmd} +5 -1
@@ -1,8 +1,9 @@
1
- import { randomUUID } from 'node:crypto'
2
- import { existsSync, readFileSync } from 'node:fs'
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { existsSync } from 'node:fs'
3
3
  import { join } from 'node:path'
4
- import { DOCUMENT_ENTRY, errorMessage, pushStream } from '@lincyaw/kernel'
5
- import type { DocumentFiles, Logger, Member, ReviewEnd, ReviewSnapshot, ReviewUpdate } from '@lincyaw/kernel'
4
+ import { errorMessage, pushStream } from '@lincyaw/kernel'
5
+ import { acquireCandidateLease } from '@lincyaw/kernel/node'
6
+ import type { DocumentFiles, Logger, Member, ReviewChange, ReviewEnd, ReviewSnapshot, ReviewUpdate } from '@lincyaw/kernel'
6
7
  import { trailers } from '../../domain/commit-message.ts'
7
8
  import type { WorkspaceConfig } from '../config.ts'
8
9
  import { listDocuments } from '../config.ts'
@@ -11,12 +12,12 @@ import { lockedError } from '../locks.ts'
11
12
  import type { DocumentLocks } from '../locks.ts'
12
13
  import type { Revisions } from '../revisions.ts'
13
14
  import { writeChanges } from '../writer.ts'
14
- import { GIT_ENGINE, openGitReview, pendingAgentSessionReview, resumeGitReview } from './git-review.ts'
15
+ import { openGitReview, pendingAgentSessionReview, resumeGitReview } from './git-review.ts'
15
16
  import type { GitReview } from './git-review.ts'
16
17
  import { readRecord } from './record.ts'
17
18
  import type { ReviewRecord } from './record.ts'
18
19
  import { rollBackLeftTaskReview } from './task-reviews.ts'
19
- import { validateDocumentSource } from '../source-editor.ts'
20
+ import { AgentWorkspace } from './agent-workspace.ts'
20
21
 
21
22
  export const AGENT_SESSION_TRAILER = 'Presmium-Session'
22
23
  export const TURN_TRAILER = 'Presmium-Turn'
@@ -32,6 +33,7 @@ export interface AgentSessionReviewsOptions {
32
33
  /** How a plugin's task writes, for rolling back the tasks a process left. */
33
34
  files?: DocumentFiles
34
35
  log: Logger
36
+ flush?(documents: string[], member: Member): Promise<void>
35
37
  }
36
38
 
37
39
  interface OpenReview {
@@ -42,7 +44,9 @@ interface OpenReview {
42
44
  turns: { from: number, to: number }
43
45
  running: boolean
44
46
  opened: string
45
- release: () => void
47
+ backend?: 'deltabox'
48
+ awaitingDeltabox?: boolean
49
+ workspace?: AgentWorkspace
46
50
  timer?: ReturnType<typeof setTimeout>
47
51
  }
48
52
 
@@ -69,21 +73,21 @@ function commitSummary(files: string[], lang: string | undefined): string {
69
73
  }
70
74
 
71
75
  /**
72
- * The review of a dsh agent session's changes to the whole workspace: one at a time, under the workspace's lock,
73
- * across the session's turns. A review that no page watches rolls back after the configured time.
76
+ * A dsh session reviews its private candidate; only publication briefly locks the author's workspace.
77
+ * A review that no page watches drops its candidate changes after the configured time.
74
78
  */
75
79
  export class AgentSessionReviews {
76
80
  readonly #options: AgentSessionReviewsOptions
77
81
  #open?: OpenReview
78
82
  #queue: Promise<unknown> = Promise.resolve()
79
- readonly #workspaceFiles: DocumentFiles
80
83
  readonly #watchers = new Set<(update: ReviewUpdate) => void>()
81
84
  readonly #listeners = new Set<(event: ReviewEvent) => void>()
82
85
  #closed = false
86
+ readonly #workspaces = new Map<string, AgentWorkspace>()
87
+ readonly #retired = new Set<string>()
83
88
 
84
89
  constructor(options: AgentSessionReviewsOptions) {
85
90
  this.#options = options
86
- this.#workspaceFiles = { write: async changes => writeChanges(options.config, changes, true) }
87
91
  }
88
92
 
89
93
  /** Takes up the reviews a process that has ended left: resumes its agent session's review, rolls back its tasks' reviews. */
@@ -97,11 +101,12 @@ export class AgentSessionReviews {
97
101
  try {
98
102
  const pending = pendingAgentSessionReview(scopeDir)
99
103
  if (pending?.session) {
100
- await this.#serial(() => this.#resume(pending))
104
+ await this.#serial(() => this.#resume(pending), () => pending.workspace ? [pending.workspace.root] : [])
101
105
  continue
102
106
  }
103
107
  await rollBackLeftTaskReview(this.#options, document)
104
108
  } catch (error) {
109
+ if (readRecord(scopeDir)?.session) throw error
105
110
  log.warn(`the review left in ${document || '.'} was not taken up: ${errorMessage(error)}`)
106
111
  }
107
112
  }
@@ -110,30 +115,106 @@ export class AgentSessionReviews {
110
115
  async #resume(pending: ReviewRecord): Promise<void> {
111
116
  const { config, log } = this.#options
112
117
  const session = pending.session!
113
- const release = this.#options.locks.claim('', lockHolder(session.session))
114
- if (!release) throw new Error(`its lock is ${this.#options.locks.holder('')}'s`)
115
- try {
116
- const review = await resumeGitReview(pending, { workspaceRoot: config.root, files: this.#workspaceFiles, onRestore: paths => log.warn(`session ${session.session}: the agent changed the git directory, put back: ${paths.join(', ')}`) })
117
- const open: OpenReview = { review, document: session.document, session: session.session, member: session.member, turns: session.turns, running: false, opened: session.opened, release }
118
- this.#open = open
119
- log.info(`the review of session ${session.session} in ${session.document || '.'} (turns ${session.turns.from}-${session.turns.to}) waits for its author again`)
120
- this.#scheduleRollback(open)
121
- } catch (error) {
122
- release()
123
- throw error
124
- }
118
+ const workspace = pending.workspace ? AgentWorkspace.resume(config, pending.workspace) : undefined
119
+ const root = workspace?.root ?? config.root
120
+ const review = await resumeGitReview(pending, { workspaceRoot: root, files: { write: async changes => workspace ? workspace.writeCandidate(changes) : writeChanges({ ...config, root }, changes, true) }, onRestore: paths => { workspace?.changed(); log.warn(`session ${session.session}: the agent changed the git directory, put back: ${paths.join(', ')}`) } })
121
+ const empty = (await review.diff()).length === 0
122
+ if (empty && session.backend !== 'deltabox') { await review.close(); workspace?.dispose(); return }
123
+ if (!workspace) { review.suspend(); throw new Error('A legacy review needs to be accepted or rejected with the version that created it before concurrent editing can start.') }
124
+ this.#workspaces.set(session.session, workspace)
125
+ const open: OpenReview = { review, document: session.document, session: session.session, member: session.member, turns: session.turns, running: session.backend === 'deltabox', opened: session.opened, workspace, backend: session.backend, awaitingDeltabox: session.backend === 'deltabox' }
126
+ this.#open = open
127
+ log.info(`the review of session ${session.session} in ${session.document || '.'} (turns ${session.turns.from}-${session.turns.to}) waits for its author again`)
128
+ this.#scheduleRollback(open)
125
129
  }
126
130
 
127
- async snapshot(): Promise<ReviewSnapshot | undefined> {
128
- const open = this.#open
129
- return open && await this.#snapshotOf(open)
131
+ workspace(session: string): Promise<{ root: string, version: string }> {
132
+ return this.#serial(async () => {
133
+ this.#retired.delete(session)
134
+ let workspace = this.#workspaces.get(session)
135
+ if (!workspace) { workspace = await AgentWorkspace.create(this.#options.config); this.#workspaces.set(session, workspace) }
136
+ return { root: workspace.root, version: workspace.version }
137
+ }, false)
138
+ }
139
+
140
+ refreshWorkspace(session: string): Promise<boolean> {
141
+ return this.#serial(async () => {
142
+ const workspace = this.#workspaces.get(session)
143
+ return workspace && this.#open?.session !== session ? workspace.refresh() : false
144
+ }, () => this.#workspaces.has(session) ? [this.#workspaces.get(session)!.root] : [])
145
+ }
146
+
147
+ /** The DSH adapter has adopted and staged any orphaned native review before this is called. */
148
+ resumeWorkspace(session: string): Promise<void> {
149
+ return this.#serial(async () => {
150
+ const open = this.#open
151
+ if (!open || open.session !== session || !open.awaitingDeltabox) return
152
+ open.awaitingDeltabox = false
153
+ open.running = false
154
+ if ((await open.review.diff()).length === 0) {
155
+ await open.review.close()
156
+ await this.#end(open, { outcome: 'empty', files: [] })
157
+ } else {
158
+ await this.#publish(open)
159
+ this.#scheduleRollback(open)
160
+ }
161
+ })
162
+ }
163
+
164
+ closeWorkspace(session: string): Promise<void> {
165
+ return this.#serial(async () => {
166
+ if (this.#open?.session === session) { this.#retired.add(session); return }
167
+ const workspace = this.#workspaces.get(session)
168
+ this.#workspaces.delete(session)
169
+ workspace?.dispose()
170
+ }, () => this.#workspaces.has(session) ? [this.#workspaces.get(session)!.root] : [])
171
+ }
172
+
173
+ snapshot(): Promise<ReviewSnapshot | undefined> {
174
+ return this.#serial(async () => this.#open && await this.#snapshotOf(this.#open))
175
+ }
176
+
177
+ inspect(): Promise<{ snapshot: string, review: ReviewSnapshot } | undefined> {
178
+ return this.#serial(async () => { if (!this.#open) return; const { snapshot, review } = await this.#inspect(this.#open); return { snapshot, review } })
179
+ }
180
+
181
+ async #inspect(open: OpenReview) {
182
+ const { tree, version, changes } = await open.review.inspect()
183
+ const review = await this.#snapshotOf(open, changes)
184
+ review.steps = review.steps.map(step => ({ ...step, changes: step.changes.map(({ diff: _diff, ...change }) => change) }))
185
+ return { tree, review, snapshot: createHash('sha256').update(JSON.stringify([version, review])).digest('hex') }
186
+ }
187
+
188
+ async #expected(open: OpenReview, expected: string | undefined, signal?: AbortSignal): Promise<void> {
189
+ signal?.throwIfAborted()
190
+ if (expected === undefined) return
191
+ if (open.running) throw new RequestError(409, 'workspace-review-running')
192
+ if ((await this.#inspect(open)).snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
193
+ signal?.throwIfAborted()
194
+ }
195
+
196
+ check(expected: string): Promise<void> {
197
+ return this.#serial(async () => this.#expected(this.#requireOpen('', expected), expected))
198
+ }
199
+
200
+ readDiff(expected: string, path: string, step?: string): Promise<ReviewChange | undefined> {
201
+ return this.#serial(async () => {
202
+ const open = this.#requireOpen('', expected)
203
+ const current = await this.#inspect(open)
204
+ if (current.snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
205
+ const files = step === undefined ? current.review.changes : current.review.steps.find(value => value.id === step)?.changes
206
+ if (!files?.some(file => file.path === path)) return
207
+ const value = await open.review.diffFile(path, step)
208
+ if ((await this.#inspect(open)).snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
209
+ return value
210
+ })
130
211
  }
131
212
 
132
- async #snapshotOf(open: OpenReview): Promise<ReviewSnapshot> {
213
+ async #snapshotOf(open: OpenReview, changes?: ReviewChange[]): Promise<ReviewSnapshot> {
133
214
  return {
134
215
  id: open.review.task,
135
216
  document: open.document,
136
- engine: GIT_ENGINE,
217
+ engine: 'git-candidate',
137
218
  session: open.session,
138
219
  holder: lockHolder(open.session),
139
220
  turns: { ...open.turns },
@@ -141,7 +222,7 @@ export class AgentSessionReviews {
141
222
  mode: reviewSettings(this.#options.config).mode,
142
223
  opened: open.opened,
143
224
  steps: [...open.review.steps()],
144
- changes: await open.review.diff(),
225
+ changes: changes ?? await open.review.diff(),
145
226
  }
146
227
  }
147
228
 
@@ -167,30 +248,32 @@ export class AgentSessionReviews {
167
248
  }, { signal })
168
249
  }
169
250
 
170
- open(document: string, body: { session: string, turn?: number }, member: Member): Promise<ReviewSnapshot> {
251
+ open(document: string, body: { session: string, turn?: number, backend?: 'deltabox' }, member: Member): Promise<ReviewSnapshot> {
171
252
  return this.#serial(async () => {
172
253
  if (this.#closed) throw new RequestError(503, 'the workspace service is closing')
173
254
  let open = this.#open
174
255
  if (open && open.session !== body.session) throw lockedError(document, lockHolder(open.session))
175
256
  if (!open) {
176
- const release = this.#options.locks.claim('', lockHolder(body.session))
177
- if (!release) throw lockedError(document, this.#options.locks.holder('')!)
178
257
  const { config, log } = this.#options
179
258
  const turn = body.turn ?? 0
180
259
  const opened = new Date().toISOString()
260
+ let workspace = this.#workspaces.get(body.session)
261
+ if (!workspace) { workspace = await AgentWorkspace.create(config); this.#workspaces.set(body.session, workspace) }
262
+ const root = workspace.root
181
263
  try {
182
264
  const review = await openGitReview({
183
- workspaceRoot: config.root,
184
- scopeDir: config.root,
265
+ workspaceRoot: root,
266
+ scopeDir: root,
267
+ recordRoot: config.root,
268
+ workspace: workspace.record,
185
269
  task: randomUUID(),
186
- files: this.#workspaceFiles,
187
- onRestore: paths => log.warn(`session ${body.session}: the agent changed the git directory, put back: ${paths.join(', ')}`),
270
+ files: { write: async changes => workspace!.writeCandidate(changes) },
271
+ onRestore: paths => { workspace!.changed(); log.warn(`session ${body.session}: the agent changed the git directory, put back: ${paths.join(', ')}`) },
188
272
  warn: message => log.warn(`session ${body.session}: ${message}`),
189
- session: { session: body.session, document, member, turns: { from: turn, to: turn }, opened },
273
+ session: { session: body.session, document, member, turns: { from: turn, to: turn }, opened, backend: body.backend },
190
274
  })
191
- open = { review, document, session: body.session, member, turns: { from: turn, to: turn }, running: true, opened, release }
275
+ open = { review, document, session: body.session, member, turns: { from: turn, to: turn }, running: true, opened, workspace, backend: body.backend }
192
276
  } catch (error) {
193
- release()
194
277
  throw new RequestError(409, `the review of ${document || '.'} did not open: ${errorMessage(error)}`)
195
278
  }
196
279
  this.#open = open
@@ -199,16 +282,29 @@ export class AgentSessionReviews {
199
282
  open.running = true
200
283
  this.#rescheduleRollback()
201
284
  return await this.#publish(open)
202
- })
285
+ }, () => this.#workspaces.has(body.session) ? [this.#workspaces.get(body.session)!.root] : [])
203
286
  }
204
287
 
205
288
  step(document: string, body: { session: string, turn?: number, label?: string, tool?: string, end?: boolean }): Promise<ReviewSnapshot | undefined> {
206
289
  return this.#serial(async () => {
290
+ if (!this.#open && body.end) return undefined
207
291
  const open = this.#requireSession(document, body.session)
208
292
  this.#noteTurn(open, body.turn)
209
293
  if (body.label) await open.review.step(body.label, body.tool)
210
294
  if (!body.end) {
211
- open.running = true
295
+ open.running = false
296
+ if (reviewSettings(this.#options.config).mode === 'auto') {
297
+ try { await this.#accept(open, [], undefined) }
298
+ catch (error) {
299
+ if (error instanceof RequestError && error.message === 'agent-source-changed') {
300
+ await open.review.close()
301
+ await this.#end(open, { outcome: 'rejected', files: [] })
302
+ if (this.#workspaces.has(open.session)) await open.workspace!.refresh()
303
+ }
304
+ throw error
305
+ }
306
+ return undefined
307
+ }
212
308
  return await this.#publish(open)
213
309
  }
214
310
  open.running = false
@@ -227,36 +323,65 @@ export class AgentSessionReviews {
227
323
  })
228
324
  }
229
325
 
230
- accept(document: string, body: { reject?: string[], message?: string }): Promise<ReviewEnd> {
231
- return this.#serial(() => this.#accept(this.#requireOpen(document), body.reject ?? [], body.message))
326
+ accept(document: string, body: { reject?: string[], message?: string, expected?: string }, signal?: AbortSignal): Promise<ReviewEnd> {
327
+ return this.#serial(async () => {
328
+ const open = this.#requireOpen(document, body.expected)
329
+ if (open.awaitingDeltabox) throw new RequestError(409, 'workspace-review-running')
330
+ await this.#expected(open, body.expected, signal)
331
+ try { return await this.#accept(open, body.reject ?? [], body.message, signal, body.expected) }
332
+ catch (error) {
333
+ if (error instanceof RequestError && error.message === 'agent-source-changed') {
334
+ await open.review.close()
335
+ await this.#end(open, { outcome: 'rejected', files: [] })
336
+ if (this.#workspaces.has(open.session)) await open.workspace!.refresh()
337
+ }
338
+ throw error
339
+ }
340
+ })
232
341
  }
233
342
 
234
- async #accept(open: OpenReview, reject: string[], message: string | undefined): Promise<ReviewEnd> {
343
+ async #accept(open: OpenReview, reject: string[], message: string | undefined, signal?: AbortSignal, expected?: string): Promise<ReviewEnd> {
344
+ const captured = await this.#inspect(open)
345
+ if (expected !== undefined && captured.snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
235
346
  const rejected = new Set(reject)
236
- for (const change of await open.review.diff()) if (isInGitDir(change.path)) rejected.add(change.path)
237
- const files = await open.review.prepareAccept([...rejected])
238
- for (const path of files) {
239
- if (path !== DOCUMENT_ENTRY && !path.endsWith(`/${DOCUMENT_ENTRY}`)) continue
240
- const file = join(this.#options.config.root, path)
241
- if (existsSync(file)) validateDocumentSource(path, readFileSync(file, 'utf8'))
242
- }
347
+ for (const change of captured.review.changes) if (isInGitDir(change.path)) rejected.add(change.path)
348
+ const files = captured.review.changes.filter(change => !rejected.has(change.path)).map(change => change.path)
349
+ const material = await open.review.readTree(captured.tree, files)
350
+ if (!open.workspace) throw new RequestError(409, 'agent-workspace-unavailable')
243
351
  const lang = listDocuments(this.#options.config).find(doc => doc.dir === open.document)?.lang
244
352
  const steps = open.review.steps().map(step => `- ${step.label}`).slice(0, 20)
245
- const revision = await this.#options.revisions.commit({
246
- files,
247
- message: `${message?.trim() || commitSummary(files, lang)}${steps.length ? `\n\n${steps.join('\n')}` : ''}`,
248
- origin: { kind: 'agent', task: open.review.task, member: open.member },
249
- trailers: [[AGENT_SESSION_TRAILER, open.session], [TURN_TRAILER, `${open.turns.from}-${open.turns.to}`]],
250
- })
353
+ if (files.length) await this.#options.flush?.(listDocuments(this.#options.config).map(document => document.dir), open.member)
354
+ const release = await this.#options.locks.acquire('', lockHolder(open.session))
355
+ let revision
356
+ try {
357
+ revision = await this.#options.revisions.transaction(async () => {
358
+ signal?.throwIfAborted()
359
+ if ((await this.#inspect(open)).snapshot !== captured.snapshot) throw new RequestError(409, 'workspace-review-changed')
360
+ const selected = await open.review.prepareAccept([...rejected])
361
+ if (JSON.stringify(selected) !== JSON.stringify(files)) throw new RequestError(409, 'workspace-review-changed')
362
+ try { await open.review.assertTree(captured.tree, [...rejected]) }
363
+ catch { throw new RequestError(409, 'workspace-review-changed') }
364
+ signal?.throwIfAborted()
365
+ const prepared = open.workspace!.prepare(files, material)
366
+ await this.#options.revisions.checkpoint(files)
367
+ try {
368
+ open.workspace!.write(prepared.changes)
369
+ return await this.#options.revisions.commitWhileLocked({ paths: files, summary: message?.trim() || commitSummary(files, lang), body: steps.join('\n'), origin: { kind: 'agent', task: open.review.task, member: open.member }, trailers: [[AGENT_SESSION_TRAILER, open.session], [TURN_TRAILER, `${open.turns.from}-${open.turns.to}`]] })
370
+ } catch (error) { open.workspace!.write(prepared.restore); throw error }
371
+ })
372
+ } finally { release() }
251
373
  open.review.finish()
252
374
  const ended: ReviewEnd = { outcome: 'accepted', ...revision ? { revision } : {}, files }
253
375
  await this.#end(open, ended)
376
+ if (this.#workspaces.has(open.session)) await open.workspace.refresh()
254
377
  return ended
255
378
  }
256
379
 
257
- reject(document: string, body: { paths?: string[] }): Promise<ReviewUpdate> {
380
+ reject(document: string, body: { paths?: string[], expected?: string }, signal?: AbortSignal): Promise<ReviewUpdate> {
258
381
  return this.#serial(async () => {
259
- const open = this.#requireOpen(document)
382
+ const open = this.#requireOpen(document, body.expected)
383
+ if (open.awaitingDeltabox) throw new RequestError(409, 'workspace-review-running')
384
+ await this.#expected(open, body.expected, signal)
260
385
  if (body.paths) {
261
386
  await open.review.restoreFiles(body.paths)
262
387
  if ((await open.review.diff()).length > 0) return { document, review: await this.#publish(open) }
@@ -269,9 +394,11 @@ export class AgentSessionReviews {
269
394
  })
270
395
  }
271
396
 
272
- restore(document: string, body: { step: string }): Promise<ReviewSnapshot> {
397
+ restore(document: string, body: { step: string, expected?: string }, signal?: AbortSignal): Promise<ReviewSnapshot> {
273
398
  return this.#serial(async () => {
274
- const open = this.#requireOpen(document)
399
+ const open = this.#requireOpen(document, body.expected)
400
+ if (open.awaitingDeltabox) throw new RequestError(409, 'workspace-review-running')
401
+ await this.#expected(open, body.expected, signal)
275
402
  try {
276
403
  await open.review.restoreTo!(body.step)
277
404
  } catch (error) {
@@ -298,9 +425,10 @@ export class AgentSessionReviews {
298
425
  if (open) {
299
426
  clearTimeout(open.timer)
300
427
  open.review.suspend()
301
- open.release()
302
428
  }
303
429
  this.#open = undefined
430
+ for (const [session, workspace] of this.#workspaces) if (session !== open?.session) workspace.dispose()
431
+ this.#workspaces.clear()
304
432
  }
305
433
 
306
434
  #requireSession(document: string, session: string): OpenReview {
@@ -309,8 +437,9 @@ export class AgentSessionReviews {
309
437
  return open
310
438
  }
311
439
 
312
- #requireOpen(document: string): OpenReview {
440
+ #requireOpen(document: string, expected?: string): OpenReview {
313
441
  const open = this.#open
442
+ if (!open && expected !== undefined) throw new RequestError(409, 'workspace-review-changed')
314
443
  if (!open) throw new RequestError(404, `no review of ${document || '.'} is open`)
315
444
  return open
316
445
  }
@@ -318,7 +447,7 @@ export class AgentSessionReviews {
318
447
  #noteTurn(open: OpenReview, turn: number | undefined): void {
319
448
  if (turn === undefined || !Number.isInteger(turn) || turn < 0) return
320
449
  open.turns = { from: open.turns.from === 0 ? turn : Math.min(open.turns.from, turn), to: Math.max(open.turns.to, turn) }
321
- open.review.noteSession({ session: open.session, document: open.document, member: open.member, turns: open.turns, opened: open.opened })
450
+ open.review.noteSession({ session: open.session, document: open.document, member: open.member, turns: open.turns, opened: open.opened, backend: open.backend })
322
451
  }
323
452
 
324
453
  async #publish(open: OpenReview): Promise<ReviewSnapshot> {
@@ -331,7 +460,10 @@ export class AgentSessionReviews {
331
460
  async #end(open: OpenReview, ended: ReviewEnd): Promise<void> {
332
461
  clearTimeout(open.timer)
333
462
  this.#open = undefined
334
- open.release()
463
+ if (this.#retired.delete(open.session)) {
464
+ this.#workspaces.delete(open.session)
465
+ open.workspace?.dispose()
466
+ }
335
467
  this.#sendToWatchers({ document: open.document, ended })
336
468
  this.#emit({ type: 'review', document: open.document, session: open.session, ended })
337
469
  }
@@ -366,8 +498,19 @@ export class AgentSessionReviews {
366
498
  open.timer.unref?.()
367
499
  }
368
500
 
369
- #serial<T>(work: () => Promise<T>): Promise<T> {
370
- const next = this.#queue.then(work, work)
501
+ #serial<T>(work: () => Promise<T>, roots: false | (() => string[]) = () => this.#open?.workspace ? [this.#open.workspace.root] : []): Promise<T> {
502
+ const guarded = async () => {
503
+ const releases: (() => Promise<void>)[] = []
504
+ try {
505
+ if (roots && process.platform === 'darwin') {
506
+ for (const root of roots().sort()) releases.push(await acquireCandidateLease(root))
507
+ }
508
+ return await work()
509
+ } finally {
510
+ for (const release of releases.reverse()) await release()
511
+ }
512
+ }
513
+ const next = this.#queue.then(guarded, guarded)
371
514
  this.#queue = next.catch(() => undefined)
372
515
  return next
373
516
  }
@@ -0,0 +1,151 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { WindowsDependencies } from './windows-dependencies.ts'
4
+ import { existsSync, lstatSync, readFileSync, readlinkSync, realpathSync, rmSync } from 'node:fs'
5
+ import { cp, lstat, mkdir, mkdtemp, readFile, readlink, rm, symlink, writeFile } from 'node:fs/promises'
6
+ import { dirname, join, resolve } from 'node:path'
7
+ import { gitConfigArgs, gitEnvironment } from '@lincyaw/kernel'
8
+ import { isInside } from '@lincyaw/kernel/node'
9
+ import type { DocumentFileChange } from '@lincyaw/kernel'
10
+ import type { WorkspaceConfig } from '../config.ts'
11
+ import { RequestError } from '../errors.ts'
12
+ import { validateDocumentSource, versionOf } from '../source-editor.ts'
13
+ import { writeChanges } from '../writer.ts'
14
+ import { openLocalHistory } from '../local-history.ts'
15
+ import { Git } from '../git.ts'
16
+
17
+ interface FileStamp { version: string, executable?: boolean, link?: true }
18
+ export interface AgentWorkspaceRecord { root: string, original: string, base: Record<string, FileStamp> }
19
+
20
+ function git(root: string, args: string[]): Promise<string> {
21
+ return new Promise((done, fail) => execFile('git', [...gitConfigArgs(), ...args], { cwd: root, env: gitEnvironment(process.env), maxBuffer: 32 << 20 }, (error, out, stderr) => error ? fail(new Error(stderr || error.message)) : done(out)))
22
+ }
23
+
24
+ function stamp(file: string): FileStamp | undefined {
25
+ const stat = lstatSync(file, { throwIfNoEntry: false })
26
+ if (!stat) return
27
+ if (stat.isSymbolicLink()) return { version: versionOf(readlinkSync(file)), link: true }
28
+ if (!stat.isFile()) throw new RequestError(409, 'agent-source-type-changed')
29
+ return { version: versionOf(readFileSync(file)), ...stat.mode & 0o111 ? { executable: true } : {} }
30
+ }
31
+ const SANDBOX_STATE = new Set(['.deltabox', '.deltabox-lite-state'])
32
+ /**
33
+ * What a candidate copies of the author's listing: not the candidates themselves, not a sandbox's state (its live
34
+ * tree is a repository of its own), and not another repository inside the workspace, which git lists as `dir/`.
35
+ */
36
+ const isAuthorFile = (path: string) => !!path && !path.endsWith('/') && !path.startsWith('.presmium/agent-workspaces/')
37
+ && !path.split('/').some(part => SANDBOX_STATE.has(part))
38
+ const same = (a: FileStamp | undefined, b: FileStamp | undefined) => JSON.stringify(a) === JSON.stringify(b)
39
+ async function sourceStamp(file: string): Promise<FileStamp | undefined> {
40
+ let stat
41
+ try { stat = await lstat(file) } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; throw error }
42
+ if (stat.isSymbolicLink()) return { version: versionOf(await readlink(file)), link: true }
43
+ if (!stat.isFile()) throw new RequestError(409, 'agent-source-type-changed')
44
+ return { version: versionOf(await readFile(file)), ...stat.mode & 0o111 ? { executable: true } : {} }
45
+ }
46
+
47
+ /** An agent edits its own files; only a version-checked publication changes the author's workspace. */
48
+ export class AgentWorkspace {
49
+ readonly record: AgentWorkspaceRecord
50
+ readonly #config: WorkspaceConfig
51
+ #version = randomUUID()
52
+ readonly #dependencies = new WindowsDependencies()
53
+
54
+ private constructor(config: WorkspaceConfig, record: AgentWorkspaceRecord) {
55
+ this.#config = config
56
+ this.record = { ...record, root: realpathSync.native(record.root), original: realpathSync.native(record.original) }
57
+ }
58
+ get root(): string { return this.record.root }
59
+ get version(): string { return this.#version }
60
+ changed(): void { this.#version = randomUUID() }
61
+
62
+ /** Host restores invalidate a private view even when the author baseline did not move. */
63
+ writeCandidate(changes: DocumentFileChange[]): void {
64
+ if (!changes.length) return
65
+ this.changed()
66
+ writeChanges({ ...this.#config, root: this.root }, changes, true)
67
+ }
68
+
69
+ static async create(config: WorkspaceConfig): Promise<AgentWorkspace> {
70
+ const pool = join(config.root, '.presmium', 'agent-workspaces')
71
+ await mkdir(pool, { recursive: true })
72
+ await writeFile(join(pool, '.gitignore'), '*\n')
73
+ const root = join(await mkdtemp(join(pool, 'session-')), 'workspace')
74
+ await mkdir(root)
75
+ const workspace = new AgentWorkspace(config, { root, original: config.root, base: {} })
76
+ await git(root, ['init', '-q'])
77
+ await writeFile(join(root, '.git', 'info', 'exclude'), '.presmium/\nnode_modules/\ndist/\n.deltabox/\n.deltabox-lite-state/\n')
78
+ await workspace.refresh()
79
+ return workspace
80
+ }
81
+
82
+ static resume(config: WorkspaceConfig, record: AgentWorkspaceRecord): AgentWorkspace {
83
+ try {
84
+ const original = realpathSync.native(config.root)
85
+ const pool = realpathSync.native(join(original, '.presmium', 'agent-workspaces'))
86
+ const root = realpathSync.native(record.root)
87
+ if (!isInside(original, realpathSync.native(record.original)) || !isInside(realpathSync.native(record.original), original) || !isInside(root, pool) || isInside(pool, root) || !existsSync(join(root, '.git'))) throw new Error('Invalid candidate record')
88
+ } catch { throw new RequestError(409, 'agent-workspace-unavailable') }
89
+ return new AgentWorkspace(config, record)
90
+ }
91
+
92
+ async refresh(): Promise<boolean> {
93
+ const listing = ['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--', '.']
94
+ const listed = Git.isRepository(this.#config.root) ? await git(this.#config.root, listing) : await (await openLocalHistory(this.#config.root)).output(listing)
95
+ const paths = listed.split('\0').filter(isAuthorFile)
96
+ const next: Record<string, FileStamp> = {}
97
+ for (const path of new Set(paths)) {
98
+ const current = await sourceStamp(join(this.#config.root, path))
99
+ if (!current) continue
100
+ next[path] = current
101
+ if (same(current, this.record.base[path])) continue
102
+ const target = join(this.root, path)
103
+ if (same(await sourceStamp(target), current)) continue
104
+ this.changed()
105
+ await mkdir(dirname(target), { recursive: true })
106
+ await rm(target, { force: true, recursive: true })
107
+ await cp(join(this.#config.root, path), target, { dereference: false, verbatimSymlinks: true })
108
+ if (!same(await sourceStamp(join(this.#config.root, path)), current)) throw new RequestError(409, 'agent-source-changed', { paths: [path], next: 'The author changed a file while the candidate was refreshed. Read the current author files and retry.' })
109
+ }
110
+ for (const path of Object.keys(this.record.base)) if (!next[path]) { this.changed(); await rm(join(this.root, path), { force: true, recursive: true }) }
111
+ const changed = JSON.stringify(next) !== JSON.stringify(this.record.base)
112
+ this.record.base = next
113
+ const dependencyDirs = new Set(['', ...paths.filter(path => path.endsWith('package.json')).map(dirname)])
114
+ for (const dir of dependencyDirs) {
115
+ let source = join(this.#config.root, dir)
116
+ while (!existsSync(join(source, 'node_modules')) && dirname(source) !== source) source = dirname(source)
117
+ const target = join(this.root, dir, 'node_modules')
118
+ if (existsSync(join(source, 'node_modules')) && existsSync(dirname(target))) {
119
+ if (process.platform === 'win32') await this.#dependencies.sync(source, target, dirname(this.root), () => this.changed())
120
+ else if (!existsSync(target)) { this.changed(); await symlink(join(source, 'node_modules'), target, 'dir') }
121
+ }
122
+ }
123
+ if (changed || !(await git(this.root, ['rev-parse', '--verify', 'HEAD']).catch(() => '')).trim()) {
124
+ this.changed()
125
+ await git(this.root, ['add', '-A'])
126
+ await git(this.root, ['-c', 'user.name=Presmium', '-c', 'user.email=presmium@localhost', 'commit', '-q', '--allow-empty', '-m', 'Author workspace snapshot'])
127
+ }
128
+ return changed
129
+ }
130
+
131
+ /** Caller holds the original workspace's mutation lock and history transaction. */
132
+ prepare(paths: string[], fixed?: DocumentFileChange[]): { changes: DocumentFileChange[], restore: DocumentFileChange[] } {
133
+ if (fixed && (fixed.length !== paths.length || fixed.some((change, index) => change.path !== paths[index]))) throw new RequestError(409, 'workspace-review-changed')
134
+ const conflicts = paths.filter(path => !same(stamp(join(this.#config.root, path)), this.record.base[path]))
135
+ if (conflicts.length) throw new RequestError(409, 'agent-source-changed', { paths: conflicts, next: 'The author changed these files. Read the current author files again and retry your change. Nothing was published.' })
136
+ const changes: DocumentFileChange[] = [], restore: DocumentFileChange[] = []
137
+ for (const [index, path] of paths.entries()) {
138
+ if (!path || path.split('/').some(part => !part || part === '.' || part === '..' || part === '.git') || path.startsWith('.presmium/agent-workspaces/')) throw new RequestError(403, 'agent-source-path-invalid')
139
+ const before = stamp(join(this.#config.root, path)), after = fixed ? undefined : stamp(join(this.root, path))
140
+ const read = (root: string, value: FileStamp | undefined): DocumentFileChange => !value ? { path, remove: true }
141
+ : value.link ? { path, link: readlinkSync(join(root, path)) } : { path, content: readFileSync(join(root, path)), ...value.executable ? { executable: true } : {} }
142
+ const change = fixed?.[index] ?? read(this.root, after)
143
+ if ('content' in change) validateDocumentSource(path, Buffer.from(change.content).toString('utf8'), before && !before.link ? readFileSync(join(this.#config.root, path)) : undefined)
144
+ changes.push(change); restore.push(read(this.#config.root, before))
145
+ }
146
+ return { changes, restore }
147
+ }
148
+
149
+ write(changes: DocumentFileChange[]): void { writeChanges(this.#config, changes, true) }
150
+ dispose(): void { rmSync(dirname(this.root), { recursive: true, force: true }) }
151
+ }