notusci 0.1.5 → 0.1.10

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 +55 -31
  3. package/src/core.mjs +150 -81
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notusci",
3
- "version": "0.1.5",
3
+ "version": "0.1.10",
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) {
@@ -350,6 +347,11 @@ async function main(s, input) {
350
347
  case "doctor": return doctor(s);
351
348
  case "login": return login(s, input);
352
349
  case "billing": return billing(s, input);
350
+ case "usage": {
351
+ const repo = repoOrOrigin(input.repo);
352
+ return print(input.capUsd === undefined ? await api(s, "/api/usage", { query: { repo } })
353
+ : await api(s, "/api/usage/cap", { method: "POST", body: { repo, capUsd: input.capUsd } }));
354
+ }
353
355
  case "logout": return logout(s);
354
356
  case "whoami": {
355
357
  const { user, scopes, repos, installUrl } = await api(s, "/api/whoami");
@@ -375,10 +377,26 @@ async function main(s, input) {
375
377
  const saved = await api(s, `/api/repos/${repo}/target`, { method: "PUT", body });
376
378
  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
379
  }
380
+ case "secret set": {
381
+ const repo = repoOrOrigin(input.repo);
382
+ // The value comes only from stdin, never argv; one trailing newline is dropped.
383
+ if (process.stdin.isTTY) throw new Error("pipe the value on stdin, e.g. printf %s \"$VALUE\" | notusci secret set NAME");
384
+ const value = readFileSync(0, "utf8").replace(/\r?\n$/, "");
385
+ return print({ status: "saved", ...await api(s, `/api/repos/${repo}/secrets/${encodeURIComponent(input.name)}`, { method: "PUT", body: { value } }) });
386
+ }
387
+ case "secret list": {
388
+ const repo = repoOrOrigin(input.repo);
389
+ return print({ repo, ...await api(s, `/api/repos/${repo}/secrets`) });
390
+ }
391
+ case "secret rm": {
392
+ const repo = repoOrOrigin(input.repo);
393
+ await api(s, `/api/repos/${repo}/secrets/${encodeURIComponent(input.name)}`, { method: "DELETE" });
394
+ return print({ status: "deleted", repo, name: input.name });
395
+ }
378
396
  case "verify": {
379
397
  const { root, repo } = gitRepo();
380
398
  const workflow = input.workflow ?? workflowIn(root);
381
- return report(await verify(s, root, repo, workflow, input.timeoutSeconds));
399
+ return report(await verify(s, root, repo, workflow, input.timeoutSeconds, undefined, input.reuse !== false));
382
400
  }
383
401
  case "ship": {
384
402
  const repo = repoOrOrigin(input.repo);
@@ -387,7 +405,13 @@ async function main(s, input) {
387
405
  }
388
406
  case "repo set": {
389
407
  const repo = repoOrOrigin(input.repo);
390
- return print(await api(s, `/api/repos/${repo}/settings`, { method: "PUT", body: { pushWorkflow: input.pushWorkflow } }));
408
+ const { pushWorkflow, imageFromWorkspace } = input;
409
+ const body = { ...jsonValue("--settings", input.settings), ...(pushWorkflow !== undefined && { pushWorkflow }), ...(imageFromWorkspace !== undefined && { imageFromWorkspace }) };
410
+ return print(await api(s, `/api/repos/${repo}/settings`, { method: "PUT", body }));
411
+ }
412
+ case "api": {
413
+ const url = apiUrl(s.url, input.path);
414
+ return print(await api(s, url.pathname + url.search, { method: input.method, body: jsonValue("--data", input.data) }));
391
415
  }
392
416
  case "migrations list": return print(await api(s, `/api/repos/${repoOrOrigin(input.repo)}/migrations`));
393
417
  case "migrations approve": {
@@ -412,7 +436,7 @@ async function main(s, input) {
412
436
  case "rerun-failed": {
413
437
  const { root, repo } = gitRepo();
414
438
  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));
439
+ return report(await verify(s, root, repo, failed.workflow, input.timeoutSeconds, { id: input.failedVerifyId, baseSha: failed.baseSha }));
416
440
  }
417
441
  }
418
442
  }
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,60 @@ 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
+ usage: { repo: { type: "string" }, cap: { type: "string" } },
48
+ api: { data: { type: "string" } },
47
49
  };
48
50
 
49
51
  export const HELP = {
50
52
  commands: [
51
- "init [--scope SCOPES] [--no-mcp] [--billing]", "billing [--repo OWNER/REPO] [--timeout SECONDS]", "doctor",
53
+ "init [--scope SCOPES] [--no-mcp] [--billing]", "billing [--repo OWNER/REPO] [--timeout SECONDS]", "usage [--repo OWNER/REPO] [--cap USD]", "doctor",
52
54
  "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]",
55
+ "target set [--repo OWNER/REPO] [--file TARGET.json] [--auto-promote on|off] [--auto-release on|off]",
56
+ "secret set NAME [--repo OWNER/REPO] (value on stdin)", "secret list [--repo OWNER/REPO]", "secret rm NAME [--repo OWNER/REPO]",
57
+ "verify [--workflow PATH] [--timeout SECONDS] [--no-reuse]",
54
58
  "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",
59
+ "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
60
  "migrations list [--repo OWNER/REPO]", "migrations approve MANIFEST_DIGEST --push ID --reason TEXT [--repo OWNER/REPO] [--force-destructive]",
57
61
  "search-logs ID --query LITERAL [--limit COUNT] [--repo OWNER/REPO]",
58
- "rerun-failed ID [--timeout SECONDS]", "--version",
62
+ "rerun-failed ID [--timeout SECONDS]", "api METHOD PATH [--data JSON|@FILE]", "--version",
59
63
  ],
60
64
  scopes: SCOPES,
61
65
  docs: "https://ci.notusworks.com/docs/agents.md",
62
66
  setup: "https://ci.notusworks.com/llms.txt",
67
+ settings: "https://ci.notusworks.com/api/settings",
68
+ 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
69
  };
64
70
 
71
+ /** A JSON option value, or `{ file }` for `@FILE`. @param {string} flag @param {string | undefined} value */
72
+ function jsonOption(flag, value) {
73
+ if (value === undefined) return undefined;
74
+ if (value.startsWith("@")) return { file: value.slice(1) };
75
+ return { json: jsonText(flag, value) };
76
+ }
77
+
78
+ /** @param {string} flag @param {string} text */
79
+ export function jsonText(flag, text) {
80
+ try { return JSON.parse(text); } catch { throw usage(`${flag} takes JSON or @FILE`); }
81
+ }
82
+
83
+ /** The URL for an API path, only ever on the logged-in server. @param {string} base @param {string} path */
84
+ export function apiUrl(base, path) {
85
+ const url = new URL(path, `${base}/`);
86
+ 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");
87
+ return url;
88
+ }
89
+
65
90
  /** @param {string[]} args @returns {any} */
66
91
  export function parseCommand(args) {
67
92
  if (!args.length || args[0] === "help" || args.includes("--help") || args.includes("-h")) return { command: "help" };
@@ -110,10 +135,29 @@ export function parseCommand(args) {
110
135
  if (!values.file && autoPromote === undefined && autoRelease === undefined) throw usage("target set needs --file, --auto-promote or --auto-release");
111
136
  return { command: "target set", repo: values.repo, file: values.file, autoPromote, autoRelease };
112
137
  }
138
+ if (command === "api") {
139
+ if (positionals.length !== 2) throw usage("usage: notusci api METHOD PATH [--data JSON|@FILE]");
140
+ const method = positionals[0].toUpperCase();
141
+ if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(method)) throw usage("METHOD must be GET, POST, PUT, PATCH or DELETE");
142
+ if (method === "GET" && values.data !== undefined) throw usage("--data needs POST, PUT, PATCH or DELETE");
143
+ apiUrl("https://notusci.invalid", positionals[1]);
144
+ return { command, method, path: positionals[1], data: jsonOption("--data", values.data) };
145
+ }
113
146
  if (command === "repo") {
114
147
  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"] };
148
+ const push = values["push-workflow"] !== undefined || values.off === true; const image = values["image-from-workspace"] !== undefined || values["image-from-dockerfile"] === true;
149
+ if ((values["push-workflow"] !== undefined && values.off) || (values["image-from-workspace"] !== undefined && values["image-from-dockerfile"]) || (!push && !image && values.settings === undefined)) {
150
+ throw usage("repo set needs --settings JSON, --push-workflow PATH or --off, and/or --image-from-workspace JSON or --image-from-dockerfile");
151
+ }
152
+ /** @type {{ command: string, repo?: string, settings?: { json?: any, file?: string }, pushWorkflow?: string | null, imageFromWorkspace?: unknown }} */
153
+ const out = { command: "repo set", repo: values.repo };
154
+ if (values.settings !== undefined) out.settings = jsonOption("--settings", values.settings);
155
+ if (push) out.pushWorkflow = values.off ? null : values["push-workflow"];
156
+ if (image) {
157
+ try { out.imageFromWorkspace = values["image-from-dockerfile"] ? null : JSON.parse(values["image-from-workspace"] ?? ""); }
158
+ catch { throw usage("--image-from-workspace takes JSON, e.g. '{\"root\":\"/usr/src/app\",\"stages\":{\"build\":[\"dist\"]}}'"); }
159
+ }
160
+ return out;
117
161
  }
118
162
  if (command === "migrations") {
119
163
  if (positionals[0] === "list") { expect("list"); return { command: "migrations list", repo: values.repo }; }
@@ -124,12 +168,23 @@ export function parseCommand(args) {
124
168
  return { command: "migrations approve", repo: values.repo, manifestDigest: positionals[1], pushRunId: values.push.toLowerCase(),
125
169
  reason: values.reason, forceDestructive: values["force-destructive"] === true };
126
170
  }
171
+ if (command === "secret") {
172
+ const [action, name] = positionals;
173
+ if (action === "list" && positionals.length === 1) return { command: "secret list", repo: values.repo };
174
+ if ((action === "set" || action === "rm") && positionals.length === 2) return { command: `secret ${action}`, name, repo: values.repo };
175
+ throw usage("usage: notusci secret set NAME | secret list | secret rm NAME");
176
+ }
127
177
  if (command === "verify") {
128
178
  expect();
129
179
  if (values.workflow === "") throw usage("--workflow must not be empty");
130
- return { command, workflow: values.workflow, timeoutSeconds: timeoutSeconds ?? 540 };
180
+ return { command, workflow: values.workflow, timeoutSeconds: timeoutSeconds ?? 540, ...(values["no-reuse"] ? { reuse: false } : {}) };
131
181
  }
132
182
  if (command === "billing") { expect(); return { command, repo: values.repo, timeoutSeconds: timeoutSeconds ?? 90 }; }
183
+ if (command === "usage") {
184
+ expect(); const capUsd = values.cap === undefined ? undefined : Number(values.cap);
185
+ if (capUsd !== undefined && !(capUsd >= 0)) throw usage("--cap must be a number of dollars, 0 or more");
186
+ return { command, repo: values.repo, ...(capUsd !== undefined ? { capUsd } : {}) };
187
+ }
133
188
  if (command === "search-logs") {
134
189
  expect("*"); const runId = /^[1-9]\d*$/.test(positionals[0]) ? Number(positionals[0]) : positionals[0].toLowerCase();
135
190
  if ((typeof runId === "number" ? !Number.isSafeInteger(runId) : !isPushRunId(runId)) || !values.query) throw usage("search-logs requires a valid ID and --query");
@@ -187,7 +242,7 @@ export function renderError({ error = "", code, next, ...extra }, now = Date.now
187
242
  next: `Tell the human the monthly limit is reached and resets on ${resetsOn}. Do not retry.`, ...extra, resetsOn };
188
243
  }
189
244
  if (code === "payment_required") {
190
- return { error: "The 300-minute NotusCI trial is used up. Set up billing to continue.", code,
245
+ return { error: "This account's NotusCI minutes are used up (Free: 1,000 a month; the Pro trial: 3,000). Upgrade to Pro to continue.", code,
191
246
  next: `${NPX} billing`, ...extra };
192
247
  }
193
248
  if (code === "missing_scope") return { error, code, next: `${NPX} login --scope ${String(extra.scopes)}`, ...extra };
@@ -261,7 +316,7 @@ export function boundedWaitSeconds(remainingMilliseconds) {
261
316
 
262
317
  /** @param {string} cwd @param {string[]} args @param {number} [maxBuffer] */
263
318
  function git(cwd, args, maxBuffer = MAX_WIRE_BYTES) {
264
- try { return execFileSync("git", args, { cwd, encoding: "buffer", maxBuffer }); }
319
+ try { return execFileSync("git", args, { cwd, encoding: "buffer", maxBuffer, stdio: ["ignore", "pipe", "pipe"] }); }
265
320
  catch { throw new Error(`git ${args.slice(0, 2).join(" ")} failed`); }
266
321
  }
267
322
 
@@ -297,12 +352,6 @@ export function sourceIdentity(repo, source) {
297
352
  return hash.digest("hex");
298
353
  }
299
354
 
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
355
  const dependencyNames = new Set(["pnpm-lock.yaml", "pnpm-workspace.yaml", "package.json", ".npmrc", "pnpmfile.cjs", ".pnpmfile.cjs"]);
307
356
 
308
357
  /** @param {string} repo @param {string} workflow @param {{path:string,mode:string,bytes:Buffer}[]} files */
@@ -335,85 +384,105 @@ export function dependencyHint(cwd, repo, workflow) {
335
384
  return dependencyHintForFiles(repo, workflow, files);
336
385
  }
337
386
 
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) };
387
+ /** Classify paths that differ from the base. Skip-worktree paths upload their index content; a path that is now a
388
+ * gitlink is skipped, or deleted when the base had a file there; anything else not kept (tracked or
389
+ * untracked-and-not-ignored) as a file or link is a deletion.
390
+ * @param {string[]} changed
391
+ * @param {{index: Map<string, {mode: string, oid: string, skip: boolean}>, untracked: Set<string>, gitlinks: Map<string, string>}} tree
392
+ * `gitlinks` maps each path whose new mode is 160000 to its base mode
393
+ * @param {(path: string) => "file" | "link" | "absent"} kind */
394
+ export function overlayPaths(changed, { index, untracked, gitlinks }, kind) {
395
+ /** @type {string[]} */
396
+ const disk = [];
397
+ /** @type {string[]} */
398
+ const indexed = [];
399
+ /** @type {string[]} */
400
+ const deletions = [];
401
+ for (const path of [...new Set(changed)].sort()) {
402
+ const entry = index.get(path);
403
+ if (gitlinks.has(path) || entry?.mode === "160000") {
404
+ if (["100644", "100755", "120000"].includes(gitlinks.get(path) ?? "")) deletions.push(path);
405
+ } else if (entry?.skip) indexed.push(path);
406
+ else if ((entry || untracked.has(path)) && kind(path) !== "absent") disk.push(path);
407
+ else deletions.push(path);
408
+ }
409
+ return { disk, indexed, deletions };
344
410
  }
345
411
 
346
- /** @param {string} cwd */
347
- export function sourceBaseSha(cwd) {
412
+ /** @param {string} error @param {string} next */
413
+ const tooLarge = (error, next = "Commit and push the large files, then retry.") => new CliError({ code: "too_large", error, next });
414
+
415
+ /** The newest commit of HEAD's history on an origin remote-tracking branch, or `preferred` while it still qualifies.
416
+ * @param {string} cwd @param {string} [preferred] a failed verify's base */
417
+ export function sourceBase(cwd, preferred) {
348
418
  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;
419
+ const tips = git(root, ["for-each-ref", "--format=%(objectname)", "refs/remotes/origin/"]).toString().split("\n").filter(Boolean);
420
+ const ok = (/** @type {string[]} */ ...args) => { try { git(root, args); return true; } catch { return false; } };
421
+ if (preferred && /^[0-9a-f]{40}$/.test(preferred) && ok("merge-base", "--is-ancestor", preferred, "HEAD")
422
+ && git(root, ["for-each-ref", "--contains", preferred, "--count=1", "refs/remotes/origin/"]).length) return preferred;
423
+ let base = "";
424
+ if (tips.length) try { base = git(root, ["merge-base", "HEAD", ...tips]).toString().trim(); } catch {}
425
+ if (/^[0-9a-f]{40}$/.test(base)) return base;
426
+ const shallow = git(root, ["rev-parse", "--is-shallow-repository"]).toString().trim() === "true";
427
+ throw new CliError({ code: "base_unavailable", error: "No commit of HEAD's history is on a remote-tracking branch of origin",
428
+ next: shallow ? "git fetch --deepen=100 origin, then retry" : "git push -u origin HEAD, then retry" });
352
429
  }
353
430
 
354
- /** Build the raw Git base and final local overlay. @param {string} cwd */
355
- export function buildSource(cwd, includeObjects = true) {
431
+ /** The overlay of every path that differs from `baseSha`, which GitHub must already have. @param {string} cwd @param {string} baseSha */
432
+ export function buildSource(cwd, baseSha) {
356
433
  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);
434
+ // An untracked embedded repository is listed as "dir/"; it is not uploaded.
435
+ const untracked = paths(git(root, ["ls-files", "--others", "--exclude-standard", "-z"])).filter(path => !path.endsWith("/"));
436
+ /** @type {Map<string, {mode: string, oid: string, skip: boolean}>} */
437
+ const index = new Map();
438
+ for (const line of paths(git(root, ["ls-files", "-s", "-t", "-z"]))) {
439
+ const tab = line.indexOf("\t"); const [tag, mode, oid] = line.slice(0, tab).split(" ");
440
+ index.set(line.slice(tab + 1), { mode, oid, skip: tag === "S" });
441
+ }
442
+ const raw = paths(git(root, ["diff", "--no-renames", "--raw", "-z", baseSha, "--"]));
443
+ const changed = [...untracked]; const gitlinks = new Map();
444
+ for (let i = 0; i + 1 < raw.length; i += 2) {
445
+ const [oldMode, newMode] = raw[i].slice(1).split(" ");
446
+ changed.push(raw[i + 1]);
447
+ if (newMode === "160000") gitlinks.set(raw[i + 1], oldMode);
368
448
  }
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") };
449
+ const { disk, indexed, deletions } = overlayPaths(changed, { index, untracked: new Set(untracked), gitlinks }, path => {
450
+ try { const stat = lstatSync(`${root}/${path}`); return stat.isFile() ? "file" : stat.isSymbolicLink() ? "link" : "absent"; }
451
+ catch (error) { if (["ENOENT", "ENOTDIR"].includes(/** @type {NodeJS.ErrnoException} */ (error).code ?? "")) return "absent"; throw error; }
379
452
  });
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"]))]);
453
+ if (disk.length + indexed.length + deletions.length > MAX_PATHS) throw tooLarge(`changes exceed ${MAX_PATHS} paths`);
454
+ for (const path of [...disk, ...indexed, ...deletions]) checkPath(path);
382
455
  /** @type {{path:string,mode:"100644"|"100755"|"120000",data:string}[]} */
383
456
  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);
457
+ let wireBytes = 0;
458
+ /** @param {string} path @param {"100644"|"100755"|"120000"} mode @param {Buffer} data */
459
+ const add = (path, mode, data) => {
460
+ if (data.length > MAX_FILE_BYTES) throw tooLarge(`file exceeds 32 MiB: ${path}`, "Commit and push it, then retry.");
461
+ if (mode === "120000" && data.length > MAX_PATH_BYTES) throw new Error(`link target exceeds ${MAX_PATH_BYTES} bytes: ${path}`);
462
+ wireBytes += Math.ceil(data.length / 3) * 4;
463
+ if (wireBytes > MAX_WIRE_BYTES) throw tooLarge("changes exceed the 64 MiB upload limit");
405
464
  overlay.push({ path, mode, data: data.toString("base64") });
465
+ };
466
+ for (const path of disk) {
467
+ const stat = lstatSync(`${root}/${path}`);
468
+ if (stat.isSymbolicLink()) add(path, "120000", Buffer.from(readlinkSync(`${root}/${path}`)));
469
+ else {
470
+ if (stat.size > MAX_FILE_BYTES) throw tooLarge(`file exceeds 32 MiB: ${path}`, "Commit and push it, then retry.");
471
+ add(path, stat.mode & 0o111 ? "100755" : "100644", readFileSync(`${root}/${path}`));
472
+ }
473
+ }
474
+ for (const path of indexed) {
475
+ const { mode, oid } = /** @type {{mode: "100644"|"100755"|"120000", oid: string}} */ (index.get(path));
476
+ if (!["100644", "100755", "120000"].includes(mode)) throw new Error(`unsupported Git entry mode ${mode}: ${path}`);
477
+ 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.");
478
+ add(path, mode, git(root, ["cat-file", "blob", oid], MAX_FILE_BYTES + 1));
406
479
  }
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 };
480
+ return { schemaVersion: 2, baseSha, overlay, deletions };
412
481
  }
413
482
 
414
483
  /** @param {ReturnType<typeof buildSource>} source */
415
484
  export function encodeSource(source) {
416
485
  const body = JSON.stringify(source);
417
- if (Buffer.byteLength(body) > MAX_WIRE_BYTES) throw new Error("verification upload exceeds the 64 MiB transport limit");
486
+ if (Buffer.byteLength(body) > MAX_WIRE_BYTES) throw tooLarge("changes exceed the 64 MiB upload limit");
418
487
  return body;
419
488
  }