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

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
@@ -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,54 @@
1
+ import { WORKSPACE_CONFIG } from '@lincyaw/compiler'
2
+ import { applyMigration, planMigration } from '@lincyaw/compiler/migrate'
3
+ import type { MigrationPlan } from '@lincyaw/compiler/migrate'
4
+ import { DOCUMENT_ENTRY, hasRole, jsonResponse } from '@lincyaw/kernel'
5
+ import type { Route, WorkspaceMigrationAnswer } from '@lincyaw/kernel'
6
+ import type { WorkspaceConfig } from './config.ts'
7
+ import type { DocumentsChange } from './document-operations.ts'
8
+ import { catchRequestErrors, RequestError } from './errors.ts'
9
+ import type { DocumentLocks } from './locks.ts'
10
+ import type { Revisions } from './revisions.ts'
11
+
12
+ const dirOf = (path: string) => path.split('/').slice(0, -1).join('/')
13
+ /** The document folder a migrated file belongs to: a translation belongs to its original. */
14
+ const ownerOf = (path: string) => dirOf(path).replace(/(^|\/)locales\/[^/]+$/, '').replace(/\/\.presmium\/freeze$|^\.presmium\/freeze$/, '')
15
+
16
+ /**
17
+ * `POST workspace/migrate`, Studio's Upgrade: the migration of `presmium migrate`, recorded as one revision per
18
+ * document (its rename, translations and content) and one for the workspace file.
19
+ */
20
+ export function workspaceMigrateRoute(options: { config: WorkspaceConfig, locks: DocumentLocks, revisions?: Revisions, changed(change: DocumentsChange): Promise<void> | void }): Route {
21
+ const { config, locks, revisions } = options
22
+ return {
23
+ role: 'owner', maxBody: 1024,
24
+ handle: (request, ctx) => catchRequestErrors(async () => {
25
+ if (request.method !== 'POST') throw new RequestError(405, 'POST')
26
+ if (!hasRole(ctx.member, 'owner') || ctx.document !== '') throw new RequestError(403, 'workspace-migrate-forbidden')
27
+ const release = await locks.acquire('', 'workspace:migrate')
28
+ try {
29
+ const run = async (): Promise<WorkspaceMigrationAnswer> => {
30
+ const plan: MigrationPlan = planMigration(config.root)
31
+ const groups = new Map<string, string[]>()
32
+ const add = (path: string) => {
33
+ const owner = path === WORKSPACE_CONFIG ? WORKSPACE_CONFIG : ownerOf(path)
34
+ groups.set(owner, [...groups.get(owner) ?? [], path])
35
+ }
36
+ for (const { from, to } of plan.renames) { add(from); add(to) }
37
+ for (const { path } of plan.writes) add(path)
38
+ if (revisions) await revisions.checkpoint([...groups.values()].flat())
39
+ applyMigration(plan)
40
+ const revisionIds: string[] = []
41
+ if (revisions) for (const [owner, paths] of groups) {
42
+ const summary = owner === WORKSPACE_CONFIG ? `Upgrade ${WORKSPACE_CONFIG}` : `Upgrade ${owner ? `${owner}/` : ''}${DOCUMENT_ENTRY}`
43
+ const revision = await revisions.commitWhileLocked({ paths, summary, body: 'Convert to the current document format (presmium migrate).', origin: { kind: 'document', member: ctx.member } })
44
+ if (revision) revisionIds.push(revision.id)
45
+ }
46
+ return { documents: plan.documents.map(dirOf), workspaceFile: plan.workspaceFile, problems: plan.problems, revisions: revisionIds }
47
+ }
48
+ const answer = revisions ? await revisions.transaction(run) : await run()
49
+ if (answer.documents.length) await options.changed({ removed: [], added: answer.documents })
50
+ return jsonResponse(answer)
51
+ } finally { release() }
52
+ }),
53
+ }
54
+ }
@@ -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,16 +3,17 @@ 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'
7
- import type { DocumentFileChange, DocumentFiles } from '@lincyaw/kernel'
6
+ import { topLevelRanks, workspaceDocuments } from '@lincyaw/compiler'
7
+ import { CHANGES_MAX_BYTES, CHANGES_MAX_FILES, DOCUMENT_ENTRY, ranksBetween, validateDocument } from '@lincyaw/kernel'
8
+ import type { DocumentFileChange, DocumentFiles, DocumentPlacement } from '@lincyaw/kernel'
8
9
  import { isWithin, rewriteLinks } from '../domain/paths.ts'
9
10
  import { isDocumentDir, listDocuments } from './config.ts'
10
11
  import type { WorkspaceConfig } from './config.ts'
11
12
  import { findTemplate } from './templates.ts'
12
13
 
13
14
  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
15
+ export const DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES = CHANGES_MAX_FILES
16
+ export const DOCUMENT_OPERATION_MAX_BACKUP_BYTES = CHANGES_MAX_BYTES
16
17
 
17
18
  export class FilesError extends Error {}
18
19
  export class DocumentCheckpointRefusal extends FilesError {
@@ -238,19 +239,30 @@ function writeTemplate(config: WorkspaceConfig, dir: string, template: string, t
238
239
  if (!entries.some(entry => entry.path === DOCUMENT_ENTRY)) throw new FilesError(`The document template must contain ${DOCUMENT_ENTRY}.`)
239
240
  writeChanges(config, entries.map(({ path, executable }) => {
240
241
  const content = readFileSync(join(source, path))
241
- return { path: `${dir}/${path}`, content: path === DOCUMENT_ENTRY ? freshDocument(content, title, documentId) : content, ...executable ? { executable } : {} }
242
+ return { path: `${dir}/${path}`, content: path === DOCUMENT_ENTRY ? freshDocument(content, { parent: null, rank: topLevelRanks(config.root, 1)[0]! }, title, documentId) : content, ...executable ? { executable } : {} }
242
243
  }))
243
244
  }
244
245
 
246
+ /** Where a copy of the document in `dir` goes: beside it, right after it. */
247
+ function placementAfter(config: WorkspaceConfig, dir: string): DocumentPlacement {
248
+ const { tree } = workspaceDocuments(config.root)
249
+ const node = tree.order.find(node => node.path === `${dir}/${DOCUMENT_ENTRY}`)
250
+ if (!node) return { parent: null, rank: topLevelRanks(config.root, 1)[0]! }
251
+ const siblings = tree.children.get(node.parent) ?? []
252
+ const next = siblings[siblings.indexOf(node.id) + 1]
253
+ return { parent: node.parent, rank: ranksBetween(node.placement.rank || null, next === undefined ? null : tree.byId.get(next)!.placement.rank || null, 1)[0]! }
254
+ }
255
+
245
256
  /** A copy is a new document; block/section identities remain inside its new namespace. */
246
- function freshDocument(content: Uint8Array, title?: string, documentId?: string): Buffer {
257
+ function freshDocument(content: Uint8Array, placement: DocumentPlacement, title?: string, documentId?: string): Buffer {
247
258
  let value: unknown
248
259
  try { value = JSON.parse(Buffer.from(content).toString('utf8')) }
249
- catch { throw new FilesError(`Invalid ${DOCUMENT_ENTRY}: expected a JSON teaching document.`) }
260
+ catch { throw new FilesError(`Invalid ${DOCUMENT_ENTRY}: expected a JSON Presmium document.`) }
250
261
  const validated = validateDocument(value)
251
262
  if (!validated.document) throw new FilesError(`Invalid ${DOCUMENT_ENTRY}: ${validated.issues[0]?.message ?? 'document validation failed'}`)
252
263
  const document = validated.document
253
264
  document.id = documentId ?? randomUUID()
265
+ document.placement = placement
254
266
  if (title !== undefined) {
255
267
  document.metadata.title = title
256
268
  for (const section of Object.values(document.sections)) if (section.title === '{{title}}') section.title = title
@@ -263,13 +275,14 @@ function copyDocument(config: WorkspaceConfig, from: string, to: string, documen
263
275
  assertDocumentDir(config, to)
264
276
  const entries = documentSourceEntries(join(config.root, from))
265
277
  if (!entries.some(entry => entry.path === DOCUMENT_ENTRY)) throw new FilesError(`The copied document must contain ${DOCUMENT_ENTRY}.`)
278
+ const placement = placementAfter(config, from)
266
279
  writeChanges(config, entries.map(({ path, link, executable }): DocumentFileChange => {
267
280
  if (link !== undefined) {
268
281
  if (path === DOCUMENT_ENTRY) throw new FilesError('The canonical document entry cannot be a symbolic link when copied.')
269
282
  return { path: `${to}/${path}`, link }
270
283
  }
271
284
  const content = readFileSync(join(config.root, from, path))
272
- if (path === DOCUMENT_ENTRY) return { path: `${to}/${path}`, content: freshDocument(content, title, documentId) }
285
+ if (path === DOCUMENT_ENTRY) return { path: `${to}/${path}`, content: freshDocument(content, placement, title, documentId) }
273
286
  if (path.endsWith('.md')) return { path: `${to}/${path}`, content: Buffer.from(rewriteLinks(content.toString('utf8'), `${to}/${path}`, `${from}/${path}`, from, to)) }
274
287
  return { path: `${to}/${path}`, content, ...executable ? { executable } : {} }
275
288
  }))
@@ -1,6 +1,10 @@
1
1
  {
2
- "schemaVersion": 1,
2
+ "schemaVersion": 2,
3
3
  "id": "document-template",
4
+ "placement": {
5
+ "parent": null,
6
+ "rank": "a0"
7
+ },
4
8
  "metadata": {
5
9
  "title": "{{title}}",
6
10
  "lang": "zh-CN",