heyquilt 0.3.174 → 0.3.176

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +6 -3
  2. package/RELEASES.md +30 -0
  3. package/bin/quilt.js +1 -75
  4. package/desktop/main.js +22 -9
  5. package/package.json +2 -3
  6. package/src/ai-vm.js +1 -1
  7. package/src/api/memory-store.js +1 -5
  8. package/src/api/server.js +4 -45
  9. package/src/api/supabase-store.js +0 -10
  10. package/src/autowork.js +7 -142
  11. package/src/base-pick.js +125 -12
  12. package/src/branch-view.js +1 -1
  13. package/src/connection.js +12 -37
  14. package/src/control.js +16 -93
  15. package/src/fsutil.js +1 -1
  16. package/src/git-aside.js +70 -0
  17. package/src/github-commit.js +1 -2
  18. package/src/gitstate.js +326 -0
  19. package/src/held.js +12 -53
  20. package/src/history.js +1 -25
  21. package/src/live-merge.js +42 -161
  22. package/src/mcp.js +6 -90
  23. package/src/merge3.js +21 -5
  24. package/src/pathrules.js +1 -1
  25. package/src/protocol.js +6 -11
  26. package/src/read-bases.js +3 -5
  27. package/src/relay-live-write.js +37 -44
  28. package/src/relay-mcp.js +30 -164
  29. package/src/relay-prune.js +3 -6
  30. package/src/relay-turn-sync.js +7 -11
  31. package/src/runner.js +2 -4
  32. package/src/server.js +61 -1717
  33. package/src/session.js +895 -844
  34. package/src/setup.js +11 -3
  35. package/src/status.js +2 -5
  36. package/src/swap-in.js +56 -13
  37. package/src/turn-sync-plan.js +2 -2
  38. package/src/turn-sync.js +1 -1
  39. package/src/ui/agent-guide.js +3 -1
  40. package/src/ui/app.css +4 -96
  41. package/src/ui/app.js +1 -1
  42. package/src/ui/chat.js +2 -6
  43. package/src/ui/cloud-ai-model.js +0 -13
  44. package/src/ui/cloud-ai.js +2 -10
  45. package/src/ui/connections.js +2 -1
  46. package/src/ui/fileview.js +7 -20
  47. package/src/ui/git-rule.js +2 -13
  48. package/src/ui/home.js +2 -8
  49. package/src/ui/session-words.js +27 -0
  50. package/src/ui/session.js +34 -407
  51. package/src/ui-server.js +7 -56
  52. package/src/api/routes/seam-connect.js +0 -103
  53. package/src/api/routes/session-migrate.js +0 -39
  54. package/src/force-date.js +0 -27
  55. package/src/quilt-default.js +0 -84
  56. package/src/quilt-history.js +0 -106
  57. package/src/quilt-remote.js +0 -78
  58. package/src/seam-access.js +0 -97
  59. package/src/seam-url.js +0 -15
  60. package/src/session-follow.js +0 -583
  61. package/src/session-layout3.js +0 -466
  62. package/src/session-migrate.js +0 -123
  63. package/src/session-quilt.js +0 -126
  64. package/src/session-seam.js +0 -312
  65. package/src/source-live/bring-in.js +0 -391
  66. package/src/source-live/land.js +0 -410
  67. package/src/source-live/live-block.js +0 -1166
  68. package/src/source-live/live-square.js +0 -116
  69. package/src/ui/force-words.js +0 -19
  70. package/src/ui/quiltview.js +0 -213
  71. package/src/ui/seam-model.js +0 -309
package/src/control.js CHANGED
@@ -1,6 +1,5 @@
1
1
  // Local control API (127.0.0.1 only) so the CLI and the MCP server can talk to
2
2
  // a running session. Discovery info is written to .quilt/daemon.json.
3
- import { readAccount } from './account.js'
4
3
  import http from 'node:http'
5
4
  import fs from 'node:fs'
6
5
  import path from 'node:path'
@@ -12,26 +11,22 @@ import { runMailTool, MAIL_TOOLS } from './mail-tools.js'
12
11
  import { runAppTool, APP_TOOLS } from './app-tools.js'
13
12
  import { runWakeTool } from './wake-tool.js'
14
13
  import { wakeCheck } from './wake.js'
15
- import { seamAccess, sessionCredential } from './seam-access.js'
16
- import { runSessionSeamTool } from './session-seam.js'
17
- import { appSeamUrl } from './seam-url.js'
18
- import { squareFor } from './session-follow.js'
19
- import { shareWithPeople } from './session-layout3.js'
20
- import { QUILT_MOVE_TIMEOUT_MS } from './connection.js'
21
14
  import { FEATURES } from './protocol.js'
22
15
  import { currentVersion } from './releases.js'
23
16
  import { UPDATE_HOW } from './update-check.js'
24
17
 
25
- // Routes git mode had (removed with it in R3, 0.3.140; Seam's plans/quilt-source-control/16 "Compatibility
26
- // with older apps"): an older Quilt's MCP server, hook or git helper calling one gets 410 and what to do,
27
- // not a bare "not found".
18
+ // Routes an older Quilt had and this one has not: its MCP server, hook, git helper or `quilt` command
19
+ // calling one gets 410 and what to do, not a bare "not found".
28
20
  export const RETIRED_ROUTES = new Set([
29
21
  'GET /branches', 'GET /commits', 'GET /merges', 'GET /sync-status', 'GET /uncommitted',
30
22
  'POST /adopt', 'POST /agent-commits', 'POST /branches/sync', 'POST /clash', 'POST /commit-request',
31
23
  'POST /commit-request/commit', 'POST /commit-request/done', 'POST /git/credential', 'POST /git/push-check',
32
- 'POST /github-sync', 'POST /github-token', 'POST /github/recheck', 'POST /unpublished'
24
+ 'POST /github-sync', 'POST /github-token', 'POST /github/recheck', 'POST /unpublished',
25
+ // What an older `quilt commit`, `quilt session` and its source-control tools called.
26
+ 'POST /quilt-plan', 'POST /quilt-migrate', 'POST /quilt-make', 'POST /quilt-switch', 'POST /quilt-unswitch',
27
+ 'POST /quilt-shadow', 'POST /quilt-follow', 'POST /seam', 'POST /square-commit'
33
28
  ])
34
- export const RETIRED_WORDS = `Quilt no longer syncs with git, so this is gone: a session's code is committed and merged in Seam (seam_commit, seam_merge, quilt commit), and git in your folder is yours as it was. What asked for it is from an older Quilt. ${UPDATE_HOW.replace(/, then rejoin the session\.$/, ', then start your AI tool\'s session again so it loads the new Quilt tools.')}`
29
+ export const RETIRED_WORDS = `This command or tool no longer exists in Quilt. A session's code is committed with git, in your own folder, as in any git project; Quilt keeps everyone's files in sync and leaves git to you. What asked for it is from an older Quilt. ${UPDATE_HOW.replace(/, then rejoin the session\.$/, ', then start your AI tool\'s session again so it loads the new Quilt tools.')}`
35
30
 
36
31
  export async function startControl (session, extras = {}) {
37
32
  const token = crypto.randomBytes(16).toString('hex')
@@ -48,41 +43,6 @@ export async function startControl (session, extras = {}) {
48
43
  return (await apiCall(await secretsApi(), 'GET', '/v1/agents/me/wake')).wake
49
44
  }
50
45
  })
51
- // Seam's tools for this folder's AI sessions, in a session that is a quilt (session-seam.js), as
52
- // this session's member: its person, or its agent on a cloud machine (seam-access.js).
53
- // Kept on the session, so its AI's runs (autowork.js) read Seam as the same member.
54
- if (extras.apiAuth && !session.apiAuth) session.apiAuth = extras.apiAuth
55
- const seam = session.seamMember ? session.seamMember() : (session.seam || (session.seam = seamAccess({ api: () => appSeamUrl(), credential: sessionCredential({ apiAuth: extras.apiAuth, account: readAccount }) })))
56
- const shared = new Set() // squares this person holds and has shared with the session's other people
57
- const seamTool = async (b) => {
58
- const q = session.quilt
59
- if (!q || !q.id) return { content: [{ type: 'text', text: 'This session is not a quilt, so it has no Seam tools.' }], isError: true }
60
- const branch = session.squareBranchKey ? session.squareBranchKey() : session.branchKey()
61
- const at = squareFor(q, branch)
62
- const square = at ? at.square : ((q.squares || {})[branch] || null)
63
- const fail = (text) => ({ content: [{ type: 'text', text }], isError: true })
64
- // The folder's live block on that square: the folder itself, following it in place, or a
65
- // separate one (session-follow.js). Its commit is `quilt commit`'s: what the relay holds.
66
- const f = session.squareFollower
67
- const here = f && f.here && at && f.here.square === at.square ? f.here : null
68
- const sep = f && f.following && at && f.following.square === at.square ? f.following : null
69
- const live = (here && here.block) || (sep && sep.block) || null
70
- if (here && !here.block && (b.tool === 'seam_commit' || b.tool === 'seam_merge')) return fail(here.problem ? `This folder can't follow its square yet (${here.problem}); Quilt tries again by itself.` : 'This folder is still starting to follow its square; try again in a moment.')
71
- let c
72
- try { c = await seam.client(q.id, square ? [square] : []) } catch (err) { return fail(err.message) }
73
- // The folder's live work is read and committed as this member.
74
- if (live) live.client = c.client
75
- if (c.person && square && !shared.has(square)) {
76
- shared.add(square)
77
- // The square's holder shares it with the session's other people, so their AIs (working for them) write there too.
78
- shareWithPeople(c.client, q.id, square, session.members || []).catch(() => shared.delete(square))
79
- }
80
- const next = at ? async () => session.conn.branchRequest({ op: 'quilt-next', token: c.token, branch }, { timeoutMs: QUILT_MOVE_TIMEOUT_MS }) : null
81
- // Open held conflicts (held.js) keep their paths from landing until they are resolved.
82
- return runSessionSeamTool(String(b.tool || ''), b.args || {}, { client: c.client, quilt: q.id, square, live, next, branch, held: () => (session.heldList ? session.heldList() : []) })
83
- }
84
- // The app's square panel (ui-server.js) commits and merges through the same tools, as the same member.
85
- session.seamTool = seamTool
86
46
  // Every open held conflict in the session (held.js), whoever's, first among the notices every MCP answer
87
47
  // starts with (an older `quilt mcp` too), until someone resolves it. Not taken: said again each time.
88
48
  const heldFirst = (b) => {
@@ -145,31 +105,10 @@ export async function startControl (session, extras = {}) {
145
105
  'POST /chat-link/extend': (b) => session.extendChatLink(String(b.who || ''), b.minutes),
146
106
  'POST /agent': (b) => { session.addAgent(b.client); return { ok: true } },
147
107
  'POST /feed': (b) => ({ entries: session.agentFeedFor(b.who, { limit: Math.min(Number(b.limit) || 40, 300) }) }),
148
- // The chronology: { path, by, since, task, limit } (see Session.historyQuery).
149
- // In a session linked to a quilt (Seam), the quilt's log too (Session.historyLinked): { entries, note? }.
150
- 'POST /history': (b) => session.historyLinked(b),
108
+ // The chronology: { path, by, since, task, limit } (see Session.historyQuery), as { entries }.
109
+ 'POST /history': (b) => ({ entries: session.historyQuery(b) }),
151
110
  'GET /tree': () => session.tree(),
152
111
  'POST /sharing': (b) => ({ on: session.setAgentSharing(b.on !== false) }),
153
- // `quilt session migrate --dry-run`: what making the session a quilt would do (the relay's dry run).
154
- 'POST /quilt-plan': () => session.quiltPlan(),
155
- // The quilt this session is (Seam), as the relay last said; null while it is not (session-seam.js).
156
- 'GET /quilt': () => ({ quilt: session.quilt || null }),
157
- // One of Seam's tools (session-seam.js SEAM_SESSION_TOOLS), { tool, args }: an MCP tool result.
158
- 'POST /seam': (b) => seamTool(b),
159
- // `quilt session migrate`: the relay makes the session a quilt, as its owner (their sign-in).
160
- 'POST /quilt-migrate': () => session.quiltMigrate(process.env.SEAM_TOKEN || (readAccount() || {}).token),
161
- // "Make this a quilt" (`quilt session migrate`, the app's button): made a quilt and moved into its squares in one go.
162
- 'POST /quilt-make': () => session.quiltMake(process.env.SEAM_TOKEN || (readAccount() || {}).token),
163
- // `quilt session migrate --switch` / `--back`: the session's files into its squares (layout 3), or back.
164
- 'POST /quilt-switch': () => session.quiltSwitch(process.env.SEAM_TOKEN || (readAccount() || {}).token),
165
- 'POST /quilt-unswitch': (b) => session.quiltUnswitch(process.env.SEAM_TOKEN || (readAccount() || {}).token, Array.isArray(b.carried) ? b.carried : []),
166
- // `quilt session migrate --shadow <quilt>`: link the session to the quilt an import of its git remote fills (16 step 1).
167
- 'POST /quilt-shadow': (b) => session.quiltShadowLink(process.env.SEAM_TOKEN || (readAccount() || {}).token, b.quilt ?? null),
168
- // `quilt session follow <folder>`: at layout 3, that folder follows this branch's square, live.
169
- 'POST /quilt-follow': (b) => session.quiltFollow(null, b.dir),
170
- // `quilt commit <message>`: at layout 3, the square this folder follows is committed, as this person.
171
- 'POST /square-commit': (b) => session.squareCommit(String(b.message || '')),
172
-
173
112
  'POST /work': (b) => {
174
113
  if (b.state === 'working') session.personaSays(b.via, b.note)
175
114
  const work = session.setWork(b.state, b.note)
@@ -216,9 +155,6 @@ export async function startControl (session, extras = {}) {
216
155
  // Held conflicts (held.js): the list (quilt_resolve_merge without a how), and resolving one { ref, how } (any member, any conflict).
217
156
  'GET /held': () => ({ held: session.heldList ? session.heldList() : [] }),
218
157
  'POST /resolve-merge': (b) => session.resolveHeld({ ref: String(b.ref || ''), how: String(b.how || ''), via: b.via ? String(b.via) : null }),
219
- // The session's stale_write_minutes (Seam's 07): { minutes }; only the owner sets it.
220
- 'GET /stale-write': () => session.staleWrite(),
221
- 'POST /stale-write': (b) => session.setStaleWrite(b.minutes),
222
158
  // Secrets (`quilt run`, quilt_secret_names): asked of the API as this session's own identity
223
159
  // (its person, or the agent it runs as). Run tokens and names only: never a value.
224
160
  'POST /secrets/run': async (b) => createRun(await secretsApi(), { room: session.room, label: String(b.label || '').slice(0, 200) }),
@@ -260,7 +196,7 @@ export async function startControl (session, extras = {}) {
260
196
  const auth = await secretsApi()
261
197
  return { text: await runAppTool(b.tool, b.args && typeof b.args === 'object' ? b.args : {}, { call: (method, route, body) => apiCall(auth, method, route, body, 40_000), room: session.room }) }
262
198
  },
263
- // `version` and `features` (what this app tells the relay it can do): the CLI checks them before a move (bin/quilt.js).
199
+ // `version` and `features`: this app's version and what it tells the relay it can do.
264
200
  'GET /info': (b) => ({ room: session.room, dir: session.root, name: session.actorName(b.via), person: session.name, kind: session.kind, invite: extras.invite || null, viewInvite: extras.viewInvite || null, access: session.access, pid: process.pid, version: appVersion(), features: session.features || FEATURES })
265
201
  }
266
202
  const server = http.createServer(async (req, res) => {
@@ -348,10 +284,10 @@ export function findDaemon (start = process.env.QUILT_DIR || process.cwd()) {
348
284
  const appVersion = () => { try { return currentVersion() } catch { return '' } }
349
285
 
350
286
  /**
351
- * `timeoutMs`: give up (throw) when the session hasn't answered by then (git's helpers: git must never wait on Quilt).
352
- * Without it, it waits as long as the session takes (a move into Seam can take minutes): node:http, not fetch, whose
353
- * own limit gave up after 5 minutes with nothing but "fetch failed". A session that can't be reached, or that
354
- * stopped while answering, throws with what happened and what to do (`unreachable`).
287
+ * `timeoutMs`: give up (throw) when the session hasn't answered by then.
288
+ * Without it, it waits as long as the session takes: node:http, not fetch, whose own limit gave up after
289
+ * 5 minutes with nothing but "fetch failed". A session that can't be reached, or that stopped while
290
+ * answering, throws with what happened and what to do (`unreachable`).
355
291
  */
356
292
  export function call (daemon, method, route, body, { timeoutMs = 0 } = {}) {
357
293
  const data = body ? JSON.stringify(body) : null
@@ -394,7 +330,7 @@ export function call (daemon, method, route, body, { timeoutMs = 0 } = {}) {
394
330
  /**
395
331
  * The control server couldn't be reached (nothing listens: the app closed this session or restarted), or
396
332
  * it closed the connection before answering (the session stopped meanwhile: left, quit, or sent away by
397
- * the relay). `cut` tells the two apart for callers that say more (a move into Seam goes on without the app).
333
+ * the relay). The error says which, with what to do.
398
334
  */
399
335
  export function unreachable (daemon, err) {
400
336
  const code = (err && err.code) || ''
@@ -403,18 +339,5 @@ export function unreachable (daemon, err) {
403
339
  const msg = cut
404
340
  ? `Quilt's app${where} stopped answering in the middle of this (${code || err.message}): the session there stopped (left, Quilt quit or restarted, or the relay sent this app away to update). Open the session in Quilt again, then check before trying again.`
405
341
  : `Quilt's app${where} isn't answering: the session there is not running any more (Quilt quit, restarted, or left it). Open it in Quilt (or run quilt join here), then try again.`
406
- return Object.assign(new Error(msg), { unreachable: true, cut, code })
407
- }
408
-
409
- /**
410
- * Why `quilt session migrate` (or --switch, --back) must not start through this app, from its GET /info,
411
- * or null. The move ends by sending away every app that can't follow a square (no `quilt-folders`): the
412
- * owner's own app too, cutting this command's answer off mid-way. An app older than this check says
413
- * neither its features nor its version; `cliVersion` is the quilt command's own.
414
- */
415
- export function moveRefusal (info, cliVersion = '') {
416
- const features = info && typeof info.features === 'string' ? info.features.split(',') : null
417
- if (features && features.includes('quilt-folders')) return null
418
- const was = info && info.version ? ` (${info.version})` : ''
419
- return `Quilt's app for this folder${was} is older than this quilt command${cliVersion ? ` (${cliVersion})` : ''}: the move sends it away to update at the end, and this command would lose its answer. Update Quilt, or restart it so it runs the new version, then run this again.`
342
+ return Object.assign(new Error(msg), { unreachable: true, code })
420
343
  }
package/src/fsutil.js CHANGED
@@ -29,7 +29,7 @@ export function closeWatcher (w) {
29
29
  export function loadIgnore (root) {
30
30
  const ig = makeIgnore()
31
31
  // A submodule (.gitmodules) is a repository of its own that git keeps as one commit id: its files
32
- // are its own git's, never the session's (nor a Seam square's, which holds it as a gitlink).
32
+ // are its own git's, never the session's.
33
33
  for (const p of submodulePaths(root)) ig.add(`/${p}`)
34
34
  const visit = (dirRel) => {
35
35
  const dir = path.join(root, dirRel)
@@ -0,0 +1,70 @@
1
+ // A folder's .git that an older Quilt set aside, put back. Before 0.3.175 Quilt could move a folder's .git into
2
+ // .quilt/git-before-seam, with a note beside it of the branch it was on, its linked worktrees and the lock it
3
+ // put on a worktree. Nothing sets a .git aside any more; a session gives it back when it starts. The folder
4
+ // name and the lock's text are the ones those versions wrote, so they stay as they are.
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+
8
+ export const GIT_ASIDE = path.join('.quilt', 'git-before-seam')
9
+
10
+ /** The folder's .git set aside by an older Quilt: { branch, at, kind } (from its note), or null. */
11
+ export function gitAsideOf (root) {
12
+ const aside = path.join(root, GIT_ASIDE)
13
+ try { fs.lstatSync(aside) } catch { return null }
14
+ try { return JSON.parse(fs.readFileSync(`${aside}.json`, 'utf8')) } catch { return { branch: null } }
15
+ }
16
+
17
+ // What an older Quilt wrote into a worktree's admin folder in its repository (git worktree lock) while its
18
+ // .git was aside: the exact text, so only that lock is removed.
19
+ const LOCK_REASON = 'Quilt: this worktree follows a Seam square, with its .git set aside in .quilt/git-before-seam; Quilt unlocks it when git comes back.\n'
20
+
21
+ /** Where a worktree's .git file points (its repository's .git/worktrees/<name>), or null. */
22
+ function worktreeAdmin (gitFile) {
23
+ try {
24
+ const m = /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(gitFile, 'utf8'))
25
+ return m ? path.resolve(path.dirname(gitFile), m[1].trim()) : null
26
+ } catch { return null }
27
+ }
28
+ /** Where a worktree's .git pointer file is: at its .git, or still set aside in its own .quilt. */
29
+ const pointerPlaces = (file) => [file, path.join(path.dirname(file), GIT_ASIDE)]
30
+
31
+ /**
32
+ * Rewrites a worktree's .git pointer file in place, wherever it is now (pointerPlaces), when `was(text)`
33
+ * says it is the one expected: through an open handle, never by making the file anew, so a worktree
34
+ * whose own .git is still aside finds it in its .quilt and not a new .git in its folder. Whether it wrote.
35
+ */
36
+ function rewritePointer (file, text, was) {
37
+ for (const at of pointerPlaces(file)) {
38
+ let fd
39
+ try { if (!fs.statSync(at).isFile()) continue; fd = fs.openSync(at, 'r+') } catch { continue }
40
+ try {
41
+ if (!was(fs.readFileSync(fd, 'utf8'))) return false
42
+ fs.ftruncateSync(fd, 0)
43
+ fs.writeSync(fd, text, 0)
44
+ return true
45
+ } catch { return false } finally { fs.closeSync(fd) }
46
+ }
47
+ return false
48
+ }
49
+
50
+ /** Puts the .git set aside back (one rename): true when it did; false with nothing aside, or with a new .git in the way (both kept). */
51
+ export function putGitBack (root) {
52
+ const git = path.join(root, '.git')
53
+ const aside = path.join(root, GIT_ASIDE)
54
+ const note = gitAsideOf(root)
55
+ if (!note) return false
56
+ try { fs.lstatSync(git); return false } catch {}
57
+ fs.renameSync(aside, git)
58
+ // Its linked worktrees' pointers, as they were (one changed since is left as it is).
59
+ for (const w of note.worktrees || []) rewritePointer(w.file, w.was, (now) => now.includes(GIT_ASIDE))
60
+ fs.rmSync(`${aside}.json`, { force: true })
61
+ // The lock this set, and only that one (someone may have locked the worktree since, for their own reason):
62
+ // where it was set, or where its repository's .git is now (set aside meanwhile, its pointer says).
63
+ if (note.locked) {
64
+ for (const admin of new Set([note.locked, worktreeAdmin(git)].filter(Boolean))) {
65
+ const lock = path.join(admin, 'locked')
66
+ try { if (fs.readFileSync(lock, 'utf8') === LOCK_REASON) fs.rmSync(lock, { force: true }) } catch {}
67
+ }
68
+ }
69
+ return true
70
+ }
@@ -1,5 +1,4 @@
1
- // R3 removed GitHub commits; only this pure helper stays, because test/unit/history.test.js (in
2
- // another square, sq:09a100d0) still imports it from here. Delete this file with that test's import.
1
+ // The one pure helper left of Quilt's own GitHub commits: test/unit/history.test.js imports it from here.
3
2
  import { blameChange } from './history.js'
4
3
 
5
4
  /** Who besides `me` made the changes in one text file's edit (history.js blameChange). */
@@ -0,0 +1,326 @@
1
+ // What git is doing to a synced folder. Quilt only reads git here: which branch (or commit) the
2
+ // folder is on, whether git is at work in it, and what a file looked like at a commit, so a
3
+ // checkout of another branch is told apart from edits and the folder can follow its branch
4
+ // (session.js). Nothing here writes to git, fetches, or talks to a remote. Every git call is
5
+ // asynchronous (the app's window and its relay connection never wait on git); the file reads
6
+ // below are synchronous.
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+ import { execFile } from 'node:child_process'
10
+ import { watch } from 'chokidar'
11
+ import { looksBinary, sha1, MAX_STORED_BINARY_BYTES, closeWatcher } from './fsutil.js'
12
+
13
+ export const GIT_TIMEOUT_MS = 5000
14
+ // A hold ends this long after the last file or git event in the folder.
15
+ export const SETTLE_MS = 500
16
+ // An index.lock this old, with no other operation under way, may be one a crashed git left behind.
17
+ export const STALE_LOCK_MS = 60 * 1000
18
+
19
+ // What marks git at work in a folder: its index lock, and the operations that take HEAD off its
20
+ // branch until they finish (a rebase, a bisect).
21
+ const MARKERS = [
22
+ ['index.lock', 'index-lock'], ['rebase-merge', 'rebase'], ['rebase-apply', 'rebase'], ['BISECT_LOG', 'bisect']
23
+ ]
24
+
25
+ // Output read in one go: a listing of a big repository, or a batch of files (see filesAt).
26
+ const MAX_OUTPUT = 256 * 1024 * 1024
27
+ // More paths than this are not passed on the command line: the whole tree is asked, and filtered.
28
+ const MAX_PATHSPECS = 200
29
+
30
+ /** Runs git: its output (a string, or a Buffer with `buffer`), or null when it fails. */
31
+ async function run (root, args, opts) {
32
+ return (await call(root, args, opts)).out
33
+ }
34
+
35
+ const gitBinary = () => process.env.QUILT_GIT || 'git'
36
+
37
+ /**
38
+ * Runs git: { out } or, when it fails, { out: null, missing, timedOut }
39
+ * (missing: the git binary could not be started at all; timedOut: it ran
40
+ * past GIT_TIMEOUT_MS and was stopped). Never rejects. Git is told to take
41
+ * no lock it can do without, so a read here never looks like git at work.
42
+ */
43
+ function call (root, args, { buffer = false, input, timeout = GIT_TIMEOUT_MS, env = {} } = {}) {
44
+ // QUILT_GIT lets tests point at a git binary that doesn't exist, to exercise
45
+ // the "git is unreachable" path without touching the real PATH.
46
+ const bin = gitBinary()
47
+ return new Promise((resolve) => {
48
+ const done = (out, missing, late, stderr = '') => resolve({ out, missing, timedOut: late, stderr })
49
+ let child
50
+ try {
51
+ child = execFile(bin, args, {
52
+ cwd: root,
53
+ encoding: buffer ? 'buffer' : 'utf8',
54
+ timeout,
55
+ maxBuffer: MAX_OUTPUT,
56
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', ...env }
57
+ }, (err, stdout, stderr) => {
58
+ if (!err) return done(stdout, false, false)
59
+ const missing = err.code === 'ENOENT' || err.code === 'EACCES'
60
+ done(null, missing, !missing && (err.killed === true || err.signal === 'SIGTERM'), String(stderr || ''))
61
+ })
62
+ } catch (err) { // a cwd that is gone, say
63
+ return done(null, err.code === 'ENOENT' || err.code === 'EACCES', false)
64
+ }
65
+ child.stdin.on('error', () => {}) // git may exit before reading all of it
66
+ child.stdin.end(input)
67
+ })
68
+ }
69
+
70
+ /** The branch .git/HEAD names (even one with no commits yet), or null (detached, or not a repo). No git call. */
71
+ export function headRef (root) {
72
+ const dir = gitDir(root)
73
+ if (!dir) return null
74
+ try {
75
+ const m = /^ref:\s*refs\/heads\/(.+)$/.exec(fs.readFileSync(path.join(dir, 'HEAD'), 'utf8').trim())
76
+ return m ? m[1] : null
77
+ } catch { return null }
78
+ }
79
+
80
+ /** A file's bytes as Quilt keys them (lastKnown, sharedKey): its text, or "bin:<sha1>". */
81
+ function keyOf (buf) {
82
+ return looksBinary(buf) ? `bin:${sha1(buf)}` : buf.toString('utf8')
83
+ }
84
+
85
+ /** The folder's .git directory (a worktree's .git file points at it), or null. */
86
+ export function gitDir (root) {
87
+ const dot = path.join(root, '.git')
88
+ let st
89
+ try { st = fs.statSync(dot) } catch { return null }
90
+ if (st.isDirectory()) return dot
91
+ try {
92
+ const m = /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(dot, 'utf8'))
93
+ if (!m) return null
94
+ const dir = path.resolve(root, m[1].trim())
95
+ return fs.existsSync(dir) ? dir : null
96
+ } catch { return null }
97
+ }
98
+
99
+ /**
100
+ * Where HEAD points, read from .git/HEAD alone (no git call): a branch's name, `@<12 hex>` for a
101
+ * detached commit, or null (not a repo, or unreadable). The same key headKey gives.
102
+ */
103
+ export function headName (root) {
104
+ const dir = gitDir(root)
105
+ if (!dir) return null
106
+ let head
107
+ try { head = fs.readFileSync(path.join(dir, 'HEAD'), 'utf8').trim() } catch { return null }
108
+ const ref = /^ref:\s*refs\/heads\/(.+)$/.exec(head)
109
+ if (ref) return ref[1]
110
+ return /^[0-9a-f]{40,64}$/.test(head) ? `@${head.slice(0, 12)}` : null
111
+ }
112
+
113
+ /**
114
+ * Where HEAD points: a branch, or a detached commit. Null when the folder is not a
115
+ * repo, when git is unreachable (sha lookup fails), or on an unborn branch (a fresh
116
+ * `git init` with no commits yet): in every case there's nothing to compare against.
117
+ */
118
+ export async function headKey (root) {
119
+ const dir = gitDir(root)
120
+ if (!dir) return null
121
+ let head
122
+ try { head = fs.readFileSync(path.join(dir, 'HEAD'), 'utf8').trim() } catch { return null }
123
+ const sha = ((await run(root, ['rev-parse', '--verify', '-q', 'HEAD'])) || '').trim() || null
124
+ if (!sha) return null
125
+ const ref = /^ref:\s*refs\/heads\/(.+)$/.exec(head)
126
+ if (ref) return { key: ref[1], branch: ref[1], sha }
127
+ return { key: `@${sha.slice(0, 12)}`, branch: null, sha }
128
+ }
129
+
130
+ /** The commit a branch points at (wherever HEAD is), or null. */
131
+ export async function branchTip (root, branch) {
132
+ if (!branch || !gitDir(root)) return null
133
+ return ((await run(root, ['rev-parse', '--verify', '-q', `refs/heads/${branch}^{commit}`])) || '').trim() || null
134
+ }
135
+
136
+ /**
137
+ * The git operation in progress in this folder, or null. `dir` lets a caller
138
+ * that already has it skip re-resolving it. `leftover`: an index.lock known to
139
+ * be left behind (its lockStamp, from leftoverLock), not counted.
140
+ */
141
+ export function busy (root, dir = gitDir(root), leftover = null) {
142
+ if (!dir) return null
143
+ for (const [file, kind] of MARKERS) {
144
+ if (!fs.existsSync(path.join(dir, file))) continue
145
+ if (kind === 'index-lock' && leftover && lockStamp(root, dir) === leftover) continue
146
+ return kind
147
+ }
148
+ return null
149
+ }
150
+
151
+ /** Which index.lock is there (its mtime and inode), or null. A new lock is another stamp. */
152
+ export function lockStamp (root, dir = gitDir(root)) {
153
+ if (!dir) return null
154
+ try { const st = fs.statSync(path.join(dir, 'index.lock')); return `${st.mtimeMs}:${st.ino}` } catch { return null }
155
+ }
156
+
157
+ /**
158
+ * The index.lock's stamp when it looks left behind by a git that crashed: the
159
+ * only marker of an operation, older than STALE_LOCK_MS, and `git status`
160
+ * runs. Null otherwise. The file is never touched: deleting it is yours to do.
161
+ */
162
+ export async function leftoverLock (root, now = Date.now()) {
163
+ const dir = gitDir(root)
164
+ if (busy(root, dir) !== 'index-lock') return null
165
+ const stamp = lockStamp(root, dir)
166
+ if (!stamp || busy(root, dir, stamp)) return null // another operation under way too
167
+ if (now - Number(stamp.split(':')[0]) < STALE_LOCK_MS) return null
168
+ if (await run(root, ['status', '--porcelain', '--untracked-files=no']) === null) return null
169
+ return lockStamp(root, dir) === stamp ? stamp : null
170
+ }
171
+
172
+ /** A cheap signal that git wrote the index (stash, reset, checkout, add...). Editors never do. */
173
+ export function indexStamp (root) {
174
+ const dir = gitDir(root)
175
+ if (!dir) return null
176
+ try { const st = fs.statSync(path.join(dir, 'index')); return `${st.mtimeMs}:${st.size}` } catch { return null }
177
+ }
178
+
179
+ /**
180
+ * Several files at one commit, in a few git calls whatever their number:
181
+ * rel -> key (the file as Quilt keys it: its text, or "bin:<sha1>", as checkout
182
+ * would write it), null (not there), or undefined (not read: bigger than Quilt
183
+ * shares, behind a filter such as Git LFS, or a git call failed). `out.failed`
184
+ * counts the files a failed git call left unread. Null only when git itself
185
+ * can't be run.
186
+ */
187
+ export async function filesAt (root, sha, rels) {
188
+ const out = new Map()
189
+ out.failed = 0
190
+ if (!rels.length) return out
191
+ const unread = (list) => { for (const rel of list) out.set(rel, undefined); out.failed += list.length }
192
+ // Sizes first, so a huge file can't overflow the read of the contents.
193
+ const check = await call(root, ['cat-file', '--batch-check=%(objectname) %(objecttype) %(objectsize)'], { input: rels.map((r) => `${sha}:${r}\n`).join('') })
194
+ if (check.missing) return null
195
+ const lines = check.out === null ? [] : check.out.split('\n').slice(0, rels.length)
196
+ if (lines.length !== rels.length) { unread(rels); return out }
197
+ // A path with a filter (Git LFS, say) is never read: its smudged size is unknown (the blob is
198
+ // a pointer), and running the filter can be slow or fail. The attributes are asked in one call.
199
+ const filtered = await filterOf(root, rels)
200
+ if (filtered === null) { unread(rels); return out }
201
+ const fetch = [] // [rel, blob id, size]
202
+ rels.forEach((rel, i) => {
203
+ const [id, type, size] = lines[i].split(' ')
204
+ if (type !== 'blob' || !/^\d+$/.test(size)) out.set(rel, null) // "<name> missing", or a folder there
205
+ else if (Number(size) > MAX_STORED_BINARY_BYTES || filtered.has(rel)) out.set(rel, undefined)
206
+ else fetch.push([rel, id, Number(size)])
207
+ })
208
+ // With --filters each line is "<blob> <path>": the path picks the line-ending conversion, as
209
+ // checkout would. That can change a size, so each file's own size is read from the batch's headers.
210
+ // Older git (2.34, say, as many Windows machines have) gives the blob's own size there instead, so where
211
+ // the conversion changes the length the size is checked: the content must end on the newline before the
212
+ // next header (or the end). Where it doesn't, the rest are read one at a time, which is exact.
213
+ const one = async (rel, id) => {
214
+ const r = await call(root, ['cat-file', '--filters', `--path=${rel}`, id], { buffer: true })
215
+ if (r.missing) return false
216
+ if (r.out === null) { unread([rel]); return true }
217
+ const key = keyOf(r.out)
218
+ out.set(rel, key.startsWith(LFS_POINTER) ? undefined : key)
219
+ return true
220
+ }
221
+ const HEADER = /^[0-9a-f]{40,64} (blob \d+|missing)$/
222
+ const read = async (chunk) => {
223
+ const buf = await call(root, ['cat-file', '--batch', '--filters'], { buffer: true, input: chunk.map(([rel, id]) => `${id} ${rel}\n`).join('') })
224
+ if (buf.missing) return false
225
+ if (buf.out === null) { unread(chunk.map(([rel]) => rel)); return true }
226
+ let at = 0
227
+ for (let i = 0; i < chunk.length; i++) {
228
+ const rel = chunk[i][0]
229
+ const nl = buf.out.indexOf(10, at)
230
+ const header = nl < 0 ? '' : buf.out.subarray(at, nl).toString('utf8')
231
+ if (/ missing$/.test(header)) { out.set(rel, null); at = nl + 1; continue }
232
+ const size = Number(header.split(' ')[2])
233
+ if (nl < 0 || !Number.isInteger(size)) { unread(chunk.slice(i).map(([r]) => r)); return true }
234
+ const end = nl + 1 + size
235
+ const last = i === chunk.length - 1
236
+ const after = last ? '' : buf.out.subarray(end + 1, buf.out.indexOf(10, end + 1)).toString('utf8')
237
+ if (buf.out[end] !== 10 || (last ? end + 1 !== buf.out.length : !HEADER.test(after))) {
238
+ for (const [r, id] of chunk.slice(i)) if (!(await one(r, id))) return false
239
+ return true
240
+ }
241
+ const key = keyOf(buf.out.subarray(nl + 1, end))
242
+ out.set(rel, key.startsWith(LFS_POINTER) ? undefined : key) // an LFS pointer is not the file
243
+ at = end + 1
244
+ }
245
+ return true
246
+ }
247
+ let chunk = []; let bytes = 0
248
+ for (const f of fetch) {
249
+ if (chunk.length && bytes + f[2] > MAX_OUTPUT / 4) {
250
+ if (!(await read(chunk))) return null
251
+ chunk = []; bytes = 0
252
+ }
253
+ chunk.push(f); bytes += f[2]
254
+ }
255
+ if (chunk.length && !(await read(chunk))) return null
256
+ return out
257
+ }
258
+
259
+ const LFS_POINTER = 'version https://git-lfs'
260
+
261
+ /** The paths with a `filter` attribute set (in .gitattributes), or null when git failed. */
262
+ async function filterOf (root, rels) {
263
+ const out = await run(root, ['check-attr', '-z', '--stdin', 'filter'], { input: rels.join('\0') + '\0' })
264
+ if (out === null) return null
265
+ const f = out.split('\0')
266
+ const filtered = new Set()
267
+ for (let i = 0; i + 2 < f.length; i += 3) if (f[i + 2] !== 'unspecified' && f[i + 2] !== 'unset') filtered.add(f[i])
268
+ return filtered
269
+ }
270
+
271
+ /** A file's bytes at commit `sha`, as checkout would write it (null when git can't say). */
272
+ export async function blobAt (root, sha, rel) {
273
+ const out = await run(root, ['cat-file', '--filters', `${sha}:${rel}`], { buffer: true })
274
+ return out === null ? null : out
275
+ }
276
+
277
+ /**
278
+ * What git says about `paths` now (all of the folder with none), in two git calls whatever
279
+ * their number: `dirty` (changed, staged, untracked or conflicted), `unmerged` (a conflict
280
+ * git left for the person to resolve) and `tracked` (in the index). Null when git fails.
281
+ */
282
+ export async function treeState (root, paths) {
283
+ const spec = paths.length <= MAX_PATHSPECS ? ['--', ...paths] : []
284
+ const status = await run(root, ['--literal-pathspecs', 'status', '--porcelain=v2', '-z', '--untracked-files=all', ...spec])
285
+ if (status === null) return null // not asking for the second when the first failed (or timed out)
286
+ const listed = await run(root, ['--literal-pathspecs', 'ls-files', '-z', ...spec])
287
+ if (listed === null) return null
288
+ const dirty = new Set()
289
+ const unmerged = new Set()
290
+ const f = status.split('\0')
291
+ for (let i = 0; i < f.length; i++) {
292
+ const e = f[i]
293
+ if (e[0] === '1') dirty.add(e.split(' ').slice(8).join(' '))
294
+ else if (e[0] === '2') dirty.add(e.split(' ').slice(9).join(' ')).add(f[++i]) // renamed: both paths
295
+ else if (e[0] === 'u') {
296
+ const rel = e.split(' ').slice(10).join(' ')
297
+ dirty.add(rel)
298
+ unmerged.add(rel)
299
+ } else if (e[0] === '?' || e[0] === '!') dirty.add(e.slice(2))
300
+ }
301
+ return { dirty, unmerged, tracked: new Set(listed.split('\0').filter(Boolean)) }
302
+ }
303
+
304
+ /**
305
+ * Watches the folder's .git for HEAD moving, the index being written and git starting or
306
+ * finishing work (see busy); events: head, index, busy, idle.
307
+ */
308
+ export function watchGit (root, onEvent) {
309
+ const dir = gitDir(root)
310
+ if (!dir) return { close: async () => {} }
311
+ const names = new Set(['HEAD', 'index', ...MARKERS.map(([f]) => f)])
312
+ let wasBusy = !!busy(root, dir)
313
+ const watcher = watch(dir, { ignoreInitial: true, depth: 0, followSymlinks: false })
314
+ const onAny = (p) => {
315
+ const name = path.basename(p)
316
+ if (!names.has(name)) return
317
+ if (name === 'HEAD') onEvent({ type: 'head' })
318
+ else if (name === 'index') onEvent({ type: 'index' })
319
+ else {
320
+ const now = !!busy(root, dir)
321
+ if (now !== wasBusy) { wasBusy = now; onEvent({ type: now ? 'busy' : 'idle' }) }
322
+ }
323
+ }
324
+ watcher.on('add', onAny).on('change', onAny).on('unlink', onAny).on('addDir', onAny).on('unlinkDir', onAny).on('error', () => {})
325
+ return { close: () => closeWatcher(watcher) }
326
+ }