heyquilt 0.3.170 → 0.3.171

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 (61) hide show
  1. package/RELEASES.md +22 -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 +91 -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 +592 -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 +173 -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 +650 -554
  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 +391 -51
  42. package/src/status.js +8 -12
  43. package/src/textdiff.js +54 -0
  44. package/src/turn-sync-plan.js +6 -18
  45. package/src/turn-sync.js +28 -21
  46. package/src/ui/agent-guide.js +13 -13
  47. package/src/ui/app.css +19 -40
  48. package/src/ui/boxes.js +8 -16
  49. package/src/ui/common.js +1 -1
  50. package/src/ui/fileview.js +11 -15
  51. package/src/ui/loom-model.js +18 -16
  52. package/src/ui/loom.css +1 -2
  53. package/src/ui/loom.js +6 -6
  54. package/src/ui/rail-model.js +25 -64
  55. package/src/ui/rail.js +48 -60
  56. package/src/ui/seam-model.js +39 -3
  57. package/src/ui/session.js +36 -54
  58. package/src/ui/tree.js +22 -129
  59. package/src/ui-server.js +2 -6
  60. package/src/release-words.js +0 -18
  61. 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,19 @@ 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 } from './base-pick.js'
58
+ import { HELD_MAP, SETTINGS_MAP, readHeld, findHeld, settleHeld, staleWriteMinutes, setStaleWriteMinutes, renderHeld, heldLandingNote } from './held.js'
56
59
  import { RELAY_NAME as RELAY_BY, isRelay } from './ui/chat.js'
57
60
  import { cleanTyping, TYPING_MS, AGENT_TYPING_MS } from './ui/chat.js'
58
61
  import { DEFAULT_KEY } from './branchdocs.js'
@@ -113,6 +116,7 @@ const CLASH_RECORDS = 100
113
116
  const KEEP_DONE_COMMITS = 100 // finished commit requests kept, newest (the board shows which task's work was committed)
114
117
  const COLORS = ['#4f4fa0', '#3b6a9a', '#4a7a45', '#855a9c', '#a8701c', '#2e7a80', '#9c4f6b']
115
118
  const RECENT_MS = 2 * 60 * 1000
119
+ const RECENT_WRITER_MS = 15 * 60 * 1000 // quilt_before_edit shows who wrote a file this recently (presence, never a hold)
116
120
 
117
121
  /**
118
122
  * A peer's edits from its presence that are still recent, newest first. Its presence keeps its last
@@ -130,10 +134,8 @@ function processAlive (pid) {
130
134
  try { process.kill(pid, 0); return true } catch (err) { return err.code === 'EPERM' }
131
135
  }
132
136
  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
137
+ // "Working" that only our AI's edits said lapses once its files have been quiet this long (forgetQuietEdits).
138
+ const EDIT_QUIET_MS = 10 * 60 * 1000
137
139
  const NOTICE_CAP = 20
138
140
  const CATCH_UP_KEEP_MS = 3 * 24 * 60 * 60 * 1000 // an unread "while you were away" goes after this
139
141
  const CATCH_UP_FILES = 200 // paths kept per person in it
@@ -171,8 +173,6 @@ const CATCHER_WAITING = 'another member is bringing these commits in'
171
173
  const RELAY_WAITING = 'the relay is bringing these commits into the session'
172
174
  // How long a git pull's settle waits for the relay to be at the pulled commit before sharing it as before (planSettle).
173
175
  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
176
  const SETTLE_BOXES_MS = 1500 // after an edit to one of our boxed files: does git have it as the session does now?
177
177
  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
178
  const INDEX_WATCH_MS = 8000 // after a bring-in, how long the index is checked against what another git may write back
@@ -202,8 +202,24 @@ function notSharedLines (list) {
202
202
  /** What a move says when it made the room's read token again (server.js freshReadToken). */
203
203
  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
204
 
205
+ /** Writes `data` to `abs` and returns the file's stat as the write left it (taken before it is closed). */
206
+ // Quilt's own file in the making (writeOver, rescueSave): never synced.
207
+ const QUILT_TEMP = /^\..+\.quilt-(tmp|save)$/
208
+ // A file emptied this recently may be a save half done (truncated, not written yet): looked at again first.
209
+ const SETTLE_MS = 250
210
+
211
+ function writeAndStat (abs, data, mode = undefined) {
212
+ const fd = fs.openSync(abs, 'w', mode)
213
+ try {
214
+ const buf = typeof data === 'string' ? Buffer.from(data, 'utf8') : data
215
+ let off = 0
216
+ while (off < buf.length) off += fs.writeSync(fd, buf, off, buf.length - off)
217
+ return fs.fstatSync(fd)
218
+ } finally { fs.closeSync(fd) }
219
+ }
220
+
205
221
  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 }) {
222
+ 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
223
  super()
208
224
  // 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
225
  this.apiAuth = apiAuth
@@ -269,9 +285,10 @@ export class Session extends EventEmitter {
269
285
  this.transfers = 0 // large uploads and downloads running
270
286
  this.transferQueue = [] // resolvers waiting for one to finish
271
287
  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()
288
+ // Boxes (someone's unfinished work on one file, kept out of other folders until it's committed):
289
+ // path -> { by, pattern, note, ts, box: true }. The relay keeps them, outside the shared doc; we keep
290
+ // the last list. Quilt holds no files (no-holds, 2026-11-13): a box never stops anyone writing.
291
+ this.boxed = new Map()
275
292
  this.chat = this.doc.getArray('chat') // { by, text, ts }
276
293
  this.activity = this.doc.getArray('activity') // { by, path, kind, detail, ts }
277
294
  this.agentFeed = this.doc.getArray('agentFeed') // { id, by, tool, conv, kind, text, ts, summary?, title? }
@@ -287,9 +304,8 @@ export class Session extends EventEmitter {
287
304
  this.aiSent = [] // [{ via, targets, text, ts }]
288
305
  // Each AI session working through this app (its `quilt mcp`, by its `via` id) under a name of
289
306
  // 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.
307
+ // ppid, named, inbox, seenAt, touchedAt }. Its messages, inbox and duties are its own.
291
308
  this.personas = new Map()
292
- this.autoVia = new Map() // a file claimed for one AI session as it edited -> that session's via
293
309
  // The agent's webhook subscription (webhooks.js), kept in .quilt/webhook.json: inbox events are POSTed there.
294
310
  this.webhook = null
295
311
  this.webhookTransport = webhookTransport // { fetch, delays } for tests
@@ -309,29 +325,31 @@ export class Session extends EventEmitter {
309
325
  // ages out on our clock, not theirs.
310
326
  this.typing = {}
311
327
  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)
328
+ // Files our AI changed (see boxEdit): path -> when it last did. Forgotten once quiet for editQuietMs
329
+ // (forgetQuietEdits), and "working" that only these edits said lapses with them.
330
+ this.aiEdits = new Map()
331
+ this.boxing = new Set() // our files whose box is on its way to the relay (boxEdit)
316
332
  // Ghosts: files someone else has boxed, not written here. For each, this folder's version from before
317
333
  // the box ({ text } or { b64 }; null: it wasn't there), put back when an edit here is refused. Kept in state.json.
318
334
  this.boxBase = new Map()
319
335
  // Our boxes: what the session had before the edit that opened each (null: no file). Back to that, the box holds
320
336
  // nothing of ours (our edit undone, or taken back) and opens like a committed one.
321
337
  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
338
+ this.editQuietMs = editQuietMs
325
339
  // Whether our AI takes work from the board by itself (tasks.js PICKUP_MODES); null: this person's setting.
326
340
  this.aiTasks = aiTasks
327
341
  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()
342
+ this.editQuietTimer = setInterval(() => this.forgetQuietEdits(), Math.max(50, Math.min(60_000, Math.floor(editQuietMs / 3))))
343
+ if (this.editQuietTimer.unref) this.editQuietTimer.unref()
330
344
  // What this person's AI should hear next time it talks to Quilt (an edit of its that was undone).
331
345
  this.notices = []
332
346
 
333
347
  this.ig = loadIgnore(this.root)
334
348
  this.lastKnown = new Map() // path -> text content, or "bin:<sha1>"
349
+ this.relayWriting = new Set() // paths with a live write at the relay, not answered yet (relayIngest)
350
+ this.relayAgain = new Set() // of those, the ones saved again meanwhile: taken in once the answer is here
351
+ this.relayLocal = new Set() // paths the relay asked to be edited here as before (its answer's `fallback`), once
352
+ this.overwritten = new RecentTexts() // the texts a partner's change was lately written over here: a save's possible base (base-pick.js)
335
353
  // path -> sha1 of lastKnown when state.json was last saved (null: a state file from before this was kept).
336
354
  this.known = null
337
355
  // path -> why the shared version could not be written. Tried again by
@@ -344,7 +362,7 @@ export class Session extends EventEmitter {
344
362
  this.reconcileTimer = null
345
363
  this.ready = false
346
364
  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)
365
+ this.settleTried = new Set() // held merges from before no-holds already tried against a session version (id:sha1)
348
366
  this.lastActivityPush = new Map()
349
367
  this.warnedLarge = new Set()
350
368
  this.agents = new Set()
@@ -407,7 +425,6 @@ export class Session extends EventEmitter {
407
425
  this.upstreamPoll = null
408
426
  this.upstreamSaid = '' // the advice last given, so it's given once per state
409
427
  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
428
  this.upstreamDeferred = null // the commit this folder let another member's folder bring in first
412
429
  this.clashAbsent = null // { task, name, since }: a clash task's assignee seen gone from the branch
413
430
  this.clashWait = null // { sha, since }: since when this folder has waited for the first in line to write the clash task
@@ -602,7 +619,7 @@ export class Session extends EventEmitter {
602
619
  this.joinedEmpty = !hadState && !walk(this.root, this.ig).some((rel) => this.syncable(rel))
603
620
  // 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
621
  this.gitAside = hasGitDir(this.root) ? null : gitAsideOf(this.root)
605
- if (hadState) this.loadClaims()
622
+ if (hadState) this.loadBoxes()
606
623
  // The branch whose square this folder follows: the checkout's branch name, the set-aside note's, else the room's default.
607
624
  this.branch = headBranch(this.root) || (this.gitAside && this.gitAside.branch) || DEFAULT_KEY
608
625
  // The form saved is the saved branch's; another branch's is the relay's to say when it is joined.
@@ -639,7 +656,7 @@ export class Session extends EventEmitter {
639
656
  this.conn.on('fatal', (err) => this.emit('fatal', err))
640
657
  this.conn.on('pass', (p) => this.adoptPass(p))
641
658
  this.conn.on('problem', (msg) => this.setRelayProblem(msg))
642
- this.conn.on('claims', (list) => this.setClaims(list))
659
+ this.conn.on('boxes', (list) => this.setBoxes(list))
643
660
  this.conn.on('access', (a) => this.setAccess(a))
644
661
  this.conn.on('members', (m) => this.setMembers(m))
645
662
  this.conn.on('branches', (list) => this.setBranches(list))
@@ -911,6 +928,10 @@ export class Session extends EventEmitter {
911
928
  this.scheduleStatusWrite()
912
929
  })
913
930
  this.taskComments.observe(() => this.scheduleStatusWrite())
931
+ // Held conflicts (held.js): the app and quilt_status show every open one as it comes and goes.
932
+ this.doc.getMap(HELD_MAP).observe(() => { this.scheduleStatusWrite(); this.emit('held', this.heldList()) })
933
+ // The owner's stale_write_minutes (held.js): Session settings and the CLI show it as it changes.
934
+ this.doc.getMap(SETTINGS_MAP).observe(() => this.scheduleStatusWrite())
914
935
  this.agentFeed.observe((ev) => {
915
936
  const added = []
916
937
  for (const item of ev.changes.added) for (const e of item.content.getContent()) if (e && e.id) added.push(e)
@@ -1091,7 +1112,7 @@ export class Session extends EventEmitter {
1091
1112
  }
1092
1113
 
1093
1114
  syncable (rel) {
1094
- return isSafeRelPath(rel) && !isIgnored(this.ig, rel)
1115
+ return isSafeRelPath(rel) && !isIgnored(this.ig, rel) && !QUILT_TEMP.test(path.posix.basename(rel))
1095
1116
  }
1096
1117
 
1097
1118
  /**
@@ -1284,11 +1305,8 @@ export class Session extends EventEmitter {
1284
1305
  const ours = disk ? disk.key : null // re-read: it may have changed again before the relay synced
1285
1306
  const theirs = this.sharedKey(rel)
1286
1307
  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
1308
  const pulled = via === 'pull'
1291
- if (theirs === base && !claimedByOther) { release(); return this.ingest(rel, { pulled }) ? 'pushed' : null } // nobody else touched it
1309
+ if (theirs === base) { release(); return this.ingest(rel, { pulled }) ? 'pushed' : null } // nobody else touched it
1292
1310
  if (ours === theirs || (ours === null && theirs === undefined)) {
1293
1311
  release()
1294
1312
  if (ours === null) this.lastKnown.delete(rel); else this.lastKnown.set(rel, ours)
@@ -1303,7 +1321,6 @@ export class Session extends EventEmitter {
1303
1321
  return null
1304
1322
  }
1305
1323
  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
1324
  if (binary || ours === null || theirs === undefined) return this.autoSettle({ rel, base, ours, theirs, theirsBy, disk, binary, via })
1308
1325
  const { text, conflicts } = merge3(base || '', ours, theirs)
1309
1326
  // Ours already has the session's change in it (git combined them here: a stash popped over a pull):
@@ -1349,21 +1366,18 @@ export class Session extends EventEmitter {
1349
1366
 
1350
1367
  /**
1351
1368
  * 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'.
1369
+ * itself (Seam's 07 "Conflicts in the live state", ruling 2026-11-13). Lines only one side changed
1370
+ * are kept; where both changed the same lines nobody wins: the session's version, which landed
1371
+ * first, stays, and ours there is held for this writer (or any AI) to resolve (held.js); a binary
1372
+ * both changed keeps the session's, with ours held; an edit beats a deletion. Ours is kept too
1373
+ * (the record, .quilt/merges/<id>/). Returns 'merged'.
1356
1374
  */
1357
1375
  autoSettle ({ rel, base, ours, theirs, theirsBy, disk, binary, via = null }) {
1358
1376
  const release = () => this.merging.delete(rel)
1359
1377
  const pulled = via === 'pull'
1360
1378
  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
1379
  const text = (k) => (typeof k === 'string' && !k.startsWith('bin:') ? k : null)
1366
- const keep = ({ how, reason, lost = [] }) => {
1380
+ const keep = ({ how, reason }) => {
1367
1381
  try {
1368
1382
  const rec = openMerge(this.bdoc, this.merges, {
1369
1383
  path: rel, by: this.name, byId: this.myKey(), others: by ? [by] : [], kind: 'conflict',
@@ -1374,8 +1388,8 @@ export class Session extends EventEmitter {
1374
1388
  this.writeMergeFiles(rec.id, { base, ours, theirs, disk })
1375
1389
  updateMerge(this.bdoc, this.merges, rec.id, { state: 'done', how, resolvedBy: 'Quilt', reason: rec.reason }, LOCAL)
1376
1390
  } catch {}
1377
- this.noteLostLines(rel, { by, lost, oursWon: how === 'mine' })
1378
1391
  }
1392
+ const where = { branch: this.branchKey() }
1379
1393
  // An edit beats a deletion: nothing anyone wrote is thrown away.
1380
1394
  if (ours === null) {
1381
1395
  release()
@@ -1392,41 +1406,38 @@ export class Session extends EventEmitter {
1392
1406
  this.log(`🧵 ${rel}: ${by || 'the session'} deleted it, but you changed it, so it stays`)
1393
1407
  return 'merged'
1394
1408
  }
1409
+ // Ours stays on this folder's disk under .quilt (keepHeldLocal), for resolving it "mine".
1410
+ const holdWhole = (kind) => {
1411
+ try {
1412
+ 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 })
1413
+ 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) }
1414
+ 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}).`)
1415
+ } catch (err) { this.log(`could not hold your version of ${rel}: ${err.message}`) }
1416
+ // ours is set aside (the record, .quilt/merges/<id>/): the session's version comes back to disk.
1417
+ this.lastKnown.set(rel, ours)
1418
+ this.tryWrite(rel)
1419
+ }
1395
1420
  if (binary) {
1396
1421
  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`)
1422
+ keep({ how: 'theirs', reason: `Both changed it: ${by || 'the session'}'s version, which landed first, stays; yours is held` })
1423
+ holdWhole('binary')
1424
+ this.log(`⚖️ ${rel}: both changed it; ${by || 'the session'}'s version stays and yours is held (quilt_resolve_merge)`)
1400
1425
  return 'merged'
1401
1426
  }
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 })
1427
+ // No common version (git couldn't read it, or both made the file): nothing lines up to combine.
1428
+ if (typeof base !== 'string') {
1429
+ release()
1430
+ keep({ how: 'theirs', reason: `Both made it: ${by || 'the session'}'s version stays; yours is held` })
1431
+ holdWhole('lines')
1432
+ return 'merged'
1433
+ }
1434
+ const r = this.liveRules().write({ doc: this.bdoc, where, path: rel, base, ours, theirs, by: this.name, byId: this.myKey(), others: by ? [by] : [] })
1435
+ 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
1436
  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 })
1437
+ 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
1438
  return 'merged'
1410
1439
  }
1411
1440
 
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
1441
  /** Writes a merged text to the shared doc and the disk as one edit of ours (`pulled`: one a git pull brought). */
1431
1442
  applyMerged (rel, text, detail, { pulled = false } = {}) {
1432
1443
  const abs = resolveInside(this.root, rel)
@@ -1446,48 +1457,6 @@ export class Session extends EventEmitter {
1446
1457
  this.log(`🧵 merged ${rel} ${detail}`)
1447
1458
  }
1448
1459
 
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
1460
  /** Keeps the three versions of a merge on this machine, for Send to… and for files too big for the record. */
1492
1461
  writeMergeFiles (id, { base, ours, theirs, disk = null }) {
1493
1462
  if (!id) return
@@ -1605,7 +1574,7 @@ export class Session extends EventEmitter {
1605
1574
  * reason not to use it. `outside`: a parent is a link leading out of the
1606
1575
  * project, so the file is never read (it may be anyone's).
1607
1576
  */
1608
- readDisk (rel) {
1577
+ readDisk (rel, { settle = false } = {}) {
1609
1578
  let abs
1610
1579
  try { abs = resolveInside(this.root, rel) } catch { return { skip: true, outside: true } }
1611
1580
  let st
@@ -1614,6 +1583,15 @@ export class Session extends EventEmitter {
1614
1583
  if (st.size > MAX_STORED_BINARY_BYTES) return { tooLarge: true }
1615
1584
  const exec = process.platform !== 'win32' && !!(st.mode & 0o111)
1616
1585
  const buf = fs.readFileSync(abs)
1586
+ // `settle` (taking it in, or writing over it): being written as it was read (it changed during the read, or
1587
+ // reads empty just after being emptied, as a save that truncates first does) is `unsettled`, looked at again
1588
+ // shortly, never taken in half-written.
1589
+ let again = null
1590
+ if (settle) { try { again = fs.lstatSync(abs) } catch {} }
1591
+ const known = this.lastKnown.get(rel)
1592
+ const unsettled = settle && (!again || again.size !== st.size || again.mtimeMs !== st.mtimeMs || buf.length !== st.size ||
1593
+ (buf.length === 0 && typeof known === 'string' && known.length > 0 && Date.now() - st.mtimeMs < SETTLE_MS))
1594
+ if (unsettled) return { unsettled: true, mtime: st.mtimeMs }
1617
1595
  if (looksBinary(buf)) {
1618
1596
  if (buf.length > MAX_BINARY_BYTES && this.largeFilesOff) return { tooLarge: true }
1619
1597
  const hash = sha1(buf)
@@ -1708,7 +1686,6 @@ export class Session extends EventEmitter {
1708
1686
  if (q.read_token) lines.push(readTokenLine(q.read_token))
1709
1687
  if (q.large) lines.push(largeLine(q.large))
1710
1688
  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
1689
  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
1690
  lines.push(...notSharedLines(q.not_shared))
1714
1691
  const moved = Object.keys(q.tasks || {}).length
@@ -1855,7 +1832,7 @@ export class Session extends EventEmitter {
1855
1832
  else {
1856
1833
  for (const rel of new Set([...walk(this.root, this.ig), ...this.lastKnown.keys()])) {
1857
1834
  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}`) }
1835
+ try { this.ingest(rel, { same: true, box: !!(writers && writers.get(rel) === this.name) }) } catch (err) { this.log(`could not sync ${rel}: ${err.message}`) }
1859
1836
  }
1860
1837
  }
1861
1838
  this.scanDisk({ baseline: true })
@@ -1946,10 +1923,8 @@ export class Session extends EventEmitter {
1946
1923
  const texts = typeof e.before === 'string' || typeof e.after === 'string' ? { before: e.before, after: e.after } : undefined
1947
1924
  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
1925
  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)
1926
+ // 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.
1927
+ if (e.kind !== 'deleted' && this.aiMayBeEditing()) this.aiEdits.set(e.path, Date.now())
1953
1928
  }
1954
1929
  // 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
1930
  const push = () => { if (this.stopped) return; for (const e of list) { try { this.pushActivity(e.path, e.kind, e.detail || '') } catch {} } }
@@ -2009,7 +1984,9 @@ export class Session extends EventEmitter {
2009
1984
  const r = await this.squareFollower.commit({ message })
2010
1985
  if (r && r.nothing) return { nothing: true, text: 'Nothing to commit: the square has no work since its last commit.' }
2011
1986
  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)}` : ''}.` }
1987
+ // Paths with an open held conflict stayed live (live-block.js commit): said, with how to resolve them.
1988
+ const left = r && r.left_held && r.left_held.length ? ` ${heldLandingNote(r.left_held)}` : ''
1989
+ return { ...r, text: `Committed to square ${squareShort(this.squareFollower.here.square)}${head ? ` as ${String(head).slice(0, 12)}` : ''}.${left}` }
2013
1990
  }
2014
1991
 
2015
1992
  /**
@@ -2196,10 +2173,10 @@ export class Session extends EventEmitter {
2196
2173
 
2197
2174
  /**
2198
2175
  * 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.
2176
+ * `pulled`: git brought this version (a pull), so it is not an edit of ours: never boxed, and counted as the pull's.
2177
+ * `box`: false keeps this edit from boxing the file for us (leaveSquare: another member's work).
2200
2178
  */
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 } = {}) {
2179
+ ingest (rel, { pulled = false, same = false, box: mayBox = true } = {}) {
2203
2180
  if (!this.syncable(rel) || this.inSquare || this.syncStopped) return false
2204
2181
  if (this.merging.has(rel)) return false // its offline merge hasn't run yet; see mergeOffline
2205
2182
  // A plain `rm` of a file a fetched pull would bring (git said to remove it): making way, not a deletion.
@@ -2207,7 +2184,8 @@ export class Session extends EventEmitter {
2207
2184
  if (this.writeFailed.has(rel)) return false // the shared version never reached the disk: what's there is no edit of ours
2208
2185
  // New ignore rules: a box of ours on a file they now leave out lets go (settleBoxesOnce).
2209
2186
  if (IGNORE_FILES.includes(path.posix.basename(rel)) || rel === '.gitmodules') { this.ig = loadIgnore(this.root) }
2210
- const disk = this.readDisk(rel)
2187
+ const disk = this.readDisk(rel, { settle: true })
2188
+ if (disk && disk.unsettled) { this.settleSoon(rel); return false }
2211
2189
  const boxed = this.boxedByOther(rel)
2212
2190
  if (boxed) {
2213
2191
  // Someone else's box: what this folder has is its version from before the box, never theirs.
@@ -2220,8 +2198,7 @@ export class Session extends EventEmitter {
2220
2198
  this.scheduleStateSave()
2221
2199
  return false
2222
2200
  }
2223
- this.rejectBoxed(rel, disk, boxed)
2224
- return false
2201
+ return this.editBoxed(rel, disk, boxed)
2225
2202
  }
2226
2203
  const gitWas = this.gitOnly.get(rel) // git's version of a file the document hasn't, as this folder last had it
2227
2204
  if (this.gitOnly.size && this.gitOnly.has(rel)) {
@@ -2255,23 +2232,18 @@ export class Session extends EventEmitter {
2255
2232
  // A diff branch: deleting a file git had changes the session though neither side has an entry for it.
2256
2233
  const gitDeletion = !disk && this.followsGit(rel) && (gitWas !== undefined || this.lastKnown.has(rel))
2257
2234
  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
2235
  const refusal = this.writeRefusal(rel)
2264
2236
  if (refusal && changesIt) {
2265
2237
  this.rejectLocal(rel, disk, refusal)
2266
2238
  return false
2267
2239
  }
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.
2240
+ // A change of ours while our AI works goes into a box of ours (unfinished work, out of other folders
2241
+ // until it's committed). A person typing by hand while their AI sits idle edits live with everyone.
2242
+ // Quilt's own line in .gitignore (ignoreQuiltState) is nobody's edit: never boxed for anyone.
2271
2243
  const quiltOwn = this.quiltOwnWrite === rel && disk && disk.key === this.quiltOwnKey
2272
2244
  if (quiltOwn) { this.quiltOwnWrite = null; this.quiltOwnKey = null }
2273
2245
  // 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)
2246
+ if (mayBox && (disk || this.boxesOn()) && !pulled && !quiltOwn && this.ready && !this.seeding && changesIt && this.aiMayBeEditing()) this.boxEdit(rel)
2275
2247
 
2276
2248
  if (!disk) {
2277
2249
  if (!this.files.has(rel) && !this.blobs.has(rel)) {
@@ -2294,9 +2266,11 @@ export class Session extends EventEmitter {
2294
2266
  this.lastKnown.delete(rel)
2295
2267
  return false
2296
2268
  }
2269
+ let gone
2297
2270
  this.transact(() => {
2298
2271
  const was = this.files.get(rel)
2299
2272
  const before = was ? was.toString() : undefined
2273
+ gone = before
2300
2274
  this.files.delete(rel)
2301
2275
  this.blobs.delete(rel)
2302
2276
  if (this.modes.has(rel)) this.modes.delete(rel)
@@ -2306,6 +2280,8 @@ export class Session extends EventEmitter {
2306
2280
  if (base && !this.fileBases.has(rel)) this.fileBases.set(rel, base)
2307
2281
  }
2308
2282
  this.recordActivity(rel, 'deleted', '', { before, after: before === undefined ? undefined : '' }, { pulled })
2283
+ // With the same text added elsewhere by this folder, a move (edits others make to rel follow it).
2284
+ if (!pulled && this.ready && typeof gone === 'string') this.liveRules().noteGone({ doc: this.bdoc, path: rel, text: gone, by: this.name })
2309
2285
  }, LOCAL)
2310
2286
  this.lastKnown.delete(rel)
2311
2287
  this.setOnDisk(rel, null)
@@ -2325,6 +2301,36 @@ export class Session extends EventEmitter {
2325
2301
  // Storage refused it, but it's small enough to share inside the document.
2326
2302
  }
2327
2303
 
2304
+ // A file another member moved away (deleted here, the same text added elsewhere): this edit goes to where it went.
2305
+ if (!disk.binary && !pulled && !this.files.has(rel) && !this.blobs.has(rel) && this.ready && this.bdoc) {
2306
+ const mv = this.liveRules().movedTo({ doc: this.bdoc, path: rel, by: this.name })
2307
+ if (mv && this.files.has(mv.to) && this.syncable(mv.to)) return this.followMove(rel, disk, mv)
2308
+ }
2309
+ // A live write is merged against what this folder last had (lastKnown): what landed in the shared file
2310
+ // meanwhile stays, and the ways a clash is caught run on it (live-merge.js). Lines both changed keep
2311
+ // the shared version; this folder gets the result back, and its own lines are held (held.js).
2312
+ let text = disk.binary ? null : disk.text
2313
+ let rewrite = false
2314
+ if (!disk.binary && !pulled && !same && this.ready && !this.seeding) {
2315
+ const known = this.lastKnown.get(rel)
2316
+ const t = this.files.get(rel)
2317
+ // The relay takes it as a write (relay-live-write.js): merged there, one write at a time per file, and
2318
+ // applied in whole lines, never as an edit of the text here that a CRDT would mix with someone else's.
2319
+ if (t && typeof known === 'string' && !/^bin:[0-9a-f]{40}$/.test(known) && this.relayWritesOn() && !this.relayLocal.delete(rel)) return this.relayIngest(rel, disk, known)
2320
+ if (t && typeof known === 'string' && !/^bin:[0-9a-f]{40}$/.test(known)) {
2321
+ 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) })
2322
+ if (r.text !== disk.text) { text = r.text; rewrite = true }
2323
+ // Every change of this write was held: the shared file stays as it is, and this folder gets it back.
2324
+ if (rewrite && text === t.toString()) {
2325
+ try { this.writeFile(rel, resolveInside(this.root, rel), text) } catch (err) { this.log(`could not write ${rel}: ${err.message}`) }
2326
+ this.lastKnown.set(rel, text)
2327
+ return false
2328
+ }
2329
+ } else if (!t && !this.blobs.has(rel)) {
2330
+ // A new file: nothing to merge, but its lines are on record as this member's (the next writer's stale check).
2331
+ this.liveRules().write({ doc: this.bdoc, where: { branch: this.branchKey() }, path: rel, ours: disk.text, by: this.name })
2332
+ }
2333
+ }
2328
2334
  let detail = ''
2329
2335
  // A diff branch: the edit of a file only git had starts from git's text, so its history says what changed.
2330
2336
  const fromGit = this.diffForm && !this.files.has(rel) && !this.blobs.has(rel) && !this.gone.has(rel) && typeof gitWas === 'string' && !gitWas.startsWith('bin:') ? gitWas : null
@@ -2345,30 +2351,171 @@ export class Session extends EventEmitter {
2345
2351
  if (fromGit) ytext.insert(0, fromGit)
2346
2352
  this.files.set(rel, ytext)
2347
2353
  }
2348
- return applyTextDiff(ytext, disk.text)
2354
+ return applyTextDiff(ytext, text)
2349
2355
  }
2350
- texts = { before, after: disk.text }
2356
+ texts = { before, after: text }
2351
2357
  // Folders on one branch pull the same commits, often at the same moment: made under an id
2352
2358
  // taken from the change, the pull's edit is the same edit from each of them, and lands once.
2353
2359
  // 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()
2360
+ detail = pulled || same ? asClient(this.bdoc, sameEditClient(pulled ? 'pull' : 'square', rel, this.files.has(rel) ? before : null, text), put) : put()
2355
2361
  }
2356
2362
  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
2363
  this.notePresentHere(rel, this.entryBase())
2358
2364
  this.recordActivity(rel, existed ? 'edited' : 'created', detail, texts, { pulled })
2365
+ if (!existed && !disk.binary && !pulled && this.ready) this.liveRules().noteNew({ doc: this.bdoc, path: rel, text, by: this.name })
2359
2366
  }, LOCAL)
2360
- this.lastKnown.set(rel, disk.key)
2367
+ if (rewrite) {
2368
+ // This folder gets what the shared file got: the lines that landed first, with its own other changes.
2369
+ try { this.writeFile(rel, resolveInside(this.root, rel), text) } catch (err) { this.log(`could not write ${rel}: ${err.message}`) }
2370
+ this.lastKnown.set(rel, text)
2371
+ } else this.lastKnown.set(rel, disk.key)
2361
2372
  this.setOnDisk(rel, null)
2362
2373
  this.noteMyEdit(rel, { pulled })
2363
- if (!pulled) this.noteQueuedEdit(rel)
2364
2374
  return true
2365
2375
  }
2366
2376
 
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)}`)
2377
+ /** Whether this folder's text edits go to the relay as writes (it takes them, and this folder is connected on a branch). */
2378
+ relayWritesOn () {
2379
+ return !!(this.conn && this.conn.relayWrites && this.conn.connected && this.conn.branchKey !== null && !this.noRelayWrites && !this.inSquare)
2380
+ }
2381
+
2382
+ /**
2383
+ * An edit of a text the session has, sent to the relay as a live write against `base` (what this
2384
+ * folder last synced of it). Until the relay answers, the path waits: a remote change is not written
2385
+ * over the edit (writeOut sees disk differ), and a further save is taken in after the answer, on it.
2386
+ * True (the session's version changes, or the edit is held).
2387
+ */
2388
+ relayIngest (rel, disk, base) {
2389
+ if (this.relayWriting.has(rel)) { this.relayAgain.add(rel); return true }
2390
+ this.relayWriting.add(rel)
2391
+ const text = disk.text
2392
+ // Made from the text a partner's change was just written over (an editor's older read)? It goes too
2393
+ // (`older`): the relay puts the save onto the base, and where the partner changed it since, the newer lines stay.
2394
+ const older = this.overwritten.pick(rel, base, text)
2395
+ const trusted = !!(this.liveEngine && this.liveEngine.trusted.get(rel) === text)
2396
+ const key = this.conn.branchKey
2397
+ const req = { path: rel, base: versionOf(base), ...(base.length <= 256 * 1024 ? { baseText: base } : {}), text, ...(older !== base ? { older } : {}), ...(trusted ? { trusted: true } : {}) }
2398
+ // What does not touch the text stays an edit here: its mode, and where a diff branch's entry started.
2399
+ this.transact(() => {
2400
+ if (disk.exec) { if (this.modes.get(rel) !== 'x') this.modes.set(rel, 'x') } else if (this.modes.has(rel)) this.modes.delete(rel)
2401
+ this.notePresentHere(rel, this.entryBase())
2402
+ }, LOCAL)
2403
+ this.noteMyEdit(rel)
2404
+ this.conn.liveWrite(req, { baseOf: () => base }).then(
2405
+ (r) => this.relayWrote(rel, disk, r, key, trusted),
2406
+ (err) => this.relayFailed(rel, err)
2407
+ )
2408
+ return true
2409
+ }
2410
+
2411
+ /** 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. */
2412
+ relayWrote (rel, disk, r, key, trusted) {
2413
+ this.relayWriting.delete(rel)
2414
+ if (this.stopped) return
2415
+ if (r.fallback) { this.relayLocal.add(rel); this.relayAgain.delete(rel); try { this.ingest(rel) } catch (err) { this.log(`could not sync ${rel}: ${err.message}`) } return }
2416
+ if (trusted && this.liveEngine) this.liveEngine.trusted.delete(rel)
2417
+ if (this.conn.branchKey !== key) { this.relayAgain.delete(rel); this.queue(rel); return } // the folder moved to another branch meanwhile
2418
+ const result = r.same ? disk.text : r.text
2419
+ this.overwritten.forget(rel)
2420
+ if (r.detail) this.transact(() => this.recordActivity(rel, 'edited', r.detail, { before: r.before ?? '', after: result }), LOCAL)
2421
+ let now = null
2422
+ try { now = this.readDisk(rel) } catch {}
2423
+ if (now && !now.binary && now.text === disk.text) {
2424
+ // Disk still has what was sent: it gets the result (the lines that landed first, with this edit's others).
2425
+ let over = true
2426
+ if (result !== disk.text) {
2427
+ try {
2428
+ const abs = resolveInside(this.root, rel)
2429
+ over = this.writeOver(rel, abs, result, now)
2430
+ if (over === null) { this.writeFile(rel, abs, result); over = true }
2431
+ } catch (err) { this.log(`could not write ${rel}: ${err.message}`) }
2432
+ }
2433
+ // Saved again in that instant: that save is taken in next, merged on what was sent.
2434
+ this.lastKnown.set(rel, over === false ? disk.text : result)
2435
+ } else this.lastKnown.set(rel, disk.text) // saved again since: that save is taken in next, merged on what was sent
2436
+ this.setOnDisk(rel, null)
2437
+ for (const n of r.notices || []) this.notice(n)
2438
+ for (const l of r.logs || []) this.log(l)
2439
+ for (const x of r.local || []) { try { this.keepHeldLocal(x.id, { result: x.result, mine: x.mine }) } catch {} }
2440
+ if (Array.isArray(r.gone) && r.gone.length) {
2441
+ let uses = []
2442
+ try { uses = findUses(r.gone, this.sessionTexts(), { skip: rel }) } catch {}
2443
+ const w = removedNameWarning(rel, uses)
2444
+ if (w) { this.notice(w); this.log(`⚠️ ${w}`) }
2445
+ }
2446
+ if (this.relayAgain.delete(rel) || (now && now.key !== this.lastKnown.get(rel))) {
2447
+ try { this.ingest(rel) } catch (err) { this.log(`could not sync ${rel}: ${err.message}`) }
2448
+ }
2449
+ }
2450
+
2451
+ /** A live write the relay never answered: an older relay (the edit goes in here, as before), or no connection (tried again). */
2452
+ relayFailed (rel, err) {
2453
+ this.relayWriting.delete(rel)
2454
+ this.relayAgain.delete(rel)
2455
+ if (this.stopped) return
2456
+ if (/unknown branch request/.test(err.message)) { this.noRelayWrites = true; try { this.ingest(rel) } catch {} return }
2457
+ if (this.relayProblem !== err.message) this.log(`${rel}: your edit waits to reach the session (${err.message}); it is tried again`)
2458
+ this.relayProblem = err.message
2459
+ const t = setTimeout(() => { if (!this.stopped) this.queue(rel) }, 1000)
2460
+ t.unref?.()
2461
+ }
2462
+
2463
+ /**
2464
+ * The live-write engine (live-merge.js) for this session: held conflicts go to the room's document,
2465
+ * the writer's AI hears through notices, and the removed-name search reads the files this folder synced.
2466
+ */
2467
+ liveRules () {
2468
+ if (!this.liveEngine) {
2469
+ this.liveEngine = new LiveRules({
2470
+ room: () => this.doc,
2471
+ staleMinutes: () => staleWriteMinutes(this.doc, this.members),
2472
+ notice: (t) => this.notice(t),
2473
+ log: (t) => this.log(t),
2474
+ texts: () => this.sessionTexts(),
2475
+ origin: LOCAL,
2476
+ keepLocal: (id, texts) => this.keepHeldLocal(id, texts)
2477
+ })
2478
+ }
2479
+ return this.liveEngine
2480
+ }
2481
+
2482
+ /** The text files this folder last synced, as [path, text] (the removed-name search). */
2483
+ * sessionTexts () {
2484
+ for (const [rel, k] of this.lastKnown) if (typeof k === 'string' && !/^bin:[0-9a-f]{40}$/.test(k)) yield [rel, k]
2485
+ }
2486
+
2487
+ /** Where this machine keeps a held conflict's texts too big for the room's document (and a binary's bytes). */
2488
+ heldDir (id) { return path.join(this.stateDir, 'held', String(id).replace(/[^0-9a-f]/g, '')) }
2489
+
2490
+ keepHeldLocal (id, { result = null, mine = null }) {
2491
+ const dir = this.heldDir(id)
2492
+ fs.mkdirSync(dir, { recursive: true })
2493
+ if (result != null) fs.writeFileSync(path.join(dir, 'result'), result)
2494
+ if (mine != null) fs.writeFileSync(path.join(dir, 'mine'), mine)
2495
+ }
2496
+
2497
+ /**
2498
+ * An edit to `rel`, which another member moved to `mv.to` (deleted it and added the same text there):
2499
+ * merged into `mv.to` as a live write, and `rel` comes off this folder again. True.
2500
+ */
2501
+ followMove (rel, disk, mv) {
2502
+ const known = this.lastKnown.get(rel)
2503
+ const base = typeof known === 'string' && !/^bin:[0-9a-f]{40}$/.test(known) ? known : mv.text
2504
+ const t = this.files.get(mv.to)
2505
+ 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] })
2506
+ this.transact(() => {
2507
+ const before = t.toString()
2508
+ const detail = applyTextDiff(t, r.text)
2509
+ this.recordActivity(mv.to, 'edited', detail, { before, after: r.text })
2510
+ }, LOCAL)
2511
+ try { this.writeFile(mv.to, resolveInside(this.root, mv.to), r.text) } catch {}
2512
+ this.lastKnown.set(mv.to, r.text)
2513
+ try { fs.rmSync(resolveInside(this.root, rel), { force: true }) } catch {}
2514
+ this.lastKnown.delete(rel)
2515
+ this.noteMyEdit(mv.to)
2516
+ this.notice(`${mv.by} moved ${rel} to ${mv.to}; your edit to ${rel} went into ${mv.to}. Edit ${mv.to} from now on.`)
2517
+ this.log(`🧵 ${rel} was moved to ${mv.to} by ${mv.by}: your edit went there`)
2518
+ return true
2372
2519
  }
2373
2520
 
2374
2521
  /** Queues a line for this person's AI; the local MCP server hands pending notices over with its next answer. */
@@ -2534,9 +2681,7 @@ export class Session extends EventEmitter {
2534
2681
  // ------------------------------------------------------- shared -> local --
2535
2682
 
2536
2683
  fromRemote (rel) {
2537
- const claim = this.claimFor(rel)
2538
- if (claim && this.ownClaim(claim)) this.reclaim(rel)
2539
- else this.writeOut(rel)
2684
+ this.writeOut(rel)
2540
2685
  }
2541
2686
 
2542
2687
  /**
@@ -2569,28 +2714,6 @@ export class Session extends EventEmitter {
2569
2714
  }
2570
2715
  }
2571
2716
 
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
2717
  writeOut (rel) {
2595
2718
  if (!this.syncable(rel) || this.inSquare || this.syncStopped) return
2596
2719
  if (this.ghost(rel)) return
@@ -2598,8 +2721,10 @@ export class Session extends EventEmitter {
2598
2721
  let abs
2599
2722
  try { abs = resolveInside(this.root, rel) } catch (err) { this.log(err.message); return }
2600
2723
  const shared = this.sharedKey(rel)
2601
- const disk = this.readDisk(rel)
2724
+ const disk = this.readDisk(rel, { settle: true })
2602
2725
  if (disk && (disk.skip || disk.tooLarge)) return
2726
+ // A save being written right now: never written over; it is taken in once it is whole (and merged).
2727
+ if (disk && disk.unsettled) { this.settleSoon(rel); return }
2603
2728
  const known = this.lastKnown.get(rel)
2604
2729
  if (shared === undefined && this.followsGit(rel)) {
2605
2730
  // A diff branch leaves this file to git (branch-view.js): the folder's own checkout's stays, never
@@ -2609,8 +2734,14 @@ export class Session extends EventEmitter {
2609
2734
  }
2610
2735
 
2611
2736
  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.
2737
+ // The file changed here in the instant before this remote change arrived: a text both sides
2738
+ // have is merged as a live write (ingest, against what this folder last had), never overwritten.
2739
+ const t = this.files.get(rel)
2740
+ if (!disk.binary && t && typeof known === 'string' && !/^bin:[0-9a-f]{40}$/.test(known) && !this.writeFailed.has(rel) && !this.downloading.has(rel)) {
2741
+ queueMicrotask(() => { try { this.ingest(rel) } catch (err) { this.log(`could not merge ${rel}: ${err.message}`) } })
2742
+ return
2743
+ }
2744
+ // Otherwise keep a copy so nothing is lost.
2614
2745
  this.keepConflict(rel, disk)
2615
2746
  }
2616
2747
 
@@ -2628,9 +2759,17 @@ export class Session extends EventEmitter {
2628
2759
  if (!disk || disk.key !== shared) { this.downloadLarge(rel, b); return }
2629
2760
  this.setOnDisk(rel, b.hash)
2630
2761
  } else if (!disk || disk.key !== shared) {
2762
+ // Saved again since the look above (or made since, when there was nothing): that save is taken in
2763
+ // and merged, never written over (2026-11-14).
2764
+ if (this.savedSince(abs, disk)) { this.queue(rel); return }
2765
+ // What a partner's change is written over: a save made from it is told apart (base-pick.js).
2766
+ if (disk && !disk.binary && disk.key === known && this.files.has(rel)) this.overwritten.note(rel, disk.text)
2631
2767
  fs.mkdirSync(path.dirname(abs), { recursive: true })
2632
2768
  const t = this.files.get(rel)
2633
- this.writeFile(rel, abs, t ? t.toString() : Buffer.from(b.data, 'base64'))
2769
+ const data = t ? t.toString() : Buffer.from(b.data, 'base64')
2770
+ const over = disk ? this.writeOver(rel, abs, data, disk) : null
2771
+ if (over === false) { this.queue(rel); return }
2772
+ if (over === null) this.writeFile(rel, abs, data)
2634
2773
  }
2635
2774
  if (!b || !b.stored) this.setOnDisk(rel, null)
2636
2775
  this.lastKnown.set(rel, shared)
@@ -2666,26 +2805,114 @@ export class Session extends EventEmitter {
2666
2805
  return true
2667
2806
  }
2668
2807
 
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)
2675
- }
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)
2686
- }
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}`)
2808
+ /**
2809
+ * An edit here to a file someone else has boxed. It is never undone: Quilt holds no files (no-holds,
2810
+ * 2026-11-13). Their box opens, so their work reaches every folder (the relay tells them), and this
2811
+ * edit goes in straight away through the normal merge (autoSettle), from this folder's version
2812
+ * before the box. Returns true when the session's version changed.
2813
+ */
2814
+ editBoxed (rel, disk, box) {
2815
+ const before = this.boxBase.has(rel) ? this.boxBase.get(rel) : undefined
2816
+ const base = before === null ? null : before && typeof before.text === 'string' ? before.text : undefined
2817
+ if (this.boxBase.delete(rel)) this.scheduleStateSave()
2818
+ 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}`))
2819
+ // Not someone else's box here any more, from now: the session's version is written to this folder again.
2820
+ this.boxed.delete(rel)
2821
+ this.log(`📦 ${rel} was in ${box.of || box.by}'s box: it opened, and your change goes in with their work`)
2822
+ const ours = disk ? disk.key : null
2823
+ const theirs = this.sharedKey(rel)
2824
+ if (theirs === base || (theirs === undefined && base === null)) return this.ingest(rel) // their box changed nothing of it
2825
+ const binary = [ours, theirs].some((k) => typeof k === 'string' && k.startsWith('bin:')) || !!(before && typeof before.b64 === 'string')
2826
+ return this.autoSettle({ rel, base: binary ? null : base, ours, theirs, theirsBy: box.of || box.by, disk, binary, via: null }) === 'merged'
2827
+ }
2828
+
2829
+ /**
2830
+ * Writes the session's version over a file of this folder's that a save may land in at the same moment:
2831
+ * in a file of its own put in place by a rename, only if the file is still as `disk` read it (savedSince),
2832
+ * and the file replaced stays open across the rename, so a save into it in that instant is put back as a
2833
+ * save of its own (rescueSave), never lost with the old file. True written; false saved since (not written);
2834
+ * null where this can't be done (Windows, a read-only file: the caller writes it as before).
2835
+ */
2836
+ writeOver (rel, abs, data, disk) {
2837
+ if (process.platform === 'win32') return null
2838
+ const tmp = path.join(path.dirname(abs), `.${path.basename(abs)}.quilt-tmp`)
2839
+ let old = null
2840
+ try {
2841
+ old = fs.openSync(abs, 'r')
2842
+ // As it was before the look below: a save into it after this is either seen by that look or after the rename.
2843
+ const seen = fs.fstatSync(old)
2844
+ const st = writeAndStat(tmp, data, seen.mode & 0o7777)
2845
+ if (this.savedSince(abs, disk)) { fs.rmSync(tmp, { force: true }); return false }
2846
+ fs.renameSync(tmp, abs)
2847
+ this.noteWritten(rel, abs, st)
2848
+ const now = fs.fstatSync(old)
2849
+ if (now.size !== seen.size || now.mtimeMs !== seen.mtimeMs) { this.rescueSave(rel, abs, old, data, disk && typeof disk.text === 'string' ? disk.text : null); old = null }
2850
+ return true
2851
+ } catch {
2852
+ try { fs.rmSync(tmp, { force: true }) } catch {}
2853
+ return null
2854
+ } finally { if (old !== null) { try { fs.closeSync(old) } catch {} } }
2855
+ }
2856
+
2857
+ /**
2858
+ * A save that landed in a file writeOver replaced: once whole, it goes back on disk (if the file still has
2859
+ * what was written) and is taken in. Saved again since: its own change (against `before`, what disk had
2860
+ * before the write) goes onto that newer save, the newer one winning where both changed a line.
2861
+ */
2862
+ async rescueSave (rel, abs, fd, wrote, before = null) {
2863
+ try {
2864
+ let last = null
2865
+ for (let i = 0; i < 50; i++) {
2866
+ const st = fs.fstatSync(fd)
2867
+ if (last && st.size === last.size && st.mtimeMs === last.mtimeMs) break
2868
+ last = st
2869
+ await new Promise((resolve) => setTimeout(resolve, 20))
2870
+ }
2871
+ const size = fs.fstatSync(fd).size
2872
+ const bytes = Buffer.alloc(size)
2873
+ let off = 0
2874
+ while (off < size) { const n = fs.readSync(fd, bytes, off, size - off, off); if (!n) break; off += n }
2875
+ if (this.stopped) return
2876
+ const now = (() => { try { return fs.readFileSync(abs) } catch { return null } })()
2877
+ const w = Buffer.isBuffer(wrote) ? wrote : Buffer.from(wrote, 'utf8')
2878
+ // Disk still has a version Quilt wrote (this one, or a newer one it wrote since): the save goes back over it.
2879
+ const k = this.lastKnown.get(rel)
2880
+ const ours = now && (now.equals(w) || (typeof k === 'string' && !k.startsWith('bin:') && now.toString('utf8') === k))
2881
+ if (!now || bytes.equals(w)) return // gone, or nothing of its own
2882
+ const tmp = path.join(path.dirname(abs), `.${path.basename(abs)}.quilt-save`)
2883
+ if (ours) {
2884
+ fs.writeFileSync(tmp, bytes, { mode: fs.statSync(abs).mode & 0o7777 })
2885
+ fs.renameSync(tmp, abs)
2886
+ } else {
2887
+ // Saved again since, from what Quilt wrote: the late save's own change goes onto that save.
2888
+ if (typeof before !== 'string' || looksBinary(bytes) || looksBinary(now)) return
2889
+ const onto = mergeLive(before, bytes.toString('utf8'), w.toString('utf8')).text
2890
+ // Both saves are this folder's: where they changed the same place, both go in (nothing is lost; its writer sees both).
2891
+ const merged = mergeLive(w.toString('utf8'), onto, now.toString('utf8'), { union: true }).text
2892
+ if (merged === now.toString('utf8')) return
2893
+ fs.writeFileSync(tmp, merged, { mode: fs.statSync(abs).mode & 0o7777 })
2894
+ let again = null
2895
+ try { again = fs.readFileSync(abs) } catch {}
2896
+ if (!again || !again.equals(now)) { fs.rmSync(tmp, { force: true }); return }
2897
+ fs.renameSync(tmp, abs)
2898
+ }
2899
+ this.log(`${rel}: a save landed while Quilt wrote the session's version; it is taken in now`)
2900
+ this.queue(rel)
2901
+ } catch {} finally { try { fs.closeSync(fd) } catch {} }
2902
+ }
2903
+
2904
+ /** A file read half-written (readDisk `unsettled`): taken in a moment later. */
2905
+ settleSoon (rel) {
2906
+ const t = setTimeout(() => { if (!this.stopped) this.queue(rel) }, SETTLE_MS / 5)
2907
+ t.unref?.()
2908
+ }
2909
+
2910
+ /** Whether the file at abs changed since `disk` (readDisk's look; null: there was none) was read. */
2911
+ savedSince (abs, disk) {
2912
+ let st = null
2913
+ try { st = fs.lstatSync(abs) } catch {}
2914
+ if (!disk) return !!st
2915
+ return !st || (typeof disk.mtime === 'number' && st.mtimeMs !== disk.mtime)
2689
2916
  }
2690
2917
 
2691
2918
  /** Keeps our version of rel aside before something replaces it. */
@@ -2700,29 +2927,30 @@ export class Session extends EventEmitter {
2700
2927
  /** Writes the shared version of rel. A read-only copy of ours is made writable, or moved aside if it can't be. */
2701
2928
  writeFile (rel, abs, data) {
2702
2929
  try {
2703
- fs.writeFileSync(abs, data)
2704
- return this.noteWritten(rel, abs)
2930
+ return this.noteWritten(rel, abs, writeAndStat(abs, data))
2705
2931
  } catch (err) {
2706
2932
  if (err.code !== 'EACCES' && err.code !== 'EPERM') throw err
2707
2933
  }
2934
+ let st
2708
2935
  try {
2709
2936
  fs.chmodSync(abs, (fs.statSync(abs).mode & 0o7777) | 0o200)
2710
- fs.writeFileSync(abs, data)
2937
+ st = writeAndStat(abs, data)
2711
2938
  } catch {
2712
2939
  this.moveAside(rel, abs)
2713
- fs.writeFileSync(abs, data)
2940
+ st = writeAndStat(abs, data)
2714
2941
  }
2715
- this.noteWritten(rel, abs)
2942
+ this.noteWritten(rel, abs, st)
2716
2943
  }
2717
2944
 
2718
2945
  /**
2719
2946
  * The re-scan learns of a file Quilt wrote at once: the watcher can miss
2720
2947
  * events in a folder Quilt just created, and a file the re-scan never saw
2721
- * would never be noticed gone.
2948
+ * would never be noticed gone. `st`: the file as this write left it (read
2949
+ * before it was closed), so a save landing right after it is never taken for it.
2722
2950
  */
2723
- noteWritten (rel, abs) {
2951
+ noteWritten (rel, abs, st = null) {
2724
2952
  try {
2725
- const st = fs.lstatSync(abs)
2953
+ if (!st) st = fs.lstatSync(abs)
2726
2954
  this.diskStats.set(rel, `${st.ino}:${st.size}:${st.mtimeMs}:${st.ctimeMs}`)
2727
2955
  } catch {}
2728
2956
  }
@@ -2924,7 +3152,7 @@ export class Session extends EventEmitter {
2924
3152
  }
2925
3153
  const now = this.readDisk(rel)
2926
3154
  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
3155
+ if (this.sharedKey(rel) !== sharedBefore || this.downloading.has(rel)) return // a partner's version landed first: it stays
2928
3156
  const existed = this.files.has(rel) || this.blobs.has(rel)
2929
3157
  this.transact(() => {
2930
3158
  this.files.delete(rel)
@@ -3378,7 +3606,7 @@ export class Session extends EventEmitter {
3378
3606
 
3379
3607
  /**
3380
3608
  * 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.
3609
+ * its files (or the project when it lists none), and the checklist.
3382
3610
  */
3383
3611
  taskBrief (id) {
3384
3612
  const task = this.taskList().find((t) => t.id === id)
@@ -3386,10 +3614,7 @@ export class Session extends EventEmitter {
3386
3614
  const files = task.files || []
3387
3615
  const all = this.history.entries()
3388
3616
  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 }
3617
+ return { task, history, checklist: this.readChecklist(), me: this.name }
3393
3618
  }
3394
3619
 
3395
3620
  /**
@@ -3914,8 +4139,7 @@ export class Session extends EventEmitter {
3914
4139
 
3915
4140
  // ------------------------------------------------- AI sessions (persona.js) --
3916
4141
  // 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.
4142
+ // Each is a member of its own, named after its work, so partners message the right one.
3919
4143
 
3920
4144
  /**
3921
4145
  * An AI session (one `quilt mcp`, by its `via` id) says hello. Its name is taken from the git
@@ -3934,13 +4158,12 @@ export class Session extends EventEmitter {
3934
4158
  const now = Date.now()
3935
4159
  let p = this.personas.get(via)
3936
4160
  // 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".
4161
+ // process): it keeps its name and inbox instead of becoming "… 2".
3938
4162
  if (!p && chain[0]) {
3939
4163
  // A run Quilt started on its own (autowork.js) is known by its process: the tool, or the wrapper that started it.
3940
4164
  const same = [...this.personas.values()].find((q) => q.chain && (q.chain[0] === chain[0] || (q.auto && chain.includes(q.chain[0]))))
3941
4165
  if (same) {
3942
4166
  this.personas.delete(same.via)
3943
- for (const [rel, v] of this.autoVia) if (v === same.via) this.autoVia.set(rel, via)
3944
4167
  same.via = via
3945
4168
  this.personas.set(via, same)
3946
4169
  p = same
@@ -4052,8 +4275,6 @@ export class Session extends EventEmitter {
4052
4275
  for (const c of plan.changes) {
4053
4276
  const refusal = this.writeRefusal(c.path)
4054
4277
  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
4278
  }
4058
4279
  for (const c of plan.changes) {
4059
4280
  const abs = resolveInside(this.root, c.path)
@@ -4111,7 +4332,7 @@ export class Session extends EventEmitter {
4111
4332
  /** Who an action from this AI session is by: its own name, or this member's. */
4112
4333
  actorName (via) { const p = this.persona(via); return p ? p.name : this.name }
4113
4334
 
4114
- /** The claim request fields that make the relay act for an AI session (server.js claimant). */
4335
+ /** The box request fields that make the relay act for an AI session (server.js boxOwner). */
4115
4336
  as (via) { const p = this.persona(via); return p ? { as: { id: p.rid || p.via, label: p.label } } : {} }
4116
4337
 
4117
4338
  /** Whether a name is this member's or one of its AI sessions' (now or before a rename). */
@@ -4129,14 +4350,8 @@ export class Session extends EventEmitter {
4129
4350
  return [this.name, ...(this.aiOf ? [aiName(this.aiOf)] : []), ...[...this.personas.values()].flatMap((p) => [p.name, ...p.aliases])]
4130
4351
  }
4131
4352
 
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
- }
4353
+ /** Whether a box is this member's or one of its AI sessions': its work is in this folder. */
4354
+ isOwnBox (c) { return !!c && (c.by === this.name || c.of === this.name || this.isMine(c.by)) }
4140
4355
 
4141
4356
  /**
4142
4357
  * How an AI session reads the inbox: by its own name only. What is written to "<person>'s AI"
@@ -4200,7 +4415,7 @@ export class Session extends EventEmitter {
4200
4415
  if (label) this.renamePersona(via, label, 'prompt')
4201
4416
  }
4202
4417
 
4203
- /** An AI session used a Quilt tool: it is here, and its claims' idle time starts again (once a minute at most). */
4418
+ /** An AI session used a Quilt tool: it is here. */
4204
4419
  touchPersona (via) {
4205
4420
  const p = this.persona(via)
4206
4421
  if (!p) return
@@ -4208,9 +4423,6 @@ export class Session extends EventEmitter {
4208
4423
  const wasAway = now - p.seenAt > PERSONA_AWAY_MS
4209
4424
  p.seenAt = now
4210
4425
  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
4426
  }
4215
4427
 
4216
4428
  /** The AI session a hook belongs to: the one whose tool process is among the hook's parents. */
@@ -4516,21 +4728,11 @@ export class Session extends EventEmitter {
4516
4728
  this.scheduleStatusWrite()
4517
4729
  }
4518
4730
 
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.
4731
+ // ------------------------------------------------------------- boxes --
4732
+ // Quilt holds no files (no-holds, 2026-11-13): nobody claims, queues for or hands off a file, and no
4733
+ // write is refused or undone because someone else is working on it. What our AI changes in a git
4734
+ // folder goes into a box of ours (unfinished work, kept out of other folders until it's committed);
4735
+ // anyone who edits a boxed file opens it, and their change merges with the work in it (editBoxed).
4534
4736
 
4535
4737
  /** 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
4738
  aiMayBeEditing () {
@@ -4543,127 +4745,94 @@ export class Session extends EventEmitter {
4543
4745
  */
4544
4746
  boxesOn () { return !!this.git }
4545
4747
 
4546
- /** The box covering rel when someone else holds it (their unfinished work: not written here), else null. */
4748
+ /** The box on rel when it is someone else's (their unfinished work: not written here), else null. */
4547
4749
  boxedByOther (rel) {
4548
- const c = this.claimFor(rel)
4549
- return c && c.box && !this.ownClaim(c) ? c : null
4750
+ const c = this.boxAt(rel)
4751
+ return c && !this.isOwnBox(c) ? c : null
4550
4752
  }
4551
4753
 
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)
4754
+ /** The box on exactly rel (whoever's), or null. */
4755
+ boxAt (rel) {
4756
+ const c = this.boxed.get(rel)
4757
+ return c && c.box !== false ? c : null
4555
4758
  }
4556
4759
 
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
4760
+ /**
4761
+ * Our AI changed rel here: noted for its working state, and, in a git folder, boxed for us (once:
4762
+ * a box of ours already there keeps its first version, boxFrom). Someone else's box on it was opened
4763
+ * before this (editBoxed), and a box the relay can't give (a race, an older relay) leaves the edit live.
4764
+ */
4765
+ boxEdit (rel) {
4766
+ this.aiEdits.set(rel, Date.now())
4767
+ if (!this.conn || !this.boxesOn() || this.ownBox(rel) || this.boxing.has(rel)) return
4768
+ this.boxing.add(rel)
4769
+ this.boxFrom.set(rel, this.sharedKey(rel) ?? null) // called before the edit goes in
4567
4770
  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))
4771
+ this.noteActivity(`Editing ${rel}`)
4772
+ this.conn.boxRequest({ op: 'box', pattern: rel, note }).then((r) => {
4773
+ if (r && r.boxed === 0) this.boxFrom.delete(rel)
4774
+ }, (err) => {
4775
+ this.boxFrom.delete(rel)
4776
+ this.log(`could not box ${rel} for you (it stays live with everyone): ${err.message}`)
4777
+ }).finally(() => this.boxing.delete(rel))
4574
4778
  }
4575
4779
 
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 () {
4780
+ /** Forgets our AI's edits that have been quiet a while: "working" that only those edits said lapses with them. */
4781
+ forgetQuietEdits () {
4604
4782
  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(() => {})
4783
+ const cutoff = Date.now() - this.editQuietMs
4784
+ for (const [rel, ts] of this.aiEdits) if (ts <= cutoff) this.aiEdits.delete(rel)
4785
+ // So a commit isn't held up by an agent that never said done.
4786
+ if (this.workFromEdits && !this.aiEdits.size && this.work?.state === 'working' && Date.now() - (this.agentReportedAt || 0) >= this.editQuietMs) this.finishEditing().catch(() => {})
4611
4787
  }
4612
4788
 
4613
4789
  /** Our own box on exactly rel, or null. */
4614
4790
  ownBox (rel) {
4615
- const c = this.claims.get(rel)
4616
- return c && c.box && this.ownClaim(c) ? c : null
4791
+ const c = this.boxAt(rel)
4792
+ return c && this.isOwnBox(c) ? c : null
4617
4793
  }
4618
4794
 
4619
4795
  /**
4620
4796
  * 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.
4797
+ * MCP's quilt_before_edit, or a hook): for each path, who wrote it recently (presence) and whose
4798
+ * unfinished work is boxed on it, and what people said about those files in chat, as context. It
4799
+ * never claims and never refuses: every path stays writable (no-holds, 2026-11-13). When no chat
4800
+ * reader can see our AI work, it is marked working, so the host doesn't commit under it.
4625
4801
  */
4626
4802
  async prepareEdit (paths, via = null) {
4627
4803
  const files = []
4628
4804
  const p0 = this.persona(via)
4805
+ const me = p0 ? p0.name : this.name
4629
4806
  for (const p of [...new Set((paths || []).map((x) => String(x || '').replace(/\\/g, '/').replace(/^\.\//, '')))]) {
4630
4807
  if (!p) continue
4631
4808
  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
- }
4809
+ const b = this.boxedByOther(p)
4810
+ 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
4811
  }
4812
+ // A session still named after its tool takes a name from the first file it edits.
4813
+ const first = files.find((f) => f.shared)
4814
+ if (p0 && !p0.named && first && labelFromFile(first.path)) this.renamePersona(via, labelFromFile(first.path), 'file')
4658
4815
  const chat = this.chatAbout(files.filter((f) => f.shared).map((f) => f.path))
4659
- if (files.some((f) => f.claimed)) this.reportWorking(this.focus || '')
4816
+ if (first) this.reportWorking((p0 && p0.focus) || this.focus || '')
4660
4817
  return { me: p0 ? p0.name : this.name, files, chat }
4661
4818
  }
4662
4819
 
4820
+ /** Who wrote rel in the session lately (the room's activity), newest first: [{ by, at }]. Presence, never a hold. */
4821
+ recentWriters (rel, { within = RECENT_WRITER_MS, now = Date.now() } = {}) {
4822
+ const out = new Map()
4823
+ for (let i = this.activity.length - 1; i >= 0; i--) {
4824
+ const a = this.activity.get(i)
4825
+ if (!a || a.path !== rel || !a.by || a.kind === 'switched') continue
4826
+ if (now - (a.ts || 0) > within) break
4827
+ if (!out.has(a.by)) out.set(a.by, { by: a.by, at: a.ts || 0 })
4828
+ }
4829
+ return [...out.values()]
4830
+ }
4831
+
4663
4832
  /**
4664
4833
  * 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).
4834
+ * it counts as working for commits, until it says done or goes quiet (nothing reported, no file
4835
+ * of its changed, for the quiet time).
4667
4836
  */
4668
4837
  reportWorking (note = '') {
4669
4838
  this.agentReportedAt = Date.now()
@@ -4675,7 +4844,7 @@ export class Session extends EventEmitter {
4675
4844
  // ------------------------------------------- agent threads, written by Quilt --
4676
4845
  // An agent's thread (its lane in the feed) should show what it did in order, whatever tool it
4677
4846
  // 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.
4847
+ // the thread itself as they post, move tasks, leave notes and edit.
4679
4848
 
4680
4849
  /**
4681
4850
  * Whether Quilt writes this actor's thread itself: an agent member (CLI, webhooks), or one AI
@@ -4754,10 +4923,7 @@ export class Session extends EventEmitter {
4754
4923
  return chatAbout(paths, { messages: this.chat.toArray().filter((m) => this.canSee(m)), me: this.name })
4755
4924
  }
4756
4925
 
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
- */
4926
+ /** What this member owes before work moves on: direct messages and mentions not answered yet (duties.js). */
4761
4927
  duties (via = null) {
4762
4928
  const p = this.persona(via)
4763
4929
  const me = p ? [p.name, ...p.aliases] : this.name
@@ -4767,7 +4933,6 @@ export class Session extends EventEmitter {
4767
4933
  return {
4768
4934
  me: p ? p.name : this.name,
4769
4935
  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
4936
  pickup: person ? 'off' : pickup,
4772
4937
  next: person ? null : nextTask(this.taskList(), { name: this.name, asAi: this.kind !== 'agent' }, pickup)
4773
4938
  }
@@ -4786,133 +4951,12 @@ export class Session extends EventEmitter {
4786
4951
  try { return pickupMode(getSettings().aiTasks) } catch { return 'off' }
4787
4952
  }
4788
4953
 
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. */
4954
+ /** Done with a piece of work: says we're done. Nothing is held, so nothing is let go of (boxes stay until committed). */
4870
4955
  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)
4956
+ if (!this.persona(via)) this.aiEdits.clear()
4873
4957
  if (this.work?.state === 'working') this.setWork('done')
4874
4958
  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
4959
+ return { released: 0 }
4916
4960
  }
4917
4961
 
4918
4962
  /**
@@ -4923,12 +4967,12 @@ export class Session extends EventEmitter {
4923
4967
  async boxes () {
4924
4968
  const text = (d) => (!d || d.skip || d.tooLarge ? null : d.binary ? { binary: true } : d.text)
4925
4969
  const out = []
4926
- for (const c of this.claims.values()) {
4927
- if (!c || !c.box || /[*?[]/.test(c.pattern) || !isSafeRelPath(c.pattern)) continue
4970
+ for (const c of this.boxed.values()) {
4971
+ if (!c || c.box === false || /[*?[]/.test(c.pattern) || !isSafeRelPath(c.pattern)) continue
4928
4972
  const rel = c.pattern
4929
4973
  const t = this.files.get(rel)
4930
4974
  const after = t ? t.toString() : this.blobs.has(rel) ? { binary: true } : null
4931
- const mine = this.ownClaim(c)
4975
+ const mine = this.isOwnBox(c)
4932
4976
  let before = null
4933
4977
  if (mine) {
4934
4978
  const base = this.boxBase.has(rel) ? this.boxBase.get(rel) : null
@@ -4939,7 +4983,7 @@ export class Session extends EventEmitter {
4939
4983
  } else {
4940
4984
  try { before = text(this.readDisk(rel)) } catch { before = null }
4941
4985
  }
4942
- out.push(boxEntry({ claim: c, mine, before, after }))
4986
+ out.push(boxEntry({ box: c, mine, before, after }))
4943
4987
  }
4944
4988
  return { on: this.boxesOn(), boxes: out.sort((a, b) => a.ts - b.ts || a.path.localeCompare(b.path)) }
4945
4989
  }
@@ -4952,19 +4996,13 @@ export class Session extends EventEmitter {
4952
4996
  if (!this.ownBox(p)) { notBoxed.push(p); continue }
4953
4997
  if (!this.conn) throw new Error('not connected to the relay')
4954
4998
  // 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 })
4999
+ const r = await this.conn.boxRequest({ op: 'unbox', pattern: p, release: false })
4956
5000
  if (r.unboxed) { unpacked.push(p); this.boxFrom.delete(p) } else notBoxed.push(p)
4957
5001
  }
4958
5002
  if (unpacked.length) this.noteActivity(`Unpacked ${unpacked.join(', ')}`, { via })
4959
5003
  return { unpacked, notBoxed }
4960
5004
  }
4961
5005
 
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
5006
  /**
4969
5007
  * Why we can't reach the relay (e.g. no session pass), or null once that's fixed.
4970
5008
  * Logged once per new reason, not on every retry, and shown in status.
@@ -4977,26 +5015,20 @@ export class Session extends EventEmitter {
4977
5015
  this.emit('status-changed')
4978
5016
  }
4979
5017
 
4980
- /** Takes the relay's claim list, logging what changed. */
4981
- setClaims (list) {
4982
- const was = this.claims
5018
+ /** Takes the relay's box list (its MSG_CLAIMS, which lists boxes only), and writes out what opened. */
5019
+ setBoxes (list) {
5020
+ const was = this.boxed
4983
5021
  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.)
5022
+ // An older relay still sends claims: only boxes are kept, and nothing anyone holds is enforced here.
5023
+ 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)
5024
+ this.boxed = next
5025
+ try { fs.writeFileSync(path.join(this.stateDir, 'boxes.json'), JSON.stringify([...next.values()])) } catch {}
4996
5026
  // 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()
5027
+ if (this.ready && [...next].some(([p, c]) => c.handedFrom && this.isOwnBox(c) && !(was.get(p) && this.isOwnBox(was.get(p))))) this.scheduleStatusWrite()
5028
+ // A box someone else held opened (committed, unpacked, opened by an edit): its file reaches this folder now.
5029
+ // (Also one that opened while this folder was away: its ghost is still on record.)
4998
5030
  if (this.ready) {
4999
- const opened = new Set([...was].filter(([, c]) => c.box && !this.ownClaim(c)).map(([p]) => p))
5031
+ const opened = new Set([...was].filter(([, c]) => !this.isOwnBox(c)).map(([p]) => p))
5000
5032
  for (const p of this.boxBase.keys()) opened.add(p)
5001
5033
  for (const p of opened) {
5002
5034
  if (this.boxedByOther(p)) continue // still someone else's box
@@ -5006,14 +5038,13 @@ export class Session extends EventEmitter {
5006
5038
  }
5007
5039
  if (this.ready) this.settleReleasedMerges()
5008
5040
  this.scheduleStatusWrite()
5009
- this.emit('claims', [...next.values()])
5041
+ this.emit('boxes', [...next.values()])
5010
5042
  }
5011
5043
 
5012
5044
  /**
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.
5045
+ * Our offline edits an older app held back because someone held the file (open 'claimed' records):
5046
+ * nobody holds files now (no-holds, 2026-11-13), so each goes in straight away through the normal
5047
+ * merge (autoSettle).
5017
5048
  */
5018
5049
  settleReleasedMerges () {
5019
5050
  // A file changed here several times while someone held it (a pull each time) has a record for each,
@@ -5032,7 +5063,7 @@ export class Session extends EventEmitter {
5032
5063
  const rec = recs[recs.length - 1]
5033
5064
  if (recs.some((r) => r.binary || r.theirsHash === null) || rec.oursDeleted) continue
5034
5065
  // 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
5066
+ if (!this.syncable(rec.path) || this.writeRefusal(rec.path) || this.merging.has(rec.path)) continue
5036
5067
  const theirs = this.sharedKey(rec.path)
5037
5068
  if (typeof theirs !== 'string' || theirs.startsWith('bin:')) continue
5038
5069
  const tried = `${recs.map((r) => r.id).join(',')}:${sha1(theirs)}`
@@ -5045,17 +5076,15 @@ export class Session extends EventEmitter {
5045
5076
  if (typeof ours !== 'string') continue
5046
5077
  const holder = rec.claimedBy || rec.others[0] || 'someone'
5047
5078
  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 })
5079
+ // 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.
5080
+ if (theirs === (base ?? '')) this.applyMerged(rec.path, ours, 'held from before Quilt stopped holding files')
5081
+ else this.autoSettle({ rel: rec.path, base: base ?? null, ours, theirs, theirsBy: holder, disk, binary: false, via: null })
5082
+ 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
5083
  } catch (err) {
5055
5084
  this.log(`could not combine ${rec.path}: ${err.message}`)
5056
5085
  continue
5057
5086
  }
5058
- this.log(`✅ ${holder} let go of ${rec.path}: your changes went in`)
5087
+ this.log(`✅ ${rec.path}: your changes held for ${holder} went in`)
5059
5088
  if (this.catchUp?.mine?.conflicts.includes(rec.path)) {
5060
5089
  const m = this.catchUp.mine
5061
5090
  m.conflicts = m.conflicts.filter((p) => p !== rec.path)
@@ -5065,32 +5094,92 @@ export class Session extends EventEmitter {
5065
5094
  }
5066
5095
  }
5067
5096
 
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
5097
+ /** Last known boxes, so someone else's unfinished work isn't written here before the relay answers (or while offline). */
5098
+ loadBoxes () {
5099
+ let list = null
5100
+ try { list = JSON.parse(fs.readFileSync(path.join(this.stateDir, 'boxes.json'), 'utf8')) } catch {}
5101
+ // A folder from before no-holds kept them with its claims (claims.json): the boxes stay, every claim goes.
5102
+ if (!list) { try { list = JSON.parse(fs.readFileSync(path.join(this.stateDir, 'claims.json'), 'utf8')) } catch {} }
5103
+ for (const c of Array.isArray(list) ? list : []) if (c && c.box === true && typeof c.pattern === 'string') this.boxed.set(c.pattern, c)
5104
+ try { fs.rmSync(path.join(this.stateDir, 'claims.json'), { force: true }) } catch {}
5088
5105
  }
5089
5106
 
5090
5107
  // ------------------------------------------------------------ merges --
5091
5108
 
5092
5109
  mergeList () { return readMerges(this.merges) }
5093
5110
 
5111
+ // ------------------------------------------------------ held conflicts --
5112
+
5113
+ /** Every held conflict in the session (held.js), open ones first, without their texts (status goes out often). */
5114
+ heldList () {
5115
+ if (!this.doc) return []
5116
+ return readHeld(this.doc.getMap(HELD_MAP)).map(({ result, mine, ...r }) => r)
5117
+ }
5118
+
5119
+ /** The open ones, as the top of every tool answer says them to `me` ('' with none). */
5120
+ heldNotice (me = this.name) { return this.doc ? renderHeld(this.heldList(), { me }) : '' }
5121
+
5122
+ /** The session's stale_write_minutes: { minutes } (the owner's setting, else 15; 0: off). */
5123
+ staleWrite () { return { minutes: staleWriteMinutes(this.doc, this.members) } }
5124
+
5125
+ /** The owner sets the session's stale_write_minutes (0 turns the stale-write check off). */
5126
+ setStaleWrite (minutes) {
5127
+ 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.')
5128
+ return { minutes: setStaleWriteMinutes(this.doc, { minutes, by: this.name }) }
5129
+ }
5130
+
5131
+ /**
5132
+ * quilt_resolve_merge: settles one held conflict, named by its id or path. `how`: 'theirs' drops the
5133
+ * held lines (the file stays as it is), 'mine' puts them over the shared ones (merged with whatever
5134
+ * changed since), 'edited' says the resolved file is already written. Any member may resolve any
5135
+ * one; resolving one already resolved says so and changes nothing. { text, record, already }.
5136
+ */
5137
+ resolveHeld ({ ref, how, via = null }) {
5138
+ const map = this.doc.getMap(HELD_MAP)
5139
+ const rec = findHeld(map, ref)
5140
+ if (!rec) throw new Error(`There is no held conflict for ${ref || 'that'}: quilt_status lists the open ones.`)
5141
+ const who = this.actorName ? this.actorName(via) : this.name
5142
+ 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.` }
5143
+ let wrote = ''
5144
+ if (how === 'mine') wrote = this.applyHeldMine(rec)
5145
+ const r = settleHeld(this.doc, map, rec.id, { how, by: who }, LOCAL)
5146
+ 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.` }
5147
+ 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`
5148
+ this.log(`⚖️ ${who} resolved the held conflict in ${rec.path} ("${how}")`)
5149
+ return { already: false, record: r.record, text: `Resolved ${rec.path} (id ${rec.id}): ${said}.` }
5150
+ }
5151
+
5152
+ /** 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. */
5153
+ applyHeldMine (rec) {
5154
+ const dir = this.heldDir(rec.id)
5155
+ const local = (name) => { try { return fs.readFileSync(path.join(dir, name)) } catch { return null } }
5156
+ const onSquare = this.inSquare && this.inSquare.square
5157
+ const elsewhere = rec.where.square ? rec.where.square !== onSquare : rec.where.branch ? (this.inSquare || rec.where.branch !== this.branchKey()) : false
5158
+ 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".`)
5159
+ const abs = resolveInside(this.root, rec.path)
5160
+ if (rec.kind === 'binary') {
5161
+ const buf = local('mine')
5162
+ 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".`)
5163
+ fs.mkdirSync(path.dirname(abs), { recursive: true })
5164
+ fs.writeFileSync(abs, buf)
5165
+ if (!this.inSquare) this.ingest(rec.path)
5166
+ return 'their version of the file'
5167
+ }
5168
+ const mine = rec.mine ?? (local('mine') ? local('mine').toString('utf8') : null)
5169
+ const result = rec.result ?? (local('result') ? local('result').toString('utf8') : null)
5170
+ 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".`)
5171
+ let current = null
5172
+ if (this.inSquare) { try { current = fs.readFileSync(abs, 'utf8') } catch {} } else current = this.files.get(rec.path)?.toString() ?? null
5173
+ const text = applyMine({ mine, result }, current)
5174
+ if (this.inSquare) {
5175
+ // The folder's block takes it in as this member's edit (live-block.js scan), as a resolution: no stale-write check.
5176
+ this.liveRules().trust(rec.path, text)
5177
+ fs.mkdirSync(path.dirname(abs), { recursive: true })
5178
+ fs.writeFileSync(abs, text)
5179
+ } else this.applyMerged(rec.path, text, 'resolving a held conflict ("mine")')
5180
+ return `${rec.hunks.length + (rec.more || 0)} change(s)`
5181
+ }
5182
+
5094
5183
  /** Where this machine keeps a merge's base, ours and theirs (and PROMPT.md for Send to…). */
5095
5184
  mergeDir (id) { return path.join(this.stateDir, 'merges', id) }
5096
5185
 
@@ -5104,17 +5193,8 @@ export class Session extends EventEmitter {
5104
5193
  return { ours, base, theirs }
5105
5194
  }
5106
5195
 
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
- }
5196
+ /** A merge as status shows it: without its texts. */
5197
+ mergeStatus ({ ours, base, ...m }) { return m }
5118
5198
 
5119
5199
  // ------------------------------------------------------------ AI feed --
5120
5200
 
@@ -5283,8 +5363,8 @@ export class Session extends EventEmitter {
5283
5363
  const was = this.agentState?.status
5284
5364
  this.agentState = state ? { tool: state.tool || null, status: state.status || 'idle', ...(state.reason ? { reason: state.reason } : {}), ...(state.notes ? { notes: state.notes } : {}) } : null
5285
5365
  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(() => {})
5366
+ // Our AI finished its turn: its edits no longer say it is working.
5367
+ if (was === 'working' && this.agentState?.status !== 'working') this.aiEdits.clear()
5288
5368
  }
5289
5369
 
5290
5370
  publishAgentState () {
@@ -5304,7 +5384,7 @@ export class Session extends EventEmitter {
5304
5384
 
5305
5385
  /**
5306
5386
  * Every shared path with who last edited it (from activity and live
5307
- * presence) and the claim covering it. Read from the shared doc.
5387
+ * presence) and the box on it (someone's unfinished work). Read from the shared doc.
5308
5388
  */
5309
5389
  tree () {
5310
5390
  const edited = new Map()
@@ -5319,11 +5399,11 @@ export class Session extends EventEmitter {
5319
5399
  const editing = id === this.doc.clientID ? Object.fromEntries(this.myEdits) : (st.editing || {})
5320
5400
  for (const [p, ts] of Object.entries(editing)) note(p, st.name, ts)
5321
5401
  }
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)
5402
+ // `active` is false when whoever boxed it isn't in the session (older relays don't say: active).
5403
+ // Shown as people see it: an older app's AI session ("Dana · login", of: Dana) is its person.
5404
+ 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 } : {}) })
5405
+ const boxOf = (p) => {
5406
+ const c = this.boxAt(p)
5327
5407
  return c ? shown(c) : null
5328
5408
  }
5329
5409
  // Files that are GitHub's version, not edited in the session since (the relay marks them: relay-sync.js markFromGithub).
@@ -5336,16 +5416,15 @@ export class Session extends EventEmitter {
5336
5416
  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
5417
  for (const p of listed) {
5338
5418
  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 }
5419
+ if (square) { out.push({ path: p, binary: square.get(p), edited: edited.get(p) || null, box: boxOf(p), github: null }); continue }
5340
5420
  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) })
5421
+ 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
5422
  }
5343
5423
  out.push(...this.chatFileEntries())
5344
5424
  out.sort((a, b) => a.path.localeCompare(b.path))
5345
5425
  return {
5346
5426
  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)
5427
+ boxes: [...this.boxed.values()].map(shown)
5349
5428
  }
5350
5429
  }
5351
5430
 
@@ -5542,20 +5621,40 @@ export class Session extends EventEmitter {
5542
5621
  // The session's call: whether the owner has transcripts on, and the agents in it.
5543
5622
  voice: { transcribe: transcribeSetting(this.doc, this.members).on, agents: callAgents(this.doc, this.conn ? this.liveCall() : '', this.members) },
5544
5623
  peers,
5545
- claims: [...this.claims.values()].sort((a, b) => a.ts - b.ts),
5624
+ boxes: [...this.boxed.values()].sort((a, b) => a.ts - b.ts),
5546
5625
  tasks: this.taskList(),
5547
5626
  // Without the texts (up to 400 KB a record): status goes out on every
5548
5627
  // change. The full records are at GET /merges and the app's merges route.
5549
5628
  merges: this.mergeList().map((m) => this.mergeStatus(m)),
5629
+ // Held conflicts (held.js): every open one in the session, whoever's, until someone resolves it.
5630
+ held: this.heldList(),
5631
+ // How long a write may not remove lines someone else added (the owner's stale_write_minutes; 0: off).
5632
+ staleWriteMinutes: staleWriteMinutes(this.doc, this.members),
5550
5633
  catchUp: this.catchUp,
5551
5634
  activity: this.activity.toArray().slice(-30),
5552
5635
  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
5636
  chat: this.messages({ limit: 20, markRead: false }),
5554
5637
  unread: this.unreadCount(),
5555
- fileCount: this.files.size + this.blobs.size
5638
+ fileCount: this.sharedFileCount()
5556
5639
  }
5557
5640
  }
5558
5641
 
5642
+ /**
5643
+ * How many files the session shares here. Following a square in place, the folder is the square's live
5644
+ * copy (squareFiles), never the frozen branch document (2026-11-14: quilt_status said 4 with 5), looked
5645
+ * at no more than every few seconds.
5646
+ */
5647
+ sharedFileCount () {
5648
+ if (!this.inSquare) return this.files.size + this.blobs.size
5649
+ const now = Date.now()
5650
+ if (!this.squareCount || now - this.squareCount.at > 3000) {
5651
+ let n = 0
5652
+ try { n = (this.squareFiles() || new Map()).size } catch {}
5653
+ this.squareCount = { at: now, n }
5654
+ }
5655
+ return this.squareCount.n
5656
+ }
5657
+
5559
5658
  scheduleStatusWrite () {
5560
5659
  if (this.statusTimer || !this.ready) return
5561
5660
  this.statusTimer = setTimeout(() => {
@@ -5566,11 +5665,8 @@ export class Session extends EventEmitter {
5566
5665
 
5567
5666
  async stop () {
5568
5667
  this.ready = false
5569
- clearInterval(this.autoClaimTimer)
5668
+ clearInterval(this.editQuietTimer)
5570
5669
  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
5670
  this.stopped = true
5575
5671
  clearInterval(this.retryTimer)
5576
5672
  if (this.watcher) await closeWatcher(this.watcher)