@lincyaw/workspace 1.0.0-rc.8 → 1.0.0-rc.80
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/package.json +7 -5
- package/src/node/authoring-clients.ts +73 -20
- package/src/node/authoring-windows.ts +165 -0
- package/src/node/build.ts +54 -24
- package/src/node/capture.ts +356 -0
- package/src/node/config.ts +1 -0
- package/src/node/document-audio.ts +60 -41
- package/src/node/document-authoring.ts +7 -1
- package/src/node/document-images.ts +20 -10
- package/src/node/document-voice.ts +100 -6
- package/src/node/locks.ts +12 -0
- package/src/node/media-upload-messages.ts +4 -0
- package/src/node/media-upload-page.ts +57 -0
- package/src/node/media-upload.css +4 -0
- package/src/node/media-uploads.ts +116 -0
- package/src/node/projects.ts +18 -3
- package/src/node/review/agent-session-reviews.ts +167 -60
- package/src/node/review/agent-workspace.ts +107 -0
- package/src/node/review/git-review.ts +41 -11
- package/src/node/review/record.ts +4 -1
- package/src/node/review/routes.ts +7 -0
- package/src/node/review/workspace-review.ts +87 -0
- package/src/node/revision-files.ts +54 -0
- package/src/node/revisions.ts +217 -56
- package/src/node/routes.ts +8 -57
- package/src/node/serve.ts +93 -20
- package/src/node/site.ts +1 -1
- package/src/node/source-editor.ts +35 -19
- package/src/node/speech-settings.ts +6 -8
- package/src/node/templates.ts +2 -2
- package/src/node/workbench-api.ts +14 -3
- package/src/node/workspace-changes.ts +130 -0
- package/src/node/workspace-source.ts +133 -0
- package/src/node/writer.ts +3 -3
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto'
|
|
2
|
-
import { existsSync
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { existsSync } from 'node:fs'
|
|
3
3
|
import { join } from 'node:path'
|
|
4
|
-
import {
|
|
5
|
-
import type { DocumentFiles, Logger, Member, ReviewEnd, ReviewSnapshot, ReviewUpdate } from '@lincyaw/kernel'
|
|
4
|
+
import { errorMessage, pushStream } from '@lincyaw/kernel'
|
|
5
|
+
import type { DocumentFiles, Logger, Member, ReviewChange, ReviewEnd, ReviewSnapshot, ReviewUpdate } from '@lincyaw/kernel'
|
|
6
6
|
import { trailers } from '../../domain/commit-message.ts'
|
|
7
7
|
import type { WorkspaceConfig } from '../config.ts'
|
|
8
8
|
import { listDocuments } from '../config.ts'
|
|
@@ -11,12 +11,12 @@ import { lockedError } from '../locks.ts'
|
|
|
11
11
|
import type { DocumentLocks } from '../locks.ts'
|
|
12
12
|
import type { Revisions } from '../revisions.ts'
|
|
13
13
|
import { writeChanges } from '../writer.ts'
|
|
14
|
-
import {
|
|
14
|
+
import { openGitReview, pendingAgentSessionReview, resumeGitReview } from './git-review.ts'
|
|
15
15
|
import type { GitReview } from './git-review.ts'
|
|
16
16
|
import { readRecord } from './record.ts'
|
|
17
17
|
import type { ReviewRecord } from './record.ts'
|
|
18
18
|
import { rollBackLeftTaskReview } from './task-reviews.ts'
|
|
19
|
-
import {
|
|
19
|
+
import { AgentWorkspace } from './agent-workspace.ts'
|
|
20
20
|
|
|
21
21
|
export const AGENT_SESSION_TRAILER = 'Presmium-Session'
|
|
22
22
|
export const TURN_TRAILER = 'Presmium-Turn'
|
|
@@ -32,6 +32,7 @@ export interface AgentSessionReviewsOptions {
|
|
|
32
32
|
/** How a plugin's task writes, for rolling back the tasks a process left. */
|
|
33
33
|
files?: DocumentFiles
|
|
34
34
|
log: Logger
|
|
35
|
+
flush?(documents: string[], member: Member): Promise<void>
|
|
35
36
|
}
|
|
36
37
|
|
|
37
38
|
interface OpenReview {
|
|
@@ -42,7 +43,7 @@ interface OpenReview {
|
|
|
42
43
|
turns: { from: number, to: number }
|
|
43
44
|
running: boolean
|
|
44
45
|
opened: string
|
|
45
|
-
|
|
46
|
+
workspace?: AgentWorkspace
|
|
46
47
|
timer?: ReturnType<typeof setTimeout>
|
|
47
48
|
}
|
|
48
49
|
|
|
@@ -69,21 +70,21 @@ function commitSummary(files: string[], lang: string | undefined): string {
|
|
|
69
70
|
}
|
|
70
71
|
|
|
71
72
|
/**
|
|
72
|
-
*
|
|
73
|
-
*
|
|
73
|
+
* A dsh session reviews its private candidate; only publication briefly locks the author's workspace.
|
|
74
|
+
* A review that no page watches drops its candidate changes after the configured time.
|
|
74
75
|
*/
|
|
75
76
|
export class AgentSessionReviews {
|
|
76
77
|
readonly #options: AgentSessionReviewsOptions
|
|
77
78
|
#open?: OpenReview
|
|
78
79
|
#queue: Promise<unknown> = Promise.resolve()
|
|
79
|
-
readonly #workspaceFiles: DocumentFiles
|
|
80
80
|
readonly #watchers = new Set<(update: ReviewUpdate) => void>()
|
|
81
81
|
readonly #listeners = new Set<(event: ReviewEvent) => void>()
|
|
82
82
|
#closed = false
|
|
83
|
+
readonly #workspaces = new Map<string, AgentWorkspace>()
|
|
84
|
+
readonly #retired = new Set<string>()
|
|
83
85
|
|
|
84
86
|
constructor(options: AgentSessionReviewsOptions) {
|
|
85
87
|
this.#options = options
|
|
86
|
-
this.#workspaceFiles = { write: async changes => writeChanges(options.config, changes, true) }
|
|
87
88
|
}
|
|
88
89
|
|
|
89
90
|
/** Takes up the reviews a process that has ended left: resumes its agent session's review, rolls back its tasks' reviews. */
|
|
@@ -102,6 +103,7 @@ export class AgentSessionReviews {
|
|
|
102
103
|
}
|
|
103
104
|
await rollBackLeftTaskReview(this.#options, document)
|
|
104
105
|
} catch (error) {
|
|
106
|
+
if (readRecord(scopeDir)?.session) throw error
|
|
105
107
|
log.warn(`the review left in ${document || '.'} was not taken up: ${errorMessage(error)}`)
|
|
106
108
|
}
|
|
107
109
|
}
|
|
@@ -110,30 +112,88 @@ export class AgentSessionReviews {
|
|
|
110
112
|
async #resume(pending: ReviewRecord): Promise<void> {
|
|
111
113
|
const { config, log } = this.#options
|
|
112
114
|
const session = pending.session!
|
|
113
|
-
const
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
throw error
|
|
124
|
-
}
|
|
115
|
+
const workspace = pending.workspace ? AgentWorkspace.resume(config, pending.workspace) : undefined
|
|
116
|
+
const root = workspace?.root ?? config.root
|
|
117
|
+
const review = await resumeGitReview(pending, { workspaceRoot: root, files: { write: async changes => writeChanges({ ...config, root }, changes, true) }, onRestore: paths => log.warn(`session ${session.session}: the agent changed the git directory, put back: ${paths.join(', ')}`) })
|
|
118
|
+
if ((await review.diff()).length === 0) { await review.close(); workspace?.dispose(); return }
|
|
119
|
+
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.') }
|
|
120
|
+
this.#workspaces.set(session.session, workspace)
|
|
121
|
+
const open: OpenReview = { review, document: session.document, session: session.session, member: session.member, turns: session.turns, running: false, opened: session.opened, workspace }
|
|
122
|
+
this.#open = open
|
|
123
|
+
log.info(`the review of session ${session.session} in ${session.document || '.'} (turns ${session.turns.from}-${session.turns.to}) waits for its author again`)
|
|
124
|
+
this.#scheduleRollback(open)
|
|
125
125
|
}
|
|
126
126
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
127
|
+
workspace(session: string): Promise<{ root: string }> {
|
|
128
|
+
return this.#serial(async () => {
|
|
129
|
+
this.#retired.delete(session)
|
|
130
|
+
let workspace = this.#workspaces.get(session)
|
|
131
|
+
if (!workspace) { workspace = await AgentWorkspace.create(this.#options.config); this.#workspaces.set(session, workspace) }
|
|
132
|
+
return { root: workspace.root }
|
|
133
|
+
})
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
refreshWorkspace(session: string): Promise<void> {
|
|
137
|
+
return this.#serial(async () => {
|
|
138
|
+
const workspace = this.#workspaces.get(session)
|
|
139
|
+
if (workspace && this.#open?.session !== session) await workspace.refresh()
|
|
140
|
+
})
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
closeWorkspace(session: string): Promise<void> {
|
|
144
|
+
return this.#serial(async () => {
|
|
145
|
+
if (this.#open?.session === session) { this.#retired.add(session); return }
|
|
146
|
+
const workspace = this.#workspaces.get(session)
|
|
147
|
+
this.#workspaces.delete(session)
|
|
148
|
+
workspace?.dispose()
|
|
149
|
+
})
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
snapshot(): Promise<ReviewSnapshot | undefined> {
|
|
153
|
+
return this.#serial(async () => this.#open && await this.#snapshotOf(this.#open))
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
inspect(): Promise<{ snapshot: string, review: ReviewSnapshot } | undefined> {
|
|
157
|
+
return this.#serial(async () => { if (!this.#open) return; const { snapshot, review } = await this.#inspect(this.#open); return { snapshot, review } })
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async #inspect(open: OpenReview) {
|
|
161
|
+
const { tree, version, changes } = await open.review.inspect()
|
|
162
|
+
const review = await this.#snapshotOf(open, changes)
|
|
163
|
+
review.steps = review.steps.map(step => ({ ...step, changes: step.changes.map(({ diff: _diff, ...change }) => change) }))
|
|
164
|
+
return { tree, review, snapshot: createHash('sha256').update(JSON.stringify([version, review])).digest('hex') }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async #expected(open: OpenReview, expected: string | undefined, signal?: AbortSignal): Promise<void> {
|
|
168
|
+
signal?.throwIfAborted()
|
|
169
|
+
if (expected === undefined) return
|
|
170
|
+
if (open.running) throw new RequestError(409, 'workspace-review-running')
|
|
171
|
+
if ((await this.#inspect(open)).snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
|
|
172
|
+
signal?.throwIfAborted()
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
check(expected: string): Promise<void> {
|
|
176
|
+
return this.#serial(async () => this.#expected(this.#requireOpen('', expected), expected))
|
|
130
177
|
}
|
|
131
178
|
|
|
132
|
-
|
|
179
|
+
readDiff(expected: string, path: string, step?: string): Promise<ReviewChange | undefined> {
|
|
180
|
+
return this.#serial(async () => {
|
|
181
|
+
const open = this.#requireOpen('', expected)
|
|
182
|
+
const current = await this.#inspect(open)
|
|
183
|
+
if (current.snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
|
|
184
|
+
const files = step === undefined ? current.review.changes : current.review.steps.find(value => value.id === step)?.changes
|
|
185
|
+
if (!files?.some(file => file.path === path)) return
|
|
186
|
+
const value = await open.review.diffFile(path, step)
|
|
187
|
+
if ((await this.#inspect(open)).snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
|
|
188
|
+
return value
|
|
189
|
+
})
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async #snapshotOf(open: OpenReview, changes?: ReviewChange[]): Promise<ReviewSnapshot> {
|
|
133
193
|
return {
|
|
134
194
|
id: open.review.task,
|
|
135
195
|
document: open.document,
|
|
136
|
-
engine:
|
|
196
|
+
engine: 'git-candidate',
|
|
137
197
|
session: open.session,
|
|
138
198
|
holder: lockHolder(open.session),
|
|
139
199
|
turns: { ...open.turns },
|
|
@@ -141,7 +201,7 @@ export class AgentSessionReviews {
|
|
|
141
201
|
mode: reviewSettings(this.#options.config).mode,
|
|
142
202
|
opened: open.opened,
|
|
143
203
|
steps: [...open.review.steps()],
|
|
144
|
-
changes: await open.review.diff(),
|
|
204
|
+
changes: changes ?? await open.review.diff(),
|
|
145
205
|
}
|
|
146
206
|
}
|
|
147
207
|
|
|
@@ -173,24 +233,26 @@ export class AgentSessionReviews {
|
|
|
173
233
|
let open = this.#open
|
|
174
234
|
if (open && open.session !== body.session) throw lockedError(document, lockHolder(open.session))
|
|
175
235
|
if (!open) {
|
|
176
|
-
const release = this.#options.locks.claim('', lockHolder(body.session))
|
|
177
|
-
if (!release) throw lockedError(document, this.#options.locks.holder('')!)
|
|
178
236
|
const { config, log } = this.#options
|
|
179
237
|
const turn = body.turn ?? 0
|
|
180
238
|
const opened = new Date().toISOString()
|
|
239
|
+
let workspace = this.#workspaces.get(body.session)
|
|
240
|
+
if (!workspace) { workspace = await AgentWorkspace.create(config); this.#workspaces.set(body.session, workspace) }
|
|
241
|
+
const root = workspace.root
|
|
181
242
|
try {
|
|
182
243
|
const review = await openGitReview({
|
|
183
|
-
workspaceRoot:
|
|
184
|
-
scopeDir:
|
|
244
|
+
workspaceRoot: root,
|
|
245
|
+
scopeDir: root,
|
|
246
|
+
recordRoot: config.root,
|
|
247
|
+
workspace: workspace.record,
|
|
185
248
|
task: randomUUID(),
|
|
186
|
-
files:
|
|
249
|
+
files: { write: async changes => writeChanges({ ...config, root }, changes, true) },
|
|
187
250
|
onRestore: paths => log.warn(`session ${body.session}: the agent changed the git directory, put back: ${paths.join(', ')}`),
|
|
188
251
|
warn: message => log.warn(`session ${body.session}: ${message}`),
|
|
189
252
|
session: { session: body.session, document, member, turns: { from: turn, to: turn }, opened },
|
|
190
253
|
})
|
|
191
|
-
open = { review, document, session: body.session, member, turns: { from: turn, to: turn }, running: true, opened,
|
|
254
|
+
open = { review, document, session: body.session, member, turns: { from: turn, to: turn }, running: true, opened, workspace }
|
|
192
255
|
} catch (error) {
|
|
193
|
-
release()
|
|
194
256
|
throw new RequestError(409, `the review of ${document || '.'} did not open: ${errorMessage(error)}`)
|
|
195
257
|
}
|
|
196
258
|
this.#open = open
|
|
@@ -204,11 +266,24 @@ export class AgentSessionReviews {
|
|
|
204
266
|
|
|
205
267
|
step(document: string, body: { session: string, turn?: number, label?: string, tool?: string, end?: boolean }): Promise<ReviewSnapshot | undefined> {
|
|
206
268
|
return this.#serial(async () => {
|
|
269
|
+
if (!this.#open && body.end) return undefined
|
|
207
270
|
const open = this.#requireSession(document, body.session)
|
|
208
271
|
this.#noteTurn(open, body.turn)
|
|
209
272
|
if (body.label) await open.review.step(body.label, body.tool)
|
|
210
273
|
if (!body.end) {
|
|
211
|
-
open.running =
|
|
274
|
+
open.running = false
|
|
275
|
+
if (reviewSettings(this.#options.config).mode === 'auto') {
|
|
276
|
+
try { await this.#accept(open, [], undefined) }
|
|
277
|
+
catch (error) {
|
|
278
|
+
if (error instanceof RequestError && error.message === 'agent-source-changed') {
|
|
279
|
+
await open.review.close()
|
|
280
|
+
await this.#end(open, { outcome: 'rejected', files: [] })
|
|
281
|
+
if (this.#workspaces.has(open.session)) await open.workspace!.refresh()
|
|
282
|
+
}
|
|
283
|
+
throw error
|
|
284
|
+
}
|
|
285
|
+
return undefined
|
|
286
|
+
}
|
|
212
287
|
return await this.#publish(open)
|
|
213
288
|
}
|
|
214
289
|
open.running = false
|
|
@@ -227,36 +302,62 @@ export class AgentSessionReviews {
|
|
|
227
302
|
})
|
|
228
303
|
}
|
|
229
304
|
|
|
230
|
-
accept(document: string, body: { reject?: string[], message?: string }): Promise<ReviewEnd> {
|
|
231
|
-
return this.#serial(() =>
|
|
305
|
+
accept(document: string, body: { reject?: string[], message?: string, expected?: string }, signal?: AbortSignal): Promise<ReviewEnd> {
|
|
306
|
+
return this.#serial(async () => {
|
|
307
|
+
const open = this.#requireOpen(document, body.expected)
|
|
308
|
+
await this.#expected(open, body.expected, signal)
|
|
309
|
+
try { return await this.#accept(open, body.reject ?? [], body.message, signal, body.expected) }
|
|
310
|
+
catch (error) {
|
|
311
|
+
if (error instanceof RequestError && error.message === 'agent-source-changed') {
|
|
312
|
+
await open.review.close()
|
|
313
|
+
await this.#end(open, { outcome: 'rejected', files: [] })
|
|
314
|
+
if (this.#workspaces.has(open.session)) await open.workspace!.refresh()
|
|
315
|
+
}
|
|
316
|
+
throw error
|
|
317
|
+
}
|
|
318
|
+
})
|
|
232
319
|
}
|
|
233
320
|
|
|
234
|
-
async #accept(open: OpenReview, reject: string[], message: string | undefined): Promise<ReviewEnd> {
|
|
321
|
+
async #accept(open: OpenReview, reject: string[], message: string | undefined, signal?: AbortSignal, expected?: string): Promise<ReviewEnd> {
|
|
322
|
+
const captured = await this.#inspect(open)
|
|
323
|
+
if (expected !== undefined && captured.snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
|
|
235
324
|
const rejected = new Set(reject)
|
|
236
|
-
for (const change of
|
|
237
|
-
const files =
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
const file = join(this.#options.config.root, path)
|
|
241
|
-
if (existsSync(file)) validateDocumentSource(path, readFileSync(file, 'utf8'))
|
|
242
|
-
}
|
|
325
|
+
for (const change of captured.review.changes) if (isInGitDir(change.path)) rejected.add(change.path)
|
|
326
|
+
const files = captured.review.changes.filter(change => !rejected.has(change.path)).map(change => change.path)
|
|
327
|
+
const material = await open.review.readTree(captured.tree, files)
|
|
328
|
+
if (!open.workspace) throw new RequestError(409, 'agent-workspace-unavailable')
|
|
243
329
|
const lang = listDocuments(this.#options.config).find(doc => doc.dir === open.document)?.lang
|
|
244
330
|
const steps = open.review.steps().map(step => `- ${step.label}`).slice(0, 20)
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
331
|
+
if (files.length) await this.#options.flush?.(listDocuments(this.#options.config).map(document => document.dir), open.member)
|
|
332
|
+
const release = await this.#options.locks.acquire('', lockHolder(open.session))
|
|
333
|
+
let revision
|
|
334
|
+
try {
|
|
335
|
+
revision = await this.#options.revisions.transaction(async () => {
|
|
336
|
+
signal?.throwIfAborted()
|
|
337
|
+
if ((await this.#inspect(open)).snapshot !== captured.snapshot) throw new RequestError(409, 'workspace-review-changed')
|
|
338
|
+
const selected = await open.review.prepareAccept([...rejected])
|
|
339
|
+
if (JSON.stringify(selected) !== JSON.stringify(files)) throw new RequestError(409, 'workspace-review-changed')
|
|
340
|
+
try { await open.review.assertTree(captured.tree, [...rejected]) }
|
|
341
|
+
catch { throw new RequestError(409, 'workspace-review-changed') }
|
|
342
|
+
signal?.throwIfAborted()
|
|
343
|
+
const prepared = open.workspace!.prepare(files, material)
|
|
344
|
+
try {
|
|
345
|
+
open.workspace!.write(prepared.changes)
|
|
346
|
+
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}`]] })
|
|
347
|
+
} catch (error) { open.workspace!.write(prepared.restore); throw error }
|
|
348
|
+
})
|
|
349
|
+
} finally { release() }
|
|
251
350
|
open.review.finish()
|
|
252
351
|
const ended: ReviewEnd = { outcome: 'accepted', ...revision ? { revision } : {}, files }
|
|
253
352
|
await this.#end(open, ended)
|
|
353
|
+
if (this.#workspaces.has(open.session)) await open.workspace.refresh()
|
|
254
354
|
return ended
|
|
255
355
|
}
|
|
256
356
|
|
|
257
|
-
reject(document: string, body: { paths?: string[] }): Promise<ReviewUpdate> {
|
|
357
|
+
reject(document: string, body: { paths?: string[], expected?: string }, signal?: AbortSignal): Promise<ReviewUpdate> {
|
|
258
358
|
return this.#serial(async () => {
|
|
259
|
-
const open = this.#requireOpen(document)
|
|
359
|
+
const open = this.#requireOpen(document, body.expected)
|
|
360
|
+
await this.#expected(open, body.expected, signal)
|
|
260
361
|
if (body.paths) {
|
|
261
362
|
await open.review.restoreFiles(body.paths)
|
|
262
363
|
if ((await open.review.diff()).length > 0) return { document, review: await this.#publish(open) }
|
|
@@ -269,9 +370,10 @@ export class AgentSessionReviews {
|
|
|
269
370
|
})
|
|
270
371
|
}
|
|
271
372
|
|
|
272
|
-
restore(document: string, body: { step: string }): Promise<ReviewSnapshot> {
|
|
373
|
+
restore(document: string, body: { step: string, expected?: string }, signal?: AbortSignal): Promise<ReviewSnapshot> {
|
|
273
374
|
return this.#serial(async () => {
|
|
274
|
-
const open = this.#requireOpen(document)
|
|
375
|
+
const open = this.#requireOpen(document, body.expected)
|
|
376
|
+
await this.#expected(open, body.expected, signal)
|
|
275
377
|
try {
|
|
276
378
|
await open.review.restoreTo!(body.step)
|
|
277
379
|
} catch (error) {
|
|
@@ -298,9 +400,10 @@ export class AgentSessionReviews {
|
|
|
298
400
|
if (open) {
|
|
299
401
|
clearTimeout(open.timer)
|
|
300
402
|
open.review.suspend()
|
|
301
|
-
open.release()
|
|
302
403
|
}
|
|
303
404
|
this.#open = undefined
|
|
405
|
+
for (const [session, workspace] of this.#workspaces) if (session !== open?.session) workspace.dispose()
|
|
406
|
+
this.#workspaces.clear()
|
|
304
407
|
}
|
|
305
408
|
|
|
306
409
|
#requireSession(document: string, session: string): OpenReview {
|
|
@@ -309,8 +412,9 @@ export class AgentSessionReviews {
|
|
|
309
412
|
return open
|
|
310
413
|
}
|
|
311
414
|
|
|
312
|
-
#requireOpen(document: string): OpenReview {
|
|
415
|
+
#requireOpen(document: string, expected?: string): OpenReview {
|
|
313
416
|
const open = this.#open
|
|
417
|
+
if (!open && expected !== undefined) throw new RequestError(409, 'workspace-review-changed')
|
|
314
418
|
if (!open) throw new RequestError(404, `no review of ${document || '.'} is open`)
|
|
315
419
|
return open
|
|
316
420
|
}
|
|
@@ -331,7 +435,10 @@ export class AgentSessionReviews {
|
|
|
331
435
|
async #end(open: OpenReview, ended: ReviewEnd): Promise<void> {
|
|
332
436
|
clearTimeout(open.timer)
|
|
333
437
|
this.#open = undefined
|
|
334
|
-
open.
|
|
438
|
+
if (this.#retired.delete(open.session)) {
|
|
439
|
+
this.#workspaces.delete(open.session)
|
|
440
|
+
open.workspace?.dispose()
|
|
441
|
+
}
|
|
335
442
|
this.#sendToWatchers({ document: open.document, ended })
|
|
336
443
|
this.#emit({ type: 'review', document: open.document, session: open.session, ended })
|
|
337
444
|
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import { existsSync, lstatSync, readFileSync, readlinkSync, rmSync } from 'node:fs'
|
|
3
|
+
import { cp, lstat, mkdir, mkdtemp, readFile, readlink, rm, symlink, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { dirname, join, resolve } from 'node:path'
|
|
5
|
+
import { gitConfigArgs, gitEnvironment } from '@lincyaw/kernel'
|
|
6
|
+
import type { DocumentFileChange } from '@lincyaw/kernel'
|
|
7
|
+
import type { WorkspaceConfig } from '../config.ts'
|
|
8
|
+
import { RequestError } from '../errors.ts'
|
|
9
|
+
import { validateDocumentSource, versionOf } from '../source-editor.ts'
|
|
10
|
+
import { writeChanges } from '../writer.ts'
|
|
11
|
+
|
|
12
|
+
interface FileStamp { version: string, executable?: boolean, link?: true }
|
|
13
|
+
export interface AgentWorkspaceRecord { root: string, original: string, base: Record<string, FileStamp> }
|
|
14
|
+
|
|
15
|
+
function git(root: string, args: string[]): Promise<string> {
|
|
16
|
+
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)))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function stamp(file: string): FileStamp | undefined {
|
|
20
|
+
const stat = lstatSync(file, { throwIfNoEntry: false })
|
|
21
|
+
if (!stat) return
|
|
22
|
+
if (stat.isSymbolicLink()) return { version: versionOf(readlinkSync(file)), link: true }
|
|
23
|
+
if (!stat.isFile()) throw new RequestError(409, 'agent-source-type-changed')
|
|
24
|
+
return { version: versionOf(readFileSync(file)), ...stat.mode & 0o111 ? { executable: true } : {} }
|
|
25
|
+
}
|
|
26
|
+
const same = (a: FileStamp | undefined, b: FileStamp | undefined) => JSON.stringify(a) === JSON.stringify(b)
|
|
27
|
+
async function sourceStamp(file: string): Promise<FileStamp | undefined> {
|
|
28
|
+
let stat
|
|
29
|
+
try { stat = await lstat(file) } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; throw error }
|
|
30
|
+
if (stat.isSymbolicLink()) return { version: versionOf(await readlink(file)), link: true }
|
|
31
|
+
if (!stat.isFile()) throw new RequestError(409, 'agent-source-type-changed')
|
|
32
|
+
return { version: versionOf(await readFile(file)), ...stat.mode & 0o111 ? { executable: true } : {} }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** An agent edits its own files; only a version-checked publication changes the author's workspace. */
|
|
36
|
+
export class AgentWorkspace {
|
|
37
|
+
readonly record: AgentWorkspaceRecord
|
|
38
|
+
readonly #config: WorkspaceConfig
|
|
39
|
+
|
|
40
|
+
private constructor(config: WorkspaceConfig, record: AgentWorkspaceRecord) { this.#config = config; this.record = record }
|
|
41
|
+
get root(): string { return this.record.root }
|
|
42
|
+
|
|
43
|
+
static async create(config: WorkspaceConfig): Promise<AgentWorkspace> {
|
|
44
|
+
const pool = join(config.root, '.presmium', 'agent-workspaces')
|
|
45
|
+
await mkdir(pool, { recursive: true })
|
|
46
|
+
await writeFile(join(pool, '.gitignore'), '*\n')
|
|
47
|
+
const root = join(await mkdtemp(join(pool, 'session-')), 'workspace')
|
|
48
|
+
await mkdir(root)
|
|
49
|
+
const workspace = new AgentWorkspace(config, { root, original: config.root, base: {} })
|
|
50
|
+
await git(root, ['init', '-q'])
|
|
51
|
+
await workspace.refresh()
|
|
52
|
+
return workspace
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
static resume(config: WorkspaceConfig, record: AgentWorkspaceRecord): AgentWorkspace {
|
|
56
|
+
if (resolve(record.original) !== config.root || !resolve(record.root).startsWith(`${join(config.root, '.presmium', 'agent-workspaces')}/`) || !existsSync(join(record.root, '.git'))) throw new RequestError(409, 'agent-workspace-unavailable')
|
|
57
|
+
return new AgentWorkspace(config, record)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async refresh(): Promise<void> {
|
|
61
|
+
const paths = (await git(this.#config.root, ['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--', '.'])).split('\0').filter(path => path && !path.startsWith('.presmium/agent-workspaces/'))
|
|
62
|
+
const next: Record<string, FileStamp> = {}
|
|
63
|
+
for (const path of new Set(paths)) {
|
|
64
|
+
const current = await sourceStamp(join(this.#config.root, path))
|
|
65
|
+
if (!current) continue
|
|
66
|
+
next[path] = current
|
|
67
|
+
const target = join(this.root, path)
|
|
68
|
+
if (same(await sourceStamp(target), current)) continue
|
|
69
|
+
await mkdir(dirname(target), { recursive: true })
|
|
70
|
+
await rm(target, { force: true, recursive: true })
|
|
71
|
+
await cp(join(this.#config.root, path), target, { dereference: false, verbatimSymlinks: true })
|
|
72
|
+
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.' })
|
|
73
|
+
}
|
|
74
|
+
for (const path of Object.keys(this.record.base)) if (!next[path]) await rm(join(this.root, path), { force: true, recursive: true })
|
|
75
|
+
this.record.base = next
|
|
76
|
+
const dependencyDirs = new Set(['', ...paths.filter(path => path.endsWith('package.json')).map(dirname)])
|
|
77
|
+
for (const dir of dependencyDirs) {
|
|
78
|
+
let source = join(this.#config.root, dir)
|
|
79
|
+
while (!existsSync(join(source, 'node_modules')) && dirname(source) !== source) source = dirname(source)
|
|
80
|
+
const target = join(this.root, dir, 'node_modules')
|
|
81
|
+
if (existsSync(join(source, 'node_modules')) && !existsSync(target) && existsSync(dirname(target))) await symlink(join(source, 'node_modules'), target, 'dir')
|
|
82
|
+
}
|
|
83
|
+
await git(this.root, ['add', '-A'])
|
|
84
|
+
await git(this.root, ['-c', 'user.name=Presmium', '-c', 'user.email=presmium@localhost', 'commit', '-q', '--allow-empty', '-m', 'Author workspace snapshot'])
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Caller holds the original workspace's mutation lock and history transaction. */
|
|
88
|
+
prepare(paths: string[], fixed?: DocumentFileChange[]): { changes: DocumentFileChange[], restore: DocumentFileChange[] } {
|
|
89
|
+
if (fixed && (fixed.length !== paths.length || fixed.some((change, index) => change.path !== paths[index]))) throw new RequestError(409, 'workspace-review-changed')
|
|
90
|
+
const conflicts = paths.filter(path => !same(stamp(join(this.#config.root, path)), this.record.base[path]))
|
|
91
|
+
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.' })
|
|
92
|
+
const changes: DocumentFileChange[] = [], restore: DocumentFileChange[] = []
|
|
93
|
+
for (const [index, path] of paths.entries()) {
|
|
94
|
+
if (!path || path.split('/').some(part => !part || part === '.' || part === '..' || part === '.git') || path.startsWith('.presmium/agent-workspaces/')) throw new RequestError(403, 'agent-source-path-invalid')
|
|
95
|
+
const before = stamp(join(this.#config.root, path)), after = fixed ? undefined : stamp(join(this.root, path))
|
|
96
|
+
const read = (root: string, value: FileStamp | undefined): DocumentFileChange => !value ? { path, remove: true }
|
|
97
|
+
: value.link ? { path, link: readlinkSync(join(root, path)) } : { path, content: readFileSync(join(root, path)), ...value.executable ? { executable: true } : {} }
|
|
98
|
+
const change = fixed?.[index] ?? read(this.root, after)
|
|
99
|
+
if ('content' in change) validateDocumentSource(path, Buffer.from(change.content).toString('utf8'), before && !before.link ? readFileSync(join(this.#config.root, path)) : undefined)
|
|
100
|
+
changes.push(change); restore.push(read(this.#config.root, before))
|
|
101
|
+
}
|
|
102
|
+
return { changes, restore }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
write(changes: DocumentFileChange[]): void { writeChanges(this.#config, changes, true) }
|
|
106
|
+
dispose(): void { rmSync(dirname(this.root), { recursive: true, force: true }) }
|
|
107
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { execFile } from 'node:child_process'
|
|
2
|
+
import { createHash } from 'node:crypto'
|
|
2
3
|
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmdirSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
4
|
import { tmpdir } from 'node:os'
|
|
4
5
|
import { dirname, join, relative, resolve, sep } from 'node:path'
|
|
@@ -12,6 +13,10 @@ import type { AgentSessionRecord, ReviewRecord } from './record.ts'
|
|
|
12
13
|
|
|
13
14
|
export interface GitReview extends ChangeReview {
|
|
14
15
|
readonly task: string
|
|
16
|
+
inspect(details?: boolean): Promise<{ tree: string, version: string, changes: ReviewChange[] }>
|
|
17
|
+
diffFile(path: string, step?: string): Promise<ReviewChange | undefined>
|
|
18
|
+
readTree(tree: string, paths: string[]): Promise<DocumentFileChange[]>
|
|
19
|
+
assertTree(tree: string, except: string[]): Promise<void>
|
|
15
20
|
restoreFiles(paths: string[]): Promise<void>
|
|
16
21
|
noteSession(session: Omit<AgentSessionRecord, 'checkpoints' | 'steps'>): void
|
|
17
22
|
suspend(): void
|
|
@@ -137,13 +142,14 @@ class ReviewTrees {
|
|
|
137
142
|
.map(this.fromGit).sort((a, b) => a.localeCompare(b))
|
|
138
143
|
}
|
|
139
144
|
|
|
140
|
-
async compare(from: string, to: string): Promise<ReviewChange[]> {
|
|
145
|
+
async compare(from: string, to: string, details = true, only?: string): Promise<ReviewChange[]> {
|
|
141
146
|
if (from === to) return []
|
|
142
|
-
const
|
|
147
|
+
const paths = only === undefined ? [] : ['--', this.toGit(only)]
|
|
148
|
+
const status = (await this.#text([...DIFF, '--name-status', '-z', from, to, ...paths])).split('\0').filter(Boolean)
|
|
143
149
|
const kinds = new Map<string, ReviewChangeKind>()
|
|
144
150
|
for (let i = 0; i + 1 < status.length; i += 2) kinds.set(status[i + 1]!, status[i]!.startsWith('A') ? 'added' : status[i]!.startsWith('D') ? 'deleted' : 'modified')
|
|
145
151
|
const counts = new Map<string, { added: number, removed: number, binary: boolean }>()
|
|
146
|
-
for (const entry of (await this.#text([...DIFF, '--numstat', '-z', from, to])).split('\0').filter(Boolean)) {
|
|
152
|
+
for (const entry of (await this.#text([...DIFF, '--numstat', '-z', from, to, ...paths])).split('\0').filter(Boolean)) {
|
|
147
153
|
const [added = '0', removed = '0', ...path] = entry.split('\t')
|
|
148
154
|
const binary = added === '-'
|
|
149
155
|
counts.set(path.join('\t'), { added: binary ? 0 : Number(added), removed: binary ? 0 : Number(removed), binary })
|
|
@@ -152,7 +158,7 @@ class ReviewTrees {
|
|
|
152
158
|
for (const [path, kind] of kinds) {
|
|
153
159
|
const count = counts.get(path) ?? { added: 0, removed: 0, binary: false }
|
|
154
160
|
const change: ReviewChange = { path: this.fromGit(path), kind, ...count }
|
|
155
|
-
if (!count.binary && changes.filter(c => c.diff).length < MAX_DIFFS) {
|
|
161
|
+
if (details && !count.binary && changes.filter(c => c.diff).length < MAX_DIFFS) {
|
|
156
162
|
const diff = await this.#text([...DIFF, from, to, '--', path])
|
|
157
163
|
if (diff.length <= MAX_DIFF) change.diff = diff
|
|
158
164
|
}
|
|
@@ -190,10 +196,11 @@ class ReviewTrees {
|
|
|
190
196
|
}
|
|
191
197
|
}
|
|
192
198
|
|
|
193
|
-
async
|
|
199
|
+
async read(tree: string, paths: string[]): Promise<DocumentFileChange[]> {
|
|
194
200
|
const entries = new Map<string, { mode: string, oid: string }>()
|
|
195
201
|
for (const entry of (await this.#text(['ls-tree', '-r', '-z', tree, '--', ...paths])).split('\0').filter(Boolean)) {
|
|
196
|
-
const
|
|
202
|
+
const separator = entry.indexOf('\t')
|
|
203
|
+
const meta = entry.slice(0, separator), path = entry.slice(separator + 1)
|
|
197
204
|
const [mode = '', , oid = ''] = meta.split(' ')
|
|
198
205
|
entries.set(path, { mode, oid })
|
|
199
206
|
}
|
|
@@ -208,7 +215,11 @@ class ReviewTrees {
|
|
|
208
215
|
const blob = await this.#git(['cat-file', 'blob', entry.oid])
|
|
209
216
|
changes.push(entry.mode === '120000' ? { path: this.fromGit(path), link: blob.toString('utf8') } : { path: this.fromGit(path), content: blob, ...entry.mode === '100755' ? { executable: true } : {} })
|
|
210
217
|
}
|
|
211
|
-
|
|
218
|
+
return changes
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async #write(tree: string, paths: string[]): Promise<void> {
|
|
222
|
+
await this.#files!.write(await this.read(tree, paths))
|
|
212
223
|
}
|
|
213
224
|
|
|
214
225
|
async reset(tree: string): Promise<void> {
|
|
@@ -227,6 +238,8 @@ export interface GitReviewOptions {
|
|
|
227
238
|
onRestore?: (paths: string[]) => void
|
|
228
239
|
warn?: (message: string) => void
|
|
229
240
|
files?: DocumentFiles
|
|
241
|
+
recordRoot?: string
|
|
242
|
+
workspace?: ReviewRecord['workspace']
|
|
230
243
|
}
|
|
231
244
|
|
|
232
245
|
const recovering = new Map<string, Promise<{ task: string, paths: string[] } | undefined>>()
|
|
@@ -298,7 +311,7 @@ export async function openGitReview(options: GitReviewOptions & { session?: Omit
|
|
|
298
311
|
throw error
|
|
299
312
|
}
|
|
300
313
|
const saved = guard.saved()
|
|
301
|
-
const record: ReviewRecord = { scopeDir, dirs, snapshot, task: options.task, ...THIS_PROCESS, ...saved ? { guard: saved } : {}, ...options.session ? { session: { ...options.session, checkpoints: [], steps: [] } } : {} }
|
|
314
|
+
const record: ReviewRecord = { scopeDir, dirs, snapshot, task: options.task, ...THIS_PROCESS, ...options.recordRoot ? { recordRoot: options.recordRoot } : {}, ...options.workspace ? { workspace: options.workspace } : {}, ...saved ? { guard: saved } : {}, ...options.session ? { session: { ...options.session, checkpoints: [], steps: [] } } : {} }
|
|
302
315
|
return createGitReview({ scopeDir, trees, restoreGitDir: guard.restore, record, warn: options.warn })
|
|
303
316
|
}
|
|
304
317
|
|
|
@@ -335,7 +348,7 @@ function createGitReview(open: { scopeDir: string, trees: ReviewTrees, restoreGi
|
|
|
335
348
|
if (settled) return
|
|
336
349
|
settled = true
|
|
337
350
|
openScopes.delete(scopeDir)
|
|
338
|
-
if (!suspended) removeRecord(scopeDir)
|
|
351
|
+
if (!suspended) removeRecord(record.recordRoot ?? scopeDir)
|
|
339
352
|
trees.dispose()
|
|
340
353
|
}
|
|
341
354
|
const live = () => {
|
|
@@ -349,6 +362,12 @@ function createGitReview(open: { scopeDir: string, trees: ReviewTrees, restoreGi
|
|
|
349
362
|
await trees.restore(snapshot, [...rejected])
|
|
350
363
|
return changes.filter(path => !rejected.has(path))
|
|
351
364
|
}
|
|
365
|
+
const inspect = async (details = false) => {
|
|
366
|
+
live()
|
|
367
|
+
restoreGitDir()
|
|
368
|
+
const tree = await trees.tree()
|
|
369
|
+
return { tree, version: createHash('sha256').update(JSON.stringify([snapshot, tree, checkpoints])).digest('hex'), changes: await trees.compare(snapshot, tree, details) }
|
|
370
|
+
}
|
|
352
371
|
|
|
353
372
|
return {
|
|
354
373
|
root: scopeDir,
|
|
@@ -372,10 +391,21 @@ function createGitReview(open: { scopeDir: string, trees: ReviewTrees, restoreGi
|
|
|
372
391
|
return step
|
|
373
392
|
},
|
|
374
393
|
steps: () => steps,
|
|
375
|
-
|
|
394
|
+
inspect,
|
|
395
|
+
readTree: (tree, paths) => { live(); return trees.read(tree, paths.map(trees.toGit)) },
|
|
396
|
+
async assertTree(tree, except) {
|
|
397
|
+
live()
|
|
398
|
+
if ((await trees.changedPaths(tree, await trees.tree())).some(path => !except.includes(path))) throw new Error('workspace-review-changed')
|
|
399
|
+
},
|
|
400
|
+
diff: async () => (await inspect(true)).changes,
|
|
401
|
+
async diffFile(path, step) {
|
|
376
402
|
live()
|
|
377
403
|
restoreGitDir()
|
|
378
|
-
|
|
404
|
+
const at = step === undefined ? -1 : steps.findIndex(value => value.id === step)
|
|
405
|
+
if (step !== undefined && at < 0) return
|
|
406
|
+
const from = at < 0 ? snapshot : checkpoints[at]!, to = at < 0 ? await trees.tree() : checkpoints[at + 1]!
|
|
407
|
+
if (!(await trees.compare(from, to, false, path)).some(change => change.path === path)) return
|
|
408
|
+
return (await trees.compare(from, to, true, path)).find(change => change.path === path)
|
|
379
409
|
},
|
|
380
410
|
async restoreTo(stepId) {
|
|
381
411
|
live()
|
|
@@ -5,6 +5,7 @@ import { join } from 'node:path'
|
|
|
5
5
|
import type { Member, ReviewStep } from '@lincyaw/kernel'
|
|
6
6
|
import type { SavedGitDir } from './git-guard.ts'
|
|
7
7
|
import type { GitDirs } from './git-review.ts'
|
|
8
|
+
import type { AgentWorkspaceRecord } from './agent-workspace.ts'
|
|
8
9
|
|
|
9
10
|
export interface AgentSessionRecord {
|
|
10
11
|
session: string
|
|
@@ -18,6 +19,8 @@ export interface AgentSessionRecord {
|
|
|
18
19
|
|
|
19
20
|
/** A review in progress, kept in the user's state directory so that another process can roll it back or resume it. */
|
|
20
21
|
export interface ReviewRecord {
|
|
22
|
+
recordRoot?: string
|
|
23
|
+
workspace?: AgentWorkspaceRecord
|
|
21
24
|
/** The directory the review covers: a document's for a plugin's task, the workspace root for an agent session. */
|
|
22
25
|
scopeDir: string
|
|
23
26
|
dirs: GitDirs
|
|
@@ -66,7 +69,7 @@ export function readRecord(scopeDir: string): ReviewRecord | undefined {
|
|
|
66
69
|
}
|
|
67
70
|
|
|
68
71
|
export function writeRecord(record: ReviewRecord): void {
|
|
69
|
-
const file = recordFile(record.scopeDir)
|
|
72
|
+
const file = recordFile(record.recordRoot ?? record.scopeDir)
|
|
70
73
|
mkdirSync(recordsDir(), { recursive: true, mode: 0o700 })
|
|
71
74
|
writeFileSync(`${file}.${process.pid}`, JSON.stringify(record), { mode: 0o600 })
|
|
72
75
|
renameSync(`${file}.${process.pid}`, file)
|