okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-life (final 576d06553) into f-0213-int66331f9bc

main
24.1 KiB507 linesraw
1/**
2 * Time-skip, from the App Host.
3 *
4 * Strata Control owns the job: checkpointing, isolated candidates, the checks and the decision all
5 * live in `strata_control/time_skip.py` and are driven through the `strata timeskip` CLI. This
6 * module is only the bridge — it starts that command, streams its output, and reads back the durable
7 * `run.json` the job writes.
8 *
9 * Two rules it must not break:
10 *
11 *   1. **It never decides anything.** Whether a candidate was kept is the job's answer, read from
12 *      disk. This module does not compute a status, a score or a progress fraction.
13 *   2. **It never reports progress it does not have.** The job's phases are coarse and a check can
14 *      take minutes with nothing to say, so the stream carries what the command actually printed and
15 *      the UI shows a phase, not a percentage.
16 *
17 * A run is a job, not a request: it outlives the HTTP call that started it. The endpoint returns the
18 * run id immediately and the client follows it with `/api/timeskip/status`.
19 */
20import { spawn } from 'node:child_process';
21import { endTreeThenKill, ownGroup } from './process-tree.mjs';
22import { existsSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
23import { isAbsolute, join, relative, resolve } from 'node:path';
24import { timeSkipDir } from './platform-paths.mjs';
25
26/** Where runs are recorded. Mirrors the CLI's own default resolution. */
27function stateDir(env = process.env) {
28  return timeSkipDir(env);
29}
30
31function readRun(root, id) {
32  const file = join(root, id, 'run.json');
33  if (!existsSync(file)) return null;
34  try {
35    return JSON.parse(readFileSync(file, 'utf8'));
36  } catch {
37    // A partially written record is not a run: the job writes atomically, so a parse failure means
38    // something else touched the file. Report it as missing rather than as an empty run.
39    return null;
40  }
41}
42
43function listRuns(root) {
44  if (!existsSync(root)) return [];
45  const out = [];
46  for (const entry of readdirSync(root, { withFileTypes: true })) {
47    if (!entry.isDirectory()) continue;
48    const run = readRun(root, entry.name);
49    if (run) out.push(summarise(run));
50  }
51  return out.sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0));
52}
53
54/**
55 * The projection the UI consumes.
56 *
57 * Everything here is copied from the job's own record. `decision` and `needsUserReview` are the
58 * job's answers; `phase` is its current state. There is deliberately no derived `percent`.
59 */
60function summarise(run) {
61  const attempts = run.attempts ?? [];
62  const checkpoints = run.checkpoints ?? [];
63  return {
64    id: run.id,
65    phase: run.state,
66    workspace: run.workspace,
67    prompt: run.prompt,
68    startedAt: run.started_at ?? null,
69    finishedAt: run.finished_at ?? null,
70    attempts: attempts.map((a) => ({
71      index: a.index,
72      decision: a.decision ?? null,
73      reason: a.reason ?? '',
74      checks: (a.checks ?? []).map((c) => ({ id: c.id, outcome: c.outcome, kind: c.kind })),
75    })),
76    checkpoints: checkpoints.map((c) => ({
77      id: c.id,
78      label: c.label,
79      digest: c.digest,
80      checks: (c.checks ?? []).map((x) => ({ id: x.id, outcome: x.outcome, kind: x.kind })),
81    })),
82    selectedCheckpoint: run.selected_checkpoint ?? null,
83    decision: run.decision ?? null,
84    // `unknown` checks must survive to the UI as unknown; a caller that renders this as a failure
85    // or as a pass is the bug this field exists to prevent.
86    needsUserReview: Boolean(run.decision?.needs_user_review),
87    error: run.error ?? null,
88  };
89}
90
91const TERMINAL = new Set(['completed', 'cancelled', 'failed', 'interrupted']);
92const SKIP_DIRS = new Set(['.git', '.strata', '__pycache__', 'node_modules']);
93const MAX_TEXT_BYTES = 200_000;
94const MAX_LISTED = 60;
95const MAX_WITH_TEXT = 12;
96
97/** Every file under a folder, as relative forward-slash paths. */
98function walkFiles(root) {
99  const out = [];
100  if (!root || !existsSync(root)) return out;
101  const walk = dir => {
102    for (const entry of readdirSync(dir, { withFileTypes: true })) {
103      if (out.length > 5000) return;
104      const full = join(dir, entry.name);
105      if (entry.isDirectory()) { if (!SKIP_DIRS.has(entry.name)) walk(full); }
106      else if (entry.isFile()) out.push(relative(root, full).split('\\').join('/'));
107    }
108  };
109  walk(root);
110  return out.sort();
111}
112
113function readText(path) {
114  try {
115    if (statSync(path).size > MAX_TEXT_BYTES) return { big: true };
116    const buffer = readFileSync(path);
117    if (buffer.subarray(0, 4096).includes(0)) return { binary: true };
118    return { text: buffer.toString('utf8') };
119  } catch { return { missing: true }; }
120}
121
122/** Whether two files hold the same bytes (a big file that did not change must not be listed as changed). Files over 64 MB are treated as changed. */
123function sameBytes(a, b) {
124  try {
125    const sa = statSync(a), sb = statSync(b);
126    if (sa.size !== sb.size) return false;
127    if (sa.size > 64 * 1024 * 1024) return false;
128    return readFileSync(a).equals(readFileSync(b));
129  } catch { return false; }
130}
131
132/** What the assistant is told for one revision attempt. It works on a copy, so it is told to stay in it and to say what it did. */
133export function timeskipRevisionMessage(request) {
134  return [
135    'You are improving a copy of the user\'s work. The current folder is that copy: the original is safe and you cannot see it.',
136    'Rules:',
137    '1. Work only inside the current folder. Never read or write outside it.',
138    '2. Make the change the user asked for by creating or editing files here. If the folder is empty, create the file(s) the request needs.',
139    '3. Do not delete the user\'s files unless the request says to.',
140    '4. Do not run long programs or start servers.',
141    '5. When you are done, answer in one or two plain sentences: what you changed.',
142    '',
143    'The request:',
144    String(request).trim(),
145  ].join('\n');
146}
147
148/** End a process and everything it started (the job, the Python it runs, the revision command and its Node). */
149function killTree(child) {
150  endTreeThenKill(child);          // Windows: taskkill /T. Linux and macOS: the job leads its own process group (startDetached), so the group is ended (#4529 #4570)
151}
152
153/** How big a folder is, stopping early once it is clearly too big to copy for a trial. */
154export function measureFolder(root, { maxFiles = 3000, maxBytes = 300 * 1024 * 1024 } = {}) {
155  let files = 0, bytes = 0, tooBig = false;
156  const walk = dir => {
157    if (tooBig) return;
158    let entries;
159    try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
160    for (const entry of entries) {
161      const full = join(dir, entry.name);
162      if (entry.isDirectory()) { if (!SKIP_DIRS.has(entry.name)) walk(full); }
163      else if (entry.isFile()) {
164        files += 1;
165        try { bytes += statSync(full).size; } catch { /* ignore */ }
166        if (files > maxFiles || bytes > maxBytes) { tooBig = true; return; }
167      }
168      if (tooBig) return;
169    }
170  };
171  walk(root);
172  return { files, bytes, tooBig };
173}
174
175/**
176 * What a run changed, file by file: the saved original against the revision, for the Compare view.
177 * Reads the folders the job itself kept; it decides nothing.
178 */
179/** Pictures the Compare view shows side by side (read as bytes through /api/timeskip/file, never as text). */
180export const IMAGE_TYPES = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml', bmp: 'image/bmp' };
181const MAX_IMAGE_BYTES = 12 * 1024 * 1024;
182export const imageTypeOf = path => IMAGE_TYPES[String(path).split('.').pop().toLowerCase()] ?? null;
183
184/** The two folders a run compares: the saved original and the revision (or the last attempt when the checks kept nothing). */
185export function runRoots(record) {
186  const baseline = (record.checkpoints ?? []).find(c => c.label === 'baseline');
187  const selected = (record.checkpoints ?? []).find(c => c.id === record.selected_checkpoint);
188  const attempts = record.attempts ?? [];
189  const last = attempts[attempts.length - 1] ?? null;
190  const useAttempt = !selected || selected.id === baseline?.id;
191  return { baseRoot: baseline?.path ?? null, updatedRoot: (useAttempt ? last?.path : selected?.path) ?? null, useAttempt, last };
192}
193
194/** The absolute path of one picture of a run, for one side, or null: not a picture, not inside the run's folder, missing or too big. */
195export function runImagePath(record, relPath, version) {
196  if (!imageTypeOf(relPath)) return null;
197  const { baseRoot, updatedRoot } = runRoots(record);
198  const root = version === 'original' ? baseRoot : version === 'updated' ? updatedRoot : null;
199  if (!root) return null;
200  const full = resolve(root, ...String(relPath).split('/'));
201  const inside = relative(resolve(root), full);
202  if (!inside || inside.startsWith('..') || isAbsolute(inside)) return null;
203  try { const st = statSync(full); return st.isFile() && st.size <= MAX_IMAGE_BYTES ? full : null; } catch { return null; }
204}
205
206/**
207 * Files that are the program's own housekeeping, not the person's work: a browser profile, a cache folder, a tool's hidden folder. They are
208 * still listed when they changed (never hidden from the person), but last, and without their contents, so the comparison opens on the work
209 * that was asked for and not on a cache file.
210 */
211const NOISE_DIR = /^(?:\.[^.]|__pycache__$|node_modules$|cache$|gpucache$|code cache$|crashpad$|shadercache$)/i;
212export const isNoisePath = path => String(path).split('/').slice(0, -1).some(seg => NOISE_DIR.test(seg));
213const NOISE_LISTED = 5;
214
215/** Order in the Compare view: the page or document that was made first, other readable work next, pictures, then everything else, then housekeeping. */
216function rankOf(entry) {
217  if (entry.noise) return 4;
218  const ext = String(entry.path).split('.').pop().toLowerCase();
219  if (entry.unreadable) return 3;
220  if (ext === 'html' || ext === 'htm') return 0;
221  if (entry.image) return 2;
222  return 1;
223}
224
225export function diffRun(record) {
226  // A kept checkpoint is the revision; when nothing was kept (the checks could not decide) the person looks at the last attempt.
227  const { baseRoot, updatedRoot, useAttempt, last } = runRoots(record);
228  if (!baseRoot || !updatedRoot) return { files: [], applyAttempt: null, more: 0 };
229  const paths = [...new Set([...walkFiles(baseRoot), ...walkFiles(updatedRoot)])].sort();
230  const found = [];
231  for (const path of paths) {
232    const noise = isNoisePath(path);
233    // Housekeeping is compared as bytes only (never read as text): a browser profile can hold thousands of files.
234    if (noise) {
235      const A = join(baseRoot, path), B = join(updatedRoot, path);
236      const inA = existsSync(A), inB = existsSync(B);
237      let differs = !inA || !inB;
238      if (!differs) { try { differs = statSync(A).size !== statSync(B).size || !readFileSync(A).equals(readFileSync(B)); } catch { differs = true; } }
239      if (differs) found.push({ path, status: !inA ? 'added' : !inB ? 'removed' : 'changed', unreadable: true, noise: true });
240      continue;
241    }
242    const a = readText(join(baseRoot, path)), b = readText(join(updatedRoot, path));
243    const status = a.missing ? 'added' : b.missing ? 'removed' : null;
244    const same = !status && a.text !== undefined && a.text === b.text;
245    if (same) continue;
246    // A file too big to read as text is the same file when its bytes are the same: it must not show up as a change.
247    if (!status && (a.big || b.big) && sameBytes(join(baseRoot, path), join(updatedRoot, path))) continue;
248    if (imageTypeOf(path)) {
249      // A picture is compared as bytes and shown from the file itself, never read as text.
250      let differs = true;
251      try { differs = a.missing || b.missing || !readFileSync(join(baseRoot, path)).equals(readFileSync(join(updatedRoot, path))); } catch { /* treat as changed */ }
252      if (!differs) continue;
253      found.push({ path, status: status ?? 'changed', image: true });
254      continue;
255    }
256    if (!status && !a.text && !b.text && !a.big && !b.big) {
257      // Both binary: compare sizes only.
258      try { if (statSync(join(baseRoot, path)).size === statSync(join(updatedRoot, path)).size && readFileSync(join(baseRoot, path)).equals(readFileSync(join(updatedRoot, path)))) continue; } catch { /* treat as changed */ }
259    }
260    const entry = { path, status: status ?? 'changed' };
261    const textual = (a.text !== undefined || a.missing) && (b.text !== undefined || b.missing);
262    if (textual) entry._text = { original: a.text ?? '', updated: b.text ?? '' };
263    else entry.unreadable = true;
264    found.push(entry);
265  }
266  // Only housekeeping changed (a cache, a browser profile): the assistant changed nothing the person asked about.
267  if (found.length && found.every(e => e.noise)) return { files: [], applyAttempt: useAttempt ? (last?.index ?? null) : null, more: 0, housekeeping: found.length };
268  found.sort((x, y) => rankOf(x) - rankOf(y) || (x.path < y.path ? -1 : x.path > y.path ? 1 : 0));
269  const files = [];
270  let withText = 0, more = 0, noiseListed = 0;
271  for (const entry of found) {
272    if (entry.noise && noiseListed >= NOISE_LISTED) { more += 1; continue; }
273    if (files.length >= MAX_LISTED) { more += 1; continue; }
274    if (entry.noise) noiseListed += 1;
275    const { _text, ...rest } = entry;
276    if (_text) { if (withText < MAX_WITH_TEXT) { rest.original = _text.original; rest.updated = _text.updated; withText += 1; } else rest.unreadable = true; }
277    files.push(rest);
278  }
279  return { files, applyAttempt: useAttempt ? (last?.index ?? null) : null, more };
280}
281
282/**
283 * Run one `strata timeskip …` command and collect its result.
284 *
285 * The command is given a bounded time. A Time-skip run can legitimately take many minutes (each
286 * attempt is an agent turn), so the default bound is generous, and exceeding it is reported as a
287 * timeout rather than as success.
288 */
289export function createTimeSkip({ repoRoot, python, pythonArgs = [], timeoutMs = 30 * 60 * 1000, env = process.env } = {}) {
290  const cli = join(repoRoot, 'strata.py');
291
292  /** Runs this host started and is still driving. A run that is not terminal and not in here died with its host. */
293  const live = new Map();
294  /** id -> promise that settles when the job's process has ended. */
295  const endedOf = new Map();
296  /** Runs the person stopped: their folders are deleted, so the answer to "what became of it" is kept here (until the host restarts). */
297  const stopped = new Set();
298  const withLive = summary => (summary && !TERMINAL.has(summary.phase) && !live.has(summary.id) ? { ...summary, phase: 'interrupted' } : summary);
299
300  function runCli(args, { signal } = {}) {
301    return new Promise((resolve) => {
302      const root = stateDir(env);
303      const child = spawn(python, [...pythonArgs, cli, ...args, '--output', 'json'], {
304        cwd: repoRoot,
305        windowsHide: true,
306        env: { ...env, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8', STRATA_TIMESKIP_DIR: root },
307        stdio: ['ignore', 'pipe', 'pipe'],
308      });
309      let stdout = '';
310      let stderr = '';
311      let timedOut = false;
312      const timer = setTimeout(() => {
313        timedOut = true;
314        try {
315          child.kill('SIGTERM');
316        } catch {
317          /* already gone */
318        }
319      }, timeoutMs);
320      const onAbort = () => {
321        try {
322          child.kill('SIGTERM');
323        } catch {
324          /* already gone */
325        }
326      };
327      signal?.addEventListener('abort', onAbort, { once: true });
328
329      child.stdout.on('data', (b) => {
330        stdout += b.toString();
331      });
332      child.stderr.on('data', (b) => {
333        stderr += b.toString();
334      });
335      child.on('error', (e) => {
336        clearTimeout(timer);
337        signal?.removeEventListener('abort', onAbort);
338        resolve({ ok: false, code: null, error: `could not start the Time-skip command: ${e.message}` });
339      });
340      child.on('close', (code) => {
341        clearTimeout(timer);
342        signal?.removeEventListener('abort', onAbort);
343        if (timedOut) {
344          resolve({ ok: false, code, error: `the Time-skip command did not finish within ${Math.round(timeoutMs / 1000)}s` });
345          return;
346        }
347        // The CLI's machine envelope is one JSON object on stdout; anything else is a defect worth
348        // surfacing rather than guessing at.
349        let parsed = null;
350        try {
351          parsed = JSON.parse(stdout.trim().split('\n').filter(Boolean).pop() ?? '');
352        } catch {
353          parsed = null;
354        }
355        if (!parsed) {
356          resolve({ ok: false, code, error: stderr.trim() || stdout.trim() || `the command exited ${code} with no JSON` });
357          return;
358        }
359        resolve({ ok: Boolean(parsed.ok), code, envelope: parsed, stderr: stderr.trim() });
360      });
361    });
362  }
363
364  return {
365    stateDir: () => stateDir(env),
366
367    /** Every recorded run, newest first. */
368    list: () => listRuns(stateDir(env)).map(withLive),
369
370    /** One run's durable record, or null. */
371    status: (id) => {
372      if (!/^[0-9a-f]{8,64}$/.test(String(id ?? ''))) return null;
373      if (stopped.has(id)) return { id, phase: 'cancelled', workspace: null, prompt: null, startedAt: null, finishedAt: null, attempts: [], checkpoints: [], selectedCheckpoint: null, decision: null, needsUserReview: false, error: null };
374      const run = readRun(stateDir(env), id);
375      return run ? withLive(summarise(run)) : null;
376    },
377
378    /** The changed files of a run (saved original against the revision), for the Compare view. */
379    files: id => {
380      if (!/^[0-9a-f]{8,64}$/.test(String(id ?? ''))) return null;
381      const run = readRun(stateDir(env), id);
382      return run ? diffRun(run) : null;
383    },
384
385    /** One picture of a run (original or updated), for the Compare view: { path, type } or null. */
386    image: (id, relPath, version) => {
387      if (!/^[0-9a-f]{8,64}$/.test(String(id ?? ''))) return null;
388      const run = readRun(stateDir(env), id);
389      const full = run ? runImagePath(run, relPath, version) : null;
390      return full ? { path: full, type: imageTypeOf(relPath) } : null;
391    },
392
393    /** Settles when the job's process has ended (immediately for a run this host is not driving). */
394    whenEnded: id => endedOf.get(id) ?? Promise.resolve(),
395
396    /**
397     * Stop a run and clean up after it: the job and everything it started are ended (the whole process tree), and the run's folder, which
398     * holds the copies of the person's files, is deleted. The person's own files were never touched by the run. Afterwards the run reads as
399     * cancelled. Returns false for an id that is not a run.
400     */
401    async stop(id) {
402      if (!/^[0-9a-f]{8,64}$/.test(String(id ?? ''))) return false;
403      const folder = join(stateDir(env), id);
404      if (!live.has(id) && !existsSync(folder) && !stopped.has(id)) return false;
405      stopped.add(id);
406      const child = live.get(id);
407      if (child) killTree(child);
408      await Promise.race([endedOf.get(id) ?? Promise.resolve(), new Promise(r => setTimeout(r, 8000))]);
409      for (let i = 0; i < 6 && existsSync(folder); i++) {
410        try { rmSync(folder, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); } catch { await new Promise(r => setTimeout(r, 400)); }
411      }
412      return true;
413    },
414
415
416    /**
417     * Start a run. Returns as soon as the job has been *accepted*; the caller follows the run id.
418     *
419     * Note the deliberate absence of a `reviseCommand` argument: a revision is performed by the
420     * Harness through `integrations/harness/revise_once.py`, and letting an HTTP caller supply an
421     * arbitrary shell command would hand a remote caller command execution. The path is configured,
422     * not requested.
423     */
424    async start({ workspace, prompt, attempts = 2, reviseCommand = null, signal } = {}) {
425      if (!workspace || typeof workspace !== 'string') {
426        return { ok: false, code: 2, error: 'workspace is required' };
427      }
428      if (!prompt || typeof prompt !== 'string') {
429        return { ok: false, code: 2, error: 'prompt is required' };
430      }
431      const args = ['timeskip', 'run', '--workspace', workspace, '--prompt', prompt,
432        '--attempts', String(Math.max(0, Math.min(10, Number(attempts) || 0)))];
433      if (reviseCommand) args.push('--revise-command', reviseCommand);
434      const result = await runCli(args, { signal });
435      if (!result.ok) return { ok: false, code: result.code ?? 6, error: result.error ?? result.stderr };
436      const run = result.envelope?.run;
437      return run ? { ok: true, run: summarise(run) } : { ok: false, code: 6, error: 'the job reported success but wrote no run record' };
438    },
439
440    /**
441     * Start a run and return as soon as its record exists; the job goes on without the caller waiting.
442     * The caller follows the run id with `status`. A command that ends before any record appears is an error, in the command's words.
443     */
444    async startDetached({ workspace, prompt, attempts = 1, reviseCommand = null, extraEnv = {} } = {}) {
445      if (!workspace || typeof workspace !== 'string') return { ok: false, code: 2, error: 'workspace is required' };
446      if (!prompt || typeof prompt !== 'string') return { ok: false, code: 2, error: 'prompt is required' };
447      const root = stateDir(env);
448      const before = new Set(existsSync(root) ? readdirSync(root) : []);
449      const args = ['timeskip', 'run', '--workspace', workspace, '--prompt', prompt,
450        '--attempts', String(Math.max(0, Math.min(10, Number(attempts) || 0))), '--output', 'json'];
451      if (reviseCommand) args.push('--revise-command', reviseCommand);
452      const child = spawn(python, [...pythonArgs, cli, ...args], {
453        cwd: repoRoot, windowsHide: true, detached: ownGroup(), env: { ...env, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8', ...extraEnv, STRATA_TIMESKIP_DIR: root }, stdio: ['ignore', 'pipe', 'pipe'],
454      });
455      let out = '', err = '', closed = null;
456      child.stdout.on('data', b => { out += b.toString(); });
457      child.stderr.on('data', b => { err += b.toString(); });
458      const ended = new Promise(resolve => {
459        child.on('error', e => { closed = { code: null, error: `could not start the Time-skip command: ${e.message}` }; resolve(); });
460        child.on('close', code => { closed = { code }; resolve(); });
461      });
462      const deadline = Date.now() + 20_000;
463      let id = null;
464      while (!id && Date.now() < deadline) {
465        if (existsSync(root)) {
466          for (const name of readdirSync(root)) {
467            if (before.has(name)) continue;
468            const run = readRun(root, name);
469            if (run && run.prompt === prompt) { id = name; break; }
470          }
471        }
472        if (id || closed) break;
473        await new Promise(r => setTimeout(r, 100));
474      }
475      if (!id) {
476        if (!closed) { try { child.kill('SIGTERM'); } catch { /* gone */ } return { ok: false, code: 6, error: 'the Time-skip job did not start in time' }; }
477        let message = closed.error ?? '';
478        try { const parsed = JSON.parse(out.trim().split('\n').filter(Boolean).pop() ?? ''); message = message || parsed?.error?.message || parsed?.error || ''; } catch { /* not JSON */ }
479        return { ok: false, code: closed.code ?? 6, error: String(message || err.trim() || out.trim() || 'the Time-skip command ended without a run').slice(0, 600) };
480      }
481      live.set(id, child);
482      endedOf.set(id, ended);
483      void ended.then(() => live.delete(id));
484      return { ok: true, run: withLive(summarise(readRun(root, id))) };
485    },
486
487    /** Apply the retained result, or preview it. Refuses when the destination changed. */
488    async apply({ id, workspace = null, dryRun = false, restore = false, attempt = null, signal } = {}) {
489      if (!/^[0-9a-f]{8,64}$/.test(String(id ?? ''))) {
490        return { ok: false, code: 2, error: 'a run id is required' };
491      }
492      const args = ['timeskip', 'apply', id];
493      if (workspace) args.push('--workspace', workspace);
494      if (dryRun) args.push('--dry-run');
495      if (restore) args.push('--restore');
496      if (attempt !== null && attempt !== undefined) args.push('--attempt', String(Math.max(1, Math.floor(Number(attempt)) || 1)));
497      const result = await runCli(args, { signal });
498      if (!result.ok) {
499        // Exit 6 is the documented "refused / uncertain" code, which is how a concurrent user edit
500        // arrives here. It is a normal outcome, not an internal error.
501        return { ok: false, code: result.code ?? 6, conflict: result.code === 6,
502                 error: result.error ?? result.stderr };
503      }
504      return { ok: true, apply: result.envelope?.apply ?? result.envelope?.restore ?? null };
505    },
506  };
507}