heyquilt 0.3.175 → 0.3.177

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/RELEASES.md CHANGED
@@ -11,6 +11,29 @@ Format: `## <version> — <YYYY-MM-DD>`, an optional one-line summary, then bull
11
11
  Lead each bullet with a short bold phrase. Inline `code` and **bold** are rendered;
12
12
  nothing else is.
13
13
 
14
+ ## 0.3.177 — 2026-11-17
15
+
16
+ - **No more boxes.** Every edit is shared with everyone as it is made, in a git folder or any other. Nothing is kept out of your folder until someone commits it, and there is nothing to unpack.
17
+ - **The left pane is People.** It lists who is in the session and what each is working on, as before, without the boxes under each name. Folded, it shows everyone's face; click one to open it again.
18
+ - **AIs are no longer told about boxes.** `quilt_unpack` is gone, and `quilt_status`, `quilt_list_files`, the edit check and the guide your AI gets no longer mention boxed work.
19
+ - **Older apps keep working.** An app from before this version that asks to keep a file out of other folders is told nothing is kept, so its edit is shared like any other.
20
+ - **Commits come into your folder by themselves.** When a partner pushes, or a pull request is merged on GitHub, your branch moves forward to those commits within about a minute and your uncommitted work stays where it is. After a partner commits and pushes what you were both editing, your git shows nothing left to commit. There is nothing to pull.
21
+ - **Two cases are left to your own git, and Quilt says so.** If your branch has commits of its own that the remote doesn't, or a new commit changed the same lines as work you haven't committed, Quilt brings nothing in and tells you and your AI why, once, with the pull command to use (`git pull --rebase --autostash`). `quilt_status` lists it under "Git". Files a partner's commit added that the session already put in your folder are staged for you, so git does not refuse the pull over them.
22
+ - **What AIs are told about git is true again.** The guide no longer promises task branches, pull requests opened or merged by Quilt, or git tools that don't exist. A test now checks that every tool the guide names is one Quilt has.
23
+
24
+ ## 0.3.176 — 2026-11-16
25
+
26
+ A clash stays in your own file for your AI to settle, the way git does it. And your folder follows the git branch you check out.
27
+
28
+ - **Your folder follows its git branch.** When you check out another branch in git (`git checkout`, `git switch`), your folder moves to that branch in the session by itself. The files git changed for the checkout are not sent to the branch you left, and nobody still on it gets them. A branch the session has not seen starts from your folder as git left it; on a branch the session already has, your folder gets the session's work there, uncommitted work included. Before this, the checkout went unnoticed and the other branch's files were shared as edits to the branch you started on.
29
+ - **Nothing is shared while git is at work.** While git is busy in your folder (a checkout, a pull, a stash, a rebase), Quilt takes nothing in from it and writes nobody's changes into it. It carries on about half a second after git is done, and nothing is lost: what you saved and what others changed meanwhile both arrive then.
30
+ - **Uncommitted work stays on its branch.** Work the session has on one branch, which git carries along when you switch, stays in the session on the branch it was made on. On a branch the session already has, your folder gets that branch's own files in its place.
31
+ - **Switched while Quilt was off.** When it starts again it joins the branch your folder is on now. What it had saved of the other branch is kept for when you go back, and is never mixed into this one.
32
+ - **A checkout of a commit** (a detached HEAD) gets a place of its own in the session, named after the commit. During a rebase or a bisect your folder stays on its branch and waits; what the rebase changed is shared when it is over.
33
+ - **Git may still ask you to stash first.** The session's uncommitted work is in your folder, so git refuses a checkout that would overwrite it, as it does with your own. `git stash` and then the checkout, one right after the other, is safe: neither is taken for an edit.
34
+ - **A clash stays in your file.** When your save changes the same lines someone else just changed, none of that save is shared. Your file gets both versions of those lines between conflict markers (`<<<<<<< mine`, `=======`, `>>>>>>> session`), with their other changes already merged in, and your AI is told why. Once it has settled them and saved, the file is shared. Nobody else ever gets a file with markers in it, and a partner's later change is never written over a file you are still settling.
35
+ - **No side record for it.** A clash between folders no longer parks your lines in a record that needs `quilt_resolve_merge`. Agents with no folder and apps before this version keep the old way for now.
36
+
14
37
  ## 0.3.175 — 2026-11-16
15
38
 
16
39
  Quilt works with git only: its own source control is gone from the app, the relay and the AI tools. Two rules that held saves which clashed with nothing are gone too, and a save made from an old copy of a file no longer erases a teammate's change.
package/bin/quilt.js CHANGED
@@ -30,7 +30,7 @@ Usage:
30
30
  With the key, status, messages, say, tasks, task, history,
31
31
  focus, tool and mcp work too
32
32
  quilt setup Connect Claude Code / Cursor / others via MCP
33
- quilt status Show collaborators, boxed work, activity, chat
33
+ quilt status Show collaborators, activity, chat
34
34
  quilt history [path] [--by name] [--since 2h] [--task id] [--diff] [-n 30]
35
35
  Who changed what, when, and for which task
36
36
  quilt chat Live chat (messages, DMs, files) in this terminal
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heyquilt",
3
- "version": "0.3.175",
3
+ "version": "0.3.177",
4
4
  "description": "Real-time, tool-agnostic pair vibe coding: sync a project folder live between collaborators using any AI coding tool.",
5
5
  "author": {
6
6
  "name": "Daniel Carmichael",
@@ -24,7 +24,7 @@ export const TASK_WORKFLOW =
24
24
  'When finished, move the ticket to QA (not straight to Done) with `qaNotes`: describe the changes you made and how you self-validated them. ' +
25
25
  'Keep qaNotes, verified and task comments brief: a few short sentences, no logs or play-by-play. ' +
26
26
  'Moving to Done still requires `verified` (what you ran and what you saw). Unit tests passing is not enough when the app itself was not exercised. ' +
27
- 'Taking a task puts your folder on a branch of your own for it (quilt/<you>/<task>). Get the task\'s files into git before you move it to QA: commit only those files and push the branch; Quilt opens the pull request and ties it to the task. Done merges that pull request once its checks pass: a person moves it to Done (you may, when the owner lets agents push to any branch). Without a folder, `quilt_git_commit` with the task (the pull request opens by itself); when agents may not commit, ask with `quilt_request_commit`. Work only in the session has not shipped.'
27
+ 'Get the task\'s files into git before you move it to QA: commit only the files you changed and push, on a branch of your own with a pull request you open yourself where the project works that way. Quilt does not commit, push, open pull requests or merge them for anyone. Without a folder you cannot commit: say in `qaNotes` which files need committing. Work only in the session has not shipped.'
28
28
 
29
29
  /** Markdown bullets for AGENTS.md / CLAUDE.md (same steps as TASK_WORKFLOW). */
30
30
  export const TASK_WORKFLOW_MD =
@@ -35,8 +35,8 @@ export const TASK_WORKFLOW_MD =
35
35
  ' 4. **Test** it: confirm the tests you touch pass, then run the project\'s own checks under "Verifying a change" below.\n' +
36
36
  ' 5. **QA**: move to `qa` (not straight to Done) with `qaNotes` describing the changes and how you self-validated them.\n' +
37
37
  ' Keep `qaNotes`, `verified` and task comments brief: a few short sentences, no logs or play-by-play.\n' +
38
- ' 6. **Done** (after QA): `quilt_move_task` to `done` needs `verified`, what you ran and what you saw. Unit tests passing is not enough when the app itself was not exercised. Done merges the task\'s pull request once its checks pass; when the owner keeps agents to branches of their own, a person moves it to Done.\n' +
39
- ' 7. **Commit and push** before QA: only the task\'s files, with a message, on the branch Quilt put your folder on when you took the task (quilt/<you>/<task>); Quilt opens the pull request. Without a folder, `quilt_git_commit` with the task. When agents may not commit, ask with `quilt_request_commit`. Work only in the session has not shipped.'
38
+ ' 6. **Done** (after QA): `quilt_move_task` to `done` needs `verified`, what you ran and what you saw. Unit tests passing is not enough when the app itself was not exercised.\n' +
39
+ ' 7. **Commit and push** before QA: only the files you changed, with a message; on a branch of your own with a pull request you open yourself, where the project works that way. Quilt does not commit, push or merge for anyone. Without a folder you cannot commit: say in `qaNotes` which files need committing. Work only in the session has not shipped.'
40
40
 
41
41
  /** Scaffolded into AGENTS.md by `quilt setup` when the project has no checklist yet. Owners edit it in place. */
42
42
  export const CHECKLIST_SCAFFOLD = `${CHECKLIST_HEADING}
package/src/connection.js CHANGED
@@ -6,7 +6,7 @@ import WebSocket from 'ws'
6
6
  import crypto from 'node:crypto'
7
7
  import * as Y from 'yjs'
8
8
  import {
9
- MSG_SYNC, MSG_AWARENESS, MSG_QUERY_AWARENESS, MSG_AUTH, MSG_CLAIM, MSG_CLAIMS,
9
+ MSG_SYNC, MSG_AWARENESS, MSG_QUERY_AWARENESS, MSG_AUTH,
10
10
  MSG_ACCESS, MSG_ADMIN, MSG_MEMBERS, MSG_PASS, MSG_BRANCH, MSG_BRANCHES,
11
11
  CLOSE_AUTH_FAILED, CLOSE_NAME_TAKEN, CLOSE_ROOM_FULL, CLOSE_DENIED, CLOSE_ENDED, CLOSE_PASS_EXPIRED,
12
12
  encoding, decoding, syncProtocol, awarenessProtocol,
@@ -430,11 +430,6 @@ export class Connection extends EventEmitter {
430
430
  const msg = JSON.parse(decoding.readVarString(dec))
431
431
  this.emit('members', msg)
432
432
  this.settle(msg.reply, 'request refused')
433
- } else if (type === MSG_CLAIMS) {
434
- // The room's boxes (the field keeps its old name): Quilt holds no files, so only boxes come here.
435
- const { claims, reply } = JSON.parse(decoding.readVarString(dec))
436
- this.emit('boxes', claims)
437
- this.settle(reply, 'box refused')
438
433
  }
439
434
  }
440
435
 
@@ -498,11 +493,13 @@ export class Connection extends EventEmitter {
498
493
  */
499
494
  async liveWrite (req, { baseOf = null, timeoutMs = REQUEST_TIMEOUT_MS } = {}) {
500
495
  if (this.branchKey === null) throw new Error('not on a branch')
501
- let r = await this.branchRequest({ op: 'live-write', branch: this.branchKey, ...req }, { timeoutMs })
496
+ // The branch the write was made on, asked again on that one: the folder may move to another meanwhile.
497
+ const branch = this.branchKey
498
+ let r = await this.branchRequest({ op: 'live-write', branch, ...req }, { timeoutMs })
502
499
  if (r.needBase) {
503
500
  const t = baseOf ? baseOf() : null
504
- r = await this.branchRequest({ op: 'live-write', branch: this.branchKey, ...req, ...(typeof t === 'string' ? { baseText: t } : { retry: true }) }, { timeoutMs })
505
- if (r.needBase) r = await this.branchRequest({ op: 'live-write', branch: this.branchKey, ...req, retry: true }, { timeoutMs })
501
+ r = await this.branchRequest({ op: 'live-write', branch, ...req, ...(typeof t === 'string' ? { baseText: t } : { retry: true }) }, { timeoutMs })
502
+ if (r.needBase) r = await this.branchRequest({ op: 'live-write', branch, ...req, retry: true }, { timeoutMs })
506
503
  }
507
504
  return r
508
505
  }
@@ -544,9 +541,6 @@ export class Connection extends EventEmitter {
544
541
  })
545
542
  }
546
543
 
547
- /** Asks the relay to box or unbox a file; resolves with its reply. Needs a live connection. */
548
- boxRequest (req) { return this.request(MSG_CLAIM, req, 'boxes') }
549
-
550
544
  /** Approve / deny / change / remove someone, or set who may admit (relay enforces who may). */
551
545
  adminRequest (req, { timeoutMs } = {}) { return this.request(MSG_ADMIN, req, 'changes to who is in the session', null, timeoutMs) }
552
546
 
package/src/control.js CHANGED
@@ -86,7 +86,6 @@ export async function startControl (session, extras = {}) {
86
86
  const remind = await wake.reminder()
87
87
  return { notices: [...heldFirst(b), ...notices, ...(remind ? [remind] : [])] }
88
88
  },
89
- 'POST /unpack': (b) => session.unpack(b.paths, b.via),
90
89
  // Before an agent changes files (any tool): who else changed them lately, and what did people say
91
90
  // about them? It never refuses (Session.prepareEdit, duties.js).
92
91
  'POST /before-edit': (b) => session.prepareEdit(Array.isArray(b.paths) ? b.paths.slice(0, 100) : [], b.via),
package/src/duties.js CHANGED
@@ -259,9 +259,8 @@ export function renderChatAbout (said, { now = Date.now(), max = 8 } = {}) {
259
259
  }
260
260
 
261
261
  /**
262
- * Who else wrote the files an agent is about to change lately, and whose unfinished work is boxed on
263
- * them (quilt_before_edit's `files`: [{ path, recent: [{ by, at }], box?: { by } }]). Presence, never a
264
- * hold: '' when nobody.
262
+ * Who else wrote the files an agent is about to change lately (quilt_before_edit's `files`:
263
+ * [{ path, recent: [{ by, at }] }]). Presence, never a hold: '' when nobody.
265
264
  */
266
265
  export function renderRecent (files, { now = Date.now() } = {}) {
267
266
  const lines = []
@@ -269,7 +268,6 @@ export function renderRecent (files, { now = Date.now() } = {}) {
269
268
  if (!f || !f.path) continue
270
269
  const who = (f.recent || []).filter((w) => w && w.by).map((w) => `${w.by} ${ago(w.at, now)}`)
271
270
  if (who.length) lines.push(`- ${f.path}: changed lately by ${who.join(', ')}`)
272
- if (f.box && f.box.by) lines.push(`- ${f.path}: ${f.box.by}'s unfinished work is boxed on it; your edit opens the box and merges with it`)
273
271
  }
274
272
  if (!lines.length) return ''
275
273
  return 'Others working on these files (nobody holds files: edit them; changes merge as they arrive, and a clash on the same lines comes back to you to resolve):\n' + lines.join('\n')
@@ -0,0 +1,475 @@
1
+ // What git is doing to a synced folder: which branch (or commit) the folder is on, whether git is
2
+ // at work in it, and what a file looked like at a commit, so a checkout of another branch is told
3
+ // apart from edits and the folder can follow its branch (session.js). Quilt does two things to git
4
+ // itself, both at the end of this file: it fetches the branch's upstream, and it moves the branch
5
+ // forward to a commit it is behind (never merging history). Every git call is asynchronous (the
6
+ // app's window and its relay connection never wait on git); the file reads 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, the operations that take HEAD off its branch
20
+ // until they finish (a rebase, a bisect), and the ones that stop on a conflict with git's own markers
21
+ // in the files until the person settles it (a merge, a cherry-pick, a revert).
22
+ const MARKERS = [
23
+ ['index.lock', 'index-lock'], ['rebase-merge', 'rebase'], ['rebase-apply', 'rebase'], ['BISECT_LOG', 'bisect'],
24
+ ['MERGE_HEAD', 'merge'], ['CHERRY_PICK_HEAD', 'cherry-pick'], ['REVERT_HEAD', 'revert']
25
+ ]
26
+
27
+ // Output read in one go: a listing of a big repository, or a batch of files (see filesAt).
28
+ const MAX_OUTPUT = 256 * 1024 * 1024
29
+ // More paths than this are not passed on the command line: the whole tree is asked, and filtered.
30
+ const MAX_PATHSPECS = 200
31
+ // Index locks this process holds (lockIndex): Quilt's own work, never git at work in the folder.
32
+ const ownLocks = new Set()
33
+
34
+ /** Runs git: its output (a string, or a Buffer with `buffer`), or null when it fails. */
35
+ async function run (root, args, opts) {
36
+ return (await call(root, args, opts)).out
37
+ }
38
+
39
+ const gitBinary = () => process.env.QUILT_GIT || 'git'
40
+
41
+ /**
42
+ * Runs git: { out } or, when it fails, { out: null, missing, timedOut }
43
+ * (missing: the git binary could not be started at all; timedOut: it ran
44
+ * past GIT_TIMEOUT_MS and was stopped). Never rejects. Git is told to take
45
+ * no lock it can do without, so a read here never looks like git at work.
46
+ */
47
+ function call (root, args, { buffer = false, input, timeout = GIT_TIMEOUT_MS, env = {} } = {}) {
48
+ // QUILT_GIT lets tests point at a git binary that doesn't exist, to exercise
49
+ // the "git is unreachable" path without touching the real PATH.
50
+ const bin = gitBinary()
51
+ return new Promise((resolve) => {
52
+ const done = (out, missing, late, stderr = '') => resolve({ out, missing, timedOut: late, stderr })
53
+ let child
54
+ try {
55
+ child = execFile(bin, args, {
56
+ cwd: root,
57
+ encoding: buffer ? 'buffer' : 'utf8',
58
+ timeout,
59
+ maxBuffer: MAX_OUTPUT,
60
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', ...env }
61
+ }, (err, stdout, stderr) => {
62
+ if (!err) return done(stdout, false, false)
63
+ const missing = err.code === 'ENOENT' || err.code === 'EACCES'
64
+ done(null, missing, !missing && (err.killed === true || err.signal === 'SIGTERM'), String(stderr || ''))
65
+ })
66
+ } catch (err) { // a cwd that is gone, say
67
+ return done(null, err.code === 'ENOENT' || err.code === 'EACCES', false)
68
+ }
69
+ child.stdin.on('error', () => {}) // git may exit before reading all of it
70
+ child.stdin.end(input)
71
+ })
72
+ }
73
+
74
+ /** The branch .git/HEAD names (even one with no commits yet), or null (detached, or not a repo). No git call. */
75
+ export function headRef (root) {
76
+ const dir = gitDir(root)
77
+ if (!dir) return null
78
+ try {
79
+ const m = /^ref:\s*refs\/heads\/(.+)$/.exec(fs.readFileSync(path.join(dir, 'HEAD'), 'utf8').trim())
80
+ return m ? m[1] : null
81
+ } catch { return null }
82
+ }
83
+
84
+ /** A file's bytes as Quilt keys them (lastKnown, sharedKey): its text, or "bin:<sha1>". */
85
+ function keyOf (buf) {
86
+ return looksBinary(buf) ? `bin:${sha1(buf)}` : buf.toString('utf8')
87
+ }
88
+
89
+ /** The folder's .git directory (a worktree's .git file points at it), or null. */
90
+ export function gitDir (root) {
91
+ const dot = path.join(root, '.git')
92
+ let st
93
+ try { st = fs.statSync(dot) } catch { return null }
94
+ if (st.isDirectory()) return dot
95
+ try {
96
+ const m = /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(dot, 'utf8'))
97
+ if (!m) return null
98
+ const dir = path.resolve(root, m[1].trim())
99
+ return fs.existsSync(dir) ? dir : null
100
+ } catch { return null }
101
+ }
102
+
103
+ /**
104
+ * Where HEAD points, read from .git/HEAD alone (no git call): a branch's name, `@<12 hex>` for a
105
+ * detached commit, or null (not a repo, or unreadable). The same key headKey gives.
106
+ */
107
+ export function headName (root) {
108
+ const dir = gitDir(root)
109
+ if (!dir) return null
110
+ let head
111
+ try { head = fs.readFileSync(path.join(dir, 'HEAD'), 'utf8').trim() } catch { return null }
112
+ const ref = /^ref:\s*refs\/heads\/(.+)$/.exec(head)
113
+ if (ref) return ref[1]
114
+ return /^[0-9a-f]{40,64}$/.test(head) ? `@${head.slice(0, 12)}` : null
115
+ }
116
+
117
+ /**
118
+ * Where HEAD points: a branch, or a detached commit. Null when the folder is not a
119
+ * repo, when git is unreachable (sha lookup fails), or on an unborn branch (a fresh
120
+ * `git init` with no commits yet): in every case there's nothing to compare against.
121
+ */
122
+ export async function headKey (root) {
123
+ const dir = gitDir(root)
124
+ if (!dir) return null
125
+ let head
126
+ try { head = fs.readFileSync(path.join(dir, 'HEAD'), 'utf8').trim() } catch { return null }
127
+ const sha = ((await run(root, ['rev-parse', '--verify', '-q', 'HEAD'])) || '').trim() || null
128
+ if (!sha) return null
129
+ const ref = /^ref:\s*refs\/heads\/(.+)$/.exec(head)
130
+ if (ref) return { key: ref[1], branch: ref[1], sha }
131
+ return { key: `@${sha.slice(0, 12)}`, branch: null, sha }
132
+ }
133
+
134
+ /** The commit a branch points at (wherever HEAD is), or null. */
135
+ export async function branchTip (root, branch) {
136
+ if (!branch || !gitDir(root)) return null
137
+ return ((await run(root, ['rev-parse', '--verify', '-q', `refs/heads/${branch}^{commit}`])) || '').trim() || null
138
+ }
139
+
140
+ /**
141
+ * The git operation in progress in this folder, or null. `dir` lets a caller
142
+ * that already has it skip re-resolving it. `leftover`: an index.lock known to
143
+ * be left behind (its lockStamp, from leftoverLock), not counted.
144
+ */
145
+ export function busy (root, dir = gitDir(root), leftover = null) {
146
+ if (!dir) return null
147
+ for (const [file, kind] of MARKERS) {
148
+ if (!fs.existsSync(path.join(dir, file))) continue
149
+ if (kind === 'index-lock' && ((leftover && lockStamp(root, dir) === leftover) || ownLocks.has(path.join(dir, file)))) continue
150
+ return kind
151
+ }
152
+ return null
153
+ }
154
+
155
+ /** Which index.lock is there (its mtime and inode), or null. A new lock is another stamp. */
156
+ export function lockStamp (root, dir = gitDir(root)) {
157
+ if (!dir) return null
158
+ try { const st = fs.statSync(path.join(dir, 'index.lock')); return `${st.mtimeMs}:${st.ino}` } catch { return null }
159
+ }
160
+
161
+ /**
162
+ * The index.lock's stamp when it looks left behind by a git that crashed: the
163
+ * only marker of an operation, older than STALE_LOCK_MS, and `git status`
164
+ * runs. Null otherwise. The file is never touched: deleting it is yours to do.
165
+ */
166
+ export async function leftoverLock (root, now = Date.now()) {
167
+ const dir = gitDir(root)
168
+ if (busy(root, dir) !== 'index-lock') return null
169
+ const stamp = lockStamp(root, dir)
170
+ if (!stamp || busy(root, dir, stamp)) return null // another operation under way too
171
+ if (now - Number(stamp.split(':')[0]) < STALE_LOCK_MS) return null
172
+ if (await run(root, ['status', '--porcelain', '--untracked-files=no']) === null) return null
173
+ return lockStamp(root, dir) === stamp ? stamp : null
174
+ }
175
+
176
+ /** A cheap signal that git wrote the index (stash, reset, checkout, add...). Editors never do. */
177
+ export function indexStamp (root) {
178
+ const dir = gitDir(root)
179
+ if (!dir) return null
180
+ try { const st = fs.statSync(path.join(dir, 'index')); return `${st.mtimeMs}:${st.size}` } catch { return null }
181
+ }
182
+
183
+ /**
184
+ * Several files at one commit, in a few git calls whatever their number:
185
+ * rel -> key (the file as Quilt keys it: its text, or "bin:<sha1>", as checkout
186
+ * would write it), null (not there), or undefined (not read: bigger than Quilt
187
+ * shares, behind a filter such as Git LFS, or a git call failed). `out.failed`
188
+ * counts the files a failed git call left unread. Null only when git itself
189
+ * can't be run.
190
+ */
191
+ export async function filesAt (root, sha, rels) {
192
+ const out = new Map()
193
+ out.failed = 0
194
+ if (!rels.length) return out
195
+ const unread = (list) => { for (const rel of list) out.set(rel, undefined); out.failed += list.length }
196
+ // Sizes first, so a huge file can't overflow the read of the contents.
197
+ const check = await call(root, ['cat-file', '--batch-check=%(objectname) %(objecttype) %(objectsize)'], { input: rels.map((r) => `${sha}:${r}\n`).join('') })
198
+ if (check.missing) return null
199
+ const lines = check.out === null ? [] : check.out.split('\n').slice(0, rels.length)
200
+ if (lines.length !== rels.length) { unread(rels); return out }
201
+ // A path with a filter (Git LFS, say) is never read: its smudged size is unknown (the blob is
202
+ // a pointer), and running the filter can be slow or fail. The attributes are asked in one call.
203
+ const filtered = await filterOf(root, rels)
204
+ if (filtered === null) { unread(rels); return out }
205
+ const fetch = [] // [rel, blob id, size]
206
+ rels.forEach((rel, i) => {
207
+ const [id, type, size] = lines[i].split(' ')
208
+ if (type !== 'blob' || !/^\d+$/.test(size)) out.set(rel, null) // "<name> missing", or a folder there
209
+ else if (Number(size) > MAX_STORED_BINARY_BYTES || filtered.has(rel)) out.set(rel, undefined)
210
+ else fetch.push([rel, id, Number(size)])
211
+ })
212
+ // With --filters each line is "<blob> <path>": the path picks the line-ending conversion, as
213
+ // checkout would. That can change a size, so each file's own size is read from the batch's headers.
214
+ // Older git (2.34, say, as many Windows machines have) gives the blob's own size there instead, so where
215
+ // the conversion changes the length the size is checked: the content must end on the newline before the
216
+ // next header (or the end). Where it doesn't, the rest are read one at a time, which is exact.
217
+ const one = async (rel, id) => {
218
+ const r = await call(root, ['cat-file', '--filters', `--path=${rel}`, id], { buffer: true })
219
+ if (r.missing) return false
220
+ if (r.out === null) { unread([rel]); return true }
221
+ const key = keyOf(r.out)
222
+ out.set(rel, key.startsWith(LFS_POINTER) ? undefined : key)
223
+ return true
224
+ }
225
+ const HEADER = /^[0-9a-f]{40,64} (blob \d+|missing)$/
226
+ const read = async (chunk) => {
227
+ const buf = await call(root, ['cat-file', '--batch', '--filters'], { buffer: true, input: chunk.map(([rel, id]) => `${id} ${rel}\n`).join('') })
228
+ if (buf.missing) return false
229
+ if (buf.out === null) { unread(chunk.map(([rel]) => rel)); return true }
230
+ let at = 0
231
+ for (let i = 0; i < chunk.length; i++) {
232
+ const rel = chunk[i][0]
233
+ const nl = buf.out.indexOf(10, at)
234
+ const header = nl < 0 ? '' : buf.out.subarray(at, nl).toString('utf8')
235
+ if (/ missing$/.test(header)) { out.set(rel, null); at = nl + 1; continue }
236
+ const size = Number(header.split(' ')[2])
237
+ if (nl < 0 || !Number.isInteger(size)) { unread(chunk.slice(i).map(([r]) => r)); return true }
238
+ const end = nl + 1 + size
239
+ const last = i === chunk.length - 1
240
+ const after = last ? '' : buf.out.subarray(end + 1, buf.out.indexOf(10, end + 1)).toString('utf8')
241
+ if (buf.out[end] !== 10 || (last ? end + 1 !== buf.out.length : !HEADER.test(after))) {
242
+ for (const [r, id] of chunk.slice(i)) if (!(await one(r, id))) return false
243
+ return true
244
+ }
245
+ const key = keyOf(buf.out.subarray(nl + 1, end))
246
+ out.set(rel, key.startsWith(LFS_POINTER) ? undefined : key) // an LFS pointer is not the file
247
+ at = end + 1
248
+ }
249
+ return true
250
+ }
251
+ let chunk = []; let bytes = 0
252
+ for (const f of fetch) {
253
+ if (chunk.length && bytes + f[2] > MAX_OUTPUT / 4) {
254
+ if (!(await read(chunk))) return null
255
+ chunk = []; bytes = 0
256
+ }
257
+ chunk.push(f); bytes += f[2]
258
+ }
259
+ if (chunk.length && !(await read(chunk))) return null
260
+ return out
261
+ }
262
+
263
+ const LFS_POINTER = 'version https://git-lfs'
264
+
265
+ /** The paths with a `filter` attribute set (in .gitattributes), or null when git failed. */
266
+ async function filterOf (root, rels) {
267
+ const out = await run(root, ['check-attr', '-z', '--stdin', 'filter'], { input: rels.join('\0') + '\0' })
268
+ if (out === null) return null
269
+ const f = out.split('\0')
270
+ const filtered = new Set()
271
+ for (let i = 0; i + 2 < f.length; i += 3) if (f[i + 2] !== 'unspecified' && f[i + 2] !== 'unset') filtered.add(f[i])
272
+ return filtered
273
+ }
274
+
275
+ /** A file's bytes at commit `sha`, as checkout would write it (null when git can't say). */
276
+ export async function blobAt (root, sha, rel) {
277
+ const out = await run(root, ['cat-file', '--filters', `${sha}:${rel}`], { buffer: true })
278
+ return out === null ? null : out
279
+ }
280
+
281
+ /**
282
+ * What git says about `paths` now (all of the folder with none), in two git calls whatever
283
+ * their number: `dirty` (changed, staged, untracked or conflicted), `unmerged` (a conflict
284
+ * git left for the person to resolve) and `tracked` (in the index). Null when git fails.
285
+ */
286
+ export async function treeState (root, paths) {
287
+ const spec = paths.length <= MAX_PATHSPECS ? ['--', ...paths] : []
288
+ const status = await run(root, ['--literal-pathspecs', 'status', '--porcelain=v2', '-z', '--untracked-files=all', ...spec])
289
+ if (status === null) return null // not asking for the second when the first failed (or timed out)
290
+ const listed = await run(root, ['--literal-pathspecs', 'ls-files', '-z', ...spec])
291
+ if (listed === null) return null
292
+ const dirty = new Set()
293
+ const unmerged = new Set()
294
+ const f = status.split('\0')
295
+ for (let i = 0; i < f.length; i++) {
296
+ const e = f[i]
297
+ if (e[0] === '1') dirty.add(e.split(' ').slice(8).join(' '))
298
+ else if (e[0] === '2') dirty.add(e.split(' ').slice(9).join(' ')).add(f[++i]) // renamed: both paths
299
+ else if (e[0] === 'u') {
300
+ const rel = e.split(' ').slice(10).join(' ')
301
+ dirty.add(rel)
302
+ unmerged.add(rel)
303
+ } else if (e[0] === '?' || e[0] === '!') dirty.add(e.slice(2))
304
+ }
305
+ return { dirty, unmerged, tracked: new Set(listed.split('\0').filter(Boolean)) }
306
+ }
307
+
308
+ /**
309
+ * Watches the folder's .git for HEAD moving, the index being written and git starting or
310
+ * finishing work (see busy); events: head, index, busy, idle.
311
+ */
312
+ export function watchGit (root, onEvent) {
313
+ const dir = gitDir(root)
314
+ if (!dir) return { close: async () => {} }
315
+ const names = new Set(['HEAD', 'index', ...MARKERS.map(([f]) => f)])
316
+ let wasBusy = !!busy(root, dir)
317
+ const watcher = watch(dir, { ignoreInitial: true, depth: 0, followSymlinks: false })
318
+ const onAny = (p) => {
319
+ const name = path.basename(p)
320
+ if (!names.has(name)) return
321
+ if (name === 'HEAD') onEvent({ type: 'head' })
322
+ else if (name === 'index') onEvent({ type: 'index' })
323
+ else {
324
+ const now = !!busy(root, dir)
325
+ if (now !== wasBusy) { wasBusy = now; onEvent({ type: now ? 'busy' : 'idle' }) }
326
+ }
327
+ }
328
+ watcher.on('add', onAny).on('change', onAny).on('unlink', onAny).on('addDir', onAny).on('unlinkDir', onAny).on('error', () => {})
329
+ return { close: () => closeWatcher(watcher) }
330
+ }
331
+
332
+ // ------------------------------------------------------------ upstream --
333
+ // What the folder's branch has to catch up with. A fetch can wait on the network: it gets longer.
334
+ export const FETCH_TIMEOUT_MS = 60 * 1000
335
+
336
+ /**
337
+ * The branch's upstream: { name ("origin/main"), remote ("origin"), sha }, or null (no upstream
338
+ * set, or git failed). It is read from the folder's own git config: nobody sets it in Quilt.
339
+ */
340
+ export async function upstreamOf (root) {
341
+ const name = ((await run(root, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'])) || '').trim()
342
+ if (!name) return null
343
+ const sha = ((await run(root, ['rev-parse', '-q', '--verify', '@{upstream}^{commit}'])) || '').trim() || null
344
+ const branch = headRef(root)
345
+ const remote = branch ? ((await run(root, ['config', '--get', `branch.${branch}.remote`])) || '').trim() : ''
346
+ return { name, remote: remote || null, sha }
347
+ }
348
+
349
+ /**
350
+ * Fetches the branch's upstream remote in the background: only remote-tracking refs move, never
351
+ * a file, the index or a branch. No prompt ever waits for a password (GIT_TERMINAL_PROMPT=0, no
352
+ * askpass): a remote that needs one the folder doesn't have just isn't fetched. Returns
353
+ * { ok, error }: `error` says in plain English why it failed (fetchProblem), null when it worked.
354
+ */
355
+ export async function fetchUpstream (root, remote) {
356
+ if (!remote || remote === '.') return { ok: false, error: null, skipped: true }
357
+ const r = await call(root, ['-c', 'core.askPass=', 'fetch', '--quiet', '--no-tags', '--no-write-fetch-head', remote], {
358
+ timeout: FETCH_TIMEOUT_MS,
359
+ env: { GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '', SSH_ASKPASS: '', GCM_INTERACTIVE: 'never', GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND || 'ssh -o BatchMode=yes' }
360
+ })
361
+ if (r.out !== null) return { ok: true, error: null }
362
+ return { ok: false, error: fetchProblem({ stderr: r.stderr, remote, timedOut: r.timedOut, missing: r.missing }) }
363
+ }
364
+
365
+ /** Why a fetch failed, in a few plain words (never the remote's address: it may hold a password). */
366
+ export function fetchProblem ({ stderr = '', remote = 'origin', timedOut = false, missing = false } = {}) {
367
+ const e = String(stderr || '').toLowerCase()
368
+ if (missing) return "git can't be run here"
369
+ if (timedOut) return `fetching from ${remote} took over a minute and was stopped`
370
+ if (/does not appear to be a git repository|not a git repository|no such remote/.test(e)) return `${remote} isn't a repository git can fetch from`
371
+ if (/could not read (username|password)|terminal prompts disabled|authentication failed|permission denied \(publickey|host key verification failed|invalid username or password|access denied|returned error: 40[13]/.test(e)) {
372
+ return `git can't sign in to ${remote} from this folder`
373
+ }
374
+ if (/could not resolve host|failed to connect|connection (timed out|refused)|network is unreachable|operation timed out|couldn't connect|unable to access|no route to host|temporary failure in name resolution/.test(e)) {
375
+ return `can't reach ${remote} (no network?)`
376
+ }
377
+ const line = String(stderr || '').split('\n').map((l) => l.replace(/^(fatal|error):\s*/i, '').trim()).find(Boolean)
378
+ return line ? `git fetch failed: ${line.replace(/[a-z]+:\/\/[^\s'"]*@/gi, '').slice(0, 120)}` : 'git fetch failed'
379
+ }
380
+
381
+ /** How `from` and `to` stand: { ahead: commits only `from` has, behind: commits only `to` has }; null when git can't say. */
382
+ export async function aheadBehind (root, from, to) {
383
+ const m = /^(\d+)\s+(\d+)$/.exec(String((await run(root, ['rev-list', '--left-right', '--count', `${from}...${to}`])) || '').trim())
384
+ return m ? { ahead: Number(m[1]), behind: Number(m[2]) } : null
385
+ }
386
+
387
+ /**
388
+ * The paths that differ between two commits: rel -> { status (git's letter: A, M, D, T), exec
389
+ * (whether `to` has it as an executable; null when it is gone there), plain (an ordinary file at
390
+ * both ends: no link, no submodule) }. Null when git fails.
391
+ */
392
+ export async function changesBetween (root, from, to) {
393
+ const out = await run(root, ['diff', '--no-renames', '--no-ext-diff', '--raw', '-z', from, to])
394
+ if (out === null) return null
395
+ const f = out.split('\0')
396
+ const changes = new Map()
397
+ for (let i = 0; i + 1 < f.length; i += 2) {
398
+ const m = /^:(\d{6}) (\d{6}) \S+ \S+ ([A-Z])/.exec(f[i])
399
+ if (!m || !f[i + 1]) continue
400
+ const file = (mode) => mode === '000000' || mode.startsWith('100')
401
+ changes.set(f[i + 1], { status: m[3], exec: m[2] === '000000' ? null : m[2] === '100755', plain: file(m[1]) && file(m[2]) })
402
+ }
403
+ return changes
404
+ }
405
+
406
+ /** Stages `rels` as they are in the folder (git add); whether git did. */
407
+ export async function stage (root, rels) {
408
+ for (let i = 0; i < rels.length; i += MAX_PATHSPECS) {
409
+ if ((await call(root, ['--literal-pathspecs', 'add', '--', ...rels.slice(i, i + MAX_PATHSPECS)])).out === null) return false
410
+ }
411
+ return true
412
+ }
413
+
414
+ /**
415
+ * Moves the folder's branch from `from` to `to` and sets the index to `to`, leaving every file as it
416
+ * is; `during()` (writing `to`'s files: session.js bringIn) runs first. git's index lock is held
417
+ * throughout, so a person's `git commit` meanwhile either went first (the branch is no longer at
418
+ * `from`: not moved) or is refused by git and asked again. The index is set before the branch
419
+ * moves: git reads HEAD, then the index, and only then takes the lock, so a commit that read the new
420
+ * HEAD reads the new index too, and one that read the old HEAD fails git's own check that HEAD
421
+ * hasn't moved. Never a commit on `to` made from the old index or missing `to`'s files, which would
422
+ * undo `to`'s changes. Returns whether it moved.
423
+ */
424
+ export async function fastForward (root, branch, from, to, during = null) {
425
+ const lock = await lockIndex(root)
426
+ if (!lock) return false
427
+ try {
428
+ if (((await run(root, ['rev-parse', '-q', '--verify', `refs/heads/${branch}`])) || '').trim() !== from) return false
429
+ if (during) await during()
430
+ const kept = lock.keep()
431
+ if (!(await lock.setIndex(to))) return false
432
+ if ((await call(root, ['update-ref', '-m', 'quilt: catch up with upstream', `refs/heads/${branch}`, to, from])).out === null) {
433
+ if (kept) lock.putBack()
434
+ return false
435
+ }
436
+ return true
437
+ } finally { lock.release() }
438
+ }
439
+
440
+ /**
441
+ * Takes git's index lock (index.lock) as git itself does, asking again for up to two seconds while
442
+ * another git holds it; null when it can't. While it is held, `setIndex(sha)` makes the index
443
+ * `sha`'s tree (keeping what git knows of files that didn't change) and `release()` lets git in again.
444
+ */
445
+ async function lockIndex (root) {
446
+ const dir = gitDir(root)
447
+ if (!dir) return null
448
+ const index = path.join(dir, 'index')
449
+ const lock = `${index}.lock`
450
+ const prev = `${index}.quilt-prev-${process.pid}`
451
+ for (let i = 0; i < 20; i++) {
452
+ try {
453
+ fs.closeSync(fs.openSync(lock, 'wx'))
454
+ ownLocks.add(lock)
455
+ return {
456
+ async setIndex (sha) {
457
+ const next = `${index}.quilt-${process.pid}`
458
+ try { fs.copyFileSync(index, next) } catch {}
459
+ const r = await call(root, ['read-tree', '--reset', sha], { env: { GIT_INDEX_FILE: next } })
460
+ try {
461
+ if (r.out === null) return false
462
+ fs.renameSync(next, index)
463
+ return true
464
+ } catch { return false } finally { fs.rmSync(next, { force: true }); fs.rmSync(`${next}.lock`, { force: true }) }
465
+ },
466
+ // A copy of the index as it is, put back by putBack() (the branch it was for didn't move after all).
467
+ keep () { try { fs.copyFileSync(index, prev); return true } catch { return false } },
468
+ putBack () { try { fs.renameSync(prev, index) } catch {} },
469
+ release () { fs.rmSync(prev, { force: true }); fs.rmSync(lock, { force: true }); ownLocks.delete(lock) }
470
+ }
471
+ } catch (err) { if (err.code !== 'EEXIST') return null }
472
+ await new Promise((resolve) => setTimeout(resolve, 100))
473
+ }
474
+ return null
475
+ }
package/src/hooks.js CHANGED
@@ -209,8 +209,8 @@ async function preEdit (event, d, api, state, say, name) {
209
209
  // What people said about these files in chat, shown once per message per AI session.
210
210
  const said = (r.chat || []).filter((q) => q.id && !seen.has(`ask:${q.id}`))
211
211
  // Who else changed them lately, shown once per file and writer per AI session.
212
- const key = (f) => `recent:${f.path}:${(f.recent || []).map((w) => w.by).join(',')}:${f.box ? f.box.by : ''}`
213
- const recent = files.filter((f) => ((f.recent && f.recent.length) || f.box) && !seen.has(key(f)))
212
+ const key = (f) => `recent:${f.path}:${(f.recent || []).map((w) => w.by).join(',')}`
213
+ const recent = files.filter((f) => f.recent && f.recent.length && !seen.has(key(f)))
214
214
  if (!said.length && !recent.length) return { exitCode: 0 }
215
215
  state.update((s) => {
216
216
  for (const q of said) s.seen.push(`ask:${q.id}`)