heyquilt 0.3.175 → 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.
- package/RELEASES.md +13 -0
- package/package.json +2 -2
- package/src/connection.js +5 -3
- package/src/gitstate.js +326 -0
- package/src/live-merge.js +21 -2
- package/src/mcp.js +1 -1
- package/src/merge3.js +17 -1
- package/src/relay-live-write.js +10 -4
- package/src/session.js +836 -36
- package/src/setup.js +8 -0
- package/src/status.js +2 -0
- package/src/ui/agent-guide.js +2 -1
package/src/session.js
CHANGED
|
@@ -41,10 +41,10 @@ import { MentionRunner, parseOnMention, readOnMention, writeOnMention } from './
|
|
|
41
41
|
import { pickChecklist } from './agent-task-workflow.js'
|
|
42
42
|
import { changeRefusal, TALK_REFUSED } from './session-access.js'
|
|
43
43
|
import { canAdmit } from './admit-policy.js'
|
|
44
|
-
import { merge3, hasMarkers, mergeLive } from './merge3.js'
|
|
44
|
+
import { merge3, mergeAuto, hasMarkers, mergeLive } from './merge3.js'
|
|
45
45
|
import { sameEditClient, asClient } from './same-edit.js'
|
|
46
46
|
import { openMerge, updateMerge, readMerges, pruneMerges, cleanName } from './merges.js'
|
|
47
|
-
import { LiveRules, applyMine, findUses, removedNameWarning } from './live-merge.js'
|
|
47
|
+
import { LiveRules, applyMine, findUses, removedNameWarning, clashNotice, clashStillNotice } from './live-merge.js'
|
|
48
48
|
import { versionOf } from './read-bases.js'
|
|
49
49
|
import { RecentTexts, olderCopyNotice } from './base-pick.js'
|
|
50
50
|
import { swapIn, settled, savedInto } from './swap-in.js'
|
|
@@ -54,6 +54,7 @@ import { RELAY_NAME as RELAY_BY, isRelay } from './ui/chat.js'
|
|
|
54
54
|
import { cleanTyping, TYPING_MS, AGENT_TYPING_MS } from './ui/chat.js'
|
|
55
55
|
import { DEFAULT_KEY } from './branchdocs.js'
|
|
56
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'
|
|
57
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'
|
|
58
59
|
import { toolInUse } from './agents/common.js'
|
|
59
60
|
|
|
@@ -71,19 +72,6 @@ function hasGitDir (root) {
|
|
|
71
72
|
try { fs.statSync(path.join(root, '.git')); return true } catch { return false }
|
|
72
73
|
}
|
|
73
74
|
|
|
74
|
-
/** The branch a git checkout in `root` is on, read from .git/HEAD (no git run); null when none or detached. */
|
|
75
|
-
function headBranch (root) {
|
|
76
|
-
try {
|
|
77
|
-
let dir = path.join(root, '.git')
|
|
78
|
-
if (fs.statSync(dir).isFile()) {
|
|
79
|
-
const m = /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(dir, 'utf8'))
|
|
80
|
-
if (!m) return null
|
|
81
|
-
dir = path.resolve(root, m[1].trim())
|
|
82
|
-
}
|
|
83
|
-
const m = /^ref:\s*refs\/heads\/(.+)$/m.exec(fs.readFileSync(path.join(dir, 'HEAD'), 'utf8'))
|
|
84
|
-
return m ? m[1].trim() : null
|
|
85
|
-
} catch { return null }
|
|
86
|
-
}
|
|
87
75
|
const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904' // git's empty tree, the base of a branch pushed from nothing
|
|
88
76
|
|
|
89
77
|
/**
|
|
@@ -146,8 +134,14 @@ const RETRY_MS = 30 * 1000
|
|
|
146
134
|
const MOVE_RETRY_MAX_MS = 5 * 60 * 1000
|
|
147
135
|
// Large uploads and downloads each hold the whole file in memory (twice), so only this many run at once.
|
|
148
136
|
const MAX_TRANSFERS = 2
|
|
137
|
+
// Queued when HEAD moves, so a checkout that changes no file still runs flushPending. Never syncable (.quilt is ignored).
|
|
138
|
+
const HEAD_CHANGED = '.quilt/HEAD-changed'
|
|
149
139
|
// Settles in a row that couldn't ask git (about a minute) before saying so; the folder stays held regardless.
|
|
150
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
|
|
151
145
|
const FLUSH_MS = 40 // file changes are flushed this long after the first
|
|
152
146
|
// How often a folder looks for commits its branch is behind (fetching its upstream first).
|
|
153
147
|
const UPSTREAM_MS = Number(process.env.QUILT_UPSTREAM_MS) || 60 * 1000
|
|
@@ -321,6 +315,8 @@ export class Session extends EventEmitter {
|
|
|
321
315
|
this.lastKnown = new Map() // path -> text content, or "bin:<sha1>"
|
|
322
316
|
this.relayWriting = new Set() // paths with a live write at the relay, not answered yet (relayIngest)
|
|
323
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)
|
|
324
320
|
this.relayLocal = new Set() // paths the relay asked to be edited here as before (its answer's `fallback`), once
|
|
325
321
|
this.overwritten = new RecentTexts() // the texts Quilt replaced on disk, and the saves made from them (base-pick.js)
|
|
326
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
|
|
@@ -375,19 +371,19 @@ export class Session extends EventEmitter {
|
|
|
375
371
|
this.startNameSent = false
|
|
376
372
|
this.logs = [] // the last 200 log lines (for status and tests)
|
|
377
373
|
// Git awareness (gitstate.js): a git operation in this folder is recognised, not broadcast as edits.
|
|
378
|
-
this.git = null // { key, branch, sha } this folder
|
|
379
|
-
this.gitSeen = null // the head last
|
|
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
|
|
380
376
|
this.gitIndex = null // indexStamp at the last flush
|
|
381
377
|
this.gitWatcher = null
|
|
382
|
-
this.hold = null // { kind: 'busy'|'
|
|
378
|
+
this.hold = null // { kind: 'busy'|'switching', since, to?, waiting? } while this folder's sync is held (git at work; moving to another branch)
|
|
383
379
|
this.upstreamAfterHold = null // a look at the upstream asked while held ({ fetch }): asked again when the hold ends
|
|
384
380
|
this.heldPaths = new Set() // paths that changed (here or in the room) while held
|
|
385
381
|
this.heldConflicts = new Set() // paths git left a conflict in during this hold (see noteConflict)
|
|
386
382
|
this.stashSeen = null // the stash's mark when the folder was last quiet: a change by the settle means the person stashed
|
|
387
383
|
this.headChangedAt = 0
|
|
388
384
|
this.settleTimer = null
|
|
389
|
-
this.savedGit = null // { key, sha
|
|
390
|
-
this.rejoin = false //
|
|
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
|
|
391
387
|
this.gitFailures = 0 // settles in a row that couldn't ask git
|
|
392
388
|
// Commits made outside the session that this branch is behind (see bringIn): { name, url, sha,
|
|
393
389
|
// behind, ahead, diverged, conflicts, waiting, checkedAt } of the branch's upstream, or null.
|
|
@@ -585,8 +581,16 @@ export class Session extends EventEmitter {
|
|
|
585
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.
|
|
586
582
|
this.gitAside = hasGitDir(this.root) ? null : gitAsideOf(this.root)
|
|
587
583
|
if (hadState) this.loadBoxes()
|
|
588
|
-
//
|
|
589
|
-
|
|
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
|
|
590
594
|
// The form saved is the saved branch's; another branch's is the relay's to say when it is joined.
|
|
591
595
|
if (this.savedBranch !== this.branch) { this.branchForm = null; this.diffBase = null }
|
|
592
596
|
|
|
@@ -605,7 +609,7 @@ export class Session extends EventEmitter {
|
|
|
605
609
|
doc: this.doc,
|
|
606
610
|
// An app's saved document from before branch documents is the room's old one: the relay kept it as that branch's.
|
|
607
611
|
// base: the commit a branch new to the session starts from (a partner without it locally creates it there).
|
|
608
|
-
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 } : {}) },
|
|
609
613
|
// state.bin is a copy of an older document of this branch (it was removed and started again): never merged.
|
|
610
614
|
onStaleBranch: (reply) => this.staleBranch(reply),
|
|
611
615
|
beforeRemote: () => { if (this.ready) this.flushPending() }
|
|
@@ -625,13 +629,15 @@ export class Session extends EventEmitter {
|
|
|
625
629
|
this.conn.on('access', (a) => this.setAccess(a))
|
|
626
630
|
this.conn.on('members', (m) => this.setMembers(m))
|
|
627
631
|
this.conn.on('branches', (list) => this.setBranches(list))
|
|
632
|
+
// A move's own join is the move's to finish (finishMove): this.branch changes only once the folder is there.
|
|
628
633
|
this.conn.on('branch-joined', (r) => {
|
|
629
|
-
if (typeof r.branch !== 'string' || !r.branch) return
|
|
634
|
+
if (typeof r.branch !== 'string' || !r.branch || (this.hold && this.hold.kind === 'switching')) return
|
|
630
635
|
if (typeof r.epoch === 'string' && r.epoch && !this.staleRejoin) this.branchEpoch = r.epoch
|
|
631
636
|
// An older relay says no form: its documents are all full ones.
|
|
632
637
|
this.branchForm = r.form === 'diff' ? 'diff' : 'full'
|
|
633
638
|
if (r.form === 'diff' && typeof r.diffBase === 'string') this.diffBase = r.diffBase
|
|
634
639
|
this.branch = r.branch
|
|
640
|
+
this.announceBranch()
|
|
635
641
|
this.scheduleStatusWrite()
|
|
636
642
|
})
|
|
637
643
|
this.conn.on('branch-refused', (why) => this.log(`⚠️ the relay refused this folder's branch: ${why}`))
|
|
@@ -643,7 +649,7 @@ export class Session extends EventEmitter {
|
|
|
643
649
|
// We've synced this folder before: hold what was edited while we were
|
|
644
650
|
// away, let the relay tell us what the others did, then merge the two.
|
|
645
651
|
const marks = historyMarks(this.history.entries()) // what we had seen: the catch-up is the rest
|
|
646
|
-
const offline = this.captureOffline(null)
|
|
652
|
+
const offline = away ? { entries: [], take: [], downloads: [] } : this.captureOffline(null)
|
|
647
653
|
this.goLive()
|
|
648
654
|
if (offline.entries.length) this.log(`${offline.entries.length} file(s) changed while you were away; merging once the relay has synced…`)
|
|
649
655
|
const synced = this.conn.waitForSync()
|
|
@@ -655,6 +661,15 @@ export class Session extends EventEmitter {
|
|
|
655
661
|
this.awayBackups = null
|
|
656
662
|
this.emit('debug', `offline merge did not run: ${err && err.message}`)
|
|
657
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
|
+
}
|
|
658
673
|
} else {
|
|
659
674
|
this.log('waiting for relay…')
|
|
660
675
|
const sync = this.conn.waitForSync()
|
|
@@ -917,10 +932,12 @@ export class Session extends EventEmitter {
|
|
|
917
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)
|
|
918
933
|
this.known = meta.known ? new Map(Object.entries(meta.known)) : null
|
|
919
934
|
this.behindAtSave = new Map(Object.entries(meta.behind && typeof meta.behind === 'object' ? meta.behind : {}).filter(([, v]) => typeof v === 'string'))
|
|
920
|
-
// No gitKey (an older state file): taken as the branch the folder is on now.
|
|
921
935
|
this.savedRole = typeof meta.role === 'string' ? meta.role : null
|
|
922
936
|
this.savedSeenAt = typeof meta.seenAt === 'number' ? meta.seenAt : null
|
|
923
|
-
|
|
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
|
|
924
941
|
return true
|
|
925
942
|
} catch {
|
|
926
943
|
return false
|
|
@@ -1016,7 +1033,7 @@ export class Session extends EventEmitter {
|
|
|
1016
1033
|
}
|
|
1017
1034
|
// When we were last in touch with the session: "you left 3h ago" on the next catch-up.
|
|
1018
1035
|
if (this.conn && this.conn.connected) this.savedSeenAt = Date.now()
|
|
1019
|
-
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 } : {}) }))
|
|
1020
1037
|
}
|
|
1021
1038
|
|
|
1022
1039
|
/** This member's role, so the next start knows it before the relay says (ignoreQuiltState). */
|
|
@@ -1215,10 +1232,12 @@ export class Session extends EventEmitter {
|
|
|
1215
1232
|
|
|
1216
1233
|
/** Merges one captured path. Returns what happened, or null when nothing needed doing. */
|
|
1217
1234
|
async mergeOne (e) {
|
|
1235
|
+
if (e.carried) return this.mergeCarried(e) // work a checkout carried from another branch
|
|
1218
1236
|
const { rel, base, via = null } = e
|
|
1219
1237
|
const release = () => this.merging.delete(rel)
|
|
1220
1238
|
const disk = this.readDisk(rel)
|
|
1221
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
|
|
1222
1241
|
const ours = disk ? disk.key : null // re-read: it may have changed again before the relay synced
|
|
1223
1242
|
const theirs = this.sharedKey(rel)
|
|
1224
1243
|
const theirsBy = this.lastEditorOf(rel)
|
|
@@ -1542,6 +1561,23 @@ export class Session extends EventEmitter {
|
|
|
1542
1561
|
this.flushTimer = null
|
|
1543
1562
|
const paths = [...this.pending]
|
|
1544
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
|
+
}
|
|
1545
1581
|
this.ingestAll(paths)
|
|
1546
1582
|
}
|
|
1547
1583
|
|
|
@@ -1559,6 +1595,698 @@ export class Session extends EventEmitter {
|
|
|
1559
1595
|
try { fs.lstatSync(path.join(this.root, ...rel.split('/'))); return true } catch { return false }
|
|
1560
1596
|
}
|
|
1561
1597
|
|
|
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.
|
|
1607
|
+
|
|
1608
|
+
/**
|
|
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.
|
|
1612
|
+
*/
|
|
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
|
|
1618
|
+
}
|
|
1619
|
+
|
|
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
|
|
1624
|
+
}
|
|
1625
|
+
|
|
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)
|
|
1633
|
+
}
|
|
1634
|
+
|
|
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) }
|
|
1640
|
+
|
|
1641
|
+
/**
|
|
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.
|
|
1644
|
+
*/
|
|
1645
|
+
gitTask (fn) {
|
|
1646
|
+
const run = this.gitChain.then(() => this.stopped ? undefined : fn())
|
|
1647
|
+
this.gitChain = run.catch(() => {})
|
|
1648
|
+
return run
|
|
1649
|
+
}
|
|
1650
|
+
|
|
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)
|
|
1656
|
+
}
|
|
1657
|
+
|
|
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)
|
|
1664
|
+
this.scheduleStatusWrite()
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1667
|
+
releaseHold () {
|
|
1668
|
+
this.hold = null
|
|
1669
|
+
clearTimeout(this.settleTimer); this.settleTimer = null
|
|
1670
|
+
this.emit('hold', null)
|
|
1671
|
+
this.scheduleStatusWrite()
|
|
1672
|
+
}
|
|
1673
|
+
|
|
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
|
|
1692
|
+
}
|
|
1693
|
+
|
|
1694
|
+
/**
|
|
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.
|
|
1699
|
+
*/
|
|
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')
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
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])
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
/**
|
|
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.
|
|
1757
|
+
*/
|
|
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
|
+
}
|
|
1764
|
+
}
|
|
1765
|
+
|
|
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.
|
|
1771
|
+
|
|
1772
|
+
/**
|
|
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).
|
|
1777
|
+
*/
|
|
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
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
/**
|
|
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.
|
|
1800
|
+
*/
|
|
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 })
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1811
|
+
/**
|
|
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.
|
|
1816
|
+
*/
|
|
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)
|
|
1827
|
+
this.scheduleStatusWrite()
|
|
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.`)
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
|
|
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 }
|
|
1855
|
+
}
|
|
1856
|
+
|
|
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))
|
|
1860
|
+
}
|
|
1861
|
+
|
|
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
|
|
1871
|
+
}
|
|
1872
|
+
|
|
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))
|
|
1877
|
+
}
|
|
1878
|
+
|
|
1879
|
+
/**
|
|
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.
|
|
1883
|
+
*/
|
|
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 })
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
/**
|
|
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.
|
|
1916
|
+
*/
|
|
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 }
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
/**
|
|
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.
|
|
2009
|
+
*/
|
|
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}`) }
|
|
2020
|
+
}
|
|
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)
|
|
2025
|
+
}
|
|
2026
|
+
|
|
2027
|
+
/**
|
|
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.
|
|
2037
|
+
*/
|
|
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
|
|
2104
|
+
}
|
|
2105
|
+
|
|
2106
|
+
/**
|
|
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.
|
|
2112
|
+
*/
|
|
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)
|
|
2122
|
+
return null
|
|
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}`) }
|
|
2185
|
+
}
|
|
2186
|
+
|
|
2187
|
+
/**
|
|
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.)
|
|
2191
|
+
*/
|
|
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)
|
|
2216
|
+
}
|
|
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)
|
|
2243
|
+
try {
|
|
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 }
|
|
2254
|
+
}
|
|
2255
|
+
|
|
2256
|
+
/**
|
|
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.
|
|
2259
|
+
*/
|
|
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
|
+
})
|
|
2288
|
+
}
|
|
2289
|
+
|
|
1562
2290
|
/**
|
|
1563
2291
|
* Puts back the .git an older Quilt set aside in this folder (git-aside.js), once, when the session
|
|
1564
2292
|
* starts and the relay has synced. A folder that got a new .git meanwhile keeps both. Whether git came back.
|
|
@@ -1604,7 +2332,7 @@ export class Session extends EventEmitter {
|
|
|
1604
2332
|
ingest (rel, { pulled = false } = {}) {
|
|
1605
2333
|
if (!this.syncable(rel)) return false
|
|
1606
2334
|
if (this.merging.has(rel)) return false // its offline merge hasn't run yet; see mergeOffline
|
|
1607
|
-
|
|
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
|
|
1608
2336
|
if (this.downloading.has(rel)) return false // our copy is being replaced by a download
|
|
1609
2337
|
if (this.writeFailed.has(rel)) return false // the shared version never reached the disk: what's there is no edit of ours
|
|
1610
2338
|
// New ignore rules: a box of ours on a file they now leave out lets go (settleBoxesOnce).
|
|
@@ -1714,6 +2442,17 @@ export class Session extends EventEmitter {
|
|
|
1714
2442
|
return true
|
|
1715
2443
|
}
|
|
1716
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`)
|
|
1717
2456
|
if (disk.key === this.sharedKey(rel)) {
|
|
1718
2457
|
this.lastKnown.set(rel, disk.key)
|
|
1719
2458
|
if (stored && stored.stored) this.setOnDisk(rel, stored.hash)
|
|
@@ -1849,7 +2588,9 @@ export class Session extends EventEmitter {
|
|
|
1849
2588
|
...(typeof base === 'string' && base.length <= 256 * 1024 ? { baseText: base } : {}),
|
|
1850
2589
|
text,
|
|
1851
2590
|
...(older !== base && typeof older === 'string' ? { older } : {}),
|
|
1852
|
-
...(fromGit ? { fromGit: true } : {})
|
|
2591
|
+
...(fromGit ? { fromGit: 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 })
|
|
1853
2594
|
}
|
|
1854
2595
|
// What does not touch the text stays an edit here: its mode, and where a diff branch's entry started.
|
|
1855
2596
|
this.transact(() => {
|
|
@@ -1873,6 +2614,7 @@ export class Session extends EventEmitter {
|
|
|
1873
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 }
|
|
1874
2615
|
if (trusted && this.liveEngine) this.liveEngine.trusted.delete(rel)
|
|
1875
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)
|
|
1876
2618
|
const result = r.same ? disk.text : r.text
|
|
1877
2619
|
// A save told of a clash is not an older copy its writer may save from unknowing: what it saves next is meant.
|
|
1878
2620
|
const clashed = (r.held || []).length > 0
|
|
@@ -1887,7 +2629,11 @@ export class Session extends EventEmitter {
|
|
|
1887
2629
|
if (r.detail) this.transact(() => this.recordActivity(rel, created && !r.before ? 'created' : 'edited', r.detail, { before: r.before ?? '', after: result }, { pulled }), LOCAL)
|
|
1888
2630
|
let now = null
|
|
1889
2631
|
try { now = this.readDisk(rel) } catch {}
|
|
1890
|
-
|
|
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) {
|
|
1891
2637
|
// Disk still has what was sent: it gets the result (the lines that landed first, with this edit's others).
|
|
1892
2638
|
let over = true
|
|
1893
2639
|
if (result !== disk.text) {
|
|
@@ -1900,7 +2646,7 @@ export class Session extends EventEmitter {
|
|
|
1900
2646
|
}
|
|
1901
2647
|
// Saved again in that instant: that save is taken in next, merged on what was sent.
|
|
1902
2648
|
this.lastKnown.set(rel, over === false ? disk.text : result)
|
|
1903
|
-
} else this.lastKnown.set(rel, disk.text) // saved again since:
|
|
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
|
|
1904
2650
|
this.setOnDisk(rel, null)
|
|
1905
2651
|
for (const n of r.notices || []) this.notice(n)
|
|
1906
2652
|
for (const l of r.logs || []) this.log(l)
|
|
@@ -1916,6 +2662,45 @@ export class Session extends EventEmitter {
|
|
|
1916
2662
|
}
|
|
1917
2663
|
}
|
|
1918
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
|
+
|
|
1919
2704
|
/** A live write the relay never answered: an older relay (the edit goes in here, as before), or no connection (tried again). */
|
|
1920
2705
|
relayFailed (rel, err) {
|
|
1921
2706
|
this.relayWriting.delete(rel)
|
|
@@ -2184,6 +2969,7 @@ export class Session extends EventEmitter {
|
|
|
2184
2969
|
if (!this.syncable(rel)) return
|
|
2185
2970
|
if (this.ghost(rel)) return
|
|
2186
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
|
|
2187
2973
|
let abs
|
|
2188
2974
|
try { abs = resolveInside(this.root, rel) } catch (err) { this.log(err.message); return }
|
|
2189
2975
|
const shared = this.sharedKey(rel)
|
|
@@ -2583,6 +3369,7 @@ export class Session extends EventEmitter {
|
|
|
2583
3369
|
/** Tries failed uploads, downloads and writes again. */
|
|
2584
3370
|
retryFailed () {
|
|
2585
3371
|
if (!this.ready || this.stopped) return
|
|
3372
|
+
if (this.hold && this.hold.kind === 'switching' && !this.following) this.recheckSoon()
|
|
2586
3373
|
const failed = [...this.retry]
|
|
2587
3374
|
this.retry.clear()
|
|
2588
3375
|
for (const [rel, kind] of failed) {
|
|
@@ -2695,6 +3482,7 @@ export class Session extends EventEmitter {
|
|
|
2695
3482
|
disk = null // read again once it's our turn, so waiting uploads don't hold files in memory
|
|
2696
3483
|
if (this.uploading.get(rel) === hash) return
|
|
2697
3484
|
this.uploading.set(rel, hash)
|
|
3485
|
+
const doc = this.bdoc
|
|
2698
3486
|
// If a partner's version lands while this uploads, theirs wins (ours is kept as a conflict copy).
|
|
2699
3487
|
const sharedBefore = this.sharedKey(rel)
|
|
2700
3488
|
await this.startTransfer()
|
|
@@ -2718,6 +3506,8 @@ export class Session extends EventEmitter {
|
|
|
2718
3506
|
}
|
|
2719
3507
|
const now = this.readDisk(rel)
|
|
2720
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
|
|
2721
3511
|
if (this.sharedKey(rel) !== sharedBefore || this.downloading.has(rel)) return // a partner's version landed first: it stays
|
|
2722
3512
|
const existed = this.files.has(rel) || this.blobs.has(rel)
|
|
2723
3513
|
this.transact(() => {
|
|
@@ -2793,6 +3583,7 @@ export class Session extends EventEmitter {
|
|
|
2793
3583
|
if (!cur || cur.hash !== entry.hash) return // replaced meanwhile; that version is on its way
|
|
2794
3584
|
if (this.stopped) return
|
|
2795
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)
|
|
2796
3587
|
const abs = resolveInside(this.root, rel)
|
|
2797
3588
|
let st = null
|
|
2798
3589
|
try { st = fs.lstatSync(abs) } catch {}
|
|
@@ -2834,6 +3625,7 @@ export class Session extends EventEmitter {
|
|
|
2834
3625
|
// --------------------------------------------------------------- watcher --
|
|
2835
3626
|
|
|
2836
3627
|
async startWatcher () {
|
|
3628
|
+
this.startGitWatch()
|
|
2837
3629
|
this.scanDisk({ baseline: true }) // the folder was just reconciled; the first re-scan catches anything since
|
|
2838
3630
|
this.watcher = watch(this.root, {
|
|
2839
3631
|
ignoreInitial: true,
|
|
@@ -2863,7 +3655,13 @@ export class Session extends EventEmitter {
|
|
|
2863
3655
|
})
|
|
2864
3656
|
this.watcher.on('error', (err) => this.log(`watcher error: ${err.message}`))
|
|
2865
3657
|
await new Promise((resolve) => this.watcher.once('ready', resolve))
|
|
2866
|
-
this.reconcileTimer = setInterval(() => {
|
|
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)
|
|
2867
3665
|
this.reconcileTimer.unref()
|
|
2868
3666
|
this.scanDisk()
|
|
2869
3667
|
}
|
|
@@ -4219,10 +5017,10 @@ export class Session extends EventEmitter {
|
|
|
4219
5017
|
}
|
|
4220
5018
|
|
|
4221
5019
|
/**
|
|
4222
|
-
* Whether an AI's edits here go into boxes (docs/superpowers/specs/2026-10-16-git-boxes-design.md)
|
|
4223
|
-
*
|
|
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.
|
|
4224
5022
|
*/
|
|
4225
|
-
boxesOn () { return
|
|
5023
|
+
boxesOn () { return false }
|
|
4226
5024
|
|
|
4227
5025
|
/** The box on rel when it is someone else's (their unfinished work: not written here), else null. */
|
|
4228
5026
|
boxedByOther (rel) {
|
|
@@ -4997,6 +5795,8 @@ export class Session extends EventEmitter {
|
|
|
4997
5795
|
room: this.room,
|
|
4998
5796
|
server: this.server,
|
|
4999
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,
|
|
5000
5800
|
connected: !!(this.conn && this.conn.connected),
|
|
5001
5801
|
...(this.relayProblem ? { problem: this.relayProblem } : {}),
|
|
5002
5802
|
access: this.access,
|