@lincyaw/workspace 1.0.0-rc.13 → 1.0.0-rc.131

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +4 -4
  2. package/package.json +8 -5
  3. package/src/domain/paths.ts +0 -15
  4. package/src/node/agent-activity.ts +46 -0
  5. package/src/node/archive.ts +33 -0
  6. package/src/node/authoring-clients.ts +73 -20
  7. package/src/node/authoring-windows.ts +165 -0
  8. package/src/node/build.ts +28 -23
  9. package/src/node/capture.ts +383 -0
  10. package/src/node/config.ts +136 -50
  11. package/src/node/document-assets.ts +2 -2
  12. package/src/node/document-audio.ts +65 -46
  13. package/src/node/document-authoring.ts +30 -15
  14. package/src/node/document-check.ts +36 -0
  15. package/src/node/document-history.ts +32 -5
  16. package/src/node/document-images.ts +24 -14
  17. package/src/node/document-import.ts +123 -0
  18. package/src/node/document-index.ts +644 -0
  19. package/src/node/document-materials.ts +80 -0
  20. package/src/node/document-operations.ts +4 -2
  21. package/src/node/document-transcription.ts +2 -1
  22. package/src/node/document-voice.ts +121 -13
  23. package/src/node/git-runner.mjs +19 -0
  24. package/src/node/git.ts +141 -22
  25. package/src/node/host-activity.ts +17 -0
  26. package/src/node/host-upgrade.ts +28 -0
  27. package/src/node/jobs.ts +40 -8
  28. package/src/node/local-history.ts +84 -0
  29. package/src/node/locks.ts +12 -0
  30. package/src/node/mcp-settings.ts +68 -0
  31. package/src/node/media-upload-messages.ts +4 -0
  32. package/src/node/media-upload-page.ts +57 -0
  33. package/src/node/media-upload.css +4 -0
  34. package/src/node/media-uploads.ts +116 -0
  35. package/src/node/page-delete.ts +0 -1
  36. package/src/node/project-files.ts +2 -2
  37. package/src/node/projects.ts +20 -5
  38. package/src/node/review/agent-session-reviews.ts +194 -63
  39. package/src/node/review/agent-workspace.ts +124 -0
  40. package/src/node/review/git-review.ts +47 -15
  41. package/src/node/review/record.ts +5 -1
  42. package/src/node/review/routes.ts +9 -1
  43. package/src/node/review/workspace-review.ts +87 -0
  44. package/src/node/revision-files.ts +54 -0
  45. package/src/node/revisions.ts +244 -59
  46. package/src/node/routes.ts +52 -59
  47. package/src/node/serve.ts +267 -52
  48. package/src/node/site.ts +5 -5
  49. package/src/node/source-editor.ts +66 -26
  50. package/src/node/speech-settings.ts +6 -8
  51. package/src/node/templates.ts +2 -2
  52. package/src/node/tree-operations.ts +425 -0
  53. package/src/node/tree-routes.ts +94 -0
  54. package/src/node/workbench-api.ts +14 -3
  55. package/src/node/workspace-changes.ts +130 -0
  56. package/src/node/workspace-migrate.ts +54 -0
  57. package/src/node/workspace-source.ts +133 -0
  58. package/src/node/writer.ts +21 -8
  59. package/templates/document/default/{lecture.json → index.pmd} +5 -1
@@ -1,7 +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'
6
+ import { CHANGES_MAX_BYTES, LOCAL_AUTHOR, SOURCE_MAX_BYTES, DOCUMENT_ENTRY } from '@lincyaw/kernel'
5
7
  import { leavesRoot } from '../domain/paths.ts'
6
8
  import { commitMessage, memberAddress, originOf } from '../domain/commit-message.ts'
7
9
  import type { CommitOrigin } from '../domain/commit-message.ts'
@@ -11,6 +13,9 @@ import { RequestError } from './errors.ts'
11
13
  import type { Git } from './git.ts'
12
14
  import { documentDirOf, isGeneratedPath, makeDocumentDir, writeChanges } from './writer.ts'
13
15
  import type { DocumentWriter } from './writer.ts'
16
+ import { revisionDigest, revisionFiles } from './revision-files.ts'
17
+ import type { RevisionFile } from './revision-files.ts'
18
+ import { captureLocalBaseline } from './local-history.ts'
14
19
 
15
20
  const FIELD = '\x00'
16
21
  const RECORD = '\x1e'
@@ -86,9 +91,9 @@ function undoTargets(entries: LogEntry[]): UndoTargets {
86
91
  if (at >= 0) stack.splice(at, 1)
87
92
  }
88
93
  for (const entry of [...entries].reverse()) {
94
+ if (entry.root) { done.length = 0; undone.length = 0; continue }
89
95
  const origin = originOf(entry.message)
90
96
  if (!origin) continue
91
- if (entry.root) { done.length = 0; undone.length = 0; continue }
92
97
  if (origin.operation) {
93
98
  done.length = 0
94
99
  undone.length = 0
@@ -177,6 +182,18 @@ export interface LockedCommit {
177
182
  trailers?: [string, string][]
178
183
  }
179
184
 
185
+ export interface RevisionChanges {
186
+ head?: string
187
+ ref?: string
188
+ index?: Buffer
189
+ indexPath: string
190
+ indexStamp: string
191
+ snapshot: string
192
+ files: UncommittedFile[]
193
+ encoded?: TreeFile[]
194
+ raw: RevisionFile[]
195
+ }
196
+
180
197
  export class Revisions implements RevisionService {
181
198
  readonly #git: Git
182
199
  readonly #files: RevisionFiles
@@ -186,19 +203,14 @@ export class Revisions implements RevisionService {
186
203
  this.#files = files
187
204
  }
188
205
 
189
- /** One authoring transaction holds the git queue and restores its index if file saving or committing fails. */
206
+ /** Serialize authoring work; commitWhileLocked owns its index changes and rollback. */
190
207
  transaction<T>(work: () => Promise<T>): Promise<T> {
191
- return this.#git.exclusive(async () => {
192
- const index = resolve(this.#git.root, (await this.#git.output(['rev-parse', '--git-path', 'index'])).trim())
193
- const before = existsSync(index) ? readFileSync(index) : undefined
194
- try {
195
- return await work()
196
- } catch (error) {
197
- if (before) writeFileSync(index, before)
198
- else rmSync(index, { force: true })
199
- throw error
200
- }
201
- })
208
+ return this.#git.exclusive(work)
209
+ }
210
+
211
+ /** Capture external preimages before a source mutation; the caller holds the revision transaction. */
212
+ async checkpoint(paths: string[]): Promise<void> {
213
+ if (this.#git.localHistory) await captureLocalBaseline(this.#git, paths)
202
214
  }
203
215
 
204
216
  commit(change: { files: string[], message: string, origin: CommitOrigin, trailers?: [string, string][] }): Promise<Revision | undefined> {
@@ -208,15 +220,177 @@ export class Revisions implements RevisionService {
208
220
 
209
221
  /** Commits the paths; the caller holds the git lock (`Git.exclusive`). */
210
222
  async commitWhileLocked(commit: LockedCommit): Promise<Revision | undefined> {
211
- const { summary, body, origin } = commit
212
223
  const unique = [...new Set(commit.paths.map(path => path.replace(/^\.?\/+|\/+$/g, '')).filter(path => path && !leavesRoot(path)))]
213
224
  if (unique.length === 0) return undefined
214
- await this.#git.output(['add', '-A', '--', ...unique], { GIT_LITERAL_PATHSPECS: '1' })
215
- const staged = (await this.#git.output(['diff', '--cached', '--name-only', '--', ...unique], { GIT_LITERAL_PATHSPECS: '1' })).trim()
216
- if (!staged) return undefined
217
- const message = withTrailers(commitMessage(summary, body, origin, commit.revert), commit.trailers ?? [])
218
- await this.#git.output([...await this.#identity(), 'commit', '-q', '--no-verify', '-m', message, ...this.#author(origin.member), '--', ...unique], { GIT_LITERAL_PATHSPECS: '1' })
219
- return this.#revision('HEAD')
225
+ const captured = await this.observeChanges(unique)
226
+ if (!captured.raw.length) return undefined
227
+ return this.#applyFrozen('commit', await this.freezeCommit(captured), commit)
228
+ }
229
+
230
+ /** Exact current raw bytes, HEAD/ref and index observation; never compiles or stages the real index. */
231
+ async observeChanges(roots: string[] = ['']): Promise<RevisionChanges> {
232
+ const before = await this.#changeState(), files = await this.uncommittedFiles(roots)
233
+ const raw = revisionFiles(this.#files.config.root, files.map(file => file.path))
234
+ const after = await this.#changeState()
235
+ if (!this.#sameState(before, after)) throw new RequestError(409, 'changes-state-changed')
236
+ return { ...before, files, raw, snapshot: revisionDigest(JSON.stringify([before.head, before.ref, before.indexStamp, raw.map(file => [file.path, file.mode, file.stamp])])) }
237
+ }
238
+
239
+ /** Encode approved raw bytes before an external confirmation; later filters cannot change these blobs. */
240
+ async freezeCommit(captured: RevisionChanges): Promise<RevisionChanges> {
241
+ await this.#verifyChanges(captured)
242
+ const encoded: TreeFile[] = []
243
+ for (const file of captured.raw) {
244
+ const data = file.change
245
+ if (!data) throw new RequestError(409, 'changes-file-unsupported')
246
+ if ('remove' in data) { encoded.push({ path: file.path, mode: '000000', oid: '' }); continue }
247
+ const bytes = 'link' in data ? Buffer.from(data.link) : Buffer.from(data.content)
248
+ const blob = await this.#git.run(['hash-object', '-w', ...'link' in data ? ['--no-filters'] : [`--path=${file.path}`], '--stdin'], {}, bytes)
249
+ if (blob.code !== 0) throw new RequestError(409, 'changes-encoding-failed')
250
+ encoded.push({ path: file.path, mode: file.mode, oid: blob.stdout.toString('utf8').trim() })
251
+ }
252
+ await this.#verifyChanges(captured)
253
+ return { ...captured, encoded }
254
+ }
255
+
256
+ /** Caller holds document locks; this is the only Git queue entry for a reviewed changes operation. */
257
+ applyChanges(which: 'commit' | 'discard', captured: RevisionChanges, commit?: LockedCommit, check?: () => void): Promise<Revision | undefined> {
258
+ return this.#git.exclusive(async () => this.#applyFrozen(which, which === 'commit' && !captured.encoded ? await this.freezeCommit(captured) : captured, commit, check))
259
+ }
260
+
261
+ /** Where the repository keeps its index: fixed for the repository, so asked once. */
262
+ #indexName?: Promise<string>
263
+
264
+ async #changeState() {
265
+ const [head, ref, indexName] = await Promise.all([
266
+ this.#git.run(['rev-parse', '--verify', '--quiet', 'HEAD']),
267
+ this.#git.run(['symbolic-ref', '--quiet', 'HEAD']),
268
+ this.#indexName ??= this.#git.output(['rev-parse', '--git-path', 'index']).catch((error: unknown) => { this.#indexName = undefined; throw error }),
269
+ ])
270
+ if (ref.code !== 0 && ref.code !== 1 || head.code !== 0 && !(head.code === 1 && ref.code === 0)) throw new RequestError(409, 'changes-repository-unavailable')
271
+ const indexPath = resolve(this.#git.root, indexName.trim()), index = existsSync(indexPath) ? readFileSync(indexPath) : undefined
272
+ 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' }
273
+ }
274
+
275
+ #sameState(a: Pick<RevisionChanges, 'head' | 'ref' | 'indexStamp'>, b: Pick<RevisionChanges, 'head' | 'ref' | 'indexStamp'>): boolean {
276
+ return a.head === b.head && a.ref === b.ref && a.indexStamp === b.indexStamp
277
+ }
278
+
279
+ async #verifyChanges(captured: RevisionChanges, files = true): Promise<void> {
280
+ if (!this.#sameState(captured, await this.#changeState())) throw new RequestError(409, 'changes-state-changed')
281
+ if (files) {
282
+ const current = revisionFiles(this.#files.config.root, captured.raw.map(file => file.path))
283
+ 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')
284
+ }
285
+ }
286
+
287
+ async #applyFrozen(which: 'commit' | 'discard', captured: RevisionChanges, commit?: LockedCommit, check?: () => void): Promise<Revision | undefined> {
288
+ if (!captured.raw.length || captured.raw.some(file => !file.change)) throw new RequestError(409, 'changes-file-unsupported')
289
+ const gitDir = resolve(this.#git.root, (await this.#git.output(['rev-parse', '--git-dir'])).trim())
290
+ if (['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'rebase-merge', 'rebase-apply', 'sequencer'].some(name => existsSync(join(gitDir, name)))
291
+ || (await this.#git.output(['ls-files', '--unmerged', '-z'])).length) throw new RequestError(409, 'changes-repository-busy')
292
+ const lock = `${captured.indexPath}.lock`
293
+ let fd: number
294
+ try { fd = openSync(lock, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600) }
295
+ catch { throw new RequestError(409, 'changes-index-busy') }
296
+ // The review Git guard already excludes *.lock entries; active private indexes must share that lifetime.
297
+ let identity: ReturnType<typeof fstatSync> | undefined
298
+ const work = join(dirname(captured.indexPath), `presmium-index-${randomUUID()}.lock`)
299
+ let installed = false, published = false, wrote = false, created = false, recovery = false
300
+ const restoreIndex = () => {
301
+ if (captured.index) { const previous = join(work, 'previous'); writeFileSync(previous, captured.index, { mode: 0o600 }); renameSync(previous, captured.indexPath) }
302
+ else rmSync(captured.indexPath, { force: true })
303
+ }
304
+ try {
305
+ identity = fstatSync(fd)
306
+ mkdirSync(work, { mode: 0o700 }); created = true
307
+ await this.#verifyChanges(captured); check?.()
308
+ const env = (name: string) => ({ GIT_INDEX_FILE: join(work, name), GIT_LITERAL_PATHSPECS: '1', GIT_OPTIONAL_LOCKS: '0' })
309
+ const next = env('next'), selected = env('selected')
310
+ if (captured.index) writeFileSync(next.GIT_INDEX_FILE, captured.index)
311
+ else await this.#git.output(['read-tree', '--empty'], next)
312
+ await this.#git.output(['read-tree', captured.head ?? '--empty'], selected)
313
+ const base = (await this.#git.output(['write-tree'], selected)).trim()
314
+ const files: TreeFile[] = []
315
+ const targets: DocumentFileChange[] = []
316
+ const encoded = new Map(captured.encoded?.map(file => [file.path, file]))
317
+ let targetBytes = 0
318
+ for (const file of captured.raw) {
319
+ if (which === 'discard') {
320
+ const item = await this.#atTree(captured.head, file.path)
321
+ files.push(item)
322
+ const target = await this.#treeChange(item, CHANGES_MAX_BYTES - targetBytes)
323
+ targetBytes += 'content' in target ? Buffer.byteLength(target.content) : 'link' in target ? Buffer.byteLength(target.link) : 0
324
+ targets.push(target)
325
+ } else {
326
+ const frozen = encoded.get(file.path)
327
+ if (!frozen) throw new RequestError(409, 'changes-encoding-failed')
328
+ files.push(frozen)
329
+ }
330
+ }
331
+ const zero = '0'.repeat(base.length)
332
+ 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(''))
333
+ for (const index of [next, selected]) {
334
+ const updated = await this.#git.run(['-C', this.#git.top, 'update-index', '-z', '--index-info'], index, input)
335
+ if (updated.code !== 0) throw new RequestError(409, 'changes-index-update-failed')
336
+ }
337
+ let revision: Revision | undefined
338
+ if (which === 'commit') {
339
+ if (!commit) throw new RequestError(400, 'changes-request-invalid')
340
+ const tree = (await this.#git.output(['write-tree'], selected)).trim()
341
+ if (tree !== base) {
342
+ const member = await this.#author(commit.origin.member), origin = { ...commit.origin, ...member ? { member } : {} }
343
+ const message = withTrailers(commitMessage(commit.summary, commit.body, origin, commit.revert), commit.trailers ?? [])
344
+ const author = member && /^(.*) <([^>]*)>$/.exec(memberAddress(member))
345
+ 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()
346
+ revision = await this.#revision(hash)
347
+ if (!revision) throw new RequestError(409, 'changes-revision-unavailable')
348
+ }
349
+ }
350
+ // Blobs are already fixed; preserve late working edits while verifying the real index and branch.
351
+ await this.#verifyChanges(captured, which === 'discard'); check?.()
352
+ if (which === 'discard') { wrote = true; await this.#writeChanges(targets) }
353
+ renameSync(next.GIT_INDEX_FILE, captured.indexPath); installed = true
354
+ if (revision) {
355
+ const result = await this.#git.run(['update-ref', captured.ref ?? 'HEAD', revision.id, captured.head ?? zero])
356
+ if (result.code !== 0) throw new RequestError(409, 'changes-state-changed')
357
+ published = true
358
+ }
359
+ return revision
360
+ } catch (error) {
361
+ if (!published) {
362
+ try { if (wrote) await this.#writeChanges(captured.raw.map(file => file.change!)) } catch { recovery = true }
363
+ try { if (installed) restoreIndex() } catch { recovery = true }
364
+ if (recovery) throw new RequestError(500, 'changes-recovery-required')
365
+ }
366
+ throw error
367
+ } finally {
368
+ // Cleanup cannot turn an already published commit into a reported failure.
369
+ try { closeSync(fd) } catch {}
370
+ try {
371
+ const current = lstatSync(lock, { throwIfNoEntry: false })
372
+ if (identity && current?.ino === identity.ino && current.dev === identity.dev) rmSync(lock, { force: true })
373
+ } catch {}
374
+ try { if (created && !recovery) rmSync(work, { recursive: true, force: true }) } catch {}
375
+ }
376
+ }
377
+
378
+ async #atTree(head: string | undefined, path: string): Promise<TreeFile> {
379
+ if (!head) return { path, mode: '000000', oid: '' }
380
+ const raw = await this.#git.output(['ls-tree', '-z', head, '--', path], { GIT_LITERAL_PATHSPECS: '1' })
381
+ const entry = raw.split('\0')[0] ?? '', at = entry.indexOf('\t'), meta = entry.slice(0, at).split(' ')
382
+ if (at < 0) return { path, mode: '000000', oid: '' }
383
+ if (!['100644', '100755', '120000'].includes(meta[0] ?? '')) throw new RequestError(409, 'changes-file-unsupported')
384
+ return { path, mode: meta[0]!, oid: meta[2]! }
385
+ }
386
+
387
+ async #treeChange(file: TreeFile, maxBytes = CHANGES_MAX_BYTES): Promise<DocumentFileChange> {
388
+ if (/^0+$/.test(file.mode)) return { path: file.path, remove: true }
389
+ const size = Number((await this.#git.output(['cat-file', '-s', file.oid])).trim())
390
+ if (!Number.isSafeInteger(size) || size > maxBytes) throw new RequestError(413, 'changes-selection-too-large')
391
+ const blob = await this.#git.run(['cat-file', 'blob', file.oid])
392
+ if (blob.code !== 0) throw new RequestError(409, 'changes-object-unavailable')
393
+ return file.mode === '120000' ? { path: file.path, link: blob.stdout.toString('utf8') } : { path: file.path, content: blob.stdout, executable: file.mode === '100755' }
220
394
  }
221
395
 
222
396
  async status(paths: string[] = ['']): Promise<{ branch?: string, uncommitted: number }> {
@@ -228,10 +402,10 @@ export class Revisions implements RevisionService {
228
402
  const specs = paths.map(path => path || '.')
229
403
  const status = await this.#statusOf(paths)
230
404
  const counts = new Map<string, [number, number]>()
231
- const numstat = await this.#git.tryOutput(['diff', '--numstat', '-z', '--no-renames', 'HEAD', '--', ...specs], { GIT_LITERAL_PATHSPECS: '1' })
405
+ 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' })
232
406
  if (numstat.ok) {
233
407
  for (const entry of numstat.output.split('\0').filter(Boolean)) {
234
- const [added = '-', removed = '-', path = ''] = entry.split('\t')
408
+ const [added = '-', removed = '-', ...named] = entry.split('\t'), path = named.join('\t')
235
409
  if (added !== '-') counts.set(this.#fromTop(path), [Number(added), Number(removed)])
236
410
  }
237
411
  }
@@ -244,14 +418,8 @@ export class Revisions implements RevisionService {
244
418
 
245
419
  discard(paths: string[]): Promise<void> {
246
420
  return this.#git.exclusive(async () => {
247
- const files: TreeFile[] = []
248
- for (const path of paths) {
249
- const listed = await this.#git.tryOutput(['ls-tree', '-z', 'HEAD', '--', path], { GIT_LITERAL_PATHSPECS: '1' })
250
- const [meta = '', named] = (listed.ok ? listed.output.split('\0')[0] ?? '' : '').split('\t')
251
- const [mode = '', , oid = ''] = meta.split(' ')
252
- files.push(named && mode ? { path, mode, oid } : { path, mode: '000000', oid: '' })
253
- }
254
- await this.#write(files)
421
+ const captured = await this.observeChanges(paths)
422
+ if (captured.raw.length) await this.#applyFrozen('discard', captured)
255
423
  })
256
424
  }
257
425
 
@@ -270,6 +438,13 @@ export class Revisions implements RevisionService {
270
438
  return this.#git.exclusive(async () => undoTargets(await this.#entries(document))[which])
271
439
  }
272
440
 
441
+ /** The first parent of a revision in the current history; none for the root. */
442
+ async parentOf(id: string): Promise<string | undefined> {
443
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(id)) throw new RequestError(400, 'history-file-invalid')
444
+ const result = await this.#git.tryOutput(['rev-parse', '--verify', '--quiet', `${id}^1`])
445
+ return result.ok ? result.output.trim() || undefined : undefined
446
+ }
447
+
273
448
  async head(): Promise<string | undefined> {
274
449
  const result = await this.#git.tryOutput(['rev-parse', '--verify', 'HEAD'])
275
450
  return result.ok ? result.output.trim() : undefined
@@ -281,7 +456,7 @@ export class Revisions implements RevisionService {
281
456
  if (!(await this.#git.tryOutput(['merge-base', '--is-ancestor', id, 'HEAD'])).ok) throw new RequestError(404, 'history-revision-not-found')
282
457
  const topPath = relative(this.#git.top, resolve(this.#files.config.root, path)).split(sep).join('/')
283
458
  const listed = await this.#git.output(['-C', this.#git.top, 'ls-tree', '-z', id, '--', topPath], { GIT_LITERAL_PATHSPECS: '1' })
284
- const [meta = '', named] = (listed.split('\0')[0] ?? '').split('\t')
459
+ const record = listed.split('\0')[0] ?? '', at = record.indexOf('\t'), meta = record.slice(0, at), named = record.slice(at + 1)
285
460
  const [mode, type, oid] = meta.split(' ')
286
461
  if (named !== topPath || !oid) throw new RequestError(404, 'history-file-not-found')
287
462
  if (type !== 'blob' || !['100644', '100755'].includes(mode!)) throw new RequestError(422, 'history-file-not-regular-text')
@@ -344,7 +519,7 @@ export class Revisions implements RevisionService {
344
519
  while (at < tree.length) {
345
520
  const space = tree.indexOf(32, at), zero = tree.indexOf(0, space + 1)
346
521
  if (space < at || zero < space || zero + 1 + oidBytes > tree.length) throw new RequestError(500, 'history-tree-read-failed')
347
- if (tree.subarray(space + 1, zero).toString('utf8') === 'lecture.json') found = ['100644', '100755'].includes(tree.subarray(at, space).toString('ascii'))
522
+ if (tree.subarray(space + 1, zero).toString('utf8') === DOCUMENT_ENTRY) found = ['100644', '100755'].includes(tree.subarray(at, space).toString('ascii'))
348
523
  at = zero + 1 + oidBytes
349
524
  }
350
525
  regular.set(oid, found); cursor = end + 1
@@ -392,8 +567,6 @@ export class Revisions implements RevisionService {
392
567
  const { target, tree, changes } = planned
393
568
  const originalHead = await this.head()
394
569
  const restore = await this.#changes(tree, 'HEAD')
395
- const indexPath = resolve(this.#git.root, (await this.#git.output(['rev-parse', '--git-path', 'index'])).trim())
396
- const oldIndex = existsSync(indexPath) ? readFileSync(indexPath) : undefined
397
570
  try {
398
571
  await this.#write(changes)
399
572
  const subject = target.message.split('\n')[0] ?? target.id
@@ -406,13 +579,19 @@ export class Revisions implements RevisionService {
406
579
  const afterHead = await this.head()
407
580
  if (afterHead !== originalHead) throw new RequestError(409, 'history-readback-changed', { committed: true, snapshot: afterHead })
408
581
  await this.#write(restore)
409
- if (oldIndex) writeFileSync(indexPath, oldIndex)
410
- else rmSync(indexPath, { force: true })
411
582
  throw error
412
583
  }
413
584
  })
414
585
  }
415
586
 
587
+ /** Checks a whole import before writing; one Git process regardless of file count. */
588
+ async ignoresAny(paths: string[]): Promise<boolean> {
589
+ if (!paths.length) return false
590
+ const answer = await this.#git.run(['check-ignore', '-z', '--stdin'], {}, Buffer.from(paths.map(path => `${path}\0`).join('')))
591
+ if (answer.code > 1) throw new Error('history-ignore-check-failed')
592
+ return answer.code === 0
593
+ }
594
+
416
595
  /** Whether git ignores the path, which a commit then leaves out. */
417
596
  async ignores(path: string): Promise<boolean> {
418
597
  return (await this.#git.run(['check-ignore', '-q', '--', path])).code === 0
@@ -440,7 +619,7 @@ export class Revisions implements RevisionService {
440
619
  const entries = log.ok ? parseLog(log.output).map(entry => ({ ...entry, files: entry.files.map(this.#fromTop) })) : []
441
620
  if (entries.length) {
442
621
  const rootIds = new Set((await this.#git.output(['rev-list', '--max-parents=0', 'HEAD'])).trim().split('\n'))
443
- for (const entry of entries) if (rootIds.has(entry.id)) entry.root = true
622
+ for (const entry of entries) if (rootIds.has(entry.id) || /^Presmium-Baseline: true$/m.test(entry.message)) entry.root = true
444
623
  }
445
624
  if (document === undefined) return entries
446
625
  const candidates = entries.flatMap((entry, index) => entry.files.filter(path => !leavesRoot(path) && (document === '' || path.startsWith(document + '/'))).map(path => ({ index, path, id: entry.id })))
@@ -454,8 +633,8 @@ export class Revisions implements RevisionService {
454
633
  }
455
634
 
456
635
  async #statusOf(paths: string[]): Promise<{ code: string, path: string }[]> {
457
- const status = await this.#git.tryOutput(['status', '--porcelain=v1', '-z', '--no-renames', '--untracked-files=all', '--', ...paths.map(path => path || '.')], { GIT_LITERAL_PATHSPECS: '1' })
458
- if (!status.ok) return []
636
+ 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' })
637
+ if (!status.ok) throw new RequestError(409, 'changes-repository-unavailable')
459
638
  return status.output.split('\0').filter(Boolean)
460
639
  .map(entry => ({ code: entry.slice(0, 2), path: this.#fromTop(entry.slice(3)) }))
461
640
  .filter(({ path }) => !isGeneratedPath(path))
@@ -502,29 +681,24 @@ export class Revisions implements RevisionService {
502
681
  }
503
682
 
504
683
  async #write(files: TreeFile[]): Promise<void> {
684
+ const changes = await Promise.all(files.map(file => this.#treeChange(file)))
685
+ return this.#writeChanges(changes)
686
+ }
687
+
688
+ async #writeChanges(files: DocumentFileChange[]): Promise<void> {
505
689
  const { config, writer } = this.#files
506
690
  const changes: { change: DocumentFileChange, dir?: string }[] = []
507
- for (const file of files) {
508
- if (file.mode === '160000') throw new Error(`${file.path} is a submodule: not reverted`)
509
- const dir = documentDirOf(config, file.path)
510
- if (/^0+$/.test(file.mode)) {
511
- changes.push({ change: { path: file.path, remove: true }, dir })
512
- continue
513
- }
514
- const blob = (await this.#git.run(['cat-file', 'blob', file.oid])).stdout
515
- const change: DocumentFileChange = file.mode === '120000' ? { path: file.path, link: blob.toString('utf8') } : { path: file.path, content: blob, ...file.mode === '100755' ? { executable: true } : {} }
516
- changes.push({ change, dir })
691
+ for (const change of files) changes.push({ change, dir: documentDirOf(config, change.path) })
692
+ const outside = changes.filter(({ dir }) => dir === undefined).map(({ change }) => change)
693
+ for (const { path } of outside) {
694
+ const open = writableByOthers(config.root, path)
695
+ if (open) throw new Error(`the revert would write ${path}, in ${open}, which more than serve may write`)
517
696
  }
518
697
  const inDocuments = changes.filter(({ dir }) => dir !== undefined)
519
698
  for (const dir of new Set(inDocuments.filter(({ change }) => !('remove' in change)).map(({ dir }) => dir!))) {
520
699
  if (!exists(join(config.root, dir))) makeDocumentDir(config.root, dir)
521
700
  }
522
701
  if (inDocuments.length > 0) await writer.write(inDocuments.map(({ change }) => change))
523
- const outside = changes.filter(({ dir }) => dir === undefined).map(({ change }) => change)
524
- for (const { path } of outside) {
525
- const open = writableByOthers(config.root, path)
526
- if (open) throw new Error(`the revert would write ${path}, in ${open}, which more than serve may write`)
527
- }
528
702
  if (outside.length > 0) writeChanges(config, outside, true)
529
703
  for (const dir of new Set(inDocuments.map(({ dir }) => dir!))) {
530
704
  if (!dir) continue
@@ -545,8 +719,15 @@ export class Revisions implements RevisionService {
545
719
  return entry && revision(entry)
546
720
  }
547
721
 
548
- #author(member: Member | undefined): string[] {
549
- return member ? [`--author=${memberAddress(member)}`] : []
722
+ /**
723
+ * The member a commit names as its author. The local author (the one person a local service serves) is the
724
+ * repository's configured git user when git has one, so that their saves are theirs; members of a shared service
725
+ * have their own name and email.
726
+ */
727
+ async #author(member: Member | undefined): Promise<Member | undefined> {
728
+ if (!member || member.email || member.id !== LOCAL_AUTHOR.id || member.name !== LOCAL_AUTHOR.name) return member
729
+ const [name, email] = await Promise.all([this.#git.tryOutput(['config', 'user.name']), this.#git.tryOutput(['config', 'user.email'])])
730
+ return name.ok && email.ok && name.output.trim() && email.output.trim() ? { ...member, name: name.output.trim(), email: email.output.trim() } : member
550
731
  }
551
732
 
552
733
  async #identity(): Promise<string[]> {
@@ -580,7 +761,11 @@ function writableByOthers(root: string, path: string): string | undefined {
580
761
 
581
762
  function lineCount(path: string): [number, number] | undefined {
582
763
  try {
583
- const bytes = readFileSync(path)
764
+ const stat = lstatSync(path)
765
+ if (!stat.isFile() || stat.size > SOURCE_MAX_BYTES) return
766
+ const file = revisionFiles(dirname(path), [basename(path)])[0], change = file?.change
767
+ if (!change || !('content' in change)) return
768
+ const bytes = Buffer.from(change.content)
584
769
  if (bytes.includes(0)) return undefined
585
770
  const text = bytes.toString('utf8')
586
771
  return [text === '' ? 0 : text.split('\n').length - (text.endsWith('\n') ? 1 : 0), 0]
@@ -1,20 +1,20 @@
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
+ import { migrationNeed } from '@lincyaw/compiler/migrate'
6
7
  import { saveSummary } from '../domain/commit-message.ts'
7
8
  import { documentSummaries, listDocuments } from './config.ts'
8
9
  import type { WorkspaceConfig } from './config.ts'
9
10
  import { documentsDiff } from './document-operations.ts'
10
11
  import type { DocumentOperations, DocumentsChange } from './document-operations.ts'
11
12
  import { catchRequestErrors, RequestError } from './errors.ts'
12
- import { lockedError } from './locks.ts'
13
13
  import type { DocumentLocks } from './locks.ts'
14
14
  import type { Revisions } from './revisions.ts'
15
15
  import { reviewRoutes } from './review/routes.ts'
16
16
  import type { AgentSessionReviews } from './review/agent-session-reviews.ts'
17
- import { MAX_SOURCE, MAX_SOURCE_CHANGES, validateDocumentSource } from './source-editor.ts'
17
+ import { MAX_SOURCE, MAX_SOURCE_CHANGES } from './source-editor.ts'
18
18
  import type { SourceEditor } from './source-editor.ts'
19
19
  import { listTemplates } from './templates.ts'
20
20
  import type { Jobs } from './jobs.ts'
@@ -25,8 +25,11 @@ import { createDocumentAudioAuthoring } from './document-audio.ts'
25
25
  import { createDocumentImageAuthoring } from './document-images.ts'
26
26
  import { createDocumentTranscriptions, documentTranscriptionRoutes } from './document-transcription.ts'
27
27
  import type { DocumentTranscriptions, ProductionAudioAuthoring, SpeechService } from '@lincyaw/kernel'
28
- import { documentDirOf } from './writer.ts'
29
28
  import { createDocumentHistory } from './document-history.ts'
29
+ import { createWorkspaceChanges } from './workspace-changes.ts'
30
+ import { DocumentIndex } from './document-index.ts'
31
+ import type { TreeOperations } from './tree-operations.ts'
32
+ import { treeRoutes } from './tree-routes.ts'
30
33
 
31
34
  const { version } = createRequire(import.meta.url)('../../package.json') as { version: string }
32
35
 
@@ -45,6 +48,7 @@ export interface WorkspaceRoutesOptions {
45
48
  documentEditor: DocumentEditor
46
49
  locks: DocumentLocks
47
50
  revisions?: Revisions
51
+ projectRevisions?: Revisions
48
52
  operations?: DocumentOperations
49
53
  reviews?: AgentSessionReviews
50
54
  documentsChanged(change: DocumentsChange): Promise<void> | void
@@ -61,7 +65,19 @@ export interface WorkspaceRoutesOptions {
61
65
  historyRoutes?: Record<string, Route>
62
66
  authoringClientRoutes?: Record<string, Route>
63
67
  projectRoutes?: Record<string, Route>
68
+ documentImport?: Route
69
+ documentMaterials?: Route
70
+ workspaceMigrate?: Route
71
+ mcpSettings?: Route
64
72
  speechSettings?: Route
73
+ changesRoutes?: Record<string, Route>
74
+ /** Shared mutable allow-list; a later local Studio may register its preview origin. */
75
+ previewOrigins?: string[]
76
+ hostUpgrade?: Route
77
+ /** The document tree's index; without one, the routes read the tree from the files on each request. */
78
+ index?: DocumentIndex
79
+ /** The tree operations; without them `tree/operation` refuses. */
80
+ treeOperations?: TreeOperations
65
81
  }
66
82
 
67
83
  function toRendererIds(body: unknown): string[] | undefined {
@@ -70,13 +86,6 @@ function toRendererIds(body: unknown): string[] | undefined {
70
86
  return ids.length > 0 ? ids : undefined
71
87
  }
72
88
 
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
89
 
81
90
  function toSaveMessage(value: unknown): string {
82
91
  return typeof value === 'string' ? [...(value.trim().split(/\r?\n/)[0] ?? '').trim()].slice(0, 200).join('') : ''
@@ -87,26 +96,33 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
87
96
  const { config, editor, locks, revisions, operations, reviews, workbench } = options
88
97
  const listed = () => listDocuments(config).map(doc => doc.dir)
89
98
  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
- }
99
+ const changes = options.changesRoutes ?? createWorkspaceChanges({ config, editor, locks, revisions, changed: options.documentsChanged }).routes
105
100
  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
101
  const ownedTranscriptions = options.transcriptions ? undefined : createDocumentTranscriptions({ root: config.root, editor, audio: options.audio, speech: options.speech })
107
102
  const transcriptions = options.transcriptions ?? ownedTranscriptions!
108
103
  const ownedAudio = options.audioAuthoringRoutes ? undefined : createDocumentAudioAuthoring({ root: config.root, editor, revisions, audio: options.audio, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
109
104
  const routes: Record<string, Route> = {
105
+ ...options.hostUpgrade ? { 'host-upgrade': options.hostUpgrade } : {},
106
+ ...options.previewOrigins ? { 'preview-origins': {
107
+ role: 'owner', maxBody: 8192,
108
+ handle: async (request: Request) => {
109
+ if (request.method !== 'POST') return problemResponse(405, 'POST')
110
+ const body: unknown = await request.json().catch(() => undefined)
111
+ if (!isRecord(body) || Object.keys(body).some(key => key !== 'origins') || !Array.isArray(body.origins) || body.origins.length > 16) return problemResponse(400, 'preview-origins-invalid')
112
+ const origins: string[] = []
113
+ for (const value of body.origins) {
114
+ if (typeof value !== 'string' || value.length > 2048) return problemResponse(400, 'preview-origins-invalid')
115
+ let url: URL
116
+ try { url = new URL(value) } catch { return problemResponse(400, 'preview-origins-invalid') }
117
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.origin !== value) return problemResponse(400, 'preview-origins-invalid')
118
+ if (!origins.includes(value) && !options.previewOrigins!.includes(value)) origins.push(value)
119
+ }
120
+ if (options.previewOrigins!.length + origins.length > 128) return problemResponse(413, 'preview-origins-limit')
121
+ options.previewOrigins!.push(...origins)
122
+ return jsonResponse({ added: origins.length })
123
+ },
124
+ } satisfies Route } : {},
125
+ ...options.mcpSettings ? { 'mcp-settings': options.mcpSettings } : {},
110
126
  ...options.speechSettings ? { 'speech-settings': options.speechSettings } : {},
111
127
  ...documentEditorRoutes({ root: config.root, editor, documentEditor: options.documentEditor, workbench }),
112
128
  ...(options.audioAuthoringRoutes ?? ownedAudio!.routes),
@@ -117,8 +133,9 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
117
133
  role: 'reader',
118
134
  handle: (request, ctx) => catchRequestErrors(async () => {
119
135
  if (request.method === 'GET') {
120
- const status = revisions ? await revisions.status(editor.roots(scopeOf(ctx))) : {}
121
- return jsonResponse({ title: config.title, documents: documentSummaries(config), templates: listTemplates(config), git: Boolean(revisions), ...status, single: config.singleDeck } satisfies DocumentsAnswer)
136
+ const status = options.projectRevisions ? await options.projectRevisions.status(editor.roots(scopeOf(ctx))) : {}
137
+ const migration = migrationNeed(config.root)
138
+ return jsonResponse({ title: config.title, documents: documentSummaries(config), templates: listTemplates(config), git: Boolean(revisions), ...status, single: config.singleDeck, ...migration ? { migration } : {} } satisfies DocumentsAnswer)
122
139
  }
123
140
  if (request.method !== 'POST') return problemResponse(405, 'GET or POST')
124
141
  return problemResponse(409, 'project-plan-required')
@@ -127,6 +144,9 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
127
144
  ...(options.historyRoutes ?? ownedHistory!.routes),
128
145
  ...options.authoringClientRoutes,
129
146
  ...options.projectRoutes,
147
+ ...options.documentImport ? { 'documents/import': options.documentImport } : {},
148
+ ...options.documentMaterials ? { 'document/materials': options.documentMaterials } : {},
149
+ ...options.workspaceMigrate ? { 'workspace/migrate': options.workspaceMigrate } : {},
130
150
  'files': {
131
151
  role: 'editor',
132
152
  handle: (request, ctx) => catchRequestErrors(async () => {
@@ -178,39 +198,12 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
178
198
  return jsonResponse(await editor.transaction(scopeOf(ctx), changes, ctx.member, history) satisfies SourceTransactionAnswer)
179
199
  }),
180
200
  },
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
- },
201
+ ...changes,
202
+ ...treeRoutes(options.index ?? new DocumentIndex(config), options.treeOperations),
202
203
  ...workbench ? workbenchRoutes(workbench) : {},
203
204
  ...options.jobs ? jobRoutes(options.jobs, editor) : {},
204
205
  ...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
- },
206
+
214
207
  }
215
208
  return { routes: authorizeWorkspaceRoutes(routes, options.launcherToken), close: async () => { await Promise.all([ownedTranscriptions?.close(), ownedAudio?.close(), ownedHistory?.close()]) } }
216
209
  }
@@ -257,7 +250,7 @@ function workbenchRoutes(workbench: WorkbenchApi): Record<string, Route> {
257
250
  const params = new URL(request.url).searchParams
258
251
  const renderer = params.get('view') ?? undefined
259
252
  if (renderer !== undefined && renderer !== 'web' && renderer !== 'slides') return problemResponse(400, 'view must be web or slides')
260
- return jsonResponse(await workbench.preview(ctx.document, renderer, params.get('prefetch') === '1'))
253
+ return jsonResponse(await workbench.preview(ctx.document, renderer, params.get('prefetch') === '1', request.headers.get('x-presmium-preview-origin') ?? undefined))
261
254
  }),
262
255
  },
263
256
  'build': {