heyquilt 0.3.170 → 0.3.172

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/RELEASES.md +30 -0
  2. package/bin/quilt.js +16 -9
  3. package/package.json +2 -2
  4. package/src/agent-task-workflow.js +2 -9
  5. package/src/base-pick.js +212 -0
  6. package/src/boxes.js +6 -7
  7. package/src/catchup.js +1 -1
  8. package/src/chat-links.js +1 -3
  9. package/src/connection.js +24 -5
  10. package/src/control.js +27 -20
  11. package/src/duties.js +32 -56
  12. package/src/github-commit.js +1 -1
  13. package/src/held.js +323 -0
  14. package/src/hooks.js +27 -66
  15. package/src/identity.js +1 -1
  16. package/src/inbox.js +5 -4
  17. package/src/key-cli.js +1 -1
  18. package/src/live-merge.js +599 -0
  19. package/src/mcp.js +57 -102
  20. package/src/merge3.js +65 -1
  21. package/src/now-summary.js +4 -6
  22. package/src/pathrules.js +1 -1
  23. package/src/persona.js +1 -1
  24. package/src/presence.js +2 -0
  25. package/src/protocol.js +2 -2
  26. package/src/read-bases.js +123 -0
  27. package/src/relay-ask.js +2 -2
  28. package/src/relay-live-write.js +179 -0
  29. package/src/relay-mcp.js +173 -212
  30. package/src/relay-prune.js +2 -2
  31. package/src/relay-turn-sync.js +146 -142
  32. package/src/runner.js +0 -2
  33. package/src/server.js +253 -375
  34. package/src/session-follow.js +3 -1
  35. package/src/session-quilt.js +2 -21
  36. package/src/session-seam.js +35 -7
  37. package/src/session.js +795 -553
  38. package/src/setup.js +15 -25
  39. package/src/source-live/bring-in.js +5 -5
  40. package/src/source-live/land.js +20 -3
  41. package/src/source-live/live-block.js +503 -52
  42. package/src/status.js +8 -12
  43. package/src/swap-in.js +81 -0
  44. package/src/textdiff.js +54 -0
  45. package/src/turn-sync-plan.js +6 -18
  46. package/src/turn-sync.js +28 -21
  47. package/src/ui/agent-guide.js +13 -13
  48. package/src/ui/app.css +19 -40
  49. package/src/ui/boxes.js +8 -16
  50. package/src/ui/common.js +1 -1
  51. package/src/ui/fileview.js +11 -15
  52. package/src/ui/loom-model.js +18 -16
  53. package/src/ui/loom.css +1 -2
  54. package/src/ui/loom.js +6 -6
  55. package/src/ui/rail-model.js +25 -64
  56. package/src/ui/rail.js +48 -60
  57. package/src/ui/seam-model.js +39 -3
  58. package/src/ui/session.js +36 -54
  59. package/src/ui/tree.js +22 -129
  60. package/src/ui-server.js +2 -6
  61. package/src/release-words.js +0 -18
  62. package/src/seam-claims.js +0 -53
@@ -24,15 +24,26 @@ import * as Y from 'yjs'
24
24
  import { Connection, REMOTE } from '../connection.js'
25
25
  import { FEATURES } from '../protocol.js'
26
26
  import { applyTextDiff } from '../textdiff.js'
27
- import { mergeAuto, mergeSmart } from '../merge3.js'
27
+ import { mergeLive } from '../merge3.js'
28
+ import { versionOf } from '../read-bases.js'
29
+ import { RecentTexts, atimeWorks, keepWritten, letGo } from '../base-pick.js'
30
+ import { swapIn } from '../swap-in.js'
31
+ import { findUses, removedNameWarning } from '../live-merge.js'
28
32
  // Seam's block folders and ids come from Seam's client package (@heyquilt/seam), never Seam's server code.
29
33
  import { blobId, under } from '@heyquilt/seam/lib/quilts/records.js'
30
34
  import { isText } from '@heyquilt/seam/lib/quilts/textdiff.js'
31
35
  import { checkout, findBlock, saveBlock, localChanges, conflictStyle, BLOCK_DIR } from '@heyquilt/seam/lib/quilts/block.js'
32
36
  import { liveKey, liveMaps, liveHead, entryOf, entryId, overlay } from './live-square.js'
37
+ import { readHeld, heldPathsOn, heldLandingNote } from '../held.js'
33
38
 
34
39
  export const MAX_LIVE_TEXT = 2 * 1024 * 1024
40
+ // A live write carries the text of its base up to this size, so the relay never has to ask for it.
41
+ const INLINE_BASE = 256 * 1024
35
42
  const SCAN_MS = 40
43
+ // This block's own file in the making (write, rescue): never anyone's edit.
44
+ const QUILT_TEMP = /^\..+\.quilt-(tmp|save)$/
45
+ // A file emptied this recently may be a save half done (truncated, not written yet): looked at again first.
46
+ const SETTLE_MS = 250
36
47
  // On macOS, Node's fs.watch shares one FSEvents stream per process and rebuilds it whenever a watch
37
48
  // is added or removed (another folder's block opening, this folder's next square after a merge), so
38
49
  // an edit in that gap is never delivered. The block looks at the folder this often too, as the
@@ -73,15 +84,17 @@ export class LiveBlock {
73
84
  * `onEdits(list, doc, held)`: the edits this folder made, as each scan takes them into the live
74
85
  * document `doc` ([{ path, kind: created|edited|deleted, detail, before?, after? }]), so the session
75
86
  * keeps them on record (who changed what) as it did on its branch; `held()` resolves once the relay
76
- * holds them.
87
+ * holds them. `rules`: the session's live-write engine (live-merge.js LiveRules): each edit is merged
88
+ * against what disk last had and the ways a clash is caught run on it; held lines go to the room.
77
89
  */
78
- constructor ({ dir, client, quilt, square, paths = [''], relay, api = '', inPlace = null, skip = null, skipDir = null, record = null, reader = null, log = null, onEdits = null, onWrite = null, started = null, stepMs = STEP_MS }) {
79
- Object.assign(this, { dir: path.resolve(dir), client, quilt, squareRef: square, paths, relayOpts: relay, api, inPlace, skip, skipDir, record, reader: reader || client, logFn: log, onEdits, onWrite, stepMs })
90
+ constructor ({ dir, client, quilt, square, paths = [''], relay, api = '', inPlace = null, skip = null, skipDir = null, record = null, reader = null, log = null, onEdits = null, onWrite = null, started = null, stepMs = STEP_MS, rules = null }) {
91
+ Object.assign(this, { dir: path.resolve(dir), client, quilt, squareRef: square, paths, relayOpts: relay, api, inPlace, skip, skipDir, record, reader: reader || client, logFn: log, onEdits, onWrite, stepMs, rules })
80
92
  // `started(block)`: told as it starts to open, so whoever waits for it can stop it part-way (abandon).
81
93
  if (started) started(this)
82
94
  this.known = {} // path -> { blob, mode, size, mtimeMs }: what is on disk as this block last read or wrote it
83
95
  this.cache = new Map() // blob id -> bytes (the snapshot's files this block wrote out)
84
96
  this.lastText = new Map() // path -> { id, text }: a live text as disk last had it (bytes no server holds), for combining (scan)
97
+ this.overwritten = new RecentTexts() // the texts a partner's change was lately written over here: a save's possible base (base-pick.js)
85
98
  this.queue = Promise.resolve()
86
99
  this.closed = false
87
100
  this.errors = []
@@ -254,7 +267,11 @@ export class LiveBlock {
254
267
  const m = liveMaps(this.doc)
255
268
  const firstLook = !this.inPlace.seen && !this.inPlace.fresh
256
269
  const own = firstLook && this.inPlace.own ? await this.inPlace.own() : null
257
- const disk = new Map(this.diskChanges({}).filter((c) => !this.skipped(c.path)).map((c) => [c.path, c]))
270
+ // A file being written as it is read is looked at again (diskChanges leaves it out meanwhile), never taken for absent.
271
+ let seen = this.diskChanges({})
272
+ for (let i = 0; i < 20 && this.unsettled; i++) { this.unsettled = false; await new Promise((resolve) => setTimeout(resolve, SETTLE_MS / 5)); seen = this.diskChanges({}) }
273
+ this.unsettled = false
274
+ const disk = new Map(seen.filter((c) => !this.skipped(c.path)).map((c) => [c.path, c]))
258
275
  const paths = new Set([...disk.keys(), ...Object.keys(this.block.files), ...m.files.keys(), ...m.blobs.keys(), ...m.gone.keys(), ...m.clean.keys()])
259
276
  const out = { same: 0, taken: [], brought: [], combined: [] }
260
277
  for (const p of [...paths].sort()) {
@@ -332,8 +349,8 @@ export class LiveBlock {
332
349
  * The folder's copy of `p` (disk entry `d`) combined with the square's, against what the folder last
333
350
  * had (the session's last sync of it, `inPlace.base`; after a restart, the blob the block last saw):
334
351
  * the bytes to write, or null when there is nothing to combine (the square did not change it since,
335
- * or that base is not known, or a side is not text). Where both changed the same lines, the folder's
336
- * edit is kept (mergeAuto, the folder's side newer) and the square's lines it replaced are said.
352
+ * or that base is not known, or a side is not text). Where both changed the same lines, nobody wins:
353
+ * the square's lines, which landed first, stay, and the folder's are held (live-merge.js, held.js).
337
354
  */
338
355
  async combineAway (p, d) {
339
356
  if (!d.bytes || d.mode === 'symlink' || !isText(d.bytes)) return null
@@ -358,13 +375,27 @@ export class LiveBlock {
358
375
  // A box on a file the folder never moved past: the box's work is the file now.
359
376
  if (base === ours) return want.bytes
360
377
  if (theirs === base) return null
361
- const r = mergeAuto(base, ours, theirs, { oursNewer: true })
362
- if (r.lost.length && this.logFn) this.logFn(`${p}: your edit made while away and the square's both changed the same lines; yours were kept, and the square's (${r.lost.reduce((n, x) => n + x.lines.length, 0)} line(s)) are in its history`)
363
- return r.text === ours ? null : Buffer.from(r.text, 'utf8')
378
+ const text = this.rules
379
+ ? this.rules.write({ doc: this.doc, where: { square: this.block.square }, path: p, base, ours, theirs, by: this.by, others: [this.writerOf(p)].filter(Boolean), texts: () => this.diskTexts() }).text
380
+ : mergeLive(base, ours, theirs).text
381
+ return text === ours ? null : Buffer.from(text, 'utf8')
364
382
  }
365
383
 
366
384
  skipped (p) { return !!(this.skip && this.skip(p)) }
367
385
 
386
+ /** Who last wrote `p` in the square (its writers map), or null. */
387
+ writerOf (p) { const w = this.doc && liveMaps(this.doc).writers.get(p); return (w && w.by) || null }
388
+
389
+ /** The folder's text files as [path, text], read as needed (the removed-name search). */
390
+ * diskTexts () {
391
+ for (const [p, k] of Object.entries(this.known)) {
392
+ if (!k || k.mode === 'symlink' || this.skipped(p) || (k.size > 0 && k.size > 512 * 1024)) continue
393
+ let bytes
394
+ try { bytes = fs.readFileSync(path.join(this.dir, ...p.split('/'))) } catch { continue }
395
+ if (bytes.length <= 512 * 1024 && isText(bytes)) yield [p, bytes.toString('utf8')]
396
+ }
397
+ }
398
+
368
399
  /** Whether `p` is inside a folder with a .git of its own (a submodule): never this block's to read or write. */
369
400
  nested (p) {
370
401
  const parts = p.split('/')
@@ -379,7 +410,11 @@ export class LiveBlock {
379
410
  * big folder is not read on every scan, nor one that is a repository of its own (a submodule).
380
411
  */
381
412
  diskChanges (files) {
382
- if (!this.inPlace) return localChanges(this.dir, { paths: this.block.paths, files })
413
+ if (!this.inPlace) {
414
+ // Seam's localChanges reads what changed: who read a file a partner's change was written into is asked first.
415
+ for (const p of [...this.overwritten.map.keys()]) { try { this.lookBeforeRead(p, fs.lstatSync(path.join(this.dir, ...p.split('/'))), files) } catch {} }
416
+ return localChanges(this.dir, { paths: this.block.paths, files })
417
+ }
383
418
  const out = []
384
419
  const seen = new Set()
385
420
  const visit = (rel) => {
@@ -390,19 +425,32 @@ export class LiveBlock {
390
425
  if (d.name === '.git' || d.name === BLOCK_DIR) continue
391
426
  // A folder with a .git of its own (a submodule, a repository inside this one) is its own: the square holds it as a gitlink at most.
392
427
  if (d.isDirectory()) { if (!(this.skipDir && this.skipDir(r)) && !fs.existsSync(path.join(this.dir, r, '.git'))) visit(r); continue }
393
- if (!(d.isFile() || d.isSymbolicLink()) || this.skipped(r)) continue
428
+ if (!(d.isFile() || d.isSymbolicLink()) || this.skipped(r) || QUILT_TEMP.test(d.name)) continue
394
429
  const abs = path.join(this.dir, r)
395
430
  let st
396
431
  try { st = fs.lstatSync(abs) } catch { continue }
397
432
  seen.add(r)
398
433
  const k = files[r]
399
434
  if (k && k.size === st.size && k.mtimeMs === st.mtimeMs) continue
435
+ this.lookBeforeRead(r, st, files)
400
436
  let bytes
401
437
  try { bytes = st.isSymbolicLink() ? Buffer.from(fs.readlinkSync(abs)) : fs.readFileSync(abs) } catch { continue }
402
438
  const mode = st.isSymbolicLink() ? 'symlink' : (st.mode & 0o111) && process.platform !== 'win32' ? 'exec' : 'file'
439
+ // Being written as it was read (it changed during the read, or it reads empty a moment after being
440
+ // emptied, as a save that truncates first does): looked at again shortly, never taken in half-written.
441
+ if (!st.isSymbolicLink()) {
442
+ let again = null
443
+ try { again = fs.lstatSync(abs) } catch {}
444
+ const midWrite = !again || again.size !== st.size || again.mtimeMs !== st.mtimeMs || bytes.length !== st.size
445
+ if (midWrite || (bytes.length === 0 && k && k.size > 0 && Date.now() - st.mtimeMs < SETTLE_MS)) { this.unsettled = true; continue }
446
+ }
403
447
  const id = blobId(bytes)
404
- if (k && k.blob === id && k.mode === mode) continue
405
- out.push({ path: r, status: k ? 'modified' : 'added', blob: id, mode, size: bytes.length, bytes })
448
+ // The same bytes (touched, or rewritten as they were): seen as of the look before this read.
449
+ if (k && k.blob === id && k.mode === mode) { if (files === this.known) files[r] = { ...k, size: st.size, mtimeMs: st.mtimeMs }; continue }
450
+ // `stat`: the file as it was just before this read. Recorded as seen, a save made after the read
451
+ // still differs from it, so the next scan reads it again (2026-11-14: a save between this read
452
+ // and a later look at the file was marked seen and never taken in).
453
+ out.push({ path: r, status: k ? 'modified' : 'added', blob: id, mode, size: bytes.length, bytes, stat: { size: st.size, mtimeMs: st.mtimeMs } })
406
454
  }
407
455
  }
408
456
  visit('')
@@ -418,12 +466,14 @@ export class LiveBlock {
418
466
  if (this.block.at !== this.head) return // 05: no ingest against the wrong base; pull re-projects first
419
467
  const m = liveMaps(this.doc)
420
468
  const snap = this.block.files
469
+ const readAt = Date.now()
421
470
  let changes = this.diskChanges(this.known)
471
+ if (this.unsettled) { this.unsettled = false; this.scanSoon(SCAN_MS * 2) }
422
472
  // What the session never syncs is never taken in; noting its size and time spares reading it again.
423
473
  for (const c of changes) {
424
474
  if (!this.skipped(c.path)) continue
425
475
  if (c.status === 'deleted') { delete this.known[c.path]; continue }
426
- try { const st = fs.lstatSync(path.join(this.dir, ...c.path.split('/'))); this.known[c.path] = { blob: c.blob, mode: c.mode, size: st.size, mtimeMs: st.mtimeMs } } catch {}
476
+ try { this.known[c.path] = { blob: c.blob, mode: c.mode, ...this.seenStat(c.path, c, readAt) } } catch {}
427
477
  }
428
478
  changes = changes.filter((c) => !this.skipped(c.path))
429
479
  if (!changes.length) return
@@ -447,9 +497,25 @@ export class LiveBlock {
447
497
  uploads = []
448
498
  }
449
499
  }
500
+ const taken = []
501
+ const rewrite = []
502
+ const moved = []
503
+ // A text edit goes to the relay as a write (relay-live-write.js): merged there against the version this
504
+ // folder last synced and applied in whole lines, one write at a time per file. What the relay doesn't
505
+ // take that way (an older relay, a refusal) and everything else (deletions, binaries) is edited here.
506
+ if (this.relayWrites()) {
507
+ const viaRelay = changes.filter((c) => this.relayWritable(c, uploads, m, snap))
508
+ const back = []
509
+ for (const c of viaRelay) {
510
+ if (this.closed) return
511
+ const how = await this.relayWrite(c, { m, snap, changes, readAt, taken, moved })
512
+ if (how === 'local') back.push(c)
513
+ }
514
+ changes = changes.filter((c) => !viaRelay.includes(c) || back.includes(c))
515
+ }
450
516
  // What each file held before, for the record of who changed what (onEdits): the live document's text, else the head's.
451
517
  const before = new Map()
452
- if (this.onEdits) {
518
+ if (this.onEdits || this.rules) {
453
519
  for (const c of changes) {
454
520
  const t = m.files.get(c.path)
455
521
  if (t) { before.set(c.path, t.toString()); continue }
@@ -478,13 +544,29 @@ export class LiveBlock {
478
544
  both.set(c.path, { base, head: head ? head.toString('utf8') : null })
479
545
  } catch {}
480
546
  }
481
- const taken = []
482
- const rewrite = []
483
547
  this.doc.transact(() => {
484
548
  for (const c of changes) {
485
549
  const p = c.path
486
550
  const base = snap[p]
487
551
  const had = !!(base && !m.gone.has(p)) || m.files.has(p) || m.blobs.has(p)
552
+ // A file another member moved away (deleted, the same text added elsewhere): this edit goes where it went.
553
+ if (this.rules && c.status !== 'deleted' && !had && c.mode !== 'symlink' && c.bytes.length <= MAX_LIVE_TEXT && isText(c.bytes)) {
554
+ const mv = this.rules.movedTo({ doc: this.doc, path: p, by: this.by })
555
+ const to = mv && m.files.get(mv.to)
556
+ if (to && !changes.some((x) => x.path === mv.to)) {
557
+ const last = this.lastText.get(p)
558
+ const r = this.rules.write({ doc: this.doc, where: { square: this.block.square }, path: mv.to, base: last ? last.text : mv.text, ours: c.bytes.toString('utf8'), theirs: to.toString(), by: this.by, others: [mv.by], texts: () => this.diskTexts() })
559
+ const was = to.toString()
560
+ const detail = applyTextDiff(to, r.text)
561
+ m.writers.set(mv.to, { by: this.by, ts: Date.now(), at: this.block.at })
562
+ taken.push({ path: mv.to, kind: 'edited', detail, before: was, after: r.text })
563
+ rewrite.push({ path: mv.to, bytes: Buffer.from(r.text, 'utf8'), mode: m.modes.get(mv.to) === 'exec' ? 'exec' : 'file' })
564
+ moved.push({ from: p, to: mv.to, by: mv.by })
565
+ continue
566
+ }
567
+ }
568
+ // Who wrote it before this edit: the one whose lines landed first, should they clash.
569
+ const prior = (m.writers.get(p) || {}).by || null
488
570
  // Whose work this path is now (on going back to git, its box is theirs: Session.leaveSquare), and the
489
571
  // head it was made on: the relay combines an edit made on a head it has moved on from (bring-in.js lateEdits).
490
572
  m.writers.set(p, { by: this.by, ts: Date.now(), at: this.block.at })
@@ -492,6 +574,8 @@ export class LiveBlock {
492
574
  if (base) { m.clean.delete(p); m.gone.set(p, { by: this.by, ts: Date.now() }) } else m.clean.set(p, { at: this.block.at })
493
575
  delete this.known[p]
494
576
  if (had) taken.push({ path: p, kind: 'deleted', detail: '', ...(before.has(p) ? { before: before.get(p), after: '' } : {}) })
577
+ // With the same text added elsewhere by this folder, a move (edits others make to it follow it).
578
+ if (this.rules && before.has(p)) this.rules.noteGone({ doc: this.doc, path: p, text: before.get(p), by: this.by })
495
579
  continue
496
580
  }
497
581
  const kind = had ? 'edited' : 'created'
@@ -511,29 +595,233 @@ export class LiveBlock {
511
595
  let after = c.bytes.toString('utf8')
512
596
  const w = both.get(p)
513
597
  const cur = w ? (fresh ? w.head : t.toString()) : null
514
- if (w && cur !== null && cur !== w.base && cur !== after) {
515
- const r = mergeSmart(w.base, after, cur)
516
- // The same lines changed on both sides: the newer edit, this one, wins them (as everywhere in Quilt).
517
- after = r.conflicts.length ? mergeAuto(w.base, after, cur, { oursNewer: true }).text : r.text
518
- if (after !== c.bytes.toString('utf8')) rewrite.push({ path: p, bytes: Buffer.from(after, 'utf8'), mode: c.mode })
598
+ if (this.rules) {
599
+ // Merged against what disk last had, and the ways a clash is caught run on it (live-merge.js):
600
+ // lines both changed keep what landed first, this folder's are held, and disk gets the result.
601
+ const theirs = cur !== null ? cur : fresh ? (before.has(p) ? before.get(p) : null) : t.toString()
602
+ after = this.rules.write({ doc: this.doc, where: { square: this.block.square }, path: p, base: w ? w.base : theirs, ours: after, theirs, by: this.by, others: [prior].filter(Boolean), texts: () => this.diskTexts() }).text
603
+ } else if (w && cur !== null && cur !== w.base && cur !== after) {
604
+ // No engine (a block opened outside a session): what landed first keeps the lines both changed,
605
+ // and this folder's are said in its log, never dropped without a word.
606
+ const r = mergeLive(w.base, after, cur)
607
+ after = r.text
608
+ if (r.held.length && this.logFn) this.logFn(`${p}: someone changed the same lines first, so the square keeps theirs; your lines there:\n${r.held.flatMap((h) => h.ours).slice(0, 20).map((l) => `- ${l}`).join('\n')}`)
519
609
  }
610
+ if (after !== c.bytes.toString('utf8')) rewrite.push({ path: p, bytes: Buffer.from(after, 'utf8'), mode: c.mode })
520
611
  let detail = applyTextDiff(t, after)
521
612
  this.lastText.set(p, { id: blobId(Buffer.from(after, 'utf8')), text: after })
522
613
  // A file new to the live document took its whole text: what changed is measured from the head's.
523
614
  if (fresh && before.has(p)) { const probe = new Y.Doc().getText(); probe.insert(0, before.get(p)); detail = applyTextDiff(probe, after) }
524
615
  if (c.mode === 'exec') m.modes.set(p, 'exec'); else if (m.modes.has(p)) m.modes.delete(p)
525
616
  if (detail || !had) taken.push({ path: p, kind, detail, before: before.get(p) ?? '', after })
617
+ if (!had && this.rules) this.rules.noteNew({ doc: this.doc, path: p, text: after, by: this.by })
526
618
  }
527
- const st = fs.lstatSync(path.join(this.dir, ...p.split('/')))
528
- this.known[p] = { blob: c.blob, mode: c.mode, size: st.size, mtimeMs: st.mtimeMs }
619
+ this.known[p] = { blob: c.blob, mode: c.mode, ...this.seenStat(p, c, readAt) }
529
620
  }
530
621
  })
531
- // Disk gets the combination: what the square had that this edit was not made on.
532
- for (const x of rewrite) this.write(x.path, x)
622
+ // Disk gets the combination: what the square had that this edit was not made on. Never over a save
623
+ // made since this scan read the file: that save is taken in next, merged with the combination.
624
+ for (const x of rewrite) {
625
+ if (this.write(x.path, x, { guard: true }) === false) {
626
+ const c = changes.find((y) => y.path === x.path)
627
+ if (c && c.bytes) this.lastText.set(x.path, { id: c.blob, text: c.bytes.toString('utf8') })
628
+ this.scanSoon()
629
+ }
630
+ }
631
+ // An edit to a moved file went to where it went: the old path comes off disk again.
632
+ for (const mv of moved) {
633
+ this.write(mv.from, null)
634
+ if (this.rules) this.rules.notice(`${mv.by} moved ${mv.from} to ${mv.to}; your edit to ${mv.from} went into ${mv.to}. Edit ${mv.to} from now on.`)
635
+ if (this.logFn) this.logFn(`${mv.from} was moved to ${mv.to} by ${mv.by}: your edit went there`)
636
+ }
533
637
  this.saveSoon()
534
638
  if (this.onEdits && taken.length) { try { this.onEdits(taken, this.doc, () => this.conn.confirmBranch()) } catch (err) { if (this.logFn) this.logFn(`could not record ${taken.length} edit(s): ${err.message}`) } }
535
639
  }
536
640
 
641
+ /** Whether the relay takes this folder's text edits as writes (relay-live-write.js), and this block may send them. */
642
+ relayWrites () { return !!(this.conn && this.conn.relayWrites && !this.noRelayWrites && this.conn.connected !== false) }
643
+
644
+ /** A change the relay takes as a write: a text file's new content (not a deletion, a binary, a link, or a file back as the head has it with nobody's live text on it). */
645
+ relayWritable (c, uploads, m, snap) {
646
+ if (c.status === 'deleted' || c.mode === 'symlink' || !c.bytes || c.bytes.length > MAX_LIVE_TEXT || !isText(c.bytes)) return false
647
+ if (uploads.some((u) => u.id === c.blob)) return false
648
+ const head = snap[c.path]
649
+ if (head && head.blob === c.blob && head.mode === c.mode && !m.files.has(c.path)) return false
650
+ return true
651
+ }
652
+
653
+ /**
654
+ * What disk had of `p` as this block last synced it: the text its last write or write-out left (lastText),
655
+ * else the head's file when that is what it had, else the blob it knew; null when not known.
656
+ */
657
+ async syncedText (p) {
658
+ const k = this.known[p]
659
+ if (!k || !k.blob) return null
660
+ const last = this.lastText.get(p)
661
+ if (last && last.id === k.blob) return last.text
662
+ try { const b = await this.bytesOf(k.blob); return isText(b) ? b.toString('utf8') : null } catch { return null }
663
+ }
664
+
665
+ /**
666
+ * One text edit, as a write to the relay. 'done' (in, and disk has the result unless it was saved again
667
+ * meanwhile), 'local' (the relay asked for it to be edited here as before), or 'later' (not sent: the
668
+ * next scan tries again, and nothing is written over it meanwhile).
669
+ */
670
+ async relayWrite (c, { m, snap, changes, readAt, taken, moved }) {
671
+ const p = c.path
672
+ const text = c.bytes.toString('utf8')
673
+ const had = !!(snap[p] && !m.gone.has(p)) || m.files.has(p) || m.blobs.has(p)
674
+ // A file another member moved away (deleted, the same text added elsewhere): this edit goes where it went.
675
+ let target = p
676
+ let mv = null
677
+ let base
678
+ if (this.rules && !had) {
679
+ const to = this.rules.movedTo({ doc: this.doc, path: p, by: this.by })
680
+ if (to && m.files.get(to.to) && !changes.some((x) => x.path === to.to)) { mv = to; target = to.to }
681
+ }
682
+ if (mv) { const last = this.lastText.get(p); base = last ? last.text : mv.text } else base = await this.syncedText(p)
683
+ // Made from the text a partner's change was just written over (an editor's older read)? It goes too
684
+ // (`older`): the relay puts the save onto the base, and where the partner changed it since, the newer lines stay.
685
+ const older = !mv && typeof base === 'string' ? this.overwritten.pick(p, base, text) : base
686
+ // Where this folder can tell who read its files, it vouches for the base (`seen`): nothing is held for merely looking like an older read.
687
+ const seen = !mv && typeof base === 'string' && this.overwritten.sure(p, base, this.atimeOn())
688
+ const known = !!this.known[p]
689
+ const trusted = !!(this.rules && this.rules.trusted && this.rules.trusted.get(target) === text)
690
+ const req = {
691
+ path: target,
692
+ base: typeof base === 'string' ? versionOf(base) : null,
693
+ // Small, or not live yet (the head's text, which the relay never reads): its text goes with it.
694
+ ...(typeof base === 'string' && (base.length <= INLINE_BASE || !m.files.has(target)) ? { baseText: base } : {}),
695
+ // Known here but its text is not (after a restart): the relay merges it as a stale write.
696
+ ...(typeof base !== 'string' && known && !mv ? { baseUnknown: true } : {}),
697
+ text,
698
+ ...(older !== base && typeof older === 'string' ? { older } : {}),
699
+ ...(seen ? { seen: true } : {}),
700
+ mode: c.mode,
701
+ at: this.block.at,
702
+ ...(trusted ? { trusted: true } : {})
703
+ }
704
+ let r
705
+ try {
706
+ r = await this.conn.liveWrite(req, { baseOf: () => (typeof base === 'string' ? base : null) })
707
+ } catch (err) {
708
+ if (/unknown branch request/.test(err.message)) { this.noRelayWrites = true; return 'local' }
709
+ if (this.logFn && this.writeProblem !== err.message) this.logFn(`${p}: your edit waits to reach the square (${err.message}); it is tried again`)
710
+ this.writeProblem = err.message
711
+ this.scanSoon(1000)
712
+ return 'later'
713
+ }
714
+ this.writeProblem = null
715
+ if (r.fallback) return 'local'
716
+ if (trusted) this.rules.trusted.delete(target)
717
+ const result = r.same ? text : r.text
718
+ // Seen as read; disk gets the result only if it was not saved again since (then that save comes next, on this text).
719
+ if (mv) {
720
+ this.write(p, null)
721
+ const want = { bytes: Buffer.from(result, 'utf8'), mode: m.modes.get(target) === 'exec' ? 'exec' : 'file' }
722
+ this.write(target, want, { guard: true })
723
+ moved.push({ from: p, to: target, by: mv.by })
724
+ } else {
725
+ this.overwritten.forget(p)
726
+ this.known[p] = { blob: c.blob, mode: c.mode, ...this.seenStat(p, c, readAt) }
727
+ this.lastText.set(p, { id: c.blob, text })
728
+ if (result !== text) {
729
+ // What landed first is written over this save: a next save made without reading it is told apart (base-pick.js).
730
+ const kept = {}
731
+ if (this.write(p, { bytes: Buffer.from(result, 'utf8'), mode: c.mode }, { guard: true, keep: kept, before: text }) === false) this.scanSoon()
732
+ else this.overwritten.note(p, text, kept.wrote || null)
733
+ }
734
+ }
735
+ for (const n of r.notices || []) { try { if (this.rules) this.rules.notice(n) } catch {} }
736
+ for (const l of r.logs || []) if (this.logFn) this.logFn(l)
737
+ for (const x of r.local || []) { try { if (this.rules && this.rules.keepLocal) this.rules.keepLocal(x.id, { result: x.result, mine: x.mine }) } catch {} }
738
+ // Names this write removed that other files here still use: said to the writer, never a block.
739
+ if (this.rules && Array.isArray(r.gone) && r.gone.length) {
740
+ let uses = []
741
+ try { uses = findUses(r.gone, this.diskTexts(), { skip: target }) } catch {}
742
+ const w = removedNameWarning(target, uses)
743
+ if (w) { this.rules.notice(w); if (this.logFn) this.logFn(`⚠️ ${w}`) }
744
+ }
745
+ if (r.detail || !had) taken.push({ path: target, kind: had || mv ? 'edited' : 'created', detail: r.detail || '', before: r.before ?? '', after: result })
746
+ if (!had && !mv && this.rules) this.rules.noteNew({ doc: this.doc, path: p, text: result, by: this.by })
747
+ return 'done'
748
+ }
749
+
750
+ /**
751
+ * The size and time to record for a change this scan read: the file as it was just before the read
752
+ * (diskChanges' `stat`); else, when it was changed around the time of the read, none (-1), so it is
753
+ * read again rather than taken as seen (Seam's own walk, which does not say).
754
+ */
755
+ seenStat (p, c, readAt) {
756
+ if (c.stat) return { size: c.stat.size, mtimeMs: c.stat.mtimeMs }
757
+ try {
758
+ const st = fs.lstatSync(path.join(this.dir, ...p.split('/')))
759
+ if (st.mtimeMs >= readAt - 5 || st.size !== c.bytes.length) return { size: -1, mtimeMs: -1 }
760
+ return { size: st.size, mtimeMs: st.mtimeMs }
761
+ } catch { return { size: -1, mtimeMs: -1 } }
762
+ }
763
+
764
+ /**
765
+ * The file at `p` (`st`, its lstat) changed since this block saw it and is about to be read: if a partner's
766
+ * change was written into it lately, who read it since is asked first (base-pick.js), before this read.
767
+ */
768
+ lookBeforeRead (p, st, files = this.known) {
769
+ if (!this.overwritten.has(p)) return
770
+ const k = files[p]
771
+ if (k && st && k.size === st.size && k.mtimeMs === st.mtimeMs) return
772
+ this.overwritten.look(p, st, { atime: this.atimeOn() })
773
+ }
774
+
775
+ /**
776
+ * swap-in.js for this block (the second name beside its record, in .quilt/tmp): false when the file at the
777
+ * path is a save not taken in (nothing replaced); else the bytes of a save written into the file replaced
778
+ * (or null). A save replaced in the one system call swap-in.js cannot cover is said to its writer.
779
+ */
780
+ swapInto (p, abs, tmp, look) {
781
+ const r = swapIn(abs, tmp, look, { asideDir: this.record ? path.join(path.dirname(this.record), 'tmp') : null })
782
+ if (r.replaced) {
783
+ const w = `A save of ${p} landed in the same instant Quilt wrote the square's version over it, and could not be kept: save ${p} again (your editor still has it).`
784
+ try { if (this.rules) this.rules.notice(w) } catch {}
785
+ if (this.logFn) this.logFn(`⚠️ ${w}`)
786
+ }
787
+ return r.placed ? r.displaced : false
788
+ }
789
+
790
+ /** Whether this folder's disk shows who read a file (base-pick.js atimeWorks), looked at once. */
791
+ atimeOn () {
792
+ if (this.atimeSeen === undefined) this.atimeSeen = atimeWorks(this.dir)
793
+ return this.atimeSeen
794
+ }
795
+
796
+ /**
797
+ * Whether `p` on disk changed since this block last read or wrote it (a save not taken in yet): then
798
+ * nothing is written over it. A different size or time with the same bytes is no change (and is
799
+ * noted as seen).
800
+ */
801
+ diskMoved (p) {
802
+ const abs = path.join(this.dir, ...p.split('/'))
803
+ const k = this.known[p]
804
+ let st
805
+ try { st = fs.lstatSync(abs) } catch { return !!k } // gone here but known: a deletion not taken in yet
806
+ if (!k) return true // a file here this block never took in
807
+ if (k.size === st.size && k.mtimeMs === st.mtimeMs) return false
808
+ this.lookBeforeRead(p, st)
809
+ let bytes
810
+ try { bytes = st.isSymbolicLink() ? Buffer.from(fs.readlinkSync(abs)) : fs.readFileSync(abs) } catch { return true }
811
+ const mode = st.isSymbolicLink() ? 'symlink' : (st.mode & 0o111) && process.platform !== 'win32' ? 'exec' : 'file'
812
+ if (blobId(bytes) !== k.blob || (k.mode && mode !== k.mode && k.mode !== 'conflict')) return true
813
+ this.known[p] = { ...k, size: st.size, mtimeMs: st.mtimeMs }
814
+ return false
815
+ }
816
+
817
+ /** A scan soon (a save to take in that a write-out left alone, or a write to send again). */
818
+ scanSoon (ms = SCAN_MS) {
819
+ if (this.closed) return
820
+ clearTimeout(this.scanTimer)
821
+ this.scanTimer = setTimeout(() => this.run(() => this.scan()), ms)
822
+ this.scanTimer.unref?.()
823
+ }
824
+
537
825
  /** Bytes of a blob, from this block's cache or the server. */
538
826
  async bytesOf (id) {
539
827
  if (!this.cache.has(id)) {
@@ -564,25 +852,174 @@ export class LiveBlock {
564
852
  return s ? this.headFile(p, s) : null
565
853
  }
566
854
 
567
- write (p, want) {
855
+ /**
856
+ * Puts `want` on disk at `p` (null: removes it). `guard`: only if disk still has what this block last
857
+ * read or wrote there (diskMoved), looked at again just before the file is replaced; false when it was
858
+ * left alone, so a save made meanwhile is taken in (and merged) rather than overwritten.
859
+ */
860
+ write (p, want, { guard = false, keep = null, before: was = null } = {}) {
568
861
  const abs = path.join(this.dir, ...p.split('/'))
569
- if (!want) { fs.rmSync(abs, { force: true }); delete this.known[p]; this.lastText.delete(p); this.wrote(p); return }
862
+ if (guard && this.diskMoved(p)) return false
863
+ if (!want) { fs.rmSync(abs, { force: true }); delete this.known[p]; this.lastText.delete(p); this.wrote(p); return true }
570
864
  fs.mkdirSync(path.dirname(abs), { recursive: true })
571
865
  const tmp = path.join(path.dirname(abs), `.${path.basename(abs)}.quilt-tmp`)
572
- if (want.mode === 'symlink') { fs.rmSync(abs, { force: true }); fs.symlinkSync(want.bytes.toString('utf8'), abs) } else {
866
+ // What is recorded as seen is the written file as it was before it took its place (a rename keeps its
867
+ // size and time): a save that lands right after it differs from it, so it is taken in, never taken as
868
+ // this write (2026-11-14: a save between the rename and a look at the file afterwards was lost).
869
+ let st
870
+ if (want.mode === 'symlink') { fs.rmSync(abs, { force: true }); fs.symlinkSync(want.bytes.toString('utf8'), abs); st = fs.lstatSync(abs) } else {
573
871
  fs.writeFileSync(tmp, want.bytes, { mode: want.mode === 'exec' ? 0o755 : 0o644 })
574
- fs.renameSync(tmp, abs)
872
+ st = fs.lstatSync(tmp)
873
+ const last = this.lastText.get(p)
874
+ // What disk had (`was`, when the caller read it): a save that lands in or takes the place of the file replaced was made from it.
875
+ const before = typeof was === 'string' ? was : last && this.known[p] && last.id === this.known[p].blob ? last.text : null
876
+ const placed = this.place(p, abs, tmp, { guard, before, wrote: want.bytes, keep })
877
+ if (!placed) return false
575
878
  }
576
- const st = fs.lstatSync(abs)
577
879
  this.known[p] = { blob: blobId(want.bytes), mode: want.mode, size: st.size, mtimeMs: st.mtimeMs }
578
880
  if (this.doc && liveMaps(this.doc).files.has(p) && want.bytes.length <= MAX_LIVE_TEXT) this.lastText.set(p, { id: this.known[p].blob, text: want.bytes.toString('utf8') })
579
881
  else this.lastText.delete(p)
580
882
  this.saveSoon()
581
883
  this.wrote(p)
884
+ return true
582
885
  }
583
886
 
584
887
  wrote (p) { if (this.onWrite) { try { this.onWrite(p) } catch {} } }
585
888
 
889
+ /**
890
+ * Puts `tmp` in the place of `abs` (a rename). `guard`: not when disk changed since this block last
891
+ * saw it (diskMoved): false then. A save into the file being replaced, landing in the instant between
892
+ * that look and the rename (an editor that truncates and writes, opened just before it), would be
893
+ * gone with the old file: the old file stays open across the rename, and what was saved into it after
894
+ * the look is put back as a save of its own (rescue, looked at again 100 ms later too), taken in by the next
895
+ * scan. The replace is always one rename (the file is never absent); a save that took the file's place by a
896
+ * rename of its own before the last look is never replaced (swap-in.js): false, and it is taken in. `keep`: an object that gets the written file kept open (`wrote`, base-pick.js keepWritten).
897
+ */
898
+ place (p, abs, tmp, { guard = false, before = null, wrote = null, keep = null } = {}) {
899
+ let old = null
900
+ let look = null
901
+ let kept = null
902
+ let displaced = null
903
+ if (guard) { try { old = fs.openSync(abs, 'r'); look = fs.lstatSync(abs) } catch {} }
904
+ try {
905
+ // As it was before the look below: a save into it after this is either seen by that look or after the rename.
906
+ const seen = old !== null ? fs.fstatSync(old) : null
907
+ // Changed since this block saw it, or replaced since it was opened (look is another file): left alone.
908
+ if (guard && (this.diskMoved(p) || (look && seen && !look.isSymbolicLink() && look.ino !== seen.ino))) { fs.rmSync(tmp, { force: true }); return false }
909
+ if (keep) kept = keepWritten(tmp)
910
+ if (guard && old === null) {
911
+ // Nothing there at the look: put in only if nothing is there now (a hard link never replaces a save made meanwhile).
912
+ try { fs.linkSync(tmp, abs); fs.rmSync(tmp, { force: true }) } catch (err) {
913
+ if (err.code !== 'EEXIST') fs.renameSync(tmp, abs)
914
+ else {
915
+ fs.rmSync(tmp, { force: true })
916
+ let dir = false
917
+ try { dir = fs.lstatSync(abs).isDirectory() } catch {}
918
+ if (dir) throw err // a folder where the file goes: as a rename would fail
919
+ return false
920
+ }
921
+ }
922
+ } else if (old !== null && look && !look.isSymbolicLink()) {
923
+ // Never over a save it can see (swap-in.js): one that took the file's place since the look is taken in first.
924
+ displaced = this.swapInto(p, abs, tmp, look)
925
+ if (displaced === false) return false
926
+ } else fs.renameSync(tmp, abs)
927
+ if (keep) { keep.wrote = kept; kept = null }
928
+ if (old !== null) {
929
+ const now = fs.fstatSync(old)
930
+ // A save written into the file replaced: back as a save of its own, once whole (rescue), or at once.
931
+ if (now.size !== seen.size || now.mtimeMs !== seen.mtimeMs) { this.rescue(p, old, { before, wrote }); old = null } else if (displaced) { const bytes = displaced; setImmediate(() => { this.run(() => this.putBack(p, bytes, { before, wrote })).catch(() => {}) }) } else {
932
+ // An editor that opened the file just before the rename may write into it a moment after: looked at once more.
933
+ const fd = old
934
+ old = null
935
+ const t = setTimeout(() => {
936
+ let later = null
937
+ try { later = fs.fstatSync(fd) } catch {}
938
+ if (!this.closed && later && (later.size !== seen.size || later.mtimeMs !== seen.mtimeMs)) this.rescue(p, fd, { before, wrote })
939
+ else { try { fs.closeSync(fd) } catch {} }
940
+ }, 100)
941
+ t.unref?.()
942
+ }
943
+ }
944
+ return true
945
+ } finally {
946
+ letGo(kept)
947
+ if (old !== null) { try { fs.closeSync(old) } catch {} }
948
+ }
949
+ }
950
+
951
+ /**
952
+ * A save that landed in a file this block replaced (place): once it is written out in full, it goes back
953
+ * on disk as a save of its own. Saved again since (from what this block wrote, without it): its own
954
+ * change goes onto that newer save (`before`: what disk had before the write, `wrote`: the write), the
955
+ * newer one winning where both changed a line, so neither is lost.
956
+ */
957
+ async rescue (p, fd, { before = null, wrote = null } = {}) {
958
+ try {
959
+ let last = null
960
+ for (let i = 0; i < 50; i++) {
961
+ const st = fs.fstatSync(fd)
962
+ if (last && st.size === last.size && st.mtimeMs === last.mtimeMs) break
963
+ last = st
964
+ await new Promise((resolve) => setTimeout(resolve, 20))
965
+ }
966
+ const size = fs.fstatSync(fd).size
967
+ const bytes = Buffer.alloc(size)
968
+ let off = 0
969
+ while (off < size) { const n = fs.readSync(fd, bytes, off, size - off, off); if (!n) break; off += n }
970
+ if (this.closed) return
971
+ await this.run(() => this.putBack(p, bytes, { before, wrote }))
972
+ } catch {} finally { try { fs.closeSync(fd) } catch {} }
973
+ }
974
+
975
+ /**
976
+ * A save of `p` (`bytes`) that this block's write took out of the path (it landed in the file replaced, or
977
+ * took that file's place in the instant before) goes back on disk as a save of its own: over what this block
978
+ * wrote, whole; saved again since (from what this block wrote, without it), its own change (`before`: what
979
+ * disk had before the write, `wrote`: the write) goes onto that newer save, both kept where both changed a
980
+ * line. Run in the block's queue.
981
+ */
982
+ async putBack (p, bytes, { before = null, wrote = null } = {}) {
983
+ const abs = path.join(this.dir, ...p.split('/'))
984
+ const k = this.known[p]
985
+ if (k && k.blob === blobId(bytes)) return
986
+ const tmp = path.join(path.dirname(abs), `.${path.basename(abs)}.quilt-save`)
987
+ const mode = k && k.mode === 'exec' ? 0o755 : 0o644
988
+ // Put back only over the file as looked at (place, swap-in.js): saved again in that instant, looked at again.
989
+ let placed = false
990
+ let ours = false
991
+ for (let attempt = 0; attempt < 5 && !placed; attempt++) {
992
+ if (!this.diskMoved(p)) {
993
+ // Disk still has what this block wrote: the save goes back over it.
994
+ ours = true
995
+ fs.writeFileSync(tmp, bytes, { mode })
996
+ placed = this.place(p, abs, tmp, { guard: true })
997
+ continue
998
+ }
999
+ ours = false
1000
+ let look = null
1001
+ try { look = fs.lstatSync(abs) } catch {}
1002
+ let now = null
1003
+ try { now = fs.readFileSync(abs) } catch {}
1004
+ if (!now || !look || typeof before !== 'string' || !wrote || !isText(bytes) || !isText(now)) return
1005
+ const onto = mergeLive(before, bytes.toString('utf8'), wrote.toString('utf8')).text
1006
+ // Both saves are this folder's: where they changed the same place, both go in (nothing is lost; its writer sees both).
1007
+ const merged = mergeLive(wrote.toString('utf8'), onto, now.toString('utf8'), { union: true }).text
1008
+ if (merged === now.toString('utf8')) return
1009
+ fs.writeFileSync(tmp, merged, { mode })
1010
+ // Only over that newer save as it is (it is taken in with the late one's change on it).
1011
+ if (look.isSymbolicLink()) { fs.rmSync(tmp, { force: true }); return }
1012
+ const again = this.swapInto(p, abs, tmp, look)
1013
+ placed = again !== false
1014
+ if (again) { const was = now; setImmediate(() => { this.run(() => this.putBack(p, again, { before: was.toString('utf8'), wrote: Buffer.from(merged, 'utf8') })).catch(() => {}) }) }
1015
+ }
1016
+ if (!placed) { this.scanSoon(); return }
1017
+ // Made from what disk had before this block's write, which it landed in: merged against that (base-pick.js).
1018
+ if (ours && typeof before === 'string' && isText(bytes)) this.overwritten.mark(p, bytes.toString('utf8'), before)
1019
+ if (this.logFn) this.logFn(`${p}: a save landed while Quilt wrote the session's version; it is taken in now`)
1020
+ this.scanSoon()
1021
+ }
1022
+
586
1023
  /** Moves the block to the document's head (a commit by anyone in the square), then writes the overlay out. */
587
1024
  async pull () {
588
1025
  if (this.closed) return
@@ -599,7 +1036,13 @@ export class LiveBlock {
599
1036
  const want = await this.wanted(p)
600
1037
  const id = want ? blobId(want.bytes) : null
601
1038
  const have = this.known[p] ? this.known[p].blob : null
602
- if (id !== have || (want && this.known[p].mode !== want.mode)) this.write(p, want)
1039
+ // Never over a save not taken in yet (one made since the scan above): the next scan merges it.
1040
+ if (id !== have || (want && this.known[p].mode !== want.mode)) {
1041
+ const was = have && want ? await this.syncedText(p) : null
1042
+ const kept = typeof was === 'string' ? {} : null
1043
+ if (this.write(p, want, { guard: true, keep: kept, before: was }) === false) this.scanSoon()
1044
+ else if (typeof was === 'string') this.overwritten.note(p, was, kept.wrote || null) // a save made from it is told apart (base-pick.js), by who reads the file written
1045
+ }
603
1046
  } catch (err) { failed.push({ path: p, err }) }
604
1047
  }
605
1048
  this.noteOutOfStep(failed)
@@ -628,7 +1071,7 @@ export class LiveBlock {
628
1071
  // Already on disk as the new head has it (the commit was made from this very work): left alone.
629
1072
  const k = this.known[f.path]
630
1073
  if (e ? k && e.mode !== 'conflict' && k.blob === e.blob && k.mode === e.mode : !k) continue
631
- this.write(f.path, e ? await this.headFile(f.path, b.files[f.path], `c:${to}`) : null)
1074
+ if (this.write(f.path, e ? await this.headFile(f.path, b.files[f.path], `c:${to}`) : null, { guard: true }) === false) this.scanSoon()
632
1075
  }
633
1076
  b.at = to
634
1077
  // A square with no commit of its own (a rebase only moved its base): a commit's expect_head is none.
@@ -649,10 +1092,18 @@ export class LiveBlock {
649
1092
  return overlay(this.doc).map((e) => ({ path: e.path, status: e.op === 'delete' ? 'deleted' : this.block.files[e.path] ? 'modified' : 'added' }))
650
1093
  }
651
1094
 
1095
+ /** Paths with an open held conflict on this square (held.js, in the room's document): they stay live until it is resolved. */
1096
+ heldPaths () {
1097
+ const map = this.rules && this.rules.heldMap ? this.rules.heldMap() : null
1098
+ return map && this.block ? heldPathsOn(readHeld(map), this.block.square) : []
1099
+ }
1100
+
652
1101
  /**
653
1102
  * Seals the live document as a commit on the square: the overlay (every writer's work, not only
654
1103
  * this folder's) is committed through the API with the head it is relative to as `expect_head`,
655
- * then the relay moves the head and drops what was committed (live-square.js `seal`).
1104
+ * then the relay moves the head and drops what was committed (live-square.js `seal`). A path with
1105
+ * an open held conflict (Seam's 07 "Terms held aside") stays live and the rest is committed
1106
+ * (`left_held`); with nothing else to commit it is refused (code 'held_conflict', naming them).
656
1107
  */
657
1108
  async commit ({ message = '' } = {}) {
658
1109
  if (!this.client) throw new Error('sign in to Seam first (quilt login, or set SEAM_TOKEN): a commit is made as you')
@@ -663,23 +1114,21 @@ export class LiveBlock {
663
1114
  // the live document names it (a square from before 0.3.135's switch took agents' scratch files in).
664
1115
  let list = overlay(this.doc).filter((e) => !(this.skipped(e.path) && !this.block.files[e.path]))
665
1116
  if (!list.length) return { nothing: true }
1117
+ // A path with an open held conflict never lands until it is resolved; one such file never holds back the rest.
1118
+ const held = new Set(this.heldPaths())
1119
+ const leftHeld = list.filter((e) => held.has(e.path)).map((e) => e.path)
1120
+ list = list.filter((e) => !held.has(e.path))
1121
+ if (!list.length) {
1122
+ const err = new Error(heldLandingNote(leftHeld, { none: true }))
1123
+ err.code = 'held_conflict'
1124
+ err.paths = leftHeld
1125
+ throw err
1126
+ }
666
1127
  const uploads = list.filter((e) => e.bytes).map((e) => ({ kind: 'blob', id: blobId(e.bytes), bytes: e.bytes }))
667
1128
  if (uploads.length) await this.client.upload(this.block.quilt, uploads)
668
- // A file another square claims stays live and the rest is committed, so one claimed file never
669
- // holds back everything else the folder holds (2026-11-05: web/AGENTS.md, claimed by Brandon,
670
- // kept 30 files from landing); it is committed once the claim ends. All claimed is refused.
671
- const leftClaimed = []
672
- let r
673
- for (;;) {
674
- const changes = list.map((e) => e.op === 'delete' ? { path: e.path, op: 'delete' } : { path: e.path, op: 'put', blob: entryId(e), mode: e.mode })
675
- try { r = await this.client.commit(this.block.quilt, this.block.square, { expect_head: this.block.head || null, message, changes }); break } catch (err) {
676
- const path = err && err.code === 'claim_refused' ? (err.path || err.extra?.path) : null
677
- if (!path || list.length < 2 || !list.some((e) => e.path === path)) throw err
678
- leftClaimed.push(path)
679
- list = list.filter((e) => e.path !== path)
680
- }
681
- }
682
- if (leftClaimed.length) r = { ...r, left_claimed: leftClaimed }
1129
+ const changes = list.map((e) => e.op === 'delete' ? { path: e.path, op: 'delete' } : { path: e.path, op: 'put', blob: entryId(e), mode: e.mode })
1130
+ let r = await this.client.commit(this.block.quilt, this.block.square, { expect_head: this.block.head || null, message, changes })
1131
+ if (leftHeld.length) r = { ...r, left_held: leftHeld }
683
1132
  const sealed = Object.fromEntries(list.map((e) => [e.path, entryId(e)]))
684
1133
  await this.conn.branchRequest({ op: 'seal', branch: this.block.live, prev: head, head: r.square.head, sealed })
685
1134
  await waitUntil(() => this.head === r.square.head, 10000, 'the sealed head')
@@ -706,9 +1155,9 @@ export class LiveBlock {
706
1155
  })
707
1156
  }
708
1157
 
709
- /** Merges the square into a line (07), after sealing anything uncommitted. */
1158
+ /** Merges the square into a line (07), after sealing anything uncommitted (paths with an open held conflict stay live). */
710
1159
  async merge ({ into = 'main', message } = {}) {
711
- await this.commit({ message: message || 'Work in progress' })
1160
+ try { await this.commit({ message: message || 'Work in progress' }) } catch (err) { if (err.code !== 'held_conflict') throw err }
712
1161
  return this.client.merge(this.block.quilt, into, { square: this.block.square, expect_head: this.block.head, ...(message ? { message } : {}) })
713
1162
  }
714
1163
 
@@ -722,6 +1171,7 @@ export class LiveBlock {
722
1171
  clearInterval(this.stepTimer)
723
1172
  for (const t of this.settleTimers || []) clearTimeout(t)
724
1173
  if (this.watcher) this.watcher.close()
1174
+ this.overwritten.close()
725
1175
  if (this.conn) this.conn.close()
726
1176
  }
727
1177
 
@@ -733,6 +1183,7 @@ export class LiveBlock {
733
1183
  for (const t of this.settleTimers || []) clearTimeout(t)
734
1184
  if (this.watcher) this.watcher.close()
735
1185
  await this.queue.catch(() => {})
1186
+ this.overwritten.close()
736
1187
  if (this.record && this.block && this.block.at) { try { this.save() } catch {} }
737
1188
  if (this.conn) this.conn.close()
738
1189
  }