@lincyaw/workspace 1.0.0-rc.4 → 1.0.0-rc.40
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 +6 -5
- package/src/node/authoring-clients.ts +23 -4
- package/src/node/build.ts +67 -10
- package/src/node/capture.ts +356 -0
- package/src/node/config.ts +1 -0
- package/src/node/document-authoring.ts +7 -1
- package/src/node/locks.ts +12 -0
- package/src/node/review/agent-session-reviews.ts +102 -44
- package/src/node/review/agent-workspace.ts +106 -0
- package/src/node/review/git-review.ts +4 -2
- package/src/node/review/record.ts +4 -1
- package/src/node/review/routes.ts +7 -0
- package/src/node/revisions.ts +14 -4
- package/src/node/routes.ts +1 -1
- package/src/node/serve.ts +58 -12
- package/src/node/site.ts +1 -1
- package/src/node/source-editor.ts +3 -7
- package/src/node/workbench-api.ts +14 -3
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto'
|
|
2
|
-
import { existsSync
|
|
2
|
+
import { existsSync } from 'node:fs'
|
|
3
3
|
import { join } from 'node:path'
|
|
4
|
-
import {
|
|
4
|
+
import { errorMessage, pushStream } from '@lincyaw/kernel'
|
|
5
5
|
import type { DocumentFiles, Logger, Member, ReviewEnd, ReviewSnapshot, ReviewUpdate } from '@lincyaw/kernel'
|
|
6
6
|
import { trailers } from '../../domain/commit-message.ts'
|
|
7
7
|
import type { WorkspaceConfig } 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,18 +112,41 @@ 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
|
-
|
|
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
|
+
}
|
|
126
|
+
|
|
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
|
+
})
|
|
125
150
|
}
|
|
126
151
|
|
|
127
152
|
async snapshot(): Promise<ReviewSnapshot | undefined> {
|
|
@@ -133,7 +158,7 @@ export class AgentSessionReviews {
|
|
|
133
158
|
return {
|
|
134
159
|
id: open.review.task,
|
|
135
160
|
document: open.document,
|
|
136
|
-
engine:
|
|
161
|
+
engine: 'git-candidate',
|
|
137
162
|
session: open.session,
|
|
138
163
|
holder: lockHolder(open.session),
|
|
139
164
|
turns: { ...open.turns },
|
|
@@ -173,24 +198,26 @@ export class AgentSessionReviews {
|
|
|
173
198
|
let open = this.#open
|
|
174
199
|
if (open && open.session !== body.session) throw lockedError(document, lockHolder(open.session))
|
|
175
200
|
if (!open) {
|
|
176
|
-
const release = this.#options.locks.claim('', lockHolder(body.session))
|
|
177
|
-
if (!release) throw lockedError(document, this.#options.locks.holder('')!)
|
|
178
201
|
const { config, log } = this.#options
|
|
179
202
|
const turn = body.turn ?? 0
|
|
180
203
|
const opened = new Date().toISOString()
|
|
204
|
+
let workspace = this.#workspaces.get(body.session)
|
|
205
|
+
if (!workspace) { workspace = await AgentWorkspace.create(config); this.#workspaces.set(body.session, workspace) }
|
|
206
|
+
const root = workspace.root
|
|
181
207
|
try {
|
|
182
208
|
const review = await openGitReview({
|
|
183
|
-
workspaceRoot:
|
|
184
|
-
scopeDir:
|
|
209
|
+
workspaceRoot: root,
|
|
210
|
+
scopeDir: root,
|
|
211
|
+
recordRoot: config.root,
|
|
212
|
+
workspace: workspace.record,
|
|
185
213
|
task: randomUUID(),
|
|
186
|
-
files:
|
|
214
|
+
files: { write: async changes => writeChanges({ ...config, root }, changes, true) },
|
|
187
215
|
onRestore: paths => log.warn(`session ${body.session}: the agent changed the git directory, put back: ${paths.join(', ')}`),
|
|
188
216
|
warn: message => log.warn(`session ${body.session}: ${message}`),
|
|
189
217
|
session: { session: body.session, document, member, turns: { from: turn, to: turn }, opened },
|
|
190
218
|
})
|
|
191
|
-
open = { review, document, session: body.session, member, turns: { from: turn, to: turn }, running: true, opened,
|
|
219
|
+
open = { review, document, session: body.session, member, turns: { from: turn, to: turn }, running: true, opened, workspace }
|
|
192
220
|
} catch (error) {
|
|
193
|
-
release()
|
|
194
221
|
throw new RequestError(409, `the review of ${document || '.'} did not open: ${errorMessage(error)}`)
|
|
195
222
|
}
|
|
196
223
|
this.#open = open
|
|
@@ -204,11 +231,24 @@ export class AgentSessionReviews {
|
|
|
204
231
|
|
|
205
232
|
step(document: string, body: { session: string, turn?: number, label?: string, tool?: string, end?: boolean }): Promise<ReviewSnapshot | undefined> {
|
|
206
233
|
return this.#serial(async () => {
|
|
234
|
+
if (!this.#open && body.end) return undefined
|
|
207
235
|
const open = this.#requireSession(document, body.session)
|
|
208
236
|
this.#noteTurn(open, body.turn)
|
|
209
237
|
if (body.label) await open.review.step(body.label, body.tool)
|
|
210
238
|
if (!body.end) {
|
|
211
|
-
open.running =
|
|
239
|
+
open.running = false
|
|
240
|
+
if (reviewSettings(this.#options.config).mode === 'auto') {
|
|
241
|
+
try { await this.#accept(open, [], undefined) }
|
|
242
|
+
catch (error) {
|
|
243
|
+
if (error instanceof RequestError && error.message === 'agent-source-changed') {
|
|
244
|
+
await open.review.close()
|
|
245
|
+
await this.#end(open, { outcome: 'rejected', files: [] })
|
|
246
|
+
if (this.#workspaces.has(open.session)) await open.workspace!.refresh()
|
|
247
|
+
}
|
|
248
|
+
throw error
|
|
249
|
+
}
|
|
250
|
+
return undefined
|
|
251
|
+
}
|
|
212
252
|
return await this.#publish(open)
|
|
213
253
|
}
|
|
214
254
|
open.running = false
|
|
@@ -228,29 +268,43 @@ export class AgentSessionReviews {
|
|
|
228
268
|
}
|
|
229
269
|
|
|
230
270
|
accept(document: string, body: { reject?: string[], message?: string }): Promise<ReviewEnd> {
|
|
231
|
-
return this.#serial(() =>
|
|
271
|
+
return this.#serial(async () => {
|
|
272
|
+
const open = this.#requireOpen(document)
|
|
273
|
+
try { return await this.#accept(open, body.reject ?? [], body.message) }
|
|
274
|
+
catch (error) {
|
|
275
|
+
if (error instanceof RequestError && error.message === 'agent-source-changed') {
|
|
276
|
+
await open.review.close()
|
|
277
|
+
await this.#end(open, { outcome: 'rejected', files: [] })
|
|
278
|
+
if (this.#workspaces.has(open.session)) await open.workspace!.refresh()
|
|
279
|
+
}
|
|
280
|
+
throw error
|
|
281
|
+
}
|
|
282
|
+
})
|
|
232
283
|
}
|
|
233
284
|
|
|
234
285
|
async #accept(open: OpenReview, reject: string[], message: string | undefined): Promise<ReviewEnd> {
|
|
235
286
|
const rejected = new Set(reject)
|
|
236
287
|
for (const change of await open.review.diff()) if (isInGitDir(change.path)) rejected.add(change.path)
|
|
237
288
|
const files = await open.review.prepareAccept([...rejected])
|
|
238
|
-
|
|
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
|
-
}
|
|
289
|
+
if (!open.workspace) throw new RequestError(409, 'agent-workspace-unavailable')
|
|
243
290
|
const lang = listDocuments(this.#options.config).find(doc => doc.dir === open.document)?.lang
|
|
244
291
|
const steps = open.review.steps().map(step => `- ${step.label}`).slice(0, 20)
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
292
|
+
if (files.length) await this.#options.flush?.(listDocuments(this.#options.config).map(document => document.dir), open.member)
|
|
293
|
+
const release = await this.#options.locks.acquire('', lockHolder(open.session))
|
|
294
|
+
let revision
|
|
295
|
+
try {
|
|
296
|
+
revision = await this.#options.revisions.transaction(async () => {
|
|
297
|
+
const prepared = open.workspace!.prepare(files)
|
|
298
|
+
try {
|
|
299
|
+
open.workspace!.write(prepared.changes)
|
|
300
|
+
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}`]] })
|
|
301
|
+
} catch (error) { open.workspace!.write(prepared.restore); throw error }
|
|
302
|
+
})
|
|
303
|
+
} finally { release() }
|
|
251
304
|
open.review.finish()
|
|
252
305
|
const ended: ReviewEnd = { outcome: 'accepted', ...revision ? { revision } : {}, files }
|
|
253
306
|
await this.#end(open, ended)
|
|
307
|
+
if (this.#workspaces.has(open.session)) await open.workspace.refresh()
|
|
254
308
|
return ended
|
|
255
309
|
}
|
|
256
310
|
|
|
@@ -298,9 +352,10 @@ export class AgentSessionReviews {
|
|
|
298
352
|
if (open) {
|
|
299
353
|
clearTimeout(open.timer)
|
|
300
354
|
open.review.suspend()
|
|
301
|
-
open.release()
|
|
302
355
|
}
|
|
303
356
|
this.#open = undefined
|
|
357
|
+
for (const [session, workspace] of this.#workspaces) if (session !== open?.session) workspace.dispose()
|
|
358
|
+
this.#workspaces.clear()
|
|
304
359
|
}
|
|
305
360
|
|
|
306
361
|
#requireSession(document: string, session: string): OpenReview {
|
|
@@ -331,7 +386,10 @@ export class AgentSessionReviews {
|
|
|
331
386
|
async #end(open: OpenReview, ended: ReviewEnd): Promise<void> {
|
|
332
387
|
clearTimeout(open.timer)
|
|
333
388
|
this.#open = undefined
|
|
334
|
-
open.
|
|
389
|
+
if (this.#retired.delete(open.session)) {
|
|
390
|
+
this.#workspaces.delete(open.session)
|
|
391
|
+
open.workspace?.dispose()
|
|
392
|
+
}
|
|
335
393
|
this.#sendToWatchers({ document: open.document, ended })
|
|
336
394
|
this.#emit({ type: 'review', document: open.document, session: open.session, ended })
|
|
337
395
|
}
|
|
@@ -0,0 +1,106 @@
|
|
|
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[]): { changes: DocumentFileChange[], restore: DocumentFileChange[] } {
|
|
89
|
+
const conflicts = paths.filter(path => !same(stamp(join(this.#config.root, path)), this.record.base[path]))
|
|
90
|
+
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.' })
|
|
91
|
+
const changes: DocumentFileChange[] = [], restore: DocumentFileChange[] = []
|
|
92
|
+
for (const path of paths) {
|
|
93
|
+
if (!path || path.split('/').some(part => !part || part === '.' || part === '..' || part === '.git') || path.startsWith('.presmium/agent-workspaces/')) throw new RequestError(403, 'agent-source-path-invalid')
|
|
94
|
+
const before = stamp(join(this.#config.root, path)), after = stamp(join(this.root, path))
|
|
95
|
+
const read = (root: string, value: FileStamp | undefined): DocumentFileChange => !value ? { path, remove: true }
|
|
96
|
+
: value.link ? { path, link: readlinkSync(join(root, path)) } : { path, content: readFileSync(join(root, path)), ...value.executable ? { executable: true } : {} }
|
|
97
|
+
const change = read(this.root, after)
|
|
98
|
+
if ('content' in change) validateDocumentSource(path, Buffer.from(change.content).toString('utf8'), before && !before.link ? readFileSync(join(this.#config.root, path)) : undefined)
|
|
99
|
+
changes.push(change); restore.push(read(this.#config.root, before))
|
|
100
|
+
}
|
|
101
|
+
return { changes, restore }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
write(changes: DocumentFileChange[]): void { writeChanges(this.#config, changes, true) }
|
|
105
|
+
dispose(): void { rmSync(dirname(this.root), { recursive: true, force: true }) }
|
|
106
|
+
}
|
|
@@ -227,6 +227,8 @@ export interface GitReviewOptions {
|
|
|
227
227
|
onRestore?: (paths: string[]) => void
|
|
228
228
|
warn?: (message: string) => void
|
|
229
229
|
files?: DocumentFiles
|
|
230
|
+
recordRoot?: string
|
|
231
|
+
workspace?: ReviewRecord['workspace']
|
|
230
232
|
}
|
|
231
233
|
|
|
232
234
|
const recovering = new Map<string, Promise<{ task: string, paths: string[] } | undefined>>()
|
|
@@ -298,7 +300,7 @@ export async function openGitReview(options: GitReviewOptions & { session?: Omit
|
|
|
298
300
|
throw error
|
|
299
301
|
}
|
|
300
302
|
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: [] } } : {} }
|
|
303
|
+
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
304
|
return createGitReview({ scopeDir, trees, restoreGitDir: guard.restore, record, warn: options.warn })
|
|
303
305
|
}
|
|
304
306
|
|
|
@@ -335,7 +337,7 @@ function createGitReview(open: { scopeDir: string, trees: ReviewTrees, restoreGi
|
|
|
335
337
|
if (settled) return
|
|
336
338
|
settled = true
|
|
337
339
|
openScopes.delete(scopeDir)
|
|
338
|
-
if (!suspended) removeRecord(scopeDir)
|
|
340
|
+
if (!suspended) removeRecord(record.recordRoot ?? scopeDir)
|
|
339
341
|
trees.dispose()
|
|
340
342
|
}
|
|
341
343
|
const 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)
|
|
@@ -18,6 +18,13 @@ export function reviewRoutes(reviews: AgentSessionReviews): Record<string, Route
|
|
|
18
18
|
handle: (request, ctx) => catchRequestErrors(async () => (request.method === 'POST' ? handle(await readBody(request), ctx.document) : problemResponse(405, 'POST'))),
|
|
19
19
|
})
|
|
20
20
|
return {
|
|
21
|
+
'review/workspace': post(async body => {
|
|
22
|
+
const session = toText(body.session, 200)
|
|
23
|
+
if (!session) return problemResponse(400, '{ session }')
|
|
24
|
+
if (body.close === true) { await reviews.closeWorkspace(session); return jsonResponse({ closed: true }) }
|
|
25
|
+
if (body.refresh === true) await reviews.refreshWorkspace(session)
|
|
26
|
+
return jsonResponse(await reviews.workspace(session))
|
|
27
|
+
}),
|
|
21
28
|
'review': {
|
|
22
29
|
role: 'editor',
|
|
23
30
|
handle: (request, ctx) => catchRequestErrors(async () => {
|
package/src/node/revisions.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { existsSync, lstatSync, mkdtempSync, readdirSync, readFileSync, rmdirSyn
|
|
|
2
2
|
import { tmpdir } from 'node:os'
|
|
3
3
|
import { join, relative, resolve, sep } from 'node:path'
|
|
4
4
|
import type { DocumentFileChange, HistoryRevision, Member, RevertResult, Revision, RevisionsAnswer, RevisionService, UncommittedFile } from '@lincyaw/kernel'
|
|
5
|
+
import { LOCAL_AUTHOR } from '@lincyaw/kernel'
|
|
5
6
|
import { leavesRoot } from '../domain/paths.ts'
|
|
6
7
|
import { commitMessage, memberAddress, originOf } from '../domain/commit-message.ts'
|
|
7
8
|
import type { CommitOrigin } from '../domain/commit-message.ts'
|
|
@@ -208,14 +209,16 @@ export class Revisions implements RevisionService {
|
|
|
208
209
|
|
|
209
210
|
/** Commits the paths; the caller holds the git lock (`Git.exclusive`). */
|
|
210
211
|
async commitWhileLocked(commit: LockedCommit): Promise<Revision | undefined> {
|
|
211
|
-
const { summary, body
|
|
212
|
+
const { summary, body } = commit
|
|
212
213
|
const unique = [...new Set(commit.paths.map(path => path.replace(/^\.?\/+|\/+$/g, '')).filter(path => path && !leavesRoot(path)))]
|
|
213
214
|
if (unique.length === 0) return undefined
|
|
214
215
|
await this.#git.output(['add', '-A', '--', ...unique], { GIT_LITERAL_PATHSPECS: '1' })
|
|
215
216
|
const staged = (await this.#git.output(['diff', '--cached', '--name-only', '--', ...unique], { GIT_LITERAL_PATHSPECS: '1' })).trim()
|
|
216
217
|
if (!staged) return undefined
|
|
218
|
+
const member = await this.#author(commit.origin.member)
|
|
219
|
+
const origin = { ...commit.origin, ...member ? { member } : {} }
|
|
217
220
|
const message = withTrailers(commitMessage(summary, body, origin, commit.revert), commit.trailers ?? [])
|
|
218
|
-
await this.#git.output([...await this.#identity(), 'commit', '-q', '--no-verify', '-m', message, ...
|
|
221
|
+
await this.#git.output([...await this.#identity(), 'commit', '-q', '--no-verify', '-m', message, ...member ? [`--author=${memberAddress(member)}`] : [], '--', ...unique], { GIT_LITERAL_PATHSPECS: '1' })
|
|
219
222
|
return this.#revision('HEAD')
|
|
220
223
|
}
|
|
221
224
|
|
|
@@ -545,8 +548,15 @@ export class Revisions implements RevisionService {
|
|
|
545
548
|
return entry && revision(entry)
|
|
546
549
|
}
|
|
547
550
|
|
|
548
|
-
|
|
549
|
-
|
|
551
|
+
/**
|
|
552
|
+
* The member a commit names as its author. The local author (the one person a local service serves) is the
|
|
553
|
+
* repository's configured git user when git has one, so that their saves are theirs; members of a shared service
|
|
554
|
+
* have their own name and email.
|
|
555
|
+
*/
|
|
556
|
+
async #author(member: Member | undefined): Promise<Member | undefined> {
|
|
557
|
+
if (!member || member.email || member.id !== LOCAL_AUTHOR.id || member.name !== LOCAL_AUTHOR.name) return member
|
|
558
|
+
const [name, email] = await Promise.all([this.#git.tryOutput(['config', 'user.name']), this.#git.tryOutput(['config', 'user.email'])])
|
|
559
|
+
return name.ok && email.ok && name.output.trim() && email.output.trim() ? { ...member, name: name.output.trim(), email: email.output.trim() } : member
|
|
550
560
|
}
|
|
551
561
|
|
|
552
562
|
async #identity(): Promise<string[]> {
|
package/src/node/routes.ts
CHANGED
|
@@ -257,7 +257,7 @@ function workbenchRoutes(workbench: WorkbenchApi): Record<string, Route> {
|
|
|
257
257
|
const params = new URL(request.url).searchParams
|
|
258
258
|
const renderer = params.get('view') ?? undefined
|
|
259
259
|
if (renderer !== undefined && renderer !== 'web' && renderer !== 'slides') return problemResponse(400, 'view must be web or slides')
|
|
260
|
-
return jsonResponse(await workbench.preview(ctx.document, renderer, params.get('prefetch') === '1'))
|
|
260
|
+
return jsonResponse(await workbench.preview(ctx.document, renderer, params.get('prefetch') === '1', request.headers.get('x-presmium-preview-origin') ?? undefined))
|
|
261
261
|
}),
|
|
262
262
|
},
|
|
263
263
|
'build': {
|