notusci 0.1.4 → 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 +59 -36
  3. package/src/core.mjs +152 -84
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notusci",
3
- "version": "0.1.4",
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) {
@@ -365,16 +362,36 @@ async function main(s, input) {
365
362
  return print({ status: "revoked", id: input.id });
366
363
  case "target set": {
367
364
  const repo = repoOrOrigin(input.repo);
368
- let config;
369
- try { config = JSON.parse(readFileSync(input.file, "utf8")); }
370
- catch { throw new CliError({ code: "usage", error: `${input.file} must be a readable JSON file`, next: "Fix --file and retry." }); }
371
- await api(s, `/api/repos/${repo}/target`, { method: "PUT", body: { config, digitaloceanToken: process.env.DIGITALOCEAN_TOKEN, autoPromote: input.autoPromote } });
372
- return print({ status: "saved", repo });
365
+ const { autoPromote, autoRelease } = input;
366
+ /** @type {Record<string, unknown>} */
367
+ let body = { autoPromote, autoRelease };
368
+ if (input.file) {
369
+ try { body = { ...body, config: JSON.parse(readFileSync(input.file, "utf8")), digitaloceanToken: process.env.DIGITALOCEAN_TOKEN }; }
370
+ catch { throw new CliError({ code: "usage", error: `${input.file} must be a readable JSON file`, next: "Fix --file and retry." }); }
371
+ }
372
+ const saved = await api(s, `/api/repos/${repo}/target`, { method: "PUT", body });
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." } : {}) });
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 });
373
390
  }
374
391
  case "verify": {
375
392
  const { root, repo } = gitRepo();
376
393
  const workflow = input.workflow ?? workflowIn(root);
377
- 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));
378
395
  }
379
396
  case "ship": {
380
397
  const repo = repoOrOrigin(input.repo);
@@ -383,7 +400,13 @@ async function main(s, input) {
383
400
  }
384
401
  case "repo set": {
385
402
  const repo = repoOrOrigin(input.repo);
386
- 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) }));
387
410
  }
388
411
  case "migrations list": return print(await api(s, `/api/repos/${repoOrOrigin(input.repo)}/migrations`));
389
412
  case "migrations approve": {
@@ -408,7 +431,7 @@ async function main(s, input) {
408
431
  case "rerun-failed": {
409
432
  const { root, repo } = gitRepo();
410
433
  const failed = await api(s, `/api/verifies/${input.failedVerifyId}/wait`, { query: { repo, timeoutSeconds: 1 } });
411
- 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 }));
412
435
  }
413
436
  }
414
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";
@@ -33,35 +32,60 @@ const OPTIONS = {
33
32
  init: { scope: { type: "string" }, "no-mcp": { type: "boolean" }, billing: { type: "boolean" } },
34
33
  login: { scope: { type: "string" } },
35
34
  doctor: {}, logout: {}, token: {}, whoami: {}, repos: {}, version: {}, "--version": {},
36
- target: { repo: { type: "string" }, file: { type: "string" }, "auto-promote": { type: "string" } },
37
- verify: { workflow: { type: "string" }, timeout: { type: "string" } },
35
+ target: { repo: { type: "string" }, file: { type: "string" }, "auto-promote": { type: "string" }, "auto-release": { 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]", "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" };
@@ -100,15 +124,39 @@ export function parseCommand(args) {
100
124
  }
101
125
  if (command === "target") {
102
126
  expect("set");
103
- if (!values.file) throw usage("--file is required");
104
- const auto = values["auto-promote"];
105
- if (auto !== undefined && auto !== "on" && auto !== "off") throw usage("--auto-promote must be on or off");
106
- return { command: "target set", repo: values.repo, file: values.file, autoPromote: auto === undefined ? undefined : auto === "on" };
127
+ /** @param {string} name */
128
+ const flag = name => {
129
+ const value = values[name];
130
+ if (value !== undefined && value !== "on" && value !== "off") throw usage(`--${name} must be on or off`);
131
+ return value === undefined ? undefined : value === "on";
132
+ };
133
+ const autoPromote = flag("auto-promote"); const autoRelease = flag("auto-release");
134
+ if (!values.file && autoPromote === undefined && autoRelease === undefined) throw usage("target set needs --file, --auto-promote or --auto-release");
135
+ return { command: "target set", repo: values.repo, file: values.file, autoPromote, autoRelease };
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) };
107
144
  }
108
145
  if (command === "repo") {
109
146
  expect("set");
110
- if ((values["push-workflow"] === undefined) === (values.off !== true)) throw usage("repo set needs exactly one of --push-workflow PATH or --off");
111
- 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;
112
160
  }
113
161
  if (command === "migrations") {
114
162
  if (positionals[0] === "list") { expect("list"); return { command: "migrations list", repo: values.repo }; }
@@ -119,10 +167,16 @@ export function parseCommand(args) {
119
167
  return { command: "migrations approve", repo: values.repo, manifestDigest: positionals[1], pushRunId: values.push.toLowerCase(),
120
168
  reason: values.reason, forceDestructive: values["force-destructive"] === true };
121
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
+ }
122
176
  if (command === "verify") {
123
177
  expect();
124
178
  if (values.workflow === "") throw usage("--workflow must not be empty");
125
- return { command, workflow: values.workflow, timeoutSeconds: timeoutSeconds ?? 540 };
179
+ return { command, workflow: values.workflow, timeoutSeconds: timeoutSeconds ?? 540, ...(values["no-reuse"] ? { reuse: false } : {}) };
126
180
  }
127
181
  if (command === "billing") { expect(); return { command, repo: values.repo, timeoutSeconds: timeoutSeconds ?? 90 }; }
128
182
  if (command === "search-logs") {
@@ -256,7 +310,7 @@ export function boundedWaitSeconds(remainingMilliseconds) {
256
310
 
257
311
  /** @param {string} cwd @param {string[]} args @param {number} [maxBuffer] */
258
312
  function git(cwd, args, maxBuffer = MAX_WIRE_BYTES) {
259
- try { return execFileSync("git", args, { cwd, encoding: "buffer", maxBuffer }); }
313
+ try { return execFileSync("git", args, { cwd, encoding: "buffer", maxBuffer, stdio: ["ignore", "pipe", "pipe"] }); }
260
314
  catch { throw new Error(`git ${args.slice(0, 2).join(" ")} failed`); }
261
315
  }
262
316
 
@@ -292,12 +346,6 @@ export function sourceIdentity(repo, source) {
292
346
  return hash.digest("hex");
293
347
  }
294
348
 
295
- /** Attach only the immutable Git base; the receipt already owns its overlay.
296
- * @param {{baseSha:string,objects?:{oid:string,type:string,data:string}[],overlay?:unknown[],deletions?:string[]}} source */
297
- export function baseAttachment(source) {
298
- return { schemaVersion: 1, baseSha: source.baseSha, objects: source.objects ?? [], overlay: [], deletions: [] };
299
- }
300
-
301
349
  const dependencyNames = new Set(["pnpm-lock.yaml", "pnpm-workspace.yaml", "package.json", ".npmrc", "pnpmfile.cjs", ".pnpmfile.cjs"]);
302
350
 
303
351
  /** @param {string} repo @param {string} workflow @param {{path:string,mode:string,bytes:Buffer}[]} files */
@@ -330,85 +378,105 @@ export function dependencyHint(cwd, repo, workflow) {
330
378
  return dependencyHintForFiles(repo, workflow, files);
331
379
  }
332
380
 
333
- /** @param {string} entry */
334
- export function parseTreeEntry(entry) {
335
- const tab = entry.indexOf("\t");
336
- const match = entry.slice(0, tab).match(/^(\d+)\s+(\w+)\s+([0-9a-f]{40})\s+(\d+)$/);
337
- if (tab < 0 || !match) throw new Error("invalid Git tree entry");
338
- 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 };
339
404
  }
340
405
 
341
- /** @param {string} cwd */
342
- 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) {
343
412
  const root = git(cwd, ["rev-parse", "--show-toplevel"]).toString().trim();
344
- const baseSha = git(root, ["rev-parse", "--verify", "HEAD"]).toString().trim();
345
- if (!/^[0-9a-f]{40}$/.test(baseSha)) throw new Error("HEAD must resolve to a SHA-1 commit");
346
- 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" });
347
423
  }
348
424
 
349
- /** Build the raw Git base and final local overlay. @param {string} cwd */
350
- 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) {
351
427
  const root = git(cwd, ["rev-parse", "--show-toplevel"]).toString().trim();
352
- const baseSha = sourceBaseSha(root);
353
- /** @type {Map<string,number>} */
354
- const finalFiles = new Map();
355
- for (const entry of paths(git(root, ["ls-tree", "-rlz", "--full-tree", baseSha]))) {
356
- const { mode, type, oid, size, path } = parseTreeEntry(entry);
357
- checkPath(path);
358
- if (type !== "blob" || !["100644", "100755", "120000"].includes(mode)) throw new Error(`unsupported Git entry mode ${mode}: ${path}`);
359
- if (size > MAX_FILE_BYTES) throw new Error(`Git file exceeds 32 MiB: ${path}`);
360
- if (mode === "120000" && size > MAX_PATH_BYTES) throw new Error(`link target exceeds ${MAX_PATH_BYTES} bytes: ${path}`);
361
- if (!Number.isSafeInteger(size)) throw new Error(`invalid Git tree entry: ${path}`);
362
- 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" });
363
435
  }
364
- const objectIds = includeObjects ? [baseSha, ...git(root, ["rev-list", "--objects", "--no-object-names", `${baseSha}^{tree}`]).toString().trim().split("\n").filter(Boolean)] : [];
365
- let decodedBytes = 0;
366
- const objects = objectIds.map(oid => {
367
- const type = git(root, ["cat-file", "-t", oid]).toString().trim();
368
- if (type !== "commit" && type !== "tree" && type !== "blob") throw new Error(`unsupported Git object type ${type}`);
369
- const raw = git(root, ["cat-file", type, oid], MAX_FILE_BYTES + 1);
370
- if (type === "blob" && raw.length > MAX_FILE_BYTES) throw new Error(`Git blob ${oid} exceeds 32 MiB`);
371
- decodedBytes += raw.length;
372
- if (decodedBytes > MAX_TREE_BYTES) throw new Error("base Git objects exceed the 256 MiB decoded limit");
373
- 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; }
374
446
  });
375
-
376
- 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);
377
449
  /** @type {{path:string,mode:"100644"|"100755"|"120000",data:string}[]} */
378
450
  const overlay = [];
379
- /** @type {string[]} */
380
- const deletions = [];
381
- for (const path of [...changed].sort()) {
382
- checkPath(path);
383
- let stat;
384
- try { stat = lstatSync(`${root}/${path}`); } catch (error) {
385
- if (/** @type {NodeJS.ErrnoException} */ (error).code === "ENOENT") { deletions.push(path); finalFiles.delete(path); continue; }
386
- throw error;
387
- }
388
- let mode;
389
- let data;
390
- if (stat.isSymbolicLink()) {
391
- mode = /** @type {const} */ ("120000");
392
- data = Buffer.from(readlinkSync(`${root}/${path}`));
393
- if (data.length > MAX_PATH_BYTES) throw new Error(`link target exceeds ${MAX_PATH_BYTES} bytes: ${path}`);
394
- } else if (stat.isFile()) {
395
- mode = stat.mode & 0o111 ? /** @type {const} */ ("100755") : /** @type {const} */ ("100644");
396
- if (stat.size > MAX_FILE_BYTES) throw new Error(`file exceeds 32 MiB: ${path}`);
397
- data = readFileSync(`${root}/${path}`);
398
- } else throw new Error(`unsupported changed file type: ${path}`);
399
- 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");
400
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));
401
473
  }
402
- if (finalFiles.size > MAX_PATHS) throw new Error(`resolved source exceeds ${MAX_PATHS} paths`);
403
- let finalBytes = 0;
404
- for (const size of finalFiles.values()) finalBytes += size;
405
- if (finalBytes > MAX_TREE_BYTES) throw new Error("resolved source exceeds the 256 MiB decoded limit");
406
- return { schemaVersion: includeObjects ? 1 : 2, baseSha, ...(includeObjects ? { objects } : {}), overlay, deletions };
474
+ return { schemaVersion: 2, baseSha, overlay, deletions };
407
475
  }
408
476
 
409
477
  /** @param {ReturnType<typeof buildSource>} source */
410
478
  export function encodeSource(source) {
411
479
  const body = JSON.stringify(source);
412
- 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");
413
481
  return body;
414
482
  }