heyquilt 0.3.176 → 0.3.178

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
@@ -53,8 +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'
57
- import { headKey, headName, branchTip, busy as gitBusy, leftoverLock, indexStamp, filesAt, blobAt, treeState, watchGit, SETTLE_MS as GIT_SETTLE_MS, STALE_LOCK_MS } from './gitstate.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, hasBranch, switchBranch } from './gitstate.js'
58
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'
59
58
  import { toolInUse } from './agents/common.js'
60
59
 
@@ -67,6 +66,9 @@ function slug (s, max = 40) {
67
66
  return String(s || '').toLowerCase().normalize('NFKD').replace(/[^\w\s-]/g, '').trim().replace(/[\s_]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '').slice(0, max).replace(/-$/, '') || 'work'
68
67
  }
69
68
 
69
+ /** The branches an agent owns: quilt/<its name>/<its task>. */
70
+ export const agentPrefix = (name) => `quilt/${slug(name, 30)}/`
71
+
70
72
  /** Whether `root` is a git checkout (a .git folder, or a worktree's pointer file). */
71
73
  function hasGitDir (root) {
72
74
  try { fs.statSync(path.join(root, '.git')); return true } catch { return false }
@@ -154,7 +156,6 @@ const CATCHER_WAITING = 'another member is bringing these commits in'
154
156
  const RELAY_WAITING = 'the relay is bringing these commits into the session'
155
157
  // How long a git pull's settle waits for the relay to be at the pulled commit before sharing it as before (planSettle).
156
158
  const RELAY_PULL_WAIT_MS = 15 * 1000
157
- const SETTLE_BOXES_MS = 1500 // after an edit to one of our boxed files: does git have it as the session does now?
158
159
  const RELAY_ASK_EVERY_MS = 5 * 1000 // a folder waiting for the relay asks it again this often (server.js SYNC_EVERY_GIT_MS)
159
160
  const INDEX_WATCH_MS = 8000 // after a bring-in, how long the index is checked against what another git may write back
160
161
 
@@ -255,10 +256,6 @@ export class Session extends EventEmitter {
255
256
  this.transfers = 0 // large uploads and downloads running
256
257
  this.transferQueue = [] // resolvers waiting for one to finish
257
258
  this.stopped = false
258
- // Boxes (someone's unfinished work on one file, kept out of other folders until it's committed):
259
- // path -> { by, pattern, note, ts, box: true }. The relay keeps them, outside the shared doc; we keep
260
- // the last list. Quilt holds no files (no-holds, 2026-11-13): a box never stops anyone writing.
261
- this.boxed = new Map()
262
259
  this.chat = this.doc.getArray('chat') // { by, text, ts }
263
260
  this.activity = this.doc.getArray('activity') // { by, path, kind, detail, ts }
264
261
  this.agentFeed = this.doc.getArray('agentFeed') // { id, by, tool, conv, kind, text, ts, summary?, title? }
@@ -292,16 +289,9 @@ export class Session extends EventEmitter {
292
289
  // ages out on our clock, not theirs.
293
290
  this.typing = {}
294
291
  this.typingSeen = new Map()
295
- // Files our AI changed (see boxEdit): path -> when it last did. Forgotten once quiet for editQuietMs
292
+ // Files our AI changed (see noteAiEdit): path -> when it last did. Forgotten once quiet for editQuietMs
296
293
  // (forgetQuietEdits), and "working" that only these edits said lapses with them.
297
294
  this.aiEdits = new Map()
298
- this.boxing = new Set() // our files whose box is on its way to the relay (boxEdit)
299
- // Ghosts: files someone else has boxed, not written here. For each, this folder's version from before
300
- // the box ({ text } or { b64 }; null: it wasn't there), put back when an edit here is refused. Kept in state.json.
301
- this.boxBase = new Map()
302
- // Our boxes: what the session had before the edit that opened each (null: no file). Back to that, the box holds
303
- // nothing of ours (our edit undone, or taken back) and opens like a committed one.
304
- this.boxFrom = new Map()
305
295
  this.editQuietMs = editQuietMs
306
296
  // Whether our AI takes work from the board by itself (tasks.js PICKUP_MODES); null: this person's setting.
307
297
  this.aiTasks = aiTasks
@@ -385,13 +375,16 @@ export class Session extends EventEmitter {
385
375
  this.savedGit = null // { key, sha } from state.json: the branch this folder synced at the last stop
386
376
  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
387
377
  this.gitFailures = 0 // settles in a row that couldn't ask git
388
- // Commits made outside the session that this branch is behind (see bringIn): { name, url, sha,
389
- // behind, ahead, diverged, conflicts, waiting, checkedAt } of the branch's upstream, or null.
378
+ // The branch's upstream and the commits this branch is behind it (see bringIn): { name, sha, behind,
379
+ // ahead, waiting? (why Quilt left them to the person's git), brought? { count, files, at } }, or null.
390
380
  this.upstream = null
391
381
  this.upstreamTimer = null
392
382
  this.upstreamFetch = false
393
383
  this.upstreamPoll = null
394
384
  this.upstreamSaid = '' // the advice last given, so it's given once per state
385
+ this.fetchSaid = '' // why the last fetch failed, so it's logged once
386
+ this.upstreamTries = 0 // looks in a row that found the folder not quiet, or not in step with the session yet
387
+ this.peerTips = new Map() // awareness client -> the commit their folder said it is at, on this branch
395
388
  this.fetchState = null // the last git fetch of the upstream: { ok, error, at } (noteFetch)
396
389
  this.upstreamDeferred = null // the commit this folder let another member's folder bring in first
397
390
  this.clashAbsent = null // { task, name, since }: a clash task's assignee seen gone from the branch
@@ -580,7 +573,7 @@ export class Session extends EventEmitter {
580
573
  const hadState = this.loadState()
581
574
  // 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.
582
575
  this.gitAside = hasGitDir(this.root) ? null : gitAsideOf(this.root)
583
- if (hadState) this.loadBoxes()
576
+ for (const f of ['boxes.json', 'claims.json']) { try { fs.rmSync(path.join(this.stateDir, f), { force: true }) } catch {} } // what older versions kept here
584
577
  // Where git has the folder: a branch, or a detached commit (keyed `@<sha>`). Without a commit to read
585
578
  // (a branch with no commits yet, or git not running here) the branch HEAD names, with no commit.
586
579
  this.git = await this.headAt()
@@ -625,7 +618,6 @@ export class Session extends EventEmitter {
625
618
  this.conn.on('fatal', (err) => this.emit('fatal', err))
626
619
  this.conn.on('pass', (p) => this.adoptPass(p))
627
620
  this.conn.on('problem', (msg) => this.setRelayProblem(msg))
628
- this.conn.on('boxes', (list) => this.setBoxes(list))
629
621
  this.conn.on('access', (a) => this.setAccess(a))
630
622
  this.conn.on('members', (m) => this.setMembers(m))
631
623
  this.conn.on('branches', (list) => this.setBranches(list))
@@ -929,7 +921,6 @@ export class Session extends EventEmitter {
929
921
  this.branchForm = meta.form === 'diff' || meta.form === 'full' ? meta.form : null
930
922
  this.diffBase = typeof meta.diffBase === 'string' ? meta.diffBase : null
931
923
  this.storedOnDisk = new Map(Object.entries(meta.storedOnDisk || {}))
932
- 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)
933
924
  this.known = meta.known ? new Map(Object.entries(meta.known)) : null
934
925
  this.behindAtSave = new Map(Object.entries(meta.behind && typeof meta.behind === 'object' ? meta.behind : {}).filter(([, v]) => typeof v === 'string'))
935
926
  this.savedRole = typeof meta.role === 'string' ? meta.role : null
@@ -1033,7 +1024,7 @@ export class Session extends EventEmitter {
1033
1024
  }
1034
1025
  // When we were last in touch with the session: "you left 3h ago" on the next catch-up.
1035
1026
  if (this.conn && this.conn.connected) this.savedSeenAt = Date.now()
1036
- 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, ...(this.boxBase.size ? { boxBase: Object.fromEntries(this.boxBase) } : {}), ...(Object.keys(behind).length ? { behind } : {}), ...this.roleState(), ...(this.savedSeenAt ? { seenAt: this.savedSeenAt } : {}) }))
1027
+ 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 } : {}) }))
1037
1028
  }
1038
1029
 
1039
1030
  /** This member's role, so the next start knows it before the relay says (ignoreQuiltState). */
@@ -1669,6 +1660,9 @@ export class Session extends EventEmitter {
1669
1660
  clearTimeout(this.settleTimer); this.settleTimer = null
1670
1661
  this.emit('hold', null)
1671
1662
  this.scheduleStatusWrite()
1663
+ // git is done here (a commit, a fetch, a checkout): partners hear where this folder is, and it looks at its upstream.
1664
+ this.shareTip()
1665
+ this.checkUpstreamSoon()
1672
1666
  }
1673
1667
 
1674
1668
  /** (Re)arms the hold's timer: it ends GIT_SETTLE_MS after the last file or git event. */
@@ -2287,6 +2281,367 @@ export class Session extends EventEmitter {
2287
2281
  })
2288
2282
  }
2289
2283
 
2284
+ // ------------------------------------------------------------ upstream --
2285
+ // Commits the folder's branch is behind (a partner pushed, a pull request merged on GitHub) come in
2286
+ // by themselves. Quilt fetches the branch's upstream (once a minute, and when a partner's folder says
2287
+ // it moved); when the branch can simply move forward, it writes those commits' files under the
2288
+ // folder's uncommitted work and moves the branch and the index there (gitstate.js fastForward), as
2289
+ // `git pull --autostash` would. It never merges git history: a branch with commits of its own the
2290
+ // upstream hasn't, or uncommitted work on the same lines as a commit, is left to the person's git.
2291
+
2292
+ /** Starts looking at the upstream: now, then every UPSTREAM_MS. */
2293
+ startUpstream () {
2294
+ if (!this.git || !this.bringInUpstream || this.upstreamPoll) return
2295
+ this.shareTip()
2296
+ this.upstreamPoll = setInterval(() => this.checkUpstreamSoon({ fetch: true }), UPSTREAM_MS)
2297
+ this.upstreamPoll.unref()
2298
+ this.checkUpstreamSoon({ fetch: true, delay: 2000 })
2299
+ }
2300
+
2301
+ /** Tells partners which commit this folder's branch is at, so theirs look for it when it moves. */
2302
+ shareTip () {
2303
+ if (!this.conn || !this.conn.awareness || !this.conn.awareness.getLocalState() || !this.git) return
2304
+ const was = this.conn.awareness.getLocalState().tip
2305
+ const tip = this.git.branch && this.git.sha ? { key: this.git.key, sha: this.git.sha } : null
2306
+ if (JSON.stringify(was || null) !== JSON.stringify(tip)) this.conn.awareness.setLocalStateField('tip', tip)
2307
+ }
2308
+
2309
+ /** 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). */
2310
+ notePeerTips () {
2311
+ if (!this.git || !this.git.branch || !this.bringInUpstream || !this.conn) return
2312
+ let moved = false
2313
+ for (const [id, st] of this.conn.awareness.getStates()) {
2314
+ if (id === this.doc.clientID || !st || !st.tip || st.tip.key !== this.git.key || typeof st.tip.sha !== 'string') continue
2315
+ if (this.peerTips.get(id) === st.tip.sha) continue
2316
+ this.peerTips.set(id, st.tip.sha)
2317
+ if (st.tip.sha !== this.git.sha) moved = true
2318
+ }
2319
+ if (!moved) return
2320
+ this.checkUpstreamSoon({ fetch: true, delay: 1500 })
2321
+ for (const ms of [10 * 1000, 30 * 1000]) setTimeout(() => this.checkUpstreamSoon({ fetch: true }), ms).unref()
2322
+ }
2323
+
2324
+ /** Looks at the upstream once the folder has been quiet for `delay`; `fetch`: asks the remote first. */
2325
+ checkUpstreamSoon ({ fetch = false, delay = GIT_SETTLE_MS } = {}) {
2326
+ if (this.stopped || !this.git || !this.bringInUpstream) return
2327
+ this.upstreamFetch = this.upstreamFetch || fetch
2328
+ clearTimeout(this.upstreamTimer)
2329
+ this.upstreamTimer = setTimeout(() => {
2330
+ this.upstreamTimer = null
2331
+ const f = this.upstreamFetch
2332
+ this.upstreamFetch = false
2333
+ this.checkUpstream({ fetch: f }).catch((err) => this.log(`could not look for new commits: ${err.message}`))
2334
+ }, delay)
2335
+ this.upstreamTimer.unref()
2336
+ }
2337
+
2338
+ /** 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). */
2339
+ upstreamLater () {
2340
+ this.checkUpstreamSoon({ delay: Math.min(UPSTREAM_MS, 2000 * 2 ** Math.min(this.upstreamTries++, 5)) })
2341
+ }
2342
+
2343
+ /** Nothing of git's or the session's is on its way in this folder: the disk is what the session has. */
2344
+ quietForUpstream () {
2345
+ return this.ready && !this.stopped && !this.hold && !this.pendingMove && !this.arriving && !this.gitBusy() && !this.pending.size && !this.merging.size
2346
+ }
2347
+
2348
+ /**
2349
+ * Where the folder's branch stands against its upstream, and, when it is only behind, the commits
2350
+ * brought in (bringIn). The fetch runs on its own (it can wait on the network); what reads and moves
2351
+ * the branch runs with the folder's other git work, one piece at a time.
2352
+ */
2353
+ async checkUpstream ({ fetch = false } = {}) {
2354
+ if (this.stopped || !this.ready || !this.git || !this.git.branch) return
2355
+ const branch = this.git.branch
2356
+ const up = await upstreamOf(this.root)
2357
+ if (!up || !up.remote || up.remote === '.') { this.setUpstream(null); return }
2358
+ if (fetch) {
2359
+ const f = await fetchUpstream(this.root, up.remote)
2360
+ if (this.stopped) return
2361
+ if (!f.ok && f.error && f.error !== this.fetchSaid) this.log(`could not look for new commits on ${up.name}: ${f.error}`)
2362
+ this.fetchSaid = f.ok ? '' : f.error || ''
2363
+ }
2364
+ await this.gitTask(async () => {
2365
+ if (!this.git || this.git.branch !== branch || headName(this.root) !== branch) return
2366
+ if (!this.quietForUpstream()) { this.upstreamLater(); return }
2367
+ const now = await upstreamOf(this.root)
2368
+ const at = await branchTip(this.root, branch)
2369
+ if (!now || !now.sha || !at || this.stopped) return
2370
+ if (at === now.sha) { this.setUpstream({ name: now.name, sha: now.sha, behind: 0, ahead: 0 }); return }
2371
+ const n = await aheadBehind(this.root, at, now.sha)
2372
+ if (!n) return
2373
+ const facts = { name: now.name, sha: now.sha, ...n }
2374
+ if (!n.behind) { this.setUpstream(facts); return }
2375
+ const commits = (k) => `${k} commit${k === 1 ? '' : 's'}`
2376
+ if (n.ahead) {
2377
+ await this.stageArrived(at, now.sha)
2378
+ 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.` })
2379
+ return
2380
+ }
2381
+ await this.bringIn(at, now.sha, facts)
2382
+ })
2383
+ }
2384
+
2385
+ /**
2386
+ * The upstream's commits wait for the person's own pull, and the session already put some of the
2387
+ * files they add in this folder (a partner's folder brought them in). git refuses a pull over a
2388
+ * file it doesn't track, so each one this folder has exactly as the commits have it is staged:
2389
+ * a pull with --autostash then goes through, and ends with nothing to commit for them.
2390
+ */
2391
+ async stageArrived (from, to) {
2392
+ const changes = await changesBetween(this.root, from, to)
2393
+ if (!changes) return
2394
+ const added = [...changes].filter(([, c]) => c.status === 'A' && c.plain).map(([rel]) => rel)
2395
+ if (!added.length) return
2396
+ const [theirs, state] = [await filesAt(this.root, to, added), await treeState(this.root, added)]
2397
+ if (!theirs || !state || this.stopped || !this.quietForUpstream()) return
2398
+ const here = added.filter((rel) => {
2399
+ if (state.tracked.has(rel)) return false
2400
+ let d = null
2401
+ try { d = this.readDisk(rel) } catch { return false }
2402
+ return !!d && !d.skip && !d.tooLarge && d.key === theirs.get(rel)
2403
+ })
2404
+ if (!here.length || !(await stage(this.root, here))) return
2405
+ this.gitIndex = indexStamp(this.root) // Quilt's own write of the index: no burst of git's
2406
+ 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`)
2407
+ }
2408
+
2409
+ /** Keeps what is known of the upstream, and says why commits wait (to the log and the AI) once per reason. */
2410
+ setUpstream (u) {
2411
+ const was = JSON.stringify(this.upstream)
2412
+ this.upstream = u
2413
+ const said = u && u.waiting ? `${u.sha}:${u.waiting}` : ''
2414
+ if (said && said !== this.upstreamSaid) {
2415
+ this.log(`⏸️ ${u.waiting}`)
2416
+ this.notice(u.waiting)
2417
+ }
2418
+ this.upstreamSaid = said
2419
+ if (JSON.stringify(u) !== was) { this.emit('status-changed'); this.scheduleStatusWrite() }
2420
+ }
2421
+
2422
+ /**
2423
+ * The branch is at `from` and only behind `to`: each file the commits changed is written under
2424
+ * the folder's own work (untouched here: the commits' version; changed here too, on other lines:
2425
+ * both), then the index and the branch move to `to`. All or nothing: when a file can't be combined
2426
+ * (the same lines changed here and there, a binary both changed, a link, a file Quilt can't read)
2427
+ * nothing is written and the commits are left to the person's git, with the reason said once.
2428
+ */
2429
+ async bringIn (from, to, facts) {
2430
+ const branch = this.git.branch
2431
+ const changes = await changesBetween(this.root, from, to)
2432
+ if (!changes) return
2433
+ const rels = [...changes.keys()]
2434
+ const [base, theirs] = [await filesAt(this.root, from, rels), await filesAt(this.root, to, rels)]
2435
+ if (!base || !theirs || this.stopped) return
2436
+ if (!this.quietForUpstream() || headName(this.root) !== branch) { this.upstreamLater(); return }
2437
+ const isText = (k) => typeof k === 'string' && !k.startsWith('bin:')
2438
+ const writes = new Map() // rel -> the file's key after (null: deleted)
2439
+ const clashes = []
2440
+ const unread = []
2441
+ for (const rel of rels) {
2442
+ const b = base.get(rel)
2443
+ const t = theirs.get(rel)
2444
+ let d = null
2445
+ try { d = this.readDisk(rel) } catch { d = { skip: true } }
2446
+ const o = !d ? null : d.skip || d.tooLarge ? undefined : d.key
2447
+ if (!changes.get(rel).plain || b === undefined || t === undefined || o === undefined) { unread.push(rel); continue }
2448
+ // A file whose clash is still in this folder (its own lines between markers) is its writer's to settle first.
2449
+ if (this.clashed.has(rel)) { clashes.push(rel); continue }
2450
+ // The session and this folder must agree first: a change still on its way waits for the next look.
2451
+ if (this.syncable(rel) && !this.followsGit(rel) && (o ?? undefined) !== this.sharedKey(rel)) { this.upstreamLater(); return }
2452
+ if (o === t) continue // the session has it already (a partner committed what everyone was editing)
2453
+ if (o === b) { writes.set(rel, t); continue } // untouched here: the commits' version
2454
+ if ((b === null || isText(b)) && isText(o) && isText(t)) {
2455
+ const r = merge3(b ?? '', o, t)
2456
+ if (!r.conflicts.length) { if (r.text !== o) writes.set(rel, r.text); continue }
2457
+ }
2458
+ clashes.push(rel)
2459
+ }
2460
+ this.upstreamTries = 0
2461
+ const commits = `${facts.behind} commit${facts.behind === 1 ? '' : 's'}`
2462
+ const list = (a) => a.slice(0, 4).join(', ') + (a.length > 4 ? ` and ${a.length - 4} more` : '')
2463
+ if (unread.length) {
2464
+ 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.` })
2465
+ return
2466
+ }
2467
+ if (clashes.length) {
2468
+ 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.` })
2469
+ return
2470
+ }
2471
+ let written = 0
2472
+ const writeFiles = async () => {
2473
+ for (const [rel, key] of writes) {
2474
+ const abs = resolveInside(this.root, rel)
2475
+ if (key === null) {
2476
+ fs.rmSync(abs, { force: true })
2477
+ removeEmptyParents(this.root, path.dirname(abs))
2478
+ } else {
2479
+ const data = key.startsWith('bin:') ? await blobAt(this.root, to, rel) : key
2480
+ if (data === null) throw new Error(`git could not read ${rel}`)
2481
+ fs.mkdirSync(path.dirname(abs), { recursive: true })
2482
+ this.writeFile(rel, abs, data)
2483
+ }
2484
+ written++
2485
+ // Shared as the commits' change, not an edit of this person's (the next look at the file finds nothing new).
2486
+ if (this.syncable(rel)) this.ingest(rel, { pulled: true })
2487
+ }
2488
+ // git tracks whether a file can be run: the folder's files follow the commits in that too.
2489
+ if (process.platform !== 'win32') {
2490
+ for (const [rel, c] of changes) {
2491
+ if (c.exec === null) continue
2492
+ try {
2493
+ const abs = resolveInside(this.root, rel)
2494
+ const mode = fs.statSync(abs).mode
2495
+ if (!!(mode & 0o100) !== c.exec) fs.chmodSync(abs, c.exec ? mode | 0o111 : mode & ~0o111)
2496
+ } catch {}
2497
+ }
2498
+ }
2499
+ }
2500
+ let moved = false
2501
+ try { moved = await fastForward(this.root, branch, from, to, writeFiles) } catch (err) { this.log(`could not bring in ${facts.name}'s commits: ${err.message}`) }
2502
+ if (!moved) { this.checkUpstreamSoon({ delay: 5000 }); return }
2503
+ // What git and Quilt just wrote is accounted for: the next flush is no burst of git's.
2504
+ this.git = { key: this.git.key, branch, sha: to }
2505
+ this.gitSeen = this.git
2506
+ this.gitIndex = indexStamp(this.root)
2507
+ this.headChangedAt = 0
2508
+ this.scheduleStateSave()
2509
+ this.shareTip()
2510
+ this.log(`⬇️ brought in ${commits} from ${facts.name}${written ? ` (${written} file${written === 1 ? '' : 's'} written)` : ': the session already had their files'}`)
2511
+ this.setUpstream({ name: facts.name, sha: to, behind: 0, ahead: 0, brought: { count: facts.behind, files: written, at: Date.now() } })
2512
+ }
2513
+
2514
+ // -------------------------------------------------------- task branches --
2515
+ // An agent that is a member of its own (never a person, or a person's AI session) works on a branch
2516
+ // of its own for each task. Taking a task moves its folder, a git clone, onto quilt/<agent>/<task>,
2517
+ // made from the commit the folder is at and without the uncommitted work everyone has on the branch
2518
+ // it leaves (the session keeps that there). The agent commits and pushes there with its own git, and
2519
+ // its tasks move to QA only once that is done. People's folders are never moved: they pair on the
2520
+ // branch they are on.
2521
+
2522
+ /** One branch move at a time in this agent's folder (two at once fought over git's index). */
2523
+ branchForTask (task) {
2524
+ const p = (this.branchMoves || Promise.resolve()).then(() => this.branchForTaskNow(task))
2525
+ this.branchMoves = p.catch(() => {})
2526
+ return p
2527
+ }
2528
+
2529
+ /** Waits, a few seconds at most, for git and a move between branches in this folder to finish; whether they have. */
2530
+ async gitQuiet (ms = 8000) {
2531
+ const busy = () => !!(this.hold || this.pendingMove || this.gitBusy())
2532
+ const until = Date.now() + ms
2533
+ while (busy() && Date.now() < until) await new Promise((resolve) => setTimeout(resolve, 200))
2534
+ return !busy()
2535
+ }
2536
+
2537
+ /** The folder has arrived on `branch` in git and in the session, and is quiet: waited for, for `ms` at most. */
2538
+ async arrivedOn (branch, ms = 20000) {
2539
+ const there = () => !!this.git && this.git.branch === branch && !this.hold && !this.pendingMove
2540
+ const until = Date.now() + ms
2541
+ while (!there() && Date.now() < until) await new Promise((resolve) => setTimeout(resolve, 200))
2542
+ return there()
2543
+ }
2544
+
2545
+ /**
2546
+ * This agent took `task`: its folder goes onto the task's branch. Returns { branch, from } (where
2547
+ * it is now, and the branch it was made from or left), { stayed, why } when the folder stays where
2548
+ * it is, or null when there is nothing to do (a person, no git clone, on the task's branch already).
2549
+ */
2550
+ async branchForTaskNow (task) {
2551
+ if (this.kind !== 'agent' || this.stopped || !this.git || !this.git.branch || !task || !task.title) return null
2552
+ if (!(await this.gitQuiet())) return null
2553
+ const prefix = agentPrefix(this.name)
2554
+ const name = `${prefix}${slug(task.title)}`
2555
+ let from = this.git.branch
2556
+ if (from === name) return null
2557
+ if (from.startsWith(prefix)) {
2558
+ // On another task's branch: left for the default branch, so the new task starts from there and
2559
+ // not on top of the other's commits. Work of its own not committed yet would be left behind.
2560
+ const dirty = await this.ownUncommitted()
2561
+ if (dirty.length) {
2562
+ const why = `${dirty.slice(0, 4).join(', ')}${dirty.length > 4 ? ` and ${dirty.length - 4} more` : ''} ${dirty.length === 1 ? 'is' : 'are'} not committed on it. Commit (or put back) your changes there, then take the task again for a branch of its own.`
2563
+ this.log(`🌿 staying on ${from}: ${why}`)
2564
+ return { stayed: from, why }
2565
+ }
2566
+ const main = (this.branchList.find((b) => b && b.default) || {}).key || 'main'
2567
+ const back = await switchBranch(this.root, main, { force: true })
2568
+ if (back || !(await this.arrivedOn(main))) {
2569
+ const why = `git could not go back to ${main} from it${back ? ` (${back})` : ''}.`
2570
+ this.log(`🌿 staying on ${from}: ${why}`)
2571
+ return { stayed: from, why }
2572
+ }
2573
+ from = main
2574
+ }
2575
+ // A branch named after the task from before (the task was taken, left and taken again) is carried on with.
2576
+ const again = await hasBranch(this.root, name)
2577
+ // A new one starts from the latest the remote has of the branch it is made from (the agent's last
2578
+ // task, merged meanwhile, is then in it): fetched and brought in now, when that is all it takes.
2579
+ if (!again && this.bringInUpstream) {
2580
+ await this.caughtUp(from)
2581
+ if (!(await this.gitQuiet()) || !this.git || this.git.branch !== from) return null
2582
+ }
2583
+ const said = await switchBranch(this.root, name, { create: !again, force: true })
2584
+ if (said || !(await this.arrivedOn(name))) {
2585
+ const why = `git could not ${again ? 'check out' : 'make'} ${name}${said ? ` (${said})` : ''}.`
2586
+ this.log(`🌿 staying on ${from}: ${why}`)
2587
+ return { stayed: from, why }
2588
+ }
2589
+ this.log(`🌿 on ${name} for "${task.title}"${again ? '' : ` (made from ${from})`}: commit and push there`)
2590
+ return { branch: name, from, ...(again ? { again: true } : {}) }
2591
+ }
2592
+
2593
+ /**
2594
+ * Fetches `branch`'s upstream and waits, `ms` at most, for the folder to have its commits (bringIn
2595
+ * runs once the folder is in step with the session, which takes a moment just after arriving on the
2596
+ * branch). Whether the branch is at its upstream; false too when its commits are left to the person's git.
2597
+ */
2598
+ async caughtUp (branch, ms = 15000) {
2599
+ const until = Date.now() + ms
2600
+ for (let first = true; Date.now() < until; first = false) {
2601
+ await this.gitQuiet()
2602
+ await this.checkUpstream({ fetch: first }).catch(() => {})
2603
+ const up = await upstreamOf(this.root)
2604
+ const tip = await branchTip(this.root, branch)
2605
+ if (!up || !up.sha || !tip || this.stopped) return false
2606
+ if (up.sha === tip) return true
2607
+ const n = await aheadBehind(this.root, tip, up.sha)
2608
+ if (!n || !n.behind || (this.upstream && this.upstream.sha === up.sha && this.upstream.waiting)) return false
2609
+ await new Promise((resolve) => setTimeout(resolve, 1000))
2610
+ }
2611
+ return false
2612
+ }
2613
+
2614
+ /** The files this agent wrote on the branch it is on (by the session's record) that git has not committed, sorted. */
2615
+ async ownUncommitted () {
2616
+ const mine = new Set()
2617
+ for (const a of this.activity) if (a && a.by === this.name && a.branch === this.branch && typeof a.path === 'string' && a.path) mine.add(a.path)
2618
+ if (!mine.size) return []
2619
+ const st = await treeState(this.root, [...mine])
2620
+ return st ? [...mine].filter((rel) => st.dirty.has(rel)).sort() : []
2621
+ }
2622
+
2623
+ /**
2624
+ * Whether this agent's work is in git, asked when it moves a task to QA or Done: null when there is
2625
+ * nothing to hold it to (a person, no git clone, a folder not on a branch of the agent's own), else
2626
+ * { ok: true, branch } or { ok: false, why } with what to do.
2627
+ */
2628
+ async taskInGit () {
2629
+ if (this.kind !== 'agent' || !this.git || !this.git.branch || !this.git.branch.startsWith(agentPrefix(this.name))) return null
2630
+ const branch = this.git.branch
2631
+ const dirty = await this.ownUncommitted()
2632
+ if (dirty.length) {
2633
+ return { ok: false, why: `Get this task's work into git first: ${dirty.slice(0, 6).join(', ')}${dirty.length > 6 ? ` and ${dirty.length - 6} more` : ''} ${dirty.length === 1 ? 'is' : 'are'} not committed on ${branch}. Commit only the files you changed, push with \`git push -u origin ${branch}\`, then move the task again.` }
2634
+ }
2635
+ const up = await upstreamOf(this.root)
2636
+ const tip = await branchTip(this.root, branch)
2637
+ if (!up || !up.sha || !tip) return { ok: false, why: `Push ${branch} first: \`git push -u origin ${branch}\`. Open the pull request yourself (\`gh pr create\`), then move the task again.` }
2638
+ if (up.sha !== tip) {
2639
+ const n = await aheadBehind(this.root, tip, up.sha)
2640
+ if (!n || n.ahead) return { ok: false, why: `Push ${branch} first: it has ${n ? `${n.ahead} commit${n.ahead === 1 ? '' : 's'}` : 'commits'} the remote doesn't (\`git push\`). Then move the task again.` }
2641
+ }
2642
+ return { ok: true, branch }
2643
+ }
2644
+
2290
2645
  /**
2291
2646
  * Puts back the .git an older Quilt set aside in this folder (git-aside.js), once, when the session
2292
2647
  * starts and the relay has synced. A folder that got a new .git meanwhile keeps both. Whether git came back.
@@ -2327,7 +2682,7 @@ export class Session extends EventEmitter {
2327
2682
 
2328
2683
  /**
2329
2684
  * Pushes the on-disk state of a path into the shared doc. Returns true if anything changed.
2330
- * `pulled`: git brought this version (a pull), so it is not an edit of ours: never boxed, and counted as the pull's.
2685
+ * `pulled`: git brought this version (a pull), so it is not an edit of ours: it is counted as the pull's.
2331
2686
  */
2332
2687
  ingest (rel, { pulled = false } = {}) {
2333
2688
  if (!this.syncable(rel)) return false
@@ -2335,24 +2690,9 @@ export class Session extends EventEmitter {
2335
2690
  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
2336
2691
  if (this.downloading.has(rel)) return false // our copy is being replaced by a download
2337
2692
  if (this.writeFailed.has(rel)) return false // the shared version never reached the disk: what's there is no edit of ours
2338
- // New ignore rules: a box of ours on a file they now leave out lets go (settleBoxesOnce).
2339
2693
  if (IGNORE_FILES.includes(path.posix.basename(rel)) || rel === '.gitmodules') { this.ig = loadIgnore(this.root) }
2340
2694
  const disk = this.readDisk(rel, { settle: true })
2341
2695
  if (disk && disk.unsettled) { this.settleSoon(rel); return false }
2342
- const boxed = this.boxedByOther(rel)
2343
- if (boxed) {
2344
- // Someone else's box: what this folder has is its version from before the box, never theirs.
2345
- if ((disk ? disk.key : undefined) === this.lastKnown.get(rel)) return false // no edit
2346
- if (disk && (disk.skip || disk.tooLarge)) return false
2347
- // Git brought it in (the owner pushed it, and this folder pulled): git's, kept here, not shared.
2348
- if (pulled) {
2349
- if (disk) this.lastKnown.set(rel, disk.key); else this.lastKnown.delete(rel)
2350
- this.boxBase.set(rel, !disk ? null : disk.binary ? { b64: disk.buf.toString('base64') } : { text: disk.text })
2351
- this.scheduleStateSave()
2352
- return false
2353
- }
2354
- return this.editBoxed(rel, disk, boxed)
2355
- }
2356
2696
  const gitWas = this.gitOnly.get(rel) // git's version of a file the document hasn't, as this folder last had it
2357
2697
  if (this.gitOnly.size && this.gitOnly.has(rel)) {
2358
2698
  // A file git has that this branch's document hasn't, as the move left it: git's, not an edit.
@@ -2390,13 +2730,11 @@ export class Session extends EventEmitter {
2390
2730
  this.rejectLocal(rel, disk, refusal)
2391
2731
  return false
2392
2732
  }
2393
- // A change of ours while our AI works goes into a box of ours (unfinished work, out of other folders
2394
- // until it's committed). A person typing by hand while their AI sits idle edits live with everyone.
2395
- // Quilt's own line in .gitignore (ignoreQuiltState) is nobody's edit: never boxed for anyone.
2733
+ // A change of ours while our AI works is noted for its working state (noteAiEdit).
2734
+ // Quilt's own line in .gitignore (ignoreQuiltState) is nobody's edit.
2396
2735
  const quiltOwn = this.quiltOwnWrite === rel && disk && disk.key === this.quiltOwnKey
2397
2736
  if (quiltOwn) { this.quiltOwnWrite = null; this.quiltOwnKey = null }
2398
- // With boxes, a deletion is boxed too: it reaches nobody else's folder until it's committed.
2399
- if ((disk || this.boxesOn()) && !pulled && !quiltOwn && this.ready && !this.seeding && changesIt && this.aiMayBeEditing()) this.boxEdit(rel)
2737
+ if (disk && !pulled && !quiltOwn && this.ready && !this.seeding && changesIt && this.aiMayBeEditing()) this.noteAiEdit(rel)
2400
2738
 
2401
2739
  if (!disk) {
2402
2740
  if (!this.files.has(rel) && !this.blobs.has(rel)) {
@@ -2967,7 +3305,6 @@ export class Session extends EventEmitter {
2967
3305
 
2968
3306
  writeOut (rel) {
2969
3307
  if (!this.syncable(rel)) return
2970
- if (this.ghost(rel)) return
2971
3308
  if (this.merging.has(rel)) return // mergeOffline writes this path once it has merged it
2972
3309
  if (this.held()) { this.heldPaths.add(rel); return } // written when the hold ends (resumeHeld), or not at all once the folder has moved
2973
3310
  let abs
@@ -3027,7 +3364,6 @@ export class Session extends EventEmitter {
3027
3364
  if (!b || !b.stored) this.setOnDisk(rel, null)
3028
3365
  this.lastKnown.set(rel, shared)
3029
3366
  }
3030
- // New ignore rules: a box of ours on a file they now leave out lets go (settleBoxesOnce).
3031
3367
  if (IGNORE_FILES.includes(path.posix.basename(rel)) || rel === '.gitmodules') { this.ig = loadIgnore(this.root) }
3032
3368
 
3033
3369
  if (this.ready && !this.arriving) { // a move writing its branch onto the folder is no partner's change
@@ -3040,45 +3376,6 @@ export class Session extends EventEmitter {
3040
3376
  }
3041
3377
  }
3042
3378
 
3043
- /**
3044
- * Whether rel is someone else's box (docs/superpowers/specs/2026-10-16-git-boxes-design.md): their
3045
- * unfinished work stays in the session, not in this folder, so nothing run here commits it. The
3046
- * folder's version is kept, for putting back an edit refused meanwhile; lastKnown stays at it, so
3047
- * it's no edit of ours.
3048
- */
3049
- ghost (rel) {
3050
- if (!this.boxedByOther(rel)) return false
3051
- if (!this.boxBase.has(rel)) {
3052
- let d = null
3053
- try { d = this.readDisk(rel) } catch {}
3054
- if (d && (d.skip || d.tooLarge)) return true // nothing Quilt would ever put back
3055
- this.boxBase.set(rel, !d ? null : d.binary ? { b64: d.buf.toString('base64') } : { text: d.text })
3056
- this.scheduleStateSave()
3057
- }
3058
- return true
3059
- }
3060
-
3061
- /**
3062
- * An edit here to a file someone else has boxed. It is never undone: Quilt holds no files (no-holds,
3063
- * 2026-11-13). Their box opens, so their work reaches every folder (the relay tells them), and this
3064
- * edit goes in straight away through the normal merge (autoSettle), from this folder's version
3065
- * before the box. Returns true when the session's version changed.
3066
- */
3067
- editBoxed (rel, disk, box) {
3068
- const before = this.boxBase.has(rel) ? this.boxBase.get(rel) : undefined
3069
- const base = before === null ? null : before && typeof before.text === 'string' ? before.text : undefined
3070
- if (this.boxBase.delete(rel)) this.scheduleStateSave()
3071
- 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}`))
3072
- // Not someone else's box here any more, from now: the session's version is written to this folder again.
3073
- this.boxed.delete(rel)
3074
- this.log(`📦 ${rel} was in ${box.of || box.by}'s box: it opened, and your change goes in with their work`)
3075
- const ours = disk ? disk.key : null
3076
- const theirs = this.sharedKey(rel)
3077
- if (theirs === base || (theirs === undefined && base === null)) return this.ingest(rel) // their box changed nothing of it
3078
- const binary = [ours, theirs].some((k) => typeof k === 'string' && k.startsWith('bin:')) || !!(before && typeof before.b64 === 'string')
3079
- return this.autoSettle({ rel, base: binary ? null : base, ours, theirs, theirsBy: box.of || box.by, disk, binary, via: null }) === 'merged'
3080
- }
3081
-
3082
3379
  /**
3083
3380
  * Writes the session's version over a file of this folder's that a save may land in at the same moment:
3084
3381
  * in a file of its own put in place by one atomic exchange (swap-in.js; the file is never absent at its
@@ -3561,7 +3858,6 @@ export class Session extends EventEmitter {
3561
3858
 
3562
3859
  /** Downloads and decrypts a large file, then writes it into the folder. */
3563
3860
  async downloadLarge (rel, entry) {
3564
- if (this.ghost(rel)) return // someone else's box: downloaded once it opens
3565
3861
  if (this.downloading.get(rel) === entry.hash) return
3566
3862
  this.downloading.set(rel, entry.hash)
3567
3863
  const before = this.readDisk(rel)?.key
@@ -3582,7 +3878,6 @@ export class Session extends EventEmitter {
3582
3878
  const cur = this.blobs.get(rel)
3583
3879
  if (!cur || cur.hash !== entry.hash) return // replaced meanwhile; that version is on its way
3584
3880
  if (this.stopped) return
3585
- if (this.ghost(rel)) return // boxed by someone else meanwhile: written once it opens
3586
3881
  if (this.held()) { this.heldPaths.add(rel); return } // git is at work here: written once the hold ends (resumeHeld)
3587
3882
  const abs = resolveInside(this.root, rel)
3588
3883
  let st = null
@@ -3626,6 +3921,7 @@ export class Session extends EventEmitter {
3626
3921
 
3627
3922
  async startWatcher () {
3628
3923
  this.startGitWatch()
3924
+ this.startUpstream()
3629
3925
  this.scanDisk({ baseline: true }) // the folder was just reconciled; the first re-scan catches anything since
3630
3926
  this.watcher = watch(this.root, {
3631
3927
  ignoreInitial: true,
@@ -3718,6 +4014,8 @@ export class Session extends EventEmitter {
3718
4014
  if (s && id !== this.doc.clientID) this.log(`👋 ${s.name} joined (${s.tool})`)
3719
4015
  }
3720
4016
  if (removed.length) this.log(`${removed.length === 1 ? 'a partner' : `${removed.length} partners`} left`)
4017
+ for (const id of removed) this.peerTips.delete(id)
4018
+ this.notePeerTips()
3721
4019
  this.scheduleStatusWrite()
3722
4020
  this.scheduleTypingExpiry()
3723
4021
  })
@@ -4609,9 +4907,6 @@ export class Session extends EventEmitter {
4609
4907
  /** Who an action from this AI session is by: its own name, or this member's. */
4610
4908
  actorName (via) { const p = this.persona(via); return p ? p.name : this.name }
4611
4909
 
4612
- /** The box request fields that make the relay act for an AI session (server.js boxOwner). */
4613
- as (via) { const p = this.persona(via); return p ? { as: { id: p.rid || p.via, label: p.label } } : {} }
4614
-
4615
4910
  /** Whether a name is this member's or one of its AI sessions' (now or before a rename). */
4616
4911
  isMine (name) {
4617
4912
  if (!name) return false
@@ -4627,9 +4922,6 @@ export class Session extends EventEmitter {
4627
4922
  return [this.name, ...(this.aiOf ? [aiName(this.aiOf)] : []), ...[...this.personas.values()].flatMap((p) => [p.name, ...p.aliases])]
4628
4923
  }
4629
4924
 
4630
- /** Whether a box is this member's or one of its AI sessions': its work is in this folder. */
4631
- isOwnBox (c) { return !!c && (c.by === this.name || c.of === this.name || this.isMine(c.by)) }
4632
-
4633
4925
  /**
4634
4926
  * How an AI session reads the inbox: by its own name only. What is written to "<person>'s AI"
4635
4927
  * is the cloud AI's, and work for the person's AI waits on the board until they ask for it.
@@ -5005,54 +5297,17 @@ export class Session extends EventEmitter {
5005
5297
  this.scheduleStatusWrite()
5006
5298
  }
5007
5299
 
5008
- // ------------------------------------------------------------- boxes --
5009
- // Quilt holds no files (no-holds, 2026-11-13): nobody claims, queues for or hands off a file, and no
5010
- // write is refused or undone because someone else is working on it. What our AI changes in a git
5011
- // folder goes into a box of ours (unfinished work, kept out of other folders until it's committed);
5012
- // anyone who edits a boxed file opens it, and their change merges with the work in it (editBoxed).
5300
+ // ------------------------------------------------------- an AI's edits --
5301
+ // Quilt holds no files: nobody claims, queues for or hands off a file, and no write is refused or
5302
+ // undone because someone else is working on it. Every edit is shared as it is made.
5013
5303
 
5014
5304
  /** An agent session, or a person whose AI is working or whose tool Quilt can't read: an edit is probably the AI's. */
5015
5305
  aiMayBeEditing () {
5016
5306
  return this.kind === 'agent' || this.agentState?.status !== 'idle' || this.work?.state === 'working'
5017
5307
  }
5018
5308
 
5019
- /**
5020
- * Whether an AI's edits here go into boxes (docs/superpowers/specs/2026-10-16-git-boxes-design.md).
5021
- * Boxes are off, by the owner's decision of 2026-11-16: no edit is boxed, in a git folder or any other.
5022
- */
5023
- boxesOn () { return false }
5024
-
5025
- /** The box on rel when it is someone else's (their unfinished work: not written here), else null. */
5026
- boxedByOther (rel) {
5027
- const c = this.boxAt(rel)
5028
- return c && !this.isOwnBox(c) ? c : null
5029
- }
5030
-
5031
- /** The box on exactly rel (whoever's), or null. */
5032
- boxAt (rel) {
5033
- const c = this.boxed.get(rel)
5034
- return c && c.box !== false ? c : null
5035
- }
5036
-
5037
- /**
5038
- * Our AI changed rel here: noted for its working state, and, in a git folder, boxed for us (once:
5039
- * a box of ours already there keeps its first version, boxFrom). Someone else's box on it was opened
5040
- * before this (editBoxed), and a box the relay can't give (a race, an older relay) leaves the edit live.
5041
- */
5042
- boxEdit (rel) {
5043
- this.aiEdits.set(rel, Date.now())
5044
- if (!this.conn || !this.boxesOn() || this.ownBox(rel) || this.boxing.has(rel)) return
5045
- this.boxing.add(rel)
5046
- this.boxFrom.set(rel, this.sharedKey(rel) ?? null) // called before the edit goes in
5047
- const note = this.focus ? `editing: ${this.focus}` : 'editing'
5048
- this.noteActivity(`Editing ${rel}`)
5049
- this.conn.boxRequest({ op: 'box', pattern: rel, note }).then((r) => {
5050
- if (r && r.boxed === 0) this.boxFrom.delete(rel)
5051
- }, (err) => {
5052
- this.boxFrom.delete(rel)
5053
- this.log(`could not box ${rel} for you (it stays live with everyone): ${err.message}`)
5054
- }).finally(() => this.boxing.delete(rel))
5055
- }
5309
+ /** Our AI changed rel here: noted for its working state. */
5310
+ noteAiEdit (rel) { this.aiEdits.set(rel, Date.now()) }
5056
5311
 
5057
5312
  /** Forgets our AI's edits that have been quiet a while: "working" that only those edits said lapses with them. */
5058
5313
  forgetQuietEdits () {
@@ -5063,18 +5318,12 @@ export class Session extends EventEmitter {
5063
5318
  if (this.workFromEdits && !this.aiEdits.size && this.work?.state === 'working' && Date.now() - (this.agentReportedAt || 0) >= this.editQuietMs) this.finishEditing().catch(() => {})
5064
5319
  }
5065
5320
 
5066
- /** Our own box on exactly rel, or null. */
5067
- ownBox (rel) {
5068
- const c = this.boxAt(rel)
5069
- return c && this.isOwnBox(c) ? c : null
5070
- }
5071
-
5072
5321
  /**
5073
5322
  * The check every agent makes before it changes files, whatever tool it runs in (the local
5074
- * MCP's quilt_before_edit, or a hook): for each path, who wrote it recently (presence) and whose
5075
- * unfinished work is boxed on it, and what people said about those files in chat, as context. It
5076
- * never claims and never refuses: every path stays writable (no-holds, 2026-11-13). When no chat
5077
- * reader can see our AI work, it is marked working, so the host doesn't commit under it.
5323
+ * MCP's quilt_before_edit, or a hook): for each path, who wrote it recently (presence), and
5324
+ * what people said about those files in chat, as context. It never claims and never refuses: every
5325
+ * path stays writable. When no chat reader can see our AI work, it is marked working, so the host
5326
+ * doesn't commit under it.
5078
5327
  */
5079
5328
  async prepareEdit (paths, via = null) {
5080
5329
  const files = []
@@ -5083,8 +5332,7 @@ export class Session extends EventEmitter {
5083
5332
  for (const p of [...new Set((paths || []).map((x) => String(x || '').replace(/\\/g, '/').replace(/^\.\//, '')))]) {
5084
5333
  if (!p) continue
5085
5334
  if (!this.syncable(p)) { files.push({ path: p, shared: false }); continue }
5086
- const b = this.boxedByOther(p)
5087
- files.push({ path: p, shared: true, ok: true, recent: this.recentWriters(p).filter((w) => w.by !== me), ...(b ? { box: { by: b.of || b.by } } : {}) })
5335
+ files.push({ path: p, shared: true, ok: true, recent: this.recentWriters(p).filter((w) => w.by !== me) })
5088
5336
  }
5089
5337
  // A session still named after its tool takes a name from the first file it edits.
5090
5338
  const first = files.find((f) => f.shared)
@@ -5231,7 +5479,7 @@ export class Session extends EventEmitter {
5231
5479
  try { return pickupMode(getSettings().aiTasks) } catch { return 'off' }
5232
5480
  }
5233
5481
 
5234
- /** Done with a piece of work: says we're done. Nothing is held, so nothing is let go of (boxes stay until committed). */
5482
+ /** Done with a piece of work: says we're done. Nothing is held, so nothing is let go of. */
5235
5483
  async finishEditing (via = null) {
5236
5484
  if (!this.persona(via)) this.aiEdits.clear()
5237
5485
  if (this.work?.state === 'working') this.setWork('done')
@@ -5239,50 +5487,6 @@ export class Session extends EventEmitter {
5239
5487
  return { released: 0 }
5240
5488
  }
5241
5489
 
5242
- /**
5243
- * The session's boxes as the app shows them (boxes.js): each with what it changes from the version
5244
- * this folder has. Someone else's: from this folder's version before the box (what is on disk);
5245
- * ours: from what git last committed. `on`: whether this folder's own edits box (a git repository).
5246
- */
5247
- async boxes () {
5248
- const text = (d) => (!d || d.skip || d.tooLarge ? null : d.binary ? { binary: true } : d.text)
5249
- const out = []
5250
- for (const c of this.boxed.values()) {
5251
- if (!c || c.box === false || /[*?[]/.test(c.pattern) || !isSafeRelPath(c.pattern)) continue
5252
- const rel = c.pattern
5253
- const t = this.files.get(rel)
5254
- const after = t ? t.toString() : this.blobs.has(rel) ? { binary: true } : null
5255
- const mine = this.isOwnBox(c)
5256
- let before = null
5257
- if (mine) {
5258
- const base = this.boxBase.has(rel) ? this.boxBase.get(rel) : null
5259
- before = base === null ? null : typeof base.text === 'string' ? base.text : { binary: true }
5260
- } else if (this.boxBase.has(rel)) {
5261
- const base = this.boxBase.get(rel)
5262
- before = base === null ? null : typeof base.text === 'string' ? base.text : { binary: true }
5263
- } else {
5264
- try { before = text(this.readDisk(rel)) } catch { before = null }
5265
- }
5266
- out.push(boxEntry({ box: c, mine, before, after }))
5267
- }
5268
- return { on: this.boxesOn(), boxes: out.sort((a, b) => a.ts - b.ts || a.path.localeCompare(b.path)) }
5269
- }
5270
-
5271
- /** Our AI shares boxed files before they're committed: their content reaches every folder now, and we keep the files. */
5272
- async unpack (paths, via = null) {
5273
- const unpacked = []
5274
- const notBoxed = []
5275
- for (const p of [...new Set((paths || []).map((x) => String(x || '').replace(/\\/g, '/').replace(/^\.\//, '')).filter(Boolean))]) {
5276
- if (!this.ownBox(p)) { notBoxed.push(p); continue }
5277
- if (!this.conn) throw new Error('not connected to the relay')
5278
- // 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'.
5279
- const r = await this.conn.boxRequest({ op: 'unbox', pattern: p, release: false })
5280
- if (r.unboxed) { unpacked.push(p); this.boxFrom.delete(p) } else notBoxed.push(p)
5281
- }
5282
- if (unpacked.length) this.noteActivity(`Unpacked ${unpacked.join(', ')}`, { via })
5283
- return { unpacked, notBoxed }
5284
- }
5285
-
5286
5490
  /**
5287
5491
  * Why we can't reach the relay (e.g. no session pass), or null once that's fixed.
5288
5492
  * Logged once per new reason, not on every retry, and shown in status.
@@ -5295,32 +5499,6 @@ export class Session extends EventEmitter {
5295
5499
  this.emit('status-changed')
5296
5500
  }
5297
5501
 
5298
- /** Takes the relay's box list (its MSG_CLAIMS, which lists boxes only), and writes out what opened. */
5299
- setBoxes (list) {
5300
- const was = this.boxed
5301
- const next = new Map()
5302
- // An older relay still sends claims: only boxes are kept, and nothing anyone holds is enforced here.
5303
- 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)
5304
- this.boxed = next
5305
- try { fs.writeFileSync(path.join(this.stateDir, 'boxes.json'), JSON.stringify([...next.values()])) } catch {}
5306
- // A box handed to us (our cloud AI stopped with it, server.js handBackCloudBoxes): our git may have it already.
5307
- if (this.ready && [...next].some(([p, c]) => c.handedFrom && this.isOwnBox(c) && !(was.get(p) && this.isOwnBox(was.get(p))))) this.scheduleStatusWrite()
5308
- // A box someone else held opened (committed, unpacked, opened by an edit): its file reaches this folder now.
5309
- // (Also one that opened while this folder was away: its ghost is still on record.)
5310
- if (this.ready) {
5311
- const opened = new Set([...was].filter(([, c]) => !this.isOwnBox(c)).map(([p]) => p))
5312
- for (const p of this.boxBase.keys()) opened.add(p)
5313
- for (const p of opened) {
5314
- if (this.boxedByOther(p)) continue // still someone else's box
5315
- if (this.boxBase.delete(p)) this.scheduleStateSave()
5316
- this.tryWrite(p)
5317
- }
5318
- }
5319
- if (this.ready) this.settleReleasedMerges()
5320
- this.scheduleStatusWrite()
5321
- this.emit('boxes', [...next.values()])
5322
- }
5323
-
5324
5502
  /**
5325
5503
  * Our offline edits an older app held back because someone held the file (open 'claimed' records):
5326
5504
  * nobody holds files now (no-holds, 2026-11-13), so each goes in straight away through the normal
@@ -5374,16 +5552,6 @@ export class Session extends EventEmitter {
5374
5552
  }
5375
5553
  }
5376
5554
 
5377
- /** Last known boxes, so someone else's unfinished work isn't written here before the relay answers (or while offline). */
5378
- loadBoxes () {
5379
- let list = null
5380
- try { list = JSON.parse(fs.readFileSync(path.join(this.stateDir, 'boxes.json'), 'utf8')) } catch {}
5381
- // A folder from before no-holds kept them with its claims (claims.json): the boxes stay, every claim goes.
5382
- if (!list) { try { list = JSON.parse(fs.readFileSync(path.join(this.stateDir, 'claims.json'), 'utf8')) } catch {} }
5383
- for (const c of Array.isArray(list) ? list : []) if (c && c.box === true && typeof c.pattern === 'string') this.boxed.set(c.pattern, c)
5384
- try { fs.rmSync(path.join(this.stateDir, 'claims.json'), { force: true }) } catch {}
5385
- }
5386
-
5387
5555
  // ------------------------------------------------------------ merges --
5388
5556
 
5389
5557
  mergeList () { return readMerges(this.merges) }
@@ -5653,7 +5821,7 @@ export class Session extends EventEmitter {
5653
5821
 
5654
5822
  /**
5655
5823
  * Every shared path with who last edited it (from activity and live
5656
- * presence) and the box on it (someone's unfinished work). Read from the shared doc.
5824
+ * presence). Read from the shared doc.
5657
5825
  */
5658
5826
  tree () {
5659
5827
  const edited = new Map()
@@ -5668,13 +5836,6 @@ export class Session extends EventEmitter {
5668
5836
  const editing = id === this.doc.clientID ? Object.fromEntries(this.myEdits) : (st.editing || {})
5669
5837
  for (const [p, ts] of Object.entries(editing)) note(p, st.name, ts)
5670
5838
  }
5671
- // `active` is false when whoever boxed it isn't in the session (older relays don't say: active).
5672
- // Shown as people see it: an older app's AI session ("Dana · login", of: Dana) is its person.
5673
- 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 } : {}) })
5674
- const boxOf = (p) => {
5675
- const c = this.boxAt(p)
5676
- return c ? shown(c) : null
5677
- }
5678
5839
  // Files that are GitHub's version, not edited in the session since (the relay marks them: relay-sync.js markFromGithub).
5679
5840
  const gh = this.bdoc ? this.bdoc.getMap('fromGithub') : null
5680
5841
  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 }
@@ -5684,14 +5845,11 @@ export class Session extends EventEmitter {
5684
5845
  for (const p of listed) {
5685
5846
  if (!isSafeRelPath(p)) continue
5686
5847
  const blob = this.blobs.get(p)
5687
- 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) })
5848
+ 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) })
5688
5849
  }
5689
5850
  out.push(...this.chatFileEntries())
5690
5851
  out.sort((a, b) => a.path.localeCompare(b.path))
5691
- return {
5692
- files: out,
5693
- boxes: [...this.boxed.values()].map(shown)
5694
- }
5852
+ return { files: out }
5695
5853
  }
5696
5854
 
5697
5855
  /** The chat files folder, for the file tree: each file I can see that is saved there, with who sent it. */
@@ -5797,6 +5955,8 @@ export class Session extends EventEmitter {
5797
5955
  branch: this.branch,
5798
5956
  // A git checkout: where git has the folder, and whether its sync is held (git at work, or moving to the branch `to`).
5799
5957
  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,
5958
+ // The branch against its upstream, once looked at: commits it is behind and why they wait, or what was last brought in.
5959
+ ...(this.upstream ? { upstream: this.upstream } : {}),
5800
5960
  connected: !!(this.conn && this.conn.connected),
5801
5961
  ...(this.relayProblem ? { problem: this.relayProblem } : {}),
5802
5962
  access: this.access,
@@ -5823,7 +5983,6 @@ export class Session extends EventEmitter {
5823
5983
  // The session's call: whether the owner has transcripts on, and the agents in it.
5824
5984
  voice: { transcribe: transcribeSetting(this.doc, this.members).on, agents: callAgents(this.doc, this.conn ? this.liveCall() : '', this.members) },
5825
5985
  peers,
5826
- boxes: [...this.boxed.values()].sort((a, b) => a.ts - b.ts),
5827
5986
  tasks: this.taskList(),
5828
5987
  // Without the texts (up to 400 KB a record): status goes out on every
5829
5988
  // change. The full records are at GET /merges and the app's merges route.