@lincyaw/workspace 1.0.0-rc.45 → 1.0.0-rc.47

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.45",
3
+ "version": "1.0.0-rc.47",
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/kernel": "1.0.0-rc.45",
38
- "@lincyaw/compiler": "1.0.0-rc.45",
39
- "@lincyaw/server": "1.0.0-rc.45"
37
+ "@lincyaw/kernel": "1.0.0-rc.47",
38
+ "@lincyaw/compiler": "1.0.0-rc.47",
39
+ "@lincyaw/server": "1.0.0-rc.47"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@types/mime-types": "^3.0.1",
43
- "@lincyaw/mcp": "1.0.0-rc.45"
43
+ "@lincyaw/mcp": "1.0.0-rc.47"
44
44
  }
45
45
  }
@@ -13,6 +13,7 @@ import type { Revisions } from './revisions.ts'
13
13
  import { DOCUMENT_OPERATION_MAX_BACKUP_BYTES, DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, documentDirOf } from './writer.ts'
14
14
  import { catchRequestErrors, RequestError } from './errors.ts'
15
15
  import { projectConfiguration, projectDigest, projectMaterial } from './project-files.ts'
16
+ import { listTemplates } from './templates.ts'
16
17
 
17
18
  type Admission = { signature: string, admission: Promise<ProjectPlan> }
18
19
  type Stored = { member: string, origin: ProjectCaller['origin'], signature: string, plan: ProjectPlan, material?: ReturnType<typeof projectMaterial>, canonical?: { change: DocumentChange, planId: string, source: CanonicalSource }, receipt?: ProjectApplied, work?: Promise<ProjectApplied> }
@@ -59,14 +60,28 @@ export function createProjectAuthoring(options: { config: WorkspaceConfig, opera
59
60
  }
60
61
  const key = (request: ProjectPlanRequest, caller: ProjectCaller) => JSON.stringify([caller.member.id, caller.origin, request.id])
61
62
  const service: ProjectAuthoring = {
62
- async capabilities(caller) {
63
+ async capabilities(caller, query = {}) {
63
64
  if (closed) throw new RequestError(503, 'project-owner-closed')
65
+ const offset = query.templatesOffset ?? 0
66
+ if (!Number.isSafeInteger(offset) || offset < 0 || Object.keys(query).some(key => key !== 'templatesOffset')) throw new RequestError(400, 'project-request-invalid')
64
67
  const observed = await observation(), directory = reasons(caller), metadata = reasons(caller, { op: 'retitle', dir: caller.boundDocument ?? '', title: 'capability' })
65
68
  if (!observed.snapshot && !directory.includes('project-git-unavailable')) directory.push('project-head-unavailable')
66
69
  const actions = Object.fromEntries(['create', 'copy', 'rename', 'delete', 'retitle'].map(op => { const unavailable = op === 'retitle' ? metadata : directory; return [op, { available: unavailable.length === 0, reasons: unavailable }] })) as import('@lincyaw/kernel').ProjectCapabilities['actions']
67
70
  const available = Object.values(actions).some(action => action.available)
68
- return bounded({ available, actions, reasons: available ? [] : [...new Set([...directory, ...metadata])], observation: observed, verification: 'configuration-only', rootDirectoryOperations: false,
69
- limits: { requestChars: PROJECT_MAX_REQUEST_CHARS, responseChars: PROJECT_MAX_RESPONSE_CHARS, backupEntries: DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, backupBytes: DOCUMENT_OPERATION_MAX_BACKUP_BYTES, plans: PROJECT_MAX_PLANS, ttlMs: PROJECT_PLAN_TTL_MS } })
71
+ const answer: import('@lincyaw/kernel').ProjectCapabilities = { available, actions, reasons: available ? [] : [...new Set([...directory, ...metadata])], observation: observed, verification: 'configuration-only', rootDirectoryOperations: false,
72
+ limits: { requestChars: PROJECT_MAX_REQUEST_CHARS, responseChars: PROJECT_MAX_RESPONSE_CHARS, backupEntries: DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, backupBytes: DOCUMENT_OPERATION_MAX_BACKUP_BYTES, plans: PROJECT_MAX_PLANS, ttlMs: PROJECT_PLAN_TTL_MS } }
73
+ if (caller.boundDocument === undefined) {
74
+ const templates = listTemplates(config)
75
+ if (offset > templates.length) throw new RequestError(400, 'project-request-invalid')
76
+ answer.templates = []
77
+ for (const template of templates.slice(offset, offset + 20)) {
78
+ if (JSON.stringify({ ...answer, templates: [...answer.templates, template], nextTemplatesOffset: offset + answer.templates.length + 1 }).length > PROJECT_MAX_RESPONSE_CHARS) break
79
+ answer.templates.push(template)
80
+ }
81
+ if (!answer.templates.length && offset < templates.length) throw new RequestError(413, 'project-response-too-large')
82
+ if (offset + answer.templates.length < templates.length) answer.nextTemplatesOffset = offset + answer.templates.length
83
+ } else if (offset) throw new RequestError(403, 'project-workspace-scope-required')
84
+ return bounded(answer)
70
85
  },
71
86
  async plan(request, caller) {
72
87
  budget(request)
@@ -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
@@ -24,6 +24,8 @@ import { createJobs, OUTPUTS_PATH } from './jobs.ts'
24
24
  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
+ import { createWorkspaceSource } from './workspace-source.ts'
28
+ import { createWorkspaceChanges } from './workspace-changes.ts'
27
29
  import { createTaskReviewService } from './review/task-reviews.ts'
28
30
  import { Revisions } from './revisions.ts'
29
31
  import { WORKSPACE_ID, authorizeWorkspaceRoutes, workspaceRoutes, workspaceRoutesPlugin } from './routes.ts'
@@ -118,6 +120,8 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
118
120
  let documentEditor: DocumentEditor | undefined
119
121
  let documentHistory: ReturnType<typeof createDocumentHistory> | undefined
120
122
  let workspaceReview: ReturnType<typeof createWorkspaceReview> | undefined
123
+ let workspaceSource: ReturnType<typeof createWorkspaceSource> | undefined
124
+ let workspaceChanges: ReturnType<typeof createWorkspaceChanges> | undefined
121
125
  let projectAuthoring: ReturnType<typeof createProjectAuthoring> | undefined
122
126
  let authoringClients: ReturnType<typeof createAuthoringClients> | undefined
123
127
  let transcriptions: ReturnType<typeof createDocumentTranscriptions> | undefined
@@ -275,6 +279,8 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
275
279
  get voiceAuthoring() { return voiceAuthoring?.service },
276
280
  speechSettings,
277
281
  get workspaceReview() { return workspaceReview },
282
+ get workspaceSource() { return workspaceSource },
283
+ get workspaceChanges() { return workspaceChanges?.service },
278
284
  get transcriptions() { return transcriptions },
279
285
  get transcriptionAdoption() { return transcriptionAdoption?.service },
280
286
  get capture() { return capture?.service },
@@ -387,6 +393,8 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
387
393
  voiceAuthoring = createDocumentVoiceAuthoring({ editor, services: authoringServices, revision: document => { const latest = compileSessions.get(document)?.latest; return latest ? irRevision(latest.doc) : undefined } })
388
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) })
389
395
  history = openHistory()
396
+ workspaceChanges = createWorkspaceChanges({ config, editor, locks, revisions: history?.revisions, changed: documentsChanged })
397
+ workspaceSource = createWorkspaceSource({ config, editor, revisions: history?.revisions })
390
398
  workspaceReview = history && createWorkspaceReview(history.agentSessionReviews)
391
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' })
392
400
  projectAuthoring = createProjectAuthoring({ config, documentEditor, operations: history?.operations, revisions: history?.revisions, git: history?.git })
@@ -398,6 +406,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
398
406
  imageAuthoring = createDocumentImageAuthoring({ root, editor, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
399
407
  const routeOptions = {
400
408
  speechSettings: speechSettingsRoute(speechSettings),
409
+ changesRoutes: workspaceChanges.routes,
401
410
  config,
402
411
  editor,
403
412
  documentEditor,
@@ -1,8 +1,8 @@
1
1
  import { createHash } from 'node:crypto'
2
- import { lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readdirSync, realpathSync } from 'node:fs'
3
3
  import { join } from 'node:path'
4
4
  import { WORKSPACE_CONFIG } from '@lincyaw/compiler'
5
- import { DOCUMENT_ENTRY, validateDocument } from '@lincyaw/kernel'
5
+ import { DOCUMENT_ENTRY, SOURCE_MAX_BYTES, SOURCE_MAX_FILES, validateDocument } from '@lincyaw/kernel'
6
6
  import type { ConflictAnswer, DocumentFileChange, FilesAnswer, Member, Revision, SavedAnswer, SourceAnswer, SourceFile, SourceTransactionAnswer, SourceTransactionChange } from '@lincyaw/kernel'
7
7
  import { isWithin } from '../domain/paths.ts'
8
8
  import { listDocumentEntries, readDocumentSummary } from './config.ts'
@@ -12,8 +12,8 @@ import type { DocumentLocks } from './locks.ts'
12
12
  import { documentDirOf, FilesError, writeChanges } from './writer.ts'
13
13
  import type { DocumentWriter } from './writer.ts'
14
14
 
15
- export const MAX_SOURCE = 2 << 20
16
- export const MAX_SOURCE_CHANGES = 16
15
+ export const MAX_SOURCE = SOURCE_MAX_BYTES
16
+ export const MAX_SOURCE_CHANGES = SOURCE_MAX_FILES
17
17
  const MAX_FILES = 2000
18
18
  const HIDDEN_FROM_EDITOR = new Set(['node_modules', 'dist', '.git', '.presmium'])
19
19
  const BINARY = /\.(?:png|jpe?g|gif|webp|avif|ico|bmp|pdf|wasm|zip|gz|tgz|bz2|xz|7z|woff2?|ttf|otf|eot|mp3|mp4|m4a|wav|ogg|oga|webm|mov|avi|mkv|bin|so|dylib|dll|exe|pyc|xlsx?|docx?|pptx?|parquet|npy|npz|pkl|db|sqlite)$/i
@@ -48,6 +48,8 @@ interface Scope {
48
48
  }
49
49
 
50
50
  export interface SourceTransactionHistory {
51
+ /** Runs on final locked preimages, before any file is created or changed. */
52
+ check?(files: readonly { path: string, before?: Uint8Array }[]): void
51
53
  run<T>(work: () => Promise<T>): Promise<T>
52
54
  commit(paths: string[], lang: string | undefined): Promise<Revision | undefined>
53
55
  }
@@ -153,9 +155,20 @@ export class SourceEditor {
153
155
 
154
156
  #readBytes(scope: Scope, path: string, member: Member, documents?: readonly DocumentEntry[]): Buffer {
155
157
  const file = this.#readableFile(scope, path, member, documents)
156
- const bytes = readFileSync(file)
157
- if (bytes.byteLength > MAX_SOURCE) throw new RequestError(413, `${path} is larger than the editor opens (${MAX_SOURCE} bytes)`)
158
- return bytes
158
+ const before = lstatSync(file)
159
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
160
+ try {
161
+ const opened = fstatSync(fd)
162
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) throw new RequestError(409, 'source-file-changed')
163
+ if (opened.size > MAX_SOURCE) throw new RequestError(413, `${path} is larger than the editor opens (${MAX_SOURCE} bytes)`)
164
+ const bytes = Buffer.alloc(opened.size + 1)
165
+ let length = 0, count = 0
166
+ while (length < bytes.length && (count = readSync(fd, bytes, length, bytes.length - length, null)) > 0) length += count
167
+ const after = fstatSync(fd), current = lstatSync(file)
168
+ if (length !== opened.size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs
169
+ || current.dev !== opened.dev || current.ino !== opened.ino || realpathSync(file) !== file) throw new RequestError(409, 'source-file-changed')
170
+ return bytes.subarray(0, length)
171
+ } finally { closeSync(fd) }
159
172
  }
160
173
 
161
174
  read(scope: Scope, path: string, member: Member): SourceAnswer {
@@ -225,10 +238,16 @@ export class SourceEditor {
225
238
  if (bytes > MAX_SOURCE) throw new RequestError(413, `the transaction is larger than the editor saves (${MAX_SOURCE} bytes)`)
226
239
  for (const path of paths) if ([...paths].some(other => path !== other && path.startsWith(`${other}/`))) throw new RequestError(400, `a source file cannot also be a parent directory: ${path}`)
227
240
  const document = documents[0]
228
- if (!document || documents.some(found => found?.dir !== document.dir)) throw new RequestError(400, 'a source transaction must stay in one document')
229
- const scopeDir = document.dir
241
+ if ((!document && !(scope.home && member.roles.includes('owner'))) || documents.some(found => found?.dir !== document?.dir)) throw new RequestError(400, 'a source transaction must stay in one document or the owner workspace scope')
242
+ if (!document && changes.some(change => change.path === DOCUMENT_ENTRY || change.path.endsWith(`/${DOCUMENT_ENTRY}`))) throw new RequestError(422, 'create-a-document-with-valid-content')
243
+ const scopeDir = document?.dir ?? ''
230
244
  const release = this.#locks ? await this.#locks.acquire(scopeDir, 'editor:transaction') : () => {}
231
245
  const work = async (): Promise<SourceTransactionAnswer> => {
246
+ const current = listDocumentEntries(this.#config)
247
+ for (const [index, change] of changes.entries()) {
248
+ this.#assertEditable(scope, change.path, member, current)
249
+ if (this.#documentHolding(change.path, current)?.dir !== documents[index]?.dir) throw new RequestError(409, 'source-scope-changed')
250
+ }
232
251
  // Read every preimage before creating directories or writing any file.
233
252
  const snapshots = changes.map(change => {
234
253
  const written = typeof change.content === 'string' ? Buffer.from(change.content, 'utf8') : Buffer.from(change.content)
@@ -253,16 +272,17 @@ export class SourceEditor {
253
272
  return { path: change.path, before: undefined, written, executable: false }
254
273
  })
255
274
  for (const snapshot of snapshots) if (snapshot.path !== binaryPath) validateDocumentSource(snapshot.path, snapshot.written.toString('utf8'), snapshot.before)
275
+ history?.check?.(snapshots)
256
276
  if (dryRun) return { versions: snapshots.map(snapshot => ({ path: snapshot.path, version: versionOf(snapshot.written) })) }
257
277
  const created: string[] = []
258
278
  const edited = snapshots.filter(snapshot => snapshot.before && !snapshot.written.equals(snapshot.before))
259
279
  const touched = snapshots.filter(snapshot => !snapshot.before || !snapshot.written.equals(snapshot.before)).map(snapshot => snapshot.path)
260
- const lang = history && touched.length ? readDocumentSummary(this.#config, document).lang : undefined
261
- const write = (next: DocumentFileChange[]) => this.#writer.write(next)
280
+ const lang = history && touched.length && document ? readDocumentSummary(this.#config, document).lang : undefined
281
+ const write = async (next: DocumentFileChange[]) => document ? await this.#writer.write(next) : writeChanges(this.#config, next, true)
262
282
  try {
263
283
  // Exclusive creation prevents replacing a file created outside serve after validation.
264
284
  for (const snapshot of snapshots) if (!snapshot.before) {
265
- await this.#writer.create(snapshot.path, snapshot.written)
285
+ await this.#writer.create(snapshot.path, snapshot.written, document === undefined)
266
286
  created.push(snapshot.path)
267
287
  }
268
288
  if (edited.length) await write(edited.map(snapshot => ({ path: snapshot.path, content: snapshot.written, ...snapshot.executable ? { executable: true } : {} })))
@@ -1,4 +1,4 @@
1
- import { existsSync, lstatSync, readdirSync, statSync } from 'node:fs'
1
+ import { existsSync, lstatSync, readdirSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { fileURLToPath } from 'node:url'
4
4
  import type { WorkspaceConfig } from './config.ts'
@@ -14,7 +14,7 @@ function templatesDir(config: WorkspaceConfig): string {
14
14
  export function listTemplates(config: WorkspaceConfig): string[] {
15
15
  const dir = templatesDir(config)
16
16
  try {
17
- return readdirSync(dir).filter(name => statSync(join(dir, name)).isDirectory()).sort()
17
+ return readdirSync(dir).filter(name => findTemplate(config, name) !== undefined).sort()
18
18
  } catch {
19
19
  return []
20
20
  }
@@ -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
+ }
@@ -0,0 +1,133 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { DOCUMENT_ENTRY, hasRole, SOURCE_FRAGMENT_CHARS, SOURCE_MAX_REQUEST_CHARS, SOURCE_MAX_RESPONSE_CHARS } from '@lincyaw/kernel'
3
+ import type { SourceCaller, SourceSaved, WorkspaceSource } from '@lincyaw/kernel'
4
+ import { validateSourceEdit, validateSourceList, validateSourceRead } from '@lincyaw/kernel/node'
5
+ import { listDocumentEntries } from './config.ts'
6
+ import type { WorkspaceConfig } from './config.ts'
7
+ import { RequestError } from './errors.ts'
8
+ import { saveSummary } from '../domain/commit-message.ts'
9
+ import type { Revisions } from './revisions.ts'
10
+ import { validateDocumentSource } from './source-editor.ts'
11
+ import type { SourceEditor } from './source-editor.ts'
12
+
13
+ const size = (value: unknown) => JSON.stringify(value).length
14
+ const fits = (value: unknown) => size(value) <= SOURCE_MAX_RESPONSE_CHARS
15
+ const digest = (value: string) => createHash('sha256').update(value).digest('hex')
16
+ const canonical = (path: string) => path === DOCUMENT_ENTRY || path.endsWith(`/${DOCUMENT_ENTRY}`)
17
+ /** SourceEditor keeps detailed conflicts for Web; MCP never returns full conflicting file contents. */
18
+ async function bounded<T>(work: () => Promise<T>): Promise<T> {
19
+ try { return await work() }
20
+ catch (error) {
21
+ const value = error as { message?: string, status?: number, code?: string, detail?: { conflict?: { version?: string }, exists?: boolean, issues?: { path?: string, code?: string, message?: string, severity?: string }[] } }
22
+ if (error instanceof Error && error.name === 'AbortError') throw error
23
+ if (value.message?.startsWith('source-') || value.message === 'authoring-review-required') throw error
24
+ if (value.message === 'document-invalid') {
25
+ const issues = value.detail?.issues?.slice(0, 4).map(issue => ({ path: issue.path?.slice(0, 500) ?? '', code: issue.code?.slice(0, 100) ?? 'document-invalid', message: issue.message?.slice(0, 240) ?? '', severity: issue.severity === 'warning' ? 'warning' : 'error' })) ?? []
26
+ while (size({ issues }) > SOURCE_MAX_RESPONSE_CHARS - 1024 && issues.length) issues.pop()
27
+ throw new RequestError(422, 'document-invalid', { issues })
28
+ }
29
+ if (value.message === 'document-identity-changed') throw new RequestError(422, 'document-identity-changed')
30
+ if (value.status === 409) throw new RequestError(409, value.detail?.exists ? 'source-file-exists' : 'source-version-changed', value.detail?.conflict?.version ? { version: value.detail.conflict.version } : undefined)
31
+ const status = value.status ?? ({ ENOENT: 404, EEXIST: 409, ELOOP: 403, EACCES: 403, EISDIR: 415 } as Record<string, number>)[value.code ?? ''] ?? 500
32
+ throw new RequestError(status, status === 404 ? 'source-file-not-found' : status === 409 ? 'source-file-exists' : status === 403 ? 'source-file-forbidden' : status === 413 ? 'source-file-too-large' : status === 415 ? 'source-text-required' : status < 500 ? 'source-request-invalid' : 'source-operation-failed')
33
+ }
34
+ }
35
+
36
+ /** A bounded adapter over the native source scope, preflight, transaction and history owner. */
37
+ export function createWorkspaceSource(options: { config: WorkspaceConfig, editor: SourceEditor, revisions?: Revisions }): WorkspaceSource {
38
+ const { config, editor, revisions } = options
39
+ const scope = (document: string | undefined, caller: SourceCaller) => {
40
+ if (!hasRole(caller.member, 'editor')) throw new RequestError(403, 'source-file-forbidden')
41
+ if (caller.boundDocument !== undefined) {
42
+ if (document !== undefined && document !== caller.boundDocument) throw new RequestError(403, 'source-file-forbidden')
43
+ return { document: caller.boundDocument, home: false }
44
+ }
45
+ if (document && !listDocumentEntries(config).some(entry => entry.dir === document)) throw new RequestError(404, 'source-file-not-found')
46
+ return editor.scope(document ?? '')
47
+ }
48
+ const request = (value: unknown) => { if (size(value) > SOURCE_MAX_REQUEST_CHARS) throw new RequestError(413, 'source-request-too-large') }
49
+ const writer = (caller: SourceCaller) => {
50
+ if (!hasRole(caller.member, 'owner') || caller.boundDocument !== undefined || caller.confirmed) throw new RequestError(403, 'source-file-forbidden')
51
+ if (caller.origin === 'agent' && config.settings['presmium.assistant']?.review === 'required') throw new RequestError(409, 'authoring-review-required')
52
+ }
53
+ const repair = (path: string, before: Uint8Array | undefined) => {
54
+ if (!canonical(path)) return
55
+ if (!before || !listDocumentEntries(config).some(entry => entry.entry === path)) throw new RequestError(409, 'source-canonical-edit-required')
56
+ try { validateDocumentSource(path, Buffer.from(before).toString('utf8')) }
57
+ catch (error) { if ((error as Error).message === 'document-invalid') return; throw error }
58
+ throw new RequestError(409, 'source-canonical-edit-required')
59
+ }
60
+ return {
61
+ list: (query, caller) => bounded(async () => {
62
+ request(query)
63
+ if (!validateSourceList(query)) throw new RequestError(400, 'source-request-invalid')
64
+ const owned = scope(query.document, caller), listed = editor.files(owned, caller.member)
65
+ const files = listed.files.filter(file => !query.query || file.path.toLowerCase().includes(query.query.toLowerCase()))
66
+ const snapshot = digest(JSON.stringify([owned, query.query ?? '', files, listed.truncated ?? false])), offset = query.offset ?? 0
67
+ if (offset > 0 && !query.snapshot || query.snapshot !== undefined && query.snapshot !== snapshot) throw new RequestError(409, 'source-list-changed')
68
+ if (offset > files.length) throw new RequestError(400, 'source-request-invalid')
69
+ const answer = { files: [] as typeof files, snapshot, ...listed.truncated ? { truncated: true as const } : {} }
70
+ for (const file of files.slice(offset, offset + 20)) {
71
+ if (!fits({ ...answer, files: [...answer.files, file], nextOffset: offset + answer.files.length + 1 })) break
72
+ answer.files.push(file)
73
+ }
74
+ if (!answer.files.length && offset < files.length) throw new RequestError(413, 'source-response-too-large')
75
+ return { ...answer, ...offset + answer.files.length < files.length ? { nextOffset: offset + answer.files.length } : {} }
76
+ }),
77
+ read: (query, caller) => bounded(async () => {
78
+ request(query)
79
+ if (!validateSourceRead(query)) throw new RequestError(400, 'source-request-invalid')
80
+ const value = editor.read(scope(query.document, caller), query.path, caller.member), offset = query.offset ?? 0
81
+ if (offset > 0 && !query.version || query.version !== undefined && query.version !== value.version) throw new RequestError(409, 'source-version-changed')
82
+ if (offset > value.content.length) throw new RequestError(400, 'source-request-invalid')
83
+ const answer = { path: value.path, version: value.version, text: value.content.slice(offset, offset + SOURCE_FRAGMENT_CHARS), offset, totalChars: value.content.length, nextOffset: 0 }
84
+ const cursor = () => answer.nextOffset = offset + answer.text.length
85
+ cursor()
86
+ while (!fits(answer) && answer.text.length) { answer.text = answer.text.slice(0, Math.floor(answer.text.length / 2)); cursor() }
87
+ if (!fits(answer) || !answer.text.length && offset < value.content.length) throw new RequestError(413, 'source-response-too-large')
88
+ const { nextOffset, ...part } = answer
89
+ return { ...part, ...nextOffset < value.content.length ? { nextOffset } : {} }
90
+ }),
91
+ prepare: (edit, caller) => bounded(async () => {
92
+ request(edit); writer(caller)
93
+ if (!validateSourceEdit(edit)) throw new RequestError(400, 'source-request-invalid')
94
+ const document = edit.document, owned = scope(document, caller), edits = 'edits' in edit ? edit.edits : [edit]
95
+ const captured = edits.map(file => {
96
+ const creating = 'create' in file && file.create === true
97
+ if (creating && (canonical(file.path) || file.version !== undefined)) throw new RequestError(409, 'source-canonical-edit-required')
98
+ const before = creating ? undefined : editor.read(owned, file.path, caller.member)
99
+ if (file.version !== undefined && before?.version !== file.version) throw new RequestError(409, 'source-version-changed')
100
+ repair(file.path, before && Buffer.from(before.content))
101
+ let content: string
102
+ if ('content' in file) content = file.content
103
+ else {
104
+ const first = before!.content.indexOf(file.find)
105
+ if (first < 0 || before!.content.indexOf(file.find, first + 1) >= 0) throw new RequestError(409, 'source-find-not-unique')
106
+ content = before!.content.slice(0, first) + file.replace + before!.content.slice(first + file.find.length)
107
+ }
108
+ return { path: file.path, content, base: before?.version ?? null, changed: creating || before!.content !== content }
109
+ })
110
+ const changes = captured.map(({ changed: _changed, ...file }) => file)
111
+ await editor.planTransaction(owned, changes, caller.member)
112
+ let work: Promise<SourceSaved> | undefined
113
+ return { change: (signal?: AbortSignal) => work ??= bounded(async () => {
114
+ const result = await editor.transaction(owned, changes, caller.member, {
115
+ check: files => {
116
+ signal?.throwIfAborted(); writer(caller)
117
+ if (JSON.stringify(scope(document, caller)) !== JSON.stringify(owned)) throw new RequestError(409, 'source-scope-changed')
118
+ for (const file of files) repair(file.path, file.before)
119
+ },
120
+ run: task => revisions ? revisions.transaction(task) : task(),
121
+ commit: async (paths, lang) => {
122
+ if (!revisions) return
123
+ if ((await Promise.all(paths.map(path => revisions.ignores(path)))).some(Boolean)) throw new RequestError(409, 'source-ignored-file')
124
+ return revisions.commitWhileLocked({ paths, summary: saveSummary(paths[0]!, lang), body: '', origin: { kind: caller.origin === 'agent' ? 'agent' : 'editor', member: caller.member } })
125
+ },
126
+ })
127
+ let current = false
128
+ try { current = result.versions.every(value => editor.read(owned, value.path, caller.member).version === value.version) } catch { /* A successful write is not safely retryable when readback changes or fails. */ }
129
+ return { saved: true as const, changed: captured.some(file => file.changed), ...captured.length === 1 ? { path: captured[0]!.path } : { files: captured.length }, ...result.revision ? { revision: result.revision.id } : {}, ...!current ? { current: false as const } : {} }
130
+ }) }
131
+ }),
132
+ }
133
+ }
@@ -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 {