notusci 0.1.1 → 0.1.3

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 (3) hide show
  1. package/package.json +1 -1
  2. package/src/cli.mjs +87 -9
  3. package/src/core.mjs +106 -12
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notusci",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "CI for coding agents: verify uncommitted changes with your GitHub Actions workflow and get typed JSON",
5
5
  "license": "MIT",
6
6
  "homepage": "https://ci.notusworks.com",
package/src/cli.mjs CHANGED
@@ -7,8 +7,8 @@ import { homedir, hostname } from "node:os";
7
7
  import { delimiter, dirname, join } from "node:path";
8
8
  import { setTimeout as sleep } from "node:timers/promises";
9
9
  import {
10
- CliError, HELP, NPX, boundedWaitSeconds, buildSource, encodeSource, parseCommand, pickWorkflow, renderError,
11
- repositoryFromRemote, runPath, setCodexServer, setCursorServer, shouldWaitAgain,
10
+ CliError, HELP, NPX, authFile, baseAttachment, boundedWaitSeconds, buildSource, dependencyHint, encodeSource, parseCommand, pickWorkflow, renderError,
11
+ repositoryFromRemote, runPath, setCodexServer, setCursorServer, shouldWaitAgain, sourceBaseSha, sourceIdentity,
12
12
  } from "./core.mjs";
13
13
 
14
14
  const DEFAULT_URL = "https://notusci-api.binh-08d.workers.dev";
@@ -17,7 +17,7 @@ const LOCAL_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
17
17
 
18
18
  /** @param {unknown} value */
19
19
  const print = value => process.stdout.write(`${JSON.stringify(value)}\n`);
20
- const authPath = () => join(homedir(), ".config", "notusci", "auth.json");
20
+ const authPath = () => authFile(process.env.NOTUSCI_CONFIG_DIR, homedir());
21
21
 
22
22
  /** @param {string} path @param {string} text */
23
23
  function writePrivate(path, text) {
@@ -27,7 +27,7 @@ function writePrivate(path, text) {
27
27
  renameSync(temp, path);
28
28
  }
29
29
 
30
- /** @typedef {{url: string, token?: string, state: {url?: string, token?: string, pending?: any}}} Session */
30
+ /** @typedef {{url: string, token?: string, state: {url?: string, token?: string, pending?: any, billing?: any}}} Session */
31
31
 
32
32
  /** @returns {Session} */
33
33
  function session() {
@@ -43,7 +43,7 @@ function session() {
43
43
  return { url: base, token: process.env.NOTUSCI_TOKEN ?? ((state.url ?? DEFAULT_URL) === base ? state.token : undefined), state };
44
44
  }
45
45
 
46
- /** Save the token and pending login; a URL from NOTUSCI_URL is not persisted. @param {Session} s @param {{token?: string, pending?: any}} state */
46
+ /** Save private CLI state; a URL from NOTUSCI_URL is not persisted. @param {Session} s @param {{token?: string, pending?: any, billing?: any}} state */
47
47
  function save(s, state) {
48
48
  s.state = { url: process.env.NOTUSCI_URL ? s.state.url : s.url, ...state };
49
49
  writePrivate(authPath(), `${JSON.stringify(s.state, null, 2)}\n`);
@@ -217,9 +217,35 @@ async function init(s, input) {
217
217
  catch { mcp[name] = "failed"; }
218
218
  }
219
219
  }
220
+ if (input.billing) return billing(s, { repo, timeoutSeconds: 90 });
220
221
  print({ status: "ready", user: me.user, repo: listed(me, repo).repo, scopes: me.scopes, workflow, mcp, next: `${NPX} verify` });
221
222
  }
222
223
 
224
+ /** @param {Session} s @param {{repo?: string, timeoutSeconds: number}} input */
225
+ async function billing(s, input) {
226
+ const repo = repoOrOrigin(input.repo);
227
+ const deadline = Date.now() + input.timeoutSeconds * 1000;
228
+ let status = await api(s, "/api/billing", { query: { repo }, deadline });
229
+ if (status.status === "active") {
230
+ save(s, { token: s.state.token, pending: s.state.pending });
231
+ return print({ status: "ready", billing: status, next: `${NPX} verify` });
232
+ }
233
+ let action = s.state.billing;
234
+ if (!action || action.repo.toLowerCase() !== repo.toLowerCase() || new Date(action.expiresAt).getTime() <= Date.now()) {
235
+ action = { ...await api(s, "/api/billing/checkouts", { method: "POST", body: { repo }, deadline }), repo };
236
+ save(s, { token: s.state.token, pending: s.state.pending, billing: action });
237
+ }
238
+ while (Date.now() + 2_000 <= deadline) {
239
+ await sleep(2_000);
240
+ status = await api(s, "/api/billing", { query: { repo }, deadline });
241
+ if (status.status === "active") {
242
+ save(s, { token: s.state.token, pending: s.state.pending });
243
+ return print({ status: "ready", billing: status, next: `${NPX} verify` });
244
+ }
245
+ }
246
+ print({ status: "action_required", action: action.action, expiresAt: action.expiresAt });
247
+ }
248
+
223
249
  /** @param {Session} s */
224
250
  async function doctor(s) {
225
251
  /** @type {any[]} */
@@ -279,6 +305,38 @@ async function waitUntilReady(s, path, repo, deadline = Infinity) {
279
305
  }
280
306
  }
281
307
 
308
+ /** @param {Session} s @param {string} root @param {string} repo @param {string} workflow @param {number} timeoutSeconds @param {string} [rerunOf] */
309
+ async function verify(s, root, repo, workflow, timeoutSeconds, rerunOf) {
310
+ const baseSha = sourceBaseSha(root); const startedAt = performance.now(); const deadline = Date.now() + timeoutSeconds * 1000;
311
+ const base = await api(s, "/api/verify/base", { query: { repo, baseSha, workflow }, deadline });
312
+ if (base?.schemaVersion !== 2 || typeof base.present !== "boolean") throw new Error("invalid base probe response");
313
+ const source = buildSource(root, false);
314
+ if (source.baseSha !== baseSha) throw new Error("HEAD changed during verification upload");
315
+ const expectedIdentity = sourceIdentity(repo, source); const idempotencyKey = randomUUID();
316
+ const hint = dependencyHint(root, repo, workflow);
317
+ let body = { ...source, ...(hint ? { dependencyHint: hint } : {}) };
318
+ if (!base.present) {
319
+ const full = buildSource(root);
320
+ if (sourceIdentity(repo, full) !== expectedIdentity) throw new Error("working tree changed during verification upload");
321
+ body = { ...body, objects: full.objects };
322
+ }
323
+ let submitted = await api(s, "/api/verify/v2", { method: "POST", body: encodeSource(body), timeoutSeconds: 300,
324
+ deadline, query: { repo, workflow, idempotencyKey, rerunOf } });
325
+ if (submitted?.schemaVersion !== 2 || typeof submitted.verifyId !== "string" || submitted.sourceIdentity !== expectedIdentity
326
+ || typeof submitted.baseRequired !== "boolean")
327
+ throw new Error("invalid Source v2 admission response");
328
+ if (submitted.baseRequired) {
329
+ const full = buildSource(root);
330
+ if (sourceIdentity(repo, full) !== expectedIdentity) throw new Error("working tree changed during base attachment");
331
+ submitted = await api(s, `/api/verifies/${submitted.verifyId}/base`, { method: "PUT", body: encodeSource(baseAttachment(full)), timeoutSeconds: 300,
332
+ deadline, query: { repo } });
333
+ if (submitted?.schemaVersion !== 2 || typeof submitted.verifyId !== "string" || submitted.sourceIdentity !== expectedIdentity || submitted.baseRequired !== false)
334
+ throw new Error("invalid Source v2 base attachment response");
335
+ }
336
+ const result = await waitUntilReady(s, `/api/verifies/${submitted.verifyId}/wait`, repo, deadline);
337
+ return { ...result, clientTiming: { probeToReadyMs: Math.round((performance.now() - startedAt) * 1000) / 1000 } };
338
+ }
339
+
282
340
  /** Print a verify or ship result; one stopped by usage limits is also an error. @param {any} result */
283
341
  function report(result) {
284
342
  print(result);
@@ -291,7 +349,16 @@ async function main(s, input) {
291
349
  case "init": return init(s, input);
292
350
  case "doctor": return doctor(s);
293
351
  case "login": return login(s, input);
352
+ case "billing": return billing(s, input);
294
353
  case "logout": return logout(s);
354
+ case "whoami": {
355
+ const { user, scopes, repos, installUrl } = await api(s, "/api/whoami");
356
+ return print({ user, scopes, repos, installUrl });
357
+ }
358
+ case "repos": {
359
+ const { user, repos, installUrl } = await api(s, "/api/whoami");
360
+ return print({ user, repos, installUrl });
361
+ }
295
362
  case "token list": return print({ tokens: await api(s, "/api/tokens") });
296
363
  case "token revoke":
297
364
  await api(s, `/api/tokens/${encodeURIComponent(input.id)}`, { method: "DELETE" });
@@ -307,28 +374,39 @@ async function main(s, input) {
307
374
  case "verify": {
308
375
  const { root, repo } = gitRepo();
309
376
  const workflow = input.workflow ?? workflowIn(root);
310
- const source = buildSource(root);
311
- const { verifyId } = await api(s, "/api/verifies", { method: "POST", body: encodeSource(source), timeoutSeconds: 300,
312
- query: { repo, workflow, idempotencyKey: randomUUID(), baseSha: source.baseSha } });
313
- return report(await waitUntilReady(s, `/api/verifies/${verifyId}/wait`, repo, Date.now() + input.timeoutSeconds * 1000));
377
+ return report(await verify(s, root, repo, workflow, input.timeoutSeconds));
314
378
  }
315
379
  case "ship": {
316
380
  const repo = repoOrOrigin(input.repo);
317
381
  const { shipId } = await api(s, "/api/ships", { method: "POST", body: { repo, pushRunId: input.runId } });
318
382
  return report(await waitUntilReady(s, `/api/ships/${shipId}/wait`, repo));
319
383
  }
384
+ case "approve": {
385
+ const repo = repoOrOrigin(input.repo);
386
+ return print(await api(s, `/api/pull-requests/${input.runId}/approve`, { method: "POST", query: { repo } }));
387
+ }
320
388
  case "wait": {
321
389
  const repo = repoOrOrigin(input.repo);
322
390
  if (input.timeoutSeconds === undefined) return print(await api(s, runPath(input.runId, "wait"), { query: { repo }, timeoutSeconds: 35 }));
323
391
  return print(await waitUntilReady(s, runPath(input.runId, "wait"), repo, Date.now() + input.timeoutSeconds * 1000));
324
392
  }
325
393
  case "failures": return print(await api(s, runPath(input.runId, "failures"), { query: { repo: repoOrOrigin(input.repo) } }));
394
+ case "search-logs": {
395
+ const kind = typeof input.runId === "string" ? "pushes" : "runs";
396
+ return print(await api(s, `/api/${kind}/${input.runId}/logs/search`, { query: { repo: repoOrOrigin(input.repo), query: input.query, limit: input.limit } }));
397
+ }
398
+ case "rerun-failed": {
399
+ const { root, repo } = gitRepo();
400
+ const failed = await api(s, `/api/verifies/${input.failedVerifyId}/wait`, { query: { repo, timeoutSeconds: 1 } });
401
+ return report(await verify(s, root, repo, failed.workflow, input.timeoutSeconds, input.failedVerifyId));
402
+ }
326
403
  }
327
404
  }
328
405
 
329
406
  try {
330
407
  const input = parseCommand(process.argv.slice(2));
331
408
  if (input.command === "help") print(HELP);
409
+ else if (input.command === "version") print({ version: JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version });
332
410
  else await main(session(), input);
333
411
  }
334
412
  catch (error) {
package/src/core.mjs CHANGED
@@ -1,6 +1,8 @@
1
1
  import { execFileSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
2
3
  import { lstatSync, readFileSync, readlinkSync } from "node:fs";
3
4
  import { Buffer } from "node:buffer";
5
+ import { join } from "node:path";
4
6
  import { parseArgs } from "node:util";
5
7
 
6
8
  const repositoryPattern = /^[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+$/;
@@ -10,6 +12,8 @@ const MAX_TREE_BYTES = 256 * 1024 * 1024;
10
12
  const MAX_PATHS = 20_000;
11
13
  const MAX_PATH_BYTES = 1_024;
12
14
  export const NPX = "npx -y notusci@latest";
15
+ /** @param {string | undefined} configDir @param {string} home */
16
+ export const authFile = (configDir, home) => configDir ? join(configDir, "auth.json") : join(home, ".config", "notusci", "auth.json");
13
17
  const SCOPES = ["read", "verify", "ship:staging", "ship:prod"];
14
18
  const DEFAULT_SCOPES = SCOPES.join(",");
15
19
 
@@ -26,21 +30,29 @@ function usage(error) {
26
30
 
27
31
  /** @type {Record<string, Record<string, {type: "string" | "boolean"}>>} */
28
32
  const OPTIONS = {
29
- init: { scope: { type: "string" }, "no-mcp": { type: "boolean" } },
33
+ init: { scope: { type: "string" }, "no-mcp": { type: "boolean" }, billing: { type: "boolean" } },
30
34
  login: { scope: { type: "string" } },
31
- doctor: {}, logout: {}, token: {},
35
+ doctor: {}, logout: {}, token: {}, whoami: {}, repos: {}, version: {}, "--version": {},
32
36
  target: { repo: { type: "string" }, file: { type: "string" }, "auto-promote": { type: "string" } },
33
37
  verify: { workflow: { type: "string" }, timeout: { type: "string" } },
34
38
  wait: { repo: { type: "string" }, timeout: { type: "string" } },
35
39
  failures: { repo: { type: "string" } },
40
+ "search-logs": { repo: { type: "string" }, query: { type: "string" }, limit: { type: "string" } },
41
+ "rerun-failed": { timeout: { type: "string" } },
36
42
  ship: { repo: { type: "string" } },
43
+ approve: { repo: { type: "string" } },
44
+ billing: { repo: { type: "string" }, timeout: { type: "string" } },
37
45
  };
38
46
 
39
47
  export const HELP = {
40
48
  commands: [
41
- "init [--scope SCOPES] [--no-mcp]", "doctor", "login [--scope SCOPES]", "logout", "token list", "token revoke ID",
42
- "target set --repo OWNER/REPO --file TARGET.json [--auto-promote on|off]", "verify [--workflow PATH] [--timeout SECONDS]",
49
+ "init [--scope SCOPES] [--no-mcp] [--billing]", "billing [--repo OWNER/REPO] [--timeout SECONDS]", "doctor",
50
+ "login [--scope SCOPES]", "logout", "whoami", "repos", "token list", "token revoke ID",
51
+ "target set [--repo OWNER/REPO] --file TARGET.json [--auto-promote on|off]", "verify [--workflow PATH] [--timeout SECONDS]",
43
52
  "wait ID [--repo OWNER/REPO] [--timeout SECONDS]", "failures ID [--repo OWNER/REPO]", "ship ID [--repo OWNER/REPO]",
53
+ "approve ID [--repo OWNER/REPO]",
54
+ "search-logs ID --query LITERAL [--limit COUNT] [--repo OWNER/REPO]",
55
+ "rerun-failed ID [--timeout SECONDS]", "--version",
44
56
  ],
45
57
  scopes: SCOPES,
46
58
  docs: "https://ci.notusworks.com/docs/agents.md",
@@ -74,9 +86,10 @@ export function parseCommand(args) {
74
86
  const scopes = [...new Set((values.scope ?? DEFAULT_SCOPES).split(","))];
75
87
  const unknown = scopes.filter(scope => !SCOPES.includes(scope));
76
88
  if (unknown.length) throw usage(`unknown scope ${unknown.join(",")}; scopes are ${SCOPES.join(",")}`);
77
- return command === "init" ? { command, scopes, mcp: !values["no-mcp"] } : { command, scopes };
89
+ return command === "init" ? { command, scopes, mcp: !values["no-mcp"], billing: values.billing === true } : { command, scopes };
78
90
  }
79
- if (command === "doctor" || command === "logout") { expect(); return { command }; }
91
+ if (["doctor", "logout", "whoami", "repos"].includes(command)) { expect(); return { command }; }
92
+ if (command === "version" || command === "--version") { expect(); return { command: "version" }; }
80
93
  if (command === "token") {
81
94
  if (positionals[0] === "revoke") { expect("revoke", "*"); return { command: "token revoke", id: positionals[1] }; }
82
95
  expect("list");
@@ -94,12 +107,29 @@ export function parseCommand(args) {
94
107
  if (values.workflow === "") throw usage("--workflow must not be empty");
95
108
  return { command, workflow: values.workflow, timeoutSeconds: timeoutSeconds ?? 540 };
96
109
  }
110
+ if (command === "billing") { expect(); return { command, repo: values.repo, timeoutSeconds: timeoutSeconds ?? 90 }; }
111
+ if (command === "search-logs") {
112
+ expect("*"); const runId = /^[1-9]\d*$/.test(positionals[0]) ? Number(positionals[0]) : positionals[0].toLowerCase();
113
+ if ((typeof runId === "number" ? !Number.isSafeInteger(runId) : !isPushRunId(runId)) || !values.query) throw usage("search-logs requires a valid ID and --query");
114
+ const limit = values.limit === undefined ? undefined : Number(values.limit);
115
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 100)) throw usage("--limit must be 1 through 100");
116
+ return { command, runId, repo: values.repo, query: values.query, limit };
117
+ }
118
+ if (command === "rerun-failed") {
119
+ expect("*"); const id = positionals[0].toLowerCase();
120
+ if (!isPushRunId(id)) throw usage("rerun-failed requires a verify UUID");
121
+ return { command, failedVerifyId: id, timeoutSeconds: timeoutSeconds ?? 540 };
122
+ }
97
123
  expect("*");
98
124
  const raw = positionals[0];
99
125
  const runId = /^[1-9]\d*$/.test(raw) ? Number(raw) : raw.toLowerCase();
100
126
  if (typeof runId === "number" ? !Number.isSafeInteger(runId) : !isPushRunId(runId)) {
101
127
  throw usage("ID must be a positive safe integer or UUID");
102
128
  }
129
+ if (command === "approve") {
130
+ if (typeof runId !== "string") throw usage("approve requires a NotusCI pull request run UUID");
131
+ return { command, runId, repo: values.repo };
132
+ }
103
133
  if (command === "ship") {
104
134
  if (typeof runId !== "string") throw usage("ship requires a NotusCI push UUID");
105
135
  return { command, runId, repo: values.repo };
@@ -135,8 +165,8 @@ export function renderError({ error = "", code, next, ...extra }, now = Date.now
135
165
  next: `Tell the human the monthly limit is reached and resets on ${resetsOn}. Do not retry.`, ...extra, resetsOn };
136
166
  }
137
167
  if (code === "payment_required") {
138
- return { error: "The 300-minute NotusCI trial is used up. Card setup is coming soon.", code,
139
- next: "Tell the human the trial is used up and card setup is coming soon. Do not retry.", ...extra };
168
+ return { error: "The 300-minute NotusCI trial is used up. Set up billing to continue.", code,
169
+ next: `${NPX} billing`, ...extra };
140
170
  }
141
171
  if (code === "missing_scope") return { error, code, next: `${NPX} login --scope ${String(extra.scopes)}`, ...extra };
142
172
  /** @type {Record<string, string>} */
@@ -226,6 +256,63 @@ function checkPath(path) {
226
256
  if (!path || Buffer.byteLength(path) > MAX_PATH_BYTES) throw new Error(`path exceeds ${MAX_PATH_BYTES} bytes: ${path}`);
227
257
  }
228
258
 
259
+ /** @param {string} a @param {string} b */
260
+ const utf8Compare = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
261
+
262
+ /** @param {Buffer|string} value */
263
+ const sha256 = value => createHash("sha256").update(value).digest("hex");
264
+
265
+ /** Compute the transport-neutral identity for a normalized Source v2 overlay.
266
+ * @param {string} repo @param {{baseSha:string,overlay:{path:string,mode:string,data:string}[],deletions:string[]}} source */
267
+ export function sourceIdentity(repo, source) {
268
+ const hash = createHash("sha256");
269
+ hash.update(`notusci-source-v2\0repo\0${repo.toLowerCase()}\0base\0${source.baseSha}\0`);
270
+ for (const file of [...source.overlay].sort((a, b) => utf8Compare(a.path, b.path))) {
271
+ const bytes = Buffer.from(file.data, "base64");
272
+ hash.update(`file\0${Buffer.byteLength(file.path)}\0${file.path}\0${file.mode}\0${sha256(bytes)}\0`);
273
+ }
274
+ for (const path of [...source.deletions].sort(utf8Compare)) hash.update(`delete\0${Buffer.byteLength(path)}\0${path}\0`);
275
+ return hash.digest("hex");
276
+ }
277
+
278
+ /** Attach only the immutable Git base; the receipt already owns its overlay.
279
+ * @param {{baseSha:string,objects?:{oid:string,type:string,data:string}[],overlay?:unknown[],deletions?:string[]}} source */
280
+ export function baseAttachment(source) {
281
+ return { schemaVersion: 1, baseSha: source.baseSha, objects: source.objects ?? [], overlay: [], deletions: [] };
282
+ }
283
+
284
+ const dependencyNames = new Set(["pnpm-lock.yaml", "pnpm-workspace.yaml", "package.json", ".npmrc", "pnpmfile.cjs", ".pnpmfile.cjs"]);
285
+
286
+ /** @param {string} repo @param {string} workflow @param {{path:string,mode:string,bytes:Buffer}[]} files */
287
+ export function dependencyHintForFiles(repo, workflow, files) {
288
+ const entries = [];
289
+ for (const file of [...files].sort((a, b) => utf8Compare(a.path, b.path))) {
290
+ if (file.path.endsWith("pnpm-lock.yaml") && /^\s*patchedDependencies:\s*(?:#.*)?$/m.test(file.bytes.toString("utf8"))) return undefined;
291
+ entries.push(`file\0${Buffer.byteLength(file.path)}\0${file.path}\0${file.mode}\0${sha256(file.bytes)}\0`);
292
+ }
293
+ return sha256(`notusci-dependency-hint-v1\0repo\0${repo.toLowerCase()}\0workflow\0${Buffer.byteLength(workflow)}\0${workflow}\0${entries.join("")}`);
294
+ }
295
+
296
+ /** A conservative, untrusted snapshot candidate hint. @param {string} cwd @param {string} repo @param {string} workflow */
297
+ export function dependencyHint(cwd, repo, workflow) {
298
+ const root = git(cwd, ["rev-parse", "--show-toplevel"]).toString().trim();
299
+ const candidates = new Set(paths(git(root, ["ls-files", "-co", "--exclude-standard", "-z"])));
300
+ candidates.add(workflow);
301
+ const selected = [...candidates].filter(path => path === workflow || dependencyNames.has(path.slice(path.lastIndexOf("/") + 1))).sort(utf8Compare);
302
+ const files = [];
303
+ for (const path of selected) {
304
+ checkPath(path);
305
+ let stat;
306
+ try { stat = lstatSync(`${root}/${path}`); } catch { return undefined; }
307
+ let mode, bytes;
308
+ if (stat.isSymbolicLink()) { mode = "120000"; bytes = Buffer.from(readlinkSync(`${root}/${path}`)); }
309
+ else if (stat.isFile()) { mode = stat.mode & 0o111 ? "100755" : "100644"; bytes = readFileSync(`${root}/${path}`); }
310
+ else return undefined;
311
+ files.push({ path, mode, bytes });
312
+ }
313
+ return dependencyHintForFiles(repo, workflow, files);
314
+ }
315
+
229
316
  /** @param {string} entry */
230
317
  export function parseTreeEntry(entry) {
231
318
  const tab = entry.indexOf("\t");
@@ -234,11 +321,18 @@ export function parseTreeEntry(entry) {
234
321
  return { mode: match[1], type: match[2], oid: match[3], size: Number(match[4]), path: entry.slice(tab + 1) };
235
322
  }
236
323
 
237
- /** Build the raw Git base and final local overlay. @param {string} cwd */
238
- export function buildSource(cwd) {
324
+ /** @param {string} cwd */
325
+ export function sourceBaseSha(cwd) {
239
326
  const root = git(cwd, ["rev-parse", "--show-toplevel"]).toString().trim();
240
327
  const baseSha = git(root, ["rev-parse", "--verify", "HEAD"]).toString().trim();
241
328
  if (!/^[0-9a-f]{40}$/.test(baseSha)) throw new Error("HEAD must resolve to a SHA-1 commit");
329
+ return baseSha;
330
+ }
331
+
332
+ /** Build the raw Git base and final local overlay. @param {string} cwd */
333
+ export function buildSource(cwd, includeObjects = true) {
334
+ const root = git(cwd, ["rev-parse", "--show-toplevel"]).toString().trim();
335
+ const baseSha = sourceBaseSha(root);
242
336
  /** @type {Map<string,number>} */
243
337
  const finalFiles = new Map();
244
338
  for (const entry of paths(git(root, ["ls-tree", "-rlz", "--full-tree", baseSha]))) {
@@ -250,7 +344,7 @@ export function buildSource(cwd) {
250
344
  if (!Number.isSafeInteger(size)) throw new Error(`invalid Git tree entry: ${path}`);
251
345
  finalFiles.set(path, size);
252
346
  }
253
- const objectIds = [baseSha, ...git(root, ["rev-list", "--objects", "--no-object-names", `${baseSha}^{tree}`]).toString().trim().split("\n").filter(Boolean)];
347
+ const objectIds = includeObjects ? [baseSha, ...git(root, ["rev-list", "--objects", "--no-object-names", `${baseSha}^{tree}`]).toString().trim().split("\n").filter(Boolean)] : [];
254
348
  let decodedBytes = 0;
255
349
  const objects = objectIds.map(oid => {
256
350
  const type = git(root, ["cat-file", "-t", oid]).toString().trim();
@@ -292,7 +386,7 @@ export function buildSource(cwd) {
292
386
  let finalBytes = 0;
293
387
  for (const size of finalFiles.values()) finalBytes += size;
294
388
  if (finalBytes > MAX_TREE_BYTES) throw new Error("resolved source exceeds the 256 MiB decoded limit");
295
- return { schemaVersion: 1, baseSha, objects, overlay, deletions };
389
+ return { schemaVersion: includeObjects ? 1 : 2, baseSha, ...(includeObjects ? { objects } : {}), overlay, deletions };
296
390
  }
297
391
 
298
392
  /** @param {ReturnType<typeof buildSource>} source */