heyquilt 0.3.147 → 0.3.149

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.
@@ -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,99 @@
1
+ // Quilt's side of seam: live squares in a Quilt session. Seam (src/quilts/) never imports this.
2
+ // The gate before held work lands (land.js, Daniel 2026-11-03): once the folder has been quiet, the
3
+ // project's own fast tests run on the person's computer, in a fresh copy of the folder as the square
4
+ // holds it then (not the live folder, where edits arriving meanwhile would change what is tested), and
5
+ // the work lands only when they pass. The command is the project's fast test script (Quilt's AGENTS.md
6
+ // and package.json name it `test:fast`, unit and integration tests with the project's test setup;
7
+ // never the whole suite), or what the person set (setting `landGate`, env QUILT_LAND_GATE: a command,
8
+ // or `off`).
9
+ import fs from 'node:fs'
10
+ import os from 'node:os'
11
+ import path from 'node:path'
12
+ import { spawn } from 'node:child_process'
13
+
14
+ export const FAST_SCRIPT = 'test:fast'
15
+ // A run that takes longer is stopped and counts as failed (a test that never ends would hold the work for good).
16
+ export const GATE_TIMEOUT_MS = Number(process.env.QUILT_LAND_GATE_TIMEOUT_MS) > 0 ? Number(process.env.QUILT_LAND_GATE_TIMEOUT_MS) : 20 * 60 * 1000
17
+ // What a run keeps of its output for the note: its end, where the failing tests are listed.
18
+ const KEEP_OUT = 256 * 1024
19
+ // Copied into the fresh copy as links, never byte for byte: installed packages, and Quilt's own state.
20
+ const LINKED = new Set(['node_modules'])
21
+ const SKIPPED = new Set(['.quilt', '.git'])
22
+
23
+ /**
24
+ * What the gate runs in `dir`: { command } (a shell command), { off: true }, or { missing } (why it
25
+ * can't run: no fast test script, no installed packages). `env.QUILT_LAND_GATE` first, then the
26
+ * setting `landGate`, then the project's `test:fast` script.
27
+ */
28
+ export function gateCommand (dir, { env = process.env, settings = {} } = {}) {
29
+ const set = String(env.QUILT_LAND_GATE ?? settings.landGate ?? '').trim()
30
+ if (set.toLowerCase() === 'off') return { off: true }
31
+ if (set) return { command: set }
32
+ let pkg = null
33
+ try { pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')) } catch {}
34
+ if (!pkg) return { missing: 'this folder has no package.json, so Quilt has no fast tests to run before your work lands (set landGate to a command, or off)' }
35
+ if (!pkg.scripts || !pkg.scripts[FAST_SCRIPT]) return { missing: `package.json has no "${FAST_SCRIPT}" script, so Quilt has no fast tests to run before your work lands (add one, or set landGate to a command, or off)` }
36
+ if (!fs.existsSync(path.join(dir, 'node_modules'))) return { missing: 'this folder has no node_modules (run npm ci), so its tests can\'t run before your work lands' }
37
+ return { command: `npm run ${FAST_SCRIPT}` }
38
+ }
39
+
40
+ /** The failing tests a run names (node --test's "✖ failing tests:" list, else every ✖ line), at most 20. */
41
+ export function failingTests (out) {
42
+ const lines = String(out || '').split('\n')
43
+ const at = lines.findIndex((l) => /^✖ failing tests:/.test(l.trim()))
44
+ const pick = (from) => [...new Set(lines.slice(from).map((l) => l.trim()).filter((l) => /^✖ /.test(l) && !/^✖ failing tests:/.test(l)).map((l) => l.slice(2).replace(/\s*\(\d+(\.\d+)?m?s\)$/, '').trim()))]
45
+ return (at >= 0 ? pick(at + 1) : pick(0)).slice(0, 20)
46
+ }
47
+
48
+ /** A fresh copy of `dir` (copy-on-write where the disk can), its node_modules linked: the folder as it is now. */
49
+ export function freshCopy (dir, into = fs.mkdtempSync(path.join(os.tmpdir(), 'quilt-land-gate-'))) {
50
+ for (const name of fs.readdirSync(dir)) {
51
+ if (SKIPPED.has(name)) continue
52
+ const from = path.join(dir, name)
53
+ const to = path.join(into, name)
54
+ if (LINKED.has(name)) { fs.symlinkSync(from, to, 'dir'); continue }
55
+ const nested = []
56
+ fs.cpSync(from, to, { recursive: true, verbatimSymlinks: true, mode: fs.constants.COPYFILE_FICLONE, filter: (src) => { if (path.basename(src) !== 'node_modules' || src === from) return true; nested.push(src); return false } })
57
+ // A package's own node_modules further down (web/node_modules): linked too.
58
+ for (const src of nested) { const at = path.join(into, path.relative(dir, src)); fs.mkdirSync(path.dirname(at), { recursive: true }); fs.symlinkSync(src, at, 'dir') }
59
+ }
60
+ return into
61
+ }
62
+
63
+ /**
64
+ * Runs `command` in a fresh copy of `dir`. `signal` stops it (an edit arrived: what it tests is old).
65
+ * Answers { ok, code, ms, failing, out } or { stopped: true }. The copy is removed after.
66
+ */
67
+ export async function runGate ({ dir, command, signal = null, env = process.env, timeoutMs = GATE_TIMEOUT_MS }) {
68
+ const t0 = Date.now()
69
+ const copy = freshCopy(dir)
70
+ // Never Quilt's own test runner's context: a gate started from inside a test would run as its child.
71
+ const { NODE_TEST_CONTEXT, ...rest } = env
72
+ try {
73
+ return await new Promise((resolve) => {
74
+ let out = ''
75
+ const child = spawn(command, { cwd: copy, shell: true, env: { ...rest, CI: rest.CI || '1' }, stdio: ['ignore', 'pipe', 'pipe'], detached: process.platform !== 'win32', windowsHide: true })
76
+ const take = (d) => { out += d; if (out.length > KEEP_OUT * 2) out = out.slice(-KEEP_OUT) }
77
+ child.stdout.on('data', take)
78
+ child.stderr.on('data', take)
79
+ let stopped = false
80
+ let timedOut = false
81
+ const kill = () => { try { if (process.platform !== 'win32') process.kill(-child.pid, 'SIGTERM'); else child.kill() } catch {} }
82
+ const stop = () => { stopped = true; kill() }
83
+ const timer = setTimeout(() => { timedOut = true; kill() }, timeoutMs)
84
+ timer.unref?.()
85
+ if (signal) { if (signal.aborted) stop(); else signal.addEventListener('abort', stop, { once: true }) }
86
+ child.on('error', (err) => resolve({ ok: false, code: -1, ms: Date.now() - t0, failing: [], out: String(err.message) }))
87
+ child.on('close', (code) => {
88
+ clearTimeout(timer)
89
+ if (signal) signal.removeEventListener('abort', stop)
90
+ if (stopped) return resolve({ stopped: true, ms: Date.now() - t0 })
91
+ if (timedOut) return resolve({ ok: false, code: null, timedOut: true, ms: Date.now() - t0, failing: failingTests(out.slice(-KEEP_OUT)), out: out.slice(-KEEP_OUT) })
92
+ out = out.slice(-KEEP_OUT)
93
+ resolve({ ok: code === 0, code, ms: Date.now() - t0, failing: code === 0 ? [] : failingTests(out), out })
94
+ })
95
+ })
96
+ } finally {
97
+ fs.rm(copy, { recursive: true, force: true }, () => {})
98
+ }
99
+ }