@lincyaw/workspace 1.0.0-rc.13 → 1.0.0-rc.131
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/README.md +4 -4
- package/package.json +8 -5
- package/src/domain/paths.ts +0 -15
- package/src/node/agent-activity.ts +46 -0
- package/src/node/archive.ts +33 -0
- package/src/node/authoring-clients.ts +73 -20
- package/src/node/authoring-windows.ts +165 -0
- package/src/node/build.ts +28 -23
- package/src/node/capture.ts +383 -0
- package/src/node/config.ts +136 -50
- package/src/node/document-assets.ts +2 -2
- package/src/node/document-audio.ts +65 -46
- package/src/node/document-authoring.ts +30 -15
- package/src/node/document-check.ts +36 -0
- package/src/node/document-history.ts +32 -5
- package/src/node/document-images.ts +24 -14
- package/src/node/document-import.ts +123 -0
- package/src/node/document-index.ts +644 -0
- package/src/node/document-materials.ts +80 -0
- package/src/node/document-operations.ts +4 -2
- package/src/node/document-transcription.ts +2 -1
- package/src/node/document-voice.ts +121 -13
- package/src/node/git-runner.mjs +19 -0
- package/src/node/git.ts +141 -22
- package/src/node/host-activity.ts +17 -0
- package/src/node/host-upgrade.ts +28 -0
- package/src/node/jobs.ts +40 -8
- package/src/node/local-history.ts +84 -0
- package/src/node/locks.ts +12 -0
- package/src/node/mcp-settings.ts +68 -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/page-delete.ts +0 -1
- package/src/node/project-files.ts +2 -2
- package/src/node/projects.ts +20 -5
- package/src/node/review/agent-session-reviews.ts +194 -63
- package/src/node/review/agent-workspace.ts +124 -0
- package/src/node/review/git-review.ts +47 -15
- package/src/node/review/record.ts +5 -1
- package/src/node/review/routes.ts +9 -1
- package/src/node/review/workspace-review.ts +87 -0
- package/src/node/revision-files.ts +54 -0
- package/src/node/revisions.ts +244 -59
- package/src/node/routes.ts +52 -59
- package/src/node/serve.ts +267 -52
- package/src/node/site.ts +5 -5
- package/src/node/source-editor.ts +66 -26
- package/src/node/speech-settings.ts +6 -8
- package/src/node/templates.ts +2 -2
- package/src/node/tree-operations.ts +425 -0
- package/src/node/tree-routes.ts +94 -0
- package/src/node/workbench-api.ts +14 -3
- package/src/node/workspace-changes.ts +130 -0
- package/src/node/workspace-migrate.ts +54 -0
- package/src/node/workspace-source.ts +133 -0
- package/src/node/writer.ts +21 -8
- package/templates/document/default/{lecture.json → index.pmd} +5 -1
|
@@ -1,10 +1,12 @@
|
|
|
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'
|
|
5
6
|
import { gitConfigArgs, gitEnvironment } from '@lincyaw/kernel'
|
|
6
7
|
import type { ChangeReview, DocumentFileChange, DocumentFiles, ReviewChange, ReviewChangeKind, ReviewStep } from '@lincyaw/kernel'
|
|
7
8
|
import { isInside } from '@lincyaw/kernel/node'
|
|
9
|
+
import { addPathspecs, nestedRepositories } from '../git.ts'
|
|
8
10
|
import { snapshotGitDir } from './git-guard.ts'
|
|
9
11
|
import type { SavedGitDir } from './git-guard.ts'
|
|
10
12
|
import { isHolderAlive, readRecord, removeRecord, THIS_PROCESS, writeRecord } from './record.ts'
|
|
@@ -12,6 +14,10 @@ import type { AgentSessionRecord, ReviewRecord } from './record.ts'
|
|
|
12
14
|
|
|
13
15
|
export interface GitReview extends ChangeReview {
|
|
14
16
|
readonly task: string
|
|
17
|
+
inspect(details?: boolean): Promise<{ tree: string, version: string, changes: ReviewChange[] }>
|
|
18
|
+
diffFile(path: string, step?: string): Promise<ReviewChange | undefined>
|
|
19
|
+
readTree(tree: string, paths: string[]): Promise<DocumentFileChange[]>
|
|
20
|
+
assertTree(tree: string, except: string[]): Promise<void>
|
|
15
21
|
restoreFiles(paths: string[]): Promise<void>
|
|
16
22
|
noteSession(session: Omit<AgentSessionRecord, 'checkpoints' | 'steps'>): void
|
|
17
23
|
suspend(): void
|
|
@@ -35,7 +41,7 @@ function git(cwd: string, args: string[], env: Record<string, string> = {}): Pro
|
|
|
35
41
|
cwd,
|
|
36
42
|
encoding: 'buffer',
|
|
37
43
|
maxBuffer: 256 << 20,
|
|
38
|
-
env: { ...gitEnvironment(process.env), ...env, GIT_OPTIONAL_LOCKS: '0'
|
|
44
|
+
env: { ...gitEnvironment(process.env), GIT_LITERAL_PATHSPECS: '1', ...env, GIT_OPTIONAL_LOCKS: '0' },
|
|
39
45
|
}, (error, stdout, stderr) => {
|
|
40
46
|
if (error) reject(new Error(`git ${args[0]}: ${stderr.toString('utf8').trim() || error.message}`))
|
|
41
47
|
else resolve(stdout)
|
|
@@ -106,8 +112,8 @@ class ReviewTrees {
|
|
|
106
112
|
this.#files = options.files
|
|
107
113
|
}
|
|
108
114
|
|
|
109
|
-
#git(args: string[], index?: string): Promise<Buffer> {
|
|
110
|
-
return git(this.top, args, { ...this.#env, ...index ? { GIT_INDEX_FILE: index } : {} })
|
|
115
|
+
#git(args: string[], index?: string, env: Record<string, string> = {}): Promise<Buffer> {
|
|
116
|
+
return git(this.top, args, { ...this.#env, ...index ? { GIT_INDEX_FILE: index } : {}, ...env })
|
|
111
117
|
}
|
|
112
118
|
|
|
113
119
|
async #text(args: string[], index?: string): Promise<string> {
|
|
@@ -124,7 +130,8 @@ class ReviewTrees {
|
|
|
124
130
|
async tree(): Promise<string> {
|
|
125
131
|
const index = this.#index()
|
|
126
132
|
try {
|
|
127
|
-
await this.#
|
|
133
|
+
const nested = nestedRepositories(await this.#text(['ls-files', '--others', '--exclude-standard', '-z', '--', this.#pathspec], index))
|
|
134
|
+
await this.#git(['add', '-A', '--', ...addPathspecs([this.#pathspec], nested)], index, { GIT_LITERAL_PATHSPECS: '0' })
|
|
128
135
|
return (await this.#text(['write-tree'], index)).trim()
|
|
129
136
|
} finally {
|
|
130
137
|
rmSync(index, { force: true })
|
|
@@ -137,13 +144,14 @@ class ReviewTrees {
|
|
|
137
144
|
.map(this.fromGit).sort((a, b) => a.localeCompare(b))
|
|
138
145
|
}
|
|
139
146
|
|
|
140
|
-
async compare(from: string, to: string): Promise<ReviewChange[]> {
|
|
147
|
+
async compare(from: string, to: string, details = true, only?: string): Promise<ReviewChange[]> {
|
|
141
148
|
if (from === to) return []
|
|
142
|
-
const
|
|
149
|
+
const paths = only === undefined ? [] : ['--', this.toGit(only)]
|
|
150
|
+
const status = (await this.#text([...DIFF, '--name-status', '-z', from, to, ...paths])).split('\0').filter(Boolean)
|
|
143
151
|
const kinds = new Map<string, ReviewChangeKind>()
|
|
144
152
|
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
153
|
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)) {
|
|
154
|
+
for (const entry of (await this.#text([...DIFF, '--numstat', '-z', from, to, ...paths])).split('\0').filter(Boolean)) {
|
|
147
155
|
const [added = '0', removed = '0', ...path] = entry.split('\t')
|
|
148
156
|
const binary = added === '-'
|
|
149
157
|
counts.set(path.join('\t'), { added: binary ? 0 : Number(added), removed: binary ? 0 : Number(removed), binary })
|
|
@@ -152,7 +160,7 @@ class ReviewTrees {
|
|
|
152
160
|
for (const [path, kind] of kinds) {
|
|
153
161
|
const count = counts.get(path) ?? { added: 0, removed: 0, binary: false }
|
|
154
162
|
const change: ReviewChange = { path: this.fromGit(path), kind, ...count }
|
|
155
|
-
if (!count.binary && changes.filter(c => c.diff).length < MAX_DIFFS) {
|
|
163
|
+
if (details && !count.binary && changes.filter(c => c.diff).length < MAX_DIFFS) {
|
|
156
164
|
const diff = await this.#text([...DIFF, from, to, '--', path])
|
|
157
165
|
if (diff.length <= MAX_DIFF) change.diff = diff
|
|
158
166
|
}
|
|
@@ -190,10 +198,11 @@ class ReviewTrees {
|
|
|
190
198
|
}
|
|
191
199
|
}
|
|
192
200
|
|
|
193
|
-
async
|
|
201
|
+
async read(tree: string, paths: string[]): Promise<DocumentFileChange[]> {
|
|
194
202
|
const entries = new Map<string, { mode: string, oid: string }>()
|
|
195
203
|
for (const entry of (await this.#text(['ls-tree', '-r', '-z', tree, '--', ...paths])).split('\0').filter(Boolean)) {
|
|
196
|
-
const
|
|
204
|
+
const separator = entry.indexOf('\t')
|
|
205
|
+
const meta = entry.slice(0, separator), path = entry.slice(separator + 1)
|
|
197
206
|
const [mode = '', , oid = ''] = meta.split(' ')
|
|
198
207
|
entries.set(path, { mode, oid })
|
|
199
208
|
}
|
|
@@ -208,7 +217,11 @@ class ReviewTrees {
|
|
|
208
217
|
const blob = await this.#git(['cat-file', 'blob', entry.oid])
|
|
209
218
|
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
219
|
}
|
|
211
|
-
|
|
220
|
+
return changes
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async #write(tree: string, paths: string[]): Promise<void> {
|
|
224
|
+
await this.#files!.write(await this.read(tree, paths))
|
|
212
225
|
}
|
|
213
226
|
|
|
214
227
|
async reset(tree: string): Promise<void> {
|
|
@@ -227,6 +240,8 @@ export interface GitReviewOptions {
|
|
|
227
240
|
onRestore?: (paths: string[]) => void
|
|
228
241
|
warn?: (message: string) => void
|
|
229
242
|
files?: DocumentFiles
|
|
243
|
+
recordRoot?: string
|
|
244
|
+
workspace?: ReviewRecord['workspace']
|
|
230
245
|
}
|
|
231
246
|
|
|
232
247
|
const recovering = new Map<string, Promise<{ task: string, paths: string[] } | undefined>>()
|
|
@@ -298,7 +313,7 @@ export async function openGitReview(options: GitReviewOptions & { session?: Omit
|
|
|
298
313
|
throw error
|
|
299
314
|
}
|
|
300
315
|
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: [] } } : {} }
|
|
316
|
+
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
317
|
return createGitReview({ scopeDir, trees, restoreGitDir: guard.restore, record, warn: options.warn })
|
|
303
318
|
}
|
|
304
319
|
|
|
@@ -335,7 +350,7 @@ function createGitReview(open: { scopeDir: string, trees: ReviewTrees, restoreGi
|
|
|
335
350
|
if (settled) return
|
|
336
351
|
settled = true
|
|
337
352
|
openScopes.delete(scopeDir)
|
|
338
|
-
if (!suspended) removeRecord(scopeDir)
|
|
353
|
+
if (!suspended) removeRecord(record.recordRoot ?? scopeDir)
|
|
339
354
|
trees.dispose()
|
|
340
355
|
}
|
|
341
356
|
const live = () => {
|
|
@@ -349,6 +364,12 @@ function createGitReview(open: { scopeDir: string, trees: ReviewTrees, restoreGi
|
|
|
349
364
|
await trees.restore(snapshot, [...rejected])
|
|
350
365
|
return changes.filter(path => !rejected.has(path))
|
|
351
366
|
}
|
|
367
|
+
const inspect = async (details = false) => {
|
|
368
|
+
live()
|
|
369
|
+
restoreGitDir()
|
|
370
|
+
const tree = await trees.tree()
|
|
371
|
+
return { tree, version: createHash('sha256').update(JSON.stringify([snapshot, tree, checkpoints])).digest('hex'), changes: await trees.compare(snapshot, tree, details) }
|
|
372
|
+
}
|
|
352
373
|
|
|
353
374
|
return {
|
|
354
375
|
root: scopeDir,
|
|
@@ -372,10 +393,21 @@ function createGitReview(open: { scopeDir: string, trees: ReviewTrees, restoreGi
|
|
|
372
393
|
return step
|
|
373
394
|
},
|
|
374
395
|
steps: () => steps,
|
|
375
|
-
|
|
396
|
+
inspect,
|
|
397
|
+
readTree: (tree, paths) => { live(); return trees.read(tree, paths.map(trees.toGit)) },
|
|
398
|
+
async assertTree(tree, except) {
|
|
399
|
+
live()
|
|
400
|
+
if ((await trees.changedPaths(tree, await trees.tree())).some(path => !except.includes(path))) throw new Error('workspace-review-changed')
|
|
401
|
+
},
|
|
402
|
+
diff: async () => (await inspect(true)).changes,
|
|
403
|
+
async diffFile(path, step) {
|
|
376
404
|
live()
|
|
377
405
|
restoreGitDir()
|
|
378
|
-
|
|
406
|
+
const at = step === undefined ? -1 : steps.findIndex(value => value.id === step)
|
|
407
|
+
if (step !== undefined && at < 0) return
|
|
408
|
+
const from = at < 0 ? snapshot : checkpoints[at]!, to = at < 0 ? await trees.tree() : checkpoints[at + 1]!
|
|
409
|
+
if (!(await trees.compare(from, to, false, path)).some(change => change.path === path)) return
|
|
410
|
+
return (await trees.compare(from, to, true, path)).find(change => change.path === path)
|
|
379
411
|
},
|
|
380
412
|
async restoreTo(stepId) {
|
|
381
413
|
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
|
|
@@ -12,12 +13,15 @@ export interface AgentSessionRecord {
|
|
|
12
13
|
member: Member
|
|
13
14
|
turns: { from: number, to: number }
|
|
14
15
|
opened: string
|
|
16
|
+
backend?: 'deltabox'
|
|
15
17
|
checkpoints: string[]
|
|
16
18
|
steps: ReviewStep[]
|
|
17
19
|
}
|
|
18
20
|
|
|
19
21
|
/** A review in progress, kept in the user's state directory so that another process can roll it back or resume it. */
|
|
20
22
|
export interface ReviewRecord {
|
|
23
|
+
recordRoot?: string
|
|
24
|
+
workspace?: AgentWorkspaceRecord
|
|
21
25
|
/** The directory the review covers: a document's for a plugin's task, the workspace root for an agent session. */
|
|
22
26
|
scopeDir: string
|
|
23
27
|
dirs: GitDirs
|
|
@@ -66,7 +70,7 @@ export function readRecord(scopeDir: string): ReviewRecord | undefined {
|
|
|
66
70
|
}
|
|
67
71
|
|
|
68
72
|
export function writeRecord(record: ReviewRecord): void {
|
|
69
|
-
const file = recordFile(record.scopeDir)
|
|
73
|
+
const file = recordFile(record.recordRoot ?? record.scopeDir)
|
|
70
74
|
mkdirSync(recordsDir(), { recursive: true, mode: 0o700 })
|
|
71
75
|
writeFileSync(`${file}.${process.pid}`, JSON.stringify(record), { mode: 0o600 })
|
|
72
76
|
renameSync(`${file}.${process.pid}`, file)
|
|
@@ -18,6 +18,14 @@ 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.resumed === true) await reviews.resumeWorkspace(session)
|
|
26
|
+
const changed = body.refresh === true ? await reviews.refreshWorkspace(session) : false
|
|
27
|
+
return jsonResponse({ ...await reviews.workspace(session), changed })
|
|
28
|
+
}),
|
|
21
29
|
'review': {
|
|
22
30
|
role: 'editor',
|
|
23
31
|
handle: (request, ctx) => catchRequestErrors(async () => {
|
|
@@ -39,7 +47,7 @@ export function reviewRoutes(reviews: AgentSessionReviews): Record<string, Route
|
|
|
39
47
|
const session = toText(body.session, 200)
|
|
40
48
|
if (!session) return problemResponse(400, '{ session, turn? }')
|
|
41
49
|
const turn = toTurn(body.turn)
|
|
42
|
-
return jsonResponse({ review: await reviews.open(ctx.document, { session, ...turn !== undefined ? { turn } : {} }, ctx.member) })
|
|
50
|
+
return jsonResponse({ review: await reviews.open(ctx.document, { session, ...turn !== undefined ? { turn } : {}, ...body.backend === 'deltabox' ? { backend: 'deltabox' as const } : {} }, ctx.member) })
|
|
43
51
|
}),
|
|
44
52
|
},
|
|
45
53
|
'review/step': post(async (body, document) => {
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { hasRole, WORKSPACE_REVIEW_FRAGMENT_CHARS, WORKSPACE_REVIEW_MAX_REQUEST_CHARS, WORKSPACE_REVIEW_MAX_RESPONSE_CHARS } from '@lincyaw/kernel'
|
|
3
|
+
import type { Member, WorkspaceReview, WorkspaceReviewAnswer, WorkspaceReviewChange } from '@lincyaw/kernel'
|
|
4
|
+
import { validateWorkspaceReviewChange, validateWorkspaceReviewQuery } from '@lincyaw/kernel/node'
|
|
5
|
+
import { RequestError } from '../errors.ts'
|
|
6
|
+
import type { AgentSessionReviews } from './agent-session-reviews.ts'
|
|
7
|
+
|
|
8
|
+
const size = (value: unknown) => JSON.stringify(value).length
|
|
9
|
+
const authorize = (member: Member) => { if (!hasRole(member, 'owner')) throw new RequestError(403, 'workspace-review-permission-denied') }
|
|
10
|
+
const budget = (value: unknown) => { if (size(value) > WORKSPACE_REVIEW_MAX_REQUEST_CHARS) throw new RequestError(413, 'workspace-review-request-too-large') }
|
|
11
|
+
const fits = (value: unknown) => size(value) <= WORKSPACE_REVIEW_MAX_RESPONSE_CHARS
|
|
12
|
+
|
|
13
|
+
/** Bounded publication interface over the same review queue, candidate trees and writer used by Web. */
|
|
14
|
+
export function createWorkspaceReview(reviews: AgentSessionReviews): WorkspaceReview {
|
|
15
|
+
const inspect = async (change: WorkspaceReviewChange, member: Member) => {
|
|
16
|
+
authorize(member); budget(change)
|
|
17
|
+
if (!validateWorkspaceReviewChange(change)) throw new RequestError(400, 'workspace-review-change-invalid')
|
|
18
|
+
const state = await reviews.inspect()
|
|
19
|
+
if (!state || state.snapshot !== change.snapshot) throw new RequestError(409, 'workspace-review-changed')
|
|
20
|
+
if (state.review.running) throw new RequestError(409, 'workspace-review-running')
|
|
21
|
+
if (change.action === 'restore') {
|
|
22
|
+
if (!state.review.steps.some(step => step.id === change.step)) throw new RequestError(404, 'workspace-review-step-not-found')
|
|
23
|
+
} else {
|
|
24
|
+
const selected = change.action === 'accept' ? change.reject : change.paths
|
|
25
|
+
if (selected?.some(path => !state.review.changes.some(file => file.path === path))) throw new RequestError(409, 'workspace-review-path-changed')
|
|
26
|
+
}
|
|
27
|
+
return state
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
async read(query, member) {
|
|
31
|
+
authorize(member); budget(query)
|
|
32
|
+
if (!validateWorkspaceReviewQuery(query)) throw new RequestError(400, 'workspace-review-query-invalid')
|
|
33
|
+
const part = query.part ?? 'summary', offset = query.offset ?? 0
|
|
34
|
+
if ((query.path !== undefined || query.step !== undefined) && part !== 'diff' || offset > 0 && !query.snapshot || part === 'summary' && offset !== 0) throw new RequestError(400, 'workspace-review-query-invalid')
|
|
35
|
+
const state = await reviews.inspect()
|
|
36
|
+
if (query.snapshot !== undefined && state?.snapshot !== query.snapshot) throw new RequestError(409, 'workspace-review-changed')
|
|
37
|
+
if (!state) {
|
|
38
|
+
if (part !== 'summary') throw new RequestError(404, 'workspace-review-not-found')
|
|
39
|
+
return { review: null }
|
|
40
|
+
}
|
|
41
|
+
const { review, snapshot } = state
|
|
42
|
+
const answer: WorkspaceReviewAnswer = { review: { id: review.id, document: review.document, running: review.running, mode: review.mode, files: review.changes.length, steps: review.steps.length }, snapshot }
|
|
43
|
+
if (!fits(answer)) throw new RequestError(413, 'workspace-review-response-too-large')
|
|
44
|
+
if (part === 'summary') return answer
|
|
45
|
+
if (part === 'diff') {
|
|
46
|
+
if (!query.path) throw new RequestError(400, 'workspace-review-query-invalid')
|
|
47
|
+
if (query.step && !review.steps.some(step => step.id === query.step)) throw new RequestError(404, 'workspace-review-step-not-found')
|
|
48
|
+
const change = await reviews.readDiff(snapshot, query.path, query.step)
|
|
49
|
+
if (!change) throw new RequestError(404, 'workspace-review-file-not-found')
|
|
50
|
+
if (change.diff === undefined) throw new RequestError(409, 'workspace-review-diff-unavailable')
|
|
51
|
+
const totalChars = change.diff.length
|
|
52
|
+
if (offset > totalChars) throw new RequestError(400, 'workspace-review-query-invalid')
|
|
53
|
+
answer.diff = { path: query.path, ...query.step ? { step: query.step } : {}, text: change.diff.slice(offset, offset + WORKSPACE_REVIEW_FRAGMENT_CHARS), offset, totalChars, sha256: createHash('sha256').update(change.diff).digest('hex') }
|
|
54
|
+
const cursor = () => { if (offset + answer.diff!.text.length < totalChars) answer.nextOffset = offset + answer.diff!.text.length; else delete answer.nextOffset }
|
|
55
|
+
cursor()
|
|
56
|
+
while (!fits(answer) && answer.diff.text.length) { answer.diff.text = answer.diff.text.slice(0, Math.floor(answer.diff.text.length / 2)); cursor() }
|
|
57
|
+
if (!fits(answer) || !answer.diff.text.length && offset < totalChars) throw new RequestError(413, 'workspace-review-response-too-large')
|
|
58
|
+
return answer
|
|
59
|
+
}
|
|
60
|
+
const rows = part === 'files' ? review.changes : review.steps.map(({ changes, ...step }) => ({ ...step, label: step.label.slice(0, 240), ...step.tool ? { tool: step.tool.slice(0, 100) } : {}, files: changes.length }))
|
|
61
|
+
if (offset > rows.length) throw new RequestError(400, 'workspace-review-query-invalid')
|
|
62
|
+
const selected: unknown[] = []
|
|
63
|
+
for (const row of rows.slice(offset, offset + 20)) {
|
|
64
|
+
if (!fits({ ...answer, [part]: [...selected, row], nextOffset: offset + selected.length + 1 })) break
|
|
65
|
+
selected.push(row)
|
|
66
|
+
}
|
|
67
|
+
if (!selected.length && offset < rows.length) throw new RequestError(413, 'workspace-review-response-too-large')
|
|
68
|
+
Object.assign(answer, { [part]: selected }, offset + selected.length < rows.length ? { nextOffset: offset + selected.length } : {})
|
|
69
|
+
return answer
|
|
70
|
+
},
|
|
71
|
+
async check(change, member) { await inspect(change, member); await reviews.check(change.snapshot) },
|
|
72
|
+
async change(change, member, signal) {
|
|
73
|
+
const state = await inspect(change, member)
|
|
74
|
+
signal?.throwIfAborted()
|
|
75
|
+
if (change.action === 'accept') {
|
|
76
|
+
const ended = await reviews.accept(state.review.document, { reject: change.reject, message: change.message, expected: change.snapshot }, signal)
|
|
77
|
+
return { outcome: ended.outcome === 'accepted' ? 'accepted' : 'empty', ...ended.revision ? { revision: ended.revision.id } : {}, files: ended.files.length }
|
|
78
|
+
}
|
|
79
|
+
if (change.action === 'reject') {
|
|
80
|
+
const result = await reviews.reject(state.review.document, { paths: change.paths, expected: change.snapshot }, signal)
|
|
81
|
+
return result.ended ? { outcome: 'rejected', files: result.ended.files.length } : { outcome: 'updated', remainingFiles: result.review?.changes.length ?? 0 }
|
|
82
|
+
}
|
|
83
|
+
const result = await reviews.restore(state.review.document, { step: change.step, expected: change.snapshot }, signal)
|
|
84
|
+
return { outcome: 'restored', remainingFiles: result.changes.length }
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readlinkSync, realpathSync } from 'node:fs'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import type { DocumentFileChange } from '@lincyaw/kernel'
|
|
5
|
+
import { RequestError } from './errors.ts'
|
|
6
|
+
import { DOCUMENT_OPERATION_MAX_BACKUP_BYTES, DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES } from './writer.ts'
|
|
7
|
+
|
|
8
|
+
export interface RevisionFile {
|
|
9
|
+
path: string
|
|
10
|
+
mode: '000000' | '100644' | '100755' | '120000' | 'unsupported'
|
|
11
|
+
stamp: string
|
|
12
|
+
change?: DocumentFileChange
|
|
13
|
+
}
|
|
14
|
+
export const revisionDigest = (value: string | Uint8Array) => createHash('sha256').update(value).digest('hex')
|
|
15
|
+
|
|
16
|
+
/** Raw preimages are distinct from filtered Git blobs, particularly for CRLF files and symlinks. */
|
|
17
|
+
export function revisionFiles(root: string, paths: string[]): RevisionFile[] {
|
|
18
|
+
if (paths.length > DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES) throw new RequestError(413, 'changes-selection-too-large')
|
|
19
|
+
let total = 0
|
|
20
|
+
return paths.map(path => {
|
|
21
|
+
const parts = path.split('/')
|
|
22
|
+
if (!path || path.startsWith('/') || path.includes('\0') || parts.some(part => !part || part === '.' || part === '..' || part === '.git')) throw new RequestError(403, 'changes-path-forbidden')
|
|
23
|
+
if (path.includes('\\')) return { path, mode: 'unsupported', stamp: 'unsupported-name' }
|
|
24
|
+
let parent = root
|
|
25
|
+
for (const part of parts.slice(0, -1)) {
|
|
26
|
+
parent = join(parent, part)
|
|
27
|
+
const entry = lstatSync(parent, { throwIfNoEntry: false })
|
|
28
|
+
if (!entry) break
|
|
29
|
+
if (!entry.isDirectory() || realpathSync(parent) !== parent) return { path, mode: 'unsupported', stamp: 'unsafe-parent' }
|
|
30
|
+
}
|
|
31
|
+
const file = join(root, path), before = lstatSync(file, { throwIfNoEntry: false })
|
|
32
|
+
if (!before) return { path, mode: '000000', stamp: 'absent', change: { path, remove: true } }
|
|
33
|
+
if (before.isSymbolicLink()) {
|
|
34
|
+
const link = readlinkSync(file), after = lstatSync(file)
|
|
35
|
+
if (before.ino !== after.ino || before.dev !== after.dev || before.ctimeMs !== after.ctimeMs) throw new RequestError(409, 'changes-state-changed')
|
|
36
|
+
return { path, mode: '120000', stamp: revisionDigest('link:' + link), change: { path, link } }
|
|
37
|
+
}
|
|
38
|
+
if (!before.isFile()) return { path, mode: 'unsupported', stamp: `unsupported:${before.mode}` }
|
|
39
|
+
if ((total += before.size) > DOCUMENT_OPERATION_MAX_BACKUP_BYTES) throw new RequestError(413, 'changes-selection-too-large')
|
|
40
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
|
|
41
|
+
try {
|
|
42
|
+
const opened = fstatSync(fd)
|
|
43
|
+
if (!opened.isFile() || opened.ino !== before.ino || opened.dev !== before.dev || opened.size !== before.size) throw new RequestError(409, 'changes-state-changed')
|
|
44
|
+
const buffer = Buffer.alloc(opened.size + 1)
|
|
45
|
+
let length = 0, count = 0
|
|
46
|
+
while (length < buffer.length && (count = readSync(fd, buffer, length, buffer.length - length, null)) > 0) length += count
|
|
47
|
+
const bytes = buffer.subarray(0, length), after = fstatSync(fd), current = lstatSync(file)
|
|
48
|
+
if (length !== opened.size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs
|
|
49
|
+
|| current.ino !== opened.ino || current.dev !== opened.dev || realpathSync(file) !== file) throw new RequestError(409, 'changes-state-changed')
|
|
50
|
+
const executable = (opened.mode & 0o111) !== 0
|
|
51
|
+
return { path, mode: executable ? '100755' : '100644', stamp: revisionDigest(bytes), change: { path, content: bytes, executable } }
|
|
52
|
+
} finally { closeSync(fd) }
|
|
53
|
+
})
|
|
54
|
+
}
|