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,583 +0,0 @@
1
- // Quilt's side of Seam (Seam's plans/quilt-source-control/16, "How a session becomes a quilt"): once a
2
- // session is switched to layout 3 (session-layout3.js), each branch's live work is a square's live
3
- // document on the relay (`quilt/<square>`), and a folder follows it through a live block
4
- // (source-live/live-block.js): its files mirror the square, every edit goes into the live document.
5
- //
6
- // SquareFollower is that link for one Session. The session's own folder follows its branch's square
7
- // in place, by itself, as soon as the relay says the session is a layout-3 quilt (`onQuilt`): the
8
- // folder already equals the square's live document (the switch copied the branch document into it
9
- // and checked), so nothing is checked out; the session's branch-document sync and git-mode upstream
10
- // work stop for the folder (Session.enterSquare) and the block takes over. When the relay says the
11
- // session went back (layout 2), or the branch's square changed, the block closes and the old sync
12
- // resumes (Session.leaveSquare). `follow({ dir, client })` also opens a block in a SEPARATE folder
13
- // (`quilt session follow <folder>`). Nothing here runs with Seam off for the app (seam-url.js) or for
14
- // a session the relay does not say is a quilt at layout 3, so GitHub-backed sessions never reach it.
15
- //
16
- // In a quilt, agents see no git and no GitHub at all: it is all Seam. So while the folder follows its
17
- // square, its .git (a folder, or a worktree's pointer file) is set aside in .quilt/git-before-seam with
18
- // one rename, and git there answers "not a git repository"; going back to layout 2 puts it back before
19
- // git-mode sync resumes, and a restart while following keeps it aside. It is never deleted.
20
- import fs from 'node:fs'
21
- import path from 'node:path'
22
- import * as Y from 'yjs'
23
- import { FEATURES } from './protocol.js'
24
- import { openLiveBlock } from './source-live/live-block.js'
25
- import { appSeamUrl } from './seam-url.js'
26
- import { lastWriters, liveMaps } from './source-live/live-square.js'
27
- import { broughtOf } from './source-live/bring-in.js'
28
- import { Lander, landOn } from './source-live/land.js'
29
- import { getSettings } from './settings.js'
30
- import { catchUpWords } from './ui/seam-model.js'
31
- import { QUILT_MOVE_TIMEOUT_MS } from './connection.js'
32
- import { squareShort } from '@heyquilt/seam/lib/quilts/errors.js'
33
-
34
- const LAYOUT_QUILT = 3
35
- const PREFIX = 'quilt/'
36
- // A folder whose block could not open (the relay or Seam did not answer) tries again this often, its sync still held.
37
- const RETRY_MS = 30 * 1000
38
- // The files of the square's uncommitted work that status lists (the count is all of them).
39
- const WORK_LISTED = 50
40
- // How often a folder asks whether main moved past its square's base (catchUp), besides when the relay says something of the quilt.
41
- export const CATCH_UP_MS = Number(process.env.QUILT_CATCH_UP_MS) || 60 * 1000
42
-
43
- /** The square the folder on `branch` follows: `{ square, key }`, or null while the session is not a layout-3 quilt. */
44
- export function squareFor (quilt, branch) {
45
- if (!quilt || quilt.layout !== LAYOUT_QUILT || !branch) return null
46
- const key = (quilt.live || {})[branch]
47
- if (typeof key !== 'string' || !key.startsWith(PREFIX) || key.length === PREFIX.length) return null
48
- return { square: key.slice(PREFIX.length), key }
49
- }
50
-
51
- export const GIT_ASIDE = path.join('.quilt', 'git-before-seam')
52
-
53
- /** The folder's .git set aside while it follows its square: { branch, at, kind } (from its note), or null. */
54
- export function gitAsideOf (root) {
55
- const aside = path.join(root, GIT_ASIDE)
56
- try { fs.lstatSync(aside) } catch { return null }
57
- try { return JSON.parse(fs.readFileSync(`${aside}.json`, 'utf8')) } catch { return { branch: null } }
58
- }
59
-
60
- // Written into a worktree's admin folder in its repository (git worktree lock) while its .git is aside.
61
- const LOCK_REASON = 'Quilt: this worktree follows a Seam square, with its .git set aside in .quilt/git-before-seam; Quilt unlocks it when git comes back.\n'
62
-
63
- /** Where a worktree's .git file points (its repository's .git/worktrees/<name>), or null. */
64
- function worktreeAdmin (gitFile) {
65
- try {
66
- const m = /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(gitFile, 'utf8'))
67
- return m ? path.resolve(path.dirname(gitFile), m[1].trim()) : null
68
- } catch { return null }
69
- }
70
-
71
- /** The other worktrees of the repository whose .git folder is `gitFolder` that are still there: their folders. */
72
- export function otherWorktrees (gitFolder) {
73
- let names
74
- try { names = fs.readdirSync(path.join(gitFolder, 'worktrees')) } catch { return [] }
75
- const out = []
76
- for (const n of names.sort()) {
77
- try {
78
- const dot = fs.readFileSync(path.join(gitFolder, 'worktrees', n, 'gitdir'), 'utf8').trim()
79
- if (dot && fs.existsSync(dot)) out.push(path.dirname(dot))
80
- } catch {}
81
- }
82
- return out
83
- }
84
-
85
- const real = (p) => { try { return fs.realpathSync(p) } catch { return path.resolve(p) } }
86
-
87
- /**
88
- * The folder's own linked worktrees (`git worktree add`, in the folder or anywhere else): each one's
89
- * .git pointer file names `<.git>/worktrees/<name>`, so moving the .git would leave them answering
90
- * "not a git repository". [{ file, was, name }] for each pointer that names this .git.
91
- */
92
- function linkedWorktrees (gitDir) {
93
- let names = []
94
- try { names = fs.readdirSync(path.join(gitDir, 'worktrees')) } catch { return [] }
95
- const out = []
96
- for (const name of names) {
97
- const admin = path.join(gitDir, 'worktrees', name)
98
- try {
99
- let file = fs.readFileSync(path.join(admin, 'gitdir'), 'utf8').trim()
100
- if (!path.isAbsolute(file)) file = path.resolve(admin, file)
101
- // A worktree that follows a square too has its pointer set aside in its own .quilt.
102
- for (const at of pointerPlaces(file)) {
103
- let was
104
- try { was = fs.readFileSync(at, 'utf8') } catch { continue }
105
- const m = /^gitdir:\s*(.+?)\s*$/m.exec(was)
106
- if (m && real(path.resolve(path.dirname(file), m[1])) === real(admin)) out.push({ file, was, name })
107
- break
108
- }
109
- } catch {}
110
- }
111
- return out
112
- }
113
-
114
- /** Where a worktree's .git pointer file is: at its .git, or set aside (it follows a square too). */
115
- const pointerPlaces = (file) => [file, path.join(path.dirname(file), GIT_ASIDE)]
116
-
117
- /**
118
- * Rewrites a worktree's .git pointer file in place, wherever it is now (pointerPlaces), when `was(text)`
119
- * says it is the one expected: through an open handle, never by making the file anew, so a worktree
120
- * that sets its own .git aside meanwhile (both follow squares, at once) finds it in its .quilt and
121
- * not a new .git in its folder. Whether it wrote.
122
- */
123
- function rewritePointer (file, text, was) {
124
- for (const at of pointerPlaces(file)) {
125
- let fd
126
- try { if (!fs.statSync(at).isFile()) continue; fd = fs.openSync(at, 'r+') } catch { continue }
127
- try {
128
- if (!was(fs.readFileSync(fd, 'utf8'))) return false
129
- fs.ftruncateSync(fd, 0)
130
- fs.writeSync(fd, text, 0)
131
- return true
132
- } catch { return false } finally { fs.closeSync(fd) }
133
- }
134
- return false
135
- }
136
-
137
- /**
138
- * Sets the folder's .git aside (one rename into .quilt): { moved, already?, both?, locked?, worktrees? }.
139
- * A .git kept aside from before (a restart while following) stays where it is; a new .git made
140
- * meanwhile is left alone (both: true), never moved over the one aside. A worktree's .git file
141
- * points into its repository: that worktree is locked there meanwhile (locked: true), so git in the
142
- * repository never prunes it as gone. A repository's other worktrees share its .git folder: their
143
- * .git files are pointed at it where it is now (and back as they were with it, putGitBack), so
144
- * they keep working; `worktrees` names their folders.
145
- */
146
- export function setGitAside (root, { branch = null } = {}) {
147
- const git = path.join(root, '.git')
148
- const aside = path.join(root, GIT_ASIDE)
149
- let st = null
150
- try { st = fs.lstatSync(git) } catch {}
151
- if (gitAsideOf(root)) return { moved: false, already: true, ...(st ? { both: true } : {}) }
152
- if (!st) return { moved: false }
153
- const kind = st.isDirectory() ? 'folder' : 'file'
154
- const admin = kind === 'file' ? worktreeAdmin(git) : null
155
- let locked = null
156
- if (admin && fs.existsSync(admin) && !fs.existsSync(path.join(admin, 'locked'))) {
157
- fs.writeFileSync(path.join(admin, 'locked'), LOCK_REASON)
158
- locked = admin
159
- }
160
- const worktrees = kind === 'folder' ? otherWorktrees(git) : []
161
- const linked = kind === 'folder' ? linkedWorktrees(git) : []
162
- fs.mkdirSync(path.dirname(aside), { recursive: true })
163
- fs.writeFileSync(`${aside}.json`, JSON.stringify({ branch, at: new Date().toISOString(), kind, ...(locked ? { locked } : {}), ...(linked.length ? { worktrees: linked.map(({ file, was }) => ({ file, was })) } : {}) }))
164
- try { fs.renameSync(git, aside) } catch (err) {
165
- if (locked) fs.rmSync(path.join(locked, 'locked'), { force: true })
166
- fs.rmSync(`${aside}.json`, { force: true })
167
- throw err
168
- }
169
- for (const w of linked) rewritePointer(w.file, `gitdir: ${path.join(real(aside), 'worktrees', w.name)}\n`, (now) => now === w.was)
170
- return { moved: true, ...(locked ? { locked: true } : {}), ...(worktrees.length ? { worktrees } : {}) }
171
- }
172
-
173
- /** Puts the .git set aside back (one rename): true when it did; false with nothing aside, or with a new .git in the way (both kept). */
174
- export function putGitBack (root) {
175
- const git = path.join(root, '.git')
176
- const aside = path.join(root, GIT_ASIDE)
177
- const note = gitAsideOf(root)
178
- if (!note) return false
179
- try { fs.lstatSync(git); return false } catch {}
180
- fs.renameSync(aside, git)
181
- // Its linked worktrees' pointers, as they were (one changed since is left as it is).
182
- for (const w of note.worktrees || []) rewritePointer(w.file, w.was, (now) => now.includes(GIT_ASIDE))
183
- fs.rmSync(`${aside}.json`, { force: true })
184
- // The lock this set, and only that one (someone may have locked the worktree since, for their own reason):
185
- // where it was set, or where its repository's .git is now (set aside meanwhile, its pointer says).
186
- if (note.locked) {
187
- for (const admin of new Set([note.locked, worktreeAdmin(git)].filter(Boolean))) {
188
- const lock = path.join(admin, 'locked')
189
- try { if (fs.readFileSync(lock, 'utf8') === LOCK_REASON) fs.rmSync(lock, { force: true }) } catch {}
190
- }
191
- }
192
- return true
193
- }
194
-
195
- // The branch document's maps keyed by path (Session.bindBranchDoc): what a file's change touches.
196
- const PATH_MAPS = ['files', 'blobs', 'gone', 'modes']
197
-
198
- /**
199
- * The paths of branch document `doc` with changes the relay does not hold (its state vector `sv`,
200
- * and `deleted`, an update of its deletions, both encoded): at layout 3, edits the read-only
201
- * document refused (they reached it after the switch) or never got (the app was offline). A change
202
- * that only deleted text counts too: Yjs keeps deletions apart from the state vector, so the relay's
203
- * own are compared.
204
- */
205
- export function unsentPaths (doc, sv, deleted) {
206
- const out = new Set()
207
- const held = Y.decodeStateVector(sv)
208
- const gone = Y.decodeUpdate(deleted).ds.clients
209
- const past = (item) => item.id.clock + item.length > (held.get(item.id.client) || 0)
210
- const goneThere = (item) => (gone.get(item.id.client) || []).some((d) => d.clock <= item.id.clock && item.id.clock + item.length <= d.clock + d.len)
211
- const touched = (item) => past(item) || (item.deleted && !goneThere(item))
212
- for (const name of PATH_MAPS) {
213
- for (const [p, item] of doc.getMap(name)._map) {
214
- if (touched(item)) { out.add(p); continue }
215
- const type = item.content && item.content.type
216
- if (!(type instanceof Y.Text)) continue
217
- for (let it = type._start; it; it = it.right) if (touched(it)) { out.add(p); break }
218
- }
219
- }
220
- return out
221
- }
222
-
223
- const withQuilts =(f) => (String(f || FEATURES).split(',').includes('quilts') ? String(f || FEATURES) : `${f || FEATURES},quilts`)
224
-
225
- /** The one line the app and quilt_status show for a folder that follows its square. */
226
- export function squareLine ({ square, quilt, problem = '', opening = false }) {
227
- const short = squareShort(square || '')
228
- const name = (quilt && (quilt.slug || quilt.id)) || 'the quilt'
229
- if (problem) return `This folder's work belongs in square ${short} of ${name}, but it can't follow it yet (${problem}); Quilt tries again by itself, and nothing here is sent anywhere meanwhile.`
230
- if (opening) return `This folder is starting to follow square ${short} of ${name}.`
231
- return `This folder's work is live in square ${short} of ${name}: every edit reaches everyone on it. Commit it with quilt commit "<message>".`
232
- }
233
-
234
- // How long a read of the quilt through the relay may take: the relay reads Seam with the room's one
235
- // read token and retries a busy Seam (429, 503) itself, so a folder waits for it rather than giving up
236
- // after a branch request's 10 s (the second rehearsal: an app restarted with two others failed its
237
- // first try that way, and followed 30 s later).
238
- export const QUILT_READ_TIMEOUT_MS = 60 * 1000
239
-
240
- /**
241
- * Reads of the room's quilt through the relay (server.js quiltBlockRead), with the room's read
242
- * token: the calls a block reads with, so a member needs no Seam sign-in to follow its square.
243
- */
244
- export function relayReader (conn) {
245
- const read = async (fields) => {
246
- if (!conn || !conn.connected) throw new Error('not connected to the relay')
247
- try {
248
- return await conn.branchRequest({ op: 'quilt-block', ...fields }, { timeoutMs: QUILT_READ_TIMEOUT_MS })
249
- } catch (err) {
250
- throw new Error(`reading the square's ${fields.call} through the relay: ${err.message}`)
251
- }
252
- }
253
- return {
254
- square: async (q, s) => (await read({ call: 'square', square: s })).square,
255
- tree: async (q, rev, paths) => (await read({ call: 'tree', rev, ...(paths ? { paths } : {}) })).tree,
256
- blobs: async (q, ids) => {
257
- const out = {}
258
- for (let i = 0; i < ids.length; i += 200) Object.assign(out, (await read({ call: 'blobs', ids: ids.slice(i, i + 200) })).blobs)
259
- return { blobs: out }
260
- },
261
- diff: async (q, o = {}) => (await read({ call: 'diff', from: o.from, to: o.to, ...(o.paths ? { paths: o.paths } : {}) })).diff,
262
- cat: async (q, rev, file, o = {}) => (await read({ call: 'cat', rev, file, format: o.format })).cat
263
- }
264
- }
265
-
266
- export class SquareFollower {
267
- /** @param {object} session a Session (server, room, secret, name, identity, passes, tool, kind, features, quilt, branchKey(), log) */
268
- constructor (session, { open = openLiveBlock, retryMs = RETRY_MS, catchUpMs = CATCH_UP_MS } = {}) {
269
- this.session = session
270
- this.open = open
271
- this.retryMs = retryMs
272
- this.catchUpMs = catchUpMs
273
- this.following = null // { square, dir, block }: a separate folder
274
- this.here = null // { square, quilt, block, opening, problem }: the session's own folder, in place
275
- this.turn = Promise.resolve() // one change of square at a time
276
- }
277
-
278
- relayOpts () {
279
- const s = this.session
280
- // A person's session has no identity of its own (it signs in with passes): its connection loads this computer's.
281
- const identity = s.identity || (s.conn && s.conn.identity) || null
282
- return { server: s.server, room: s.room, secret: s.secret, name: s.name, identity, passes: s.passes, tool: s.tool, kind: s.kind, features: withQuilts(s.features) }
283
- }
284
-
285
- /** Opens the block at `dir` (its own folder, signed in to Seam with `client`) on the session's branch's square. */
286
- async follow ({ dir, client } = {}) {
287
- if (!appSeamUrl()) throw new Error('Seam is turned off for this app (QUILT_SOURCE_URL=off).')
288
- if (!dir) throw new Error('Give the folder the square\'s files go to.')
289
- const s = this.session
290
- // Its own folder: inside the session's folder, the block's files would sync a second time.
291
- if (s.root) {
292
- const rel = path.relative(path.resolve(s.root), path.resolve(dir))
293
- if (!rel || (!rel.startsWith('..') && !path.isAbsolute(rel))) throw new Error('Give a folder outside this session\'s folder: the square\'s files are synced there by Seam, not by this folder.')
294
- }
295
- if (!s.quilt) throw new Error('This session is not a quilt.')
296
- const branch = s.branchKey()
297
- const at = squareFor(s.quilt, branch)
298
- if (!at) throw new Error(`The session is a quilt, but ${branch} has no live square yet (the owner switches it with quilt session migrate --switch).`)
299
- if (this.following && this.following.square === at.square && this.following.dir === dir) return { square: at.square, dir }
300
- await this.closeSeparate()
301
- const block = await this.open({ dir, client, quilt: s.quilt.id, square: at.square, api: appSeamUrl(), relay: this.relayOpts(), rules: s.liveRules ? s.liveRules() : null })
302
- this.following = { square: at.square, dir, block }
303
- if (s.log) s.log(`🧵 ${dir} follows the square ${at.square} of ${s.quilt.slug || s.quilt.id}: edits there are live for everyone on it.`)
304
- return { square: at.square, dir }
305
- }
306
-
307
- /** The relay's `quilt` message: the folder follows its branch's square in place, or lets go of one the branch no longer has. */
308
- onQuilt (quilt) {
309
- const s = this.session
310
- // Held before the first await: nothing of the folder reaches the read-only branch document while the block opens.
311
- const at = this.inPlaceOn() ? squareFor(quilt, s.squareBranchKey ? s.squareBranchKey() : s.branchKey()) : null
312
- const entered = at && s.enterSquare && !(this.here && this.here.square === at.square) ? at.square : null
313
- if (entered) s.enterSquare(at, quilt)
314
- const next = this.turn.then(() => this.settle(quilt, entered)).catch((err) => { if (s.log) s.log(`🧵 ${err.message}`) })
315
- this.turn = next
316
- // A merge onto main moves a branch on (quiltNext), and the relay says so: the other squares may be behind now.
317
- next.then(() => this.catchUpSoon())
318
- return next
319
- }
320
-
321
- /** Seam on for the app, a folder of the session's own, and a session that can hold its sync (a Session). */
322
- inPlaceOn () { return !!(appSeamUrl() && this.session.root && this.session.enterSquare) }
323
-
324
- /** `entered`: the square onQuilt already held the session's sync for. */
325
- async settle (quilt, entered = null) {
326
- const s = this.session
327
- const at = this.inPlaceOn() ? squareFor(quilt, s.squareBranchKey ? s.squareBranchKey() : s.branchKey()) : null
328
- // The separate folder lets go of a square the branch no longer has (switched back, moved).
329
- const sep = this.following && squareFor(quilt, s.branchKey())
330
- if (this.following && !(sep && sep.square === this.following.square)) {
331
- const was = this.following.square
332
- await this.closeSeparate()
333
- if (s.log) s.log(`🧵 stopped following the square ${was}: ${sep ? `the branch is on ${sep.square} now` : 'the session is back on its branch documents'}.`)
334
- }
335
- if (this.here && (!at || at.square !== this.here.square)) {
336
- const was = this.here.square
337
- // Moved on (a merge): what the folder has not sent yet reaches the old square first, and the relay takes it on to the new one.
338
- if (at && this.here.block && this.here.block.flush) await this.here.block.flush().catch(() => {})
339
- const writers = this.writersHere()
340
- await this.closeHere()
341
- if (!at) {
342
- if (s.leaveSquare) await s.leaveSquare({ writers })
343
- if (s.log) s.log(`🧵 this folder stopped following square ${squareShort(was)}: the session is back on its branches, and the folder syncs with its branch as before.`)
344
- } else if (s.log) s.log(`🧵 this folder left square ${squareShort(was)}: its branch is on ${squareShort(at.square)} now.`)
345
- }
346
- if (!at || (this.here && this.here.square === at.square)) return
347
- // The branch may only be known now (a folder without git learns the room's default branch after
348
- // the relay's quilt message): the session's own sync holds before the block opens, every time, or
349
- // it writes the read-only branch document's older copy over the square's files and the block takes
350
- // that for this member's edits (2026-11-01: an agent's new folder put 166 stale files into main's square).
351
- if (s.enterSquare && entered !== at.square) s.enterSquare(at, quilt)
352
- await this.openHere(at, quilt)
353
- }
354
-
355
- /** The session's own folder becomes the square's block (live-block.js, in place). */
356
- async openHere (at, quilt, { fresh = false } = {}) {
357
- const s = this.session
358
- const here = { square: at.square, quilt, block: null, problem: '', opening: true }
359
- this.here = here
360
- if (s.scheduleStatusWrite) s.scheduleStatusWrite()
361
- // A folder that joined the quilt empty (Session.joinedEmpty): what it has is the session's sync from
362
- // the read-only branch document, an older copy of the square's files. Its first look takes nothing
363
- // of that for its edits (no refused writes, boxes or branch work of its own); only a file changed
364
- // on disk since the session wrote it is the member's.
365
- const empty = !fresh && !!s.joinedEmpty
366
- try {
367
- // Edits the read-only branch document refused (they reached it after the switch) are the folder's too.
368
- const unsent = !fresh && !empty && s.unsentPaths ? await s.unsentPaths().catch(() => null) : null
369
- const block = await this.open({
370
- dir: s.root,
371
- // A square opened for this folder's branch (Session.openSquareHere: the branch had none) takes the folder as it is: its files are the work.
372
- inPlace: fresh ? { edited: () => false, fresh: true } : empty ? { edited: (p) => !!(s.editedSinceSync && s.editedSinceSync(p)), fresh: true } : s.folderWins === at.square ? { edited: () => true } : { edited: (p) => s.editedSinceSync(p) || !!(unsent && unsent.has(p)) || !!(s.boxedHere && s.boxedHere(p)), boxed: (p) => !!(s.boxedHere && s.boxedHere(p)), heldBack: (p) => !!(s.heldBackHere && s.heldBackHere(p)), synced: (p) => !!(s.syncedHere && s.syncedHere(p)), base: s.syncedText ? (p) => s.syncedText(p) : null, own: () => (s.branchOwnPaths ? s.branchOwnPaths() : null), atTip: ((quilt && quilt.atTip) || []).includes(s.squareBranchKey ? s.squareBranchKey() : s.branchKey()) },
373
- skip: (p) => !s.syncable(p),
374
- skipDir: s.ignoredDir ? (p) => s.ignoredDir(p) : null,
375
- record: path.join(s.stateDir || path.join(s.root, '.quilt'), 'block.json'),
376
- reader: s.squareReader ? s.squareReader() : relayReader(s.conn),
377
- client: s.seamWriteClient ? await s.seamWriteClient() : null,
378
- quilt: quilt.id,
379
- square: at.square,
380
- api: appSeamUrl(),
381
- relay: this.relayOpts(),
382
- log: (m) => { if (s.log) s.log(`🧵 ${m}`) },
383
- started: (b) => { here.starting = b },
384
- // Who changed what goes on as on the branch: this folder's edits on record as its member's.
385
- onEdits: s.squareEdits ? (list, doc, held) => { if (this.here === here) s.squareEdits(list, doc, held) } : null,
386
- // The live-write engine (live-merge.js): each edit merged against what disk last had, clashes held in the room.
387
- rules: s.liveRules ? s.liveRules() : null,
388
- // A file the square wrote to disk: the app redraws its Files list and an open file (as for a change its watcher heard).
389
- onWrite: (p) => { if (this.here === here && s.emit) s.emit('file-changed', { path: p }) }
390
- })
391
- if (this.here !== here) { await block.close().catch(() => {}); return }
392
- if (empty) s.joinedEmpty = false
393
- here.block = block
394
- here.opening = false
395
- if (s.followSquareDoc) s.followSquareDoc(block.doc)
396
- // What the square holds not committed yet (status `work`) changes with every edit on it, anyone's: the app hears.
397
- if (block.doc && block.doc.on && s.scheduleStatusWrite) block.doc.on('update', () => { if (this.here === here) s.scheduleStatusWrite() })
398
- if (s.log) s.log(`🧵 ${squareLine({ square: at.square, quilt })}`)
399
- // Another member's app brought main in, or a commit moved the head: how far behind, and what conflicts, asked again.
400
- if (block.doc && block.doc.getMap) block.doc.getMap('live').observe(() => { if (this.here === here) this.catchUpSoon() })
401
- here.catchUpTimer = setInterval(() => this.catchUp().catch(() => {}), this.catchUpMs)
402
- here.catchUpTimer.unref?.()
403
- here.lander = this.landerFor(here, block, at, quilt)
404
- this.catchUp().catch(() => {})
405
- } catch (err) {
406
- if (this.here !== here) return
407
- here.opening = false
408
- here.problem = String(err.message || err).slice(0, 300)
409
- if (s.log) s.log(`🧵 ${squareLine({ square: at.square, quilt, problem: here.problem })}`)
410
- clearTimeout(this.retryTimer)
411
- this.retryTimer = setTimeout(() => {
412
- if (this.here !== here || s.stopped) return
413
- this.here = null
414
- this.onQuilt(s.quilt)
415
- }, this.retryMs)
416
- if (this.retryTimer.unref) this.retryTimer.unref()
417
- }
418
- if (s.scheduleStatusWrite) s.scheduleStatusWrite()
419
- }
420
-
421
- /** git moved the folder to another branch: it follows that branch's square, as the square has it (git's checkout is not an edit). */
422
- async branchMoved (quilt) {
423
- const s = this.session
424
- const at = squareFor(quilt, s.squareBranchKey())
425
- if (at && this.here && this.here.square === at.square) return
426
- const was = this.here && this.here.square
427
- const writers = this.writersHere()
428
- await this.closeHere()
429
- if (!at) {
430
- if (s.leaveSquare) await s.leaveSquare({ writers })
431
- return
432
- }
433
- if (s.log && was) s.log(`🧵 this folder left square ${squareShort(was)} for ${s.squareBranchKey()}'s, ${squareShort(at.square)}.`)
434
- s.enterSquare(at, quilt)
435
- await this.openHere(at, quilt, { fresh: true })
436
- }
437
-
438
- /**
439
- * The folder's held work lands by itself (source-live/land.js): a person's folder only (an agent's
440
- * own square has its AI; a cloud AI's folder works for its person, who lands), with Seam on and
441
- * landing not turned off. Every edit on the square (anyone's) starts its quiet again.
442
- */
443
- landerFor (here, block, at, quilt) {
444
- const s = this.session
445
- if (!this.landing || s.kind === 'agent' || s.aiOf || !s.seamClientNow || !s.conn) return null
446
- const branch = s.squareBranchKey ? s.squareBranchKey() : s.branchKey()
447
- const lander = new Lander({
448
- quilt: quilt.id,
449
- square: at.square,
450
- line: 'main',
451
- block,
452
- ...(this.landOpts || {}),
453
- client: async () => { const c = await s.seamClientNow(); if (c) block.client = c; return c },
454
- next: async () => { const { token } = await s.seamMember().client(quilt.id, [at.square]); return s.conn.branchRequest({ op: 'quilt-next', token, branch }, { timeoutMs: QUILT_MOVE_TIMEOUT_MS }) },
455
- catchUp: () => this.catchUp(),
456
- hasAi: () => !!(s.hasCloudAi && s.hasCloudAi()),
457
- person: s.name,
458
- board: { list: () => s.taskList(), add: (f) => s.addTask(f), comment: (id, text) => s.commentTask({ id, text }), move: (id, column) => s.updateTask({ id, column }) },
459
- notify: (text) => { if (s.noteToSelf) s.noteToSelf(text) },
460
- log: (m) => { if (this.here === here && s.log) s.log(`🧵 ${m}`) }
461
- })
462
- if (block.doc && block.doc.getMap) {
463
- const m = liveMaps(block.doc)
464
- const edited = () => { if (this.here === here) lander.edited() }
465
- for (const k of ['files', 'blobs', 'gone']) m[k].observeDeep(edited)
466
- }
467
- lander.soon(lander.quietMs + 50)
468
- return lander
469
- }
470
-
471
- /** Whether held work lands by itself here (land.js landOn), read each time a block opens. */
472
- get landing () {
473
- let settings = {}
474
- try { settings = getSettings() } catch {}
475
- return landOn({ settings })
476
- }
477
-
478
- /** catchUp in a moment: the relay says something of the quilt in bursts, and one ask answers them all. */
479
- catchUpSoon () {
480
- if (!this.here || !this.here.block || this.catchUpTimer) return
481
- this.catchUpTimer = setTimeout(() => { this.catchUpTimer = null; this.catchUp().catch(() => {}) }, 1000)
482
- this.catchUpTimer.unref?.()
483
- }
484
-
485
- /**
486
- * Bringing main in (server.js quiltCatchUp, source-live/bring-in.js): asks the relay, as this member,
487
- * whether main moved past the square's base; when it did and it is this member's turn (its holder
488
- * first, else a writer), the relay brings main's new patches into the square, and this folder, like
489
- * every folder on it, gets the new files. The answer says how far behind the square is, for status.
490
- */
491
- async catchUp () {
492
- const s = this.session
493
- const h = this.here
494
- if (!h || !h.block || h.catching || s.stopped || !s.conn || !s.conn.connected || !s.seamMember || !appSeamUrl()) return null
495
- h.catching = true
496
- try {
497
- const { token } = await s.seamMember().client(h.quilt.id, [h.square])
498
- const branch = s.squareBranchKey ? s.squareBranchKey() : s.branchKey()
499
- const r = await s.conn.branchRequest({ op: 'quilt-catch-up', token, branch }, { timeoutMs: QUILT_MOVE_TIMEOUT_MS })
500
- if (this.here !== h) return null
501
- h.behind = r.behind || 0
502
- h.conflicted = r.conflicted || 0
503
- // Main waits for a folder on the square too old to follow its base moving (server.js outdatedOn): whose.
504
- h.outdated = Array.isArray(r.outdated) ? r.outdated.map(String).slice(0, 10) : []
505
- h.catchUpProblem = ''
506
- if (r.brought && s.log) s.log(`🧵 ${catchUpWords({ brought: { ...r.brought, at: Date.now() }, lands: !!h.lander }).join(' ')}`)
507
- // The desktop app run from this folder restarts on its own once main's new code is in it (desktop/main.js).
508
- if (r.brought) process.emit('quilt:brought-in', { root: s.root })
509
- if (s.scheduleStatusWrite) s.scheduleStatusWrite()
510
- // A look at landing the held work too (a square with commits and nothing typed lands this way).
511
- if (h.lander && !h.lander.busy) setTimeout(() => { if (this.here === h && h.lander) h.lander.tick().then(() => { if (s.scheduleStatusWrite) s.scheduleStatusWrite() }).catch(() => {}) }, 0).unref?.()
512
- return r
513
- } catch (err) {
514
- if (this.here === h && h.catchUpProblem !== err.message) {
515
- h.catchUpProblem = err.message
516
- if (s.log) s.log(`🧵 couldn't check whether main moved past square ${squareShort(h.square)} (${err.message}); Quilt asks again in a minute.`)
517
- }
518
- return null
519
- } finally { h.catching = false }
520
- }
521
-
522
- /** Where the session's own folder stands, for status: { square, quilt, line, problem?, opening? }, or null. */
523
- status () {
524
- const h = this.here
525
- if (!h) return null
526
- const quilt = { id: h.quilt.id, slug: h.quilt.slug || '' }
527
- const problem = h.problem || (h.block && (h.block.problem || h.block.outOfStep)) || ''
528
- // `work`: the square's live work not committed yet (everyone's on it, as the relay holds it), for the app's count and list.
529
- let work = null
530
- try { if (h.block && h.block.status) { const all = h.block.status(); work = { count: all.length, files: all.slice(0, WORK_LISTED) } } } catch {}
531
- // Main brought in (by this app or another member's): the live document keeps the last time, for everyone.
532
- const b = h.block ? broughtOf(h.block.doc) : null
533
- const brought = b ? { at: b.at, by: b.by || '', patches: b.patches || 0, combined: b.combined || [], conflicts: b.conflicts || [], ...(Array.isArray(b.stale) && b.stale.length ? { stale: b.stale } : {}) } : null
534
- const catching = { ...(h.behind ? { behind: h.behind } : {}), ...(h.behind && h.outdated && h.outdated.length ? { outdated: h.outdated } : {}), ...(h.conflicted !== undefined ? { conflicted: h.conflicted } : {}), ...(brought ? { brought } : {}) }
535
- // What landing the held work did last (land.js): landed, kept aside, asked the person's AI, waiting.
536
- if (h.lander) catching.lands = true
537
- if (h.lander && h.lander.state) catching.landing = h.lander.state
538
- const words = h.block ? catchUpWords(catching).join(' ') : ''
539
- return { square: h.square, short: squareShort(h.square).slice(3), quilt, ...(h.opening ? { opening: true } : {}), ...(problem ? { problem } : {}), ...(work ? { work } : {}), ...catching, line: squareLine({ square: h.square, quilt, problem: h.problem, opening: h.opening }) + (h.block && h.block.problem ? ` ${h.block.problem}.` : '') + (h.block && h.block.outOfStep ? ` ${h.block.outOfStep}.` : '') + (words ? ` ${words}` : '') }
540
- }
541
-
542
- /** Who last wrote each path of the square's live work (live-square.js lastWriters), or null without an open block. */
543
- writersHere () {
544
- const b = this.here && this.here.block
545
- try { return b && b.doc ? lastWriters(b.doc) : null } catch { return null }
546
- }
547
-
548
- /** Commits the square's live work from the session's own folder (live-block.js commit). */
549
- async commit ({ message = '' } = {}) {
550
- const h = this.here
551
- if (!h) throw new Error('This folder does not follow a square: the session is not a quilt at layout 3 (or Seam is off for this app).')
552
- if (!h.block) throw new Error(h.problem ? `This folder can't follow its square yet: ${h.problem}` : 'This folder is still starting to follow its square; try again in a moment.')
553
- if (!message || !String(message).trim()) throw new Error('Say what the commit is (a message).')
554
- return h.block.commit({ message: String(message).slice(0, 2000) })
555
- }
556
-
557
- async closeHere () {
558
- const h = this.here
559
- this.here = null
560
- clearTimeout(this.retryTimer)
561
- clearTimeout(this.catchUpTimer)
562
- this.catchUpTimer = null
563
- if (h) clearInterval(h.catchUpTimer)
564
- if (h && h.lander) h.lander.stop()
565
- if (this.session.unfollowSquareDoc) this.session.unfollowSquareDoc()
566
- if (h && h.block && h.block.close) await h.block.close().catch(() => {})
567
- // Still opening (waiting for the relay, say): stopped where it is, or its connection outlives the folder's square.
568
- else if (h && h.starting && h.starting.abandon) h.starting.abandon()
569
- }
570
-
571
- async closeSeparate () {
572
- const f = this.following
573
- this.following = null
574
- if (f && f.block && f.block.close) await f.block.close().catch(() => {})
575
- }
576
-
577
- async close () {
578
- await this.closeSeparate()
579
- await this.closeHere()
580
- }
581
-
582
- stop () { return this.close() }
583
- }