@lincyaw/workspace 1.0.0-rc.46 → 1.0.0-rc.48

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workspace",
3
- "version": "1.0.0-rc.46",
3
+ "version": "1.0.0-rc.48",
4
4
  "description": "Presmium's workspace service (presmium serve): documents, their history, reviews and the workspace site",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -34,12 +34,12 @@
34
34
  "mime-types": "3.0.2",
35
35
  "playwright-chromium": "1.64.1",
36
36
  "yaml": "^2.9.1",
37
- "@lincyaw/compiler": "1.0.0-rc.46",
38
- "@lincyaw/kernel": "1.0.0-rc.46",
39
- "@lincyaw/server": "1.0.0-rc.46"
37
+ "@lincyaw/compiler": "1.0.0-rc.48",
38
+ "@lincyaw/kernel": "1.0.0-rc.48",
39
+ "@lincyaw/server": "1.0.0-rc.48"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@types/mime-types": "^3.0.1",
43
- "@lincyaw/mcp": "1.0.0-rc.46"
43
+ "@lincyaw/mcp": "1.0.0-rc.48"
44
44
  }
45
45
  }
@@ -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
+ }
@@ -1,8 +1,9 @@
1
- import { existsSync, lstatSync, mkdtempSync, readdirSync, readFileSync, rmdirSync, rmSync, writeFileSync } from 'node:fs'
1
+ import { randomUUID } from 'node:crypto'
2
+ import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, writeFileSync } from 'node:fs'
2
3
  import { tmpdir } from 'node:os'
3
- import { join, relative, resolve, sep } from 'node:path'
4
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path'
4
5
  import type { DocumentFileChange, HistoryRevision, Member, RevertResult, Revision, RevisionsAnswer, RevisionService, UncommittedFile } from '@lincyaw/kernel'
5
- import { LOCAL_AUTHOR } from '@lincyaw/kernel'
6
+ import { CHANGES_MAX_BYTES, LOCAL_AUTHOR, SOURCE_MAX_BYTES } from '@lincyaw/kernel'
6
7
  import { leavesRoot } from '../domain/paths.ts'
7
8
  import { commitMessage, memberAddress, originOf } from '../domain/commit-message.ts'
8
9
  import type { CommitOrigin } from '../domain/commit-message.ts'
@@ -12,6 +13,8 @@ import { RequestError } from './errors.ts'
12
13
  import type { Git } from './git.ts'
13
14
  import { documentDirOf, isGeneratedPath, makeDocumentDir, writeChanges } from './writer.ts'
14
15
  import type { DocumentWriter } from './writer.ts'
16
+ import { revisionDigest, revisionFiles } from './revision-files.ts'
17
+ import type { RevisionFile } from './revision-files.ts'
15
18
 
16
19
  const FIELD = '\x00'
17
20
  const RECORD = '\x1e'
@@ -178,6 +181,18 @@ export interface LockedCommit {
178
181
  trailers?: [string, string][]
179
182
  }
180
183
 
184
+ export interface RevisionChanges {
185
+ head?: string
186
+ ref?: string
187
+ index?: Buffer
188
+ indexPath: string
189
+ indexStamp: string
190
+ snapshot: string
191
+ files: UncommittedFile[]
192
+ encoded?: TreeFile[]
193
+ raw: RevisionFile[]
194
+ }
195
+
181
196
  export class Revisions implements RevisionService {
182
197
  readonly #git: Git
183
198
  readonly #files: RevisionFiles
@@ -187,19 +202,9 @@ export class Revisions implements RevisionService {
187
202
  this.#files = files
188
203
  }
189
204
 
190
- /** One authoring transaction holds the git queue and restores its index if file saving or committing fails. */
205
+ /** Serialize authoring work; commitWhileLocked owns its index changes and rollback. */
191
206
  transaction<T>(work: () => Promise<T>): Promise<T> {
192
- return this.#git.exclusive(async () => {
193
- const index = resolve(this.#git.root, (await this.#git.output(['rev-parse', '--git-path', 'index'])).trim())
194
- const before = existsSync(index) ? readFileSync(index) : undefined
195
- try {
196
- return await work()
197
- } catch (error) {
198
- if (before) writeFileSync(index, before)
199
- else rmSync(index, { force: true })
200
- throw error
201
- }
202
- })
207
+ return this.#git.exclusive(work)
203
208
  }
204
209
 
205
210
  commit(change: { files: string[], message: string, origin: CommitOrigin, trailers?: [string, string][] }): Promise<Revision | undefined> {
@@ -209,17 +214,174 @@ export class Revisions implements RevisionService {
209
214
 
210
215
  /** Commits the paths; the caller holds the git lock (`Git.exclusive`). */
211
216
  async commitWhileLocked(commit: LockedCommit): Promise<Revision | undefined> {
212
- const { summary, body } = commit
213
217
  const unique = [...new Set(commit.paths.map(path => path.replace(/^\.?\/+|\/+$/g, '')).filter(path => path && !leavesRoot(path)))]
214
218
  if (unique.length === 0) return undefined
215
- await this.#git.output(['add', '-A', '--', ...unique], { GIT_LITERAL_PATHSPECS: '1' })
216
- const staged = (await this.#git.output(['diff', '--cached', '--name-only', '--', ...unique], { GIT_LITERAL_PATHSPECS: '1' })).trim()
217
- if (!staged) return undefined
218
- const member = await this.#author(commit.origin.member)
219
- const origin = { ...commit.origin, ...member ? { member } : {} }
220
- const message = withTrailers(commitMessage(summary, body, origin, commit.revert), commit.trailers ?? [])
221
- await this.#git.output([...await this.#identity(), 'commit', '-q', '--no-verify', '-m', message, ...member ? [`--author=${memberAddress(member)}`] : [], '--', ...unique], { GIT_LITERAL_PATHSPECS: '1' })
222
- return this.#revision('HEAD')
219
+ const captured = await this.observeChanges(unique)
220
+ if (!captured.raw.length) return undefined
221
+ return this.#applyFrozen('commit', await this.freezeCommit(captured), commit)
222
+ }
223
+
224
+ /** Exact current raw bytes, HEAD/ref and index observation; never compiles or stages the real index. */
225
+ async observeChanges(roots: string[] = ['']): Promise<RevisionChanges> {
226
+ const before = await this.#changeState(), files = await this.uncommittedFiles(roots)
227
+ const raw = revisionFiles(this.#files.config.root, files.map(file => file.path))
228
+ const after = await this.#changeState()
229
+ if (!this.#sameState(before, after)) throw new RequestError(409, 'changes-state-changed')
230
+ return { ...before, files, raw, snapshot: revisionDigest(JSON.stringify([before.head, before.ref, before.indexStamp, raw.map(file => [file.path, file.mode, file.stamp])])) }
231
+ }
232
+
233
+ /** Encode approved raw bytes before an external confirmation; later filters cannot change these blobs. */
234
+ async freezeCommit(captured: RevisionChanges): Promise<RevisionChanges> {
235
+ await this.#verifyChanges(captured)
236
+ const encoded: TreeFile[] = []
237
+ for (const file of captured.raw) {
238
+ const data = file.change
239
+ if (!data) throw new RequestError(409, 'changes-file-unsupported')
240
+ if ('remove' in data) { encoded.push({ path: file.path, mode: '000000', oid: '' }); continue }
241
+ const bytes = 'link' in data ? Buffer.from(data.link) : Buffer.from(data.content)
242
+ const blob = await this.#git.run(['hash-object', '-w', ...'link' in data ? ['--no-filters'] : [`--path=${file.path}`], '--stdin'], {}, bytes)
243
+ if (blob.code !== 0) throw new RequestError(409, 'changes-encoding-failed')
244
+ encoded.push({ path: file.path, mode: file.mode, oid: blob.stdout.toString('utf8').trim() })
245
+ }
246
+ await this.#verifyChanges(captured)
247
+ return { ...captured, encoded }
248
+ }
249
+
250
+ /** Caller holds document locks; this is the only Git queue entry for a reviewed changes operation. */
251
+ applyChanges(which: 'commit' | 'discard', captured: RevisionChanges, commit?: LockedCommit, check?: () => void): Promise<Revision | undefined> {
252
+ return this.#git.exclusive(async () => this.#applyFrozen(which, which === 'commit' && !captured.encoded ? await this.freezeCommit(captured) : captured, commit, check))
253
+ }
254
+
255
+ async #changeState() {
256
+ const [head, ref, indexName] = await Promise.all([
257
+ this.#git.run(['rev-parse', '--verify', '--quiet', 'HEAD']),
258
+ this.#git.run(['symbolic-ref', '--quiet', 'HEAD']),
259
+ this.#git.output(['rev-parse', '--git-path', 'index']),
260
+ ])
261
+ if (ref.code !== 0 && ref.code !== 1 || head.code !== 0 && !(head.code === 1 && ref.code === 0)) throw new RequestError(409, 'changes-repository-unavailable')
262
+ const indexPath = resolve(this.#git.root, indexName.trim()), index = existsSync(indexPath) ? readFileSync(indexPath) : undefined
263
+ return { ...head.code === 0 ? { head: head.stdout.toString('utf8').trim() } : {}, ...ref.code === 0 ? { ref: ref.stdout.toString('utf8').trim() } : {}, indexPath, index, indexStamp: index ? revisionDigest(index) : 'absent' }
264
+ }
265
+
266
+ #sameState(a: Pick<RevisionChanges, 'head' | 'ref' | 'indexStamp'>, b: Pick<RevisionChanges, 'head' | 'ref' | 'indexStamp'>): boolean {
267
+ return a.head === b.head && a.ref === b.ref && a.indexStamp === b.indexStamp
268
+ }
269
+
270
+ async #verifyChanges(captured: RevisionChanges, files = true): Promise<void> {
271
+ if (!this.#sameState(captured, await this.#changeState())) throw new RequestError(409, 'changes-state-changed')
272
+ if (files) {
273
+ const current = revisionFiles(this.#files.config.root, captured.raw.map(file => file.path))
274
+ if (JSON.stringify(current.map(file => [file.path, file.mode, file.stamp])) !== JSON.stringify(captured.raw.map(file => [file.path, file.mode, file.stamp]))) throw new RequestError(409, 'changes-state-changed')
275
+ }
276
+ }
277
+
278
+ async #applyFrozen(which: 'commit' | 'discard', captured: RevisionChanges, commit?: LockedCommit, check?: () => void): Promise<Revision | undefined> {
279
+ if (!captured.raw.length || captured.raw.some(file => !file.change)) throw new RequestError(409, 'changes-file-unsupported')
280
+ const gitDir = resolve(this.#git.root, (await this.#git.output(['rev-parse', '--git-dir'])).trim())
281
+ if (['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'rebase-merge', 'rebase-apply', 'sequencer'].some(name => existsSync(join(gitDir, name)))
282
+ || (await this.#git.output(['ls-files', '--unmerged', '-z'])).length) throw new RequestError(409, 'changes-repository-busy')
283
+ const lock = `${captured.indexPath}.lock`
284
+ let fd: number
285
+ try { fd = openSync(lock, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600) }
286
+ catch { throw new RequestError(409, 'changes-index-busy') }
287
+ // The review Git guard already excludes *.lock entries; active private indexes must share that lifetime.
288
+ let identity: ReturnType<typeof fstatSync> | undefined
289
+ const work = join(dirname(captured.indexPath), `presmium-index-${randomUUID()}.lock`)
290
+ let installed = false, published = false, wrote = false, created = false, recovery = false
291
+ const restoreIndex = () => {
292
+ if (captured.index) { const previous = join(work, 'previous'); writeFileSync(previous, captured.index, { mode: 0o600 }); renameSync(previous, captured.indexPath) }
293
+ else rmSync(captured.indexPath, { force: true })
294
+ }
295
+ try {
296
+ identity = fstatSync(fd)
297
+ mkdirSync(work, { mode: 0o700 }); created = true
298
+ await this.#verifyChanges(captured); check?.()
299
+ const env = (name: string) => ({ GIT_INDEX_FILE: join(work, name), GIT_LITERAL_PATHSPECS: '1', GIT_OPTIONAL_LOCKS: '0' })
300
+ const next = env('next'), selected = env('selected')
301
+ if (captured.index) writeFileSync(next.GIT_INDEX_FILE, captured.index)
302
+ else await this.#git.output(['read-tree', '--empty'], next)
303
+ await this.#git.output(['read-tree', captured.head ?? '--empty'], selected)
304
+ const base = (await this.#git.output(['write-tree'], selected)).trim()
305
+ const files: TreeFile[] = []
306
+ const targets: DocumentFileChange[] = []
307
+ const encoded = new Map(captured.encoded?.map(file => [file.path, file]))
308
+ let targetBytes = 0
309
+ for (const file of captured.raw) {
310
+ if (which === 'discard') {
311
+ const item = await this.#atTree(captured.head, file.path)
312
+ files.push(item)
313
+ const target = await this.#treeChange(item, CHANGES_MAX_BYTES - targetBytes)
314
+ targetBytes += 'content' in target ? Buffer.byteLength(target.content) : 'link' in target ? Buffer.byteLength(target.link) : 0
315
+ targets.push(target)
316
+ } else {
317
+ const frozen = encoded.get(file.path)
318
+ if (!frozen) throw new RequestError(409, 'changes-encoding-failed')
319
+ files.push(frozen)
320
+ }
321
+ }
322
+ const zero = '0'.repeat(base.length)
323
+ const input = Buffer.from(files.map(file => `${/^0+$/.test(file.mode) ? '0' : file.mode} ${file.oid || zero}\t${relative(this.#git.top, join(this.#files.config.root, file.path)).split(sep).join('/')}\0`).join(''))
324
+ for (const index of [next, selected]) {
325
+ const updated = await this.#git.run(['-C', this.#git.top, 'update-index', '-z', '--index-info'], index, input)
326
+ if (updated.code !== 0) throw new RequestError(409, 'changes-index-update-failed')
327
+ }
328
+ let revision: Revision | undefined
329
+ if (which === 'commit') {
330
+ if (!commit) throw new RequestError(400, 'changes-request-invalid')
331
+ const tree = (await this.#git.output(['write-tree'], selected)).trim()
332
+ if (tree !== base) {
333
+ const member = await this.#author(commit.origin.member), origin = { ...commit.origin, ...member ? { member } : {} }
334
+ const message = withTrailers(commitMessage(commit.summary, commit.body, origin, commit.revert), commit.trailers ?? [])
335
+ const author = member && /^(.*) <([^>]*)>$/.exec(memberAddress(member))
336
+ const hash = (await this.#git.output([...await this.#identity(), 'commit-tree', tree, ...captured.head ? ['-p', captured.head] : [], '-m', message], { ...selected, ...author ? { GIT_AUTHOR_NAME: author[1]!, GIT_AUTHOR_EMAIL: author[2]! } : {} })).trim()
337
+ revision = await this.#revision(hash)
338
+ if (!revision) throw new RequestError(409, 'changes-revision-unavailable')
339
+ }
340
+ }
341
+ // Blobs are already fixed; preserve late working edits while verifying the real index and branch.
342
+ await this.#verifyChanges(captured, which === 'discard'); check?.()
343
+ if (which === 'discard') { wrote = true; await this.#writeChanges(targets) }
344
+ renameSync(next.GIT_INDEX_FILE, captured.indexPath); installed = true
345
+ if (revision) {
346
+ const result = await this.#git.run(['update-ref', captured.ref ?? 'HEAD', revision.id, captured.head ?? zero])
347
+ if (result.code !== 0) throw new RequestError(409, 'changes-state-changed')
348
+ published = true
349
+ }
350
+ return revision
351
+ } catch (error) {
352
+ if (!published) {
353
+ try { if (wrote) await this.#writeChanges(captured.raw.map(file => file.change!)) } catch { recovery = true }
354
+ try { if (installed) restoreIndex() } catch { recovery = true }
355
+ if (recovery) throw new RequestError(500, 'changes-recovery-required')
356
+ }
357
+ throw error
358
+ } finally {
359
+ // Cleanup cannot turn an already published commit into a reported failure.
360
+ try { closeSync(fd) } catch {}
361
+ try {
362
+ const current = lstatSync(lock, { throwIfNoEntry: false })
363
+ if (identity && current?.ino === identity.ino && current.dev === identity.dev) rmSync(lock, { force: true })
364
+ } catch {}
365
+ try { if (created && !recovery) rmSync(work, { recursive: true, force: true }) } catch {}
366
+ }
367
+ }
368
+
369
+ async #atTree(head: string | undefined, path: string): Promise<TreeFile> {
370
+ if (!head) return { path, mode: '000000', oid: '' }
371
+ const raw = await this.#git.output(['ls-tree', '-z', head, '--', path], { GIT_LITERAL_PATHSPECS: '1' })
372
+ const entry = raw.split('\0')[0] ?? '', at = entry.indexOf('\t'), meta = entry.slice(0, at).split(' ')
373
+ if (at < 0) return { path, mode: '000000', oid: '' }
374
+ if (!['100644', '100755', '120000'].includes(meta[0] ?? '')) throw new RequestError(409, 'changes-file-unsupported')
375
+ return { path, mode: meta[0]!, oid: meta[2]! }
376
+ }
377
+
378
+ async #treeChange(file: TreeFile, maxBytes = CHANGES_MAX_BYTES): Promise<DocumentFileChange> {
379
+ if (/^0+$/.test(file.mode)) return { path: file.path, remove: true }
380
+ const size = Number((await this.#git.output(['cat-file', '-s', file.oid])).trim())
381
+ if (!Number.isSafeInteger(size) || size > maxBytes) throw new RequestError(413, 'changes-selection-too-large')
382
+ const blob = await this.#git.run(['cat-file', 'blob', file.oid])
383
+ if (blob.code !== 0) throw new RequestError(409, 'changes-object-unavailable')
384
+ return file.mode === '120000' ? { path: file.path, link: blob.stdout.toString('utf8') } : { path: file.path, content: blob.stdout, executable: file.mode === '100755' }
223
385
  }
224
386
 
225
387
  async status(paths: string[] = ['']): Promise<{ branch?: string, uncommitted: number }> {
@@ -231,10 +393,10 @@ export class Revisions implements RevisionService {
231
393
  const specs = paths.map(path => path || '.')
232
394
  const status = await this.#statusOf(paths)
233
395
  const counts = new Map<string, [number, number]>()
234
- const numstat = await this.#git.tryOutput(['diff', '--numstat', '-z', '--no-renames', 'HEAD', '--', ...specs], { GIT_LITERAL_PATHSPECS: '1' })
396
+ const numstat = await this.#git.tryOutput(['-c', 'diff.autoRefreshIndex=false', 'diff', '--numstat', '-z', '--no-renames', '--no-ext-diff', '--no-textconv', 'HEAD', '--', ...specs], { GIT_LITERAL_PATHSPECS: '1', GIT_OPTIONAL_LOCKS: '0' })
235
397
  if (numstat.ok) {
236
398
  for (const entry of numstat.output.split('\0').filter(Boolean)) {
237
- const [added = '-', removed = '-', path = ''] = entry.split('\t')
399
+ const [added = '-', removed = '-', ...named] = entry.split('\t'), path = named.join('\t')
238
400
  if (added !== '-') counts.set(this.#fromTop(path), [Number(added), Number(removed)])
239
401
  }
240
402
  }
@@ -247,14 +409,8 @@ export class Revisions implements RevisionService {
247
409
 
248
410
  discard(paths: string[]): Promise<void> {
249
411
  return this.#git.exclusive(async () => {
250
- const files: TreeFile[] = []
251
- for (const path of paths) {
252
- const listed = await this.#git.tryOutput(['ls-tree', '-z', 'HEAD', '--', path], { GIT_LITERAL_PATHSPECS: '1' })
253
- const [meta = '', named] = (listed.ok ? listed.output.split('\0')[0] ?? '' : '').split('\t')
254
- const [mode = '', , oid = ''] = meta.split(' ')
255
- files.push(named && mode ? { path, mode, oid } : { path, mode: '000000', oid: '' })
256
- }
257
- await this.#write(files)
412
+ const captured = await this.observeChanges(paths)
413
+ if (captured.raw.length) await this.#applyFrozen('discard', captured)
258
414
  })
259
415
  }
260
416
 
@@ -284,7 +440,7 @@ export class Revisions implements RevisionService {
284
440
  if (!(await this.#git.tryOutput(['merge-base', '--is-ancestor', id, 'HEAD'])).ok) throw new RequestError(404, 'history-revision-not-found')
285
441
  const topPath = relative(this.#git.top, resolve(this.#files.config.root, path)).split(sep).join('/')
286
442
  const listed = await this.#git.output(['-C', this.#git.top, 'ls-tree', '-z', id, '--', topPath], { GIT_LITERAL_PATHSPECS: '1' })
287
- const [meta = '', named] = (listed.split('\0')[0] ?? '').split('\t')
443
+ const record = listed.split('\0')[0] ?? '', at = record.indexOf('\t'), meta = record.slice(0, at), named = record.slice(at + 1)
288
444
  const [mode, type, oid] = meta.split(' ')
289
445
  if (named !== topPath || !oid) throw new RequestError(404, 'history-file-not-found')
290
446
  if (type !== 'blob' || !['100644', '100755'].includes(mode!)) throw new RequestError(422, 'history-file-not-regular-text')
@@ -395,8 +551,6 @@ export class Revisions implements RevisionService {
395
551
  const { target, tree, changes } = planned
396
552
  const originalHead = await this.head()
397
553
  const restore = await this.#changes(tree, 'HEAD')
398
- const indexPath = resolve(this.#git.root, (await this.#git.output(['rev-parse', '--git-path', 'index'])).trim())
399
- const oldIndex = existsSync(indexPath) ? readFileSync(indexPath) : undefined
400
554
  try {
401
555
  await this.#write(changes)
402
556
  const subject = target.message.split('\n')[0] ?? target.id
@@ -409,8 +563,6 @@ export class Revisions implements RevisionService {
409
563
  const afterHead = await this.head()
410
564
  if (afterHead !== originalHead) throw new RequestError(409, 'history-readback-changed', { committed: true, snapshot: afterHead })
411
565
  await this.#write(restore)
412
- if (oldIndex) writeFileSync(indexPath, oldIndex)
413
- else rmSync(indexPath, { force: true })
414
566
  throw error
415
567
  }
416
568
  })
@@ -457,8 +609,8 @@ export class Revisions implements RevisionService {
457
609
  }
458
610
 
459
611
  async #statusOf(paths: string[]): Promise<{ code: string, path: string }[]> {
460
- const status = await this.#git.tryOutput(['status', '--porcelain=v1', '-z', '--no-renames', '--untracked-files=all', '--', ...paths.map(path => path || '.')], { GIT_LITERAL_PATHSPECS: '1' })
461
- if (!status.ok) return []
612
+ const status = await this.#git.tryOutput(['status', '--porcelain=v1', '-z', '--no-renames', '--untracked-files=all', '--', ...paths.map(path => path || '.')], { GIT_LITERAL_PATHSPECS: '1', GIT_OPTIONAL_LOCKS: '0' })
613
+ if (!status.ok) throw new RequestError(409, 'changes-repository-unavailable')
462
614
  return status.output.split('\0').filter(Boolean)
463
615
  .map(entry => ({ code: entry.slice(0, 2), path: this.#fromTop(entry.slice(3)) }))
464
616
  .filter(({ path }) => !isGeneratedPath(path))
@@ -505,29 +657,24 @@ export class Revisions implements RevisionService {
505
657
  }
506
658
 
507
659
  async #write(files: TreeFile[]): Promise<void> {
660
+ const changes = await Promise.all(files.map(file => this.#treeChange(file)))
661
+ return this.#writeChanges(changes)
662
+ }
663
+
664
+ async #writeChanges(files: DocumentFileChange[]): Promise<void> {
508
665
  const { config, writer } = this.#files
509
666
  const changes: { change: DocumentFileChange, dir?: string }[] = []
510
- for (const file of files) {
511
- if (file.mode === '160000') throw new Error(`${file.path} is a submodule: not reverted`)
512
- const dir = documentDirOf(config, file.path)
513
- if (/^0+$/.test(file.mode)) {
514
- changes.push({ change: { path: file.path, remove: true }, dir })
515
- continue
516
- }
517
- const blob = (await this.#git.run(['cat-file', 'blob', file.oid])).stdout
518
- const change: DocumentFileChange = file.mode === '120000' ? { path: file.path, link: blob.toString('utf8') } : { path: file.path, content: blob, ...file.mode === '100755' ? { executable: true } : {} }
519
- changes.push({ change, dir })
667
+ for (const change of files) changes.push({ change, dir: documentDirOf(config, change.path) })
668
+ const outside = changes.filter(({ dir }) => dir === undefined).map(({ change }) => change)
669
+ for (const { path } of outside) {
670
+ const open = writableByOthers(config.root, path)
671
+ if (open) throw new Error(`the revert would write ${path}, in ${open}, which more than serve may write`)
520
672
  }
521
673
  const inDocuments = changes.filter(({ dir }) => dir !== undefined)
522
674
  for (const dir of new Set(inDocuments.filter(({ change }) => !('remove' in change)).map(({ dir }) => dir!))) {
523
675
  if (!exists(join(config.root, dir))) makeDocumentDir(config.root, dir)
524
676
  }
525
677
  if (inDocuments.length > 0) await writer.write(inDocuments.map(({ change }) => change))
526
- const outside = changes.filter(({ dir }) => dir === undefined).map(({ change }) => change)
527
- for (const { path } of outside) {
528
- const open = writableByOthers(config.root, path)
529
- if (open) throw new Error(`the revert would write ${path}, in ${open}, which more than serve may write`)
530
- }
531
678
  if (outside.length > 0) writeChanges(config, outside, true)
532
679
  for (const dir of new Set(inDocuments.map(({ dir }) => dir!))) {
533
680
  if (!dir) continue
@@ -590,7 +737,11 @@ function writableByOthers(root: string, path: string): string | undefined {
590
737
 
591
738
  function lineCount(path: string): [number, number] | undefined {
592
739
  try {
593
- const bytes = readFileSync(path)
740
+ const stat = lstatSync(path)
741
+ if (!stat.isFile() || stat.size > SOURCE_MAX_BYTES) return
742
+ const file = revisionFiles(dirname(path), [basename(path)])[0], change = file?.change
743
+ if (!change || !('content' in change)) return
744
+ const bytes = Buffer.from(change.content)
594
745
  if (bytes.includes(0)) return undefined
595
746
  const text = bytes.toString('utf8')
596
747
  return [text === '' ? 0 : text.split('\n').length - (text.endsWith('\n') ? 1 : 0), 0]
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { createRequire } from 'node:module'
3
3
  import { DOCUMENT_ENTRY, fnv1a64, hasRole, isRecord, jsonResponse, problemResponse, PRODUCTION_AUDIO_AUTHORING, pushStream, SPEECH, sseResponse } from '@lincyaw/kernel'
4
- import type { ChangesAnswer, CommitAnswer, CompileJob, DocumentsAnswer, JobsAnswer, Member, PresmiumNodePlugin, RequestContext, Route, SavedAnswer, ServerContribution, SourceTransactionAnswer, SourceTransactionChange } from '@lincyaw/kernel'
4
+ import type { CompileJob, DocumentsAnswer, JobsAnswer, PresmiumNodePlugin, RequestContext, Route, SavedAnswer, ServerContribution, SourceTransactionAnswer, SourceTransactionChange } from '@lincyaw/kernel'
5
5
  import { hasBearerToken } from '@lincyaw/server'
6
6
  import { saveSummary } from '../domain/commit-message.ts'
7
7
  import { documentSummaries, listDocuments } from './config.ts'
@@ -9,12 +9,11 @@ import type { WorkspaceConfig } from './config.ts'
9
9
  import { documentsDiff } from './document-operations.ts'
10
10
  import type { DocumentOperations, DocumentsChange } from './document-operations.ts'
11
11
  import { catchRequestErrors, RequestError } from './errors.ts'
12
- import { lockedError } from './locks.ts'
13
12
  import type { DocumentLocks } from './locks.ts'
14
13
  import type { Revisions } from './revisions.ts'
15
14
  import { reviewRoutes } from './review/routes.ts'
16
15
  import type { AgentSessionReviews } from './review/agent-session-reviews.ts'
17
- import { MAX_SOURCE, MAX_SOURCE_CHANGES, validateDocumentSource } from './source-editor.ts'
16
+ import { MAX_SOURCE, MAX_SOURCE_CHANGES } from './source-editor.ts'
18
17
  import type { SourceEditor } from './source-editor.ts'
19
18
  import { listTemplates } from './templates.ts'
20
19
  import type { Jobs } from './jobs.ts'
@@ -25,8 +24,8 @@ import { createDocumentAudioAuthoring } from './document-audio.ts'
25
24
  import { createDocumentImageAuthoring } from './document-images.ts'
26
25
  import { createDocumentTranscriptions, documentTranscriptionRoutes } from './document-transcription.ts'
27
26
  import type { DocumentTranscriptions, ProductionAudioAuthoring, SpeechService } from '@lincyaw/kernel'
28
- import { documentDirOf } from './writer.ts'
29
27
  import { createDocumentHistory } from './document-history.ts'
28
+ import { createWorkspaceChanges } from './workspace-changes.ts'
30
29
 
31
30
  const { version } = createRequire(import.meta.url)('../../package.json') as { version: string }
32
31
 
@@ -62,6 +61,7 @@ export interface WorkspaceRoutesOptions {
62
61
  authoringClientRoutes?: Record<string, Route>
63
62
  projectRoutes?: Record<string, Route>
64
63
  speechSettings?: Route
64
+ changesRoutes?: Record<string, Route>
65
65
  }
66
66
 
67
67
  function toRendererIds(body: unknown): string[] | undefined {
@@ -70,13 +70,6 @@ function toRendererIds(body: unknown): string[] | undefined {
70
70
  return ids.length > 0 ? ids : undefined
71
71
  }
72
72
 
73
- const NO_GIT = 'the workspace is not a git repository: run git init in it to use the document operations and the history'
74
-
75
-
76
- function toChosenPaths(body: unknown, uncommitted: string[]): string[] {
77
- const asked = isRecord(body) && Array.isArray(body.paths) ? body.paths.filter((path): path is string => typeof path === 'string') : undefined
78
- return asked ? uncommitted.filter(path => asked.includes(path)) : uncommitted
79
- }
80
73
 
81
74
  function toSaveMessage(value: unknown): string {
82
75
  return typeof value === 'string' ? [...(value.trim().split(/\r?\n/)[0] ?? '').trim()].slice(0, 200).join('') : ''
@@ -87,21 +80,7 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
87
80
  const { config, editor, locks, revisions, operations, reviews, workbench } = options
88
81
  const listed = () => listDocuments(config).map(doc => doc.dir)
89
82
  const scopeOf = (ctx: RequestContext) => editor.scope(ctx.document)
90
- const uncommitted = async (ctx: RequestContext) => (revisions ? await revisions.uncommittedFiles(editor.roots(scopeOf(ctx))) : [])
91
- const withChosenChanges = async (request: Request, ctx: RequestContext, holder: string, work: (revisions: Revisions, paths: string[], member: Member, body: Record<string, unknown>) => Promise<Response>) => {
92
- if (request.method !== 'POST') return problemResponse(405, 'POST')
93
- if (!revisions) return problemResponse(409, NO_GIT)
94
- const body: unknown = await request.json().catch(() => ({}))
95
- const paths = toChosenPaths(body, (await uncommitted(ctx)).map(file => file.path))
96
- if (paths.length === 0) return problemResponse(409, 'no changes to take: every file is as committed')
97
- const claimed = locks.claimAll(paths.map(path => documentDirOf(config, path) ?? ''), holder)
98
- if ('holder' in claimed) throw lockedError(claimed.document, claimed.holder)
99
- try {
100
- return await work(revisions, paths, ctx.member, isRecord(body) ? body : {})
101
- } finally {
102
- claimed.release()
103
- }
104
- }
83
+ const changes = options.changesRoutes ?? createWorkspaceChanges({ config, editor, locks, revisions, changed: options.documentsChanged }).routes
105
84
  const ownedHistory = options.historyRoutes ? undefined : createDocumentHistory({ config, editor, locks, revisions, changed: (before, after) => options.documentsChanged(documentsDiff(before, after)), reverted: (target, revision) => reviews?.reverted(target, revision) })
106
85
  const ownedTranscriptions = options.transcriptions ? undefined : createDocumentTranscriptions({ root: config.root, editor, audio: options.audio, speech: options.speech })
107
86
  const transcriptions = options.transcriptions ?? ownedTranscriptions!
@@ -178,39 +157,11 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
178
157
  return jsonResponse(await editor.transaction(scopeOf(ctx), changes, ctx.member, history) satisfies SourceTransactionAnswer)
179
158
  }),
180
159
  },
181
- 'changes': {
182
- role: 'editor',
183
- handle: (request, ctx) => catchRequestErrors(async () => {
184
- if (request.method !== 'GET') return problemResponse(405, 'GET')
185
- return jsonResponse({ files: await uncommitted(ctx) } satisfies ChangesAnswer)
186
- }),
187
- },
188
- 'changes/commit': {
189
- role: 'editor',
190
- handle: (request, ctx) => catchRequestErrors(() => withChosenChanges(request, ctx, 'editor:commit', async (history, paths, member, body) => {
191
- const message = typeof body.message === 'string' ? body.message.trim().slice(0, 4000) : ''
192
- if (!message) return problemResponse(400, '{ message: what the change is, paths? }')
193
- for (const path of paths) {
194
- if (!path.endsWith(`/${DOCUMENT_ENTRY}`) && path !== DOCUMENT_ENTRY) continue
195
- const source = editor.read(scopeOf(ctx), path, member)
196
- validateDocumentSource(path, source.content)
197
- }
198
- const revision = await history.commit({ files: paths, message, origin: { kind: 'editor', member } })
199
- return jsonResponse({ ...revision ? { revision } : {}, paths } satisfies CommitAnswer)
200
- })),
201
- },
160
+ ...changes,
202
161
  ...workbench ? workbenchRoutes(workbench) : {},
203
162
  ...options.jobs ? jobRoutes(options.jobs, editor) : {},
204
163
  ...reviews ? reviewRoutes(reviews) : {},
205
- 'changes/discard': {
206
- role: 'editor',
207
- handle: (request, ctx) => catchRequestErrors(() => withChosenChanges(request, ctx, 'editor:discard', async (history, paths) => {
208
- const before = listed()
209
- await history.discard(paths)
210
- await options.documentsChanged(documentsDiff(before, listed()))
211
- return jsonResponse({ paths } satisfies CommitAnswer)
212
- })),
213
- },
164
+
214
165
  }
215
166
  return { routes: authorizeWorkspaceRoutes(routes, options.launcherToken), close: async () => { await Promise.all([ownedTranscriptions?.close(), ownedAudio?.close(), ownedHistory?.close()]) } }
216
167
  }
package/src/node/serve.ts CHANGED
@@ -25,6 +25,7 @@ import { DocumentLocks } from './locks.ts'
25
25
  import { AgentSessionReviews } from './review/agent-session-reviews.ts'
26
26
  import { createWorkspaceReview } from './review/workspace-review.ts'
27
27
  import { createWorkspaceSource } from './workspace-source.ts'
28
+ import { createWorkspaceChanges } from './workspace-changes.ts'
28
29
  import { createTaskReviewService } from './review/task-reviews.ts'
29
30
  import { Revisions } from './revisions.ts'
30
31
  import { WORKSPACE_ID, authorizeWorkspaceRoutes, workspaceRoutes, workspaceRoutesPlugin } from './routes.ts'
@@ -120,6 +121,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
120
121
  let documentHistory: ReturnType<typeof createDocumentHistory> | undefined
121
122
  let workspaceReview: ReturnType<typeof createWorkspaceReview> | undefined
122
123
  let workspaceSource: ReturnType<typeof createWorkspaceSource> | undefined
124
+ let workspaceChanges: ReturnType<typeof createWorkspaceChanges> | undefined
123
125
  let projectAuthoring: ReturnType<typeof createProjectAuthoring> | undefined
124
126
  let authoringClients: ReturnType<typeof createAuthoringClients> | undefined
125
127
  let transcriptions: ReturnType<typeof createDocumentTranscriptions> | undefined
@@ -278,6 +280,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
278
280
  speechSettings,
279
281
  get workspaceReview() { return workspaceReview },
280
282
  get workspaceSource() { return workspaceSource },
283
+ get workspaceChanges() { return workspaceChanges?.service },
281
284
  get transcriptions() { return transcriptions },
282
285
  get transcriptionAdoption() { return transcriptionAdoption?.service },
283
286
  get capture() { return capture?.service },
@@ -390,6 +393,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
390
393
  voiceAuthoring = createDocumentVoiceAuthoring({ editor, services: authoringServices, revision: document => { const latest = compileSessions.get(document)?.latest; return latest ? irRevision(latest.doc) : undefined } })
391
394
  workbench = createWorkbenchBackend({ root, compileSessionOf, serverHost, voices: voiceAuthoring.service, diagnostics: running.diagnostics, url: () => options.publicUrl ? new URL(options.publicUrl).origin : running.url, basePath, preview, log, warmSite: dir => site?.warm(dir) ?? Promise.resolve(), viewerPage: (dir, wait) => site?.app(dir, wait) ?? Promise.resolve(undefined) })
392
395
  history = openHistory()
396
+ workspaceChanges = createWorkspaceChanges({ config, editor, locks, revisions: history?.revisions, changed: documentsChanged })
393
397
  workspaceSource = createWorkspaceSource({ config, editor, revisions: history?.revisions })
394
398
  workspaceReview = history && createWorkspaceReview(history.agentSessionReviews)
395
399
  documentEditor = createDocumentEditor({ productionPlan: async (document, source) => { const audio = (await authoringServices(document, source)).audio; if (!audio) throw new RequestError(503, 'caption-production-unavailable'); return audio.readPlan({ source }) }, editor, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
@@ -402,6 +406,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
402
406
  imageAuthoring = createDocumentImageAuthoring({ root, editor, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
403
407
  const routeOptions = {
404
408
  speechSettings: speechSettingsRoute(speechSettings),
409
+ changesRoutes: workspaceChanges.routes,
405
410
  config,
406
411
  editor,
407
412
  documentEditor,
@@ -0,0 +1,130 @@
1
+ import { CHANGES_MAX_REQUEST_CHARS, CHANGES_MAX_RESPONSE_CHARS, DOCUMENT_ENTRY, hasRole, jsonResponse, problemResponse } from '@lincyaw/kernel'
2
+ import type { ChangesCaller, WorkspaceChanges, WorkspaceChangesResult } from '@lincyaw/kernel'
3
+ import { validateChangesQuery, validateWorkspaceChangesRequest } from '@lincyaw/kernel/node'
4
+ import { listDocuments } from './config.ts'
5
+ import type { WorkspaceConfig } from './config.ts'
6
+ import { catchRequestErrors, RequestError } from './errors.ts'
7
+ import { documentsDiff } from './document-operations.ts'
8
+ import type { DocumentsChange } from './document-operations.ts'
9
+ import type { DocumentLocks } from './locks.ts'
10
+ import type { Revisions } from './revisions.ts'
11
+ import { MAX_SOURCE, validateDocumentSource } from './source-editor.ts'
12
+ import type { SourceEditor } from './source-editor.ts'
13
+ import { documentDirOf, isGeneratedPath } from './writer.ts'
14
+ import type { Route } from '@lincyaw/kernel'
15
+
16
+ const size = (value: unknown) => JSON.stringify(value).length
17
+ async function bounded<T>(work: () => Promise<T>): Promise<T> {
18
+ try { return await work() }
19
+ catch (error) {
20
+ const value = error as { message?: string, status?: number }
21
+ if (value.message?.startsWith('changes-') || value.message === 'authoring-review-required') throw error
22
+ throw new RequestError(value.status ?? 409, value.message === 'document-invalid' ? 'changes-document-invalid' : 'changes-operation-failed')
23
+ }
24
+ }
25
+ /** Web and MCP share the same capture, policy, document locks and frozen Revisions application. */
26
+ export function createWorkspaceChanges(options: { config: WorkspaceConfig, editor: SourceEditor, locks: DocumentLocks, revisions?: Revisions, changed(change: DocumentsChange): Promise<void> | void }) {
27
+ const { config, editor, locks, revisions } = options
28
+ const scope = (document: string | undefined, caller: ChangesCaller) => {
29
+ if (!hasRole(caller.member, 'editor')) throw new RequestError(403, 'changes-permission-denied')
30
+ if (caller.boundDocument !== undefined) {
31
+ if (document !== undefined && document !== caller.boundDocument) throw new RequestError(403, 'changes-permission-denied')
32
+ return { document: caller.boundDocument, home: false }
33
+ }
34
+ return editor.scope(document ?? '')
35
+ }
36
+ const writer = (caller: ChangesCaller) => {
37
+ if (!hasRole(caller.member, 'editor') || caller.origin === 'agent' && (!hasRole(caller.member, 'owner') || caller.boundDocument !== undefined || caller.confirmed)) throw new RequestError(403, 'changes-permission-denied')
38
+ if (caller.origin === 'agent' && config.settings['presmium.assistant']?.review === 'required') throw new RequestError(409, 'authoring-review-required')
39
+ }
40
+ const budget = (value: unknown) => { if (size(value) > CHANGES_MAX_REQUEST_CHARS) throw new RequestError(413, 'changes-request-too-large') }
41
+ const service: WorkspaceChanges = {
42
+ list: (query, caller) => bounded(async () => {
43
+ budget(query)
44
+ if (!validateChangesQuery(query)) throw new RequestError(400, 'changes-request-invalid')
45
+ const owned = scope(query.document, caller)
46
+ if (!revisions) return { available: false, files: [] }
47
+ const state = await revisions.observeChanges(editor.roots(owned)), offset = query.offset ?? 0
48
+ if (query.snapshot !== undefined && query.snapshot !== state.snapshot || offset > 0 && !query.snapshot) throw new RequestError(409, 'changes-state-changed')
49
+ if (offset > state.files.length) throw new RequestError(400, 'changes-request-invalid')
50
+ const raw = new Map(state.raw.map(file => [file.path, file]))
51
+ const files = [] as import('@lincyaw/kernel').WorkspaceChangesAnswer['files']
52
+ for (const file of state.files.slice(offset, offset + 20)) {
53
+ if (!editor.canEdit(owned, file.path, caller.member)) throw new RequestError(403, 'changes-permission-denied')
54
+ const row = { ...file, ...raw.get(file.path)?.mode === 'unsupported' ? { unsupported: true as const } : {} }
55
+ if (size({ available: true, snapshot: state.snapshot, files: [...files, row], nextOffset: offset + files.length + 1 }) > CHANGES_MAX_RESPONSE_CHARS) break
56
+ files.push(row)
57
+ }
58
+ if (!files.length && offset < state.files.length) throw new RequestError(413, 'changes-response-too-large')
59
+ return { available: true, snapshot: state.snapshot, files, ...offset + files.length < state.files.length ? { nextOffset: offset + files.length } : {} }
60
+ }),
61
+ prepare: (request, caller) => bounded(async () => {
62
+ budget(request); writer(caller)
63
+ if (!validateWorkspaceChangesRequest(request) || request.action === 'commit' && !request.message.trim()) throw new RequestError(400, 'changes-request-invalid')
64
+ const action = request.action, message = request.action === 'commit' ? request.message.trim() : undefined
65
+ const owned = scope(request.document, caller)
66
+ if (!revisions) throw new RequestError(409, 'changes-git-unavailable')
67
+ const observed = await revisions.observeChanges(editor.roots(owned))
68
+ if (request.snapshot !== undefined && request.snapshot !== observed.snapshot) throw new RequestError(409, 'changes-state-changed')
69
+ const chosen = new Set(request.paths ?? observed.files.map(file => file.path))
70
+ if (!chosen.size) throw new RequestError(409, 'changes-empty')
71
+ const known = new Set(observed.files.map(file => file.path))
72
+ if ([...chosen].some(path => !known.has(path))) throw new RequestError(409, 'changes-selection-changed')
73
+ const paths = observed.files.filter(file => chosen.has(file.path)).map(file => file.path)
74
+ let captured = { ...observed, files: observed.files.filter(file => chosen.has(file.path)), raw: observed.raw.filter(file => chosen.has(file.path)) }
75
+ if (captured.raw.some(file => !file.change)) throw new RequestError(409, 'changes-file-unsupported')
76
+ const owners = paths.map(path => documentDirOf(config, path))
77
+ const check = () => {
78
+ writer(caller)
79
+ for (const [index, path] of paths.entries()) {
80
+ if (!editor.canEdit(owned, path, caller.member) || isGeneratedPath(path)) throw new RequestError(403, 'changes-permission-denied')
81
+ if (documentDirOf(config, path) !== owners[index]) throw new RequestError(409, 'changes-state-changed')
82
+ }
83
+ }
84
+ check()
85
+ if (action === 'commit') for (const file of captured.raw) {
86
+ if (file.path === DOCUMENT_ENTRY || file.path.endsWith(`/${DOCUMENT_ENTRY}`)) {
87
+ if (!file.change || !('content' in file.change)) throw new RequestError(409, 'changes-document-invalid')
88
+ if (Buffer.byteLength(file.change.content) > MAX_SOURCE) throw new RequestError(413, 'changes-selection-too-large')
89
+ let text: string
90
+ try { text = new TextDecoder('utf-8', { fatal: true }).decode(file.change.content) } catch { throw new RequestError(422, 'changes-document-invalid') }
91
+ validateDocumentSource(file.path, text)
92
+ }
93
+ }
94
+ if (action === 'commit') captured = await revisions.freezeCommit(captured)
95
+ let pending: Promise<WorkspaceChangesResult> | undefined
96
+ return { paths: Object.freeze([...paths]), change: signal => pending ??= bounded(async () => {
97
+ signal?.throwIfAborted(); check()
98
+ const claim = locks.claimAll(owners.map(owner => owner ?? ''), `editor:${action}`)
99
+ if ('holder' in claim) throw new RequestError(409, 'changes-workspace-busy')
100
+ const before = listDocuments(config).map(document => document.dir)
101
+ try {
102
+ const revision = await revisions.applyChanges(action, captured, action === 'commit' ? { paths, summary: message!.split('\n')[0]!, body: message!.split('\n').slice(1).join('\n'), origin: { kind: caller.origin === 'agent' ? 'agent' : 'editor', member: caller.member } } : undefined, () => { signal?.throwIfAborted(); check() })
103
+ let refreshed: false | undefined
104
+ if (action === 'discard') {
105
+ try { await options.changed(documentsDiff(before, listDocuments(config).map(document => document.dir))) } catch { refreshed = false }
106
+ }
107
+ return { ...refreshed === false ? { refreshed } : {}, action, files: paths.length, ...action === 'commit' ? { committed: Boolean(revision), ...revision ? { revision } : {} } : {} }
108
+ } finally { claim.release() }
109
+ }) }
110
+ }),
111
+ }
112
+ const routes: Record<string, Route> = {
113
+ changes: { role: 'editor', handle: (request, ctx) => catchRequestErrors(async () => {
114
+ if (request.method !== 'GET') return problemResponse(405, 'GET')
115
+ if (!revisions) return jsonResponse({ files: [] })
116
+ const files = await revisions.uncommittedFiles(editor.roots(editor.scope(ctx.document)))
117
+ return jsonResponse({ files })
118
+ }) },
119
+ ...Object.fromEntries((['commit', 'discard'] as const).map(action => [`changes/${action}`, { role: 'editor', handle: (request, ctx) => catchRequestErrors(async () => {
120
+ if (request.method !== 'POST') return problemResponse(405, 'POST')
121
+ const body: unknown = await request.json().catch(() => undefined)
122
+ if (!body || typeof body !== 'object' || Array.isArray(body)) throw new RequestError(400, 'changes-request-invalid')
123
+ const input = body as Record<string, unknown>
124
+ const prepared = await service.prepare({ ...input, document: ctx.document, action, ...action === 'discard' ? { confirm: true } : {} } as import('@lincyaw/kernel').WorkspaceChangesRequest, { member: ctx.member, origin: 'editor' })
125
+ const result = await prepared.change(request.signal)
126
+ return jsonResponse({ paths: prepared.paths, ...result.refreshed === false ? { refreshed: false } : {}, ...result.revision ? { revision: result.revision } : {} })
127
+ }) } satisfies Route])),
128
+ }
129
+ return { service, routes }
130
+ }
@@ -3,7 +3,7 @@ import { closeSync, constants, cpSync, fstatSync, lstatSync, mkdirSync, mkdtempS
3
3
  import type { Stats } from 'node:fs'
4
4
  import { tmpdir } from 'node:os'
5
5
  import { dirname, join } from 'node:path'
6
- import { DOCUMENT_ENTRY, validateDocument } from '@lincyaw/kernel'
6
+ import { CHANGES_MAX_BYTES, CHANGES_MAX_FILES, DOCUMENT_ENTRY, validateDocument } from '@lincyaw/kernel'
7
7
  import type { DocumentFileChange, DocumentFiles } from '@lincyaw/kernel'
8
8
  import { isWithin, rewriteLinks } from '../domain/paths.ts'
9
9
  import { isDocumentDir, listDocuments } from './config.ts'
@@ -11,8 +11,8 @@ import type { WorkspaceConfig } from './config.ts'
11
11
  import { findTemplate } from './templates.ts'
12
12
 
13
13
  const NOT_COPIED = new Set(['node_modules', 'dist', '.git'])
14
- export const DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES = 16_384
15
- export const DOCUMENT_OPERATION_MAX_BACKUP_BYTES = 512 << 20
14
+ export const DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES = CHANGES_MAX_FILES
15
+ export const DOCUMENT_OPERATION_MAX_BACKUP_BYTES = CHANGES_MAX_BYTES
16
16
 
17
17
  export class FilesError extends Error {}
18
18
  export class DocumentCheckpointRefusal extends FilesError {