@amalgm/shell 0.1.164-main.40070365614 → 0.1.164-main.40795482467

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 (319) hide show
  1. package/dist/accepted-fold.d.ts +24 -46
  2. package/dist/accepted-fold.js +62 -140
  3. package/dist/accepted-fold.js.map +1 -1
  4. package/dist/accepted-tail.d.ts +3 -3
  5. package/dist/accepted-tail.js +6 -6
  6. package/dist/accepted-tail.js.map +1 -1
  7. package/dist/apply-control.d.ts +9 -4
  8. package/dist/apply-control.js +18 -5
  9. package/dist/apply-control.js.map +1 -1
  10. package/dist/apply-enter-build.d.ts +6 -7
  11. package/dist/apply-enter-build.js +4 -10
  12. package/dist/apply-enter-build.js.map +1 -1
  13. package/dist/apply-enter-plan.d.ts +9 -7
  14. package/dist/apply-enter-plan.js +40 -27
  15. package/dist/apply-enter-plan.js.map +1 -1
  16. package/dist/apply-local-work.d.ts +8 -20
  17. package/dist/apply-local-work.js +18 -95
  18. package/dist/apply-local-work.js.map +1 -1
  19. package/dist/apply-showing.d.ts +15 -1
  20. package/dist/apply-showing.js +26 -4
  21. package/dist/apply-showing.js.map +1 -1
  22. package/dist/apply-window-ground.d.ts +7 -9
  23. package/dist/apply-window-ground.js +16 -11
  24. package/dist/apply-window-ground.js.map +1 -1
  25. package/dist/apply-window-host.d.ts +29 -4
  26. package/dist/apply-window-host.js +212 -280
  27. package/dist/apply-window-host.js.map +1 -1
  28. package/dist/apply-window-line.d.ts +2 -1
  29. package/dist/apply-window-line.js +5 -4
  30. package/dist/apply-window-line.js.map +1 -1
  31. package/dist/apply-window-recovery.js +18 -30
  32. package/dist/apply-window-recovery.js.map +1 -1
  33. package/dist/apply-window-reveal.d.ts +0 -7
  34. package/dist/apply-window-reveal.js +5 -48
  35. package/dist/apply-window-reveal.js.map +1 -1
  36. package/dist/apply-window-rows.d.ts +1 -24
  37. package/dist/apply-window-rows.js.map +1 -1
  38. package/dist/apply-window-saves.d.ts +16 -9
  39. package/dist/apply-window-saves.js +65 -19
  40. package/dist/apply-window-saves.js.map +1 -1
  41. package/dist/apply-window-store.d.ts +6 -6
  42. package/dist/apply-window-store.js +7 -4
  43. package/dist/apply-window-store.js.map +1 -1
  44. package/dist/apply-window-verify.d.ts +4 -7
  45. package/dist/apply-window-verify.js +4 -23
  46. package/dist/apply-window-verify.js.map +1 -1
  47. package/dist/baseline-content.d.ts +3 -5
  48. package/dist/baseline-content.js +7 -44
  49. package/dist/baseline-content.js.map +1 -1
  50. package/dist/content-cache-retention.d.ts +3 -2
  51. package/dist/content-cache-retention.js +11 -11
  52. package/dist/content-cache-retention.js.map +1 -1
  53. package/dist/content-capture-pool.d.ts +4 -47
  54. package/dist/content-capture-pool.js +3 -42
  55. package/dist/content-capture-pool.js.map +1 -1
  56. package/dist/content-capture-worker.d.ts +2 -3
  57. package/dist/content-capture-worker.js +2 -19
  58. package/dist/content-capture-worker.js.map +1 -1
  59. package/dist/declaration-absorption.d.ts +9 -15
  60. package/dist/declaration-absorption.js +14 -32
  61. package/dist/declaration-absorption.js.map +1 -1
  62. package/dist/declaration-commit.d.ts +0 -5
  63. package/dist/declaration-commit.js +1 -6
  64. package/dist/declaration-commit.js.map +1 -1
  65. package/dist/declaration-save.d.ts +0 -4
  66. package/dist/declaration-save.js +0 -4
  67. package/dist/declaration-save.js.map +1 -1
  68. package/dist/detection/accepted-result.js +1 -1
  69. package/dist/detection/accepted-result.js.map +1 -1
  70. package/dist/detection/admission-save.d.ts +7 -17
  71. package/dist/detection/admission-save.js +4 -11
  72. package/dist/detection/admission-save.js.map +1 -1
  73. package/dist/detection/admission-units.d.ts +10 -26
  74. package/dist/detection/admission-units.js +12 -50
  75. package/dist/detection/admission-units.js.map +1 -1
  76. package/dist/detection/apply-ownership.d.ts +2 -2
  77. package/dist/detection/apply-ownership.js +2 -7
  78. package/dist/detection/apply-ownership.js.map +1 -1
  79. package/dist/detection/capture-outcome.js +12 -19
  80. package/dist/detection/capture-outcome.js.map +1 -1
  81. package/dist/detection/dispositions.d.ts +1 -1
  82. package/dist/detection/dispositions.js +3 -4
  83. package/dist/detection/dispositions.js.map +1 -1
  84. package/dist/detection/ground-proof.d.ts +1 -3
  85. package/dist/detection/ground-proof.js +0 -9
  86. package/dist/detection/ground-proof.js.map +1 -1
  87. package/dist/detection/ground-reader.d.ts +1 -5
  88. package/dist/detection/ground-reader.js +1 -31
  89. package/dist/detection/ground-reader.js.map +1 -1
  90. package/dist/detection/notebook-basis.d.ts +1 -2
  91. package/dist/detection/notebook-basis.js +2 -4
  92. package/dist/detection/notebook-basis.js.map +1 -1
  93. package/dist/detection/owed-selection.d.ts +2 -3
  94. package/dist/detection/owed-selection.js +3 -6
  95. package/dist/detection/owed-selection.js.map +1 -1
  96. package/dist/detection/portable.d.ts +7 -48
  97. package/dist/detection/portable.js +46 -155
  98. package/dist/detection/portable.js.map +1 -1
  99. package/dist/detection/repository-state.d.ts +35 -0
  100. package/dist/detection/repository-state.js +51 -0
  101. package/dist/detection/repository-state.js.map +1 -0
  102. package/dist/detection/root-examination.d.ts +1 -11
  103. package/dist/detection/root-examination.js +69 -127
  104. package/dist/detection/root-examination.js.map +1 -1
  105. package/dist/detection/runtime.d.ts +8 -32
  106. package/dist/detection/runtime.js +36 -140
  107. package/dist/detection/runtime.js.map +1 -1
  108. package/dist/detection/scope-frame.d.ts +32 -62
  109. package/dist/detection/scope-frame.js +139 -214
  110. package/dist/detection/scope-frame.js.map +1 -1
  111. package/dist/detection/scoped-identity-port.d.ts +1 -1
  112. package/dist/detection/scoped-identity-port.js +3 -4
  113. package/dist/detection/scoped-identity-port.js.map +1 -1
  114. package/dist/detection/walk-law.d.ts +3 -11
  115. package/dist/detection/walk-law.js +5 -9
  116. package/dist/detection/walk-law.js.map +1 -1
  117. package/dist/git/ground-owners.d.ts +8 -0
  118. package/dist/git/ground-owners.js +25 -0
  119. package/dist/git/ground-owners.js.map +1 -0
  120. package/dist/git/home.d.ts +39 -0
  121. package/dist/git/home.js +81 -0
  122. package/dist/git/home.js.map +1 -0
  123. package/dist/git/marker.d.ts +21 -0
  124. package/dist/git/marker.js +30 -0
  125. package/dist/git/marker.js.map +1 -0
  126. package/dist/git/objects.d.ts +42 -0
  127. package/dist/git/objects.js +144 -0
  128. package/dist/git/objects.js.map +1 -0
  129. package/dist/git/rail.d.ts +90 -0
  130. package/dist/git/rail.js +341 -0
  131. package/dist/git/rail.js.map +1 -0
  132. package/dist/git/read-state.d.ts +21 -0
  133. package/dist/git/read-state.js +143 -0
  134. package/dist/git/read-state.js.map +1 -0
  135. package/dist/git/repository.d.ts +48 -0
  136. package/dist/git/repository.js +110 -0
  137. package/dist/git/repository.js.map +1 -0
  138. package/dist/git/write-files.d.ts +9 -0
  139. package/dist/git/write-files.js +125 -0
  140. package/dist/git/write-files.js.map +1 -0
  141. package/dist/git-binding.d.ts +0 -53
  142. package/dist/git-binding.js +3 -114
  143. package/dist/git-binding.js.map +1 -1
  144. package/dist/git-command.js +11 -2
  145. package/dist/git-command.js.map +1 -1
  146. package/dist/git-index-entries.d.ts +7 -15
  147. package/dist/git-index-entries.js +3 -41
  148. package/dist/git-index-entries.js.map +1 -1
  149. package/dist/git-index-format.d.ts +4 -7
  150. package/dist/git-index-format.js +41 -106
  151. package/dist/git-index-format.js.map +1 -1
  152. package/dist/graph-publication.d.ts +6 -7
  153. package/dist/graph-publication.js +9 -21
  154. package/dist/graph-publication.js.map +1 -1
  155. package/dist/ground-basis.d.ts +1 -37
  156. package/dist/ground-basis.js +5 -162
  157. package/dist/ground-basis.js.map +1 -1
  158. package/dist/ground-database.js +0 -22
  159. package/dist/ground-database.js.map +1 -1
  160. package/dist/ground-install-saves.d.ts +0 -4
  161. package/dist/ground-install-saves.js +0 -4
  162. package/dist/ground-install-saves.js.map +1 -1
  163. package/dist/ground-inventory-schema.js +0 -3
  164. package/dist/ground-inventory-schema.js.map +1 -1
  165. package/dist/ground-marks.d.ts +7 -33
  166. package/dist/ground-marks.js +8 -55
  167. package/dist/ground-marks.js.map +1 -1
  168. package/dist/ground-relations.d.ts +2 -2
  169. package/dist/ground-relations.js +5 -10
  170. package/dist/ground-relations.js.map +1 -1
  171. package/dist/ground-row.d.ts +0 -7
  172. package/dist/ground-row.js +7 -12
  173. package/dist/ground-row.js.map +1 -1
  174. package/dist/ground-save-ops.d.ts +2 -1
  175. package/dist/ground-save-ops.js +2 -1
  176. package/dist/ground-save-ops.js.map +1 -1
  177. package/dist/ground-store.d.ts +0 -10
  178. package/dist/ground-store.js +19 -131
  179. package/dist/ground-store.js.map +1 -1
  180. package/dist/materialize-records.d.ts +19 -20
  181. package/dist/materialize-records.js +123 -244
  182. package/dist/materialize-records.js.map +1 -1
  183. package/dist/materialized-graph.d.ts +3 -22
  184. package/dist/materialized-graph.js +1 -142
  185. package/dist/materialized-graph.js.map +1 -1
  186. package/dist/received-state.d.ts +4 -6
  187. package/dist/received-state.js +6 -11
  188. package/dist/received-state.js.map +1 -1
  189. package/dist/root-install.d.ts +1 -2
  190. package/dist/root-install.js +2 -11
  191. package/dist/root-install.js.map +1 -1
  192. package/dist/sharing-admission.d.ts +1 -2
  193. package/dist/sharing-admission.js +8 -77
  194. package/dist/sharing-admission.js.map +1 -1
  195. package/dist/source-witness.d.ts +1 -7
  196. package/dist/source-witness.js +0 -12
  197. package/dist/source-witness.js.map +1 -1
  198. package/dist/user-ground-host.d.ts +21 -35
  199. package/dist/user-ground-host.js +423 -1484
  200. package/dist/user-ground-host.js.map +1 -1
  201. package/npm-shrinkwrap.json +24 -24
  202. package/package.json +5 -5
  203. package/dist/apply-window-repository.d.ts +0 -97
  204. package/dist/apply-window-repository.js +0 -464
  205. package/dist/apply-window-repository.js.map +0 -1
  206. package/dist/detection/codec-standing.d.ts +0 -27
  207. package/dist/detection/codec-standing.js +0 -86
  208. package/dist/detection/codec-standing.js.map +0 -1
  209. package/dist/detection/git-notice.d.ts +0 -104
  210. package/dist/detection/git-notice.js +0 -483
  211. package/dist/detection/git-notice.js.map +0 -1
  212. package/dist/detection/held-survey.d.ts +0 -39
  213. package/dist/detection/held-survey.js +0 -105
  214. package/dist/detection/held-survey.js.map +0 -1
  215. package/dist/detection/held-territory.d.ts +0 -73
  216. package/dist/detection/held-territory.js +0 -266
  217. package/dist/detection/held-territory.js.map +0 -1
  218. package/dist/detection/name-reach.d.ts +0 -12
  219. package/dist/detection/name-reach.js +0 -28
  220. package/dist/detection/name-reach.js.map +0 -1
  221. package/dist/detection/own-channel.d.ts +0 -17
  222. package/dist/detection/own-channel.js +0 -31
  223. package/dist/detection/own-channel.js.map +0 -1
  224. package/dist/detection/repository-publication.d.ts +0 -22
  225. package/dist/detection/repository-publication.js +0 -81
  226. package/dist/detection/repository-publication.js.map +0 -1
  227. package/dist/detection/repository-routes.d.ts +0 -50
  228. package/dist/detection/repository-routes.js +0 -118
  229. package/dist/detection/repository-routes.js.map +0 -1
  230. package/dist/detection/repository-seals.d.ts +0 -98
  231. package/dist/detection/repository-seals.js +0 -145
  232. package/dist/detection/repository-seals.js.map +0 -1
  233. package/dist/detection/seal-law.d.ts +0 -59
  234. package/dist/detection/seal-law.js +0 -103
  235. package/dist/detection/seal-law.js.map +0 -1
  236. package/dist/git-capture.d.ts +0 -47
  237. package/dist/git-capture.js +0 -153
  238. package/dist/git-capture.js.map +0 -1
  239. package/dist/git-card.d.ts +0 -30
  240. package/dist/git-card.js +0 -136
  241. package/dist/git-card.js.map +0 -1
  242. package/dist/git-checkpoint-construction.d.ts +0 -54
  243. package/dist/git-checkpoint-construction.js +0 -126
  244. package/dist/git-checkpoint-construction.js.map +0 -1
  245. package/dist/git-checkpoint-preparation.d.ts +0 -47
  246. package/dist/git-checkpoint-preparation.js +0 -201
  247. package/dist/git-checkpoint-preparation.js.map +0 -1
  248. package/dist/git-configuration.d.ts +0 -53
  249. package/dist/git-configuration.js +0 -238
  250. package/dist/git-configuration.js.map +0 -1
  251. package/dist/git-evidence.d.ts +0 -50
  252. package/dist/git-evidence.js +0 -114
  253. package/dist/git-evidence.js.map +0 -1
  254. package/dist/git-facts.d.ts +0 -2
  255. package/dist/git-facts.js +0 -35
  256. package/dist/git-facts.js.map +0 -1
  257. package/dist/git-index-witness.d.ts +0 -34
  258. package/dist/git-index-witness.js +0 -85
  259. package/dist/git-index-witness.js.map +0 -1
  260. package/dist/git-literal-batch.d.ts +0 -82
  261. package/dist/git-literal-batch.js +0 -152
  262. package/dist/git-literal-batch.js.map +0 -1
  263. package/dist/git-literal-host.d.ts +0 -76
  264. package/dist/git-literal-host.js +0 -185
  265. package/dist/git-literal-host.js.map +0 -1
  266. package/dist/git-literal-read.d.ts +0 -74
  267. package/dist/git-literal-read.js +0 -186
  268. package/dist/git-literal-read.js.map +0 -1
  269. package/dist/git-literal-replay.d.ts +0 -83
  270. package/dist/git-literal-replay.js +0 -393
  271. package/dist/git-literal-replay.js.map +0 -1
  272. package/dist/git-native-file.d.ts +0 -42
  273. package/dist/git-native-file.js +0 -145
  274. package/dist/git-native-file.js.map +0 -1
  275. package/dist/git-native-index.d.ts +0 -27
  276. package/dist/git-native-index.js +0 -44
  277. package/dist/git-native-index.js.map +0 -1
  278. package/dist/git-operation-host.d.ts +0 -42
  279. package/dist/git-operation-host.js +0 -115
  280. package/dist/git-operation-host.js.map +0 -1
  281. package/dist/git-private-repository.d.ts +0 -4
  282. package/dist/git-private-repository.js +0 -66
  283. package/dist/git-private-repository.js.map +0 -1
  284. package/dist/git-private-view.d.ts +0 -72
  285. package/dist/git-private-view.js +0 -318
  286. package/dist/git-private-view.js.map +0 -1
  287. package/dist/git-records.d.ts +0 -29
  288. package/dist/git-records.js +0 -119
  289. package/dist/git-records.js.map +0 -1
  290. package/dist/git-ref-store.d.ts +0 -12
  291. package/dist/git-ref-store.js +0 -68
  292. package/dist/git-ref-store.js.map +0 -1
  293. package/dist/git-registration-host.d.ts +0 -42
  294. package/dist/git-registration-host.js +0 -98
  295. package/dist/git-registration-host.js.map +0 -1
  296. package/dist/git-repository-host.d.ts +0 -291
  297. package/dist/git-repository-host.js +0 -1291
  298. package/dist/git-repository-host.js.map +0 -1
  299. package/dist/git-spelling.d.ts +0 -41
  300. package/dist/git-spelling.js +0 -233
  301. package/dist/git-spelling.js.map +0 -1
  302. package/dist/git-tree-objects.d.ts +0 -22
  303. package/dist/git-tree-objects.js +0 -205
  304. package/dist/git-tree-objects.js.map +0 -1
  305. package/dist/git-worktree-host.d.ts +0 -2
  306. package/dist/git-worktree-host.js +0 -16
  307. package/dist/git-worktree-host.js.map +0 -1
  308. package/dist/ground-territory.d.ts +0 -106
  309. package/dist/ground-territory.js +0 -340
  310. package/dist/ground-territory.js.map +0 -1
  311. package/dist/repository-checkpoint-file.d.ts +0 -20
  312. package/dist/repository-checkpoint-file.js +0 -129
  313. package/dist/repository-checkpoint-file.js.map +0 -1
  314. package/dist/repository-statement.d.ts +0 -21
  315. package/dist/repository-statement.js +0 -33
  316. package/dist/repository-statement.js.map +0 -1
  317. package/dist/reveal-owner.d.ts +0 -16
  318. package/dist/reveal-owner.js +0 -74
  319. package/dist/reveal-owner.js.map +0 -1
@@ -1,1291 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { closeSync, createReadStream, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readSync, renameSync, rmSync, unlinkSync, writeFileSync, } from "node:fs";
3
- import { mkdtemp, open, readFile, rm, writeFile } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { dirname, join, resolve } from "node:path";
6
- import { applyRepositoryIdentitySteps, cardIdSteps, checkpointIdSteps, deriveStateId, digestSteps, encodeRepositoryTransportSteps, expectedRepositorySteps, inspectRepositoryTransportSteps, ITEMS_PER_BOUNDARY, portableFileMode, repositoryIdentityChangesSteps, repositoryIdentityDelta, repositoryIdentityHashSteps, repositoryIdentityMapSteps, repositoryApplyTerritory, repositoryPayloadVersion, repositoryTransportMetadataBytes, shownCheckpointSteps, } from "@amalgm/live";
7
- import { isLocalOnlyPath } from "@amalgm/core/identity";
8
- import { gitHost, gitText, runGit } from "./git-command.js";
9
- import { gitOperationWitness, mergeOperation, refuseUnsupportedGitOperation } from "./git-operation-host.js";
10
- import { readRevealMarker, REVEAL_MARKER, revealStorageOf, revealStoragePhysical, writeRevealMarker, } from "./reveal-owner.js";
11
- import { atomicWriteIn, ensureDirBeneath } from "./filesystem.js";
12
- import { CaptureSourceChangedError, hashContentFile, writeCacheHint } from "./content-cache-host.js";
13
- import { checkpointEvidenceFromFile, proveRepositoryTransportFile } from "./repository-checkpoint-file.js";
14
- import { createSha256, sha256Hex } from "./sha256.js";
15
- import { literalRepositoryIdentitySteps, literalRepositoryIdentityMapSteps, collectLiteralRepositoryView, observeLiteralPaths, } from "./git-literal-host.js";
16
- import { leafPayload, leafShows } from "./git-literal-read.js";
17
- import { repositoryStatement } from "./repository-statement.js";
18
- import { PrivateGitView } from "./git-private-view.js";
19
- import { gitWriter, installLiteralCheckpoint } from "./git-literal-replay.js";
20
- import { prepareLiteralCheckpoint, } from "./git-checkpoint-preparation.js";
21
- import { withinGitBoundary } from "./git-index-entries.js";
22
- import { accountedPaths, checkpointReads, constructLiteralCheckpoint, independentOf, } from "./git-checkpoint-construction.js";
23
- import { optionalLstat, PhysicalPathWitnesses } from "./physical-path-witness.js";
24
- import { recordFileDurability } from "./durability-barrier.js";
25
- import { flushEach } from "./flush.js";
26
- import { GitCapture } from "./git-capture.js";
27
- import { identityMembers } from "./git-spelling.js";
28
- import { stashList } from "./git-card.js";
29
- import { concatInTurns, eachInTurns, finishStepsInTurns, mapInTurns, turnBoundary } from "./turns.js";
30
- import { looseRefs } from "./git-ref-store.js";
31
- import { checkoutObject, gitStorageDirectory, gitStorageOutside, namesGitRepository } from "./git-binding.js";
32
- import { settleAll } from "./settled.js";
33
- import { admissionProof, closeSource, sourceProofs, witnessProof } from "./source-proof.js";
34
- import { physicalKey, sourceSignature } from "./source-signature.js";
35
- const bufferView = (bytes) => Buffer.isBuffer(bytes)
36
- ? bytes
37
- : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
38
- /** What one lstat of `directory`'s `.git` entry says, with Git's own test of
39
- * the storage it names, followed through a link as Git follows it. */
40
- export const gitMarker = (directory, marker) => {
41
- const kind = marker.isDirectory() ? "directory" : marker.isFile() ? "file" : marker.isSymbolicLink() ? "link" : "other";
42
- return { physicalKey: physicalKey(marker), kind, repository: kind !== "other" && namesGitRepository(directory, marker) };
43
- };
44
- /** The `.git` entry as it stands now; null when absent. */
45
- export function observeGitMarker(directory) {
46
- try {
47
- return gitMarker(directory, lstatSync(join(directory, ".git"), { bigint: true }));
48
- }
49
- catch (error) {
50
- const code = error.code;
51
- if (code === "ENOENT" || code === "ENOTDIR")
52
- return null;
53
- throw error;
54
- }
55
- }
56
- /** Classification observes only the filesystem: a `.git` Git cannot use is
57
- * no repository, and its folder is ordinary ground. Git command health
58
- * belongs to Card + Checkpoint capture and cannot demote repository ground. */
59
- export const marksRepository = (marker) => marker?.repository ?? false;
60
- export const hasGitMarker = (directory) => marksRepository(observeGitMarker(directory));
61
- /** The nested repositories a reading of `identity`'s repository must not enter. */
62
- export function nestedRepositoryPaths(identity) {
63
- return identity
64
- .filter((entry) => entry.type === "repo.git")
65
- .map((entry) => entry.path)
66
- .sort();
67
- }
68
- /** The common `.git` directory needs no Git invocation; a `.git` file
69
- * (worktree, submodule) is resolved by Git itself. */
70
- const gitDirectory = (repository) => gitStorageDirectory(repository).directory;
71
- /** Beneath the reveal marker every repository state is the reveal's own, so a
72
- * Git lock there is one an interrupted attempt left: its index lock, or the
73
- * lock of a ref, HEAD, config, packed-refs or shallow update it ran. Each
74
- * would refuse the resumed attempt's same write forever. Apply refuses shared
75
- * worktree storage, so this storage holds every lock its writes take. */
76
- async function clearInterruptedLocks(storage) {
77
- const cleared = new Set();
78
- const visit = (directory, recurse) => {
79
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
80
- const path = join(directory, entry.name);
81
- if (entry.isDirectory()) {
82
- if (recurse)
83
- visit(path, true);
84
- }
85
- else if (entry.name.endsWith(".lock")) {
86
- unlinkSync(path);
87
- cleared.add(directory);
88
- }
89
- }
90
- };
91
- visit(storage, false);
92
- if (existsSync(join(storage, "refs")))
93
- visit(join(storage, "refs"), true);
94
- await flushEach([], cleared);
95
- }
96
- /** Begins a reveal, or resumes the one its marker journals.
97
- *
98
- * The reveal marker is the repository's own journal of an unfinished Apply
99
- * on working ground: durable before the first repository effect, durably
100
- * gone before the reveal returns. It names the attempt whose receipt owns
101
- * the reveal (src/reveal-owner.ts), and that receipt froze, at binding,
102
- * whether the reveal creates the repository's storage. Working ground never
103
- * shows a `.git` without its marker: a fresh `.git` is assembled at the
104
- * caller's private staging path and renamed in whole, so a crash can leave
105
- * only the owner's resumable journal, never a bare marker a person or Detect
106
- * could mistake for a repository. Storage that stood must be the storage the
107
- * receipt bound; it takes this attempt's marker, replacing any a finished or
108
- * released attempt left, since the line holds one intent. A resumed reveal
109
- * first clears the locks its interrupted attempt left.
110
- *
111
- * Owned ground has no receipt, no reader but its own install, and no
112
- * durability but that install's one barrier, so it journals nothing: fresh
113
- * storage is created in place, and standing storage is an earlier state of
114
- * the same install, which the import's acceptance completes. */
115
- async function beginRepositoryReveal(repository, ground, fresh) {
116
- if (ground.kind === "owned") {
117
- if (fresh) {
118
- rmSync(join(repository, ".git"), { recursive: true, force: true });
119
- mkdirSync(join(repository, ".git"));
120
- }
121
- return;
122
- }
123
- const { attempt } = ground.reveal;
124
- const standing = revealStorageOf(repository);
125
- if (standing !== null && readRevealMarker(standing) === attempt) {
126
- await clearInterruptedLocks(standing);
127
- return;
128
- }
129
- if (!fresh) {
130
- if (standing === null || revealStoragePhysical(standing) !== ground.reveal.storage) {
131
- throw new Error("The repository's Git storage is not the storage this reveal bound");
132
- }
133
- await writeRevealMarker(standing, attempt);
134
- return;
135
- }
136
- if (optionalLstat(join(repository, ".git"))) {
137
- throw new Error("A Git marker stands where this reveal creates the repository's storage");
138
- }
139
- const storage = ground.staging;
140
- rmSync(storage, { recursive: true, force: true });
141
- mkdirSync(storage);
142
- await writeRevealMarker(storage, attempt);
143
- renameSync(storage, join(repository, ".git"));
144
- await flushEach([], [repository]);
145
- }
146
- async function finishRepositoryReveal(repository, ground) {
147
- if (ground.kind === "owned")
148
- return;
149
- const storage = gitDirectory(repository);
150
- rmSync(join(storage, REVEAL_MARKER), { force: true });
151
- await flushEach([], [storage]);
152
- }
153
- const CAPTURE_ATTEMPTS = 3;
154
- /** The first attempt uses the caller's capture; a source that moved while
155
- * it was read is asked again from a fresh one. */
156
- async function retrySourceChange(capture, operation) {
157
- for (let attempt = 0;; attempt += 1) {
158
- try {
159
- return await operation(attempt === 0 ? capture : new GitCapture(capture.repository));
160
- }
161
- catch (error) {
162
- if (!(error instanceof CaptureSourceChangedError) || attempt + 1 >= CAPTURE_ATTEMPTS)
163
- throw error;
164
- }
165
- }
166
- }
167
- /** One collected repository moment over its walked members, with its
168
- * unclosed source. Detect retains the proof and closes it once, at the
169
- * admission that trusts it; Apply's readback closes it itself. */
170
- async function collectState(capture, members, nestedRepositories, lane, proven) {
171
- const directory = gitDirectory(capture.repository);
172
- refuseUnsupportedGitOperation(directory);
173
- // Asked together, answered in order.
174
- const [configuration, { value: card, proof: cardProof }, operation, view] = await settleAll([
175
- capture.configuration(), capture.card(), Promise.resolve().then(() => mergeOperation(directory)),
176
- collectLiteralRepositoryView(capture, members, nestedRepositories, lane, proven)
177
- ]);
178
- const checkpoint = {
179
- baseCommit: card.head.commit, branch: card.head.branch,
180
- stagedPatch: view.stagedPatch, unstagedPatch: view.unstagedPatch, indexFlags: view.indexFlags,
181
- unmerged: view.unmerged, untracked: view.untracked, operation,
182
- };
183
- const cardId = await finishStepsInTurns(cardIdSteps(card, createSha256));
184
- const checkpointId = await finishStepsInTurns(checkpointIdSteps(checkpoint, createSha256));
185
- // Operation markers are native files in the observed Git directory, so
186
- // admission re-reads them with the other physical witnesses.
187
- const markers = witnessProof([gitOperationWitness(directory, operation)]);
188
- const proof = sourceProofs([cardProof, configuration, markers, view.proof]);
189
- return { capture, state: { stateId: deriveStateId(cardId, checkpointId, sha256Hex),
190
- cardId, checkpointId, card, checkpoint, pack: null }, view, configuration, proof };
191
- }
192
- /** Physical observation for publication. Selection and package sealing have
193
- * not happened; the caller retains this source proof, unclosed, and its
194
- * admission closes it once. */
195
- export function observeRepositoryForPublication(capture, identity, lane, proven) {
196
- return retrySourceChange(capture, attempt => collectState(attempt, identityMembers(identity), nestedRepositoryPaths(identity), lane, proven));
197
- }
198
- /** Seal an observation when publication selected every observed member. No
199
- * second Git/worktree observation is necessary; the original proof still
200
- * closes once, at admission. */
201
- export async function captureObservedRepository(observed, identity, observedIdentity, basis) {
202
- return sealRepository(observed, await selectedLiteralIdentity(identity, observed.view, observedIdentity), observed.view.leaves, basis);
203
- }
204
- /** The literal identity of the selected members. Publication usually selects
205
- * exactly the observed members, whose literal map the observation already
206
- * derived: equal paths and UUIDs, where a leaf's type and payload come from
207
- * the same view and every other entry must match as recorded. */
208
- async function selectedLiteralIdentity(selected, view, observed) {
209
- const derived = () => finishStepsInTurns(literalRepositoryIdentityMapSteps(selected, view));
210
- if (selected.length !== observed.entries.length)
211
- return derived();
212
- const byPath = new Map();
213
- await eachInTurns(observed.entries, entry => byPath.set(entry.path, entry));
214
- let visited = 0;
215
- for (const entry of selected) {
216
- const other = byPath.get(entry.path);
217
- if (other?.uuid !== entry.uuid || !(view.leaves.has(entry.path)
218
- || (other.type === entry.type && (other.payloadVersion ?? null) === (entry.payloadVersion ?? null))))
219
- return derived();
220
- if (++visited % ITEMS_PER_BOUNDARY === 0)
221
- await turnBoundary();
222
- }
223
- return observed;
224
- }
225
- /** The same Card + Checkpoint without the untracked names a caller accounts
226
- * for separately. */
227
- async function withoutUntracked(state, omitted) {
228
- const untracked = [];
229
- await eachInTurns(state.checkpoint.untracked, file => { if (!omitted(file.path))
230
- untracked.push(file); });
231
- const checkpoint = { ...state.checkpoint, untracked };
232
- const checkpointId = await finishStepsInTurns(checkpointIdSteps(checkpoint, createSha256));
233
- return { ...state, checkpoint, checkpointId, stateId: deriveStateId(state.cardId, checkpointId, sha256Hex) };
234
- }
235
- /** The id of what a reading that never enters `hidden` shows of a
236
- * Checkpoint whose own id is `id` (Live shownCheckpointSteps): `id` itself
237
- * when nothing it holds is hidden. */
238
- async function shownCheckpointIdOf(checkpoint, hidden, id) {
239
- const shown = await finishStepsInTurns(shownCheckpointSteps(checkpoint, hidden));
240
- return shown === checkpoint ? id : finishStepsInTurns(checkpointIdSteps(shown, createSha256));
241
- }
242
- /** The Checkpoint id a reading confined to `territory` takes from the
243
- * package in `file`: its own on an exact territory, else the package with
244
- * its silent ground dropped. */
245
- async function shownCheckpointId(file, layout, territory) {
246
- if (territory.exact)
247
- return layout.checkpointId;
248
- return shownCheckpointIdOf(await checkpointEvidenceFromFile(file, layout), territory.silent, layout.checkpointId);
249
- }
250
- const cardTips = (card) => [...new Set([
251
- ...(card.head.commit ? [card.head.commit] : []),
252
- ...card.refs.flatMap((ref) => ref.kind === "direct" ? [ref.commit] : []),
253
- ...card.stash.map((entry) => entry.commit),
254
- ])];
255
- /** The commits a state names: its Card tips and an unfinished merge's heads. */
256
- const stateCommits = (state) => [...new Set([...cardTips(state.card), ...(state.checkpoint.operation?.heads ?? [])])];
257
- /** Every object a state's pack delivers: its commits and each conflict
258
- * stage. A gitlink records a commit owned by the nested repository, which
259
- * the outer repository preserves as an opaque index value but never packs. */
260
- const stateWants = (state) => [...new Set([...stateCommits(state),
261
- ...state.checkpoint.unmerged.flatMap((entry) => entry.stages
262
- .filter((stage) => stage.mode !== "160000").map((stage) => stage.objectId))])];
263
- /** The previous boundaries the receiver holds: those its tips reach under
264
- * the horizon it received. */
265
- async function receiverHolds(binding, horizon, tips, boundaries) {
266
- const receiver = await PrivateGitView.open(binding, horizon);
267
- try {
268
- return [...(await receiver.reached(tips, boundaries)).keys()];
269
- }
270
- finally {
271
- await receiver.close();
272
- }
273
- }
274
- /** Produce the same native thin-pack work as upload-pack: current wants minus
275
- * receiver haves. Ref updates and Amalgm metadata remain outside the pack. */
276
- async function nativePack(binding, current, previous) {
277
- const commits = stateCommits(current);
278
- const wants = stateWants(current);
279
- if (wants.length === 0)
280
- return null;
281
- const scratch = await mkdtemp(join(tmpdir(), "amalgm-repo-pack-"));
282
- const file = join(scratch, "repository.pack");
283
- try {
284
- const view = await PrivateGitView.open(binding, current.card.shallow);
285
- try {
286
- // The receiver holds each previous tip's closure under the previous
287
- // horizon. A previous boundary this horizon moved past (Git's
288
- // unshallow) is a commit it holds, if at all, without its parents. As
289
- // upload-pack does, every traversal stops at those boundaries, so the
290
- // haves subtract only what the receiver holds; each one this state
291
- // reaches wants its parents, so the history newly exposed beneath it
292
- // travels; and each one the receiver holds is an edge, so its tree
293
- // never travels again.
294
- const boundary = new Set(current.card.shallow ?? []);
295
- const received = previous?.shallow ?? [];
296
- const unshallowed = received.filter(commit => !boundary.has(commit));
297
- const haves = previous ? await view.present(cardTips(previous)) : [];
298
- const [exposed, held] = unshallowed.length ? await settleAll([
299
- view.reached(commits, unshallowed).then(found => [...found.values()].flat()),
300
- receiverHolds(binding, received, haves, unshallowed),
301
- ]) : [[], []];
302
- const revisions = Buffer.from([
303
- ...unshallowed.map(commit => `--shallow ${commit}`),
304
- ...new Set([...wants, ...exposed]),
305
- ...[...haves, ...held].map(commit => `^${commit}`), "",
306
- ].join("\n"), "utf8");
307
- await view.exportPack(revisions, file, received.length > 0);
308
- }
309
- finally {
310
- await view.close();
311
- }
312
- const bytes = await readFile(file);
313
- if (bytes.byteLength < 12 || bytes.subarray(0, 4).toString("ascii") !== "PACK") {
314
- throw new Error("Git produced an invalid repository pack");
315
- }
316
- if (bytes.readUInt32BE(8) === 0)
317
- return null;
318
- return { bytes, sha256: await finishStepsInTurns(digestSteps(bytes, createSha256)) };
319
- }
320
- finally {
321
- await rm(scratch, { recursive: true, force: true });
322
- }
323
- }
324
- /** Content-addressed cache bytes are evidence, not ground. A cached head that
325
- * cannot prove the row's declared state is a cache miss, never a Detect fault. */
326
- export async function readPriorRepositoryTransport(cacheDir, row) {
327
- if (row?.type !== "repo.git" || !row.payloadVersion || !row.transportVersion)
328
- return null;
329
- const file = join(cacheDir, `${row.transportVersion}.bin`);
330
- try {
331
- const layout = await inspectRepositoryTransportFile(file);
332
- if (repositoryPayloadVersion(layout, sha256Hex) === row.payloadVersion) {
333
- return { file, transportVersion: row.transportVersion, layout };
334
- }
335
- }
336
- catch (error) {
337
- if (error.code === "ENOENT")
338
- return null;
339
- // An unreadable envelope is the same miss.
340
- }
341
- await rm(file, { force: true });
342
- return null;
343
- }
344
- export function pairRepositoryObservation(uuid, directory, observed, identityHash) {
345
- const payloadVersion = repositoryPayloadVersion({ stateId: observed.state.stateId, identityHash }, sha256Hex);
346
- return observationPair(uuid, directory, payloadVersion, observed.configuration, observed.view.sourceBinding, observed.proof);
347
- }
348
- /** The one pairing formula: a configuration stamp names the complete observed
349
- * payload and the repository directory the Git binding resolved. */
350
- function observationPair(uuid, directory, payloadVersion, configuration, binding, proof) {
351
- const checkout = checkoutObject(binding);
352
- return Object.freeze({ uuid, absolutePath: directory, payloadVersion,
353
- gitConfigurationObservation: configuration.stamp(uuid, payloadVersion, binding),
354
- physicalKey: checkout.physicalKey, filesystemMode: checkout.mode, proof });
355
- }
356
- /** One closed reading of a repository's ground. A leaf `proven` names is
357
- * that Git object while its proof holds (ProvenLeaf), so only leaves no
358
- * proof names are read. */
359
- export function readRepository(repository, boundaries, lane, proven) {
360
- return retrySourceChange(new GitCapture(repository), attempt => readRepositoryAttempt(attempt, boundaries, lane, proven));
361
- }
362
- const repositoryDirectoryStats = (path) => {
363
- const stat = lstatSync(path, { bigint: true });
364
- if (!stat.isDirectory() || stat.isSymbolicLink())
365
- throw new CaptureSourceChangedError("repository directory changed kind");
366
- return stat;
367
- };
368
- const repositoryDirectoryWitness = (path) => {
369
- return sourceSignature(repositoryDirectoryStats(path));
370
- };
371
- /** Keep only witnesses; a cached Apply comparison must not retain patches,
372
- * untracked contents, conflict contents or the construction view's closure. */
373
- function repositoryNamespaceProof(source, witnesses) {
374
- const ordered = [...witnesses].sort(([a], [b]) => a.length - b.length);
375
- const check = (directory, witness) => {
376
- if (repositoryDirectoryWitness(directory) !== witness) {
377
- throw new CaptureSourceChangedError("repository namespace changed before reuse");
378
- }
379
- };
380
- return sourceProofs([source, admissionProof(() => {
381
- for (const [directory, witness] of ordered)
382
- check(directory, witness);
383
- for (let index = ordered.length - 1; index >= 0; index -= 1)
384
- check(...ordered[index]);
385
- })]);
386
- }
387
- async function readRepositoryAttempt(capture, boundaries, lane, proven) {
388
- const repository = capture.repository;
389
- const members = new Map();
390
- const directoryWitnesses = new Map();
391
- const walk = (directory, stats, prefix) => {
392
- directoryWitnesses.set(directory, sourceSignature(stats));
393
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
394
- if (entry.name.toLowerCase() === ".git" || isLocalOnlyPath(entry.name))
395
- continue;
396
- const path = prefix ? `${prefix}/${entry.name}` : entry.name;
397
- const absolute = join(directory, entry.name);
398
- if (boundaries.includes(path))
399
- members.set(path, { kind: "boundary" });
400
- else if (!entry.isDirectory())
401
- members.set(path, { kind: "leaf" });
402
- else if (hasGitMarker(absolute))
403
- members.set(path, { kind: "repository" });
404
- else {
405
- const child = repositoryDirectoryStats(absolute);
406
- members.set(path, { kind: "directory", stats: child });
407
- walk(absolute, child, path);
408
- }
409
- }
410
- };
411
- walk(repository, repositoryDirectoryStats(repository), "");
412
- // An unadmitted repository's ground is not this one's to read.
413
- const { state, view, configuration, proof: source } = await collectState(capture, function* () {
414
- for (const [path, { kind }] of members)
415
- yield { path, kind: kind === "repository" ? "directory" : kind };
416
- }(), boundaries, lane, proven);
417
- const proof = repositoryNamespaceProof(source, directoryWitnesses);
418
- await closeSource(proof);
419
- return { repository, boundaries: [...boundaries], state, view, configuration, members, proof };
420
- }
421
- /** Judge one reading against one identity and the remainder it may keep.
422
- * The identity is a territory's (Live repositoryApplyTerritory): each of its
423
- * nested repositories is a boundary the reading did not enter, and nothing
424
- * else it names lies within one. Remainder is accounted one member at a
425
- * time, never by an excluded ancestor: it must keep its type and stay
426
- * outside Git's index. */
427
- export async function judgeRepository(reading, identity, remainder) {
428
- const { boundaries, state, view, configuration, members, proof } = reading;
429
- const expected = new Map(), kept = new Map();
430
- let unread = false;
431
- await eachInTurns(identity, entry => {
432
- unread ||= entry.type === "repo.git" ? !boundaries.includes(entry.path) : withinGitBoundary(entry.path, boundaries);
433
- expected.set(entry.path, entry);
434
- });
435
- if (unread)
436
- throw new Error("repository reading is judged only under the boundaries it read");
437
- await eachInTurns(remainder, entry => { kept.set(entry.path, entry); });
438
- const { accounted } = view;
439
- const keptStats = new Map();
440
- // The identity travels as Git spells each member; the walk read the disk's spelling.
441
- const { spelling } = view;
442
- let identityMatches = spelling.complete;
443
- const respelled = spelling.differs ? new Set() : null;
444
- await eachInTurns(members, ([diskPath, member]) => {
445
- const path = spelling.portable(diskPath);
446
- respelled?.add(path);
447
- if (member.kind === "boundary")
448
- return;
449
- const wanted = expected.get(path) ?? kept.get(path);
450
- if (!wanted || (kept.has(path) && accounted.has(path)))
451
- identityMatches = false;
452
- if (member.kind === "repository")
453
- identityMatches = false;
454
- else if (member.kind === "directory") {
455
- if (wanted?.type !== "folder")
456
- identityMatches = false;
457
- else if (kept.has(path))
458
- keptStats.set(path, member.stats);
459
- }
460
- else if (!view.leaves.has(path))
461
- identityMatches = false;
462
- else if (kept.has(path)) {
463
- const leaf = view.leaves.get(path);
464
- if (leaf.type !== wanted.type)
465
- identityMatches = false;
466
- else
467
- keptStats.set(path, leaf.stats);
468
- }
469
- });
470
- const read = respelled ?? members;
471
- await eachInTurns(identity, entry => { if (entry.type !== "repo.git" && !read.has(entry.path))
472
- identityMatches = false; });
473
- const keptRemainder = [];
474
- await eachInTurns(remainder, entry => { if (keptStats.has(entry.path))
475
- keptRemainder.push(entry); });
476
- const expectedState = remainder.length === 0 ? state : await withoutUntracked(state, path => !expected.has(path));
477
- // One literal reading of the identity's members, then of the remainder kept.
478
- const observed = await finishStepsInTurns(literalRepositoryIdentitySteps(keptRemainder.length === 0 ? identity : [...identity, ...keptRemainder], view));
479
- const observedRemainder = observed.slice(identity.length);
480
- const observedIdentity = observedRemainder.length === 0 ? observed : observed.slice(0, identity.length);
481
- const identityHash = await finishStepsInTurns(repositoryIdentityHashSteps(observedIdentity, createSha256));
482
- const wholeHash = observedRemainder.length === 0 ? identityHash
483
- : await finishStepsInTurns(repositoryIdentityHashSteps(observed, createSha256));
484
- const observedPayload = repositoryPayloadVersion({ stateId: state.stateId, identityHash: wholeHash }, sha256Hex);
485
- const binding = view.sourceBinding;
486
- return { stateId: expectedState.stateId, identityHash, identityMatches, observedPayload,
487
- remainder: await mapInTurns(observedRemainder, entry => ({ entry, stats: keptStats.get(entry.path) })),
488
- proof,
489
- pair: (uuid, directory) => observationPair(uuid, directory, observedPayload, configuration, binding, proof) };
490
- }
491
- /** One observed repository moment shows a result exactly when it reads the
492
- * state the result shows and the identity it acts on, each member holding
493
- * its accepted payload. */
494
- export async function repositoryObservationMatches(observed, stateId, identity) {
495
- return observed.stateId === stateId && observed.identityMatches
496
- && observed.identityHash === await finishStepsInTurns(repositoryIdentityHashSteps(identity, createSha256));
497
- }
498
- const ordinaryMember = (entry) => ["file.text", "file.binary", "link"].includes(entry.type);
499
- /** Compile the selected working files over the observed native Git history,
500
- * index and continuation. Retained members keep their advertised content
501
- * witnesses; immutable byte sources never become physical stat evidence.
502
- * Every other selected member is read once, on a content thread, and must
503
- * reproduce the type and payload its entry declares. */
504
- export async function captureSelectedRepository(observed, identity, retained, lane, basis) {
505
- const repository = observed.capture.repository;
506
- const examined = new Map();
507
- const boundaries = nestedRepositoryPaths(identity);
508
- const accounted = await accountedPaths(observed.view.index, independentOf(boundaries));
509
- const selected = new Map(), additionalPaths = [];
510
- await eachInTurns(identity, entry => {
511
- selected.set(entry.path, entry);
512
- if (ordinaryMember(entry) && !accounted.has(entry.path))
513
- additionalPaths.push(entry.path);
514
- });
515
- if (selected.size !== identity.length)
516
- throw new Error("selected repository contains duplicate paths");
517
- const reads = [];
518
- await eachInTurns(await checkpointReads(observed.view.index, boundaries, additionalPaths), request => {
519
- const entry = selected.get(request.path);
520
- if (entry !== undefined && ordinaryMember(entry) && !retained.has(request.path))
521
- reads.push(request);
522
- });
523
- const current = await observeLiteralPaths(repository, observed.view.format, reads, new PhysicalPathWitnesses(), lane);
524
- // The observation's own Card fact, already answered: its tree is the base.
525
- const { tree: base } = await observed.capture.card();
526
- const view = await PrivateGitView.open(observed.view.sourceBinding, observed.state.card.shallow);
527
- let constructed;
528
- try {
529
- constructed = await constructLiteralCheckpoint({
530
- view, index: observed.view.index, accounted, base, boundaries, additionalPaths,
531
- read: path => {
532
- const entry = selected.get(path);
533
- if (!entry || !ordinaryMember(entry))
534
- return null;
535
- const observation = current.get(path);
536
- const leaf = retained.get(path) ?? (observation?.kind === "leaf" ? observation.leaf : null);
537
- if (!leaf)
538
- throw new Error(`selected observed repository member is unavailable: ${path}`);
539
- const payload = leafPayload(entry.payloadVersion, view.format, leaf);
540
- if (entry.type !== leaf.type || entry.payloadVersion !== payload) {
541
- throw new Error(`selected repository source does not reproduce its member: ${path}`);
542
- }
543
- examined.set(path, leaf);
544
- return leaf;
545
- },
546
- });
547
- let overlaps = false;
548
- await eachInTurns(identity, entry => { overlaps ||= ordinaryMember(entry) && !examined.has(entry.path); });
549
- if (overlaps)
550
- throw new Error("selected ordinary member overlaps an opaque Git owner");
551
- }
552
- finally {
553
- await view.close();
554
- }
555
- const checkpoint = { ...observed.state.checkpoint, ...constructed };
556
- const checkpointId = await finishStepsInTurns(checkpointIdSteps(checkpoint, createSha256));
557
- const state = { ...observed.state, checkpoint, checkpointId,
558
- stateId: deriveStateId(observed.state.cardId, checkpointId, sha256Hex) };
559
- return sealRepository({ ...observed, state }, await finishStepsInTurns(repositoryIdentityMapSteps(identity, createSha256)), examined, basis);
560
- }
561
- /** Seal the selected result, unless the ground shows what this computer's
562
- * notebook already holds for the repository: then that package is the result
563
- * and nothing is sealed. `leaves` holds what was read of each ordinary member
564
- * `identity` names. */
565
- async function sealRepository(observed, identity, leaves, basis) {
566
- const { state, view, proof } = observed;
567
- // A repository delta extends the immutable parent transport, never the
568
- // machine's mutable SQLite projection: Detect may already have recorded a
569
- // child move before the enclosing repository capture runs. A map the
570
- // parent's header does not name is no base, for the delta or for judging
571
- // the ground: the transport is then self-contained.
572
- const previous = basis && basis.previous?.identityHash === basis.prior.layout.identityHash ? basis.previous : null;
573
- const changes = previous && (previous.identityHash === identity.identityHash ? []
574
- : await finishStepsInTurns(repositoryIdentityChangesSteps(previous.entries, identity.entries)));
575
- if (basis && await showsBasis(observed, identity, leaves, basis, previous, changes)) {
576
- const { transportVersion, layout } = basis.prior;
577
- return { transportVersion, layout, identity: previous ?? identity, bytes: null, proof };
578
- }
579
- const pack = await nativePack(view.sourceBinding, state, previous && basis.prior.layout.card);
580
- const { bytes, layout } = await finishStepsInTurns(encodeRepositoryTransportSteps({ ...state, pack }, {
581
- parentTransportVersion: previous && basis.prior.transportVersion,
582
- identityHash: identity.identityHash,
583
- identityDelta: repositoryIdentityDelta(identity, changes),
584
- }));
585
- return { transportVersion: await finishStepsInTurns(digestSteps(bytes, createSha256)),
586
- layout, identity, bytes: bufferView(bytes), proof };
587
- }
588
- /**
589
- * Whether the ground shows the notebook's package (Live expectedRepository).
590
- * Every file belongs to its nearest repository, so a record revealed for
591
- * another entity changes this repository's ground without changing its
592
- * package: there each entity's own row speaks, and the package is judged on
593
- * the rest. Equal maps are judged by the package's state alone. Otherwise
594
- * rows are read only for the differences and the ground they speak for, and
595
- * every pass runs in steps; a difference that is this computer's own work,
596
- * or a member that disagrees with its row, is a change. `previous` is the
597
- * package's own map when proven, and `changes` the ground's differences from
598
- * it.
599
- */
600
- async function showsBasis(observed, identity, leaves, { prior, shared }, previous, changes) {
601
- const { state, view } = observed, { layout } = prior;
602
- if (identity.identityHash === layout.identityHash)
603
- return state.stateId === layout.stateId;
604
- if (!previous || !changes || state.cardId !== layout.cardId)
605
- return false;
606
- const rows = new Map();
607
- const rowOf = (uuid) => {
608
- if (!rows.has(uuid))
609
- rows.set(uuid, shared(uuid));
610
- return rows.get(uuid);
611
- };
612
- const repository = observed.capture.repository;
613
- const expectation = await finishStepsInTurns(expectedRepositorySteps(changes, previous.entries, identity.entries, uuid => repositoryStatement(repository, rowOf(uuid))));
614
- if (!expectation || expectation.unstated.length > 0)
615
- return false;
616
- // Each member a row speaks for holds that row's bytes and mode.
617
- let held = true;
618
- const holds = (member) => {
619
- if (!held || member.type === "folder")
620
- return;
621
- const leaf = leaves.get(member.path), type = member.type;
622
- held = member.payloadVersion != null && leaf !== undefined && leafShows(member.payloadVersion, view.format, leaf)
623
- && portableFileMode(type, rowOf(member.uuid).filesystemMode) === portableFileMode(type, Number.parseInt(leaf.mode, 8));
624
- };
625
- // The Checkpoint shows the package's where the package speaks: neither
626
- // side's worktree is read on silent ground or at a member beyond the map.
627
- const beyond = [];
628
- await eachInTurns(expectation.silenced, holds);
629
- if (!held)
630
- return false;
631
- await eachInTurns(expectation.extras, member => { holds(member); if (member.type !== "folder")
632
- beyond.push(member.path); });
633
- if (!held)
634
- return false;
635
- const hidden = beyond.length ? [...expectation.silent, ...beyond] : expectation.silent;
636
- // An exact cut is silent only about the package's own nested repositories,
637
- // which its Checkpoint never enters.
638
- const expected = expectation.exact && !beyond.length ? layout.checkpointId
639
- : await shownCheckpointIdOf(await checkpointEvidenceFromFile(prior.file, layout), hidden, layout.checkpointId);
640
- return await shownCheckpointIdOf(state.checkpoint, hidden, state.checkpointId) === expected;
641
- }
642
- /** Only these immutable object components are flushed by Git's writer
643
- * contract (gitWriter). Other files, including pack retention markers, remain
644
- * the final barrier's responsibility. The object directory comes from its
645
- * owner, Git. Only owned ground has that barrier, so only an owned reveal
646
- * scans; working Apply never walks old packs. */
647
- async function gitObjectFiles(repository) {
648
- const binding = { purpose: "binding" };
649
- const objects = resolve(repository, await gitText(repository, ["rev-parse", "--git-path", "objects"], binding));
650
- const hashLength = await gitText(repository, ["rev-parse", "--show-object-format"], binding) === "sha256" ? 64 : 40;
651
- const loose = new RegExp(`^[0-9a-f]{${hashLength - 2}}$`);
652
- const packed = new RegExp(`^pack-[0-9a-f]{${hashLength}}\\.(pack|idx|rev)$`);
653
- const files = [];
654
- for (const directory of readdirSync(objects, { withFileTypes: true })) {
655
- if (!directory.isDirectory() || (directory.name !== "pack" && !/^[0-9a-f]{2}$/.test(directory.name)))
656
- continue;
657
- const pattern = directory.name === "pack" ? packed : loose;
658
- for (const entry of readdirSync(join(objects, directory.name), { withFileTypes: true })) {
659
- if (entry.isFile() && pattern.test(entry.name))
660
- files.push(join(objects, directory.name, entry.name));
661
- }
662
- }
663
- return files;
664
- }
665
- async function newlyDurableGitObjects(repository, priorFiles) {
666
- return priorFiles === null ? [] : (await gitObjectFiles(repository))
667
- .filter((file) => !priorFiles.has(file)).map(recordFileDurability);
668
- }
669
- async function readShallowBoundary(repository) {
670
- const file = resolve(repository, await gitText(repository, ["rev-parse", "--git-path", "shallow"], { purpose: "binding" }));
671
- let text = "";
672
- try {
673
- text = await readFile(file, "utf8");
674
- }
675
- catch (error) {
676
- if (error.code !== "ENOENT")
677
- throw error;
678
- }
679
- return { file, commits: new Set(text.split("\n").filter(Boolean)) };
680
- }
681
- /** Whether `state` keeps every commit the repository now bounds. Only then is
682
- * the refs' history whole under the state's boundary; a state that drops one
683
- * (Git's deepen or unshallow) declares history beneath it that no ref shows. */
684
- const keepsBoundary = (current, state) => {
685
- const bound = new Set(state.card.shallow ?? []);
686
- return [...current].every((commit) => bound.has(commit));
687
- };
688
- async function installShallowBoundary(file, commits) {
689
- if (commits.length === 0) {
690
- rmSync(file, { force: true });
691
- return;
692
- }
693
- // Renamed over as a new inode, never written in place, inside the Git
694
- // directory that init made: a vanished repository is never re-created.
695
- atomicWriteIn(file, `${[...commits].sort().join("\n")}\n`, 0o644);
696
- }
697
- /** Card refs replace the stored ref set in two steps, because Git 2.39's
698
- * `update-ref --stdin` has no symbolic verb. One transaction writes every
699
- * direct value and deletes every stored ref the Card lacks. Card names are
700
- * literal, so no update or delete may follow a symbolic ref (a clone's
701
- * `refs/remotes/origin/HEAD` would otherwise write `origin/main` twice), and
702
- * only the command-line flag covers every command; `option no-deref` covers
703
- * one. Each differing symbolic relationship is then set by name. The stored
704
- * set includes the loose store, since for-each-ref omits a dangling or cyclic
705
- * symbolic ref that must still go. Rerunning both steps is idempotent. */
706
- async function forceRefs(git, repository, state) {
707
- const wanted = new Set(state.card.refs.map((ref) => ref.name));
708
- const listed = await gitText(repository, ["for-each-ref", "--format=%(refname)", "refs"], { purpose: "apply" });
709
- const stored = looseRefs(repository);
710
- const commands = [
711
- ...state.card.refs.flatMap((ref) => ref.kind === "direct" ? [`update ${ref.name} ${ref.commit}`] : []),
712
- ...[...new Set([...(listed ? listed.split("\n") : []), ...stored.keys()])]
713
- .filter((name) => name !== "refs/stash" && !wanted.has(name))
714
- .map((name) => `delete ${name}`),
715
- "",
716
- ];
717
- await git(repository, ["update-ref", "--no-deref", "--stdin"], Buffer.from(commands.join("\n"), "utf8"));
718
- for (const ref of state.card.refs) {
719
- if (ref.kind !== "symbolic")
720
- continue;
721
- const current = stored.get(ref.name)?.();
722
- if (current?.kind === "symbolic" && current.target === ref.target)
723
- continue;
724
- await git(repository, ["symbolic-ref", ref.name, ref.target]);
725
- }
726
- }
727
- /** Git keeps the stash stack only in the `refs/stash` reflog, so a differing
728
- * stack is rebuilt by value: drop the ref and its log, then store every entry
729
- * oldest first. An equal stack is left untouched. */
730
- async function forceStash(git, repository, state) {
731
- const wanted = state.card.stash;
732
- const current = await stashList(repository);
733
- if (current.length === wanted.length && current.every((entry, index) => entry.commit === wanted[index].commit && entry.message === wanted[index].message)) {
734
- return;
735
- }
736
- await git(repository, ["update-ref", "-d", "refs/stash"]);
737
- for (let index = wanted.length - 1; index >= 0; index -= 1) {
738
- const entry = wanted[index];
739
- await git(repository, ["stash", "store", `--message=${entry.message}`, entry.commit]);
740
- }
741
- }
742
- async function forceHead(git, repository, state) {
743
- const { head } = state.card;
744
- if (head.branch !== null) {
745
- await git(repository, ["symbolic-ref", "HEAD", `refs/heads/${head.branch}`]);
746
- }
747
- else if (head.commit !== null) {
748
- await git(repository, ["update-ref", "--no-deref", "HEAD", head.commit]);
749
- }
750
- else
751
- throw new Error("unborn repository state has no branch");
752
- }
753
- async function installMergeOperation(repository, operation) {
754
- const directory = gitDirectory(repository);
755
- for (const file of ["MERGE_HEAD", "MERGE_MSG", "MERGE_MODE"]) {
756
- rmSync(join(directory, file), { force: true });
757
- }
758
- if (operation === null)
759
- return;
760
- writeFileSync(join(directory, "MERGE_HEAD"), `${operation.heads.join("\n")}\n`);
761
- writeFileSync(join(directory, "MERGE_MSG"), operation.message);
762
- writeFileSync(join(directory, "MERGE_MODE"), operation.mode);
763
- }
764
- /**
765
- * What keeps this machine from revealing a repository result in `format` at
766
- * `repository`, or null. Every refusal is decided here, before a reveal
767
- * marker: beneath the marker only effects run, and a refusal there could
768
- * never resolve. Apply's guard asks first and waits on the answer.
769
- *
770
- * - Older Git accepts unknown -c keys without implementing their contract.
771
- * The writer acknowledgement requires core.fsync/core.fsyncMethod, which
772
- * became available in Git 2.36.
773
- * - Git storage lies inside `root`, the ground the reveal may write. Nothing
774
- * watches storage outside it: a person can change its refs or index
775
- * without touching the workspace, and a replacement root can name the
776
- * same storage.
777
- * - Existing storage keeps its object format. `fresh` says the reveal
778
- * creates the storage: its `.git` may hold only its marker, which Git
779
- * would not recognise, and `init` itself refuses a format change on any
780
- * earlier attempt.
781
- */
782
- export async function repositoryRevealRefusal(repository, root, format, fresh) {
783
- const { version } = gitHost();
784
- const parsed = /^git version (\d+)\.(\d+)\.(\d+)(?:[.\s-]|$)/.exec(version);
785
- if (!parsed || Number(parsed[1]) < 2 || (Number(parsed[1]) === 2 && Number(parsed[2]) < 36)) {
786
- return `Git 2.36 or newer is required for durable repository materialization; found ${version}.`;
787
- }
788
- const outside = gitStorageOutside(repository, root);
789
- if (outside) {
790
- return `This checkout keeps its Git storage at ${outside}, outside its workspace ${root}. `
791
- + "Nothing watches storage there, so Apply requires a checkout's Git storage inside its workspace.";
792
- }
793
- if (!fresh && await gitText(repository, ["rev-parse", "--show-object-format"], { purpose: "binding" }) !== format) {
794
- return `This checkout stores Git objects in another format than the accepted repository's ${format}.`;
795
- }
796
- return null;
797
- }
798
- async function forceRemotes(git, repository, remotes) {
799
- const existing = (await gitText(repository, ["remote"], { purpose: "apply" })).split("\n").filter(Boolean);
800
- const wanted = new Map(remotes.map((remote) => [remote.name, remote.url]));
801
- for (const name of existing) {
802
- if (!wanted.has(name))
803
- await git(repository, ["remote", "remove", name]);
804
- }
805
- for (const [name, url] of wanted) {
806
- if (existing.includes(name))
807
- await git(repository, ["remote", "set-url", name, url]);
808
- else
809
- await git(repository, ["remote", "add", name, url]);
810
- }
811
- }
812
- function readExact(file, offset, bytes) {
813
- const result = Buffer.allocUnsafe(bytes);
814
- const descriptor = openSync(file, "r");
815
- try {
816
- let cursor = 0;
817
- while (cursor < bytes) {
818
- const count = readSync(descriptor, result, cursor, bytes - cursor, offset + cursor);
819
- if (count === 0)
820
- throw new Error("repository transport file is truncated");
821
- cursor += count;
822
- }
823
- return result;
824
- }
825
- finally {
826
- closeSync(descriptor);
827
- }
828
- }
829
- /** A transport's layout from its header alone; the pack and Checkpoint
830
- * bytes it locates are never read. */
831
- export async function inspectRepositoryTransportFile(file) {
832
- const handle = await open(file, "r");
833
- let metadata, size;
834
- try {
835
- ({ size } = await handle.stat());
836
- const head = async (bytes) => {
837
- const result = Buffer.allocUnsafe(bytes);
838
- for (let cursor = 0; cursor < bytes;) {
839
- const { bytesRead } = await handle.read(result, cursor, bytes - cursor, cursor);
840
- if (bytesRead === 0)
841
- throw new Error("repository transport file is truncated");
842
- cursor += bytesRead;
843
- }
844
- return result;
845
- };
846
- metadata = await head(repositoryTransportMetadataBytes(await head(12)));
847
- }
848
- finally {
849
- await handle.close();
850
- }
851
- return finishStepsInTurns(inspectRepositoryTransportSteps(metadata, size));
852
- }
853
- const REPOSITORY_IDENTITY_CACHE_CONTRACT = "amalgm.repository-identity-cache.v2";
854
- /** A sealed frontier is one header line, then exactly one line per entry in
855
- * the map's order, then nothing. Lines are read and written in bounded steps,
856
- * so a large map never holds the thread for one whole parse. */
857
- const repositoryIdentityCacheFile = (cacheDir, transportVersion) => join(cacheDir, "repository-identities", `${transportVersion}.jsonl`);
858
- const frontierHeader = (transportVersion, identityHash, entries) => JSON.stringify({ contract: REPOSITORY_IDENTITY_CACHE_CONTRACT, transportVersion, identityHash, entries });
859
- /** An entry's one line: its own fields in one order. A line that is not this
860
- * serialization of what it parses to is no line of a sealed frontier, so an
861
- * entry read back holds exactly the fields the map's hash covers. */
862
- const identityLine = ({ path, uuid, type, payloadVersion }) => JSON.stringify(payloadVersion === undefined ? { path, uuid, type } : { path, uuid, type, payloadVersion });
863
- /** Identity frontiers this process has proven, by immutable transport. A
864
- * transport names exactly one map, so a proven frontier never goes stale; the
865
- * bound, in entries, only limits memory. The newest frontier always stays. */
866
- const provenFrontiers = new Map();
867
- const PROVEN_FRONTIER_ENTRIES = 100_000;
868
- let provenFrontierEntries = 0;
869
- function rememberFrontier(transportVersion, identity) {
870
- const known = provenFrontiers.get(transportVersion);
871
- if (known)
872
- provenFrontierEntries -= known.entries.length;
873
- provenFrontiers.delete(transportVersion);
874
- provenFrontiers.set(transportVersion, identity);
875
- provenFrontierEntries += identity.entries.length;
876
- for (const [version, frontier] of provenFrontiers) {
877
- if (provenFrontierEntries <= PROVEN_FRONTIER_ENTRIES || version === transportVersion)
878
- break;
879
- provenFrontiers.delete(version);
880
- provenFrontierEntries -= frontier.entries.length;
881
- }
882
- }
883
- /** Seal the compact full identity frontier beside the current transport. The
884
- * evidence is disposable, but its content is accepted only when its hash
885
- * equals the immutable transport header that names it. */
886
- export async function sealCachedRepositoryIdentity(cacheDir, transportVersion, identity, identityHash) {
887
- if (identity.identityHash !== identityHash) {
888
- throw new Error("repository identity evidence does not match its transport");
889
- }
890
- rememberFrontier(transportVersion, identity);
891
- const text = [];
892
- await finishStepsInTurns(frontierTextSteps(transportVersion, identity, run => { text.push(Buffer.from(run, "utf8")); }));
893
- await writeCacheHint(cacheDir, repositoryIdentityCacheFile(cacheDir, transportVersion), await concatInTurns(text));
894
- }
895
- function* frontierTextSteps(transportVersion, identity, emit) {
896
- const { entries } = identity;
897
- emit(`${frontierHeader(transportVersion, identity.identityHash, entries.length)}\n`);
898
- let run = "";
899
- for (let index = 0; index < entries.length; index += 1) {
900
- run += `${identityLine(entries[index])}\n`;
901
- if ((index + 1) % ITEMS_PER_BOUNDARY === 0) {
902
- emit(run);
903
- run = "";
904
- yield;
905
- }
906
- }
907
- emit(run);
908
- }
909
- /** The map a sealed frontier holds, or null when any byte of it is not the
910
- * frontier `identityHash` names: the header, the count, each line, nothing
911
- * after the last. The map's own hash, never the file's bytes, decides. */
912
- function* sealedFrontierSteps(text, transportVersion, identityHash) {
913
- let end = text.indexOf("\n");
914
- if (end < 0)
915
- return null;
916
- const header = text.slice(0, end);
917
- const count = JSON.parse(header).entries;
918
- if (typeof count !== "number" || header !== frontierHeader(transportVersion, identityHash, count))
919
- return null;
920
- const entries = [];
921
- while (entries.length < count) {
922
- const start = end + 1;
923
- end = text.indexOf("\n", start);
924
- if (end < 0)
925
- return null;
926
- const line = text.slice(start, end);
927
- const entry = JSON.parse(line);
928
- if (identityLine(entry) !== line)
929
- return null;
930
- entries.push(entry);
931
- if (entries.length % ITEMS_PER_BOUNDARY === 0)
932
- yield;
933
- }
934
- if (end !== text.length - 1)
935
- return null;
936
- const identity = yield* repositoryIdentityMapSteps(entries, createSha256);
937
- return identity.identityHash === identityHash ? identity : null;
938
- }
939
- async function readSealedRepositoryIdentity(cacheDir, transportVersion, identityHash) {
940
- try {
941
- const text = await readFile(repositoryIdentityCacheFile(cacheDir, transportVersion), "utf8");
942
- return await finishStepsInTurns(sealedFrontierSteps(text, transportVersion, identityHash));
943
- }
944
- catch {
945
- return null;
946
- }
947
- }
948
- /** The identity map one transport names, only where it is already proven:
949
- * in memory, or sealed beside the cache and equal to `identityHash`, the
950
- * transport's own header. It never replays a chain. */
951
- export async function provenRepositoryIdentity(cacheDir, transportVersion, identityHash) {
952
- // A remembered map was proven against this transport's own header.
953
- const proven = provenFrontiers.get(transportVersion);
954
- if (proven)
955
- return proven;
956
- const sealed = await readSealedRepositoryIdentity(cacheDir, transportVersion, identityHash);
957
- if (sealed)
958
- rememberFrontier(transportVersion, sealed);
959
- return sealed;
960
- }
961
- /** Reconstruct the exact identity map named by one immutable repository
962
- * transport. Compact sealed evidence survives ancestor-pack pruning; without
963
- * it, the chain is replayed forward from the nearest package whose map is
964
- * already proven, or from the root, and seals the frontier. A link the cache
965
- * lacks is fetched through `fetchLink` when one is given, and is otherwise
966
- * not held. No mutable entity row can substitute for either proof. */
967
- export async function readCachedRepositoryIdentity(cacheDir, transportVersion, fetchLink) {
968
- const proven = provenFrontiers.get(transportVersion);
969
- if (proven)
970
- return proven;
971
- const layoutOf = async (version) => {
972
- const file = join(cacheDir, `${version}.bin`);
973
- try {
974
- return await inspectRepositoryTransportFile(file);
975
- }
976
- catch {
977
- if (!fetchLink)
978
- return null;
979
- }
980
- // A failed fetch is a fault with its own cause, never an absent package.
981
- await fetchLink(version);
982
- try {
983
- return await inspectRepositoryTransportFile(file);
984
- }
985
- catch {
986
- return null;
987
- }
988
- };
989
- const current = await layoutOf(transportVersion);
990
- if (!current)
991
- return null;
992
- const reversed = [];
993
- const versions = new Set();
994
- let base = null;
995
- for (let version = transportVersion, layout = current; version !== null;) {
996
- if (versions.has(version) || !layout)
997
- return null;
998
- versions.add(version);
999
- const known = await provenRepositoryIdentity(cacheDir, version, layout.identityHash);
1000
- if (known) {
1001
- base = { version, identity: known };
1002
- break;
1003
- }
1004
- reversed.push({ version, layout });
1005
- version = layout.parentTransportVersion;
1006
- layout = version === null ? null : await layoutOf(version);
1007
- }
1008
- if (reversed.length === 0)
1009
- return base.identity;
1010
- // A chain that does not replay to its own headers proves nothing.
1011
- try {
1012
- let parent = base?.version ?? null;
1013
- let identity = base?.identity.entries ?? null;
1014
- for (const node of reversed.reverse()) {
1015
- if (node.layout.parentTransportVersion !== parent)
1016
- return null;
1017
- identity = await finishStepsInTurns(applyRepositoryIdentitySteps(identity, node.layout, createSha256));
1018
- parent = node.version;
1019
- }
1020
- // Each applied node proved its declared map, the last one this header's.
1021
- const result = { entries: identity ?? [], identityHash: current.identityHash };
1022
- await sealCachedRepositoryIdentity(cacheDir, transportVersion, result, current.identityHash);
1023
- return result;
1024
- }
1025
- catch {
1026
- return null;
1027
- }
1028
- }
1029
- /** The reducer's package port over one immutable cache. A package or chain
1030
- * link the cache lacks comes through `download`, so a fold never depends on
1031
- * which packages this machine happens to hold. */
1032
- export function cachedRepositoryIdentity(cacheDir, download) {
1033
- return async ({ uuid, transportVersion }) => (await readCachedRepositoryIdentity(cacheDir, transportVersion, async (version) => {
1034
- await download([{ entityId: uuid, entityType: "repo.git", kind: "git", contentHash: version }]);
1035
- }))?.entries ?? null;
1036
- }
1037
- async function* hashed(source, hash) {
1038
- for await (const chunk of source) {
1039
- hash.update(chunk);
1040
- yield chunk;
1041
- }
1042
- }
1043
- export async function readRepositoryLink(sealed) {
1044
- if (await hashContentFile(sealed.file) !== sealed.transportVersion) {
1045
- throw new Error("repository transport failed its immutable hash");
1046
- }
1047
- return { ...sealed, layout: await inspectRepositoryTransportFile(sealed.file) };
1048
- }
1049
- /** Each link names the one before it (the first names the base, or null at
1050
- * the root), and the maps fold from the base's map; each fold checks its
1051
- * package's header. Only the result's Checkpoint is ever revealed, so only
1052
- * its contents are proven; older packages are proven by their hash. */
1053
- export async function proveRepositoryChain(base, links) {
1054
- const result = links.at(-1);
1055
- if (!result)
1056
- throw new Error("repository transport chain is empty");
1057
- let prior = base?.transportVersion ?? null;
1058
- let identity = base?.identity ?? null;
1059
- for (const link of links) {
1060
- if (link.layout.parentTransportVersion !== prior)
1061
- throw new Error("repository transport chain is discontinuous");
1062
- identity = await finishStepsInTurns(applyRepositoryIdentitySteps(identity, link.layout, createSha256));
1063
- prior = link.transportVersion;
1064
- }
1065
- await proveRepositoryTransportFile(result.file, result.layout);
1066
- return { links, identity: identity, earlier: base?.packages ?? null };
1067
- }
1068
- /** Whether the repository at `path` may start a rebuild from `state`: Git
1069
- * marks it and it holds every object the state names. A candidate only, so
1070
- * a failed read is no candidate: a present tip does not prove its history,
1071
- * which the import's acceptance decides. */
1072
- export async function repositoryHolds(path, state) {
1073
- try {
1074
- return hasGitMarker(path) && await holdsState(path, state);
1075
- }
1076
- catch {
1077
- return false;
1078
- }
1079
- }
1080
- /** Import a chain's packs and accept them the way Git accepts a fetch. The
1081
- * first attempt starts after the base and skips the packages the repository
1082
- * already holds (a resumed reveal). If it fails, nothing is exposed yet, only
1083
- * kept packs were added, so the same attempt imports every package from the
1084
- * root and accepts again. A failure there is a fault. */
1085
- async function importRepositoryChain(git, repository, chain, fresh, current) {
1086
- const result = chain.links.at(-1).layout;
1087
- const absent = fresh ? 0 : await firstAbsentTransport(repository, chain.links, current);
1088
- try {
1089
- await importPacks(git, repository, chain.links.slice(absent));
1090
- await acceptImport(repository, result, current);
1091
- }
1092
- catch (error) {
1093
- if (chain.earlier === null && absent === 0)
1094
- throw error;
1095
- await importPacks(git, repository, [...chain.earlier ? await chain.earlier() : [], ...chain.links]);
1096
- await acceptImport(repository, result, current);
1097
- }
1098
- }
1099
- async function importPacks(git, repository, links) {
1100
- for (const link of links) {
1101
- if (link.layout.pack)
1102
- await importPackFile(git, repository, link.file, link.layout.pack);
1103
- }
1104
- }
1105
- /** Git's own acceptance of fetched objects, its connectivity check: every
1106
- * object the result names reaches, through objects present, the result's own
1107
- * shallow boundary or history the repository already holds whole. The refs'
1108
- * history is whole down to the repository's current boundary, so while the
1109
- * result keeps that boundary the walk stops at what the refs reach. A result
1110
- * that drops it is walked to its own boundary without the refs, as Git's
1111
- * deepening fetch is. It reads raw objects (lazy fetch is off for every Shell
1112
- * Git process) under the result's boundary, which the reveal installs only
1113
- * afterwards. */
1114
- async function acceptImport(repository, state, current) {
1115
- const wants = stateWants(state);
1116
- if (wants.length === 0)
1117
- return;
1118
- const shallow = state.card.shallow ?? [];
1119
- const scratch = shallow.length > 0 ? await mkdtemp(join(tmpdir(), "amalgm-repository-boundary-")) : null;
1120
- try {
1121
- const boundary = scratch ? join(scratch, "shallow") : "";
1122
- if (scratch)
1123
- await writeFile(boundary, `${[...shallow].sort().join("\n")}\n`);
1124
- await runGit(repository, ["--shallow-file", boundary, "--no-replace-objects",
1125
- "rev-list", "--objects", "--stdin", ...keepsBoundary(current, state) ? ["--not", "--all"] : [], "--quiet"], { input: Buffer.from(`${wants.join("\n")}\n`, "utf8"), purpose: "apply" });
1126
- }
1127
- finally {
1128
- if (scratch)
1129
- await rm(scratch, { recursive: true, force: true });
1130
- }
1131
- }
1132
- async function importPackFile(git, repository, file, pack) {
1133
- const hash = createHash("sha256");
1134
- const source = createReadStream(file, {
1135
- start: pack.range.offset,
1136
- end: pack.range.offset + pack.range.bytes - 1,
1137
- });
1138
- await git(repository, ["index-pack", "--stdin", "--fix-thin", "--keep=amalgm repository transport"], hashed(source, hash));
1139
- if (hash.digest("hex") !== pack.sha256)
1140
- throw new Error("repository Git pack checksum mismatch");
1141
- }
1142
- /** A transport's pack delivers every object its state wants, and each pack
1143
- * closes over its parent's wants. Walking the links from the newest, the
1144
- * first the repository already holds ends what must be imported: only the
1145
- * ranges after it are absent. A link is held when its wants are present and
1146
- * it keeps the current boundary, since a present tip shows nothing of the
1147
- * history a pack exposes beneath that boundary. Like `repositoryHolds`, this
1148
- * is a candidate that the import's acceptance confirms. */
1149
- async function firstAbsentTransport(repository, links, current) {
1150
- for (let index = links.length - 1; index >= 0; index -= 1) {
1151
- const layout = links[index].layout;
1152
- if (keepsBoundary(current, layout) && await holdsState(repository, layout))
1153
- return index + 1;
1154
- }
1155
- return 0;
1156
- }
1157
- /** Whether `repository` holds every object one state wants. */
1158
- async function holdsState(repository, state) {
1159
- const wants = stateWants(state);
1160
- if (wants.length === 0)
1161
- return true;
1162
- const report = await runGit(repository, ["--no-replace-objects", "cat-file", "--batch-check=%(objectname) %(objecttype)"], { input: Buffer.from(`${wants.join("\n")}\n`, "utf8"), purpose: "apply" });
1163
- return !report.toString("utf8").split("\n").some((line) => line.endsWith(" missing"));
1164
- }
1165
- function readRange(file, range) {
1166
- return range.bytes === 0 ? Buffer.alloc(0) : readExact(file, range.offset, range.bytes);
1167
- }
1168
- function checkpointFileSource(file, checkpoint) {
1169
- const content = (range) => {
1170
- if (range === null)
1171
- throw new Error("repository transport omitted checkpoint content");
1172
- return readRange(file, range);
1173
- };
1174
- return {
1175
- baseCommit: checkpoint.baseCommit,
1176
- stagedPatch: readRange(file, checkpoint.stagedPatch),
1177
- unstagedPatch: readRange(file, checkpoint.unstagedPatch),
1178
- indexFlags: checkpoint.indexFlags,
1179
- untracked: checkpoint.untracked.map(entry => ({ ...entry, read: () => content(entry.content) })),
1180
- unmerged: checkpoint.unmerged.map(entry => ({ ...entry,
1181
- worktree: entry.worktree === null ? null : { ...entry.worktree, path: entry.path,
1182
- read: () => content(entry.worktree.content) },
1183
- })),
1184
- };
1185
- }
1186
- async function applyCheckpointFile(repository, file, checkpoint, territory, ground, installMetadata) {
1187
- const revealed = await installLiteralCheckpoint(repository, checkpointFileSource(file, checkpoint), territory, ground, installMetadata);
1188
- await installMergeOperation(repository, checkpoint.operation === null ? null : {
1189
- kind: checkpoint.operation.kind, heads: checkpoint.operation.heads,
1190
- message: readRange(file, checkpoint.operation.message), mode: readRange(file, checkpoint.operation.mode),
1191
- });
1192
- return revealed;
1193
- }
1194
- /** Recover retained working bytes from their immutable transport chain. This
1195
- * owns private Git objects only; it never checks out files or touches the live
1196
- * repository, its index, refs, or metadata. The caller must close the result. */
1197
- export async function prepareRepositoryFiles(chain) {
1198
- const links = [];
1199
- for (const sealed of chain)
1200
- links.push(await readRepositoryLink(sealed));
1201
- const { identity } = await proveRepositoryChain(null, links);
1202
- const latest = links.at(-1);
1203
- const scratch = await mkdtemp(join(tmpdir(), "amalgm-retained-repository-"));
1204
- let checkpoint;
1205
- try {
1206
- await runGit(scratch, ["init", "--quiet", `--object-format=${latest.layout.card.objectFormat}`, "--template="], { purpose: "apply" });
1207
- await importPacks(gitWriter("private"), scratch, links);
1208
- await acceptImport(scratch, latest.layout, new Set());
1209
- checkpoint = await prepareLiteralCheckpoint(scratch, checkpointFileSource(latest.file, latest.layout.checkpoint), repositoryApplyTerritory(identity, []), null);
1210
- return {
1211
- layout: latest.layout, identity, checkpoint,
1212
- close: async () => { await checkpoint.close(); await rm(scratch, { recursive: true, force: true }); },
1213
- };
1214
- }
1215
- catch (error) {
1216
- await checkpoint?.close();
1217
- await rm(scratch, { recursive: true, force: true });
1218
- throw error;
1219
- }
1220
- }
1221
- /** Apply a proven repository chain by streaming each Git range directly into
1222
- * index-pack. The chain was proven when it was read, and every range is
1223
- * hashed as it streams, so the reveal walks, hashes and folds nothing again.
1224
- * The reveal acts on the result's territory: owned ground holds nothing any
1225
- * other rail owns. */
1226
- export async function applyRepositoryFiles(repository, chain, ground) {
1227
- const { identity } = chain;
1228
- const latest = chain.links.at(-1);
1229
- const { transportVersion, layout: state } = latest;
1230
- const territory = repositoryApplyTerritory(identity, ground.kind === "working" ? ground.standing : ground.standingOf(identity));
1231
- // Created only beneath ground that stands (filesystem.ts ensureDirBeneath).
1232
- ensureDirBeneath(dirname(repository), repository, 0o755);
1233
- // Working ground's receipt froze whether the reveal creates its storage;
1234
- // owned ground creates storage wherever no repository stands.
1235
- const fresh = ground.kind === "working" ? ground.reveal.storage === null : !hasGitMarker(repository);
1236
- // Owned ground holds only what this install creates, its storage included.
1237
- const root = ground.kind === "working" ? ground.root : repository;
1238
- const refusal = await repositoryRevealRefusal(repository, root, state.card.objectFormat, fresh);
1239
- if (refusal)
1240
- throw new Error(refusal);
1241
- const git = gitWriter(ground.kind);
1242
- await beginRepositoryReveal(repository, ground, fresh);
1243
- await git(repository, ["init", "--quiet", `--object-format=${state.card.objectFormat}`, "--template="]);
1244
- // Only owned ground has a barrier to acknowledge Git's flushes to. An
1245
- // object already standing was not necessarily flushed by this reveal's
1246
- // writers, so only the objects this reveal adds are acknowledged.
1247
- const priorFiles = ground.kind === "owned" ? new Set(await gitObjectFiles(repository)) : null;
1248
- const boundary = await readShallowBoundary(repository);
1249
- await importRepositoryChain(git, repository, chain, fresh, boundary.commits);
1250
- const declined = await applyCheckpointFile(repository, latest.file, state.checkpoint, territory, ground, async () => {
1251
- await installShallowBoundary(boundary.file, state.card.shallow ?? []);
1252
- await forceRemotes(git, repository, state.card.remotes);
1253
- await forceRefs(git, repository, state);
1254
- await forceStash(git, repository, state);
1255
- await forceHead(git, repository, state);
1256
- });
1257
- // The readback closes before its reveal marker retires. It proves only the
1258
- // reveal's own result, read through its territory: on working ground,
1259
- // untracked names the result does not hold are kept remainder or a person's
1260
- // addition, which Verify judges against the receipt. A result path the
1261
- // reveal declined leaves the person's ground standing, so the reveal has
1262
- // done all it may; its marker retires and Verify reads that ground as
1263
- // foreign.
1264
- const reading = await readRepository(repository, territory.silent, "apply", ground.kind === "working" ? ground.proven : null);
1265
- const own = new Set(state.checkpoint.untracked.map(file => file.path));
1266
- const proof = ground.kind === "working" ? await withoutUntracked(reading.state, path => !own.has(path)) : reading.state;
1267
- if (proof.cardId !== state.cardId
1268
- || (declined.size === 0 && proof.checkpointId !== await shownCheckpointId(latest.file, state, territory))) {
1269
- throw new Error("materialized repository does not reproduce its declared state");
1270
- }
1271
- await finishRepositoryReveal(repository, ground);
1272
- return {
1273
- stateId: state.stateId,
1274
- cardId: state.cardId,
1275
- checkpointId: state.checkpointId,
1276
- card: state.card,
1277
- transportVersion,
1278
- identity,
1279
- territory,
1280
- durableFiles: await newlyDurableGitObjects(repository, priorFiles),
1281
- reading,
1282
- };
1283
- }
1284
- /** The state a repository package shows when read through its territory:
1285
- * the package itself on an exact territory, else the package with its silent
1286
- * ground dropped. It is read from the package alone, never from ground. */
1287
- export async function shownRepositoryState({ file, layout }, territory) {
1288
- return territory.exact ? layout.stateId
1289
- : deriveStateId(layout.cardId, await shownCheckpointId(file, layout, territory), sha256Hex);
1290
- }
1291
- //# sourceMappingURL=git-repository-host.js.map