heyquilt 0.3.170 → 0.3.172

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 (62) hide show
  1. package/RELEASES.md +30 -0
  2. package/bin/quilt.js +16 -9
  3. package/package.json +2 -2
  4. package/src/agent-task-workflow.js +2 -9
  5. package/src/base-pick.js +212 -0
  6. package/src/boxes.js +6 -7
  7. package/src/catchup.js +1 -1
  8. package/src/chat-links.js +1 -3
  9. package/src/connection.js +24 -5
  10. package/src/control.js +27 -20
  11. package/src/duties.js +32 -56
  12. package/src/github-commit.js +1 -1
  13. package/src/held.js +323 -0
  14. package/src/hooks.js +27 -66
  15. package/src/identity.js +1 -1
  16. package/src/inbox.js +5 -4
  17. package/src/key-cli.js +1 -1
  18. package/src/live-merge.js +599 -0
  19. package/src/mcp.js +57 -102
  20. package/src/merge3.js +65 -1
  21. package/src/now-summary.js +4 -6
  22. package/src/pathrules.js +1 -1
  23. package/src/persona.js +1 -1
  24. package/src/presence.js +2 -0
  25. package/src/protocol.js +2 -2
  26. package/src/read-bases.js +123 -0
  27. package/src/relay-ask.js +2 -2
  28. package/src/relay-live-write.js +179 -0
  29. package/src/relay-mcp.js +173 -212
  30. package/src/relay-prune.js +2 -2
  31. package/src/relay-turn-sync.js +146 -142
  32. package/src/runner.js +0 -2
  33. package/src/server.js +253 -375
  34. package/src/session-follow.js +3 -1
  35. package/src/session-quilt.js +2 -21
  36. package/src/session-seam.js +35 -7
  37. package/src/session.js +795 -553
  38. package/src/setup.js +15 -25
  39. package/src/source-live/bring-in.js +5 -5
  40. package/src/source-live/land.js +20 -3
  41. package/src/source-live/live-block.js +503 -52
  42. package/src/status.js +8 -12
  43. package/src/swap-in.js +81 -0
  44. package/src/textdiff.js +54 -0
  45. package/src/turn-sync-plan.js +6 -18
  46. package/src/turn-sync.js +28 -21
  47. package/src/ui/agent-guide.js +13 -13
  48. package/src/ui/app.css +19 -40
  49. package/src/ui/boxes.js +8 -16
  50. package/src/ui/common.js +1 -1
  51. package/src/ui/fileview.js +11 -15
  52. package/src/ui/loom-model.js +18 -16
  53. package/src/ui/loom.css +1 -2
  54. package/src/ui/loom.js +6 -6
  55. package/src/ui/rail-model.js +25 -64
  56. package/src/ui/rail.js +48 -60
  57. package/src/ui/seam-model.js +39 -3
  58. package/src/ui/session.js +36 -54
  59. package/src/ui/tree.js +22 -129
  60. package/src/ui-server.js +2 -6
  61. package/src/release-words.js +0 -18
  62. package/src/seam-claims.js +0 -53
@@ -0,0 +1,599 @@
1
+ // What happens to a live write when it arrives (Seam's plans/quilt-source-control/07 "Conflicts in the
2
+ // live state", ruling 2026-11-13): it is merged against the version its writer started from, and the
3
+ // ways a clash is caught run on it, in milliseconds, with no AI and no project code. One engine for
4
+ // every live path: on the relay, a folder's save sent as a live write (relay-live-write.js, from
5
+ // session.js ingest and source-live/live-block.js scan), a hosted agent's quilt_write_file and a
6
+ // sandboxed agent's `quilt sync` (relay-mcp.js, relay-turn-sync.js); in a folder, what a relay without
7
+ // live writes leaves to it, and offline merges (session.js autoSettle).
8
+ //
9
+ // same lines both changed them: the shared file keeps what landed first, the writer's lines are held
10
+ // stale write it removes lines another member added within stale_write_minutes: they stay, held to confirm
11
+ // removed name an identifier gone from the file is still used elsewhere: a warning, never a block
12
+ // parse a .json or plain .js file the merge broke: the whole write is held
13
+ // moves one writer deleted a path and added the same text elsewhere: edits to the old path follow
14
+ //
15
+ // Held lines go to the room's document (held.js), where every member's app and AI sees them.
16
+ import vm from 'node:vm'
17
+ import path from 'node:path'
18
+ import { diffLines as diffIndices } from './textdiff.js'
19
+ import { mergeLive } from './merge3.js'
20
+ import { HELD_MAP, addHeld, readHeld, settleHeld, overBudget, heldTaskTitle, STALE_WRITE_MINUTES } from './held.js'
21
+
22
+ export const ADDS_MAP = 'lineAdds' // in the file's document: "<path>\0<writer>" -> [{ ts, lines }]
23
+ export const MOVES_MAP = 'moves' // in the file's document: old path -> { to, by, ts, text }
24
+ export const MOVE_MS = 2 * 60 * 1000 // a deletion and an add of the same text by one writer this close together are a move
25
+ export const MOVE_KEEP_MS = 30 * 60 * 1000 // and edits to the old path follow it to the new one for this long
26
+ export const MAX_NAME_TEXT = 512 * 1024 // files past this are not searched for removed names
27
+ export const MAX_NAMES = 10
28
+ export const MAX_USES = 10
29
+ const ADDS_PER_KEY = 20
30
+ const MAX_MOVE_TEXT = 64 * 1024
31
+
32
+ const lines = (s) => String(s ?? '').split('\n')
33
+ const counts = (ls) => { const m = new Map(); for (const l of ls) m.set(l, (m.get(l) || 0) + 1); return m }
34
+
35
+ /** A line worth tracking as someone's addition: six characters or more with words in it, not only brackets or blank. */
36
+ export const significant = (l) => { const t = String(l).trim(); return t.length >= 6 && /\w/.test(t) }
37
+
38
+ /** The lines `after` has that `before` has not (each counted), keeping only significant ones. */
39
+ export function addedLines (before, after) {
40
+ const have = counts(lines(before))
41
+ const out = []
42
+ for (const l of lines(after)) {
43
+ const n = have.get(l) || 0
44
+ if (n) have.set(l, n - 1); else if (significant(l)) out.push(l)
45
+ }
46
+ return out
47
+ }
48
+
49
+ const words = (l) => new Set(String(l).match(/\w+/g) || [])
50
+
51
+ /** Whether `b` is `a` edited rather than replaced: half their words or more in common. */
52
+ export function similar (a, b) {
53
+ const x = words(a)
54
+ const y = words(b)
55
+ if (!x.size || !y.size) return false
56
+ let both = 0
57
+ for (const w of x) if (y.has(w)) both++
58
+ return both / (x.size + y.size - both) >= 0.5
59
+ }
60
+
61
+ /**
62
+ * Whether `n` (a writer's line where `l` was) is an edit of the older line `o` that `l` replaced, not
63
+ * of `l`: it drops a word `l` brought in. The mark of a whole file written from a
64
+ * read older than `l`, whose writer never saw `l` (2026-11-14: a stale write's line, similar to the
65
+ * newer one, replaced it without a word). `n` must be an edit of `o` (similar to it).
66
+ */
67
+ export function editsOlder (l, n, o) {
68
+ if (typeof o !== 'string' || !similar(o, n)) return false
69
+ const was = words(o)
70
+ const novel = [...words(l)].filter((w) => !was.has(w))
71
+ if (!novel.length) return false
72
+ const ws = words(n)
73
+ return novel.some((w) => !ws.has(w))
74
+ }
75
+
76
+ /**
77
+ * The stale-write check: `next` is what a write would make of `cur` (the shared text). Any change of
78
+ * it that removes one of `protect` (lines someone else added recently) is undone, so those lines
79
+ * stay; each undone change is a hunk held for the writer to confirm. A line changed into a similar
80
+ * one (an edit of it, not its removal) is not protected, unless the new line edits the older line the
81
+ * protected one replaced (`was`: protected line -> the line it replaced; editsOlder): that hunk is
82
+ * held too, marked `older` (the same line changed by two writers). `edits`: any lines in a protected
83
+ * line's place make it an edit (its writer saw it); only a removal is held. { text, held, lines }.
84
+ */
85
+ export function protectLines (cur, next, protect, { was = null, edits = false } = {}) {
86
+ const P = new Set((protect || []).filter(significant))
87
+ if (!P.size || cur === next) return { text: next, held: [], lines: [] }
88
+ const older = (l, n) => !!(was && was.has(l) && editsOlder(l, n, was.get(l)))
89
+ const a = lines(cur)
90
+ const b = lines(next)
91
+ const ca = counts(a)
92
+ const cb = counts(b)
93
+ const out = []
94
+ const held = []
95
+ const kept = new Set()
96
+ let pos = 0
97
+ for (const h of diffIndices(a, b)) {
98
+ const [bs, bl] = h.buffer2
99
+ out.push(...b.slice(pos, bs))
100
+ // `edits`: a line replaced by others in its place is edited, not removed (the writer saw it: base-pick.js).
101
+ const lost = edits && h.buffer2Content.some(significant) ? [] : h.buffer1Content.filter((l) => P.has(l) && (cb.get(l) || 0) < (ca.get(l) || 0) && !h.buffer2Content.some((n) => similar(l, n) && !older(l, n)))
102
+ if (lost.length) {
103
+ const edited = lost.every((l) => h.buffer2Content.some((n) => older(l, n)))
104
+ held.push({ at: out.length, base: h.buffer1Content, ours: h.buffer2Content, theirs: h.buffer1Content, ...(edited ? { older: true } : {}) })
105
+ out.push(...h.buffer1Content)
106
+ for (const l of lost) kept.add(l)
107
+ } else out.push(...h.buffer2Content)
108
+ pos = bs + bl
109
+ }
110
+ out.push(...b.slice(pos))
111
+ return { text: out.join('\n'), held, lines: [...kept] }
112
+ }
113
+
114
+ const MODULE = /^\s*(import\s*[\w{*'"]|export\s|export\{)/m
115
+
116
+ /**
117
+ * Why `text` does not parse as `p`'s language, or null when it does or there is nothing to check
118
+ * it with: a .json file must JSON.parse; a plain .js/.cjs file (no top-level import or export) must
119
+ * compile as a script. Nothing else is checked (no parser dependency).
120
+ */
121
+ export function parseProblem (p, text) {
122
+ const ext = path.posix.extname(String(p)).toLowerCase()
123
+ if (ext === '.json') {
124
+ try { JSON.parse(text); return null } catch (err) { return err.message }
125
+ }
126
+ if (ext === '.js' || ext === '.cjs') {
127
+ if (MODULE.test(text)) return null
128
+ const body = String(text).replace(/^#!.*/, '')
129
+ // Compiled as a function body, never run: a CommonJS file may `return` at its top level.
130
+ try { new vm.Script(`(function () {\n${body}\n})`, { filename: p }); return null } catch (err) { return err.message } // eslint-disable-line no-new
131
+ }
132
+ return null
133
+ }
134
+
135
+ const KEYWORDS = new Set(('abstract arguments async await boolean break byte case catch char class const continue debugger default delete do double else enum eval export extends false final finally float for function goto if implements import in instanceof int interface let long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with yield ' +
136
+ 'undefined NaN Infinity console window document require module exports process global globalThis ' +
137
+ 'def elif except lambda nonlocal pass raise None True False self from print assert ' +
138
+ 'func struct impl trait type pub mut match loop where crate mod use unsafe dyn ' +
139
+ 'select insert update values into table create where order group join left right inner outer ' +
140
+ 'string number object symbol bigint any never unknown readonly keyof declare namespace as is of get set then else end').split(' '))
141
+ const IDENT = /[A-Za-z_$][\w$]*/g
142
+ // Prose and markup: only names that look like code (camelCase, snake_case, $) count when removed there.
143
+ const PROSE = new Set(['.md', '.markdown', '.mdx', '.txt', '.rst', '.adoc', '.csv', '.tsv', '.log', '.html', '.htm', '.xml', '.svg'])
144
+ const codeLike = (n) => /[a-z][A-Z]/.test(n) || n.includes('_') || n.includes('$')
145
+
146
+ const names = (text) => new Set(String(text).match(IDENT) || [])
147
+
148
+ // Comments and string literals, by language, cheaply (one pass, no parser): a name only in a comment
149
+ // or a quoted string is no use of it. A template literal (`…`) is left as it is (it holds code).
150
+ const SLASH = new Set(['.js', '.mjs', '.cjs', '.jsx', '.ts', '.tsx', '.mts', '.cts', '.c', '.h', '.cc', '.cpp', '.hpp', '.cs', '.java', '.kt', '.kts', '.go', '.rs', '.swift', '.dart', '.scala', '.php', '.css', '.scss', '.less', '.json5', '.jsonc', '.vue', '.svelte'])
151
+ const HASH = new Set(['.py', '.rb', '.sh', '.bash', '.zsh', '.yml', '.yaml', '.toml', '.r', '.pl', '.ex', '.exs', '.nim', '.cr'])
152
+ const blank = (m) => m.replace(/[^\n]/g, ' ')
153
+
154
+ /** Blanks `text`'s comments (`line` starts one: '//' or '#'; `block`: C's) and quoted strings, keeping line breaks. */
155
+ function blankOut (text, { line, block }) {
156
+ const out = []
157
+ let i = 0
158
+ const n = text.length
159
+ while (i < n) {
160
+ const c = text[i]
161
+ if (block && c === '/' && text[i + 1] === '*') {
162
+ const e = text.indexOf('*/', i + 2)
163
+ const to = e < 0 ? n : e + 2
164
+ out.push(blank(text.slice(i, to))); i = to; continue
165
+ }
166
+ if (text.startsWith(line, i)) {
167
+ const e = text.indexOf('\n', i)
168
+ const to = e < 0 ? n : e
169
+ out.push(blank(text.slice(i, to))); i = to; continue
170
+ }
171
+ if (c === '\'' || c === '"') {
172
+ let j = i + 1
173
+ while (j < n && text[j] !== c && text[j] !== '\n') j += text[j] === '\\' ? 2 : 1
174
+ const to = Math.min(n, j + 1)
175
+ out.push(blank(text.slice(i, to))); i = to; continue
176
+ }
177
+ out.push(c); i++
178
+ }
179
+ return out.join('')
180
+ }
181
+
182
+ /** `text` with its comments and quoted strings blanked out (line breaks kept, so line numbers stay), for `p`'s language; as it is when not known. */
183
+ export function stripComments (p, text) {
184
+ const ext = path.posix.extname(String(p)).toLowerCase()
185
+ const t = String(text)
186
+ if (t.length > MAX_NAME_TEXT) return t
187
+ if (SLASH.has(ext)) return blankOut(t, { line: '//', block: true })
188
+ if (HASH.has(ext)) return blankOut(t, { line: '#', block: false })
189
+ if (ext === '.sql' || ext === '.lua' || ext === '.hs') return blankOut(t, { line: '--', block: false })
190
+ if (ext === '.html' || ext === '.htm' || ext === '.xml' || ext === '.svg' || ext === '.md') return t.replace(/<!--[\s\S]*?-->/g, blank)
191
+ return t
192
+ }
193
+
194
+ /** The names `p`'s text uses outside its comments and strings. */
195
+ export const codeNames = (p, text) => names(stripComments(p, text))
196
+
197
+ /** Identifiers in `before` that `after` has nowhere (comments and strings aside), worth looking for elsewhere: at most MAX_NAMES. */
198
+ export function removedNames (p, before, after) {
199
+ if (typeof before !== 'string' || typeof after !== 'string' || before === after) return []
200
+ if (before.length > MAX_NAME_TEXT || after.length > MAX_NAME_TEXT) return []
201
+ const prose = PROSE.has(path.posix.extname(String(p)).toLowerCase())
202
+ // Only the lines the write removed can hold a name it removed: those are read outside their comments and
203
+ // strings; a name still anywhere in `after` (even in a comment) is not gone (cheap, for a long file).
204
+ const left = counts(lines(after))
205
+ const removed = []
206
+ for (const l of lines(before)) { const k = left.get(l) || 0; if (k) left.set(l, k - 1); else removed.push(l) }
207
+ if (!removed.length) return []
208
+ // What `after` still names: its lines as they were (as they are), and the lines it added outside their comments.
209
+ const had = counts(lines(before))
210
+ const kept = []
211
+ const added = []
212
+ for (const l of lines(after)) { const k = had.get(l) || 0; if (k) { had.set(l, k - 1); kept.push(l) } else added.push(l) }
213
+ const now = new Set([...names(kept.join('\n')), ...codeNames(p, added.join('\n'))])
214
+ const gone = [...codeNames(p, removed.join('\n'))].filter((n) => !now.has(n) && n.length >= 4 && !KEYWORDS.has(n) && !/^\d/.test(n) && (!prose || codeLike(n)))
215
+ // Code-looking and longer names first: the likeliest to be a function or variable someone calls.
216
+ return gone.sort((a, b) => (codeLike(b) - codeLike(a)) || b.length - a.length).slice(0, MAX_NAMES)
217
+ }
218
+
219
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
220
+
221
+ /** Whole-word uses of `list` in `texts` (an iterable of [path, text]), skipping `skip`: [{ name, path, line }], at most `max`. */
222
+ export function findUses (list, texts, { skip = null, max = MAX_USES } = {}) {
223
+ const out = []
224
+ if (!list.length || !texts) return out
225
+ const res = list.map((n) => [n, new RegExp(`(^|[^\\w$])${escapeRe(n)}(?![\\w$])`)])
226
+ for (const [p, text] of texts) {
227
+ if (p === skip || typeof text !== 'string' || text.length > MAX_NAME_TEXT) continue
228
+ const here = res.filter(([n]) => text.includes(n))
229
+ if (!here.length) continue
230
+ const ls = stripComments(p, text).split('\n')
231
+ for (let i = 0; i < ls.length && out.length < max; i++) {
232
+ for (const [n, re] of here) if (re.test(ls[i])) { out.push({ name: n, path: p, line: i + 1 }); break }
233
+ }
234
+ if (out.length >= max) break
235
+ }
236
+ return out
237
+ }
238
+
239
+ /** The warning a writer gets for names it removed that other files still use, or ''. */
240
+ export function removedNameWarning (p, uses) {
241
+ if (!uses.length) return ''
242
+ const by = new Map()
243
+ for (const u of uses) by.set(u.name, [...(by.get(u.name) || []), `${u.path}:${u.line}`])
244
+ const parts = [...by].map(([n, at]) => `you removed \`${n}\` from ${p}; ${at.join(', ')} still ${at.length === 1 ? 'uses' : 'use'} it`)
245
+ return `${parts.join('; ')}. Nothing was blocked: check those uses still work.`
246
+ }
247
+
248
+ /** What resolving a held record "mine" writes, given what the file holds now: the writer's lines put back over it, or null when unknown. */
249
+ export function applyMine (rec, current, { mine = rec && rec.mine, result = rec && rec.result } = {}) {
250
+ if (typeof mine !== 'string') return null
251
+ if (typeof current !== 'string' || typeof result !== 'string' || current === result || current === mine) return mine
252
+ // Changed since it was held: the later changes stay, the writer's lines go over the held ones.
253
+ const r = mergeLive(result, mine, current)
254
+ return r.held.length ? r.mine : r.text
255
+ }
256
+
257
+ /** What others added to `p` in `doc` since `since` (not by `not`): one entry per write, [{ by, ts, lines }]. */
258
+ export function recentAdds (doc, p, { not = '', since = 0 } = {}) {
259
+ const out = []
260
+ if (!doc) return out
261
+ const m = doc.getMap(ADDS_MAP)
262
+ const prefix = `${p}\0`
263
+ m.forEach((list, key) => {
264
+ const by = key.slice(prefix.length)
265
+ if (!key.startsWith(prefix) || by === not || !Array.isArray(list)) return
266
+ for (const e of list) if (e && e.ts >= since && Array.isArray(e.lines)) out.push({ by, ts: e.ts, lines: e.lines.filter((l) => typeof l === 'string'), was: Array.isArray(e.was) ? e.was.filter((x) => Array.isArray(x) && typeof x[0] === 'string' && typeof x[1] === 'string') : [] })
267
+ })
268
+ return out
269
+ }
270
+
271
+ /**
272
+ * The lines a write must not drop without asking: those of each recent addition by someone else that
273
+ * the write leaves out entirely (none of its lines is in `text`), the mark of a whole file written
274
+ * from an older read. A write that keeps part of an addition is working on it, not overwriting it.
275
+ */
276
+ export function vanished (adds, text) {
277
+ const present = new Set(String(text).split('\n'))
278
+ const out = []
279
+ for (const e of adds) {
280
+ const ls = e.lines.filter(significant)
281
+ // A line edited rather than dropped is told apart where it changed (protectLines), not here.
282
+ if (ls.length && ls.every((l) => !present.has(l))) out.push(...ls)
283
+ }
284
+ return out
285
+ }
286
+
287
+ /**
288
+ * For each significant line `after` has where `before` had a similar one (an edit of a line, not a new
289
+ * one): [line, the line it replaced]. At most 200.
290
+ */
291
+ export function replacedLines (before, after) {
292
+ const out = []
293
+ for (const h of diffIndices(lines(before), lines(after))) {
294
+ if (!h.buffer1Content.length || !h.buffer2Content.length) continue
295
+ for (const n of h.buffer2Content) {
296
+ if (!significant(n)) continue
297
+ const o = h.buffer1Content.find((x) => similar(x, n))
298
+ if (o !== undefined && o !== n) out.push([n, o])
299
+ if (out.length >= 200) return out
300
+ }
301
+ }
302
+ return out
303
+ }
304
+
305
+ /**
306
+ * Notes lines `by` added to `p` now (`keepMs`: older entries are dropped as it goes); `was`: [line,
307
+ * the line it replaced] for the added lines that edit an older one (replacedLines).
308
+ */
309
+ export function noteAdds (doc, p, by, added, { now = Date.now(), keepMs = STALE_WRITE_MINUTES * 60_000, was = [] } = {}) {
310
+ if (!doc || !by) return
311
+ const m = doc.getMap(ADDS_MAP)
312
+ const key = `${p}\0${by}`
313
+ const old = Array.isArray(m.get(key)) ? m.get(key) : []
314
+ const kept = old.filter((e) => e && now - e.ts <= keepMs)
315
+ const cut = (l) => String(l).slice(0, 500)
316
+ const ls = added.slice(0, 200).map(cut)
317
+ const w = was.filter(([n]) => ls.includes(cut(n))).slice(0, 50).map(([n, o]) => [cut(n), cut(o)])
318
+ const next = added.length ? [...kept, { ts: now, lines: ls, ...(w.length ? { was: w } : {}) }].slice(-ADDS_PER_KEY) : kept
319
+ if (next.length) { if (next.length !== old.length || added.length) m.set(key, next) } else if (m.has(key)) m.delete(key)
320
+ // Anyone's entries gone stale with nothing newer: nobody needs them.
321
+ const stale = []
322
+ m.forEach((list, k) => { if (k !== key && Array.isArray(list) && !list.some((e) => e && now - e.ts <= keepMs)) stale.push(k) })
323
+ for (const k of stale) m.delete(k)
324
+ }
325
+
326
+ // Names a write removed from a file lately (removedNames), in the room's document, so a use another write
327
+ // adds of one still gone is said to its writer: name -> { path, by, ts }.
328
+ export const GONE_NAMES_MAP = 'goneNames'
329
+ export const GONE_KEEP_MS = 60 * 60 * 1000
330
+ const GONE_MAX = 200
331
+
332
+ /** Notes `names` gone from `p` by `by`'s write now (older notes go as it goes). */
333
+ export function noteGoneNames (room, p, by, list, { now = Date.now(), origin = null } = {}) {
334
+ if (!room || !list.length) return
335
+ const m = room.getMap(GONE_NAMES_MAP)
336
+ room.transact(() => {
337
+ for (const n of list) m.set(n, { path: p, by, ts: now })
338
+ const old = []
339
+ m.forEach((v, k) => { if (!v || now - (v.ts || 0) > GONE_KEEP_MS) old.push(k) })
340
+ for (const k of old) m.delete(k)
341
+ if (m.size > GONE_MAX) [...m.entries()].sort((a, b) => (a[1].ts || 0) - (b[1].ts || 0)).slice(0, m.size - GONE_MAX).forEach(([k]) => m.delete(k))
342
+ }, origin)
343
+ }
344
+
345
+ const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
346
+ /** Whether `text` defines `n` (a cheap look: `function n`, `class n`, `const n =`, `def n`, `n = function`…). */
347
+ const defines = (text, n) => new RegExp(`(^|[^\\w$])((function|class|const|let|var|def|fn|func|type|interface|struct|enum|trait)\\s*\\*?\\s+${escape(n)}(?![\\w$])|${escape(n)}\\s*[:=]\\s*(async\\b|function\\b|\\(|[\\w$]+\\s*=>))`, 'm').test(text)
348
+
349
+ /**
350
+ * The names a write of `p` (`prev` -> `text`) adds a use of that a write lately removed from another file,
351
+ * and that are still gone from it (its text in `texts`, comments aside): [{ name, from, by, ts }], at most 5.
352
+ */
353
+ export function usesOfGone (room, p, prev, text, texts, { now = Date.now() } = {}) {
354
+ if (!room || typeof text !== 'string' || text.length > MAX_NAME_TEXT) return []
355
+ const m = room.getMap(GONE_NAMES_MAP)
356
+ if (!m.size) return []
357
+ const added = addedLines(prev, text)
358
+ if (!added.length) return []
359
+ const used = codeNames(p, added.join('\n'))
360
+ const hits = []
361
+ for (const n of used) {
362
+ const e = m.get(n)
363
+ if (!e || e.path === p || now - (e.ts || 0) > GONE_KEEP_MS || defines(stripComments(p, text), n)) continue
364
+ hits.push({ name: n, from: e.path, by: e.by, ts: e.ts })
365
+ }
366
+ if (!hits.length) return []
367
+ const at = new Map()
368
+ try { for (const [q, t] of texts || []) if (hits.some((h) => h.from === q)) at.set(q, t) } catch {}
369
+ return hits.filter((h) => !(typeof at.get(h.from) === 'string' && codeNames(h.from, at.get(h.from)).has(h.name))).slice(0, 5)
370
+ }
371
+
372
+ /** The warning a writer gets for uses it added of names gone lately, or ''. */
373
+ export function goneNameWarning (p, list, me = '') {
374
+ if (!list.length) return ''
375
+ const ago = (ts) => { const s = Math.max(0, Math.round((Date.now() - ts) / 1000)); return s < 60 ? `${s}s ago` : `${Math.round(s / 60)}m ago` }
376
+ const parts = list.map((h) => `you added a use of \`${h.name}\` in ${p}, but ${h.by === me ? 'you' : h.by} removed it from ${h.from} ${ago(h.ts)} and it is not there now`)
377
+ return `${parts.join('; ')}. Nothing was blocked: check it still exists (it may have been renamed or moved).`
378
+ }
379
+
380
+ /**
381
+ * The engine both live paths share, one per session. Options: `room()` the room's Y.Doc (held
382
+ * conflicts and the stale-write setting); `staleMinutes()`; `notice(text)` for the writer's AI;
383
+ * `log(text)`; `texts()` the session's text files as [path, text] for the removed-name search;
384
+ * `origin` for the room's transactions; `folder` false for a writer with no folder (a hosted agent),
385
+ * which its notices say.
386
+ */
387
+ export class LiveRules {
388
+ constructor ({ room, staleMinutes = () => STALE_WRITE_MINUTES, notice = () => {}, log = () => {}, texts = () => [], origin = null, keepLocal = null, folder = true }) {
389
+ Object.assign(this, { room, staleMinutes, notice, log, texts, origin, keepLocal, folder })
390
+ this.recentGone = new Map() // path -> { text, by, ts }: deletions by this folder, for moves
391
+ this.recentNew = new Map() // path -> { text, by, ts }: files this folder created, for moves
392
+ this.trusted = new Map() // path -> text a resolution wrote to disk, taken in without the stale-write check
393
+ }
394
+
395
+ /** The next write of `p` with exactly `text` is a resolution's ("mine"): no stale-write check on it. */
396
+ trust (p, text) { this.trusted.set(p, text) }
397
+
398
+ heldMap () { const d = this.room(); return d ? d.getMap(HELD_MAP) : null }
399
+
400
+ /**
401
+ * One write of `p` by `by`: `ours` the writer's text, made on `base` (null when not known),
402
+ * `theirs` what the shared file holds now (null when it has nothing). `doc` is the file's own
403
+ * document (where additions and moves are kept). `where`: { branch } or { square }; `others`: who
404
+ * landed first; `union`: the project marks the path merge=union (.gitattributes), so both sides'
405
+ * lines go in where both changed them. Returns { text, held: [records], warnings: [strings] }:
406
+ * `text` is what the shared file and the writer's folder get.
407
+ * `seen`: the writer's folder vouches that `ours` was made on `base` (or `older`): it can tell who read its
408
+ * files (base-pick.js). A line someone added lately that this write changes is then its edit, whatever it
409
+ * changes of it: never held for looking like an edit of the line before it (editsOlder), nor for being
410
+ * unlike it (only a removal, with nothing in its place, asks its writer to confirm).
411
+ */
412
+ write ({ doc, where = {}, path: p, base = null, ours, theirs = null, by, byId = null, others = [], texts = null, union = false, strict = false, nameSearch = true, older = null, seen = false }) {
413
+ const now = Date.now()
414
+ const map = this.heldMap()
415
+ const all = map ? readHeld(map) : []
416
+ // `older`: the save was found to be made from this text, older than `base` (what its folder last had;
417
+ // base-pick.js). It is first put onto `base`: where it differs from `older` only, its changes stay; where
418
+ // `base` changed since (a partner's change that reached the folder after the save's read), the newer
419
+ // lines stay and the save's are held for its writer, never taken over them and never dropped unsaid.
420
+ const saved = ours
421
+ let olderHeld = []
422
+ let olderKind = 'lines'
423
+ let olderLines = []
424
+ // Held are only the lines both the save and the newer text changed: a line the save merely has as the older
425
+ // text had it (it never touched it) takes the newer one, with nothing held.
426
+ if (typeof older === 'string' && typeof base === 'string' && older !== base && older !== ours) {
427
+ const r0 = mergeLive(older, ours, base, { union })
428
+ if (r0.text !== ours) {
429
+ olderHeld = r0.held.map((h) => ({ at: h.at, base: h.base, ours: h.ours, theirs: h.theirs }))
430
+ // Only lines the save lacks: a stale write's (confirmable as one); anything else, the same lines.
431
+ if (olderHeld.length && olderHeld.every((h) => !h.ours.length)) { olderKind = 'stale'; olderLines = olderHeld.flatMap((h) => h.theirs).filter(significant) }
432
+ if (olderKind === 'stale' && !olderLines.length) olderKind = 'lines'
433
+ ours = r0.text
434
+ }
435
+ }
436
+ // Same lines: merged against what landed first (only when something did since the writer's base).
437
+ const landed = typeof theirs === 'string' && typeof base === 'string' && theirs !== base && theirs !== ours
438
+ let text = ours
439
+ let mine = ours
440
+ let held = []
441
+ let kind = null
442
+ let parseWhy = ''
443
+ if (landed) {
444
+ const r = mergeLive(base, ours, theirs, { union })
445
+ text = r.text; mine = r.mine; held = r.held
446
+ if (held.length) kind = 'lines'
447
+ // Parse: a file both sides left parsing that the merge broke is the writer's to settle, whole.
448
+ const bad = text !== ours && text !== theirs ? parseProblem(p, held.length ? mine : text) : null
449
+ if (bad && !parseProblem(p, ours) && !parseProblem(p, theirs)) {
450
+ held = diffIndices(lines(theirs), lines(mine)).map((h) => ({ at: h.buffer1[0], base: h.buffer1Content, ours: h.buffer2Content, theirs: h.buffer1Content }))
451
+ text = theirs
452
+ kind = 'parse'
453
+ parseWhy = bad
454
+ }
455
+ }
456
+ // Stale write: lines someone else added minutes ago stay, unless this writer was told and removes them again.
457
+ // `strict` (a write whose base is not known for sure): the writer's own recent lines stay too, since
458
+ // another of its writes at the same moment (another loop on one agent's key) may have added them.
459
+ const minutes = Number(this.staleMinutes()) || 0
460
+ const cur = typeof theirs === 'string' ? theirs : null
461
+ let stale = { text, held: [], lines: [] }
462
+ let preStale = text
463
+ // A text a resolution wrote ("mine"): what it removes was decided by whoever resolved it.
464
+ const trusted = this.trusted.get(p) === ours
465
+ if (trusted) this.trusted.delete(p)
466
+ if (cur !== null && kind !== 'parse' && minutes > 0 && text !== cur && !trusted) {
467
+ const windowMs = minutes * 60_000
468
+ // What the writer was told of already: its stale holds (open, or lately settled), any stale hold
469
+ // resolved "mine" lately, and the kept lines of its own same-line holds (it is resolving them).
470
+ const recent = (r) => r.state === 'open' || now - (r.resolvedTs || 0) < windowMs
471
+ const told = new Set([
472
+ ...all.filter((r) => r.kind === 'stale' && r.path === p && ((r.by === by && recent(r)) || (r.state === 'resolved' && r.how === 'mine' && recent(r)))).flatMap((r) => r.lines),
473
+ ...all.filter((r) => r.kind === 'lines' && r.path === p && r.by === by && recent(r)).flatMap((r) => r.hunks.flatMap((h) => h.theirs))
474
+ ])
475
+ const adds = recentAdds(doc, p, { not: strict ? '' : by, since: now - windowMs })
476
+ const protect = vanished(adds, text)
477
+ // The line each recent addition replaced, so a write that edits the older line is told apart (editsOlder).
478
+ const was = new Map()
479
+ if (!seen) for (const e of adds) for (const [n, o] of e.was || []) was.set(n, o)
480
+ const honored = protect.filter((l) => told.has(l))
481
+ const keep = protect.filter((l) => !told.has(l))
482
+ stale = protectLines(cur, text, keep, { was, edits: seen })
483
+ preStale = text
484
+ text = stale.text
485
+ if (kind === 'lines') mine = protectLines(cur, mine, keep, { was, edits: seen }).text
486
+ // Removed again after being told: honoured, and what told them is settled.
487
+ if (honored.length && map) {
488
+ for (const r of all) if (r.state === 'open' && r.kind === 'stale' && r.path === p && r.by === by && r.lines.some((l) => honored.includes(l))) settleHeld(this.room(), map, r.id, { how: 'mine', by }, this.origin)
489
+ }
490
+ }
491
+ // A record whose held lines are now in the file (its writer, or anyone, wrote them back in) is settled.
492
+ if (map) {
493
+ for (const r of all) {
494
+ if (r.state !== 'open' || r.path !== p || (r.kind !== 'lines' && r.kind !== 'parse') || !r.hunks.length) continue
495
+ if (r.hunks.every((h) => significant(h.ours.join(' ')) && text.includes(h.ours.join('\n')))) settleHeld(this.room(), map, r.id, { how: 'edited', by }, this.origin)
496
+ }
497
+ }
498
+ const records = []
499
+ const who = others.filter((n) => n && n !== by)
500
+ if (held.length && map) {
501
+ const reason = kind === 'parse' ? `merged with ${who.join(', ') || 'the session'}'s changes, ${p} would not parse (${String(parseWhy).slice(0, 200)})` : `${who.join(', ') || 'Someone'} changed the same lines first`
502
+ records.push(this.hold({ path: p, kind, by, byId, others: who, where, hunks: held, reason, result: text, mine }))
503
+ }
504
+ if (stale.held.length && map) {
505
+ // A line someone changed after the version this write started from, edited by it from the older line: a same-line clash.
506
+ const older = stale.held.filter((h) => h.older).map(({ older, ...h }) => h)
507
+ const removed = stale.held.filter((h) => !h.older)
508
+ const olderLines = new Set(older.flatMap((h) => h.theirs))
509
+ if (older.length) records.push(this.hold({ path: p, kind: 'lines', by, byId, others: who, where, hunks: older, reason: `${who.join(', ') || 'Someone'} changed the same line(s) after the version this write started from`, result: text, mine: preStale }))
510
+ if (removed.length) {
511
+ const ls = stale.lines.filter((l) => !olderLines.has(l))
512
+ records.push(this.hold({ path: p, kind: 'stale', by, byId, others: who, where, hunks: removed, lines: ls, reason: `the write removed ${ls.length} line(s) ${strict ? 'added' : 'someone else added'} in the last ${minutes} minutes${strict ? ', and the version it started from is not known' : ''}`, result: text, mine: preStale }))
513
+ }
514
+ }
515
+ if (olderHeld.length && map) {
516
+ const n = olderHeld.length
517
+ const reason = olderKind === 'stale'
518
+ ? `the save was made from an older read of ${p}: it lacks ${olderLines.length} line(s) the file had since, which stay`
519
+ : `${who.join(', ') || 'Someone'} changed the same line(s) after the version this save was made from (an older read of ${p}); ${n === 1 ? 'that hunk keeps' : 'those hunks keep'} the newer lines`
520
+ records.push(this.hold({ path: p, kind: olderKind, by, byId, others: who, where, hunks: olderHeld, lines: olderLines, reason, result: text, mine: mergeLive(base, saved, text).text }))
521
+ }
522
+ // What this write added, for the next writer's stale check (with the lines they replaced).
523
+ const prev = cur ?? base ?? ''
524
+ if (doc && minutes > 0) noteAdds(doc, p, by, addedLines(prev, text), { now, keepMs: minutes * 60_000, was: replacedLines(prev, text) })
525
+ // Removed names still used elsewhere: a warning, never a block (`nameSearch` false: the caller searches, with `gone`).
526
+ const warnings = []
527
+ const gone = removedNames(p, cur ?? base, text)
528
+ if (gone.length && nameSearch) {
529
+ let uses = []
530
+ try { uses = findUses(gone, (texts || this.texts)(), { skip: p }) } catch {}
531
+ const w = removedNameWarning(p, uses)
532
+ if (w) warnings.push(w)
533
+ }
534
+ // Names gone from the session lately: noted, and a use this write adds of one still gone is said.
535
+ try {
536
+ const room = this.room()
537
+ if (room) {
538
+ if (gone.length) noteGoneNames(room, p, by, gone, { now, origin: this.origin })
539
+ const w = goneNameWarning(p, usesOfGone(room, p, prev, text, (texts || this.texts)(), { now }), by)
540
+ if (w) warnings.push(w)
541
+ }
542
+ } catch {}
543
+ for (const r of records) {
544
+ const n = r.hunks.length + (r.more || 0)
545
+ // Past the two-attempt budget (held.js): the writer's AI stops, and the relay puts it on the board for their person.
546
+ if (overBudget(r)) {
547
+ this.notice(`Quilt held back your change(s) in ${p} again (id ${r.id}): ${r.reason}. It has been resolved ${r.attempts} times and clashed again each time, so it becomes a task on the board for your person ("${heldTaskTitle(r)}"). Stop working on this conflict and leave it to them; ${p} keeps the version that landed first.`)
548
+ this.log(`⚖️ ${p}: held again after ${r.attempts} resolutions; it goes to the board for a person`)
549
+ continue
550
+ }
551
+ // A hosted agent has no folder: the shared file is what it reads next.
552
+ const back = this.folder ? 'and your folder has it now' : 'which is what you read next'
553
+ this.notice(`Quilt held back ${r.kind === 'stale' ? `your removal of ${r.lines.length} line(s)` : `${n} of your change(s)`} in ${p}: ${r.reason}. ${p} keeps the version that landed first, ${back}. Resolve it with quilt_resolve_merge { path: "${p}", how: "theirs" | "mine" | "edited" } (id ${r.id}).`)
554
+ this.log(`⚖️ ${p}: ${r.reason}; your lines are held (quilt_resolve_merge)`)
555
+ }
556
+ for (const w of warnings) { this.notice(w); this.log(`⚠️ ${w}`) }
557
+ return { text, held: records, warnings, gone }
558
+ }
559
+
560
+ hold (fields) {
561
+ const rec = addHeld(this.room(), this.heldMap(), fields, this.origin)
562
+ if (rec.local && this.keepLocal) { try { this.keepLocal(rec.id, { result: fields.result, mine: fields.mine }) } catch {} }
563
+ return rec
564
+ }
565
+
566
+ /** A deletion of `p` by `by` (text: what it held): with a matching new file, a move. */
567
+ noteGone ({ doc, path: p, text, by }) {
568
+ if (typeof text !== 'string' || text.trim().length < 20) return null
569
+ const now = Date.now()
570
+ this.recentGone.set(p, { text, by, ts: now })
571
+ for (const [to, n] of this.recentNew) if (n.by === by && now - n.ts <= MOVE_MS && n.text === text && to !== p) return this.noteMove(doc, p, to, by, text)
572
+ return null
573
+ }
574
+
575
+ /** A new file `p` by `by`: with a matching deletion, a move. */
576
+ noteNew ({ doc, path: p, text, by }) {
577
+ if (typeof text !== 'string' || text.trim().length < 20) return null
578
+ const now = Date.now()
579
+ this.recentNew.set(p, { text, by, ts: now })
580
+ for (const [from, g] of this.recentGone) if (g.by === by && now - g.ts <= MOVE_MS && g.text === text && from !== p) return this.noteMove(doc, from, p, by, text)
581
+ return null
582
+ }
583
+
584
+ noteMove (doc, from, to, by, text) {
585
+ this.recentGone.delete(from)
586
+ this.recentNew.delete(to)
587
+ for (const m of [this.recentGone, this.recentNew]) for (const [k, v] of m) if (Date.now() - v.ts > MOVE_MS) m.delete(k)
588
+ if (doc) doc.getMap(MOVES_MAP).set(from, { to, by, ts: Date.now(), text: text.slice(0, MAX_MOVE_TEXT) })
589
+ return { from, to }
590
+ }
591
+
592
+ /** Where `p` moved, when another member (not `by`) moved it lately: { to, by, ts, text }, or null. */
593
+ movedTo ({ doc, path: p, by }) {
594
+ if (!doc) return null
595
+ const m = doc.getMap(MOVES_MAP).get(p)
596
+ if (!m || typeof m.to !== 'string' || m.by === by || Date.now() - (m.ts || 0) > MOVE_KEEP_MS) return null
597
+ return m
598
+ }
599
+ }