Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/server/src/push.ts?version=310&format=json
305 linesspeed 75% · codex-capacity-chair 25%Last change codex-capacity-chair in version 181, 4 versions changed it

You're reading version 310. The newest is 318, and no version since then changed this file. Go to the newestCompare with 318

1// Out to Artifacts (#8): shared's files as one git commit on main of the
2// project's repo, with the publish message and the agent as author. The repo
3// is created on first use. isomorphic-git works in an in-memory filesystem:
4// a depth-1 clone of main with nothing checked out, then a new tree from
5// shared's files that compresses and writes only what changed (abso issue 293).
6import { createHash } from "node:crypto";
7import git from "isomorphic-git";
8import http from "isomorphic-git/http/web";
9import type { FileModes } from "../../worker/project/project-api.ts";
10import type { SqliteStorage } from "./engine-project.ts";
11import { GitDiskIntake } from "./git-disk-intake.ts";
12import { GitFileContents } from "./git-file-contents.ts";
13import { gitHttp } from "./git-http.ts";
14import { MemoryFS } from "./memory-fs.ts";
16export interface PushResult {
17 repo: string;
18 remote: string;
19 commit: string;
20 version: number;
21 ms: number;
24/** New blob bytes per push before the push out splits into parts: Artifacts refuses a push much over 20 MB. */
25const PUSH_BATCH = 16 * 1024 * 1024;
27/** A file as a tree entry holds it: its blob and its mode ("100644", "100755", "120000"). */
28export interface TreeFile {
29 oid: string;
30 mode: string;
33/** Every file in a tree, and every folder's tree oid ("" is the root), read from tree objects only. */
34export async function readTreeFiles(
35 fs: MemoryFS,
36 dir: string,
37 oid: string,
38 prefix = "",
39 files = new Map<string, TreeFile>(),
40 trees = new Map<string, string>(),
41 cache?: object,
42): Promise<{ files: Map<string, TreeFile>; trees: Map<string, string> }> {
43 trees.set(prefix, oid);
44 const { tree } = await git.readTree({ fs, dir, oid, cache });
45 for (const e of tree) {
46 const path = prefix === "" ? e.path : `${prefix}/${e.path}`;
47 if (e.type === "tree") await readTreeFiles(fs, dir, e.oid, path, files, trees, cache);
48 else if (e.type === "blob") files.set(path, { oid: e.oid, mode: e.mode });
49 }
50 return { files, trees };
53/**
54 * Hash the Git header and content separately so export does not allocate a second whole-file buffer.
55 */
56export async function blobOid(bytes: Uint8Array): Promise<string> {
57 return createHash("sha1").update(`blob ${bytes.byteLength}\0`).update(bytes).digest("hex");
60const parentOf = (path: string) => {
61 const cut = path.lastIndexOf("/");
62 return cut < 0 ? "" : path.slice(0, cut);
63};
65/**
66 * The tree for `files`, written bottom up. A folder with nothing changed under it keeps its old tree oid (`before`),
67 * so only the folders on a changed path are written again.
68 */
69export async function writeTrees(
70 fs: MemoryFS,
71 dir: string,
72 files: Map<string, TreeFile>,
73 before: Map<string, string>,
74 changed: Set<string>,
75): Promise<string> {
76 const dirty = new Set<string>([""]);
77 for (const path of changed) for (let d = parentOf(path); d !== ""; d = parentOf(d)) dirty.add(d);
78 type Entry = { mode: string; oid: string; type: "blob" | "tree" };
79 const kids = new Map<string, Map<string, Entry>>([["", new Map()]]);
80 const folder = (d: string) => {
81 let k = kids.get(d);
82 if (!k) {
83 kids.set(d, (k = new Map()));
84 if (d !== "") folder(parentOf(d));
85 }
86 return k;
87 };
88 for (const [path, f] of files)
89 folder(parentOf(path)).set(path.slice(path.lastIndexOf("/") + 1), { ...f, type: "blob" });
90 // Deepest first, so a folder's subfolders have their oids before it is written.
91 const depth = (d: string) => (d === "" ? 0 : d.split("/").length);
92 const order = [...kids.keys()].sort((a, b) => depth(b) - depth(a));
93 let root = "";
94 for (const d of order) {
95 const old = before.get(d);
96 const oid =
97 old !== undefined && !dirty.has(d)
98 ? old
99 : await git.writeTree({ fs, dir, tree: [...kids.get(d)!].map(([path, e]) => ({ path, ...e })) });
100 if (d === "") root = oid;
101 else folder(parentOf(d)).set(d.slice(d.lastIndexOf("/") + 1), { mode: "040000", oid, type: "tree" });
102 }
103 return root;
106/**
107 * A project's Artifacts repo: abso-<project>. Project names are letters, digits, ".", "_" and "-" (validName), which
108 * repo names take as they are.
109 */
110export function repoName(project: string): string {
111 return `abso-${project}`;
114/** The project one of our repos holds, or null for a repo that isn't ours. */
115export function projectOfRepo(repo: string): string | null {
116 return repo.startsWith("abso-") && repo.length > "abso-".length ? repo.slice("abso-".length) : null;
119/** The repo's remote and a write token good for `seconds`, creating the repo if it's new. */
120export async function writeAccess(
121 artifacts: Artifacts,
122 name: string,
123 seconds = 600,
124): Promise<{ remote: string; secret: string }> {
125 try {
126 using repo = await artifacts.get(name);
127 const [info, token] = await Promise.all([repo.info(), repo.createToken("write", seconds)]);
128 return { remote: info!.remote, secret: token.plaintext.split("?expires=")[0]! };
129 } catch {
130 const created = await artifacts.create(name, { description: `abso project ${name}`, setDefaultBranch: "main" });
131 return { remote: created.remote, secret: created.token.split("?expires=")[0]! };
132 }
135export interface SharedFiles {
136 version: number;
137 files: Record<string, string>;
138 modes?: FileModes;
139 blobs?: Record<string, string>;
140 last?: { agent: string; message: string };
143/**
144 * Shared's files as commits on top of `head` (null: a repo with no main yet), in the repo at `dir`. `part` is called
145 * with each earlier part's commit when the new blobs are too big for one push. Answers the last commit and how many
146 * paths changed.
147 */
148export async function commitShared(
149 fs: MemoryFS,
150 dir: string,
151 head: string | null,
152 shared: SharedFiles,
153 readBlob: (sha256: string) => Uint8Array | null,
154 part: (commit: string) => Promise<void> = async () => {},
155 cache?: object,
156): Promise<{ commit: string; changed: number }> {
157 const old = head
158 ? await readTreeFiles(
159 fs,
160 dir,
161 (await git.readCommit({ fs, dir, oid: head, cache })).commit.tree,
162 "",
163 new Map(),
164 new Map(),
165 cache,
166 )
167 : { files: new Map<string, TreeFile>(), trees: new Map<string, string>() };
168 const blobs = shared.blobs ?? {};
169 const now = new Map<string, TreeFile>();
170 const changed = new Set<string>();
171 for (const path of old.files.keys()) if (!(path in shared.files) && !(path in blobs)) changed.add(path);
172 // A file whose blob and mode match the last push keeps its entry; only a new blob is compressed and written.
173 const put = async (path: string, bytes: Uint8Array, mode: string, oid: string) => {
174 const was = old.files.get(path);
175 if (was?.oid !== oid) await git.writeBlob({ fs, dir, blob: bytes });
176 if (was?.oid !== oid || was.mode !== mode) changed.add(path);
177 now.set(path, { oid, mode });
178 };
179 // Each file goes into the tree as a blob with its mode (#27): 100755 for exec, 120000 for a link, whose blob is
180 // its target.
181 const enc = new TextEncoder();
182 const agent = shared.last?.agent ?? "abso";
183 const author = { name: agent, email: `${agent}@abso.invalid` };
184 const committer = { name: "abso", email: "abso@abso.invalid" };
185 const say = (p: string) => `${shared.last?.message ?? "Start the project"}${p}\n\nabso-version: ${shared.version}\n`;
186 let parent = head;
187 // A part holds what's written so far and preserves old entries for files not reached yet.
188 const commitNow = async (message: string) => {
189 const files = new Map(now);
190 for (const [path, f] of old.files)
191 if (!files.has(path) && (path in blobs || path in shared.files)) files.set(path, f);
192 const tree = await writeTrees(fs, dir, files, old.trees, changed);
193 parent = await git.commit({
194 cache,
195 fs,
196 dir,
197 message,
198 author,
199 committer,
200 tree,
201 parent: parent ? [parent] : [],
202 ref: "main",
203 });
204 return parent;
205 };
206 // Artifacts refuses a push much over 20 MB, so when new text or binary blobs add up
207 // to more than PUSH_BATCH, the earlier ones go in commits of their own
208 // first. Every part carries abso-version, so intake never takes them in.
209 let pending = 0;
210 let parts = 0;
211 for (const path of Object.keys(shared.files)) {
212 const mode = shared.modes?.[path];
213 const link = typeof mode?.link === "string" ? mode.link : null;
214 const bytes = enc.encode(link ?? shared.files[path]!);
215 const oid = await blobOid(bytes);
216 const fresh = old.files.get(path)?.oid !== oid;
217 if (fresh && pending > 0 && pending + bytes.byteLength > PUSH_BATCH) {
218 await part(await commitNow(say(` (part ${++parts})`)));
219 pending = 0;
220 }
221 if (fresh) pending += bytes.byteLength;
222 await put(path, bytes, link !== null ? "120000" : mode?.exec ? "100755" : "100644", oid);
223 }
224 for (const [path, sha] of Object.entries(blobs)) {
225 const bytes = readBlob(sha);
226 if (!bytes) throw new Error(`${path}: blob ${sha} is missing from the project's store`);
227 const oid = await blobOid(bytes);
228 const fresh = old.files.get(path)?.oid !== oid;
229 if (fresh && pending > 0 && pending + bytes.byteLength > PUSH_BATCH) {
230 await part(await commitNow(say(` (part ${++parts})`)));
231 pending = 0;
232 }
233 if (fresh) pending += bytes.byteLength;
234 await put(path, bytes, shared.modes?.[path]?.exec ? "100755" : "100644", oid);
235 }
236 const commit = await commitNow(say(parts > 0 ? ` (part ${parts + 1}, last)` : ""));
237 return { commit, changed: changed.size };
240export async function pushShared(
241 artifacts: Artifacts,
242 project: string,
243 shared: SharedFiles,
244 /** A binary file's bytes by SHA-256 (#27), from the project's blob store. */
245 readBlob: (sha256: string) => Uint8Array | null = () => null,
246 disk?: { storage: SqliteStorage; maxPackBytes: number; maxObjectBytes: number; maxDecodedBytes: number },
247): Promise<PushResult> {
248 const t0 = Date.now();
249 const name = repoName(project);
250 const { remote, secret } = await writeAccess(artifacts, name);
251 const onAuth = () => ({ username: "x", password: secret });
252 using contents = disk ? new GitFileContents(disk.storage, disk.maxObjectBytes, disk.maxDecodedBytes) : undefined;
253 using intake = disk
254 ? new GitDiskIntake(disk.storage, disk.maxPackBytes, disk.maxObjectBytes, disk.maxDecodedBytes)
255 : undefined;
256 const cache = disk ? {} : undefined;
257 if (intake && cache) intake.attach(cache);
258 const transport = disk ? gitHttp() : http;
259 let fs = new MemoryFS(contents);
260 const dir = "/repo";
261 // A new repo has no main yet. isomorphic-git "clones" an empty repo without
262 // an error but leaves HEAD on master, so check for main and start clean.
263 // Nothing is checked out: the new tree is built from tree objects (293).
264 // Only an explicitly absent main is an empty repository. Transport, decode,
265 // and size failures must never become permission to replace remote history.
266 const refs = await git.listServerRefs({ http: transport, url: remote, onAuth, prefix: "refs/heads/main" });
267 let head: string | null = null;
268 if (refs.some((ref) => ref.ref === "refs/heads/main")) {
269 await git.clone({
270 fs,
271 http: transport,
272 cache,
273 dir,
274 url: remote,
275 ref: "main",
276 singleBranch: true,
277 depth: 1,
278 noCheckout: true,
279 onAuth,
280 });
281 intake?.assertReady();
282 head = await git.resolveRef({ fs, dir, ref: "main" });
283 }
284 if (head === null) {
285 fs = new MemoryFS(contents);
286 await git.init({ fs, dir, defaultBranch: "main" });
287 }
288 const t1 = Date.now();
289 const push = () => git.push({ fs, http: transport, cache, dir, url: remote, ref: "main", remoteRef: "main", onAuth });
290 const { commit, changed } = await commitShared(
291 fs,
292 dir,
293 head,
294 shared,
295 readBlob,
296 async () => void (await push()),
297 cache,
298 );
299 const t2 = Date.now();
300 await push();
301 console.log(
302 `push ${project} v${shared.version}: clone ${t1 - t0} ms, files ${t2 - t1} ms (${changed} changed), push ${Date.now() - t2} ms`,
303 );
304 return { repo: name, remote, commit, version: shared.version, ms: Date.now() - t0 };