@lincyaw/workspace 1.0.0-rc.8 → 1.0.0-rc.81

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.
@@ -18,6 +18,13 @@ export function reviewRoutes(reviews: AgentSessionReviews): Record<string, Route
18
18
  handle: (request, ctx) => catchRequestErrors(async () => (request.method === 'POST' ? handle(await readBody(request), ctx.document) : problemResponse(405, 'POST'))),
19
19
  })
20
20
  return {
21
+ 'review/workspace': post(async body => {
22
+ const session = toText(body.session, 200)
23
+ if (!session) return problemResponse(400, '{ session }')
24
+ if (body.close === true) { await reviews.closeWorkspace(session); return jsonResponse({ closed: true }) }
25
+ if (body.refresh === true) await reviews.refreshWorkspace(session)
26
+ return jsonResponse(await reviews.workspace(session))
27
+ }),
21
28
  'review': {
22
29
  role: 'editor',
23
30
  handle: (request, ctx) => catchRequestErrors(async () => {
@@ -0,0 +1,87 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { hasRole, WORKSPACE_REVIEW_FRAGMENT_CHARS, WORKSPACE_REVIEW_MAX_REQUEST_CHARS, WORKSPACE_REVIEW_MAX_RESPONSE_CHARS } from '@lincyaw/kernel'
3
+ import type { Member, WorkspaceReview, WorkspaceReviewAnswer, WorkspaceReviewChange } from '@lincyaw/kernel'
4
+ import { validateWorkspaceReviewChange, validateWorkspaceReviewQuery } from '@lincyaw/kernel/node'
5
+ import { RequestError } from '../errors.ts'
6
+ import type { AgentSessionReviews } from './agent-session-reviews.ts'
7
+
8
+ const size = (value: unknown) => JSON.stringify(value).length
9
+ const authorize = (member: Member) => { if (!hasRole(member, 'owner')) throw new RequestError(403, 'workspace-review-permission-denied') }
10
+ const budget = (value: unknown) => { if (size(value) > WORKSPACE_REVIEW_MAX_REQUEST_CHARS) throw new RequestError(413, 'workspace-review-request-too-large') }
11
+ const fits = (value: unknown) => size(value) <= WORKSPACE_REVIEW_MAX_RESPONSE_CHARS
12
+
13
+ /** Bounded publication interface over the same review queue, candidate trees and writer used by Web. */
14
+ export function createWorkspaceReview(reviews: AgentSessionReviews): WorkspaceReview {
15
+ const inspect = async (change: WorkspaceReviewChange, member: Member) => {
16
+ authorize(member); budget(change)
17
+ if (!validateWorkspaceReviewChange(change)) throw new RequestError(400, 'workspace-review-change-invalid')
18
+ const state = await reviews.inspect()
19
+ if (!state || state.snapshot !== change.snapshot) throw new RequestError(409, 'workspace-review-changed')
20
+ if (state.review.running) throw new RequestError(409, 'workspace-review-running')
21
+ if (change.action === 'restore') {
22
+ if (!state.review.steps.some(step => step.id === change.step)) throw new RequestError(404, 'workspace-review-step-not-found')
23
+ } else {
24
+ const selected = change.action === 'accept' ? change.reject : change.paths
25
+ if (selected?.some(path => !state.review.changes.some(file => file.path === path))) throw new RequestError(409, 'workspace-review-path-changed')
26
+ }
27
+ return state
28
+ }
29
+ return {
30
+ async read(query, member) {
31
+ authorize(member); budget(query)
32
+ if (!validateWorkspaceReviewQuery(query)) throw new RequestError(400, 'workspace-review-query-invalid')
33
+ const part = query.part ?? 'summary', offset = query.offset ?? 0
34
+ if ((query.path !== undefined || query.step !== undefined) && part !== 'diff' || offset > 0 && !query.snapshot || part === 'summary' && offset !== 0) throw new RequestError(400, 'workspace-review-query-invalid')
35
+ const state = await reviews.inspect()
36
+ if (query.snapshot !== undefined && state?.snapshot !== query.snapshot) throw new RequestError(409, 'workspace-review-changed')
37
+ if (!state) {
38
+ if (part !== 'summary') throw new RequestError(404, 'workspace-review-not-found')
39
+ return { review: null }
40
+ }
41
+ const { review, snapshot } = state
42
+ const answer: WorkspaceReviewAnswer = { review: { id: review.id, document: review.document, running: review.running, mode: review.mode, files: review.changes.length, steps: review.steps.length }, snapshot }
43
+ if (!fits(answer)) throw new RequestError(413, 'workspace-review-response-too-large')
44
+ if (part === 'summary') return answer
45
+ if (part === 'diff') {
46
+ if (!query.path) throw new RequestError(400, 'workspace-review-query-invalid')
47
+ if (query.step && !review.steps.some(step => step.id === query.step)) throw new RequestError(404, 'workspace-review-step-not-found')
48
+ const change = await reviews.readDiff(snapshot, query.path, query.step)
49
+ if (!change) throw new RequestError(404, 'workspace-review-file-not-found')
50
+ if (change.diff === undefined) throw new RequestError(409, 'workspace-review-diff-unavailable')
51
+ const totalChars = change.diff.length
52
+ if (offset > totalChars) throw new RequestError(400, 'workspace-review-query-invalid')
53
+ answer.diff = { path: query.path, ...query.step ? { step: query.step } : {}, text: change.diff.slice(offset, offset + WORKSPACE_REVIEW_FRAGMENT_CHARS), offset, totalChars, sha256: createHash('sha256').update(change.diff).digest('hex') }
54
+ const cursor = () => { if (offset + answer.diff!.text.length < totalChars) answer.nextOffset = offset + answer.diff!.text.length; else delete answer.nextOffset }
55
+ cursor()
56
+ while (!fits(answer) && answer.diff.text.length) { answer.diff.text = answer.diff.text.slice(0, Math.floor(answer.diff.text.length / 2)); cursor() }
57
+ if (!fits(answer) || !answer.diff.text.length && offset < totalChars) throw new RequestError(413, 'workspace-review-response-too-large')
58
+ return answer
59
+ }
60
+ const rows = part === 'files' ? review.changes : review.steps.map(({ changes, ...step }) => ({ ...step, label: step.label.slice(0, 240), ...step.tool ? { tool: step.tool.slice(0, 100) } : {}, files: changes.length }))
61
+ if (offset > rows.length) throw new RequestError(400, 'workspace-review-query-invalid')
62
+ const selected: unknown[] = []
63
+ for (const row of rows.slice(offset, offset + 20)) {
64
+ if (!fits({ ...answer, [part]: [...selected, row], nextOffset: offset + selected.length + 1 })) break
65
+ selected.push(row)
66
+ }
67
+ if (!selected.length && offset < rows.length) throw new RequestError(413, 'workspace-review-response-too-large')
68
+ Object.assign(answer, { [part]: selected }, offset + selected.length < rows.length ? { nextOffset: offset + selected.length } : {})
69
+ return answer
70
+ },
71
+ async check(change, member) { await inspect(change, member); await reviews.check(change.snapshot) },
72
+ async change(change, member, signal) {
73
+ const state = await inspect(change, member)
74
+ signal?.throwIfAborted()
75
+ if (change.action === 'accept') {
76
+ const ended = await reviews.accept(state.review.document, { reject: change.reject, message: change.message, expected: change.snapshot }, signal)
77
+ return { outcome: ended.outcome === 'accepted' ? 'accepted' : 'empty', ...ended.revision ? { revision: ended.revision.id } : {}, files: ended.files.length }
78
+ }
79
+ if (change.action === 'reject') {
80
+ const result = await reviews.reject(state.review.document, { paths: change.paths, expected: change.snapshot }, signal)
81
+ return result.ended ? { outcome: 'rejected', files: result.ended.files.length } : { outcome: 'updated', remainingFiles: result.review?.changes.length ?? 0 }
82
+ }
83
+ const result = await reviews.restore(state.review.document, { step: change.step, expected: change.snapshot }, signal)
84
+ return { outcome: 'restored', remainingFiles: result.changes.length }
85
+ },
86
+ }
87
+ }
@@ -0,0 +1,54 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readlinkSync, realpathSync } from 'node:fs'
3
+ import { join } from 'node:path'
4
+ import type { DocumentFileChange } from '@lincyaw/kernel'
5
+ import { RequestError } from './errors.ts'
6
+ import { DOCUMENT_OPERATION_MAX_BACKUP_BYTES, DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES } from './writer.ts'
7
+
8
+ export interface RevisionFile {
9
+ path: string
10
+ mode: '000000' | '100644' | '100755' | '120000' | 'unsupported'
11
+ stamp: string
12
+ change?: DocumentFileChange
13
+ }
14
+ export const revisionDigest = (value: string | Uint8Array) => createHash('sha256').update(value).digest('hex')
15
+
16
+ /** Raw preimages are distinct from filtered Git blobs, particularly for CRLF files and symlinks. */
17
+ export function revisionFiles(root: string, paths: string[]): RevisionFile[] {
18
+ if (paths.length > DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES) throw new RequestError(413, 'changes-selection-too-large')
19
+ let total = 0
20
+ return paths.map(path => {
21
+ const parts = path.split('/')
22
+ if (!path || path.startsWith('/') || path.includes('\0') || parts.some(part => !part || part === '.' || part === '..' || part === '.git')) throw new RequestError(403, 'changes-path-forbidden')
23
+ if (path.includes('\\')) return { path, mode: 'unsupported', stamp: 'unsupported-name' }
24
+ let parent = root
25
+ for (const part of parts.slice(0, -1)) {
26
+ parent = join(parent, part)
27
+ const entry = lstatSync(parent, { throwIfNoEntry: false })
28
+ if (!entry) break
29
+ if (!entry.isDirectory() || realpathSync(parent) !== parent) return { path, mode: 'unsupported', stamp: 'unsafe-parent' }
30
+ }
31
+ const file = join(root, path), before = lstatSync(file, { throwIfNoEntry: false })
32
+ if (!before) return { path, mode: '000000', stamp: 'absent', change: { path, remove: true } }
33
+ if (before.isSymbolicLink()) {
34
+ const link = readlinkSync(file), after = lstatSync(file)
35
+ if (before.ino !== after.ino || before.dev !== after.dev || before.ctimeMs !== after.ctimeMs) throw new RequestError(409, 'changes-state-changed')
36
+ return { path, mode: '120000', stamp: revisionDigest('link:' + link), change: { path, link } }
37
+ }
38
+ if (!before.isFile()) return { path, mode: 'unsupported', stamp: `unsupported:${before.mode}` }
39
+ if ((total += before.size) > DOCUMENT_OPERATION_MAX_BACKUP_BYTES) throw new RequestError(413, 'changes-selection-too-large')
40
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
41
+ try {
42
+ const opened = fstatSync(fd)
43
+ if (!opened.isFile() || opened.ino !== before.ino || opened.dev !== before.dev || opened.size !== before.size) throw new RequestError(409, 'changes-state-changed')
44
+ const buffer = Buffer.alloc(opened.size + 1)
45
+ let length = 0, count = 0
46
+ while (length < buffer.length && (count = readSync(fd, buffer, length, buffer.length - length, null)) > 0) length += count
47
+ const bytes = buffer.subarray(0, length), after = fstatSync(fd), current = lstatSync(file)
48
+ if (length !== opened.size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs
49
+ || current.ino !== opened.ino || current.dev !== opened.dev || realpathSync(file) !== file) throw new RequestError(409, 'changes-state-changed')
50
+ const executable = (opened.mode & 0o111) !== 0
51
+ return { path, mode: executable ? '100755' : '100644', stamp: revisionDigest(bytes), change: { path, content: bytes, executable } }
52
+ } finally { closeSync(fd) }
53
+ })
54
+ }
@@ -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 } 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,8 @@ 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'
14
18
 
15
19
  const FIELD = '\x00'
16
20
  const RECORD = '\x1e'
@@ -177,6 +181,18 @@ export interface LockedCommit {
177
181
  trailers?: [string, string][]
178
182
  }
179
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
+
180
196
  export class Revisions implements RevisionService {
181
197
  readonly #git: Git
182
198
  readonly #files: RevisionFiles
@@ -186,19 +202,9 @@ export class Revisions implements RevisionService {
186
202
  this.#files = files
187
203
  }
188
204
 
189
- /** 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. */
190
206
  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
- })
207
+ return this.#git.exclusive(work)
202
208
  }
203
209
 
204
210
  commit(change: { files: string[], message: string, origin: CommitOrigin, trailers?: [string, string][] }): Promise<Revision | undefined> {
@@ -208,15 +214,174 @@ export class Revisions implements RevisionService {
208
214
 
209
215
  /** Commits the paths; the caller holds the git lock (`Git.exclusive`). */
210
216
  async commitWhileLocked(commit: LockedCommit): Promise<Revision | undefined> {
211
- const { summary, body, origin } = commit
212
217
  const unique = [...new Set(commit.paths.map(path => path.replace(/^\.?\/+|\/+$/g, '')).filter(path => path && !leavesRoot(path)))]
213
218
  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')
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' }
220
385
  }
221
386
 
222
387
  async status(paths: string[] = ['']): Promise<{ branch?: string, uncommitted: number }> {
@@ -228,10 +393,10 @@ export class Revisions implements RevisionService {
228
393
  const specs = paths.map(path => path || '.')
229
394
  const status = await this.#statusOf(paths)
230
395
  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' })
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' })
232
397
  if (numstat.ok) {
233
398
  for (const entry of numstat.output.split('\0').filter(Boolean)) {
234
- const [added = '-', removed = '-', path = ''] = entry.split('\t')
399
+ const [added = '-', removed = '-', ...named] = entry.split('\t'), path = named.join('\t')
235
400
  if (added !== '-') counts.set(this.#fromTop(path), [Number(added), Number(removed)])
236
401
  }
237
402
  }
@@ -244,14 +409,8 @@ export class Revisions implements RevisionService {
244
409
 
245
410
  discard(paths: string[]): Promise<void> {
246
411
  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)
412
+ const captured = await this.observeChanges(paths)
413
+ if (captured.raw.length) await this.#applyFrozen('discard', captured)
255
414
  })
256
415
  }
257
416
 
@@ -281,7 +440,7 @@ export class Revisions implements RevisionService {
281
440
  if (!(await this.#git.tryOutput(['merge-base', '--is-ancestor', id, 'HEAD'])).ok) throw new RequestError(404, 'history-revision-not-found')
282
441
  const topPath = relative(this.#git.top, resolve(this.#files.config.root, path)).split(sep).join('/')
283
442
  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')
443
+ const record = listed.split('\0')[0] ?? '', at = record.indexOf('\t'), meta = record.slice(0, at), named = record.slice(at + 1)
285
444
  const [mode, type, oid] = meta.split(' ')
286
445
  if (named !== topPath || !oid) throw new RequestError(404, 'history-file-not-found')
287
446
  if (type !== 'blob' || !['100644', '100755'].includes(mode!)) throw new RequestError(422, 'history-file-not-regular-text')
@@ -392,8 +551,6 @@ export class Revisions implements RevisionService {
392
551
  const { target, tree, changes } = planned
393
552
  const originalHead = await this.head()
394
553
  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
554
  try {
398
555
  await this.#write(changes)
399
556
  const subject = target.message.split('\n')[0] ?? target.id
@@ -406,8 +563,6 @@ export class Revisions implements RevisionService {
406
563
  const afterHead = await this.head()
407
564
  if (afterHead !== originalHead) throw new RequestError(409, 'history-readback-changed', { committed: true, snapshot: afterHead })
408
565
  await this.#write(restore)
409
- if (oldIndex) writeFileSync(indexPath, oldIndex)
410
- else rmSync(indexPath, { force: true })
411
566
  throw error
412
567
  }
413
568
  })
@@ -454,8 +609,8 @@ export class Revisions implements RevisionService {
454
609
  }
455
610
 
456
611
  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 []
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')
459
614
  return status.output.split('\0').filter(Boolean)
460
615
  .map(entry => ({ code: entry.slice(0, 2), path: this.#fromTop(entry.slice(3)) }))
461
616
  .filter(({ path }) => !isGeneratedPath(path))
@@ -502,29 +657,24 @@ export class Revisions implements RevisionService {
502
657
  }
503
658
 
504
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> {
505
665
  const { config, writer } = this.#files
506
666
  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 })
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`)
517
672
  }
518
673
  const inDocuments = changes.filter(({ dir }) => dir !== undefined)
519
674
  for (const dir of new Set(inDocuments.filter(({ change }) => !('remove' in change)).map(({ dir }) => dir!))) {
520
675
  if (!exists(join(config.root, dir))) makeDocumentDir(config.root, dir)
521
676
  }
522
677
  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
678
  if (outside.length > 0) writeChanges(config, outside, true)
529
679
  for (const dir of new Set(inDocuments.map(({ dir }) => dir!))) {
530
680
  if (!dir) continue
@@ -545,8 +695,15 @@ export class Revisions implements RevisionService {
545
695
  return entry && revision(entry)
546
696
  }
547
697
 
548
- #author(member: Member | undefined): string[] {
549
- return member ? [`--author=${memberAddress(member)}`] : []
698
+ /**
699
+ * The member a commit names as its author. The local author (the one person a local service serves) is the
700
+ * repository's configured git user when git has one, so that their saves are theirs; members of a shared service
701
+ * have their own name and email.
702
+ */
703
+ async #author(member: Member | undefined): Promise<Member | undefined> {
704
+ if (!member || member.email || member.id !== LOCAL_AUTHOR.id || member.name !== LOCAL_AUTHOR.name) return member
705
+ const [name, email] = await Promise.all([this.#git.tryOutput(['config', 'user.name']), this.#git.tryOutput(['config', 'user.email'])])
706
+ return name.ok && email.ok && name.output.trim() && email.output.trim() ? { ...member, name: name.output.trim(), email: email.output.trim() } : member
550
707
  }
551
708
 
552
709
  async #identity(): Promise<string[]> {
@@ -580,7 +737,11 @@ function writableByOthers(root: string, path: string): string | undefined {
580
737
 
581
738
  function lineCount(path: string): [number, number] | undefined {
582
739
  try {
583
- 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)
584
745
  if (bytes.includes(0)) return undefined
585
746
  const text = bytes.toString('utf8')
586
747
  return [text === '' ? 0 : text.split('\n').length - (text.endsWith('\n') ? 1 : 0), 0]