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
@@ -24,15 +24,25 @@ 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 } from '../base-pick.js'
30
+ import { findUses, removedNameWarning } from '../live-merge.js'
28
31
  // Seam's block folders and ids come from Seam's client package (@heyquilt/seam), never Seam's server code.
29
32
  import { blobId, under } from '@heyquilt/seam/lib/quilts/records.js'
30
33
  import { isText } from '@heyquilt/seam/lib/quilts/textdiff.js'
31
34
  import { checkout, findBlock, saveBlock, localChanges, conflictStyle, BLOCK_DIR } from '@heyquilt/seam/lib/quilts/block.js'
32
35
  import { liveKey, liveMaps, liveHead, entryOf, entryId, overlay } from './live-square.js'
36
+ import { readHeld, heldPathsOn, heldLandingNote } from '../held.js'
33
37
 
34
38
  export const MAX_LIVE_TEXT = 2 * 1024 * 1024
39
+ // A live write carries the text of its base up to this size, so the relay never has to ask for it.
40
+ const INLINE_BASE = 256 * 1024
35
41
  const SCAN_MS = 40
42
+ // This block's own file in the making (write, rescue): never anyone's edit.
43
+ const QUILT_TEMP = /^\..+\.quilt-(tmp|save)$/
44
+ // A file emptied this recently may be a save half done (truncated, not written yet): looked at again first.
45
+ const SETTLE_MS = 250
36
46
  // On macOS, Node's fs.watch shares one FSEvents stream per process and rebuilds it whenever a watch
37
47
  // is added or removed (another folder's block opening, this folder's next square after a merge), so
38
48
  // an edit in that gap is never delivered. The block looks at the folder this often too, as the
@@ -73,15 +83,17 @@ export class LiveBlock {
73
83
  * `onEdits(list, doc, held)`: the edits this folder made, as each scan takes them into the live
74
84
  * document `doc` ([{ path, kind: created|edited|deleted, detail, before?, after? }]), so the session
75
85
  * keeps them on record (who changed what) as it did on its branch; `held()` resolves once the relay
76
- * holds them.
86
+ * holds them. `rules`: the session's live-write engine (live-merge.js LiveRules): each edit is merged
87
+ * against what disk last had and the ways a clash is caught run on it; held lines go to the room.
77
88
  */
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 })
89
+ 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 }) {
90
+ 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
91
  // `started(block)`: told as it starts to open, so whoever waits for it can stop it part-way (abandon).
81
92
  if (started) started(this)
82
93
  this.known = {} // path -> { blob, mode, size, mtimeMs }: what is on disk as this block last read or wrote it
83
94
  this.cache = new Map() // blob id -> bytes (the snapshot's files this block wrote out)
84
95
  this.lastText = new Map() // path -> { id, text }: a live text as disk last had it (bytes no server holds), for combining (scan)
96
+ this.overwritten = new RecentTexts() // the texts a partner's change was lately written over here: a save's possible base (base-pick.js)
85
97
  this.queue = Promise.resolve()
86
98
  this.closed = false
87
99
  this.errors = []
@@ -254,7 +266,11 @@ export class LiveBlock {
254
266
  const m = liveMaps(this.doc)
255
267
  const firstLook = !this.inPlace.seen && !this.inPlace.fresh
256
268
  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]))
269
+ // A file being written as it is read is looked at again (diskChanges leaves it out meanwhile), never taken for absent.
270
+ let seen = this.diskChanges({})
271
+ for (let i = 0; i < 20 && this.unsettled; i++) { this.unsettled = false; await new Promise((resolve) => setTimeout(resolve, SETTLE_MS / 5)); seen = this.diskChanges({}) }
272
+ this.unsettled = false
273
+ const disk = new Map(seen.filter((c) => !this.skipped(c.path)).map((c) => [c.path, c]))
258
274
  const paths = new Set([...disk.keys(), ...Object.keys(this.block.files), ...m.files.keys(), ...m.blobs.keys(), ...m.gone.keys(), ...m.clean.keys()])
259
275
  const out = { same: 0, taken: [], brought: [], combined: [] }
260
276
  for (const p of [...paths].sort()) {
@@ -332,8 +348,8 @@ export class LiveBlock {
332
348
  * The folder's copy of `p` (disk entry `d`) combined with the square's, against what the folder last
333
349
  * had (the session's last sync of it, `inPlace.base`; after a restart, the blob the block last saw):
334
350
  * 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.
351
+ * or that base is not known, or a side is not text). Where both changed the same lines, nobody wins:
352
+ * the square's lines, which landed first, stay, and the folder's are held (live-merge.js, held.js).
337
353
  */
338
354
  async combineAway (p, d) {
339
355
  if (!d.bytes || d.mode === 'symlink' || !isText(d.bytes)) return null
@@ -358,13 +374,27 @@ export class LiveBlock {
358
374
  // A box on a file the folder never moved past: the box's work is the file now.
359
375
  if (base === ours) return want.bytes
360
376
  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')
377
+ const text = this.rules
378
+ ? 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
379
+ : mergeLive(base, ours, theirs).text
380
+ return text === ours ? null : Buffer.from(text, 'utf8')
364
381
  }
365
382
 
366
383
  skipped (p) { return !!(this.skip && this.skip(p)) }
367
384
 
385
+ /** Who last wrote `p` in the square (its writers map), or null. */
386
+ writerOf (p) { const w = this.doc && liveMaps(this.doc).writers.get(p); return (w && w.by) || null }
387
+
388
+ /** The folder's text files as [path, text], read as needed (the removed-name search). */
389
+ * diskTexts () {
390
+ for (const [p, k] of Object.entries(this.known)) {
391
+ if (!k || k.mode === 'symlink' || this.skipped(p) || (k.size > 0 && k.size > 512 * 1024)) continue
392
+ let bytes
393
+ try { bytes = fs.readFileSync(path.join(this.dir, ...p.split('/'))) } catch { continue }
394
+ if (bytes.length <= 512 * 1024 && isText(bytes)) yield [p, bytes.toString('utf8')]
395
+ }
396
+ }
397
+
368
398
  /** Whether `p` is inside a folder with a .git of its own (a submodule): never this block's to read or write. */
369
399
  nested (p) {
370
400
  const parts = p.split('/')
@@ -390,7 +420,7 @@ export class LiveBlock {
390
420
  if (d.name === '.git' || d.name === BLOCK_DIR) continue
391
421
  // 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
422
  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
423
+ if (!(d.isFile() || d.isSymbolicLink()) || this.skipped(r) || QUILT_TEMP.test(d.name)) continue
394
424
  const abs = path.join(this.dir, r)
395
425
  let st
396
426
  try { st = fs.lstatSync(abs) } catch { continue }
@@ -400,9 +430,21 @@ export class LiveBlock {
400
430
  let bytes
401
431
  try { bytes = st.isSymbolicLink() ? Buffer.from(fs.readlinkSync(abs)) : fs.readFileSync(abs) } catch { continue }
402
432
  const mode = st.isSymbolicLink() ? 'symlink' : (st.mode & 0o111) && process.platform !== 'win32' ? 'exec' : 'file'
433
+ // Being written as it was read (it changed during the read, or it reads empty a moment after being
434
+ // emptied, as a save that truncates first does): looked at again shortly, never taken in half-written.
435
+ if (!st.isSymbolicLink()) {
436
+ let again = null
437
+ try { again = fs.lstatSync(abs) } catch {}
438
+ const midWrite = !again || again.size !== st.size || again.mtimeMs !== st.mtimeMs || bytes.length !== st.size
439
+ if (midWrite || (bytes.length === 0 && k && k.size > 0 && Date.now() - st.mtimeMs < SETTLE_MS)) { this.unsettled = true; continue }
440
+ }
403
441
  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 })
442
+ // The same bytes (touched, or rewritten as they were): seen as of the look before this read.
443
+ if (k && k.blob === id && k.mode === mode) { if (files === this.known) files[r] = { ...k, size: st.size, mtimeMs: st.mtimeMs }; continue }
444
+ // `stat`: the file as it was just before this read. Recorded as seen, a save made after the read
445
+ // still differs from it, so the next scan reads it again (2026-11-14: a save between this read
446
+ // and a later look at the file was marked seen and never taken in).
447
+ out.push({ path: r, status: k ? 'modified' : 'added', blob: id, mode, size: bytes.length, bytes, stat: { size: st.size, mtimeMs: st.mtimeMs } })
406
448
  }
407
449
  }
408
450
  visit('')
@@ -418,12 +460,14 @@ export class LiveBlock {
418
460
  if (this.block.at !== this.head) return // 05: no ingest against the wrong base; pull re-projects first
419
461
  const m = liveMaps(this.doc)
420
462
  const snap = this.block.files
463
+ const readAt = Date.now()
421
464
  let changes = this.diskChanges(this.known)
465
+ if (this.unsettled) { this.unsettled = false; this.scanSoon(SCAN_MS * 2) }
422
466
  // What the session never syncs is never taken in; noting its size and time spares reading it again.
423
467
  for (const c of changes) {
424
468
  if (!this.skipped(c.path)) continue
425
469
  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 {}
470
+ try { this.known[c.path] = { blob: c.blob, mode: c.mode, ...this.seenStat(c.path, c, readAt) } } catch {}
427
471
  }
428
472
  changes = changes.filter((c) => !this.skipped(c.path))
429
473
  if (!changes.length) return
@@ -447,9 +491,25 @@ export class LiveBlock {
447
491
  uploads = []
448
492
  }
449
493
  }
494
+ const taken = []
495
+ const rewrite = []
496
+ const moved = []
497
+ // A text edit goes to the relay as a write (relay-live-write.js): merged there against the version this
498
+ // folder last synced and applied in whole lines, one write at a time per file. What the relay doesn't
499
+ // take that way (an older relay, a refusal) and everything else (deletions, binaries) is edited here.
500
+ if (this.relayWrites()) {
501
+ const viaRelay = changes.filter((c) => this.relayWritable(c, uploads, m, snap))
502
+ const back = []
503
+ for (const c of viaRelay) {
504
+ if (this.closed) return
505
+ const how = await this.relayWrite(c, { m, snap, changes, readAt, taken, moved })
506
+ if (how === 'local') back.push(c)
507
+ }
508
+ changes = changes.filter((c) => !viaRelay.includes(c) || back.includes(c))
509
+ }
450
510
  // What each file held before, for the record of who changed what (onEdits): the live document's text, else the head's.
451
511
  const before = new Map()
452
- if (this.onEdits) {
512
+ if (this.onEdits || this.rules) {
453
513
  for (const c of changes) {
454
514
  const t = m.files.get(c.path)
455
515
  if (t) { before.set(c.path, t.toString()); continue }
@@ -478,13 +538,29 @@ export class LiveBlock {
478
538
  both.set(c.path, { base, head: head ? head.toString('utf8') : null })
479
539
  } catch {}
480
540
  }
481
- const taken = []
482
- const rewrite = []
483
541
  this.doc.transact(() => {
484
542
  for (const c of changes) {
485
543
  const p = c.path
486
544
  const base = snap[p]
487
545
  const had = !!(base && !m.gone.has(p)) || m.files.has(p) || m.blobs.has(p)
546
+ // A file another member moved away (deleted, the same text added elsewhere): this edit goes where it went.
547
+ if (this.rules && c.status !== 'deleted' && !had && c.mode !== 'symlink' && c.bytes.length <= MAX_LIVE_TEXT && isText(c.bytes)) {
548
+ const mv = this.rules.movedTo({ doc: this.doc, path: p, by: this.by })
549
+ const to = mv && m.files.get(mv.to)
550
+ if (to && !changes.some((x) => x.path === mv.to)) {
551
+ const last = this.lastText.get(p)
552
+ 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() })
553
+ const was = to.toString()
554
+ const detail = applyTextDiff(to, r.text)
555
+ m.writers.set(mv.to, { by: this.by, ts: Date.now(), at: this.block.at })
556
+ taken.push({ path: mv.to, kind: 'edited', detail, before: was, after: r.text })
557
+ rewrite.push({ path: mv.to, bytes: Buffer.from(r.text, 'utf8'), mode: m.modes.get(mv.to) === 'exec' ? 'exec' : 'file' })
558
+ moved.push({ from: p, to: mv.to, by: mv.by })
559
+ continue
560
+ }
561
+ }
562
+ // Who wrote it before this edit: the one whose lines landed first, should they clash.
563
+ const prior = (m.writers.get(p) || {}).by || null
488
564
  // Whose work this path is now (on going back to git, its box is theirs: Session.leaveSquare), and the
489
565
  // head it was made on: the relay combines an edit made on a head it has moved on from (bring-in.js lateEdits).
490
566
  m.writers.set(p, { by: this.by, ts: Date.now(), at: this.block.at })
@@ -492,6 +568,8 @@ export class LiveBlock {
492
568
  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
569
  delete this.known[p]
494
570
  if (had) taken.push({ path: p, kind: 'deleted', detail: '', ...(before.has(p) ? { before: before.get(p), after: '' } : {}) })
571
+ // With the same text added elsewhere by this folder, a move (edits others make to it follow it).
572
+ if (this.rules && before.has(p)) this.rules.noteGone({ doc: this.doc, path: p, text: before.get(p), by: this.by })
495
573
  continue
496
574
  }
497
575
  const kind = had ? 'edited' : 'created'
@@ -511,29 +589,192 @@ export class LiveBlock {
511
589
  let after = c.bytes.toString('utf8')
512
590
  const w = both.get(p)
513
591
  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 })
592
+ if (this.rules) {
593
+ // Merged against what disk last had, and the ways a clash is caught run on it (live-merge.js):
594
+ // lines both changed keep what landed first, this folder's are held, and disk gets the result.
595
+ const theirs = cur !== null ? cur : fresh ? (before.has(p) ? before.get(p) : null) : t.toString()
596
+ 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
597
+ } else if (w && cur !== null && cur !== w.base && cur !== after) {
598
+ // No engine (a block opened outside a session): what landed first keeps the lines both changed,
599
+ // and this folder's are said in its log, never dropped without a word.
600
+ const r = mergeLive(w.base, after, cur)
601
+ after = r.text
602
+ 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
603
  }
604
+ if (after !== c.bytes.toString('utf8')) rewrite.push({ path: p, bytes: Buffer.from(after, 'utf8'), mode: c.mode })
520
605
  let detail = applyTextDiff(t, after)
521
606
  this.lastText.set(p, { id: blobId(Buffer.from(after, 'utf8')), text: after })
522
607
  // A file new to the live document took its whole text: what changed is measured from the head's.
523
608
  if (fresh && before.has(p)) { const probe = new Y.Doc().getText(); probe.insert(0, before.get(p)); detail = applyTextDiff(probe, after) }
524
609
  if (c.mode === 'exec') m.modes.set(p, 'exec'); else if (m.modes.has(p)) m.modes.delete(p)
525
610
  if (detail || !had) taken.push({ path: p, kind, detail, before: before.get(p) ?? '', after })
611
+ if (!had && this.rules) this.rules.noteNew({ doc: this.doc, path: p, text: after, by: this.by })
526
612
  }
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 }
613
+ this.known[p] = { blob: c.blob, mode: c.mode, ...this.seenStat(p, c, readAt) }
529
614
  }
530
615
  })
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)
616
+ // Disk gets the combination: what the square had that this edit was not made on. Never over a save
617
+ // made since this scan read the file: that save is taken in next, merged with the combination.
618
+ for (const x of rewrite) {
619
+ if (this.write(x.path, x, { guard: true }) === false) {
620
+ const c = changes.find((y) => y.path === x.path)
621
+ if (c && c.bytes) this.lastText.set(x.path, { id: c.blob, text: c.bytes.toString('utf8') })
622
+ this.scanSoon()
623
+ }
624
+ }
625
+ // An edit to a moved file went to where it went: the old path comes off disk again.
626
+ for (const mv of moved) {
627
+ this.write(mv.from, null)
628
+ 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.`)
629
+ if (this.logFn) this.logFn(`${mv.from} was moved to ${mv.to} by ${mv.by}: your edit went there`)
630
+ }
533
631
  this.saveSoon()
534
632
  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
633
  }
536
634
 
635
+ /** Whether the relay takes this folder's text edits as writes (relay-live-write.js), and this block may send them. */
636
+ relayWrites () { return !!(this.conn && this.conn.relayWrites && !this.noRelayWrites && this.conn.connected !== false) }
637
+
638
+ /** 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). */
639
+ relayWritable (c, uploads, m, snap) {
640
+ if (c.status === 'deleted' || c.mode === 'symlink' || !c.bytes || c.bytes.length > MAX_LIVE_TEXT || !isText(c.bytes)) return false
641
+ if (uploads.some((u) => u.id === c.blob)) return false
642
+ const head = snap[c.path]
643
+ if (head && head.blob === c.blob && head.mode === c.mode && !m.files.has(c.path)) return false
644
+ return true
645
+ }
646
+
647
+ /**
648
+ * What disk had of `p` as this block last synced it: the text its last write or write-out left (lastText),
649
+ * else the head's file when that is what it had, else the blob it knew; null when not known.
650
+ */
651
+ async syncedText (p) {
652
+ const k = this.known[p]
653
+ if (!k || !k.blob) return null
654
+ const last = this.lastText.get(p)
655
+ if (last && last.id === k.blob) return last.text
656
+ try { const b = await this.bytesOf(k.blob); return isText(b) ? b.toString('utf8') : null } catch { return null }
657
+ }
658
+
659
+ /**
660
+ * One text edit, as a write to the relay. 'done' (in, and disk has the result unless it was saved again
661
+ * meanwhile), 'local' (the relay asked for it to be edited here as before), or 'later' (not sent: the
662
+ * next scan tries again, and nothing is written over it meanwhile).
663
+ */
664
+ async relayWrite (c, { m, snap, changes, readAt, taken, moved }) {
665
+ const p = c.path
666
+ const text = c.bytes.toString('utf8')
667
+ const had = !!(snap[p] && !m.gone.has(p)) || m.files.has(p) || m.blobs.has(p)
668
+ // A file another member moved away (deleted, the same text added elsewhere): this edit goes where it went.
669
+ let target = p
670
+ let mv = null
671
+ let base
672
+ if (this.rules && !had) {
673
+ const to = this.rules.movedTo({ doc: this.doc, path: p, by: this.by })
674
+ if (to && m.files.get(to.to) && !changes.some((x) => x.path === to.to)) { mv = to; target = to.to }
675
+ }
676
+ if (mv) { const last = this.lastText.get(p); base = last ? last.text : mv.text } else base = await this.syncedText(p)
677
+ // Made from the text a partner's change was just written over (an editor's older read)? It goes too
678
+ // (`older`): the relay puts the save onto the base, and where the partner changed it since, the newer lines stay.
679
+ const older = !mv && typeof base === 'string' ? this.overwritten.pick(p, base, text) : base
680
+ const known = !!this.known[p]
681
+ const trusted = !!(this.rules && this.rules.trusted && this.rules.trusted.get(target) === text)
682
+ const req = {
683
+ path: target,
684
+ base: typeof base === 'string' ? versionOf(base) : null,
685
+ // Small, or not live yet (the head's text, which the relay never reads): its text goes with it.
686
+ ...(typeof base === 'string' && (base.length <= INLINE_BASE || !m.files.has(target)) ? { baseText: base } : {}),
687
+ // Known here but its text is not (after a restart): the relay merges it as a stale write.
688
+ ...(typeof base !== 'string' && known && !mv ? { baseUnknown: true } : {}),
689
+ text,
690
+ ...(older !== base && typeof older === 'string' ? { older } : {}),
691
+ mode: c.mode,
692
+ at: this.block.at,
693
+ ...(trusted ? { trusted: true } : {})
694
+ }
695
+ let r
696
+ try {
697
+ r = await this.conn.liveWrite(req, { baseOf: () => (typeof base === 'string' ? base : null) })
698
+ } catch (err) {
699
+ if (/unknown branch request/.test(err.message)) { this.noRelayWrites = true; return 'local' }
700
+ if (this.logFn && this.writeProblem !== err.message) this.logFn(`${p}: your edit waits to reach the square (${err.message}); it is tried again`)
701
+ this.writeProblem = err.message
702
+ this.scanSoon(1000)
703
+ return 'later'
704
+ }
705
+ this.writeProblem = null
706
+ if (r.fallback) return 'local'
707
+ if (trusted) this.rules.trusted.delete(target)
708
+ const result = r.same ? text : r.text
709
+ // Seen as read; disk gets the result only if it was not saved again since (then that save comes next, on this text).
710
+ if (mv) {
711
+ this.write(p, null)
712
+ const want = { bytes: Buffer.from(result, 'utf8'), mode: m.modes.get(target) === 'exec' ? 'exec' : 'file' }
713
+ this.write(target, want, { guard: true })
714
+ moved.push({ from: p, to: target, by: mv.by })
715
+ } else {
716
+ this.overwritten.forget(p)
717
+ this.known[p] = { blob: c.blob, mode: c.mode, ...this.seenStat(p, c, readAt) }
718
+ this.lastText.set(p, { id: c.blob, text })
719
+ if (result !== text && this.write(p, { bytes: Buffer.from(result, 'utf8'), mode: c.mode }, { guard: true }) === false) this.scanSoon()
720
+ }
721
+ for (const n of r.notices || []) { try { if (this.rules) this.rules.notice(n) } catch {} }
722
+ for (const l of r.logs || []) if (this.logFn) this.logFn(l)
723
+ 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 {} }
724
+ // Names this write removed that other files here still use: said to the writer, never a block.
725
+ if (this.rules && Array.isArray(r.gone) && r.gone.length) {
726
+ let uses = []
727
+ try { uses = findUses(r.gone, this.diskTexts(), { skip: target }) } catch {}
728
+ const w = removedNameWarning(target, uses)
729
+ if (w) { this.rules.notice(w); if (this.logFn) this.logFn(`⚠️ ${w}`) }
730
+ }
731
+ if (r.detail || !had) taken.push({ path: target, kind: had || mv ? 'edited' : 'created', detail: r.detail || '', before: r.before ?? '', after: result })
732
+ if (!had && !mv && this.rules) this.rules.noteNew({ doc: this.doc, path: p, text: result, by: this.by })
733
+ return 'done'
734
+ }
735
+
736
+ /**
737
+ * The size and time to record for a change this scan read: the file as it was just before the read
738
+ * (diskChanges' `stat`); else, when it was changed around the time of the read, none (-1), so it is
739
+ * read again rather than taken as seen (Seam's own walk, which does not say).
740
+ */
741
+ seenStat (p, c, readAt) {
742
+ if (c.stat) return { size: c.stat.size, mtimeMs: c.stat.mtimeMs }
743
+ try {
744
+ const st = fs.lstatSync(path.join(this.dir, ...p.split('/')))
745
+ if (st.mtimeMs >= readAt - 5 || st.size !== c.bytes.length) return { size: -1, mtimeMs: -1 }
746
+ return { size: st.size, mtimeMs: st.mtimeMs }
747
+ } catch { return { size: -1, mtimeMs: -1 } }
748
+ }
749
+
750
+ /**
751
+ * Whether `p` on disk changed since this block last read or wrote it (a save not taken in yet): then
752
+ * nothing is written over it. A different size or time with the same bytes is no change (and is
753
+ * noted as seen).
754
+ */
755
+ diskMoved (p) {
756
+ const abs = path.join(this.dir, ...p.split('/'))
757
+ const k = this.known[p]
758
+ let st
759
+ try { st = fs.lstatSync(abs) } catch { return !!k } // gone here but known: a deletion not taken in yet
760
+ if (!k) return true // a file here this block never took in
761
+ if (k.size === st.size && k.mtimeMs === st.mtimeMs) return false
762
+ let bytes
763
+ try { bytes = st.isSymbolicLink() ? Buffer.from(fs.readlinkSync(abs)) : fs.readFileSync(abs) } catch { return true }
764
+ const mode = st.isSymbolicLink() ? 'symlink' : (st.mode & 0o111) && process.platform !== 'win32' ? 'exec' : 'file'
765
+ if (blobId(bytes) !== k.blob || (k.mode && mode !== k.mode && k.mode !== 'conflict')) return true
766
+ this.known[p] = { ...k, size: st.size, mtimeMs: st.mtimeMs }
767
+ return false
768
+ }
769
+
770
+ /** A scan soon (a save to take in that a write-out left alone, or a write to send again). */
771
+ scanSoon (ms = SCAN_MS) {
772
+ if (this.closed) return
773
+ clearTimeout(this.scanTimer)
774
+ this.scanTimer = setTimeout(() => this.run(() => this.scan()), ms)
775
+ this.scanTimer.unref?.()
776
+ }
777
+
537
778
  /** Bytes of a blob, from this block's cache or the server. */
538
779
  async bytesOf (id) {
539
780
  if (!this.cache.has(id)) {
@@ -564,25 +805,113 @@ export class LiveBlock {
564
805
  return s ? this.headFile(p, s) : null
565
806
  }
566
807
 
567
- write (p, want) {
808
+ /**
809
+ * Puts `want` on disk at `p` (null: removes it). `guard`: only if disk still has what this block last
810
+ * read or wrote there (diskMoved), looked at again just before the file is replaced; false when it was
811
+ * left alone, so a save made meanwhile is taken in (and merged) rather than overwritten.
812
+ */
813
+ write (p, want, { guard = false } = {}) {
568
814
  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 }
815
+ if (guard && this.diskMoved(p)) return false
816
+ if (!want) { fs.rmSync(abs, { force: true }); delete this.known[p]; this.lastText.delete(p); this.wrote(p); return true }
570
817
  fs.mkdirSync(path.dirname(abs), { recursive: true })
571
818
  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 {
819
+ // What is recorded as seen is the written file as it was before it took its place (a rename keeps its
820
+ // size and time): a save that lands right after it differs from it, so it is taken in, never taken as
821
+ // this write (2026-11-14: a save between the rename and a look at the file afterwards was lost).
822
+ let st
823
+ if (want.mode === 'symlink') { fs.rmSync(abs, { force: true }); fs.symlinkSync(want.bytes.toString('utf8'), abs); st = fs.lstatSync(abs) } else {
573
824
  fs.writeFileSync(tmp, want.bytes, { mode: want.mode === 'exec' ? 0o755 : 0o644 })
574
- fs.renameSync(tmp, abs)
825
+ st = fs.lstatSync(tmp)
826
+ const last = this.lastText.get(p)
827
+ const before = last && this.known[p] && last.id === this.known[p].blob ? last.text : null
828
+ const placed = this.place(p, abs, tmp, { guard, before, wrote: want.bytes })
829
+ if (!placed) return false
575
830
  }
576
- const st = fs.lstatSync(abs)
577
831
  this.known[p] = { blob: blobId(want.bytes), mode: want.mode, size: st.size, mtimeMs: st.mtimeMs }
578
832
  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
833
  else this.lastText.delete(p)
580
834
  this.saveSoon()
581
835
  this.wrote(p)
836
+ return true
582
837
  }
583
838
 
584
839
  wrote (p) { if (this.onWrite) { try { this.onWrite(p) } catch {} } }
585
840
 
841
+ /**
842
+ * Puts `tmp` in the place of `abs` (a rename). `guard`: not when disk changed since this block last
843
+ * saw it (diskMoved): false then. A save into the file being replaced, landing in the instant between
844
+ * that look and the rename (an editor that truncates and writes, opened just before it), would be
845
+ * gone with the old file: the old file stays open across the rename, and what was saved into it after
846
+ * the look is put back as a save of its own (rescue), taken in by the next scan.
847
+ */
848
+ place (p, abs, tmp, { guard = false, before = null, wrote = null } = {}) {
849
+ let old = null
850
+ if (guard) { try { old = fs.openSync(abs, 'r') } catch {} }
851
+ try {
852
+ // As it was before the look below: a save into it after this is either seen by that look or after the rename.
853
+ const seen = old !== null ? fs.fstatSync(old) : null
854
+ if (guard && this.diskMoved(p)) { fs.rmSync(tmp, { force: true }); return false }
855
+ fs.renameSync(tmp, abs)
856
+ if (old !== null) {
857
+ const now = fs.fstatSync(old)
858
+ if (now.size !== seen.size || now.mtimeMs !== seen.mtimeMs) { this.rescue(p, old, { before, wrote }); old = null }
859
+ }
860
+ return true
861
+ } finally { if (old !== null) { try { fs.closeSync(old) } catch {} } }
862
+ }
863
+
864
+ /**
865
+ * A save that landed in a file this block replaced (place): once it is written out in full, it goes back
866
+ * on disk as a save of its own. Saved again since (from what this block wrote, without it): its own
867
+ * change goes onto that newer save (`before`: what disk had before the write, `wrote`: the write), the
868
+ * newer one winning where both changed a line, so neither is lost.
869
+ */
870
+ async rescue (p, fd, { before = null, wrote = null } = {}) {
871
+ try {
872
+ let last = null
873
+ for (let i = 0; i < 50; i++) {
874
+ const st = fs.fstatSync(fd)
875
+ if (last && st.size === last.size && st.mtimeMs === last.mtimeMs) break
876
+ last = st
877
+ await new Promise((resolve) => setTimeout(resolve, 20))
878
+ }
879
+ const size = fs.fstatSync(fd).size
880
+ const bytes = Buffer.alloc(size)
881
+ let off = 0
882
+ while (off < size) { const n = fs.readSync(fd, bytes, off, size - off, off); if (!n) break; off += n }
883
+ if (this.closed) return
884
+ await this.run(async () => {
885
+ const abs = path.join(this.dir, ...p.split('/'))
886
+ const k = this.known[p]
887
+ if (k && k.blob === blobId(bytes)) return
888
+ const tmp = path.join(path.dirname(abs), `.${path.basename(abs)}.quilt-save`)
889
+ const mode = k && k.mode === 'exec' ? 0o755 : 0o644
890
+ if (!this.diskMoved(p)) {
891
+ // Disk still has what this block wrote: the save goes back over it.
892
+ fs.writeFileSync(tmp, bytes, { mode })
893
+ this.place(p, abs, tmp, { guard: true })
894
+ } else {
895
+ let now = null
896
+ try { now = fs.readFileSync(abs) } catch {}
897
+ if (!now || typeof before !== 'string' || !wrote || !isText(bytes) || !isText(now)) return
898
+ const onto = mergeLive(before, bytes.toString('utf8'), wrote.toString('utf8')).text
899
+ // Both saves are this folder's: where they changed the same place, both go in (nothing is lost; its writer sees both).
900
+ const merged = mergeLive(wrote.toString('utf8'), onto, now.toString('utf8'), { union: true }).text
901
+ if (merged === now.toString('utf8')) return
902
+ fs.writeFileSync(tmp, merged, { mode })
903
+ // Only over that newer save as it is (it is taken in with the late one's change on it).
904
+ let again = null
905
+ try { again = fs.readFileSync(abs) } catch {}
906
+ if (!again || !again.equals(now)) { fs.rmSync(tmp, { force: true }); return }
907
+ fs.renameSync(tmp, abs)
908
+ }
909
+ if (this.logFn) this.logFn(`${p}: a save landed while Quilt wrote the session's version; it is taken in now`)
910
+ this.scanSoon()
911
+ })
912
+ } catch {} finally { try { fs.closeSync(fd) } catch {} }
913
+ }
914
+
586
915
  /** Moves the block to the document's head (a commit by anyone in the square), then writes the overlay out. */
587
916
  async pull () {
588
917
  if (this.closed) return
@@ -599,7 +928,12 @@ export class LiveBlock {
599
928
  const want = await this.wanted(p)
600
929
  const id = want ? blobId(want.bytes) : null
601
930
  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)
931
+ // Never over a save not taken in yet (one made since the scan above): the next scan merges it.
932
+ if (id !== have || (want && this.known[p].mode !== want.mode)) {
933
+ const was = have && want ? await this.syncedText(p) : null
934
+ if (this.write(p, want, { guard: true }) === false) this.scanSoon()
935
+ else if (typeof was === 'string') this.overwritten.note(p, was) // a save made from it is told apart (base-pick.js)
936
+ }
603
937
  } catch (err) { failed.push({ path: p, err }) }
604
938
  }
605
939
  this.noteOutOfStep(failed)
@@ -628,7 +962,7 @@ export class LiveBlock {
628
962
  // Already on disk as the new head has it (the commit was made from this very work): left alone.
629
963
  const k = this.known[f.path]
630
964
  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)
965
+ if (this.write(f.path, e ? await this.headFile(f.path, b.files[f.path], `c:${to}`) : null, { guard: true }) === false) this.scanSoon()
632
966
  }
633
967
  b.at = to
634
968
  // A square with no commit of its own (a rebase only moved its base): a commit's expect_head is none.
@@ -649,10 +983,18 @@ export class LiveBlock {
649
983
  return overlay(this.doc).map((e) => ({ path: e.path, status: e.op === 'delete' ? 'deleted' : this.block.files[e.path] ? 'modified' : 'added' }))
650
984
  }
651
985
 
986
+ /** Paths with an open held conflict on this square (held.js, in the room's document): they stay live until it is resolved. */
987
+ heldPaths () {
988
+ const map = this.rules && this.rules.heldMap ? this.rules.heldMap() : null
989
+ return map && this.block ? heldPathsOn(readHeld(map), this.block.square) : []
990
+ }
991
+
652
992
  /**
653
993
  * Seals the live document as a commit on the square: the overlay (every writer's work, not only
654
994
  * 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`).
995
+ * then the relay moves the head and drops what was committed (live-square.js `seal`). A path with
996
+ * an open held conflict (Seam's 07 "Terms held aside") stays live and the rest is committed
997
+ * (`left_held`); with nothing else to commit it is refused (code 'held_conflict', naming them).
656
998
  */
657
999
  async commit ({ message = '' } = {}) {
658
1000
  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 +1005,21 @@ export class LiveBlock {
663
1005
  // the live document names it (a square from before 0.3.135's switch took agents' scratch files in).
664
1006
  let list = overlay(this.doc).filter((e) => !(this.skipped(e.path) && !this.block.files[e.path]))
665
1007
  if (!list.length) return { nothing: true }
1008
+ // A path with an open held conflict never lands until it is resolved; one such file never holds back the rest.
1009
+ const held = new Set(this.heldPaths())
1010
+ const leftHeld = list.filter((e) => held.has(e.path)).map((e) => e.path)
1011
+ list = list.filter((e) => !held.has(e.path))
1012
+ if (!list.length) {
1013
+ const err = new Error(heldLandingNote(leftHeld, { none: true }))
1014
+ err.code = 'held_conflict'
1015
+ err.paths = leftHeld
1016
+ throw err
1017
+ }
666
1018
  const uploads = list.filter((e) => e.bytes).map((e) => ({ kind: 'blob', id: blobId(e.bytes), bytes: e.bytes }))
667
1019
  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 }
1020
+ const changes = list.map((e) => e.op === 'delete' ? { path: e.path, op: 'delete' } : { path: e.path, op: 'put', blob: entryId(e), mode: e.mode })
1021
+ let r = await this.client.commit(this.block.quilt, this.block.square, { expect_head: this.block.head || null, message, changes })
1022
+ if (leftHeld.length) r = { ...r, left_held: leftHeld }
683
1023
  const sealed = Object.fromEntries(list.map((e) => [e.path, entryId(e)]))
684
1024
  await this.conn.branchRequest({ op: 'seal', branch: this.block.live, prev: head, head: r.square.head, sealed })
685
1025
  await waitUntil(() => this.head === r.square.head, 10000, 'the sealed head')
@@ -706,9 +1046,9 @@ export class LiveBlock {
706
1046
  })
707
1047
  }
708
1048
 
709
- /** Merges the square into a line (07), after sealing anything uncommitted. */
1049
+ /** Merges the square into a line (07), after sealing anything uncommitted (paths with an open held conflict stay live). */
710
1050
  async merge ({ into = 'main', message } = {}) {
711
- await this.commit({ message: message || 'Work in progress' })
1051
+ try { await this.commit({ message: message || 'Work in progress' }) } catch (err) { if (err.code !== 'held_conflict') throw err }
712
1052
  return this.client.merge(this.block.quilt, into, { square: this.block.square, expect_head: this.block.head, ...(message ? { message } : {}) })
713
1053
  }
714
1054