heyquilt 0.3.148 → 0.3.150

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 CHANGED
@@ -11,6 +11,19 @@ Format: `## <version> — <YYYY-MM-DD>`, an optional one-line summary, then bull
11
11
  Lead each bullet with a short bold phrase. Inline `code` and **bold** are rendered;
12
12
  nothing else is.
13
13
 
14
+ ## 0.3.150 — 2026-11-04
15
+
16
+ - **Quilt no longer runs tests on your computer before your work lands.** Held work goes into Seam's main as soon as your folder is quiet, as before 0.3.148's test step. Tests run in Seam, only for the files a change touches.
17
+
18
+ ## 0.3.149 — 2026-11-04
19
+
20
+ - **Agents that run commands can talk in calls.** `quilt voice say <text>` says it out loud in the session's call, `quilt voice join` joins it (or leaves with `--leave`), and `quilt voice transcript` reads what was said: the same as the call tools, for agents that use the command line instead of MCP.
21
+ - **Call transcripts stay in the order you spoke.** A short line could finish being written down before a longer one said just before it, and showed up first. Lines now go in in the order they were said.
22
+ - **Your folder's work reaches main by itself.** Once your folder has been quiet for a minute and a half, Quilt commits what your square holds and merges it onto main, waiting for main's required checks as `seam merge --wait` does; your folder carries on in a new square. Nothing waits for you to commit or merge, however long the work was held. Turn it off with `"autoLand": "off"` in Quilt's settings file.
23
+ - **Your work lands only when the project's fast tests pass.** Before it merges, Quilt runs the project's `test:fast` script in a fresh copy of your folder on your computer. If tests fail, the work stays held and you get one note naming the failing tests; Quilt tries again after your next change. An edit made while the tests run starts them again once the folder is quiet, and a run over 20 minutes counts as failed. Set `"landGate"` in Quilt's settings file (or `QUILT_LAND_GATE`) to another command, or to `off`.
24
+ - **A conflict with main settles without you.** Quilt takes Seam's own merge when it offers one; otherwise your cloud AI, if you connected one, gets a task to settle it (two tries); otherwise main's version stays in the file and yours is kept in a square of its own, titled "Your <file> from <time>, kept when main changed the same lines", and Quilt tells you once in chat. Nothing is lost.
25
+ - **Release notes no longer conflict.** Two people adding bullets to `RELEASES.md` (or any CHANGELOG-style file, or one marked `merge=union`) keep both. Work made on an older copy of a file, which took main's newer lines out and conflicted with the next patch beside them, is now put onto main's copy first.
26
+
14
27
  ## 0.3.148 — 2026-11-03
15
28
 
16
29
  - **The call says when an agent can't hear you.** Name an agent that Quilt has no way to wake and the call says so, with its face greyed out, instead of showing it joining forever. A person's cloud AI counts as one that wakes by itself.
package/bin/quilt.js CHANGED
@@ -37,6 +37,9 @@ Usage:
37
37
  quilt say [@name] <message> Message everyone, or one person with @name
38
38
  quilt send <file> [@name] [message] Send a file (not added to the project)
39
39
  quilt inbox --wait [--timeout <sec>] [--json] Wait for your next mention, direct message or task and print it (exit 2: timed out)
40
+ quilt voice say <text> Agents: say it out loud in the session's call (everyone hears it in your voice)
41
+ quilt voice join [--leave] Agents: join the call when someone says your name in it, or leave it
42
+ quilt voice transcript [-n 50] What was said in the session's calls, oldest first
40
43
  quilt wake [webhook|email|command|wait|push|schedule|turns|none] [--url U | --address A | --code C | --command CMD | --every N] How Quilt wakes you (step 2 of joining); no method: the ways that fit you
41
44
  quilt webhook set <url> [--bearer-env VAR] | clear | test | status Your webhook (quilt_webhook_subscribe): the relay POSTs your mentions, DMs and tasks there, even while you sleep
42
45
  quilt messages [--all] [--with name] [--grep text] [--before id] [-n 30]
@@ -103,6 +106,7 @@ async function main () {
103
106
  case 'inbox': return argv.includes('--wait') ? inboxWait() : messages()
104
107
  case 'webhook': return webhookCmd()
105
108
  case 'wake': return wakeCmd()
109
+ case 'voice': return voiceCmd()
106
110
  case 'get': return getFile()
107
111
  case 'commit': if (!argv.join(' ').trim()) fail('Usage: quilt commit <message>'); return simple('/square-commit', { message: argv.join(' ') }, (r) => r.text)
108
112
  case 'run': return runCmd()
@@ -663,6 +667,28 @@ function splitRecipient (args) {
663
667
  return { to: undefined, rest: args }
664
668
  }
665
669
 
670
+ // An agent in the session's voice call, from the command line: the same as quilt_voice_say,
671
+ // quilt_voice_join and quilt_voice_transcript, for agents that run commands instead of MCP.
672
+ async function voiceCmd () {
673
+ const [sub, ...rest] = argv
674
+ const usage = 'usage: quilt voice say <text> | quilt voice join [--leave] | quilt voice transcript [-n 50]'
675
+ if (sub === 'say') {
676
+ const text = rest.join(' ').trim()
677
+ if (!text) fail(usage)
678
+ return simple('/voice-say', { text }, () => 'Said in the call: everyone in it hears it in your voice.')
679
+ }
680
+ if (sub === 'join') {
681
+ return simple('/voice-join', { leave: rest.includes('--leave') }, (r) => r.in ? `You are in the call with ${r.people.join(', ')}. Only a line that says your name reaches you; answer out loud with quilt voice say.` : 'You left the call.')
682
+ }
683
+ if (sub === 'transcript') {
684
+ const i = rest.indexOf('-n')
685
+ const limit = i >= 0 ? Number(rest[i + 1]) || 50 : 50
686
+ const { renderLines } = await import('../src/voice.js')
687
+ return simple('/voice-transcript', { limit }, (r) => renderLines(r))
688
+ }
689
+ fail(usage)
690
+ }
691
+
666
692
  async function say () {
667
693
  const flag = (f) => { const i = argv.indexOf(f); if (i === -1) return false; argv.splice(i, 1); return true }
668
694
  const everyone = flag('--everyone')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heyquilt",
3
- "version": "0.3.148",
3
+ "version": "0.3.150",
4
4
  "description": "Real-time, tool-agnostic pair vibe coding: sync a project folder live between collaborators using any AI coding tool.",
5
5
  "author": {
6
6
  "name": "Daniel Carmichael",
@@ -20,7 +20,7 @@
20
20
  "test:stress": "node --disable-warning=ExperimentalWarning --import ./test/helpers/setup.js --test --test-concurrency=1 test/stress/*.test.js",
21
21
  "test:file": "node --disable-warning=ExperimentalWarning --import ./test/helpers/setup.js --test",
22
22
  "test:coverage": "node scripts/coverage.mjs",
23
- "test:fast": "node --disable-warning=ExperimentalWarning --import ./test/helpers/setup.js --test test/unit/*.test.js test/integration/*.test.js",
23
+ "test:fast": "node scripts/test-fast.mjs",
24
24
  "serve": "node bin/quilt.js serve",
25
25
  "app": "electron .",
26
26
  "dist:mac": "electron-builder --mac",
package/src/inbox.js CHANGED
@@ -196,8 +196,8 @@ export function describeEvent (e) {
196
196
  if (e.kind === 'mention') return `${who} ${e.follows ? 'wrote again in chat after mentioning you' : 'mentioned you in chat'}${idOf(e)}: ${e.text}`
197
197
  if (e.kind === 'voice') {
198
198
  const before = Array.isArray(e.said) && e.said.length ? ` Just before, in the call: ${e.said.map((l) => `${l.by}: "${clip(l.text, 300)}"`).join(' / ')}.` : ''
199
- const join = e.joined ? '' : ' You are not in the call yet: if it is for you, join it with quilt_voice_join (quilt_voice_transcript reads more of what was said).'
200
- return `${who} said your name in the voice call: "${e.text}".${before}${join} If it is for you, first say a few words at once with quilt_voice_say that fit what was asked, so people know you heard (in your own words, never a stock phrase); then answer out loud once you have it (no reply in chat needed). Stay quiet if it is not for you.`
199
+ const join = e.joined ? '' : ' You are not in the call yet: if it is for you, join it with quilt_voice_join (`quilt voice join` on the command line; quilt_voice_transcript reads more of what was said).'
200
+ return `${who} said your name in the voice call: "${e.text}".${before}${join} If it is for you, first say a few words at once with quilt_voice_say (\`quilt voice say <text>\`) that fit what was asked, so people know you heard (in your own words, never a stock phrase); then answer out loud the same way once you have it, not in chat. Stay quiet if it is not for you.`
201
201
  }
202
202
  if (e.kind === 'email') return `New email for the session (no reply needed in chat)${idOf(e)}: ${e.text}${e.mail ? ` Read it with quilt_mail (read: "${e.mail}"); answer by email with quilt_mail_send (reply_to: "${e.mail}") if it needs one.` : ''}`
203
203
  if (e.kind === 'task') {
package/src/runner.js CHANGED
@@ -167,6 +167,8 @@ export async function runSession ({ dir, conn, name, tool, color = null, shareBy
167
167
  // listens before the session starts: what was written to their cloud AI while it was away arrives
168
168
  // as the session syncs, before start() returns, and is its work.
169
169
  autowork().attach(session)
170
+ // Whether this person connected a cloud AI, as the API last said (land.js asks it to settle conflicts in their square).
171
+ session.cloudAiKnown = () => { try { return !!autowork().cloudAi() } catch { return false } }
170
172
  try {
171
173
  await session.start({ waitTimeoutMs: 15000 })
172
174
  } catch (err) {
package/src/server.js CHANGED
@@ -36,7 +36,7 @@ import {
36
36
  syncStep1Message, updateMessage, awarenessMessage, bytesMessage, jsonMessage
37
37
  } from './protocol.js'
38
38
  import { isLiveKey, liveRequest, liveKey, liveMaps, liveHead, overlay, seal, entryId, startHead } from './source-live/live-square.js'
39
- import { conflictsAhead, commitAhead, staleAhead, standHead, moveLive, lateEdits, sideReader, HOLDER_WAIT_MS } from './source-live/bring-in.js'
39
+ import { conflictsAhead, commitAhead, staleAhead, olderCopiesAhead, unionMarked, standHead, moveLive, lateEdits, sideReader, HOLDER_WAIT_MS } from './source-live/bring-in.js'
40
40
  import { blobId } from '@heyquilt/seam/lib/quilts/records.js'
41
41
  import { planSessionQuilt, quiltPlanRefusal, describeQuiltPlan, fileHash } from './session-quilt.js'
42
42
  import { makeQuiltWithoutHistory, termsFor } from './session-migrate.js'
@@ -2417,18 +2417,38 @@ class Room {
2417
2417
  standHead(doc, stale, liveHead(doc))
2418
2418
  this.log(`[${this.name}] square ${squareShort(id)}: ${stale.length} live file(s) were older copies of main's, not edits; main's stand (${stale.slice(0, 5).join(', ')}${stale.length > 5 ? ', …' : ''})`)
2419
2419
  }
2420
- const ahead = await conflictsAhead(seam, q, sq, doc, sq.line || 'main')
2420
+ // Work edited on an older copy of main's file is put onto the square's copy first: main's newer lines are nobody's deletion.
2421
+ // Files the project marks merge=union (its .gitattributes) combine like RELEASES.md: both sides stay.
2422
+ const marked = await unionMarked(seam, q, sq.line || 'main')
2423
+ const older = await olderCopiesAhead(seam, q, sq, doc, sq.line || 'main', { marked }).catch((err) => { this.log(`[${this.name}] could not look for work made on older copies of main's files in square ${squareShort(id)}: ${err.message}`); return [] })
2424
+ if (older.length) this.log(`[${this.name}] square ${squareShort(id)}: ${older.length} live file(s) were edited on an older copy of main's; their edits were put onto the square's copy (${older.slice(0, 5).join(', ')}${older.length > 5 ? ', …' : ''})`)
2425
+ const ahead = await conflictsAhead(seam, q, sq, doc, sq.line || 'main', { marked })
2421
2426
  const head = ahead.length ? await commitAhead(seam, q, sq, doc, ahead, by) : sq.head
2422
2427
  const r = await seam.rebase(q, id, { expect_head: head || null })
2423
2428
  if (r.noop || !r.square) { this.catchUps.delete(id); return done() }
2424
2429
  const to = r.square.head || r.square.base
2425
2430
  const terms = [...new Set([...(r.terms || []).map((t) => t.path), ...ahead])]
2426
- const m = await this.moveSquareLive(seam, q, lk, doc, { prev: head || sq.base, head: to, base: !r.square.head, by, brought: { patches: sq.behind_by, conflicts: terms, ...(stale.length ? { stale: stale.slice(0, 50) } : {}) } })
2431
+ const m = await this.moveSquareLive(seam, q, lk, doc, { prev: head || sq.base, head: to, base: !r.square.head, by, marked, brought: { patches: sq.behind_by, conflicts: terms, ...(stale.length ? { stale: stale.slice(0, 50) } : {}) } })
2427
2432
  this.catchUps.delete(id)
2428
2433
  this.log(`[${this.name}] brought ${sq.behind_by} patch(es) of ${sq.line || 'main'} into square ${squareShort(id)} as ${by || 'a member'}${m.combined.length ? `, combining ${m.combined.length} live file(s)` : ''}${terms.length ? `; ${terms.length} conflict(s) kept in the square` : ''}`)
2429
2434
  return done({ brought: { patches: sq.behind_by, combined: m.combined, conflicts: [...new Set([...terms, ...m.conflicts])], ...(stale.length ? { stale: stale.slice(0, 50) } : {}) }, ...(r.square.conflicted_paths ? { conflicted: r.square.conflicted_paths } : {}) })
2430
2435
  }
2431
2436
 
2437
+ /**
2438
+ * A member's app tells its own person something Quilt did with their square's work by itself
2439
+ * (session-follow.js: their version of a file kept in a square of its own when main's change won
2440
+ * the same lines): a note from Quilt in chat, to them alone. Nobody else is told.
2441
+ */
2442
+ quiltNote (ws, req) {
2443
+ const a = this.access.get(ws)
2444
+ const name = this.names.get(ws)
2445
+ if (!a || a.role === 'viewer' || (a.state && a.state !== 'approved') || !name) throw new Error('only a member who may change files is told about their square')
2446
+ const text = String(req.text || '').trim().slice(0, 1000)
2447
+ if (!text) throw new Error('a note needs its words')
2448
+ const m = this.postChat({ by: 'Quilt', to: name, text, kind: 'note' })
2449
+ return { ok: true, message: m.id }
2450
+ }
2451
+
2432
2452
  /** A square's live document moved onto `head` (bring-in.js moveLive), late edits made on the old head combined after (lateEdits). */
2433
2453
  async moveSquareLive (reader, q, lk, doc, opts) {
2434
2454
  const r = await moveLive(reader, q, doc, opts)
@@ -3743,7 +3763,7 @@ class Room {
3743
3763
  read.then(answer, (err) => answer({ ok: false, error: err.message }))
3744
3764
  return
3745
3765
  }
3746
- reply = { id: req.id, op: req.op, ...this.branchRequest(ws, req) }
3766
+ reply = { id: req.id, op: req.op, ...(req.op === 'quilt-note' ? this.quiltNote(ws, req) : this.branchRequest(ws, req)) }
3747
3767
  } catch (err) {
3748
3768
  reply = { id: req.id, op: req.op, ok: false, error: err.message }
3749
3769
  }
@@ -23,8 +23,10 @@ import * as Y from 'yjs'
23
23
  import { FEATURES } from './protocol.js'
24
24
  import { openLiveBlock } from './source-live/live-block.js'
25
25
  import { appSeamUrl } from './seam-url.js'
26
- import { lastWriters } from './source-live/live-square.js'
26
+ import { lastWriters, liveMaps } from './source-live/live-square.js'
27
27
  import { broughtOf } from './source-live/bring-in.js'
28
+ import { Lander, landOn } from './source-live/land.js'
29
+ import { getSettings } from './settings.js'
28
30
  import { catchUpWords } from './ui/seam-model.js'
29
31
  import { QUILT_MOVE_TIMEOUT_MS } from './connection.js'
30
32
  import { squareShort } from '@heyquilt/seam/lib/quilts/errors.js'
@@ -396,6 +398,7 @@ export class SquareFollower {
396
398
  if (block.doc && block.doc.getMap) block.doc.getMap('live').observe(() => { if (this.here === here) this.catchUpSoon() })
397
399
  here.catchUpTimer = setInterval(() => this.catchUp().catch(() => {}), this.catchUpMs)
398
400
  here.catchUpTimer.unref?.()
401
+ here.lander = this.landerFor(here, block, at, quilt)
399
402
  this.catchUp().catch(() => {})
400
403
  } catch (err) {
401
404
  if (this.here !== here) return
@@ -430,6 +433,46 @@ export class SquareFollower {
430
433
  await this.openHere(at, quilt, { fresh: true })
431
434
  }
432
435
 
436
+ /**
437
+ * The folder's held work lands by itself (source-live/land.js): a person's folder only (an agent's
438
+ * own square has its AI; a cloud AI's folder works for its person, who lands), with Seam on and
439
+ * landing not turned off. Every edit on the square (anyone's) starts its quiet again.
440
+ */
441
+ landerFor (here, block, at, quilt) {
442
+ const s = this.session
443
+ if (!this.landing || s.kind === 'agent' || s.aiOf || !s.seamClientNow || !s.conn) return null
444
+ const branch = s.squareBranchKey ? s.squareBranchKey() : s.branchKey()
445
+ const lander = new Lander({
446
+ quilt: quilt.id,
447
+ square: at.square,
448
+ line: 'main',
449
+ block,
450
+ ...(this.landOpts || {}),
451
+ client: async () => { const c = await s.seamClientNow(); if (c) block.client = c; return c },
452
+ next: async () => { const { token } = await s.seamMember().client(quilt.id, [at.square]); return s.conn.branchRequest({ op: 'quilt-next', token, branch }, { timeoutMs: QUILT_MOVE_TIMEOUT_MS }) },
453
+ catchUp: () => this.catchUp(),
454
+ hasAi: () => !!(s.hasCloudAi && s.hasCloudAi()),
455
+ person: s.name,
456
+ board: { list: () => s.taskList(), add: (f) => s.addTask(f), comment: (id, text) => s.commentTask({ id, text }), move: (id, column) => s.updateTask({ id, column }) },
457
+ notify: (text) => { if (s.noteToSelf) s.noteToSelf(text) },
458
+ log: (m) => { if (this.here === here && s.log) s.log(`🧵 ${m}`) }
459
+ })
460
+ if (block.doc && block.doc.getMap) {
461
+ const m = liveMaps(block.doc)
462
+ const edited = () => { if (this.here === here) lander.edited() }
463
+ for (const k of ['files', 'blobs', 'gone']) m[k].observeDeep(edited)
464
+ }
465
+ lander.soon(lander.quietMs + 50)
466
+ return lander
467
+ }
468
+
469
+ /** Whether held work lands by itself here (land.js landOn), read each time a block opens. */
470
+ get landing () {
471
+ let settings = {}
472
+ try { settings = getSettings() } catch {}
473
+ return landOn({ settings })
474
+ }
475
+
433
476
  /** catchUp in a moment: the relay says something of the quilt in bursts, and one ask answers them all. */
434
477
  catchUpSoon () {
435
478
  if (!this.here || !this.here.block || this.catchUpTimer) return
@@ -458,8 +501,10 @@ export class SquareFollower {
458
501
  // Main waits for a folder on the square too old to follow its base moving (server.js outdatedOn): whose.
459
502
  h.outdated = Array.isArray(r.outdated) ? r.outdated.map(String).slice(0, 10) : []
460
503
  h.catchUpProblem = ''
461
- if (r.brought && s.log) s.log(`🧵 ${catchUpWords({ brought: { ...r.brought, at: Date.now() } }).join(' ')}`)
504
+ if (r.brought && s.log) s.log(`🧵 ${catchUpWords({ brought: { ...r.brought, at: Date.now() }, lands: !!h.lander }).join(' ')}`)
462
505
  if (s.scheduleStatusWrite) s.scheduleStatusWrite()
506
+ // A look at landing the held work too (a square with commits and nothing typed lands this way).
507
+ if (h.lander && !h.lander.busy) setTimeout(() => { if (this.here === h && h.lander) h.lander.tick().then(() => { if (s.scheduleStatusWrite) s.scheduleStatusWrite() }).catch(() => {}) }, 0).unref?.()
463
508
  return r
464
509
  } catch (err) {
465
510
  if (this.here === h && h.catchUpProblem !== err.message) {
@@ -483,6 +528,9 @@ export class SquareFollower {
483
528
  const b = h.block ? broughtOf(h.block.doc) : null
484
529
  const brought = b ? { at: b.at, by: b.by || '', patches: b.patches || 0, combined: b.combined || [], conflicts: b.conflicts || [], ...(Array.isArray(b.stale) && b.stale.length ? { stale: b.stale } : {}) } : null
485
530
  const catching = { ...(h.behind ? { behind: h.behind } : {}), ...(h.behind && h.outdated && h.outdated.length ? { outdated: h.outdated } : {}), ...(h.conflicted !== undefined ? { conflicted: h.conflicted } : {}), ...(brought ? { brought } : {}) }
531
+ // What landing the held work did last (land.js): landed, kept aside, asked the person's AI, waiting.
532
+ if (h.lander) catching.lands = true
533
+ if (h.lander && h.lander.state) catching.landing = h.lander.state
486
534
  const words = h.block ? catchUpWords(catching).join(' ') : ''
487
535
  return { square: h.square, short: squareShort(h.square).slice(3), quilt, ...(h.opening ? { opening: true } : {}), ...(problem ? { problem } : {}), ...(work ? { work } : {}), ...catching, line: squareLine({ square: h.square, quilt, problem: h.problem, opening: h.opening }) + (h.block && h.block.problem ? ` ${h.block.problem}.` : '') + (h.block && h.block.outOfStep ? ` ${h.block.outOfStep}.` : '') + (words ? ` ${words}` : '') }
488
536
  }
@@ -509,6 +557,7 @@ export class SquareFollower {
509
557
  clearTimeout(this.catchUpTimer)
510
558
  this.catchUpTimer = null
511
559
  if (h) clearInterval(h.catchUpTimer)
560
+ if (h && h.lander) h.lander.stop()
512
561
  if (this.session.unfollowSquareDoc) this.session.unfollowSquareDoc()
513
562
  if (h && h.block && h.block.close) await h.block.close().catch(() => {})
514
563
  // Still opening (waiting for the relay, say): stopped where it is, or its connection outlives the folder's square.
package/src/session.js CHANGED
@@ -4028,6 +4028,29 @@ export class Session extends EventEmitter {
4028
4028
  return false
4029
4029
  }
4030
4030
 
4031
+ /**
4032
+ * Whether this person has a cloud AI to hand work to (land.js asks it to settle a conflict in their
4033
+ * square): in the session now, or connected to their account as the app last heard (cloudAiKnown,
4034
+ * set by runner.js from the API's answer). Never their AI sessions on a computer: those are them.
4035
+ */
4036
+ hasCloudAi () {
4037
+ if (this.aiOf || this.kind === 'agent') return false
4038
+ return !!(this.cloudAiLive() || (this.cloudAiKnown && this.cloudAiKnown()))
4039
+ }
4040
+
4041
+ /**
4042
+ * One note to this person about their own work (land.js: their version of a file kept aside when
4043
+ * main's change won the same lines): from Quilt in chat, to them alone (the relay's quilt-note), and
4044
+ * told to their AI sessions at their next call. A relay too old for it leaves the log line only.
4045
+ */
4046
+ noteToSelf (text) {
4047
+ const t = String(text || '').slice(0, 1000)
4048
+ if (!t) return
4049
+ this.log(`🧵 ${t}`)
4050
+ this.notice(t)
4051
+ if (this.conn && this.conn.connected) this.conn.branchRequest({ op: 'quilt-note', text: t }).catch(() => {})
4052
+ }
4053
+
4031
4054
  /** Who an action from this AI session is by: its own name, or this member's. */
4032
4055
  actorName (via) { const p = this.persona(via); return p ? p.name : this.name }
4033
4056
 
@@ -17,7 +17,7 @@
17
17
  // rebase keeps it as a conflict in the square, the same as a merge does with live work (session-seam.js
18
18
  // seam_merge): members see it marked in their folders and settle it, and nothing typed is lost.
19
19
  import { liveMaps, liveHead, entryOf, overlay, seal } from './live-square.js'
20
- import { mergeSmart, withMarkers } from '../merge3.js'
20
+ import { mergeSmart, withMarkers, unionMatcher } from '../merge3.js'
21
21
  import { applyTextDiff } from '../textdiff.js'
22
22
  import { blobId } from '@heyquilt/seam/lib/quilts/records.js'
23
23
  import { isText } from '@heyquilt/seam/lib/quilts/textdiff.js'
@@ -77,22 +77,129 @@ function liveSide (doc, p) {
77
77
  * when the work is what the new head has, { text } when they combine (text, both changed), or
78
78
  * { conflict } (the same lines changed differently, or a binary, deletion or term on both sides).
79
79
  */
80
- export function combine (o, l, n) {
80
+ export function combine (o, l, n, { union = false } = {}) {
81
81
  if (l.id === n.id) return { same: true }
82
82
  if (o.id === n.id) return { keep: true }
83
83
  if (o.id === l.id) return { same: true, theirs: true }
84
84
  if (o.text === null || l.text === null || n.text === null || l.id === null || n.id === null) return { conflict: true }
85
- const m = mergeSmart(o.text, l.text, n.text)
85
+ let m = mergeSmart(o.text, l.text, n.text)
86
+ // A changelog (isChangelog): where both changed one place, both sides stay, the work's first (git's merge=union).
87
+ if (m.conflicts.length && union) m = mergeSmart(o.text, l.text, n.text, { union: true })
86
88
  return m.conflicts.length ? { conflict: true } : m.text === n.text ? { same: true } : { text: m.text }
87
89
  }
88
90
 
91
+ // Changelog-style files: each side adds its own entries, and two sides that added at one place both
92
+ // stay (git's merge=union) instead of conflicting. RELEASES.md is Quilt's own (AGENTS.md: every
93
+ // user-visible change adds a bullet there). A project marks others with merge=union in .gitattributes.
94
+ export const CHANGELOG = /(^|\/)(RELEASES|CHANGELOG|CHANGES|HISTORY|NEWS)(\.(md|markdown|txt|rst))?$/i
95
+ export const isChangelog = (p, marked = null) => CHANGELOG.test(String(p || '')) || !!(marked && marked(p))
96
+
97
+ /** The files the project's .gitattributes (at `rev`, its top folder) marks merge=union, as a matcher, or null. */
98
+ export async function unionMarked (reader, q, rev) {
99
+ if (!reader || typeof reader.cat !== 'function') return null
100
+ try {
101
+ const r = await reader.cat(q, rev, '.gitattributes')
102
+ const text = r && r.content && !r.conflict ? Buffer.from(r.content, 'base64').toString('utf8') : ''
103
+ return /merge=union/.test(text) ? unionMatcher([['', text]]) : null
104
+ } catch { return null }
105
+ }
106
+
107
+ /** How far apart two texts are: the lines one has and the other lacks, counted with repeats. */
108
+ export function lineDistance (a, b) {
109
+ const n = new Map()
110
+ for (const x of String(a).split('\n')) n.set(x, (n.get(x) || 0) + 1)
111
+ for (const x of String(b).split('\n')) n.set(x, (n.get(x) || 0) - 1)
112
+ let d = 0
113
+ for (const v of n.values()) d += Math.abs(v)
114
+ return d
115
+ }
116
+
117
+ /**
118
+ * Work made on an older copy of main's file (2026-11-03, sq:09a100d0's RELEASES.md: the folder's
119
+ * copy was main's from days before plus one new bullet, so against the square's base it "deleted"
120
+ * main's newer sections, and main's next patch, adding a section beside them, conflicted). `text`
121
+ * is the work, `from` the copy it ought to be relative to, `older` main's earlier texts of the path
122
+ * (newest first). When one of them is nearer to the work than `from` is, the work was made on it:
123
+ * its edits are put onto `onto` three ways from that copy. { text, from: its index } or null (none
124
+ * nearer, or the edits do not combine there; a changelog keeps both sides, `union`).
125
+ */
126
+ export function onOlderCopy (text, from, onto, older, { union = false } = {}) {
127
+ if (typeof text !== 'string' || typeof from !== 'string' || typeof onto !== 'string') return null
128
+ const far = lineDistance(from, text)
129
+ let best = -1
130
+ let bestD = far
131
+ for (let i = 0; i < older.length; i++) {
132
+ if (typeof older[i] !== 'string' || older[i] === from) continue
133
+ const d = lineDistance(older[i], text)
134
+ if (d < bestD) { best = i; bestD = d }
135
+ }
136
+ if (best < 0) return null
137
+ let m = mergeSmart(older[best], text, onto)
138
+ if (m.conflicts.length && union) m = mergeSmart(older[best], text, onto, { union: true })
139
+ return m.conflicts.length ? null : { text: m.text, from: best }
140
+ }
141
+
142
+ // How many of main's earlier versions of a file onOlderCopy reads, newest first, and in what batches.
143
+ export const OLDER_LOOKS = 100
144
+ const OLDER_BATCH = 20
145
+
146
+ /** Main's earlier texts of `p` before `rev` (text up to 2 MiB), newest first, read with `reader` (pathHistory, blobs). */
147
+ export async function olderTexts (reader, q, p, rev, { limit = OLDER_LOOKS } = {}) {
148
+ if (!reader || typeof reader.pathHistory !== 'function') return []
149
+ let h
150
+ try { h = await reader.pathHistory(q, p, { rev, limit }) } catch { return [] }
151
+ const ids = []
152
+ for (const e of (h && h.entries) || []) if (e.op === 'put' && e.blob && (e.size ?? 0) <= MAX_TEXT && !ids.includes(e.blob)) ids.push(e.blob)
153
+ const out = []
154
+ for (let i = 0; i < ids.length; i += OLDER_BATCH) {
155
+ const got = (await reader.blobs(q, ids.slice(i, i + OLDER_BATCH)).catch(() => ({ blobs: {} }))).blobs || {}
156
+ for (const id of ids.slice(i, i + OLDER_BATCH)) {
157
+ const b = got[id] ? Buffer.from(got[id], 'base64') : null
158
+ out.push(b && isText(b) ? b.toString('utf8') : null)
159
+ }
160
+ }
161
+ return out
162
+ }
163
+
164
+ /**
165
+ * Before the rebase: live text files that would not combine with main because they were edited on an
166
+ * older copy of main's file (onOlderCopy). Each one's edits are put onto the square's head copy in the
167
+ * live document (one transaction, `origin` relay-quilt), so main's newer lines are no longer taken
168
+ * out and the move combines them as any edit. Returns the paths it moved.
169
+ */
170
+ export async function olderCopiesAhead (reader, q, sq, doc, tip, { marked = null } = {}) {
171
+ if (!reader || typeof reader.pathHistory !== 'function') return []
172
+ const paths = overlay(doc).filter((x) => x.bytes).map((x) => x.path)
173
+ const changed = [...await changedBetween(reader, q, `c:${sq.base}`, tip, paths)]
174
+ if (!changed.length) return []
175
+ const head = await sidesAt(reader, q, sq.head ? `c:${sq.head}` : `c:${sq.base}`, changed)
176
+ const now = await sidesAt(reader, q, tip, changed)
177
+ const m = liveMaps(doc)
178
+ const out = []
179
+ for (const p of changed) {
180
+ const l = liveSide(doc, p)
181
+ const [h, t] = [head.get(p), now.get(p)]
182
+ const union = isChangelog(p, marked)
183
+ if (!l || l.text === null || !h || h.text === null || h.term || !t || t.term || !combine(h, l, t, { union }).conflict) continue
184
+ const r = onOlderCopy(l.text, h.text, h.text, await olderTexts(reader, q, p, tip), { union })
185
+ if (!r) continue
186
+ const moved = { id: blobId(Buffer.from(r.text, 'utf8')), text: r.text }
187
+ if (combine(h, moved, t, { union }).conflict) continue
188
+ const y = m.files.get(p)
189
+ if (!y || y.toString() !== l.text) continue
190
+ doc.transact(() => applyTextDiff(y, r.text), 'relay-quilt')
191
+ out.push(p)
192
+ }
193
+ return out
194
+ }
195
+
89
196
  /**
90
197
  * Before the rebase: the square's live files that would not combine with main (`sq` Seam's square,
91
198
  * `tip` main's revision now). Its new head will have, for each, main's file where the square's commits
92
199
  * did not change it, else Seam's combination of both; one that does not combine there is a conflict
93
200
  * in the square already, and its live work goes with it.
94
201
  */
95
- export async function conflictsAhead (reader, q, sq, doc, tip) {
202
+ export async function conflictsAhead (reader, q, sq, doc, tip, { marked = null } = {}) {
96
203
  const paths = overlay(doc).map((x) => x.path)
97
204
  const changed = [...await changedBetween(reader, q, `c:${sq.base}`, tip, paths)]
98
205
  if (!changed.length) return []
@@ -105,13 +212,14 @@ export async function conflictsAhead (reader, q, sq, doc, tip) {
105
212
  if (!l) continue
106
213
  const [b, h, t] = [base.get(p), head.get(p), now.get(p)]
107
214
  let theirs = t
215
+ const union = isChangelog(p, marked)
108
216
  if (h.id !== b.id) {
109
- const c = combine(b, h, t)
217
+ const c = combine(b, h, t, { union })
110
218
  if (c.conflict) { out.push(p); continue }
111
219
  if (c.text !== undefined) theirs = { id: blobId(Buffer.from(c.text, 'utf8')), text: c.text }
112
220
  else if (!c.theirs) theirs = h
113
221
  }
114
- if (combine(h, l, theirs).conflict) out.push(p)
222
+ if (combine(h, l, theirs, { union }).conflict) out.push(p)
115
223
  }
116
224
  return out
117
225
  }
@@ -200,7 +308,7 @@ export async function commitAhead (seam, q, sq, doc, paths, by) {
200
308
  * is kept in the document for everyone's status. { combined, conflicts, dropped, late } or throws when
201
309
  * the live head is no longer `prev`.
202
310
  */
203
- export async function moveLive (reader, q, doc, { prev, head, base = false, by = '', brought = null }) {
311
+ export async function moveLive (reader, q, doc, { prev, head, base = false, by = '', brought = null, marked = null }) {
204
312
  const moved = await changedBetween(reader, q, `c:${prev}`, `c:${head}`)
205
313
  const old = new Map()
206
314
  const now = new Map()
@@ -220,7 +328,7 @@ export async function moveLive (reader, q, doc, { prev, head, base = false, by =
220
328
  const l = liveSide(doc, p)
221
329
  if (!l) continue
222
330
  const [o, n] = [old.get(p), now.get(p)]
223
- const c = combine(o, l, n)
331
+ const c = combine(o, l, n, { union: isChangelog(p, marked) })
224
332
  if (c.same) { drop[p] = l.id; out.dropped.push(p); continue }
225
333
  if (c.keep) continue
226
334
  const t = m.files.get(p)
@@ -0,0 +1,393 @@
1
+ // Quilt's side of seam: live squares in a Quilt session. Seam (src/quilts/) never imports this.
2
+ // A person's held work lands by itself (Daniel, 2026-11-03). A folder's square holds the person's live
3
+ // work until someone commits and merges it, and when another merge changed the same lines it held a
4
+ // conflict too, waiting for a person nobody had asked (sq:09a100d0's RELEASES.md against main:1076).
5
+ // Agents' squares have their AI asked; a person's folder square had no one. Now, whatever how long the
6
+ // work was held, the person's app (as them, with their own Seam sign-in) lands it with no step of theirs:
7
+ //
8
+ // 1. Quiet for a moment (LAND_QUIET_MS after the last edit to the square, anyone's): the square's live
9
+ // work is committed with a message naming its files and merged onto its line, waiting for the
10
+ // line's required checks the way `seam merge --wait` does (merge-wait.js); the folder carries on
11
+ // in a new square (the relay's quilt-next).
12
+ // 2. A conflict in the square is settled without asking the person, in this order:
13
+ // a. what Seam offers by itself: a conflict's word-level suggestion, else its additive and
14
+ // whitespace steps (a changelog also its union step: bring-in.js isChangelog), else the work
15
+ // put onto main's copy when it was made on an older one (bring-in.js onOlderCopy);
16
+ // b. the person's own AI on their cloud machine, when they connected one: a task on the board for
17
+ // "<person>'s AI" (the relay wakes it, as for any task given to it; the same for every AI
18
+ // tool), with the file, both sides and what to do. AI_ATTEMPTS tries, as Seam gives an AI.
19
+ // AI sessions on the person's computer ARE the person, and are never handed this;
20
+ // c. else main's side stays in the file, and the person's version of each such file is kept in a
21
+ // square of its own, opened from their work and titled so they find it; the held square then
22
+ // merges, and the person is told once, in chat. Nothing is lost.
23
+ //
24
+ // Only the square's holder's app lands it; a writer's app does once the holder's has been quiet for
25
+ // HOLDER_WAIT_MS more (offline), the same turn as bringing main in (bring-in.js).
26
+ import { mergeWaiting } from '@heyquilt/seam/lib/quilts/merge-wait.js'
27
+ import { parseMarkers } from '@heyquilt/seam/lib/quilts/conflict-format.js'
28
+ import { blobId } from '@heyquilt/seam/lib/quilts/records.js'
29
+ import { squareShort } from '@heyquilt/seam/lib/quilts/errors.js'
30
+ import { isChangelog, onOlderCopy, olderTexts, unionMarked, HOLDER_WAIT_MS } from './bring-in.js'
31
+
32
+ const num = (v, d) => (Number(v) > 0 ? Number(v) : d)
33
+ // How long the square's work is left alone after its last edit before it lands.
34
+ export const LAND_QUIET_MS = num(process.env.QUILT_LAND_QUIET_MS, 90 * 1000)
35
+ // Seam's own number of tries an AI gets at one conflict (Seam's events.js AI_ATTEMPTS).
36
+ export const AI_ATTEMPTS = 2
37
+ // How long one try of the person's AI may take before it counts as failed.
38
+ export const AI_ATTEMPT_MS = num(process.env.QUILT_LAND_AI_MS, 15 * 60 * 1000)
39
+ // How long a merge waits for the line's required checks (seconds), as `seam merge --wait` would.
40
+ export const LAND_WAIT_S = num(process.env.QUILT_LAND_WAIT_S, 30 * 60)
41
+ // After a merge the line refused for something only a person can give (an approval, a red check), the next try.
42
+ export const REFUSED_RETRY_MS = 10 * 60 * 1000
43
+ // Seam's ladder steps a person never has to choose, tried on each conflict in turn (seam_resolve's rule).
44
+ export const RULES = ['additive', 'whitespace']
45
+
46
+ /**
47
+ * Whether held work lands by itself: on, unless QUILT_LAND=off or the person turned it off in their
48
+ * settings (autoLand: 'off'). Under node --test (Quilt's own tests) it is off unless a test sets
49
+ * QUILT_LAND=on: a square merging by itself after a quiet moment would change what other tests watch.
50
+ */
51
+ export function landOn ({ env = process.env, settings = {} } = {}) {
52
+ const v = String(env.QUILT_LAND || '').toLowerCase()
53
+ if (v === 'off') return false
54
+ if (v === 'on') return true
55
+ if (env.NODE_TEST_CONTEXT) return false
56
+ return settings.autoLand !== 'off'
57
+ }
58
+
59
+ const listed = (names) => `${names.slice(0, 5).join(', ')}${names.length > 5 ? ` and ${names.length - 5} more` : ''}`
60
+ const clock = (ts) => new Date(ts).toISOString().slice(11, 16) + ' UTC'
61
+
62
+ /** The commit message of work that lands by itself: its files, and that Quilt landed it. */
63
+ export function landMessage (paths) {
64
+ const names = [...new Set(paths)].sort()
65
+ return names.length ? `Work on ${listed(names)}, landed by Quilt once the folder went quiet` : 'Work landed by Quilt once the folder went quiet'
66
+ }
67
+
68
+ /** The square the person's version of files is kept in, titled so they find it. */
69
+ export function keptTitle (paths, at) {
70
+ const names = [...new Set(paths)].sort()
71
+ const what = names.length === 1 ? names[0] : `${names.length} files (${listed(names)})`
72
+ return `Your ${what} from ${clock(at)}, kept when main changed the same lines`.slice(0, 200)
73
+ }
74
+
75
+ /** The board task that asks the person's AI to settle a conflict: the file and the square, with the conflict's term so a retry is told apart. */
76
+ export function aiTaskTitle ({ paths, square, term }) {
77
+ return `Settle ${listed(paths)} in ${squareShort(square)}: main changed the same lines as the held work (conflict ${String(term || '').slice(0, 8)})`.slice(0, 200)
78
+ }
79
+
80
+ /** The one notice the person gets when their version was kept aside. */
81
+ export function keptNotice ({ paths, kept, line = 'main', patch = null }) {
82
+ return `Your held work${patch ? ` landed on ${line} as patch ${patch}` : ` is landing on ${line}`}, but ${listed(paths)} changed on ${line} in the same lines, so ${line}'s version stayed there. Your version is kept in square ${squareShort(kept)} ("Your … kept when main changed the same lines"): nothing was lost.`
83
+ }
84
+
85
+ /**
86
+ * The sides of a conflicted file as Seam writes it in its snapshot format (cat format snapshot):
87
+ * { ours, theirs, base } texts (null for a side that deleted it), or null when it is not one plain
88
+ * two-sided term (a name conflict, more sides, no markers).
89
+ */
90
+ export function sidesOf (text) {
91
+ let regions
92
+ try { regions = parseMarkers(text) } catch { return null }
93
+ const blocks = regions.filter((r) => !r.ok)
94
+ if (blocks.length !== 1 || blocks[0].format !== 'snapshot' || regions.some((r) => r.ok && r.ok.some((l) => l !== ''))) return null
95
+ const b = blocks[0]
96
+ if (!b.sides || b.sides.length !== 2) return null
97
+ const t = (s) => (s && !s.deleted && typeof s.text === 'string' ? s.text : null)
98
+ const bases = b.removes || []
99
+ return { ours: t(b.sides[0]), theirs: t(b.sides[1]), base: typeof bases[0] === 'string' ? bases[0] : (bases[0] && typeof bases[0].text === 'string' ? bases[0].text : '') }
100
+ }
101
+
102
+ /**
103
+ * Lands one folder's square. Everything it touches comes in `o`: `quilt`, `square`, `line`; `client()`
104
+ * (a Seam client as this member: square, diff, tree, cat, resolve, merge, events, openSquare, upload,
105
+ * commit, pathHistory, blobs, quilt); `block` (the folder's live block: status, commit, moveTo, block);
106
+ * `next()` (the relay moves the branch on to a new square after a merge); `catchUp()` (main brought
107
+ * in first); `hasAi()` (the person connected a cloud AI); `board` ({ list, add, comment, move }) as the
108
+ * person; `notify(text)` (one note to the person, in chat); `log`; `now`, `quietMs`, `aiMs`,
109
+ * `holderWaitMs`, `waitS` and `marked(path)` (a project's merge=union files).
110
+ */
111
+ export class Lander {
112
+ constructor (o) {
113
+ Object.assign(this, { quietMs: LAND_QUIET_MS, aiMs: AI_ATTEMPT_MS, holderWaitMs: HOLDER_WAIT_MS, waitS: LAND_WAIT_S, now: Date.now, log: () => {}, notify: () => {}, hasAi: () => false, catchUp: async () => null, marked: null }, o)
114
+ this.lastEdit = this.now()
115
+ this.busy = false
116
+ this.timer = null
117
+ this.stopped = false
118
+ this.refusedAt = 0
119
+ this.refusedHead = null
120
+ this.state = null // what it did last, for status: { landed } | { kept } | { asked } | { waiting }
121
+ }
122
+
123
+ /** An edit reached the square (anyone's): the quiet starts again, and a look is due once it lasts. */
124
+ edited () {
125
+ this.lastEdit = this.now()
126
+ this.soon(this.quietMs + 50)
127
+ }
128
+
129
+ soon (ms) {
130
+ if (this.stopped) return
131
+ clearTimeout(this.timer)
132
+ this.timer = setTimeout(() => { this.timer = null; this.tick().catch(() => {}) }, ms)
133
+ this.timer.unref?.()
134
+ }
135
+
136
+ stop () { this.stopped = true; clearTimeout(this.timer) }
137
+
138
+ async me (c) {
139
+ if (this.memberId) return this.memberId
140
+ const q = await c.quilt(this.quilt).catch(() => null)
141
+ this.memberId = (q && q.you && q.you.member_id) || null
142
+ return this.memberId
143
+ }
144
+
145
+ /** One look: lands the square's work, or settles its conflict first. Answers what it did ({ did, ... }). */
146
+ async tick () {
147
+ if (this.busy || this.stopped) return { did: 'busy' }
148
+ this.busy = true
149
+ try { return await this.look() } catch (err) {
150
+ this.log(`couldn't land square ${squareShort(this.square)}'s work by itself (${String(err.message || err).slice(0, 300)}); Quilt tries again in a minute.`)
151
+ return { did: 'failed', error: err.message }
152
+ } finally { this.busy = false }
153
+ }
154
+
155
+ async look () {
156
+ const c = await this.client()
157
+ if (!c) return { did: 'no-client' }
158
+ let sq = await c.square(this.quilt, this.square)
159
+ if (!sq || sq.state !== 'open') return { did: 'closed' }
160
+ // Seam moved the square's head itself (someone settled a conflict there, the person's AI from its own
161
+ // folder): the live document follows first, so a commit of the live work is made on the right head.
162
+ const want = sq.head || sq.base
163
+ if (this.block.moveTo && this.block.head && want && this.block.head !== want) {
164
+ await this.block.moveTo(want, { base: !sq.head }).catch(() => null)
165
+ // Still moving (the relay brings main in this moment): the next look.
166
+ if (this.block.head !== want) { this.soon(15 * 1000); return { did: 'moving' } }
167
+ }
168
+ const work = this.block.status ? this.block.status() : []
169
+ if (!work.length && !sq.head) return { did: 'nothing' }
170
+ const me = await this.me(c)
171
+ const holder = !!me && me === sq.holder
172
+ const quiet = this.now() - this.lastEdit
173
+ const need = this.quietMs + (holder ? 0 : this.holderWaitMs)
174
+ if (quiet < need) { this.soon(need - quiet + 50); return { did: 'waiting', for: need - quiet } }
175
+ // Main first: the square takes main's newer patches (bring-in.js), and then this looks again.
176
+ if (sq.behind_by) {
177
+ await this.catchUp()
178
+ sq = await c.square(this.quilt, this.square)
179
+ if (!sq || sq.state !== 'open') return { did: 'closed' }
180
+ if (sq.behind_by) { this.soon(30 * 1000); return { did: 'behind' } }
181
+ }
182
+ if (sq.conflicted_paths) return this.settle(c, sq)
183
+ // Refused for something only a person gives: not again for a while, unless the square changed.
184
+ const headNow = sq.head || null
185
+ if (this.refusedAt && this.refusedHead === headNow && !work.length && this.now() - this.refusedAt < REFUSED_RETRY_MS) return { did: 'refused-wait' }
186
+ let head = sq.head
187
+ if (work.length) {
188
+ const r = await this.block.commit({ message: landMessage(work.map((w) => w.path)) })
189
+ head = (r && r.square && r.square.head) || (this.block.block && this.block.block.head) || head
190
+ }
191
+ if (!head) return { did: 'nothing' }
192
+ return this.merge(c, sq, head)
193
+ }
194
+
195
+ async merge (c, sq, head) {
196
+ const line = sq.line || this.line || 'main'
197
+ const message = await this.title(c, sq).catch(() => null)
198
+ let r
199
+ try {
200
+ r = await mergeWaiting(c, this.quilt, line, { square: sq.id, expect_head: head, commit_live: false, ...(message ? { message } : {}) }, { wait: this.waitS, say: (t) => this.log(t) })
201
+ } catch (err) {
202
+ // An approval, a red check, a frozen line: a person's to give. Said once; tried again later.
203
+ this.refusedAt = this.now()
204
+ this.refusedHead = head
205
+ this.state = { waiting: String(err.message || err).split('\n')[0].slice(0, 300), at: this.now() }
206
+ this.log(`square ${squareShort(sq.id)}'s held work could not merge onto ${line} yet: ${this.state.waiting}`)
207
+ this.soon(REFUSED_RETRY_MS)
208
+ return { did: 'refused', error: err.message }
209
+ }
210
+ if (r && r.ok && r.merged) {
211
+ this.refusedAt = 0
212
+ const patch = r.merged.patch_no ?? null
213
+ this.state = { landed: { line, patch, at: this.now() } }
214
+ this.log(`landed square ${squareShort(sq.id)}'s held work on ${line}${patch != null ? ` as patch ${patch}` : ''}, with no step of yours.`)
215
+ this.closeAsks(sq, `Settled, and the held work landed on ${line}${patch != null ? ` as patch ${patch}` : ''}.`)
216
+ if (this.keptNote) { const n = this.keptNote; this.keptNote = null; this.notify(keptNotice({ ...n, line, patch })) }
217
+ try { await this.next() } catch (err) { this.log(`the folder's branch did not move to a new square yet (${err.message}); it does on the next look.`) }
218
+ return { did: 'landed', patch, line }
219
+ }
220
+ // A conflict: Seam rebased the square onto the line and kept it there (on_conflict rebase). The folder follows; settled next.
221
+ const to = (r && r.square && r.square.head) || (r && r.head) || null
222
+ if (to && this.block.moveTo) await this.block.moveTo(to).catch(() => {})
223
+ this.soon(1000)
224
+ return { did: 'conflict', terms: ((r && r.terms) || []).map((t) => t.path) }
225
+ }
226
+
227
+ /** The patch's title: the square's own commit messages (Seam would take the square's title, "Uncommitted work from …"). */
228
+ async title (c, sq) {
229
+ if (!c.log) return null
230
+ const log = await c.log(this.quilt, { rev: `sq:${sq.id}`, limit: 50 })
231
+ const own = ((log && log.commits) || []).filter((x) => x && x.square_id === sq.id && x.message).map((x) => String(x.message).split('\n')[0].trim()).filter(Boolean).reverse()
232
+ const uniq = [...new Set(own)]
233
+ if (!uniq.length) return null
234
+ if (uniq.length === 1) return uniq[0].slice(0, 200)
235
+ const all = `${uniq.length} commits: ${uniq.join('; ')}`
236
+ return all.length > 200 ? `${all.slice(0, 199)}…` : all
237
+ }
238
+
239
+ /** The square's conflicted files at its head: [{ path, term }]. */
240
+ async conflicts (c, sq) {
241
+ if (!sq.head) return []
242
+ const d = await c.diff(this.quilt, { from: `c:${sq.base}`, to: `c:${sq.head}`, format: 'names' })
243
+ const paths = ((d && d.files) || []).map((f) => f.path)
244
+ const out = []
245
+ for (let i = 0; i < paths.length; i += 100) {
246
+ const t = await c.tree(this.quilt, `c:${sq.head}`, paths.slice(i, i + 100))
247
+ for (const e of (t && t.entries) || []) if (e.mode === 'conflict') out.push({ path: e.path, term: e.term || '' })
248
+ }
249
+ return out
250
+ }
251
+
252
+ /** Settles the square's conflicts (2a, then 2b, then 2c at the top of this file), then looks again to merge. */
253
+ async settle (c, sq) {
254
+ const line = sq.line || this.line || 'main'
255
+ let head = sq.head
256
+ const resolve = async (path, entry) => {
257
+ const r = await c.resolve(this.quilt, sq.id, { expect_head: head, entries: [{ path, ...entry }] })
258
+ head = (r && r.square && r.square.head) || (r && r.result && r.result.id) || head
259
+ return r
260
+ }
261
+ let left = await this.conflicts(c, sq)
262
+ const settled = []
263
+ // Files the project marks merge=union (.gitattributes) are changelogs too.
264
+ if (!this.marked) this.marked = await unionMarked(c, this.quilt, line)
265
+ for (const x of left) {
266
+ // a. Seam's own answers: its suggestion, then its ladder steps; a changelog keeps both sides.
267
+ const tries = [{ choose: 'suggestion' }, ...RULES.map((rule) => ({ rule })), ...(isChangelog(x.path, this.marked) ? [{ rule: 'union' }] : [])]
268
+ let done = false
269
+ for (const t of tries) {
270
+ try { await resolve(x.path, t); done = true; settled.push({ path: x.path, how: t.choose || `rule:${t.rule}` }); break } catch (err) {
271
+ if (err.status === 409 && err.code !== 'conflict_taken') { head = (await c.square(this.quilt, sq.id)).head } else if (err.status && err.status >= 500) throw err
272
+ }
273
+ }
274
+ if (done) continue
275
+ // a. Work made on an older copy of main's file: its edits put onto main's copy.
276
+ const moved = await this.olderCopy(c, sq, line, x.path).catch(() => null)
277
+ if (moved) {
278
+ await c.upload(this.quilt, [{ kind: 'blob', id: moved.id, bytes: moved.bytes }])
279
+ try { await resolve(x.path, { choose: { blob: moved.id } }); settled.push({ path: x.path, how: 'older-copy' }); continue } catch {}
280
+ }
281
+ }
282
+ if (settled.length) {
283
+ this.log(`settled ${listed(settled.map((s) => s.path))} in square ${squareShort(sq.id)} as Seam offered (${[...new Set(settled.map((s) => s.how))].join(', ')}), with no step of yours.`)
284
+ if (this.block.moveTo && head) await this.block.moveTo(head).catch(() => {})
285
+ sq = await c.square(this.quilt, sq.id)
286
+ left = sq && sq.conflicted_paths ? await this.conflicts(c, sq) : []
287
+ }
288
+ if (!left.length) { this.closeAsks(sq); this.soon(settled.length ? 1000 : 30 * 1000); return { did: 'settled', settled } }
289
+ // b. The person's AI on their cloud machine, AI_ATTEMPTS tries.
290
+ if (this.hasAi() && this.board) {
291
+ const asked = this.ask(sq, left)
292
+ if (asked) return asked
293
+ }
294
+ // c. Main's side stays; the person's version is kept in a square of its own; the held work merges.
295
+ return this.keepAside(c, sq, left)
296
+ }
297
+
298
+ /** 2a's last step: the conflicted file's own side was made on an older copy of main's. { id, bytes } of the settled text, or null. */
299
+ async olderCopy (c, sq, line, path) {
300
+ const r = await c.cat(this.quilt, `c:${sq.head}`, path, { format: 'snapshot' })
301
+ if (!r || !r.conflict || !r.content) return null
302
+ const s = sidesOf(Buffer.from(r.content, 'base64').toString('utf8'))
303
+ if (!s || s.ours == null || s.theirs == null) return null
304
+ const union = isChangelog(path, this.marked)
305
+ const moved = onOlderCopy(s.ours, s.base, s.theirs, await olderTexts(c, this.quilt, path, line), { union })
306
+ if (!moved) return null
307
+ const bytes = Buffer.from(moved.text, 'utf8')
308
+ return { id: blobId(bytes), bytes }
309
+ }
310
+
311
+ /** The board's tasks this lander made for square `sq` (its marker in the title), and those for conflict `term`. */
312
+ asks (sq, term = null) {
313
+ let all = []
314
+ try { all = this.board.list() || [] } catch { return [] }
315
+ const mark = squareShort(sq.id)
316
+ return all.filter((t) => t && typeof t.title === 'string' && t.title.startsWith('Settle ') && t.title.includes(mark) && (!term || t.title.includes(`(conflict ${String(term).slice(0, 8)})`)))
317
+ }
318
+
319
+ /** 2b: a try of the person's AI is waiting, or a new one asked: { did }. Null once AI_ATTEMPTS tries failed. */
320
+ ask (sq, left) {
321
+ const term = left[0].term
322
+ const tries = this.asks(sq, term)
323
+ const open = tries.find((t) => !t.archived && t.column !== 'done' && t.column !== 'qa' && this.now() - (t.ts || 0) < this.aiMs)
324
+ if (open) { this.soon(Math.min(60 * 1000, this.aiMs)); return { did: 'asked', task: open.id, attempt: tries.length } }
325
+ if (tries.length >= AI_ATTEMPTS) return null
326
+ const paths = left.map((x) => x.path)
327
+ let task
328
+ // A board this member can't add to (a viewer's, say): straight to the rule, never a wait.
329
+ try { task = this.board.add({ title: aiTaskTitle({ paths, square: sq.id, term }), assignee: this.person, forAi: true }) } catch (err) { this.log(`couldn't ask ${this.person}'s AI on the board (${err.message})`); return null }
330
+ const id = task && (task.id || (task.task && task.task.id))
331
+ const line = sq.line || this.line || 'main'
332
+ const why = [
333
+ `${this.person}'s held work in square ${squareShort(sq.id)} and a newer patch on ${line} changed the same lines of ${listed(paths)}. This is try ${tries.length + 1} of ${AI_ATTEMPTS}.`,
334
+ `Read both sides with seam_square_status and seam_cat (rev sq:${squareShort(sq.id).slice(3)}, format git shows ours = the held work, theirs = ${line}'s). Keep what each side meant: settle each file with seam_resolve, or write the file without the markers, then seam_commit.`,
335
+ `Then move this task to Done. Quilt merges the square by itself once nothing in it is conflicted. If you can't settle it, say why in a comment and move it to Done: Quilt keeps ${line}'s side and keeps ${this.person}'s version in a square of its own.`
336
+ ].join('\n\n')
337
+ if (id) { try { this.board.comment(id, why) } catch {} }
338
+ this.state = { asked: { paths, attempt: tries.length + 1, at: this.now() } }
339
+ this.log(`asked ${this.person}'s AI to settle ${listed(paths)} in square ${squareShort(sq.id)} (try ${tries.length + 1} of ${AI_ATTEMPTS}).`)
340
+ this.soon(Math.min(60 * 1000, this.aiMs))
341
+ return { did: 'asked', task: id, attempt: tries.length + 1 }
342
+ }
343
+
344
+ /** Tasks asked of the AI for a square whose conflicts are all settled now: to Done, with a word. */
345
+ closeAsks (sq, words = 'Settled: nothing in the square is conflicted now, and Quilt merges it by itself.') {
346
+ if (!this.board || !sq) return
347
+ for (const t of this.asks(sq)) {
348
+ if (t.archived || t.column === 'done') continue
349
+ try { this.board.comment(t.id, words) } catch {}
350
+ try { this.board.move(t.id, 'done') } catch {}
351
+ }
352
+ }
353
+
354
+ /** 2c: main's side stays in each file; the person's version goes into a square of its own; the held work merges after. */
355
+ async keepAside (c, sq, left) {
356
+ const line = sq.line || this.line || 'main'
357
+ const at = this.now()
358
+ const mine = []
359
+ for (const x of left) {
360
+ const r = await c.cat(this.quilt, `c:${sq.head}`, x.path, { format: 'snapshot' })
361
+ const s = r && r.conflict && r.content ? sidesOf(Buffer.from(r.content, 'base64').toString('utf8')) : null
362
+ mine.push({ path: x.path, text: s ? s.ours : null, known: !!s })
363
+ }
364
+ const paths = left.map((x) => x.path)
365
+ const kept = await c.openSquare(this.quilt, { title: keptTitle(paths, at), line })
366
+ const changes = mine.filter((m) => m.known).map((m) => m.text == null ? { path: m.path, op: 'delete' } : { path: m.path, op: 'put', content: Buffer.from(m.text, 'utf8').toString('base64') })
367
+ if (changes.length) await c.commit(this.quilt, kept.id, { expect_head: null, message: `${keptTitle(paths, at)} (from square ${squareShort(sq.id)})`, changes })
368
+ let head = sq.head
369
+ for (const x of left) {
370
+ const r = await c.resolve(this.quilt, sq.id, { expect_head: head, entries: [{ path: x.path, choose: 'theirs' }], remember: false })
371
+ head = (r && r.square && r.square.head) || head
372
+ }
373
+ if (this.block.moveTo && head) await this.block.moveTo(head).catch(() => {})
374
+ this.closeAsks(sq, `Quilt kept ${line}'s side and put ${this.person}'s version in square ${squareShort(kept.id)}.`)
375
+ this.state = { kept: { paths, square: kept.id, title: keptTitle(paths, at), at } }
376
+ this.keptNote = { paths, kept: kept.id }
377
+ this.log(`kept ${line}'s side of ${listed(paths)} in square ${squareShort(sq.id)}; your version is in square ${squareShort(kept.id)} ("${keptTitle(paths, at)}").`)
378
+ // The held work merges now: no wait for quiet, the person did nothing since.
379
+ // The rest of the held work (anything still live, not committed) goes with it.
380
+ const now = await c.square(this.quilt, sq.id)
381
+ let r = null
382
+ if (now && !now.conflicted_paths) {
383
+ const work = this.block.status ? this.block.status() : []
384
+ let to = now.head
385
+ if (work.length) { const w = await this.block.commit({ message: landMessage(work.map((x) => x.path)) }); to = (w && w.square && w.square.head) || to }
386
+ if (to) r = await this.merge(c, now, to)
387
+ }
388
+ // Told once: with the patch when it landed now, else at once (it lands on a later look).
389
+ if (this.keptNote) { const n = this.keptNote; this.keptNote = null; this.notify(keptNotice({ ...n, line })) }
390
+ if (!r) this.soon(1000)
391
+ return { ...(r || { did: 'kept' }), kept: kept.id }
392
+ }
393
+ }
@@ -73,10 +73,18 @@ export function catchUpWords (s) {
73
73
  if (stale.length) out.push(`${files(stale.length)} in this square ${stale.length === 1 ? 'was an older copy' : 'were older copies'} of main's, not anyone's edit: main's ${stale.length === 1 ? 'version stands' : 'versions stand'} (${listed(stale)}).`)
74
74
  }
75
75
  const n = s.conflicted ?? (b && b.conflicts ? b.conflicts.length : 0)
76
+ const l = s.landing || null
76
77
  if (n) {
77
78
  const named = b && b.conflicts && b.conflicts.length ? ` (${listed(b.conflicts)})` : ''
78
- out.push(`${files(n)} ${n === 1 ? 'conflicts' : 'conflict'} with main and ${n === 1 ? 'is' : 'are'} marked in this folder${named}: settle ${n === 1 ? 'it' : 'them'}, commit, and merge again.`)
79
+ // Held work lands by itself (source-live/land.js): the conflict is settled without the person.
80
+ if (s.lands) out.push(`${files(n)} ${n === 1 ? 'conflicts' : 'conflict'} with main and ${n === 1 ? 'is' : 'are'} marked in this folder${named}. Quilt settles ${n === 1 ? 'it' : 'them'} by itself: Seam's own merge if it has one, else your cloud AI if you connected one, else main's version stays and yours is kept in a square of its own. Then your work merges.`)
81
+ else out.push(`${files(n)} ${n === 1 ? 'conflicts' : 'conflict'} with main and ${n === 1 ? 'is' : 'are'} marked in this folder${named}: settle ${n === 1 ? 'it' : 'them'}, commit, and merge again.`)
79
82
  }
83
+ if (l && l.asked) out.push(`Your cloud AI is settling ${listed(l.asked.paths || [])} (try ${l.asked.attempt} of 2); your work merges once it is settled.`)
84
+ if (l && l.kept) out.push(`Main changed the same lines as your ${listed(l.kept.paths || [])}, so main's version stayed there; yours is kept in square sq:${String(l.kept.square || '').slice(-8)} ("${l.kept.title || ''}").`)
85
+ if (l && l.landed) out.push(`Your held work landed on ${l.landed.line || 'main'}${l.landed.patch != null ? ` as patch ${l.landed.patch}` : ''} at ${new Date(l.landed.at).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}, with no step of yours.`)
86
+ if (l && l.waiting) out.push(`Your held work is waiting to merge: ${l.waiting}`)
87
+ if (l && l.held) out.push(l.held.missing ? `Your held work did not land: ${l.held.missing}.` : `Your held work did not land: the fast tests failed${(l.held.failing || []).length ? ` (${listed(l.held.failing)})` : ''}. It lands after your next change once they pass.`)
80
88
  return out
81
89
  }
82
90
 
package/src/ui-server.js CHANGED
@@ -693,10 +693,15 @@ export async function startUi ({ port = 7420, onShutdown, preview = false, repor
693
693
  const audio = typeof b.audio === 'string' ? b.audio : ''
694
694
  const seconds = Number(b.seconds)
695
695
  if (!audio || !(seconds > 0) || seconds > 60) throw httpError(400, 'A clip is up to a minute of audio.')
696
- const out = await asAccount((token) => transcribeVoice({ token, audio, seconds }))
697
- const line = out.text ? s.addVoiceLine(out.text) : null
698
- return { line, used: out.used, cap: out.cap }
696
+ // Clips transcribe side by side, but their lines go in the order they were said: each waits for
697
+ // the clip before it, so a short clip finishing first never jumps ahead of a long one.
698
+ const turn = asAccount((token) => transcribeVoice({ token, audio, seconds }))
699
+ const before = clipOrder.get(s) || Promise.resolve()
700
+ const added = before.then(() => turn).then((out) => ({ line: out.text ? s.addVoiceLine(out.text) : null, used: out.used, cap: out.cap }))
701
+ clipOrder.set(s, added.catch(() => {}))
702
+ return added
699
703
  }
704
+ const clipOrder = new WeakMap() // session -> its last clip's line, once written
700
705
 
701
706
  // An agent's line in the call we're in, as speech from quilt-api (Fluxions): asked once per line,
702
707
  // kept a little while so the window asking again (a reload) costs nothing.