notusci 0.1.1 → 0.1.2

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