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/src/session.js CHANGED
@@ -41,10 +41,10 @@ import { MentionRunner, parseOnMention, readOnMention, writeOnMention } from './
41
41
  import { pickChecklist } from './agent-task-workflow.js'
42
42
  import { changeRefusal, TALK_REFUSED } from './session-access.js'
43
43
  import { canAdmit } from './admit-policy.js'
44
- import { merge3, hasMarkers, mergeLive } from './merge3.js'
44
+ import { merge3, mergeAuto, hasMarkers, mergeLive } from './merge3.js'
45
45
  import { sameEditClient, asClient } from './same-edit.js'
46
46
  import { openMerge, updateMerge, readMerges, pruneMerges, cleanName } from './merges.js'
47
- import { LiveRules, applyMine, findUses, removedNameWarning } from './live-merge.js'
47
+ import { LiveRules, applyMine, findUses, removedNameWarning, clashNotice, clashStillNotice } from './live-merge.js'
48
48
  import { versionOf } from './read-bases.js'
49
49
  import { RecentTexts, olderCopyNotice } from './base-pick.js'
50
50
  import { swapIn, settled, savedInto } from './swap-in.js'
@@ -53,7 +53,7 @@ import { HELD_MAP, readHeld, findHeld, settleHeld, renderHeld, versionsOf, versi
53
53
  import { RELAY_NAME as RELAY_BY, isRelay } from './ui/chat.js'
54
54
  import { cleanTyping, TYPING_MS, AGENT_TYPING_MS } from './ui/chat.js'
55
55
  import { DEFAULT_KEY } from './branchdocs.js'
56
- import { boxEntry } from './boxes.js'
56
+ import { headKey, headName, branchTip, busy as gitBusy, leftoverLock, indexStamp, filesAt, blobAt, treeState, watchGit, SETTLE_MS as GIT_SETTLE_MS, STALE_LOCK_MS, upstreamOf, fetchUpstream, aheadBehind, changesBetween, fastForward, stage } from './gitstate.js'
57
57
  import { cleanVoice, newCallId, voiceView, inVoice, transcribeSetting, setTranscribe, addLine, readLines, MAX_IN_CALL, CALL_FULL, callAgents, setAgentLeft, notInCall, agentSays, markCallForAgents, namedAgents, callPing, spokenReply, AGENT_REPLY_MS } from './voice.js'
58
58
  import { toolInUse } from './agents/common.js'
59
59
 
@@ -71,19 +71,6 @@ function hasGitDir (root) {
71
71
  try { fs.statSync(path.join(root, '.git')); return true } catch { return false }
72
72
  }
73
73
 
74
- /** The branch a git checkout in `root` is on, read from .git/HEAD (no git run); null when none or detached. */
75
- function headBranch (root) {
76
- try {
77
- let dir = path.join(root, '.git')
78
- if (fs.statSync(dir).isFile()) {
79
- const m = /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(dir, 'utf8'))
80
- if (!m) return null
81
- dir = path.resolve(root, m[1].trim())
82
- }
83
- const m = /^ref:\s*refs\/heads\/(.+)$/m.exec(fs.readFileSync(path.join(dir, 'HEAD'), 'utf8'))
84
- return m ? m[1].trim() : null
85
- } catch { return null }
86
- }
87
74
  const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904' // git's empty tree, the base of a branch pushed from nothing
88
75
 
89
76
  /**
@@ -146,8 +133,14 @@ const RETRY_MS = 30 * 1000
146
133
  const MOVE_RETRY_MAX_MS = 5 * 60 * 1000
147
134
  // Large uploads and downloads each hold the whole file in memory (twice), so only this many run at once.
148
135
  const MAX_TRANSFERS = 2
136
+ // Queued when HEAD moves, so a checkout that changes no file still runs flushPending. Never syncable (.quilt is ignored).
137
+ const HEAD_CHANGED = '.quilt/HEAD-changed'
149
138
  // Settles in a row that couldn't ask git (about a minute) before saying so; the folder stays held regardless.
150
139
  const GIT_FAILURES_TO_SAY = 30
140
+ // Before a folder leaves a branch, its saves still on their way to the relay are waited for this long at most.
141
+ const MOVE_WRITES_WAIT_MS = 3000
142
+ // A rebase or a bisect that has held the folder this long is said (once): it may be waiting on the person.
143
+ const HOLD_SAY_MS = 10 * 1000
151
144
  const FLUSH_MS = 40 // file changes are flushed this long after the first
152
145
  // How often a folder looks for commits its branch is behind (fetching its upstream first).
153
146
  const UPSTREAM_MS = Number(process.env.QUILT_UPSTREAM_MS) || 60 * 1000
@@ -160,7 +153,6 @@ const CATCHER_WAITING = 'another member is bringing these commits in'
160
153
  const RELAY_WAITING = 'the relay is bringing these commits into the session'
161
154
  // How long a git pull's settle waits for the relay to be at the pulled commit before sharing it as before (planSettle).
162
155
  const RELAY_PULL_WAIT_MS = 15 * 1000
163
- const SETTLE_BOXES_MS = 1500 // after an edit to one of our boxed files: does git have it as the session does now?
164
156
  const RELAY_ASK_EVERY_MS = 5 * 1000 // a folder waiting for the relay asks it again this often (server.js SYNC_EVERY_GIT_MS)
165
157
  const INDEX_WATCH_MS = 8000 // after a bring-in, how long the index is checked against what another git may write back
166
158
 
@@ -261,10 +253,6 @@ export class Session extends EventEmitter {
261
253
  this.transfers = 0 // large uploads and downloads running
262
254
  this.transferQueue = [] // resolvers waiting for one to finish
263
255
  this.stopped = false
264
- // Boxes (someone's unfinished work on one file, kept out of other folders until it's committed):
265
- // path -> { by, pattern, note, ts, box: true }. The relay keeps them, outside the shared doc; we keep
266
- // the last list. Quilt holds no files (no-holds, 2026-11-13): a box never stops anyone writing.
267
- this.boxed = new Map()
268
256
  this.chat = this.doc.getArray('chat') // { by, text, ts }
269
257
  this.activity = this.doc.getArray('activity') // { by, path, kind, detail, ts }
270
258
  this.agentFeed = this.doc.getArray('agentFeed') // { id, by, tool, conv, kind, text, ts, summary?, title? }
@@ -298,16 +286,9 @@ export class Session extends EventEmitter {
298
286
  // ages out on our clock, not theirs.
299
287
  this.typing = {}
300
288
  this.typingSeen = new Map()
301
- // Files our AI changed (see boxEdit): path -> when it last did. Forgotten once quiet for editQuietMs
289
+ // Files our AI changed (see noteAiEdit): path -> when it last did. Forgotten once quiet for editQuietMs
302
290
  // (forgetQuietEdits), and "working" that only these edits said lapses with them.
303
291
  this.aiEdits = new Map()
304
- this.boxing = new Set() // our files whose box is on its way to the relay (boxEdit)
305
- // Ghosts: files someone else has boxed, not written here. For each, this folder's version from before
306
- // the box ({ text } or { b64 }; null: it wasn't there), put back when an edit here is refused. Kept in state.json.
307
- this.boxBase = new Map()
308
- // Our boxes: what the session had before the edit that opened each (null: no file). Back to that, the box holds
309
- // nothing of ours (our edit undone, or taken back) and opens like a committed one.
310
- this.boxFrom = new Map()
311
292
  this.editQuietMs = editQuietMs
312
293
  // Whether our AI takes work from the board by itself (tasks.js PICKUP_MODES); null: this person's setting.
313
294
  this.aiTasks = aiTasks
@@ -321,6 +302,8 @@ export class Session extends EventEmitter {
321
302
  this.lastKnown = new Map() // path -> text content, or "bin:<sha1>"
322
303
  this.relayWriting = new Set() // paths with a live write at the relay, not answered yet (relayIngest)
323
304
  this.relayAgain = new Set() // of those, the ones saved again meanwhile: taken in once the answer is here
305
+ this.clashed = new Map() // path -> its text with conflict markers, as last seen: not shared until they are gone (relayClashed)
306
+ this.noClashMarkers = false // as an app before 0.3.176: a clash goes to a held record, not into the file (tests)
324
307
  this.relayLocal = new Set() // paths the relay asked to be edited here as before (its answer's `fallback`), once
325
308
  this.overwritten = new RecentTexts() // the texts Quilt replaced on disk, and the saves made from them (base-pick.js)
326
309
  this.wroteHere = new Map() // path -> { ino, size, mtimeMs, text, sure }: the text file Quilt last wrote there, read back from memory once confirmed untouched
@@ -375,27 +358,30 @@ export class Session extends EventEmitter {
375
358
  this.startNameSent = false
376
359
  this.logs = [] // the last 200 log lines (for status and tests)
377
360
  // Git awareness (gitstate.js): a git operation in this folder is recognised, not broadcast as edits.
378
- this.git = null // { key, branch, sha } this folder was on when the session started (null: not a repo)
379
- this.gitSeen = null // the head last seen by classifyBurst
361
+ this.git = null // { key, branch, sha }: where git had this folder when the session started or it last moved (null: not a repo)
362
+ this.gitSeen = null // the head last read from git
380
363
  this.gitIndex = null // indexStamp at the last flush
381
364
  this.gitWatcher = null
382
- this.hold = null // { kind: 'busy'|'settling'|'switching', since, prevHead, to? } while this folder's sync is held
365
+ this.hold = null // { kind: 'busy'|'switching', since, to?, waiting? } while this folder's sync is held (git at work; moving to another branch)
383
366
  this.upstreamAfterHold = null // a look at the upstream asked while held ({ fetch }): asked again when the hold ends
384
367
  this.heldPaths = new Set() // paths that changed (here or in the room) while held
385
368
  this.heldConflicts = new Set() // paths git left a conflict in during this hold (see noteConflict)
386
369
  this.stashSeen = null // the stash's mark when the folder was last quiet: a change by the settle means the person stashed
387
370
  this.headChangedAt = 0
388
371
  this.settleTimer = null
389
- this.savedGit = null // { key, sha, held } from state.json: the branch synced, and whether a hold was on, at the last stop
390
- this.rejoin = false // restarted held: when the hold ends, every path is checked, not only those seen changing
372
+ this.savedGit = null // { key, sha } from state.json: the branch this folder synced at the last stop
373
+ this.rejoin = false // started on another branch than the one saved: if the hold ends back on the saved one, every path is checked, not only those seen changing
391
374
  this.gitFailures = 0 // settles in a row that couldn't ask git
392
- // Commits made outside the session that this branch is behind (see bringIn): { name, url, sha,
393
- // behind, ahead, diverged, conflicts, waiting, checkedAt } of the branch's upstream, or null.
375
+ // The branch's upstream and the commits this branch is behind it (see bringIn): { name, sha, behind,
376
+ // ahead, waiting? (why Quilt left them to the person's git), brought? { count, files, at } }, or null.
394
377
  this.upstream = null
395
378
  this.upstreamTimer = null
396
379
  this.upstreamFetch = false
397
380
  this.upstreamPoll = null
398
381
  this.upstreamSaid = '' // the advice last given, so it's given once per state
382
+ this.fetchSaid = '' // why the last fetch failed, so it's logged once
383
+ this.upstreamTries = 0 // looks in a row that found the folder not quiet, or not in step with the session yet
384
+ this.peerTips = new Map() // awareness client -> the commit their folder said it is at, on this branch
399
385
  this.fetchState = null // the last git fetch of the upstream: { ok, error, at } (noteFetch)
400
386
  this.upstreamDeferred = null // the commit this folder let another member's folder bring in first
401
387
  this.clashAbsent = null // { task, name, since }: a clash task's assignee seen gone from the branch
@@ -584,9 +570,17 @@ export class Session extends EventEmitter {
584
570
  const hadState = this.loadState()
585
571
  // A folder whose .git an older Quilt set aside (git-aside.js): it comes back once the relay has synced (gitBack); its branch is the note's until then.
586
572
  this.gitAside = hasGitDir(this.root) ? null : gitAsideOf(this.root)
587
- if (hadState) this.loadBoxes()
588
- // The branch this folder is on: the checkout's branch name, the set-aside note's, else the room's default.
589
- this.branch = headBranch(this.root) || (this.gitAside && this.gitAside.branch) || DEFAULT_KEY
573
+ for (const f of ['boxes.json', 'claims.json']) { try { fs.rmSync(path.join(this.stateDir, f), { force: true }) } catch {} } // what older versions kept here
574
+ // Where git has the folder: a branch, or a detached commit (keyed `@<sha>`). Without a commit to read
575
+ // (a branch with no commits yet, or git not running here) the branch HEAD names, with no commit.
576
+ this.git = await this.headAt()
577
+ this.gitSeen = this.git
578
+ this.gitIndex = indexStamp(this.root)
579
+ // Started on another branch than the one last synced: nothing in this tree is that branch's offline work (startAway).
580
+ const away = hadState && this.startAway()
581
+ // The branch document this folder syncs: the one git has it on (still the saved one, until the folder
582
+ // has moved, when it started away), the set-aside note's, else the room's default (a folder without git).
583
+ this.branch = (this.git && this.git.key) || (this.gitAside && this.gitAside.branch) || DEFAULT_KEY
590
584
  // The form saved is the saved branch's; another branch's is the relay's to say when it is joined.
591
585
  if (this.savedBranch !== this.branch) { this.branchForm = null; this.diffBase = null }
592
586
 
@@ -605,7 +599,7 @@ export class Session extends EventEmitter {
605
599
  doc: this.doc,
606
600
  // An app's saved document from before branch documents is the room's old one: the relay kept it as that branch's.
607
601
  // base: the commit a branch new to the session starts from (a partner without it locally creates it there).
608
- branch: { key: this.branch, doc: this.bdoc, ...(this.branchEpoch && this.savedBranch === this.branch ? { epoch: this.branchEpoch } : {}) },
602
+ branch: { key: this.branch, doc: this.bdoc, ...(this.git && this.git.sha ? { base: this.git.sha } : {}), ...(this.branchEpoch && this.savedBranch === this.branch ? { epoch: this.branchEpoch } : {}) },
609
603
  // state.bin is a copy of an older document of this branch (it was removed and started again): never merged.
610
604
  onStaleBranch: (reply) => this.staleBranch(reply),
611
605
  beforeRemote: () => { if (this.ready) this.flushPending() }
@@ -621,17 +615,18 @@ export class Session extends EventEmitter {
621
615
  this.conn.on('fatal', (err) => this.emit('fatal', err))
622
616
  this.conn.on('pass', (p) => this.adoptPass(p))
623
617
  this.conn.on('problem', (msg) => this.setRelayProblem(msg))
624
- this.conn.on('boxes', (list) => this.setBoxes(list))
625
618
  this.conn.on('access', (a) => this.setAccess(a))
626
619
  this.conn.on('members', (m) => this.setMembers(m))
627
620
  this.conn.on('branches', (list) => this.setBranches(list))
621
+ // A move's own join is the move's to finish (finishMove): this.branch changes only once the folder is there.
628
622
  this.conn.on('branch-joined', (r) => {
629
- if (typeof r.branch !== 'string' || !r.branch) return
623
+ if (typeof r.branch !== 'string' || !r.branch || (this.hold && this.hold.kind === 'switching')) return
630
624
  if (typeof r.epoch === 'string' && r.epoch && !this.staleRejoin) this.branchEpoch = r.epoch
631
625
  // An older relay says no form: its documents are all full ones.
632
626
  this.branchForm = r.form === 'diff' ? 'diff' : 'full'
633
627
  if (r.form === 'diff' && typeof r.diffBase === 'string') this.diffBase = r.diffBase
634
628
  this.branch = r.branch
629
+ this.announceBranch()
635
630
  this.scheduleStatusWrite()
636
631
  })
637
632
  this.conn.on('branch-refused', (why) => this.log(`⚠️ the relay refused this folder's branch: ${why}`))
@@ -643,7 +638,7 @@ export class Session extends EventEmitter {
643
638
  // We've synced this folder before: hold what was edited while we were
644
639
  // away, let the relay tell us what the others did, then merge the two.
645
640
  const marks = historyMarks(this.history.entries()) // what we had seen: the catch-up is the rest
646
- const offline = this.captureOffline(null)
641
+ const offline = away ? { entries: [], take: [], downloads: [] } : this.captureOffline(null)
647
642
  this.goLive()
648
643
  if (offline.entries.length) this.log(`${offline.entries.length} file(s) changed while you were away; merging once the relay has synced…`)
649
644
  const synced = this.conn.waitForSync()
@@ -655,6 +650,15 @@ export class Session extends EventEmitter {
655
650
  this.awayBackups = null
656
651
  this.emit('debug', `offline merge did not run: ${err && err.message}`)
657
652
  })
653
+ if (away) {
654
+ // The document loaded from disk is the saved branch as it was at the last stop: the folder moves to
655
+ // where git has it once the relay has synced. Never synced: the hold stays on and nothing is shared.
656
+ synced.then(() => {
657
+ const to = this.resumeAway
658
+ this.resumeAway = null
659
+ if (to) this.followHead(to)
660
+ }, () => {})
661
+ }
658
662
  } else {
659
663
  this.log('waiting for relay…')
660
664
  const sync = this.conn.waitForSync()
@@ -914,13 +918,14 @@ export class Session extends EventEmitter {
914
918
  this.branchForm = meta.form === 'diff' || meta.form === 'full' ? meta.form : null
915
919
  this.diffBase = typeof meta.diffBase === 'string' ? meta.diffBase : null
916
920
  this.storedOnDisk = new Map(Object.entries(meta.storedOnDisk || {}))
917
- for (const [rel, v] of Object.entries(meta.boxBase && typeof meta.boxBase === 'object' ? meta.boxBase : {})) if (v === null || (v && (typeof v.text === 'string' || typeof v.b64 === 'string'))) this.boxBase.set(rel, v)
918
921
  this.known = meta.known ? new Map(Object.entries(meta.known)) : null
919
922
  this.behindAtSave = new Map(Object.entries(meta.behind && typeof meta.behind === 'object' ? meta.behind : {}).filter(([, v]) => typeof v === 'string'))
920
- // No gitKey (an older state file): taken as the branch the folder is on now.
921
923
  this.savedRole = typeof meta.role === 'string' ? meta.role : null
922
924
  this.savedSeenAt = typeof meta.seenAt === 'number' ? meta.seenAt : null
923
- this.savedGit = typeof meta.gitKey === 'string' && meta.gitKey ? { key: meta.gitKey, sha: typeof meta.gitSha === 'string' ? meta.gitSha : null, held: !!meta.gitHeld } : null
925
+ // The branch git had the folder on at the last stop. A state file without it (written before folders
926
+ // followed their branch) names the branch it synced, when that is a real one.
927
+ const was = typeof meta.gitKey === 'string' && meta.gitKey ? meta.gitKey : !this.legacyState && this.savedBranch && this.savedBranch !== DEFAULT_KEY ? this.savedBranch : null
928
+ this.savedGit = was ? { key: was, sha: typeof meta.gitSha === 'string' ? meta.gitSha : null } : null
924
929
  return true
925
930
  } catch {
926
931
  return false
@@ -1016,7 +1021,7 @@ export class Session extends EventEmitter {
1016
1021
  }
1017
1022
  // When we were last in touch with the session: "you left 3h ago" on the next catch-up.
1018
1023
  if (this.conn && this.conn.connected) this.savedSeenAt = Date.now()
1019
- fs.writeFileSync(path.join(this.stateDir, 'state.json'), JSON.stringify({ room: this.room, server: this.server, layout: 2, branch: this.branch, ...(this.branchEpoch ? { epoch: this.branchEpoch } : {}), ...(this.branchForm ? { form: this.branchForm } : {}), ...(this.diffBase ? { diffBase: this.diffBase } : {}), storedOnDisk: Object.fromEntries(this.storedOnDisk), known, ...(this.boxBase.size ? { boxBase: Object.fromEntries(this.boxBase) } : {}), ...(Object.keys(behind).length ? { behind } : {}), ...this.roleState(), ...(this.savedSeenAt ? { seenAt: this.savedSeenAt } : {}) }))
1024
+ fs.writeFileSync(path.join(this.stateDir, 'state.json'), JSON.stringify({ room: this.room, server: this.server, layout: 2, branch: this.branch, ...(this.branchEpoch ? { epoch: this.branchEpoch } : {}), ...(this.branchForm ? { form: this.branchForm } : {}), ...(this.diffBase ? { diffBase: this.diffBase } : {}), ...(this.git ? { gitKey: this.git.key, ...(this.git.sha ? { gitSha: this.git.sha } : {}) } : {}), storedOnDisk: Object.fromEntries(this.storedOnDisk), known, ...(Object.keys(behind).length ? { behind } : {}), ...this.roleState(), ...(this.savedSeenAt ? { seenAt: this.savedSeenAt } : {}) }))
1020
1025
  }
1021
1026
 
1022
1027
  /** This member's role, so the next start knows it before the relay says (ignoreQuiltState). */
@@ -1215,10 +1220,12 @@ export class Session extends EventEmitter {
1215
1220
 
1216
1221
  /** Merges one captured path. Returns what happened, or null when nothing needed doing. */
1217
1222
  async mergeOne (e) {
1223
+ if (e.carried) return this.mergeCarried(e) // work a checkout carried from another branch
1218
1224
  const { rel, base, via = null } = e
1219
1225
  const release = () => this.merging.delete(rel)
1220
1226
  const disk = this.readDisk(rel)
1221
1227
  if (disk && (disk.skip || disk.tooLarge)) { release(); return null }
1228
+ if (disk && !disk.binary && hasMarkers(disk.text)) { release(); return null } // a clash to settle in the file (relayClashed): not merged or shared with its markers
1222
1229
  const ours = disk ? disk.key : null // re-read: it may have changed again before the relay synced
1223
1230
  const theirs = this.sharedKey(rel)
1224
1231
  const theirsBy = this.lastEditorOf(rel)
@@ -1542,6 +1549,23 @@ export class Session extends EventEmitter {
1542
1549
  this.flushTimer = null
1543
1550
  const paths = [...this.pending]
1544
1551
  this.pending.clear()
1552
+ if (this.hold) {
1553
+ for (const rel of paths) if (rel !== HEAD_CHANGED) this.heldPaths.add(rel)
1554
+ // Only a change here puts the end of the hold off: the flush before each update from the session
1555
+ // (beforeRemote) has none, and a partner typing must not hold this folder for good.
1556
+ // A move to another branch ends on its own (finishMove).
1557
+ if (paths.length && this.hold.kind !== 'switching') this.settleHoldSoon()
1558
+ // A move that didn't finish follows HEAD wherever git takes it next (back to the old branch resumes it).
1559
+ else if (this.hold.kind === 'switching' && paths.includes(HEAD_CHANGED) && !this.following) this.recheckSoon()
1560
+ return
1561
+ }
1562
+ if (this.git && this.isBurst()) {
1563
+ // git is at work here, or has just been: held until it is known whether the folder is still on its branch.
1564
+ for (const rel of paths) if (rel !== HEAD_CHANGED) this.heldPaths.add(rel)
1565
+ this.setHold('busy')
1566
+ this.settleHoldSoon()
1567
+ return
1568
+ }
1545
1569
  this.ingestAll(paths)
1546
1570
  }
1547
1571
 
@@ -1559,6 +1583,931 @@ export class Session extends EventEmitter {
1559
1583
  try { fs.lstatSync(path.join(this.root, ...rel.split('/'))); return true } catch { return false }
1560
1584
  }
1561
1585
 
1586
+ // ------------------------------------------------------------------ git --
1587
+ // A folder that is a git checkout is on one branch of the session at a time, the one git has it
1588
+ // on. Quilt never switches branches itself: when a person or an agent checks out another branch
1589
+ // in git, the folder moves to that branch's document, and the branch it left keeps its work in
1590
+ // the session. While git is at work in the folder (its index lock is there, or a rebase or a
1591
+ // bisect has HEAD off its branch) and while a move is under way, the folder's sync is held:
1592
+ // nothing is taken in and nothing from the session is written out. Git work that leaves the
1593
+ // folder on its branch (a commit, a stash, a reset, a pull) is shared afterwards as the edits it
1594
+ // made, like any other change to the files.
1595
+
1596
+ /**
1597
+ * Where git has the folder now: { key, branch, sha } (a branch, or a detached commit keyed `@<sha>`).
1598
+ * A branch with no commits yet, or a folder whose git can't be run, has no sha. Null when it is
1599
+ * not a repository or HEAD can't be read.
1600
+ */
1601
+ async headAt () {
1602
+ const head = await headKey(this.root)
1603
+ if (head) return head
1604
+ const key = headName(this.root)
1605
+ return key ? { key, branch: key.startsWith('@') ? null : key, sha: null } : null
1606
+ }
1607
+
1608
+ /** The key of where HEAD is (headAt), or null when git can't say. */
1609
+ async headNow () {
1610
+ const head = await this.headAt()
1611
+ return head ? head.key : null
1612
+ }
1613
+
1614
+ /** Did git just touch this folder? (its index written, HEAD moved, or an operation under way) */
1615
+ isBurst () {
1616
+ const stamp = indexStamp(this.root)
1617
+ const indexChanged = stamp !== this.gitIndex
1618
+ this.gitIndex = stamp
1619
+ const at = headName(this.root)
1620
+ return indexChanged || Date.now() - this.headChangedAt < 2000 || !!this.gitBusy() || (!!at && at !== this.git.key)
1621
+ }
1622
+
1623
+ /** The git operation under way in this folder, or null; a leftover index.lock doesn't count. */
1624
+ gitBusy () { return gitBusy(this.root, undefined, this.leftoverLock) }
1625
+
1626
+ /** Whether the folder's sync is held: git is at work on it, or it is moving to another branch. (A move's own writes go through: arrive.) */
1627
+ held () { return !!(this.hold && !this.arriving) }
1628
+
1629
+ /**
1630
+ * Runs git work in this folder one piece at a time, in order (the end of a hold, a move, a look
1631
+ * at HEAD), each skipped once stopped.
1632
+ */
1633
+ gitTask (fn) {
1634
+ const run = this.gitChain.then(() => this.stopped ? undefined : fn())
1635
+ this.gitChain = run.catch(() => {})
1636
+ return run
1637
+ }
1638
+
1639
+ /** The disk at rel is as Quilt last wrote or read it (or still absent, for a path it never had). */
1640
+ untouchedHere (rel) {
1641
+ const disk = this.readDisk(rel)
1642
+ if (disk && (disk.skip || disk.tooLarge)) return false
1643
+ return (disk ? disk.key : undefined) === this.lastKnown.get(rel)
1644
+ }
1645
+
1646
+ setHold (kind, extra = {}) {
1647
+ // A move to another branch ends only once the folder is there (finishMove): git at work meanwhile doesn't change it.
1648
+ if (this.hold && (this.hold.kind === kind || this.hold.kind === 'switching')) return
1649
+ // since: when the folder was first held, kept across kinds.
1650
+ this.hold = { kind, since: this.hold ? this.hold.since : Date.now(), ...extra }
1651
+ this.emit('hold', this.hold)
1652
+ this.scheduleStatusWrite()
1653
+ }
1654
+
1655
+ releaseHold () {
1656
+ this.hold = null
1657
+ clearTimeout(this.settleTimer); this.settleTimer = null
1658
+ this.emit('hold', null)
1659
+ this.scheduleStatusWrite()
1660
+ // git is done here (a commit, a fetch, a checkout): partners hear where this folder is, and it looks at its upstream.
1661
+ this.shareTip()
1662
+ this.checkUpstreamSoon()
1663
+ }
1664
+
1665
+ /** (Re)arms the hold's timer: it ends GIT_SETTLE_MS after the last file or git event. */
1666
+ settleHoldSoon () {
1667
+ if (!this.hold || this.hold.kind === 'switching' || this.stopped) return
1668
+ clearTimeout(this.settleTimer)
1669
+ const gen = ++this.settleGen
1670
+ this.settleTimer = setTimeout(() => {
1671
+ this.settleTimer = null
1672
+ this.gitTask(() => this.onSettled(gen)).catch((err) => {
1673
+ this.log(`could not settle: ${err.message}`)
1674
+ this.settleHoldSoon() // every hold has a way out: asked again
1675
+ })
1676
+ }, GIT_SETTLE_MS)
1677
+ this.settleTimer.unref()
1678
+ }
1679
+
1680
+ /** Whether a hold is on that a settle may end now. */
1681
+ settleable () {
1682
+ return !!this.hold && this.hold.kind !== 'switching' && !this.stopped
1683
+ }
1684
+
1685
+ /**
1686
+ * The folder has been quiet since git touched it. Still at work: looked at again later. On another
1687
+ * branch (or commit) now: the folder moves there (followHead). Otherwise it is still on its branch:
1688
+ * the hold ends, and what changed meanwhile is shared or written out (resumeHeld).
1689
+ * `gen`: the settleHoldSoon that armed it. A later one (a file or git event since) means not settled yet.
1690
+ */
1691
+ async onSettled (gen = this.settleGen) {
1692
+ if (!this.settleable()) return
1693
+ if (this.gitBusy() === 'index-lock' && Date.now() - this.lastFileEventAt >= STALE_LOCK_MS) {
1694
+ // Only the index lock, there a while, and the tree quiet as long (a long checkout writes files
1695
+ // all along): a git that crashed may have left it.
1696
+ const stamp = await leftoverLock(this.root)
1697
+ if (!this.settleable()) return
1698
+ if (stamp) {
1699
+ this.leftoverLock = stamp
1700
+ this.log('⚠️ a leftover .git/index.lock is being ignored; delete it if git complains')
1701
+ }
1702
+ }
1703
+ const head = await this.headAt()
1704
+ if (!this.settleable()) return
1705
+ // Still mid-operation, or a file or git event since this settle's timer was armed: looked at again later.
1706
+ const busy = this.gitBusy()
1707
+ if (busy || gen !== this.settleGen) {
1708
+ // A rebase or a bisect can stay open for a long time (a conflict to resolve): said once, to the person and their AI.
1709
+ if (busy && busy !== 'index-lock' && !this.hold.said && Date.now() - this.hold.since >= HOLD_SAY_MS) {
1710
+ this.hold.said = true
1711
+ const text = `git is in the middle of a ${busy} in this folder, so nothing here is shared and nothing from the session is written here until it is finished (or aborted).`
1712
+ this.log(`⏸️ ${text}`)
1713
+ this.notice(text)
1714
+ }
1715
+ this.settleHoldSoon()
1716
+ return
1717
+ }
1718
+ if (!head || head.key !== headName(this.root)) {
1719
+ // HEAD can't be read (or moved while it was): nothing is shared until it can. Asked again, for good.
1720
+ if (!head && ++this.gitFailures === GIT_FAILURES_TO_SAY) this.log('⚠️ Quilt can\'t read git here; this folder stays paused')
1721
+ this.settleHoldSoon()
1722
+ return
1723
+ }
1724
+ this.gitFailures = 0
1725
+ if (head.key !== this.git.key) {
1726
+ // On another branch (or a detached commit) now: the folder follows it there.
1727
+ this.followHead(head.key)
1728
+ return
1729
+ }
1730
+ this.git = head
1731
+ this.gitSeen = head
1732
+ // What git wrote is accounted for here: the next flush is an edit unless git moves again.
1733
+ this.gitIndex = indexStamp(this.root)
1734
+ this.headChangedAt = 0
1735
+ const late = new Set(this.heldPaths)
1736
+ this.heldPaths.clear()
1737
+ // Started on another branch and back on the saved one before the move ran: changes made while Quilt was off were never seen.
1738
+ if (this.rejoin) for (const rel of [...this.sharedPaths(), ...walk(this.root, this.ig)]) late.add(rel)
1739
+ this.rejoin = false
1740
+ this.releaseHold()
1741
+ this.resumeHeld([...late])
1742
+ }
1743
+
1744
+ /**
1745
+ * The hold is over and the folder is still on its branch. Each path that changed meanwhile: where
1746
+ * the disk is as Quilt left it, the session's version is written out; where it changed here (git
1747
+ * rewrote it, or someone saved it), it is taken in as an edit, merged with the session's as any save is.
1748
+ */
1749
+ resumeHeld (paths) {
1750
+ for (const rel of paths) {
1751
+ if (!this.syncable(rel) || this.merging.has(rel)) continue
1752
+ if (this.untouchedHere(rel)) this.tryWrite(rel)
1753
+ else this.ingestAll([rel])
1754
+ }
1755
+ }
1756
+
1757
+ // ------------------------------------------------------------ branches --
1758
+ // Uncommitted work git carries over in a checkout is the old branch's (the session has it
1759
+ // there): on a branch the session already has, Quilt writes that branch's version over it; a
1760
+ // branch new to the session starts from the folder as git left it, carried work included.
1761
+ // Nothing is synced branch on branch.
1762
+
1763
+ /**
1764
+ * At start, before captureOffline: git has the folder on another branch than the one this session
1765
+ * last synced (a checkout while Quilt was off). Its tree is then that other branch's, not the
1766
+ * saved branch's work plus offline edits, so nothing is captured from it. The folder joins the
1767
+ * saved branch held, and moves to where git has it once the relay has synced (start: followHead).
1768
+ */
1769
+ startAway () {
1770
+ const saved = this.savedGit
1771
+ if (!saved || !this.git || this.git.key === saved.key) return false
1772
+ const at = this.git.key
1773
+ this.git = { key: saved.key, branch: saved.key.startsWith('@') ? null : saved.key, sha: saved.sha }
1774
+ this.gitSeen = this.git
1775
+ // An unfinished offline merge's bases are no bases for this move; left, the next start would read them.
1776
+ fs.rmSync(this.heldBasesFile, { force: true })
1777
+ // What the folder had of the saved branch: the session's version at the last stop.
1778
+ for (const rel of this.sharedPaths()) {
1779
+ const k = this.sharedKey(rel)
1780
+ if (this.syncable(rel) && k !== undefined) this.lastKnown.set(rel, k)
1781
+ }
1782
+ this.rejoin = true
1783
+ this.hold = { kind: 'switching', since: Date.now(), to: at }
1784
+ this.resumeAway = at
1785
+ return true
1786
+ }
1787
+
1788
+ /**
1789
+ * git moved HEAD to branch `to` (a checkout in a terminal or by an agent, or while Quilt was
1790
+ * stopped): the folder moves there.
1791
+ */
1792
+ followHead (to) {
1793
+ if (!to || this.stopped || this.following || this.pendingMove || to === this.branch) return
1794
+ this.following = to
1795
+ this.setHold('switching', { to }) // nothing more is shared on the old branch from here
1796
+ this.gitTask(() => this.moveTo(to))
1797
+ // The branch it failed on: a move can retarget on the way (moveTo, abandonMove).
1798
+ .catch((err) => this.moveFailed((this.pendingMove && this.pendingMove.to) || (this.hold && this.hold.to) || to, err))
1799
+ .finally(() => { this.following = null })
1800
+ }
1801
+
1802
+ /**
1803
+ * A move that didn't finish: the folder stays held (nothing of either branch reaches the
1804
+ * other) and recheckMove tries again, less and less often, or follows git wherever it goes
1805
+ * next. A refusal the relay will repeat (a viewer starting a branch, the branch limit) is
1806
+ * said once, with what to do; checking the old branch out again resumes sync there.
1807
+ */
1808
+ moveFailed (to, err) {
1809
+ if (this.stopped || !this.hold || this.hold.kind !== 'switching') return
1810
+ const msg = (err && err.message) || String(err)
1811
+ const connected = !!(this.conn && this.conn.connected)
1812
+ const refused = connected && !/did not answer|not connected|disconnected/.test(msg)
1813
+ // Offline is no try: reconnecting tries again at once (start: the 'connected' status clears moveRetryAt).
1814
+ if (connected) this.moveTries = (this.moveTries || 0) + 1
1815
+ this.moveRetryAt = !connected ? 0 : Date.now() + (refused ? MOVE_RETRY_MAX_MS : Math.min(MOVE_RETRY_MAX_MS, RETRY_MS * 2 ** (this.moveTries - 1)))
1816
+ this.hold.waiting = refused ? 'refused' : 'retrying'
1817
+ this.emit('hold', this.hold)
1818
+ this.scheduleStatusWrite()
1819
+ const said = `${to}\0${refused ? msg : ''}`
1820
+ if (this.moveSaid === said) return
1821
+ this.moveSaid = said
1822
+ if (refused) {
1823
+ const text = `The session can't take ${to}: ${msg}. This folder isn't syncing while it's on ${to}; check out ${this.branch} again in git to keep syncing there.`
1824
+ this.log(`⚠️ ${text}`)
1825
+ this.notice(text)
1826
+ } else {
1827
+ this.log(`⚠️ You're on ${to} in git, but its work in the session can't be loaded yet (${msg}). This folder waits and tries again.`)
1828
+ }
1829
+ }
1830
+
1831
+ /** While a move is unfinished: where is HEAD now? Back on the folder's branch resumes it; elsewhere is followed (backing off on the same branch). */
1832
+ async recheckMove () {
1833
+ if (!this.hold || this.hold.kind !== 'switching' || this.following || this.stopped) return null
1834
+ const at = await this.headNow()
1835
+ if (this.stopped || !at || this.following) return null
1836
+ const m = this.pendingMove
1837
+ const target = m ? m.to : this.hold.to
1838
+ if (at !== this.branch && at === target && Date.now() < (this.moveRetryAt || 0)) return null // tried a moment ago
1839
+ this.following = at
1840
+ try {
1841
+ if (m) return await (m.to === at ? this.finishMove(m) : this.abandonMove(m, at))
1842
+ if (at === this.branch) return this.settleBack()
1843
+ this.hold.to = at
1844
+ return await this.moveTo(at)
1845
+ } finally { this.following = null }
1846
+ }
1847
+
1848
+ /** recheckMove, as git work; what fails is a move that failed again. */
1849
+ recheckSoon () {
1850
+ this.gitTask(() => this.recheckMove()).catch((err) => this.moveFailed(this.pendingMove ? this.pendingMove.to : this.hold && this.hold.to, err))
1851
+ }
1852
+
1853
+ /** HEAD is back on the folder's branch before it moved: the trip ends like any git work there (onSettled). */
1854
+ settleBack () {
1855
+ this.moveTries = 0
1856
+ this.moveSaid = null
1857
+ this.hold = { kind: 'busy', since: this.hold ? this.hold.since : Date.now() }
1858
+ this.emit('hold', this.hold)
1859
+ this.scheduleStatusWrite()
1860
+ this.settleHoldSoon()
1861
+ return null
1862
+ }
1863
+
1864
+ /** This folder's saves that are at the relay and not answered yet (relayIngest) have their answers, or MOVE_WRITES_WAIT_MS has passed. */
1865
+ async relayWritesDone () {
1866
+ const until = Date.now() + MOVE_WRITES_WAIT_MS
1867
+ while (this.relayWriting.size && Date.now() < until && !this.stopped) await new Promise((resolve) => setTimeout(resolve, 20))
1868
+ }
1869
+
1870
+ /**
1871
+ * Moves this folder to branch `to`, which git has already checked out: every change on the
1872
+ * branch it leaves is confirmed in the session where it can be, that branch's document is kept
1873
+ * aside here (parkLocalState), and finishMove joins the new one. Runs as git work.
1874
+ */
1875
+ async moveTo (to) {
1876
+ const from = this.branch
1877
+ const at = await this.headNow()
1878
+ if (this.stopped) return null
1879
+ if (at === from) return this.settleBack()
1880
+ if (at && at !== to) { to = at; if (this.hold) this.hold.to = at }
1881
+ // A save of this folder's still on its way to the relay is the branch's it was made on: its answer first.
1882
+ await this.relayWritesDone()
1883
+ if (this.stopped) return null
1884
+ // The commit the branch it leaves is at now (commits made since the folder came to it included).
1885
+ const fromSha = (this.git && this.git.branch && await branchTip(this.root, this.git.branch)) || (this.git ? this.git.sha : null)
1886
+ // path -> the old branch's version as this folder had it (as lastKnown keys it), to tell what git carried over.
1887
+ // A change from the session that came while the folder was held is not on its disk: not what git carried.
1888
+ const oldKeys = new Map()
1889
+ for (const rel of this.sharedPaths()) if (this.syncable(rel)) oldKeys.set(rel, this.lastKnown.has(rel) ? this.lastKnown.get(rel) : this.sharedKey(rel) ?? null)
1890
+ // What doesn't reach the relay now stays in `from`'s document kept here, and goes out when the folder is back.
1891
+ try { await this.conn.confirmBranch() } catch (err) { this.emit('debug', `confirming ${from} before moving: ${err.message}`) }
1892
+ if (this.stopped) return null
1893
+ this.ig = loadIgnore(this.root) // the checkout's own ignore files
1894
+ const carried = await this.carriedFrom(oldKeys, fromSha)
1895
+ if (this.stopped) return null
1896
+ this.parkLocalState(from)
1897
+ const doc = new Y.Doc()
1898
+ const left = this.unparkLocalState(to, doc)
1899
+ return this.finishMove({ from, to, doc, left, epoch: left ? this.parkedEpoch(to) : null, carried })
1900
+ }
1901
+
1902
+ /**
1903
+ * Joins the new branch's document, writes it onto the folder and goes live there. HEAD is
1904
+ * read again before and after the join: if git has moved on (a quick checkout back, or a
1905
+ * retry long after), this move is dropped without writing anything and the folder follows
1906
+ * HEAD from where it is. Tried again (recheckMove) when the relay can't load the branch yet.
1907
+ */
1908
+ async finishMove (m) {
1909
+ const { from, to, carried } = m
1910
+ let { doc, left } = m
1911
+ let at = await this.headNow()
1912
+ if (this.stopped) return null
1913
+ if (at !== to) return this.abandonMove(m, at)
1914
+ let head = await this.headAt()
1915
+ let reply
1916
+ let fresh = null // the relay's document of `to` is newer than the one this folder kept
1917
+ try {
1918
+ // base: the commit a branch new to the session starts from. It starts as a full document, made from the folder.
1919
+ reply = await this.conn.joinBranch(to, doc, { ...(head && head.sha ? { base: head.sha } : {}), epoch: m.epoch || null, onStale: () => (fresh = new Y.Doc()) })
1920
+ await this.conn.waitForBranchSync()
1921
+ } catch (err) {
1922
+ if (fresh) fresh.destroy()
1923
+ this.pendingMove = m
1924
+ throw err
1925
+ }
1926
+ if (fresh) {
1927
+ // `to` was removed from the session and started again since this folder left it: what it
1928
+ // kept of the old document is dropped, and the folder arrives as one that was never there.
1929
+ doc.destroy()
1930
+ m.doc = doc = fresh
1931
+ m.left = left = null
1932
+ m.epoch = null
1933
+ const said = `${to} was removed from the session (nobody was on it for 30 days) and has been started again since, so what this folder had kept of it is not brought back; the session's files there are on disk.`
1934
+ this.log(`⚠️ ${said}`)
1935
+ this.notice(said)
1936
+ }
1937
+ if (this.stopped) return null
1938
+ head = await this.headAt()
1939
+ at = head ? head.key : null
1940
+ if (this.stopped) return null
1941
+ if (at !== to) return this.abandonMove(m, at)
1942
+ this.pendingMove = null
1943
+ this.moveTries = 0
1944
+ this.moveSaid = null
1945
+ const old = this.bdoc
1946
+ this.bindBranchDoc(doc)
1947
+ old.destroy()
1948
+ this.branch = reply.branch || to
1949
+ this.branchEpoch = typeof reply.epoch === 'string' && reply.epoch ? reply.epoch : null
1950
+ this.branchForm = reply.form === 'diff' ? 'diff' : 'full'
1951
+ this.diffBase = reply.form === 'diff' && typeof reply.diffBase === 'string' ? reply.diffBase : null
1952
+ this.git = head
1953
+ this.gitSeen = head
1954
+ this.rejoin = false
1955
+ this.observeBranch()
1956
+ this.announceBranch()
1957
+ let entries = []
1958
+ let movedOn = null
1959
+ try { entries = await this.arrive({ created: !!reply.created, left, carried }) } finally {
1960
+ // git moved again while the branch was written: still held, and the folder follows on (below).
1961
+ const now = headName(this.root)
1962
+ if (now && now !== this.git.key && !this.stopped && this.hold) { movedOn = now; this.hold.to = now }
1963
+ if (!movedOn) {
1964
+ // What git and the move wrote is accounted for: the next flush is an edit unless git moves again.
1965
+ const late = [...this.heldPaths]
1966
+ this.heldPaths.clear()
1967
+ this.releaseHold()
1968
+ this.gitIndex = indexStamp(this.root)
1969
+ this.headChangedAt = 0
1970
+ this.scanDisk({ baseline: true })
1971
+ this.requeue(late.filter((rel) => this.syncable(rel) && !this.untouchedHere(rel)))
1972
+ }
1973
+ }
1974
+ if (this.stopped) return null
1975
+ if (entries.length && !movedOn) {
1976
+ this.mergeHeld(entries).then(({ conflicts }) => {
1977
+ if (conflicts) this.log(`🔀 ${conflicts} file${conflicts === 1 ? '' : 's'} you changed on ${to} clash with the session's; see Merges.`)
1978
+ }).catch((err) => this.log(`could not merge: ${err.message}`))
1979
+ } else for (const e of entries) this.merging.delete(e.rel)
1980
+ this.saveStateNow()
1981
+ fs.rmSync(this.branchStateDir(to), { recursive: true, force: true }) // in state.bin from here
1982
+ const note = this.moveNote({ from, to: this.branch, created: !!reply.created, carried: [...carried.keys()] })
1983
+ this.log(`🔀 ${note}`)
1984
+ // Agents working in this folder hear it with their next answer; the room sees it in the activity log.
1985
+ this.notice(`This folder moved from ${from} to ${this.branch} (a checkout in git): its files are ${this.branch}'s in the session now, and ${from}'s work stays in the session on ${from}.`)
1986
+ this.doc.transact(() => {
1987
+ this.activity.push([{ by: this.name, path: '', kind: 'switched', detail: '', branch: this.branch, from, ts: Date.now() }])
1988
+ if (this.activity.length > 300) this.activity.delete(0, this.activity.length - 300)
1989
+ }, LOCAL)
1990
+ this.emit('branch', this.branch)
1991
+ this.scheduleStatusWrite()
1992
+ if (movedOn) { this.following = movedOn; return this.moveTo(movedOn) }
1993
+ return { branch: this.branch, note }
1994
+ }
1995
+
1996
+ /**
1997
+ * git moved on before a move finished: nothing of it was written. The connection goes back
1998
+ * to the folder's branch if the join had moved it, and the folder settles there (HEAD came
1999
+ * back) or moves to wherever HEAD is now.
2000
+ */
2001
+ async abandonMove (m, at) {
2002
+ this.pendingMove = null
2003
+ m.doc.destroy()
2004
+ if (this.conn.branchKey !== this.branch) {
2005
+ this.conn.setBranch(this.branch, this.bdoc) // a reconnect meanwhile joins it again by itself
2006
+ this.conn.branchEpoch = this.branchEpoch // the document it holds, for that join (not the one it left)
2007
+ try {
2008
+ await this.conn.joinBranch(this.branch, this.bdoc)
2009
+ await this.conn.waitForBranchSync()
2010
+ } catch (err) { this.emit('debug', `rejoining ${this.branch}: ${err.message}`) }
2011
+ }
2012
+ if (this.stopped) return null
2013
+ if (!at || at === this.branch) return this.settleBack()
2014
+ if (this.hold) this.hold.to = at
2015
+ return this.moveTo(at)
2016
+ }
2017
+
2018
+ /**
2019
+ * Writes the branch document onto a folder git has just put on that branch. A document new
2020
+ * to the session (or empty) is made from the folder as git left it instead, carried work
2021
+ * included. Otherwise what git carried over from the old branch (`carried`: path -> the
2022
+ * old branch's version, still on disk) gets this branch's version, or HEAD's when the
2023
+ * document hasn't the path: the old branch's work never enters this one. Any other path git
2024
+ * shows as changed (an edit made on this branch while Quilt wasn't looking) is merged into
2025
+ * the document: against the version this folder had when it last left the branch (`left`),
2026
+ * else HEAD's; returned as entries for mergeHeld. A file HEAD has that the document hasn't
2027
+ * is left as git has it, and not shared.
2028
+ */
2029
+ async arrive ({ created, left = null, carried = new Map() }) {
2030
+ // What this folder knew of the branch it left says nothing about this one.
2031
+ this.lastKnown.clear()
2032
+ this.storedOnDisk.clear()
2033
+ this.known = null
2034
+ this.writeFailed.clear()
2035
+ this.retry.clear()
2036
+ this.gitOnly.clear()
2037
+ this.clashed.clear()
2038
+ this.relayAgain.clear()
2039
+ this.relayLocal.clear()
2040
+ this.overwritten.close()
2041
+ if (created || (!this.files.size && !this.blobs.size && !(this.diffForm && this.gone.size))) {
2042
+ // What the folder brings to the session is its starting point, not a change anyone made.
2043
+ this.arriving = true
2044
+ this.seeding = true
2045
+ try { for (const rel of walk(this.root, this.ig)) this.ingest(rel) } finally { this.seeding = false; this.arriving = false }
2046
+ return []
2047
+ }
2048
+ // Carried, and still as git carried it (an edit made since is this branch's, and merges).
2049
+ const away = new Set([...carried].filter(([rel, key]) => { const d = this.readDisk(rel); return (d ? d.key : null) === key }).map(([rel]) => rel))
2050
+ const tree = await treeState(this.root, [])
2051
+ if (this.stopped) return []
2052
+ // git can't say what it changed: every path that differs from the session's is merged (a record at worst).
2053
+ const dirty = (tree
2054
+ ? [...tree.dirty].filter((rel) => this.syncable(rel))
2055
+ : [...new Set([...this.sharedPaths(), ...walk(this.root, this.ig)])].filter((rel) => {
2056
+ if (!this.syncable(rel)) return false
2057
+ const disk = this.readDisk(rel)
2058
+ return !(disk && (disk.skip || disk.tooLarge)) && (disk ? disk.key : undefined) !== this.sharedKey(rel)
2059
+ })).filter((rel) => !away.has(rel))
2060
+ const fromHead = [...away].filter((rel) => this.sharedKey(rel) === undefined) // the document hasn't it: HEAD's file
2061
+ // Carried, then edited since the checkout: only that edit is this branch's. Merged against the carried version.
2062
+ const editedSince = new Set(dirty.filter((rel) => carried.has(rel)))
2063
+ const ask = [...dirty, ...fromHead]
2064
+ const atHead = this.git && this.git.sha && ask.length ? await filesAt(this.root, this.git.sha, ask) : null
2065
+ const bins = new Map()
2066
+ for (const rel of [...fromHead, ...editedSince]) {
2067
+ const k = atHead ? atHead.get(rel) : null
2068
+ if (typeof k === 'string' && k.startsWith('bin:')) bins.set(rel, await blobAt(this.root, this.git.sha, rel))
2069
+ }
2070
+ if (this.stopped) return []
2071
+ const changed = new Set(dirty)
2072
+ const shared = this.sharedPaths()
2073
+ this.arriving = true
2074
+ try {
2075
+ this.writeBackAll([...shared].filter((rel) => this.syncable(rel) && !changed.has(rel)))
2076
+ // A diff branch: what the session deleted goes from the folder too (a change of the folder's own to one merges below).
2077
+ if (this.diffForm) this.writeBackAll([...this.gone.keys()].filter((rel) => this.syncable(rel) && !changed.has(rel) && !this.files.has(rel) && !this.blobs.has(rel)))
2078
+ for (const rel of fromHead) this.putHeadVersion(rel, atHead ? atHead.get(rel) : null, bins.get(rel))
2079
+ // HEAD's files the document hasn't: git's, not this folder's change, so not shared.
2080
+ for (const rel of walk(this.root, this.ig)) {
2081
+ if (shared.has(rel) || changed.has(rel) || this.lastKnown.has(rel) || !this.syncable(rel)) continue
2082
+ const disk = this.readDisk(rel)
2083
+ if (disk && !disk.skip && !disk.tooLarge) { this.lastKnown.set(rel, disk.key); this.gitOnly.set(rel, disk.key) }
2084
+ }
2085
+ } finally { this.arriving = false }
2086
+ const baseOf = (rel) => left && left.has(rel) ? left.get(rel) : atHead ? atHead.get(rel) ?? undefined : undefined
2087
+ const entries = []
2088
+ for (const rel of dirty) {
2089
+ if (!editedSince.has(rel)) { entries.push({ rel, base: baseOf(rel), via: 'hold' }); continue }
2090
+ // Merged with this branch's version (HEAD's file when its document hasn't the path): see mergeCarried.
2091
+ entries.push({ rel, base: carried.get(rel), via: 'hold', carried: true, head: atHead ? atHead.get(rel) : undefined, headBuf: bins.get(rel) })
2092
+ }
2093
+ for (const e of entries) this.merging.add(e.rel)
2094
+ return entries
2095
+ }
2096
+
2097
+ /**
2098
+ * A path git carried over from the old branch, edited after the checkout: only that edit is
2099
+ * this branch's. Merged three-way (base: the carried version; ours: the disk; theirs: this
2100
+ * branch's version, or HEAD's file when its document hasn't the path). Anything that doesn't
2101
+ * merge cleanly (a clash, a binary, a file this branch hasn't) is set aside: never a shared
2102
+ * merge record, which would carry the old branch's text into this one.
2103
+ */
2104
+ async mergeCarried ({ rel, base, head, headBuf }) {
2105
+ this.merging.delete(rel)
2106
+ const disk = this.readDisk(rel)
2107
+ if (disk && (disk.skip || disk.tooLarge)) return null
2108
+ const ours = disk ? disk.key : null
2109
+ const inDoc = this.sharedKey(rel) !== undefined
2110
+ if (!inDoc && head === undefined) {
2111
+ // git couldn't read HEAD's file (too large, a filter): left as it is, and not shared.
2112
+ if (disk) this.lastKnown.set(rel, disk.key)
2113
+ return null
2114
+ }
2115
+ const theirs = inDoc ? this.sharedKey(rel) : head // null: neither this branch nor its commit has it
2116
+ if (ours === theirs) { if (ours === null) this.lastKnown.delete(rel); else this.lastKnown.set(rel, ours); return null }
2117
+ if (ours === base) { this.putBranchVersion(rel, { inDoc, head, headBuf }); return null } // not edited after all
2118
+ if (theirs === null) { this.setAsideCarried(rel, { inDoc, head, headBuf, clash: false }); return null } // not on this branch
2119
+ // Edited here and changed on this branch too: combined by Quilt, as mergeOne does.
2120
+ const binary = [base, ours, theirs].some((k) => typeof k === 'string' && k.startsWith('bin:'))
2121
+ if (inDoc) return this.autoSettle({ rel, base, ours, theirs, theirsBy: this.lastEditorOf(rel), disk, binary })
2122
+ // This branch's commit has it, its document doesn't yet: the merge goes onto the disk, and is shared from there.
2123
+ if (ours === null) { this.putHeadVersion(rel, head, headBuf); return null }
2124
+ if (binary) return null // ours, edited after the checkout, is the newer version: it stays, and is shared from the disk
2125
+ const r = mergeAuto(base || '', ours, theirs, { oursNewer: true })
2126
+ this.writeFile(rel, resolveInside(this.root, rel), r.text)
2127
+ this.log(`🧵 ${rel}: your edit after switching to ${this.branch} is merged with ${this.branch}'s own change to it`)
2128
+ return 'merged'
2129
+ }
2130
+
2131
+ /** This branch's version of rel onto the disk: its document's, else HEAD's file, else none. */
2132
+ putBranchVersion (rel, { inDoc, head, headBuf }) {
2133
+ if (!inDoc) return this.putHeadVersion(rel, head, headBuf)
2134
+ const disk = this.readDisk(rel)
2135
+ if (disk && !disk.skip && !disk.tooLarge) this.lastKnown.set(rel, disk.key) // replaced without a copy here: setAsideCarried keeps one
2136
+ this.tryWrite(rel)
2137
+ }
2138
+
2139
+ /** A carried path edited after the checkout that can't merge: the folder's copy under .quilt/conflicts, this branch's version on disk, said once. */
2140
+ setAsideCarried (rel, { inDoc, head, headBuf, clash }) {
2141
+ let dest = null
2142
+ try {
2143
+ if (this.onDisk(rel)) {
2144
+ dest = path.join(this.stateDir, 'conflicts', `${Date.now()}`, ...rel.split('/'))
2145
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
2146
+ fs.copyFileSync(resolveInside(this.root, rel), dest)
2147
+ }
2148
+ } catch (err) { this.log(`could not keep a copy of ${rel}: ${err.message}`); return }
2149
+ this.putBranchVersion(rel, { inDoc, head, headBuf })
2150
+ const copy = dest ? `; your copy is in ${path.relative(this.root, dest).split(path.sep).join('/')}` : ''
2151
+ const text = clash
2152
+ ? `Your edit to ${rel} after switching to ${this.branch} and ${this.branch}'s own change to it are not combined on their own, so ${this.branch}'s version is on disk${copy}.`
2153
+ : `${rel} came over from the old branch in the checkout and isn't on ${this.branch}, so it's off the disk${copy}.`
2154
+ this.log(`📦 ${text}`)
2155
+ this.notice(text)
2156
+ }
2157
+
2158
+ /** A carried path the branch's document hasn't: HEAD's file goes back (`key` from filesAt, `buf` for a binary), or none when HEAD hasn't it either. */
2159
+ putHeadVersion (rel, key, buf) {
2160
+ if (key === undefined) return // git couldn't read it (too large, a filter): left as it is
2161
+ try {
2162
+ const abs = resolveInside(this.root, rel)
2163
+ if (key === null) {
2164
+ fs.rmSync(abs, { force: true })
2165
+ removeEmptyParents(this.root, path.dirname(abs))
2166
+ this.lastKnown.delete(rel)
2167
+ return
2168
+ }
2169
+ const data = key.startsWith('bin:') ? buf : key
2170
+ if (data === null || data === undefined) return
2171
+ fs.mkdirSync(path.dirname(abs), { recursive: true })
2172
+ this.writeFile(rel, abs, data)
2173
+ this.lastKnown.set(rel, key)
2174
+ if (this.sharedKey(rel) === undefined) this.gitOnly.set(rel, key)
2175
+ } catch (err) { this.log(`could not put ${rel} back to your last commit: ${err.message}`) }
2176
+ }
2177
+
2178
+ /**
2179
+ * The paths git carried over from the old branch (path -> the old branch's version): changed
2180
+ * on disk, where the old branch's document differs from its HEAD. (git keeps uncommitted
2181
+ * changes across a checkout; Quilt wrote the session's work there as such.)
2182
+ */
2183
+ async carriedFrom (oldKeys, fromSha) {
2184
+ const out = new Map()
2185
+ const tree = await treeState(this.root, [])
2186
+ if (!tree) return out
2187
+ const dirty = [...tree.dirty].filter((rel) => this.syncable(rel))
2188
+ const was = fromSha && dirty.length ? await filesAt(this.root, fromSha, dirty) : null
2189
+ for (const rel of dirty) {
2190
+ const disk = this.readDisk(rel)
2191
+ if (disk && (disk.skip || disk.tooLarge)) continue
2192
+ // The old branch had uncommitted work here, and git kept a change across the checkout. (The disk may
2193
+ // have been edited again since: arrive merges that edit against the old branch's version.)
2194
+ const head = was ? was.get(rel) : undefined // undefined: git couldn't read it
2195
+ if (oldKeys.has(rel)) { if (oldKeys.get(rel) !== head) out.set(rel, oldKeys.get(rel)) } else if (!disk && head !== null && head !== undefined) out.set(rel, null) // a deletion the old branch made
2196
+ }
2197
+ return out
2198
+ }
2199
+
2200
+ /** The session's version of each path onto the disk, over what git put there (git has that: no copy is kept). */
2201
+ writeBackAll (rels) {
2202
+ for (const rel of rels) {
2203
+ const disk = this.readDisk(rel)
2204
+ if (disk && (disk.skip || disk.tooLarge)) continue
2205
+ if (disk) this.lastKnown.set(rel, disk.key); else this.lastKnown.delete(rel)
2206
+ this.tryWrite(rel)
2207
+ }
2208
+ }
2209
+
2210
+ /** Merges each entry ({ rel, base }) into the session, keeping it out of normal sync while it runs: how many need a person (conflicts), and how many changed the session (changed). */
2211
+ async mergeHeld (entries) {
2212
+ for (const e of entries) this.merging.add(e.rel)
2213
+ let conflicts = 0
2214
+ let changed = 0
2215
+ for (const e of entries) {
2216
+ if (this.stopped) break
2217
+ try {
2218
+ const r = await this.mergeOne(e)
2219
+ if (r === 'conflict') conflicts++
2220
+ else if (r) changed++
2221
+ } catch (err) { this.log(`could not merge ${e.rel}: ${err.message}`) }
2222
+ this.merging.delete(e.rel)
2223
+ }
2224
+ for (const e of entries) this.merging.delete(e.rel)
2225
+ return { conflicts, changed }
2226
+ }
2227
+
2228
+ /** Where the saved state of branch `key` waits while this folder is on another branch. */
2229
+ branchStateDir (key) { return path.join(this.stateDir, 'branches', Buffer.from(key, 'utf8').toString('base64url')) }
2230
+
2231
+ /** Keeps the branch this folder leaves: its document as this app has it (anything the relay hasn't got yet included). */
2232
+ parkLocalState (key) {
2233
+ const dir = this.branchStateDir(key)
2234
+ try {
2235
+ fs.mkdirSync(dir, { recursive: true })
2236
+ fs.writeFileSync(path.join(dir, 'state.bin'), Y.encodeStateAsUpdate(this.bdoc))
2237
+ if (this.branchEpoch) fs.writeFileSync(path.join(dir, 'epoch'), this.branchEpoch)
2238
+ else fs.rmSync(path.join(dir, 'epoch'), { force: true })
2239
+ } catch (err) { this.log(`could not keep ${key}'s state: ${err.message}`) }
2240
+ }
2241
+
2242
+ /** Which document of branch `key` its kept state is a copy of (parkLocalState), or null. */
2243
+ parkedEpoch (key) {
2244
+ try { return fs.readFileSync(path.join(this.branchStateDir(key), 'epoch'), 'utf8').trim() || null } catch { return null }
2245
+ }
2246
+
2247
+ /**
2248
+ * The saved document of a branch this folder was on before (into `doc`). Returns what the folder
2249
+ * had of each path when it left (path -> key), or null when it was never on that branch here.
2250
+ */
2251
+ unparkLocalState (key, doc) {
2252
+ try { Y.applyUpdate(doc, fs.readFileSync(path.join(this.branchStateDir(key), 'state.bin')), LOCAL) } catch { return null }
2253
+ const left = new Map()
2254
+ for (const rel of [...doc.getMap('files').keys(), ...doc.getMap('blobs').keys()]) left.set(rel, docKey(doc, rel))
2255
+ return left
2256
+ }
2257
+
2258
+ /** Partners see which branch this folder is on (presence). */
2259
+ announceBranch () {
2260
+ if (this.conn && this.conn.awareness.getLocalState()) this.conn.awareness.setLocalStateField('branch', this.branch)
2261
+ }
2262
+
2263
+ /** What a move says in the log. */
2264
+ moveNote ({ from, to, created, carried = [] }) {
2265
+ const head = `You're on ${to} now (you switched in git)`
2266
+ if (created) return `${head}. ${to} is new to the session: this folder's files are its starting point, and ${from}'s work stays in the session on ${from}.`
2267
+ const list = carried.slice(0, 3).join(', ') + (carried.length > 3 ? ', …' : '')
2268
+ const brought = carried.length ? ` git had carried ${from}'s uncommitted work in ${list} over: that stays in the session on ${from}, and ${to}'s version is on disk.` : ''
2269
+ return `${head}; the session's work there is on disk.${brought}`
2270
+ }
2271
+
2272
+ /** Watches the folder's .git: HEAD moving is looked at with the next flush, and git starting work holds the folder at once. */
2273
+ startGitWatch () {
2274
+ if (this.gitWatcher || !this.git) return
2275
+ this.gitWatcher = watchGit(this.root, (e) => {
2276
+ if (this.stopped) return
2277
+ if (e.type === 'head') { this.headChangedAt = Date.now(); this.queue(HEAD_CHANGED) } else if (e.type === 'busy') { this.setHold('busy'); this.settleHoldSoon() } else this.settleHoldSoon() // idle, index
2278
+ })
2279
+ }
2280
+
2281
+ // ------------------------------------------------------------ upstream --
2282
+ // Commits the folder's branch is behind (a partner pushed, a pull request merged on GitHub) come in
2283
+ // by themselves. Quilt fetches the branch's upstream (once a minute, and when a partner's folder says
2284
+ // it moved); when the branch can simply move forward, it writes those commits' files under the
2285
+ // folder's uncommitted work and moves the branch and the index there (gitstate.js fastForward), as
2286
+ // `git pull --autostash` would. It never merges git history: a branch with commits of its own the
2287
+ // upstream hasn't, or uncommitted work on the same lines as a commit, is left to the person's git.
2288
+
2289
+ /** Starts looking at the upstream: now, then every UPSTREAM_MS. */
2290
+ startUpstream () {
2291
+ if (!this.git || !this.bringInUpstream || this.upstreamPoll) return
2292
+ this.shareTip()
2293
+ this.upstreamPoll = setInterval(() => this.checkUpstreamSoon({ fetch: true }), UPSTREAM_MS)
2294
+ this.upstreamPoll.unref()
2295
+ this.checkUpstreamSoon({ fetch: true, delay: 2000 })
2296
+ }
2297
+
2298
+ /** Tells partners which commit this folder's branch is at, so theirs look for it when it moves. */
2299
+ shareTip () {
2300
+ if (!this.conn || !this.conn.awareness || !this.conn.awareness.getLocalState() || !this.git) return
2301
+ const was = this.conn.awareness.getLocalState().tip
2302
+ const tip = this.git.branch && this.git.sha ? { key: this.git.key, sha: this.git.sha } : null
2303
+ if (JSON.stringify(was || null) !== JSON.stringify(tip)) this.conn.awareness.setLocalStateField('tip', tip)
2304
+ }
2305
+
2306
+ /** A partner's folder on this branch is at a commit this one isn't: it may have pushed, so this folder fetches (again a little later: a push follows its commit). */
2307
+ notePeerTips () {
2308
+ if (!this.git || !this.git.branch || !this.bringInUpstream || !this.conn) return
2309
+ let moved = false
2310
+ for (const [id, st] of this.conn.awareness.getStates()) {
2311
+ if (id === this.doc.clientID || !st || !st.tip || st.tip.key !== this.git.key || typeof st.tip.sha !== 'string') continue
2312
+ if (this.peerTips.get(id) === st.tip.sha) continue
2313
+ this.peerTips.set(id, st.tip.sha)
2314
+ if (st.tip.sha !== this.git.sha) moved = true
2315
+ }
2316
+ if (!moved) return
2317
+ this.checkUpstreamSoon({ fetch: true, delay: 1500 })
2318
+ for (const ms of [10 * 1000, 30 * 1000]) setTimeout(() => this.checkUpstreamSoon({ fetch: true }), ms).unref()
2319
+ }
2320
+
2321
+ /** Looks at the upstream once the folder has been quiet for `delay`; `fetch`: asks the remote first. */
2322
+ checkUpstreamSoon ({ fetch = false, delay = GIT_SETTLE_MS } = {}) {
2323
+ if (this.stopped || !this.git || !this.bringInUpstream) return
2324
+ this.upstreamFetch = this.upstreamFetch || fetch
2325
+ clearTimeout(this.upstreamTimer)
2326
+ this.upstreamTimer = setTimeout(() => {
2327
+ this.upstreamTimer = null
2328
+ const f = this.upstreamFetch
2329
+ this.upstreamFetch = false
2330
+ this.checkUpstream({ fetch: f }).catch((err) => this.log(`could not look for new commits: ${err.message}`))
2331
+ }, delay)
2332
+ this.upstreamTimer.unref()
2333
+ }
2334
+
2335
+ /** The folder isn't ready for a look at its upstream yet: asked again, a little later each time (the next minute's look comes anyway). */
2336
+ upstreamLater () {
2337
+ this.checkUpstreamSoon({ delay: Math.min(UPSTREAM_MS, 2000 * 2 ** Math.min(this.upstreamTries++, 5)) })
2338
+ }
2339
+
2340
+ /** Nothing of git's or the session's is on its way in this folder: the disk is what the session has. */
2341
+ quietForUpstream () {
2342
+ return this.ready && !this.stopped && !this.hold && !this.pendingMove && !this.arriving && !this.gitBusy() && !this.pending.size && !this.merging.size
2343
+ }
2344
+
2345
+ /**
2346
+ * Where the folder's branch stands against its upstream, and, when it is only behind, the commits
2347
+ * brought in (bringIn). The fetch runs on its own (it can wait on the network); what reads and moves
2348
+ * the branch runs with the folder's other git work, one piece at a time.
2349
+ */
2350
+ async checkUpstream ({ fetch = false } = {}) {
2351
+ if (this.stopped || !this.ready || !this.git || !this.git.branch) return
2352
+ const branch = this.git.branch
2353
+ const up = await upstreamOf(this.root)
2354
+ if (!up || !up.remote || up.remote === '.') { this.setUpstream(null); return }
2355
+ if (fetch) {
2356
+ const f = await fetchUpstream(this.root, up.remote)
2357
+ if (this.stopped) return
2358
+ if (!f.ok && f.error && f.error !== this.fetchSaid) this.log(`could not look for new commits on ${up.name}: ${f.error}`)
2359
+ this.fetchSaid = f.ok ? '' : f.error || ''
2360
+ }
2361
+ await this.gitTask(async () => {
2362
+ if (!this.git || this.git.branch !== branch || headName(this.root) !== branch) return
2363
+ if (!this.quietForUpstream()) { this.upstreamLater(); return }
2364
+ const now = await upstreamOf(this.root)
2365
+ const at = await branchTip(this.root, branch)
2366
+ if (!now || !now.sha || !at || this.stopped) return
2367
+ if (at === now.sha) { this.setUpstream({ name: now.name, sha: now.sha, behind: 0, ahead: 0 }); return }
2368
+ const n = await aheadBehind(this.root, at, now.sha)
2369
+ if (!n) return
2370
+ const facts = { name: now.name, sha: now.sha, ...n }
2371
+ if (!n.behind) { this.setUpstream(facts); return }
2372
+ const commits = (k) => `${k} commit${k === 1 ? '' : 's'}`
2373
+ if (n.ahead) {
2374
+ await this.stageArrived(at, now.sha)
2375
+ this.setUpstream({ ...facts, waiting: `${branch} has ${commits(n.ahead)} of its own and ${now.name} has ${commits(n.behind)} it doesn't. Quilt never merges git history: pull with \`git pull --rebase --autostash\` (or \`--no-rebase\` to merge) when you are ready.` })
2376
+ return
2377
+ }
2378
+ await this.bringIn(at, now.sha, facts)
2379
+ })
2380
+ }
2381
+
2382
+ /**
2383
+ * The upstream's commits wait for the person's own pull, and the session already put some of the
2384
+ * files they add in this folder (a partner's folder brought them in). git refuses a pull over a
2385
+ * file it doesn't track, so each one this folder has exactly as the commits have it is staged:
2386
+ * a pull with --autostash then goes through, and ends with nothing to commit for them.
2387
+ */
2388
+ async stageArrived (from, to) {
2389
+ const changes = await changesBetween(this.root, from, to)
2390
+ if (!changes) return
2391
+ const added = [...changes].filter(([, c]) => c.status === 'A' && c.plain).map(([rel]) => rel)
2392
+ if (!added.length) return
2393
+ const [theirs, state] = [await filesAt(this.root, to, added), await treeState(this.root, added)]
2394
+ if (!theirs || !state || this.stopped || !this.quietForUpstream()) return
2395
+ const here = added.filter((rel) => {
2396
+ if (state.tracked.has(rel)) return false
2397
+ let d = null
2398
+ try { d = this.readDisk(rel) } catch { return false }
2399
+ return !!d && !d.skip && !d.tooLarge && d.key === theirs.get(rel)
2400
+ })
2401
+ if (!here.length || !(await stage(this.root, here))) return
2402
+ this.gitIndex = indexStamp(this.root) // Quilt's own write of the index: no burst of git's
2403
+ this.log(`staged ${here.length} file${here.length === 1 ? '' : 's'} the session brought here from ${to.slice(0, 7)} (${here.slice(0, 3).join(', ')}${here.length > 3 ? ', …' : ''}), so a pull with --autostash goes through`)
2404
+ }
2405
+
2406
+ /** Keeps what is known of the upstream, and says why commits wait (to the log and the AI) once per reason. */
2407
+ setUpstream (u) {
2408
+ const was = JSON.stringify(this.upstream)
2409
+ this.upstream = u
2410
+ const said = u && u.waiting ? `${u.sha}:${u.waiting}` : ''
2411
+ if (said && said !== this.upstreamSaid) {
2412
+ this.log(`⏸️ ${u.waiting}`)
2413
+ this.notice(u.waiting)
2414
+ }
2415
+ this.upstreamSaid = said
2416
+ if (JSON.stringify(u) !== was) { this.emit('status-changed'); this.scheduleStatusWrite() }
2417
+ }
2418
+
2419
+ /**
2420
+ * The branch is at `from` and only behind `to`: each file the commits changed is written under
2421
+ * the folder's own work (untouched here: the commits' version; changed here too, on other lines:
2422
+ * both), then the index and the branch move to `to`. All or nothing: when a file can't be combined
2423
+ * (the same lines changed here and there, a binary both changed, a link, a file Quilt can't read)
2424
+ * nothing is written and the commits are left to the person's git, with the reason said once.
2425
+ */
2426
+ async bringIn (from, to, facts) {
2427
+ const branch = this.git.branch
2428
+ const changes = await changesBetween(this.root, from, to)
2429
+ if (!changes) return
2430
+ const rels = [...changes.keys()]
2431
+ const [base, theirs] = [await filesAt(this.root, from, rels), await filesAt(this.root, to, rels)]
2432
+ if (!base || !theirs || this.stopped) return
2433
+ if (!this.quietForUpstream() || headName(this.root) !== branch) { this.upstreamLater(); return }
2434
+ const isText = (k) => typeof k === 'string' && !k.startsWith('bin:')
2435
+ const writes = new Map() // rel -> the file's key after (null: deleted)
2436
+ const clashes = []
2437
+ const unread = []
2438
+ for (const rel of rels) {
2439
+ const b = base.get(rel)
2440
+ const t = theirs.get(rel)
2441
+ let d = null
2442
+ try { d = this.readDisk(rel) } catch { d = { skip: true } }
2443
+ const o = !d ? null : d.skip || d.tooLarge ? undefined : d.key
2444
+ if (!changes.get(rel).plain || b === undefined || t === undefined || o === undefined) { unread.push(rel); continue }
2445
+ // A file whose clash is still in this folder (its own lines between markers) is its writer's to settle first.
2446
+ if (this.clashed.has(rel)) { clashes.push(rel); continue }
2447
+ // The session and this folder must agree first: a change still on its way waits for the next look.
2448
+ if (this.syncable(rel) && !this.followsGit(rel) && (o ?? undefined) !== this.sharedKey(rel)) { this.upstreamLater(); return }
2449
+ if (o === t) continue // the session has it already (a partner committed what everyone was editing)
2450
+ if (o === b) { writes.set(rel, t); continue } // untouched here: the commits' version
2451
+ if ((b === null || isText(b)) && isText(o) && isText(t)) {
2452
+ const r = merge3(b ?? '', o, t)
2453
+ if (!r.conflicts.length) { if (r.text !== o) writes.set(rel, r.text); continue }
2454
+ }
2455
+ clashes.push(rel)
2456
+ }
2457
+ this.upstreamTries = 0
2458
+ const commits = `${facts.behind} commit${facts.behind === 1 ? '' : 's'}`
2459
+ const list = (a) => a.slice(0, 4).join(', ') + (a.length > 4 ? ` and ${a.length - 4} more` : '')
2460
+ if (unread.length) {
2461
+ this.setUpstream({ ...facts, waiting: `${facts.name} has ${commits} this folder doesn't, and Quilt can't read ${list(unread)} to bring ${unread.length === 1 ? 'it' : 'them'} in (too large, a link, a submodule, or behind a filter such as Git LFS). Nothing was brought in: pull with \`git pull --rebase --autostash\` (or \`--no-rebase\` to merge) when you are ready.` })
2462
+ return
2463
+ }
2464
+ if (clashes.length) {
2465
+ this.setUpstream({ ...facts, waiting: `${facts.name} has ${commits} this folder doesn't, and ${list(clashes)} changed there on the same lines as work here that isn't committed. Nothing was brought in: commit your work, then pull with \`git pull --rebase --autostash\` (or \`--no-rebase\` to merge) and settle the conflict there.` })
2466
+ return
2467
+ }
2468
+ let written = 0
2469
+ const writeFiles = async () => {
2470
+ for (const [rel, key] of writes) {
2471
+ const abs = resolveInside(this.root, rel)
2472
+ if (key === null) {
2473
+ fs.rmSync(abs, { force: true })
2474
+ removeEmptyParents(this.root, path.dirname(abs))
2475
+ } else {
2476
+ const data = key.startsWith('bin:') ? await blobAt(this.root, to, rel) : key
2477
+ if (data === null) throw new Error(`git could not read ${rel}`)
2478
+ fs.mkdirSync(path.dirname(abs), { recursive: true })
2479
+ this.writeFile(rel, abs, data)
2480
+ }
2481
+ written++
2482
+ // Shared as the commits' change, not an edit of this person's (the next look at the file finds nothing new).
2483
+ if (this.syncable(rel)) this.ingest(rel, { pulled: true })
2484
+ }
2485
+ // git tracks whether a file can be run: the folder's files follow the commits in that too.
2486
+ if (process.platform !== 'win32') {
2487
+ for (const [rel, c] of changes) {
2488
+ if (c.exec === null) continue
2489
+ try {
2490
+ const abs = resolveInside(this.root, rel)
2491
+ const mode = fs.statSync(abs).mode
2492
+ if (!!(mode & 0o100) !== c.exec) fs.chmodSync(abs, c.exec ? mode | 0o111 : mode & ~0o111)
2493
+ } catch {}
2494
+ }
2495
+ }
2496
+ }
2497
+ let moved = false
2498
+ try { moved = await fastForward(this.root, branch, from, to, writeFiles) } catch (err) { this.log(`could not bring in ${facts.name}'s commits: ${err.message}`) }
2499
+ if (!moved) { this.checkUpstreamSoon({ delay: 5000 }); return }
2500
+ // What git and Quilt just wrote is accounted for: the next flush is no burst of git's.
2501
+ this.git = { key: this.git.key, branch, sha: to }
2502
+ this.gitSeen = this.git
2503
+ this.gitIndex = indexStamp(this.root)
2504
+ this.headChangedAt = 0
2505
+ this.scheduleStateSave()
2506
+ this.shareTip()
2507
+ this.log(`⬇️ brought in ${commits} from ${facts.name}${written ? ` (${written} file${written === 1 ? '' : 's'} written)` : ': the session already had their files'}`)
2508
+ this.setUpstream({ name: facts.name, sha: to, behind: 0, ahead: 0, brought: { count: facts.behind, files: written, at: Date.now() } })
2509
+ }
2510
+
1562
2511
  /**
1563
2512
  * Puts back the .git an older Quilt set aside in this folder (git-aside.js), once, when the session
1564
2513
  * starts and the relay has synced. A folder that got a new .git meanwhile keeps both. Whether git came back.
@@ -1599,32 +2548,17 @@ export class Session extends EventEmitter {
1599
2548
 
1600
2549
  /**
1601
2550
  * Pushes the on-disk state of a path into the shared doc. Returns true if anything changed.
1602
- * `pulled`: git brought this version (a pull), so it is not an edit of ours: never boxed, and counted as the pull's.
2551
+ * `pulled`: git brought this version (a pull), so it is not an edit of ours: it is counted as the pull's.
1603
2552
  */
1604
2553
  ingest (rel, { pulled = false } = {}) {
1605
2554
  if (!this.syncable(rel)) return false
1606
2555
  if (this.merging.has(rel)) return false // its offline merge hasn't run yet; see mergeOffline
1607
- // A plain `rm` of a file a fetched pull would bring (git said to remove it): making way, not a deletion.
2556
+ if (this.held()) { this.heldPaths.add(rel); return false } // git is at work in this folder, or it is moving to another branch; see onSettled
1608
2557
  if (this.downloading.has(rel)) return false // our copy is being replaced by a download
1609
2558
  if (this.writeFailed.has(rel)) return false // the shared version never reached the disk: what's there is no edit of ours
1610
- // New ignore rules: a box of ours on a file they now leave out lets go (settleBoxesOnce).
1611
2559
  if (IGNORE_FILES.includes(path.posix.basename(rel)) || rel === '.gitmodules') { this.ig = loadIgnore(this.root) }
1612
2560
  const disk = this.readDisk(rel, { settle: true })
1613
2561
  if (disk && disk.unsettled) { this.settleSoon(rel); return false }
1614
- const boxed = this.boxedByOther(rel)
1615
- if (boxed) {
1616
- // Someone else's box: what this folder has is its version from before the box, never theirs.
1617
- if ((disk ? disk.key : undefined) === this.lastKnown.get(rel)) return false // no edit
1618
- if (disk && (disk.skip || disk.tooLarge)) return false
1619
- // Git brought it in (the owner pushed it, and this folder pulled): git's, kept here, not shared.
1620
- if (pulled) {
1621
- if (disk) this.lastKnown.set(rel, disk.key); else this.lastKnown.delete(rel)
1622
- this.boxBase.set(rel, !disk ? null : disk.binary ? { b64: disk.buf.toString('base64') } : { text: disk.text })
1623
- this.scheduleStateSave()
1624
- return false
1625
- }
1626
- return this.editBoxed(rel, disk, boxed)
1627
- }
1628
2562
  const gitWas = this.gitOnly.get(rel) // git's version of a file the document hasn't, as this folder last had it
1629
2563
  if (this.gitOnly.size && this.gitOnly.has(rel)) {
1630
2564
  // A file git has that this branch's document hasn't, as the move left it: git's, not an edit.
@@ -1662,13 +2596,11 @@ export class Session extends EventEmitter {
1662
2596
  this.rejectLocal(rel, disk, refusal)
1663
2597
  return false
1664
2598
  }
1665
- // A change of ours while our AI works goes into a box of ours (unfinished work, out of other folders
1666
- // until it's committed). A person typing by hand while their AI sits idle edits live with everyone.
1667
- // Quilt's own line in .gitignore (ignoreQuiltState) is nobody's edit: never boxed for anyone.
2599
+ // A change of ours while our AI works is noted for its working state (noteAiEdit).
2600
+ // Quilt's own line in .gitignore (ignoreQuiltState) is nobody's edit.
1668
2601
  const quiltOwn = this.quiltOwnWrite === rel && disk && disk.key === this.quiltOwnKey
1669
2602
  if (quiltOwn) { this.quiltOwnWrite = null; this.quiltOwnKey = null }
1670
- // With boxes, a deletion is boxed too: it reaches nobody else's folder until it's committed.
1671
- if ((disk || this.boxesOn()) && !pulled && !quiltOwn && this.ready && !this.seeding && changesIt && this.aiMayBeEditing()) this.boxEdit(rel)
2603
+ if (disk && !pulled && !quiltOwn && this.ready && !this.seeding && changesIt && this.aiMayBeEditing()) this.noteAiEdit(rel)
1672
2604
 
1673
2605
  if (!disk) {
1674
2606
  if (!this.files.has(rel) && !this.blobs.has(rel)) {
@@ -1714,6 +2646,17 @@ export class Session extends EventEmitter {
1714
2646
  return true
1715
2647
  }
1716
2648
 
2649
+ // A clash to settle in this file (relayClashed): not shared while its markers are in it. Saved again
2650
+ // with them still there, its writer's AI is told once more.
2651
+ if (!disk.binary && hasMarkers(disk.text)) {
2652
+ if (this.clashed.get(rel) !== disk.text) {
2653
+ this.clashed.set(rel, disk.text)
2654
+ this.notice(clashStillNotice(rel))
2655
+ this.log(`⚖️ ${rel}: still has conflict markers, so it is not shared yet`)
2656
+ }
2657
+ return false
2658
+ }
2659
+ if (this.clashed.delete(rel)) this.log(`⚖️ ${rel}: its conflict markers are gone; sharing it`)
1717
2660
  if (disk.key === this.sharedKey(rel)) {
1718
2661
  this.lastKnown.set(rel, disk.key)
1719
2662
  if (stored && stored.stored) this.setOnDisk(rel, stored.hash)
@@ -1849,7 +2792,9 @@ export class Session extends EventEmitter {
1849
2792
  ...(typeof base === 'string' && base.length <= 256 * 1024 ? { baseText: base } : {}),
1850
2793
  text,
1851
2794
  ...(older !== base && typeof older === 'string' ? { older } : {}),
1852
- ...(fromGit ? { fromGit: true } : {})
2795
+ ...(fromGit ? { fromGit: true } : {}),
2796
+ // A clash is settled in this folder's own file (relayClashed): the relay takes nothing of a save that clashes.
2797
+ ...(this.noClashMarkers ? {} : { markers: true })
1853
2798
  }
1854
2799
  // What does not touch the text stays an edit here: its mode, and where a diff branch's entry started.
1855
2800
  this.transact(() => {
@@ -1873,6 +2818,7 @@ export class Session extends EventEmitter {
1873
2818
  if (r.fallback) { this.relayLocal.add(rel); this.relayAgain.delete(rel); try { this.ingest(rel, { pulled }) } catch (err) { this.log(`could not sync ${rel}: ${err.message}`) } return }
1874
2819
  if (trusted && this.liveEngine) this.liveEngine.trusted.delete(rel)
1875
2820
  if (this.conn.branchKey !== key) { this.relayAgain.delete(rel); this.queue(rel); return } // the folder moved to another branch meanwhile
2821
+ if (r.conflict) return this.relayClashed(rel, disk, r)
1876
2822
  const result = r.same ? disk.text : r.text
1877
2823
  // A save told of a clash is not an older copy its writer may save from unknowing: what it saves next is meant.
1878
2824
  const clashed = (r.held || []).length > 0
@@ -1887,7 +2833,11 @@ export class Session extends EventEmitter {
1887
2833
  if (r.detail) this.transact(() => this.recordActivity(rel, created && !r.before ? 'created' : 'edited', r.detail, { before: r.before ?? '', after: result }, { pulled }), LOCAL)
1888
2834
  let now = null
1889
2835
  try { now = this.readDisk(rel) } catch {}
1890
- if (now && !now.binary && now.text === disk.text) {
2836
+ // git is at work here, or the folder is moving to another branch: the result is not written over what git
2837
+ // may be writing. This folder had what it sent; the result comes to disk when the hold ends (resumeHeld).
2838
+ const held = this.held()
2839
+ if (held) this.heldPaths.add(rel)
2840
+ if (!held && now && !now.binary && now.text === disk.text) {
1891
2841
  // Disk still has what was sent: it gets the result (the lines that landed first, with this edit's others).
1892
2842
  let over = true
1893
2843
  if (result !== disk.text) {
@@ -1900,7 +2850,7 @@ export class Session extends EventEmitter {
1900
2850
  }
1901
2851
  // Saved again in that instant: that save is taken in next, merged on what was sent.
1902
2852
  this.lastKnown.set(rel, over === false ? disk.text : result)
1903
- } else this.lastKnown.set(rel, disk.text) // saved again since: that save is taken in next, merged on what was sent
2853
+ } else this.lastKnown.set(rel, disk.text) // saved again since (or held): what the disk has is taken in next, merged on what was sent
1904
2854
  this.setOnDisk(rel, null)
1905
2855
  for (const n of r.notices || []) this.notice(n)
1906
2856
  for (const l of r.logs || []) this.log(l)
@@ -1916,6 +2866,45 @@ export class Session extends EventEmitter {
1916
2866
  }
1917
2867
  }
1918
2868
 
2869
+ /**
2870
+ * The relay took nothing of a save of rel: someone changed the same lines first. The file here gets the save
2871
+ * merged onto the session's text as it is now, with both versions of the clashing lines between markers, and
2872
+ * the writer's AI is told. That text (`r.base`) is what the next save is merged against; a save with markers
2873
+ * still in it is never sent (ingest), and a partner's change is not written over the file meanwhile (writeOut
2874
+ * sees an edit not sent yet).
2875
+ */
2876
+ relayClashed (rel, disk, r) {
2877
+ // git is at work here, or the folder is moving: nothing is written into the file now. The save is sent again when the hold ends.
2878
+ if (this.held()) { this.relayAgain.delete(rel); this.heldPaths.add(rel); return }
2879
+ this.overwritten.forget(rel)
2880
+ for (const n of r.notices || []) this.notice(n)
2881
+ for (const l of r.logs || []) this.log(l)
2882
+ const who = (r.others || []).join(', ') || 'someone'
2883
+ let now = null
2884
+ try { now = this.readDisk(rel) } catch {}
2885
+ let over = false
2886
+ if (now && !now.binary && now.text === disk.text && typeof r.text === 'string' && typeof r.base === 'string') {
2887
+ try {
2888
+ const abs = resolveInside(this.root, rel)
2889
+ over = this.writeOver(rel, abs, r.text, now)
2890
+ if (over === null) { this.writeFile(rel, abs, r.text); over = true }
2891
+ } catch (err) { this.log(`could not write ${rel}: ${err.message}`); this.relayAgain.delete(rel); return }
2892
+ }
2893
+ if (over) {
2894
+ this.lastKnown.set(rel, r.base)
2895
+ this.setOnDisk(rel, null)
2896
+ this.clashed.set(rel, r.text)
2897
+ this.relayAgain.delete(rel)
2898
+ this.notice(clashNotice(rel, who))
2899
+ this.log(`⚖️ ${rel}: ${who} changed the same lines first; both versions are in your file to settle`)
2900
+ this.scheduleStatusWrite?.()
2901
+ return
2902
+ }
2903
+ // Saved again since: that save is taken in next, on what this folder last had.
2904
+ this.relayAgain.delete(rel)
2905
+ try { this.ingest(rel) } catch (err) { this.log(`could not sync ${rel}: ${err.message}`) }
2906
+ }
2907
+
1919
2908
  /** A live write the relay never answered: an older relay (the edit goes in here, as before), or no connection (tried again). */
1920
2909
  relayFailed (rel, err) {
1921
2910
  this.relayWriting.delete(rel)
@@ -2182,8 +3171,8 @@ export class Session extends EventEmitter {
2182
3171
 
2183
3172
  writeOut (rel) {
2184
3173
  if (!this.syncable(rel)) return
2185
- if (this.ghost(rel)) return
2186
3174
  if (this.merging.has(rel)) return // mergeOffline writes this path once it has merged it
3175
+ if (this.held()) { this.heldPaths.add(rel); return } // written when the hold ends (resumeHeld), or not at all once the folder has moved
2187
3176
  let abs
2188
3177
  try { abs = resolveInside(this.root, rel) } catch (err) { this.log(err.message); return }
2189
3178
  const shared = this.sharedKey(rel)
@@ -2241,7 +3230,6 @@ export class Session extends EventEmitter {
2241
3230
  if (!b || !b.stored) this.setOnDisk(rel, null)
2242
3231
  this.lastKnown.set(rel, shared)
2243
3232
  }
2244
- // New ignore rules: a box of ours on a file they now leave out lets go (settleBoxesOnce).
2245
3233
  if (IGNORE_FILES.includes(path.posix.basename(rel)) || rel === '.gitmodules') { this.ig = loadIgnore(this.root) }
2246
3234
 
2247
3235
  if (this.ready && !this.arriving) { // a move writing its branch onto the folder is no partner's change
@@ -2254,45 +3242,6 @@ export class Session extends EventEmitter {
2254
3242
  }
2255
3243
  }
2256
3244
 
2257
- /**
2258
- * Whether rel is someone else's box (docs/superpowers/specs/2026-10-16-git-boxes-design.md): their
2259
- * unfinished work stays in the session, not in this folder, so nothing run here commits it. The
2260
- * folder's version is kept, for putting back an edit refused meanwhile; lastKnown stays at it, so
2261
- * it's no edit of ours.
2262
- */
2263
- ghost (rel) {
2264
- if (!this.boxedByOther(rel)) return false
2265
- if (!this.boxBase.has(rel)) {
2266
- let d = null
2267
- try { d = this.readDisk(rel) } catch {}
2268
- if (d && (d.skip || d.tooLarge)) return true // nothing Quilt would ever put back
2269
- this.boxBase.set(rel, !d ? null : d.binary ? { b64: d.buf.toString('base64') } : { text: d.text })
2270
- this.scheduleStateSave()
2271
- }
2272
- return true
2273
- }
2274
-
2275
- /**
2276
- * An edit here to a file someone else has boxed. It is never undone: Quilt holds no files (no-holds,
2277
- * 2026-11-13). Their box opens, so their work reaches every folder (the relay tells them), and this
2278
- * edit goes in straight away through the normal merge (autoSettle), from this folder's version
2279
- * before the box. Returns true when the session's version changed.
2280
- */
2281
- editBoxed (rel, disk, box) {
2282
- const before = this.boxBase.has(rel) ? this.boxBase.get(rel) : undefined
2283
- const base = before === null ? null : before && typeof before.text === 'string' ? before.text : undefined
2284
- if (this.boxBase.delete(rel)) this.scheduleStateSave()
2285
- if (this.conn) this.conn.boxRequest({ op: 'unbox', pattern: rel, edit: true }).catch((err) => this.log(`could not open ${box.by}'s box on ${rel}: ${err.message}`))
2286
- // Not someone else's box here any more, from now: the session's version is written to this folder again.
2287
- this.boxed.delete(rel)
2288
- this.log(`📦 ${rel} was in ${box.of || box.by}'s box: it opened, and your change goes in with their work`)
2289
- const ours = disk ? disk.key : null
2290
- const theirs = this.sharedKey(rel)
2291
- if (theirs === base || (theirs === undefined && base === null)) return this.ingest(rel) // their box changed nothing of it
2292
- const binary = [ours, theirs].some((k) => typeof k === 'string' && k.startsWith('bin:')) || !!(before && typeof before.b64 === 'string')
2293
- return this.autoSettle({ rel, base: binary ? null : base, ours, theirs, theirsBy: box.of || box.by, disk, binary, via: null }) === 'merged'
2294
- }
2295
-
2296
3245
  /**
2297
3246
  * Writes the session's version over a file of this folder's that a save may land in at the same moment:
2298
3247
  * in a file of its own put in place by one atomic exchange (swap-in.js; the file is never absent at its
@@ -2583,6 +3532,7 @@ export class Session extends EventEmitter {
2583
3532
  /** Tries failed uploads, downloads and writes again. */
2584
3533
  retryFailed () {
2585
3534
  if (!this.ready || this.stopped) return
3535
+ if (this.hold && this.hold.kind === 'switching' && !this.following) this.recheckSoon()
2586
3536
  const failed = [...this.retry]
2587
3537
  this.retry.clear()
2588
3538
  for (const [rel, kind] of failed) {
@@ -2695,6 +3645,7 @@ export class Session extends EventEmitter {
2695
3645
  disk = null // read again once it's our turn, so waiting uploads don't hold files in memory
2696
3646
  if (this.uploading.get(rel) === hash) return
2697
3647
  this.uploading.set(rel, hash)
3648
+ const doc = this.bdoc
2698
3649
  // If a partner's version lands while this uploads, theirs wins (ours is kept as a conflict copy).
2699
3650
  const sharedBefore = this.sharedKey(rel)
2700
3651
  await this.startTransfer()
@@ -2718,6 +3669,8 @@ export class Session extends EventEmitter {
2718
3669
  }
2719
3670
  const now = this.readDisk(rel)
2720
3671
  if (!now || now.key !== diskKey) return // it changed again; that change is already queued
3672
+ if (this.bdoc !== doc) return // the folder moved to another branch meanwhile: this was the old branch's
3673
+ if (this.held()) { this.heldPaths.add(rel); return } // git is at work here: looked at again when the hold ends
2721
3674
  if (this.sharedKey(rel) !== sharedBefore || this.downloading.has(rel)) return // a partner's version landed first: it stays
2722
3675
  const existed = this.files.has(rel) || this.blobs.has(rel)
2723
3676
  this.transact(() => {
@@ -2771,7 +3724,6 @@ export class Session extends EventEmitter {
2771
3724
 
2772
3725
  /** Downloads and decrypts a large file, then writes it into the folder. */
2773
3726
  async downloadLarge (rel, entry) {
2774
- if (this.ghost(rel)) return // someone else's box: downloaded once it opens
2775
3727
  if (this.downloading.get(rel) === entry.hash) return
2776
3728
  this.downloading.set(rel, entry.hash)
2777
3729
  const before = this.readDisk(rel)?.key
@@ -2792,7 +3744,7 @@ export class Session extends EventEmitter {
2792
3744
  const cur = this.blobs.get(rel)
2793
3745
  if (!cur || cur.hash !== entry.hash) return // replaced meanwhile; that version is on its way
2794
3746
  if (this.stopped) return
2795
- if (this.ghost(rel)) return // boxed by someone else meanwhile: written once it opens
3747
+ if (this.held()) { this.heldPaths.add(rel); return } // git is at work here: written once the hold ends (resumeHeld)
2796
3748
  const abs = resolveInside(this.root, rel)
2797
3749
  let st = null
2798
3750
  try { st = fs.lstatSync(abs) } catch {}
@@ -2834,6 +3786,8 @@ export class Session extends EventEmitter {
2834
3786
  // --------------------------------------------------------------- watcher --
2835
3787
 
2836
3788
  async startWatcher () {
3789
+ this.startGitWatch()
3790
+ this.startUpstream()
2837
3791
  this.scanDisk({ baseline: true }) // the folder was just reconciled; the first re-scan catches anything since
2838
3792
  this.watcher = watch(this.root, {
2839
3793
  ignoreInitial: true,
@@ -2863,7 +3817,13 @@ export class Session extends EventEmitter {
2863
3817
  })
2864
3818
  this.watcher.on('error', (err) => this.log(`watcher error: ${err.message}`))
2865
3819
  await new Promise((resolve) => this.watcher.once('ready', resolve))
2866
- this.reconcileTimer = setInterval(() => { if (this.ready) this.scanDisk() }, RECONCILE_MS)
3820
+ this.reconcileTimer = setInterval(() => {
3821
+ if (!this.ready) return
3822
+ // A checkout the git watcher missed (one that changes no file leaves nothing else to see).
3823
+ const at = this.git && !this.hold ? headName(this.root) : null
3824
+ if (at && at !== this.git.key) this.queue(HEAD_CHANGED)
3825
+ this.scanDisk()
3826
+ }, RECONCILE_MS)
2867
3827
  this.reconcileTimer.unref()
2868
3828
  this.scanDisk()
2869
3829
  }
@@ -2920,6 +3880,8 @@ export class Session extends EventEmitter {
2920
3880
  if (s && id !== this.doc.clientID) this.log(`👋 ${s.name} joined (${s.tool})`)
2921
3881
  }
2922
3882
  if (removed.length) this.log(`${removed.length === 1 ? 'a partner' : `${removed.length} partners`} left`)
3883
+ for (const id of removed) this.peerTips.delete(id)
3884
+ this.notePeerTips()
2923
3885
  this.scheduleStatusWrite()
2924
3886
  this.scheduleTypingExpiry()
2925
3887
  })
@@ -3811,9 +4773,6 @@ export class Session extends EventEmitter {
3811
4773
  /** Who an action from this AI session is by: its own name, or this member's. */
3812
4774
  actorName (via) { const p = this.persona(via); return p ? p.name : this.name }
3813
4775
 
3814
- /** The box request fields that make the relay act for an AI session (server.js boxOwner). */
3815
- as (via) { const p = this.persona(via); return p ? { as: { id: p.rid || p.via, label: p.label } } : {} }
3816
-
3817
4776
  /** Whether a name is this member's or one of its AI sessions' (now or before a rename). */
3818
4777
  isMine (name) {
3819
4778
  if (!name) return false
@@ -3829,9 +4788,6 @@ export class Session extends EventEmitter {
3829
4788
  return [this.name, ...(this.aiOf ? [aiName(this.aiOf)] : []), ...[...this.personas.values()].flatMap((p) => [p.name, ...p.aliases])]
3830
4789
  }
3831
4790
 
3832
- /** Whether a box is this member's or one of its AI sessions': its work is in this folder. */
3833
- isOwnBox (c) { return !!c && (c.by === this.name || c.of === this.name || this.isMine(c.by)) }
3834
-
3835
4791
  /**
3836
4792
  * How an AI session reads the inbox: by its own name only. What is written to "<person>'s AI"
3837
4793
  * is the cloud AI's, and work for the person's AI waits on the board until they ask for it.
@@ -4207,54 +5163,17 @@ export class Session extends EventEmitter {
4207
5163
  this.scheduleStatusWrite()
4208
5164
  }
4209
5165
 
4210
- // ------------------------------------------------------------- boxes --
4211
- // Quilt holds no files (no-holds, 2026-11-13): nobody claims, queues for or hands off a file, and no
4212
- // write is refused or undone because someone else is working on it. What our AI changes in a git
4213
- // folder goes into a box of ours (unfinished work, kept out of other folders until it's committed);
4214
- // anyone who edits a boxed file opens it, and their change merges with the work in it (editBoxed).
5166
+ // ------------------------------------------------------- an AI's edits --
5167
+ // Quilt holds no files: nobody claims, queues for or hands off a file, and no write is refused or
5168
+ // undone because someone else is working on it. Every edit is shared as it is made.
4215
5169
 
4216
5170
  /** An agent session, or a person whose AI is working or whose tool Quilt can't read: an edit is probably the AI's. */
4217
5171
  aiMayBeEditing () {
4218
5172
  return this.kind === 'agent' || this.agentState?.status !== 'idle' || this.work?.state === 'working'
4219
5173
  }
4220
5174
 
4221
- /**
4222
- * Whether an AI's edits here go into boxes (docs/superpowers/specs/2026-10-16-git-boxes-design.md):
4223
- * always, in a folder that is a git repository. One that isn't never boxes: nothing there could commit it.
4224
- */
4225
- boxesOn () { return !!this.git }
4226
-
4227
- /** The box on rel when it is someone else's (their unfinished work: not written here), else null. */
4228
- boxedByOther (rel) {
4229
- const c = this.boxAt(rel)
4230
- return c && !this.isOwnBox(c) ? c : null
4231
- }
4232
-
4233
- /** The box on exactly rel (whoever's), or null. */
4234
- boxAt (rel) {
4235
- const c = this.boxed.get(rel)
4236
- return c && c.box !== false ? c : null
4237
- }
4238
-
4239
- /**
4240
- * Our AI changed rel here: noted for its working state, and, in a git folder, boxed for us (once:
4241
- * a box of ours already there keeps its first version, boxFrom). Someone else's box on it was opened
4242
- * before this (editBoxed), and a box the relay can't give (a race, an older relay) leaves the edit live.
4243
- */
4244
- boxEdit (rel) {
4245
- this.aiEdits.set(rel, Date.now())
4246
- if (!this.conn || !this.boxesOn() || this.ownBox(rel) || this.boxing.has(rel)) return
4247
- this.boxing.add(rel)
4248
- this.boxFrom.set(rel, this.sharedKey(rel) ?? null) // called before the edit goes in
4249
- const note = this.focus ? `editing: ${this.focus}` : 'editing'
4250
- this.noteActivity(`Editing ${rel}`)
4251
- this.conn.boxRequest({ op: 'box', pattern: rel, note }).then((r) => {
4252
- if (r && r.boxed === 0) this.boxFrom.delete(rel)
4253
- }, (err) => {
4254
- this.boxFrom.delete(rel)
4255
- this.log(`could not box ${rel} for you (it stays live with everyone): ${err.message}`)
4256
- }).finally(() => this.boxing.delete(rel))
4257
- }
5175
+ /** Our AI changed rel here: noted for its working state. */
5176
+ noteAiEdit (rel) { this.aiEdits.set(rel, Date.now()) }
4258
5177
 
4259
5178
  /** Forgets our AI's edits that have been quiet a while: "working" that only those edits said lapses with them. */
4260
5179
  forgetQuietEdits () {
@@ -4265,18 +5184,12 @@ export class Session extends EventEmitter {
4265
5184
  if (this.workFromEdits && !this.aiEdits.size && this.work?.state === 'working' && Date.now() - (this.agentReportedAt || 0) >= this.editQuietMs) this.finishEditing().catch(() => {})
4266
5185
  }
4267
5186
 
4268
- /** Our own box on exactly rel, or null. */
4269
- ownBox (rel) {
4270
- const c = this.boxAt(rel)
4271
- return c && this.isOwnBox(c) ? c : null
4272
- }
4273
-
4274
5187
  /**
4275
5188
  * The check every agent makes before it changes files, whatever tool it runs in (the local
4276
- * MCP's quilt_before_edit, or a hook): for each path, who wrote it recently (presence) and whose
4277
- * unfinished work is boxed on it, and what people said about those files in chat, as context. It
4278
- * never claims and never refuses: every path stays writable (no-holds, 2026-11-13). When no chat
4279
- * reader can see our AI work, it is marked working, so the host doesn't commit under it.
5189
+ * MCP's quilt_before_edit, or a hook): for each path, who wrote it recently (presence), and
5190
+ * what people said about those files in chat, as context. It never claims and never refuses: every
5191
+ * path stays writable. When no chat reader can see our AI work, it is marked working, so the host
5192
+ * doesn't commit under it.
4280
5193
  */
4281
5194
  async prepareEdit (paths, via = null) {
4282
5195
  const files = []
@@ -4285,8 +5198,7 @@ export class Session extends EventEmitter {
4285
5198
  for (const p of [...new Set((paths || []).map((x) => String(x || '').replace(/\\/g, '/').replace(/^\.\//, '')))]) {
4286
5199
  if (!p) continue
4287
5200
  if (!this.syncable(p)) { files.push({ path: p, shared: false }); continue }
4288
- const b = this.boxedByOther(p)
4289
- files.push({ path: p, shared: true, ok: true, recent: this.recentWriters(p).filter((w) => w.by !== me), ...(b ? { box: { by: b.of || b.by } } : {}) })
5201
+ files.push({ path: p, shared: true, ok: true, recent: this.recentWriters(p).filter((w) => w.by !== me) })
4290
5202
  }
4291
5203
  // A session still named after its tool takes a name from the first file it edits.
4292
5204
  const first = files.find((f) => f.shared)
@@ -4433,7 +5345,7 @@ export class Session extends EventEmitter {
4433
5345
  try { return pickupMode(getSettings().aiTasks) } catch { return 'off' }
4434
5346
  }
4435
5347
 
4436
- /** Done with a piece of work: says we're done. Nothing is held, so nothing is let go of (boxes stay until committed). */
5348
+ /** Done with a piece of work: says we're done. Nothing is held, so nothing is let go of. */
4437
5349
  async finishEditing (via = null) {
4438
5350
  if (!this.persona(via)) this.aiEdits.clear()
4439
5351
  if (this.work?.state === 'working') this.setWork('done')
@@ -4441,50 +5353,6 @@ export class Session extends EventEmitter {
4441
5353
  return { released: 0 }
4442
5354
  }
4443
5355
 
4444
- /**
4445
- * The session's boxes as the app shows them (boxes.js): each with what it changes from the version
4446
- * this folder has. Someone else's: from this folder's version before the box (what is on disk);
4447
- * ours: from what git last committed. `on`: whether this folder's own edits box (a git repository).
4448
- */
4449
- async boxes () {
4450
- const text = (d) => (!d || d.skip || d.tooLarge ? null : d.binary ? { binary: true } : d.text)
4451
- const out = []
4452
- for (const c of this.boxed.values()) {
4453
- if (!c || c.box === false || /[*?[]/.test(c.pattern) || !isSafeRelPath(c.pattern)) continue
4454
- const rel = c.pattern
4455
- const t = this.files.get(rel)
4456
- const after = t ? t.toString() : this.blobs.has(rel) ? { binary: true } : null
4457
- const mine = this.isOwnBox(c)
4458
- let before = null
4459
- if (mine) {
4460
- const base = this.boxBase.has(rel) ? this.boxBase.get(rel) : null
4461
- before = base === null ? null : typeof base.text === 'string' ? base.text : { binary: true }
4462
- } else if (this.boxBase.has(rel)) {
4463
- const base = this.boxBase.get(rel)
4464
- before = base === null ? null : typeof base.text === 'string' ? base.text : { binary: true }
4465
- } else {
4466
- try { before = text(this.readDisk(rel)) } catch { before = null }
4467
- }
4468
- out.push(boxEntry({ box: c, mine, before, after }))
4469
- }
4470
- return { on: this.boxesOn(), boxes: out.sort((a, b) => a.ts - b.ts || a.path.localeCompare(b.path)) }
4471
- }
4472
-
4473
- /** Our AI shares boxed files before they're committed: their content reaches every folder now, and we keep the files. */
4474
- async unpack (paths, via = null) {
4475
- const unpacked = []
4476
- const notBoxed = []
4477
- for (const p of [...new Set((paths || []).map((x) => String(x || '').replace(/\\/g, '/').replace(/^\.\//, '')).filter(Boolean))]) {
4478
- if (!this.ownBox(p)) { notBoxed.push(p); continue }
4479
- if (!this.conn) throw new Error('not connected to the relay')
4480
- // As this member, not the AI session asking: the box may be the member's own (an edit on disk) or one of its sessions'.
4481
- const r = await this.conn.boxRequest({ op: 'unbox', pattern: p, release: false })
4482
- if (r.unboxed) { unpacked.push(p); this.boxFrom.delete(p) } else notBoxed.push(p)
4483
- }
4484
- if (unpacked.length) this.noteActivity(`Unpacked ${unpacked.join(', ')}`, { via })
4485
- return { unpacked, notBoxed }
4486
- }
4487
-
4488
5356
  /**
4489
5357
  * Why we can't reach the relay (e.g. no session pass), or null once that's fixed.
4490
5358
  * Logged once per new reason, not on every retry, and shown in status.
@@ -4497,32 +5365,6 @@ export class Session extends EventEmitter {
4497
5365
  this.emit('status-changed')
4498
5366
  }
4499
5367
 
4500
- /** Takes the relay's box list (its MSG_CLAIMS, which lists boxes only), and writes out what opened. */
4501
- setBoxes (list) {
4502
- const was = this.boxed
4503
- const next = new Map()
4504
- // An older relay still sends claims: only boxes are kept, and nothing anyone holds is enforced here.
4505
- for (const c of Array.isArray(list) ? list : []) if (c && c.box === true && typeof c.pattern === 'string' && typeof c.by === 'string') next.set(c.pattern, c)
4506
- this.boxed = next
4507
- try { fs.writeFileSync(path.join(this.stateDir, 'boxes.json'), JSON.stringify([...next.values()])) } catch {}
4508
- // A box handed to us (our cloud AI stopped with it, server.js handBackCloudBoxes): our git may have it already.
4509
- if (this.ready && [...next].some(([p, c]) => c.handedFrom && this.isOwnBox(c) && !(was.get(p) && this.isOwnBox(was.get(p))))) this.scheduleStatusWrite()
4510
- // A box someone else held opened (committed, unpacked, opened by an edit): its file reaches this folder now.
4511
- // (Also one that opened while this folder was away: its ghost is still on record.)
4512
- if (this.ready) {
4513
- const opened = new Set([...was].filter(([, c]) => !this.isOwnBox(c)).map(([p]) => p))
4514
- for (const p of this.boxBase.keys()) opened.add(p)
4515
- for (const p of opened) {
4516
- if (this.boxedByOther(p)) continue // still someone else's box
4517
- if (this.boxBase.delete(p)) this.scheduleStateSave()
4518
- this.tryWrite(p)
4519
- }
4520
- }
4521
- if (this.ready) this.settleReleasedMerges()
4522
- this.scheduleStatusWrite()
4523
- this.emit('boxes', [...next.values()])
4524
- }
4525
-
4526
5368
  /**
4527
5369
  * Our offline edits an older app held back because someone held the file (open 'claimed' records):
4528
5370
  * nobody holds files now (no-holds, 2026-11-13), so each goes in straight away through the normal
@@ -4576,16 +5418,6 @@ export class Session extends EventEmitter {
4576
5418
  }
4577
5419
  }
4578
5420
 
4579
- /** Last known boxes, so someone else's unfinished work isn't written here before the relay answers (or while offline). */
4580
- loadBoxes () {
4581
- let list = null
4582
- try { list = JSON.parse(fs.readFileSync(path.join(this.stateDir, 'boxes.json'), 'utf8')) } catch {}
4583
- // A folder from before no-holds kept them with its claims (claims.json): the boxes stay, every claim goes.
4584
- if (!list) { try { list = JSON.parse(fs.readFileSync(path.join(this.stateDir, 'claims.json'), 'utf8')) } catch {} }
4585
- for (const c of Array.isArray(list) ? list : []) if (c && c.box === true && typeof c.pattern === 'string') this.boxed.set(c.pattern, c)
4586
- try { fs.rmSync(path.join(this.stateDir, 'claims.json'), { force: true }) } catch {}
4587
- }
4588
-
4589
5421
  // ------------------------------------------------------------ merges --
4590
5422
 
4591
5423
  mergeList () { return readMerges(this.merges) }
@@ -4855,7 +5687,7 @@ export class Session extends EventEmitter {
4855
5687
 
4856
5688
  /**
4857
5689
  * Every shared path with who last edited it (from activity and live
4858
- * presence) and the box on it (someone's unfinished work). Read from the shared doc.
5690
+ * presence). Read from the shared doc.
4859
5691
  */
4860
5692
  tree () {
4861
5693
  const edited = new Map()
@@ -4870,13 +5702,6 @@ export class Session extends EventEmitter {
4870
5702
  const editing = id === this.doc.clientID ? Object.fromEntries(this.myEdits) : (st.editing || {})
4871
5703
  for (const [p, ts] of Object.entries(editing)) note(p, st.name, ts)
4872
5704
  }
4873
- // `active` is false when whoever boxed it isn't in the session (older relays don't say: active).
4874
- // Shown as people see it: an older app's AI session ("Dana · login", of: Dana) is its person.
4875
- const shown = (c) => ({ by: c.of || c.by, ...(typeof c.byId === 'string' ? { byId: c.byId } : {}), ...(typeof c.of === 'string' ? { of: c.of } : {}), pattern: c.pattern, note: c.note, ts: c.ts, box: true, active: c.active !== false, ...(typeof c.activeAt === 'number' ? { activeAt: c.activeAt } : {}) })
4876
- const boxOf = (p) => {
4877
- const c = this.boxAt(p)
4878
- return c ? shown(c) : null
4879
- }
4880
5705
  // Files that are GitHub's version, not edited in the session since (the relay marks them: relay-sync.js markFromGithub).
4881
5706
  const gh = this.bdoc ? this.bdoc.getMap('fromGithub') : null
4882
5707
  const fromGithub = (p) => { const v = gh && gh.get(p); return v && typeof v.sha === 'string' ? { sha: v.sha, by: v.by || '', at: v.at || 0, came: v.came || 0, subject: v.subject || '' } : null }
@@ -4886,14 +5711,11 @@ export class Session extends EventEmitter {
4886
5711
  for (const p of listed) {
4887
5712
  if (!isSafeRelPath(p)) continue
4888
5713
  const blob = this.blobs.get(p)
4889
- out.push({ path: p, binary: blob ? !this.files.has(p) : this.diffForm && this.files.has(p) === false && /^bin:/.test(String(this.gitOnly.get(p) || '')), edited: edited.get(p) || null, box: boxOf(p), github: fromGithub(p) })
5714
+ out.push({ path: p, binary: blob ? !this.files.has(p) : this.diffForm && this.files.has(p) === false && /^bin:/.test(String(this.gitOnly.get(p) || '')), edited: edited.get(p) || null, github: fromGithub(p) })
4890
5715
  }
4891
5716
  out.push(...this.chatFileEntries())
4892
5717
  out.sort((a, b) => a.path.localeCompare(b.path))
4893
- return {
4894
- files: out,
4895
- boxes: [...this.boxed.values()].map(shown)
4896
- }
5718
+ return { files: out }
4897
5719
  }
4898
5720
 
4899
5721
  /** The chat files folder, for the file tree: each file I can see that is saved there, with who sent it. */
@@ -4997,6 +5819,10 @@ export class Session extends EventEmitter {
4997
5819
  room: this.room,
4998
5820
  server: this.server,
4999
5821
  branch: this.branch,
5822
+ // A git checkout: where git has the folder, and whether its sync is held (git at work, or moving to the branch `to`).
5823
+ git: this.git ? { branch: this.git.branch, key: this.git.key, hold: this.hold ? { kind: this.hold.kind, since: this.hold.since, to: this.hold.to || null, waiting: this.hold.waiting || null } : null } : null,
5824
+ // The branch against its upstream, once looked at: commits it is behind and why they wait, or what was last brought in.
5825
+ ...(this.upstream ? { upstream: this.upstream } : {}),
5000
5826
  connected: !!(this.conn && this.conn.connected),
5001
5827
  ...(this.relayProblem ? { problem: this.relayProblem } : {}),
5002
5828
  access: this.access,
@@ -5023,7 +5849,6 @@ export class Session extends EventEmitter {
5023
5849
  // The session's call: whether the owner has transcripts on, and the agents in it.
5024
5850
  voice: { transcribe: transcribeSetting(this.doc, this.members).on, agents: callAgents(this.doc, this.conn ? this.liveCall() : '', this.members) },
5025
5851
  peers,
5026
- boxes: [...this.boxed.values()].sort((a, b) => a.ts - b.ts),
5027
5852
  tasks: this.taskList(),
5028
5853
  // Without the texts (up to 400 KB a record): status goes out on every
5029
5854
  // change. The full records are at GET /merges and the app's merges route.