heyquilt 0.3.170 → 0.3.172

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/RELEASES.md +30 -0
  2. package/bin/quilt.js +16 -9
  3. package/package.json +2 -2
  4. package/src/agent-task-workflow.js +2 -9
  5. package/src/base-pick.js +212 -0
  6. package/src/boxes.js +6 -7
  7. package/src/catchup.js +1 -1
  8. package/src/chat-links.js +1 -3
  9. package/src/connection.js +24 -5
  10. package/src/control.js +27 -20
  11. package/src/duties.js +32 -56
  12. package/src/github-commit.js +1 -1
  13. package/src/held.js +323 -0
  14. package/src/hooks.js +27 -66
  15. package/src/identity.js +1 -1
  16. package/src/inbox.js +5 -4
  17. package/src/key-cli.js +1 -1
  18. package/src/live-merge.js +599 -0
  19. package/src/mcp.js +57 -102
  20. package/src/merge3.js +65 -1
  21. package/src/now-summary.js +4 -6
  22. package/src/pathrules.js +1 -1
  23. package/src/persona.js +1 -1
  24. package/src/presence.js +2 -0
  25. package/src/protocol.js +2 -2
  26. package/src/read-bases.js +123 -0
  27. package/src/relay-ask.js +2 -2
  28. package/src/relay-live-write.js +179 -0
  29. package/src/relay-mcp.js +173 -212
  30. package/src/relay-prune.js +2 -2
  31. package/src/relay-turn-sync.js +146 -142
  32. package/src/runner.js +0 -2
  33. package/src/server.js +253 -375
  34. package/src/session-follow.js +3 -1
  35. package/src/session-quilt.js +2 -21
  36. package/src/session-seam.js +35 -7
  37. package/src/session.js +795 -553
  38. package/src/setup.js +15 -25
  39. package/src/source-live/bring-in.js +5 -5
  40. package/src/source-live/land.js +20 -3
  41. package/src/source-live/live-block.js +503 -52
  42. package/src/status.js +8 -12
  43. package/src/swap-in.js +81 -0
  44. package/src/textdiff.js +54 -0
  45. package/src/turn-sync-plan.js +6 -18
  46. package/src/turn-sync.js +28 -21
  47. package/src/ui/agent-guide.js +13 -13
  48. package/src/ui/app.css +19 -40
  49. package/src/ui/boxes.js +8 -16
  50. package/src/ui/common.js +1 -1
  51. package/src/ui/fileview.js +11 -15
  52. package/src/ui/loom-model.js +18 -16
  53. package/src/ui/loom.css +1 -2
  54. package/src/ui/loom.js +6 -6
  55. package/src/ui/rail-model.js +25 -64
  56. package/src/ui/rail.js +48 -60
  57. package/src/ui/seam-model.js +39 -3
  58. package/src/ui/session.js +36 -54
  59. package/src/ui/tree.js +22 -129
  60. package/src/ui-server.js +2 -6
  61. package/src/release-words.js +0 -18
  62. package/src/seam-claims.js +0 -53
package/src/session.js CHANGED
@@ -22,7 +22,7 @@ import { MAX_SHARED_FILE_BYTES, FEATURES } from './protocol.js'
22
22
  import { formatBytes } from './status.js'
23
23
  import {
24
24
  loadIgnore, IGNORE_FILES, isIgnored, isSafeRelPath, resolveInside, looksBinary, sha1, walk,
25
- toPosix, globMatcher, MAX_TEXT_BYTES, MAX_BINARY_BYTES, LARGE_FILE_BYTES, MAX_STORED_BINARY_BYTES, CHAT_FILES, closeWatcher
25
+ toPosix, MAX_TEXT_BYTES, MAX_BINARY_BYTES, LARGE_FILE_BYTES, MAX_STORED_BINARY_BYTES, CHAT_FILES, closeWatcher
26
26
  } from './fsutil.js'
27
27
  import { wrapForRelay, relayKeyId, deriveWrapKey, newFileKey, wrapKey, unwrapKey, encryptBlob, decryptBlob, blobId } from './largefiles.js'
28
28
  import { applyTextDiff } from './textdiff.js'
@@ -35,7 +35,6 @@ import { linkedHistory, mergeLinked } from './quilt-history.js'
35
35
  import { readAccount } from './account.js'
36
36
  import { seamAccess, sessionCredential, isAgentKey } from './seam-access.js'
37
37
  import { startAsQuilt } from './quilt-default.js'
38
- import { releaseInSeam } from './seam-claims.js'
39
38
  import { historyMarks, awayChanges, mergeCatchUp, emptyCatchUp } from './catchup.js'
40
39
  import { Inbox, mentionsMe, describeEvent } from './inbox.js'
41
40
  import { projectRules, renderRules, gatherPlan, planKey } from './project-rules.js'
@@ -44,15 +43,20 @@ import { withContext, queryConversation } from './conversation.js'
44
43
  import { personaName, cleanLabel, labelFromBranch, labelFromText, labelFromFile, gitBranch, aiName } from './persona.js'
45
44
  import { aiOwners, ownAiChatter } from './ui/chat.js'
46
45
  import { cloudReader, isCloudAi } from './cloud-ai.js'
47
- import { chatAbout, waitingOn, queuedFor, renderQueueNotice, askForIt, heldRefusal, answered, addressees, unaddressed, sentByAnother, renderRepeat, replyFor, renderReplied, PERSON_INBOX } from './duties.js'
46
+ import { chatAbout, waitingOn, answered, addressees, unaddressed, sentByAnother, renderRepeat, replyFor, renderReplied, PERSON_INBOX } from './duties.js'
48
47
  import { makeSubscription, deliverEvents, deliverWebhook, parseWebhookUrl, webhookPayload } from './webhooks.js'
49
48
  import { MentionRunner, parseOnMention, readOnMention, writeOnMention } from './on-mention.js'
50
49
  import { pickChecklist } from './agent-task-workflow.js'
51
50
  import { changeRefusal, TALK_REFUSED } from './session-access.js'
52
51
  import { canAdmit } from './admit-policy.js'
53
- import { merge3, mergeAuto, hasMarkers } from './merge3.js'
52
+ import { merge3, hasMarkers, mergeLive } from './merge3.js'
54
53
  import { sameEditClient, asClient } from './same-edit.js'
55
54
  import { openMerge, updateMerge, readMerges, pruneMerges, cleanName } from './merges.js'
55
+ import { LiveRules, applyMine, findUses, removedNameWarning } from './live-merge.js'
56
+ import { versionOf } from './read-bases.js'
57
+ import { RecentTexts, atimeWorks, keepWritten, letGo } from './base-pick.js'
58
+ import { swapIn } from './swap-in.js'
59
+ import { HELD_MAP, SETTINGS_MAP, readHeld, findHeld, settleHeld, staleWriteMinutes, setStaleWriteMinutes, renderHeld, heldLandingNote } from './held.js'
56
60
  import { RELAY_NAME as RELAY_BY, isRelay } from './ui/chat.js'
57
61
  import { cleanTyping, TYPING_MS, AGENT_TYPING_MS } from './ui/chat.js'
58
62
  import { DEFAULT_KEY } from './branchdocs.js'
@@ -113,6 +117,7 @@ const CLASH_RECORDS = 100
113
117
  const KEEP_DONE_COMMITS = 100 // finished commit requests kept, newest (the board shows which task's work was committed)
114
118
  const COLORS = ['#4f4fa0', '#3b6a9a', '#4a7a45', '#855a9c', '#a8701c', '#2e7a80', '#9c4f6b']
115
119
  const RECENT_MS = 2 * 60 * 1000
120
+ const RECENT_WRITER_MS = 15 * 60 * 1000 // quilt_before_edit shows who wrote a file this recently (presence, never a hold)
116
121
 
117
122
  /**
118
123
  * A peer's edits from its presence that are still recent, newest first. Its presence keeps its last
@@ -130,10 +135,8 @@ function processAlive (pid) {
130
135
  try { process.kill(pid, 0); return true } catch (err) { return err.code === 'EPERM' }
131
136
  }
132
137
  const PERSONA_AWAY_MS = 30 * 60 * 1000 // an AI session not heard from this long is no longer shown as here
133
- const AUTO_CLAIM_QUIET_MS = 10 * 60 * 1000 // a file we stopped editing this long ago is let go of (long enough for partners to see the claim)
134
- // Our AI stopped working (its chat reader says so) while someone waits for a file it held: this long
135
- // for it to hand the file on itself, then Quilt hands it on for it.
136
- const HANDOFF_GRACE_MS = 2 * 60 * 1000
138
+ // "Working" that only our AI's edits said lapses once its files have been quiet this long (forgetQuietEdits).
139
+ const EDIT_QUIET_MS = 10 * 60 * 1000
137
140
  const NOTICE_CAP = 20
138
141
  const CATCH_UP_KEEP_MS = 3 * 24 * 60 * 60 * 1000 // an unread "while you were away" goes after this
139
142
  const CATCH_UP_FILES = 200 // paths kept per person in it
@@ -171,8 +174,6 @@ const CATCHER_WAITING = 'another member is bringing these commits in'
171
174
  const RELAY_WAITING = 'the relay is bringing these commits into the session'
172
175
  // How long a git pull's settle waits for the relay to be at the pulled commit before sharing it as before (planSettle).
173
176
  const RELAY_PULL_WAIT_MS = 15 * 1000
174
- // How long an automatic claim on its way to the relay is waited for before it is taken as never made (releaseAutoClaims).
175
- const AUTO_CLAIM_ARRIVE_MS = 30 * 1000
176
177
  const SETTLE_BOXES_MS = 1500 // after an edit to one of our boxed files: does git have it as the session does now?
177
178
  const RELAY_ASK_EVERY_MS = 5 * 1000 // a folder waiting for the relay asks it again this often (server.js SYNC_EVERY_GIT_MS)
178
179
  const INDEX_WATCH_MS = 8000 // after a bring-in, how long the index is checked against what another git may write back
@@ -202,8 +203,29 @@ function notSharedLines (list) {
202
203
  /** What a move says when it made the room's read token again (server.js freshReadToken). */
203
204
  const readTokenLine = (why) => `The session's read token for its quilt was ${why === 'missing' ? 'missing' : why === 'expiring' ? 'about to end' : 'no longer taken by Seam'}, so a new one was made: every folder reads its square with it.`
204
205
 
206
+ /** Writes `data` to `abs` and returns the file's stat as the write left it (taken before it is closed). */
207
+ // Quilt's own file in the making (writeOver, rescueSave): never synced.
208
+ const QUILT_TEMP = /^\..+\.quilt-(tmp|save)$/
209
+ // A file emptied this recently may be a save half done (truncated, not written yet): looked at again first.
210
+ const SETTLE_MS = 250
211
+ // A text Quilt wrote up to this long is kept in memory while the file is untouched (noteWritten, readDisk).
212
+ const WROTE_TEXT = 1024 * 1024
213
+ const WROTE_BYTES = 32 * 1024 * 1024 // all of them together; past it the oldest are read from disk again
214
+ // After a write-out, the file it replaced is looked at once more this much later: a save into it, opened just before.
215
+ const LATE_WRITE_MS = 100
216
+
217
+ function writeAndStat (abs, data, mode = undefined) {
218
+ const fd = fs.openSync(abs, 'w', mode)
219
+ try {
220
+ const buf = typeof data === 'string' ? Buffer.from(data, 'utf8') : data
221
+ let off = 0
222
+ while (off < buf.length) off += fs.writeSync(fd, buf, off, buf.length - off)
223
+ return fs.fstatSync(fd)
224
+ } finally { fs.closeSync(fd) }
225
+ }
226
+
205
227
  export class Session extends EventEmitter {
206
- constructor ({ dir, server, room, secret, key = '', viewSecret = '', name, tool = 'unknown', color = null, prefer = 'remote', kind = 'human', shareAgent = true, summarize = null, identity = null, passes = null, startName = '', startAgentCommits = '', newSession = false, quiltDefault = null, workspace = '', autoClaimQuietMs = AUTO_CLAIM_QUIET_MS, handoffGraceMs = HANDOFF_GRACE_MS, aiTasks = null, pushLocalCommits = null, webhookTransport = null, pullWaitMs = PULL_WAIT_MS, bringInUpstream = true, clashReassignMs = CLASH_REASSIGN_MS, clashWaitMs = CLASH_WAIT_MS, clashSettleMs = CLASH_SETTLE_MS, clashIdleMs = CLASH_IDLE_MS, catcherWaitMs = CATCHER_WAIT_MS, gitBacking = true, gitRemote = null, followsRelay = true, turns = false, features = null, cli = defaultCli(), apiAuth = null }) {
228
+ constructor ({ dir, server, room, secret, key = '', viewSecret = '', name, tool = 'unknown', color = null, prefer = 'remote', kind = 'human', shareAgent = true, summarize = null, identity = null, passes = null, startName = '', startAgentCommits = '', newSession = false, quiltDefault = null, workspace = '', editQuietMs = EDIT_QUIET_MS, aiTasks = null, pushLocalCommits = null, webhookTransport = null, pullWaitMs = PULL_WAIT_MS, bringInUpstream = true, clashReassignMs = CLASH_REASSIGN_MS, clashWaitMs = CLASH_WAIT_MS, clashSettleMs = CLASH_SETTLE_MS, clashIdleMs = CLASH_IDLE_MS, catcherWaitMs = CATCHER_WAIT_MS, gitBacking = true, gitRemote = null, followsRelay = true, turns = false, features = null, cli = defaultCli(), apiAuth = null }) {
207
229
  super()
208
230
  // The Quilt sign-in this session runs as, for the accounts API and Seam (seam-access.js): its person's, or its agent's key.
209
231
  this.apiAuth = apiAuth
@@ -269,9 +291,10 @@ export class Session extends EventEmitter {
269
291
  this.transfers = 0 // large uploads and downloads running
270
292
  this.transferQueue = [] // resolvers waiting for one to finish
271
293
  this.stopped = false
272
- // pattern -> { by, pattern, note, ts }. The relay owns claims (it checks
273
- // who asks), so they live outside the shared doc; we keep the last list.
274
- this.claims = new Map()
294
+ // Boxes (someone's unfinished work on one file, kept out of other folders until it's committed):
295
+ // path -> { by, pattern, note, ts, box: true }. The relay keeps them, outside the shared doc; we keep
296
+ // the last list. Quilt holds no files (no-holds, 2026-11-13): a box never stops anyone writing.
297
+ this.boxed = new Map()
275
298
  this.chat = this.doc.getArray('chat') // { by, text, ts }
276
299
  this.activity = this.doc.getArray('activity') // { by, path, kind, detail, ts }
277
300
  this.agentFeed = this.doc.getArray('agentFeed') // { id, by, tool, conv, kind, text, ts, summary?, title? }
@@ -287,9 +310,8 @@ export class Session extends EventEmitter {
287
310
  this.aiSent = [] // [{ via, targets, text, ts }]
288
311
  // Each AI session working through this app (its `quilt mcp`, by its `via` id) under a name of
289
312
  // its own: "<first name> · <label>" (persona.js). via -> { via, name, label, aliases, tool,
290
- // ppid, named, inbox, seenAt, touchedAt }. Its messages, claims, inbox and duties are its own.
313
+ // ppid, named, inbox, seenAt, touchedAt }. Its messages, inbox and duties are its own.
291
314
  this.personas = new Map()
292
- this.autoVia = new Map() // a file claimed for one AI session as it edited -> that session's via
293
315
  // The agent's webhook subscription (webhooks.js), kept in .quilt/webhook.json: inbox events are POSTed there.
294
316
  this.webhook = null
295
317
  this.webhookTransport = webhookTransport // { fetch, delays } for tests
@@ -309,29 +331,33 @@ export class Session extends EventEmitter {
309
331
  // ages out on our clock, not theirs.
310
332
  this.typing = {}
311
333
  this.typingSeen = new Map()
312
- // Claims follow edits (see autoClaim): path -> when this person last changed it. Released when
313
- // their AI goes idle, when the file has been quiet for autoClaimQuietMs, and at stop.
314
- this.autoClaims = new Map()
315
- this.reboxing = new Set() // our files whose box is being asked for again (autoClaim)
334
+ // Files our AI changed (see boxEdit): path -> when it last did. Forgotten once quiet for editQuietMs
335
+ // (forgetQuietEdits), and "working" that only these edits said lapses with them.
336
+ this.aiEdits = new Map()
337
+ this.boxing = new Set() // our files whose box is on its way to the relay (boxEdit)
316
338
  // Ghosts: files someone else has boxed, not written here. For each, this folder's version from before
317
339
  // the box ({ text } or { b64 }; null: it wasn't there), put back when an edit here is refused. Kept in state.json.
318
340
  this.boxBase = new Map()
319
341
  // Our boxes: what the session had before the edit that opened each (null: no file). Back to that, the box holds
320
342
  // nothing of ours (our edit undone, or taken back) and opens like a committed one.
321
343
  this.boxFrom = new Map()
322
- this.queueNoticed = new Map() // claim pattern -> when our AI was last told someone waits for it
323
- this.autoClaimQuietMs = autoClaimQuietMs
324
- this.handoffGraceMs = handoffGraceMs
344
+ this.editQuietMs = editQuietMs
325
345
  // Whether our AI takes work from the board by itself (tasks.js PICKUP_MODES); null: this person's setting.
326
346
  this.aiTasks = aiTasks
327
347
  this.pushLocalCommits = pushLocalCommits
328
- this.autoClaimTimer = setInterval(() => this.releaseQuietAutoClaims(), Math.max(50, Math.min(60_000, Math.floor(autoClaimQuietMs / 3))))
329
- if (this.autoClaimTimer.unref) this.autoClaimTimer.unref()
348
+ this.editQuietTimer = setInterval(() => this.forgetQuietEdits(), Math.max(50, Math.min(60_000, Math.floor(editQuietMs / 3))))
349
+ if (this.editQuietTimer.unref) this.editQuietTimer.unref()
330
350
  // What this person's AI should hear next time it talks to Quilt (an edit of its that was undone).
331
351
  this.notices = []
332
352
 
333
353
  this.ig = loadIgnore(this.root)
334
354
  this.lastKnown = new Map() // path -> text content, or "bin:<sha1>"
355
+ this.relayWriting = new Set() // paths with a live write at the relay, not answered yet (relayIngest)
356
+ this.relayAgain = new Set() // of those, the ones saved again meanwhile: taken in once the answer is here
357
+ this.relayLocal = new Set() // paths the relay asked to be edited here as before (its answer's `fallback`), once
358
+ this.overwritten = new RecentTexts() // the texts a partner's change was lately written over here: a save's possible base (base-pick.js)
359
+ this.wroteHere = new Map() // path -> { ino, size, mtimeMs, text }: the text file Quilt last wrote there, read back from memory while untouched
360
+ this.wroteBytes = 0 // their texts' length, together
335
361
  // path -> sha1 of lastKnown when state.json was last saved (null: a state file from before this was kept).
336
362
  this.known = null
337
363
  // path -> why the shared version could not be written. Tried again by
@@ -344,7 +370,7 @@ export class Session extends EventEmitter {
344
370
  this.reconcileTimer = null
345
371
  this.ready = false
346
372
  this.myEdits = new Map() // path -> ts of my last edit
347
- this.settleTried = new Set() // claimed merges already tried against a session version (id:sha1)
373
+ this.settleTried = new Set() // held merges from before no-holds already tried against a session version (id:sha1)
348
374
  this.lastActivityPush = new Map()
349
375
  this.warnedLarge = new Set()
350
376
  this.agents = new Set()
@@ -407,7 +433,6 @@ export class Session extends EventEmitter {
407
433
  this.upstreamPoll = null
408
434
  this.upstreamSaid = '' // the advice last given, so it's given once per state
409
435
  this.fetchState = null // the last git fetch of the upstream: { ok, error, at } (noteFetch)
410
- this.clashClaims = null // the files held for this member's clash task: { task, via, paths } (claimClashFiles)
411
436
  this.upstreamDeferred = null // the commit this folder let another member's folder bring in first
412
437
  this.clashAbsent = null // { task, name, since }: a clash task's assignee seen gone from the branch
413
438
  this.clashWait = null // { sha, since }: since when this folder has waited for the first in line to write the clash task
@@ -602,7 +627,7 @@ export class Session extends EventEmitter {
602
627
  this.joinedEmpty = !hadState && !walk(this.root, this.ig).some((rel) => this.syncable(rel))
603
628
  // Restarted while the folder follows its square: its .git is set aside (session-follow.js) and stays so; its branch is the note's.
604
629
  this.gitAside = hasGitDir(this.root) ? null : gitAsideOf(this.root)
605
- if (hadState) this.loadClaims()
630
+ if (hadState) this.loadBoxes()
606
631
  // The branch whose square this folder follows: the checkout's branch name, the set-aside note's, else the room's default.
607
632
  this.branch = headBranch(this.root) || (this.gitAside && this.gitAside.branch) || DEFAULT_KEY
608
633
  // The form saved is the saved branch's; another branch's is the relay's to say when it is joined.
@@ -639,7 +664,7 @@ export class Session extends EventEmitter {
639
664
  this.conn.on('fatal', (err) => this.emit('fatal', err))
640
665
  this.conn.on('pass', (p) => this.adoptPass(p))
641
666
  this.conn.on('problem', (msg) => this.setRelayProblem(msg))
642
- this.conn.on('claims', (list) => this.setClaims(list))
667
+ this.conn.on('boxes', (list) => this.setBoxes(list))
643
668
  this.conn.on('access', (a) => this.setAccess(a))
644
669
  this.conn.on('members', (m) => this.setMembers(m))
645
670
  this.conn.on('branches', (list) => this.setBranches(list))
@@ -911,6 +936,10 @@ export class Session extends EventEmitter {
911
936
  this.scheduleStatusWrite()
912
937
  })
913
938
  this.taskComments.observe(() => this.scheduleStatusWrite())
939
+ // Held conflicts (held.js): the app and quilt_status show every open one as it comes and goes.
940
+ this.doc.getMap(HELD_MAP).observe(() => { this.scheduleStatusWrite(); this.emit('held', this.heldList()) })
941
+ // The owner's stale_write_minutes (held.js): Session settings and the CLI show it as it changes.
942
+ this.doc.getMap(SETTINGS_MAP).observe(() => this.scheduleStatusWrite())
914
943
  this.agentFeed.observe((ev) => {
915
944
  const added = []
916
945
  for (const item of ev.changes.added) for (const e of item.content.getContent()) if (e && e.id) added.push(e)
@@ -1091,7 +1120,7 @@ export class Session extends EventEmitter {
1091
1120
  }
1092
1121
 
1093
1122
  syncable (rel) {
1094
- return isSafeRelPath(rel) && !isIgnored(this.ig, rel)
1123
+ return isSafeRelPath(rel) && !isIgnored(this.ig, rel) && !QUILT_TEMP.test(path.posix.basename(rel))
1095
1124
  }
1096
1125
 
1097
1126
  /**
@@ -1284,11 +1313,8 @@ export class Session extends EventEmitter {
1284
1313
  const ours = disk ? disk.key : null // re-read: it may have changed again before the relay synced
1285
1314
  const theirs = this.sharedKey(rel)
1286
1315
  const theirsBy = this.lastEditorOf(rel)
1287
- // Claimed by someone else meanwhile: a record, even if they haven't changed it yet (ingest would reject it).
1288
- const claim = this.claimFor(rel)
1289
- const claimedByOther = claim && !this.ownClaim(claim)
1290
1316
  const pulled = via === 'pull'
1291
- if (theirs === base && !claimedByOther) { release(); return this.ingest(rel, { pulled }) ? 'pushed' : null } // nobody else touched it
1317
+ if (theirs === base) { release(); return this.ingest(rel, { pulled }) ? 'pushed' : null } // nobody else touched it
1292
1318
  if (ours === theirs || (ours === null && theirs === undefined)) {
1293
1319
  release()
1294
1320
  if (ours === null) this.lastKnown.delete(rel); else this.lastKnown.set(rel, ours)
@@ -1303,7 +1329,6 @@ export class Session extends EventEmitter {
1303
1329
  return null
1304
1330
  }
1305
1331
  const binary = [base, ours, theirs].some((k) => typeof k === 'string' && k.startsWith('bin:'))
1306
- if (claimedByOther) return this.openConflict({ rel, base, ours, theirs, theirsBy, disk, kind: 'claimed', claimedBy: claim.by, binary, via })
1307
1332
  if (binary || ours === null || theirs === undefined) return this.autoSettle({ rel, base, ours, theirs, theirsBy, disk, binary, via })
1308
1333
  const { text, conflicts } = merge3(base || '', ours, theirs)
1309
1334
  // Ours already has the session's change in it (git combined them here: a stash popped over a pull):
@@ -1349,21 +1374,18 @@ export class Session extends EventEmitter {
1349
1374
 
1350
1375
  /**
1351
1376
  * Both the folder (ours) and the session (theirs) changed rel since base: Quilt combines them
1352
- * itself, and nobody is asked (docs/superpowers/specs/2026-10-18-automatic-merges.md). Lines only
1353
- * one side changed are kept; lines both changed go to the newer edit; a binary file is the newer
1354
- * version; an edit beats a deletion. What lost is kept (the record, .quilt/merges/<id>/, the
1355
- * file's history) and whoever wrote it is told. Returns 'merged'.
1377
+ * itself (Seam's 07 "Conflicts in the live state", ruling 2026-11-13). Lines only one side changed
1378
+ * are kept; where both changed the same lines nobody wins: the session's version, which landed
1379
+ * first, stays, and ours there is held for this writer (or any AI) to resolve (held.js); a binary
1380
+ * both changed keeps the session's, with ours held; an edit beats a deletion. Ours is kept too
1381
+ * (the record, .quilt/merges/<id>/). Returns 'merged'.
1356
1382
  */
1357
1383
  autoSettle ({ rel, base, ours, theirs, theirsBy, disk, binary, via = null }) {
1358
1384
  const release = () => this.merging.delete(rel)
1359
1385
  const pulled = via === 'pull'
1360
1386
  const by = theirsBy ? cleanName(theirsBy) : null
1361
- // When ours was written: a pull's file is as new as the commit that last changed it (not the
1362
- // moment git wrote it), anything else as its last save.
1363
- const oursAt = (pulled && this.committedAt(rel)) || (disk && Number.isFinite(disk.mtime) ? disk.mtime : Date.now())
1364
- const oursNewer = oursAt >= this.sessionEditedAt(rel)
1365
1387
  const text = (k) => (typeof k === 'string' && !k.startsWith('bin:') ? k : null)
1366
- const keep = ({ how, reason, lost = [] }) => {
1388
+ const keep = ({ how, reason }) => {
1367
1389
  try {
1368
1390
  const rec = openMerge(this.bdoc, this.merges, {
1369
1391
  path: rel, by: this.name, byId: this.myKey(), others: by ? [by] : [], kind: 'conflict',
@@ -1374,8 +1396,8 @@ export class Session extends EventEmitter {
1374
1396
  this.writeMergeFiles(rec.id, { base, ours, theirs, disk })
1375
1397
  updateMerge(this.bdoc, this.merges, rec.id, { state: 'done', how, resolvedBy: 'Quilt', reason: rec.reason }, LOCAL)
1376
1398
  } catch {}
1377
- this.noteLostLines(rel, { by, lost, oursWon: how === 'mine' })
1378
1399
  }
1400
+ const where = { branch: this.branchKey() }
1379
1401
  // An edit beats a deletion: nothing anyone wrote is thrown away.
1380
1402
  if (ours === null) {
1381
1403
  release()
@@ -1392,41 +1414,38 @@ export class Session extends EventEmitter {
1392
1414
  this.log(`🧵 ${rel}: ${by || 'the session'} deleted it, but you changed it, so it stays`)
1393
1415
  return 'merged'
1394
1416
  }
1417
+ // Ours stays on this folder's disk under .quilt (keepHeldLocal), for resolving it "mine".
1418
+ const holdWhole = (kind) => {
1419
+ try {
1420
+ const rec = this.liveRules().hold({ path: rel, kind, by: this.name, byId: this.myKey(), others: by ? [by] : [], where, hunks: kind === 'binary' ? [] : [{ at: 0, base: [], ours: ours.split('\n'), theirs: theirs.split('\n') }], reason: `${by || 'the session'} changed it first, and the two versions have nothing in common to merge`, result: kind === 'binary' ? null : theirs, mine: kind === 'binary' ? null : ours })
1421
+ if (kind === 'binary' && disk && disk.buf) { fs.mkdirSync(this.heldDir(rec.id), { recursive: true }); fs.writeFileSync(path.join(this.heldDir(rec.id), 'mine'), disk.buf) }
1422
+ this.notice(`Quilt held back your version of ${rel}: ${by || 'someone'} changed it first, so the session keeps theirs and your folder has it now. Resolve it with quilt_resolve_merge { path: "${rel}", how: "theirs" | "mine" | "edited" } (id ${rec.id}).`)
1423
+ } catch (err) { this.log(`could not hold your version of ${rel}: ${err.message}`) }
1424
+ // ours is set aside (the record, .quilt/merges/<id>/): the session's version comes back to disk.
1425
+ this.lastKnown.set(rel, ours)
1426
+ this.tryWrite(rel)
1427
+ }
1395
1428
  if (binary) {
1396
1429
  release()
1397
- if (oursNewer) this.ingest(rel, { pulled }); else { this.lastKnown.set(rel, ours); this.tryWrite(rel) }
1398
- keep({ how: oursNewer ? 'mine' : 'theirs', reason: `Both changed it: the newer version (${oursNewer ? 'yours' : `${by || 'the session'}'s`}) stays`, lost: [{ side: oursNewer ? 'theirs' : 'ours', lines: [], kept: [], at: 0 }] })
1399
- this.log(`🧵 ${rel}: both changed it; the newer version (${oursNewer ? 'yours' : `${by || 'the session'}'s`}) stays`)
1430
+ keep({ how: 'theirs', reason: `Both changed it: ${by || 'the session'}'s version, which landed first, stays; yours is held` })
1431
+ holdWhole('binary')
1432
+ this.log(`⚖️ ${rel}: both changed it; ${by || 'the session'}'s version stays and yours is held (quilt_resolve_merge)`)
1433
+ return 'merged'
1434
+ }
1435
+ // No common version (git couldn't read it, or both made the file): nothing lines up to combine.
1436
+ if (typeof base !== 'string') {
1437
+ release()
1438
+ keep({ how: 'theirs', reason: `Both made it: ${by || 'the session'}'s version stays; yours is held` })
1439
+ holdWhole('lines')
1400
1440
  return 'merged'
1401
1441
  }
1402
- // No common version (git couldn't read it, or both made the file): nothing lines up to combine,
1403
- // so the newer version is the file, as for a binary.
1404
- const r = typeof base === 'string' ? mergeAuto(base, ours, theirs, { oursNewer })
1405
- : { text: oursNewer ? ours : theirs, lost: [{ side: oursNewer ? 'theirs' : 'ours', lines: (oursNewer ? theirs : ours).split('\n').filter(Boolean), kept: [], at: 0 }] }
1406
- this.applyMerged(rel, r.text, `with ${by || 'the session'}'s changes${r.lost.length ? ' (the newer edit kept where both changed the same lines)' : ''}`, { pulled })
1442
+ const r = this.liveRules().write({ doc: this.bdoc, where, path: rel, base, ours, theirs, by: this.name, byId: this.myKey(), others: by ? [by] : [] })
1443
+ this.applyMerged(rel, r.text, `with ${by || 'the session'}'s changes${r.held.length ? ' (where both changed the same lines, theirs stays and yours is held)' : ''}`, { pulled })
1407
1444
  release()
1408
- if (r.lost.length) keep({ how: oursNewer ? 'mine' : 'theirs', reason: `Merged by Quilt: where both changed the same lines, the newer edit (${oursNewer ? 'yours' : `${by || 'the session'}'s`}) stays`, lost: r.lost })
1445
+ if (r.held.length) keep({ how: 'theirs', reason: `Merged by Quilt: where both changed the same lines, ${by || 'the session'}'s version, which landed first, stays; yours is held to resolve` })
1409
1446
  return 'merged'
1410
1447
  }
1411
1448
 
1412
- /**
1413
- * Tells whoever's lines lost an automatic merge (autoSettle): this person in the log and the
1414
- * catch-up, someone else in a direct message. A notice, never a task.
1415
- */
1416
- noteLostLines (rel, { by, lost, oursWon }) {
1417
- if (!lost.length) return
1418
- const shown = lost.flatMap((l) => l.lines).slice(0, 12)
1419
- const lines = shown.length ? `\n${shown.map((l) => `- ${l}`).join('\n')}` : ''
1420
- if (!oursWon) {
1421
- this.log(`🧵 ${rel}: Quilt merged your changes with ${by || 'the session'}'s; where you both changed the same lines, their newer edit stays. Your lines are in the file's history and in .quilt/merges/.${lines}`)
1422
- return
1423
- }
1424
- if (!by || by === this.name) return
1425
- try {
1426
- this.say(`Quilt merged ${rel}: where we both changed the same lines, my newer edit stays. Your lines it replaced are in the file's history (Changes):${lines}`, { to: by })
1427
- } catch {}
1428
- }
1429
-
1430
1449
  /** Writes a merged text to the shared doc and the disk as one edit of ours (`pulled`: one a git pull brought). */
1431
1450
  applyMerged (rel, text, detail, { pulled = false } = {}) {
1432
1451
  const abs = resolveInside(this.root, rel)
@@ -1446,48 +1465,6 @@ export class Session extends EventEmitter {
1446
1465
  this.log(`🧵 merged ${rel} ${detail}`)
1447
1466
  }
1448
1467
 
1449
- /**
1450
- * The two sides cannot be combined on their own: the session's version
1451
- * stays on disk and in the doc, ours is kept in the record and under
1452
- * .quilt/merges/<id>/, and everyone sees the record until someone settles it.
1453
- */
1454
- openConflict ({ rel, base, ours, theirs, theirsBy, disk, kind, reason = null, claimedBy = null, binary, via = null }) {
1455
- const text = (k) => (typeof k === 'string' && !k.startsWith('bin:') ? k : null)
1456
- // theirsBy and claimedBy are peer-written (an activity entry, a claim):
1457
- // flatten them so a stray control character can't make openMerge throw
1458
- // and leave this conflict silently unrecorded.
1459
- const by = theirsBy ? cleanName(theirsBy) : null
1460
- const claimant = claimedBy ? cleanName(claimedBy) : null
1461
- const rec = openMerge(this.bdoc, this.merges, {
1462
- path: rel,
1463
- by: this.name,
1464
- byId: this.myKey(),
1465
- others: by ? [by] : [],
1466
- kind,
1467
- ours: binary ? null : text(ours),
1468
- oursDeleted: ours === null,
1469
- via,
1470
- base: binary ? null : text(base),
1471
- theirsHash: theirs === undefined ? null : sha1(theirs),
1472
- binary,
1473
- claimedBy: claimant,
1474
- // One line of at most 500 characters, or the record would be invalid.
1475
- // eslint-disable-next-line no-control-regex
1476
- reason: reason ? String(reason).replace(/[\u0000-\u001f\u007f]+/g, ' ').trim().slice(0, 500) || null : null
1477
- }, LOCAL)
1478
- this.writeMergeFiles(rec.id, { base, ours, theirs, disk })
1479
- // The session's version goes back on disk (or the file goes, if the session
1480
- // deleted it). lastKnown is set to ours first so writeOut doesn't also copy
1481
- // it to .quilt/conflicts: the merge folder already has it.
1482
- this.merging.delete(rel)
1483
- if (ours === null) this.lastKnown.delete(rel); else this.lastKnown.set(rel, ours)
1484
- this.tryWrite(rel)
1485
- // Only a file someone holds comes here now (autoSettle combines the rest): it waits for them.
1486
- this.log(`⏳ ${rel}: ${claimant || by || 'someone'} has it claimed. Your changes are kept and go in, merged by Quilt, once they let go of it.`)
1487
- this.emit('file-changed', { path: rel, by: by || 'partner' })
1488
- return 'conflict'
1489
- }
1490
-
1491
1468
  /** Keeps the three versions of a merge on this machine, for Send to… and for files too big for the record. */
1492
1469
  writeMergeFiles (id, { base, ours, theirs, disk = null }) {
1493
1470
  if (!id) return
@@ -1605,7 +1582,7 @@ export class Session extends EventEmitter {
1605
1582
  * reason not to use it. `outside`: a parent is a link leading out of the
1606
1583
  * project, so the file is never read (it may be anyone's).
1607
1584
  */
1608
- readDisk (rel) {
1585
+ readDisk (rel, { settle = false } = {}) {
1609
1586
  let abs
1610
1587
  try { abs = resolveInside(this.root, rel) } catch { return { skip: true, outside: true } }
1611
1588
  let st
@@ -1613,7 +1590,22 @@ export class Session extends EventEmitter {
1613
1590
  if (!st.isFile()) return { skip: true }
1614
1591
  if (st.size > MAX_STORED_BINARY_BYTES) return { tooLarge: true }
1615
1592
  const exec = process.platform !== 'win32' && !!(st.mode & 0o111)
1593
+ // The text Quilt wrote there, untouched since (same file, size and time): not read again. Quilt never
1594
+ // reads its own write, so a read of it is someone else's (base-pick.js: did a save's writer see it?).
1595
+ const w = this.wroteHere.get(rel)
1596
+ if (w && w.ino === st.ino && w.size === st.size && w.mtimeMs === st.mtimeMs) return { text: w.text, key: w.text, exec, mtime: st.mtimeMs }
1597
+ // About to read a file a partner's change was written into: who read it since is asked first.
1598
+ if (this.overwritten.has(rel)) this.overwritten.look(rel, st, { atime: this.atimeOn() })
1616
1599
  const buf = fs.readFileSync(abs)
1600
+ // `settle` (taking it in, or writing over it): being written as it was read (it changed during the read, or
1601
+ // reads empty just after being emptied, as a save that truncates first does) is `unsettled`, looked at again
1602
+ // shortly, never taken in half-written.
1603
+ let again = null
1604
+ if (settle) { try { again = fs.lstatSync(abs) } catch {} }
1605
+ const known = this.lastKnown.get(rel)
1606
+ const unsettled = settle && (!again || again.size !== st.size || again.mtimeMs !== st.mtimeMs || buf.length !== st.size ||
1607
+ (buf.length === 0 && typeof known === 'string' && known.length > 0 && Date.now() - st.mtimeMs < SETTLE_MS))
1608
+ if (unsettled) return { unsettled: true, mtime: st.mtimeMs }
1617
1609
  if (looksBinary(buf)) {
1618
1610
  if (buf.length > MAX_BINARY_BYTES && this.largeFilesOff) return { tooLarge: true }
1619
1611
  const hash = sha1(buf)
@@ -1708,7 +1700,6 @@ export class Session extends EventEmitter {
1708
1700
  if (q.read_token) lines.push(readTokenLine(q.read_token))
1709
1701
  if (q.large) lines.push(largeLine(q.large))
1710
1702
  if (q.rebased) lines.push(`Someone's unfinished work boxed on an older main went onto main's newer copy as their change only, not their whole file: ${q.rebased.slice(0, 8).map((x) => `${x.path} (${x.branch})`).join(', ')}.`)
1711
- if (q.claims && q.claims.left && q.claims.left.length) lines.push(`Claims not moved: ${q.claims.left.map((c) => `${c.pattern} (${c.why})`).join(', ')}.`)
1712
1703
  if (q.layout === 3) lines.push('Its files are in its squares now; apps without Seam are asked to update. quilt session migrate --back goes back to git.')
1713
1704
  lines.push(...notSharedLines(q.not_shared))
1714
1705
  const moved = Object.keys(q.tasks || {}).length
@@ -1855,7 +1846,7 @@ export class Session extends EventEmitter {
1855
1846
  else {
1856
1847
  for (const rel of new Set([...walk(this.root, this.ig), ...this.lastKnown.keys()])) {
1857
1848
  if (!this.syncable(rel) || this.untouchedHere(rel)) continue
1858
- try { this.ingest(rel, { same: true, claim: !!(writers && writers.get(rel) === this.name) }) } catch (err) { this.log(`could not sync ${rel}: ${err.message}`) }
1849
+ try { this.ingest(rel, { same: true, box: !!(writers && writers.get(rel) === this.name) }) } catch (err) { this.log(`could not sync ${rel}: ${err.message}`) }
1859
1850
  }
1860
1851
  }
1861
1852
  this.scanDisk({ baseline: true })
@@ -1946,10 +1937,8 @@ export class Session extends EventEmitter {
1946
1937
  const texts = typeof e.before === 'string' || typeof e.after === 'string' ? { before: e.before, after: e.after } : undefined
1947
1938
  try { this.recordActivity(e.path, e.kind, e.detail || '', texts, { activity: false }) } catch (err) { this.emit('debug', `could not record ${e.path}: ${err.message}`) }
1948
1939
  this.noteMyEdit(e.path)
1949
- // Claims follow edits here too (as ingest makes them on a branch): the room's claims on this
1950
- // branch, which the Loom stitches, quilt_before_edit answers and the file queue hang on.
1951
- const claim = this.claimFor(e.path)
1952
- if (e.kind !== 'deleted' && (!claim || this.autoClaims.has(e.path)) && this.aiMayBeEditing()) this.autoClaim(e.path)
1940
+ // Our AI's edits here count for its working state, as on a branch; a square is this member's own, so nothing is boxed.
1941
+ if (e.kind !== 'deleted' && this.aiMayBeEditing()) this.aiEdits.set(e.path, Date.now())
1953
1942
  }
1954
1943
  // The room's activity names a file the relay finds in the square (server.js onBranch): sent once the relay holds the edit, over the block's connection.
1955
1944
  const push = () => { if (this.stopped) return; for (const e of list) { try { this.pushActivity(e.path, e.kind, e.detail || '') } catch {} } }
@@ -2009,7 +1998,9 @@ export class Session extends EventEmitter {
2009
1998
  const r = await this.squareFollower.commit({ message })
2010
1999
  if (r && r.nothing) return { nothing: true, text: 'Nothing to commit: the square has no work since its last commit.' }
2011
2000
  const head = r && r.square && r.square.head
2012
- return { ...r, text: `Committed to square ${squareShort(this.squareFollower.here.square)}${head ? ` as ${String(head).slice(0, 12)}` : ''}.` }
2001
+ // Paths with an open held conflict stayed live (live-block.js commit): said, with how to resolve them.
2002
+ const left = r && r.left_held && r.left_held.length ? ` ${heldLandingNote(r.left_held)}` : ''
2003
+ return { ...r, text: `Committed to square ${squareShort(this.squareFollower.here.square)}${head ? ` as ${String(head).slice(0, 12)}` : ''}.${left}` }
2013
2004
  }
2014
2005
 
2015
2006
  /**
@@ -2196,10 +2187,10 @@ export class Session extends EventEmitter {
2196
2187
 
2197
2188
  /**
2198
2189
  * Pushes the on-disk state of a path into the shared doc. Returns true if anything changed.
2199
- * `pulled`: git brought this version (a pull), so it is not an edit of ours: never claimed, and counted as the pull's.
2190
+ * `pulled`: git brought this version (a pull), so it is not an edit of ours: never boxed, and counted as the pull's.
2191
+ * `box`: false keeps this edit from boxing the file for us (leaveSquare: another member's work).
2200
2192
  */
2201
- /** `claim`: false keeps this edit from claiming (boxing) the file for us (leaveSquare: another member's work). */
2202
- ingest (rel, { pulled = false, same = false, claim: mayClaim = true } = {}) {
2193
+ ingest (rel, { pulled = false, same = false, box: mayBox = true } = {}) {
2203
2194
  if (!this.syncable(rel) || this.inSquare || this.syncStopped) return false
2204
2195
  if (this.merging.has(rel)) return false // its offline merge hasn't run yet; see mergeOffline
2205
2196
  // A plain `rm` of a file a fetched pull would bring (git said to remove it): making way, not a deletion.
@@ -2207,7 +2198,8 @@ export class Session extends EventEmitter {
2207
2198
  if (this.writeFailed.has(rel)) return false // the shared version never reached the disk: what's there is no edit of ours
2208
2199
  // New ignore rules: a box of ours on a file they now leave out lets go (settleBoxesOnce).
2209
2200
  if (IGNORE_FILES.includes(path.posix.basename(rel)) || rel === '.gitmodules') { this.ig = loadIgnore(this.root) }
2210
- const disk = this.readDisk(rel)
2201
+ const disk = this.readDisk(rel, { settle: true })
2202
+ if (disk && disk.unsettled) { this.settleSoon(rel); return false }
2211
2203
  const boxed = this.boxedByOther(rel)
2212
2204
  if (boxed) {
2213
2205
  // Someone else's box: what this folder has is its version from before the box, never theirs.
@@ -2220,8 +2212,7 @@ export class Session extends EventEmitter {
2220
2212
  this.scheduleStateSave()
2221
2213
  return false
2222
2214
  }
2223
- this.rejectBoxed(rel, disk, boxed)
2224
- return false
2215
+ return this.editBoxed(rel, disk, boxed)
2225
2216
  }
2226
2217
  const gitWas = this.gitOnly.get(rel) // git's version of a file the document hasn't, as this folder last had it
2227
2218
  if (this.gitOnly.size && this.gitOnly.has(rel)) {
@@ -2255,23 +2246,18 @@ export class Session extends EventEmitter {
2255
2246
  // A diff branch: deleting a file git had changes the session though neither side has an entry for it.
2256
2247
  const gitDeletion = !disk && this.followsGit(rel) && (gitWas !== undefined || this.lastKnown.has(rel))
2257
2248
  const changesIt = (disk ? disk.key : undefined) !== this.sharedKey(rel) || gitDeletion
2258
- const claim = this.claimFor(rel)
2259
- if (claim && !this.ownClaim(claim) && changesIt) {
2260
- this.rejectClaimed(rel, disk, claim)
2261
- return false
2262
- }
2263
2249
  const refusal = this.writeRefusal(rel)
2264
2250
  if (refusal && changesIt) {
2265
2251
  this.rejectLocal(rel, disk, refusal)
2266
2252
  return false
2267
2253
  }
2268
- // A change of ours to a file nobody holds claims it for us while our AI works on it. A person
2269
- // typing by hand while their AI sits idle keeps editing live with everyone, as before.
2270
- // Quilt's own line in .gitignore (ignoreQuiltState) is nobody's edit: never claimed for anyone.
2254
+ // A change of ours while our AI works goes into a box of ours (unfinished work, out of other folders
2255
+ // until it's committed). A person typing by hand while their AI sits idle edits live with everyone.
2256
+ // Quilt's own line in .gitignore (ignoreQuiltState) is nobody's edit: never boxed for anyone.
2271
2257
  const quiltOwn = this.quiltOwnWrite === rel && disk && disk.key === this.quiltOwnKey
2272
2258
  if (quiltOwn) { this.quiltOwnWrite = null; this.quiltOwnKey = null }
2273
2259
  // With boxes, a deletion is boxed too: it reaches nobody else's folder until it's committed.
2274
- if (mayClaim && (disk || this.boxesOn()) && !pulled && !quiltOwn && this.ready && !this.seeding && changesIt && (!claim || this.autoClaims.has(rel) || this.unboxedOwn(rel, claim)) && this.aiMayBeEditing()) this.autoClaim(rel)
2260
+ if (mayBox && (disk || this.boxesOn()) && !pulled && !quiltOwn && this.ready && !this.seeding && changesIt && this.aiMayBeEditing()) this.boxEdit(rel)
2275
2261
 
2276
2262
  if (!disk) {
2277
2263
  if (!this.files.has(rel) && !this.blobs.has(rel)) {
@@ -2294,9 +2280,11 @@ export class Session extends EventEmitter {
2294
2280
  this.lastKnown.delete(rel)
2295
2281
  return false
2296
2282
  }
2283
+ let gone
2297
2284
  this.transact(() => {
2298
2285
  const was = this.files.get(rel)
2299
2286
  const before = was ? was.toString() : undefined
2287
+ gone = before
2300
2288
  this.files.delete(rel)
2301
2289
  this.blobs.delete(rel)
2302
2290
  if (this.modes.has(rel)) this.modes.delete(rel)
@@ -2306,6 +2294,8 @@ export class Session extends EventEmitter {
2306
2294
  if (base && !this.fileBases.has(rel)) this.fileBases.set(rel, base)
2307
2295
  }
2308
2296
  this.recordActivity(rel, 'deleted', '', { before, after: before === undefined ? undefined : '' }, { pulled })
2297
+ // With the same text added elsewhere by this folder, a move (edits others make to rel follow it).
2298
+ if (!pulled && this.ready && typeof gone === 'string') this.liveRules().noteGone({ doc: this.bdoc, path: rel, text: gone, by: this.name })
2309
2299
  }, LOCAL)
2310
2300
  this.lastKnown.delete(rel)
2311
2301
  this.setOnDisk(rel, null)
@@ -2325,9 +2315,50 @@ export class Session extends EventEmitter {
2325
2315
  // Storage refused it, but it's small enough to share inside the document.
2326
2316
  }
2327
2317
 
2328
- let detail = ''
2318
+ // A file another member moved away (deleted here, the same text added elsewhere): this edit goes to where it went.
2319
+ if (!disk.binary && !pulled && !this.files.has(rel) && !this.blobs.has(rel) && this.ready && this.bdoc) {
2320
+ const mv = this.liveRules().movedTo({ doc: this.bdoc, path: rel, by: this.name })
2321
+ if (mv && this.files.has(mv.to) && this.syncable(mv.to)) return this.followMove(rel, disk, mv)
2322
+ }
2323
+ // A live write is merged against what this folder last had (lastKnown): what landed in the shared file
2324
+ // meanwhile stays, and the ways a clash is caught run on it (live-merge.js). Lines both changed keep
2325
+ // the shared version; this folder gets the result back, and its own lines are held (held.js).
2326
+ let text = disk.binary ? null : disk.text
2327
+ let rewrite = false
2329
2328
  // A diff branch: the edit of a file only git had starts from git's text, so its history says what changed.
2330
2329
  const fromGit = this.diffForm && !this.files.has(rel) && !this.blobs.has(rel) && !this.gone.has(rel) && typeof gitWas === 'string' && !gitWas.startsWith('bin:') ? gitWas : null
2330
+ if (!disk.binary && !same && this.ready && !this.seeding) {
2331
+ const known = this.lastKnown.get(rel)
2332
+ const t = this.files.get(rel)
2333
+ const knownText = typeof known === 'string' && !/^bin:[0-9a-f]{40}$/.test(known)
2334
+ // The relay takes it as a write (relay-live-write.js): merged there, one write at a time per file, and
2335
+ // applied in whole lines, never as an edit of the text here that a CRDT would mix with someone else's.
2336
+ // So does a git pull's edit, and a file new to the branch (against git's text, for a diff branch's
2337
+ // first edit of a file git has): made by two folders at once, both are kept, never one over the other.
2338
+ if (this.relayWriting.has(rel)) { this.relayAgain.add(rel); return true } // its write's answer first, then this save, on it
2339
+ if (t && knownText && this.relayWritesOn() && !this.relayLocal.delete(rel)) return this.relayIngest(rel, disk, known, { pulled })
2340
+ // A file this folder never had the session's text of (made here while a partner made it too): both kept, never one over the other.
2341
+ if (t && known === undefined && this.relayWritesOn() && !this.relayLocal.delete(rel)) return this.relayIngest(rel, disk, null, { pulled })
2342
+ if (!t && !this.blobs.has(rel) && this.relayWritesOn() && !this.relayLocal.delete(rel)) return this.relayIngest(rel, disk, fromGit, { pulled, fromGit: fromGit !== null })
2343
+ }
2344
+ if (!disk.binary && !pulled && !same && this.ready && !this.seeding) {
2345
+ const known = this.lastKnown.get(rel)
2346
+ const t = this.files.get(rel)
2347
+ if (t && typeof known === 'string' && !/^bin:[0-9a-f]{40}$/.test(known)) {
2348
+ const r = this.liveRules().write({ doc: this.bdoc, where: { branch: this.branchKey() }, path: rel, base: known, ours: disk.text, theirs: t.toString(), by: this.name, byId: this.myKey(), others: [this.lastEditorOf(rel)].filter(Boolean) })
2349
+ if (r.text !== disk.text) { text = r.text; rewrite = true }
2350
+ // Every change of this write was held: the shared file stays as it is, and this folder gets it back.
2351
+ if (rewrite && text === t.toString()) {
2352
+ try { this.writeFile(rel, resolveInside(this.root, rel), text) } catch (err) { this.log(`could not write ${rel}: ${err.message}`) }
2353
+ this.lastKnown.set(rel, text)
2354
+ return false
2355
+ }
2356
+ } else if (!t && !this.blobs.has(rel)) {
2357
+ // A new file: nothing to merge, but its lines are on record as this member's (the next writer's stale check).
2358
+ this.liveRules().write({ doc: this.bdoc, where: { branch: this.branchKey() }, path: rel, ours: disk.text, by: this.name })
2359
+ }
2360
+ }
2361
+ let detail = ''
2331
2362
  this.transact(() => {
2332
2363
  const existed = this.files.has(rel) || this.blobs.has(rel) || fromGit !== null
2333
2364
  let texts
@@ -2345,30 +2376,191 @@ export class Session extends EventEmitter {
2345
2376
  if (fromGit) ytext.insert(0, fromGit)
2346
2377
  this.files.set(rel, ytext)
2347
2378
  }
2348
- return applyTextDiff(ytext, disk.text)
2379
+ return applyTextDiff(ytext, text)
2349
2380
  }
2350
- texts = { before, after: disk.text }
2381
+ texts = { before, after: text }
2351
2382
  // Folders on one branch pull the same commits, often at the same moment: made under an id
2352
2383
  // taken from the change, the pull's edit is the same edit from each of them, and lands once.
2353
2384
  // So is the square's work every folder brings back when a session leaves layout 3 (leaveSquare).
2354
- detail = pulled || same ? asClient(this.bdoc, sameEditClient(pulled ? 'pull' : 'square', rel, this.files.has(rel) ? before : null, disk.text), put) : put()
2385
+ detail = pulled || same ? asClient(this.bdoc, sameEditClient(pulled ? 'pull' : 'square', rel, this.files.has(rel) ? before : null, text), put) : put()
2355
2386
  }
2356
2387
  if (disk.exec) { if (this.modes.get(rel) !== 'x') this.modes.set(rel, 'x') } else if (this.modes.has(rel)) this.modes.delete(rel)
2357
2388
  this.notePresentHere(rel, this.entryBase())
2358
2389
  this.recordActivity(rel, existed ? 'edited' : 'created', detail, texts, { pulled })
2390
+ if (!existed && !disk.binary && !pulled && this.ready) this.liveRules().noteNew({ doc: this.bdoc, path: rel, text, by: this.name })
2359
2391
  }, LOCAL)
2360
- this.lastKnown.set(rel, disk.key)
2392
+ if (rewrite) {
2393
+ // This folder gets what the shared file got: the lines that landed first, with its own other changes.
2394
+ try { this.writeFile(rel, resolveInside(this.root, rel), text) } catch (err) { this.log(`could not write ${rel}: ${err.message}`) }
2395
+ this.lastKnown.set(rel, text)
2396
+ } else this.lastKnown.set(rel, disk.key)
2361
2397
  this.setOnDisk(rel, null)
2362
2398
  this.noteMyEdit(rel, { pulled })
2363
- if (!pulled) this.noteQueuedEdit(rel)
2364
2399
  return true
2365
2400
  }
2366
2401
 
2367
- /** Someone else claimed rel: keep our version aside, put the shared one back on disk, and tell our AI. */
2368
- rejectClaimed (rel, disk, claim) {
2369
- const why = `it is claimed by ${claim.by}${claim.note ? ` (${claim.note})` : ''}`
2370
- this.rejectLocal(rel, disk, why, claim.by)
2371
- this.notice(`Your change to ${rel} was undone: ${why}. ${askForIt(rel, claim)}`)
2402
+ /** Whether this folder's text edits go to the relay as writes (it takes them, and this folder is connected on a branch). */
2403
+ relayWritesOn () {
2404
+ return !!(this.conn && this.conn.relayWrites && this.conn.connected && this.conn.branchKey !== null && !this.noRelayWrites && !this.inSquare)
2405
+ }
2406
+
2407
+ /**
2408
+ * An edit of a text the session has, sent to the relay as a live write against `base` (what this
2409
+ * folder last synced of it; null for a file new to the branch, or git's text with `fromGit`: a diff
2410
+ * branch's first edit of a file only git had). Until the relay answers, the path waits: a remote change
2411
+ * is not written over the edit (writeOut sees disk differ), and a further save is taken in after the
2412
+ * answer, on it. `pulled`: a git pull brought it (counted as the pull's). True (the session's version
2413
+ * changes, or the edit is held).
2414
+ */
2415
+ relayIngest (rel, disk, base, { pulled = false, fromGit = false } = {}) {
2416
+ if (this.relayWriting.has(rel)) { this.relayAgain.add(rel); return true }
2417
+ this.relayWriting.add(rel)
2418
+ const text = disk.text
2419
+ const created = base === null && !this.files.has(rel) && !this.blobs.has(rel)
2420
+ // Made from the text a partner's change was just written over, by a writer who never read the newer one
2421
+ // (base-pick.js)? It goes too (`older`): the relay puts the save onto the base, and where the partner
2422
+ // changed it since, the newer lines stay. Where this folder can tell who read its files, it vouches for
2423
+ // the base (`seen`): nothing is held for merely looking like an older read.
2424
+ const older = typeof base === 'string' ? this.overwritten.pick(rel, base, text) : base
2425
+ const seen = typeof base === 'string' && !fromGit && this.overwritten.sure(rel, base, this.atimeOn())
2426
+ const trusted = !!(this.liveEngine && this.liveEngine.trusted.get(rel) === text)
2427
+ const key = this.conn.branchKey
2428
+ const req = {
2429
+ path: rel,
2430
+ base: typeof base === 'string' ? versionOf(base) : null,
2431
+ ...(typeof base === 'string' && base.length <= 256 * 1024 ? { baseText: base } : {}),
2432
+ text,
2433
+ ...(older !== base && typeof older === 'string' ? { older } : {}),
2434
+ ...(fromGit ? { fromGit: true } : {}),
2435
+ ...(seen ? { seen: true } : {}),
2436
+ ...(trusted ? { trusted: true } : {})
2437
+ }
2438
+ // What does not touch the text stays an edit here: its mode, and where a diff branch's entry started.
2439
+ this.transact(() => {
2440
+ if (disk.exec) { if (this.modes.get(rel) !== 'x') this.modes.set(rel, 'x') } else if (this.modes.has(rel)) this.modes.delete(rel)
2441
+ this.notePresentHere(rel, this.entryBase())
2442
+ }, LOCAL)
2443
+ // A new file of this folder's: with a deletion of the same text here, a move (edits others make to the old path follow it).
2444
+ if (created && !pulled) { try { this.liveRules().noteNew({ doc: this.bdoc, path: rel, text, by: this.name }) } catch {} }
2445
+ this.noteMyEdit(rel, { pulled })
2446
+ this.conn.liveWrite(req, { baseOf: () => base }).then(
2447
+ (r) => this.relayWrote(rel, disk, r, key, trusted, { pulled, created }),
2448
+ (err) => this.relayFailed(rel, err)
2449
+ )
2450
+ return true
2451
+ }
2452
+
2453
+ /** The relay's answer to a live write of rel: the activity record, the result on disk (unless saved again since), what the writer must hear. */
2454
+ relayWrote (rel, disk, r, key, trusted, { pulled = false, created = false } = {}) {
2455
+ this.relayWriting.delete(rel)
2456
+ if (this.stopped) return
2457
+ 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 }
2458
+ if (trusted && this.liveEngine) this.liveEngine.trusted.delete(rel)
2459
+ if (this.conn.branchKey !== key) { this.relayAgain.delete(rel); this.queue(rel); return } // the folder moved to another branch meanwhile
2460
+ const result = r.same ? disk.text : r.text
2461
+ this.overwritten.forget(rel)
2462
+ if (r.detail) this.transact(() => this.recordActivity(rel, created && !r.before ? 'created' : 'edited', r.detail, { before: r.before ?? '', after: result }, { pulled }), LOCAL)
2463
+ let now = null
2464
+ try { now = this.readDisk(rel) } catch {}
2465
+ if (now && !now.binary && now.text === disk.text) {
2466
+ // Disk still has what was sent: it gets the result (the lines that landed first, with this edit's others).
2467
+ let over = true
2468
+ if (result !== disk.text) {
2469
+ const kept = {}
2470
+ try {
2471
+ const abs = resolveInside(this.root, rel)
2472
+ over = this.writeOver(rel, abs, result, now, kept)
2473
+ if (over === null) { this.writeFile(rel, abs, result); over = true }
2474
+ } catch (err) { this.log(`could not write ${rel}: ${err.message}`) }
2475
+ // What landed first was written over this save: a next save made without reading it is told apart (base-pick.js).
2476
+ if (over === true) this.overwritten.note(rel, disk.text, kept.wrote || null); else letGo(kept.wrote)
2477
+ }
2478
+ // Saved again in that instant: that save is taken in next, merged on what was sent.
2479
+ this.lastKnown.set(rel, over === false ? disk.text : result)
2480
+ } else this.lastKnown.set(rel, disk.text) // saved again since: that save is taken in next, merged on what was sent
2481
+ this.setOnDisk(rel, null)
2482
+ for (const n of r.notices || []) this.notice(n)
2483
+ for (const l of r.logs || []) this.log(l)
2484
+ for (const x of r.local || []) { try { this.keepHeldLocal(x.id, { result: x.result, mine: x.mine }) } catch {} }
2485
+ if (Array.isArray(r.gone) && r.gone.length) {
2486
+ let uses = []
2487
+ try { uses = findUses(r.gone, this.sessionTexts(), { skip: rel }) } catch {}
2488
+ const w = removedNameWarning(rel, uses)
2489
+ if (w) { this.notice(w); this.log(`⚠️ ${w}`) }
2490
+ }
2491
+ if (this.relayAgain.delete(rel) || (now && now.key !== this.lastKnown.get(rel))) {
2492
+ try { this.ingest(rel) } catch (err) { this.log(`could not sync ${rel}: ${err.message}`) }
2493
+ }
2494
+ }
2495
+
2496
+ /** A live write the relay never answered: an older relay (the edit goes in here, as before), or no connection (tried again). */
2497
+ relayFailed (rel, err) {
2498
+ this.relayWriting.delete(rel)
2499
+ this.relayAgain.delete(rel)
2500
+ if (this.stopped) return
2501
+ if (/unknown branch request/.test(err.message)) { this.noRelayWrites = true; try { this.ingest(rel) } catch {} return }
2502
+ if (this.relayProblem !== err.message) this.log(`${rel}: your edit waits to reach the session (${err.message}); it is tried again`)
2503
+ this.relayProblem = err.message
2504
+ const t = setTimeout(() => { if (!this.stopped) this.queue(rel) }, 1000)
2505
+ t.unref?.()
2506
+ }
2507
+
2508
+ /**
2509
+ * The live-write engine (live-merge.js) for this session: held conflicts go to the room's document,
2510
+ * the writer's AI hears through notices, and the removed-name search reads the files this folder synced.
2511
+ */
2512
+ liveRules () {
2513
+ if (!this.liveEngine) {
2514
+ this.liveEngine = new LiveRules({
2515
+ room: () => this.doc,
2516
+ staleMinutes: () => staleWriteMinutes(this.doc, this.members),
2517
+ notice: (t) => this.notice(t),
2518
+ log: (t) => this.log(t),
2519
+ texts: () => this.sessionTexts(),
2520
+ origin: LOCAL,
2521
+ keepLocal: (id, texts) => this.keepHeldLocal(id, texts)
2522
+ })
2523
+ }
2524
+ return this.liveEngine
2525
+ }
2526
+
2527
+ /** The text files this folder last synced, as [path, text] (the removed-name search). */
2528
+ * sessionTexts () {
2529
+ for (const [rel, k] of this.lastKnown) if (typeof k === 'string' && !/^bin:[0-9a-f]{40}$/.test(k)) yield [rel, k]
2530
+ }
2531
+
2532
+ /** Where this machine keeps a held conflict's texts too big for the room's document (and a binary's bytes). */
2533
+ heldDir (id) { return path.join(this.stateDir, 'held', String(id).replace(/[^0-9a-f]/g, '')) }
2534
+
2535
+ keepHeldLocal (id, { result = null, mine = null }) {
2536
+ const dir = this.heldDir(id)
2537
+ fs.mkdirSync(dir, { recursive: true })
2538
+ if (result != null) fs.writeFileSync(path.join(dir, 'result'), result)
2539
+ if (mine != null) fs.writeFileSync(path.join(dir, 'mine'), mine)
2540
+ }
2541
+
2542
+ /**
2543
+ * An edit to `rel`, which another member moved to `mv.to` (deleted it and added the same text there):
2544
+ * merged into `mv.to` as a live write, and `rel` comes off this folder again. True.
2545
+ */
2546
+ followMove (rel, disk, mv) {
2547
+ const known = this.lastKnown.get(rel)
2548
+ const base = typeof known === 'string' && !/^bin:[0-9a-f]{40}$/.test(known) ? known : mv.text
2549
+ const t = this.files.get(mv.to)
2550
+ const r = this.liveRules().write({ doc: this.bdoc, where: { branch: this.branchKey() }, path: mv.to, base, ours: disk.text, theirs: t.toString(), by: this.name, byId: this.myKey(), others: [mv.by] })
2551
+ this.transact(() => {
2552
+ const before = t.toString()
2553
+ const detail = applyTextDiff(t, r.text)
2554
+ this.recordActivity(mv.to, 'edited', detail, { before, after: r.text })
2555
+ }, LOCAL)
2556
+ try { this.writeFile(mv.to, resolveInside(this.root, mv.to), r.text) } catch {}
2557
+ this.lastKnown.set(mv.to, r.text)
2558
+ try { fs.rmSync(resolveInside(this.root, rel), { force: true }) } catch {}
2559
+ this.lastKnown.delete(rel)
2560
+ this.noteMyEdit(mv.to)
2561
+ this.notice(`${mv.by} moved ${rel} to ${mv.to}; your edit to ${rel} went into ${mv.to}. Edit ${mv.to} from now on.`)
2562
+ this.log(`🧵 ${rel} was moved to ${mv.to} by ${mv.by}: your edit went there`)
2563
+ return true
2372
2564
  }
2373
2565
 
2374
2566
  /** Queues a line for this person's AI; the local MCP server hands pending notices over with its next answer. */
@@ -2534,9 +2726,7 @@ export class Session extends EventEmitter {
2534
2726
  // ------------------------------------------------------- shared -> local --
2535
2727
 
2536
2728
  fromRemote (rel) {
2537
- const claim = this.claimFor(rel)
2538
- if (claim && this.ownClaim(claim)) this.reclaim(rel)
2539
- else this.writeOut(rel)
2729
+ this.writeOut(rel)
2540
2730
  }
2541
2731
 
2542
2732
  /**
@@ -2569,28 +2759,6 @@ export class Session extends EventEmitter {
2569
2759
  }
2570
2760
  }
2571
2761
 
2572
- /**
2573
- * A partner changed a path we claimed (their quilt should have refused, so
2574
- * it's an old or misbehaving client): keep their version aside and put ours
2575
- * back into the shared doc.
2576
- */
2577
- reclaim (rel) {
2578
- if (!this.syncable(rel)) return
2579
- const t = this.files.get(rel)
2580
- const b = this.blobs.get(rel)
2581
- if ((t || (b && !b.stored)) && this.sharedKey(rel) !== this.lastKnown.get(rel)) {
2582
- const dest = path.join(this.stateDir, 'rejected', `${Date.now()}`, ...rel.split('/'))
2583
- fs.mkdirSync(path.dirname(dest), { recursive: true })
2584
- fs.writeFileSync(dest, t ? t.toString() : Buffer.from(b.data, 'base64'))
2585
- }
2586
- // Outside the observer, so the revert goes out as its own update.
2587
- queueMicrotask(() => {
2588
- try {
2589
- if (this.ingest(rel)) this.log(`🔒 reverted a partner's change to ${rel}, which you claimed; theirs is in .quilt/rejected`)
2590
- } catch (err) { this.log(`could not revert ${rel}: ${err.message}`) }
2591
- })
2592
- }
2593
-
2594
2762
  writeOut (rel) {
2595
2763
  if (!this.syncable(rel) || this.inSquare || this.syncStopped) return
2596
2764
  if (this.ghost(rel)) return
@@ -2598,8 +2766,10 @@ export class Session extends EventEmitter {
2598
2766
  let abs
2599
2767
  try { abs = resolveInside(this.root, rel) } catch (err) { this.log(err.message); return }
2600
2768
  const shared = this.sharedKey(rel)
2601
- const disk = this.readDisk(rel)
2769
+ const disk = this.readDisk(rel, { settle: true })
2602
2770
  if (disk && (disk.skip || disk.tooLarge)) return
2771
+ // A save being written right now: never written over; it is taken in once it is whole (and merged).
2772
+ if (disk && disk.unsettled) { this.settleSoon(rel); return }
2603
2773
  const known = this.lastKnown.get(rel)
2604
2774
  if (shared === undefined && this.followsGit(rel)) {
2605
2775
  // A diff branch leaves this file to git (branch-view.js): the folder's own checkout's stays, never
@@ -2609,8 +2779,15 @@ export class Session extends EventEmitter {
2609
2779
  }
2610
2780
 
2611
2781
  if (this.ready && disk && disk.key !== known && disk.key !== shared) {
2612
- // The file changed locally in the instant before this remote change
2613
- // arrived. Keep a copy so nothing is lost.
2782
+ // The file changed here in the instant before this remote change arrived: a text both sides
2783
+ // have is merged as a live write (ingest, against what this folder last had), never overwritten.
2784
+ const t = this.files.get(rel)
2785
+ // So is a save at the relay right now (a file new to the branch too): its answer comes first, then this.
2786
+ if ((this.relayWriting.has(rel) || (!disk.binary && t && typeof known === 'string' && !/^bin:[0-9a-f]{40}$/.test(known))) && !this.writeFailed.has(rel) && !this.downloading.has(rel)) {
2787
+ queueMicrotask(() => { try { this.ingest(rel) } catch (err) { this.log(`could not merge ${rel}: ${err.message}`) } })
2788
+ return
2789
+ }
2790
+ // Otherwise keep a copy so nothing is lost.
2614
2791
  this.keepConflict(rel, disk)
2615
2792
  }
2616
2793
 
@@ -2628,9 +2805,19 @@ export class Session extends EventEmitter {
2628
2805
  if (!disk || disk.key !== shared) { this.downloadLarge(rel, b); return }
2629
2806
  this.setOnDisk(rel, b.hash)
2630
2807
  } else if (!disk || disk.key !== shared) {
2808
+ // Saved again since the look above (or made since, when there was nothing): that save is taken in
2809
+ // and merged, never written over (2026-11-14).
2810
+ if (this.savedSince(abs, disk)) { this.queue(rel); return }
2811
+ // What a partner's change is written over: a save made from it is told apart (base-pick.js), by who reads the file written.
2812
+ const was = disk && !disk.binary && disk.key === known && this.files.has(rel) ? disk.text : null
2631
2813
  fs.mkdirSync(path.dirname(abs), { recursive: true })
2632
2814
  const t = this.files.get(rel)
2633
- this.writeFile(rel, abs, t ? t.toString() : Buffer.from(b.data, 'base64'))
2815
+ const data = t ? t.toString() : Buffer.from(b.data, 'base64')
2816
+ const kept = was !== null ? {} : null
2817
+ const over = this.writeOver(rel, abs, data, disk, kept)
2818
+ if (over === false) { this.queue(rel); return }
2819
+ if (over === null) this.writeFile(rel, abs, data)
2820
+ if (was !== null) this.overwritten.note(rel, was, kept.wrote || null)
2634
2821
  }
2635
2822
  if (!b || !b.stored) this.setOnDisk(rel, null)
2636
2823
  this.lastKnown.set(rel, shared)
@@ -2666,26 +2853,193 @@ export class Session extends EventEmitter {
2666
2853
  return true
2667
2854
  }
2668
2855
 
2669
- /** An edit here to a file someone else has boxed: ours kept aside, the folder's version from before the box put back. */
2670
- rejectBoxed (rel, disk, claim) {
2671
- if (disk) {
2672
- const dest = path.join(this.stateDir, 'rejected', `${Date.now()}`, ...rel.split('/'))
2673
- fs.mkdirSync(path.dirname(dest), { recursive: true })
2674
- fs.writeFileSync(dest, disk.binary ? disk.buf : disk.text)
2856
+ /**
2857
+ * An edit here to a file someone else has boxed. It is never undone: Quilt holds no files (no-holds,
2858
+ * 2026-11-13). Their box opens, so their work reaches every folder (the relay tells them), and this
2859
+ * edit goes in straight away through the normal merge (autoSettle), from this folder's version
2860
+ * before the box. Returns true when the session's version changed.
2861
+ */
2862
+ editBoxed (rel, disk, box) {
2863
+ const before = this.boxBase.has(rel) ? this.boxBase.get(rel) : undefined
2864
+ const base = before === null ? null : before && typeof before.text === 'string' ? before.text : undefined
2865
+ if (this.boxBase.delete(rel)) this.scheduleStateSave()
2866
+ 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}`))
2867
+ // Not someone else's box here any more, from now: the session's version is written to this folder again.
2868
+ this.boxed.delete(rel)
2869
+ this.log(`📦 ${rel} was in ${box.of || box.by}'s box: it opened, and your change goes in with their work`)
2870
+ const ours = disk ? disk.key : null
2871
+ const theirs = this.sharedKey(rel)
2872
+ if (theirs === base || (theirs === undefined && base === null)) return this.ingest(rel) // their box changed nothing of it
2873
+ const binary = [ours, theirs].some((k) => typeof k === 'string' && k.startsWith('bin:')) || !!(before && typeof before.b64 === 'string')
2874
+ return this.autoSettle({ rel, base: binary ? null : base, ours, theirs, theirsBy: box.of || box.by, disk, binary, via: null }) === 'merged'
2875
+ }
2876
+
2877
+ /**
2878
+ * Writes the session's version over a file of this folder's that a save may land in at the same moment:
2879
+ * in a file of its own put in place by one rename (the file is never absent at its path), only over the
2880
+ * file `disk` read (savedSince, then swap-in.js: a save that took its place by a rename of its own before
2881
+ * Quilt's last look stays and is taken in next), and the file replaced stays open across it (and is looked
2882
+ * at again LATE_WRITE_MS later), so a save into it in that instant is put back as a save of its own
2883
+ * (rescueSave), never lost with the old file. True written; false saved since (not written); null
2884
+ * where this can't be done (Windows, a read-only file: the caller writes it as before). `disk` null (no file
2885
+ * there): made only if there still is none.
2886
+ * `kept`: an object that gets the written file kept open (`wrote`, base-pick.js keepWritten).
2887
+ */
2888
+ writeOver (rel, abs, data, disk, kept = null) {
2889
+ if (process.platform === 'win32') return null
2890
+ const tmp = path.join(path.dirname(abs), `.${path.basename(abs)}.quilt-tmp`)
2891
+ if (!disk) {
2892
+ // Nothing there when looked at: put in with a hard link, which never replaces a file made meanwhile (a save: taken in next).
2893
+ try {
2894
+ const st = writeAndStat(tmp, data)
2895
+ try { fs.linkSync(tmp, abs) } catch (err) {
2896
+ fs.rmSync(tmp, { force: true })
2897
+ let dir = false
2898
+ try { dir = fs.lstatSync(abs).isDirectory() } catch {}
2899
+ return err.code === 'EEXIST' && !dir ? false : null // a folder there: written as before (and refused as before)
2900
+ }
2901
+ fs.rmSync(tmp, { force: true })
2902
+ this.noteWritten(rel, abs, st, data)
2903
+ return true
2904
+ } catch { try { fs.rmSync(tmp, { force: true }) } catch {} return null }
2675
2905
  }
2676
- const base = this.boxBase.get(rel)
2677
- const abs = resolveInside(this.root, rel)
2678
- if (base === null) {
2679
- if (disk) { fs.rmSync(abs, { force: true }); removeEmptyParents(this.root, path.dirname(abs)) }
2680
- this.lastKnown.delete(rel)
2681
- } else if (base) {
2682
- fs.mkdirSync(path.dirname(abs), { recursive: true })
2683
- this.writeFile(rel, abs, typeof base.text === 'string' ? base.text : Buffer.from(base.b64, 'base64'))
2684
- const back = this.readDisk(rel)
2685
- if (back) this.lastKnown.set(rel, back.key)
2906
+ let old = null
2907
+ let wrote = null
2908
+ try {
2909
+ old = fs.openSync(abs, 'r')
2910
+ // As it was before the look below: a save into it after this is either seen by that look or after the rename.
2911
+ const seen = fs.fstatSync(old)
2912
+ const look = fs.lstatSync(abs)
2913
+ const st = writeAndStat(tmp, data, seen.mode & 0o7777)
2914
+ // Replaced since it was opened (look is another file), or saved since disk was read: not written.
2915
+ if ((!look.isSymbolicLink() && look.ino !== seen.ino) || this.savedSince(abs, disk)) { fs.rmSync(tmp, { force: true }); return false }
2916
+ if (kept) wrote = keepWritten(tmp)
2917
+ let r = { placed: true, displaced: null, replaced: false }
2918
+ if (look.isSymbolicLink()) fs.renameSync(tmp, abs)
2919
+ else r = this.swapIn(rel, abs, tmp, look)
2920
+ // Not the file looked at any more (a save took its place): taken in next, and written again after it.
2921
+ if (!r.placed) { letGo(wrote); return false }
2922
+ this.noteWritten(rel, abs, st, data)
2923
+ if (kept) { kept.wrote = wrote; wrote = null }
2924
+ const before = disk && typeof disk.text === 'string' ? disk.text : null
2925
+ const now = fs.fstatSync(old)
2926
+ // A save written into the file replaced: back as a save of its own, once whole (rescueSave), or at once.
2927
+ if (now.size !== seen.size || now.mtimeMs !== seen.mtimeMs) { this.rescueSave(rel, abs, old, data, before); old = null } else if (r.displaced) { const bytes = r.displaced; setImmediate(() => this.putBackSave(rel, abs, bytes, data, before)) } else {
2928
+ // An editor that opened the file just before the rename may write into it a moment after: looked at once more.
2929
+ const fd = old
2930
+ old = null
2931
+ const t = setTimeout(() => {
2932
+ let later = null
2933
+ try { later = fs.fstatSync(fd) } catch {}
2934
+ if (!this.stopped && later && (later.size !== seen.size || later.mtimeMs !== seen.mtimeMs)) this.rescueSave(rel, abs, fd, data, before)
2935
+ else { try { fs.closeSync(fd) } catch {} }
2936
+ }, LATE_WRITE_MS)
2937
+ t.unref?.()
2938
+ }
2939
+ return true
2940
+ } catch {
2941
+ letGo(wrote)
2942
+ try { fs.rmSync(tmp, { force: true }) } catch {}
2943
+ return null
2944
+ } finally { if (old !== null) { try { fs.closeSync(old) } catch {} } }
2945
+ }
2946
+
2947
+ /**
2948
+ * A save that landed in a file writeOver replaced: once whole, it goes back on disk (if the file still has
2949
+ * what was written) and is taken in. Saved again since: its own change (against `before`, what disk had
2950
+ * before the write) goes onto that newer save, the newer one winning where both changed a line.
2951
+ */
2952
+ async rescueSave (rel, abs, fd, wrote, before = null) {
2953
+ try {
2954
+ let last = null
2955
+ for (let i = 0; i < 50; i++) {
2956
+ const st = fs.fstatSync(fd)
2957
+ if (last && st.size === last.size && st.mtimeMs === last.mtimeMs) break
2958
+ last = st
2959
+ await new Promise((resolve) => setTimeout(resolve, 20))
2960
+ }
2961
+ const size = fs.fstatSync(fd).size
2962
+ const bytes = Buffer.alloc(size)
2963
+ let off = 0
2964
+ while (off < size) { const n = fs.readSync(fd, bytes, off, size - off, off); if (!n) break; off += n }
2965
+ if (this.stopped) return
2966
+ this.putBackSave(rel, abs, bytes, wrote, before)
2967
+ } catch {} finally { try { fs.closeSync(fd) } catch {} }
2968
+ }
2969
+
2970
+ /**
2971
+ * A save of `rel` (`bytes`) that Quilt's write took out of the path (it landed in the file replaced, or took
2972
+ * that file's place in the instant before) goes back on disk: over what Quilt wrote (`wrote`), whole; saved
2973
+ * again since, its own change (against `before`, what disk had before the write) goes onto that newer save,
2974
+ * both kept where both changed a line. Then it is taken in.
2975
+ */
2976
+ putBackSave (rel, abs, bytes, wrote, before = null) {
2977
+ try {
2978
+ if (this.stopped) return
2979
+ const w = Buffer.isBuffer(wrote) ? wrote : Buffer.from(String(wrote), 'utf8')
2980
+ if (bytes.equals(w)) return // nothing of its own
2981
+ const tmp = path.join(path.dirname(abs), `.${path.basename(abs)}.quilt-save`)
2982
+ // Put back only over the file as looked at here (swap-in.js): saved again in that instant, it is looked at again.
2983
+ let placed = false
2984
+ let ours = false
2985
+ for (let attempt = 0; attempt < 5 && !placed; attempt++) {
2986
+ let look = null
2987
+ try { look = fs.lstatSync(abs) } catch {}
2988
+ const now = (() => { try { return fs.readFileSync(abs) } catch { return null } })()
2989
+ if (!now || !look) return // gone
2990
+ // Disk still has a version Quilt wrote (this one, or a newer one it wrote since): the save goes back over it.
2991
+ const k = this.lastKnown.get(rel)
2992
+ ours = now.equals(w) || (typeof k === 'string' && !k.startsWith('bin:') && now.toString('utf8') === k)
2993
+ let put = bytes
2994
+ if (!ours) {
2995
+ // Saved again since, from what Quilt wrote: the late save's own change goes onto that save.
2996
+ if (typeof before !== 'string' || looksBinary(bytes) || looksBinary(now)) return
2997
+ const onto = mergeLive(before, bytes.toString('utf8'), w.toString('utf8')).text
2998
+ // Both saves are this folder's: where they changed the same place, both go in (nothing is lost; its writer sees both).
2999
+ const merged = mergeLive(w.toString('utf8'), onto, now.toString('utf8'), { union: true }).text
3000
+ if (merged === now.toString('utf8')) return
3001
+ put = Buffer.from(merged, 'utf8')
3002
+ }
3003
+ fs.writeFileSync(tmp, put, { mode: look.mode & 0o7777 })
3004
+ if (look.isSymbolicLink()) { fs.renameSync(tmp, abs); placed = true; continue }
3005
+ const r = this.swapIn(rel, abs, tmp, look)
3006
+ placed = r.placed
3007
+ if (r.displaced) { const again = r.displaced; setImmediate(() => this.putBackSave(rel, abs, again, put, now.toString('utf8'))) }
3008
+ }
3009
+ if (!placed) return // saved again and again meanwhile: what is there now is taken in
3010
+ // Made from what disk had before Quilt's write: merged against that (base-pick.js).
3011
+ if (ours && typeof before === 'string' && !looksBinary(bytes)) this.overwritten.mark(rel, bytes.toString('utf8'), before)
3012
+ this.log(`${rel}: a save landed while Quilt wrote the session's version; it is taken in now`)
3013
+ this.queue(rel)
3014
+ } catch {}
3015
+ }
3016
+
3017
+ /**
3018
+ * swap-in.js for this folder (the second name in .quilt/tmp, so no file of Quilt's ever shows in the
3019
+ * project); a save replaced in the one system call it cannot cover is said to its writer.
3020
+ */
3021
+ swapIn (rel, abs, tmp, look) {
3022
+ const r = swapIn(abs, tmp, look, { asideDir: path.join(this.stateDir, 'tmp') })
3023
+ if (r.replaced) {
3024
+ const w = `A save of ${rel} landed in the same instant Quilt wrote the session's version over it, and could not be kept: save ${rel} again (your editor still has it).`
3025
+ this.notice(w)
3026
+ this.log(`⚠️ ${w}`)
2686
3027
  }
2687
- this.notice(`Your change to ${rel} was undone: ${heldRefusal(rel, claim)}`)
2688
- this.log(`📦 your change to ${rel} was undone: it is boxed by ${claim.by}`)
3028
+ return r
3029
+ }
3030
+
3031
+ /** A file read half-written (readDisk `unsettled`): taken in a moment later. */
3032
+ settleSoon (rel) {
3033
+ const t = setTimeout(() => { if (!this.stopped) this.queue(rel) }, SETTLE_MS / 5)
3034
+ t.unref?.()
3035
+ }
3036
+
3037
+ /** Whether the file at abs changed since `disk` (readDisk's look; null: there was none) was read. */
3038
+ savedSince (abs, disk) {
3039
+ let st = null
3040
+ try { st = fs.lstatSync(abs) } catch {}
3041
+ if (!disk) return !!st
3042
+ return !st || (typeof disk.mtime === 'number' && st.mtimeMs !== disk.mtime)
2689
3043
  }
2690
3044
 
2691
3045
  /** Keeps our version of rel aside before something replaces it. */
@@ -2700,33 +3054,52 @@ export class Session extends EventEmitter {
2700
3054
  /** Writes the shared version of rel. A read-only copy of ours is made writable, or moved aside if it can't be. */
2701
3055
  writeFile (rel, abs, data) {
2702
3056
  try {
2703
- fs.writeFileSync(abs, data)
2704
- return this.noteWritten(rel, abs)
3057
+ return this.noteWritten(rel, abs, writeAndStat(abs, data), data)
2705
3058
  } catch (err) {
2706
3059
  if (err.code !== 'EACCES' && err.code !== 'EPERM') throw err
2707
3060
  }
3061
+ let st
2708
3062
  try {
2709
3063
  fs.chmodSync(abs, (fs.statSync(abs).mode & 0o7777) | 0o200)
2710
- fs.writeFileSync(abs, data)
3064
+ st = writeAndStat(abs, data)
2711
3065
  } catch {
2712
3066
  this.moveAside(rel, abs)
2713
- fs.writeFileSync(abs, data)
3067
+ st = writeAndStat(abs, data)
2714
3068
  }
2715
- this.noteWritten(rel, abs)
3069
+ this.noteWritten(rel, abs, st, data)
2716
3070
  }
2717
3071
 
2718
3072
  /**
2719
3073
  * The re-scan learns of a file Quilt wrote at once: the watcher can miss
2720
3074
  * events in a folder Quilt just created, and a file the re-scan never saw
2721
- * would never be noticed gone.
3075
+ * would never be noticed gone. `st`: the file as this write left it (read
3076
+ * before it was closed), so a save landing right after it is never taken for it.
3077
+ * `data`: what was written; a text is kept (wroteHere), so reading it back while untouched reads nothing.
2722
3078
  */
2723
- noteWritten (rel, abs) {
3079
+ noteWritten (rel, abs, st = null, data = null) {
2724
3080
  try {
2725
- const st = fs.lstatSync(abs)
3081
+ if (!st) st = fs.lstatSync(abs)
2726
3082
  this.diskStats.set(rel, `${st.ino}:${st.size}:${st.mtimeMs}:${st.ctimeMs}`)
3083
+ const was = this.wroteHere.get(rel)
3084
+ if (was) { this.wroteBytes -= was.text.length; this.wroteHere.delete(rel) }
3085
+ if (typeof data === 'string' && data.length <= WROTE_TEXT) {
3086
+ this.wroteHere.set(rel, { ino: st.ino, size: st.size, mtimeMs: st.mtimeMs, text: data })
3087
+ this.wroteBytes = (this.wroteBytes || 0) + data.length
3088
+ while (this.wroteBytes > WROTE_BYTES && this.wroteHere.size) {
3089
+ const [k, v] = this.wroteHere.entries().next().value
3090
+ this.wroteBytes -= v.text.length
3091
+ this.wroteHere.delete(k)
3092
+ }
3093
+ }
2727
3094
  } catch {}
2728
3095
  }
2729
3096
 
3097
+ /** Whether this folder's disk shows who read a file (base-pick.js atimeWorks), looked at once. */
3098
+ atimeOn () {
3099
+ if (this.atimeSeen === undefined) this.atimeSeen = atimeWorks(this.root)
3100
+ return this.atimeSeen
3101
+ }
3102
+
2730
3103
  /** Moves whatever sits at rel (first join: a folder, or a file where a folder must go) into the backup folder. */
2731
3104
  moveToBackup (rel, backupDir) {
2732
3105
  const dest = path.join(backupDir, ...rel.split('/'))
@@ -2924,7 +3297,7 @@ export class Session extends EventEmitter {
2924
3297
  }
2925
3298
  const now = this.readDisk(rel)
2926
3299
  if (!now || now.key !== diskKey) return // it changed again; that change is already queued
2927
- if (this.sharedKey(rel) !== sharedBefore || this.downloading.has(rel)) return // a partner's newer version wins
3300
+ if (this.sharedKey(rel) !== sharedBefore || this.downloading.has(rel)) return // a partner's version landed first: it stays
2928
3301
  const existed = this.files.has(rel) || this.blobs.has(rel)
2929
3302
  this.transact(() => {
2930
3303
  this.files.delete(rel)
@@ -3378,7 +3751,7 @@ export class Session extends EventEmitter {
3378
3751
 
3379
3752
  /**
3380
3753
  * What an agent needs when it picks up a task: the task, recent chronology for
3381
- * its files (or the project when it lists none), claims that touch them, and the checklist.
3754
+ * its files (or the project when it lists none), and the checklist.
3382
3755
  */
3383
3756
  taskBrief (id) {
3384
3757
  const task = this.taskList().find((t) => t.id === id)
@@ -3386,10 +3759,7 @@ export class Session extends EventEmitter {
3386
3759
  const files = task.files || []
3387
3760
  const all = this.history.entries()
3388
3761
  const history = (files.length ? all.filter((e) => files.includes(e.path)) : all).slice(-8)
3389
- const claims = [...this.claims.values()]
3390
- .filter((c) => !files.length || files.some((f) => globMatcher(c.pattern)(f)))
3391
- .map((c) => ({ by: c.by, pattern: c.pattern, note: c.note }))
3392
- return { task, history, claims, checklist: this.readChecklist(), me: this.name }
3762
+ return { task, history, checklist: this.readChecklist(), me: this.name }
3393
3763
  }
3394
3764
 
3395
3765
  /**
@@ -3914,8 +4284,7 @@ export class Session extends EventEmitter {
3914
4284
 
3915
4285
  // ------------------------------------------------- AI sessions (persona.js) --
3916
4286
  // Several AI sessions often work through this one app (two Claude Code chats, Cursor, Codex).
3917
- // Each is a member of its own, named after its work, so partners message the right one and
3918
- // its claims go idle when it stops, not when its person does.
4287
+ // Each is a member of its own, named after its work, so partners message the right one.
3919
4288
 
3920
4289
  /**
3921
4290
  * An AI session (one `quilt mcp`, by its `via` id) says hello. Its name is taken from the git
@@ -3934,13 +4303,12 @@ export class Session extends EventEmitter {
3934
4303
  const now = Date.now()
3935
4304
  let p = this.personas.get(via)
3936
4305
  // The same tool session again (its `quilt mcp` restarted, or a second one from the same
3937
- // process): it keeps its name, claims and inbox instead of becoming "… 2".
4306
+ // process): it keeps its name and inbox instead of becoming "… 2".
3938
4307
  if (!p && chain[0]) {
3939
4308
  // A run Quilt started on its own (autowork.js) is known by its process: the tool, or the wrapper that started it.
3940
4309
  const same = [...this.personas.values()].find((q) => q.chain && (q.chain[0] === chain[0] || (q.auto && chain.includes(q.chain[0]))))
3941
4310
  if (same) {
3942
4311
  this.personas.delete(same.via)
3943
- for (const [rel, v] of this.autoVia) if (v === same.via) this.autoVia.set(rel, via)
3944
4312
  same.via = via
3945
4313
  this.personas.set(via, same)
3946
4314
  p = same
@@ -4052,8 +4420,6 @@ export class Session extends EventEmitter {
4052
4420
  for (const c of plan.changes) {
4053
4421
  const refusal = this.writeRefusal(c.path)
4054
4422
  if (refusal) throw new Error(refusal)
4055
- const claim = this.claimFor(c.path)
4056
- if (claim && !this.ownClaim(claim)) throw new Error(`${c.path} is claimed by ${claim.by}: ask them for it, then gather again`)
4057
4423
  }
4058
4424
  for (const c of plan.changes) {
4059
4425
  const abs = resolveInside(this.root, c.path)
@@ -4111,7 +4477,7 @@ export class Session extends EventEmitter {
4111
4477
  /** Who an action from this AI session is by: its own name, or this member's. */
4112
4478
  actorName (via) { const p = this.persona(via); return p ? p.name : this.name }
4113
4479
 
4114
- /** The claim request fields that make the relay act for an AI session (server.js claimant). */
4480
+ /** The box request fields that make the relay act for an AI session (server.js boxOwner). */
4115
4481
  as (via) { const p = this.persona(via); return p ? { as: { id: p.rid || p.via, label: p.label } } : {} }
4116
4482
 
4117
4483
  /** Whether a name is this member's or one of its AI sessions' (now or before a rename). */
@@ -4129,14 +4495,8 @@ export class Session extends EventEmitter {
4129
4495
  return [this.name, ...(this.aiOf ? [aiName(this.aiOf)] : []), ...[...this.personas.values()].flatMap((p) => [p.name, ...p.aliases])]
4130
4496
  }
4131
4497
 
4132
- /** Whether a claim is this member's or one of its AI sessions': files on this disk are ours to write. */
4133
- ownClaim (c) { return !!c && (c.by === this.name || c.of === this.name || this.isMine(c.by)) }
4134
-
4135
- /** Whether one AI session holds a claim (not this member, nor another of its sessions). */
4136
- claimHeldBy (c, via) {
4137
- const p = this.persona(via)
4138
- return !!c && !!p && (c.by === p.name || p.aliases.includes(c.by))
4139
- }
4498
+ /** Whether a box is this member's or one of its AI sessions': its work is in this folder. */
4499
+ isOwnBox (c) { return !!c && (c.by === this.name || c.of === this.name || this.isMine(c.by)) }
4140
4500
 
4141
4501
  /**
4142
4502
  * How an AI session reads the inbox: by its own name only. What is written to "<person>'s AI"
@@ -4200,7 +4560,7 @@ export class Session extends EventEmitter {
4200
4560
  if (label) this.renamePersona(via, label, 'prompt')
4201
4561
  }
4202
4562
 
4203
- /** An AI session used a Quilt tool: it is here, and its claims' idle time starts again (once a minute at most). */
4563
+ /** An AI session used a Quilt tool: it is here. */
4204
4564
  touchPersona (via) {
4205
4565
  const p = this.persona(via)
4206
4566
  if (!p) return
@@ -4208,9 +4568,6 @@ export class Session extends EventEmitter {
4208
4568
  const wasAway = now - p.seenAt > PERSONA_AWAY_MS
4209
4569
  p.seenAt = now
4210
4570
  if (wasAway) this.publishPersonas()
4211
- if (now - p.touchedAt < 60 * 1000 || !this.conn) return
4212
- p.touchedAt = now
4213
- this.conn.claimRequest({ op: 'touch', ...this.as(via) }).catch(() => {})
4214
4571
  }
4215
4572
 
4216
4573
  /** The AI session a hook belongs to: the one whose tool process is among the hook's parents. */
@@ -4516,21 +4873,11 @@ export class Session extends EventEmitter {
4516
4873
  this.scheduleStatusWrite()
4517
4874
  }
4518
4875
 
4519
- /** Asks the relay for a claim; it refuses overlaps with anyone else's. */
4520
- async claim (pattern, note = '', via = null) {
4521
- pattern = String(pattern ?? '').trim()
4522
- if (!pattern) throw new Error('pattern required')
4523
- await this.conn.claimRequest({ op: 'claim', pattern, note: String(note), ...this.as(via) })
4524
- this.autoClaims.delete(pattern) // claimed by hand now: ours until we release it
4525
- this.noteActivity(`Claimed ${pattern}${note ? ` (${String(note).slice(0, 200)})` : ''}`, { via })
4526
- return { ok: true }
4527
- }
4528
-
4529
- // --------------------------------------------------- claims follow edits --
4530
- // Whatever tool made the change, a file we edit is claimed for us (so a partner's AI is refused
4531
- // and told, instead of overwriting us), and let go when we are done: when our AI goes idle, when
4532
- // the file has been quiet for a while, or when the session stops. Claims made on purpose
4533
- // (quilt_claim, the app, `quilt claim`) are never touched here.
4876
+ // ------------------------------------------------------------- boxes --
4877
+ // Quilt holds no files (no-holds, 2026-11-13): nobody claims, queues for or hands off a file, and no
4878
+ // write is refused or undone because someone else is working on it. What our AI changes in a git
4879
+ // folder goes into a box of ours (unfinished work, kept out of other folders until it's committed);
4880
+ // anyone who edits a boxed file opens it, and their change merges with the work in it (editBoxed).
4534
4881
 
4535
4882
  /** An agent session, or a person whose AI is working or whose tool Quilt can't read: an edit is probably the AI's. */
4536
4883
  aiMayBeEditing () {
@@ -4543,127 +4890,94 @@ export class Session extends EventEmitter {
4543
4890
  */
4544
4891
  boxesOn () { return !!this.git }
4545
4892
 
4546
- /** The box covering rel when someone else holds it (their unfinished work: not written here), else null. */
4893
+ /** The box on rel when it is someone else's (their unfinished work: not written here), else null. */
4547
4894
  boxedByOther (rel) {
4548
- const c = this.claimFor(rel)
4549
- return c && c.box && !this.ownClaim(c) ? c : null
4895
+ const c = this.boxAt(rel)
4896
+ return c && !this.isOwnBox(c) ? c : null
4550
4897
  }
4551
4898
 
4552
- /** Our own claim on just rel with no box (claimed by hand, or unpacked early): our AI's next edit there boxes it. */
4553
- unboxedOwn (rel, claim) {
4554
- return this.boxesOn() && !!claim && claim.pattern === rel && claim.box !== true && !claim.clash && this.ownClaim(claim)
4899
+ /** The box on exactly rel (whoever's), or null. */
4900
+ boxAt (rel) {
4901
+ const c = this.boxed.get(rel)
4902
+ return c && c.box !== false ? c : null
4555
4903
  }
4556
4904
 
4557
- autoClaim (rel) {
4558
- const first = !this.autoClaims.has(rel)
4559
- this.autoClaims.set(rel, Date.now())
4560
- if (!this.conn) return
4561
- // A box unpacked early (quilt_unpack) boxes again with the next edit: what follows is unfinished too.
4562
- const c = this.claims.get(rel)
4563
- const rebox = !first && this.unboxedOwn(rel, c) && !this.reboxing.has(rel)
4564
- if (!first && !rebox) return
4565
- if (rebox) this.reboxing.add(rel)
4566
- if (this.boxesOn() && (first || rebox) && !(c && c.box && this.ownClaim(c))) this.boxFrom.set(rel, this.sharedKey(rel) ?? null) // called before the edit goes in
4905
+ /**
4906
+ * Our AI changed rel here: noted for its working state, and, in a git folder, boxed for us (once:
4907
+ * a box of ours already there keeps its first version, boxFrom). Someone else's box on it was opened
4908
+ * before this (editBoxed), and a box the relay can't give (a race, an older relay) leaves the edit live.
4909
+ */
4910
+ boxEdit (rel) {
4911
+ this.aiEdits.set(rel, Date.now())
4912
+ if (!this.conn || !this.boxesOn() || this.ownBox(rel) || this.boxing.has(rel)) return
4913
+ this.boxing.add(rel)
4914
+ this.boxFrom.set(rel, this.sharedKey(rel) ?? null) // called before the edit goes in
4567
4915
  const note = this.focus ? `editing: ${this.focus}` : 'editing'
4568
- if (first) this.noteActivity(`Editing ${rel}`)
4569
- this.conn.claimRequest({ op: 'claim', pattern: rel, note, ...(this.boxesOn() ? { box: true } : {}) }).catch((err) => {
4570
- // Lost the race to a partner, or an overlapping claim: their copy wins; ours is undone on the next sync.
4571
- if (first) this.autoClaims.delete(rel)
4572
- this.log(`could not claim ${rel} for you: ${err.message}`)
4573
- }).finally(() => this.reboxing.delete(rel))
4916
+ this.noteActivity(`Editing ${rel}`)
4917
+ this.conn.boxRequest({ op: 'box', pattern: rel, note }).then((r) => {
4918
+ if (r && r.boxed === 0) this.boxFrom.delete(rel)
4919
+ }, (err) => {
4920
+ this.boxFrom.delete(rel)
4921
+ this.log(`could not box ${rel} for you (it stays live with everyone): ${err.message}`)
4922
+ }).finally(() => this.boxing.delete(rel))
4574
4923
  }
4575
4924
 
4576
- /**
4577
- * Releases the claims Quilt made for us. `only(rel, lastEdit)` picks which; all of them by default.
4578
- * One someone is waiting for in its file queue is kept: our AI hands it off, with its context.
4579
- */
4580
- async releaseAutoClaims (only = () => true) {
4581
- const done = []
4582
- for (const [rel, ts] of this.autoClaims) {
4583
- if (!only(rel, ts)) continue
4584
- const c = this.claims.get(rel)
4585
- if (c && c.box && this.ownClaim(c)) continue // a box opens when it's committed (settleBoxes), not when we stop editing
4586
- if (c && this.ownClaim(c) && c.queue && c.queue.length) continue
4587
- // Not connected (the relay restarting, a network blip): kept, and let go of once the folder is back. Dropped
4588
- // from the list now, the claim would stay on the relay for good, and GitHub's changes to the file wait on it.
4589
- if (!this.conn || !this.conn.connected) continue
4590
- // Our claim is still on its way (not on record here yet): kept for a moment, unless it never comes.
4591
- if (!c && Date.now() - ts < AUTO_CLAIM_ARRIVE_MS) continue
4592
- const via = this.autoVia.get(rel)
4593
- this.autoClaims.delete(rel)
4594
- this.autoVia.delete(rel)
4595
- if (!c || !this.ownClaim(c)) continue
4596
- // A release that doesn't reach the relay is tried again with the next look.
4597
- done.push(this.conn.claimRequest({ op: 'release', pattern: rel, ...this.as(via) }).catch(() => { if (!this.stopped) { this.autoClaims.set(rel, ts); if (via) this.autoVia.set(rel, via) } }))
4598
- }
4599
- await Promise.all(done)
4600
- return done.length
4601
- }
4602
-
4603
- releaseQuietAutoClaims () {
4925
+ /** Forgets our AI's edits that have been quiet a while: "working" that only those edits said lapses with them. */
4926
+ forgetQuietEdits () {
4604
4927
  if (!this.ready || this.stopped) return
4605
- this.handOnForgotten().catch(() => {})
4606
- const cutoff = Date.now() - this.autoClaimQuietMs
4607
- this.releaseAutoClaims((rel, ts) => ts <= cutoff).then(() => {
4608
- // "Working" that only an edit check said lapses with its files, so a commit isn't held up by an agent that never said done.
4609
- if (this.workFromEdits && ![...this.autoClaims.keys()].some((rel) => !this.ownBox(rel)) && this.work?.state === 'working' && Date.now() - (this.agentReportedAt || 0) >= this.autoClaimQuietMs) this.finishEditing().catch(() => {})
4610
- }).catch(() => {})
4928
+ const cutoff = Date.now() - this.editQuietMs
4929
+ for (const [rel, ts] of this.aiEdits) if (ts <= cutoff) this.aiEdits.delete(rel)
4930
+ // So a commit isn't held up by an agent that never said done.
4931
+ if (this.workFromEdits && !this.aiEdits.size && this.work?.state === 'working' && Date.now() - (this.agentReportedAt || 0) >= this.editQuietMs) this.finishEditing().catch(() => {})
4611
4932
  }
4612
4933
 
4613
4934
  /** Our own box on exactly rel, or null. */
4614
4935
  ownBox (rel) {
4615
- const c = this.claims.get(rel)
4616
- return c && c.box && this.ownClaim(c) ? c : null
4936
+ const c = this.boxAt(rel)
4937
+ return c && this.isOwnBox(c) ? c : null
4617
4938
  }
4618
4939
 
4619
4940
  /**
4620
4941
  * The check every agent makes before it changes files, whatever tool it runs in (the local
4621
- * MCP's quilt_before_edit, or a Claude Code hook): for each path, whether it is ours to edit
4622
- * (a file nobody holds is claimed for us, and let go like any claim that follows edits), and
4623
- * what people said about those files in chat, as context. When no chat reader can see
4624
- * our AI work, it is marked working, so the host doesn't commit under it.
4942
+ * MCP's quilt_before_edit, or a hook): for each path, who wrote it recently (presence) and whose
4943
+ * unfinished work is boxed on it, and what people said about those files in chat, as context. It
4944
+ * never claims and never refuses: every path stays writable (no-holds, 2026-11-13). When no chat
4945
+ * reader can see our AI work, it is marked working, so the host doesn't commit under it.
4625
4946
  */
4626
4947
  async prepareEdit (paths, via = null) {
4627
4948
  const files = []
4628
4949
  const p0 = this.persona(via)
4950
+ const me = p0 ? p0.name : this.name
4629
4951
  for (const p of [...new Set((paths || []).map((x) => String(x || '').replace(/\\/g, '/').replace(/^\.\//, '')))]) {
4630
4952
  if (!p) continue
4631
4953
  if (!this.syncable(p)) { files.push({ path: p, shared: false }); continue }
4632
- // Who holds it, as people see them: an older app's AI session ("Dana · login") is its person.
4633
- const held = (c) => ({ by: c.of || c.by, pattern: c.pattern, note: c.note || '', queue: c.queue || [], ...(c.box ? { box: true } : {}) })
4634
- // Yours, including what an AI session of yours held before this app stopped making them.
4635
- const mine = (c) => p0 ? this.claimHeldBy(c, via) : this.ownClaim(c)
4636
- let c = this.claimFor(p)
4637
- if (c && mine(c)) {
4638
- if (this.autoClaims.has(p)) this.autoClaims.set(p, Date.now())
4639
- files.push({ path: p, shared: true, ok: true, mine: true })
4640
- continue
4641
- }
4642
- if (c) { files.push({ path: p, shared: true, ok: false, claim: held(c) }); continue }
4643
- try {
4644
- if (!this.conn) throw new Error('not connected')
4645
- const focus = (p0 && p0.focus) || this.focus
4646
- // A session still named after its tool takes a name from the first file it edits.
4647
- if (p0 && !p0.named && labelFromFile(p)) this.renamePersona(via, labelFromFile(p), 'file')
4648
- await this.conn.claimRequest({ op: 'claim', pattern: p, note: focus ? `editing: ${focus}` : 'editing', ...this.as(via) })
4649
- this.autoClaims.set(p, Date.now())
4650
- if (p0) this.autoVia.set(p, via)
4651
- this.noteActivity(`Editing ${p}`, { via })
4652
- files.push({ path: p, shared: true, ok: true, claimed: true })
4653
- } catch (err) {
4654
- c = this.claimFor(p)
4655
- files.push(c && !mine(c) ? { path: p, shared: true, ok: false, claim: held(c) } : { path: p, shared: true, ok: false, error: err.message })
4656
- }
4954
+ const b = this.boxedByOther(p)
4955
+ files.push({ path: p, shared: true, ok: true, recent: this.recentWriters(p).filter((w) => w.by !== me), ...(b ? { box: { by: b.of || b.by } } : {}) })
4657
4956
  }
4957
+ // A session still named after its tool takes a name from the first file it edits.
4958
+ const first = files.find((f) => f.shared)
4959
+ if (p0 && !p0.named && first && labelFromFile(first.path)) this.renamePersona(via, labelFromFile(first.path), 'file')
4658
4960
  const chat = this.chatAbout(files.filter((f) => f.shared).map((f) => f.path))
4659
- if (files.some((f) => f.claimed)) this.reportWorking(this.focus || '')
4961
+ if (first) this.reportWorking((p0 && p0.focus) || this.focus || '')
4660
4962
  return { me: p0 ? p0.name : this.name, files, chat }
4661
4963
  }
4662
4964
 
4965
+ /** Who wrote rel in the session lately (the room's activity), newest first: [{ by, at }]. Presence, never a hold. */
4966
+ recentWriters (rel, { within = RECENT_WRITER_MS, now = Date.now() } = {}) {
4967
+ const out = new Map()
4968
+ for (let i = this.activity.length - 1; i >= 0; i--) {
4969
+ const a = this.activity.get(i)
4970
+ if (!a || a.path !== rel || !a.by || a.kind === 'switched') continue
4971
+ if (now - (a.ts || 0) > within) break
4972
+ if (!out.has(a.by)) out.set(a.by, { by: a.by, at: a.ts || 0 })
4973
+ }
4974
+ return [...out.values()]
4975
+ }
4976
+
4663
4977
  /**
4664
4978
  * An agent said (over MCP) that it is at work. Unless a chat reader already sees it working,
4665
- * it counts as working for commits and for claims that follow edits, until it says done or
4666
- * goes quiet (nothing reported, no claimed file touched, for the quiet time).
4979
+ * it counts as working for commits, until it says done or goes quiet (nothing reported, no file
4980
+ * of its changed, for the quiet time).
4667
4981
  */
4668
4982
  reportWorking (note = '') {
4669
4983
  this.agentReportedAt = Date.now()
@@ -4675,7 +4989,7 @@ export class Session extends EventEmitter {
4675
4989
  // ------------------------------------------- agent threads, written by Quilt --
4676
4990
  // An agent's thread (its lane in the feed) should show what it did in order, whatever tool it
4677
4991
  // runs in. Agents driven by the CLI, webhooks or MCP rarely call quilt_share, so Quilt writes
4678
- // the thread itself as they post, claim, release, hand off, move tasks, leave notes and edit.
4992
+ // the thread itself as they post, move tasks, leave notes and edit.
4679
4993
 
4680
4994
  /**
4681
4995
  * Whether Quilt writes this actor's thread itself: an agent member (CLI, webhooks), or one AI
@@ -4754,10 +5068,7 @@ export class Session extends EventEmitter {
4754
5068
  return chatAbout(paths, { messages: this.chat.toArray().filter((m) => this.canSee(m)), me: this.name })
4755
5069
  }
4756
5070
 
4757
- /**
4758
- * What this member owes before work moves on: direct messages and mentions not answered yet,
4759
- * and files they hold that someone is waiting for in the file queue (`queued`, see duties.js).
4760
- */
5071
+ /** What this member owes before work moves on: direct messages and mentions not answered yet (duties.js). */
4761
5072
  duties (via = null) {
4762
5073
  const p = this.persona(via)
4763
5074
  const me = p ? [p.name, ...p.aliases] : this.name
@@ -4767,7 +5078,6 @@ export class Session extends EventEmitter {
4767
5078
  return {
4768
5079
  me: p ? p.name : this.name,
4769
5080
  waiting: person ? [] : waitingOn(this.chat.toArray().filter((m) => this.canSee(m)), me, { agent: !!p || this.kind === 'agent', settled: this.settledIds }),
4770
- queued: this.queued(via),
4771
5081
  pickup: person ? 'off' : pickup,
4772
5082
  next: person ? null : nextTask(this.taskList(), { name: this.name, asAi: this.kind !== 'agent' }, pickup)
4773
5083
  }
@@ -4786,133 +5096,12 @@ export class Session extends EventEmitter {
4786
5096
  try { return pickupMode(getSettings().aiTasks) } catch { return 'off' }
4787
5097
  }
4788
5098
 
4789
- // ------------------------------------------------------------ file queue --
4790
- // A file someone else holds is asked for in its claim's queue, not taken; its holder hands it
4791
- // on with their context when done (the relay keeps the queue, see server.js).
4792
-
4793
- /** Files we hold that someone is waiting for: [{ pattern, queue }]. */
4794
- queued (via = null) {
4795
- const p = this.persona(via)
4796
- return p ? [p.name, ...p.aliases].flatMap((n) => queuedFor([...this.claims.values()], n)) : queuedFor([...this.claims.values()], this.name)
4797
- }
4798
-
4799
- /** Asks for a file someone else holds. Resolves to { request, position, holder, pattern }. */
4800
- async requestFile (file, { title = '', description = '', task = '', via = null } = {}) {
4801
- const rel = String(file || '').replace(/\\/g, '/').replace(/^\.\//, '')
4802
- if (!rel) throw new Error('path required')
4803
- const r = await this.conn.claimRequest({ op: 'request', path: rel, title: String(title), description: String(description), ...(task ? { task: String(task) } : {}), ...this.as(via) })
4804
- this.noteActivity(`Asked for ${rel}${r && r.holder ? ` (held by ${r.holder})` : ''}${title ? `: ${String(title).slice(0, 200)}` : ''}`, { via })
4805
- return r
4806
- }
4807
-
4808
- /** Hands a file we hold to someone waiting for it (the first, or `to`: a name or request id), with our context. */
4809
- async handoff (file, { to = '', context = '', via = null } = {}) {
4810
- const rel = String(file || '').replace(/\\/g, '/').replace(/^\.\//, '')
4811
- const r = await this.conn.claimRequest({ op: 'handoff', pattern: rel, to: String(to || ''), context: String(context), ...this.as(via) })
4812
- this.autoClaims.delete(r.pattern)
4813
- this.autoVia.delete(r.pattern)
4814
- this.noteActivity(`Handed ${r.pattern || rel} to ${r.to}${context ? `: ${String(context).slice(0, 300)}` : ''}`, { via })
4815
- return r
4816
- }
4817
-
4818
- /** Takes back one of our requests. */
4819
- async withdrawRequest (request, via = null) {
4820
- const r = await this.conn.claimRequest({ op: 'withdraw', request: String(request || ''), ...this.as(via) })
4821
- return r.withdrawn || 0
4822
- }
4823
-
4824
- /**
4825
- * We just changed a file someone is waiting for: our AI hears it with its next answer (once a
4826
- * minute per file at most), so it hands the file on when done instead of forgetting them.
4827
- */
4828
- noteQueuedEdit (rel) {
4829
- const c = this.claimFor(rel)
4830
- if (!c || !this.ownClaim(c) || !c.queue || !c.queue.length) return
4831
- const last = this.queueNoticed.get(c.pattern) || 0
4832
- if (Date.now() - last < 60 * 1000) return
4833
- this.queueNoticed.set(c.pattern, Date.now())
4834
- this.notice(renderQueueNotice([{ pattern: c.pattern, queue: c.queue }]))
4835
- }
4836
-
4837
- /**
4838
- * Files Quilt claimed for our AI that someone waits for, which our AI stopped working on without
4839
- * handing on: Quilt hands each to the first in its queue, with what it knows as context, so the
4840
- * queue moves whatever tool the AI runs in (and whether or not it called quilt_handoff).
4841
- * Stopped means: its chat reader says it is idle and the file has been quiet for handoffGraceMs,
4842
- * or (no reader can see it) quiet for autoClaimQuietMs.
4843
- */
4844
- async handOnForgotten (now = Date.now()) {
4845
- if (!this.conn || this.agentState?.status === 'working') return 0
4846
- const seen = this.agentState?.tool && this.agentState.status === 'idle'
4847
- const cutoff = now - (seen ? this.handoffGraceMs : this.autoClaimQuietMs)
4848
- let handed = 0
4849
- for (const [rel, ts] of [...this.autoClaims]) {
4850
- if (ts > cutoff) continue
4851
- const c = this.claims.get(rel)
4852
- if (!c || !this.ownClaim(c) || !c.queue || !c.queue.length) continue
4853
- const via = this.autoVia.get(rel) // claimed for one of our AI sessions
4854
- const who = this.persona(via) ? this.actorName(via) : `${this.name}'s AI`
4855
- const focus = (this.persona(via) && this.persona(via).focus) || this.focus
4856
- const ago = Math.max(1, Math.round((now - ts) / 60000))
4857
- const context = `Handed on by Quilt: ${who} stopped working on ${rel} without handing it on.` +
4858
- `${focus ? ` It was working on: ${focus}.` : ''} Its last change was ${ago} minute${ago === 1 ? '' : 's'} ago; quilt_history shows what changed.`
4859
- try {
4860
- const r = await this.handoff(rel, { context, via })
4861
- handed++
4862
- this.notice(`Quilt handed ${rel} to ${r.to}, who was waiting for it, because you had stopped working on it. Ask for it again with quilt_request_file if you still need it.`)
4863
- this.log(`🤝 handed ${rel} to ${r.to}: they were waiting and your AI had stopped`)
4864
- } catch {}
4865
- }
4866
- return handed
4867
- }
4868
-
4869
- /** Done with a piece of work: lets go of the claims that followed our edits and says we're done. */
5099
+ /** Done with a piece of work: says we're done. Nothing is held, so nothing is let go of (boxes stay until committed). */
4870
5100
  async finishEditing (via = null) {
4871
- // One AI session finishing lets go of what was claimed for it; the others keep theirs.
4872
- const released = await this.releaseAutoClaims(this.persona(via) ? (rel) => this.autoVia.get(rel) === via : () => true)
5101
+ if (!this.persona(via)) this.aiEdits.clear()
4873
5102
  if (this.work?.state === 'working') this.setWork('done')
4874
5103
  this.workFromEdits = false
4875
- return { released }
4876
- }
4877
-
4878
- /** Releases one of our claims, or all of them with '*'. Resolves to the number released. */
4879
- async release (pattern = '*', via = null) {
4880
- return (await this.releaseReport(pattern, via)).released
4881
- }
4882
-
4883
- /**
4884
- * release, with what the relay said about it: { released, held?: [patterns someone waits for],
4885
- * branches?: [where it let go, when not this branch], coveredBy?, holder?, yours?: the folder or glob
4886
- * claim that covers a path that isn't a claim itself }.
4887
- */
4888
- async releaseReport (pattern = '*', via = null) {
4889
- if (this.quilt && this.quilt.id && this.quilt.layout === 3) return this.releaseInSeam(String(pattern || '*'), via)
4890
- const r = await this.conn.claimRequest({ op: 'release', pattern: String(pattern), ...this.as(via) })
4891
- if (r.released) this.noteActivity(`Released ${pattern === '*' ? 'all my claims' : pattern}`, { via })
4892
- const out = { released: r.released || 0 }
4893
- for (const k of ['held', 'branches', 'coveredBy', 'holder', 'yours']) if (r[k] !== undefined) out[k] = r[k]
4894
- return out
4895
- }
4896
-
4897
- /**
4898
- * releaseReport at layout 3, where claims are Seam's (seam-claims.js): this member lets go of theirs
4899
- * in Seam as themselves (seamMember), the claims the move made for them included, though the mover
4900
- * holds those in Seam (the relay says which: quilt-claims). One someone waits for is kept (`held`):
4901
- * Seam hands it on with a note instead.
4902
- */
4903
- async releaseInSeam (pattern = '*', via = null) {
4904
- if (!this.conn) throw new Error('not connected to the relay')
4905
- let asked
4906
- try { asked = await this.conn.claimRequest({ op: 'quilt-claims', ...this.as(via) }) } catch (err) {
4907
- // A relay from before 0.3.132 can't say whose the move's claims were: let go of nothing rather than someone else's.
4908
- throw new Error(`The relay could not say whose this session's claims are (${err.message}), so none was let go of. Try again once the relay is updated, or let go of one in Seam (seam unclaim <claim> --quilt ${this.quilt.slug || this.quilt.id}).`)
4909
- }
4910
- const { gone, ...r } = await releaseInSeam({ access: this.seamMember(), api: this.seamApiUrl ?? appSeamUrl(), quilt: this.quilt.id, asked, pattern })
4911
- if (gone.length) {
4912
- await this.conn.claimRequest({ op: 'quilt-released', ids: gone, ...this.as(via) }).catch(() => {})
4913
- this.noteActivity(`Released ${pattern === '*' ? 'all my claims' : pattern}`, { via })
4914
- }
4915
- return r
5104
+ return { released: 0 }
4916
5105
  }
4917
5106
 
4918
5107
  /**
@@ -4923,12 +5112,12 @@ export class Session extends EventEmitter {
4923
5112
  async boxes () {
4924
5113
  const text = (d) => (!d || d.skip || d.tooLarge ? null : d.binary ? { binary: true } : d.text)
4925
5114
  const out = []
4926
- for (const c of this.claims.values()) {
4927
- if (!c || !c.box || /[*?[]/.test(c.pattern) || !isSafeRelPath(c.pattern)) continue
5115
+ for (const c of this.boxed.values()) {
5116
+ if (!c || c.box === false || /[*?[]/.test(c.pattern) || !isSafeRelPath(c.pattern)) continue
4928
5117
  const rel = c.pattern
4929
5118
  const t = this.files.get(rel)
4930
5119
  const after = t ? t.toString() : this.blobs.has(rel) ? { binary: true } : null
4931
- const mine = this.ownClaim(c)
5120
+ const mine = this.isOwnBox(c)
4932
5121
  let before = null
4933
5122
  if (mine) {
4934
5123
  const base = this.boxBase.has(rel) ? this.boxBase.get(rel) : null
@@ -4939,7 +5128,7 @@ export class Session extends EventEmitter {
4939
5128
  } else {
4940
5129
  try { before = text(this.readDisk(rel)) } catch { before = null }
4941
5130
  }
4942
- out.push(boxEntry({ claim: c, mine, before, after }))
5131
+ out.push(boxEntry({ box: c, mine, before, after }))
4943
5132
  }
4944
5133
  return { on: this.boxesOn(), boxes: out.sort((a, b) => a.ts - b.ts || a.path.localeCompare(b.path)) }
4945
5134
  }
@@ -4952,19 +5141,13 @@ export class Session extends EventEmitter {
4952
5141
  if (!this.ownBox(p)) { notBoxed.push(p); continue }
4953
5142
  if (!this.conn) throw new Error('not connected to the relay')
4954
5143
  // 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'.
4955
- const r = await this.conn.claimRequest({ op: 'unbox', pattern: p, release: false })
5144
+ const r = await this.conn.boxRequest({ op: 'unbox', pattern: p, release: false })
4956
5145
  if (r.unboxed) { unpacked.push(p); this.boxFrom.delete(p) } else notBoxed.push(p)
4957
5146
  }
4958
5147
  if (unpacked.length) this.noteActivity(`Unpacked ${unpacked.join(', ')}`, { via })
4959
5148
  return { unpacked, notBoxed }
4960
5149
  }
4961
5150
 
4962
- /** The owner clears every claim held by someone who isn't in the session. Resolves to the number released. */
4963
- async clearInactiveClaims () {
4964
- const r = await this.conn.claimRequest({ op: 'clear-inactive' })
4965
- return r.released || 0
4966
- }
4967
-
4968
5151
  /**
4969
5152
  * Why we can't reach the relay (e.g. no session pass), or null once that's fixed.
4970
5153
  * Logged once per new reason, not on every retry, and shown in status.
@@ -4977,26 +5160,20 @@ export class Session extends EventEmitter {
4977
5160
  this.emit('status-changed')
4978
5161
  }
4979
5162
 
4980
- /** Takes the relay's claim list, logging what changed. */
4981
- setClaims (list) {
4982
- const was = this.claims
5163
+ /** Takes the relay's box list (its MSG_CLAIMS, which lists boxes only), and writes out what opened. */
5164
+ setBoxes (list) {
5165
+ const was = this.boxed
4983
5166
  const next = new Map()
4984
- for (const c of Array.isArray(list) ? list : []) if (c && typeof c.pattern === 'string' && typeof c.by === 'string') next.set(c.pattern, c)
4985
- if (this.ready) {
4986
- for (const [p, c] of next) {
4987
- const was = this.claims.get(p)
4988
- if (!this.ownClaim(c) && (!was || was.by !== c.by)) this.log(`🔒 ${c.by} claimed ${c.pattern}${c.note ? ` — ${c.note}` : ''}`)
4989
- }
4990
- for (const [p, c] of this.claims) if (!next.has(p) && !this.ownClaim(c)) this.log(`🔓 ${c.by} released ${p}`)
4991
- }
4992
- this.claims = next
4993
- try { fs.writeFileSync(path.join(this.stateDir, 'claims.json'), JSON.stringify([...next.values()])) } catch {}
4994
- // A box someone else held opened (committed, unpacked, handed on or released): its file reaches this folder now.
4995
- // (Also one that opened while this folder was away: its ghost is still on record.)
5167
+ // An older relay still sends claims: only boxes are kept, and nothing anyone holds is enforced here.
5168
+ 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)
5169
+ this.boxed = next
5170
+ try { fs.writeFileSync(path.join(this.stateDir, 'boxes.json'), JSON.stringify([...next.values()])) } catch {}
4996
5171
  // A box handed to us (our cloud AI stopped with it, server.js handBackCloudBoxes): our git may have it already.
4997
- if (this.ready && [...next].some(([p, c]) => c.box && c.handedFrom && this.ownClaim(c) && !(was.get(p) && this.ownClaim(was.get(p))))) this.scheduleStatusWrite()
5172
+ if (this.ready && [...next].some(([p, c]) => c.handedFrom && this.isOwnBox(c) && !(was.get(p) && this.isOwnBox(was.get(p))))) this.scheduleStatusWrite()
5173
+ // A box someone else held opened (committed, unpacked, opened by an edit): its file reaches this folder now.
5174
+ // (Also one that opened while this folder was away: its ghost is still on record.)
4998
5175
  if (this.ready) {
4999
- const opened = new Set([...was].filter(([, c]) => c.box && !this.ownClaim(c)).map(([p]) => p))
5176
+ const opened = new Set([...was].filter(([, c]) => !this.isOwnBox(c)).map(([p]) => p))
5000
5177
  for (const p of this.boxBase.keys()) opened.add(p)
5001
5178
  for (const p of opened) {
5002
5179
  if (this.boxedByOther(p)) continue // still someone else's box
@@ -5006,14 +5183,13 @@ export class Session extends EventEmitter {
5006
5183
  }
5007
5184
  if (this.ready) this.settleReleasedMerges()
5008
5185
  this.scheduleStatusWrite()
5009
- this.emit('claims', [...next.values()])
5186
+ this.emit('boxes', [...next.values()])
5010
5187
  }
5011
5188
 
5012
5189
  /**
5013
- * Our offline edits that waited only because someone held the file: once
5014
- * they let go, ours goes in if the session's version is still the one we
5015
- * started from (only we changed it). If it changed meanwhile, the two are
5016
- * never combined on their own: the record stays open for a person.
5190
+ * Our offline edits an older app held back because someone held the file (open 'claimed' records):
5191
+ * nobody holds files now (no-holds, 2026-11-13), so each goes in straight away through the normal
5192
+ * merge (autoSettle).
5017
5193
  */
5018
5194
  settleReleasedMerges () {
5019
5195
  // A file changed here several times while someone held it (a pull each time) has a record for each,
@@ -5032,7 +5208,7 @@ export class Session extends EventEmitter {
5032
5208
  const rec = recs[recs.length - 1]
5033
5209
  if (recs.some((r) => r.binary || r.theirsHash === null) || rec.oursDeleted) continue
5034
5210
  // A record anyone can write names any path: never one the session doesn't sync (.env, .git, ignored files).
5035
- if (!this.syncable(rec.path) || this.mergeHeldBy(rec) || this.writeRefusal(rec.path) || this.merging.has(rec.path)) continue
5211
+ if (!this.syncable(rec.path) || this.writeRefusal(rec.path) || this.merging.has(rec.path)) continue
5036
5212
  const theirs = this.sharedKey(rec.path)
5037
5213
  if (typeof theirs !== 'string' || theirs.startsWith('bin:')) continue
5038
5214
  const tried = `${recs.map((r) => r.id).join(',')}:${sha1(theirs)}`
@@ -5045,17 +5221,15 @@ export class Session extends EventEmitter {
5045
5221
  if (typeof ours !== 'string') continue
5046
5222
  const holder = rec.claimedBy || rec.others[0] || 'someone'
5047
5223
  try {
5048
- // Changed meanwhile: combined by Quilt (autoSettle's rule), the newer edit kept where both changed the same lines.
5049
- const oursNewer = rec.ts >= this.sessionEditedAt(rec.path)
5050
- const r = theirs === (base ?? '') ? { text: ours, lost: [] } : mergeAuto(base ?? '', ours, theirs, { oursNewer })
5051
- this.applyMerged(rec.path, r.text, `once ${holder} let go of it`)
5052
- for (const one of recs) updateMerge(this.bdoc, this.merges, one.id, { state: 'done', how: r.lost.length && !oursNewer ? 'theirs' : 'mine', resolvedBy: 'Quilt', reason: r.lost.length ? `Went in once ${holder} let go of it, merged by Quilt: the newer edit kept where both changed the same lines` : `Went in once ${holder} let go of it` }, LOCAL)
5053
- this.noteLostLines(rec.path, { by: holder, lost: r.lost, oursWon: oursNewer })
5224
+ // Ours goes in now: on its own when the session's version is still the one we started from, else merged as any other edit.
5225
+ if (theirs === (base ?? '')) this.applyMerged(rec.path, ours, 'held from before Quilt stopped holding files')
5226
+ else this.autoSettle({ rel: rec.path, base: base ?? null, ours, theirs, theirsBy: holder, disk, binary: false, via: null })
5227
+ for (const one of recs) updateMerge(this.bdoc, this.merges, one.id, { state: 'done', how: 'mine', resolvedBy: 'Quilt', reason: 'Went in: Quilt holds no files any more' }, LOCAL)
5054
5228
  } catch (err) {
5055
5229
  this.log(`could not combine ${rec.path}: ${err.message}`)
5056
5230
  continue
5057
5231
  }
5058
- this.log(`✅ ${holder} let go of ${rec.path}: your changes went in`)
5232
+ this.log(`✅ ${rec.path}: your changes held for ${holder} went in`)
5059
5233
  if (this.catchUp?.mine?.conflicts.includes(rec.path)) {
5060
5234
  const m = this.catchUp.mine
5061
5235
  m.conflicts = m.conflicts.filter((p) => p !== rec.path)
@@ -5065,32 +5239,92 @@ export class Session extends EventEmitter {
5065
5239
  }
5066
5240
  }
5067
5241
 
5068
- /** Last known claims, so they're enforced before the relay answers (or while offline). */
5069
- loadClaims () {
5070
- try {
5071
- for (const c of JSON.parse(fs.readFileSync(path.join(this.stateDir, 'claims.json'), 'utf8'))) this.claims.set(c.pattern, c)
5072
- } catch {}
5073
- }
5074
-
5075
- /**
5076
- * The claim that owns rel. The relay refuses overlapping claims, but a glob
5077
- * pair can start overlapping once a new file matches both; every client
5078
- * then picks the same owner: the earliest claim (ties broken by name, then
5079
- * pattern).
5080
- */
5081
- claimFor (rel) {
5082
- let owner = null
5083
- for (const c of this.claims.values()) {
5084
- if (!c || !globMatcher(c.pattern)(rel)) continue
5085
- if (!owner || c.ts < owner.ts || (c.ts === owner.ts && (c.by < owner.by || (c.by === owner.by && c.pattern < owner.pattern)))) owner = c
5086
- }
5087
- return owner
5242
+ /** Last known boxes, so someone else's unfinished work isn't written here before the relay answers (or while offline). */
5243
+ loadBoxes () {
5244
+ let list = null
5245
+ try { list = JSON.parse(fs.readFileSync(path.join(this.stateDir, 'boxes.json'), 'utf8')) } catch {}
5246
+ // A folder from before no-holds kept them with its claims (claims.json): the boxes stay, every claim goes.
5247
+ if (!list) { try { list = JSON.parse(fs.readFileSync(path.join(this.stateDir, 'claims.json'), 'utf8')) } catch {} }
5248
+ for (const c of Array.isArray(list) ? list : []) if (c && c.box === true && typeof c.pattern === 'string') this.boxed.set(c.pattern, c)
5249
+ try { fs.rmSync(path.join(this.stateDir, 'claims.json'), { force: true }) } catch {}
5088
5250
  }
5089
5251
 
5090
5252
  // ------------------------------------------------------------ merges --
5091
5253
 
5092
5254
  mergeList () { return readMerges(this.merges) }
5093
5255
 
5256
+ // ------------------------------------------------------ held conflicts --
5257
+
5258
+ /** Every held conflict in the session (held.js), open ones first, without their texts (status goes out often). */
5259
+ heldList () {
5260
+ if (!this.doc) return []
5261
+ return readHeld(this.doc.getMap(HELD_MAP)).map(({ result, mine, ...r }) => r)
5262
+ }
5263
+
5264
+ /** The open ones, as the top of every tool answer says them to `me` ('' with none). */
5265
+ heldNotice (me = this.name) { return this.doc ? renderHeld(this.heldList(), { me }) : '' }
5266
+
5267
+ /** The session's stale_write_minutes: { minutes } (the owner's setting, else 15; 0: off). */
5268
+ staleWrite () { return { minutes: staleWriteMinutes(this.doc, this.members) } }
5269
+
5270
+ /** The owner sets the session's stale_write_minutes (0 turns the stale-write check off). */
5271
+ setStaleWrite (minutes) {
5272
+ if (!this.access || !this.access.owner) throw new Error('Only the session\'s owner sets how long a write may not remove lines someone else added.')
5273
+ return { minutes: setStaleWriteMinutes(this.doc, { minutes, by: this.name }) }
5274
+ }
5275
+
5276
+ /**
5277
+ * quilt_resolve_merge: settles one held conflict, named by its id or path. `how`: 'theirs' drops the
5278
+ * held lines (the file stays as it is), 'mine' puts them over the shared ones (merged with whatever
5279
+ * changed since), 'edited' says the resolved file is already written. Any member may resolve any
5280
+ * one; resolving one already resolved says so and changes nothing. { text, record, already }.
5281
+ */
5282
+ resolveHeld ({ ref, how, via = null }) {
5283
+ const map = this.doc.getMap(HELD_MAP)
5284
+ const rec = findHeld(map, ref)
5285
+ if (!rec) throw new Error(`There is no held conflict for ${ref || 'that'}: quilt_status lists the open ones.`)
5286
+ const who = this.actorName ? this.actorName(via) : this.name
5287
+ if (rec.state === 'resolved') return { already: true, record: rec, text: `${rec.path} (id ${rec.id}) was already resolved${rec.resolvedBy ? ` by ${rec.resolvedBy}` : ''}${rec.how ? ` ("${rec.how}")` : ''}. Nothing changed.` }
5288
+ let wrote = ''
5289
+ if (how === 'mine') wrote = this.applyHeldMine(rec)
5290
+ const r = settleHeld(this.doc, map, rec.id, { how, by: who }, LOCAL)
5291
+ if (r.already) return { already: true, record: r.record, text: `${rec.path} (id ${rec.id}) was already resolved by ${r.record.resolvedBy || 'someone'}. Nothing changed.` }
5292
+ const said = how === 'theirs' ? `the held lines are dropped and ${rec.path} stays as it is` : how === 'mine' ? `the held lines went into ${rec.path}${wrote ? ` (${wrote})` : ''}` : `${rec.path} is taken as you wrote it`
5293
+ this.log(`⚖️ ${who} resolved the held conflict in ${rec.path} ("${how}")`)
5294
+ return { already: false, record: r.record, text: `Resolved ${rec.path} (id ${rec.id}): ${said}.` }
5295
+ }
5296
+
5297
+ /** Writes a held record's lines over the shared file, here: only on the branch or square it was held on. Returns a few words on what changed. */
5298
+ applyHeldMine (rec) {
5299
+ const dir = this.heldDir(rec.id)
5300
+ const local = (name) => { try { return fs.readFileSync(path.join(dir, name)) } catch { return null } }
5301
+ const onSquare = this.inSquare && this.inSquare.square
5302
+ const elsewhere = rec.where.square ? rec.where.square !== onSquare : rec.where.branch ? (this.inSquare || rec.where.branch !== this.branchKey()) : false
5303
+ if (elsewhere) throw new Error(`${rec.path} was held on ${rec.where.square ? `another square (sq:${rec.where.square.slice(-8)})` : `branch ${rec.where.branch}`}, not the one this folder is on: resolve it "mine" from a folder there, or write the file yourself and resolve it "edited".`)
5304
+ const abs = resolveInside(this.root, rec.path)
5305
+ if (rec.kind === 'binary') {
5306
+ const buf = local('mine')
5307
+ if (!buf) throw new Error(`${rec.path}'s held version is only on ${rec.by}'s computer: ask them, or write the file yourself and resolve it "edited".`)
5308
+ fs.mkdirSync(path.dirname(abs), { recursive: true })
5309
+ fs.writeFileSync(abs, buf)
5310
+ if (!this.inSquare) this.ingest(rec.path)
5311
+ return 'their version of the file'
5312
+ }
5313
+ const mine = rec.mine ?? (local('mine') ? local('mine').toString('utf8') : null)
5314
+ const result = rec.result ?? (local('result') ? local('result').toString('utf8') : null)
5315
+ if (typeof mine !== 'string') throw new Error(`${rec.path}'s held lines are only on ${rec.by}'s computer (the file is too big to share them): ask them, or write the file yourself and resolve it "edited".`)
5316
+ let current = null
5317
+ if (this.inSquare) { try { current = fs.readFileSync(abs, 'utf8') } catch {} } else current = this.files.get(rec.path)?.toString() ?? null
5318
+ const text = applyMine({ mine, result }, current)
5319
+ if (this.inSquare) {
5320
+ // The folder's block takes it in as this member's edit (live-block.js scan), as a resolution: no stale-write check.
5321
+ this.liveRules().trust(rec.path, text)
5322
+ fs.mkdirSync(path.dirname(abs), { recursive: true })
5323
+ fs.writeFileSync(abs, text)
5324
+ } else this.applyMerged(rec.path, text, 'resolving a held conflict ("mine")')
5325
+ return `${rec.hunks.length + (rec.more || 0)} change(s)`
5326
+ }
5327
+
5094
5328
  /** Where this machine keeps a merge's base, ours and theirs (and PROMPT.md for Send to…). */
5095
5329
  mergeDir (id) { return path.join(this.stateDir, 'merges', id) }
5096
5330
 
@@ -5104,17 +5338,8 @@ export class Session extends EventEmitter {
5104
5338
  return { ours, base, theirs }
5105
5339
  }
5106
5340
 
5107
- /** Who else holds a merge's file right now, or null: settling it (or sending it to an AI) writes the file. */
5108
- mergeHeldBy (rec) {
5109
- const claim = this.claimFor(rec.path)
5110
- return claim && !this.ownClaim(claim) ? claim : null
5111
- }
5112
-
5113
- /** A merge as status shows it: without its texts, with who holds the file and whether we asked for it. */
5114
- mergeStatus ({ ours, base, ...m }) {
5115
- const claim = m.state === 'done' ? null : this.mergeHeldBy(m)
5116
- return claim ? { ...m, heldBy: claim.of || claim.by, asked: (claim.queue || []).some((r) => r.by === this.name) } : m
5117
- }
5341
+ /** A merge as status shows it: without its texts. */
5342
+ mergeStatus ({ ours, base, ...m }) { return m }
5118
5343
 
5119
5344
  // ------------------------------------------------------------ AI feed --
5120
5345
 
@@ -5283,8 +5508,8 @@ export class Session extends EventEmitter {
5283
5508
  const was = this.agentState?.status
5284
5509
  this.agentState = state ? { tool: state.tool || null, status: state.status || 'idle', ...(state.reason ? { reason: state.reason } : {}), ...(state.notes ? { notes: state.notes } : {}) } : null
5285
5510
  this.publishAgentState()
5286
- // Our AI finished its turn: the files Quilt claimed for it while it worked are free again.
5287
- if (was === 'working' && this.agentState?.status !== 'working' && this.autoClaims.size) this.releaseAutoClaims().catch(() => {})
5511
+ // Our AI finished its turn: its edits no longer say it is working.
5512
+ if (was === 'working' && this.agentState?.status !== 'working') this.aiEdits.clear()
5288
5513
  }
5289
5514
 
5290
5515
  publishAgentState () {
@@ -5304,7 +5529,7 @@ export class Session extends EventEmitter {
5304
5529
 
5305
5530
  /**
5306
5531
  * Every shared path with who last edited it (from activity and live
5307
- * presence) and the claim covering it. Read from the shared doc.
5532
+ * presence) and the box on it (someone's unfinished work). Read from the shared doc.
5308
5533
  */
5309
5534
  tree () {
5310
5535
  const edited = new Map()
@@ -5319,11 +5544,11 @@ export class Session extends EventEmitter {
5319
5544
  const editing = id === this.doc.clientID ? Object.fromEntries(this.myEdits) : (st.editing || {})
5320
5545
  for (const [p, ts] of Object.entries(editing)) note(p, st.name, ts)
5321
5546
  }
5322
- // `active` is false when whoever holds it isn't in the session (older relays don't say: active).
5323
- // Held as people see it: an older app's AI session ("Dana · login", of: Dana) is its person.
5324
- 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, ...(c.box ? { box: true } : {}), active: c.active !== false, ...(typeof c.activeAt === 'number' ? { activeAt: c.activeAt } : {}), queue: Array.isArray(c.queue) ? c.queue.map((r) => ({ id: r.id, path: r.path, by: r.of || r.by, title: r.title, description: r.description || '', task: r.task || '', ts: r.ts })) : [] })
5325
- const claimFor = (p) => {
5326
- const c = this.claimFor(p)
5547
+ // `active` is false when whoever boxed it isn't in the session (older relays don't say: active).
5548
+ // Shown as people see it: an older app's AI session ("Dana · login", of: Dana) is its person.
5549
+ 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 } : {}) })
5550
+ const boxOf = (p) => {
5551
+ const c = this.boxAt(p)
5327
5552
  return c ? shown(c) : null
5328
5553
  }
5329
5554
  // Files that are GitHub's version, not edited in the session since (the relay marks them: relay-sync.js markFromGithub).
@@ -5336,16 +5561,15 @@ export class Session extends EventEmitter {
5336
5561
  const listed = square ? new Set(square.keys()) : this.diffForm ? new Set([...this.sharedPaths(), ...[...this.gitOnly.keys()].filter((p) => this.followsGit(p) && this.onDisk(p))]) : this.sharedPaths()
5337
5562
  for (const p of listed) {
5338
5563
  if (!isSafeRelPath(p)) continue
5339
- if (square) { out.push({ path: p, binary: square.get(p), edited: edited.get(p) || null, claim: claimFor(p), github: null }); continue }
5564
+ if (square) { out.push({ path: p, binary: square.get(p), edited: edited.get(p) || null, box: boxOf(p), github: null }); continue }
5340
5565
  const blob = this.blobs.get(p)
5341
- 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, claim: claimFor(p), github: fromGithub(p) })
5566
+ 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) })
5342
5567
  }
5343
5568
  out.push(...this.chatFileEntries())
5344
5569
  out.sort((a, b) => a.path.localeCompare(b.path))
5345
5570
  return {
5346
5571
  files: out,
5347
- // Claims on folders or globs that don't match a file yet still show up.
5348
- claims: [...this.claims.values()].map(shown)
5572
+ boxes: [...this.boxed.values()].map(shown)
5349
5573
  }
5350
5574
  }
5351
5575
 
@@ -5542,20 +5766,40 @@ export class Session extends EventEmitter {
5542
5766
  // The session's call: whether the owner has transcripts on, and the agents in it.
5543
5767
  voice: { transcribe: transcribeSetting(this.doc, this.members).on, agents: callAgents(this.doc, this.conn ? this.liveCall() : '', this.members) },
5544
5768
  peers,
5545
- claims: [...this.claims.values()].sort((a, b) => a.ts - b.ts),
5769
+ boxes: [...this.boxed.values()].sort((a, b) => a.ts - b.ts),
5546
5770
  tasks: this.taskList(),
5547
5771
  // Without the texts (up to 400 KB a record): status goes out on every
5548
5772
  // change. The full records are at GET /merges and the app's merges route.
5549
5773
  merges: this.mergeList().map((m) => this.mergeStatus(m)),
5774
+ // Held conflicts (held.js): every open one in the session, whoever's, until someone resolves it.
5775
+ held: this.heldList(),
5776
+ // How long a write may not remove lines someone else added (the owner's stale_write_minutes; 0: off).
5777
+ staleWriteMinutes: staleWriteMinutes(this.doc, this.members),
5550
5778
  catchUp: this.catchUp,
5551
5779
  activity: this.activity.toArray().slice(-30),
5552
5780
  changes: this.changes().people.map((p) => ({ ...p, files: p.files.slice(0, 10), pulled: p.pulled && { ...p.pulled, files: p.pulled.files.slice(0, 10) } })),
5553
5781
  chat: this.messages({ limit: 20, markRead: false }),
5554
5782
  unread: this.unreadCount(),
5555
- fileCount: this.files.size + this.blobs.size
5783
+ fileCount: this.sharedFileCount()
5556
5784
  }
5557
5785
  }
5558
5786
 
5787
+ /**
5788
+ * How many files the session shares here. Following a square in place, the folder is the square's live
5789
+ * copy (squareFiles), never the frozen branch document (2026-11-14: quilt_status said 4 with 5), looked
5790
+ * at no more than every few seconds.
5791
+ */
5792
+ sharedFileCount () {
5793
+ if (!this.inSquare) return this.files.size + this.blobs.size
5794
+ const now = Date.now()
5795
+ if (!this.squareCount || now - this.squareCount.at > 3000) {
5796
+ let n = 0
5797
+ try { n = (this.squareFiles() || new Map()).size } catch {}
5798
+ this.squareCount = { at: now, n }
5799
+ }
5800
+ return this.squareCount.n
5801
+ }
5802
+
5559
5803
  scheduleStatusWrite () {
5560
5804
  if (this.statusTimer || !this.ready) return
5561
5805
  this.statusTimer = setTimeout(() => {
@@ -5566,11 +5810,8 @@ export class Session extends EventEmitter {
5566
5810
 
5567
5811
  async stop () {
5568
5812
  this.ready = false
5569
- clearInterval(this.autoClaimTimer)
5813
+ clearInterval(this.editQuietTimer)
5570
5814
  clearInterval(this.personaTimer)
5571
- if (this.autoClaims.size && this.conn && !this.stopped) {
5572
- await Promise.race([this.releaseAutoClaims(), new Promise((r) => setTimeout(r, 2000))])
5573
- }
5574
5815
  this.stopped = true
5575
5816
  clearInterval(this.retryTimer)
5576
5817
  if (this.watcher) await closeWatcher(this.watcher)
@@ -5592,6 +5833,7 @@ export class Session extends EventEmitter {
5592
5833
  clearTimeout(this.typingTimer)
5593
5834
  clearTimeout(this.typingExpiryTimer)
5594
5835
  if (this.conn) this.conn.close()
5836
+ this.overwritten.close()
5595
5837
  this.saveState()
5596
5838
  this.emit('stopped')
5597
5839
  await new Promise((r) => setTimeout(r, 100))