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
package/src/session.js CHANGED
@@ -2,11 +2,7 @@
2
2
  // back. Any tool that edits files on disk (Claude Code, Cursor, Codex, vim...)
3
3
  // participates automatically; concurrent edits are merged character by
4
4
  // character by the CRDT.
5
- import { describeQuiltPlan } from './session-quilt.js'
6
- import { SquareFollower, relayReader, gitAsideOf, setGitAside, putGitBack, unsentPaths, GIT_ASIDE, squareFor } from './session-follow.js'
7
- import { appSeamUrl } from './seam-url.js'
8
- import { pushRefusal } from './session-seam.js'
9
- import { quiltClient } from '@heyquilt/seam/lib/quilts/client.js'
5
+ import { gitAsideOf, putGitBack, GIT_ASIDE } from './git-aside.js'
10
6
  import fs from 'node:fs'
11
7
  import path from 'node:path'
12
8
  import crypto from 'node:crypto'
@@ -15,7 +11,7 @@ import { execFile, execFileSync } from 'node:child_process'
15
11
  import { EventEmitter } from 'node:events'
16
12
  import * as Y from 'yjs'
17
13
  import { watch } from 'chokidar'
18
- import { Connection, PUSH_REQUEST_TIMEOUT_MS, QUILT_MOVE_TIMEOUT_MS } from './connection.js'
14
+ import { Connection, PUSH_REQUEST_TIMEOUT_MS } from './connection.js'
19
15
  import { loadIdentity } from './identity.js'
20
16
  import { writePrivateJson } from './private-file.js'
21
17
  import { MAX_SHARED_FILE_BYTES, FEATURES } from './protocol.js'
@@ -25,16 +21,12 @@ import {
25
21
  toPosix, MAX_TEXT_BYTES, MAX_BINARY_BYTES, LARGE_FILE_BYTES, MAX_STORED_BINARY_BYTES, CHAT_FILES, closeWatcher
26
22
  } from './fsutil.js'
27
23
  import { wrapForRelay, relayKeyId, deriveWrapKey, newFileKey, wrapKey, unwrapKey, encryptBlob, decryptBlob, blobId } from './largefiles.js'
28
- import { applyTextDiff } from './textdiff.js'
24
+ import { applyTextDiff, diffLines } from './textdiff.js'
29
25
  import { migrateDir } from './legacy.js'
30
26
  import { withComments, addComment as putComment } from './task-comments.js'
31
27
  import { readTasks, addTask as putTask, updateTask as patchTask, deleteTask as dropTask, planAutoTask, nextTask, pickupMode, columnName } from './tasks.js'
32
28
  import { getSettings } from './settings.js'
33
- import { HistoryLog, queryHistory, parseSince, currentTask, blameChange, lineDiff, legacyTail } from './history.js'
34
- import { linkedHistory, mergeLinked } from './quilt-history.js'
35
- import { readAccount } from './account.js'
36
- import { seamAccess, sessionCredential, isAgentKey } from './seam-access.js'
37
- import { startAsQuilt } from './quilt-default.js'
29
+ import { HistoryLog, queryHistory, parseSince, currentTask, blameChange, lineDiff } from './history.js'
38
30
  import { historyMarks, awayChanges, mergeCatchUp, emptyCatchUp } from './catchup.js'
39
31
  import { Inbox, mentionsMe, describeEvent } from './inbox.js'
40
32
  import { projectRules, renderRules, gatherPlan, planKey } from './project-rules.js'
@@ -49,22 +41,22 @@ import { MentionRunner, parseOnMention, readOnMention, writeOnMention } from './
49
41
  import { pickChecklist } from './agent-task-workflow.js'
50
42
  import { changeRefusal, TALK_REFUSED } from './session-access.js'
51
43
  import { canAdmit } from './admit-policy.js'
52
- import { merge3, hasMarkers, mergeLive } from './merge3.js'
44
+ import { merge3, mergeAuto, hasMarkers, mergeLive } from './merge3.js'
53
45
  import { sameEditClient, asClient } from './same-edit.js'
54
46
  import { openMerge, updateMerge, readMerges, pruneMerges, cleanName } from './merges.js'
55
- import { LiveRules, applyMine, findUses, removedNameWarning } from './live-merge.js'
47
+ import { LiveRules, applyMine, findUses, removedNameWarning, clashNotice, clashStillNotice } from './live-merge.js'
56
48
  import { versionOf } from './read-bases.js'
57
- import { RecentTexts } from './base-pick.js'
58
- import { swapIn } from './swap-in.js'
49
+ import { RecentTexts, olderCopyNotice } from './base-pick.js'
50
+ import { swapIn, settled, savedInto } from './swap-in.js'
59
51
  import { exchangeKind } from './exchange.js'
60
- import { HELD_MAP, SETTINGS_MAP, readHeld, findHeld, settleHeld, staleWriteMinutes, setStaleWriteMinutes, renderHeld, heldLandingNote, versionsOf, versionBy, ownHeld } from './held.js'
52
+ import { HELD_MAP, readHeld, findHeld, settleHeld, renderHeld, versionsOf, versionBy, ownHeld } from './held.js'
61
53
  import { RELAY_NAME as RELAY_BY, isRelay } from './ui/chat.js'
62
54
  import { cleanTyping, TYPING_MS, AGENT_TYPING_MS } from './ui/chat.js'
63
55
  import { DEFAULT_KEY } from './branchdocs.js'
64
56
  import { boxEntry } from './boxes.js'
57
+ import { headKey, headName, branchTip, busy as gitBusy, leftoverLock, indexStamp, filesAt, blobAt, treeState, watchGit, SETTLE_MS as GIT_SETTLE_MS, STALE_LOCK_MS } from './gitstate.js'
65
58
  import { cleanVoice, newCallId, voiceView, inVoice, transcribeSetting, setTranscribe, addLine, readLines, MAX_IN_CALL, CALL_FULL, callAgents, setAgentLeft, notInCall, agentSays, markCallForAgents, namedAgents, callPing, spokenReply, AGENT_REPLY_MS } from './voice.js'
66
59
  import { toolInUse } from './agents/common.js'
67
- import { squareShort } from '@heyquilt/seam/lib/quilts/errors.js'
68
60
 
69
61
  export { applyTextDiff }
70
62
 
@@ -80,19 +72,6 @@ function hasGitDir (root) {
80
72
  try { fs.statSync(path.join(root, '.git')); return true } catch { return false }
81
73
  }
82
74
 
83
- /** The branch a git checkout in `root` is on, read from .git/HEAD (no git run); null when none or detached. */
84
- function headBranch (root) {
85
- try {
86
- let dir = path.join(root, '.git')
87
- if (fs.statSync(dir).isFile()) {
88
- const m = /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(dir, 'utf8'))
89
- if (!m) return null
90
- dir = path.resolve(root, m[1].trim())
91
- }
92
- const m = /^ref:\s*refs\/heads\/(.+)$/m.exec(fs.readFileSync(path.join(dir, 'HEAD'), 'utf8'))
93
- return m ? m[1].trim() : null
94
- } catch { return null }
95
- }
96
75
  const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904' // git's empty tree, the base of a branch pushed from nothing
97
76
 
98
77
  /**
@@ -109,8 +88,6 @@ function defaultCli () {
109
88
  const CLASH = Symbol('clash') // clash tasks this Quilt writes (quiet for its own inbox until settleClash)
110
89
  const CLASH_REASSIGN_MS = 5 * 60 * 1000 // a clash task's assignee gone this long: the next member takes it
111
90
  const CLASH_WAIT_MS = 30 * 1000 // no clash task from the first in line this long: the next one writes it
112
- const FILE_LOG_MS = 30 * 1000 // a file's History in the app reads the quilt's log at most this often (fileHistory)
113
- const HISTORY_SEAM_OFF_MS = 60 * 1000 // quilt_history reads through the relay this long after Seam would not let this member in
114
91
  const CLASH_IDLE_MS = 15 * 60 * 1000 // a clash assignee with no progress this long is handed on
115
92
  const CLASH_SETTLE_MS = 2000 // a clash task this member wrote is told to its AI after this long, if it survived a race
116
93
  const CLASH_KEEP_MS = 3 * 24 * 60 * 60 * 1000 // a finished clash record is kept this long
@@ -153,8 +130,6 @@ const WATCH_RECHECK_MS = 80
153
130
  const RECONCILE_MS = 1000
154
131
  // Failed large-file uploads and downloads are tried again this often (and on reconnecting).
155
132
  const RETRY_MS = 30 * 1000
156
- // A folder with no square for its branch asks for one by itself, again this long after a try that failed.
157
- const SQUARE_AUTO_RETRY_MS = 60 * 1000
158
133
  // A move to a branch the relay can't load (or refused) is tried again at most this far apart.
159
134
  const MOVE_RETRY_MAX_MS = 5 * 60 * 1000
160
135
  // Large uploads and downloads each hold the whole file in memory (twice), so only this many run at once.
@@ -163,6 +138,10 @@ const MAX_TRANSFERS = 2
163
138
  const HEAD_CHANGED = '.quilt/HEAD-changed'
164
139
  // Settles in a row that couldn't ask git (about a minute) before saying so; the folder stays held regardless.
165
140
  const GIT_FAILURES_TO_SAY = 30
141
+ // Before a folder leaves a branch, its saves still on their way to the relay are waited for this long at most.
142
+ const MOVE_WRITES_WAIT_MS = 3000
143
+ // A rebase or a bisect that has held the folder this long is said (once): it may be waiting on the person.
144
+ const HOLD_SAY_MS = 10 * 1000
166
145
  const FLUSH_MS = 40 // file changes are flushed this long after the first
167
146
  // How often a folder looks for commits its branch is behind (fetching its upstream first).
168
147
  const UPSTREAM_MS = Number(process.env.QUILT_UPSTREAM_MS) || 60 * 1000
@@ -179,31 +158,6 @@ const SETTLE_BOXES_MS = 1500 // after an edit to one of our boxed files: does gi
179
158
  const RELAY_ASK_EVERY_MS = 5 * 1000 // a folder waiting for the relay asks it again this often (server.js SYNC_EVERY_GIT_MS)
180
159
  const INDEX_WATCH_MS = 8000 // after a bring-in, how long the index is checked against what another git may write back
181
160
 
182
- // The owner's app renews the room's read token this long before it ends, looks this often, and tries again after this (renewReadToken).
183
- const READ_RENEW_BEFORE_MS = 30 * 86400e3
184
- const READ_RENEW_CHECK_MS = 6 * 3600e3
185
- const READ_RENEW_RETRY_MS = 3600e3
186
-
187
- /** What a move says of large files in the session's storage that git does not have (server.js quiltSwitchNow): the folders put them in. */
188
- const largeLine = (list) => `Large files in the session's storage that git does not have are not in the squares yet (the relay can't read them); each folder that has them puts them in its square when it follows it, with a Seam sign-in on that computer: ${list.slice(0, 8).map((x) => `${x.path} (${x.branch}${x.size ? `, ${Math.max(1, Math.round(x.size / 1048576))} MB` : ''})`).join(', ')}${list.length > 8 ? `, and ${list.length - 8} more` : ''}.`
189
-
190
- /** What every member is told while the session moves (server.js withMigrationLease `moving`): what to expect, in plain words. */
191
- export const movingLine = (m) => m && m.kind === 'back'
192
- ? 'The session\'s code is moving back from Seam to its git branches. Keep Quilt open: it can take a few minutes, and your edits are kept; your folder takes git back when it is done.'
193
- : 'The session\'s code is moving into Seam, where it will be committed and merged; the session stays in Quilt. Keep Quilt open: it can take a few minutes on a large session, and your edits are kept; your folder then follows its square by itself.'
194
-
195
-
196
- /** The move's word on people Seam would not make writers of a square: their AIs can't commit there until they are. */
197
- function notSharedLines (list) {
198
- if (!(list || []).length) return []
199
- const by = new Map()
200
- for (const x of list) { const k = `${x.member || 'everyone'} (${x.why})`; by.set(k, [...(by.get(k) || []), squareShort(x.square)]) }
201
- const each = [...by].slice(0, 6).map(([who, sqs]) => `${who} in ${sqs.join(', ')}`)
202
- return [`Not every person could be made a writer of every square, so their AIs can't commit there yet: ${each.join('; ')}${by.size > 6 ? '; …' : ''}. Add them to the quilt (seam quilts add <member> --level write) and share the square (seam_share).`]
203
- }
204
- /** What a move says when it made the room's read token again (server.js freshReadToken). */
205
- const readTokenLine = (why) => `The session's read token for its quilt was ${why === 'missing' ? 'missing' : why === 'expiring' ? 'about to end' : 'no longer taken by Seam'}, so a new one was made: every folder reads its square with it.`
206
-
207
161
  /** Writes `data` to `abs` and returns the file's stat as the write left it (taken before it is closed). */
208
162
  // Quilt's own file in the making (writeOver, rescueSave): never synced.
209
163
  const QUILT_TEMP = /^\..+\.quilt-(tmp|save)$/
@@ -215,6 +169,17 @@ const WROTE_BYTES = 32 * 1024 * 1024 // all of them together; past it the oldest
215
169
  // After a write-out, the file it replaced is looked at once more this much later: a save into it, opened just before.
216
170
  const LATE_WRITE_MS = 100
217
171
 
172
+ /**
173
+ * Whether bytes are what readDisk found (`disk`): Quilt is about to write over, or let go of, the file it read.
174
+ * A text compares as text (as it was read), a binary by its bytes; null when there is nothing to compare.
175
+ */
176
+ function sameAsRead (disk) {
177
+ if (!disk) return null
178
+ if (typeof disk.text === 'string') { const t = disk.text; return (b) => b.toString('utf8') === t }
179
+ if (Buffer.isBuffer(disk.buf)) { const buf = disk.buf; return (b) => b.equals(buf) }
180
+ return null
181
+ }
182
+
218
183
  function writeAndStat (abs, data, mode = undefined) {
219
184
  const fd = fs.openSync(abs, 'w', mode)
220
185
  try {
@@ -226,10 +191,8 @@ function writeAndStat (abs, data, mode = undefined) {
226
191
  }
227
192
 
228
193
  export class Session extends EventEmitter {
229
- constructor ({ dir, server, room, secret, key = '', viewSecret = '', name, tool = 'unknown', color = null, prefer = 'remote', kind = 'human', shareAgent = true, summarize = null, identity = null, passes = null, startName = '', startAgentCommits = '', newSession = false, quiltDefault = null, workspace = '', editQuietMs = EDIT_QUIET_MS, aiTasks = null, pushLocalCommits = null, webhookTransport = null, pullWaitMs = PULL_WAIT_MS, bringInUpstream = true, clashReassignMs = CLASH_REASSIGN_MS, clashWaitMs = CLASH_WAIT_MS, clashSettleMs = CLASH_SETTLE_MS, clashIdleMs = CLASH_IDLE_MS, catcherWaitMs = CATCHER_WAIT_MS, gitBacking = true, gitRemote = null, followsRelay = true, turns = false, features = null, cli = defaultCli(), apiAuth = null }) {
194
+ constructor ({ dir, server, room, secret, key = '', viewSecret = '', name, tool = 'unknown', color = null, prefer = 'remote', kind = 'human', shareAgent = true, summarize = null, identity = null, passes = null, startName = '', startAgentCommits = '', workspace = '', editQuietMs = EDIT_QUIET_MS, aiTasks = null, pushLocalCommits = null, webhookTransport = null, pullWaitMs = PULL_WAIT_MS, bringInUpstream = true, clashReassignMs = CLASH_REASSIGN_MS, clashWaitMs = CLASH_WAIT_MS, clashSettleMs = CLASH_SETTLE_MS, clashIdleMs = CLASH_IDLE_MS, catcherWaitMs = CATCHER_WAIT_MS, gitBacking = true, gitRemote = null, followsRelay = true, turns = false, features = null, cli = defaultCli() }) {
230
195
  super()
231
- // The Quilt sign-in this session runs as, for the accounts API and Seam (seam-access.js): its person's, or its agent's key.
232
- this.apiAuth = apiAuth
233
196
  // An agent that works in turns (agent-join.js keptInProject): the relay shows it away between them.
234
197
  this.turns = turns
235
198
  this.pullWaitMs = pullWaitMs
@@ -321,9 +284,6 @@ export class Session extends EventEmitter {
321
284
  this.relayProblem = null // why the relay can't be reached, when we know (setRelayProblem)
322
285
  this.agentPrompts = new Map() // conv -> latest prompt line, so an edit can be titled after the question that started it
323
286
  this.merging = new Set() // paths held out of normal sync until their offline merge has run
324
- // At layout 3 the folder follows its branch's square in place (session-follow.js): { square, since }, and
325
- // while it does, its branch-document sync and git-mode upstream work are held (enterSquare).
326
- this.inSquare = null
327
287
  this.catchUp = null // "while you were away" (catchup.js), until the person dismisses it
328
288
  this.awayBackups = null // while joining: copies of ours kept in .quilt/conflicts, for the catch-up
329
289
  this.work = null // { state: 'working'|'done', note, ts }: what an agent says it's doing
@@ -355,9 +315,11 @@ export class Session extends EventEmitter {
355
315
  this.lastKnown = new Map() // path -> text content, or "bin:<sha1>"
356
316
  this.relayWriting = new Set() // paths with a live write at the relay, not answered yet (relayIngest)
357
317
  this.relayAgain = new Set() // of those, the ones saved again meanwhile: taken in once the answer is here
318
+ this.clashed = new Map() // path -> its text with conflict markers, as last seen: not shared until they are gone (relayClashed)
319
+ this.noClashMarkers = false // as an app before 0.3.176: a clash goes to a held record, not into the file (tests)
358
320
  this.relayLocal = new Set() // paths the relay asked to be edited here as before (its answer's `fallback`), once
359
- this.overwritten = new RecentTexts() // saves that landed in a file Quilt replaced, with the text they were made from (base-pick.js)
360
- this.wroteHere = new Map() // path -> { ino, size, mtimeMs, text }: the text file Quilt last wrote there, read back from memory while untouched
321
+ this.overwritten = new RecentTexts() // the texts Quilt replaced on disk, and the saves made from them (base-pick.js)
322
+ this.wroteHere = new Map() // path -> { ino, size, mtimeMs, text, sure }: the text file Quilt last wrote there, read back from memory once confirmed untouched
361
323
  this.wroteBytes = 0 // their texts' length, together
362
324
  // path -> sha1 of lastKnown when state.json was last saved (null: a state file from before this was kept).
363
325
  this.known = null
@@ -368,6 +330,7 @@ export class Session extends EventEmitter {
368
330
  this.flushTimer = null
369
331
  this.rechecks = new Map() // path -> timer
370
332
  this.diskStats = new Map() // path -> stat signature, for the periodic re-scan
333
+ this.diskFresh = new Map() // path -> when its stat was noted while the file's time was fresh (FRESH_MS): read again, not trusted
371
334
  this.reconcileTimer = null
372
335
  this.ready = false
373
336
  this.myEdits = new Map() // path -> ts of my last edit
@@ -406,25 +369,21 @@ export class Session extends EventEmitter {
406
369
  this.startAgentCommits = startAgentCommits // the person's default for what agents may commit, set on a new room the same way
407
370
  this.workspace = workspace // the workspace this session is in (the app knows); told to the relay as owner, so webhook events can say so
408
371
  this.startNameSent = false
409
- // A session this app just started: with QUILT_SOURCE_DEFAULT on the API it becomes a quilt from the start (quilt-default.js).
410
- this.newSession = !!newSession
411
- this.quiltDefault = quiltDefault // tests: replaces startAsQuilt's options
412
- this.startQuiltTried = false
413
372
  this.logs = [] // the last 200 log lines (for status and tests)
414
373
  // Git awareness (gitstate.js): a git operation in this folder is recognised, not broadcast as edits.
415
- this.git = null // { key, branch, sha } this folder was on when the session started (null: not a repo)
416
- this.gitSeen = null // the head last seen by classifyBurst
374
+ this.git = null // { key, branch, sha }: where git had this folder when the session started or it last moved (null: not a repo)
375
+ this.gitSeen = null // the head last read from git
417
376
  this.gitIndex = null // indexStamp at the last flush
418
377
  this.gitWatcher = null
419
- this.hold = null // { kind: 'busy'|'settling'|'switching', since, prevHead, to? } while this folder's sync is held
378
+ this.hold = null // { kind: 'busy'|'switching', since, to?, waiting? } while this folder's sync is held (git at work; moving to another branch)
420
379
  this.upstreamAfterHold = null // a look at the upstream asked while held ({ fetch }): asked again when the hold ends
421
380
  this.heldPaths = new Set() // paths that changed (here or in the room) while held
422
381
  this.heldConflicts = new Set() // paths git left a conflict in during this hold (see noteConflict)
423
382
  this.stashSeen = null // the stash's mark when the folder was last quiet: a change by the settle means the person stashed
424
383
  this.headChangedAt = 0
425
384
  this.settleTimer = null
426
- this.savedGit = null // { key, sha, held } from state.json: the branch synced, and whether a hold was on, at the last stop
427
- this.rejoin = false // restarted held: when the hold ends, every path is checked, not only those seen changing
385
+ this.savedGit = null // { key, sha } from state.json: the branch this folder synced at the last stop
386
+ this.rejoin = false // started on another branch than the one saved: if the hold ends back on the saved one, every path is checked, not only those seen changing
428
387
  this.gitFailures = 0 // settles in a row that couldn't ask git
429
388
  // Commits made outside the session that this branch is behind (see bringIn): { name, url, sha,
430
389
  // behind, ahead, diverged, conflicts, waiting, checkedAt } of the branch's upstream, or null.
@@ -521,10 +480,8 @@ export class Session extends EventEmitter {
521
480
  this.gone = doc.getMap('gone')
522
481
  this.fileBases = doc.getMap('fileBases')
523
482
  this.merges = doc.getMap('merges')
524
- // While the folder follows a square, who changed what is the square's (followSquareDoc).
525
- const record = this.squareDoc || doc
526
- this.tallies = record.getMap('changes')
527
- this.history = new HistoryLog(record, record.getArray('history'), { origin: LOCAL })
483
+ this.tallies = doc.getMap('changes')
484
+ this.history = new HistoryLog(doc, doc.getArray('history'), { origin: LOCAL })
528
485
  }
529
486
 
530
487
  /**
@@ -621,16 +578,19 @@ export class Session extends EventEmitter {
621
578
  this.loadWebhook()
622
579
  this.loadOnMention()
623
580
  const hadState = this.loadState()
624
- // A folder never synced and empty as the session starts: in a session that is a layout-3 quilt already,
625
- // whatever it gets before its block opens is the read-only branch document's older copy, never its
626
- // member's edits (session-follow.js openHere; 2026-11-01). Cleared by a first word of the quilt that is
627
- // not layout 3, and once the block opens.
628
- this.joinedEmpty = !hadState && !walk(this.root, this.ig).some((rel) => this.syncable(rel))
629
- // Restarted while the folder follows its square: its .git is set aside (session-follow.js) and stays so; its branch is the note's.
581
+ // A folder whose .git an older Quilt set aside (git-aside.js): it comes back once the relay has synced (gitBack); its branch is the note's until then.
630
582
  this.gitAside = hasGitDir(this.root) ? null : gitAsideOf(this.root)
631
583
  if (hadState) this.loadBoxes()
632
- // The branch whose square this folder follows: the checkout's branch name, the set-aside note's, else the room's default.
633
- this.branch = headBranch(this.root) || (this.gitAside && this.gitAside.branch) || DEFAULT_KEY
584
+ // Where git has the folder: a branch, or a detached commit (keyed `@<sha>`). Without a commit to read
585
+ // (a branch with no commits yet, or git not running here) the branch HEAD names, with no commit.
586
+ this.git = await this.headAt()
587
+ this.gitSeen = this.git
588
+ this.gitIndex = indexStamp(this.root)
589
+ // Started on another branch than the one last synced: nothing in this tree is that branch's offline work (startAway).
590
+ const away = hadState && this.startAway()
591
+ // The branch document this folder syncs: the one git has it on (still the saved one, until the folder
592
+ // has moved, when it started away), the set-aside note's, else the room's default (a folder without git).
593
+ this.branch = (this.git && this.git.key) || (this.gitAside && this.gitAside.branch) || DEFAULT_KEY
634
594
  // The form saved is the saved branch's; another branch's is the relay's to say when it is joined.
635
595
  if (this.savedBranch !== this.branch) { this.branchForm = null; this.diffBase = null }
636
596
 
@@ -649,7 +609,7 @@ export class Session extends EventEmitter {
649
609
  doc: this.doc,
650
610
  // An app's saved document from before branch documents is the room's old one: the relay kept it as that branch's.
651
611
  // base: the commit a branch new to the session starts from (a partner without it locally creates it there).
652
- branch: { key: this.branch, doc: this.bdoc, ...(this.branchEpoch && this.savedBranch === this.branch ? { epoch: this.branchEpoch } : {}) },
612
+ branch: { key: this.branch, doc: this.bdoc, ...(this.git && this.git.sha ? { base: this.git.sha } : {}), ...(this.branchEpoch && this.savedBranch === this.branch ? { epoch: this.branchEpoch } : {}) },
653
613
  // state.bin is a copy of an older document of this branch (it was removed and started again): never merged.
654
614
  onStaleBranch: (reply) => this.staleBranch(reply),
655
615
  beforeRemote: () => { if (this.ready) this.flushPending() }
@@ -657,9 +617,9 @@ export class Session extends EventEmitter {
657
617
  this.conn.on('status', (s) => {
658
618
  this.log(s === 'connected' ? `connected to relay` : 'disconnected from relay, reconnecting…')
659
619
  this.scheduleStatusWrite()
660
- if (s === 'connected') { this.moveRetryAt = 0; this.retryFailed(); this.ensureSquare() }
620
+ if (s === 'connected') { this.moveRetryAt = 0; this.retryFailed() }
661
621
  })
662
- this.retryTimer = setInterval(() => { this.retryFailed(); this.ensureSquare() }, RETRY_MS)
622
+ this.retryTimer = setInterval(() => this.retryFailed(), RETRY_MS)
663
623
  this.retryTimer.unref()
664
624
  this.conn.on('warn', (m) => this.emit('debug', m))
665
625
  this.conn.on('fatal', (err) => this.emit('fatal', err))
@@ -669,38 +629,15 @@ export class Session extends EventEmitter {
669
629
  this.conn.on('access', (a) => this.setAccess(a))
670
630
  this.conn.on('members', (m) => this.setMembers(m))
671
631
  this.conn.on('branches', (list) => this.setBranches(list))
672
- // Seam (Seam's plans/quilt-source-control/16): the relay says when the session is a quilt, and which.
673
- this.conn.on('quilt', (q) => {
674
- this.quilt = q
675
- if (!(q && q.layout === 3)) this.joinedEmpty = false
676
- this.emit('quilt', q)
677
- // At layout 3 this folder follows its branch's square by itself (session-follow.js).
678
- if (!this.squareFollower) this.squareFollower = new SquareFollower(this)
679
- this.squareFollower.onQuilt(q).catch(() => {})
680
- this.renewReadToken().catch(() => {})
681
- this.ensureSquare()
682
- })
683
- // A write of this folder's reached a read-only branch document at layout 3: it was not kept (server.js refusedReadOnly).
684
- this.conn.on('read-only', (r) => this.noteReadOnly(r))
685
- this.conn.on('quilt-shadow', (q) => { this.quiltShadow = q; this.emit('quilt-shadow', q) })
686
- this.conn.on('importing', (x) => { this.quiltImporting = x; this.scheduleStatusWrite(); this.emit('importing', x) })
687
- // The forced date (16 flag 9, force-date.js): live sync stopped here, or the owner's open makes the session a quilt.
688
- this.conn.on('force', (f) => this.onForce(f))
689
- // A move of the session (into Seam, or back) runs on the relay: said in the log, the app and quilt_status while it lasts.
690
- this.conn.on('moving', (m) => {
691
- const was = this.moving
692
- this.moving = m
693
- if (m && !was) this.log(`🧵 ${movingLine(m)}`)
694
- else if (!m && was) this.log(`🧵 the move of the session's code ${was.kind === 'back' ? 'back to its git branches' : 'into Seam'} is over.`)
695
- this.scheduleStatusWrite()
696
- })
632
+ // A move's own join is the move's to finish (finishMove): this.branch changes only once the folder is there.
697
633
  this.conn.on('branch-joined', (r) => {
698
- if (typeof r.branch !== 'string' || !r.branch) return
634
+ if (typeof r.branch !== 'string' || !r.branch || (this.hold && this.hold.kind === 'switching')) return
699
635
  if (typeof r.epoch === 'string' && r.epoch && !this.staleRejoin) this.branchEpoch = r.epoch
700
636
  // An older relay says no form: its documents are all full ones.
701
637
  this.branchForm = r.form === 'diff' ? 'diff' : 'full'
702
638
  if (r.form === 'diff' && typeof r.diffBase === 'string') this.diffBase = r.diffBase
703
639
  this.branch = r.branch
640
+ this.announceBranch()
704
641
  this.scheduleStatusWrite()
705
642
  })
706
643
  this.conn.on('branch-refused', (why) => this.log(`⚠️ the relay refused this folder's branch: ${why}`))
@@ -712,11 +649,9 @@ export class Session extends EventEmitter {
712
649
  // We've synced this folder before: hold what was edited while we were
713
650
  // away, let the relay tell us what the others did, then merge the two.
714
651
  const marks = historyMarks(this.history.entries()) // what we had seen: the catch-up is the rest
715
- const offline = this.captureOffline(null)
652
+ const offline = away ? { entries: [], take: [], downloads: [] } : this.captureOffline(null)
716
653
  this.goLive()
717
- // A folder that follows its square (its .git set aside) is compared with the branch document it last synced, which the
718
- // square's work has moved past: its block's first look says what went in, so nothing is said here.
719
- if (offline.entries.length && !gitAsideOf(this.root)) this.log(`${offline.entries.length} file(s) changed while you were away; merging once the relay has synced…`)
654
+ if (offline.entries.length) this.log(`${offline.entries.length} file(s) changed while you were away; merging once the relay has synced…`)
720
655
  const synced = this.conn.waitForSync()
721
656
  synced.then(() => this.mergeOffline(offline)).then((mine) => {
722
657
  if (mine) this.noteCatchUp({ ...awayChanges(this.history.entries(), marks, this.name), since: this.savedSeenAt, mine })
@@ -726,6 +661,15 @@ export class Session extends EventEmitter {
726
661
  this.awayBackups = null
727
662
  this.emit('debug', `offline merge did not run: ${err && err.message}`)
728
663
  })
664
+ if (away) {
665
+ // The document loaded from disk is the saved branch as it was at the last stop: the folder moves to
666
+ // where git has it once the relay has synced. Never synced: the hold stays on and nothing is shared.
667
+ synced.then(() => {
668
+ const to = this.resumeAway
669
+ this.resumeAway = null
670
+ if (to) this.followHead(to)
671
+ }, () => {})
672
+ }
729
673
  } else {
730
674
  this.log('waiting for relay…')
731
675
  const sync = this.conn.waitForSync()
@@ -758,8 +702,8 @@ export class Session extends EventEmitter {
758
702
  this.goLive()
759
703
  }
760
704
  await this.startWatcher()
761
- // git was set aside while following a square, and the session is not one at layout 3 now (or Seam is off here): it comes back.
762
- if (this.gitAside) this.conn.waitForSync().then(() => { if (!this.inSquare && !this.stopped) return this.gitBack() }).catch(() => {})
705
+ // An older Quilt set this folder's .git aside: it comes back, once, now that the relay has synced.
706
+ if (this.gitAside) this.conn.waitForSync().then(() => { if (!this.stopped) return this.gitBack() }).catch(() => {})
763
707
  return this
764
708
  }
765
709
 
@@ -785,9 +729,6 @@ export class Session extends EventEmitter {
785
729
  const was = this.access
786
730
  this.access = a
787
731
  if (a.state === 'approved' && a.owner) this.sendStartName()
788
- if (this.force && this.force.migrate && a.state === 'approved' && a.owner) this.onForce(this.force)
789
- // A new session becomes a quilt as its owner (in a room with no owner, the relay lets any editor: quiltPlanRefusal).
790
- if (a.state === 'approved' && a.role !== 'viewer' && (a.owner || !a.controlled)) this.startQuiltOnce()
791
732
  if (a.state === 'approved' && this.webhook && !this.webhook.local) this.migrateWebhook().catch(() => {}) // the relay sends it from now on (or again, if it lost it)
792
733
  if (a.state === 'pending' && (!was || was.state !== 'pending')) this.log(`⏳ waiting for the session owner to let you in (you were invited to ${a.invitedAs === 'viewer' ? 'view' : 'edit'})`)
793
734
  if (a.state === 'approved' && was && (was.role !== a.role || String(was.scopes) !== String(a.scopes) || String(was.scopesExcept || []) !== String(a.scopesExcept || []))) {
@@ -875,19 +816,6 @@ export class Session extends EventEmitter {
875
816
  this.rename(this.startName).catch((err) => this.log(`couldn't name the session: ${err.message}`))
876
817
  }
877
818
 
878
- /** A new session, as its owner, starts as a quilt when the API says new sessions do (flags order 8); once, in the background. */
879
- startQuiltOnce () {
880
- if (!this.newSession || this.startQuiltTried) return
881
- this.startQuiltTried = true
882
- // Made as a person: an agent's own key only reads on Seam, so an agent's new session is made as the person signed in on this computer.
883
- const credential = async () => {
884
- const c = await sessionCredential({ apiAuth: this.apiAuth, account: readAccount })()
885
- if (c && isAgentKey(c) && !process.env.SEAM_TOKEN) { const acc = readAccount(); if (acc && acc.token) return acc.token }
886
- return c
887
- }
888
- this.startingQuilt = startAsQuilt(this, { credential, ...(this.quiltDefault || {}) })
889
- }
890
-
891
819
  /** As the owner, tells the relay which workspace the session is in (once per run; again when it moves). */
892
820
  sendWorkspace () {
893
821
  if (!this.workspace || this.workspaceSent === this.workspace || !this.isOwner) return
@@ -939,8 +867,6 @@ export class Session extends EventEmitter {
939
867
  this.taskComments.observe(() => this.scheduleStatusWrite())
940
868
  // Held conflicts (held.js): the app and quilt_status show every open one as it comes and goes.
941
869
  this.doc.getMap(HELD_MAP).observe(() => { this.scheduleStatusWrite(); this.emit('held', this.heldList()) })
942
- // The owner's stale_write_minutes (held.js): Session settings and the CLI show it as it changes.
943
- this.doc.getMap(SETTINGS_MAP).observe(() => this.scheduleStatusWrite())
944
870
  this.agentFeed.observe((ev) => {
945
871
  const added = []
946
872
  for (const item of ev.changes.added) for (const e of item.content.getContent()) if (e && e.id) added.push(e)
@@ -1006,10 +932,12 @@ export class Session extends EventEmitter {
1006
932
  for (const [rel, v] of Object.entries(meta.boxBase && typeof meta.boxBase === 'object' ? meta.boxBase : {})) if (v === null || (v && (typeof v.text === 'string' || typeof v.b64 === 'string'))) this.boxBase.set(rel, v)
1007
933
  this.known = meta.known ? new Map(Object.entries(meta.known)) : null
1008
934
  this.behindAtSave = new Map(Object.entries(meta.behind && typeof meta.behind === 'object' ? meta.behind : {}).filter(([, v]) => typeof v === 'string'))
1009
- // No gitKey (an older state file): taken as the branch the folder is on now.
1010
935
  this.savedRole = typeof meta.role === 'string' ? meta.role : null
1011
936
  this.savedSeenAt = typeof meta.seenAt === 'number' ? meta.seenAt : null
1012
- this.savedGit = typeof meta.gitKey === 'string' && meta.gitKey ? { key: meta.gitKey, sha: typeof meta.gitSha === 'string' ? meta.gitSha : null, held: !!meta.gitHeld } : null
937
+ // The branch git had the folder on at the last stop. A state file without it (written before folders
938
+ // followed their branch) names the branch it synced, when that is a real one.
939
+ const was = typeof meta.gitKey === 'string' && meta.gitKey ? meta.gitKey : !this.legacyState && this.savedBranch && this.savedBranch !== DEFAULT_KEY ? this.savedBranch : null
940
+ this.savedGit = was ? { key: was, sha: typeof meta.gitSha === 'string' ? meta.gitSha : null } : null
1013
941
  return true
1014
942
  } catch {
1015
943
  return false
@@ -1105,7 +1033,7 @@ export class Session extends EventEmitter {
1105
1033
  }
1106
1034
  // When we were last in touch with the session: "you left 3h ago" on the next catch-up.
1107
1035
  if (this.conn && this.conn.connected) this.savedSeenAt = Date.now()
1108
- fs.writeFileSync(path.join(this.stateDir, 'state.json'), JSON.stringify({ room: this.room, server: this.server, layout: 2, branch: this.branch, ...(this.branchEpoch ? { epoch: this.branchEpoch } : {}), ...(this.branchForm ? { form: this.branchForm } : {}), ...(this.diffBase ? { diffBase: this.diffBase } : {}), storedOnDisk: Object.fromEntries(this.storedOnDisk), known, ...(this.boxBase.size ? { boxBase: Object.fromEntries(this.boxBase) } : {}), ...(Object.keys(behind).length ? { behind } : {}), ...this.roleState(), ...(this.savedSeenAt ? { seenAt: this.savedSeenAt } : {}) }))
1036
+ fs.writeFileSync(path.join(this.stateDir, 'state.json'), JSON.stringify({ room: this.room, server: this.server, layout: 2, branch: this.branch, ...(this.branchEpoch ? { epoch: this.branchEpoch } : {}), ...(this.branchForm ? { form: this.branchForm } : {}), ...(this.diffBase ? { diffBase: this.diffBase } : {}), ...(this.git ? { gitKey: this.git.key, ...(this.git.sha ? { gitSha: this.git.sha } : {}) } : {}), storedOnDisk: Object.fromEntries(this.storedOnDisk), known, ...(this.boxBase.size ? { boxBase: Object.fromEntries(this.boxBase) } : {}), ...(Object.keys(behind).length ? { behind } : {}), ...this.roleState(), ...(this.savedSeenAt ? { seenAt: this.savedSeenAt } : {}) }))
1109
1037
  }
1110
1038
 
1111
1039
  /** This member's role, so the next start knows it before the relay says (ignoreQuiltState). */
@@ -1229,12 +1157,9 @@ export class Session extends EventEmitter {
1229
1157
 
1230
1158
  /** Runs once the relay has synced: merges every captured path against the session's version. */
1231
1159
  async mergeOffline ({ entries, take, downloads }) {
1232
- if (this.syncStopped) { for (const e of entries) this.merging.delete(e.rel); return null }
1233
1160
  if (this.stopped) { for (const e of entries) this.merging.delete(e.rel); return null } // the next start captures them again
1234
1161
  // The saved copy was of an older document of this branch: the folder joined fresh instead (rejoinFresh).
1235
1162
  if (this.staleRejoin || this.rejoinedFresh) { for (const e of entries) this.merging.delete(e.rel); return null }
1236
- // The folder follows its square: the block takes the edits made while away in (they differ from lastKnown, editedSinceSync).
1237
- if (this.inSquare) { for (const e of entries) this.merging.delete(e.rel); return null }
1238
1163
  const counts = { pushed: 0, merged: 0, ai: 0, conflict: 0 }
1239
1164
  const paths = { merged: [], conflict: [] } // for the catch-up
1240
1165
  const queue = entries.slice()
@@ -1307,10 +1232,12 @@ export class Session extends EventEmitter {
1307
1232
 
1308
1233
  /** Merges one captured path. Returns what happened, or null when nothing needed doing. */
1309
1234
  async mergeOne (e) {
1235
+ if (e.carried) return this.mergeCarried(e) // work a checkout carried from another branch
1310
1236
  const { rel, base, via = null } = e
1311
1237
  const release = () => this.merging.delete(rel)
1312
1238
  const disk = this.readDisk(rel)
1313
1239
  if (disk && (disk.skip || disk.tooLarge)) { release(); return null }
1240
+ if (disk && !disk.binary && hasMarkers(disk.text)) { release(); return null } // a clash to settle in the file (relayClashed): not merged or shared with its markers
1314
1241
  const ours = disk ? disk.key : null // re-read: it may have changed again before the relay synced
1315
1242
  const theirs = this.sharedKey(rel)
1316
1243
  const theirsBy = this.lastEditorOf(rel)
@@ -1375,7 +1302,7 @@ export class Session extends EventEmitter {
1375
1302
 
1376
1303
  /**
1377
1304
  * Both the folder (ours) and the session (theirs) changed rel since base: Quilt combines them
1378
- * itself (Seam's 07 "Conflicts in the live state", ruling 2026-11-13). Lines only one side changed
1305
+ * itself (ruling 2026-11-13). Lines only one side changed
1379
1306
  * are kept; where both changed the same lines nobody wins: the session's version, which landed
1380
1307
  * first, stays, and ours there is held for this writer (or any AI) to resolve (held.js); a binary
1381
1308
  * both changed keeps the session's, with ours held; an edit beats a deletion. Ours is kept too
@@ -1485,7 +1412,6 @@ export class Session extends EventEmitter {
1485
1412
 
1486
1413
  /** `gitNow`: for a diff branch, what the folder has that differs from HEAD (gitstate.js changedSince), or null. */
1487
1414
  reconcileFirstJoin (gitNow = null) {
1488
- if (this.inSquare || this.syncStopped) return { pulled: 0 } // the square's block brings the folder in (session-follow.js)
1489
1415
  const onDisk = new Set(walk(this.root, this.ig))
1490
1416
  let pulled = 0; let pushed = 0; let backedUp = 0
1491
1417
  const backupDir = path.join(this.stateDir, 'conflicts', new Date().toISOString().replace(/[:.]/g, '-'))
@@ -1591,10 +1517,19 @@ export class Session extends EventEmitter {
1591
1517
  if (!st.isFile()) return { skip: true }
1592
1518
  if (st.size > MAX_STORED_BINARY_BYTES) return { tooLarge: true }
1593
1519
  const exec = process.platform !== 'win32' && !!(st.mode & 0o111)
1594
- // The text Quilt wrote there, untouched since (same file, size and time): not read again.
1520
+ // The text Quilt wrote there, untouched since: not read again once that is sure. Same file, size and time
1521
+ // is no proof (a same-length save in the same timestamp tick keeps all three: Linux's tick is ~4 ms, and
1522
+ // 2026-11-14 lost such saves); it is sure once a read made after the file's time settled (FRESH_MS) found
1523
+ // Quilt's text: a save after that read gets a later time.
1595
1524
  const w = this.wroteHere.get(rel)
1596
- if (w && w.ino === st.ino && w.size === st.size && w.mtimeMs === st.mtimeMs) return { text: w.text, key: w.text, exec, mtime: st.mtimeMs }
1525
+ const lookedAt = Date.now()
1526
+ const same = w && w.ino === st.ino && w.size === st.size && w.mtimeMs === st.mtimeMs
1527
+ if (same && w.sure) return { text: w.text, key: w.text, exec, mtime: st.mtimeMs }
1597
1528
  const buf = fs.readFileSync(abs)
1529
+ if (same && buf.length === st.size && buf.toString('utf8') === w.text) {
1530
+ if (settled(st.mtimeMs, lookedAt) && settled(w.at, lookedAt)) w.sure = true
1531
+ return { text: w.text, key: w.text, exec, mtime: st.mtimeMs }
1532
+ }
1598
1533
  // `settle` (taking it in, or writing over it): being written as it was read (it changed during the read, or
1599
1534
  // reads empty just after being emptied, as a save that truncates first does) is `unsettled`, looked at again
1600
1535
  // shortly, never taken in half-written.
@@ -1617,10 +1552,6 @@ export class Session extends EventEmitter {
1617
1552
  // ------------------------------------------------------- local -> shared --
1618
1553
 
1619
1554
  queue (rel) {
1620
- // The folder follows its square: the block sees every change; git moving HEAD may take it to another branch's square.
1621
- // The app hears of each change on disk all the same (its Files list and an open file read the folder then: squareFiles).
1622
- if (this.syncStopped) return // live sync stopped at the forced date (onForce): the folder is plain git
1623
- if (this.inSquare) { this.emit('file-changed', { path: rel }); return }
1624
1555
  this.pending.add(rel)
1625
1556
  if (!this.flushTimer) this.flushTimer = setTimeout(() => this.flushPending(), FLUSH_MS)
1626
1557
  }
@@ -1630,6 +1561,23 @@ export class Session extends EventEmitter {
1630
1561
  this.flushTimer = null
1631
1562
  const paths = [...this.pending]
1632
1563
  this.pending.clear()
1564
+ if (this.hold) {
1565
+ for (const rel of paths) if (rel !== HEAD_CHANGED) this.heldPaths.add(rel)
1566
+ // Only a change here puts the end of the hold off: the flush before each update from the session
1567
+ // (beforeRemote) has none, and a partner typing must not hold this folder for good.
1568
+ // A move to another branch ends on its own (finishMove).
1569
+ if (paths.length && this.hold.kind !== 'switching') this.settleHoldSoon()
1570
+ // A move that didn't finish follows HEAD wherever git takes it next (back to the old branch resumes it).
1571
+ else if (this.hold.kind === 'switching' && paths.includes(HEAD_CHANGED) && !this.following) this.recheckSoon()
1572
+ return
1573
+ }
1574
+ if (this.git && this.isBurst()) {
1575
+ // git is at work here, or has just been: held until it is known whether the folder is still on its branch.
1576
+ for (const rel of paths) if (rel !== HEAD_CHANGED) this.heldPaths.add(rel)
1577
+ this.setHold('busy')
1578
+ this.settleHoldSoon()
1579
+ return
1580
+ }
1633
1581
  this.ingestAll(paths)
1634
1582
  }
1635
1583
 
@@ -1643,521 +1591,715 @@ export class Session extends EventEmitter {
1643
1591
  if (!this.stopped) for (const rel of paths) this.queue(rel)
1644
1592
  }
1645
1593
 
1646
- /** The disk at rel is as Quilt last wrote or read it (or still absent, for a path it never had). */
1647
- untouchedHere (rel) {
1648
- const disk = this.readDisk(rel)
1649
- if (disk && (disk.skip || disk.tooLarge)) return false
1650
- return (disk ? disk.key : undefined) === this.lastKnown.get(rel)
1651
- }
1652
-
1653
1594
  onDisk (rel) {
1654
1595
  try { fs.lstatSync(path.join(this.root, ...rel.split('/'))); return true } catch { return false }
1655
1596
  }
1656
1597
 
1657
- /** What the folder holds at rel, as lastKnown keys it: null when nothing is there, undefined for a file never synced (a link, too large). */
1658
- diskKey (rel) {
1659
- const d = this.readDisk(rel)
1660
- if (!d) return null
1661
- return d.skip || d.tooLarge ? undefined : d.key
1662
- }
1598
+ // ------------------------------------------------------------------ git --
1599
+ // A folder that is a git checkout is on one branch of the session at a time, the one git has it
1600
+ // on. Quilt never switches branches itself: when a person or an agent checks out another branch
1601
+ // in git, the folder moves to that branch's document, and the branch it left keeps its work in
1602
+ // the session. While git is at work in the folder (its index lock is there, or a rebase or a
1603
+ // bisect has HEAD off its branch) and while a move is under way, the folder's sync is held:
1604
+ // nothing is taken in and nothing from the session is written out. Git work that leaves the
1605
+ // folder on its branch (a commit, a stash, a reset, a pull) is shared afterwards as the edits it
1606
+ // made, like any other change to the files.
1663
1607
 
1664
1608
  /**
1665
- * What making this session a quilt would do (Seam's plans/quilt-source-control/16), read only: the
1666
- * relay's dry run (behind QUILT_SOURCE_URL there, the owner's), as { plan, text }.
1609
+ * Where git has the folder now: { key, branch, sha } (a branch, or a detached commit keyed `@<sha>`).
1610
+ * A branch with no commits yet, or a folder whose git can't be run, has no sha. Null when it is
1611
+ * not a repository or HEAD can't be read.
1667
1612
  */
1668
- async quiltPlan () {
1669
- if (!this.conn || !this.conn.connected) throw new Error('not connected to the relay; the dry run needs a connection')
1670
- const r = await this.conn.branchRequest({ op: 'quilt-plan' })
1671
- return { plan: r.plan, text: describeQuiltPlan(r.plan) }
1613
+ async headAt () {
1614
+ const head = await headKey(this.root)
1615
+ if (head) return head
1616
+ const key = headName(this.root)
1617
+ return key ? { key, branch: key.startsWith('@') ? null : key, sha: null } : null
1672
1618
  }
1673
1619
 
1674
- /**
1675
- * Makes the session a quilt (Seam's plans/quilt-source-control/16, "Without history"): the relay does
1676
- * it, as the owner, with `token` (their Seam sign-in: SEAM_TOKEN, else their Quilt account's).
1677
- * What it made: { quilt, text }.
1678
- */
1679
- async quiltMigrate (token, { op = 'quilt-migrate' } = {}) {
1680
- if (!this.conn || !this.conn.connected) throw new Error('not connected to the relay; making the session a quilt needs a connection')
1681
- if (!token) throw new Error('sign in first (quilt login, or set SEAM_TOKEN): the session becomes a quilt as its owner')
1682
- const r = await this.conn.branchRequest({ op, token }, { timeoutMs: QUILT_MOVE_TIMEOUT_MS })
1683
- const q = r.quilt
1684
- // A session with a git remote moves in steps (the relay's quiltMakeWithRemote): Seam importing it, then ready for the cut-over.
1685
- if (q && (q.stage === 'importing' || q.stage === 'ready')) return { quilt: q, text: q.text }
1686
- const lines = [`Session ${this.room || ''} is now the quilt ${q.slug}.`.replace('Session is', 'This session is')]
1687
- if (q.history) lines.push(`It is the quilt its git remote was imported into: main is at patch ${q.patch && q.patch.no}, git's history before it.`)
1688
- else if (q.patch) lines.push(`Patch ${q.patch.no} holds the main branch as it was.`)
1689
- for (const s of q.squares) lines.push(`Branch ${s.from} is square ${squareShort(s.id)}.`)
1690
- for (const b of q.based_at_tip || []) {
1691
- lines.push(b.why === 'unfetched'
1692
- ? `The relay never fetched ${b.from} from git, so its square starts at main's tip with the branch's files over it: its history before the move is main's, not the branch's.`
1693
- : b.why === 'merged'
1694
- ? `${b.from}'s commit ${String(b.wanted || '').replace(/^git:/, '').slice(0, 12)} is already merged into main, so its square starts at main's tip.`
1695
- : `Seam has no commit for ${String(b.wanted || '').replace(/^git:/, '')}, so ${b.from}'s square starts at main's tip.`)
1696
- }
1697
- if (q.adoption) lines.push(`Work on the main branch that git does not have is in the square "Uncommitted work" (${squareShort(q.adoption)}).`)
1698
- if (q.read_token) lines.push(readTokenLine(q.read_token))
1699
- if (q.large) lines.push(largeLine(q.large))
1700
- if (q.rebased) lines.push(`Someone's unfinished work boxed on an older main went onto main's newer copy as their change only, not their whole file: ${q.rebased.slice(0, 8).map((x) => `${x.path} (${x.branch})`).join(', ')}.`)
1701
- if (q.layout === 3) lines.push('Its files are in its squares now; apps without Seam are asked to update. quilt session migrate --back goes back to git.')
1702
- lines.push(...notSharedLines(q.not_shared))
1703
- const moved = Object.keys(q.tasks || {}).length
1704
- if (moved) lines.push(`${moved} task${moved === 1 ? '' : 's'} with a pull request follow${moved === 1 ? 's' : ''} its square.`)
1705
- if (q.left_out.length) lines.push(`Large files left in the session's storage, not in the quilt: ${q.left_out.join(', ')}.`)
1706
- return { quilt: q, text: lines.join('\n') }
1620
+ /** The key of where HEAD is (headAt), or null when git can't say. */
1621
+ async headNow () {
1622
+ const head = await this.headAt()
1623
+ return head ? head.key : null
1707
1624
  }
1708
1625
 
1709
- /**
1710
- * The relay's word on the forced date (16 flag 9). `stopped`: the session had a git remote and did
1711
- * not cut over, so its live file sync stopped for good: this folder is plain git from now on (no
1712
- * file is written or shared by Quilt, no git work of Quilt's), said once in the log, the app and
1713
- * every quilt answer. `migrate`: a session with no git remote, past the date, opened by its owner:
1714
- * made a quilt now, as they would with the button (once per run of the app).
1715
- */
1716
- onForce (f) {
1717
- this.force = f || null
1718
- if (f && f.stopped && !this.syncStopped) {
1719
- this.syncStopped = { at: f.stopped.at }
1720
- clearTimeout(this.flushTimer)
1721
- this.flushTimer = null
1722
- this.pending.clear()
1723
- clearTimeout(this.upstreamTimer)
1724
- this.upstreamTimer = null
1725
- const why = String(f.stopped.why || 'Live sync stopped: this session\'s folder is plain git now.')
1726
- this.log(`🧵 ${why}`)
1727
- this.notice(why)
1728
- this.scheduleStatusWrite()
1729
- this.emit('force', f)
1730
- return
1731
- }
1732
- if (f && f.migrate && !f.remote && !this.forceMigrateTried && this.access && this.access.owner) {
1733
- const token = process.env.SEAM_TOKEN || (readAccount() || {}).token
1734
- if (!token) return
1735
- this.forceMigrateTried = true
1736
- this.log('🧵 The date for moving sessions into Seam has passed: making this session a quilt now (its code is committed in Seam from here on; nothing is lost).')
1737
- this.quiltMake(token).then((r) => { this.log(`🧵 ${r.text.split('\n')[0]}`); this.notice(r.text) }, (err) => this.log(`⚠️ couldn't make the session a quilt at the forced date: ${err.message}. Settings → Session → Make this a quilt tries again.`))
1738
- }
1739
- this.emit('force', f)
1626
+ /** Did git just touch this folder? (its index written, HEAD moved, or an operation under way) */
1627
+ isBurst () {
1628
+ const stamp = indexStamp(this.root)
1629
+ const indexChanged = stamp !== this.gitIndex
1630
+ this.gitIndex = stamp
1631
+ const at = headName(this.root)
1632
+ return indexChanged || Date.now() - this.headChangedAt < 2000 || !!this.gitBusy() || (!!at && at !== this.git.key)
1740
1633
  }
1741
1634
 
1742
- /**
1743
- * "Make this a quilt" (16 flag 9), the owner's button and `quilt session migrate`: the relay makes the
1744
- * session a quilt and moves its files into its squares in one go (Room.quiltMake). { quilt, text }.
1745
- */
1746
- quiltMake (token) { return this.quiltMigrate(token, { op: 'quilt-make' }) }
1635
+ /** The git operation under way in this folder, or null; a leftover index.lock doesn't count. */
1636
+ gitBusy () { return gitBusy(this.root, undefined, this.leftoverLock) }
1637
+
1638
+ /** Whether the folder's sync is held: git is at work on it, or it is moving to another branch. (A move's own writes go through: arrive.) */
1639
+ held () { return !!(this.hold && !this.arriving) }
1747
1640
 
1748
1641
  /**
1749
- * The session's files into its squares' live documents on the relay (layout 3, 16), as the
1750
- * owner, once it is a quilt: { layout, live, adoption, text }.
1642
+ * Runs git work in this folder one piece at a time, in order (the end of a hold, a move, a look
1643
+ * at HEAD), each skipped once stopped.
1751
1644
  */
1752
- async quiltSwitch (token) {
1753
- if (!this.conn || !this.conn.connected) throw new Error('not connected to the relay; moving the session needs a connection')
1754
- if (!token) throw new Error('sign in first (quilt login, or set SEAM_TOKEN): the session moves into its squares as its owner')
1755
- const r = await this.conn.branchRequest({ op: 'quilt-switch', token }, { timeoutMs: QUILT_MOVE_TIMEOUT_MS })
1756
- const lines = ['The session\'s files are in its squares now; its branches are kept, read-only.']
1757
- for (const [b, k] of Object.entries(r.live || {})) lines.push(`${b} is in square ${squareShort(k.replace(/^quilt\//, ''))}.`)
1758
- if (r.adoption) lines.push(`Work on the main branch since it became a quilt is in the square "Uncommitted work" (${squareShort(r.adoption)}).`)
1759
- if (r.read_token) lines.push(readTokenLine(r.read_token))
1760
- if (r.large) lines.push(largeLine(r.large))
1761
- if (r.rebased) lines.push(`Someone's unfinished work boxed on an older main went onto main's newer copy as their change only, not their whole file: ${r.rebased.slice(0, 8).map((x) => `${x.path} (${x.branch})`).join(', ')}.`)
1762
- lines.push('Apps without Seam are asked to update. quilt session migrate --back goes back to the branches.')
1763
- lines.push(...notSharedLines(r.not_shared))
1764
- return { ...r, text: lines.join('\n') }
1645
+ gitTask (fn) {
1646
+ const run = this.gitChain.then(() => this.stopped ? undefined : fn())
1647
+ this.gitChain = run.catch(() => {})
1648
+ return run
1765
1649
  }
1766
1650
 
1767
- /**
1768
- * At layout 3 (Seam's plans/quilt-source-control/16): `dir` (its own folder) follows this folder's
1769
- * branch's square, live (session-follow.js), signed in to Seam with `token` (else as this member). Only with
1770
- * Seam on for this app (seam-url.js) and the relay saying the session is a layout-3 quilt.
1771
- */
1772
- async quiltFollow (token, dir) {
1773
- if (!this.squareFollower) this.squareFollower = new SquareFollower(this)
1774
- // As `token`, else as this member (seamMember), the same as `quilt commit` and the Seam tools.
1775
- const client = !appSeamUrl() ? null : token ? quiltClient({ api: appSeamUrl(), token }) : await this.seamClientNow()
1776
- const r = await this.squareFollower.follow({ dir: dir ? path.resolve(this.root, String(dir)) : '', client })
1777
- return { ...r, text: `${r.dir} follows the square ${squareShort(r.square)}: edits there are live for everyone on it.` }
1651
+ /** The disk at rel is as Quilt last wrote or read it (or still absent, for a path it never had). */
1652
+ untouchedHere (rel) {
1653
+ const disk = this.readDisk(rel)
1654
+ if (disk && (disk.skip || disk.tooLarge)) return false
1655
+ return (disk ? disk.key : undefined) === this.lastKnown.get(rel)
1778
1656
  }
1779
1657
 
1780
- /**
1781
- * The folder follows its branch's square in place (session-follow.js, at layout 3): from now on
1782
- * its block takes every change, so the session's own sync of the folder holds: nothing goes to
1783
- * the read-only branch document, and no git-mode upstream work runs (no fetch, fast-forward or
1784
- * merge into uncommitted work, no boxes). Called before the block opens, so nothing slips through.
1785
- */
1786
- enterSquare (at) {
1787
- if (this.inSquare && this.inSquare.square === at.square) return
1788
- this.inSquare = { square: at.square, since: Date.now() }
1789
- clearTimeout(this.flushTimer)
1790
- this.flushTimer = null
1791
- this.pending.clear()
1792
- this.setGitAside()
1658
+ setHold (kind, extra = {}) {
1659
+ // A move to another branch ends only once the folder is there (finishMove): git at work meanwhile doesn't change it.
1660
+ if (this.hold && (this.hold.kind === kind || this.hold.kind === 'switching')) return
1661
+ // since: when the folder was first held, kept across kinds.
1662
+ this.hold = { kind, since: this.hold ? this.hold.since : Date.now(), ...extra }
1663
+ this.emit('hold', this.hold)
1793
1664
  this.scheduleStatusWrite()
1794
1665
  }
1795
1666
 
1796
- /** In a quilt nobody uses git: the folder's .git goes into .quilt while it follows its square (session-follow.js), and git-mode work stops. */
1797
- setGitAside () {
1798
- let r
1799
- try { r = setGitAside(this.root, { branch: this.branchKey() }) } catch (err) { this.log(`⚠️ couldn't set git aside in this folder (${err.message}); git still works here, but the session's code history is in Seam`); return }
1800
- if (r.both) this.log('⚠️ a new .git appeared in this folder while it follows its square; the one set aside is kept in .quilt/git-before-seam')
1801
- if (r.moved || r.already) this.gitAside = gitAsideOf(this.root)
1802
- if (r.moved) this.log('🧵 git is set aside in this folder while it follows its square (in .quilt/git-before-seam): in a quilt, Seam keeps the history. It comes back if the session goes back to its branches.')
1803
- if (r.worktrees) {
1804
- const n = r.worktrees.length
1805
- this.log(`🧵 ${n} other worktree${n === 1 ? '' : 's'} of this repository (${r.worktrees.slice(0, 5).join(', ')}${n > 5 ? `, and ${n - 5} more` : ''}) keep using git while this folder follows its square: each one's .git file points at this folder's .git in .quilt/git-before-seam meanwhile, and goes back as it was with it.`)
1806
- }
1807
- if (this.gitWatcher) { const w = this.gitWatcher; this.gitWatcher = null; Promise.resolve(w.close()).catch(() => {}) }
1808
- clearInterval(this.upstreamPoll)
1809
- this.upstreamPoll = null
1810
- this.git = null
1667
+ releaseHold () {
1668
+ this.hold = null
1669
+ clearTimeout(this.settleTimer); this.settleTimer = null
1670
+ this.emit('hold', null)
1671
+ this.scheduleStatusWrite()
1811
1672
  }
1812
1673
 
1813
- /** The .git set aside comes back (before git-mode sync resumes), and git is watched again. */
1814
- async gitBack () {
1815
- if (!gitAsideOf(this.root)) { this.gitAside = null; return false }
1816
- let back = false
1817
- try { back = putGitBack(this.root) } catch (err) { this.log(`⚠️ couldn't put git back in this folder (${err.message}); it is in .quilt/git-before-seam`); return false }
1818
- if (!back) { this.log('⚠️ this folder has a new .git, so the one set aside stays in .quilt/git-before-seam'); return false }
1819
- this.gitAside = null
1820
- this.log('git is back in this folder.')
1821
- this.scheduleStatusWrite()
1822
- return true
1674
+ /** (Re)arms the hold's timer: it ends GIT_SETTLE_MS after the last file or git event. */
1675
+ settleHoldSoon () {
1676
+ if (!this.hold || this.hold.kind === 'switching' || this.stopped) return
1677
+ clearTimeout(this.settleTimer)
1678
+ const gen = ++this.settleGen
1679
+ this.settleTimer = setTimeout(() => {
1680
+ this.settleTimer = null
1681
+ this.gitTask(() => this.onSettled(gen)).catch((err) => {
1682
+ this.log(`could not settle: ${err.message}`)
1683
+ this.settleHoldSoon() // every hold has a way out: asked again
1684
+ })
1685
+ }, GIT_SETTLE_MS)
1686
+ this.settleTimer.unref()
1687
+ }
1688
+
1689
+ /** Whether a hold is on that a settle may end now. */
1690
+ settleable () {
1691
+ return !!this.hold && this.hold.kind !== 'switching' && !this.stopped
1823
1692
  }
1824
1693
 
1825
1694
  /**
1826
- * Back from the square (the session went back to layout 2): the old sync resumes. What the folder
1827
- * holds now that differs from the branch document (the square's work, the same on every member's
1828
- * folder) is shared as one edit from all of them (same-edit.js), then git-mode work carries on.
1829
- * `writers` (path -> name, who last wrote it in the square: live-square.js lastWriters): only that
1830
- * member's folder boxes a returning file. Whichever folder ingested it first used to, so a member
1831
- * who reached the session first held another's work, and the writer's next edit reached nobody.
1695
+ * The folder has been quiet since git touched it. Still at work: looked at again later. On another
1696
+ * branch (or commit) now: the folder moves there (followHead). Otherwise it is still on its branch:
1697
+ * the hold ends, and what changed meanwhile is shared or written out (resumeHeld).
1698
+ * `gen`: the settleHoldSoon that armed it. A later one (a file or git event since) means not settled yet.
1832
1699
  */
1833
- async leaveSquare ({ writers = null } = {}) {
1834
- if (!this.inSquare) return
1835
- this.unfollowSquareDoc()
1836
- // git first: git-mode sync resumes on a folder git knows again.
1837
- await this.gitBack()
1838
- this.inSquare = null
1839
- // The block's record of the folder goes too: after branches, a later switch starts from the session's sync, not from it.
1840
- try { fs.rmSync(path.join(this.stateDir, 'block.json'), { force: true }) } catch {}
1841
- const moved = this.squareBranch && this.squareBranch !== this.branchKey()
1842
- this.squareBranch = null
1843
- if (moved) this.queue(HEAD_CHANGED)
1844
- else {
1845
- for (const rel of new Set([...walk(this.root, this.ig), ...this.lastKnown.keys()])) {
1846
- if (!this.syncable(rel) || this.untouchedHere(rel)) continue
1847
- try { this.ingest(rel, { same: true, box: !!(writers && writers.get(rel) === this.name) }) } catch (err) { this.log(`could not sync ${rel}: ${err.message}`) }
1700
+ async onSettled (gen = this.settleGen) {
1701
+ if (!this.settleable()) return
1702
+ if (this.gitBusy() === 'index-lock' && Date.now() - this.lastFileEventAt >= STALE_LOCK_MS) {
1703
+ // Only the index lock, there a while, and the tree quiet as long (a long checkout writes files
1704
+ // all along): a git that crashed may have left it.
1705
+ const stamp = await leftoverLock(this.root)
1706
+ if (!this.settleable()) return
1707
+ if (stamp) {
1708
+ this.leftoverLock = stamp
1709
+ this.log('⚠️ a leftover .git/index.lock is being ignored; delete it if git complains')
1848
1710
  }
1849
1711
  }
1850
- this.scanDisk({ baseline: true })
1851
- this.scheduleStatusWrite()
1712
+ const head = await this.headAt()
1713
+ if (!this.settleable()) return
1714
+ // Still mid-operation, or a file or git event since this settle's timer was armed: looked at again later.
1715
+ const busy = this.gitBusy()
1716
+ if (busy || gen !== this.settleGen) {
1717
+ // A rebase or a bisect can stay open for a long time (a conflict to resolve): said once, to the person and their AI.
1718
+ if (busy && busy !== 'index-lock' && !this.hold.said && Date.now() - this.hold.since >= HOLD_SAY_MS) {
1719
+ this.hold.said = true
1720
+ const text = `git is in the middle of a ${busy} in this folder, so nothing here is shared and nothing from the session is written here until it is finished (or aborted).`
1721
+ this.log(`⏸️ ${text}`)
1722
+ this.notice(text)
1723
+ }
1724
+ this.settleHoldSoon()
1725
+ return
1726
+ }
1727
+ if (!head || head.key !== headName(this.root)) {
1728
+ // HEAD can't be read (or moved while it was): nothing is shared until it can. Asked again, for good.
1729
+ if (!head && ++this.gitFailures === GIT_FAILURES_TO_SAY) this.log('⚠️ Quilt can\'t read git here; this folder stays paused')
1730
+ this.settleHoldSoon()
1731
+ return
1732
+ }
1733
+ this.gitFailures = 0
1734
+ if (head.key !== this.git.key) {
1735
+ // On another branch (or a detached commit) now: the folder follows it there.
1736
+ this.followHead(head.key)
1737
+ return
1738
+ }
1739
+ this.git = head
1740
+ this.gitSeen = head
1741
+ // What git wrote is accounted for here: the next flush is an edit unless git moves again.
1742
+ this.gitIndex = indexStamp(this.root)
1743
+ this.headChangedAt = 0
1744
+ const late = new Set(this.heldPaths)
1745
+ this.heldPaths.clear()
1746
+ // Started on another branch and back on the saved one before the move ran: changes made while Quilt was off were never seen.
1747
+ if (this.rejoin) for (const rel of [...this.sharedPaths(), ...walk(this.root, this.ig)]) late.add(rel)
1748
+ this.rejoin = false
1749
+ this.releaseHold()
1750
+ this.resumeHeld([...late])
1852
1751
  }
1853
1752
 
1854
1753
  /**
1855
- * Whether the folder's copy of `rel` changed since the session last synced it (for the square's
1856
- * first look at the folder, live-block.js adopt). A folder never synced has no edits of its own.
1754
+ * The hold is over and the folder is still on its branch. Each path that changed meanwhile: where
1755
+ * the disk is as Quilt left it, the session's version is written out; where it changed here (git
1756
+ * rewrote it, or someone saved it), it is taken in as an edit, merged with the session's as any save is.
1857
1757
  */
1858
- editedSinceSync (rel) {
1859
- if (!this.lastKnown.size) return false
1860
- const k = this.diskKey(rel)
1861
- if (k === undefined) return true // a link, or too large for the session: the folder's own
1862
- return this.lastKnown.has(rel) ? k !== this.lastKnown.get(rel) : k !== null
1758
+ resumeHeld (paths) {
1759
+ for (const rel of paths) {
1760
+ if (!this.syncable(rel) || this.merging.has(rel)) continue
1761
+ if (this.untouchedHere(rel)) this.tryWrite(rel)
1762
+ else this.ingestAll([rel])
1763
+ }
1863
1764
  }
1864
1765
 
1865
- /**
1866
- * Whether `rel` was someone else's box in this folder before the move (ghost): the folder kept its own
1867
- * copy (git's, moved on by pulls) while the session held the box's, so the square's first look puts the
1868
- * box's change onto the folder's copy (live-block.js combineAway), from what everyone had when it began.
1869
- */
1870
- boxedHere (rel) { return this.boxBase.has(rel) }
1766
+ // ------------------------------------------------------------ branches --
1767
+ // Uncommitted work git carries over in a checkout is the old branch's (the session has it
1768
+ // there): on a branch the session already has, Quilt writes that branch's version over it; a
1769
+ // branch new to the session starts from the folder as git left it, carried work included.
1770
+ // Nothing is synced branch on branch.
1871
1771
 
1872
1772
  /**
1873
- * Whether the session held `rel` back from this folder before the move: someone else's box here (the
1874
- * folder kept git's copy, or none for a new file), or a change still waiting for whoever held the file
1875
- * (an open merge record: deleted or changed offline while another held it). The folder's lack of it
1876
- * at the square's first look is then not its deletion.
1773
+ * At start, before captureOffline: git has the folder on another branch than the one this session
1774
+ * last synced (a checkout while Quilt was off). Its tree is then that other branch's, not the
1775
+ * saved branch's work plus offline edits, so nothing is captured from it. The folder joins the
1776
+ * saved branch held, and moves to where git has it once the relay has synced (start: followHead).
1877
1777
  */
1878
- heldBackHere (rel) {
1879
- if (this.boxBase.has(rel)) return true
1880
- try { return this.mergeList().some((m) => m && m.path === rel && m.state !== 'done') } catch { return false }
1881
- }
1882
-
1883
- /** Whether the session synced `rel` with this folder (the square's first look takes a file it has as git or the session left it for no edit). */
1884
- syncedHere (rel) {
1885
- if (!this.lastKnown.has(rel) || this.boxBase.has(rel)) return false
1886
- // A large file in the session's storage is not in the square (the relay can't read its bytes, so the
1887
- // move left it out and named it): the folder's copy is what puts it there, never the square's absence.
1888
- const b = this.blobs && this.blobs.get(rel)
1889
- return !(b && b.stored)
1778
+ startAway () {
1779
+ const saved = this.savedGit
1780
+ if (!saved || !this.git || this.git.key === saved.key) return false
1781
+ const at = this.git.key
1782
+ this.git = { key: saved.key, branch: saved.key.startsWith('@') ? null : saved.key, sha: saved.sha }
1783
+ this.gitSeen = this.git
1784
+ // An unfinished offline merge's bases are no bases for this move; left, the next start would read them.
1785
+ fs.rmSync(this.heldBasesFile, { force: true })
1786
+ // What the folder had of the saved branch: the session's version at the last stop.
1787
+ for (const rel of this.sharedPaths()) {
1788
+ const k = this.sharedKey(rel)
1789
+ if (this.syncable(rel) && k !== undefined) this.lastKnown.set(rel, k)
1790
+ }
1791
+ this.rejoin = true
1792
+ this.hold = { kind: 'switching', since: Date.now(), to: at }
1793
+ this.resumeAway = at
1794
+ return true
1890
1795
  }
1891
1796
 
1892
1797
  /**
1893
- * The paths whose edits this folder made into its branch document but the relay does not hold
1894
- * (session-follow.js unsentPaths): at layout 3 the read-only document refused them, so the
1895
- * folder's copy is its own work, never the switch's older copy. Empty with nothing refused;
1896
- * null when the relay can't say (an older relay).
1798
+ * git moved HEAD to branch `to` (a checkout in a terminal or by an agent, or while Quilt was
1799
+ * stopped): the folder moves there.
1897
1800
  */
1898
- async unsentPaths () {
1899
- if (!this.bdoc || !this.conn || !this.conn.connected || this.conn.branchKey === null) return null
1900
- const r = await this.conn.branchRequest({ op: 'state', branch: this.conn.branchKey })
1901
- const bytes = (b64) => new Uint8Array(Buffer.from(String(b64 || ''), 'base64'))
1902
- return unsentPaths(this.bdoc, bytes(r.sv), bytes(r.deleted))
1801
+ followHead (to) {
1802
+ if (!to || this.stopped || this.following || this.pendingMove || to === this.branch) return
1803
+ this.following = to
1804
+ this.setHold('switching', { to }) // nothing more is shared on the old branch from here
1805
+ this.gitTask(() => this.moveTo(to))
1806
+ // The branch it failed on: a move can retarget on the way (moveTo, abandonMove).
1807
+ .catch((err) => this.moveFailed((this.pendingMove && this.pendingMove.to) || (this.hold && this.hold.to) || to, err))
1808
+ .finally(() => { this.following = null })
1903
1809
  }
1904
1810
 
1905
1811
  /**
1906
- * The folder's block on its square is open: who changed what (the chronology, Changes) is kept in
1907
- * the square's live document from now on. It came with the branch's at the switch and goes on from
1908
- * square to square (session-layout3.js copyIntoLive, carryLive), so a file's History, Changes and
1909
- * the Files tree carry on where the branch left them.
1812
+ * A move that didn't finish: the folder stays held (nothing of either branch reaches the
1813
+ * other) and recheckMove tries again, less and less often, or follows git wherever it goes
1814
+ * next. A refusal the relay will repeat (a viewer starting a branch, the branch limit) is
1815
+ * said once, with what to do; checking the old branch out again resumes sync there.
1910
1816
  */
1911
- followSquareDoc (doc) {
1912
- if (!doc || this.squareDoc === doc) return
1913
- this.squareDoc = doc
1914
- this.history = new HistoryLog(doc, doc.getArray('history'), { origin: LOCAL })
1915
- this.tallies = doc.getMap('changes')
1817
+ moveFailed (to, err) {
1818
+ if (this.stopped || !this.hold || this.hold.kind !== 'switching') return
1819
+ const msg = (err && err.message) || String(err)
1820
+ const connected = !!(this.conn && this.conn.connected)
1821
+ const refused = connected && !/did not answer|not connected|disconnected/.test(msg)
1822
+ // Offline is no try: reconnecting tries again at once (start: the 'connected' status clears moveRetryAt).
1823
+ if (connected) this.moveTries = (this.moveTries || 0) + 1
1824
+ this.moveRetryAt = !connected ? 0 : Date.now() + (refused ? MOVE_RETRY_MAX_MS : Math.min(MOVE_RETRY_MAX_MS, RETRY_MS * 2 ** (this.moveTries - 1)))
1825
+ this.hold.waiting = refused ? 'refused' : 'retrying'
1826
+ this.emit('hold', this.hold)
1916
1827
  this.scheduleStatusWrite()
1917
- }
1918
-
1919
- /** Back on the branch's document (the block closed). */
1920
- unfollowSquareDoc () {
1921
- if (!this.squareDoc) return
1922
- this.squareDoc = null
1923
- if (this.bdoc) { this.history = new HistoryLog(this.bdoc, this.bdoc.getArray('history'), { origin: LOCAL }); this.tallies = this.bdoc.getMap('changes') }
1924
- this.scheduleStatusWrite()
1925
- }
1926
-
1927
- /**
1928
- * Edits this folder made in its square, as its block took them in (live-block.js onEdits): on
1929
- * record as this member's, the same as on a branch (recordActivity: the chronology and Changes in
1930
- * the square's live document `doc`, the room's activity, this member's presence).
1931
- */
1932
- squareEdits (list, doc, held = null) {
1933
- this.followSquareDoc(doc)
1934
- for (const e of list) {
1935
- const texts = typeof e.before === 'string' || typeof e.after === 'string' ? { before: e.before, after: e.after } : undefined
1936
- try { this.recordActivity(e.path, e.kind, e.detail || '', texts, { activity: false }) } catch (err) { this.emit('debug', `could not record ${e.path}: ${err.message}`) }
1937
- this.noteMyEdit(e.path)
1938
- // Our AI's edits here count for its working state, as on a branch; a square is this member's own, so nothing is boxed.
1939
- if (e.kind !== 'deleted' && this.aiMayBeEditing()) this.aiEdits.set(e.path, Date.now())
1828
+ const said = `${to}\0${refused ? msg : ''}`
1829
+ if (this.moveSaid === said) return
1830
+ this.moveSaid = said
1831
+ if (refused) {
1832
+ const text = `The session can't take ${to}: ${msg}. This folder isn't syncing while it's on ${to}; check out ${this.branch} again in git to keep syncing there.`
1833
+ this.log(`⚠️ ${text}`)
1834
+ this.notice(text)
1835
+ } else {
1836
+ this.log(`⚠️ You're on ${to} in git, but its work in the session can't be loaded yet (${msg}). This folder waits and tries again.`)
1940
1837
  }
1941
- // The room's activity names a file the relay finds in the square (server.js onBranch): sent once the relay holds the edit, over the block's connection.
1942
- const push = () => { if (this.stopped) return; for (const e of list) { try { this.pushActivity(e.path, e.kind, e.detail || '') } catch {} } }
1943
- if (held) held().then(push, push); else push()
1944
1838
  }
1945
1839
 
1946
- /**
1947
- * The text the session last synced for `rel` (the square's first look combines an edit made while
1948
- * away with the square's), or null: a file a diff branch leaves to git is git's, read from
1949
- * the .git set aside.
1950
- */
1951
- async syncedText (rel) {
1952
- // Someone else's box: what everyone had when it began (ghost), not the folder's own copy since.
1953
- if (this.boxBase.has(rel)) { const b = this.boxBase.get(rel); return b && typeof b.text === 'string' ? b.text : null }
1954
- const k = this.lastKnown.get(rel)
1955
- if (k !== undefined) return typeof k === 'string' && !/^bin:[0-9a-f]{40}$/.test(k) ? k : null
1956
- return null
1957
- }
1958
-
1959
- /** Whether the session never syncs anything in folder `rel` (.git, .quilt, node_modules, ignored ones): the block's walk skips it. */
1960
- ignoredDir (rel) { return !isSafeRelPath(rel) || isIgnored(this.ig, rel) || this.ig.ignores(`${rel}/`) }
1961
-
1962
- /** The branch the folder is on for its square: git's, once git moved it while following (squareHeadMoved). */
1963
- squareBranchKey () { return this.squareBranch || this.branchKey() }
1964
-
1965
- /** Reads of the quilt for the folder's block: through the relay, with the room's read token (session-follow.js relayReader). */
1966
- squareReader () { return relayReader(this.conn) }
1967
-
1968
- /**
1969
- * This member to Seam (seam-access.js): SEAM_TOKEN, else the Quilt sign-in the session runs as
1970
- * (its person's, or its agent's key traded for an agent token). The Seam tools (control.js), the
1971
- * folder's block and `quilt commit` all use this one, so they act as the same member.
1972
- */
1973
- seamMember () {
1974
- if (!this.seam) this.seam = seamAccess({ api: () => this.seamApiUrl ?? appSeamUrl(), credential: () => sessionCredential({ apiAuth: this.apiAuth, account: readAccount })() })
1975
- return this.seam
1840
+ /** While a move is unfinished: where is HEAD now? Back on the folder's branch resumes it; elsewhere is followed (backing off on the same branch). */
1841
+ async recheckMove () {
1842
+ if (!this.hold || this.hold.kind !== 'switching' || this.following || this.stopped) return null
1843
+ const at = await this.headNow()
1844
+ if (this.stopped || !at || this.following) return null
1845
+ const m = this.pendingMove
1846
+ const target = m ? m.to : this.hold.to
1847
+ if (at !== this.branch && at === target && Date.now() < (this.moveRetryAt || 0)) return null // tried a moment ago
1848
+ this.following = at
1849
+ try {
1850
+ if (m) return await (m.to === at ? this.finishMove(m) : this.abandonMove(m, at))
1851
+ if (at === this.branch) return this.settleBack()
1852
+ this.hold.to = at
1853
+ return await this.moveTo(at)
1854
+ } finally { this.following = null }
1976
1855
  }
1977
1856
 
1978
- /** A Seam client as this member for the square the folder follows (seamMember), for uploads and commits; throws with why when there is none. */
1979
- async seamClientNow () {
1980
- if (!this.quilt || !this.quilt.id) throw new Error('This session is not a quilt.')
1981
- const f = this.squareFollower
1982
- const square = (f && f.here && f.here.square) || (f && f.following && f.following.square) || null
1983
- return (await this.seamMember().client(this.quilt.id, square ? [square] : [])).client
1857
+ /** recheckMove, as git work; what fails is a move that failed again. */
1858
+ recheckSoon () {
1859
+ this.gitTask(() => this.recheckMove()).catch((err) => this.moveFailed(this.pendingMove ? this.pendingMove.to : this.hold && this.hold.to, err))
1984
1860
  }
1985
1861
 
1986
- /** The same, or null without one (the block reads through the relay meanwhile). */
1987
- async seamWriteClient () {
1988
- try { return await this.seamClientNow() } catch { return null }
1862
+ /** HEAD is back on the folder's branch before it moved: the trip ends like any git work there (onSettled). */
1863
+ settleBack () {
1864
+ this.moveTries = 0
1865
+ this.moveSaid = null
1866
+ this.hold = { kind: 'busy', since: this.hold ? this.hold.since : Date.now() }
1867
+ this.emit('hold', this.hold)
1868
+ this.scheduleStatusWrite()
1869
+ this.settleHoldSoon()
1870
+ return null
1989
1871
  }
1990
1872
 
1991
- /** `quilt commit`: the square's live work, committed from this folder (session-follow.js). */
1992
- async squareCommit (message) {
1993
- if (!this.squareFollower) throw new Error('This folder does not follow a square: the session is not a quilt at layout 3.')
1994
- // As this member, the same as seam_commit's (a cloud AI's agent token renews itself).
1995
- if (this.squareFollower.here && this.squareFollower.here.block) this.squareFollower.here.block.client = await this.seamClientNow()
1996
- const r = await this.squareFollower.commit({ message })
1997
- if (r && r.nothing) return { nothing: true, text: 'Nothing to commit: the square has no work since its last commit.' }
1998
- const head = r && r.square && r.square.head
1999
- // Paths with an open held conflict stayed live (live-block.js commit): said, with how to resolve them.
2000
- const left = r && r.left_held && r.left_held.length ? ` ${heldLandingNote(r.left_held)}` : ''
2001
- return { ...r, text: `Committed to square ${squareShort(this.squareFollower.here.square)}${head ? ` as ${String(head).slice(0, 12)}` : ''}.${left}` }
1873
+ /** This folder's saves that are at the relay and not answered yet (relayIngest) have their answers, or MOVE_WRITES_WAIT_MS has passed. */
1874
+ async relayWritesDone () {
1875
+ const until = Date.now() + MOVE_WRITES_WAIT_MS
1876
+ while (this.relayWriting.size && Date.now() < until && !this.stopped) await new Promise((resolve) => setTimeout(resolve, 20))
2002
1877
  }
2003
1878
 
2004
1879
  /**
2005
- * { branch } when this folder's branch has no square in the quilt at layout 3 (a branch made after the
2006
- * switch, or main with nothing to adopt): its edits reach nobody until one is opened for it. Else null.
1880
+ * Moves this folder to branch `to`, which git has already checked out: every change on the
1881
+ * branch it leaves is confirmed in the session where it can be, that branch's document is kept
1882
+ * aside here (parkLocalState), and finishMove joins the new one. Runs as git work.
2007
1883
  */
2008
- squareless () {
2009
- if (!this.quilt || this.quilt.layout !== 3 || !this.root) return null
2010
- const branch = this.squareBranchKey()
2011
- if (squareFor(this.quilt, branch)) return null
2012
- // ∅ is a folder with no git branch: the quilt's main line. `error`: why the square couldn't be opened by itself.
2013
- return { branch: branch === DEFAULT_KEY ? 'main' : branch, ...(this.squareOpenError ? { error: this.squareOpenError } : {}) }
1884
+ async moveTo (to) {
1885
+ const from = this.branch
1886
+ const at = await this.headNow()
1887
+ if (this.stopped) return null
1888
+ if (at === from) return this.settleBack()
1889
+ if (at && at !== to) { to = at; if (this.hold) this.hold.to = at }
1890
+ // A save of this folder's still on its way to the relay is the branch's it was made on: its answer first.
1891
+ await this.relayWritesDone()
1892
+ if (this.stopped) return null
1893
+ // The commit the branch it leaves is at now (commits made since the folder came to it included).
1894
+ const fromSha = (this.git && this.git.branch && await branchTip(this.root, this.git.branch)) || (this.git ? this.git.sha : null)
1895
+ // path -> the old branch's version as this folder had it (as lastKnown keys it), to tell what git carried over.
1896
+ // A change from the session that came while the folder was held is not on its disk: not what git carried.
1897
+ const oldKeys = new Map()
1898
+ for (const rel of this.sharedPaths()) if (this.syncable(rel)) oldKeys.set(rel, this.lastKnown.has(rel) ? this.lastKnown.get(rel) : this.sharedKey(rel) ?? null)
1899
+ // What doesn't reach the relay now stays in `from`'s document kept here, and goes out when the folder is back.
1900
+ try { await this.conn.confirmBranch() } catch (err) { this.emit('debug', `confirming ${from} before moving: ${err.message}`) }
1901
+ if (this.stopped) return null
1902
+ this.ig = loadIgnore(this.root) // the checkout's own ignore files
1903
+ const carried = await this.carriedFrom(oldKeys, fromSha)
1904
+ if (this.stopped) return null
1905
+ this.parkLocalState(from)
1906
+ const doc = new Y.Doc()
1907
+ const left = this.unparkLocalState(to, doc)
1908
+ return this.finishMove({ from, to, doc, left, epoch: left ? this.parkedEpoch(to) : null, carried })
2014
1909
  }
2015
1910
 
2016
1911
  /**
2017
- * A folder that may change files never waits on a button: when its branch has no square, one is opened
2018
- * for it by itself (when the quilt changes, on connecting, and every minute after a try that failed),
2019
- * with what is on disk as its work. Only a failure is shown, with why and the button to try again.
1912
+ * Joins the new branch's document, writes it onto the folder and goes live there. HEAD is
1913
+ * read again before and after the join: if git has moved on (a quick checkout back, or a
1914
+ * retry long after), this move is dropped without writing anything and the folder follows
1915
+ * HEAD from where it is. Tried again (recheckMove) when the relay can't load the branch yet.
2020
1916
  */
2021
- ensureSquare () {
2022
- if (this.stopped || this.openingSquare || !this.access || this.access.role === 'viewer' || !this.squareless()) return
2023
- if (!this.conn || !this.conn.connected || Date.now() < (this.squareAutoAt || 0)) return
2024
- this.squareAutoAt = Date.now() + SQUARE_AUTO_RETRY_MS
2025
- this.openBranchSquare(this.squareBranchKey(), { quiet: false }).then(
2026
- () => { this.squareOpenError = null; this.scheduleStatusWrite() },
2027
- (err) => { this.squareOpenError = String((err && err.message) || err).slice(0, 300); this.scheduleStatusWrite() }
2028
- )
1917
+ async finishMove (m) {
1918
+ const { from, to, carried } = m
1919
+ let { doc, left } = m
1920
+ let at = await this.headNow()
1921
+ if (this.stopped) return null
1922
+ if (at !== to) return this.abandonMove(m, at)
1923
+ let head = await this.headAt()
1924
+ let reply
1925
+ let fresh = null // the relay's document of `to` is newer than the one this folder kept
1926
+ try {
1927
+ // base: the commit a branch new to the session starts from. It starts as a full document, made from the folder.
1928
+ reply = await this.conn.joinBranch(to, doc, { ...(head && head.sha ? { base: head.sha } : {}), epoch: m.epoch || null, onStale: () => (fresh = new Y.Doc()) })
1929
+ await this.conn.waitForBranchSync()
1930
+ } catch (err) {
1931
+ if (fresh) fresh.destroy()
1932
+ this.pendingMove = m
1933
+ throw err
1934
+ }
1935
+ if (fresh) {
1936
+ // `to` was removed from the session and started again since this folder left it: what it
1937
+ // kept of the old document is dropped, and the folder arrives as one that was never there.
1938
+ doc.destroy()
1939
+ m.doc = doc = fresh
1940
+ m.left = left = null
1941
+ m.epoch = null
1942
+ const said = `${to} was removed from the session (nobody was on it for 30 days) and has been started again since, so what this folder had kept of it is not brought back; the session's files there are on disk.`
1943
+ this.log(`⚠️ ${said}`)
1944
+ this.notice(said)
1945
+ }
1946
+ if (this.stopped) return null
1947
+ head = await this.headAt()
1948
+ at = head ? head.key : null
1949
+ if (this.stopped) return null
1950
+ if (at !== to) return this.abandonMove(m, at)
1951
+ this.pendingMove = null
1952
+ this.moveTries = 0
1953
+ this.moveSaid = null
1954
+ const old = this.bdoc
1955
+ this.bindBranchDoc(doc)
1956
+ old.destroy()
1957
+ this.branch = reply.branch || to
1958
+ this.branchEpoch = typeof reply.epoch === 'string' && reply.epoch ? reply.epoch : null
1959
+ this.branchForm = reply.form === 'diff' ? 'diff' : 'full'
1960
+ this.diffBase = reply.form === 'diff' && typeof reply.diffBase === 'string' ? reply.diffBase : null
1961
+ this.git = head
1962
+ this.gitSeen = head
1963
+ this.rejoin = false
1964
+ this.observeBranch()
1965
+ this.announceBranch()
1966
+ let entries = []
1967
+ let movedOn = null
1968
+ try { entries = await this.arrive({ created: !!reply.created, left, carried }) } finally {
1969
+ // git moved again while the branch was written: still held, and the folder follows on (below).
1970
+ const now = headName(this.root)
1971
+ if (now && now !== this.git.key && !this.stopped && this.hold) { movedOn = now; this.hold.to = now }
1972
+ if (!movedOn) {
1973
+ // What git and the move wrote is accounted for: the next flush is an edit unless git moves again.
1974
+ const late = [...this.heldPaths]
1975
+ this.heldPaths.clear()
1976
+ this.releaseHold()
1977
+ this.gitIndex = indexStamp(this.root)
1978
+ this.headChangedAt = 0
1979
+ this.scanDisk({ baseline: true })
1980
+ this.requeue(late.filter((rel) => this.syncable(rel) && !this.untouchedHere(rel)))
1981
+ }
1982
+ }
1983
+ if (this.stopped) return null
1984
+ if (entries.length && !movedOn) {
1985
+ this.mergeHeld(entries).then(({ conflicts }) => {
1986
+ if (conflicts) this.log(`🔀 ${conflicts} file${conflicts === 1 ? '' : 's'} you changed on ${to} clash with the session's; see Merges.`)
1987
+ }).catch((err) => this.log(`could not merge: ${err.message}`))
1988
+ } else for (const e of entries) this.merging.delete(e.rel)
1989
+ this.saveStateNow()
1990
+ fs.rmSync(this.branchStateDir(to), { recursive: true, force: true }) // in state.bin from here
1991
+ const note = this.moveNote({ from, to: this.branch, created: !!reply.created, carried: [...carried.keys()] })
1992
+ this.log(`🔀 ${note}`)
1993
+ // Agents working in this folder hear it with their next answer; the room sees it in the activity log.
1994
+ this.notice(`This folder moved from ${from} to ${this.branch} (a checkout in git): its files are ${this.branch}'s in the session now, and ${from}'s work stays in the session on ${from}.`)
1995
+ this.doc.transact(() => {
1996
+ this.activity.push([{ by: this.name, path: '', kind: 'switched', detail: '', branch: this.branch, from, ts: Date.now() }])
1997
+ if (this.activity.length > 300) this.activity.delete(0, this.activity.length - 300)
1998
+ }, LOCAL)
1999
+ this.emit('branch', this.branch)
2000
+ this.scheduleStatusWrite()
2001
+ if (movedOn) { this.following = movedOn; return this.moveTo(movedOn) }
2002
+ return { branch: this.branch, note }
2029
2003
  }
2030
2004
 
2031
2005
  /**
2032
- * The app's Open a square (status `squareless`): the same ask the first refused write makes
2033
- * (openBranchSquare, the relay's quilt-open, as this member), with what went wrong said, not only
2034
- * logged. { square, text }.
2006
+ * git moved on before a move finished: nothing of it was written. The connection goes back
2007
+ * to the folder's branch if the join had moved it, and the folder settles there (HEAD came
2008
+ * back) or moves to wherever HEAD is now.
2035
2009
  */
2036
- async openSquareHere () {
2037
- if (!this.quilt || this.quilt.layout !== 3 || !this.quilt.id) throw new Error('This session\'s code is not in Seam.')
2038
- if (!this.conn || !this.conn.connected) throw new Error('This folder is not connected to the relay; try again in a moment.')
2039
- const branch = this.squareBranchKey()
2040
- const at = squareFor(this.quilt, branch)
2041
- if (at) return { square: at.square, text: `${branch} has a square already: ${squareShort(at.square)}.` }
2042
- if (this.openingSquare) throw new Error(`A square for ${branch} is being opened already; your folder follows it in a moment.`)
2043
- let r
2044
- try { r = await this.openBranchSquare(branch, { quiet: false }) } catch (err) {
2045
- // A branch the relay never had (checked out in git after the move): nothing to start its square from.
2046
- if (/is not one of this session's branches/.test(err.message)) throw new Error(`${branch} was made after the session's code moved into Seam, so the session has nothing of it to start a square from. Check out a branch the session has (main, say) and your folder follows that branch's square; or ask the session's owner.`)
2047
- throw err
2010
+ async abandonMove (m, at) {
2011
+ this.pendingMove = null
2012
+ m.doc.destroy()
2013
+ if (this.conn.branchKey !== this.branch) {
2014
+ this.conn.setBranch(this.branch, this.bdoc) // a reconnect meanwhile joins it again by itself
2015
+ this.conn.branchEpoch = this.branchEpoch // the document it holds, for that join (not the one it left)
2016
+ try {
2017
+ await this.conn.joinBranch(this.branch, this.bdoc)
2018
+ await this.conn.waitForBranchSync()
2019
+ } catch (err) { this.emit('debug', `rejoining ${this.branch}: ${err.message}`) }
2048
2020
  }
2049
- this.squareOpenError = null
2050
- return { square: r.square, text: r.opened ? `Opened square ${squareShort(r.square)} for ${branch}: your folder follows it in a moment, with your files as its work, and your edits reach everyone on it.` : `${branch} has a square already: ${squareShort(r.square)}; your folder follows it in a moment.` }
2021
+ if (this.stopped) return null
2022
+ if (!at || at === this.branch) return this.settleBack()
2023
+ if (this.hold) this.hold.to = at
2024
+ return this.moveTo(at)
2051
2025
  }
2052
2026
 
2053
2027
  /**
2054
- * The relay refused a write of this folder's to a read-only branch document (layout 3): said in
2055
- * the log, kept for status (quilt_status, the app), and told to this member's AI at its next call.
2028
+ * Writes the branch document onto a folder git has just put on that branch. A document new
2029
+ * to the session (or empty) is made from the folder as git left it instead, carried work
2030
+ * included. Otherwise what git carried over from the old branch (`carried`: path -> the
2031
+ * old branch's version, still on disk) gets this branch's version, or HEAD's when the
2032
+ * document hasn't the path: the old branch's work never enters this one. Any other path git
2033
+ * shows as changed (an edit made on this branch while Quilt wasn't looking) is merged into
2034
+ * the document: against the version this folder had when it last left the branch (`left`),
2035
+ * else HEAD's; returned as entries for mergeHeld. A file HEAD has that the document hasn't
2036
+ * is left as git has it, and not shared.
2056
2037
  */
2057
- noteReadOnly (r) {
2058
- if (!r || !r.why) return
2059
- this.readOnly = { branch: r.branch || '', ...(r.square ? { square: String(r.square) } : {}), why: String(r.why).slice(0, 500), at: Date.now() }
2060
- this.log(`⚠️ ${this.readOnly.why}`)
2061
- this.notice(this.readOnly.why)
2062
- this.scheduleStatusWrite()
2063
- if (r.noSquare) this.openBranchSquare(r.branch || this.branchKey()).catch(() => {})
2038
+ async arrive ({ created, left = null, carried = new Map() }) {
2039
+ // What this folder knew of the branch it left says nothing about this one.
2040
+ this.lastKnown.clear()
2041
+ this.storedOnDisk.clear()
2042
+ this.known = null
2043
+ this.writeFailed.clear()
2044
+ this.retry.clear()
2045
+ this.gitOnly.clear()
2046
+ this.clashed.clear()
2047
+ this.relayAgain.clear()
2048
+ this.relayLocal.clear()
2049
+ this.overwritten.close()
2050
+ if (created || (!this.files.size && !this.blobs.size && !(this.diffForm && this.gone.size))) {
2051
+ // What the folder brings to the session is its starting point, not a change anyone made.
2052
+ this.arriving = true
2053
+ this.seeding = true
2054
+ try { for (const rel of walk(this.root, this.ig)) this.ingest(rel) } finally { this.seeding = false; this.arriving = false }
2055
+ return []
2056
+ }
2057
+ // Carried, and still as git carried it (an edit made since is this branch's, and merges).
2058
+ const away = new Set([...carried].filter(([rel, key]) => { const d = this.readDisk(rel); return (d ? d.key : null) === key }).map(([rel]) => rel))
2059
+ const tree = await treeState(this.root, [])
2060
+ if (this.stopped) return []
2061
+ // git can't say what it changed: every path that differs from the session's is merged (a record at worst).
2062
+ const dirty = (tree
2063
+ ? [...tree.dirty].filter((rel) => this.syncable(rel))
2064
+ : [...new Set([...this.sharedPaths(), ...walk(this.root, this.ig)])].filter((rel) => {
2065
+ if (!this.syncable(rel)) return false
2066
+ const disk = this.readDisk(rel)
2067
+ return !(disk && (disk.skip || disk.tooLarge)) && (disk ? disk.key : undefined) !== this.sharedKey(rel)
2068
+ })).filter((rel) => !away.has(rel))
2069
+ const fromHead = [...away].filter((rel) => this.sharedKey(rel) === undefined) // the document hasn't it: HEAD's file
2070
+ // Carried, then edited since the checkout: only that edit is this branch's. Merged against the carried version.
2071
+ const editedSince = new Set(dirty.filter((rel) => carried.has(rel)))
2072
+ const ask = [...dirty, ...fromHead]
2073
+ const atHead = this.git && this.git.sha && ask.length ? await filesAt(this.root, this.git.sha, ask) : null
2074
+ const bins = new Map()
2075
+ for (const rel of [...fromHead, ...editedSince]) {
2076
+ const k = atHead ? atHead.get(rel) : null
2077
+ if (typeof k === 'string' && k.startsWith('bin:')) bins.set(rel, await blobAt(this.root, this.git.sha, rel))
2078
+ }
2079
+ if (this.stopped) return []
2080
+ const changed = new Set(dirty)
2081
+ const shared = this.sharedPaths()
2082
+ this.arriving = true
2083
+ try {
2084
+ this.writeBackAll([...shared].filter((rel) => this.syncable(rel) && !changed.has(rel)))
2085
+ // A diff branch: what the session deleted goes from the folder too (a change of the folder's own to one merges below).
2086
+ if (this.diffForm) this.writeBackAll([...this.gone.keys()].filter((rel) => this.syncable(rel) && !changed.has(rel) && !this.files.has(rel) && !this.blobs.has(rel)))
2087
+ for (const rel of fromHead) this.putHeadVersion(rel, atHead ? atHead.get(rel) : null, bins.get(rel))
2088
+ // HEAD's files the document hasn't: git's, not this folder's change, so not shared.
2089
+ for (const rel of walk(this.root, this.ig)) {
2090
+ if (shared.has(rel) || changed.has(rel) || this.lastKnown.has(rel) || !this.syncable(rel)) continue
2091
+ const disk = this.readDisk(rel)
2092
+ if (disk && !disk.skip && !disk.tooLarge) { this.lastKnown.set(rel, disk.key); this.gitOnly.set(rel, disk.key) }
2093
+ }
2094
+ } finally { this.arriving = false }
2095
+ const baseOf = (rel) => left && left.has(rel) ? left.get(rel) : atHead ? atHead.get(rel) ?? undefined : undefined
2096
+ const entries = []
2097
+ for (const rel of dirty) {
2098
+ if (!editedSince.has(rel)) { entries.push({ rel, base: baseOf(rel), via: 'hold' }); continue }
2099
+ // Merged with this branch's version (HEAD's file when its document hasn't the path): see mergeCarried.
2100
+ entries.push({ rel, base: carried.get(rel), via: 'hold', carried: true, head: atHead ? atHead.get(rel) : undefined, headBuf: bins.get(rel) })
2101
+ }
2102
+ for (const e of entries) this.merging.add(e.rel)
2103
+ return entries
2064
2104
  }
2065
2105
 
2066
2106
  /**
2067
- * The session owner's app renews the room's read token (every folder reads its square with it)
2068
- * when the relay says it is missing, refused, or ends within a month: the relay holds no
2069
- * credential that can (server.js readTokenState), the owner's sign-in can. Checked whenever the
2070
- * relay says something of the quilt and every few hours; tried at most once an hour.
2107
+ * A path git carried over from the old branch, edited after the checkout: only that edit is
2108
+ * this branch's. Merged three-way (base: the carried version; ours: the disk; theirs: this
2109
+ * branch's version, or HEAD's file when its document hasn't the path). Anything that doesn't
2110
+ * merge cleanly (a clash, a binary, a file this branch hasn't) is set aside: never a shared
2111
+ * merge record, which would carry the old branch's text into this one.
2071
2112
  */
2072
- async renewReadToken () {
2073
- const q = this.quilt
2074
- if (!q || q.layout !== 3 || !this.isOwner || !this.conn || !this.conn.connected || !appSeamUrl() || this.stopped) return null
2075
- if (!this.readRenewTimer) { this.readRenewTimer = setInterval(() => this.renewReadToken().catch(() => {}), READ_RENEW_CHECK_MS); this.readRenewTimer.unref?.() }
2076
- const r = q.read || {}
2077
- if (!(r.renew || (r.ends && r.ends - Date.now() < READ_RENEW_BEFORE_MS))) return null
2078
- if (this.readRenewAt && Date.now() - this.readRenewAt < READ_RENEW_RETRY_MS) return null
2079
- this.readRenewAt = Date.now()
2080
- try {
2081
- const { token } = await this.seamMember().client(q.id, [])
2082
- const a = await this.conn.branchRequest({ op: 'quilt-shadow', token, quilt: q.slug || q.id }, { timeoutMs: QUILT_MOVE_TIMEOUT_MS })
2083
- if (a.read && a.read.renewed) this.log(`🧵 made a new read token for ${q.slug || q.id}${a.read.until ? ` (until ${a.read.until.slice(0, 10)})` : ''}: every folder reads its square with it.`)
2084
- return a
2085
- } catch (err) {
2086
- this.log(`⚠️ couldn't renew the session's read token for ${q.slug || q.id} (${err.message}); folders can't read their squares without it. quilt session migrate --shadow ${q.slug || q.id} tries again.`)
2113
+ async mergeCarried ({ rel, base, head, headBuf }) {
2114
+ this.merging.delete(rel)
2115
+ const disk = this.readDisk(rel)
2116
+ if (disk && (disk.skip || disk.tooLarge)) return null
2117
+ const ours = disk ? disk.key : null
2118
+ const inDoc = this.sharedKey(rel) !== undefined
2119
+ if (!inDoc && head === undefined) {
2120
+ // git couldn't read HEAD's file (too large, a filter): left as it is, and not shared.
2121
+ if (disk) this.lastKnown.set(rel, disk.key)
2087
2122
  return null
2088
2123
  }
2124
+ const theirs = inDoc ? this.sharedKey(rel) : head // null: neither this branch nor its commit has it
2125
+ if (ours === theirs) { if (ours === null) this.lastKnown.delete(rel); else this.lastKnown.set(rel, ours); return null }
2126
+ if (ours === base) { this.putBranchVersion(rel, { inDoc, head, headBuf }); return null } // not edited after all
2127
+ if (theirs === null) { this.setAsideCarried(rel, { inDoc, head, headBuf, clash: false }); return null } // not on this branch
2128
+ // Edited here and changed on this branch too: combined by Quilt, as mergeOne does.
2129
+ const binary = [base, ours, theirs].some((k) => typeof k === 'string' && k.startsWith('bin:'))
2130
+ if (inDoc) return this.autoSettle({ rel, base, ours, theirs, theirsBy: this.lastEditorOf(rel), disk, binary })
2131
+ // This branch's commit has it, its document doesn't yet: the merge goes onto the disk, and is shared from there.
2132
+ if (ours === null) { this.putHeadVersion(rel, head, headBuf); return null }
2133
+ if (binary) return null // ours, edited after the checkout, is the newer version: it stays, and is shared from the disk
2134
+ const r = mergeAuto(base || '', ours, theirs, { oursNewer: true })
2135
+ this.writeFile(rel, resolveInside(this.root, rel), r.text)
2136
+ this.log(`🧵 ${rel}: your edit after switching to ${this.branch} is merged with ${this.branch}'s own change to it`)
2137
+ return 'merged'
2138
+ }
2139
+
2140
+ /** This branch's version of rel onto the disk: its document's, else HEAD's file, else none. */
2141
+ putBranchVersion (rel, { inDoc, head, headBuf }) {
2142
+ if (!inDoc) return this.putHeadVersion(rel, head, headBuf)
2143
+ const disk = this.readDisk(rel)
2144
+ if (disk && !disk.skip && !disk.tooLarge) this.lastKnown.set(rel, disk.key) // replaced without a copy here: setAsideCarried keeps one
2145
+ this.tryWrite(rel)
2146
+ }
2147
+
2148
+ /** A carried path edited after the checkout that can't merge: the folder's copy under .quilt/conflicts, this branch's version on disk, said once. */
2149
+ setAsideCarried (rel, { inDoc, head, headBuf, clash }) {
2150
+ let dest = null
2151
+ try {
2152
+ if (this.onDisk(rel)) {
2153
+ dest = path.join(this.stateDir, 'conflicts', `${Date.now()}`, ...rel.split('/'))
2154
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
2155
+ fs.copyFileSync(resolveInside(this.root, rel), dest)
2156
+ }
2157
+ } catch (err) { this.log(`could not keep a copy of ${rel}: ${err.message}`); return }
2158
+ this.putBranchVersion(rel, { inDoc, head, headBuf })
2159
+ const copy = dest ? `; your copy is in ${path.relative(this.root, dest).split(path.sep).join('/')}` : ''
2160
+ const text = clash
2161
+ ? `Your edit to ${rel} after switching to ${this.branch} and ${this.branch}'s own change to it are not combined on their own, so ${this.branch}'s version is on disk${copy}.`
2162
+ : `${rel} came over from the old branch in the checkout and isn't on ${this.branch}, so it's off the disk${copy}.`
2163
+ this.log(`📦 ${text}`)
2164
+ this.notice(text)
2165
+ }
2166
+
2167
+ /** A carried path the branch's document hasn't: HEAD's file goes back (`key` from filesAt, `buf` for a binary), or none when HEAD hasn't it either. */
2168
+ putHeadVersion (rel, key, buf) {
2169
+ if (key === undefined) return // git couldn't read it (too large, a filter): left as it is
2170
+ try {
2171
+ const abs = resolveInside(this.root, rel)
2172
+ if (key === null) {
2173
+ fs.rmSync(abs, { force: true })
2174
+ removeEmptyParents(this.root, path.dirname(abs))
2175
+ this.lastKnown.delete(rel)
2176
+ return
2177
+ }
2178
+ const data = key.startsWith('bin:') ? buf : key
2179
+ if (data === null || data === undefined) return
2180
+ fs.mkdirSync(path.dirname(abs), { recursive: true })
2181
+ this.writeFile(rel, abs, data)
2182
+ this.lastKnown.set(rel, key)
2183
+ if (this.sharedKey(rel) === undefined) this.gitOnly.set(rel, key)
2184
+ } catch (err) { this.log(`could not put ${rel} back to your last commit: ${err.message}`) }
2089
2185
  }
2090
2186
 
2091
2187
  /**
2092
- * The folder's branch has no square at layout 3 (the relay kept its edits in the branch's
2093
- * document): one is opened for it as this member (server.js quiltOpen), with the document and
2094
- * those edits, and the folder follows it when the relay says so. One ask at a time. `quiet: false`
2095
- * (the app's button, openSquareHere): a failure throws instead of only being logged.
2188
+ * The paths git carried over from the old branch (path -> the old branch's version): changed
2189
+ * on disk, where the old branch's document differs from its HEAD. (git keeps uncommitted
2190
+ * changes across a checkout; Quilt wrote the session's work there as such.)
2096
2191
  */
2097
- async openBranchSquare (branch, { quiet = true, token: given = null } = {}) {
2098
- if (this.openingSquare || !this.quilt || !this.quilt.id || !this.conn || !this.conn.connected || !appSeamUrl()) {
2099
- if (quiet) return null
2100
- throw new Error(!appSeamUrl() ? 'Seam is turned off for this app (QUILT_SOURCE_URL=off).' : 'This folder is not connected to the relay; try again in a moment.')
2192
+ async carriedFrom (oldKeys, fromSha) {
2193
+ const out = new Map()
2194
+ const tree = await treeState(this.root, [])
2195
+ if (!tree) return out
2196
+ const dirty = [...tree.dirty].filter((rel) => this.syncable(rel))
2197
+ const was = fromSha && dirty.length ? await filesAt(this.root, fromSha, dirty) : null
2198
+ for (const rel of dirty) {
2199
+ const disk = this.readDisk(rel)
2200
+ if (disk && (disk.skip || disk.tooLarge)) continue
2201
+ // The old branch had uncommitted work here, and git kept a change across the checkout. (The disk may
2202
+ // have been edited again since: arrive merges that edit against the old branch's version.)
2203
+ const head = was ? was.get(rel) : undefined // undefined: git couldn't read it
2204
+ if (oldKeys.has(rel)) { if (oldKeys.get(rel) !== head) out.set(rel, oldKeys.get(rel)) } else if (!disk && head !== null && head !== undefined) out.set(rel, null) // a deletion the old branch made
2205
+ }
2206
+ return out
2207
+ }
2208
+
2209
+ /** The session's version of each path onto the disk, over what git put there (git has that: no copy is kept). */
2210
+ writeBackAll (rels) {
2211
+ for (const rel of rels) {
2212
+ const disk = this.readDisk(rel)
2213
+ if (disk && (disk.skip || disk.tooLarge)) continue
2214
+ if (disk) this.lastKnown.set(rel, disk.key); else this.lastKnown.delete(rel)
2215
+ this.tryWrite(rel)
2101
2216
  }
2102
- this.openingSquare = true
2217
+ }
2218
+
2219
+ /** Merges each entry ({ rel, base }) into the session, keeping it out of normal sync while it runs: how many need a person (conflicts), and how many changed the session (changed). */
2220
+ async mergeHeld (entries) {
2221
+ for (const e of entries) this.merging.add(e.rel)
2222
+ let conflicts = 0
2223
+ let changed = 0
2224
+ for (const e of entries) {
2225
+ if (this.stopped) break
2226
+ try {
2227
+ const r = await this.mergeOne(e)
2228
+ if (r === 'conflict') conflicts++
2229
+ else if (r) changed++
2230
+ } catch (err) { this.log(`could not merge ${e.rel}: ${err.message}`) }
2231
+ this.merging.delete(e.rel)
2232
+ }
2233
+ for (const e of entries) this.merging.delete(e.rel)
2234
+ return { conflicts, changed }
2235
+ }
2236
+
2237
+ /** Where the saved state of branch `key` waits while this folder is on another branch. */
2238
+ branchStateDir (key) { return path.join(this.stateDir, 'branches', Buffer.from(key, 'utf8').toString('base64url')) }
2239
+
2240
+ /** Keeps the branch this folder leaves: its document as this app has it (anything the relay hasn't got yet included). */
2241
+ parkLocalState (key) {
2242
+ const dir = this.branchStateDir(key)
2103
2243
  try {
2104
- // `token`: the owner's sign-in a new session was made a quilt with (quilt-default.js).
2105
- const token = given || (await this.seamMember().client(this.quilt.id, [])).token
2106
- const r = await this.conn.branchRequest({ op: 'quilt-open', token, branch }, { timeoutMs: QUILT_MOVE_TIMEOUT_MS })
2107
- if (r.opened) this.log(`🧵 opened square ${squareShort(r.square)} for ${branch}, which had none: this folder follows it, with your edits.`)
2108
- // What is on disk is the new square's work: the folder is never written over as it starts to follow it (session-follow.js openHere).
2109
- this.folderWins = r.square
2110
- this.readOnly = null
2111
- this.scheduleStatusWrite()
2112
- return r
2113
- } catch (err) {
2114
- if (!quiet) throw err
2115
- this.log(`⚠️ couldn't open a square for ${branch} (${err.message}); your edits are kept in the session, and the next one asks again`)
2116
- return null
2117
- } finally { this.openingSquare = false }
2244
+ fs.mkdirSync(dir, { recursive: true })
2245
+ fs.writeFileSync(path.join(dir, 'state.bin'), Y.encodeStateAsUpdate(this.bdoc))
2246
+ if (this.branchEpoch) fs.writeFileSync(path.join(dir, 'epoch'), this.branchEpoch)
2247
+ else fs.rmSync(path.join(dir, 'epoch'), { force: true })
2248
+ } catch (err) { this.log(`could not keep ${key}'s state: ${err.message}`) }
2249
+ }
2250
+
2251
+ /** Which document of branch `key` its kept state is a copy of (parkLocalState), or null. */
2252
+ parkedEpoch (key) {
2253
+ try { return fs.readFileSync(path.join(this.branchStateDir(key), 'epoch'), 'utf8').trim() || null } catch { return null }
2118
2254
  }
2119
2255
 
2120
2256
  /**
2121
- * 16 step 1: links the session to the quilt an import of its git remote fills (`quilt`; null
2122
- * unlinks), as the owner with `token`. The session stays as it is; quilt_history and the app
2123
- * read the quilt's log from then on.
2257
+ * The saved document of a branch this folder was on before (into `doc`). Returns what the folder
2258
+ * had of each path when it left (path -> key), or null when it was never on that branch here.
2124
2259
  */
2125
- async quiltShadowLink (token, quilt) {
2126
- if (!this.conn || !this.conn.connected) throw new Error('not connected to the relay; linking the session needs a connection')
2127
- if (!token) throw new Error('sign in first (quilt login, or set SEAM_TOKEN): the session is linked as its owner')
2128
- const r = await this.conn.branchRequest({ op: 'quilt-shadow', token, quilt: quilt || null }, { timeoutMs: QUILT_MOVE_TIMEOUT_MS })
2129
- if (r.read) {
2130
- const name = r.shadow.slug || r.shadow.id
2131
- const until = r.read.until ? ` (until ${r.read.until.slice(0, 10)})` : ''
2132
- return { ...r, text: r.read.renewed ? `The session has a new read token for ${name}${until}: every folder reads its square with it.` : `The session's read token for ${name} works${until}; nothing to renew.` }
2133
- }
2134
- const text = r.shadow ? `This session now reads the quilt ${r.shadow.slug || r.shadow.id}'s log (quilt_history); git stays its source of truth until the cut-over.` : r.was ? `This session no longer reads the quilt ${r.was.slug || r.was.id}.` : 'This session was not linked to a quilt.'
2135
- return { ...r, text }
2260
+ unparkLocalState (key, doc) {
2261
+ try { Y.applyUpdate(doc, fs.readFileSync(path.join(this.branchStateDir(key), 'state.bin')), LOCAL) } catch { return null }
2262
+ const left = new Map()
2263
+ for (const rel of [...doc.getMap('files').keys(), ...doc.getMap('blobs').keys()]) left.set(rel, docKey(doc, rel))
2264
+ return left
2265
+ }
2266
+
2267
+ /** Partners see which branch this folder is on (presence). */
2268
+ announceBranch () {
2269
+ if (this.conn && this.conn.awareness.getLocalState()) this.conn.awareness.setLocalStateField('branch', this.branch)
2270
+ }
2271
+
2272
+ /** What a move says in the log. */
2273
+ moveNote ({ from, to, created, carried = [] }) {
2274
+ const head = `You're on ${to} now (you switched in git)`
2275
+ if (created) return `${head}. ${to} is new to the session: this folder's files are its starting point, and ${from}'s work stays in the session on ${from}.`
2276
+ const list = carried.slice(0, 3).join(', ') + (carried.length > 3 ? ', …' : '')
2277
+ const brought = carried.length ? ` git had carried ${from}'s uncommitted work in ${list} over: that stays in the session on ${from}, and ${to}'s version is on disk.` : ''
2278
+ return `${head}; the session's work there is on disk.${brought}`
2279
+ }
2280
+
2281
+ /** Watches the folder's .git: HEAD moving is looked at with the next flush, and git starting work holds the folder at once. */
2282
+ startGitWatch () {
2283
+ if (this.gitWatcher || !this.git) return
2284
+ this.gitWatcher = watchGit(this.root, (e) => {
2285
+ if (this.stopped) return
2286
+ if (e.type === 'head') { this.headChangedAt = Date.now(); this.queue(HEAD_CHANGED) } else if (e.type === 'busy') { this.setHold('busy'); this.settleHoldSoon() } else this.settleHoldSoon() // idle, index
2287
+ })
2136
2288
  }
2137
2289
 
2138
2290
  /**
2139
- * Back to the branches (layout 2) from the kept branch documents, as the owner with `token`.
2140
- * The relay refuses while the quilt has open squares, unless each is named in `carried` (its
2141
- * work carried over by hand: seam diff <square> | git apply).
2291
+ * Puts back the .git an older Quilt set aside in this folder (git-aside.js), once, when the session
2292
+ * starts and the relay has synced. A folder that got a new .git meanwhile keeps both. Whether git came back.
2142
2293
  */
2143
- async quiltUnswitch (token, carried = []) {
2144
- if (!this.conn || !this.conn.connected) throw new Error('not connected to the relay')
2145
- if (!token) throw new Error('sign in first (quilt login, or set SEAM_TOKEN): going back reads the quilt\'s open squares as its owner')
2146
- const r = await this.conn.branchRequest({ op: 'quilt-unswitch', token, carried }, { timeoutMs: QUILT_MOVE_TIMEOUT_MS })
2147
- const lines = [r.shadow
2148
- ? `The session works from its branches and git again; it still reads the quilt ${r.shadow.slug || r.shadow.id}'s log.`
2149
- : 'The session works from its branches again; the squares keep their live documents.']
2150
- const quilt = (r.quilt && (r.quilt.slug || r.quilt.id)) || ''
2151
- const list = (a) => `${a.slice(0, 8).join(', ')}${a.length > 8 ? `, and ${a.length - 8} more` : ''}`
2152
- for (const k of r.kept || []) {
2153
- const sq = squareShort(k.square)
2154
- if (k.error) { lines.push(`No folder follows square ${sq} (${k.branch}) now, and the relay could not copy its work back (${k.error}): it is in the square (seam diff ${sq} --quilt ${quilt}) and on the relay.`); continue }
2155
- if (k.copied.length) lines.push(`No folder follows square ${sq} (${k.branch}) now, so the relay copied its work into ${k.branch}: ${list(k.copied)}.`)
2156
- if (k.uncommitted) lines.push(`Its live work could not be committed in Seam (${k.uncommitted}); what was copied is in ${k.branch}.`)
2157
- else if (k.commit) lines.push(`All of square ${sq}'s work stays readable in Seam at ${String(k.commit).slice(0, 12)} (seam diff ${sq} --quilt ${quilt}).`)
2158
- for (const x of k.left) lines.push(`Not copied into ${k.branch}: ${x.path}, ${x.why}${k.commit && !k.uncommitted ? `; get it with seam cat ${String(k.commit).slice(0, 12)} ${x.path} --quilt ${quilt}` : ''}.`)
2159
- }
2160
- return { ...r, text: lines.join('\n') }
2294
+ async gitBack () {
2295
+ if (!gitAsideOf(this.root)) { this.gitAside = null; return false }
2296
+ let back = false
2297
+ try { back = putGitBack(this.root) } catch (err) { this.log(`⚠️ couldn't put git back in this folder (${err.message}); it is in ${GIT_ASIDE}`); return false }
2298
+ if (!back) { this.log(`⚠️ this folder has a new .git, so the one an older Quilt set aside stays in ${GIT_ASIDE}`); return false }
2299
+ this.gitAside = null
2300
+ this.log('git is back in this folder.')
2301
+ this.scheduleStatusWrite()
2302
+ return true
2161
2303
  }
2162
2304
 
2163
2305
  // A catch-up that stopped on clashing files is handed to ONE AI as a task (clash.js). Every
@@ -2186,12 +2328,11 @@ export class Session extends EventEmitter {
2186
2328
  /**
2187
2329
  * Pushes the on-disk state of a path into the shared doc. Returns true if anything changed.
2188
2330
  * `pulled`: git brought this version (a pull), so it is not an edit of ours: never boxed, and counted as the pull's.
2189
- * `box`: false keeps this edit from boxing the file for us (leaveSquare: another member's work).
2190
2331
  */
2191
- ingest (rel, { pulled = false, same = false, box: mayBox = true } = {}) {
2192
- if (!this.syncable(rel) || this.inSquare || this.syncStopped) return false
2332
+ ingest (rel, { pulled = false } = {}) {
2333
+ if (!this.syncable(rel)) return false
2193
2334
  if (this.merging.has(rel)) return false // its offline merge hasn't run yet; see mergeOffline
2194
- // A plain `rm` of a file a fetched pull would bring (git said to remove it): making way, not a deletion.
2335
+ if (this.held()) { this.heldPaths.add(rel); return false } // git is at work in this folder, or it is moving to another branch; see onSettled
2195
2336
  if (this.downloading.has(rel)) return false // our copy is being replaced by a download
2196
2337
  if (this.writeFailed.has(rel)) return false // the shared version never reached the disk: what's there is no edit of ours
2197
2338
  // New ignore rules: a box of ours on a file they now leave out lets go (settleBoxesOnce).
@@ -2255,7 +2396,7 @@ export class Session extends EventEmitter {
2255
2396
  const quiltOwn = this.quiltOwnWrite === rel && disk && disk.key === this.quiltOwnKey
2256
2397
  if (quiltOwn) { this.quiltOwnWrite = null; this.quiltOwnKey = null }
2257
2398
  // With boxes, a deletion is boxed too: it reaches nobody else's folder until it's committed.
2258
- if (mayBox && (disk || this.boxesOn()) && !pulled && !quiltOwn && this.ready && !this.seeding && changesIt && this.aiMayBeEditing()) this.boxEdit(rel)
2399
+ if ((disk || this.boxesOn()) && !pulled && !quiltOwn && this.ready && !this.seeding && changesIt && this.aiMayBeEditing()) this.boxEdit(rel)
2259
2400
 
2260
2401
  if (!disk) {
2261
2402
  if (!this.files.has(rel) && !this.blobs.has(rel)) {
@@ -2301,6 +2442,17 @@ export class Session extends EventEmitter {
2301
2442
  return true
2302
2443
  }
2303
2444
 
2445
+ // A clash to settle in this file (relayClashed): not shared while its markers are in it. Saved again
2446
+ // with them still there, its writer's AI is told once more.
2447
+ if (!disk.binary && hasMarkers(disk.text)) {
2448
+ if (this.clashed.get(rel) !== disk.text) {
2449
+ this.clashed.set(rel, disk.text)
2450
+ this.notice(clashStillNotice(rel))
2451
+ this.log(`⚖️ ${rel}: still has conflict markers, so it is not shared yet`)
2452
+ }
2453
+ return false
2454
+ }
2455
+ if (this.clashed.delete(rel)) this.log(`⚖️ ${rel}: its conflict markers are gone; sharing it`)
2304
2456
  if (disk.key === this.sharedKey(rel)) {
2305
2457
  this.lastKnown.set(rel, disk.key)
2306
2458
  if (stored && stored.stored) this.setOnDisk(rel, stored.hash)
@@ -2325,7 +2477,7 @@ export class Session extends EventEmitter {
2325
2477
  let rewrite = false
2326
2478
  // A diff branch: the edit of a file only git had starts from git's text, so its history says what changed.
2327
2479
  const fromGit = this.diffForm && !this.files.has(rel) && !this.blobs.has(rel) && !this.gone.has(rel) && typeof gitWas === 'string' && !gitWas.startsWith('bin:') ? gitWas : null
2328
- if (!disk.binary && !same && this.ready && !this.seeding) {
2480
+ if (!disk.binary && this.ready && !this.seeding) {
2329
2481
  const known = this.lastKnown.get(rel)
2330
2482
  const t = this.files.get(rel)
2331
2483
  const knownText = typeof known === 'string' && !/^bin:[0-9a-f]{40}$/.test(known)
@@ -2339,12 +2491,21 @@ export class Session extends EventEmitter {
2339
2491
  if (t && known === undefined && this.relayWritesOn() && !this.relayLocal.delete(rel)) return this.relayIngest(rel, disk, null, { pulled })
2340
2492
  if (!t && !this.blobs.has(rel) && this.relayWritesOn() && !this.relayLocal.delete(rel)) return this.relayIngest(rel, disk, fromGit, { pulled, fromGit: fromGit !== null })
2341
2493
  }
2342
- if (!disk.binary && !pulled && !same && this.ready && !this.seeding) {
2494
+ if (!disk.binary && !pulled && this.ready && !this.seeding) {
2343
2495
  const known = this.lastKnown.get(rel)
2344
2496
  const t = this.files.get(rel)
2345
2497
  if (t && typeof known === 'string' && !/^bin:[0-9a-f]{40}$/.test(known)) {
2346
- const r = this.liveRules().write({ doc: this.bdoc, where: { branch: this.branchKey() }, path: rel, base: known, ours: disk.text, theirs: t.toString(), by: this.name, byId: this.myKey(), others: [this.lastEditorOf(rel)].filter(Boolean) })
2498
+ // Made from a text Quilt replaced here (base-pick.js): put onto that one first, as the relay does.
2499
+ const src = this.overwritten.from(rel, known, disk.text)
2500
+ const r = this.liveRules().write({ doc: this.bdoc, where: { branch: this.branchKey() }, path: rel, base: known, ours: disk.text, theirs: t.toString(), by: this.name, byId: this.myKey(), others: [this.lastEditorOf(rel)].filter(Boolean), older: src.how === 'current' ? null : src.base })
2347
2501
  if (r.text !== disk.text) { text = r.text; rewrite = true }
2502
+ if (rewrite && !r.held.length) {
2503
+ this.overwritten.replaced(rel, disk.text)
2504
+ if (src.how === 'older') {
2505
+ this.overwritten.told(rel, disk.text)
2506
+ this.notice(olderCopyNotice(rel, Math.max(1, diffLines(disk.text.split('\n'), text.split('\n')).reduce((n, h) => n + h.buffer2[1], 0))))
2507
+ }
2508
+ }
2348
2509
  // Every change of this write was held: the shared file stays as it is, and this folder gets it back.
2349
2510
  if (rewrite && text === t.toString()) {
2350
2511
  try { this.writeFile(rel, resolveInside(this.root, rel), text) } catch (err) { this.log(`could not write ${rel}: ${err.message}`) }
@@ -2352,7 +2513,7 @@ export class Session extends EventEmitter {
2352
2513
  return false
2353
2514
  }
2354
2515
  } else if (!t && !this.blobs.has(rel)) {
2355
- // A new file: nothing to merge, but its lines are on record as this member's (the next writer's stale check).
2516
+ // A new file: nothing to merge; a deletion of the same text here makes it a move.
2356
2517
  this.liveRules().write({ doc: this.bdoc, where: { branch: this.branchKey() }, path: rel, ours: disk.text, by: this.name })
2357
2518
  }
2358
2519
  }
@@ -2379,8 +2540,7 @@ export class Session extends EventEmitter {
2379
2540
  texts = { before, after: text }
2380
2541
  // Folders on one branch pull the same commits, often at the same moment: made under an id
2381
2542
  // taken from the change, the pull's edit is the same edit from each of them, and lands once.
2382
- // So is the square's work every folder brings back when a session leaves layout 3 (leaveSquare).
2383
- detail = pulled || same ? asClient(this.bdoc, sameEditClient(pulled ? 'pull' : 'square', rel, this.files.has(rel) ? before : null, text), put) : put()
2543
+ detail = pulled ? asClient(this.bdoc, sameEditClient('pull', rel, this.files.has(rel) ? before : null, text), put) : put()
2384
2544
  }
2385
2545
  if (disk.exec) { if (this.modes.get(rel) !== 'x') this.modes.set(rel, 'x') } else if (this.modes.has(rel)) this.modes.delete(rel)
2386
2546
  this.notePresentHere(rel, this.entryBase())
@@ -2399,7 +2559,7 @@ export class Session extends EventEmitter {
2399
2559
 
2400
2560
  /** Whether this folder's text edits go to the relay as writes (it takes them, and this folder is connected on a branch). */
2401
2561
  relayWritesOn () {
2402
- return !!(this.conn && this.conn.relayWrites && this.conn.connected && this.conn.branchKey !== null && !this.noRelayWrites && !this.inSquare)
2562
+ return !!(this.conn && this.conn.relayWrites && this.conn.connected && this.conn.branchKey !== null && !this.noRelayWrites)
2403
2563
  }
2404
2564
 
2405
2565
  /**
@@ -2415,10 +2575,12 @@ export class Session extends EventEmitter {
2415
2575
  this.relayWriting.add(rel)
2416
2576
  const text = disk.text
2417
2577
  const created = base === null && !this.files.has(rel) && !this.blobs.has(rel)
2418
- // A save that landed in the file Quilt replaced was made from the text before (base-pick.js): it goes too
2419
- // (`older`), and the relay puts the save onto it, so the partner's change written meanwhile stays.
2420
- const older = typeof base === 'string' ? this.overwritten.pick(rel, base, text) : base
2578
+ // A save made from a text Quilt replaced on disk (it landed in the file replaced, or its tool read the file
2579
+ // before a partner's change was written over it: base-pick.js) goes with that text (`older`): the relay
2580
+ // puts the save onto it, so the partner's change stays.
2421
2581
  const trusted = !!(this.liveEngine && this.liveEngine.trusted.get(rel) === text)
2582
+ const src = !trusted && typeof base === 'string' ? this.overwritten.from(rel, base, text) : { base, how: 'current' }
2583
+ const older = src.base
2422
2584
  const key = this.conn.branchKey
2423
2585
  const req = {
2424
2586
  path: rel,
@@ -2427,7 +2589,8 @@ export class Session extends EventEmitter {
2427
2589
  text,
2428
2590
  ...(older !== base && typeof older === 'string' ? { older } : {}),
2429
2591
  ...(fromGit ? { fromGit: true } : {}),
2430
- ...(trusted ? { trusted: true } : {})
2592
+ // A clash is settled in this folder's own file (relayClashed): the relay takes nothing of a save that clashes.
2593
+ ...(this.noClashMarkers ? {} : { markers: true })
2431
2594
  }
2432
2595
  // What does not touch the text stays an edit here: its mode, and where a diff branch's entry started.
2433
2596
  this.transact(() => {
@@ -2438,25 +2601,39 @@ export class Session extends EventEmitter {
2438
2601
  if (created && !pulled) { try { this.liveRules().noteNew({ doc: this.bdoc, path: rel, text, by: this.name }) } catch {} }
2439
2602
  this.noteMyEdit(rel, { pulled })
2440
2603
  this.conn.liveWrite(req, { baseOf: () => base }).then(
2441
- (r) => this.relayWrote(rel, disk, r, key, trusted, { pulled, created }),
2604
+ (r) => this.relayWrote(rel, disk, r, key, { pulled, created, older: src.how === 'older', trusted }),
2442
2605
  (err) => this.relayFailed(rel, err)
2443
2606
  )
2444
2607
  return true
2445
2608
  }
2446
2609
 
2447
2610
  /** The relay's answer to a live write of rel: the activity record, the result on disk (unless saved again since), what the writer must hear. */
2448
- relayWrote (rel, disk, r, key, trusted, { pulled = false, created = false } = {}) {
2611
+ relayWrote (rel, disk, r, key, { pulled = false, created = false, older = false, trusted = false } = {}) {
2449
2612
  this.relayWriting.delete(rel)
2450
2613
  if (this.stopped) return
2451
2614
  if (r.fallback) { this.relayLocal.add(rel); this.relayAgain.delete(rel); try { this.ingest(rel, { pulled }) } catch (err) { this.log(`could not sync ${rel}: ${err.message}`) } return }
2452
2615
  if (trusted && this.liveEngine) this.liveEngine.trusted.delete(rel)
2453
2616
  if (this.conn.branchKey !== key) { this.relayAgain.delete(rel); this.queue(rel); return } // the folder moved to another branch meanwhile
2617
+ if (r.conflict) return this.relayClashed(rel, disk, r)
2454
2618
  const result = r.same ? disk.text : r.text
2619
+ // A save told of a clash is not an older copy its writer may save from unknowing: what it saves next is meant.
2620
+ const clashed = (r.held || []).length > 0
2455
2621
  this.overwritten.forget(rel)
2622
+ // Made from an older copy, and a partner's change it lacked stayed: its writer is told (saved again, it is meant).
2623
+ if (older && result !== disk.text && !clashed) {
2624
+ this.overwritten.told(rel, disk.text)
2625
+ const kept = diffLines(disk.text.split('\n'), result.split('\n')).reduce((n, h) => n + h.buffer2[1], 0)
2626
+ this.notice(olderCopyNotice(rel, Math.max(1, kept)))
2627
+ this.log(`${rel}: saved from an older copy; the change it lacked stays`)
2628
+ }
2456
2629
  if (r.detail) this.transact(() => this.recordActivity(rel, created && !r.before ? 'created' : 'edited', r.detail, { before: r.before ?? '', after: result }, { pulled }), LOCAL)
2457
2630
  let now = null
2458
2631
  try { now = this.readDisk(rel) } catch {}
2459
- if (now && !now.binary && now.text === disk.text) {
2632
+ // git is at work here, or the folder is moving to another branch: the result is not written over what git
2633
+ // may be writing. This folder had what it sent; the result comes to disk when the hold ends (resumeHeld).
2634
+ const held = this.held()
2635
+ if (held) this.heldPaths.add(rel)
2636
+ if (!held && now && !now.binary && now.text === disk.text) {
2460
2637
  // Disk still has what was sent: it gets the result (the lines that landed first, with this edit's others).
2461
2638
  let over = true
2462
2639
  if (result !== disk.text) {
@@ -2464,11 +2641,12 @@ export class Session extends EventEmitter {
2464
2641
  const abs = resolveInside(this.root, rel)
2465
2642
  over = this.writeOver(rel, abs, result, now)
2466
2643
  if (over === null) { this.writeFile(rel, abs, result); over = true }
2644
+ if (over && !clashed) this.overwritten.replaced(rel, disk.text)
2467
2645
  } catch (err) { this.log(`could not write ${rel}: ${err.message}`) }
2468
2646
  }
2469
2647
  // Saved again in that instant: that save is taken in next, merged on what was sent.
2470
2648
  this.lastKnown.set(rel, over === false ? disk.text : result)
2471
- } else this.lastKnown.set(rel, disk.text) // saved again since: that save is taken in next, merged on what was sent
2649
+ } else this.lastKnown.set(rel, disk.text) // saved again since (or held): what the disk has is taken in next, merged on what was sent
2472
2650
  this.setOnDisk(rel, null)
2473
2651
  for (const n of r.notices || []) this.notice(n)
2474
2652
  for (const l of r.logs || []) this.log(l)
@@ -2484,6 +2662,45 @@ export class Session extends EventEmitter {
2484
2662
  }
2485
2663
  }
2486
2664
 
2665
+ /**
2666
+ * The relay took nothing of a save of rel: someone changed the same lines first. The file here gets the save
2667
+ * merged onto the session's text as it is now, with both versions of the clashing lines between markers, and
2668
+ * the writer's AI is told. That text (`r.base`) is what the next save is merged against; a save with markers
2669
+ * still in it is never sent (ingest), and a partner's change is not written over the file meanwhile (writeOut
2670
+ * sees an edit not sent yet).
2671
+ */
2672
+ relayClashed (rel, disk, r) {
2673
+ // git is at work here, or the folder is moving: nothing is written into the file now. The save is sent again when the hold ends.
2674
+ if (this.held()) { this.relayAgain.delete(rel); this.heldPaths.add(rel); return }
2675
+ this.overwritten.forget(rel)
2676
+ for (const n of r.notices || []) this.notice(n)
2677
+ for (const l of r.logs || []) this.log(l)
2678
+ const who = (r.others || []).join(', ') || 'someone'
2679
+ let now = null
2680
+ try { now = this.readDisk(rel) } catch {}
2681
+ let over = false
2682
+ if (now && !now.binary && now.text === disk.text && typeof r.text === 'string' && typeof r.base === 'string') {
2683
+ try {
2684
+ const abs = resolveInside(this.root, rel)
2685
+ over = this.writeOver(rel, abs, r.text, now)
2686
+ if (over === null) { this.writeFile(rel, abs, r.text); over = true }
2687
+ } catch (err) { this.log(`could not write ${rel}: ${err.message}`); this.relayAgain.delete(rel); return }
2688
+ }
2689
+ if (over) {
2690
+ this.lastKnown.set(rel, r.base)
2691
+ this.setOnDisk(rel, null)
2692
+ this.clashed.set(rel, r.text)
2693
+ this.relayAgain.delete(rel)
2694
+ this.notice(clashNotice(rel, who))
2695
+ this.log(`⚖️ ${rel}: ${who} changed the same lines first; both versions are in your file to settle`)
2696
+ this.scheduleStatusWrite?.()
2697
+ return
2698
+ }
2699
+ // Saved again since: that save is taken in next, on what this folder last had.
2700
+ this.relayAgain.delete(rel)
2701
+ try { this.ingest(rel) } catch (err) { this.log(`could not sync ${rel}: ${err.message}`) }
2702
+ }
2703
+
2487
2704
  /** A live write the relay never answered: an older relay (the edit goes in here, as before), or no connection (tried again). */
2488
2705
  relayFailed (rel, err) {
2489
2706
  this.relayWriting.delete(rel)
@@ -2504,7 +2721,6 @@ export class Session extends EventEmitter {
2504
2721
  if (!this.liveEngine) {
2505
2722
  this.liveEngine = new LiveRules({
2506
2723
  room: () => this.doc,
2507
- staleMinutes: () => staleWriteMinutes(this.doc, this.members),
2508
2724
  notice: (t) => this.notice(t),
2509
2725
  log: (t) => this.log(t),
2510
2726
  texts: () => this.sessionTexts(),
@@ -2628,13 +2844,13 @@ export class Session extends EventEmitter {
2628
2844
  * `texts` is { before, after } for text files, so the chronology keeps the diff. `pulled`: a git pull
2629
2845
  * brought it: counted as the pull's, and left out of the activity log (notePull writes one line for it all).
2630
2846
  */
2631
- recordActivity (rel, kind, detail, texts, { pulled = false, activity = true } = {}) {
2847
+ recordActivity (rel, kind, detail, texts, { pulled = false } = {}) {
2632
2848
  const now = Date.now()
2633
2849
  this.tally(rel, kind, detail, now, texts, pulled)
2634
2850
  // A folder's starting copy of a branch (seeding) is nobody's change and no task's: it is on record, but never blamed or counted as unpublished work.
2635
2851
  this.history.record({ by: this.name, path: rel, kind, detail, before: texts?.before, after: texts?.after, task: pulled || this.seeding ? null : this.currentTask(), pulled, seed: !!this.seeding, ts: now })
2636
2852
  // A pull is logged once by notePull; a starting copy (seeding) is nobody's edit, so the file tree names no one for it.
2637
- if (pulled || this.seeding || !activity) return
2853
+ if (pulled || this.seeding) return
2638
2854
  this.pushActivity(rel, kind, detail, now)
2639
2855
  }
2640
2856
 
@@ -2726,7 +2942,6 @@ export class Session extends EventEmitter {
2726
2942
  * the others: it's noted in writeFailed and tried again later.
2727
2943
  */
2728
2944
  applyRemote (paths) {
2729
- if (this.inSquare || this.syncStopped) return
2730
2945
  const failed = []
2731
2946
  for (const p of paths) {
2732
2947
  try { this.fromRemote(p); this.writeFailed.delete(p) } catch { failed.push(p) }
@@ -2751,9 +2966,10 @@ export class Session extends EventEmitter {
2751
2966
  }
2752
2967
 
2753
2968
  writeOut (rel) {
2754
- if (!this.syncable(rel) || this.inSquare || this.syncStopped) return
2969
+ if (!this.syncable(rel)) return
2755
2970
  if (this.ghost(rel)) return
2756
2971
  if (this.merging.has(rel)) return // mergeOffline writes this path once it has merged it
2972
+ if (this.held()) { this.heldPaths.add(rel); return } // written when the hold ends (resumeHeld), or not at all once the folder has moved
2757
2973
  let abs
2758
2974
  try { abs = resolveInside(this.root, rel) } catch (err) { this.log(err.message); return }
2759
2975
  const shared = this.sharedKey(rel)
@@ -2805,6 +3021,8 @@ export class Session extends EventEmitter {
2805
3021
  const over = this.writeOver(rel, abs, data, disk)
2806
3022
  if (over === false) { this.queue(rel); return }
2807
3023
  if (over === null) this.writeFile(rel, abs, data)
3024
+ // What disk held, for a tool that read it and saves all of it back later (base-pick.js).
3025
+ if (disk && !disk.binary && typeof disk.text === 'string' && typeof data === 'string') this.overwritten.replaced(rel, disk.text)
2808
3026
  }
2809
3027
  if (!b || !b.stored) this.setOnDisk(rel, null)
2810
3028
  this.lastKnown.set(rel, shared)
@@ -2899,25 +3117,27 @@ export class Session extends EventEmitter {
2899
3117
  const st = writeAndStat(tmp, data, seen.mode & 0o7777)
2900
3118
  // Replaced since it was opened (look is another file), or saved since disk was read: not written.
2901
3119
  if ((!look.isSymbolicLink() && look.ino !== seen.ino) || this.savedSince(abs, disk)) { fs.rmSync(tmp, { force: true }); return false }
3120
+ // What disk held when it was read: the file replaced is compared by its bytes, never by size and time
3121
+ // (a same-length save in the same timestamp tick keeps both), before anything of it is let go.
3122
+ const unchanged = sameAsRead(disk)
2902
3123
  let r = { placed: true, displaced: null, other: null, replaced: false }
2903
3124
  if (look.isSymbolicLink()) fs.renameSync(tmp, abs)
2904
- else r = this.swapIn(rel, abs, tmp, look)
3125
+ else r = this.swapIn(rel, abs, tmp, look, unchanged)
2905
3126
  // Not the file looked at any more (a save took its place): taken in next, and written again after it.
2906
3127
  if (!r.placed) return false
2907
3128
  this.noteWritten(rel, abs, st, data)
2908
3129
  const before = disk && typeof disk.text === 'string' ? disk.text : null
2909
3130
  // A save that took the path in the instant of the exchange: its writer's save, taken in once whole.
2910
3131
  if (r.other !== null && r.other !== undefined) this.rescueSave(rel, abs, r.other, data, before)
2911
- const now = fs.fstatSync(old)
2912
- // A save written into the file replaced: back as a save of its own, once whole (rescueSave), or at once.
2913
- if (now.size !== seen.size || now.mtimeMs !== seen.mtimeMs) { this.rescueSave(rel, abs, old, data, before); old = null } else if (r.displaced) { const bytes = r.displaced; setImmediate(() => this.putBackSave(rel, abs, bytes, data, before)) } else {
3132
+ // A save written into the file replaced (by its bytes: savedInto): back as a save of its own, once whole (rescueSave), or at once.
3133
+ if (savedInto(old, seen, unchanged)) { this.rescueSave(rel, abs, old, data, before); old = null } else if (r.displaced) { const bytes = r.displaced; setImmediate(() => this.putBackSave(rel, abs, bytes, data, before)) } else {
2914
3134
  // An editor that opened the file just before the rename may write into it a moment after: looked at once more.
2915
3135
  const fd = old
2916
3136
  old = null
2917
3137
  const t = setTimeout(() => {
2918
- let later = null
2919
- try { later = fs.fstatSync(fd) } catch {}
2920
- if (!this.stopped && later && (later.size !== seen.size || later.mtimeMs !== seen.mtimeMs)) this.rescueSave(rel, abs, fd, data, before)
3138
+ let later = false
3139
+ try { later = savedInto(fd, seen, unchanged) } catch {}
3140
+ if (!this.stopped && later) this.rescueSave(rel, abs, fd, data, before)
2921
3141
  else { try { fs.closeSync(fd) } catch {} }
2922
3142
  }, LATE_WRITE_MS)
2923
3143
  t.unref?.()
@@ -2987,7 +3207,7 @@ export class Session extends EventEmitter {
2987
3207
  }
2988
3208
  fs.writeFileSync(tmp, put, { mode: look.mode & 0o7777 })
2989
3209
  if (look.isSymbolicLink()) { fs.renameSync(tmp, abs); placed = true; continue }
2990
- const r = this.swapIn(rel, abs, tmp, look)
3210
+ const r = this.swapIn(rel, abs, tmp, look, (b) => b.equals(now))
2991
3211
  placed = r.placed
2992
3212
  if (r.displaced) { const again = r.displaced; setImmediate(() => this.putBackSave(rel, abs, again, put, now.toString('utf8'))) }
2993
3213
  if (r.other !== null && r.other !== undefined) this.rescueSave(rel, abs, r.other, put, now.toString('utf8'))
@@ -3005,8 +3225,8 @@ export class Session extends EventEmitter {
3005
3225
  * of Quilt's ever shows in the project). Only without an atomic exchange (said once in the log): a save
3006
3226
  * replaced in the one system call the fallback cannot cover is said to its writer.
3007
3227
  */
3008
- swapIn (rel, abs, tmp, look) {
3009
- const r = swapIn(abs, tmp, look, { asideDir: path.join(this.stateDir, 'tmp'), log: (m) => this.log(m) })
3228
+ swapIn (rel, abs, tmp, look, unchanged = null) {
3229
+ const r = swapIn(abs, tmp, look, { asideDir: path.join(this.stateDir, 'tmp'), log: (m) => this.log(m), unchanged })
3010
3230
  if (r.replaced) {
3011
3231
  const w = `A save of ${rel} landed in the same instant Quilt wrote the session's version over it, and could not be kept: save ${rel} again (your editor still has it).`
3012
3232
  this.notice(w)
@@ -3066,11 +3286,12 @@ export class Session extends EventEmitter {
3066
3286
  noteWritten (rel, abs, st = null, data = null) {
3067
3287
  try {
3068
3288
  if (!st) st = fs.lstatSync(abs)
3069
- this.diskStats.set(rel, `${st.ino}:${st.size}:${st.mtimeMs}:${st.ctimeMs}`)
3289
+ this.noteStat(rel, st)
3070
3290
  const was = this.wroteHere.get(rel)
3071
3291
  if (was) { this.wroteBytes -= was.text.length; this.wroteHere.delete(rel) }
3072
3292
  if (typeof data === 'string' && data.length <= WROTE_TEXT) {
3073
- this.wroteHere.set(rel, { ino: st.ino, size: st.size, mtimeMs: st.mtimeMs, text: data })
3293
+ // Not sure yet (readDisk): a save in the same timestamp tick as this write would match its stat.
3294
+ this.wroteHere.set(rel, { ino: st.ino, size: st.size, mtimeMs: st.mtimeMs, text: data, at: Date.now(), sure: false })
3074
3295
  this.wroteBytes = (this.wroteBytes || 0) + data.length
3075
3296
  while (this.wroteBytes > WROTE_BYTES && this.wroteHere.size) {
3076
3297
  const [k, v] = this.wroteHere.entries().next().value
@@ -3116,13 +3337,18 @@ export class Session extends EventEmitter {
3116
3337
  }
3117
3338
 
3118
3339
  lastEditorOf (rel) {
3119
- // The branch's chronology first: it comes in the same update as the file, while the room's
3120
- // activity entry for it may arrive just after.
3340
+ // Who the relay wrote it for (relay-live-write.js WRITERS_MAP): it comes in the same update as the text,
3341
+ // while its writer's chronology entry follows the relay's answer. Then the branch's chronology (an edit
3342
+ // made any other way is only there), whichever is newer; the room's activity entry may arrive after both.
3343
+ const w = this.bdoc ? this.bdoc.getMap('writers').get(rel) : null
3121
3344
  const h = this.history.array
3122
3345
  for (let i = h.length - 1; i >= 0; i--) {
3123
3346
  const e = h.get(i)
3124
- if (e && e.path === rel) return e.by === this.name ? null : (e.by || null)
3347
+ if (!e || e.path !== rel) continue
3348
+ if (w && w.by && (w.ts || 0) > (e.ts || 0)) break
3349
+ return e.by === this.name ? null : (e.by || null)
3125
3350
  }
3351
+ if (w && w.by) return w.by === this.name ? null : w.by
3126
3352
  for (let i = this.activity.length - 1; i >= 0; i--) {
3127
3353
  const a = this.activity.get(i)
3128
3354
  if (a.path === rel) return a.by === this.name ? null : a.by
@@ -3142,7 +3368,8 @@ export class Session extends EventEmitter {
3142
3368
 
3143
3369
  /** Tries failed uploads, downloads and writes again. */
3144
3370
  retryFailed () {
3145
- if (!this.ready || this.stopped || this.inSquare || this.syncStopped) return
3371
+ if (!this.ready || this.stopped) return
3372
+ if (this.hold && this.hold.kind === 'switching' && !this.following) this.recheckSoon()
3146
3373
  const failed = [...this.retry]
3147
3374
  this.retry.clear()
3148
3375
  for (const [rel, kind] of failed) {
@@ -3255,6 +3482,7 @@ export class Session extends EventEmitter {
3255
3482
  disk = null // read again once it's our turn, so waiting uploads don't hold files in memory
3256
3483
  if (this.uploading.get(rel) === hash) return
3257
3484
  this.uploading.set(rel, hash)
3485
+ const doc = this.bdoc
3258
3486
  // If a partner's version lands while this uploads, theirs wins (ours is kept as a conflict copy).
3259
3487
  const sharedBefore = this.sharedKey(rel)
3260
3488
  await this.startTransfer()
@@ -3278,6 +3506,8 @@ export class Session extends EventEmitter {
3278
3506
  }
3279
3507
  const now = this.readDisk(rel)
3280
3508
  if (!now || now.key !== diskKey) return // it changed again; that change is already queued
3509
+ if (this.bdoc !== doc) return // the folder moved to another branch meanwhile: this was the old branch's
3510
+ if (this.held()) { this.heldPaths.add(rel); return } // git is at work here: looked at again when the hold ends
3281
3511
  if (this.sharedKey(rel) !== sharedBefore || this.downloading.has(rel)) return // a partner's version landed first: it stays
3282
3512
  const existed = this.files.has(rel) || this.blobs.has(rel)
3283
3513
  this.transact(() => {
@@ -3353,6 +3583,7 @@ export class Session extends EventEmitter {
3353
3583
  if (!cur || cur.hash !== entry.hash) return // replaced meanwhile; that version is on its way
3354
3584
  if (this.stopped) return
3355
3585
  if (this.ghost(rel)) return // boxed by someone else meanwhile: written once it opens
3586
+ if (this.held()) { this.heldPaths.add(rel); return } // git is at work here: written once the hold ends (resumeHeld)
3356
3587
  const abs = resolveInside(this.root, rel)
3357
3588
  let st = null
3358
3589
  try { st = fs.lstatSync(abs) } catch {}
@@ -3394,6 +3625,7 @@ export class Session extends EventEmitter {
3394
3625
  // --------------------------------------------------------------- watcher --
3395
3626
 
3396
3627
  async startWatcher () {
3628
+ this.startGitWatch()
3397
3629
  this.scanDisk({ baseline: true }) // the folder was just reconciled; the first re-scan catches anything since
3398
3630
  this.watcher = watch(this.root, {
3399
3631
  ignoreInitial: true,
@@ -3423,29 +3655,53 @@ export class Session extends EventEmitter {
3423
3655
  })
3424
3656
  this.watcher.on('error', (err) => this.log(`watcher error: ${err.message}`))
3425
3657
  await new Promise((resolve) => this.watcher.once('ready', resolve))
3426
- this.reconcileTimer = setInterval(() => { if (this.ready) this.scanDisk() }, RECONCILE_MS)
3658
+ this.reconcileTimer = setInterval(() => {
3659
+ if (!this.ready) return
3660
+ // A checkout the git watcher missed (one that changes no file leaves nothing else to see).
3661
+ const at = this.git && !this.hold ? headName(this.root) : null
3662
+ if (at && at !== this.git.key) this.queue(HEAD_CHANGED)
3663
+ this.scanDisk()
3664
+ }, RECONCILE_MS)
3427
3665
  this.reconcileTimer.unref()
3428
3666
  this.scanDisk()
3429
3667
  }
3430
3668
 
3431
3669
  /** Stats the folder and queues every path that appeared, changed or vanished since the last scan. */
3432
3670
  scanDisk ({ baseline = false } = {}) {
3433
- if (this.inSquare || this.syncStopped) return
3671
+ if (!this.diskFresh) this.diskFresh = new Map()
3434
3672
  const seen = new Set()
3435
3673
  for (const rel of walk(this.root, this.ig)) {
3436
3674
  let st
3437
3675
  try { st = fs.lstatSync(path.join(this.root, ...rel.split('/'))) } catch { continue }
3438
3676
  seen.add(rel)
3439
3677
  const sig = `${st.ino}:${st.size}:${st.mtimeMs}:${st.ctimeMs}`
3440
- if (this.diskStats.get(rel) === sig) continue
3678
+ if (this.diskStats.get(rel) === sig) {
3679
+ // The same stat is no proof the bytes are (a same-length save in the same timestamp tick keeps it): a
3680
+ // file stamped within FRESH_MS of its last look is read again, and once more after that (readDisk
3681
+ // compares), then trusted while its stat stays.
3682
+ if (this.diskFresh.has(rel)) {
3683
+ if (settled(st.mtimeMs) && settled(this.diskFresh.get(rel))) this.diskFresh.delete(rel)
3684
+ if (!baseline) this.queue(rel)
3685
+ }
3686
+ continue
3687
+ }
3441
3688
  if (!baseline) this.queue(rel)
3442
- this.diskStats.set(rel, sig)
3689
+ this.noteStat(rel, st)
3443
3690
  }
3444
3691
  for (const rel of this.diskStats.keys()) {
3445
- if (!seen.has(rel)) { this.diskStats.delete(rel); this.queue(rel) }
3692
+ if (!seen.has(rel)) { this.diskStats.delete(rel); this.diskFresh.delete(rel); this.queue(rel) }
3446
3693
  }
3447
3694
  }
3448
3695
 
3696
+ /** Records rel's stat for the re-scan (scanDisk); a file stamped in the last FRESH_MS is read again until it settles. */
3697
+ noteStat (rel, st) {
3698
+ this.diskStats.set(rel, `${st.ino}:${st.size}:${st.mtimeMs}:${st.ctimeMs}`)
3699
+ if (!this.diskFresh) this.diskFresh = new Map()
3700
+ const now = Date.now()
3701
+ if (settled(st.mtimeMs, now)) this.diskFresh.delete(rel)
3702
+ else this.diskFresh.set(rel, now)
3703
+ }
3704
+
3449
3705
  // ----------------------------------------------------- presence & social --
3450
3706
 
3451
3707
  setupPresence () {
@@ -3750,91 +4006,9 @@ export class Session extends EventEmitter {
3750
4006
  historyQuery ({ path, by, since, task, limit } = {}) {
3751
4007
  const from = parseSince(since)
3752
4008
  if (from === undefined) throw new Error('since: use a duration like 2h or 3d, "today", "yesterday", or a date')
3753
- // Once the session is a quilt (the relay says so, src/server.js branchesFields), older changes are its legacy tail.
3754
- const entries = legacyTail(this.history.entries(), { at: this.quilt && this.quilt.at, history: !!(this.quilt && this.quilt.history) })
3755
- return queryHistory(entries, { path, by, since: from ?? undefined, task, limit: Math.min(Number(limit) || 50, 500) })
3756
- }
3757
-
3758
- /**
3759
- * quilt_history: historyQuery, and in a session linked to a quilt (Seam on, the relay says the
3760
- * session is a quilt or shadows one, 16) the quilt's log merged in (quilt-history.js): read as
3761
- * this member (seamMember: SEAM_TOKEN, else the session's Quilt sign-in, the same member as the
3762
- * Seam tools), else through the relay with the room's read token.
3763
- * { entries, note? }; the diffs of the log's commits only when `with_diff`.
3764
- */
3765
- async historyLinked ({ path: p, by, since, task, limit, with_diff: withDiff } = {}) {
3766
- // The relay says whether the room is linked (it has Seam on; this app may not): its read token answers then.
3767
- const link = this.quiltLink()
3768
- if (!link) return { entries: this.historyQuery({ path: p, by, since, task, limit }) }
3769
- const from = parseSince(since)
3770
- if (from === undefined) throw new Error('since: use a duration like 2h or 3d, "today", "yesterday", or a date')
3771
- const own = legacyTail(this.history.entries(), { at: this.quilt && this.quilt.at, history: !!(this.quilt && this.quilt.history) })
3772
- const query = { path: p || '', by, since: from ?? undefined, task, limit: Math.min(Number(limit) || 50, 500), withDiff: !!withDiff }
3773
- const quilt = { id: link.id, slug: link.slug || '' }
3774
- const api = this.seamApiUrl ?? appSeamUrl()
3775
- // As this member; one Seam would not let in (an agent with no member row, say) is not asked again for a
3776
- // minute. No sign-in yet is not Seam's answer: a sign-in made meanwhile (quilt login, SEAM_TOKEN) is used at once.
3777
- let seam = null
3778
- if (api && !(this.historySeamOff && Date.now() - this.historySeamOff < HISTORY_SEAM_OFF_MS)) {
3779
- try { seam = (await this.seamMember().client(quilt.id, [], { read: true, retry: false })).client } catch (err) { if (err.status) this.historySeamOff = Date.now() }
3780
- }
3781
- if (seam) {
3782
- // No retries: Seam down falls back to the relay's read at once.
3783
- const r = await linkedHistory({ seam, quilt, entries: own, query })
3784
- if (!r.note) return { entries: r.list }
3785
- }
3786
- let got = null
3787
- try { got = this.conn && this.conn.connected ? await this.conn.branchRequest({ op: 'quilt-log', query: { ...query, with_diff: !!withDiff } }) : null } catch (err) { got = { note: `Seam's log for ${quilt.slug || quilt.id} could not be read (${err.message}); this is the session's own record.` } }
3788
- const note = !got ? `Seam's log for ${quilt.slug || quilt.id} was not read: this folder is not connected to the relay.` : got.note || ''
3789
- return { entries: mergeLinked(own, (got && got.entries) || [], { ...query, logRead: !note }), ...(note ? { note } : {}) }
3790
- }
3791
-
3792
- /** The quilt the relay says this session is, or shadows (16 step 1): { id, slug, shadow, at? }, or null. */
3793
- quiltLink () {
3794
- const l = this.quilt || this.quiltShadow
3795
- // `layout: 3`: the session's files are in its squares (the app's source control is Seam's then).
3796
- return l && l.id ? { id: l.id, slug: l.slug || '', shadow: !this.quilt, ...(this.quilt && this.quilt.at ? { at: this.quilt.at } : {}), ...(this.quilt && this.quilt.layout === 3 ? { layout: 3 } : {}) } : null
3797
- }
3798
-
3799
- /**
3800
- * A file's History in the app, in a session linked to a quilt: its live changes not in the
3801
- * quilt's log yet, then the patches that touched it (each newest first), the same chronology
3802
- * quilt_history gives agents. null when the session is not linked.
3803
- */
3804
- async fileHistory (file) {
3805
- const quilt = this.quiltLink()
3806
- if (!quilt) return null
3807
- // The app asks again after every save to the file: the log is read at most every 30 s a file.
3808
- const logs = this.fileLogs || (this.fileLogs = new Map())
3809
- let got = logs.get(file)
3810
- if (!got || got.quilt !== quilt.id || Date.now() - got.at > FILE_LOG_MS) {
3811
- const { entries, note } = await this.historyLinked({ path: file, limit: 100 })
3812
- got = { quilt: quilt.id, at: Date.now(), patches: entries.filter((e) => e.seam).reverse(), note: note || '' }
3813
- logs.delete(file)
3814
- logs.set(file, got)
3815
- if (logs.size > 50) logs.delete(logs.keys().next().value)
3816
- }
3817
- const newest = got.patches.length ? got.patches[0].ts : 0
3818
- // What git brought in is the log's, once the log was read; the session's starting copy (seed) is nobody's live work.
3819
- const live = this.history.entries().filter((e) => e.path === file && e.ts > newest && !e.seed && !(e.pulled && !got.note)).reverse()
3820
- return { quilt, live, patches: got.patches, ...(got.note ? { note: got.note } : {}) }
3821
- }
3822
-
3823
- /** A read of the linked quilt through the relay, with the room's read token: { quilt: null } when the session is not linked. */
3824
- async quiltRead (req) {
3825
- if (!this.quiltLink()) return { quilt: null }
3826
- if (!this.conn || !this.conn.connected) throw new Error('This folder is not connected to the relay.')
3827
- const { id, op, ...r } = await this.conn.branchRequest(req)
3828
- return r
4009
+ return queryHistory(this.history.entries(), { path, by, since: from ?? undefined, task, limit: Math.min(Number(limit) || 50, 500) })
3829
4010
  }
3830
4011
 
3831
- /** Who wrote each line of a file on main (Seam's blame); { working: true } while Seam works it out. */
3832
- quiltBlame (file) { return this.quiltRead({ op: 'quilt-blame', path: file }) }
3833
- /** Code search over main. */
3834
- quiltSearch (q) { return this.quiltRead({ op: 'quilt-search', q }) }
3835
- /** One patch of the log: its files and the diff of `file`. */
3836
- quiltShow (commit, file) { return this.quiltRead({ op: 'quilt-show', commit, path: file }) }
3837
-
3838
4012
  /** `input` is a title, or { title, assignee, forAi, to_ai, tool, files }. "me" means this person. */
3839
4013
  addTask (input) {
3840
4014
  const fields = typeof input === 'string' ? { title: input } : { ...(input || {}) }
@@ -4432,29 +4606,6 @@ export class Session extends EventEmitter {
4432
4606
  return false
4433
4607
  }
4434
4608
 
4435
- /**
4436
- * Whether this person has a cloud AI to hand work to (land.js asks it to settle a conflict in their
4437
- * square): in the session now, or connected to their account as the app last heard (cloudAiKnown,
4438
- * set by runner.js from the API's answer). Never their AI sessions on a computer: those are them.
4439
- */
4440
- hasCloudAi () {
4441
- if (this.aiOf || this.kind === 'agent') return false
4442
- return !!(this.cloudAiLive() || (this.cloudAiKnown && this.cloudAiKnown()))
4443
- }
4444
-
4445
- /**
4446
- * One note to this person about their own work (land.js: their version of a file kept aside when
4447
- * main's change won the same lines): from Quilt in chat, to them alone (the relay's quilt-note), and
4448
- * told to their AI sessions at their next call. A relay too old for it leaves the log line only.
4449
- */
4450
- noteToSelf (text) {
4451
- const t = String(text || '').slice(0, 1000)
4452
- if (!t) return
4453
- this.log(`🧵 ${t}`)
4454
- this.notice(t)
4455
- if (this.conn && this.conn.connected) this.conn.branchRequest({ op: 'quilt-note', text: t }).catch(() => {})
4456
- }
4457
-
4458
4609
  /** Who an action from this AI session is by: its own name, or this member's. */
4459
4610
  actorName (via) { const p = this.persona(via); return p ? p.name : this.name }
4460
4611
 
@@ -4866,10 +5017,10 @@ export class Session extends EventEmitter {
4866
5017
  }
4867
5018
 
4868
5019
  /**
4869
- * Whether an AI's edits here go into boxes (docs/superpowers/specs/2026-10-16-git-boxes-design.md):
4870
- * always, in a folder that is a git repository. One that isn't never boxes: nothing there could commit it.
5020
+ * Whether an AI's edits here go into boxes (docs/superpowers/specs/2026-10-16-git-boxes-design.md).
5021
+ * Boxes are off, by the owner's decision of 2026-11-16: no edit is boxed, in a git folder or any other.
4871
5022
  */
4872
- boxesOn () { return !!this.git }
5023
+ boxesOn () { return false }
4873
5024
 
4874
5025
  /** The box on rel when it is someone else's (their unfinished work: not written here), else null. */
4875
5026
  boxedByOther (rel) {
@@ -5248,15 +5399,6 @@ export class Session extends EventEmitter {
5248
5399
  /** The open ones, as the top of every tool answer says them to `me` ('' with none). */
5249
5400
  heldNotice (me = this.name) { return this.doc ? renderHeld(this.heldList(), { me }) : '' }
5250
5401
 
5251
- /** The session's stale_write_minutes: { minutes } (the owner's setting, else 15; 0: off). */
5252
- staleWrite () { return { minutes: staleWriteMinutes(this.doc, this.members) } }
5253
-
5254
- /** The owner sets the session's stale_write_minutes (0 turns the stale-write check off). */
5255
- setStaleWrite (minutes) {
5256
- if (!this.access || !this.access.owner) throw new Error('Only the session\'s owner sets how long a write may not remove lines someone else added.')
5257
- return { minutes: setStaleWriteMinutes(this.doc, { minutes, by: this.name }) }
5258
- }
5259
-
5260
5402
  /**
5261
5403
  * quilt_resolve_merge: settles one held conflict, named by its id or path. `how`: 'theirs' drops the
5262
5404
  * held lines (the file stays as it is), 'mine' puts them over the shared ones (merged with whatever
@@ -5282,35 +5424,28 @@ export class Session extends EventEmitter {
5282
5424
  return { already: false, record: r.record, text: `Resolved ${rec.path} (id ${rec.id}): ${said}.` }
5283
5425
  }
5284
5426
 
5285
- /** Writes a held record's lines over the shared file, here: only on the branch or square it was held on. Returns a few words on what changed. */
5427
+ /** Writes a held record's lines over the shared file, here: only on the branch it was held on. Returns a few words on what changed. */
5286
5428
  applyHeldMine (rec, v = rec) {
5287
5429
  const dir = this.heldDir(rec.id)
5288
5430
  // Texts kept on this machine (`local`) are this folder's writer's version only.
5289
5431
  const local = (name) => { if (v.by !== this.name) return null; try { return fs.readFileSync(path.join(dir, name)) } catch { return null } }
5290
- const onSquare = this.inSquare && this.inSquare.square
5291
- const elsewhere = rec.where.square ? rec.where.square !== onSquare : rec.where.branch ? (this.inSquare || rec.where.branch !== this.branchKey()) : false
5292
- if (elsewhere) throw new Error(`${rec.path} was held on ${rec.where.square ? `another square (sq:${rec.where.square.slice(-8)})` : `branch ${rec.where.branch}`}, not the one this folder is on: resolve it "mine" from a folder there, or write the file yourself and resolve it "edited".`)
5432
+ // A record an older Quilt held away from the session's branches (`where.square`) is on no branch a folder can be on.
5433
+ if (rec.where.square) throw new Error(`${rec.path} was held by an older Quilt, away from the session's branches, so its held lines can't be put in from a folder: write the file yourself and resolve it "edited".`)
5434
+ if (rec.where.branch && rec.where.branch !== this.branchKey()) throw new Error(`${rec.path} was held on branch ${rec.where.branch}, not the one this folder is on: resolve it "mine" from a folder there, or write the file yourself and resolve it "edited".`)
5293
5435
  const abs = resolveInside(this.root, rec.path)
5294
5436
  if (v.kind === 'binary') {
5295
5437
  const buf = local('mine')
5296
5438
  if (!buf) throw new Error(`${rec.path}'s held version is only on ${v.by}'s computer: ask them, or write the file yourself and resolve it "edited".`)
5297
5439
  fs.mkdirSync(path.dirname(abs), { recursive: true })
5298
5440
  fs.writeFileSync(abs, buf)
5299
- if (!this.inSquare) this.ingest(rec.path)
5441
+ this.ingest(rec.path)
5300
5442
  return 'their version of the file'
5301
5443
  }
5302
5444
  const mine = v.mine ?? (local('mine') ? local('mine').toString('utf8') : null)
5303
5445
  const result = v.result ?? (local('result') ? local('result').toString('utf8') : null)
5304
5446
  if (typeof mine !== 'string') throw new Error(`${rec.path}'s held lines are only on ${v.by}'s computer (the file is too big to share them): ask them, or write the file yourself and resolve it "edited".`)
5305
- let current = null
5306
- if (this.inSquare) { try { current = fs.readFileSync(abs, 'utf8') } catch {} } else current = this.files.get(rec.path)?.toString() ?? null
5307
- const text = applyMine({ mine, result }, current)
5308
- if (this.inSquare) {
5309
- // The folder's block takes it in as this member's edit (live-block.js scan), as a resolution: no stale-write check.
5310
- this.liveRules().trust(rec.path, text)
5311
- fs.mkdirSync(path.dirname(abs), { recursive: true })
5312
- fs.writeFileSync(abs, text)
5313
- } else this.applyMerged(rec.path, text, 'resolving a held conflict ("mine")')
5447
+ const text = applyMine({ mine, result }, this.files.get(rec.path)?.toString() ?? null)
5448
+ this.applyMerged(rec.path, text, 'resolving a held conflict ("mine")')
5314
5449
  return `${(v.hunks || []).length + (v.more || 0)} change(s)${v.by !== rec.by || versionsOf(rec).length > 1 ? ` (${v.by}'s)` : ''}`
5315
5450
  }
5316
5451
 
@@ -5545,12 +5680,9 @@ export class Session extends EventEmitter {
5545
5680
  const fromGithub = (p) => { const v = gh && gh.get(p); return v && typeof v.sha === 'string' ? { sha: v.sha, by: v.by || '', at: v.at || 0, came: v.came || 0, subject: v.subject || '' } : null }
5546
5681
  const out = []
5547
5682
  // A diff branch's files the session never changed are the folder's own checkout's (branch-view.js): listed too.
5548
- // Following a square in place (layout 3), the folder is the square's live copy: listed from disk.
5549
- const square = this.squareFiles()
5550
- const listed = square ? new Set(square.keys()) : this.diffForm ? new Set([...this.sharedPaths(), ...[...this.gitOnly.keys()].filter((p) => this.followsGit(p) && this.onDisk(p))]) : this.sharedPaths()
5683
+ const listed = this.diffForm ? new Set([...this.sharedPaths(), ...[...this.gitOnly.keys()].filter((p) => this.followsGit(p) && this.onDisk(p))]) : this.sharedPaths()
5551
5684
  for (const p of listed) {
5552
5685
  if (!isSafeRelPath(p)) continue
5553
- if (square) { out.push({ path: p, binary: square.get(p), edited: edited.get(p) || null, box: boxOf(p), github: null }); continue }
5554
5686
  const blob = this.blobs.get(p)
5555
5687
  out.push({ path: p, binary: blob ? !this.files.has(p) : this.diffForm && this.files.has(p) === false && /^bin:/.test(String(this.gitOnly.get(p) || '')), edited: edited.get(p) || null, box: boxOf(p), github: fromGithub(p) })
5556
5688
  }
@@ -5574,46 +5706,7 @@ export class Session extends EventEmitter {
5574
5706
  return out
5575
5707
  }
5576
5708
 
5577
- /**
5578
- * While the folder follows its square in place (layout 3, session-follow.js), the folder IS the
5579
- * square's live copy: every edit of everyone on the square comes to disk, and the branch document
5580
- * the session synced with is frozen, read-only, for a move back. So the app's Files and file views
5581
- * read the folder then: path -> whether it is binary (sniffed once per size and time), or null when
5582
- * the folder does not follow a square.
5583
- */
5584
- squareFiles () {
5585
- if (!this.inSquare) return null
5586
- const seen = this.squareSniff || (this.squareSniff = new Map()) // path -> { key, binary }
5587
- const out = new Map()
5588
- for (const rel of walk(this.root, this.ig)) {
5589
- if (!this.syncable(rel)) continue
5590
- let st
5591
- try { st = fs.statSync(path.join(this.root, rel)) } catch { continue }
5592
- const key = `${st.size}:${st.mtimeMs}`
5593
- let c = seen.get(rel)
5594
- if (!c || c.key !== key) {
5595
- let binary = st.size > MAX_TEXT_BYTES
5596
- if (!binary) { try { binary = looksBinary(fs.readFileSync(path.join(this.root, rel))) } catch { continue } }
5597
- c = { key, binary }
5598
- seen.set(rel, c)
5599
- }
5600
- out.set(rel, c.binary)
5601
- }
5602
- for (const rel of seen.keys()) if (!out.has(rel)) seen.delete(rel)
5603
- return out
5604
- }
5605
-
5606
- /** One file of the folder while it follows its square (squareFiles): its bytes, or null when the session doesn't sync it or it is not there. */
5607
- squareFileBytes (rel) {
5608
- if (!this.syncable(rel)) return null
5609
- try {
5610
- const p = path.join(this.root, rel)
5611
- if (!fs.statSync(p).isFile()) return null
5612
- return fs.readFileSync(p)
5613
- } catch { return null }
5614
- }
5615
-
5616
- /** Contents of one shared file, straight from the shared doc (never from disk, but for a folder following its square: squareFiles); a chat file from the chat files folder. */
5709
+ /** Contents of one shared file, straight from the shared doc (never from disk); a chat file from the chat files folder. */
5617
5710
  readShared (rel) {
5618
5711
  rel = String(rel || '').replace(/^\.\//, '')
5619
5712
  if (!isSafeRelPath(rel)) return null
@@ -5623,11 +5716,6 @@ export class Session extends EventEmitter {
5623
5716
  const buf = fs.readFileSync(path.join(this.root, rel))
5624
5717
  return buf.length <= MAX_TEXT_BYTES && !looksBinary(buf) ? { path: rel, text: buf.toString('utf8'), chat: e.chat } : { path: rel, binary: true, size: buf.length, chat: e.chat }
5625
5718
  }
5626
- if (this.inSquare) {
5627
- const buf = this.squareFileBytes(rel)
5628
- if (!buf) return null
5629
- return buf.length <= MAX_TEXT_BYTES && !looksBinary(buf) ? { path: rel, text: buf.toString('utf8') } : { path: rel, binary: true, size: buf.length }
5630
- }
5631
5719
  const t = this.files.get(rel)
5632
5720
  if (t) return { path: rel, text: t.toString() }
5633
5721
  const b = this.blobs.get(rel)
@@ -5647,10 +5735,6 @@ export class Session extends EventEmitter {
5647
5735
  if (!this.chatFileEntries().some((x) => x.path === rel)) return null
5648
5736
  return { path: rel, buf: fs.readFileSync(path.join(this.root, rel)) }
5649
5737
  }
5650
- if (this.inSquare) {
5651
- const buf = this.squareFileBytes(rel)
5652
- return buf ? { path: rel, buf } : null
5653
- }
5654
5738
  const t = this.files.get(rel)
5655
5739
  if (t) return { path: rel, buf: Buffer.from(t.toString(), 'utf8') }
5656
5740
  const b = this.blobs.get(rel)
@@ -5707,30 +5791,14 @@ export class Session extends EventEmitter {
5707
5791
  if (v && !p.persona) p.voice = { muted: v.muted, ...(v.transcribing ? { transcribing: true } : {}), ...(v.sharing ? { sharing: true } : {}) }
5708
5792
  }
5709
5793
  const myVoice = voices.get(this.name)
5710
- const square = this.squareFollower ? this.squareFollower.status() : null
5711
5794
  return {
5712
5795
  room: this.room,
5713
5796
  server: this.server,
5714
5797
  branch: this.branch,
5798
+ // A git checkout: where git has the folder, and whether its sync is held (git at work, or moving to the branch `to`).
5799
+ git: this.git ? { branch: this.git.branch, key: this.git.key, hold: this.hold ? { kind: this.hold.kind, since: this.hold.since, to: this.hold.to || null, waiting: this.hold.waiting || null } : null } : null,
5715
5800
  connected: !!(this.conn && this.conn.connected),
5716
5801
  ...(this.relayProblem ? { problem: this.relayProblem } : {}),
5717
- // The quilt the session is linked to (the app's History, Blame and search read it through the relay).
5718
- ...(this.quiltLink() ? { quilt: this.quiltLink() } : {}),
5719
- // At layout 3: the square this folder follows, with its one line (session-follow.js), and a write the relay could not keep.
5720
- ...(square ? { square } : {}),
5721
- // In Seam: each branch's square, as Seam names it (the app's sidebar shows who is on which).
5722
- ...(this.quilt && this.quilt.layout === 3 ? { squares: Object.fromEntries(Object.entries(this.quilt.live || {}).filter(([, k]) => typeof k === 'string' && k.startsWith('quilt/')).map(([b, k]) => [b, squareShort(k.slice('quilt/'.length))])) } : {}),
5723
- // The owner is moving the session into Seam or back right now (the relay's `moving`): { kind, since, line }.
5724
- ...(this.moving ? { moving: { ...this.moving, line: movingLine(this.moving) } } : {}),
5725
- // The forced date (16 flag 9): live sync stopped here (`stopped`), or when it is ({ at, remote }).
5726
- ...(this.force ? { force: this.force } : {}),
5727
- // "Make this a quilt" on a session with a git remote: Seam importing it ({ slug, repo }), or linked (quiltShadow).
5728
- ...(this.quiltImporting ? { importing: this.quiltImporting } : {}),
5729
- ...(this.quiltShadow ? { shadow: this.quiltShadow } : {}),
5730
- // The folder's branch has no square in the quilt (openSquareHere; the app's button opens one).
5731
- ...(!square && this.squareless() ? { squareless: this.squareless() } : {}),
5732
- // Until the folder follows a square, its edits reach nobody: said until it does.
5733
- ...(this.readOnly && this.quilt && this.quilt.layout === 3 && !(square && !square.opening && !square.problem) ? { readOnly: this.readOnly } : {}),
5734
5802
  access: this.access,
5735
5803
  sessionName: this.sessionName,
5736
5804
  members: this.members,
@@ -5762,8 +5830,6 @@ export class Session extends EventEmitter {
5762
5830
  merges: this.mergeList().map((m) => this.mergeStatus(m)),
5763
5831
  // Held conflicts (held.js): every open one in the session, whoever's, until someone resolves it.
5764
5832
  held: this.heldList(),
5765
- // How long a write may not remove lines someone else added (the owner's stale_write_minutes; 0: off).
5766
- staleWriteMinutes: staleWriteMinutes(this.doc, this.members),
5767
5833
  catchUp: this.catchUp,
5768
5834
  activity: this.activity.toArray().slice(-30),
5769
5835
  changes: this.changes().people.map((p) => ({ ...p, files: p.files.slice(0, 10), pulled: p.pulled && { ...p.pulled, files: p.pulled.files.slice(0, 10) } })),
@@ -5773,21 +5839,8 @@ export class Session extends EventEmitter {
5773
5839
  }
5774
5840
  }
5775
5841
 
5776
- /**
5777
- * How many files the session shares here. Following a square in place, the folder is the square's live
5778
- * copy (squareFiles), never the frozen branch document (2026-11-14: quilt_status said 4 with 5), looked
5779
- * at no more than every few seconds.
5780
- */
5781
- sharedFileCount () {
5782
- if (!this.inSquare) return this.files.size + this.blobs.size
5783
- const now = Date.now()
5784
- if (!this.squareCount || now - this.squareCount.at > 3000) {
5785
- let n = 0
5786
- try { n = (this.squareFiles() || new Map()).size } catch {}
5787
- this.squareCount = { at: now, n }
5788
- }
5789
- return this.squareCount.n
5790
- }
5842
+ /** How many files the session shares here. */
5843
+ sharedFileCount () { return this.files.size + this.blobs.size }
5791
5844
 
5792
5845
  scheduleStatusWrite () {
5793
5846
  if (this.statusTimer || !this.ready) return
@@ -5807,9 +5860,7 @@ export class Session extends EventEmitter {
5807
5860
  for (const t of this.rechecks.values()) clearTimeout(t)
5808
5861
  this.rechecks.clear()
5809
5862
  clearInterval(this.reconcileTimer)
5810
- clearInterval(this.readRenewTimer)
5811
5863
  clearInterval(this.upstreamPoll)
5812
- if (this.squareFollower) await this.squareFollower.stop()
5813
5864
  clearTimeout(this.clashTimer)
5814
5865
  if (this.clashPending) clearTimeout(this.clashPending.timer)
5815
5866
  clearTimeout(this.upstreamTimer)