notusci 0.1.5 → 0.1.9

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 +50 -31
  3. package/src/core.mjs +142 -79
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notusci",
3
- "version": "0.1.5",
3
+ "version": "0.1.9",
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, authFile, baseAttachment, boundedWaitSeconds, buildSource, dependencyHint, encodeSource, parseCommand, pickWorkflow, renderError,
11
- repositoryFromRemote, runPath, setCodexServer, setCursorServer, shouldWaitAgain, sourceBaseSha, sourceIdentity,
10
+ CliError, HELP, NPX, apiUrl, authFile, boundedWaitSeconds, buildSource, dependencyHint, encodeSource, jsonText, parseCommand, pickWorkflow, renderError,
11
+ repositoryFromRemote, runPath, setCodexServer, setCursorServer, shouldWaitAgain, sourceBase, sourceIdentity,
12
12
  } from "./core.mjs";
13
13
 
14
14
  const DEFAULT_URL = "https://notusci-api.binh-08d.workers.dev";
@@ -305,44 +305,41 @@ async function waitUntilReady(s, path, repo, deadline = Infinity) {
305
305
  }
306
306
  }
307
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");
308
+ /** Upload only what GitHub doesn't have: the diff against the newest pushed ancestor of HEAD.
309
+ * @param {Session} s @param {string} root @param {string} repo @param {string} workflow @param {number} timeoutSeconds
310
+ * @param {{id: string, baseSha?: string}} [rerun] the failed verify; its base is kept while it still qualifies
311
+ * @param {boolean} [reuse] false runs every step instead of reusing push results (spec 037) */
312
+ async function verify(s, root, repo, workflow, timeoutSeconds, rerun, reuse = true) {
313
+ const startedAt = performance.now(); const deadline = Date.now() + timeoutSeconds * 1000;
314
+ const source = buildSource(root, sourceBase(root, rerun?.baseSha));
315
315
  const expectedIdentity = sourceIdentity(repo, source); const idempotencyKey = randomUUID();
316
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")
317
+ const submitted = await api(s, "/api/verify/v2", { method: "POST", body: encodeSource({ ...source, ...(hint ? { dependencyHint: hint } : {}) }),
318
+ timeoutSeconds: 300, deadline, query: { repo, workflow, idempotencyKey, rerunOf: rerun?.id, reuse: reuse ? undefined : "false" } });
319
+ if (submitted?.schemaVersion !== 2 || typeof submitted.verifyId !== "string" || submitted.sourceIdentity !== expectedIdentity)
327
320
  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
- }
321
+ if (submitted.baseRequired === true) throw new CliError({ code: "server_outdated", error: "this NotusCI server predates diff-only verify",
322
+ next: "Tell the human the NotusCI server needs the spec 036 deploy." });
336
323
  const result = await waitUntilReady(s, `/api/verifies/${submitted.verifyId}/wait`, repo, deadline);
337
324
  return { ...result, clientTiming: { probeToReadyMs: Math.round((performance.now() - startedAt) * 1000) / 1000 } };
338
325
  }
339
326
 
340
327
  /** Print a verify or ship result; one stopped by usage limits is also an error. @param {any} result */
341
328
  function report(result) {
342
- print(result);
329
+ print(result.refusal?.code === "base_not_found"
330
+ ? { ...result, next: "git push, or git fetch --prune so the CLI picks a pushed ancestor, then verify again" } : result);
343
331
  if (result.errorCode) throw new CliError({ code: result.errorCode, error: result.error ?? "" });
344
332
  }
345
333
 
334
+ /** The value of a JSON option: inline, or read from `{ file }`. @param {string} flag @param {{ json?: any, file?: string } | undefined} option */
335
+ function jsonValue(flag, option) {
336
+ if (option?.file === undefined) return option?.json;
337
+ let text;
338
+ try { text = readFileSync(option.file, "utf8"); }
339
+ catch { throw new CliError({ code: "usage", error: `${flag} @${option.file} is not a readable file`, next: "Fix the path and retry." }); }
340
+ return jsonText(flag, text);
341
+ }
342
+
346
343
  /** @param {Session} s @param {any} input */
347
344
  async function main(s, input) {
348
345
  switch (input.command) {
@@ -375,10 +372,26 @@ async function main(s, input) {
375
372
  const saved = await api(s, `/api/repos/${repo}/target`, { method: "PUT", body });
376
373
  return print({ status: "saved", ...saved, ...(saved.autoRelease ? { note: "Every successful push to the default branch now ships itself; with autoPromote on, anyone who can push there deploys to production. Protect the branch." } : {}) });
377
374
  }
375
+ case "secret set": {
376
+ const repo = repoOrOrigin(input.repo);
377
+ // The value comes only from stdin, never argv; one trailing newline is dropped.
378
+ if (process.stdin.isTTY) throw new Error("pipe the value on stdin, e.g. printf %s \"$VALUE\" | notusci secret set NAME");
379
+ const value = readFileSync(0, "utf8").replace(/\r?\n$/, "");
380
+ return print({ status: "saved", ...await api(s, `/api/repos/${repo}/secrets/${encodeURIComponent(input.name)}`, { method: "PUT", body: { value } }) });
381
+ }
382
+ case "secret list": {
383
+ const repo = repoOrOrigin(input.repo);
384
+ return print({ repo, ...await api(s, `/api/repos/${repo}/secrets`) });
385
+ }
386
+ case "secret rm": {
387
+ const repo = repoOrOrigin(input.repo);
388
+ await api(s, `/api/repos/${repo}/secrets/${encodeURIComponent(input.name)}`, { method: "DELETE" });
389
+ return print({ status: "deleted", repo, name: input.name });
390
+ }
378
391
  case "verify": {
379
392
  const { root, repo } = gitRepo();
380
393
  const workflow = input.workflow ?? workflowIn(root);
381
- return report(await verify(s, root, repo, workflow, input.timeoutSeconds));
394
+ return report(await verify(s, root, repo, workflow, input.timeoutSeconds, undefined, input.reuse !== false));
382
395
  }
383
396
  case "ship": {
384
397
  const repo = repoOrOrigin(input.repo);
@@ -387,7 +400,13 @@ async function main(s, input) {
387
400
  }
388
401
  case "repo set": {
389
402
  const repo = repoOrOrigin(input.repo);
390
- return print(await api(s, `/api/repos/${repo}/settings`, { method: "PUT", body: { pushWorkflow: input.pushWorkflow } }));
403
+ const { pushWorkflow, imageFromWorkspace } = input;
404
+ const body = { ...jsonValue("--settings", input.settings), ...(pushWorkflow !== undefined && { pushWorkflow }), ...(imageFromWorkspace !== undefined && { imageFromWorkspace }) };
405
+ return print(await api(s, `/api/repos/${repo}/settings`, { method: "PUT", body }));
406
+ }
407
+ case "api": {
408
+ const url = apiUrl(s.url, input.path);
409
+ return print(await api(s, url.pathname + url.search, { method: input.method, body: jsonValue("--data", input.data) }));
391
410
  }
392
411
  case "migrations list": return print(await api(s, `/api/repos/${repoOrOrigin(input.repo)}/migrations`));
393
412
  case "migrations approve": {
@@ -412,7 +431,7 @@ async function main(s, input) {
412
431
  case "rerun-failed": {
413
432
  const { root, repo } = gitRepo();
414
433
  const failed = await api(s, `/api/verifies/${input.failedVerifyId}/wait`, { query: { repo, timeoutSeconds: 1 } });
415
- return report(await verify(s, root, repo, failed.workflow, input.timeoutSeconds, input.failedVerifyId));
434
+ return report(await verify(s, root, repo, failed.workflow, input.timeoutSeconds, { id: input.failedVerifyId, baseSha: failed.baseSha }));
416
435
  }
417
436
  }
418
437
  }
package/src/core.mjs CHANGED
@@ -8,7 +8,6 @@ import { parseArgs } from "node:util";
8
8
  const repositoryPattern = /^[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+$/;
9
9
  const MAX_WIRE_BYTES = 64 * 1024 * 1024;
10
10
  const MAX_FILE_BYTES = 32 * 1024 * 1024;
11
- const MAX_TREE_BYTES = 256 * 1024 * 1024;
12
11
  const MAX_PATHS = 20_000;
13
12
  const MAX_PATH_BYTES = 1_024;
14
13
  export const NPX = "npx -y notusci@latest";
@@ -34,34 +33,59 @@ const OPTIONS = {
34
33
  login: { scope: { type: "string" } },
35
34
  doctor: {}, logout: {}, token: {}, whoami: {}, repos: {}, version: {}, "--version": {},
36
35
  target: { repo: { type: "string" }, file: { type: "string" }, "auto-promote": { type: "string" }, "auto-release": { type: "string" } },
37
- verify: { workflow: { type: "string" }, timeout: { type: "string" } },
36
+ secret: { repo: { type: "string" } },
37
+ verify: { workflow: { type: "string" }, timeout: { type: "string" }, "no-reuse": { type: "boolean" } },
38
38
  wait: { repo: { type: "string" }, timeout: { type: "string" } },
39
39
  failures: { repo: { type: "string" } },
40
40
  "search-logs": { repo: { type: "string" }, query: { type: "string" }, limit: { type: "string" } },
41
41
  "rerun-failed": { timeout: { type: "string" } },
42
42
  ship: { repo: { type: "string" } },
43
43
  approve: { repo: { type: "string" } },
44
- repo: { repo: { type: "string" }, "push-workflow": { type: "string" }, off: { type: "boolean" } },
44
+ repo: { repo: { type: "string" }, settings: { type: "string" }, "push-workflow": { type: "string" }, off: { type: "boolean" }, "image-from-workspace": { type: "string" }, "image-from-dockerfile": { type: "boolean" } },
45
45
  migrations: { repo: { type: "string" }, push: { type: "string" }, reason: { type: "string" }, "force-destructive": { type: "boolean" } },
46
46
  billing: { repo: { type: "string" }, timeout: { type: "string" } },
47
+ api: { data: { type: "string" } },
47
48
  };
48
49
 
49
50
  export const HELP = {
50
51
  commands: [
51
52
  "init [--scope SCOPES] [--no-mcp] [--billing]", "billing [--repo OWNER/REPO] [--timeout SECONDS]", "doctor",
52
53
  "login [--scope SCOPES]", "logout", "whoami", "repos", "token list", "token revoke ID",
53
- "target set [--repo OWNER/REPO] [--file TARGET.json] [--auto-promote on|off] [--auto-release on|off]", "verify [--workflow PATH] [--timeout SECONDS]",
54
+ "target set [--repo OWNER/REPO] [--file TARGET.json] [--auto-promote on|off] [--auto-release on|off]",
55
+ "secret set NAME [--repo OWNER/REPO] (value on stdin)", "secret list [--repo OWNER/REPO]", "secret rm NAME [--repo OWNER/REPO]",
56
+ "verify [--workflow PATH] [--timeout SECONDS] [--no-reuse]",
54
57
  "wait ID [--repo OWNER/REPO] [--timeout SECONDS]", "failures ID [--repo OWNER/REPO]", "ship ID [--repo OWNER/REPO]",
55
- "approve ID [--repo OWNER/REPO]", "repo set [--repo OWNER/REPO] --push-workflow PATH|--off",
58
+ "approve ID [--repo OWNER/REPO]", "repo set [--repo OWNER/REPO] [--settings JSON|@FILE] [--push-workflow PATH|--off] [--image-from-workspace JSON|--image-from-dockerfile]",
56
59
  "migrations list [--repo OWNER/REPO]", "migrations approve MANIFEST_DIGEST --push ID --reason TEXT [--repo OWNER/REPO] [--force-destructive]",
57
60
  "search-logs ID --query LITERAL [--limit COUNT] [--repo OWNER/REPO]",
58
- "rerun-failed ID [--timeout SECONDS]", "--version",
61
+ "rerun-failed ID [--timeout SECONDS]", "api METHOD PATH [--data JSON|@FILE]", "--version",
59
62
  ],
60
63
  scopes: SCOPES,
61
64
  docs: "https://ci.notusworks.com/docs/agents.md",
62
65
  setup: "https://ci.notusworks.com/llms.txt",
66
+ settings: "https://ci.notusworks.com/api/settings",
67
+ note: "Features reach the API before this CLI: list repo settings with `api GET /api/settings`, set any with `repo set --settings JSON`, and call any API path with `api`.",
63
68
  };
64
69
 
70
+ /** A JSON option value, or `{ file }` for `@FILE`. @param {string} flag @param {string | undefined} value */
71
+ function jsonOption(flag, value) {
72
+ if (value === undefined) return undefined;
73
+ if (value.startsWith("@")) return { file: value.slice(1) };
74
+ return { json: jsonText(flag, value) };
75
+ }
76
+
77
+ /** @param {string} flag @param {string} text */
78
+ export function jsonText(flag, text) {
79
+ try { return JSON.parse(text); } catch { throw usage(`${flag} takes JSON or @FILE`); }
80
+ }
81
+
82
+ /** The URL for an API path, only ever on the logged-in server. @param {string} base @param {string} path */
83
+ export function apiUrl(base, path) {
84
+ const url = new URL(path, `${base}/`);
85
+ if (!path.startsWith("/") || url.origin !== new URL(base).origin) throw usage("PATH must start with / and stay on the NotusCI server, e.g. /api/settings");
86
+ return url;
87
+ }
88
+
65
89
  /** @param {string[]} args @returns {any} */
66
90
  export function parseCommand(args) {
67
91
  if (!args.length || args[0] === "help" || args.includes("--help") || args.includes("-h")) return { command: "help" };
@@ -110,10 +134,29 @@ export function parseCommand(args) {
110
134
  if (!values.file && autoPromote === undefined && autoRelease === undefined) throw usage("target set needs --file, --auto-promote or --auto-release");
111
135
  return { command: "target set", repo: values.repo, file: values.file, autoPromote, autoRelease };
112
136
  }
137
+ if (command === "api") {
138
+ if (positionals.length !== 2) throw usage("usage: notusci api METHOD PATH [--data JSON|@FILE]");
139
+ const method = positionals[0].toUpperCase();
140
+ if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(method)) throw usage("METHOD must be GET, POST, PUT, PATCH or DELETE");
141
+ if (method === "GET" && values.data !== undefined) throw usage("--data needs POST, PUT, PATCH or DELETE");
142
+ apiUrl("https://notusci.invalid", positionals[1]);
143
+ return { command, method, path: positionals[1], data: jsonOption("--data", values.data) };
144
+ }
113
145
  if (command === "repo") {
114
146
  expect("set");
115
- if ((values["push-workflow"] === undefined) === (values.off !== true)) throw usage("repo set needs exactly one of --push-workflow PATH or --off");
116
- return { command: "repo set", repo: values.repo, pushWorkflow: values.off ? null : values["push-workflow"] };
147
+ const push = values["push-workflow"] !== undefined || values.off === true; const image = values["image-from-workspace"] !== undefined || values["image-from-dockerfile"] === true;
148
+ if ((values["push-workflow"] !== undefined && values.off) || (values["image-from-workspace"] !== undefined && values["image-from-dockerfile"]) || (!push && !image && values.settings === undefined)) {
149
+ throw usage("repo set needs --settings JSON, --push-workflow PATH or --off, and/or --image-from-workspace JSON or --image-from-dockerfile");
150
+ }
151
+ /** @type {{ command: string, repo?: string, settings?: { json?: any, file?: string }, pushWorkflow?: string | null, imageFromWorkspace?: unknown }} */
152
+ const out = { command: "repo set", repo: values.repo };
153
+ if (values.settings !== undefined) out.settings = jsonOption("--settings", values.settings);
154
+ if (push) out.pushWorkflow = values.off ? null : values["push-workflow"];
155
+ if (image) {
156
+ try { out.imageFromWorkspace = values["image-from-dockerfile"] ? null : JSON.parse(values["image-from-workspace"] ?? ""); }
157
+ catch { throw usage("--image-from-workspace takes JSON, e.g. '{\"root\":\"/usr/src/app\",\"stages\":{\"build\":[\"dist\"]}}'"); }
158
+ }
159
+ return out;
117
160
  }
118
161
  if (command === "migrations") {
119
162
  if (positionals[0] === "list") { expect("list"); return { command: "migrations list", repo: values.repo }; }
@@ -124,10 +167,16 @@ export function parseCommand(args) {
124
167
  return { command: "migrations approve", repo: values.repo, manifestDigest: positionals[1], pushRunId: values.push.toLowerCase(),
125
168
  reason: values.reason, forceDestructive: values["force-destructive"] === true };
126
169
  }
170
+ if (command === "secret") {
171
+ const [action, name] = positionals;
172
+ if (action === "list" && positionals.length === 1) return { command: "secret list", repo: values.repo };
173
+ if ((action === "set" || action === "rm") && positionals.length === 2) return { command: `secret ${action}`, name, repo: values.repo };
174
+ throw usage("usage: notusci secret set NAME | secret list | secret rm NAME");
175
+ }
127
176
  if (command === "verify") {
128
177
  expect();
129
178
  if (values.workflow === "") throw usage("--workflow must not be empty");
130
- return { command, workflow: values.workflow, timeoutSeconds: timeoutSeconds ?? 540 };
179
+ return { command, workflow: values.workflow, timeoutSeconds: timeoutSeconds ?? 540, ...(values["no-reuse"] ? { reuse: false } : {}) };
131
180
  }
132
181
  if (command === "billing") { expect(); return { command, repo: values.repo, timeoutSeconds: timeoutSeconds ?? 90 }; }
133
182
  if (command === "search-logs") {
@@ -261,7 +310,7 @@ export function boundedWaitSeconds(remainingMilliseconds) {
261
310
 
262
311
  /** @param {string} cwd @param {string[]} args @param {number} [maxBuffer] */
263
312
  function git(cwd, args, maxBuffer = MAX_WIRE_BYTES) {
264
- try { return execFileSync("git", args, { cwd, encoding: "buffer", maxBuffer }); }
313
+ try { return execFileSync("git", args, { cwd, encoding: "buffer", maxBuffer, stdio: ["ignore", "pipe", "pipe"] }); }
265
314
  catch { throw new Error(`git ${args.slice(0, 2).join(" ")} failed`); }
266
315
  }
267
316
 
@@ -297,12 +346,6 @@ export function sourceIdentity(repo, source) {
297
346
  return hash.digest("hex");
298
347
  }
299
348
 
300
- /** Attach only the immutable Git base; the receipt already owns its overlay.
301
- * @param {{baseSha:string,objects?:{oid:string,type:string,data:string}[],overlay?:unknown[],deletions?:string[]}} source */
302
- export function baseAttachment(source) {
303
- return { schemaVersion: 1, baseSha: source.baseSha, objects: source.objects ?? [], overlay: [], deletions: [] };
304
- }
305
-
306
349
  const dependencyNames = new Set(["pnpm-lock.yaml", "pnpm-workspace.yaml", "package.json", ".npmrc", "pnpmfile.cjs", ".pnpmfile.cjs"]);
307
350
 
308
351
  /** @param {string} repo @param {string} workflow @param {{path:string,mode:string,bytes:Buffer}[]} files */
@@ -335,85 +378,105 @@ export function dependencyHint(cwd, repo, workflow) {
335
378
  return dependencyHintForFiles(repo, workflow, files);
336
379
  }
337
380
 
338
- /** @param {string} entry */
339
- export function parseTreeEntry(entry) {
340
- const tab = entry.indexOf("\t");
341
- const match = entry.slice(0, tab).match(/^(\d+)\s+(\w+)\s+([0-9a-f]{40})\s+(\d+)$/);
342
- if (tab < 0 || !match) throw new Error("invalid Git tree entry");
343
- return { mode: match[1], type: match[2], oid: match[3], size: Number(match[4]), path: entry.slice(tab + 1) };
381
+ /** Classify paths that differ from the base. Skip-worktree paths upload their index content; a path that is now a
382
+ * gitlink is skipped, or deleted when the base had a file there; anything else not kept (tracked or
383
+ * untracked-and-not-ignored) as a file or link is a deletion.
384
+ * @param {string[]} changed
385
+ * @param {{index: Map<string, {mode: string, oid: string, skip: boolean}>, untracked: Set<string>, gitlinks: Map<string, string>}} tree
386
+ * `gitlinks` maps each path whose new mode is 160000 to its base mode
387
+ * @param {(path: string) => "file" | "link" | "absent"} kind */
388
+ export function overlayPaths(changed, { index, untracked, gitlinks }, kind) {
389
+ /** @type {string[]} */
390
+ const disk = [];
391
+ /** @type {string[]} */
392
+ const indexed = [];
393
+ /** @type {string[]} */
394
+ const deletions = [];
395
+ for (const path of [...new Set(changed)].sort()) {
396
+ const entry = index.get(path);
397
+ if (gitlinks.has(path) || entry?.mode === "160000") {
398
+ if (["100644", "100755", "120000"].includes(gitlinks.get(path) ?? "")) deletions.push(path);
399
+ } else if (entry?.skip) indexed.push(path);
400
+ else if ((entry || untracked.has(path)) && kind(path) !== "absent") disk.push(path);
401
+ else deletions.push(path);
402
+ }
403
+ return { disk, indexed, deletions };
344
404
  }
345
405
 
346
- /** @param {string} cwd */
347
- export function sourceBaseSha(cwd) {
406
+ /** @param {string} error @param {string} next */
407
+ const tooLarge = (error, next = "Commit and push the large files, then retry.") => new CliError({ code: "too_large", error, next });
408
+
409
+ /** The newest commit of HEAD's history on an origin remote-tracking branch, or `preferred` while it still qualifies.
410
+ * @param {string} cwd @param {string} [preferred] a failed verify's base */
411
+ export function sourceBase(cwd, preferred) {
348
412
  const root = git(cwd, ["rev-parse", "--show-toplevel"]).toString().trim();
349
- const baseSha = git(root, ["rev-parse", "--verify", "HEAD"]).toString().trim();
350
- if (!/^[0-9a-f]{40}$/.test(baseSha)) throw new Error("HEAD must resolve to a SHA-1 commit");
351
- return baseSha;
413
+ const tips = git(root, ["for-each-ref", "--format=%(objectname)", "refs/remotes/origin/"]).toString().split("\n").filter(Boolean);
414
+ const ok = (/** @type {string[]} */ ...args) => { try { git(root, args); return true; } catch { return false; } };
415
+ if (preferred && /^[0-9a-f]{40}$/.test(preferred) && ok("merge-base", "--is-ancestor", preferred, "HEAD")
416
+ && git(root, ["for-each-ref", "--contains", preferred, "--count=1", "refs/remotes/origin/"]).length) return preferred;
417
+ let base = "";
418
+ if (tips.length) try { base = git(root, ["merge-base", "HEAD", ...tips]).toString().trim(); } catch {}
419
+ if (/^[0-9a-f]{40}$/.test(base)) return base;
420
+ const shallow = git(root, ["rev-parse", "--is-shallow-repository"]).toString().trim() === "true";
421
+ throw new CliError({ code: "base_unavailable", error: "No commit of HEAD's history is on a remote-tracking branch of origin",
422
+ next: shallow ? "git fetch --deepen=100 origin, then retry" : "git push -u origin HEAD, then retry" });
352
423
  }
353
424
 
354
- /** Build the raw Git base and final local overlay. @param {string} cwd */
355
- export function buildSource(cwd, includeObjects = true) {
425
+ /** The overlay of every path that differs from `baseSha`, which GitHub must already have. @param {string} cwd @param {string} baseSha */
426
+ export function buildSource(cwd, baseSha) {
356
427
  const root = git(cwd, ["rev-parse", "--show-toplevel"]).toString().trim();
357
- const baseSha = sourceBaseSha(root);
358
- /** @type {Map<string,number>} */
359
- const finalFiles = new Map();
360
- for (const entry of paths(git(root, ["ls-tree", "-rlz", "--full-tree", baseSha]))) {
361
- const { mode, type, oid, size, path } = parseTreeEntry(entry);
362
- checkPath(path);
363
- if (type !== "blob" || !["100644", "100755", "120000"].includes(mode)) throw new Error(`unsupported Git entry mode ${mode}: ${path}`);
364
- if (size > MAX_FILE_BYTES) throw new Error(`Git file exceeds 32 MiB: ${path}`);
365
- if (mode === "120000" && size > MAX_PATH_BYTES) throw new Error(`link target exceeds ${MAX_PATH_BYTES} bytes: ${path}`);
366
- if (!Number.isSafeInteger(size)) throw new Error(`invalid Git tree entry: ${path}`);
367
- finalFiles.set(path, size);
428
+ // An untracked embedded repository is listed as "dir/"; it is not uploaded.
429
+ const untracked = paths(git(root, ["ls-files", "--others", "--exclude-standard", "-z"])).filter(path => !path.endsWith("/"));
430
+ /** @type {Map<string, {mode: string, oid: string, skip: boolean}>} */
431
+ const index = new Map();
432
+ for (const line of paths(git(root, ["ls-files", "-s", "-t", "-z"]))) {
433
+ const tab = line.indexOf("\t"); const [tag, mode, oid] = line.slice(0, tab).split(" ");
434
+ index.set(line.slice(tab + 1), { mode, oid, skip: tag === "S" });
368
435
  }
369
- const objectIds = includeObjects ? [baseSha, ...git(root, ["rev-list", "--objects", "--no-object-names", `${baseSha}^{tree}`]).toString().trim().split("\n").filter(Boolean)] : [];
370
- let decodedBytes = 0;
371
- const objects = objectIds.map(oid => {
372
- const type = git(root, ["cat-file", "-t", oid]).toString().trim();
373
- if (type !== "commit" && type !== "tree" && type !== "blob") throw new Error(`unsupported Git object type ${type}`);
374
- const raw = git(root, ["cat-file", type, oid], MAX_FILE_BYTES + 1);
375
- if (type === "blob" && raw.length > MAX_FILE_BYTES) throw new Error(`Git blob ${oid} exceeds 32 MiB`);
376
- decodedBytes += raw.length;
377
- if (decodedBytes > MAX_TREE_BYTES) throw new Error("base Git objects exceed the 256 MiB decoded limit");
378
- return { oid, type, data: raw.toString("base64") };
436
+ const raw = paths(git(root, ["diff", "--no-renames", "--raw", "-z", baseSha, "--"]));
437
+ const changed = [...untracked]; const gitlinks = new Map();
438
+ for (let i = 0; i + 1 < raw.length; i += 2) {
439
+ const [oldMode, newMode] = raw[i].slice(1).split(" ");
440
+ changed.push(raw[i + 1]);
441
+ if (newMode === "160000") gitlinks.set(raw[i + 1], oldMode);
442
+ }
443
+ const { disk, indexed, deletions } = overlayPaths(changed, { index, untracked: new Set(untracked), gitlinks }, path => {
444
+ try { const stat = lstatSync(`${root}/${path}`); return stat.isFile() ? "file" : stat.isSymbolicLink() ? "link" : "absent"; }
445
+ catch (error) { if (["ENOENT", "ENOTDIR"].includes(/** @type {NodeJS.ErrnoException} */ (error).code ?? "")) return "absent"; throw error; }
379
446
  });
380
-
381
- const changed = new Set([...paths(git(root, ["diff", "--no-renames", "--name-only", "-z", "HEAD", "--"])), ...paths(git(root, ["ls-files", "--others", "--exclude-standard", "-z"]))]);
447
+ if (disk.length + indexed.length + deletions.length > MAX_PATHS) throw tooLarge(`changes exceed ${MAX_PATHS} paths`);
448
+ for (const path of [...disk, ...indexed, ...deletions]) checkPath(path);
382
449
  /** @type {{path:string,mode:"100644"|"100755"|"120000",data:string}[]} */
383
450
  const overlay = [];
384
- /** @type {string[]} */
385
- const deletions = [];
386
- for (const path of [...changed].sort()) {
387
- checkPath(path);
388
- let stat;
389
- try { stat = lstatSync(`${root}/${path}`); } catch (error) {
390
- if (/** @type {NodeJS.ErrnoException} */ (error).code === "ENOENT") { deletions.push(path); finalFiles.delete(path); continue; }
391
- throw error;
392
- }
393
- let mode;
394
- let data;
395
- if (stat.isSymbolicLink()) {
396
- mode = /** @type {const} */ ("120000");
397
- data = Buffer.from(readlinkSync(`${root}/${path}`));
398
- if (data.length > MAX_PATH_BYTES) throw new Error(`link target exceeds ${MAX_PATH_BYTES} bytes: ${path}`);
399
- } else if (stat.isFile()) {
400
- mode = stat.mode & 0o111 ? /** @type {const} */ ("100755") : /** @type {const} */ ("100644");
401
- if (stat.size > MAX_FILE_BYTES) throw new Error(`file exceeds 32 MiB: ${path}`);
402
- data = readFileSync(`${root}/${path}`);
403
- } else throw new Error(`unsupported changed file type: ${path}`);
404
- finalFiles.set(path, data.length);
451
+ let wireBytes = 0;
452
+ /** @param {string} path @param {"100644"|"100755"|"120000"} mode @param {Buffer} data */
453
+ const add = (path, mode, data) => {
454
+ if (data.length > MAX_FILE_BYTES) throw tooLarge(`file exceeds 32 MiB: ${path}`, "Commit and push it, then retry.");
455
+ if (mode === "120000" && data.length > MAX_PATH_BYTES) throw new Error(`link target exceeds ${MAX_PATH_BYTES} bytes: ${path}`);
456
+ wireBytes += Math.ceil(data.length / 3) * 4;
457
+ if (wireBytes > MAX_WIRE_BYTES) throw tooLarge("changes exceed the 64 MiB upload limit");
405
458
  overlay.push({ path, mode, data: data.toString("base64") });
459
+ };
460
+ for (const path of disk) {
461
+ const stat = lstatSync(`${root}/${path}`);
462
+ if (stat.isSymbolicLink()) add(path, "120000", Buffer.from(readlinkSync(`${root}/${path}`)));
463
+ else {
464
+ if (stat.size > MAX_FILE_BYTES) throw tooLarge(`file exceeds 32 MiB: ${path}`, "Commit and push it, then retry.");
465
+ add(path, stat.mode & 0o111 ? "100755" : "100644", readFileSync(`${root}/${path}`));
466
+ }
467
+ }
468
+ for (const path of indexed) {
469
+ const { mode, oid } = /** @type {{mode: "100644"|"100755"|"120000", oid: string}} */ (index.get(path));
470
+ if (!["100644", "100755", "120000"].includes(mode)) throw new Error(`unsupported Git entry mode ${mode}: ${path}`);
471
+ if (Number(git(root, ["cat-file", "-s", oid]).toString()) > MAX_FILE_BYTES) throw tooLarge(`file exceeds 32 MiB: ${path}`, "Commit and push it, then retry.");
472
+ add(path, mode, git(root, ["cat-file", "blob", oid], MAX_FILE_BYTES + 1));
406
473
  }
407
- if (finalFiles.size > MAX_PATHS) throw new Error(`resolved source exceeds ${MAX_PATHS} paths`);
408
- let finalBytes = 0;
409
- for (const size of finalFiles.values()) finalBytes += size;
410
- if (finalBytes > MAX_TREE_BYTES) throw new Error("resolved source exceeds the 256 MiB decoded limit");
411
- return { schemaVersion: includeObjects ? 1 : 2, baseSha, ...(includeObjects ? { objects } : {}), overlay, deletions };
474
+ return { schemaVersion: 2, baseSha, overlay, deletions };
412
475
  }
413
476
 
414
477
  /** @param {ReturnType<typeof buildSource>} source */
415
478
  export function encodeSource(source) {
416
479
  const body = JSON.stringify(source);
417
- if (Buffer.byteLength(body) > MAX_WIRE_BYTES) throw new Error("verification upload exceeds the 64 MiB transport limit");
480
+ if (Buffer.byteLength(body) > MAX_WIRE_BYTES) throw tooLarge("changes exceed the 64 MiB upload limit");
418
481
  return body;
419
482
  }