@lincyaw/workspace 1.0.0-rc.108 → 1.0.0-rc.109

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workspace",
3
- "version": "1.0.0-rc.108",
3
+ "version": "1.0.0-rc.109",
4
4
  "description": "Presmium's workspace service (presmium serve): documents, their history, reviews and the workspace site",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -34,13 +34,13 @@
34
34
  "mime-types": "3.0.2",
35
35
  "playwright-chromium": "1.64.1",
36
36
  "yaml": "^2.9.1",
37
- "@lincyaw/kernel": "1.0.0-rc.108",
38
- "@lincyaw/compiler": "1.0.0-rc.108",
39
- "@lincyaw/server": "1.0.0-rc.108",
40
- "@lincyaw/design": "1.0.0-rc.108"
37
+ "@lincyaw/compiler": "1.0.0-rc.109",
38
+ "@lincyaw/server": "1.0.0-rc.109",
39
+ "@lincyaw/design": "1.0.0-rc.109",
40
+ "@lincyaw/kernel": "1.0.0-rc.109"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/mime-types": "^3.0.1",
44
- "@lincyaw/mcp": "1.0.0-rc.108"
44
+ "@lincyaw/mcp": "1.0.0-rc.109"
45
45
  }
46
46
  }
@@ -66,6 +66,7 @@ export class DocumentOperations {
66
66
  release ??= claimed?.release
67
67
  }
68
68
  await prepared?.verify()
69
+ await this.#revisions.checkpoint(touched(operation))
69
70
  const head = await this.#revisions.head()
70
71
  const before = await this.#writer.checkpoint(touched(operation), operation.op === 'rename' ? { from: operation.dir, to: operation.to } : undefined, prepared?.changes?.map(change => change.path)).catch(error => {
71
72
  if (error instanceof DocumentCheckpointRefusal) throw new RequestError(error.status, error.message, error.detail)
package/src/node/git.ts CHANGED
@@ -13,11 +13,15 @@ export interface GitResult {
13
13
  export class Git {
14
14
  readonly root: string
15
15
  readonly top: string
16
+ readonly localHistory: boolean
17
+ readonly #environment: Record<string, string>
16
18
  #queue: Promise<unknown> = Promise.resolve()
17
19
 
18
- constructor(root: string) {
20
+ constructor(root: string, history?: { directory: string, top: string }) {
19
21
  this.root = root
20
- this.top = realpathSync(execFileSync('git', [...gitConfigArgs(), 'rev-parse', '--show-toplevel'], { cwd: root, encoding: 'utf8', env: gitEnvironment(process.env) }).trim())
22
+ this.localHistory = Boolean(history)
23
+ this.#environment = history ? { GIT_DIR: history.directory, GIT_WORK_TREE: history.top } : {}
24
+ this.top = history ? realpathSync(history.top) : realpathSync(execFileSync('git', [...gitConfigArgs(), 'rev-parse', '--show-toplevel'], { cwd: root, encoding: 'utf8', env: gitEnvironment(process.env) }).trim())
21
25
  }
22
26
 
23
27
  static isRepository(root: string): boolean {
@@ -48,7 +52,7 @@ export class Git {
48
52
  cwd: this.root,
49
53
  encoding: 'buffer',
50
54
  maxBuffer: 1 << 30,
51
- env: { ...gitEnvironment(process.env), ...env },
55
+ env: { ...gitEnvironment(process.env), ...this.#environment, ...env },
52
56
  }, (error, stdout, stderr) => {
53
57
  const code = inputError ? 1 : !error ? 0 : typeof error.code === 'number' ? error.code : 1
54
58
  done({ code, stdout, stderr: stderr.toString('utf8') + (inputError?.message ?? '') })
@@ -0,0 +1,70 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { createHash } from 'node:crypto'
3
+ import { existsSync, lstatSync } from 'node:fs'
4
+ import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises'
5
+ import { homedir } from 'node:os'
6
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path'
7
+ import { promisify } from 'node:util'
8
+ import { gitConfigArgs, gitEnvironment } from '@lincyaw/kernel'
9
+ import { Git } from './git.ts'
10
+ import { leavesRoot } from '../domain/paths.ts'
11
+
12
+ /** Editing history owns its index and refs; project commits remain an explicit author action. */
13
+ export async function openLocalHistory(root: string, env: NodeJS.ProcessEnv = process.env): Promise<Git> {
14
+ const base = join(env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'presmium', 'history')
15
+ const directory = join(base, createHash('sha256').update(root).digest('hex'))
16
+ if (existsSync(join(directory, 'HEAD'))) {
17
+ const top = (await readFile(join(directory, 'presmium-worktree'), 'utf8')).trim()
18
+ return new Git(root, { directory, top })
19
+ }
20
+ await mkdir(base, { recursive: true })
21
+ const temporary = await mkdtemp(join(base, '.prepare-'))
22
+ try {
23
+ const project = Git.isRepository(root) ? new Git(root) : undefined
24
+ const top = project?.top ?? root
25
+ await promisify(execFile)('git', [...gitConfigArgs(), 'init', '--bare', '--quiet', '--initial-branch=main', temporary], { env: gitEnvironment(env) })
26
+ const git = new Git(root, { directory: temporary, top })
27
+ await git.output(['config', 'core.bare', 'false'])
28
+ await git.output(['config', 'core.worktree', top])
29
+ await writeFile(join(temporary, 'presmium-worktree'), `${top}\n`)
30
+ let excluded = ''
31
+ if (project) {
32
+ const head = await project.run(['rev-parse', '--verify', '--quiet', 'HEAD'])
33
+ if (head.code === 0) {
34
+ const source = (await project.output(['rev-parse', '--absolute-git-dir'])).trim()
35
+ await git.output(['fetch', '--quiet', '--no-tags', source, 'HEAD'])
36
+ await git.output(['update-ref', 'refs/heads/main', (await git.output(['rev-parse', 'FETCH_HEAD'])).trim()])
37
+ await git.output(['read-tree', 'HEAD'])
38
+ }
39
+ for (const key of ['user.name', 'user.email', 'core.autocrlf', 'core.eol', 'core.safecrlf', 'core.filemode', 'core.symlinks', 'core.excludesfile']) {
40
+ const value = await project.tryOutput(['config', '--get', key])
41
+ if (value.ok) await git.output(['config', key, value.output.trimEnd()])
42
+ }
43
+ const exclude = (await project.output(['rev-parse', '--git-path', 'info/exclude'])).trim()
44
+ excluded = await readFile(resolve(root, exclude), 'utf8').catch(error => { if (error.code === 'ENOENT') return ''; throw error })
45
+ }
46
+ await writeFile(join(temporary, 'info', 'exclude'), `${excluded}\n.presmium/\nnode_modules/\ndist/\n.deltabox/\n.deltabox-lite-state/\n`)
47
+ // Capture existing files, including unsaved project changes, as a real baseline before the first edit.
48
+ await captureLocalBaseline(git, ['.'], true)
49
+ await rename(temporary, directory)
50
+ return new Git(root, { directory, top })
51
+ } finally { await rm(temporary, { recursive: true, force: true }) }
52
+ }
53
+
54
+ /** Caller owns the history queue. External edits become an explicit undo boundary before a new save. */
55
+ export async function captureLocalBaseline(git: Git, paths: string[], initial = false): Promise<void> {
56
+ if (paths.some(path => isAbsolute(path) || leavesRoot(relative(git.root, resolve(git.root, path)).split(sep).join('/')) || path.split(/[\\/]/).includes('.git'))) throw new Error('history-path-outside-workspace')
57
+ const literal = { GIT_LITERAL_PATHSPECS: '1' }
58
+ const tracked = new Set((await git.output(['ls-files', '-z', '--', ...paths], literal)).split('\0').filter(Boolean))
59
+ const excluded = await git.run(['check-ignore', '-z', '--stdin'], {}, Buffer.from(paths.map(path => `${path}\0`).join('')))
60
+ if (excluded.code !== 0 && excluded.code !== 1) throw new Error(excluded.stderr)
61
+ const ignored = new Set(excluded.stdout.toString('utf8').split('\0'))
62
+ const selected = paths.filter(path => !ignored.has(path) && (tracked.has(path) || lstatSync(join(git.root, path), { throwIfNoEntry: false })))
63
+ if (selected.length) await git.output(['add', '-A', '--', ...selected], { GIT_LITERAL_PATHSPECS: '1' })
64
+ const tree = (await git.output(['write-tree'])).trim()
65
+ const parent = await git.tryOutput(['rev-parse', '--verify', '--quiet', 'HEAD'])
66
+ if (!initial && parent.ok && tree === (await git.output(['rev-parse', 'HEAD^{tree}'])).trim()) return
67
+ const message = 'Synchronize local editing baseline\n\nPresmium-Baseline: true\n'
68
+ const commit = (await git.output(['-c', 'user.name=Presmium', '-c', 'user.email=history@presmium.invalid', 'commit-tree', tree, ...parent.ok ? ['-p', parent.output.trim()] : [], '-m', message])).trim()
69
+ await git.output(['update-ref', 'refs/heads/main', commit, parent.ok ? parent.output.trim() : '0'.repeat(commit.length)])
70
+ }
@@ -43,6 +43,8 @@ interface OpenReview {
43
43
  turns: { from: number, to: number }
44
44
  running: boolean
45
45
  opened: string
46
+ backend?: 'deltabox'
47
+ awaitingDeltabox?: boolean
46
48
  workspace?: AgentWorkspace
47
49
  timer?: ReturnType<typeof setTimeout>
48
50
  }
@@ -115,10 +117,11 @@ export class AgentSessionReviews {
115
117
  const workspace = pending.workspace ? AgentWorkspace.resume(config, pending.workspace) : undefined
116
118
  const root = workspace?.root ?? config.root
117
119
  const review = await resumeGitReview(pending, { workspaceRoot: root, files: { write: async changes => writeChanges({ ...config, root }, changes, true) }, onRestore: paths => log.warn(`session ${session.session}: the agent changed the git directory, put back: ${paths.join(', ')}`) })
118
- if ((await review.diff()).length === 0) { await review.close(); workspace?.dispose(); return }
120
+ const empty = (await review.diff()).length === 0
121
+ if (empty && session.backend !== 'deltabox') { await review.close(); workspace?.dispose(); return }
119
122
  if (!workspace) { review.suspend(); throw new Error('A legacy review needs to be accepted or rejected with the version that created it before concurrent editing can start.') }
120
123
  this.#workspaces.set(session.session, workspace)
121
- const open: OpenReview = { review, document: session.document, session: session.session, member: session.member, turns: session.turns, running: false, opened: session.opened, workspace }
124
+ const open: OpenReview = { review, document: session.document, session: session.session, member: session.member, turns: session.turns, running: session.backend === 'deltabox', opened: session.opened, workspace, backend: session.backend, awaitingDeltabox: session.backend === 'deltabox' }
122
125
  this.#open = open
123
126
  log.info(`the review of session ${session.session} in ${session.document || '.'} (turns ${session.turns.from}-${session.turns.to}) waits for its author again`)
124
127
  this.#scheduleRollback(open)
@@ -133,10 +136,27 @@ export class AgentSessionReviews {
133
136
  })
134
137
  }
135
138
 
136
- refreshWorkspace(session: string): Promise<void> {
139
+ refreshWorkspace(session: string): Promise<boolean> {
137
140
  return this.#serial(async () => {
138
141
  const workspace = this.#workspaces.get(session)
139
- if (workspace && this.#open?.session !== session) await workspace.refresh()
142
+ return workspace && this.#open?.session !== session ? workspace.refresh() : false
143
+ })
144
+ }
145
+
146
+ /** The DSH adapter has adopted and staged any orphaned native review before this is called. */
147
+ resumeWorkspace(session: string): Promise<void> {
148
+ return this.#serial(async () => {
149
+ const open = this.#open
150
+ if (!open || open.session !== session || !open.awaitingDeltabox) return
151
+ open.awaitingDeltabox = false
152
+ open.running = false
153
+ if ((await open.review.diff()).length === 0) {
154
+ await open.review.close()
155
+ await this.#end(open, { outcome: 'empty', files: [] })
156
+ } else {
157
+ await this.#publish(open)
158
+ this.#scheduleRollback(open)
159
+ }
140
160
  })
141
161
  }
142
162
 
@@ -227,7 +247,7 @@ export class AgentSessionReviews {
227
247
  }, { signal })
228
248
  }
229
249
 
230
- open(document: string, body: { session: string, turn?: number }, member: Member): Promise<ReviewSnapshot> {
250
+ open(document: string, body: { session: string, turn?: number, backend?: 'deltabox' }, member: Member): Promise<ReviewSnapshot> {
231
251
  return this.#serial(async () => {
232
252
  if (this.#closed) throw new RequestError(503, 'the workspace service is closing')
233
253
  let open = this.#open
@@ -249,9 +269,9 @@ export class AgentSessionReviews {
249
269
  files: { write: async changes => writeChanges({ ...config, root }, changes, true) },
250
270
  onRestore: paths => log.warn(`session ${body.session}: the agent changed the git directory, put back: ${paths.join(', ')}`),
251
271
  warn: message => log.warn(`session ${body.session}: ${message}`),
252
- session: { session: body.session, document, member, turns: { from: turn, to: turn }, opened },
272
+ session: { session: body.session, document, member, turns: { from: turn, to: turn }, opened, backend: body.backend },
253
273
  })
254
- open = { review, document, session: body.session, member, turns: { from: turn, to: turn }, running: true, opened, workspace }
274
+ open = { review, document, session: body.session, member, turns: { from: turn, to: turn }, running: true, opened, workspace, backend: body.backend }
255
275
  } catch (error) {
256
276
  throw new RequestError(409, `the review of ${document || '.'} did not open: ${errorMessage(error)}`)
257
277
  }
@@ -305,6 +325,7 @@ export class AgentSessionReviews {
305
325
  accept(document: string, body: { reject?: string[], message?: string, expected?: string }, signal?: AbortSignal): Promise<ReviewEnd> {
306
326
  return this.#serial(async () => {
307
327
  const open = this.#requireOpen(document, body.expected)
328
+ if (open.awaitingDeltabox) throw new RequestError(409, 'workspace-review-running')
308
329
  await this.#expected(open, body.expected, signal)
309
330
  try { return await this.#accept(open, body.reject ?? [], body.message, signal, body.expected) }
310
331
  catch (error) {
@@ -341,6 +362,7 @@ export class AgentSessionReviews {
341
362
  catch { throw new RequestError(409, 'workspace-review-changed') }
342
363
  signal?.throwIfAborted()
343
364
  const prepared = open.workspace!.prepare(files, material)
365
+ await this.#options.revisions.checkpoint(files)
344
366
  try {
345
367
  open.workspace!.write(prepared.changes)
346
368
  return await this.#options.revisions.commitWhileLocked({ paths: files, summary: message?.trim() || commitSummary(files, lang), body: steps.join('\n'), origin: { kind: 'agent', task: open.review.task, member: open.member }, trailers: [[AGENT_SESSION_TRAILER, open.session], [TURN_TRAILER, `${open.turns.from}-${open.turns.to}`]] })
@@ -357,6 +379,7 @@ export class AgentSessionReviews {
357
379
  reject(document: string, body: { paths?: string[], expected?: string }, signal?: AbortSignal): Promise<ReviewUpdate> {
358
380
  return this.#serial(async () => {
359
381
  const open = this.#requireOpen(document, body.expected)
382
+ if (open.awaitingDeltabox) throw new RequestError(409, 'workspace-review-running')
360
383
  await this.#expected(open, body.expected, signal)
361
384
  if (body.paths) {
362
385
  await open.review.restoreFiles(body.paths)
@@ -373,6 +396,7 @@ export class AgentSessionReviews {
373
396
  restore(document: string, body: { step: string, expected?: string }, signal?: AbortSignal): Promise<ReviewSnapshot> {
374
397
  return this.#serial(async () => {
375
398
  const open = this.#requireOpen(document, body.expected)
399
+ if (open.awaitingDeltabox) throw new RequestError(409, 'workspace-review-running')
376
400
  await this.#expected(open, body.expected, signal)
377
401
  try {
378
402
  await open.review.restoreTo!(body.step)
@@ -422,7 +446,7 @@ export class AgentSessionReviews {
422
446
  #noteTurn(open: OpenReview, turn: number | undefined): void {
423
447
  if (turn === undefined || !Number.isInteger(turn) || turn < 0) return
424
448
  open.turns = { from: open.turns.from === 0 ? turn : Math.min(open.turns.from, turn), to: Math.max(open.turns.to, turn) }
425
- open.review.noteSession({ session: open.session, document: open.document, member: open.member, turns: open.turns, opened: open.opened })
449
+ open.review.noteSession({ session: open.session, document: open.document, member: open.member, turns: open.turns, opened: open.opened, backend: open.backend })
426
450
  }
427
451
 
428
452
  async #publish(open: OpenReview): Promise<ReviewSnapshot> {
@@ -8,6 +8,8 @@ import type { WorkspaceConfig } from '../config.ts'
8
8
  import { RequestError } from '../errors.ts'
9
9
  import { validateDocumentSource, versionOf } from '../source-editor.ts'
10
10
  import { writeChanges } from '../writer.ts'
11
+ import { openLocalHistory } from '../local-history.ts'
12
+ import { Git } from '../git.ts'
11
13
 
12
14
  interface FileStamp { version: string, executable?: boolean, link?: true }
13
15
  export interface AgentWorkspaceRecord { root: string, original: string, base: Record<string, FileStamp> }
@@ -48,6 +50,7 @@ export class AgentWorkspace {
48
50
  await mkdir(root)
49
51
  const workspace = new AgentWorkspace(config, { root, original: config.root, base: {} })
50
52
  await git(root, ['init', '-q'])
53
+ await writeFile(join(root, '.git', 'info', 'exclude'), '.presmium/\nnode_modules/\ndist/\n.deltabox/\n.deltabox-lite-state/\n')
51
54
  await workspace.refresh()
52
55
  return workspace
53
56
  }
@@ -57,13 +60,16 @@ export class AgentWorkspace {
57
60
  return new AgentWorkspace(config, record)
58
61
  }
59
62
 
60
- async refresh(): Promise<void> {
61
- const paths = (await git(this.#config.root, ['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--', '.'])).split('\0').filter(path => path && !path.startsWith('.presmium/agent-workspaces/'))
63
+ async refresh(): Promise<boolean> {
64
+ const listing = ['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--', '.']
65
+ const listed = Git.isRepository(this.#config.root) ? await git(this.#config.root, listing) : await (await openLocalHistory(this.#config.root)).output(listing)
66
+ const paths = listed.split('\0').filter(path => path && !path.startsWith('.presmium/agent-workspaces/'))
62
67
  const next: Record<string, FileStamp> = {}
63
68
  for (const path of new Set(paths)) {
64
69
  const current = await sourceStamp(join(this.#config.root, path))
65
70
  if (!current) continue
66
71
  next[path] = current
72
+ if (same(current, this.record.base[path])) continue
67
73
  const target = join(this.root, path)
68
74
  if (same(await sourceStamp(target), current)) continue
69
75
  await mkdir(dirname(target), { recursive: true })
@@ -72,6 +78,7 @@ export class AgentWorkspace {
72
78
  if (!same(await sourceStamp(join(this.#config.root, path)), current)) throw new RequestError(409, 'agent-source-changed', { paths: [path], next: 'The author changed a file while the candidate was refreshed. Read the current author files and retry.' })
73
79
  }
74
80
  for (const path of Object.keys(this.record.base)) if (!next[path]) await rm(join(this.root, path), { force: true, recursive: true })
81
+ const changed = JSON.stringify(next) !== JSON.stringify(this.record.base)
75
82
  this.record.base = next
76
83
  const dependencyDirs = new Set(['', ...paths.filter(path => path.endsWith('package.json')).map(dirname)])
77
84
  for (const dir of dependencyDirs) {
@@ -80,8 +87,11 @@ export class AgentWorkspace {
80
87
  const target = join(this.root, dir, 'node_modules')
81
88
  if (existsSync(join(source, 'node_modules')) && !existsSync(target) && existsSync(dirname(target))) await symlink(join(source, 'node_modules'), target, 'dir')
82
89
  }
83
- await git(this.root, ['add', '-A'])
84
- await git(this.root, ['-c', 'user.name=Presmium', '-c', 'user.email=presmium@localhost', 'commit', '-q', '--allow-empty', '-m', 'Author workspace snapshot'])
90
+ if (changed || !(await git(this.root, ['rev-parse', '--verify', 'HEAD']).catch(() => '')).trim()) {
91
+ await git(this.root, ['add', '-A'])
92
+ await git(this.root, ['-c', 'user.name=Presmium', '-c', 'user.email=presmium@localhost', 'commit', '-q', '--allow-empty', '-m', 'Author workspace snapshot'])
93
+ }
94
+ return changed
85
95
  }
86
96
 
87
97
  /** Caller holds the original workspace's mutation lock and history transaction. */
@@ -13,6 +13,7 @@ export interface AgentSessionRecord {
13
13
  member: Member
14
14
  turns: { from: number, to: number }
15
15
  opened: string
16
+ backend?: 'deltabox'
16
17
  checkpoints: string[]
17
18
  steps: ReviewStep[]
18
19
  }
@@ -22,8 +22,9 @@ export function reviewRoutes(reviews: AgentSessionReviews): Record<string, Route
22
22
  const session = toText(body.session, 200)
23
23
  if (!session) return problemResponse(400, '{ session }')
24
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))
25
+ if (body.resumed === true) await reviews.resumeWorkspace(session)
26
+ const changed = body.refresh === true ? await reviews.refreshWorkspace(session) : false
27
+ return jsonResponse({ ...await reviews.workspace(session), changed })
27
28
  }),
28
29
  'review': {
29
30
  role: 'editor',
@@ -46,7 +47,7 @@ export function reviewRoutes(reviews: AgentSessionReviews): Record<string, Route
46
47
  const session = toText(body.session, 200)
47
48
  if (!session) return problemResponse(400, '{ session, turn? }')
48
49
  const turn = toTurn(body.turn)
49
- return jsonResponse({ review: await reviews.open(ctx.document, { session, ...turn !== undefined ? { turn } : {} }, ctx.member) })
50
+ return jsonResponse({ review: await reviews.open(ctx.document, { session, ...turn !== undefined ? { turn } : {}, ...body.backend === 'deltabox' ? { backend: 'deltabox' as const } : {} }, ctx.member) })
50
51
  }),
51
52
  },
52
53
  'review/step': post(async (body, document) => {
@@ -15,6 +15,7 @@ import { documentDirOf, isGeneratedPath, makeDocumentDir, writeChanges } from '.
15
15
  import type { DocumentWriter } from './writer.ts'
16
16
  import { revisionDigest, revisionFiles } from './revision-files.ts'
17
17
  import type { RevisionFile } from './revision-files.ts'
18
+ import { captureLocalBaseline } from './local-history.ts'
18
19
 
19
20
  const FIELD = '\x00'
20
21
  const RECORD = '\x1e'
@@ -90,9 +91,9 @@ function undoTargets(entries: LogEntry[]): UndoTargets {
90
91
  if (at >= 0) stack.splice(at, 1)
91
92
  }
92
93
  for (const entry of [...entries].reverse()) {
94
+ if (entry.root) { done.length = 0; undone.length = 0; continue }
93
95
  const origin = originOf(entry.message)
94
96
  if (!origin) continue
95
- if (entry.root) { done.length = 0; undone.length = 0; continue }
96
97
  if (origin.operation) {
97
98
  done.length = 0
98
99
  undone.length = 0
@@ -207,6 +208,11 @@ export class Revisions implements RevisionService {
207
208
  return this.#git.exclusive(work)
208
209
  }
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)
214
+ }
215
+
210
216
  commit(change: { files: string[], message: string, origin: CommitOrigin, trailers?: [string, string][] }): Promise<Revision | undefined> {
211
217
  const [summary = '', ...body] = change.message.trim().split('\n')
212
218
  return this.transaction(() => this.commitWhileLocked({ paths: change.files, summary, body: body.join('\n'), origin: change.origin, ...change.trailers ? { trailers: change.trailers } : {} }))
@@ -595,7 +601,7 @@ export class Revisions implements RevisionService {
595
601
  const entries = log.ok ? parseLog(log.output).map(entry => ({ ...entry, files: entry.files.map(this.#fromTop) })) : []
596
602
  if (entries.length) {
597
603
  const rootIds = new Set((await this.#git.output(['rev-list', '--max-parents=0', 'HEAD'])).trim().split('\n'))
598
- for (const entry of entries) if (rootIds.has(entry.id)) entry.root = true
604
+ for (const entry of entries) if (rootIds.has(entry.id) || /^Presmium-Baseline: true$/m.test(entry.message)) entry.root = true
599
605
  }
600
606
  if (document === undefined) return entries
601
607
  const candidates = entries.flatMap((entry, index) => entry.files.filter(path => !leavesRoot(path) && (document === '' || path.startsWith(document + '/'))).map(path => ({ index, path, id: entry.id })))
@@ -44,6 +44,7 @@ export interface WorkspaceRoutesOptions {
44
44
  documentEditor: DocumentEditor
45
45
  locks: DocumentLocks
46
46
  revisions?: Revisions
47
+ projectRevisions?: Revisions
47
48
  operations?: DocumentOperations
48
49
  reviews?: AgentSessionReviews
49
50
  documentsChanged(change: DocumentsChange): Promise<void> | void
@@ -119,7 +120,7 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
119
120
  role: 'reader',
120
121
  handle: (request, ctx) => catchRequestErrors(async () => {
121
122
  if (request.method === 'GET') {
122
- const status = revisions ? await revisions.status(editor.roots(scopeOf(ctx))) : {}
123
+ const status = options.projectRevisions ? await options.projectRevisions.status(editor.roots(scopeOf(ctx))) : {}
123
124
  return jsonResponse({ title: config.title, documents: documentSummaries(config), templates: listTemplates(config), git: Boolean(revisions), ...status, single: config.singleDeck } satisfies DocumentsAnswer)
124
125
  }
125
126
  if (request.method !== 'POST') return problemResponse(405, 'GET or POST')
package/src/node/serve.ts CHANGED
@@ -27,6 +27,7 @@ import { DocumentOperations, documentsDiff } from './document-operations.ts'
27
27
  import type { DocumentsChange } from './document-operations.ts'
28
28
  import { RequestError } from './errors.ts'
29
29
  import { Git } from './git.ts'
30
+ import { captureLocalBaseline, openLocalHistory } from './local-history.ts'
30
31
  import { createJobs, OUTPUTS_PATH } from './jobs.ts'
31
32
  import { DocumentLocks } from './locks.ts'
32
33
  import { AgentSessionReviews } from './review/agent-session-reviews.ts'
@@ -77,10 +78,11 @@ export interface WorkspaceServer {
77
78
  close(): Promise<void>
78
79
  }
79
80
 
80
- /** What the workspace keeps when it is a git repository: its revisions, the document operations and the reviews. */
81
+ /** Local editing history and the separate project version-control boundary. */
81
82
  interface WorkspaceHistory {
82
83
  git: Git
83
84
  revisions: Revisions
85
+ projectRevisions?: Revisions
84
86
  operations: DocumentOperations
85
87
  agentSessionReviews: AgentSessionReviews
86
88
  taskReviews: ChangeReviewService
@@ -141,7 +143,8 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
141
143
  const config = readWorkspaceConfig(options.dir)
142
144
  if (env.PRESMIUM_AGENT_CANDIDATE === '1') config.settings['presmium.assistant'] = { ...config.settings['presmium.assistant'], review: 'auto' }
143
145
  const { root } = config
144
- await Git.initialize(root).catch(error => log.warn(`the workspace history could not be prepared: ${errorMessage(error)}`))
146
+ const historyGit = await openLocalHistory(root, env)
147
+ await historyGit.exclusive(() => captureLocalBaseline(historyGit, ['.']))
145
148
  const operatorDirectory = resolveOperatorDir(root, options.operatorDir ?? env.PRESMIUM_OPERATOR_DIR)
146
149
  const speechSettings = new OperatorSpeechSettings(operatorDirectory, name => env[name])
147
150
  const stateDir = makeStateDir(root, env)
@@ -150,7 +153,7 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
150
153
  const agentToolListeners = new Set<(document: string) => void>()
151
154
  const locks = new DocumentLocks()
152
155
  const writer = localWriter(config)
153
- const editor = new SourceEditor({ config, writer, locks })
156
+ const editor = new SourceEditor({ config, writer, locks, beforeWrite: (paths, historyLocked) => historyLocked ? captureLocalBaseline(historyGit, paths) : historyGit.exclusive(() => captureLocalBaseline(historyGit, paths)) })
154
157
  const check = options.check ?? (compilation => compilation.check())
155
158
  const launcherToken = env.PRESMIUM_SERVICE_TOKEN || randomBytes(32).toString('hex')
156
159
  const preview = { origins: options.previewOrigins ?? [] }
@@ -304,14 +307,11 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
304
307
  }
305
308
 
306
309
  const openHistory = (): WorkspaceHistory | undefined => {
307
- if (!Git.isRepository(root)) {
308
- log.warn(`${root} is not a git repository: editing, the document operations and the history are not available (run git init)`)
309
- return undefined
310
- }
311
- const git = new Git(root)
310
+ const git = historyGit
312
311
  const revisions = new Revisions(git, { config, writer })
313
312
  return {
314
313
  revisions,
314
+ ...Git.isRepository(root) ? { projectRevisions: new Revisions(new Git(root), { config, writer }) } : {},
315
315
  operations: new DocumentOperations({ config, git, revisions, writer, changed: documentsChanged, locks }),
316
316
  git,
317
317
  agentSessionReviews: new AgentSessionReviews({ config, revisions, locks, files: writer, log, flush: (documents, member) => authoringClients?.flush(documents, member) ?? Promise.resolve() }),
@@ -463,7 +463,7 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
463
463
  })
464
464
  workbench = createWorkbenchBackend({ root, compileSessionOf, serverHost, voices: voiceAuthoring.service, diagnostics: running.diagnostics, url: () => options.publicUrl ? new URL(options.publicUrl).origin : running.url, basePath, preview, log, warmSite: dir => site?.warm(dir) ?? Promise.resolve(), viewerPage: (dir, wait) => site?.app(dir, wait) ?? Promise.resolve(undefined) })
465
465
  history = openHistory()
466
- workspaceChanges = createWorkspaceChanges({ config, editor, locks, revisions: history?.revisions, changed: documentsChanged })
466
+ workspaceChanges = createWorkspaceChanges({ config, editor, locks, revisions: history?.projectRevisions, changed: documentsChanged })
467
467
  workspaceSource = createWorkspaceSource({ config, editor, revisions: history?.revisions })
468
468
  workspaceReview = history && createWorkspaceReview(history.agentSessionReviews)
469
469
  documentEditor = createDocumentEditor({ productionPlan: async (document, source) => { const audio = (await authoringServices(document, source)).audio; if (!audio) throw new RequestError(503, 'caption-production-unavailable'); return audio.readPlan({ source }) }, editor, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
@@ -483,6 +483,7 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
483
483
  mcpSettings: mcpSettings.route,
484
484
  speechSettings: speechSettingsRoute(speechSettings),
485
485
  changesRoutes: workspaceChanges.routes,
486
+ projectRevisions: history?.projectRevisions,
486
487
  config,
487
488
  editor,
488
489
  documentEditor,
@@ -40,6 +40,7 @@ export interface SourceEditorOptions {
40
40
  config: WorkspaceConfig
41
41
  writer: DocumentWriter
42
42
  locks?: DocumentLocks
43
+ beforeWrite?(paths: string[], historyLocked: boolean): Promise<void>
43
44
  }
44
45
 
45
46
  interface Scope {
@@ -60,11 +61,13 @@ export class SourceEditor {
60
61
  readonly #config: WorkspaceConfig
61
62
  readonly #writer: DocumentWriter
62
63
  readonly #locks?: DocumentLocks
64
+ readonly #beforeWrite?: SourceEditorOptions['beforeWrite']
63
65
 
64
66
  constructor(options: SourceEditorOptions) {
65
67
  this.#config = options.config
66
68
  this.#writer = options.writer
67
69
  this.#locks = options.locks
70
+ this.#beforeWrite = options.beforeWrite
68
71
  }
69
72
 
70
73
  scope(document: string): Scope {
@@ -277,6 +280,7 @@ export class SourceEditor {
277
280
  const created: string[] = []
278
281
  const edited = snapshots.filter(snapshot => snapshot.before && !snapshot.written.equals(snapshot.before))
279
282
  const touched = snapshots.filter(snapshot => !snapshot.before || !snapshot.written.equals(snapshot.before)).map(snapshot => snapshot.path)
283
+ if (touched.length) await this.#beforeWrite?.(touched, Boolean(history))
280
284
  const lang = history && touched.length && document ? readDocumentSummary(this.#config, document).lang : undefined
281
285
  const write = async (next: DocumentFileChange[]) => document ? await this.#writer.write(next) : writeChanges(this.#config, next, true)
282
286
  try {
@@ -330,6 +334,7 @@ export class SourceEditor {
330
334
  const change: DocumentFileChange = { path, content: written, ...(lstatSync(join(this.#config.root, path)).mode & 0o111) !== 0 ? { executable: true } : {} }
331
335
  const lang = commit && !written.equals(bytes) && document ? readDocumentSummary(this.#config, document).lang : undefined
332
336
  const write = async (next: DocumentFileChange) => (outside ? writeChanges(this.#config, [next], true) : await this.#writer.write([next]))
337
+ if (!written.equals(bytes)) await this.#beforeWrite?.([path], false)
333
338
  await write(change)
334
339
  let revision: Revision | undefined
335
340
  if (commit && !written.equals(bytes)) {