@cirtium/acent-connect 1.0.1 → 1.0.2

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.
@@ -0,0 +1,512 @@
1
+ import { createHash } from "node:crypto"
2
+ import { constants, createReadStream } from "node:fs"
3
+ import {
4
+ copyFile,
5
+ cp,
6
+ lstat,
7
+ mkdir,
8
+ mkdtemp,
9
+ readFile,
10
+ realpath,
11
+ rm,
12
+ writeFile,
13
+ } from "node:fs/promises"
14
+ import { tmpdir } from "node:os"
15
+ import { basename, dirname, join } from "node:path"
16
+ import { bridgeGitEnvironment, runProcess } from "./bridge-runners.mjs"
17
+
18
+ const privateFile = (path) =>
19
+ /^(?:\.env(?:\.|$)|\.npmrc$|\.netrc$|id_(?:rsa|ed25519))/i.test(
20
+ basename(path)
21
+ ) || /\.(?:pem|key|p12)$/i.test(path)
22
+
23
+ export function workspacePath(path) {
24
+ return (
25
+ typeof path === "string" &&
26
+ path.length > 0 &&
27
+ path.length <= 512 &&
28
+ !/[\\:\x00-\x1f]/.test(path) &&
29
+ !privateFile(path) &&
30
+ path
31
+ .split("/")
32
+ .every(
33
+ (part) =>
34
+ part && part !== "." && part !== ".." && part.toLowerCase() !== ".git"
35
+ )
36
+ )
37
+ }
38
+
39
+ export function pathsOverlap(left, right) {
40
+ if (process.platform === "darwin" || process.platform === "win32") {
41
+ left = left.normalize("NFC").toLowerCase()
42
+ right = right.normalize("NFC").toLowerCase()
43
+ }
44
+ return (
45
+ left === right ||
46
+ left.startsWith(right + "/") ||
47
+ right.startsWith(left + "/")
48
+ )
49
+ }
50
+
51
+ export async function git(cwd, args, { input, isolated = false } = {}) {
52
+ const env = bridgeGitEnvironment()
53
+ if (isolated)
54
+ Object.assign(env, {
55
+ GIT_CONFIG_NOSYSTEM: "1",
56
+ GIT_CONFIG_GLOBAL: process.platform === "win32" ? "NUL" : "/dev/null",
57
+ })
58
+ const result = await runProcess(
59
+ "git",
60
+ [
61
+ "-c",
62
+ "core.hooksPath=" + (process.platform === "win32" ? "NUL" : "/dev/null"),
63
+ ...args,
64
+ ],
65
+ {
66
+ cwd,
67
+ env,
68
+ input,
69
+ timeout: 30000,
70
+ maxBytes: 16 * 1024 * 1024,
71
+ }
72
+ )
73
+ if (result.failure || result.code !== 0) {
74
+ const error = new Error(
75
+ "Bridge could not prepare, compare, or apply the Git working copy."
76
+ )
77
+ error.details = result.stderr.trim().slice(-2000)
78
+ throw error
79
+ }
80
+ return result.stdout
81
+ }
82
+
83
+ export async function fileVersion(folder, path) {
84
+ if (!workspacePath(path)) return "unsupported"
85
+ let current = folder
86
+ for (const part of path.split("/")) {
87
+ current = join(current, part)
88
+ const info = await lstat(current).catch((error) => {
89
+ if (error.code === "ENOENT") return null
90
+ if (error.code === "ENOTDIR") return false
91
+ throw error
92
+ })
93
+ if (info === null) return null
94
+ if (
95
+ !info ||
96
+ info.isSymbolicLink() ||
97
+ (current !== join(folder, path) && !info.isDirectory())
98
+ )
99
+ return "unsupported"
100
+ if (current === join(folder, path)) {
101
+ if (!info.isFile()) return "unsupported"
102
+ const digest = createHash("sha256")
103
+ for await (const buffer of createReadStream(current))
104
+ digest.update(buffer)
105
+ return (info.mode & 0o100 ? "x:" : "-:") + digest.digest("hex")
106
+ }
107
+ }
108
+ }
109
+
110
+ async function projectFiles(folder, includeIgnored = false) {
111
+ const entries = await git(folder, [
112
+ "ls-files",
113
+ "-z",
114
+ "--cached",
115
+ "--others",
116
+ ...(includeIgnored ? [] : ["--exclude-standard"]),
117
+ ])
118
+ const paths = [...new Set(entries.split("\0").filter(Boolean))]
119
+ return includeIgnored ? paths : paths.filter(workspacePath)
120
+ }
121
+
122
+ export async function projectFileVersions(folder, scopes) {
123
+ const versions = Object.create(null)
124
+ for (const path of await projectFiles(folder)) {
125
+ if (
126
+ scopes &&
127
+ !scopes.some((scope) => path === scope || path.startsWith(scope + "/"))
128
+ )
129
+ continue
130
+ const version = await fileVersion(folder, path)
131
+ if (version !== null) versions[path] = version
132
+ }
133
+ return versions
134
+ }
135
+
136
+ export async function bridgeFileVersions(folder) {
137
+ const versions = await projectFileVersions(folder)
138
+ return Object.fromEntries(
139
+ Object.entries(versions).filter(([, value]) => value !== "unsupported")
140
+ )
141
+ }
142
+
143
+ export function changedBridgePaths(expected, current) {
144
+ return [
145
+ ...new Set([...Object.keys(expected), ...Object.keys(current)]),
146
+ ].filter((path) => expected[path] !== current[path])
147
+ }
148
+
149
+ export async function mismatchedBridgePaths(
150
+ folder,
151
+ changes,
152
+ version = "after"
153
+ ) {
154
+ const versions = await Promise.all(
155
+ changes.map(({ path }) => fileVersion(folder, path))
156
+ )
157
+ return changes
158
+ .filter((change, index) => change[version] !== versions[index])
159
+ .map(({ path }) => path)
160
+ }
161
+
162
+ export function appliedBridgeChanges(jobs) {
163
+ const latest = new Map()
164
+ const order = (job) => job.appliedAt ?? job.finishedAt ?? job.startedAt ?? 0
165
+ for (const job of [...jobs].sort(
166
+ (first, second) => order(first) - order(second)
167
+ )) {
168
+ for (const change of job.changes ?? []) latest.set(change.path, change)
169
+ }
170
+ return [...latest.values()]
171
+ }
172
+
173
+ export async function bridgeReviewDiff(folder, scopes, from, to) {
174
+ const head =
175
+ from ??
176
+ (await git(folder, ["rev-parse", "--verify", "HEAD"])
177
+ .then((value) => value.trim())
178
+ .catch(() => null))
179
+ const relevant = (path) =>
180
+ workspacePath(path) &&
181
+ (!scopes.length ||
182
+ scopes.some((scope) => path === scope || path.startsWith(scope + "/")))
183
+ const untracked = !from
184
+ ? (head
185
+ ? (
186
+ await git(folder, [
187
+ "ls-files",
188
+ "--others",
189
+ "--exclude-standard",
190
+ "-z",
191
+ ])
192
+ ).split("\0")
193
+ : await projectFiles(folder)
194
+ ).filter(relevant)
195
+ : []
196
+ if (!head)
197
+ return untracked.length
198
+ ? "Files added without a prior commit: " +
199
+ untracked.slice(0, 64).join(", ").slice(0, 4000)
200
+ : ""
201
+
202
+ const diff = [
203
+ "diff",
204
+ "--no-ext-diff",
205
+ "--no-textconv",
206
+ "--no-renames",
207
+ "--no-color",
208
+ "--relative",
209
+ ]
210
+ const refs = to ? [head, to] : [head]
211
+ const changed = (
212
+ await git(folder, [...diff, "--name-only", "-z", ...refs, "--"])
213
+ )
214
+ .split("\0")
215
+ .filter(relevant)
216
+ const paths = changed.slice(0, 64)
217
+ const listing = (items) => items.slice(0, 64).join(", ").slice(0, 4000)
218
+ let patch = ""
219
+ if (paths.length) {
220
+ // Literal pathspecs keep excluded and out-of-scope file data out of the review.
221
+ patch = await git(folder, [
222
+ "--literal-pathspecs",
223
+ ...diff,
224
+ "--unified=3",
225
+ ...refs,
226
+ "--",
227
+ ...paths,
228
+ ]).catch(() => "")
229
+ }
230
+ return [
231
+ changed.length ? "Changed tracked files: " + listing(changed) : "",
232
+ untracked.length
233
+ ? "Untracked additions (read their contents in the workspace): " +
234
+ listing(untracked)
235
+ : "",
236
+ patch.slice(0, 12000),
237
+ patch.length > 12000 ||
238
+ changed.length > paths.length ||
239
+ (paths.length && !patch)
240
+ ? "Diff shortened or unavailable. Inspect the listed paths for the complete context."
241
+ : "",
242
+ ]
243
+ .filter(Boolean)
244
+ .join("\n")
245
+ }
246
+
247
+ export async function projectSnapshot(folder, work, saveBaseline) {
248
+ const paths = await projectFiles(folder)
249
+ const baseline = Object.create(null)
250
+ let bytes = 0
251
+ let fileCount = 0
252
+ await mkdir(work, { recursive: true, mode: 0o700 })
253
+ for (const path of paths) {
254
+ const source = join(folder, path)
255
+ const canonical = await realpath(source).catch((error) => {
256
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return null
257
+ throw error
258
+ })
259
+ const info =
260
+ canonical === source
261
+ ? await lstat(source).catch((error) => {
262
+ if (error.code === "ENOENT") return null
263
+ throw error
264
+ })
265
+ : null
266
+ if (!info?.isFile()) continue
267
+ bytes += info.size
268
+ if (bytes > 256 * 1024 * 1024 || ++fileCount > 25000)
269
+ throw new Error("This working folder is too large for a Bridge copy.")
270
+ const destination = join(work, path)
271
+ await mkdir(dirname(destination), { recursive: true })
272
+ await copyFile(source, destination, constants.COPYFILE_FICLONE)
273
+ baseline[path] = await fileVersion(work, path)
274
+ }
275
+ await initBridgeGit(work)
276
+ await saveBaseline(await checkpointBridgeWorkspace(work, { files: baseline }))
277
+ }
278
+
279
+ async function initBridgeGit(work) {
280
+ await git(work, ["init", "--quiet", "--template="], { isolated: true })
281
+ const info = join(work, ".git", "info")
282
+ await mkdir(info, { recursive: true })
283
+ // Preserve the reviewed file's bytes even when project attributes normalize
284
+ // text, change its encoding, or run a clean filter.
285
+ await writeFile(
286
+ join(info, "attributes"),
287
+ "* -text !eol -filter -ident -working-tree-encoding !diff\n"
288
+ )
289
+ }
290
+
291
+ export async function checkpointBridgeWorkspace(work, { files, scopes } = {}) {
292
+ const options = { isolated: true }
293
+ await git(work, ["add", "--all", ...(files ? ["--force"] : [])], options)
294
+ await git(
295
+ work,
296
+ [
297
+ "-c",
298
+ "user.name=Acent Bridge",
299
+ "-c",
300
+ "user.email=bridge@acent.invalid",
301
+ "-c",
302
+ "commit.gpgSign=false",
303
+ "commit",
304
+ "--quiet",
305
+ "--allow-empty",
306
+ "-m",
307
+ "Bridge baseline",
308
+ ],
309
+ options
310
+ )
311
+ return {
312
+ head: (await git(work, ["rev-parse", "HEAD"], options)).trim(),
313
+ files: files ?? (await projectFileVersions(work, scopes)),
314
+ }
315
+ }
316
+
317
+ export async function cloneBridgeSnapshot(snapshot, work) {
318
+ // macOS cp uses clonefile on APFS. Node's reflink flag covers other
319
+ // supported filesystems. Both fall back to an ordinary isolated copy.
320
+ if (process.platform === "darwin") {
321
+ await mkdir(work, { mode: 0o700 })
322
+ const result = await runProcess(
323
+ "/bin/cp",
324
+ ["-cR", "-P", snapshot + "/", work],
325
+ {
326
+ timeout: 120000,
327
+ maxBytes: 64 * 1024,
328
+ }
329
+ )
330
+ if (result.failure || result.code !== 0)
331
+ throw new Error("Bridge could not clone the review workspace.")
332
+ return
333
+ }
334
+ await cp(snapshot, work, {
335
+ recursive: true,
336
+ mode: constants.COPYFILE_FICLONE,
337
+ force: false,
338
+ errorOnExist: true,
339
+ })
340
+ }
341
+
342
+ export async function inspectBridgeChanges(work, baseline, scopes = []) {
343
+ const options = { isolated: true }
344
+ await git(work, ["add", "--all"], options)
345
+ const args = [
346
+ "diff",
347
+ "--cached",
348
+ "--no-renames",
349
+ "--no-ext-diff",
350
+ "--no-textconv",
351
+ ]
352
+ const paths = (
353
+ await git(
354
+ work,
355
+ [...args, "--name-only", "-z", baseline.head, "--"],
356
+ options
357
+ )
358
+ )
359
+ .split("\0")
360
+ .filter(Boolean)
361
+ const changes = await Promise.all(
362
+ paths.map(async (path) => ({
363
+ path,
364
+ before: Object.hasOwn(baseline.files, path) ? baseline.files[path] : null,
365
+ after: await fileVersion(work, path),
366
+ }))
367
+ )
368
+ const violations = changes
369
+ .filter(
370
+ ({ path, before, after }) =>
371
+ before === "unsupported" ||
372
+ after === "unsupported" ||
373
+ (scopes.length > 0 &&
374
+ !scopes.some(
375
+ (scope) => path === scope || path.startsWith(scope + "/")
376
+ ))
377
+ )
378
+ .map((change) => change.path)
379
+ if (violations.length) return { violations, changes, patch: "" }
380
+ const diffArgs = [...args, "--binary", baseline.head, "--"]
381
+ return {
382
+ violations,
383
+ changes,
384
+ patch: paths.length ? await readBridgePatch(work, diffArgs, options) : "",
385
+ }
386
+ }
387
+
388
+ async function readBridgePatch(work, args, options) {
389
+ const patch = await git(work, args, options)
390
+ if (!patch.includes("\uFFFD")) return patch
391
+
392
+ // Git can render legacy-encoded files as text. Use its binary patch format
393
+ // when decoding the output as UTF-8 might have lost bytes.
394
+ const metadata = join(await realpath(work), ".git")
395
+ if ((await realpath(metadata)) !== metadata)
396
+ throw new Error("Bridge workspace Git metadata moved.")
397
+ const info = join(metadata, "info")
398
+ await mkdir(info, { recursive: true })
399
+ if ((await realpath(info)) !== info)
400
+ throw new Error("Bridge workspace Git attributes moved.")
401
+ const path = join(info, "attributes")
402
+ const original = await lstat(path)
403
+ .then((entry) => {
404
+ if (!entry.isFile()) throw new Error("Invalid Bridge Git attributes.")
405
+ return readFile(path)
406
+ })
407
+ .catch((error) => {
408
+ if (error.code === "ENOENT") return null
409
+ throw error
410
+ })
411
+ try {
412
+ await writeFile(
413
+ path,
414
+ Buffer.concat([original ?? Buffer.alloc(0), Buffer.from("\n* -diff\n")])
415
+ )
416
+ return await git(work, args, options)
417
+ } finally {
418
+ if (original) await writeFile(path, original)
419
+ else await rm(path, { force: true })
420
+ }
421
+ }
422
+
423
+ function applyBridgePatch(folder, patch, metadata) {
424
+ return git(
425
+ folder,
426
+ [
427
+ "--git-dir=" + metadata,
428
+ "--work-tree=" + folder,
429
+ "apply",
430
+ "--whitespace=nowarn",
431
+ "-",
432
+ ],
433
+ { input: patch, isolated: true }
434
+ )
435
+ }
436
+
437
+ export async function applyVersionedBridgePatch(
438
+ folder,
439
+ { patch, changes },
440
+ { check = false, beforeApply, previewRoot = tmpdir() } = {}
441
+ ) {
442
+ if (!changes.length) return { status: "applied" }
443
+ if (changes.some(({ path }) => !workspacePath(path)))
444
+ return { status: "patch_conflict", details: "Invalid workspace path." }
445
+ if (!(await mismatchedBridgePaths(folder, changes)).length)
446
+ return { status: "applied" }
447
+ const conflicts = await mismatchedBridgePaths(folder, changes, "before")
448
+ if (conflicts.length)
449
+ return { status: "working_copy_changed", paths: conflicts }
450
+ await mkdir(previewRoot, { recursive: true, mode: 0o700 })
451
+ const preview = await realpath(
452
+ await mkdtemp(join(previewRoot, "acent-patch-"))
453
+ )
454
+ try {
455
+ await initBridgeGit(preview)
456
+ const metadata = join(preview, ".git")
457
+ await writeFile(
458
+ join(metadata, "acent-preview.json"),
459
+ JSON.stringify({
460
+ pid: process.pid,
461
+ }),
462
+ { mode: 0o600 }
463
+ )
464
+ for (const { path, before } of changes) {
465
+ if (before === null) continue
466
+ const destination = join(preview, path)
467
+ await mkdir(dirname(destination), { recursive: true })
468
+ await copyFile(
469
+ join(folder, path),
470
+ destination,
471
+ constants.COPYFILE_FICLONE
472
+ )
473
+ }
474
+ const copiedConflicts = await mismatchedBridgePaths(
475
+ preview,
476
+ changes,
477
+ "before"
478
+ )
479
+ if (copiedConflicts.length)
480
+ return { status: "working_copy_changed", paths: copiedConflicts }
481
+ await applyBridgePatch(preview, patch, metadata)
482
+ const expected = Object.fromEntries(
483
+ changes
484
+ .filter(({ after }) => after !== null)
485
+ .map(({ path, after }) => [path, after])
486
+ )
487
+ const files = await projectFiles(preview, true)
488
+ const actual = Object.fromEntries(
489
+ await Promise.all(
490
+ files.map(async (path) => [path, await fileVersion(preview, path)])
491
+ )
492
+ )
493
+ const unexpected = changedBridgePaths(expected, actual)
494
+ if (unexpected.length)
495
+ return { status: "patch_conflict", paths: unexpected }
496
+ if (check) return { status: "ready_to_apply" }
497
+ if (beforeApply && (await beforeApply()) === false)
498
+ return { status: "cancelled" }
499
+ const lateConflicts = await mismatchedBridgePaths(folder, changes, "before")
500
+ if (lateConflicts.length)
501
+ return { status: "working_copy_changed", paths: lateConflicts }
502
+ await applyBridgePatch(folder, patch, metadata)
503
+ const drift = await mismatchedBridgePaths(folder, changes)
504
+ return drift.length
505
+ ? { status: "working_copy_changed", paths: drift }
506
+ : { status: "applied" }
507
+ } catch (error) {
508
+ return { status: "patch_conflict", details: error.details || error.message }
509
+ } finally {
510
+ await rm(preview, { recursive: true, force: true }).catch(() => {})
511
+ }
512
+ }