@sema-agent/core 7.68.0 → 7.68.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/dist/core/checkpoint-requirements.d.ts +20 -1
  3. package/dist/core/checkpoint-requirements.js +11 -5
  4. package/dist/core/engine-capabilities.d.ts +8 -1
  5. package/dist/core/engine-capabilities.js +1 -1
  6. package/dist/core/file-history-store.d.ts +229 -44
  7. package/dist/core/file-history-store.js +288 -93
  8. package/dist/core/runner/contracts.d.ts +1 -1
  9. package/dist/core/runner/file-history-request.d.ts +10 -2
  10. package/dist/core/runner/file-history-request.js +17 -1
  11. package/dist/core/runner/file-history-restore.d.ts +11 -4
  12. package/dist/core/runner/file-history-restore.js +19 -5
  13. package/dist/core/runner/prepare-file-history.js +3 -3
  14. package/dist/core/runner/rewind-files.js +11 -8
  15. package/dist/core/store-contracts/file-history-store-contract.js +210 -13
  16. package/dist/core/task-spec-members.d.ts +2 -1
  17. package/dist/core/task-spec-members.js +1 -1
  18. package/dist/core/task-spec.d.ts +7 -0
  19. package/dist/core/tool-roster.d.ts +12 -0
  20. package/dist/core/tool-roster.js +12 -1
  21. package/dist/index.d.ts +2 -0
  22. package/dist/index.js +1 -0
  23. package/dist/stores/file/file-history-store.d.ts +5 -3
  24. package/dist/stores/file/file-history-store.js +42 -60
  25. package/package.json +2 -2
  26. package/test/export-surface.snapshot.json +17 -1
  27. package/wire-changes/core-stores-sql@7.68.1.json +39 -0
  28. package/wire-changes/core-stores-sql@7.68.2.json +39 -0
  29. package/wire-changes/core@7.68.1.json +95 -0
  30. package/wire-changes/core@7.68.2.json +612 -0
  31. package/wire-changes/mods-kernel@7.68.1.json +39 -0
  32. package/wire-changes/mods-kernel@7.68.2.json +39 -0
  33. package/wire-changes/primitives@7.68.1.json +39 -0
  34. package/wire-changes/primitives@7.68.2.json +39 -0
  35. package/wire-changes/wiki-gate@7.68.1.json +39 -0
  36. package/wire-changes/wiki-gate@7.68.2.json +39 -0
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readMember, thrownText } from "./thrown-value.js";
3
3
  import { readMemberGroup } from "./member-group.js";
4
- import { isAbsoluteForFamily, isWinFormPath, pathFamilyOf, relativeInEveryFamily } from "../tools/fs/safety.js";
4
+ import { isAbsoluteForFamily, isWinFormPath, pathFamilyOf, relativeInEveryFamily, startsWithDriveLetter } from "../tools/fs/safety.js";
5
5
  import { fileHistoryBoundariesToKeep, resolveFileHistoryRetention } from "./file-history-retention.js";
6
6
  import { optionKeys, receiveOptions } from "./own-property-receipt.js";
7
7
  import { readUnreadableDeleteId } from "./session.js";
@@ -31,12 +31,23 @@ function parentDirOf(absPath) {
31
31
  const norm = win ? normSlash(absPath) : absPath;
32
32
  const cut = norm.replace(/\/+$/, "");
33
33
  const i = cut.lastIndexOf("/");
34
- if (i <= 0)
34
+ const driveOnly = (p) => p.length === 2 && startsWithDriveLetter(p);
35
+ if (i < 0 || cut === "" || driveOnly(cut))
35
36
  return undefined;
36
- const parent = cut.slice(0, i);
37
+ const parent = i === 0 ? "/" : driveOnly(cut.slice(0, i)) ? `${cut.slice(0, i)}/` : cut.slice(0, i);
37
38
  return win ? parent.replace(/\//g, "\\") : parent;
38
39
  }
39
- export const FILE_HISTORY_REFUSAL_CLASSES = Object.freeze(["link_safety", "base_unavailable", "key_unresolvable"]);
40
+ function lastSegmentOf(absPath) {
41
+ const cut = (isWinFormPath(absPath) ? normSlash(absPath) : absPath).replace(/\/+$/, "");
42
+ return cut.slice(cut.lastIndexOf("/") + 1);
43
+ }
44
+ export const FILE_HISTORY_REFUSAL_CLASSES = Object.freeze(["link_safety", "base_unavailable", "key_unresolvable", "recorded_elsewhere", "place_unrecorded"]);
45
+ export function fileHistoryEntryTravels(key) {
46
+ return key.kind === "root-relative";
47
+ }
48
+ export function fileHistoryParentIdentTravels(parentIdent) {
49
+ return !isPlace(parentIdent);
50
+ }
40
51
  export function trackKeyFamilyOf(root) {
41
52
  return isWinFormPath(root) ? "win" : "posix";
42
53
  }
@@ -177,6 +188,10 @@ function judgeFileHistoryEnvelope(data) {
177
188
  return bad(`unsupported file-history envelope format ${JSON.stringify(String(data.formatVersion))} — this engine reads "file-history/1" and refuses rather than reinterpreting a foreign epoch`);
178
189
  if (!Array.isArray(data.tracked) || !Array.isArray(data.boundaries))
179
190
  return bad("file-history envelope is missing its tracked/boundaries arrays");
191
+ const omitted = data.absoluteEntriesOmitted;
192
+ if (omitted !== undefined && (typeof omitted !== "number" || !Number.isSafeInteger(omitted) || omitted < 0)) {
193
+ return bad(`file-history envelope's absoluteEntriesOmitted is ${JSON.stringify(omitted)} — a count of files left out is a non-negative integer; refused, never coerced`);
194
+ }
180
195
  const known = new Set();
181
196
  for (const t of data.tracked) {
182
197
  if (typeof t?.relOrAbsPath !== "string" || t.relOrAbsPath === "")
@@ -195,7 +210,11 @@ function judgeFileHistoryEnvelope(data) {
195
210
  return bad(`tracked row ${t.relOrAbsPath} is missing its base-availability state or version chain`);
196
211
  for (const v of t.versions) {
197
212
  void v?.backupTime;
198
- void v?.parentIdent;
213
+ if (v?.parentIdent !== undefined && typeof v.parentIdent !== "string")
214
+ return bad(`tracked row ${t.relOrAbsPath} carries a non-string parentIdent — refused, never coerced`);
215
+ if (v?.parentIdent !== undefined && !fileHistoryParentIdentTravels(v.parentIdent)) {
216
+ return bad(`tracked row ${t.relOrAbsPath} carries an ABSOLUTE place (parentIdent) on version ${String(v.version)} — an imported graph may not carry paths outside the importing root (a later boundary would re-read the tracked file there); a version's place is recorded where it is captured, never imported`);
217
+ }
199
218
  if (typeof v?.version !== "number" || !Number.isInteger(v.version) || v.version < 1)
200
219
  return bad(`tracked row ${t.relOrAbsPath} carries a non-integer version number`);
201
220
  if (v.blobHash !== null && (typeof v.blobHash !== "string" || !/^[0-9a-f]{64}$/.test(v.blobHash)))
@@ -272,25 +291,101 @@ function invalidBlobExchange(message) {
272
291
  export function boundaryPublishVerdict(attempt) {
273
292
  return attempt.aborted ? { publish: false, reason: "aborted" } : { publish: true };
274
293
  }
275
- async function parentIdentityViaEnv(env, absPath, root, signal) {
294
+ async function placeOfParentViaEnv(env, absPath, signal) {
276
295
  const parent = parentDirOf(absPath);
277
- if (parent === undefined)
278
- return undefined;
279
- const canon = await env.canonicalPath(parent, signal);
280
- if (!canon.ok)
296
+ return parent === undefined ? undefined : placeOfDirViaEnv(env, parent, signal);
297
+ }
298
+ async function placeOfDirViaEnv(env, dir, signal) {
299
+ let at = dir;
300
+ let tail = "";
301
+ for (;;) {
302
+ const canon = await env.canonicalPath(at, signal);
303
+ if (canon.ok)
304
+ return tail === "" ? canon.value : joinUnder(canon.value, tail);
305
+ if (canon.error.code !== "not_found")
306
+ return undefined;
307
+ const up = parentDirOf(at);
308
+ if (up === undefined)
309
+ return undefined;
310
+ const leaf = lastSegmentOf(at);
311
+ tail = tail === "" ? leaf : `${leaf}/${tail}`;
312
+ at = up;
313
+ }
314
+ }
315
+ function isPlace(parentIdent) {
316
+ return !relativeInEveryFamily(parentIdent);
317
+ }
318
+ function trackedPlaceOf(versions) {
319
+ for (let i = versions.length - 1; i >= 0; i--) {
320
+ const p = versions[i].parentIdent;
321
+ if (p !== undefined && isPlace(p))
322
+ return p;
323
+ }
324
+ return undefined;
325
+ }
326
+ const foldedSpelling = (p) => p.normalize("NFC").toLowerCase();
327
+ async function placeAsItStands(env, place, signal) {
328
+ const now = await placeOfDirViaEnv(env, place, signal);
329
+ if (now === undefined || now === place)
330
+ return now;
331
+ if (foldedSpelling(now) !== foldedSpelling(place))
281
332
  return undefined;
282
- let rel = relUnder(root, canon.value);
283
- if (rel === null) {
284
- const canonRoot = await env.canonicalPath(root, signal);
285
- if (canonRoot.ok)
286
- rel = relUnder(canonRoot.value, canon.value);
333
+ for (let at = place; at !== undefined; at = parentDirOf(at)) {
334
+ const info = await env.fileInfo(at, signal);
335
+ if (info.ok ? info.value.kind === "symlink" : info.error.code !== "not_found")
336
+ return undefined;
337
+ }
338
+ return now;
339
+ }
340
+ export async function resolveTrackedFile(env, root, key, versions, minted, signal) {
341
+ const resolved = resolveTrackKey(root, key, minted);
342
+ if (!resolved.ok)
343
+ return resolved;
344
+ const place = trackedPlaceOf(versions);
345
+ if (place !== undefined) {
346
+ const stands = await placeAsItStands(env, place, signal);
347
+ if (stands === undefined)
348
+ return { ok: true, held: `the directory ${key} was recorded under (${place}) no longer resolves to itself` };
349
+ const abs = joinUnder(stands, lastSegmentOf(resolved.abs));
350
+ const leaf = await env.fileInfo(abs, signal);
351
+ if (leaf.ok && leaf.value.kind === "symlink")
352
+ return { ok: true, held: `${abs} is a symbolic link now — the recorded file is not read through it` };
353
+ return { ok: true, abs };
287
354
  }
288
- return rel === null ? canon.value : rel === "" ? "." : rel;
355
+ const realRoot = await placeOfDirViaEnv(env, root, signal);
356
+ const real = await env.canonicalPath(resolved.abs, signal);
357
+ const physical = real.ok ? real.value : real.error.code === "not_found" ? await placeOfDirViaEnv(env, resolved.abs, signal) : undefined;
358
+ const under = realRoot === undefined || physical === undefined ? null : relUnder(realRoot, physical);
359
+ if (under === null || under === "")
360
+ return { ok: true, held: `${resolved.abs} does not lie under the root's real path (${realRoot ?? "unreadable"}) — a file this history records no place for is read only under the root` };
361
+ return { ok: true, abs: resolved.abs };
362
+ }
363
+ export async function trackKeyForEdit(env, root, absPath, entryOf, signal) {
364
+ const described = describeTrackKey(root, absPath);
365
+ if (described.kind === "absolute")
366
+ return described;
367
+ if (entryOf(absPath) !== undefined)
368
+ return { key: absPath, kind: "absolute", family: described.family };
369
+ const existing = entryOf(described.key);
370
+ const there = existing === undefined ? undefined : trackedPlaceOf(existing.versions);
371
+ if (there === undefined)
372
+ return described;
373
+ const here = await placeOfParentViaEnv(env, absPath, signal);
374
+ if (here === undefined || here === there || (await placeAsItStands(env, there, signal)) === here)
375
+ return described;
376
+ return { key: absPath, kind: "absolute", family: described.family };
289
377
  }
290
- export async function captureFileBackupViaEnv(env, absPath, root, signal) {
378
+ export function trackKeyForAnnul(root, absPath, has) {
379
+ const key = trackKeyOf(root, absPath);
380
+ return key !== absPath && has(absPath) ? absPath : key;
381
+ }
382
+ export function placeProvenDifferent(recorded, current) {
383
+ return current !== undefined && recorded !== current;
384
+ }
385
+ export async function captureFileBackupViaEnv(env, absPath, _root, signal) {
291
386
  if (signal?.aborted)
292
387
  return { state: "aborted" };
293
- const parentIdent = await parentIdentityViaEnv(env, absPath, root, signal);
388
+ const parentIdent = await placeOfParentViaEnv(env, absPath, signal);
294
389
  const rb = await env.readBinaryFile(absPath, signal);
295
390
  if (!rb.ok) {
296
391
  if (signal?.aborted)
@@ -334,9 +429,11 @@ export async function applyFileRestoreViaEnv(env, absPath, target, opts) {
334
429
  const signal = opts.signal;
335
430
  if (signal?.aborted)
336
431
  return { outcome: "failed", reason: "aborted" };
337
- const guard = await restorePreflight(env, absPath, opts);
432
+ const guard = await restorePreflight(env, absPath, target, opts);
338
433
  if ("refused" in guard)
339
434
  return guard.refused;
435
+ if ("convergedAtItsPlace" in guard)
436
+ return { outcome: "identical" };
340
437
  const cur = await env.readBinaryFile(absPath, signal);
341
438
  const curAbsent = !cur.ok && cur.error.code === "not_found";
342
439
  if ("absent" in target) {
@@ -359,38 +456,69 @@ export async function applyFileRestoreViaEnv(env, absPath, target, opts) {
359
456
  }
360
457
  const w = await writeRestoredBytes(env, absPath, target.bytes, signal);
361
458
  if (!w.ok)
362
- return w.refused ? { outcome: "refused", reason: `write: ${w.code}`, class: "link_safety" } : { outcome: "failed", reason: `write: ${w.code}` };
459
+ return w.refused ? { outcome: "refused", reason: `write: ${w.code}`, class: "link_safety", action: "write" } : { outcome: "failed", reason: `write: ${w.code}` };
363
460
  const modeAfter = await applyRecordedMode(env, absPath, opts, undefined);
364
461
  return { outcome: "applied", ...(modeAfter === "unpreserved" || modeAfter === "applied_unpreserved" ? { modeNotPreserved: true } : {}) };
365
462
  }
366
- async function restorePreflight(env, absPath, opts) {
463
+ async function restorePreflight(env, absPath, target, opts) {
464
+ const action = "absent" in target ? "delete" : "write";
465
+ const refuse = (cls, reason, recordedUnder) => ({
466
+ refused: { outcome: "refused", reason, class: cls, action, ...(recordedUnder !== undefined ? { recordedUnder } : {}) },
467
+ });
367
468
  const info = await env.fileInfo(absPath, opts.signal);
368
469
  if (info.ok && info.value.kind !== "file") {
369
- return {
370
- refused: {
371
- outcome: "refused",
372
- reason: info.value.kind === "symlink"
373
- ? "restore target is a SYMLINK — the recorded bytes belong to the file that was edited, not to whatever the link now points at"
374
- : `restore target is a ${info.value.kind}, not a regular file — the recorded bytes are not this object's`,
375
- class: "link_safety",
376
- },
377
- };
470
+ return refuse("link_safety", info.value.kind === "symlink"
471
+ ? "restore target is a SYMLINK — the recorded bytes belong to the file that was edited, not to whatever the link now points at"
472
+ : `restore target is a ${info.value.kind}, not a regular file — the recorded bytes are not this object's`);
378
473
  }
379
474
  const currentMode = info.ok ? info.value.mode : undefined;
380
- if (opts.parentIdent === undefined)
475
+ const recorded = await recordedPlaceOf(env, absPath, opts);
476
+ if (recorded === undefined) {
477
+ return refuse("place_unrecorded", "this version records no place (it was recorded before places were kept), so where it belongs cannot be told — it was not written; a host that knows the directory this session's earlier legs ran in names it as unplacedHistoryRecordedUnder");
478
+ }
479
+ const now = await placeOfParentViaEnv(env, absPath, opts.signal);
480
+ if (now === recorded)
381
481
  return { currentMode };
382
- const now = await parentIdentityViaEnv(env, absPath, opts.root, opts.signal);
383
482
  if (now === undefined)
483
+ return refuse("link_safety", "where this file would land cannot be read (its directory's real path did not resolve) — it was not written");
484
+ const stands = await placeAsItStands(env, recorded, opts.signal);
485
+ if (stands === undefined) {
486
+ return refuse("link_safety", `the directory this version was recorded under (${recorded}) no longer resolves to itself — it was moved or is reached through a link now — so it was not written`);
487
+ }
488
+ if (stands === now)
384
489
  return { currentMode };
385
- if (now === opts.parentIdent)
386
- return { currentMode };
387
- return {
388
- refused: {
389
- outcome: "refused",
390
- reason: `restore target's parent chain changed identity since it was recorded (recorded ${JSON.stringify(opts.parentIdent)}, now ${JSON.stringify(now)}) — writing here could land outside the task root`,
391
- class: "link_safety",
392
- },
393
- };
490
+ if (await placeHolds(env, stands, lastSegmentOf(absPath), target, opts.signal))
491
+ return { convergedAtItsPlace: true };
492
+ return refuse("recorded_elsewhere", `this version was recorded under ${stands}, and this rewind would ${action === "delete" ? "delete" : "write"} it at ${absPath} — a file is restored only where it was recorded, so it was not touched; rewind from that directory to restore it`, stands);
493
+ }
494
+ async function recordedPlaceOf(env, absPath, opts) {
495
+ const ident = opts.parentIdent;
496
+ if (ident !== undefined && isPlace(ident))
497
+ return ident;
498
+ const under = opts.unplacedHistoryRecordedUnder;
499
+ if (under === undefined)
500
+ return undefined;
501
+ const rel = relativeParentUnder(opts.root, absPath);
502
+ if (rel === undefined)
503
+ return undefined;
504
+ const base = await placeOfDirViaEnv(env, under, opts.signal);
505
+ if (base === undefined)
506
+ return undefined;
507
+ return rel === "." ? base : joinUnder(base, isWinFormPath(base) ? normSlash(rel) : rel);
508
+ }
509
+ function relativeParentUnder(root, absPath) {
510
+ const parent = parentDirOf(absPath);
511
+ const rel = parent === undefined ? null : relUnder(root, parent);
512
+ return rel === null ? undefined : rel === "" ? "." : rel;
513
+ }
514
+ async function placeHolds(env, place, leaf, target, signal) {
515
+ const dir = await env.fileInfo(place, signal);
516
+ if (!dir.ok || dir.value.kind !== "directory")
517
+ return false;
518
+ const there = await env.readBinaryFile(joinUnder(place, leaf), signal);
519
+ if ("absent" in target)
520
+ return !there.ok && there.error.code === "not_found";
521
+ return there.ok && createHash("sha256").update(there.value).digest("hex") === target.hash;
394
522
  }
395
523
  async function writeRestoredBytes(env, absPath, bytes, signal) {
396
524
  if (env.writeFileGuarded !== undefined) {
@@ -423,19 +551,21 @@ async function applyRecordedMode(env, absPath, opts, currentMode) {
423
551
  return "unchanged";
424
552
  if (currentMode === (want & 0o7777))
425
553
  return "unchanged";
554
+ const setMode = async (mode) => {
555
+ try {
556
+ return env.setFileMode !== undefined && (await env.setFileMode(absPath, mode, opts.signal)).ok;
557
+ }
558
+ catch {
559
+ return false;
560
+ }
561
+ };
426
562
  if ((want & 0o6000) !== 0) {
427
563
  const stripped = want & 0o1777;
428
564
  if (currentMode === stripped)
429
565
  return "unpreserved";
430
- if (env.setFileMode === undefined)
431
- return "unpreserved";
432
- const r = await env.setFileMode(absPath, stripped, opts.signal);
433
- return r.ok ? "applied_unpreserved" : "unpreserved";
566
+ return (await setMode(stripped)) ? "applied_unpreserved" : "unpreserved";
434
567
  }
435
- if (env.setFileMode === undefined)
436
- return "unpreserved";
437
- const r = await env.setFileMode(absPath, want & 0o7777, opts.signal);
438
- return r.ok ? "applied" : "unpreserved";
568
+ return (await setMode(want & 0o7777)) ? "applied" : "unpreserved";
439
569
  }
440
570
  const IN_MEMORY_FILE_HISTORY_STORE_OPTION_KEYS = optionKeys()({ retention: 0 });
441
571
  export class InMemoryFileHistoryStore {
@@ -530,8 +660,8 @@ export class InMemoryFileHistoryStore {
530
660
  }
531
661
  async trackEditCounted(scope, absPath, env, root, signal) {
532
662
  try {
533
- const { key, ...keyDesc } = describeTrackKey(root, absPath);
534
663
  const sc = this.scope(scope);
664
+ const { key, ...keyDesc } = await trackKeyForEdit(env, root, absPath, (k) => sc.tracked.get(k), signal);
535
665
  const already = sc.tracked.get(key);
536
666
  if (already !== undefined) {
537
667
  already.observedByLaterTouch = true;
@@ -582,8 +712,8 @@ export class InMemoryFileHistoryStore {
582
712
  }
583
713
  async annulTrackCounted(scope, absPath, root, verify) {
584
714
  try {
585
- const key = trackKeyOf(root, absPath);
586
715
  const sc = this.scopes.get(scope);
716
+ const key = trackKeyForAnnul(root, absPath, (k) => sc?.tracked.has(k) === true);
587
717
  const t = sc?.tracked.get(key);
588
718
  if (sc === undefined || t === undefined)
589
719
  return { ok: true };
@@ -645,11 +775,17 @@ export class InMemoryFileHistoryStore {
645
775
  sc.spentAttempts.add(entryId);
646
776
  return { ok: false, error: { code: "aborted", message: `boundary capture for entry "${entryId}" aborted` } };
647
777
  }
648
- const resolved = resolveTrackKey(root, key, t.keyDesc);
778
+ const resolved = await resolveTrackedFile(env, root, key, t.versions, t.keyDesc, signal);
649
779
  if (!resolved.ok) {
650
780
  sc.spentAttempts.add(entryId);
651
781
  return { ok: false, error: { code: "snapshot_failed", message: resolved.reason } };
652
782
  }
783
+ if ("held" in resolved) {
784
+ const last = t.versions[t.versions.length - 1];
785
+ if (last !== undefined)
786
+ staged.set(key, { kind: "unchanged", version: last.version });
787
+ continue;
788
+ }
653
789
  const cap = await captureFileBackupViaEnv(env, resolved.abs, root, signal);
654
790
  if (cap.state === "aborted") {
655
791
  sc.spentAttempts.add(entryId);
@@ -661,13 +797,13 @@ export class InMemoryFileHistoryStore {
661
797
  }
662
798
  const last = t.versions[t.versions.length - 1];
663
799
  if (cap.state === "absent") {
664
- if (last !== undefined && last.blobHash === null)
800
+ if (last !== undefined && last.blobHash === null && !placeProvenDifferent(last.parentIdent, cap.parentIdent))
665
801
  staged.set(key, { kind: "unchanged", version: last.version });
666
802
  else
667
803
  staged.set(key, { kind: "changed", blobHash: null, ...(cap.parentIdent !== undefined ? { parentIdent: cap.parentIdent } : {}) });
668
804
  continue;
669
805
  }
670
- if (last !== undefined && last.blobHash === cap.hash && !modeProvenDifferent(last.mode, cap.mode)) {
806
+ if (last !== undefined && last.blobHash === cap.hash && !modeProvenDifferent(last.mode, cap.mode) && !placeProvenDifferent(last.parentIdent, cap.parentIdent)) {
671
807
  staged.set(key, { kind: "unchanged", version: last.version });
672
808
  continue;
673
809
  }
@@ -704,7 +840,7 @@ export class InMemoryFileHistoryStore {
704
840
  this.releaseBlob(h);
705
841
  }
706
842
  }
707
- async restore(scope, entryId, env, root, signal) {
843
+ async restore(scope, entryId, env, root, signal, options) {
708
844
  const empty = { filesChanged: [], identicalSkipped: [], refused: [], failed: [] };
709
845
  try {
710
846
  const sc = this.scopes.get(scope);
@@ -756,6 +892,7 @@ export class InMemoryFileHistoryStore {
756
892
  ...(rec.mode !== undefined ? { mode: rec.mode } : {}),
757
893
  ...(rec.parentIdent !== undefined ? { parentIdent: rec.parentIdent } : {}),
758
894
  ...(signal !== undefined ? { signal } : {}),
895
+ ...(options?.unplacedHistoryRecordedUnder !== undefined ? { unplacedHistoryRecordedUnder: options.unplacedHistoryRecordedUnder } : {}),
759
896
  });
760
897
  }
761
898
  catch (err) {
@@ -766,7 +903,7 @@ export class InMemoryFileHistoryStore {
766
903
  else if (applied.outcome === "identical")
767
904
  ledger.identicalSkipped.push(key);
768
905
  else if (applied.outcome === "refused")
769
- ledger.refused.push({ path: key, reason: applied.reason, class: applied.class });
906
+ ledger.refused.push({ path: key, reason: applied.reason, class: applied.class, ...(applied.action !== undefined ? { action: applied.action } : {}), ...(applied.recordedUnder !== undefined ? { recordedUnder: applied.recordedUnder } : {}) });
770
907
  else
771
908
  ledger.failed.push({ path: key, reason: applied.reason });
772
909
  if ((applied.outcome === "applied" || applied.outcome === "identical") && applied.modeNotPreserved === true)
@@ -782,38 +919,10 @@ export class InMemoryFileHistoryStore {
782
919
  async canRestore(scope, entryId) {
783
920
  return this.scopes.get(scope)?.boundaries.has(entryId) ?? false;
784
921
  }
785
- async diffStats(scope, entryId, env, root) {
922
+ async diffStats(scope, entryId, env, root, options) {
786
923
  try {
787
- const sc = this.scopes.get(scope);
788
- const boundary = sc?.boundaries.get(entryId);
789
- if (sc === undefined || boundary === undefined)
790
- return null;
791
- const filesChanged = [];
792
- let insertions = 0;
793
- let deletions = 0;
794
- for (const key of [...sc.tracked.keys()].sort()) {
795
- const t = sc.tracked.get(key);
796
- let targetVersion = boundary.get(key);
797
- if (targetVersion === undefined) {
798
- if (!t.baseAvailable)
799
- continue;
800
- targetVersion = 1;
801
- }
802
- const rec = t.versions.find((v) => v.version === targetVersion);
803
- const resolved = resolveTrackKey(root, key, t.keyDesc);
804
- if (rec === undefined || !resolved.ok)
805
- continue;
806
- const targetBytes = rec.blobHash === null ? undefined : this.blobs.get(rec.blobHash);
807
- if (rec.blobHash !== null && targetBytes === undefined)
808
- continue;
809
- const delta = await previewFileDelta(env, resolved.abs, rec.blobHash, targetBytes, rec.mode);
810
- if (delta === undefined)
811
- continue;
812
- filesChanged.push(key);
813
- insertions += delta.insertions;
814
- deletions += delta.deletions;
815
- }
816
- return { filesChanged, insertions, deletions };
924
+ const plan = await planFileHistoryRestore(this, { scope, entryId, env, root, ...(options !== undefined ? { options } : {}) });
925
+ return plan.restore.outcome === "failed" && plan.restore.files.length === 0 ? null : plan.diffStats;
817
926
  }
818
927
  catch {
819
928
  return null;
@@ -903,10 +1012,12 @@ export class InMemoryFileHistoryStore {
903
1012
  return { ok: true };
904
1013
  }
905
1014
  const copy = { tracked: new Map(), boundaries: new Map(), spentAttempts: new Set(), activeAttempts: new Set(), reapedEntries: new Set([...from.reapedEntries, ...(to?.reapedEntries ?? [])]) };
906
- for (const [key, t] of from.tracked)
907
- copy.tracked.set(key, { baseAvailable: t.baseAvailable, keyDesc: { ...t.keyDesc }, ...(t.observedByLaterTouch === true ? { observedByLaterTouch: true } : {}), versions: t.versions.map((v) => ({ ...v })) });
1015
+ for (const [key, t] of from.tracked) {
1016
+ if (fileHistoryEntryTravels(t.keyDesc))
1017
+ copy.tracked.set(key, { baseAvailable: t.baseAvailable, keyDesc: { ...t.keyDesc }, ...(t.observedByLaterTouch === true ? { observedByLaterTouch: true } : {}), versions: t.versions.map((v) => ({ ...v })) });
1018
+ }
908
1019
  for (const [id, mapping] of from.boundaries)
909
- copy.boundaries.set(id, new Map(mapping));
1020
+ copy.boundaries.set(id, new Map([...mapping].filter(([key]) => copy.tracked.has(key))));
910
1021
  this.scopes.set(toScope, copy);
911
1022
  return { ok: true };
912
1023
  }
@@ -919,20 +1030,24 @@ export class InMemoryFileHistoryStore {
919
1030
  return { ok: true, history: sc === undefined || (sc.tracked.size === 0 && sc.boundaries.size === 0) ? null : this.exportOf(sc) };
920
1031
  }
921
1032
  exportOf(sc) {
1033
+ const travels = [...sc.tracked.entries()].filter(([, t]) => fileHistoryEntryTravels(t.keyDesc));
1034
+ const omitted = sc.tracked.size - travels.length;
1035
+ const kept = new Set(travels.map(([key]) => key));
922
1036
  return {
923
1037
  formatVersion: "file-history/1",
924
- tracked: [...sc.tracked.entries()]
1038
+ ...(omitted > 0 ? { absoluteEntriesOmitted: omitted } : {}),
1039
+ tracked: travels
925
1040
  .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
926
1041
  .map(([key, t]) => ({
927
1042
  relOrAbsPath: key,
928
1043
  keyKind: t.keyDesc.kind,
929
1044
  keyFamily: t.keyDesc.family,
930
1045
  baseAvailable: t.baseAvailable,
931
- versions: t.versions.map((v) => ({ version: v.version, blobHash: v.blobHash, ...(v.mode !== undefined ? { mode: v.mode } : {}), ...(v.parentIdent !== undefined ? { parentIdent: v.parentIdent } : {}), backupTime: v.backupTime })),
1046
+ versions: t.versions.map((v) => ({ version: v.version, blobHash: v.blobHash, ...(v.mode !== undefined ? { mode: v.mode } : {}), ...(v.parentIdent !== undefined && fileHistoryParentIdentTravels(v.parentIdent) ? { parentIdent: v.parentIdent } : {}), backupTime: v.backupTime })),
932
1047
  })),
933
1048
  boundaries: [...sc.boundaries.entries()]
934
1049
  .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
935
- .map(([entryId, mapping]) => ({ entryId, files: [...mapping.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([relOrAbsPath, version]) => ({ relOrAbsPath, version })) })),
1050
+ .map(([entryId, mapping]) => ({ entryId, files: [...mapping.entries()].filter(([key]) => kept.has(key)).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([relOrAbsPath, version]) => ({ relOrAbsPath, version })) })),
936
1051
  };
937
1052
  }
938
1053
  importHistory(scope, data, srcGetBlob) {
@@ -1015,4 +1130,84 @@ export class InMemoryFileHistoryStore {
1015
1130
  }
1016
1131
  }
1017
1132
  }
1133
+ const PLAN_READS = new Set(["absolutePath", "joinPath", "readTextFile", "readTextLines", "readBinaryFile", "fileInfo", "listDir", "canonicalPath", "readLink", "canonicalChain", "fileIdentity", "openBound", "exists"]);
1134
+ const PLAN_MUTATIONS = { writeFile: "write", writeFileGuarded: "write", writeFileExclusive: "write", appendFile: "write", remove: "delete", setFileMode: "mode", createDir: "none" };
1135
+ function envViewOf(env, perform) {
1136
+ const mutations = [];
1137
+ const view = new Proxy(env, {
1138
+ get(target, prop, receiver) {
1139
+ const value = Reflect.get(target, prop, receiver);
1140
+ if (typeof value !== "function" || typeof prop !== "string")
1141
+ return value;
1142
+ const fn = value;
1143
+ const kind = Object.prototype.hasOwnProperty.call(PLAN_MUTATIONS, prop) ? PLAN_MUTATIONS[prop] : undefined;
1144
+ if (kind !== undefined) {
1145
+ return (...args) => {
1146
+ const at = args[0];
1147
+ const note = () => {
1148
+ if (kind !== "none" && typeof at === "string")
1149
+ mutations.push({ at, action: kind, ...(kind === "write" && args[1] instanceof Uint8Array ? { bytes: args[1] } : {}) });
1150
+ };
1151
+ if (!perform) {
1152
+ note();
1153
+ return Promise.resolve({ ok: true, value: undefined });
1154
+ }
1155
+ return Promise.resolve(fn.apply(target, args)).then((r) => {
1156
+ if (r !== null && typeof r === "object" && r.ok === true)
1157
+ note();
1158
+ return r;
1159
+ });
1160
+ };
1161
+ }
1162
+ if (perform || PLAN_READS.has(prop))
1163
+ return fn.bind(target);
1164
+ return () => Promise.resolve({ ok: false, error: { code: "unsupported", message: `a planned restore reached ${prop}, which a plan does not perform` } });
1165
+ },
1166
+ });
1167
+ return { env: view, mutations };
1168
+ }
1169
+ export function witnessEnvOf(env) {
1170
+ return envViewOf(env, true);
1171
+ }
1172
+ export function withRewindFiles(restored, mutations, root) {
1173
+ const deleted = new Set(mutations.filter((m) => m.action === "delete").map((m) => m.at));
1174
+ const targetOf = (key) => {
1175
+ const r = resolveTrackKey(root, key);
1176
+ return r.ok ? r.abs : key;
1177
+ };
1178
+ const files = [
1179
+ ...restored.filesChanged.map((key) => {
1180
+ const targetPath = targetOf(key);
1181
+ return { path: key, targetPath, action: deleted.has(targetPath) ? "delete" : "write" };
1182
+ }),
1183
+ ...restored.refused.map((row) => ({
1184
+ path: row.path,
1185
+ targetPath: targetOf(row.path),
1186
+ ...(row.action !== undefined ? { action: row.action } : {}),
1187
+ refused: { class: row.class, reason: row.reason, ...(row.recordedUnder !== undefined ? { recordedUnder: row.recordedUnder } : {}) },
1188
+ })),
1189
+ ...restored.failed.flatMap((row) => {
1190
+ const targetPath = targetOf(row.path);
1191
+ const landed = mutations.find((m) => m.at === targetPath && m.action !== "mode");
1192
+ return landed === undefined ? [] : [{ path: row.path, targetPath, action: landed.action === "delete" ? "delete" : "write", failed: { reason: row.reason } }];
1193
+ }),
1194
+ ];
1195
+ return { ...restored, files };
1196
+ }
1197
+ export async function planFileHistoryRestore(store, input) {
1198
+ const planning = envViewOf(input.env, false);
1199
+ const restored = await store.restore(input.scope, input.entryId, planning.env, input.root, input.signal, input.options);
1200
+ const answered = withRewindFiles(restored, planning.mutations, input.root);
1201
+ let insertions = 0;
1202
+ let deletions = 0;
1203
+ for (const m of planning.mutations) {
1204
+ if (m.action === "mode")
1205
+ continue;
1206
+ const cur = await input.env.readBinaryFile(m.at, input.signal);
1207
+ const delta = countRestoreLineDiff(cur.ok ? cur.value : undefined, m.action === "write" ? m.bytes : undefined);
1208
+ insertions += delta.insertions;
1209
+ deletions += delta.deletions;
1210
+ }
1211
+ return { restore: answered, diffStats: { filesChanged: answered.filesChanged, insertions, deletions, files: answered.files } };
1212
+ }
1018
1213
  export const __testables = { joinUnder, relUnder, stripTrailSep, trackKeyOf, resolveTrackKey, parentDirOf };
@@ -2827,7 +2827,7 @@ export interface RunState {
2827
2827
  /**
2828
2828
  * Config handed to {@link Runner.resume}: the {@link TaskSpec} members the resumed leg runs with. The session comes from the checkpoint,
2829
2829
  * so the config names none of the members that live and die with a session (`SessionBoundSpecMember`, the member table's one column:
2830
- * `sessionId`, `requireExistingSession`, `resumeAt`, `resumeAtMode`, `restoreFiles`, `acceptPartialRestore`, `rewindFilesTo`); a
2830
+ * `sessionId`, `requireExistingSession`, `resumeAt`, `resumeAtMode`, `restoreFiles`, `acceptPartialRestore`, `unplacedHistoryRecordedUnder`, `rewindFilesTo`); a
2831
2831
  * resume sends no new human message, so it takes no objective, `userAttachments` or `runOrigin` (either present is refused before the
2832
2832
  * claim; a wake states its leg's word on the input it hands over). The row records no tool, hand band or server list: `tools`, `mcp`,
2833
2833
  * `a2a` and the `skills` specs are the deployment's CURRENT ones as this resume hands them (the leg dials these lists as the config doors
@@ -1,5 +1,5 @@
1
1
  /** The file-history REQUEST door and its bad-value doors — the pre-acquire half of the file-history phase (`prepare-file-history.ts`). */
2
- import type { FileHistoryStore } from "../file-history-store.js";
2
+ import type { FileHistoryRestoreOptions, FileHistoryStore } from "../file-history-store.js";
3
3
  import type { RunnerDeps, TaskSpec } from "../types.js";
4
4
  /**
5
5
  * The file-history REQUEST door: every refusal the request (`TaskSpec`) and the deployment's own seats decide
@@ -10,7 +10,13 @@ import type { RunnerDeps, TaskSpec } from "../types.js";
10
10
  * calls it BEFORE the session is acquired, so a request refused here leaves the session — its leaf included —
11
11
  * exactly as it was. What it resolves rides into the file-history phase (`prepareFileHistory`) unchanged.
12
12
  */
13
- export declare function resolveFileHistoryRequest(spec: Pick<TaskSpec, "resumeAt" | "resumeAtMode" | "restoreFiles" | "rewindFilesTo" | "fileHistory">, deps: Pick<RunnerDeps, "onTrackFailure" | "fileHistoryStore" | "fileHistoryCapture">): FileHistoryRequest;
13
+ export declare function resolveFileHistoryRequest(spec: Pick<TaskSpec, "resumeAt" | "resumeAtMode" | "restoreFiles" | "rewindFilesTo" | "fileHistory" | "unplacedHistoryRecordedUnder">, deps: Pick<RunnerDeps, "onTrackFailure" | "fileHistoryStore" | "fileHistoryCapture">): FileHistoryRequest;
14
+ /**
15
+ * THE reading of `unplacedHistoryRecordedUnder` (`TaskSpec` and `RewindFilesRequest` name it alike): a non-empty absolute path
16
+ * (in either path family) on a request that restores files, else refused by name (`rewind.invalid_spec`) — on a request that
17
+ * restores nothing it would be read by no one, and a value that is not a path is not a directory anything was recorded under.
18
+ */
19
+ export declare function readRestoreOptions(value: unknown, restores: boolean, seat: "TaskSpec" | "Runner.rewindFiles"): FileHistoryRestoreOptions | undefined;
14
20
  /**
15
21
  * The DEPLOYMENT's file-history door — the three seats a deployment sets once (`RunnerDeps.onTrackFailure`,
16
22
  * `RunnerDeps.fileHistoryStore`, `RunnerDeps.fileHistoryCapture`), each refused by name on a bad value. Read by
@@ -41,4 +47,6 @@ export interface FileHistoryRequest {
41
47
  captureStore: FileHistoryStore | undefined;
42
48
  rewindTarget: string | undefined;
43
49
  rewindBefore: boolean;
50
+ /** The restore's options ({@link readRestoreOptions}); `undefined` when the request names none. */
51
+ restoreOptions: FileHistoryRestoreOptions | undefined;
44
52
  }
@@ -1,4 +1,5 @@
1
1
  import { describeRejectedValue } from "../tool-search-setting.js";
2
+ import { relativeInEveryFamily } from "../../tools/fs/safety.js";
2
3
  export function resolveFileHistoryRequest(spec, deps) {
3
4
  const { onTrackFailure, wiredSeat, captureOff } = resolveDeploymentFileHistory(deps);
4
5
  const runDeclaredOff = resolveRunFileHistoryWord(spec.fileHistory);
@@ -22,7 +23,22 @@ export function resolveFileHistoryRequest(spec, deps) {
22
23
  throw captureDisabledRefusal(rewindTarget);
23
24
  throw storeUnconfiguredRefusal(wiredSeat, rewindTarget);
24
25
  }
25
- return { onTrackFailure, wiredSeat, runDeclaredOff, captureOff, declaredOff, fileHistoryStore, captureStore, rewindTarget, rewindBefore };
26
+ const restoreOptions = readRestoreOptions(spec.unplacedHistoryRecordedUnder, rewindTarget !== undefined, "TaskSpec");
27
+ return { onTrackFailure, wiredSeat, runDeclaredOff, captureOff, declaredOff, fileHistoryStore, captureStore, rewindTarget, rewindBefore, restoreOptions };
28
+ }
29
+ export function readRestoreOptions(value, restores, seat) {
30
+ if (value === undefined)
31
+ return undefined;
32
+ const bad = (why) => {
33
+ const e = new Error(`${seat === "TaskSpec" ? "TaskSpec.unplacedHistoryRecordedUnder" : "Runner.rewindFiles: unplacedHistoryRecordedUnder"} ${why} — nothing was rewound. It names the directory this session's older file versions (the ones that record no place) were recorded under.`);
34
+ e.code = "rewind.invalid_spec";
35
+ throw e;
36
+ };
37
+ if (typeof value !== "string" || value === "" || relativeInEveryFamily(value))
38
+ return bad(`must be a non-empty absolute path, got ${describeRejectedValue(value)}`);
39
+ if (!restores)
40
+ return bad("is set on a run that restores no file (no rewindFilesTo, and no resumeAt with restoreFiles)");
41
+ return { unplacedHistoryRecordedUnder: value };
26
42
  }
27
43
  export function resolveDeploymentFileHistory(deps) {
28
44
  const onTrackFailure = deps.onTrackFailure === undefined ? "refuse" : deps.onTrackFailure;