heyquilt 0.3.174 → 0.3.176

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 (71) hide show
  1. package/README.md +6 -3
  2. package/RELEASES.md +30 -0
  3. package/bin/quilt.js +1 -75
  4. package/desktop/main.js +22 -9
  5. package/package.json +2 -3
  6. package/src/ai-vm.js +1 -1
  7. package/src/api/memory-store.js +1 -5
  8. package/src/api/server.js +4 -45
  9. package/src/api/supabase-store.js +0 -10
  10. package/src/autowork.js +7 -142
  11. package/src/base-pick.js +125 -12
  12. package/src/branch-view.js +1 -1
  13. package/src/connection.js +12 -37
  14. package/src/control.js +16 -93
  15. package/src/fsutil.js +1 -1
  16. package/src/git-aside.js +70 -0
  17. package/src/github-commit.js +1 -2
  18. package/src/gitstate.js +326 -0
  19. package/src/held.js +12 -53
  20. package/src/history.js +1 -25
  21. package/src/live-merge.js +42 -161
  22. package/src/mcp.js +6 -90
  23. package/src/merge3.js +21 -5
  24. package/src/pathrules.js +1 -1
  25. package/src/protocol.js +6 -11
  26. package/src/read-bases.js +3 -5
  27. package/src/relay-live-write.js +37 -44
  28. package/src/relay-mcp.js +30 -164
  29. package/src/relay-prune.js +3 -6
  30. package/src/relay-turn-sync.js +7 -11
  31. package/src/runner.js +2 -4
  32. package/src/server.js +61 -1717
  33. package/src/session.js +895 -844
  34. package/src/setup.js +11 -3
  35. package/src/status.js +2 -5
  36. package/src/swap-in.js +56 -13
  37. package/src/turn-sync-plan.js +2 -2
  38. package/src/turn-sync.js +1 -1
  39. package/src/ui/agent-guide.js +3 -1
  40. package/src/ui/app.css +4 -96
  41. package/src/ui/app.js +1 -1
  42. package/src/ui/chat.js +2 -6
  43. package/src/ui/cloud-ai-model.js +0 -13
  44. package/src/ui/cloud-ai.js +2 -10
  45. package/src/ui/connections.js +2 -1
  46. package/src/ui/fileview.js +7 -20
  47. package/src/ui/git-rule.js +2 -13
  48. package/src/ui/home.js +2 -8
  49. package/src/ui/session-words.js +27 -0
  50. package/src/ui/session.js +34 -407
  51. package/src/ui-server.js +7 -56
  52. package/src/api/routes/seam-connect.js +0 -103
  53. package/src/api/routes/session-migrate.js +0 -39
  54. package/src/force-date.js +0 -27
  55. package/src/quilt-default.js +0 -84
  56. package/src/quilt-history.js +0 -106
  57. package/src/quilt-remote.js +0 -78
  58. package/src/seam-access.js +0 -97
  59. package/src/seam-url.js +0 -15
  60. package/src/session-follow.js +0 -583
  61. package/src/session-layout3.js +0 -466
  62. package/src/session-migrate.js +0 -123
  63. package/src/session-quilt.js +0 -126
  64. package/src/session-seam.js +0 -312
  65. package/src/source-live/bring-in.js +0 -391
  66. package/src/source-live/land.js +0 -410
  67. package/src/source-live/live-block.js +0 -1166
  68. package/src/source-live/live-square.js +0 -116
  69. package/src/ui/force-words.js +0 -19
  70. package/src/ui/quiltview.js +0 -213
  71. package/src/ui/seam-model.js +0 -309
@@ -1,1166 +0,0 @@
1
- // Quilt's side of seam: live squares in a Quilt session. Seam (src/quilts/) never imports this.
2
- // The folder side of a live square (Seam's plans/quilt-source-control/05): a block whose files mirror the
3
- // square's live document on the relay (live-square.js). Disk under the block is the snapshot at
4
- // `block.at` plus the overlay; every edit seen on disk goes into the live document at once, so the
5
- // relay always knows the square's uncommitted work, and every change another member of the square
6
- // makes arrives on disk. `commit` seals what the relay holds: it commits the overlay through the
7
- // quilt API and asks the relay to move the document's head, which drops what was committed.
8
- //
9
- // It reuses the session's sync engine: the relay connection (connection.js: sign-in, passes, the
10
- // branch-document protocol), the relay's branch documents themselves, and the text diff into a
11
- // Y.Text (textdiff.js). There is no git: every change on disk is an edit (decision 18).
12
- //
13
- // In place (`inPlace`): a session's own folder becomes the block at the layout-3 switch (Seam's
14
- // plans/quilt-source-control/16: the first rebuild is a no-op, because the folder already equals
15
- // the square's live document). Nothing is checked out: the record is written beside the session's
16
- // state (.quilt/block.json), what disk holds is compared with the live document file by file, and
17
- // a difference is the person's edit (in it goes) unless the session says the folder was not
18
- // touched since it last synced (then the live document's newer version comes to disk). Paths the
19
- // session never syncs (`skip`) are never read or written. Reads can go through the relay
20
- // (`reader`), so a member needs no Seam sign-in to follow; uploads and commits are the member's.
21
- import fs from 'node:fs'
22
- import path from 'node:path'
23
- import * as Y from 'yjs'
24
- import { Connection, REMOTE } from '../connection.js'
25
- import { FEATURES } from '../protocol.js'
26
- import { applyTextDiff } from '../textdiff.js'
27
- import { mergeLive } from '../merge3.js'
28
- import { versionOf } from '../read-bases.js'
29
- import { RecentTexts } from '../base-pick.js'
30
- import { swapIn } from '../swap-in.js'
31
- import { findUses, removedNameWarning } from '../live-merge.js'
32
- // Seam's block folders and ids come from Seam's client package (@heyquilt/seam), never Seam's server code.
33
- import { blobId, under } from '@heyquilt/seam/lib/quilts/records.js'
34
- import { isText } from '@heyquilt/seam/lib/quilts/textdiff.js'
35
- import { checkout, findBlock, saveBlock, localChanges, conflictStyle, BLOCK_DIR } from '@heyquilt/seam/lib/quilts/block.js'
36
- import { liveKey, liveMaps, liveHead, entryOf, entryId, overlay } from './live-square.js'
37
- import { readHeld, heldPathsOn, heldLandingNote } from '../held.js'
38
-
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
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
47
- // On macOS, Node's fs.watch shares one FSEvents stream per process and rebuilds it whenever a watch
48
- // is added or removed (another folder's block opening, this folder's next square after a merge), so
49
- // an edit in that gap is never delivered. The block looks at the folder this often too, as the
50
- // session does before the switch (session.js RECONCILE_MS).
51
- export const RECONCILE_MS = 1000
52
- // After a watcher starts, the folder is scanned again at these times (watch).
53
- const WATCH_SETTLE_MS = [250, 1000, 3000]
54
- // And this often the folder is brought in step with the square even with no news from the relay (a
55
- // write-out that failed, or one that never ran, is tried again): disk and square never disagree for
56
- // long, nor without a word (2026-11-01: a folder kept a file the square had deleted).
57
- export const STEP_MS = 15000
58
-
59
- const waitUntil = async (fn, ms = 10000, what = 'the relay') => {
60
- const t = Date.now()
61
- while (!fn()) {
62
- if (Date.now() - t > ms) throw new Error(`timed out waiting for ${what}`)
63
- await new Promise((r) => setTimeout(r, 10))
64
- }
65
- }
66
-
67
- export class LiveBlock {
68
- /**
69
- * @param {object} o
70
- * @param {string} o.dir the block's folder (empty, or a block opened before)
71
- * @param {object} o.client a quilt API client (client.js), signed in as this member
72
- * @param {string} o.quilt quilt slug or id
73
- * @param {string} [o.square] the square (else the folder's)
74
- * @param {string[]} [o.paths]
75
- * @param {object} o.relay { server, room, secret, name, identity, kind?, passes?, tool? }: the session
76
- */
77
- /**
78
- * In place, also: `inPlace` { edited(path) }: whether the session saw the folder's copy change
79
- * since it last synced it; `skip(path)`: the session never syncs it (`skipDir(path)`: nor
80
- * anything in that folder); `record`: where block.json
81
- * goes; `reader`: a client for reads (square, tree, blobs, diff), else `client`; `log`;
82
- * `onWrite(path)`: the block wrote (or deleted) that file on disk from the square, so whoever shows the
83
- * folder hears of it without waiting on a file watcher (macOS's FSEvents drops events under load).
84
- * `onEdits(list, doc, held)`: the edits this folder made, as each scan takes them into the live
85
- * document `doc` ([{ path, kind: created|edited|deleted, detail, before?, after? }]), so the session
86
- * keeps them on record (who changed what) as it did on its branch; `held()` resolves once the relay
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.
89
- */
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 })
92
- // `started(block)`: told as it starts to open, so whoever waits for it can stop it part-way (abandon).
93
- if (started) started(this)
94
- this.known = {} // path -> { blob, mode, size, mtimeMs }: what is on disk as this block last read or wrote it
95
- this.cache = new Map() // blob id -> bytes (the snapshot's files this block wrote out)
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() // saves that landed in a file this block replaced, with the text they were made from (base-pick.js)
98
- this.queue = Promise.resolve()
99
- this.closed = false
100
- this.errors = []
101
- }
102
-
103
- /** One thing at a time: scans, write-outs, re-projections and commits never interleave. */
104
- run (fn) {
105
- const p = this.queue.then(fn)
106
- this.queue = p.catch((err) => { this.errors.push(err) })
107
- return p
108
- }
109
-
110
- async open () {
111
- // A block that fails part-way lets go of what it opened: its relay connection would otherwise
112
- // reconnect for good, one more with each try the folder makes to follow its square.
113
- try { return await (this.inPlace ? this.openInPlace() : this.openCheckout()) } catch (err) {
114
- this.abandon()
115
- throw err
116
- }
117
- }
118
-
119
- async openCheckout () {
120
- const found = findBlock(this.dir)
121
- if (found && found.dir === this.dir) this.block = found.block
122
- else {
123
- const sq = await this.client.square(this.quilt, this.squareRef)
124
- this.block = (await checkout(this.client, { quilt: this.quilt, square: sq.id, paths: this.paths, dir: this.dir, api: this.api })).block
125
- }
126
- const b = this.block
127
- if (!b.square) throw new Error('a live block needs a square')
128
- b.live = liveKey(b.square)
129
- for (const [p, f] of Object.entries(b.files)) this.known[p] = { ...f }
130
- this.save()
131
- await this.connect()
132
- await this.run(async () => { await this.scan(); await this.pull() })
133
- this.watch()
134
- return this
135
- }
136
-
137
- /** The relay connection on the square's live document, with its head set. */
138
- async connect () {
139
- const b = this.block
140
- this.roomDoc = new Y.Doc()
141
- this.doc = new Y.Doc()
142
- const r = this.relayOpts
143
- // quilt-block: the relay counts it as part of the app's visit, not a visit of its own (the audit trail).
144
- // Only the square's live document: the app's own connection has the room's (chat, tasks, activity).
145
- this.conn = new Connection({ ...r, kind: r.kind || 'human', features: `${r.features || FEATURES},quilt-block`, roomDoc: false, doc: this.roomDoc, branch: { key: b.live, doc: this.doc } })
146
- this.conn.on('fatal', (err) => this.errors.push(err))
147
- // Stopped while it opens (the session stopped, or the folder moved on): its waits for the relay end with it.
148
- const stopped = new Promise((resolve, reject) => { this.stopOpening = () => reject(new Error('the block was closed while it opened')) })
149
- stopped.catch(() => {})
150
- if (this.closed) this.stopOpening()
151
- await Promise.race([this.conn.waitForSync(), stopped])
152
- await Promise.race([this.conn.waitForBranchSync(), stopped])
153
- if (!liveHead(this.doc)) {
154
- const sq = await this.reader.square(b.quilt, b.square)
155
- await this.conn.branchRequest({ op: 'start', branch: b.live, head: sq.head || sq.base })
156
- await waitUntil(() => liveHead(this.doc), 10000, 'the live head')
157
- }
158
- this.doc.on('update', (u, origin) => { if (origin === REMOTE && !this.closed) this.run(() => this.pull()) })
159
- }
160
-
161
- watch () {
162
- this.watcher = fs.watch(this.dir, { recursive: true }, (ev, name) => {
163
- if (this.closed || !name) return
164
- const rel = String(name).split(path.sep).join('/')
165
- if (rel.split('/')[0] === BLOCK_DIR || (this.skip && this.skip(rel))) return
166
- clearTimeout(this.scanTimer)
167
- this.scanTimer = setTimeout(() => this.run(() => this.scan()), SCAN_MS)
168
- })
169
- this.reconcileTimer = setInterval(() => {
170
- if (this.closed || this.reconciling) return
171
- this.reconciling = true
172
- this.run(() => this.scan()).catch(() => {}).finally(() => { this.reconciling = false })
173
- }, RECONCILE_MS)
174
- this.reconcileTimer.unref?.()
175
- this.stepTimer = setInterval(() => { if (!this.closed) this.run(() => this.pull()).catch(() => {}) }, this.stepMs)
176
- this.stepTimer.unref?.()
177
- // A watcher just started does not hear everything at once (macOS's FSEvents takes a moment): a
178
- // save in that moment would wait for the next change in the folder. Looked at again, to be sure.
179
- this.settleTimers = WATCH_SETTLE_MS.map((ms) => {
180
- const t = setTimeout(() => { if (!this.closed) this.run(() => this.scan()) }, ms)
181
- t.unref?.()
182
- return t
183
- })
184
- }
185
-
186
- /**
187
- * The block's record: Seam's .seam/block.json, or (in place) the file the session names, which
188
- * also keeps what disk held as the block last read or wrote it (`known`): after a restart, a file
189
- * that differs from it is an edit made while the app was closed, and any other difference is the
190
- * square's newer version.
191
- */
192
- save () {
193
- clearTimeout(this.saveTimer)
194
- if (!this.record) return saveBlock(this.dir, this.block)
195
- fs.mkdirSync(path.dirname(this.record), { recursive: true })
196
- fs.writeFileSync(this.record + '.tmp', JSON.stringify({ ...this.block, known: this.known }))
197
- fs.renameSync(this.record + '.tmp', this.record)
198
- }
199
-
200
- saveSoon () {
201
- if (!this.record || this.saveTimer || this.closed) return
202
- this.saveTimer = setTimeout(() => { this.saveTimer = null; try { this.save() } catch {} }, 2000)
203
- this.saveTimer.unref?.()
204
- }
205
-
206
- /**
207
- * The in-place record of an earlier run in this quilt: its `known`, or null. On this square (the
208
- * app restarted), or on the branch's earlier square (a merge moved the folder on to the next one).
209
- */
210
- priorKnown () {
211
- try {
212
- const r = JSON.parse(fs.readFileSync(this.record, 'utf8'))
213
- return r && r.inPlace && r.quilt === this.quilt && r.known && typeof r.known === 'object' ? r.known : null
214
- } catch { return null }
215
- }
216
-
217
- /**
218
- * The session's own folder as the block, nothing checked out (see the top of this file). What
219
- * happened is logged: { same, taken, brought }, the files that matched, the person's edits that
220
- * went in, and the live document's newer versions written to disk.
221
- */
222
- async openInPlace () {
223
- const sq = await this.reader.square(this.quilt, this.squareRef)
224
- const prior = this.inPlace.fresh ? null : this.priorKnown()
225
- // Followed before (the app restarted, or the folder moved on to its branch's next square): edits
226
- // are what changed since the block last saw the folder, not since the session's last sync, and
227
- // a file only the square changed (its new head: what a merge took in from main) is the square's.
228
- if (prior) this.inPlace = { ...this.inPlace, edited: (p, blob) => (blob ?? null) !== ((prior[p] && prior[p].blob) ?? null), base: null, baseBlob: (p) => (prior[p] && prior[p].blob) || null, seen: true }
229
- this.block = { api: this.api, quilt: this.quilt, square: sq.id, square_short: sq.short || null, line: sq.line || null, paths: [''], at: null, head: null, files: {}, inPlace: true, live: liveKey(sq.id) }
230
- await this.connect()
231
- const head = this.head
232
- const t = await this.reader.tree(this.quilt, `c:${head}`)
233
- const b = this.block
234
- for (const e of (t && t.entries) || []) b.files[e.path] = { blob: e.blob || null, mode: e.mode, size: e.size, ...(e.term ? { term: e.term } : {}) }
235
- b.at = head
236
- b.head = sq.head || null // a commit's expect_head: none while the square has no commit of its own (its live head is then its base)
237
- this.save()
238
- this.summary = await this.run(() => this.adopt())
239
- this.watch()
240
- return this
241
- }
242
-
243
- /** What the live document says `p` holds, as a blob id (null: absent), and whether it says so itself (not only by its head). */
244
- wantedId (p) {
245
- const e = entryOf(this.doc, p)
246
- if (e) return { id: entryId(e), mode: e.op === 'delete' ? null : e.mode, named: true }
247
- const s = this.block.files[p]
248
- const m = liveMaps(this.doc)
249
- return { id: s ? s.blob : null, mode: s ? s.mode : null, named: m.clean.has(p) }
250
- }
251
-
252
- /**
253
- * In place, once: each file on disk against the live document. Equal: nothing to do. Different
254
- * and the session saw the folder's copy change since it last synced, or, the first time the
255
- * folder follows a square, a path the live document does not name that the folder's branch
256
- * changed since it left main (`inPlace.own`, from git: in its commits, or not committed and not
257
- * synced by the session, whose own changes are others' work too; without git: a file the folder
258
- * has that the session never synced): the person's, which the scan after this takes in;
259
- * when the square changed the same text since the session last synced it, both changes are
260
- * combined first (combineAway). Otherwise the live document's version (another member's, since
261
- * the folder's last sync, or the square's head) is written: a file the folder lacks, or has as git
262
- * left it, is never taken for the person's deletion or edit (a folder whose git was behind main,
263
- * a branch that left main before main's newer work, or a member back after the switch would
264
- * undo main's work in the square, and on main at the next merge).
265
- */
266
- async adopt () {
267
- const m = liveMaps(this.doc)
268
- const firstLook = !this.inPlace.seen && !this.inPlace.fresh
269
- const own = firstLook && this.inPlace.own ? await this.inPlace.own() : null
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]))
275
- const paths = new Set([...disk.keys(), ...Object.keys(this.block.files), ...m.files.keys(), ...m.blobs.keys(), ...m.gone.keys(), ...m.clean.keys()])
276
- const out = { same: 0, taken: [], brought: [], combined: [] }
277
- for (const p of [...paths].sort()) {
278
- if (this.skipped(p) || !this.block.paths.some((x) => under(p, x)) || (this.block.files[p] || {}).mode === 'gitlink' || (this.inPlace && this.nested(p))) continue
279
- const d = disk.get(p)
280
- const w = this.wantedId(p)
281
- if (entryOf(this.doc, p) && this.staleCopy(p, d, own, firstLook)) {
282
- await this.headStands(p, m)
283
- out.brought.push(p)
284
- continue
285
- }
286
- if ((d ? d.blob : null) === w.id) {
287
- // The same bytes: a different mode on disk (made executable here) goes in as an edit too.
288
- if (d) { const st = fs.lstatSync(path.join(this.dir, ...p.split('/'))); this.known[p] = w.mode && w.mode !== d.mode ? { blob: d.blob, mode: w.mode, size: -1, mtimeMs: -1 } : { blob: d.blob, mode: d.mode, size: st.size, mtimeMs: st.mtimeMs } }
289
- out.same++
290
- continue
291
- }
292
- // A file the session held back from this folder (someone else's box, or a change waiting for
293
- // whoever held the file): the folder never had the session's copy, so lacking it is no deletion.
294
- // The square's copy comes to disk (2026-11-01: a folder's first look deleted such a file).
295
- if (firstLook && !d && w.id && this.inPlace.heldBack && this.inPlace.heldBack(p)) {
296
- this.write(p, await this.wanted(p))
297
- out.brought.push(p)
298
- continue
299
- }
300
- const synced = !!(this.inPlace.synced && this.inPlace.synced(p))
301
- const branchs = firstLook && !w.named && (own ? own.committed.has(p) || (own.uncommitted.has(p) && !synced) : !!d && !synced)
302
- if (this.inPlace.edited(p, d ? d.blob : null) || branchs) {
303
- // The square changed it too since the folder last had it (a merge while the app was closed):
304
- // only the folder's own edit goes in, combined with the square's, never its old copy over it.
305
- const merged = d && w.id ? await this.combineAway(p, d) : null
306
- if (merged) { this.write(p, { bytes: merged, mode: d.mode }); out.combined.push(p) }
307
- // The person's: the scan sees disk differ from this and takes it in (a deletion when disk has nothing).
308
- if (w.id) this.known[p] = { blob: w.id, mode: w.mode, size: -1, mtimeMs: -1 }
309
- out.taken.push(p)
310
- continue
311
- }
312
- this.write(p, await this.wanted(p))
313
- out.brought.push(p)
314
- }
315
- await this.scan()
316
- this.save()
317
- if (this.logFn && (out.taken.length || out.brought.length)) {
318
- const list = (a) => `${a.slice(0, 5).join(', ')}${a.length > 5 ? `, and ${a.length - 5} more` : ''}`
319
- this.logFn(`${out.same} file(s) already matched the square${out.taken.length ? `; ${out.taken.length} edit(s) of yours went in (${list(out.taken)})` : ''}${out.combined.length ? `, combined with the square's changes to them since this folder last synced (${list(out.combined)})` : ''}${out.brought.length ? `; ${out.brought.length} newer version(s) came from the square (${list(out.brought)})` : ''}.`)
320
- }
321
- return out
322
- }
323
-
324
- /**
325
- * Whether the live document's entry for `p` is the branch's older copy of main's file, not work: in
326
- * a square the move started at main's tip for want of the branch's own commit (`inPlace.atTip`), a
327
- * full branch document names every file as the branch has it, and a file main changed (or deleted,
328
- * or added) after the branch left it, that the branch never changed (git: not in its commits since
329
- * it left main, nothing uncommitted here, no edit the session saw), would undo main's change at the
330
- * square's merge. Only at the first look, with git to ask.
331
- */
332
- staleCopy (p, d, own, firstLook) {
333
- if (!firstLook || !this.inPlace.atTip || !own) return false
334
- if (own.committed.has(p) || own.uncommitted.has(p)) return false
335
- return !this.inPlace.edited(p, d ? d.blob : null)
336
- }
337
-
338
- /** The square's head version of `p` stands: the live document's entry goes, and disk gets the head's file (or loses it). */
339
- async headStands (p, m) {
340
- const s = this.block.files[p]
341
- this.write(p, s ? await this.headFile(p, s) : null)
342
- this.doc.transact(() => {
343
- m.files.delete(p); m.blobs.delete(p); m.gone.delete(p); m.modes.delete(p)
344
- if (s) m.clean.set(p, { at: this.block.at }); else m.clean.delete(p)
345
- })
346
- }
347
-
348
- /**
349
- * The folder's copy of `p` (disk entry `d`) combined with the square's, against what the folder last
350
- * had (the session's last sync of it, `inPlace.base`; after a restart, the blob the block last saw):
351
- * the bytes to write, or null when there is nothing to combine (the square did not change it since,
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).
354
- */
355
- async combineAway (p, d) {
356
- if (!d.bytes || d.mode === 'symlink' || !isText(d.bytes)) return null
357
- let base = this.inPlace.base ? await this.inPlace.base(p) : null
358
- if (typeof base !== 'string' && this.inPlace.baseBlob) {
359
- const id = this.inPlace.baseBlob(p)
360
- if (id) { try { const b = await this.bytesOf(id); if (isText(b)) base = b.toString('utf8') } catch {} }
361
- }
362
- if (typeof base !== 'string') return null
363
- const ours = d.bytes.toString('utf8')
364
- // Someone else's box on it before the move (inPlace.boxed): the folder kept its own copy (git's,
365
- // moved on by pulls) while the session held theirs, and `base` is what everyone had when the box
366
- // began. Their change goes onto the folder's copy, never their whole older file over it.
367
- const boxed = !!(this.inPlace.boxed && this.inPlace.boxed(p))
368
- // The folder's copy is what it last had: nothing of its own to combine. It is taken as it is (an
369
- // edit the session took in that the relay never held, a path the square does not name at the switch).
370
- if (base === ours && !boxed) return null
371
- const want = await this.wanted(p)
372
- if (!want || want.mode === 'symlink' || !isText(want.bytes)) return null
373
- const theirs = want.bytes.toString('utf8')
374
- if (theirs === ours) return null
375
- // A box on a file the folder never moved past: the box's work is the file now.
376
- if (base === ours) return want.bytes
377
- if (theirs === base) return null
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')
382
- }
383
-
384
- skipped (p) { return !!(this.skip && this.skip(p)) }
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
-
399
- /** Whether `p` is inside a folder with a .git of its own (a submodule): never this block's to read or write. */
400
- nested (p) {
401
- const parts = p.split('/')
402
- for (let i = 1; i < parts.length; i++) if (fs.existsSync(path.join(this.dir, ...parts.slice(0, i), '.git'))) return true
403
- return false
404
- }
405
-
406
- /**
407
- * What changed on disk against `files` (path -> { blob, mode, size, mtimeMs }), as Seam's
408
- * localChanges answers. In place, the walk never enters a folder the session never syncs
409
- * (`skipDir`: .git, .quilt with the git folder set aside in it, node_modules, ignored ones), so a
410
- * big folder is not read on every scan, nor one that is a repository of its own (a submodule).
411
- */
412
- diskChanges (files) {
413
- if (!this.inPlace) return localChanges(this.dir, { paths: this.block.paths, files })
414
- const out = []
415
- const seen = new Set()
416
- const visit = (rel) => {
417
- let names
418
- try { names = fs.readdirSync(path.join(this.dir, rel), { withFileTypes: true }) } catch { return }
419
- for (const d of names) {
420
- const r = rel ? `${rel}/${d.name}` : d.name
421
- if (d.name === '.git' || d.name === BLOCK_DIR) continue
422
- // 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.
423
- if (d.isDirectory()) { if (!(this.skipDir && this.skipDir(r)) && !fs.existsSync(path.join(this.dir, r, '.git'))) visit(r); continue }
424
- if (!(d.isFile() || d.isSymbolicLink()) || this.skipped(r) || QUILT_TEMP.test(d.name)) continue
425
- const abs = path.join(this.dir, r)
426
- let st
427
- try { st = fs.lstatSync(abs) } catch { continue }
428
- seen.add(r)
429
- const k = files[r]
430
- if (k && k.size === st.size && k.mtimeMs === st.mtimeMs) continue
431
- let bytes
432
- try { bytes = st.isSymbolicLink() ? Buffer.from(fs.readlinkSync(abs)) : fs.readFileSync(abs) } catch { continue }
433
- const mode = st.isSymbolicLink() ? 'symlink' : (st.mode & 0o111) && process.platform !== 'win32' ? 'exec' : 'file'
434
- // Being written as it was read (it changed during the read, or it reads empty a moment after being
435
- // emptied, as a save that truncates first does): looked at again shortly, never taken in half-written.
436
- if (!st.isSymbolicLink()) {
437
- let again = null
438
- try { again = fs.lstatSync(abs) } catch {}
439
- const midWrite = !again || again.size !== st.size || again.mtimeMs !== st.mtimeMs || bytes.length !== st.size
440
- if (midWrite || (bytes.length === 0 && k && k.size > 0 && Date.now() - st.mtimeMs < SETTLE_MS)) { this.unsettled = true; continue }
441
- }
442
- const id = blobId(bytes)
443
- // The same bytes (touched, or rewritten as they were): seen as of the look before this read.
444
- if (k && k.blob === id && k.mode === mode) { if (files === this.known) files[r] = { ...k, size: st.size, mtimeMs: st.mtimeMs }; continue }
445
- // `stat`: the file as it was just before this read. Recorded as seen, a save made after the read
446
- // still differs from it, so the next scan reads it again (2026-11-14: a save between this read
447
- // and a later look at the file was marked seen and never taken in).
448
- out.push({ path: r, status: k ? 'modified' : 'added', blob: id, mode, size: bytes.length, bytes, stat: { size: st.size, mtimeMs: st.mtimeMs } })
449
- }
450
- }
451
- visit('')
452
- for (const p of Object.keys(files)) if (!seen.has(p) && !this.skipped(p) && !this.nested(p)) out.push({ path: p, status: 'deleted' })
453
- return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
454
- }
455
-
456
- get head () { return liveHead(this.doc) }
457
- get by () { return this.relayOpts.name || '' }
458
-
459
- /** Brings every disk change under the block into the live document (an edit, never a guess). */
460
- async scan () {
461
- if (this.block.at !== this.head) return // 05: no ingest against the wrong base; pull re-projects first
462
- const m = liveMaps(this.doc)
463
- const snap = this.block.files
464
- const readAt = Date.now()
465
- let changes = this.diskChanges(this.known)
466
- if (this.unsettled) { this.unsettled = false; this.scanSoon(SCAN_MS * 2) }
467
- // What the session never syncs is never taken in; noting its size and time spares reading it again.
468
- for (const c of changes) {
469
- if (!this.skipped(c.path)) continue
470
- if (c.status === 'deleted') { delete this.known[c.path]; continue }
471
- try { this.known[c.path] = { blob: c.blob, mode: c.mode, ...this.seenStat(c.path, c, readAt) } } catch {}
472
- }
473
- changes = changes.filter((c) => !this.skipped(c.path))
474
- if (!changes.length) return
475
- let uploads = []
476
- for (const c of changes) {
477
- if (c.status === 'deleted') continue
478
- if (c.mode === 'symlink' || !isText(c.bytes) || c.bytes.length > MAX_LIVE_TEXT) uploads.push({ kind: 'blob', id: c.blob, bytes: c.bytes })
479
- }
480
- if (uploads.length) {
481
- // A binary needs Seam to hold its bytes first, as this member. Without that, the texts still go in, and the binaries wait for the next scan.
482
- try {
483
- if (!this.client) throw new Error('sign in to Seam (quilt login) so binary files reach the square')
484
- await this.client.upload(this.block.quilt, uploads)
485
- this.problem = null
486
- } catch (err) {
487
- const ids = new Set(uploads.map((u) => u.id))
488
- const waiting = changes.filter((c) => c.status !== 'deleted' && ids.has(c.blob)).map((c) => c.path)
489
- this.problem = `${waiting.length} binary file(s) are not in the square yet (${waiting.slice(0, 3).join(', ')}): ${err.message}`
490
- if (this.logFn) this.logFn(this.problem)
491
- changes = changes.filter((c) => !waiting.includes(c.path))
492
- uploads = []
493
- }
494
- }
495
- const taken = []
496
- const rewrite = []
497
- const moved = []
498
- // A text edit goes to the relay as a write (relay-live-write.js): merged there against the version this
499
- // folder last synced and applied in whole lines, one write at a time per file. What the relay doesn't
500
- // take that way (an older relay, a refusal) and everything else (deletions, binaries) is edited here.
501
- if (this.relayWrites()) {
502
- const viaRelay = changes.filter((c) => this.relayWritable(c, uploads, m, snap))
503
- const back = []
504
- for (const c of viaRelay) {
505
- if (this.closed) return
506
- const how = await this.relayWrite(c, { m, snap, changes, readAt, taken, moved })
507
- if (how === 'local') back.push(c)
508
- }
509
- changes = changes.filter((c) => !viaRelay.includes(c) || back.includes(c))
510
- }
511
- // What each file held before, for the record of who changed what (onEdits): the live document's text, else the head's.
512
- const before = new Map()
513
- if (this.onEdits || this.rules) {
514
- for (const c of changes) {
515
- const t = m.files.get(c.path)
516
- if (t) { before.set(c.path, t.toString()); continue }
517
- const b = snap[c.path]
518
- if (!b || !b.blob || m.blobs.has(c.path) || m.gone.has(c.path) || (b.size || 0) > MAX_LIVE_TEXT) continue
519
- try { const bytes = await this.bytesOf(b.blob); if (isText(bytes)) before.set(c.path, bytes.toString('utf8')) } catch {}
520
- }
521
- }
522
- // A file changed on disk and in the square since disk last had it (someone's edit, or main brought in,
523
- // reached the live document or the head before this edit was read): what disk last had is the base
524
- // the two are combined against, so the edit goes in as a change and nothing the square has is undone.
525
- const both = new Map()
526
- for (const c of changes) {
527
- if (c.status === 'deleted' || c.mode === 'symlink' || c.bytes.length > MAX_LIVE_TEXT || !isText(c.bytes)) continue
528
- const k = this.known[c.path]
529
- if (!k || !k.blob || k.blob === c.blob) continue
530
- const e = entryOf(this.doc, c.path)
531
- const s = snap[c.path]
532
- const now = e ? entryId(e) : s && s.mode !== 'conflict' ? s.blob : null
533
- if (!now || now === k.blob) continue
534
- try {
535
- const last = this.lastText.get(c.path)
536
- const base = last && last.id === k.blob ? last.text : (await this.bytesOf(k.blob)).toString('utf8')
537
- const head = e ? null : (await this.bytesOf(s.blob))
538
- if (head && !isText(head)) continue
539
- both.set(c.path, { base, head: head ? head.toString('utf8') : null })
540
- } catch {}
541
- }
542
- this.doc.transact(() => {
543
- for (const c of changes) {
544
- const p = c.path
545
- const base = snap[p]
546
- const had = !!(base && !m.gone.has(p)) || m.files.has(p) || m.blobs.has(p)
547
- // A file another member moved away (deleted, the same text added elsewhere): this edit goes where it went.
548
- if (this.rules && c.status !== 'deleted' && !had && c.mode !== 'symlink' && c.bytes.length <= MAX_LIVE_TEXT && isText(c.bytes)) {
549
- const mv = this.rules.movedTo({ doc: this.doc, path: p, by: this.by })
550
- const to = mv && m.files.get(mv.to)
551
- if (to && !changes.some((x) => x.path === mv.to)) {
552
- const last = this.lastText.get(p)
553
- 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() })
554
- const was = to.toString()
555
- const detail = applyTextDiff(to, r.text)
556
- m.writers.set(mv.to, { by: this.by, ts: Date.now(), at: this.block.at })
557
- taken.push({ path: mv.to, kind: 'edited', detail, before: was, after: r.text })
558
- rewrite.push({ path: mv.to, bytes: Buffer.from(r.text, 'utf8'), mode: m.modes.get(mv.to) === 'exec' ? 'exec' : 'file' })
559
- moved.push({ from: p, to: mv.to, by: mv.by })
560
- continue
561
- }
562
- }
563
- // Who wrote it before this edit: the one whose lines landed first, should they clash.
564
- const prior = (m.writers.get(p) || {}).by || null
565
- // Whose work this path is now (on going back to git, its box is theirs: Session.leaveSquare), and the
566
- // head it was made on: the relay combines an edit made on a head it has moved on from (bring-in.js lateEdits).
567
- m.writers.set(p, { by: this.by, ts: Date.now(), at: this.block.at })
568
- if (c.status === 'deleted') {
569
- 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 })
570
- delete this.known[p]
571
- if (had) taken.push({ path: p, kind: 'deleted', detail: '', ...(before.has(p) ? { before: before.get(p), after: '' } : {}) })
572
- // With the same text added elsewhere by this folder, a move (edits others make to it follow it).
573
- if (this.rules && before.has(p)) this.rules.noteGone({ doc: this.doc, path: p, text: before.get(p), by: this.by })
574
- continue
575
- }
576
- const kind = had ? 'edited' : 'created'
577
- if (base && base.blob === c.blob && base.mode === c.mode) {
578
- m.clean.set(p, { at: this.block.at }); m.gone.delete(p)
579
- // Back as the head has it: an edit too (undoing one), unless it never left.
580
- if (before.has(p) && before.get(p) !== c.bytes.toString('utf8')) taken.push({ path: p, kind, detail: '', before: before.get(p), after: c.bytes.toString('utf8') })
581
- } else if (uploads.some((u) => u.id === c.blob)) {
582
- m.clean.delete(p); m.gone.delete(p)
583
- m.blobs.set(p, { blob: c.blob, size: c.bytes.length, mode: c.mode })
584
- taken.push({ path: p, kind, detail: `${c.bytes.length} bytes` })
585
- } else {
586
- m.clean.delete(p); m.gone.delete(p); m.blobs.delete(p)
587
- let t = m.files.get(p)
588
- const fresh = !t
589
- if (!t) { t = new Y.Text(); m.files.set(p, t) }
590
- let after = c.bytes.toString('utf8')
591
- const w = both.get(p)
592
- const cur = w ? (fresh ? w.head : t.toString()) : null
593
- if (this.rules) {
594
- // Merged against what disk last had, and the ways a clash is caught run on it (live-merge.js):
595
- // lines both changed keep what landed first, this folder's are held, and disk gets the result.
596
- const theirs = cur !== null ? cur : fresh ? (before.has(p) ? before.get(p) : null) : t.toString()
597
- 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
598
- } else if (w && cur !== null && cur !== w.base && cur !== after) {
599
- // No engine (a block opened outside a session): what landed first keeps the lines both changed,
600
- // and this folder's are said in its log, never dropped without a word.
601
- const r = mergeLive(w.base, after, cur)
602
- after = r.text
603
- 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')}`)
604
- }
605
- if (after !== c.bytes.toString('utf8')) rewrite.push({ path: p, bytes: Buffer.from(after, 'utf8'), mode: c.mode })
606
- let detail = applyTextDiff(t, after)
607
- this.lastText.set(p, { id: blobId(Buffer.from(after, 'utf8')), text: after })
608
- // A file new to the live document took its whole text: what changed is measured from the head's.
609
- if (fresh && before.has(p)) { const probe = new Y.Doc().getText(); probe.insert(0, before.get(p)); detail = applyTextDiff(probe, after) }
610
- if (c.mode === 'exec') m.modes.set(p, 'exec'); else if (m.modes.has(p)) m.modes.delete(p)
611
- if (detail || !had) taken.push({ path: p, kind, detail, before: before.get(p) ?? '', after })
612
- if (!had && this.rules) this.rules.noteNew({ doc: this.doc, path: p, text: after, by: this.by })
613
- }
614
- this.known[p] = { blob: c.blob, mode: c.mode, ...this.seenStat(p, c, readAt) }
615
- }
616
- })
617
- // Disk gets the combination: what the square had that this edit was not made on. Never over a save
618
- // made since this scan read the file: that save is taken in next, merged with the combination.
619
- for (const x of rewrite) {
620
- if (this.write(x.path, x, { guard: true }) === false) {
621
- const c = changes.find((y) => y.path === x.path)
622
- if (c && c.bytes) this.lastText.set(x.path, { id: c.blob, text: c.bytes.toString('utf8') })
623
- this.scanSoon()
624
- }
625
- }
626
- // An edit to a moved file went to where it went: the old path comes off disk again.
627
- for (const mv of moved) {
628
- this.write(mv.from, null)
629
- 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.`)
630
- if (this.logFn) this.logFn(`${mv.from} was moved to ${mv.to} by ${mv.by}: your edit went there`)
631
- }
632
- this.saveSoon()
633
- 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}`) } }
634
- }
635
-
636
- /** Whether the relay takes this folder's text edits as writes (relay-live-write.js), and this block may send them. */
637
- relayWrites () { return !!(this.conn && this.conn.relayWrites && !this.noRelayWrites && this.conn.connected !== false) }
638
-
639
- /** 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). */
640
- relayWritable (c, uploads, m, snap) {
641
- if (c.status === 'deleted' || c.mode === 'symlink' || !c.bytes || c.bytes.length > MAX_LIVE_TEXT || !isText(c.bytes)) return false
642
- if (uploads.some((u) => u.id === c.blob)) return false
643
- const head = snap[c.path]
644
- if (head && head.blob === c.blob && head.mode === c.mode && !m.files.has(c.path)) return false
645
- return true
646
- }
647
-
648
- /**
649
- * What disk had of `p` as this block last synced it: the text its last write or write-out left (lastText),
650
- * else the head's file when that is what it had, else the blob it knew; null when not known.
651
- */
652
- async syncedText (p) {
653
- const k = this.known[p]
654
- if (!k || !k.blob) return null
655
- const last = this.lastText.get(p)
656
- if (last && last.id === k.blob) return last.text
657
- try { const b = await this.bytesOf(k.blob); return isText(b) ? b.toString('utf8') : null } catch { return null }
658
- }
659
-
660
- /**
661
- * One text edit, as a write to the relay. 'done' (in, and disk has the result unless it was saved again
662
- * meanwhile), 'local' (the relay asked for it to be edited here as before), or 'later' (not sent: the
663
- * next scan tries again, and nothing is written over it meanwhile).
664
- */
665
- async relayWrite (c, { m, snap, changes, readAt, taken, moved }) {
666
- const p = c.path
667
- const text = c.bytes.toString('utf8')
668
- const had = !!(snap[p] && !m.gone.has(p)) || m.files.has(p) || m.blobs.has(p)
669
- // A file another member moved away (deleted, the same text added elsewhere): this edit goes where it went.
670
- let target = p
671
- let mv = null
672
- let base
673
- if (this.rules && !had) {
674
- const to = this.rules.movedTo({ doc: this.doc, path: p, by: this.by })
675
- if (to && m.files.get(to.to) && !changes.some((x) => x.path === to.to)) { mv = to; target = to.to }
676
- }
677
- if (mv) { const last = this.lastText.get(p); base = last ? last.text : mv.text } else base = await this.syncedText(p)
678
- // A save that landed in the file this block replaced was made from the text before (base-pick.js): it goes
679
- // too (`older`), and the relay puts the save onto it, so the partner's change written meanwhile stays.
680
- const older = !mv && typeof base === 'string' ? this.overwritten.pick(p, base, text) : base
681
- const known = !!this.known[p]
682
- const trusted = !!(this.rules && this.rules.trusted && this.rules.trusted.get(target) === text)
683
- const req = {
684
- path: target,
685
- base: typeof base === 'string' ? versionOf(base) : null,
686
- // Small, or not live yet (the head's text, which the relay never reads): its text goes with it.
687
- ...(typeof base === 'string' && (base.length <= INLINE_BASE || !m.files.has(target)) ? { baseText: base } : {}),
688
- // Known here but its text is not (after a restart): the relay merges it as a stale write.
689
- ...(typeof base !== 'string' && known && !mv ? { baseUnknown: true } : {}),
690
- text,
691
- ...(older !== base && typeof older === 'string' ? { older } : {}),
692
- mode: c.mode,
693
- at: this.block.at,
694
- ...(trusted ? { trusted: true } : {})
695
- }
696
- let r
697
- try {
698
- r = await this.conn.liveWrite(req, { baseOf: () => (typeof base === 'string' ? base : null) })
699
- } catch (err) {
700
- if (/unknown branch request/.test(err.message)) { this.noRelayWrites = true; return 'local' }
701
- if (this.logFn && this.writeProblem !== err.message) this.logFn(`${p}: your edit waits to reach the square (${err.message}); it is tried again`)
702
- this.writeProblem = err.message
703
- this.scanSoon(1000)
704
- return 'later'
705
- }
706
- this.writeProblem = null
707
- if (r.fallback) return 'local'
708
- if (trusted) this.rules.trusted.delete(target)
709
- const result = r.same ? text : r.text
710
- // Seen as read; disk gets the result only if it was not saved again since (then that save comes next, on this text).
711
- if (mv) {
712
- this.write(p, null)
713
- const want = { bytes: Buffer.from(result, 'utf8'), mode: m.modes.get(target) === 'exec' ? 'exec' : 'file' }
714
- this.write(target, want, { guard: true })
715
- moved.push({ from: p, to: target, by: mv.by })
716
- } else {
717
- this.overwritten.forget(p)
718
- this.known[p] = { blob: c.blob, mode: c.mode, ...this.seenStat(p, c, readAt) }
719
- this.lastText.set(p, { id: c.blob, text })
720
- if (result !== text && this.write(p, { bytes: Buffer.from(result, 'utf8'), mode: c.mode }, { guard: true, before: text }) === false) this.scanSoon()
721
- }
722
- for (const n of r.notices || []) { try { if (this.rules) this.rules.notice(n) } catch {} }
723
- for (const l of r.logs || []) if (this.logFn) this.logFn(l)
724
- 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 {} }
725
- // Names this write removed that other files here still use: said to the writer, never a block.
726
- if (this.rules && Array.isArray(r.gone) && r.gone.length) {
727
- let uses = []
728
- try { uses = findUses(r.gone, this.diskTexts(), { skip: target }) } catch {}
729
- const w = removedNameWarning(target, uses)
730
- if (w) { this.rules.notice(w); if (this.logFn) this.logFn(`⚠️ ${w}`) }
731
- }
732
- if (r.detail || !had) taken.push({ path: target, kind: had || mv ? 'edited' : 'created', detail: r.detail || '', before: r.before ?? '', after: result })
733
- if (!had && !mv && this.rules) this.rules.noteNew({ doc: this.doc, path: p, text: result, by: this.by })
734
- return 'done'
735
- }
736
-
737
- /**
738
- * The size and time to record for a change this scan read: the file as it was just before the read
739
- * (diskChanges' `stat`); else, when it was changed around the time of the read, none (-1), so it is
740
- * read again rather than taken as seen (Seam's own walk, which does not say).
741
- */
742
- seenStat (p, c, readAt) {
743
- if (c.stat) return { size: c.stat.size, mtimeMs: c.stat.mtimeMs }
744
- try {
745
- const st = fs.lstatSync(path.join(this.dir, ...p.split('/')))
746
- if (st.mtimeMs >= readAt - 5 || st.size !== c.bytes.length) return { size: -1, mtimeMs: -1 }
747
- return { size: st.size, mtimeMs: st.mtimeMs }
748
- } catch { return { size: -1, mtimeMs: -1 } }
749
- }
750
-
751
- /**
752
- * swap-in.js for this block (Windows' backup and the fallback's second name beside its record, in
753
- * .quilt/tmp): { placed, displaced, other } (swap-in.js). Only without an atomic exchange (said once in
754
- * the log): a save replaced in the one system call the fallback cannot cover is said to its writer.
755
- */
756
- swapInto (p, abs, tmp, look) {
757
- const r = swapIn(abs, tmp, look, { asideDir: this.record ? path.join(path.dirname(this.record), 'tmp') : null, log: this.logFn })
758
- if (r.replaced) {
759
- 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).`
760
- try { if (this.rules) this.rules.notice(w) } catch {}
761
- if (this.logFn) this.logFn(`⚠️ ${w}`)
762
- }
763
- return r
764
- }
765
-
766
- /**
767
- * Whether `p` on disk changed since this block last read or wrote it (a save not taken in yet): then
768
- * nothing is written over it. A different size or time with the same bytes is no change (and is
769
- * noted as seen).
770
- */
771
- diskMoved (p) {
772
- const abs = path.join(this.dir, ...p.split('/'))
773
- const k = this.known[p]
774
- let st
775
- try { st = fs.lstatSync(abs) } catch { return !!k } // gone here but known: a deletion not taken in yet
776
- if (!k) return true // a file here this block never took in
777
- if (k.size === st.size && k.mtimeMs === st.mtimeMs) return false
778
- let bytes
779
- try { bytes = st.isSymbolicLink() ? Buffer.from(fs.readlinkSync(abs)) : fs.readFileSync(abs) } catch { return true }
780
- const mode = st.isSymbolicLink() ? 'symlink' : (st.mode & 0o111) && process.platform !== 'win32' ? 'exec' : 'file'
781
- if (blobId(bytes) !== k.blob || (k.mode && mode !== k.mode && k.mode !== 'conflict')) return true
782
- this.known[p] = { ...k, size: st.size, mtimeMs: st.mtimeMs }
783
- return false
784
- }
785
-
786
- /** A scan soon (a save to take in that a write-out left alone, or a write to send again). */
787
- scanSoon (ms = SCAN_MS) {
788
- if (this.closed) return
789
- clearTimeout(this.scanTimer)
790
- this.scanTimer = setTimeout(() => this.run(() => this.scan()), ms)
791
- this.scanTimer.unref?.()
792
- }
793
-
794
- /** Bytes of a blob, from this block's cache or the server. */
795
- async bytesOf (id) {
796
- if (!this.cache.has(id)) {
797
- const { blobs } = await this.reader.blobs(this.block.quilt, [id])
798
- this.cache.set(id, Buffer.from(blobs[id], 'base64'))
799
- }
800
- return this.cache.get(id)
801
- }
802
-
803
- /**
804
- * The head's file `s` (block.files) at `p` as disk holds it: { bytes, mode }. A conflict Seam keeps in
805
- * the square (a term: a rebase or merge that did not combine) has no bytes of its own: it is written
806
- * with its markers, as Seam's own folders write it, and settled by editing them out and committing.
807
- */
808
- async headFile (p, s, rev = `c:${this.block.at}`) {
809
- if (s.mode !== 'conflict') return { bytes: await this.bytesOf(s.blob), mode: s.mode }
810
- const r = await this.reader.cat(this.block.quilt, rev, p, { format: conflictStyle() })
811
- return { bytes: Buffer.from((r && r.content) || '', 'base64'), mode: 'file' }
812
- }
813
-
814
- /** What disk should hold at `p`: { bytes, mode } or null (absent). */
815
- async wanted (p) {
816
- const e = entryOf(this.doc, p)
817
- if (e && e.op === 'delete') return null
818
- if (e && e.bytes) return { bytes: e.bytes, mode: e.mode }
819
- if (e && e.blob) return { bytes: await this.bytesOf(e.blob), mode: e.mode }
820
- const s = this.block.files[p]
821
- return s ? this.headFile(p, s) : null
822
- }
823
-
824
- /**
825
- * Puts `want` on disk at `p` (null: removes it). `guard`: only if disk still has what this block last
826
- * read or wrote there (diskMoved), looked at again just before the file is replaced; false when it was
827
- * left alone, so a save made meanwhile is taken in (and merged) rather than overwritten.
828
- */
829
- write (p, want, { guard = false, before: was = null } = {}) {
830
- const abs = path.join(this.dir, ...p.split('/'))
831
- if (guard && this.diskMoved(p)) return false
832
- if (!want) { fs.rmSync(abs, { force: true }); delete this.known[p]; this.lastText.delete(p); this.wrote(p); return true }
833
- fs.mkdirSync(path.dirname(abs), { recursive: true })
834
- const tmp = path.join(path.dirname(abs), `.${path.basename(abs)}.quilt-tmp`)
835
- // What is recorded as seen is the written file as it was before it took its place (a rename keeps its
836
- // size and time): a save that lands right after it differs from it, so it is taken in, never taken as
837
- // this write (2026-11-14: a save between the rename and a look at the file afterwards was lost).
838
- let st
839
- if (want.mode === 'symlink') { fs.rmSync(abs, { force: true }); fs.symlinkSync(want.bytes.toString('utf8'), abs); st = fs.lstatSync(abs) } else {
840
- fs.writeFileSync(tmp, want.bytes, { mode: want.mode === 'exec' ? 0o755 : 0o644 })
841
- st = fs.lstatSync(tmp)
842
- const last = this.lastText.get(p)
843
- // 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.
844
- const before = typeof was === 'string' ? was : last && this.known[p] && last.id === this.known[p].blob ? last.text : null
845
- const placed = this.place(p, abs, tmp, { guard, before, wrote: want.bytes })
846
- if (!placed) return false
847
- }
848
- this.known[p] = { blob: blobId(want.bytes), mode: want.mode, size: st.size, mtimeMs: st.mtimeMs }
849
- 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') })
850
- else this.lastText.delete(p)
851
- this.saveSoon()
852
- this.wrote(p)
853
- return true
854
- }
855
-
856
- wrote (p) { if (this.onWrite) { try { this.onWrite(p) } catch {} } }
857
-
858
- /**
859
- * Puts `tmp` in the place of `abs` (a rename). `guard`: not when disk changed since this block last
860
- * saw it (diskMoved): false then. A save into the file being replaced, landing in the instant between
861
- * that look and the rename (an editor that truncates and writes, opened just before it), would be
862
- * gone with the old file: the old file stays open across the rename, and what was saved into it after
863
- * the look is put back as a save of its own (rescue, looked at again 100 ms later too), taken in by the next
864
- * scan. The replace is always one atomic exchange (swap-in.js; the file is never absent); a save that took
865
- * the file's place by a rename of its own before the last look is never replaced: false, and it is taken in;
866
- * one that took it in the instant of the exchange comes back from it and is taken in as its writer's save
867
- * (rescue).
868
- */
869
- place (p, abs, tmp, { guard = false, before = null, wrote = null } = {}) {
870
- let old = null
871
- let look = null
872
- let displaced = null
873
- let other = null
874
- if (guard) { try { old = fs.openSync(abs, 'r'); look = fs.lstatSync(abs) } catch {} }
875
- try {
876
- // As it was before the look below: a save into it after this is either seen by that look or after the rename.
877
- const seen = old !== null ? fs.fstatSync(old) : null
878
- // Changed since this block saw it, or replaced since it was opened (look is another file): left alone.
879
- if (guard && (this.diskMoved(p) || (look && seen && !look.isSymbolicLink() && look.ino !== seen.ino))) { fs.rmSync(tmp, { force: true }); return false }
880
- if (guard && old === null) {
881
- // Nothing there at the look: put in only if nothing is there now (a hard link never replaces a save made meanwhile).
882
- try { fs.linkSync(tmp, abs); fs.rmSync(tmp, { force: true }) } catch (err) {
883
- if (err.code !== 'EEXIST') fs.renameSync(tmp, abs)
884
- else {
885
- fs.rmSync(tmp, { force: true })
886
- let dir = false
887
- try { dir = fs.lstatSync(abs).isDirectory() } catch {}
888
- if (dir) throw err // a folder where the file goes: as a rename would fail
889
- return false
890
- }
891
- }
892
- } else if (old !== null && look && !look.isSymbolicLink()) {
893
- // Never over a save it can see (swap-in.js): one that took the file's place since the look is taken in first.
894
- const r = this.swapInto(p, abs, tmp, look)
895
- if (!r.placed) return false
896
- displaced = r.displaced
897
- other = r.other ?? null
898
- } else fs.renameSync(tmp, abs)
899
- // A save that took the path in the instant of the exchange: its writer's save, taken in once whole.
900
- if (other !== null) { this.rescue(p, other, { before, wrote }); other = null }
901
- if (old !== null) {
902
- const now = fs.fstatSync(old)
903
- // A save written into the file replaced: back as a save of its own, once whole (rescue), or at once.
904
- 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 {
905
- // An editor that opened the file just before the rename may write into it a moment after: looked at once more.
906
- const fd = old
907
- old = null
908
- const t = setTimeout(() => {
909
- let later = null
910
- try { later = fs.fstatSync(fd) } catch {}
911
- if (!this.closed && later && (later.size !== seen.size || later.mtimeMs !== seen.mtimeMs)) this.rescue(p, fd, { before, wrote })
912
- else { try { fs.closeSync(fd) } catch {} }
913
- }, 100)
914
- t.unref?.()
915
- }
916
- }
917
- return true
918
- } finally {
919
- if (old !== null) { try { fs.closeSync(old) } catch {} }
920
- }
921
- }
922
-
923
- /**
924
- * A save that landed in a file this block replaced (place): once it is written out in full, it goes back
925
- * on disk as a save of its own. Saved again since (from what this block wrote, without it): its own
926
- * change goes onto that newer save (`before`: what disk had before the write, `wrote`: the write), the
927
- * newer one winning where both changed a line, so neither is lost.
928
- */
929
- async rescue (p, fd, { before = null, wrote = null } = {}) {
930
- try {
931
- let last = null
932
- for (let i = 0; i < 50; i++) {
933
- const st = fs.fstatSync(fd)
934
- if (last && st.size === last.size && st.mtimeMs === last.mtimeMs) break
935
- last = st
936
- await new Promise((resolve) => setTimeout(resolve, 20))
937
- }
938
- const size = fs.fstatSync(fd).size
939
- const bytes = Buffer.alloc(size)
940
- let off = 0
941
- while (off < size) { const n = fs.readSync(fd, bytes, off, size - off, off); if (!n) break; off += n }
942
- if (this.closed) return
943
- await this.run(() => this.putBack(p, bytes, { before, wrote }))
944
- } catch {} finally { try { fs.closeSync(fd) } catch {} }
945
- }
946
-
947
- /**
948
- * A save of `p` (`bytes`) that this block's write took out of the path (it landed in the file replaced, or
949
- * took that file's place in the instant before) goes back on disk as a save of its own: over what this block
950
- * wrote, whole; saved again since (from what this block wrote, without it), its own change (`before`: what
951
- * disk had before the write, `wrote`: the write) goes onto that newer save, both kept where both changed a
952
- * line. Run in the block's queue.
953
- */
954
- async putBack (p, bytes, { before = null, wrote = null } = {}) {
955
- const abs = path.join(this.dir, ...p.split('/'))
956
- const k = this.known[p]
957
- if (k && k.blob === blobId(bytes)) return
958
- const tmp = path.join(path.dirname(abs), `.${path.basename(abs)}.quilt-save`)
959
- const mode = k && k.mode === 'exec' ? 0o755 : 0o644
960
- // Put back only over the file as looked at (place, swap-in.js): saved again in that instant, looked at again.
961
- let placed = false
962
- let ours = false
963
- for (let attempt = 0; attempt < 5 && !placed; attempt++) {
964
- if (!this.diskMoved(p)) {
965
- // Disk still has what this block wrote: the save goes back over it.
966
- ours = true
967
- fs.writeFileSync(tmp, bytes, { mode })
968
- // A save in the instant of this put-back was made from what this block wrote: merged on that (rescue).
969
- placed = this.place(p, abs, tmp, { guard: true, before: wrote && isText(wrote) ? wrote.toString('utf8') : null, wrote: bytes })
970
- continue
971
- }
972
- ours = false
973
- let look = null
974
- try { look = fs.lstatSync(abs) } catch {}
975
- let now = null
976
- try { now = fs.readFileSync(abs) } catch {}
977
- if (!now || !look || typeof before !== 'string' || !wrote || !isText(bytes) || !isText(now)) return
978
- const onto = mergeLive(before, bytes.toString('utf8'), wrote.toString('utf8')).text
979
- // Both saves are this folder's: where they changed the same place, both go in (nothing is lost; its writer sees both).
980
- const merged = mergeLive(wrote.toString('utf8'), onto, now.toString('utf8'), { union: true }).text
981
- if (merged === now.toString('utf8')) return
982
- fs.writeFileSync(tmp, merged, { mode })
983
- // Only over that newer save as it is (it is taken in with the late one's change on it).
984
- if (look.isSymbolicLink()) { fs.rmSync(tmp, { force: true }); return }
985
- const r = this.swapInto(p, abs, tmp, look)
986
- placed = r.placed
987
- const was = now.toString('utf8')
988
- if (r.displaced) { const again = r.displaced; setImmediate(() => { this.run(() => this.putBack(p, again, { before: was, wrote: Buffer.from(merged, 'utf8') })).catch(() => {}) }) }
989
- if (r.other !== null && r.other !== undefined) this.rescue(p, r.other, { before: was, wrote: Buffer.from(merged, 'utf8') })
990
- }
991
- if (!placed) { this.scanSoon(); return }
992
- // Made from what disk had before this block's write, which it landed in: merged against that (base-pick.js).
993
- if (ours && typeof before === 'string' && isText(bytes)) this.overwritten.mark(p, bytes.toString('utf8'), before)
994
- if (this.logFn) this.logFn(`${p}: a save landed while Quilt wrote the session's version; it is taken in now`)
995
- this.scanSoon()
996
- }
997
-
998
- /** Moves the block to the document's head (a commit by anyone in the square), then writes the overlay out. */
999
- async pull () {
1000
- if (this.closed) return
1001
- if (this.head && this.head !== this.block.at) await this.reproject(this.head)
1002
- await this.scan() // an edit not yet ingested is merged in before a remote change is written over it
1003
- const m = liveMaps(this.doc)
1004
- const paths = new Set([...m.files.keys(), ...m.blobs.keys(), ...m.gone.keys(), ...m.clean.keys()])
1005
- // One file that can't be written out (its bytes not readable, the disk refusing) never holds up the
1006
- // others, and is said (outOfStep, in the folder's status), then tried again (STEP_MS).
1007
- const failed = []
1008
- for (const p of paths) {
1009
- if (!this.block.paths.some((x) => under(p, x)) || this.skipped(p) || (this.inPlace && this.nested(p))) continue
1010
- try {
1011
- const want = await this.wanted(p)
1012
- const id = want ? blobId(want.bytes) : null
1013
- const have = this.known[p] ? this.known[p].blob : null
1014
- // Never over a save not taken in yet (one made since the scan above): the next scan merges it.
1015
- if (id !== have || (want && this.known[p].mode !== want.mode)) {
1016
- const was = have && want ? await this.syncedText(p) : null
1017
- if (this.write(p, want, { guard: true, before: was }) === false) this.scanSoon()
1018
- }
1019
- } catch (err) { failed.push({ path: p, err }) }
1020
- }
1021
- this.noteOutOfStep(failed)
1022
- }
1023
-
1024
- /** What a write-out could not bring in step, said once while it lasts (and when it is over). */
1025
- noteOutOfStep (failed) {
1026
- const was = this.outOfStep || null
1027
- this.outOfStep = failed.length ? `${failed.length} file(s) here are not as the square has them yet (${failed.slice(0, 3).map((f) => f.path).join(', ')}${failed.length > 3 ? ', …' : ''}): ${String(failed[0].err && failed[0].err.message || failed[0].err).slice(0, 200)}` : null
1028
- if (this.logFn && this.outOfStep && this.outOfStep !== was) this.logFn(this.outOfStep)
1029
- if (this.logFn && was && !this.outOfStep) this.logFn('every file here is as the square has it again.')
1030
- }
1031
-
1032
- /** 05 "Moving block.at": rewrites the files that are Quilt's; files in the overlay are the holder's and stay. */
1033
- async reproject (to) {
1034
- const b = this.block
1035
- const d = await this.reader.diff(b.quilt, { from: `c:${b.at}`, to: `c:${to}`, paths: b.paths, format: 'names' })
1036
- const t = d.files.length ? await this.reader.tree(b.quilt, `c:${to}`, b.paths) : { entries: [] }
1037
- const byPath = new Map(t.entries.map((e) => [e.path, e]))
1038
- const local = new Set(this.diskChanges(this.known).map((c) => c.path))
1039
- for (const f of d.files) {
1040
- const e = byPath.get(f.path)
1041
- if (e) b.files[f.path] = { blob: e.mode === 'conflict' ? null : e.blob, mode: e.mode, size: e.size, ...(e.term ? { term: e.term } : {}) }
1042
- else delete b.files[f.path]
1043
- if (entryOf(this.doc, f.path) || local.has(f.path) || this.skipped(f.path) || (this.inPlace && this.nested(f.path))) continue
1044
- // Already on disk as the new head has it (the commit was made from this very work): left alone.
1045
- const k = this.known[f.path]
1046
- if (e ? k && e.mode !== 'conflict' && k.blob === e.blob && k.mode === e.mode : !k) continue
1047
- if (this.write(f.path, e ? await this.headFile(f.path, b.files[f.path], `c:${to}`) : null, { guard: true }) === false) this.scanSoon()
1048
- }
1049
- b.at = to
1050
- // A square with no commit of its own (a rebase only moved its base): a commit's expect_head is none.
1051
- const rec = this.doc.getMap('live').get('head') || {}
1052
- b.head = rec.commit === to && rec.base ? null : to
1053
- this.save()
1054
- }
1055
-
1056
- /** Every disk change in, and the relay holding all of it. */
1057
- async flush () {
1058
- clearTimeout(this.scanTimer)
1059
- await this.run(() => this.scan())
1060
- await this.conn.confirmBranch()
1061
- }
1062
-
1063
- /** The square's uncommitted work, as the relay holds it: [{ path, status }]. */
1064
- status () {
1065
- return overlay(this.doc).map((e) => ({ path: e.path, status: e.op === 'delete' ? 'deleted' : this.block.files[e.path] ? 'modified' : 'added' }))
1066
- }
1067
-
1068
- /** Paths with an open held conflict on this square (held.js, in the room's document): they stay live until it is resolved. */
1069
- heldPaths () {
1070
- const map = this.rules && this.rules.heldMap ? this.rules.heldMap() : null
1071
- return map && this.block ? heldPathsOn(readHeld(map), this.block.square) : []
1072
- }
1073
-
1074
- /**
1075
- * Seals the live document as a commit on the square: the overlay (every writer's work, not only
1076
- * this folder's) is committed through the API with the head it is relative to as `expect_head`,
1077
- * then the relay moves the head and drops what was committed (live-square.js `seal`). A path with
1078
- * an open held conflict (Seam's 07 "Terms held aside") stays live and the rest is committed
1079
- * (`left_held`); with nothing else to commit it is refused (code 'held_conflict', naming them).
1080
- */
1081
- async commit ({ message = '' } = {}) {
1082
- if (!this.client) throw new Error('sign in to Seam first (quilt login, or set SEAM_TOKEN): a commit is made as you')
1083
- await this.flush()
1084
- return this.run(async () => {
1085
- const head = this.head
1086
- // An untracked file this folder never syncs (ignored, or a Quilt built-in) is never committed, even if
1087
- // the live document names it (a square from before 0.3.135's switch took agents' scratch files in).
1088
- let list = overlay(this.doc).filter((e) => !(this.skipped(e.path) && !this.block.files[e.path]))
1089
- if (!list.length) return { nothing: true }
1090
- // A path with an open held conflict never lands until it is resolved; one such file never holds back the rest.
1091
- const held = new Set(this.heldPaths())
1092
- const leftHeld = list.filter((e) => held.has(e.path)).map((e) => e.path)
1093
- list = list.filter((e) => !held.has(e.path))
1094
- if (!list.length) {
1095
- const err = new Error(heldLandingNote(leftHeld, { none: true }))
1096
- err.code = 'held_conflict'
1097
- err.paths = leftHeld
1098
- throw err
1099
- }
1100
- const uploads = list.filter((e) => e.bytes).map((e) => ({ kind: 'blob', id: blobId(e.bytes), bytes: e.bytes }))
1101
- if (uploads.length) await this.client.upload(this.block.quilt, uploads)
1102
- const changes = list.map((e) => e.op === 'delete' ? { path: e.path, op: 'delete' } : { path: e.path, op: 'put', blob: entryId(e), mode: e.mode })
1103
- let r = await this.client.commit(this.block.quilt, this.block.square, { expect_head: this.block.head || null, message, changes })
1104
- if (leftHeld.length) r = { ...r, left_held: leftHeld }
1105
- const sealed = Object.fromEntries(list.map((e) => [e.path, entryId(e)]))
1106
- await this.conn.branchRequest({ op: 'seal', branch: this.block.live, prev: head, head: r.square.head, sealed })
1107
- await waitUntil(() => this.head === r.square.head, 10000, 'the sealed head')
1108
- await this.reproject(r.square.head)
1109
- return r
1110
- })
1111
- }
1112
-
1113
- /**
1114
- * The square's head moved on Seam itself (a rebase, a settled conflict, a merge that kept its
1115
- * conflict in the square): the relay moves the live document onto it, each live file the move
1116
- * changed combined with it (source-live/bring-in.js), and the folder is re-projected onto it.
1117
- * `base`: the square has no commit of its own, and `head` is its new base.
1118
- */
1119
- async moveTo (head, { base = false } = {}) {
1120
- await this.flush()
1121
- return this.run(async () => {
1122
- const was = this.head
1123
- if (!head || head === was) return { moved: false }
1124
- await this.conn.branchRequest({ op: 'live-move', branch: this.block.live, prev: was, head, ...(base ? { base: true } : {}) })
1125
- await waitUntil(() => this.head === head, 10000, 'the moved head')
1126
- await this.reproject(head)
1127
- return { moved: true, head }
1128
- })
1129
- }
1130
-
1131
- /** Merges the square into a line (07), after sealing anything uncommitted (paths with an open held conflict stay live). */
1132
- async merge ({ into = 'main', message } = {}) {
1133
- try { await this.commit({ message: message || 'Work in progress' }) } catch (err) { if (err.code !== 'held_conflict') throw err }
1134
- return this.client.merge(this.block.quilt, into, { square: this.block.square, expect_head: this.block.head, ...(message ? { message } : {}) })
1135
- }
1136
-
1137
- /** Stops the block without saving its record: it never opened (open failed part-way). */
1138
- abandon () {
1139
- this.closed = true
1140
- if (this.stopOpening) this.stopOpening()
1141
- clearTimeout(this.scanTimer)
1142
- clearTimeout(this.saveTimer)
1143
- clearInterval(this.reconcileTimer)
1144
- clearInterval(this.stepTimer)
1145
- for (const t of this.settleTimers || []) clearTimeout(t)
1146
- if (this.watcher) this.watcher.close()
1147
- this.overwritten.close()
1148
- if (this.conn) this.conn.close()
1149
- }
1150
-
1151
- async close () {
1152
- this.closed = true
1153
- clearTimeout(this.scanTimer)
1154
- clearInterval(this.reconcileTimer)
1155
- clearInterval(this.stepTimer)
1156
- for (const t of this.settleTimers || []) clearTimeout(t)
1157
- if (this.watcher) this.watcher.close()
1158
- await this.queue.catch(() => {})
1159
- this.overwritten.close()
1160
- if (this.record && this.block && this.block.at) { try { this.save() } catch {} }
1161
- if (this.conn) this.conn.close()
1162
- }
1163
- }
1164
-
1165
- /** Opens (or reopens) a live block: checkout of the square's head, then the mirror. */
1166
- export const openLiveBlock = (opts) => new LiveBlock(opts).open()