@bastani/atomic 0.9.84-alpha.1 → 0.9.85-alpha.1

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 (183) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +6 -0
  3. package/dist/builtin/intercom/broker/broker.ts +25 -7
  4. package/dist/builtin/intercom/broker/spawn.ts +83 -17
  5. package/dist/builtin/intercom/index.bundle.mjs +89 -26
  6. package/dist/builtin/intercom/package.json +1 -1
  7. package/dist/builtin/mcp/package.json +1 -1
  8. package/dist/builtin/subagents/package.json +1 -1
  9. package/dist/builtin/web-access/package.json +1 -1
  10. package/dist/builtin/workflows/CHANGELOG.md +6 -0
  11. package/dist/builtin/workflows/package.json +1 -1
  12. package/dist/builtin/workflows/src/authoring.d.ts +1 -1
  13. package/dist/builtin/workflows/src/extension/index.bundle.mjs +48 -9
  14. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +48 -9
  15. package/dist/builtin/workflows/src/index.js +48 -9
  16. package/dist/builtin/workflows/src/local-worker-entry.mjs +48 -9
  17. package/dist/config.d.ts +3 -2
  18. package/dist/config.d.ts.map +1 -1
  19. package/dist/config.js +4 -3
  20. package/dist/config.js.map +1 -1
  21. package/dist/core/agent-session-export.d.ts +2 -2
  22. package/dist/core/agent-session-export.d.ts.map +1 -1
  23. package/dist/core/agent-session-export.js +4 -5
  24. package/dist/core/agent-session-export.js.map +1 -1
  25. package/dist/core/agent-session-services.js +1 -1
  26. package/dist/core/agent-session-services.js.map +1 -1
  27. package/dist/core/agent-session-summary.d.ts.map +1 -1
  28. package/dist/core/agent-session-summary.js +8 -1
  29. package/dist/core/agent-session-summary.js.map +1 -1
  30. package/dist/core/agent-session-tree.d.ts.map +1 -1
  31. package/dist/core/agent-session-tree.js +3 -6
  32. package/dist/core/agent-session-tree.js.map +1 -1
  33. package/dist/core/builtin-resource-loader.d.ts.map +1 -1
  34. package/dist/core/builtin-resource-loader.js +1 -1
  35. package/dist/core/builtin-resource-loader.js.map +1 -1
  36. package/dist/core/extensions/loader-core.d.ts +6 -2
  37. package/dist/core/extensions/loader-core.d.ts.map +1 -1
  38. package/dist/core/extensions/loader-core.js +13 -9
  39. package/dist/core/extensions/loader-core.js.map +1 -1
  40. package/dist/core/extensions/loader-discovery.js +1 -1
  41. package/dist/core/extensions/loader-discovery.js.map +1 -1
  42. package/dist/core/extensions/loader-virtual-modules.d.ts +20 -14
  43. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  44. package/dist/core/extensions/loader-virtual-modules.js +133 -78
  45. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  46. package/dist/core/extensions/ts-source-specifiers.d.ts +1 -0
  47. package/dist/core/extensions/ts-source-specifiers.d.ts.map +1 -1
  48. package/dist/core/extensions/ts-source-specifiers.js +18 -2
  49. package/dist/core/extensions/ts-source-specifiers.js.map +1 -1
  50. package/dist/core/mandatory-resource-loader.d.ts +5 -2
  51. package/dist/core/mandatory-resource-loader.d.ts.map +1 -1
  52. package/dist/core/mandatory-resource-loader.js +17 -12
  53. package/dist/core/mandatory-resource-loader.js.map +1 -1
  54. package/dist/core/model-fallback-failures.d.ts.map +1 -1
  55. package/dist/core/model-fallback-failures.js +10 -3
  56. package/dist/core/model-fallback-failures.js.map +1 -1
  57. package/dist/core/resource-loader-extensions.d.ts.map +1 -1
  58. package/dist/core/resource-loader-extensions.js +1 -1
  59. package/dist/core/resource-loader-extensions.js.map +1 -1
  60. package/dist/core/resource-loader-reload.js +1 -1
  61. package/dist/core/resource-loader-reload.js.map +1 -1
  62. package/dist/core/resume/blueprint/resume.d.ts +4 -4
  63. package/dist/core/resume/blueprint/resume.js +4 -4
  64. package/dist/core/resume/blueprint/resume.js.map +1 -1
  65. package/dist/core/resume/session-resume.d.ts +6 -3
  66. package/dist/core/resume/session-resume.d.ts.map +1 -1
  67. package/dist/core/resume/session-resume.js +159 -37
  68. package/dist/core/resume/session-resume.js.map +1 -1
  69. package/dist/core/sdk.js +1 -1
  70. package/dist/core/sdk.js.map +1 -1
  71. package/dist/core/session-manager-core.d.ts +10 -4
  72. package/dist/core/session-manager-core.d.ts.map +1 -1
  73. package/dist/core/session-manager-core.js +23 -6
  74. package/dist/core/session-manager-core.js.map +1 -1
  75. package/dist/core/session-manager-entries.d.ts +2 -2
  76. package/dist/core/session-manager-entries.d.ts.map +1 -1
  77. package/dist/core/session-manager-entries.js +2 -1
  78. package/dist/core/session-manager-entries.js.map +1 -1
  79. package/dist/core/session-manager-history.d.ts +13 -1
  80. package/dist/core/session-manager-history.d.ts.map +1 -1
  81. package/dist/core/session-manager-history.js +21 -1
  82. package/dist/core/session-manager-history.js.map +1 -1
  83. package/dist/core/session-manager-types.d.ts +3 -1
  84. package/dist/core/session-manager-types.d.ts.map +1 -1
  85. package/dist/core/session-manager-types.js.map +1 -1
  86. package/dist/core/session-manager.d.ts +1 -1
  87. package/dist/core/session-manager.d.ts.map +1 -1
  88. package/dist/core/session-manager.js +1 -1
  89. package/dist/core/session-manager.js.map +1 -1
  90. package/dist/core/session-worktree-snapshots.d.ts +61 -4
  91. package/dist/core/session-worktree-snapshots.d.ts.map +1 -1
  92. package/dist/core/session-worktree-snapshots.js +261 -28
  93. package/dist/core/session-worktree-snapshots.js.map +1 -1
  94. package/dist/core/storage/session/entry-structure.js +31 -1
  95. package/dist/core/storage/session/entry-structure.js.map +1 -1
  96. package/dist/core/tools/ask-user-question/state/build-questionnaire.d.ts.map +1 -1
  97. package/dist/core/tools/ask-user-question/state/build-questionnaire.js +2 -1
  98. package/dist/core/tools/ask-user-question/state/build-questionnaire.js.map +1 -1
  99. package/dist/core/tools/ask-user-question/state/questionnaire-session.d.ts.map +1 -1
  100. package/dist/core/tools/ask-user-question/state/questionnaire-session.js +2 -0
  101. package/dist/core/tools/ask-user-question/state/questionnaire-session.js.map +1 -1
  102. package/dist/core/tools/ask-user-question/state/selectors/field-tone.d.ts +26 -0
  103. package/dist/core/tools/ask-user-question/state/selectors/field-tone.d.ts.map +1 -0
  104. package/dist/core/tools/ask-user-question/state/selectors/field-tone.js +27 -0
  105. package/dist/core/tools/ask-user-question/state/selectors/field-tone.js.map +1 -0
  106. package/dist/core/tools/ask-user-question/state/selectors/projections.d.ts.map +1 -1
  107. package/dist/core/tools/ask-user-question/state/selectors/projections.js +1 -0
  108. package/dist/core/tools/ask-user-question/state/selectors/projections.js.map +1 -1
  109. package/dist/core/tools/ask-user-question/state/state-reducer.js +1 -1
  110. package/dist/core/tools/ask-user-question/state/state-reducer.js.map +1 -1
  111. package/dist/core/tools/ask-user-question/view/components/multi-select-view.d.ts.map +1 -1
  112. package/dist/core/tools/ask-user-question/view/components/multi-select-view.js +6 -6
  113. package/dist/core/tools/ask-user-question/view/components/multi-select-view.js.map +1 -1
  114. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.d.ts +5 -3
  115. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.d.ts.map +1 -1
  116. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.js +14 -4
  117. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.js.map +1 -1
  118. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.d.ts +2 -0
  119. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.d.ts.map +1 -1
  120. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.js +3 -3
  121. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.js.map +1 -1
  122. package/dist/core/tools/ask-user-question/view/components/wrapping-select.d.ts +16 -6
  123. package/dist/core/tools/ask-user-question/view/components/wrapping-select.d.ts.map +1 -1
  124. package/dist/core/tools/ask-user-question/view/components/wrapping-select.js +42 -24
  125. package/dist/core/tools/ask-user-question/view/components/wrapping-select.js.map +1 -1
  126. package/dist/core/tools/ask-user-question/view/tab-content-strategy.d.ts.map +1 -1
  127. package/dist/core/tools/ask-user-question/view/tab-content-strategy.js +12 -3
  128. package/dist/core/tools/ask-user-question/view/tab-content-strategy.js.map +1 -1
  129. package/dist/core/tools/read.d.ts +1 -0
  130. package/dist/core/tools/read.d.ts.map +1 -1
  131. package/dist/core/tools/read.js +13 -14
  132. package/dist/core/tools/read.js.map +1 -1
  133. package/dist/core/worktree-snapshot/index.d.ts +2 -2
  134. package/dist/core/worktree-snapshot/index.d.ts.map +1 -1
  135. package/dist/core/worktree-snapshot/index.js +1 -1
  136. package/dist/core/worktree-snapshot/index.js.map +1 -1
  137. package/dist/core/worktree-snapshot/records.d.ts +6 -0
  138. package/dist/core/worktree-snapshot/records.d.ts.map +1 -1
  139. package/dist/core/worktree-snapshot/records.js +18 -4
  140. package/dist/core/worktree-snapshot/records.js.map +1 -1
  141. package/dist/core/worktree-snapshot/restore.d.ts +24 -1
  142. package/dist/core/worktree-snapshot/restore.d.ts.map +1 -1
  143. package/dist/core/worktree-snapshot/restore.js +443 -72
  144. package/dist/core/worktree-snapshot/restore.js.map +1 -1
  145. package/dist/core/worktree-snapshot/types.d.ts +44 -0
  146. package/dist/core/worktree-snapshot/types.d.ts.map +1 -1
  147. package/dist/core/worktree-snapshot/types.js.map +1 -1
  148. package/dist/index.d.ts +2 -2
  149. package/dist/index.d.ts.map +1 -1
  150. package/dist/index.js +2 -2
  151. package/dist/index.js.map +1 -1
  152. package/dist/modes/interactive/components/tool-execution.js +2 -1
  153. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  154. package/dist/modes/interactive/interactive-slash-commands.js +4 -1
  155. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  156. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  157. package/dist/modes/interactive-engine/isolated-runtime.js +8 -0
  158. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  159. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  160. package/dist/modes/rpc/rpc-command-handler.js +11 -2
  161. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  162. package/dist/modes/rpc/rpc-command-timeouts.d.ts.map +1 -1
  163. package/dist/modes/rpc/rpc-command-timeouts.js +1 -0
  164. package/dist/modes/rpc/rpc-command-timeouts.js.map +1 -1
  165. package/dist/modes/rpc/rpc-input-scheduler.d.ts.map +1 -1
  166. package/dist/modes/rpc/rpc-input-scheduler.js +1 -0
  167. package/dist/modes/rpc/rpc-input-scheduler.js.map +1 -1
  168. package/dist/modes/rpc/rpc-types.d.ts +11 -1
  169. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  170. package/dist/modes/rpc/rpc-types.js.map +1 -1
  171. package/docs/environment-variables.md +1 -1
  172. package/docs/guides/resume-on-any-machine.md +6 -4
  173. package/docs/intercom/operations.md +4 -0
  174. package/docs/rpc/protocol.md +2 -2
  175. package/docs/sdk/reference.md +3 -0
  176. package/docs/sdk.md +2 -2
  177. package/docs/session-format.md +11 -2
  178. package/docs/sessions.md +4 -2
  179. package/docs/settings.md +1 -1
  180. package/docs/workflows/api-reference.md +2 -2
  181. package/docs/worktree-snapshots.md +13 -5
  182. package/npm-shrinkwrap.json +32 -32
  183. package/package.json +3 -3
@@ -6,10 +6,10 @@ import lockfile from "proper-lockfile";
6
6
  import { getAgentDir } from "../../config.js";
7
7
  import { locateCheckout, readRepositoryConfig, withScratchDirectory, writeSnapshotCommit, writeWorkingTree, } from "./capture.js";
8
8
  import { computeEnvironmentHash, sha256Hex } from "./env-hash.js";
9
- import { isWorkspaceGitError, unreadablePathError, unwritablePathError, WorkspaceConfigError, WorkspaceDriftError, WorkspaceGitError, WorkspaceRestoreError, } from "./errors.js";
9
+ import { isWorkspaceGitError, isWorkspaceRestoreError, unreadablePathError, unwritablePathError, WorkspaceConfigError, WorkspaceDriftError, WorkspaceGitError, WorkspaceRestoreError, } from "./errors.js";
10
10
  import { gitText, nulFields, runGit, withWorktreeSnapshotGit, } from "./git.js";
11
11
  import { loadSnapshotPathPolicy } from "./policy.js";
12
- import { assertUsableBundlePrerequisites, assertUsableSnapshotRecord } from "./records.js";
12
+ import { assertUsableBundlePrerequisites, assertUsableSnapshotRecord, isAllowedRemote } from "./records.js";
13
13
  import { DEFAULT_WORKTREE_SNAPSHOT_SETTINGS, resolveWorktreeSnapshotSettings, } from "./settings.js";
14
14
  /** The warnings a restore of `snapshot` reports from its record: omitted content and source conversion settings. */
15
15
  export function snapshotRestoreWarnings(snapshot) {
@@ -412,15 +412,17 @@ function runFetch(git, repository, refspecs) {
412
412
  }
413
413
  async function fetchCommits(git, remotes, commits) {
414
414
  let failure;
415
+ let supplied = false;
415
416
  for (const remote of remotes) {
416
417
  const missing = [];
417
418
  for (const commit of commits)
418
419
  if (!(await hasObject(git, `${commit}^{commit}`)))
419
420
  missing.push(commit);
420
421
  if (missing.length === 0)
421
- return undefined;
422
+ return { failure: undefined, supplied };
422
423
  try {
423
424
  await runFetch(git, remote, missing);
425
+ supplied = true;
424
426
  }
425
427
  catch (error) {
426
428
  if (!isWorkspaceGitError(error))
@@ -428,17 +430,25 @@ async function fetchCommits(git, remotes, commits) {
428
430
  failure = error;
429
431
  }
430
432
  }
431
- return failure;
433
+ return { failure, supplied };
432
434
  }
435
+ /**
436
+ * Makes `snapshot.head` available in the store, from the recorded remotes or else its bundle, and resolves whether
437
+ * it came from a recorded remote.
438
+ */
433
439
  async function ensureHead(git, snapshot, blobs, scratch) {
434
440
  const { head } = snapshot;
441
+ let fetched = false;
435
442
  if (!(await hasObject(git, `${head}^{commit}`))) {
436
- let failure = await fetchCommits(git, snapshot.remotes, [head]);
443
+ // Only a fetch that succeeded proves a remote has `head`: another process may import it from a bundle meanwhile.
444
+ const fromRemotes = await fetchCommits(git, snapshot.remotes, [head]);
445
+ let failure = fromRemotes.failure;
446
+ fetched = fromRemotes.supplied;
437
447
  if (!(await hasObject(git, `${head}^{commit}`)) && snapshot.bundle) {
438
448
  const data = await loadBlob(blobs, snapshot.bundle.blob, { snapshotId: snapshot.id, role: "bundle" });
439
449
  const prerequisites = bundlePrerequisites(data);
440
450
  assertUsableBundlePrerequisites(prerequisites, snapshot.id);
441
- failure = (await fetchCommits(git, snapshot.remotes, prerequisites)) ?? failure;
451
+ failure = (await fetchCommits(git, snapshot.remotes, prerequisites)).failure ?? failure;
442
452
  const file = join(scratch, "history.bundle");
443
453
  await writing(file, snapshot.id, () => writeFile(file, data));
444
454
  try {
@@ -479,7 +489,71 @@ async function ensureHead(git, snapshot, blobs, scratch) {
479
489
  }, failure);
480
490
  }
481
491
  }
482
- await runGit(["update-ref", `refs/atomic/heads/${head}`, head], git);
492
+ return fetched;
493
+ }
494
+ async function configuredRemoteUrls(git) {
495
+ const { stdout } = await runGit(["config", "-z", "--get-regexp", "^remote\\..+\\.url$"], {
496
+ ...git,
497
+ allowExitCodes: [1],
498
+ });
499
+ return nulFields(stdout).map((field) => field.slice(field.indexOf("\n") + 1));
500
+ }
501
+ /**
502
+ * Gives a shared object store the remotes its snapshots record, in their recorded order (the first as `origin`, then
503
+ * `origin-2`, …), so a capture in one of its worktrees records them too. Resolves whether the store's remotes are the
504
+ * recorded ones. A store without recorded remotes, or with a remote that is not credential-free or not of a scheme a
505
+ * restore fetches over, is left without any, as before.
506
+ */
507
+ async function configureRecordedRemotes(git, remotes) {
508
+ if (remotes.length === 0 || !remotes.every(isAllowedRemote))
509
+ return false;
510
+ let configured = await configuredRemoteUrls(git);
511
+ // A store holding the start of the recorded list was set up by a restore that stopped partway; finish it.
512
+ if (configured.length < remotes.length && configured.every((remote, index) => remote === remotes[index])) {
513
+ try {
514
+ for (let index = configured.length; index < remotes.length; index++) {
515
+ await runGit(["remote", "add", "--", index === 0 ? "origin" : `origin-${index + 1}`, remotes[index]], git);
516
+ }
517
+ return true;
518
+ }
519
+ catch (error) {
520
+ // Another process configured the store at the same moment; what it wrote is compared below.
521
+ if (!isWorkspaceGitError(error))
522
+ throw error;
523
+ }
524
+ configured = await configuredRemoteUrls(git);
525
+ }
526
+ return configured.length === remotes.length && configured.every((remote, index) => remote === remotes[index]);
527
+ }
528
+ /** Where a restore records commits a recorded remote has, as remote-tracking refs no remote's fetch ever prunes. */
529
+ const PUSHED_REFS = "refs/remotes/atomic/pushed/";
530
+ /**
531
+ * The commits a restore knows a recorded remote has, to record as remote-tracking refs: the snapshot's `head` when the
532
+ * restore fetched it from one or the snapshot recorded nothing unpushed, else the parents of its bundled commits that
533
+ * the bundle does not hold, its pushed boundary. Later captures in the store's worktrees then bundle only commits that
534
+ * are really unpushed, and never count a commit that only a bundle carried as pushed.
535
+ */
536
+ async function pushedCommits(git, snapshot, head, fetched) {
537
+ const pushed = new Set();
538
+ const historyOmitted = snapshot?.omitted.some((omission) => omission.reason === "unpushed-history-denied" || omission.reason === "bundle-over-cap");
539
+ if (fetched || (snapshot !== null && snapshot.bundle === null && !historyOmitted))
540
+ pushed.add(head);
541
+ else if (snapshot?.bundle) {
542
+ const bundled = new Set(snapshot.bundle.commits);
543
+ const parents = await runGit(["rev-list", "--no-walk=unsorted", "--parents", "--stdin"], {
544
+ ...git,
545
+ input: `${snapshot.bundle.commits.join("\n")}\n`,
546
+ allowExitCodes: [128],
547
+ });
548
+ if (parents.exitCode === 0) {
549
+ for (const line of parents.stdout.toString("utf8").split("\n")) {
550
+ for (const parent of line.split(" ").slice(1))
551
+ if (!bundled.has(parent))
552
+ pushed.add(parent);
553
+ }
554
+ }
555
+ }
556
+ return pushed;
483
557
  }
484
558
  async function reconstructTree(git, snapshot, patches, scratch) {
485
559
  const indexed = { ...git, env: { ...git.env, GIT_INDEX_FILE: join(scratch, "restore-index") } };
@@ -630,7 +704,6 @@ export async function restoreWorktree(target, options = {}) {
630
704
  return withWorktreeSnapshotGit(options.git, () => restoreValidated(target, options));
631
705
  }
632
706
  async function restoreValidated(target, options) {
633
- const settings = DEFAULT_WORKTREE_SNAPSHOT_SETTINGS;
634
707
  const { signal } = options;
635
708
  const snapshot = resolveSnapshot(target, options.snapshots);
636
709
  assertUsableSnapshotRecord(target, snapshot);
@@ -661,7 +734,21 @@ async function restoreValidated(target, options) {
661
734
  const git = { cwd: scratch, signal, env: { GIT_DIR: store } };
662
735
  await withRepositoryLock(store, async () => {
663
736
  await ensureObjectStore(store, snapshotId, signal);
664
- await ensureHead(git, snapshot ?? { id: null, head: target.head, remotes: target.remotes, bundle: null, omitted: [] }, options.blobs, scratch);
737
+ const fetched = await ensureHead(git, snapshot ?? { id: null, head: target.head, remotes: target.remotes, bundle: null, omitted: [] }, options.blobs, scratch);
738
+ // What a snapshot of other remotes, such as a fork at the same commit, says is pushed is not this store's.
739
+ const sameRemotes = snapshot === null ||
740
+ (snapshot.remotes.length === target.remotes.length &&
741
+ snapshot.remotes.every((remote, index) => remote === target.remotes[index]));
742
+ const pushed = (await configureRecordedRemotes(git, target.remotes)) && sameRemotes
743
+ ? await pushedCommits(git, snapshot, target.head, fetched)
744
+ : new Set();
745
+ await runGit(["update-ref", "--stdin"], {
746
+ ...git,
747
+ input: [
748
+ `update refs/atomic/heads/${target.head} ${target.head}\n`,
749
+ ...[...pushed].map((commit) => `update ${PUSHED_REFS}${commit} ${commit}\n`),
750
+ ].join(""),
751
+ });
665
752
  if (!(await hasObject(git, `${target.tree}^{tree}`))) {
666
753
  if (!snapshot) {
667
754
  throw new WorkspaceRestoreError("snapshot-not-found", {
@@ -673,69 +760,19 @@ async function restoreValidated(target, options) {
673
760
  await reconstructTree(git, snapshot, patches, scratch);
674
761
  }
675
762
  });
676
- await checkTarget(path, snapshotId);
677
- const createdTarget = (await statIfPresent(path)) === undefined;
678
- const id = randomUUID();
679
- const staging = options.into === undefined
680
- ? join(storeDir, "worktrees", `.staging-${id}`)
681
- : join(dirname(path), `.${basename(path)}.atomic-restore-${id}`);
682
- const record = { staging, target: path, store, createdTarget };
683
- await withRestoreRecord(storeDir, id, record, snapshotId, warn, signal, async (assertActive) => {
684
- await materialize(git, staging, target.head, target.tree, scratch, snapshotId, signal);
685
- assertActive();
686
- if (snapshot?.filters?.drivers.includes("lfs")) {
687
- const worktree = { cwd: staging, signal };
688
- const pointers = await pullLfsObjects(worktree, target.head, target.tree, snapshot.remotes);
689
- if (pointers.length > 0)
690
- warn({ code: "lfs-objects-unavailable", paths: pointers });
691
- }
692
- const checkout = await locateCheckout(staging, signal);
693
- if (checkout instanceof Error)
694
- throw checkout;
695
- const policy = await loadSnapshotPathPolicy(staging);
696
- const actual = await withScratchDirectory((verifyScratch) => writeWorkingTree(checkout, settings, policy, verifyScratch, {
697
- signal,
698
- neutral: true,
699
- seedTree: target.tree,
700
- attributesFile: join(scratch, "empty-attributes"),
701
- }));
702
- if (checkout.head !== target.head || actual.tree !== target.tree) {
703
- throw new WorkspaceRestoreError("tree-mismatch", {
704
- snapshotId,
705
- target: path,
706
- expectedTree: target.tree,
707
- actualTree: actual.tree,
708
- });
709
- }
710
- assertActive();
711
- if (createdTarget) {
712
- if ((await statIfPresent(path)) !== undefined) {
713
- throw new WorkspaceRestoreError("unsafe-target", { snapshotId, target: path, reason: "not-empty" });
714
- }
715
- }
716
- else {
717
- await writing(path, snapshotId, () => rmdir(path));
718
- }
719
- await runGit(["worktree", "move", staging, path], git);
720
- // Git moves *inside* an existing directory. If one appeared after our check, never return it as the
721
- // verified worktree: remove only the nested worktree that Git registered and leave the user's files alone.
722
- const registered = await registeredWorktrees(git);
723
- const destination = await physicalPath(path);
724
- if (!includesPath(registered, destination)) {
725
- const error = new WorkspaceRestoreError("unsafe-target", { snapshotId, target: path, reason: "not-empty" });
726
- const nested = join(destination, basename(staging));
727
- if (includesPath(registered, nested)) {
728
- try {
729
- await runGit(["worktree", "remove", "--force", "--force", nested], { ...git, signal: undefined });
730
- }
731
- catch (cleanupCause) {
732
- Object.defineProperty(error, "cleanupCause", { value: cleanupCause, configurable: true });
733
- warn({ code: "stale-restore-retained", path: nested, kind: "worktree" });
734
- }
735
- }
736
- throw error;
737
- }
738
- assertActive();
763
+ await publishWorktree({
764
+ git,
765
+ store,
766
+ storeDir,
767
+ path,
768
+ into: options.into,
769
+ head: target.head,
770
+ tree: target.tree,
771
+ snapshot,
772
+ scratch,
773
+ warn,
774
+ signal,
775
+ verify: "tree",
739
776
  });
740
777
  if (snapshot)
741
778
  for (const warning of snapshotRestoreWarnings(snapshot))
@@ -748,6 +785,340 @@ async function restoreValidated(target, options) {
748
785
  };
749
786
  });
750
787
  }
788
+ /** Restore errors after which a degraded restore can still give the session part of its snapshot (#4733). */
789
+ const DEGRADABLE_RESTORE_CODES = new Set([
790
+ "blob-missing",
791
+ "blob-corrupt",
792
+ "commits-unavailable",
793
+ "delta-failed",
794
+ "tree-mismatch",
795
+ ]);
796
+ /** Whether a degraded restore can follow `error`, the failure of an exact restore. */
797
+ export function isDegradableRestoreFailure(error) {
798
+ return isWorkspaceRestoreError(error) && DEGRADABLE_RESTORE_CODES.has(error.code);
799
+ }
800
+ /**
801
+ * Restores the best state of `snapshot` that this host can reach after an exact restore failed with `failure` (#4733),
802
+ * into a new worktree: the recorded `HEAD` with the change sets of the patch chain that apply, each whole or not at
803
+ * all, up to the first that cannot; else the closest commit it can fetch from the recorded remotes, trying the
804
+ * snapshot's pushed base, then `candidates`, then the recorded branch's tip. Rejects with `failure` when no commit is
805
+ * reachable, and with `invalid-snapshot` for a record that fails the security checks, before any Git work.
806
+ */
807
+ export async function restoreDegradedWorktree(snapshot, failure, options = {}) {
808
+ return withWorktreeSnapshotGit(options.git, () => restoreDegradedValidated(snapshot, failure, options));
809
+ }
810
+ async function restoreDegradedValidated(snapshot, failure, options) {
811
+ const { signal } = options;
812
+ assertUsableSnapshotRecord({ remotes: [...snapshot.remotes], head: snapshot.head, tree: snapshot.tree, envHash: snapshot.envHash }, snapshot);
813
+ const candidates = options.candidates ?? [];
814
+ const unusable = candidates.findIndex((commit) => !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(commit));
815
+ if (unusable >= 0)
816
+ throw new WorkspaceConfigError("sdk", `candidates[${unusable}]`, "a Git commit id");
817
+ const storeDir = resolve(options.storeDir ?? defaultWorktreeSnapshotStoreDir());
818
+ const path = join(storeDir, "worktrees", `${snapshot.id.slice(0, 12)}-${randomUUID().slice(0, 8)}`);
819
+ await checkTarget(path, snapshot.id);
820
+ const warnings = [];
821
+ const warn = (warning) => {
822
+ warnings.push(warning);
823
+ options.onWarning?.(warning);
824
+ };
825
+ await sweepRestoreRecords(storeDir, warn, signal);
826
+ return withScratchDirectory(async (scratch) => {
827
+ const store = objectStorePath(storeDir, snapshot.remotes);
828
+ const git = { cwd: scratch, signal, env: { GIT_DIR: store } };
829
+ const cause = {
830
+ cause: failure.code,
831
+ ...(failure.reason ? { causeReason: failure.reason } : {}),
832
+ hint: failure.hint,
833
+ };
834
+ const degraded = await withRepositoryLock(store, async () => {
835
+ await ensureObjectStore(store, snapshot.id, signal);
836
+ const configured = await configureRecordedRemotes(git, snapshot.remotes);
837
+ // The exact restore may have stopped before it reached the recorded commit: fetch it, or take it from the bundle.
838
+ const reached = await ensureHead(git, snapshot, options.blobs, scratch).then((fetched) => ({ fetched }), (error) => {
839
+ if (isWorkspaceRestoreError(error))
840
+ return undefined;
841
+ throw error;
842
+ });
843
+ if (reached !== undefined) {
844
+ const partial = await applicableChanges(git, snapshot, options.blobs, scratch);
845
+ await runGit(["update-ref", "--stdin"], {
846
+ ...git,
847
+ input: [
848
+ `update refs/atomic/heads/${snapshot.head} ${snapshot.head}\n`,
849
+ ...(configured && reached.fetched
850
+ ? [`update ${PUSHED_REFS}${snapshot.head} ${snapshot.head}\n`]
851
+ : []),
852
+ ].join(""),
853
+ });
854
+ return {
855
+ stage: "partial-changes",
856
+ head: snapshot.head,
857
+ tree: partial.tree,
858
+ missingLinks: partial.missingLinks,
859
+ missingPaths: partial.missingPaths,
860
+ missingCommits: [],
861
+ ...cause,
862
+ };
863
+ }
864
+ const closest = await closestCommit(git, snapshot, candidates, options.blobs);
865
+ if (closest === undefined)
866
+ throw failure;
867
+ await runGit(["update-ref", "--stdin"], {
868
+ ...git,
869
+ input: [
870
+ `update refs/atomic/heads/${closest.commit} ${closest.commit}\n`,
871
+ ...(configured && closest.fromRemote
872
+ ? [`update ${PUSHED_REFS}${closest.commit} ${closest.commit}\n`]
873
+ : []),
874
+ ].join(""),
875
+ });
876
+ return {
877
+ stage: "closest-commit",
878
+ head: closest.commit,
879
+ tree: await gitText(["rev-parse", `${closest.commit}^{tree}`], git),
880
+ basis: closest.basis,
881
+ missingLinks: snapshot.chain.flatMap((link, index) => (link.patch === null ? [] : [index])),
882
+ missingPaths: [],
883
+ missingCommits: unpushedCommits(snapshot),
884
+ ...cause,
885
+ };
886
+ });
887
+ const measured = await publishWorktree({
888
+ git,
889
+ store,
890
+ storeDir,
891
+ path,
892
+ into: undefined,
893
+ head: degraded.head,
894
+ tree: degraded.tree,
895
+ snapshot,
896
+ scratch,
897
+ warn,
898
+ signal,
899
+ verify: failure.code === "tree-mismatch" ? "head" : "tree",
900
+ });
901
+ if (measured === degraded.tree)
902
+ return { path, degraded, warnings };
903
+ // This host's checkout filters changed files: record what the worktree holds, and which files differ.
904
+ const differing = nulFields((await runGit(["diff-tree", "-r", "-z", "--name-only", "--no-renames", degraded.tree, measured], git)).stdout);
905
+ const missingPaths = [...new Set([...degraded.missingPaths, ...differing])].sort();
906
+ return { path, degraded: { ...degraded, tree: measured, missingPaths }, warnings };
907
+ });
908
+ }
909
+ /** The commits `snapshot` recorded as not pushed: its bundle's, else those its omissions name, else its `HEAD`. */
910
+ function unpushedCommits(snapshot) {
911
+ if (snapshot.bundle)
912
+ return [...snapshot.bundle.commits];
913
+ const named = snapshot.omitted.flatMap((omission) => ("commits" in omission ? omission.commits : []));
914
+ return named.length > 0 ? [...new Set(named)] : [snapshot.head];
915
+ }
916
+ /**
917
+ * The tree of `snapshot`'s `HEAD` with its patch chain applied in the store, link by link, up to the first link whose
918
+ * patch is missing, corrupt or does not give the link's tree; that link and every later one are left out whole. Lists
919
+ * the paths the left-out links touch where their patches are readable.
920
+ */
921
+ async function applicableChanges(git, snapshot, blobs, scratch) {
922
+ const indexed = { ...git, env: { ...git.env, GIT_INDEX_FILE: join(scratch, "degraded-index") } };
923
+ let tree = await gitText(["rev-parse", `${snapshot.head}^{tree}`], git);
924
+ await runGit(["read-tree", tree], indexed);
925
+ let stop = snapshot.chain.length;
926
+ const patches = [];
927
+ for (const [deltaIndex, link] of snapshot.chain.entries()) {
928
+ const patch = link.patch === null
929
+ ? null
930
+ : await loadBlob(blobs, link.patch, { snapshotId: snapshot.id, role: "patch", deltaIndex }).catch((error) => {
931
+ if (isWorkspaceRestoreError(error))
932
+ return undefined;
933
+ throw error;
934
+ });
935
+ patches.push(patch ?? undefined);
936
+ if (stop < snapshot.chain.length)
937
+ continue;
938
+ if (patch === undefined) {
939
+ stop = deltaIndex;
940
+ continue;
941
+ }
942
+ if (patch !== null) {
943
+ const file = join(scratch, `degraded-${deltaIndex}.patch`);
944
+ await writing(file, snapshot.id, () => writeFile(file, patch));
945
+ // `git apply` changes nothing when any hunk does not apply, so a link is applied whole or not at all.
946
+ const applied = await runGit(["apply", "--cached", "--binary", "--whitespace=nowarn", "--no-ignore-whitespace", "--no-3way", file], { ...indexed, allowExitCodes: [1, 128] });
947
+ if (applied.exitCode !== 0) {
948
+ stop = deltaIndex;
949
+ continue;
950
+ }
951
+ }
952
+ const written = await gitText(["write-tree"], indexed);
953
+ if (written !== link.tree) {
954
+ await runGit(["read-tree", tree], indexed);
955
+ stop = deltaIndex;
956
+ continue;
957
+ }
958
+ tree = written;
959
+ }
960
+ const missingLinks = snapshot.chain.flatMap((_link, index) => (index >= stop ? [index] : []));
961
+ const missingPaths = new Set();
962
+ for (const index of missingLinks) {
963
+ const patch = patches[index];
964
+ if (!patch)
965
+ continue;
966
+ const file = join(scratch, `degraded-${index}.patch`);
967
+ await writing(file, snapshot.id, () => writeFile(file, patch));
968
+ const listed = await runGit(["apply", "--numstat", "-z", file], { ...git, allowExitCodes: [1, 128] });
969
+ if (listed.exitCode !== 0)
970
+ continue;
971
+ for (const field of nulFields(listed.stdout)) {
972
+ const path = field.split("\t").at(-1);
973
+ if (path)
974
+ missingPaths.add(path);
975
+ }
976
+ }
977
+ return { tree, missingLinks, missingPaths: [...missingPaths].sort() };
978
+ }
979
+ /** Whether Git accepts `name`, a branch name from a snapshot record, as a branch name (`git check-ref-format --branch`). */
980
+ async function isBranchName(git, name) {
981
+ if (name.startsWith("-") || name.includes("@{") || /[\u0000-\u001f\u007f]/.test(name))
982
+ return false;
983
+ const { exitCode } = await runGit(["check-ref-format", "--branch", name], { ...git, allowExitCodes: [1, 128] });
984
+ return exitCode === 0;
985
+ }
986
+ /**
987
+ * The commit nearest `snapshot`'s `HEAD` that the store holds or a recorded remote supplies: the pushed base of its
988
+ * bundle, when the bundle is readable, then each of `candidates`, then the tip of the recorded branch (the remote's
989
+ * default branch for a detached `HEAD`).
990
+ */
991
+ async function closestCommit(git, snapshot, candidates, blobs) {
992
+ const tried = new Set([snapshot.head]);
993
+ const reachable = async (commit) => {
994
+ if (tried.has(commit))
995
+ return undefined;
996
+ tried.add(commit);
997
+ if (await hasObject(git, `${commit}^{commit}`))
998
+ return { commit, fromRemote: false };
999
+ const fetched = await fetchCommits(git, snapshot.remotes, [commit]);
1000
+ return fetched.supplied && (await hasObject(git, `${commit}^{commit}`))
1001
+ ? { commit, fromRemote: true }
1002
+ : undefined;
1003
+ };
1004
+ if (snapshot.bundle) {
1005
+ const data = await blobs?.getBlob(snapshot.bundle.blob).catch(() => undefined);
1006
+ if (data !== undefined && sha256Hex(data) === snapshot.bundle.blob) {
1007
+ const prerequisites = bundlePrerequisites(data);
1008
+ assertUsableBundlePrerequisites(prerequisites, snapshot.id);
1009
+ for (const commit of prerequisites) {
1010
+ const found = await reachable(commit);
1011
+ if (found)
1012
+ return { ...found, basis: "pushed-base" };
1013
+ }
1014
+ }
1015
+ }
1016
+ for (const commit of candidates) {
1017
+ const found = await reachable(commit);
1018
+ if (found)
1019
+ return { ...found, basis: "earlier-snapshot" };
1020
+ }
1021
+ // The recorded branch's tip, when Git accepts its name as a branch; the remote's default branch only for a
1022
+ // detached HEAD, never in place of a branch that has a name.
1023
+ if (snapshot.branch !== null && !(await isBranchName(git, snapshot.branch)))
1024
+ return undefined;
1025
+ const source = snapshot.branch === null ? "HEAD" : `refs/heads/${snapshot.branch}`;
1026
+ const ref = `refs/atomic/tips/${snapshot.id}`;
1027
+ for (const remote of snapshot.remotes) {
1028
+ try {
1029
+ await runFetch(git, remote, [`+${source}:${ref}`]);
1030
+ }
1031
+ catch (error) {
1032
+ if (!isWorkspaceGitError(error))
1033
+ throw error;
1034
+ continue;
1035
+ }
1036
+ const tip = await runGit(["rev-parse", "-q", "--verify", `${ref}^{commit}`], {
1037
+ ...git,
1038
+ allowExitCodes: [1, 128],
1039
+ });
1040
+ await runGit(["update-ref", "-d", ref], git);
1041
+ if (tip.exitCode === 0)
1042
+ return { commit: tip.stdout.toString("utf8").trim(), basis: "branch-tip", fromRemote: true };
1043
+ }
1044
+ return undefined;
1045
+ }
1046
+ /**
1047
+ * Checks `head` and `tree` out of `store` into a staging worktree, verifies it, and moves it to `path`, under a crash
1048
+ * record, so a final path never holds an unverified worktree.
1049
+ */
1050
+ async function publishWorktree(publish) {
1051
+ const { git, store, storeDir, path, head, tree, snapshot, scratch, warn, signal } = publish;
1052
+ let measured = tree;
1053
+ const settings = DEFAULT_WORKTREE_SNAPSHOT_SETTINGS;
1054
+ const snapshotId = snapshot?.id ?? null;
1055
+ await checkTarget(path, snapshotId);
1056
+ const createdTarget = (await statIfPresent(path)) === undefined;
1057
+ const id = randomUUID();
1058
+ const staging = publish.into === undefined
1059
+ ? join(storeDir, "worktrees", `.staging-${id}`)
1060
+ : join(dirname(path), `.${basename(path)}.atomic-restore-${id}`);
1061
+ const record = { staging, target: path, store, createdTarget };
1062
+ await withRestoreRecord(storeDir, id, record, snapshotId, warn, signal, async (assertActive) => {
1063
+ await materialize(git, staging, head, tree, scratch, snapshotId, signal);
1064
+ assertActive();
1065
+ if (snapshot?.filters?.drivers.includes("lfs")) {
1066
+ const worktree = { cwd: staging, signal };
1067
+ const pointers = await pullLfsObjects(worktree, head, tree, snapshot.remotes);
1068
+ if (pointers.length > 0)
1069
+ warn({ code: "lfs-objects-unavailable", paths: pointers });
1070
+ }
1071
+ const checkout = await locateCheckout(staging, signal);
1072
+ if (checkout instanceof Error)
1073
+ throw checkout;
1074
+ const policy = await loadSnapshotPathPolicy(staging);
1075
+ const actual = await withScratchDirectory((verifyScratch) => writeWorkingTree(checkout, settings, policy, verifyScratch, {
1076
+ signal,
1077
+ neutral: true,
1078
+ seedTree: tree,
1079
+ attributesFile: join(scratch, "empty-attributes"),
1080
+ }));
1081
+ measured = actual.tree;
1082
+ if (checkout.head !== head || (publish.verify === "tree" && actual.tree !== tree)) {
1083
+ throw new WorkspaceRestoreError("tree-mismatch", {
1084
+ snapshotId,
1085
+ target: path,
1086
+ expectedTree: tree,
1087
+ actualTree: actual.tree,
1088
+ });
1089
+ }
1090
+ assertActive();
1091
+ if (createdTarget) {
1092
+ if ((await statIfPresent(path)) !== undefined) {
1093
+ throw new WorkspaceRestoreError("unsafe-target", { snapshotId, target: path, reason: "not-empty" });
1094
+ }
1095
+ }
1096
+ else {
1097
+ await writing(path, snapshotId, () => rmdir(path));
1098
+ }
1099
+ await runGit(["worktree", "move", staging, path], git);
1100
+ // Git moves *inside* an existing directory. If one appeared after our check, never return it as the
1101
+ // verified worktree: remove only the nested worktree that Git registered and leave the user's files alone.
1102
+ const registered = await registeredWorktrees(git);
1103
+ const destination = await physicalPath(path);
1104
+ if (!includesPath(registered, destination)) {
1105
+ const error = new WorkspaceRestoreError("unsafe-target", { snapshotId, target: path, reason: "not-empty" });
1106
+ const nested = join(destination, basename(staging));
1107
+ if (includesPath(registered, nested)) {
1108
+ try {
1109
+ await runGit(["worktree", "remove", "--force", "--force", nested], { ...git, signal: undefined });
1110
+ }
1111
+ catch (cleanupCause) {
1112
+ Object.defineProperty(error, "cleanupCause", { value: cleanupCause, configurable: true });
1113
+ warn({ code: "stale-restore-retained", path: nested, kind: "worktree" });
1114
+ }
1115
+ }
1116
+ throw error;
1117
+ }
1118
+ assertActive();
1119
+ });
1120
+ return measured;
1121
+ }
751
1122
  /** The entry at `path`, or undefined when there is none. */
752
1123
  async function statIfPresent(path) {
753
1124
  try {