@lincyaw/workspace 1.0.0-rc.136 → 1.0.0-rc.139
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.
|
|
3
|
+
"version": "1.0.0-rc.139",
|
|
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": {
|
|
@@ -30,18 +30,20 @@
|
|
|
30
30
|
"templates"
|
|
31
31
|
],
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"
|
|
33
|
+
"@yarnpkg/nm": "4.1.2",
|
|
34
|
+
"cmd-shim": "9.0.2",
|
|
34
35
|
"image-size": "2.0.4",
|
|
36
|
+
"jszip": "^3.10.2",
|
|
35
37
|
"mime-types": "3.0.2",
|
|
36
38
|
"playwright-chromium": "1.64.1",
|
|
37
39
|
"yaml": "^2.9.1",
|
|
38
|
-
"@lincyaw/compiler": "1.0.0-rc.
|
|
39
|
-
"@lincyaw/
|
|
40
|
-
"@lincyaw/
|
|
41
|
-
"@lincyaw/design": "1.0.0-rc.
|
|
40
|
+
"@lincyaw/compiler": "1.0.0-rc.139",
|
|
41
|
+
"@lincyaw/server": "1.0.0-rc.139",
|
|
42
|
+
"@lincyaw/kernel": "1.0.0-rc.139",
|
|
43
|
+
"@lincyaw/design": "1.0.0-rc.139"
|
|
42
44
|
},
|
|
43
45
|
"devDependencies": {
|
|
44
46
|
"@types/mime-types": "^3.0.1",
|
|
45
|
-
"@lincyaw/mcp": "1.0.0-rc.
|
|
47
|
+
"@lincyaw/mcp": "1.0.0-rc.139"
|
|
46
48
|
}
|
|
47
49
|
}
|
|
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from 'node:crypto'
|
|
|
2
2
|
import { existsSync } from 'node:fs'
|
|
3
3
|
import { join } from 'node:path'
|
|
4
4
|
import { errorMessage, pushStream } from '@lincyaw/kernel'
|
|
5
|
+
import { acquireCandidateLease } from '@lincyaw/kernel/node'
|
|
5
6
|
import type { DocumentFiles, Logger, Member, ReviewChange, ReviewEnd, ReviewSnapshot, ReviewUpdate } from '@lincyaw/kernel'
|
|
6
7
|
import { trailers } from '../../domain/commit-message.ts'
|
|
7
8
|
import type { WorkspaceConfig } from '../config.ts'
|
|
@@ -100,7 +101,7 @@ export class AgentSessionReviews {
|
|
|
100
101
|
try {
|
|
101
102
|
const pending = pendingAgentSessionReview(scopeDir)
|
|
102
103
|
if (pending?.session) {
|
|
103
|
-
await this.#serial(() => this.#resume(pending))
|
|
104
|
+
await this.#serial(() => this.#resume(pending), () => pending.workspace ? [pending.workspace.root] : [])
|
|
104
105
|
continue
|
|
105
106
|
}
|
|
106
107
|
await rollBackLeftTaskReview(this.#options, document)
|
|
@@ -116,7 +117,7 @@ export class AgentSessionReviews {
|
|
|
116
117
|
const session = pending.session!
|
|
117
118
|
const workspace = pending.workspace ? AgentWorkspace.resume(config, pending.workspace) : undefined
|
|
118
119
|
const root = workspace?.root ?? config.root
|
|
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(', ')}`) })
|
|
120
|
+
const review = await resumeGitReview(pending, { workspaceRoot: root, files: { write: async changes => workspace ? workspace.writeCandidate(changes) : writeChanges({ ...config, root }, changes, true) }, onRestore: paths => { workspace?.changed(); log.warn(`session ${session.session}: the agent changed the git directory, put back: ${paths.join(', ')}`) } })
|
|
120
121
|
const empty = (await review.diff()).length === 0
|
|
121
122
|
if (empty && session.backend !== 'deltabox') { await review.close(); workspace?.dispose(); return }
|
|
122
123
|
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.') }
|
|
@@ -127,20 +128,20 @@ export class AgentSessionReviews {
|
|
|
127
128
|
this.#scheduleRollback(open)
|
|
128
129
|
}
|
|
129
130
|
|
|
130
|
-
workspace(session: string): Promise<{ root: string }> {
|
|
131
|
+
workspace(session: string): Promise<{ root: string, version: string }> {
|
|
131
132
|
return this.#serial(async () => {
|
|
132
133
|
this.#retired.delete(session)
|
|
133
134
|
let workspace = this.#workspaces.get(session)
|
|
134
135
|
if (!workspace) { workspace = await AgentWorkspace.create(this.#options.config); this.#workspaces.set(session, workspace) }
|
|
135
|
-
return { root: workspace.root }
|
|
136
|
-
})
|
|
136
|
+
return { root: workspace.root, version: workspace.version }
|
|
137
|
+
}, false)
|
|
137
138
|
}
|
|
138
139
|
|
|
139
140
|
refreshWorkspace(session: string): Promise<boolean> {
|
|
140
141
|
return this.#serial(async () => {
|
|
141
142
|
const workspace = this.#workspaces.get(session)
|
|
142
143
|
return workspace && this.#open?.session !== session ? workspace.refresh() : false
|
|
143
|
-
})
|
|
144
|
+
}, () => this.#workspaces.has(session) ? [this.#workspaces.get(session)!.root] : [])
|
|
144
145
|
}
|
|
145
146
|
|
|
146
147
|
/** The DSH adapter has adopted and staged any orphaned native review before this is called. */
|
|
@@ -166,7 +167,7 @@ export class AgentSessionReviews {
|
|
|
166
167
|
const workspace = this.#workspaces.get(session)
|
|
167
168
|
this.#workspaces.delete(session)
|
|
168
169
|
workspace?.dispose()
|
|
169
|
-
})
|
|
170
|
+
}, () => this.#workspaces.has(session) ? [this.#workspaces.get(session)!.root] : [])
|
|
170
171
|
}
|
|
171
172
|
|
|
172
173
|
snapshot(): Promise<ReviewSnapshot | undefined> {
|
|
@@ -266,8 +267,8 @@ export class AgentSessionReviews {
|
|
|
266
267
|
recordRoot: config.root,
|
|
267
268
|
workspace: workspace.record,
|
|
268
269
|
task: randomUUID(),
|
|
269
|
-
files: { write: async changes =>
|
|
270
|
-
onRestore: paths => log.warn(`session ${body.session}: the agent changed the git directory, put back: ${paths.join(', ')}`),
|
|
270
|
+
files: { write: async changes => workspace!.writeCandidate(changes) },
|
|
271
|
+
onRestore: paths => { workspace!.changed(); log.warn(`session ${body.session}: the agent changed the git directory, put back: ${paths.join(', ')}`) },
|
|
271
272
|
warn: message => log.warn(`session ${body.session}: ${message}`),
|
|
272
273
|
session: { session: body.session, document, member, turns: { from: turn, to: turn }, opened, backend: body.backend },
|
|
273
274
|
})
|
|
@@ -281,7 +282,7 @@ export class AgentSessionReviews {
|
|
|
281
282
|
open.running = true
|
|
282
283
|
this.#rescheduleRollback()
|
|
283
284
|
return await this.#publish(open)
|
|
284
|
-
})
|
|
285
|
+
}, () => this.#workspaces.has(body.session) ? [this.#workspaces.get(body.session)!.root] : [])
|
|
285
286
|
}
|
|
286
287
|
|
|
287
288
|
step(document: string, body: { session: string, turn?: number, label?: string, tool?: string, end?: boolean }): Promise<ReviewSnapshot | undefined> {
|
|
@@ -497,8 +498,19 @@ export class AgentSessionReviews {
|
|
|
497
498
|
open.timer.unref?.()
|
|
498
499
|
}
|
|
499
500
|
|
|
500
|
-
#serial<T>(work: () => Promise<T
|
|
501
|
-
const
|
|
501
|
+
#serial<T>(work: () => Promise<T>, roots: false | (() => string[]) = () => this.#open?.workspace ? [this.#open.workspace.root] : []): Promise<T> {
|
|
502
|
+
const guarded = async () => {
|
|
503
|
+
const releases: (() => Promise<void>)[] = []
|
|
504
|
+
try {
|
|
505
|
+
if (roots && process.platform === 'darwin') {
|
|
506
|
+
for (const root of roots().sort()) releases.push(await acquireCandidateLease(root))
|
|
507
|
+
}
|
|
508
|
+
return await work()
|
|
509
|
+
} finally {
|
|
510
|
+
for (const release of releases.reverse()) await release()
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
const next = this.#queue.then(guarded, guarded)
|
|
502
514
|
this.#queue = next.catch(() => undefined)
|
|
503
515
|
return next
|
|
504
516
|
}
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { execFile } from 'node:child_process'
|
|
2
|
-
import {
|
|
2
|
+
import { randomUUID } from 'node:crypto'
|
|
3
|
+
import { WindowsDependencies } from './windows-dependencies.ts'
|
|
4
|
+
import { existsSync, lstatSync, readFileSync, readlinkSync, realpathSync, rmSync } from 'node:fs'
|
|
3
5
|
import { cp, lstat, mkdir, mkdtemp, readFile, readlink, rm, symlink, writeFile } from 'node:fs/promises'
|
|
4
6
|
import { dirname, join, resolve } from 'node:path'
|
|
5
7
|
import { gitConfigArgs, gitEnvironment } from '@lincyaw/kernel'
|
|
8
|
+
import { isInside } from '@lincyaw/kernel/node'
|
|
6
9
|
import type { DocumentFileChange } from '@lincyaw/kernel'
|
|
7
10
|
import type { WorkspaceConfig } from '../config.ts'
|
|
8
11
|
import { RequestError } from '../errors.ts'
|
|
@@ -45,9 +48,23 @@ async function sourceStamp(file: string): Promise<FileStamp | undefined> {
|
|
|
45
48
|
export class AgentWorkspace {
|
|
46
49
|
readonly record: AgentWorkspaceRecord
|
|
47
50
|
readonly #config: WorkspaceConfig
|
|
51
|
+
#version = randomUUID()
|
|
52
|
+
readonly #dependencies = new WindowsDependencies()
|
|
48
53
|
|
|
49
|
-
private constructor(config: WorkspaceConfig, record: AgentWorkspaceRecord) {
|
|
54
|
+
private constructor(config: WorkspaceConfig, record: AgentWorkspaceRecord) {
|
|
55
|
+
this.#config = config
|
|
56
|
+
this.record = { ...record, root: realpathSync.native(record.root), original: realpathSync.native(record.original) }
|
|
57
|
+
}
|
|
50
58
|
get root(): string { return this.record.root }
|
|
59
|
+
get version(): string { return this.#version }
|
|
60
|
+
changed(): void { this.#version = randomUUID() }
|
|
61
|
+
|
|
62
|
+
/** Host restores invalidate a private view even when the author baseline did not move. */
|
|
63
|
+
writeCandidate(changes: DocumentFileChange[]): void {
|
|
64
|
+
if (!changes.length) return
|
|
65
|
+
this.changed()
|
|
66
|
+
writeChanges({ ...this.#config, root: this.root }, changes, true)
|
|
67
|
+
}
|
|
51
68
|
|
|
52
69
|
static async create(config: WorkspaceConfig): Promise<AgentWorkspace> {
|
|
53
70
|
const pool = join(config.root, '.presmium', 'agent-workspaces')
|
|
@@ -63,7 +80,12 @@ export class AgentWorkspace {
|
|
|
63
80
|
}
|
|
64
81
|
|
|
65
82
|
static resume(config: WorkspaceConfig, record: AgentWorkspaceRecord): AgentWorkspace {
|
|
66
|
-
|
|
83
|
+
try {
|
|
84
|
+
const original = realpathSync.native(config.root)
|
|
85
|
+
const pool = realpathSync.native(join(original, '.presmium', 'agent-workspaces'))
|
|
86
|
+
const root = realpathSync.native(record.root)
|
|
87
|
+
if (!isInside(original, realpathSync.native(record.original)) || !isInside(realpathSync.native(record.original), original) || !isInside(root, pool) || isInside(pool, root) || !existsSync(join(root, '.git'))) throw new Error('Invalid candidate record')
|
|
88
|
+
} catch { throw new RequestError(409, 'agent-workspace-unavailable') }
|
|
67
89
|
return new AgentWorkspace(config, record)
|
|
68
90
|
}
|
|
69
91
|
|
|
@@ -79,12 +101,13 @@ export class AgentWorkspace {
|
|
|
79
101
|
if (same(current, this.record.base[path])) continue
|
|
80
102
|
const target = join(this.root, path)
|
|
81
103
|
if (same(await sourceStamp(target), current)) continue
|
|
104
|
+
this.changed()
|
|
82
105
|
await mkdir(dirname(target), { recursive: true })
|
|
83
106
|
await rm(target, { force: true, recursive: true })
|
|
84
107
|
await cp(join(this.#config.root, path), target, { dereference: false, verbatimSymlinks: true })
|
|
85
108
|
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.' })
|
|
86
109
|
}
|
|
87
|
-
for (const path of Object.keys(this.record.base)) if (!next[path]) await rm(join(this.root, path), { force: true, recursive: true })
|
|
110
|
+
for (const path of Object.keys(this.record.base)) if (!next[path]) { this.changed(); await rm(join(this.root, path), { force: true, recursive: true }) }
|
|
88
111
|
const changed = JSON.stringify(next) !== JSON.stringify(this.record.base)
|
|
89
112
|
this.record.base = next
|
|
90
113
|
const dependencyDirs = new Set(['', ...paths.filter(path => path.endsWith('package.json')).map(dirname)])
|
|
@@ -92,9 +115,13 @@ export class AgentWorkspace {
|
|
|
92
115
|
let source = join(this.#config.root, dir)
|
|
93
116
|
while (!existsSync(join(source, 'node_modules')) && dirname(source) !== source) source = dirname(source)
|
|
94
117
|
const target = join(this.root, dir, 'node_modules')
|
|
95
|
-
if (existsSync(join(source, 'node_modules')) &&
|
|
118
|
+
if (existsSync(join(source, 'node_modules')) && existsSync(dirname(target))) {
|
|
119
|
+
if (process.platform === 'win32') await this.#dependencies.sync(source, target, dirname(this.root), () => this.changed())
|
|
120
|
+
else if (!existsSync(target)) { this.changed(); await symlink(join(source, 'node_modules'), target, 'dir') }
|
|
121
|
+
}
|
|
96
122
|
}
|
|
97
123
|
if (changed || !(await git(this.root, ['rev-parse', '--verify', 'HEAD']).catch(() => '')).trim()) {
|
|
124
|
+
this.changed()
|
|
98
125
|
await git(this.root, ['add', '-A'])
|
|
99
126
|
await git(this.root, ['-c', 'user.name=Presmium', '-c', 'user.email=presmium@localhost', 'commit', '-q', '--allow-empty', '-m', 'Author workspace snapshot'])
|
|
100
127
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { execFile } from 'node:child_process'
|
|
2
2
|
import { createHash } from 'node:crypto'
|
|
3
|
-
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmdirSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmdirSync, rmSync, writeFileSync } from 'node:fs'
|
|
4
4
|
import { tmpdir } from 'node:os'
|
|
5
5
|
import { dirname, join, relative, resolve, sep } from 'node:path'
|
|
6
6
|
import { gitConfigArgs, gitEnvironment } from '@lincyaw/kernel'
|
|
@@ -59,7 +59,16 @@ export interface GitDirs {
|
|
|
59
59
|
|
|
60
60
|
async function gitDirsOf(root: string): Promise<GitDirs> {
|
|
61
61
|
const [top = '', gitDir = '', commonDir = ''] = (await gitText(root, ['rev-parse', '--show-toplevel', '--absolute-git-dir', '--git-common-dir'])).split('\n')
|
|
62
|
-
return { top: realpathSync(top), gitDir: realpathSync(gitDir), commonDir: realpathSync(resolve(root, commonDir)) }
|
|
62
|
+
return { top: realpathSync.native(top), gitDir: realpathSync.native(gitDir), commonDir: realpathSync.native(resolve(root, commonDir)) }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function canonicalGitDirs(dirs: GitDirs, saved?: SavedGitDir): GitDirs {
|
|
66
|
+
// Check the recorded entry before realpath can follow a replacement symlink.
|
|
67
|
+
if (saved) {
|
|
68
|
+
const stat = lstatSync(dirs.gitDir)
|
|
69
|
+
if (!stat.isDirectory() || `${stat.dev}:${stat.ino}` !== saved.identity) throw new Error(`the git directory ${dirs.gitDir} was replaced`)
|
|
70
|
+
}
|
|
71
|
+
return { top: realpathSync.native(dirs.top), gitDir: realpathSync.native(dirs.gitDir), commonDir: realpathSync.native(dirs.commonDir) }
|
|
63
72
|
}
|
|
64
73
|
|
|
65
74
|
const COPIED_CONFIG_KEYS = '^(core\\.(filemode|symlinks|ignorecase|precomposeunicode|autocrlf|eol|safecrlf|excludesfile)|extensions\\.objectformat)$'
|
|
@@ -259,10 +268,10 @@ function gitDirGuard(gitDir: string, scopeDir: string, root: string, onRestore:
|
|
|
259
268
|
}
|
|
260
269
|
|
|
261
270
|
export function recoverGitReview(options: Omit<GitReviewOptions, 'task'>): Promise<{ task: string, paths: string[] } | undefined> {
|
|
262
|
-
const scopeDir = realpathSync(options.scopeDir)
|
|
271
|
+
const scopeDir = realpathSync.native(options.scopeDir)
|
|
263
272
|
let running = recovering.get(scopeDir)
|
|
264
273
|
if (!running) {
|
|
265
|
-
running = rollBackLeftReview(scopeDir, realpathSync(options.workspaceRoot), options).finally(() => recovering.delete(scopeDir))
|
|
274
|
+
running = rollBackLeftReview(scopeDir, realpathSync.native(options.workspaceRoot), options).finally(() => recovering.delete(scopeDir))
|
|
266
275
|
recovering.set(scopeDir, running)
|
|
267
276
|
}
|
|
268
277
|
return running
|
|
@@ -273,8 +282,9 @@ async function rollBackLeftReview(scopeDir: string, root: string, options: Omit<
|
|
|
273
282
|
if (!record || record.session || openScopes.has(scopeDir) || isHolderAlive(record)) return undefined
|
|
274
283
|
let trees: ReviewTrees | undefined
|
|
275
284
|
try {
|
|
276
|
-
|
|
277
|
-
|
|
285
|
+
const dirs = canonicalGitDirs(record.dirs, record.guard)
|
|
286
|
+
if (record.guard) gitDirGuard(dirs.gitDir, scopeDir, root, options.onRestore, record.guard).restore()
|
|
287
|
+
trees = new ReviewTrees(dirs, scopeDir, root, await isolatedGitConfig(dirs), options)
|
|
278
288
|
const paths = await trees.changedPaths(record.snapshot, await trees.tree())
|
|
279
289
|
await trees.restore(record.snapshot, paths)
|
|
280
290
|
return { task: record.task, paths }
|
|
@@ -286,14 +296,14 @@ async function rollBackLeftReview(scopeDir: string, root: string, options: Omit<
|
|
|
286
296
|
|
|
287
297
|
/** The record of an agent session's review that a process which has ended left waiting for its author. */
|
|
288
298
|
export function pendingAgentSessionReview(scopeDir: string): ReviewRecord | undefined {
|
|
289
|
-
const real = realpathSync(scopeDir)
|
|
299
|
+
const real = realpathSync.native(scopeDir)
|
|
290
300
|
const record = readRecord(real)
|
|
291
301
|
return record?.session && !openScopes.has(real) && !isHolderAlive(record) ? record : undefined
|
|
292
302
|
}
|
|
293
303
|
|
|
294
304
|
export async function openGitReview(options: GitReviewOptions & { session?: Omit<AgentSessionRecord, 'checkpoints' | 'steps'> }): Promise<GitReview> {
|
|
295
|
-
const scopeDir = realpathSync(options.scopeDir)
|
|
296
|
-
const root = realpathSync(options.workspaceRoot)
|
|
305
|
+
const scopeDir = realpathSync.native(options.scopeDir)
|
|
306
|
+
const root = realpathSync.native(options.workspaceRoot)
|
|
297
307
|
if (openScopes.has(scopeDir)) throw new Error(`a change of ${relative(root, scopeDir) || '.'} is under way already`)
|
|
298
308
|
const left = readRecord(scopeDir)
|
|
299
309
|
if (left && isHolderAlive(left)) throw new Error(`a change of ${relative(root, scopeDir) || '.'} is under way in another process (${left.pid})`)
|
|
@@ -318,14 +328,15 @@ export async function openGitReview(options: GitReviewOptions & { session?: Omit
|
|
|
318
328
|
}
|
|
319
329
|
|
|
320
330
|
export async function resumeGitReview(record: ReviewRecord, options: Omit<GitReviewOptions, 'task' | 'scopeDir'>): Promise<GitReview> {
|
|
321
|
-
const scopeDir = realpathSync(record.scopeDir)
|
|
322
|
-
const root = realpathSync(options.workspaceRoot)
|
|
331
|
+
const scopeDir = realpathSync.native(record.scopeDir)
|
|
332
|
+
const root = realpathSync.native(options.workspaceRoot)
|
|
323
333
|
if (openScopes.has(scopeDir) || isHolderAlive(record)) throw new Error(`a change of ${relative(root, scopeDir) || '.'} is under way already`)
|
|
324
|
-
const
|
|
334
|
+
const dirs = canonicalGitDirs(record.dirs, record.guard)
|
|
335
|
+
const { restore: restoreGitDir } = gitDirGuard(dirs.gitDir, scopeDir, root, options.onRestore, record.guard)
|
|
325
336
|
restoreGitDir()
|
|
326
|
-
const trees = new ReviewTrees(
|
|
337
|
+
const trees = new ReviewTrees(dirs, scopeDir, root, await isolatedGitConfig(dirs), options)
|
|
327
338
|
openScopes.add(scopeDir)
|
|
328
|
-
return createGitReview({ scopeDir, trees, restoreGitDir, record: { ...record, ...THIS_PROCESS }, warn: options.warn })
|
|
339
|
+
return createGitReview({ scopeDir, trees, restoreGitDir, record: { ...record, scopeDir, dirs, ...THIS_PROCESS }, warn: options.warn })
|
|
329
340
|
}
|
|
330
341
|
|
|
331
342
|
function createGitReview(open: { scopeDir: string, trees: ReviewTrees, restoreGitDir: () => void, record: ReviewRecord, warn?: (message: string) => void }): GitReview {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto'
|
|
2
|
-
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
3
|
import { homedir } from 'node:os'
|
|
4
4
|
import { join } from 'node:path'
|
|
5
5
|
import type { Member, ReviewStep } from '@lincyaw/kernel'
|
|
@@ -37,7 +37,31 @@ export function recordsDir(env: NodeJS.ProcessEnv = process.env): string {
|
|
|
37
37
|
return join(env.XDG_STATE_HOME || join(env.HOME || homedir(), '.local', 'state'), 'presmium', 'reviews')
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
const
|
|
40
|
+
const canonicalScope = (scopeDir: string): string => {
|
|
41
|
+
try { const path = realpathSync.native(scopeDir); return process.platform === 'win32' ? path.toLowerCase() : path } catch { return scopeDir }
|
|
42
|
+
}
|
|
43
|
+
const legacyRecordFile = (scopeDir: string) => join(recordsDir(), `${createHash('sha256').update(scopeDir).digest('hex').slice(0, 24)}.json`)
|
|
44
|
+
const recordFile = (scopeDir: string) => legacyRecordFile(canonicalScope(scopeDir))
|
|
45
|
+
|
|
46
|
+
/** Earlier Windows records could hash either the short or the long name of one directory. */
|
|
47
|
+
function recordFiles(scopeDir: string): string[] {
|
|
48
|
+
const files = new Set([recordFile(scopeDir), legacyRecordFile(scopeDir)])
|
|
49
|
+
if (process.platform === 'win32') {
|
|
50
|
+
let names: string[] = []
|
|
51
|
+
try { names = readdirSync(recordsDir()) } catch {}
|
|
52
|
+
const scope = canonicalScope(scopeDir)
|
|
53
|
+
for (const name of names) {
|
|
54
|
+
if (!/^[a-f0-9]{24}\.json$/.test(name)) continue
|
|
55
|
+
const file = join(recordsDir(), name)
|
|
56
|
+
try {
|
|
57
|
+
const record = JSON.parse(readFileSync(file, 'utf8')) as Partial<ReviewRecord> & { deck?: string }
|
|
58
|
+
const root = record.recordRoot ?? record.scopeDir ?? record.deck
|
|
59
|
+
if (root && canonicalScope(root) === scope) files.add(file)
|
|
60
|
+
} catch {}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return [...files]
|
|
64
|
+
}
|
|
41
65
|
|
|
42
66
|
export function processStartTime(pid: number): string | undefined {
|
|
43
67
|
try {
|
|
@@ -61,21 +85,25 @@ export function isHolderAlive(record: ReviewRecord): boolean {
|
|
|
61
85
|
|
|
62
86
|
/** Reads the record of a review of the directory; records of earlier versions name the directory `deck`. */
|
|
63
87
|
export function readRecord(scopeDir: string): ReviewRecord | undefined {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
88
|
+
for (const file of recordFiles(scopeDir)) {
|
|
89
|
+
try {
|
|
90
|
+
const { deck, ...record } = JSON.parse(readFileSync(file, 'utf8')) as Partial<ReviewRecord> & { deck?: string }
|
|
91
|
+
return { ...record, scopeDir: record.scopeDir ?? deck } as ReviewRecord
|
|
92
|
+
} catch {}
|
|
69
93
|
}
|
|
94
|
+
return undefined
|
|
70
95
|
}
|
|
71
96
|
|
|
72
97
|
export function writeRecord(record: ReviewRecord): void {
|
|
73
|
-
const
|
|
98
|
+
const root = record.recordRoot ?? record.scopeDir
|
|
99
|
+
const previous = recordFiles(root)
|
|
100
|
+
const file = recordFile(root)
|
|
74
101
|
mkdirSync(recordsDir(), { recursive: true, mode: 0o700 })
|
|
75
102
|
writeFileSync(`${file}.${process.pid}`, JSON.stringify(record), { mode: 0o600 })
|
|
76
103
|
renameSync(`${file}.${process.pid}`, file)
|
|
104
|
+
for (const old of previous) if (old !== file) rmSync(old, { force: true })
|
|
77
105
|
}
|
|
78
106
|
|
|
79
107
|
export function removeRecord(scopeDir: string): void {
|
|
80
|
-
|
|
108
|
+
for (const file of recordFiles(scopeDir)) rmSync(file, { force: true })
|
|
81
109
|
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { createRequire } from 'node:module'
|
|
3
|
+
import { constants, createReadStream } from 'node:fs'
|
|
4
|
+
import { chmod, copyFile, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
5
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path'
|
|
6
|
+
import { isInside } from '@lincyaw/kernel/node'
|
|
7
|
+
import type { HoisterResult, HoisterTree } from '@yarnpkg/nm'
|
|
8
|
+
|
|
9
|
+
type Manifest = { name?: string, dependencies?: Record<string, string>, devDependencies?: Record<string, string>, optionalDependencies?: Record<string, string>, peerDependencies?: Record<string, string>, bin?: string | Record<string, string> }
|
|
10
|
+
type File = { source: string, path: string, mode: number, digest: string }
|
|
11
|
+
type Package = { source: string, manifest: Manifest, files: File[], directories: string[], direct: Set<string> }
|
|
12
|
+
const validName = (name: string) => /^(?:@[^/\\]+\/)?[^/\\]+$/.test(name) && !name.split('/').some(part => part === '.' || part === '..')
|
|
13
|
+
const digestOf = async (path: string): Promise<string> => {
|
|
14
|
+
const hash = createHash('sha256')
|
|
15
|
+
for await (const chunk of createReadStream(path)) hash.update(chunk)
|
|
16
|
+
return hash.digest('hex')
|
|
17
|
+
}
|
|
18
|
+
const json = async (file: string): Promise<Manifest> => JSON.parse(await readFile(file, 'utf8').catch(error => { if (error.code === 'ENOENT') return '{}'; throw error }))
|
|
19
|
+
const namesOf = (pkg: Manifest, root = false) => new Set(Object.keys({ ...pkg.dependencies, ...pkg.optionalDependencies, ...pkg.peerDependencies, ...root ? pkg.devDependencies : {} }))
|
|
20
|
+
|
|
21
|
+
/** Materialize the installed graph, never re-resolve versions or rerun install/build scripts. */
|
|
22
|
+
export class WindowsDependencies {
|
|
23
|
+
readonly #hashes = new Map<string, { version: string, digest: string }>()
|
|
24
|
+
|
|
25
|
+
async #files(root: string): Promise<{ files: File[], directories: string[] }> {
|
|
26
|
+
const files: File[] = []
|
|
27
|
+
const directories: string[] = []
|
|
28
|
+
const walk = async (directory: string, path: string, parents: Set<string>): Promise<void> => {
|
|
29
|
+
const canonical = await realpath(directory)
|
|
30
|
+
if (!isInside(canonical, root)) throw new Error('A Windows dependency asset link leaves its package')
|
|
31
|
+
if (parents.has(canonical)) throw new Error('A Windows dependency has a recursive asset link')
|
|
32
|
+
const ancestors = new Set([...parents, canonical])
|
|
33
|
+
for (const item of (await readdir(directory)).sort()) {
|
|
34
|
+
if (item === '.git' || item === '.presmium' || (!path && item === 'node_modules')) continue
|
|
35
|
+
const source = join(directory, item)
|
|
36
|
+
const target = join(path, item)
|
|
37
|
+
const resolved = await realpath(source)
|
|
38
|
+
if (!isInside(resolved, root)) throw new Error('A Windows dependency asset link leaves its package')
|
|
39
|
+
const info = await stat(resolved, { bigint: true })
|
|
40
|
+
if (info.isDirectory()) { directories.push(target); await walk(resolved, target, ancestors) }
|
|
41
|
+
else if (info.isFile()) {
|
|
42
|
+
const version = [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs, info.mode].join(':')
|
|
43
|
+
let known = this.#hashes.get(resolved)
|
|
44
|
+
if (known?.version !== version) {
|
|
45
|
+
const digest = await digestOf(resolved)
|
|
46
|
+
this.#hashes.set(resolved, known = { version, digest })
|
|
47
|
+
}
|
|
48
|
+
files.push({ source: resolved, path: target, mode: Number(info.mode) & 0o777, digest: known!.digest })
|
|
49
|
+
} else throw new Error('A Windows dependency contains a non-file entry')
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
await walk(root, '', new Set())
|
|
53
|
+
return { files, directories }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async #graph(source: string) {
|
|
57
|
+
const packages = new Map<string, Package>()
|
|
58
|
+
const nodes = new Map<string, HoisterTree>()
|
|
59
|
+
const roots = async (directory: string): Promise<string[]> => {
|
|
60
|
+
const result: string[] = []
|
|
61
|
+
for (const name of (await readdir(directory).catch(error => { if (error.code === 'ENOENT') return []; throw error })).sort()) {
|
|
62
|
+
if (name.startsWith('.')) continue
|
|
63
|
+
if (name.startsWith('@')) for (const member of (await readdir(join(directory, name))).sort()) result.push(`${name}/${member}`)
|
|
64
|
+
else result.push(name)
|
|
65
|
+
}
|
|
66
|
+
return result.filter(validName)
|
|
67
|
+
}
|
|
68
|
+
const find = async (from: string, name: string): Promise<string | undefined> => {
|
|
69
|
+
if (!validName(name)) throw new Error('A Windows dependency has an invalid package name')
|
|
70
|
+
for (const directory of createRequire(join(from, 'package.json')).resolve.paths(name) ?? []) {
|
|
71
|
+
const found = await stat(join(directory, name)).catch(error => { if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return; throw error })
|
|
72
|
+
if (found?.isDirectory()) return realpath(join(directory, name))
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const visit = async (name: string, path: string): Promise<HoisterTree> => {
|
|
76
|
+
path = await realpath(path)
|
|
77
|
+
const id = createHash('sha256').update(path).digest('hex')
|
|
78
|
+
const nodeKey = `${name}:${id}`
|
|
79
|
+
const known = nodes.get(nodeKey)
|
|
80
|
+
if (known) return known
|
|
81
|
+
const manifest = await json(join(path, 'package.json'))
|
|
82
|
+
// Installed peers are exact dependency edges; pnpm may inject them inside this package,
|
|
83
|
+
// while the hoister's peerNames contract requires a provider in the parent.
|
|
84
|
+
const node: HoisterTree = { name, identName: manifest.name ?? name, reference: id, dependencies: new Set(), peerNames: new Set() }
|
|
85
|
+
nodes.set(nodeKey, node)
|
|
86
|
+
if (!packages.has(id)) packages.set(id, { source: path, manifest, ...await this.#files(path), direct: namesOf(manifest) })
|
|
87
|
+
const dependencies = new Set([...namesOf(manifest), ...await roots(join(path, 'node_modules'))])
|
|
88
|
+
for (const dependency of dependencies) {
|
|
89
|
+
const resolved = await find(path, dependency)
|
|
90
|
+
if (resolved) node.dependencies.add(await visit(dependency, resolved))
|
|
91
|
+
}
|
|
92
|
+
return node
|
|
93
|
+
}
|
|
94
|
+
const manifest = await json(join(source, 'package.json'))
|
|
95
|
+
const tree: HoisterTree = { name: 'presmium-candidate', identName: 'presmium-candidate', reference: 'root', dependencies: new Set(), peerNames: new Set() }
|
|
96
|
+
for (const name of await roots(join(source, 'node_modules'))) {
|
|
97
|
+
const path = await find(source, name)
|
|
98
|
+
if (path) tree.dependencies.add(await visit(name, path))
|
|
99
|
+
}
|
|
100
|
+
const edges = (node: HoisterTree) => [...node.dependencies].map(dependency => `${dependency.name}:${dependency.reference}`).sort()
|
|
101
|
+
const topology = [...nodes].sort(([a], [b]) => a.localeCompare(b)).map(([id, node]) => [id, node.identName, [...node.peerNames].sort(), edges(node)])
|
|
102
|
+
const stamp = createHash('sha256').update(JSON.stringify([manifest, edges(tree), topology, [...packages].map(([id, pkg]) => [id, pkg.files.map(file => [file.path, file.mode, file.digest]), pkg.directories])])).digest('hex')
|
|
103
|
+
return { tree, packages, stamp, direct: namesOf(manifest, true) }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async sync(source: string, target: string, state: string, changed: () => void): Promise<void> {
|
|
107
|
+
const graph = await this.#graph(source)
|
|
108
|
+
const record = join(state, `dependencies-${createHash('sha256').update(resolve(target)).digest('hex')}.json`)
|
|
109
|
+
const previous = await readFile(record, 'utf8').catch(() => '')
|
|
110
|
+
const existing = await lstat(target).catch(error => { if (error.code !== 'ENOENT') throw error })
|
|
111
|
+
if (existing?.isDirectory() && !existing.isSymbolicLink() && previous === graph.stamp) return
|
|
112
|
+
const stage = await mkdtemp(join(state, 'dependencies-'))
|
|
113
|
+
try {
|
|
114
|
+
const { hoist } = await import('@yarnpkg/nm')
|
|
115
|
+
const shim = createRequire(import.meta.url)('cmd-shim') as (source: string, target: string) => Promise<void>
|
|
116
|
+
const copy = async (node: HoisterResult, destination: string, direct: Set<string>, parents: Set<string>): Promise<void> => {
|
|
117
|
+
await mkdir(destination, { recursive: true })
|
|
118
|
+
const bins = new Map<string, string>()
|
|
119
|
+
const dependencies = [...node.dependencies].sort((a, b) => Number(direct.has(a.name)) - Number(direct.has(b.name)) || a.name.localeCompare(b.name))
|
|
120
|
+
for (const dependency of dependencies) {
|
|
121
|
+
const identity = `${dependency.name}:${[...dependency.references].sort().join(',')}`
|
|
122
|
+
if (parents.has(identity) || dependency === node) continue
|
|
123
|
+
if (!validName(dependency.name) || dependency.references.size !== 1) throw new Error('The Windows dependency layout is ambiguous')
|
|
124
|
+
const pkg = graph.packages.get([...dependency.references][0]!)!
|
|
125
|
+
const directory = join(destination, dependency.name)
|
|
126
|
+
await mkdir(directory, { recursive: true })
|
|
127
|
+
for (const path of pkg.directories) await mkdir(join(directory, path), { recursive: true })
|
|
128
|
+
for (const file of pkg.files) {
|
|
129
|
+
const output = join(directory, file.path)
|
|
130
|
+
await copyFile(file.source, output, constants.COPYFILE_FICLONE)
|
|
131
|
+
if (await digestOf(output) !== file.digest) throw new Error('Windows source dependencies changed while their candidate snapshot was copied')
|
|
132
|
+
await chmod(output, file.mode)
|
|
133
|
+
}
|
|
134
|
+
const commands = typeof pkg.manifest.bin === 'string' ? { [basename(pkg.manifest.name ?? dependency.name)]: pkg.manifest.bin } : pkg.manifest.bin ?? {}
|
|
135
|
+
for (const [name, path] of Object.entries(commands)) {
|
|
136
|
+
const entry = resolve(directory, path)
|
|
137
|
+
if (!name || name === '.' || name === '..' || /[\\/]/.test(name) || !isInside(entry, directory)) throw new Error('A Windows dependency command leaves its package')
|
|
138
|
+
const file = await stat(entry).catch(error => { if (error.code !== 'ENOENT') throw error })
|
|
139
|
+
if (file?.isFile()) bins.set(name, entry)
|
|
140
|
+
}
|
|
141
|
+
await copy(dependency, join(directory, 'node_modules'), pkg.direct, new Set([...parents, identity]))
|
|
142
|
+
}
|
|
143
|
+
for (const [name, entry] of bins) { await mkdir(join(destination, '.bin'), { recursive: true }); await shim(entry, join(destination, '.bin', name)) }
|
|
144
|
+
}
|
|
145
|
+
// Public CHECK level validates the final layout; check:true repeats a full graph check after every move.
|
|
146
|
+
await copy(hoist(graph.tree, { debugLevel: 1 }), stage, graph.direct, new Set())
|
|
147
|
+
const ordinary = async (directory: string): Promise<void> => {
|
|
148
|
+
for (const name of await readdir(directory)) {
|
|
149
|
+
const path = join(directory, name)
|
|
150
|
+
const info = await lstat(path)
|
|
151
|
+
if (info.isSymbolicLink() || (!info.isDirectory() && (!info.isFile() || info.nlink !== 1))) throw new Error('Windows candidate dependencies are not independent ordinary files')
|
|
152
|
+
if (info.isDirectory()) await ordinary(path)
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
await ordinary(stage)
|
|
156
|
+
if ((await this.#graph(source)).stamp !== graph.stamp) throw new Error('Windows source dependencies changed while their candidate snapshot was copied')
|
|
157
|
+
changed()
|
|
158
|
+
await rm(target, { recursive: true, force: true })
|
|
159
|
+
await rename(stage, target)
|
|
160
|
+
await writeFile(record, graph.stamp)
|
|
161
|
+
} finally { await rm(stage, { recursive: true, force: true, maxRetries: 3 }) }
|
|
162
|
+
}
|
|
163
|
+
}
|