heyquilt 0.3.174 → 0.3.176

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +6 -3
  2. package/RELEASES.md +30 -0
  3. package/bin/quilt.js +1 -75
  4. package/desktop/main.js +22 -9
  5. package/package.json +2 -3
  6. package/src/ai-vm.js +1 -1
  7. package/src/api/memory-store.js +1 -5
  8. package/src/api/server.js +4 -45
  9. package/src/api/supabase-store.js +0 -10
  10. package/src/autowork.js +7 -142
  11. package/src/base-pick.js +125 -12
  12. package/src/branch-view.js +1 -1
  13. package/src/connection.js +12 -37
  14. package/src/control.js +16 -93
  15. package/src/fsutil.js +1 -1
  16. package/src/git-aside.js +70 -0
  17. package/src/github-commit.js +1 -2
  18. package/src/gitstate.js +326 -0
  19. package/src/held.js +12 -53
  20. package/src/history.js +1 -25
  21. package/src/live-merge.js +42 -161
  22. package/src/mcp.js +6 -90
  23. package/src/merge3.js +21 -5
  24. package/src/pathrules.js +1 -1
  25. package/src/protocol.js +6 -11
  26. package/src/read-bases.js +3 -5
  27. package/src/relay-live-write.js +37 -44
  28. package/src/relay-mcp.js +30 -164
  29. package/src/relay-prune.js +3 -6
  30. package/src/relay-turn-sync.js +7 -11
  31. package/src/runner.js +2 -4
  32. package/src/server.js +61 -1717
  33. package/src/session.js +895 -844
  34. package/src/setup.js +11 -3
  35. package/src/status.js +2 -5
  36. package/src/swap-in.js +56 -13
  37. package/src/turn-sync-plan.js +2 -2
  38. package/src/turn-sync.js +1 -1
  39. package/src/ui/agent-guide.js +3 -1
  40. package/src/ui/app.css +4 -96
  41. package/src/ui/app.js +1 -1
  42. package/src/ui/chat.js +2 -6
  43. package/src/ui/cloud-ai-model.js +0 -13
  44. package/src/ui/cloud-ai.js +2 -10
  45. package/src/ui/connections.js +2 -1
  46. package/src/ui/fileview.js +7 -20
  47. package/src/ui/git-rule.js +2 -13
  48. package/src/ui/home.js +2 -8
  49. package/src/ui/session-words.js +27 -0
  50. package/src/ui/session.js +34 -407
  51. package/src/ui-server.js +7 -56
  52. package/src/api/routes/seam-connect.js +0 -103
  53. package/src/api/routes/session-migrate.js +0 -39
  54. package/src/force-date.js +0 -27
  55. package/src/quilt-default.js +0 -84
  56. package/src/quilt-history.js +0 -106
  57. package/src/quilt-remote.js +0 -78
  58. package/src/seam-access.js +0 -97
  59. package/src/seam-url.js +0 -15
  60. package/src/session-follow.js +0 -583
  61. package/src/session-layout3.js +0 -466
  62. package/src/session-migrate.js +0 -123
  63. package/src/session-quilt.js +0 -126
  64. package/src/session-seam.js +0 -312
  65. package/src/source-live/bring-in.js +0 -391
  66. package/src/source-live/land.js +0 -410
  67. package/src/source-live/live-block.js +0 -1166
  68. package/src/source-live/live-square.js +0 -116
  69. package/src/ui/force-words.js +0 -19
  70. package/src/ui/quiltview.js +0 -213
  71. package/src/ui/seam-model.js +0 -309
package/src/mcp.js CHANGED
@@ -40,7 +40,6 @@ import { getSettings } from './settings.js'
40
40
  import { describeSecretNames, SECRET_NAMES_DESCRIPTION, RUN_GUIDE } from './secret-names.js'
41
41
  import { appWorkspaces } from './app-workspaces.js'
42
42
  import { TRANSCRIPT_DESCRIPTION, JOIN_DESCRIPTION, SAY_DESCRIPTION, MAX_LINE, renderLines, agentsJoinCalls } from './voice.js'
43
- import { seamGate, seamNote, seamStatus, seamToolSpec, seamOnly, seamWorkflow, seamRefusal, SEAM_SESSION_TOOLS, GIT_TOOLS } from './session-seam.js'
44
43
  import { describeHeld, RESOLVE_DESCRIPTION, findHeldIn, renderOwnHeld } from './held.js'
45
44
 
46
45
  // The board's columns, from tasks.js, so this and the hosted MCP (relay-mcp.js) never drift apart.
@@ -83,7 +82,7 @@ export const MCP_INSTRUCTIONS =
83
82
  'If the person you work for lets their AI pick up work by itself (their cloud AI, on the cloud machine they connected), finishing (quilt_set_work done, a task to QA or Done) hands you your next task from the board: start it. ' +
84
83
  'Before you change files, call quilt_before_edit with their paths: it shows what people said about those files in chat and who else changed them lately, ' +
85
84
  'so you know what was asked or planned before you change them. It never refuses: nobody holds files. ' +
86
- 'Edit any file you may change: edits merge as they arrive, and if your change clashes with someone\'s on the same lines (or would erase lines a teammate added in the last 15 minutes), Quilt holds your lines and tells you: resolve it at once with quilt_resolve_merge. A conflict must not sit: until you resolve your own, moving a task to QA or Done, quilt_set_work done and commits refuse, and a conflict whose writer\'s AI is gone is handed to another AI in the session. ' +
85
+ 'Edit any file you may change: edits merge as they arrive, and if your change clashes with someone\'s on the same lines, Quilt tells you. In your own folder the clash is in the file itself: your save is not shared, and the file has both versions of those lines between conflict markers ("<<<<<<< mine", "=======", ">>>>>>> session"). Edit them to what they should be, delete the marker lines and save: it is shared then. A conflict listed at the top of a Quilt answer instead (an agent with no folder made it, or an older app) is resolved at once with quilt_resolve_merge. A conflict must not sit: until you resolve your own, moving a task to QA or Done, quilt_set_work done and commits refuse, and a conflict whose writer\'s AI is gone is handed to another AI in the session. ' +
87
86
  'A boxed file\'s edits are only in its owner\'s folder; quilt_unpack shares a box when someone needs it: decide yourself, and ask your person first for a large, risky or critical change or when the project\'s rules say so. A file boxed by someone else (quilt_status lists Boxed work) is not in your folder yet: if you edit it, their box opens and your change merges with their work. ' +
88
87
  'For an agent of its own (not a person\'s AI session), every quilt answer starts with anything new for it (direct messages, mentions, tasks handed to it): act on it. ' +
89
88
  'These rules are enforced for agents: while someone who messaged or mentioned you is waiting for an answer, the tools that move work on (tasks, focus, quilt_set_work) refuse until you answer them with quilt_message. ' +
@@ -104,25 +103,11 @@ export const MCP_INSTRUCTIONS =
104
103
  APPS_GUIDE + ' ' +
105
104
  TASK_WORKFLOW
106
105
 
107
- /**
108
- * The instructions for a folder in a session that is a quilt (session-seam.js): every sentence
109
- * about git left out, and how work lands on Seam in its place. Nothing there names git or GitHub.
110
- */
111
- export const mcpQuiltInstructions = (quilt) => `${seamOnly(MCP_INSTRUCTIONS)} ${seamNote(quilt)}`
112
-
113
- /** The session this folder is in, as its app says, when it answers at once: whether it is a quilt picks the instructions. */
114
- async function quiltAtStart () {
115
- const d = findDaemon()
116
- if (!d) return null
117
- try { return (await rawCall(d, 'GET', '/quilt', undefined, { timeoutMs: 1500 })).quilt || null } catch { return null }
118
- }
119
-
120
106
  export async function runMcp () {
121
- const startQuilt = await quiltAtStart()
122
107
  const server = new McpServer(
123
108
  { name: 'quilt', version: '0.1.0' },
124
109
  // The channel capability lets Claude Code (started with the quilt channel) take inbox events as turns.
125
- { instructions: startQuilt && startQuilt.id ? mcpQuiltInstructions(startQuilt.slug || startQuilt.id) : MCP_INSTRUCTIONS, capabilities: { resources: { subscribe: true }, experimental: { 'claude/channel': {} } } }
110
+ { instructions: MCP_INSTRUCTIONS, capabilities: { resources: { subscribe: true }, experimental: { 'claude/channel': {} } } }
126
111
  )
127
112
 
128
113
  // This AI session, by an id of its own, so the app can tell it from the others working through
@@ -197,19 +182,10 @@ export async function runMcp () {
197
182
  }
198
183
  // When this person lets their AI pick up work by itself: the next task, said as it finishes one.
199
184
  const nextUp = async (d) => { try { const n = renderNextTask((await call(d, 'GET', '/duties')).next); return n ? `\n\n➡️ ${n}` : '' } catch { return '' } }
200
- // An AI session started before its session moved into Seam (or back to git) was told the other
201
- // way in its instructions, which never change once given: the next answer says the way now, once.
202
- let toldQuilt = !!(startQuilt && startQuilt.id)
203
- const moved = async () => {
204
- const q = await quiltNow()
205
- if (q === undefined || !!q === toldQuilt) return ''
206
- toldQuilt = !!q
207
- return q ? `🧵 Since you started, ${seamNote(q.slug || q.id).replace(/^This/, 'this')} Leave aside what your instructions said about how work lands.\n\n` : '🧵 Since you started, this session went back to its git branches: quilt_status says how work lands now.\n\n'
208
- }
209
185
  const withDaemon = async (fn, { inbox = true, gate = null } = {}) => {
210
186
  const d = findDaemon(joined ? joined.dir : undefined)
211
187
  if (!d) return { content: [{ type: 'text', text: NOT_RUNNING + stale() }], isError: true }
212
- const before = async () => introduce() + (await moved()) + (await notices(d)) + (inbox ? await arrivals(d) : '')
188
+ const before = async () => introduce() + (await notices(d)) + (inbox ? await arrivals(d) : '')
213
189
  try {
214
190
  const refused = gate ? await gate(d) : ''
215
191
  if (refused) return { content: [{ type: 'text', text: (await before()) + refused + stale() }], isError: true }
@@ -227,52 +203,13 @@ export async function runMcp () {
227
203
  return `${label ? `Assigned to ${label}.` : 'Unassigned.'}${files}`
228
204
  }
229
205
 
230
- // Seam (Seam's plans/quilt-source-control/12, 16): in a session that is a quilt, the GitHub tools
231
- // refuse with the Seam tool to use instead, the same for every AI tool (session-seam.js).
232
- // undefined when the app can't say (none, or no answer): unknown, not "not a quilt".
233
- const quiltNow = async () => {
234
- const d = findDaemon(joined ? joined.dir : undefined)
235
- if (!d) return undefined
236
- let q = null
237
- try { q = (await call(d, 'GET', '/quilt')).quilt || null } catch { return undefined }
238
- syncSeamTools(q)
239
- return q
240
- }
241
- // The git-era tools are hidden while the session is a quilt (GIT_TOOLS), and refuse with the Seam tool if called.
242
- const gitTools = new Map()
243
- const gated = seamGate(server.registerTool.bind(server), quiltNow)
244
- server.registerTool = (name, spec, handler) => {
245
- const t = gated(name, spec, handler)
246
- if (GIT_TOOLS.has(name)) gitTools.set(name, t)
247
- return t
248
- }
249
- // Seam's everyday tools, served by this server itself while the session is a quilt (none
250
- // otherwise): the app runs them as this folder's member, on its square (control.js /seam).
251
- // The client is told when they come and go, as with the workspace library's tools.
252
- const seamTools = new Map()
253
- const seamCall = (name, args) => withDaemon(async (d) => {
254
- await quiltNow() // the session may have stopped being a quilt: the tool list follows
255
- const r = await call(d, 'POST', '/seam', { tool: name, args: args || {} })
256
- const text = ((r && r.content) || []).map((c) => c.text || '').join('\n')
257
- if (r && r.isError) throw new Error(text)
258
- return text
259
- }, { gate: name === 'seam_commit' || name === 'seam_merge' ? gateFor(name, { held: true }) : null })
260
- const syncSeamTools = (q) => {
261
- const on = !!(q && q.id)
262
- if (on && !seamTools.size) for (const name of SEAM_SESSION_TOOLS) seamTools.set(name, server.registerTool(name, seamToolSpec(name), (args) => seamCall(name, args)))
263
- for (const t of seamTools.values()) if (t.enabled !== on) { if (on) t.enable(); else t.disable() }
264
- for (const t of gitTools.values()) if (t.enabled === on) { if (on) t.disable(); else t.enable() }
265
- }
266
-
267
206
  server.registerTool('quilt_status', {
268
207
  description: 'See who else is in the live session, what they are working on, which files they recently edited, boxed work, recent messages, and which open tasks are assigned to you. Call this before starting work.',
269
208
  inputSchema: {}
270
209
  }, () => withDaemon(async (d) => {
271
210
  const st = await call(d, 'GET', '/status')
272
- const q = await quiltNow()
273
211
  // Open held conflicts already head the answer (the notices): not listed twice.
274
- const md = renderStatus({ ...st, held: [] }, { asAi: taskReader(st).asAi, mentionYours: true })
275
- return q ? `${seamNote(q.slug || q.id)}\n\n${seamStatus(md)}` : md
212
+ return renderStatus({ ...st, held: [] }, { asAi: taskReader(st).asAi, mentionYours: true })
276
213
  }))
277
214
 
278
215
  server.registerTool('quilt_resolve_merge', {
@@ -340,8 +277,6 @@ export async function runMcp () {
340
277
  if (column === 'qa') patch.qaNotes = qaNotes
341
278
  if (column === 'done') patch.verified = verified
342
279
  const { task } = await call(d, 'POST', '/tasks/update', patch)
343
- const q = column === 'doing' || column === 'qa' ? await quiltNow() : null
344
- if (q && column === 'doing') return pickupBrief({ ...brief, task: { ...task, comments: brief.task.comments }, workflow: seamWorkflow(TASK_WORKFLOW) })
345
280
  if (column === 'doing') return pickupBrief({ ...brief, task: { ...task, comments: brief.task.comments } })
346
281
  if (column === 'qa') return `Moved "${task.title}" to QA. Notes: ${qaNotesLine(task)}` + await nextUp(d)
347
282
  if (column === 'done') return `Moved "${task.title}" to Done. Verified: ${verifiedLine(task)}` + await nextUp(d)
@@ -704,8 +639,6 @@ export async function runMcp () {
704
639
  readerOptions: { chatDir: process.cwd() },
705
640
  onLog: (line) => { logs.push(line); if (logs.length > 50) logs.shift() },
706
641
  onFatal: async (err) => { logs.push(`stopped: ${err.message}`); await leave() },
707
- // A session this agent starts is a quilt from the start when the API says so (src/quilt-default.js).
708
- newSession: starting && !inviteServer,
709
642
  workspace
710
643
  })
711
644
  joined = { run, dir, invite: run.invite }
@@ -933,8 +866,8 @@ export async function runMcp () {
933
866
  limit: z.number().int().min(1).max(200).optional().describe('How many of the newest matching changes (default 30)')
934
867
  }
935
868
  }, ({ path: p, by, since, task, with_diff, limit }) => withDaemon(async (d) => {
936
- const { entries, note } = await call(d, 'POST', '/history', { path: p, by, since, task, limit: limit || 30, with_diff: !!with_diff })
937
- return `${formatHistory(entries, { withDiff: !!with_diff })}${note ? `\n\n${note}` : ''}`
869
+ const { entries } = await call(d, 'POST', '/history', { path: p, by, since, task, limit: limit || 30 })
870
+ return formatHistory(entries, { withDiff: !!with_diff })
938
871
  }))
939
872
 
940
873
  server.registerTool('quilt_partner_feed', {
@@ -1004,28 +937,11 @@ export async function runMcp () {
1004
937
 
1005
938
  const transport = new StdioServerTransport()
1006
939
  await server.connect(transport)
1007
- // A git-era tool hidden while the session is a quilt, called from a tool list read before the
1008
- // move (a client that missed the list's change): answered with the Seam way, not "disabled".
1009
- const onmessage = transport.onmessage
1010
- transport.onmessage = (msg, extra) => {
1011
- const name = msg && msg.method === 'tools/call' && msg.params && msg.params.name
1012
- const t = name && gitTools.get(name)
1013
- if (!t || t.enabled) return onmessage(msg, extra)
1014
- quiltNow().then((q) => {
1015
- const no = q && seamRefusal(name, q.slug || q.id)
1016
- if (!no) return onmessage(msg, extra)
1017
- return transport.send({ jsonrpc: '2.0', id: msg.id, result: { content: [{ type: 'text', text: no }], isError: true } })
1018
- }).catch(() => onmessage(msg, extra))
1019
- }
1020
940
  // The workspace library tools arrive a moment later (the client is told the tool list
1021
941
  // changed), so startup never waits on the API.
1022
942
  // fromPath reads only from the project: the session's folder, or where the agent runs.
1023
943
  const projectDirs = () => [joined?.dir, findDaemon(joined ? joined.dir : undefined)?.dir, process.env.QUILT_DIR || process.cwd()].filter(Boolean)
1024
944
  addWorkspaceTools(server, { projectDirs }).catch(() => {})
1025
- // In a session that is a quilt, Seam's tools come the same way; looked at again every half minute.
1026
- quiltNow().catch(() => {})
1027
- const seamTimer = setInterval(() => quiltNow().catch(() => {}), 30_000)
1028
- seamTimer.unref()
1029
945
  }
1030
946
 
1031
947
  /**
package/src/merge3.js CHANGED
@@ -71,7 +71,23 @@ export const withMarkers = eolAware(function withMarkers (base, ours, theirs, na
71
71
  return out.join('\n')
72
72
  })
73
73
 
74
- /** True when the text still holds markers that withMarkers put there. */
74
+ /**
75
+ * A live merge (mergeLive's { text, held }) with each clash written out between markers: the writer's lines,
76
+ * then the lines that landed first. What the writer's own file gets when the relay takes nothing of a save.
77
+ */
78
+ export function withHeldMarkers (r, names) {
79
+ const crlf = eolOf(r.text) === 'crlf'
80
+ const bare = (ls) => ls.map((l) => l.replace(/\r$/, ''))
81
+ const out = lines(crlf ? r.text.replace(/\r\n/g, '\n') : r.text)
82
+ // From the last clash to the first, so each one's place in the text still holds.
83
+ for (const h of [...r.held].sort((x, y) => y.at - x.at)) {
84
+ out.splice(h.at, h.theirs.length, `${MARK.start} (${names.mine})`, ...bare(h.ours), MARK.mid, ...bare(h.theirs), `${MARK.end} (${names.theirs})`)
85
+ }
86
+ const text = out.join('\n')
87
+ return crlf ? text.replace(/\n/g, '\r\n') : text
88
+ }
89
+
90
+ /** True when the text still holds markers that withMarkers or withHeldMarkers put there. */
75
91
  export function hasMarkers (text) {
76
92
  return typeof text === 'string' && text.split('\n').some((l) => l.startsWith(`${MARK.start} (`) || l.startsWith(`${MARK.end} (`))
77
93
  }
@@ -223,16 +239,16 @@ export const mergeAuto = eolAware(function mergeAuto (base, ours, theirs, { ours
223
239
  })
224
240
 
225
241
  /**
226
- * How a live write is merged (Seam's 07 "Conflicts in the live state", ruling 2026-11-13, which
227
- * replaces mergeAuto's "the newer edit wins" for live writes). `ours` is the writer's version, made
242
+ * How a live write is merged (ruling 2026-11-13, which replaces mergeAuto's "the newer edit wins"
243
+ * for live writes). `ours` is the writer's version, made
228
244
  * on `base`; `theirs` is what the shared file holds now, which landed first. Changes to different
229
245
  * lines all go in (lines, changes next to each other, a line only one side changed). Where both
230
246
  * changed the same lines, nobody wins: the shared file keeps theirs there and the writer's lines
231
247
  * are held, never written into the file with markers. The only same-line case combined without
232
248
  * asking is two names added to one import line (sameImport); the same change spaced differently
233
249
  * keeps theirs, with nothing held. Two words changed on one line and two blocks added at one place
234
- * are held like any same-line change (mergeSmart and mergeAuto still combine them where no live
235
- * write meets another: bringing main into a square, a box carried onto a square's head and the clash ladder).
250
+ * are held like any same-line change (mergeSmart and mergeAuto still combine them, for a merge that
251
+ * is not a live write).
236
252
  * Returns { text, held, mine }: `text` the shared file's new text, `held` the writer's lines kept
237
253
  * aside ({ at: their first line in `text`, base, ours, theirs }), `mine` the text with the writer's
238
254
  * lines in place of theirs at each held hunk (what resolving it "mine" would write).
package/src/pathrules.js CHANGED
@@ -20,7 +20,7 @@ export const CHAT_FILES = 'Chat files'
20
20
  // copies of the project.
21
21
  export const ALWAYS_IGNORED = [
22
22
  '.git', '.quilt', '.cowove', 'node_modules', '.DS_Store', 'Thumbs.db', '.claude/worktrees',
23
- // A Seam block's own record (a folder checked out with seam checkout): Seam's, never the session's.
23
+ // The record a source-control tool older Quilts worked with kept in a folder it checked out: its own, never the session's.
24
24
  '.seam',
25
25
  `/${CHAT_FILES}`,
26
26
  // Each person's own Claude Code settings (permissions, Quilt's hooks) stay on their machine.
package/src/protocol.js CHANGED
@@ -17,24 +17,19 @@ export const MSG_ADMIN = 14 // client (owner) -> relay: JSON { id, op: 'approve'
17
17
  export const MSG_MEMBERS = 15 // relay -> client: JSON { members, sessionName, pending?, reply?: { id, ok, error } }
18
18
  export const MSG_PASS = 16 // client -> relay: JSON { pass }: a fresh session pass, sent at least every 5 minutes
19
19
  export const MSG_BRANCH = 17 // client -> relay: JSON { id, op: 'join'|'confirm'|'remove', branch, base?, adopt?, sv? }
20
- export const MSG_BRANCHES = 18 // relay -> client: JSON { branches, quilt?, shadow?, reply?: { id, op, ok, error?, branch?, created?, base? } }
20
+ export const MSG_BRANCHES = 18 // relay -> client: JSON { branches, writes?, pushed?, reply?: { id, op, ok, error?, branch?, created?, base? } }
21
21
 
22
22
  // Every sync message names its document: the room's (chat, tasks, the feed, commit requests,
23
23
  // activity) is '', a branch's (its files) is the branch key. Git never allows an empty branch name.
24
24
  export const ROOM_DOC = ''
25
25
 
26
26
  // What this app can do, sent when it connects. The relay turns away apps without what a session needs.
27
- // `branches` went with git mode (R3; 16 flag 9: FEATURES becomes large-files plus the quilt words): `quilts`
28
- // says this app syncs branch documents and squares, and the relay takes either.
27
+ // large-files: this app keeps files too large for a document in the session's storage.
29
28
  // branch-diffs: this app reads a branch document that holds only what differs from git (branch-view.js).
30
- // quilts: this app works in a session whose files are in its squares' live documents (layout 3,
31
- // Seam's plans/quilt-source-control/16 flag 4: sent by every app before anyone opens a block).
32
- // quilt-folders: this app's folder follows its branch's square in place at layout 3 (session-follow.js);
33
- // an app with `quilts` but not this (0.3.125) kept syncing to the read-only branch documents.
34
- // quilt-moves: this app's folder follows a square whose base moves (main brought in): it re-projects onto
35
- // the new head, says which head each edit was made on, and takes in only its own edits. The relay brings
36
- // main into a square only when every folder on it can follow that (server.js outdatedOn); 0.3.133 and
37
- // 0.3.134, which can but don't say so, are known by their asking to bring main in.
29
+ // quilts: this app syncs a session's branch documents. The relay asks for it, or for `branches`, the name
30
+ // apps sent before; the token keeps its name because apps and relays already in use check for it.
31
+ // quilt-folders, quilt-moves: names kept for compatibility. Relays from before this release let an app
32
+ // into some sessions only when it sent them, so every app still does; this relay does not read them.
38
33
  export const FEATURES = 'large-files,branch-diffs,quilts,quilt-folders,quilt-moves'
39
34
 
40
35
  // WebSocket close codes the relay uses to refuse a client for good.
package/src/read-bases.js CHANGED
@@ -1,12 +1,10 @@
1
1
  // The recent versions of each shared file, by their hash: the base a live write is merged against
2
- // (Seam's plans/quilt-source-control/07 "Merge on arrival": every live write carries the version its
3
- // writer started from). A hosted agent's quilt_read_file answers with the version it read
2
+ // (every live write carries the version its writer started from). A hosted agent's quilt_read_file answers with the version it read
4
3
  // (`versionOf`), which quilt_write_file takes as `base`; a folder's write (relay-live-write.js) names
5
4
  // the version it last synced. Versions are kept per file, whoever read or wrote them, so many writers
6
5
  // on one file (or many loops on one agent's key) never push each other's bases out. A version the
7
6
  // relay no longer has is never silently replaced by the latest: base() says it is `unknown` and gives
8
- // the oldest version it has, and the write is merged as a stale one (the stale-write rule keeps every
9
- // member's recent lines, the writer's own included). Per room on the relay, kept on disk with the room
7
+ // the oldest version it has, and the write is merged against that. Per room on the relay, kept on disk with the room
10
8
  // (`<room>.bases.json` beside its document, written a moment after a change and when the room is saved),
11
9
  // and read back when the room is next used: a relay restart forgets no version an agent read (ruling
12
10
  // 2026-11-14, Daniel).
@@ -17,7 +15,7 @@ import crypto from 'node:crypto'
17
15
  export const KEEP_VERSIONS = 128
18
16
  /** All the texts one room keeps, together; past it the longest-unused files' versions go first. */
19
17
  export const MAX_BYTES = 24 * 1024 * 1024
20
- /** A text longer than this is not kept (a live square's text is 2 MiB at most). */
18
+ /** A text longer than this is not kept (a live write is 2 MiB at most: relay-live-write.js MAX_WRITE_TEXT). */
21
19
  export const MAX_TEXT = 2 * 1024 * 1024
22
20
 
23
21
  /** A text's version, as quilt_read_file shows it and quilt_write_file takes it: its sha1, in hex. */
@@ -1,29 +1,30 @@
1
1
  // A folder's live write, applied by the relay (plans/no-holds.md decision 2: "The relay merges each
2
2
  // write against the version the writer started from, in one step, one write at a time per file. No
3
- // check-then-write race."). A folder that saw a text file change on disk (live-block.js scan, a
4
- // square's live document; session.js ingest, a branch document) sends the relay
3
+ // check-then-write race."). A folder that saw a text file change on disk (session.js ingest, into its
4
+ // branch document) sends the relay
5
5
  //
6
- // MSG_BRANCH { op: 'live-write', branch, path, base, baseText?, text, older?, mode?, at?, trusted?, retry?, baseUnknown?, fromGit? }
6
+ // MSG_BRANCH { op: 'live-write', branch, path, base, baseText?, text, older?, retry?, baseUnknown?, fromGit?, markers? }
7
7
  //
8
8
  // `base`: the version (sha1, read-bases.js versionOf) of the shared text the folder last synced for the
9
9
  // path, null for a file it never had; `baseText`: that text itself, when the relay may not know it
10
10
  // (the folder sends it when it is small, or when the relay asked for it); `text`: what disk holds now;
11
- // `older`: the text a save that landed in the file Quilt replaced was made from (base-pick.js);
12
- // `fromGit`: a diff branch's first edit of a file only git had, `base` being git's text (the shared file
13
- // has no entry: it is git's, so the base is what it holds). A `seen` from 0.3.172 folders (their access-time
14
- // proof) is ignored: nothing is taken for an edit because it looks like one (ruling 2026-11-14).
11
+ // `older`: the older text the save was made from, one its folder's disk held before Quilt wrote over it
12
+ // (base-pick.js); `fromGit`: a diff branch's first edit of a file only git had, `base` being git's text (the
13
+ // shared file has no entry: it is git's, so the base is what it holds); `markers`: the folder settles a clash
14
+ // in its own file, so a save that clashes is not taken at all (the reply is { ok, conflict: true, text, base,
15
+ // others }: the save with both versions of the clashing lines between markers, made on `base`, the shared
16
+ // text now). A `trusted` or a `seen` from older folders is ignored.
15
17
  // The relay merges it here, synchronously (nothing else runs on the room between the read of the
16
18
  // shared text and the write of the result), through the same engine every live write uses
17
- // (live-merge.js LiveRules: same lines keep what landed first and the writer's are held, the stale-write,
18
- // removed-name and parse rules), and puts the result into the file's Y.Text in one transaction of whole
19
+ // (live-merge.js LiveRules: same lines keep what landed first and the writer's are held; the removed-name
20
+ // warning), and puts the result into the file's Y.Text in one transaction of whole
19
21
  // lines (textdiff.js applyLineDiff), so two writes of one line never come out mixed letter by letter.
20
22
  // The reply: { ok, path, version, same, text? (the result, when it is not what was sent), detail,
21
23
  // held: [ids], notices, logs, gone, local } or { ok, needBase: true } (send baseText, or `retry`
22
24
  // without it) or { ok, fallback: why } (write it as before: an edit of the Y.Text the relay checks).
23
25
  //
24
26
  // A base the relay no longer has, with no text for it, is never replaced by the latest: the write is
25
- // merged against the oldest version kept, as a stale write (`strict`: every member's recent lines stay,
26
- // the writer's own included).
27
+ // merged against the oldest version kept (`strict`).
27
28
  //
28
29
  // Apps from before this (0.3.170 and earlier) keep sending Yjs edits of the text as they always did:
29
30
  // they are combined as a CRDT does, without these guarantees (NOT-DONE.md).
@@ -31,12 +32,12 @@ import * as Y from 'yjs'
31
32
  import { LiveRules } from './live-merge.js'
32
33
  import { readBasesOf, versionOf } from './read-bases.js'
33
34
  import { applyLineDiff } from './textdiff.js'
34
- import { staleWriteMinutes } from './held.js'
35
35
  import { isSafeRelPath } from './pathrules.js'
36
- import { isLiveKey, liveMaps, liveHead, LIVE_PREFIX } from './source-live/live-square.js'
37
36
 
38
37
  export const WRITE_ORIGIN = 'relay-live-write'
39
- /** A text written live: at most this long (a square's live text, live-block.js MAX_LIVE_TEXT). */
38
+ /** In a branch document: path -> { by, ts }, who last wrote it through the relay. */
39
+ export const WRITERS_MAP = 'writers'
40
+ /** A text written live: at most this long. */
40
41
  export const MAX_WRITE_TEXT = 2 * 1024 * 1024
41
42
  const HEX40 = /^[0-9a-f]{40}$/
42
43
 
@@ -50,7 +51,7 @@ function lastEditor (room, key, rel) {
50
51
  return null
51
52
  }
52
53
 
53
- /** The text files of a document, as [path, text] (the stale and gone-name checks read them). */
54
+ /** The text files of a document, as [path, text] (the gone-name check reads them). */
54
55
  function * textsOf (files) {
55
56
  for (const [p, t] of files) if (t && typeof t.toString === 'function' && isSafeRelPath(p)) yield [p, t.toString()]
56
57
  }
@@ -70,22 +71,16 @@ export function liveWrite (room, ws, req, { origin = WRITE_ORIGIN, now = Date.no
70
71
  const rel = String(req.path ?? '').trim().replace(/^\.\//, '')
71
72
  if (!isSafeRelPath(rel)) throw new Error('That is not a path inside the project.')
72
73
  if (typeof req.text !== 'string' || req.text.length > MAX_WRITE_TEXT) throw new Error('a live write is a text of at most 2 MiB')
73
- const live = isLiveKey(k)
74
74
  // What the relay would refuse or treat apart from a plain edit goes the old way: the folder edits the
75
75
  // text as before and the relay's checks (checkChange, read-only branches, size limits) apply as ever.
76
76
  if (!room.mayWrite(a, rel)) return { ok: true, fallback: 'refused' }
77
77
  if (room.unsavable || room.branchFull(k)) return { ok: true, fallback: 'full' }
78
- if (!live && (room.meta.layout !== 2 || room.meta.syncStopped)) return { ok: true, fallback: 'read-only' }
79
- if (live && room.movedOnTo(k)) return { ok: true, fallback: 'moved' }
78
+ if (room.meta.layout !== 2) return { ok: true, fallback: 'read-only' }
80
79
  const doc = e.doc
81
80
  const files = doc.getMap('files')
82
81
  const blobs = doc.getMap('blobs')
83
- const m = live ? liveMaps(doc) : null
84
82
  const t0 = files.get(rel)
85
- if (!live && !t0 && blobs.has(rel)) return { ok: true, fallback: 'binary' }
86
- // What the shared file holds now. A square's file with no live text (or one marked back to its head)
87
- // holds its head's text, which the relay never reads: the folder's base is that text.
88
- const headOnly = live && (!t0 || m.clean.has(rel)) && !m.gone.has(rel) && !m.blobs.has(rel)
83
+ if (!t0 && blobs.has(rel)) return { ok: true, fallback: 'binary' }
89
84
  const baseText = typeof req.baseText === 'string' && req.baseText.length <= MAX_WRITE_TEXT ? req.baseText : null
90
85
  const bases = readBasesOf(room)
91
86
  const v = typeof req.base === 'string' ? req.base.trim().toLowerCase() : null
@@ -96,17 +91,17 @@ export function liveWrite (room, ws, req, { origin = WRITE_ORIGIN, now = Date.no
96
91
  if (!HEX40.test(v)) throw new Error('base is a version: 40 hex characters')
97
92
  base = bases.find(k, rel, v)
98
93
  if (base === null && baseText !== null && versionOf(baseText) === v) base = baseText
99
- if (base === null && t0 && !headOnly && versionOf(t0.toString()) === v) base = t0.toString()
94
+ if (base === null && t0 && versionOf(t0.toString()) === v) base = t0.toString()
100
95
  if (base === null) {
101
96
  // Not known here: the folder sends the text (it has it), or says it has not (retry).
102
97
  if (!req.retry) return { ok: true, needBase: true }
103
98
  strict = true
104
99
  }
105
100
  } else if (req.baseUnknown === true) strict = true // the folder knew the file but no longer has the text it synced (a restart)
106
- // A head file: the shared text is the head's, which is the folder's base (null for a file new to the square).
107
- let theirs = headOnly ? base : t0 ? t0.toString() : null
101
+ // What the shared file holds now.
102
+ let theirs = t0 ? t0.toString() : null
108
103
  // A diff branch's file only git has (no entry, not deleted in the session): it holds git's text, the base.
109
- if (!live && req.fromGit === true && !t0 && typeof base === 'string' && !doc.getMap('gone').has(rel)) theirs = base
104
+ if (req.fromGit === true && !t0 && typeof base === 'string' && !doc.getMap('gone').has(rel)) theirs = base
110
105
  if (strict) base = bases.oldest(k, rel) ?? theirs
111
106
  // Made by two at once (the folder never had it, the session has it now): both whole, at one spot.
112
107
  if (!v && req.baseUnknown !== true && theirs !== null) { base = ''; strict = true }
@@ -114,17 +109,16 @@ export function liveWrite (room, ws, req, { origin = WRITE_ORIGIN, now = Date.no
114
109
  if (typeof base === 'string' && base) bases.record(k, rel, base)
115
110
  const by = room.names.get(ws) || ''
116
111
  const byId = a.key || null
117
- // Who landed first: the square's writers map; on a branch, the last live write here, else the room's activity.
112
+ // Who landed first: the last live write here, else the room's activity.
118
113
  if (!room.liveWriters) room.liveWriters = new Map()
119
114
  const wkey = `${k}\0${rel}`
120
115
  const newer = (x, y) => (!x ? y : !y ? x : (y.ts || 0) > (x.ts || 0) ? y : x)
121
- const others = [live ? ((m.writers.get(rel) || {}).by || null) : (newer(room.liveWriters.get(wkey), lastEditor(room, k, rel)) || {}).by].filter((n) => n && n !== by)
116
+ const others = [(newer(room.liveWriters.get(wkey), lastEditor(room, k, rel)) || {}).by].filter((n) => n && n !== by)
122
117
  const notices = []
123
118
  const logs = []
124
119
  const local = []
125
120
  const rules = new LiveRules({
126
121
  room: () => room.doc,
127
- staleMinutes: () => staleWriteMinutes(room.doc, room.memberList ? room.memberList() : []),
128
122
  notice: (s) => notices.push(s),
129
123
  log: (s) => logs.push(s),
130
124
  texts: () => textsOf(files),
@@ -132,29 +126,28 @@ export function liveWrite (room, ws, req, { origin = WRITE_ORIGIN, now = Date.no
132
126
  keepLocal: (id, texts) => local.push({ id, ...texts }),
133
127
  folder: true
134
128
  })
135
- if (req.trusted === true) rules.trust(rel, req.text)
136
- const where = live ? { square: k.slice(LIVE_PREFIX.length) } : { branch: k }
129
+ const where = { branch: k }
137
130
  // The older text a rescued save was made from (base-pick.js): put onto the base first, newer lines kept.
138
131
  const older = typeof req.older === 'string' && req.older.length <= MAX_WRITE_TEXT ? req.older : null
139
132
  let r = null
140
133
  let detail = ''
141
- const before = t0 && !headOnly ? t0.toString() : theirs
142
- // The merge, what it notes in the file's document (additions, for the next stale check) and the result: one
143
- // transaction, so every member gets the write as one update.
134
+ const before = t0 ? t0.toString() : theirs
135
+ // The merge and the result: one transaction, so every member gets the write as one update.
144
136
  doc.transact(() => {
145
- r = rules.write({ doc, where, path: rel, base, ours: req.text, theirs, by, byId, others, strict, nameSearch: false, older })
137
+ r = rules.write({ doc, where, path: rel, base, ours: req.text, theirs, by, byId, others, nameSearch: false, older, markers: req.markers === true })
138
+ if (r.conflict) return
146
139
  let t = files.get(rel)
147
- if (live) {
148
- m.clean.delete(rel); m.gone.delete(rel); m.blobs.delete(rel)
149
- m.writers.set(rel, { by, ts: now, at: typeof req.at === 'string' ? req.at : liveHead(doc) })
150
- if (req.mode === 'exec') { if (m.modes.get(rel) !== 'exec') m.modes.set(rel, 'exec') } else if (req.mode === 'file' && m.modes.has(rel)) m.modes.delete(rel)
151
- // A head file's first live text: the head's text first, so what changed is told from it.
152
- if (t && headOnly && t.toString() !== (theirs ?? '')) { files.delete(rel); t = null }
153
- } else blobs.delete(rel)
140
+ blobs.delete(rel)
141
+ // Who wrote it, in the same update as the text (WRITERS_MAP): a folder that takes the text in names its
142
+ // writer at once. The writer's own chronology entry only follows the relay's answer, a moment later.
143
+ if (by && r.text !== (theirs ?? '')) doc.getMap(WRITERS_MAP).set(rel, { by, ts: now })
154
144
  if (!t) { t = new Y.Text(); if (typeof theirs === 'string') t.insert(0, theirs); files.set(rel, t) }
155
145
  detail = applyLineDiff(t, r.text)
156
146
  }, origin)
157
- if (!live && r.text !== (theirs ?? '')) {
147
+ // Someone changed the same lines first, and this writer settles that in its own file: nothing is taken.
148
+ // `base` is the shared text its marked-up file was made on, which its next save is merged against.
149
+ if (r.conflict) return { ok: true, path: rel, conflict: true, text: r.text, base: theirs, others: r.others, notices, logs }
150
+ if (r.text !== (theirs ?? '')) {
158
151
  room.liveWriters.delete(wkey)
159
152
  room.liveWriters.set(wkey, { by, ts: now })
160
153
  if (room.liveWriters.size > 5000) room.liveWriters.delete(room.liveWriters.keys().next().value)