notusci 0.1.11 → 0.1.15

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.11",
3
+ "version": "0.1.15",
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,7 +7,7 @@ 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, apiUrl, authFile, boundedWaitSeconds, buildSource, dependencyHint, encodeSource, jsonText, parseCommand, pickWorkflow, renderError,
10
+ CliError, HELP, NPX, addTakeoverGuard, apiUrl, githubPlan, authFile, billingText, boundedWaitSeconds, buildSource, dependencyHint, encodeSource, jsonText, parseCommand, pickWorkflow, renderError,
11
11
  repositoryFromRemote, runPath, setCodexServer, setCursorServer, shouldWaitAgain, sourceBase, sourceIdentity,
12
12
  } from "./core.mjs";
13
13
 
@@ -222,7 +222,55 @@ async function init(s, input) {
222
222
  }
223
223
  }
224
224
  if (input.billing) return billing(s, { repo, timeoutSeconds: 90 });
225
- print({ status: "ready", user: me.user, repo: listed(me, repo).repo, scopes: me.scopes, workflow, mcp, next: `${NPX} verify` });
225
+ const githubFirst = input.githubFirst && await githubFirstSetup(s, root, me, listed(me, repo), workflow, input.githubFirst, deadline);
226
+ print({ status: "ready", user: me.user, repo: listed(me, repo).repo, scopes: me.scopes, workflow, mcp, ...(githubFirst && { githubFirst }), next: `${NPX} verify` });
227
+ }
228
+
229
+ /** The account's GitHub plan from the local `gh` login, when it can see it. @param {string} owner @param {string} login */
230
+ function ghPlan(owner, login) {
231
+ try {
232
+ return githubPlan(execFileSync("gh", ["api", owner.toLowerCase() === login.toLowerCase() ? "user" : `orgs/${owner}`, "--jq", ".plan.name"],
233
+ { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10_000 }));
234
+ } catch { return undefined; }
235
+ }
236
+
237
+ /**
238
+ * Spec 070, init's default: guards the workflow's job so GitHub skips it during takeover, then turns GitHub-first on.
239
+ * A workflow with more than one job stays on GitHub, watched only. Never commits or pushes.
240
+ * @param {Session} s @param {string} root @param {any} me @param {{repo: string, pushWorkflow: string | null}} listing
241
+ * @param {string} workflow @param {string | true} flag a plan from --github-first, or true for the default @param {number} deadline
242
+ */
243
+ async function githubFirstSetup(s, root, me, listing, workflow, flag, deadline) {
244
+ const { repo } = listing;
245
+ const off = (/** @type {string} */ reason) => ({ status: "off", reason });
246
+ if (!me.scopes.includes("ship:prod")) return off("changing repo settings needs the ship:prod scope; rerun init with it");
247
+ const usage = await api(s, "/api/github-usage", { query: { repo }, deadline });
248
+ // A repository already on NotusCI only keeps it unless asked.
249
+ if (flag === true && listing.pushWorkflow && !usage.watching.includes(repo)) return off(`pushes already run on NotusCI (${listing.pushWorkflow}); pass --github-first PLAN to switch`);
250
+ const path = join(root, workflow);
251
+ const before = readFileSync(path, "utf8");
252
+ let guarded;
253
+ try { guarded = addTakeoverGuard(before); }
254
+ catch (error) { if (error instanceof CliError && error.body.code === "workflow_refused") return off(error.body.error); throw error; }
255
+ const detected = typeof flag === "string" ? undefined : usage.plan ?? ghPlan(repo.split("/")[0], me.user.login);
256
+ const plan = typeof flag === "string" ? flag : detected ?? "free";
257
+ const takeover = guarded.jobs === 1;
258
+ if (takeover && guarded.text !== before) writeFileSync(path, guarded.text);
259
+ const saved = await api(s, `/api/repos/${repo}/settings`, { method: "PUT", deadline,
260
+ body: { githubFirst: { plan }, ...(takeover && { pushWorkflow: workflow }) } });
261
+ const diff = execFileSync("git", ["diff", "--", workflow], { cwd: root, encoding: "utf8" });
262
+ return {
263
+ status: "on", plan, planSource: typeof flag === "string" ? "flag" : usage.plan ? "stated" : detected ? "gh" : "default",
264
+ takeover: takeover ? "on" : `off: ${workflow} has ${guarded.jobs} jobs and NotusCI runs one; pushes stay on GitHub, watched`,
265
+ ...(diff && { diff }), variables: saved.variables,
266
+ next: [
267
+ ...(diff ? [`Commit and push ${workflow}`] : []),
268
+ "Tell the human: in branch protection, require the NotusCI check instead of the GitHub job",
269
+ ...(saved.next ? [`Tell the human: ${saved.next}`] : []),
270
+ ...(!detected && typeof flag !== "string" ? ["Plan assumed free (switches earliest); if the account pays GitHub, rerun init --github-first pro|team|enterprise"] : []),
271
+ `Undo: revert ${workflow}, then ${NPX} repo set --settings '{"githubFirst":null,"pushWorkflow":null}'`,
272
+ ],
273
+ };
226
274
  }
227
275
 
228
276
  /** @param {Session} s @param {{repo?: string, timeoutSeconds: number, interval?: "month" | "year"}} input */
@@ -351,6 +399,10 @@ async function main(s, input) {
351
399
  case "doctor": return doctor(s);
352
400
  case "login": return login(s, input);
353
401
  case "billing": return billing(s, input);
402
+ case "billing status": {
403
+ const summary = await api(s, "/api/billing/summary", { query: { repo: repoOrOrigin(input.repo) } });
404
+ return input.json ? print(summary) : process.stdout.write(billingText(summary));
405
+ }
354
406
  case "usage": {
355
407
  const repo = repoOrOrigin(input.repo);
356
408
  return print(input.capUsd === undefined ? await api(s, "/api/usage", { query: { repo } })
package/src/core.mjs CHANGED
@@ -29,7 +29,7 @@ function usage(error) {
29
29
 
30
30
  /** @type {Record<string, Record<string, {type: "string" | "boolean"}>>} */
31
31
  const OPTIONS = {
32
- init: { scope: { type: "string" }, "no-mcp": { type: "boolean" }, billing: { type: "boolean" } },
32
+ init: { scope: { type: "string" }, "no-mcp": { type: "boolean" }, billing: { type: "boolean" }, "github-first": { type: "string" }, "no-github-first": { type: "boolean" } },
33
33
  login: { scope: { type: "string" } },
34
34
  doctor: {}, logout: {}, token: {}, whoami: {}, repos: {}, version: {}, "--version": {},
35
35
  target: { repo: { type: "string" }, file: { type: "string" }, "auto-promote": { type: "string" }, "auto-release": { type: "string" } },
@@ -43,14 +43,14 @@ const OPTIONS = {
43
43
  approve: { repo: { type: "string" } },
44
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
- billing: { repo: { type: "string" }, timeout: { type: "string" }, yearly: { type: "boolean" } },
46
+ billing: { repo: { type: "string" }, timeout: { type: "string" }, yearly: { type: "boolean" }, json: { type: "boolean" } },
47
47
  usage: { repo: { type: "string" }, cap: { type: "string" } },
48
48
  api: { data: { type: "string" } },
49
49
  };
50
50
 
51
51
  export const HELP = {
52
52
  commands: [
53
- "init [--scope SCOPES] [--no-mcp] [--billing]", "billing [--repo OWNER/REPO] [--yearly] [--timeout SECONDS]", "usage [--repo OWNER/REPO] [--cap USD]", "doctor",
53
+ "init [--scope SCOPES] [--no-mcp] [--billing] [--github-first free|pro|team|enterprise | --no-github-first]", "billing [--repo OWNER/REPO] [--yearly] [--timeout SECONDS]", "billing status [--repo OWNER/REPO] [--json]", "usage [--repo OWNER/REPO] [--cap USD]", "doctor",
54
54
  "login [--scope SCOPES]", "logout", "whoami", "repos", "token list", "token revoke ID",
55
55
  "target set [--repo OWNER/REPO] [--file TARGET.json] [--auto-promote on|off] [--auto-release on|off]",
56
56
  "secret set NAME [--repo OWNER/REPO] (value on stdin)", "secret list [--repo OWNER/REPO]", "secret rm NAME [--repo OWNER/REPO]",
@@ -114,7 +114,11 @@ export function parseCommand(args) {
114
114
  const scopes = [...new Set((values.scope ?? DEFAULT_SCOPES).split(","))];
115
115
  const unknown = scopes.filter(scope => !SCOPES.includes(scope));
116
116
  if (unknown.length) throw usage(`unknown scope ${unknown.join(",")}; scopes are ${SCOPES.join(",")}`);
117
- return command === "init" ? { command, scopes, mcp: !values["no-mcp"], billing: values.billing === true } : { command, scopes };
117
+ const githubFirst = values["github-first"];
118
+ if (githubFirst !== undefined && !GITHUB_PLANS.includes(githubFirst)) throw usage("--github-first takes your GitHub plan: free, pro, team or enterprise");
119
+ if (githubFirst && values["no-github-first"]) throw usage("pass --github-first PLAN or --no-github-first, not both");
120
+ return command === "init" ? { command, scopes, mcp: !values["no-mcp"], billing: values.billing === true,
121
+ githubFirst: values["no-github-first"] ? false : githubFirst ?? true } : { command, scopes };
118
122
  }
119
123
  if (["doctor", "logout", "whoami", "repos"].includes(command)) { expect(); return { command }; }
120
124
  if (command === "version" || command === "--version") { expect(); return { command: "version" }; }
@@ -179,6 +183,7 @@ export function parseCommand(args) {
179
183
  if (values.workflow === "") throw usage("--workflow must not be empty");
180
184
  return { command, workflow: values.workflow, timeoutSeconds: timeoutSeconds ?? 540, ...(values["no-reuse"] ? { reuse: false } : {}) };
181
185
  }
186
+ if (command === "billing" && positionals[0] === "status") { expect("status"); return { command: "billing status", repo: values.repo, json: values.json === true }; }
182
187
  if (command === "billing") { expect(); return { command, repo: values.repo, timeoutSeconds: timeoutSeconds ?? 90, ...(values.yearly ? { interval: "year" } : {}) }; }
183
188
  if (command === "usage") {
184
189
  expect(); const capUsd = values.cap === undefined ? undefined : Number(values.cap);
@@ -231,6 +236,27 @@ function nextMonthStart(now) {
231
236
  return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1)).toISOString().slice(0, 10);
232
237
  }
233
238
 
239
+ const PLAN_NAMES = { free: "Free", trial: "Pro trial", pro: "Pro", legacy: "Early access" };
240
+
241
+ /** `billing status` without --json: labels and numbers, one line each (077). @param {any} b @returns {string} */
242
+ export function billingText(b) {
243
+ const day = (/** @type {string} */ iso) => new Date(iso).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" });
244
+ const usd = (/** @type {number} */ n) => `$${n.toFixed(2)}`;
245
+ const row = (/** @type {string} */ label, /** @type {unknown} */ value) => value ? [`${label.padEnd(13)}${value}`] : [];
246
+ const p = b.period, o = p.overage;
247
+ const head = [`${PLAN_NAMES[/** @type {keyof typeof PLAN_NAMES} */ (b.plan)] ?? b.plan}${b.source === "comp" ? " (comp)" : ""}`,
248
+ b.interval && (b.interval === "year" ? "yearly" : "monthly"), !["trial", "free", "comp", "legacy"].includes(b.status) && b.status.replace("_", " ")];
249
+ return [head.filter(Boolean).join(" · "),
250
+ ...row("Next charge", b.nextCharge && `${usd(b.nextCharge.amountUsd)}${b.nextCharge.estimate ? " (estimate)" : ""} · ${day(b.nextCharge.at)}`),
251
+ ...row("Cancels", b.cancelsAt && day(b.cancelsAt)), ...row("Trial ends", b.trialEndsAt && day(b.trialEndsAt)),
252
+ ...row("This period", `${p.usedMinutes} / ${p.includedMinutes} min · ${p.leftMinutes} min left${b.trialEndsAt ? "" : ` · resets ${day(p.resetsAt)}`}`),
253
+ ...row("Overage", o && `${o.minutes} min · ${usd(o.usd)} of ${usd(o.capUsd)} cap`),
254
+ ...row("Card", b.paymentMethod && `${b.paymentMethod.brand} ···· ${b.paymentMethod.last4}`),
255
+ ...b.invoices.map((/** @type {any} */ i, /** @type {number} */ n) => `${(n ? "" : "Invoices").padEnd(13)}${day(i.at)} ${i.number ?? "-"} ${usd(i.amountUsd)} ${i.status} ${i.url ?? ""}`.trimEnd()),
256
+ ...row("Manage", b.actions.manage), ...row("Upgrade", b.actions.upgrade),
257
+ ].join("\n") + "\n";
258
+ }
259
+
234
260
  /**
235
261
  * Fill in the agent-facing message and `next` for an error code.
236
262
  * @param {{error?: string, code: string, next?: string, [key: string]: any}} body @returns {Record<string, any>}
@@ -251,7 +277,7 @@ export function renderError({ error = "", code, next, ...extra }, now = Date.now
251
277
  }
252
278
  if (code === "account_suspended") {
253
279
  return { error: error || "This NotusCI account is suspended for review.", code,
254
- next: "Stop. Tell the human the account is suspended and to write to binh@notusworks.com.", ...extra };
280
+ next: "Stop. Tell the human the account is suspended and to contact NotusCI at https://ci.notusworks.com/support.", ...extra };
255
281
  }
256
282
  if (code === "rate_limited") return { error, code, next: "Wait a minute before the next call; tell the human if it repeats.", ...extra };
257
283
  if (code === "missing_scope") return { error, code, next: `${NPX} login --scope ${String(extra.scopes)}`, ...extra };
@@ -265,6 +291,57 @@ export function renderError({ error = "", code, next, ...extra }, now = Date.now
265
291
  return { error, code, next: next ?? defaults[code] ?? "Tell the human the error.", ...extra };
266
292
  }
267
293
 
294
+ const GITHUB_PLANS = ["free", "pro", "team", "enterprise"];
295
+
296
+ /** GitHub's plan name (from `gh api user` or `gh api orgs/OWNER`) as a githubFirst plan; undefined when unknown. @param {unknown} name */
297
+ export function githubPlan(name) {
298
+ const value = String(name ?? "").trim().toLowerCase();
299
+ if (GITHUB_PLANS.includes(value)) return value;
300
+ if (/^(enterprise|business)/.test(value)) return "enterprise";
301
+ return undefined;
302
+ }
303
+
304
+ export const TAKEOVER_GUARD ="vars.NOTUSCI_TAKEOVER != 'true' || github.event.pull_request.head.repo.fork";
305
+
306
+ /**
307
+ * Spec 070: adds the takeover guard to each job's `if:`, keeping an existing one with `&&`.
308
+ * Returns the new text and the job count; a guard already there leaves the text as it is.
309
+ * @param {string} text a workflow file @returns {{ text: string, jobs: number }}
310
+ */
311
+ export function addTakeoverGuard(text) {
312
+ const lines = text.split("\n");
313
+ const indent = (/** @type {string} */ line) => line.length - line.trimStart().length;
314
+ const blank = (/** @type {string} */ line) => !line.trim() || line.trim().startsWith("#");
315
+ const start = lines.findIndex(line => /^jobs:\s*(#.*)?$/.test(line));
316
+ /** @type {number[]} */
317
+ const jobs = [];
318
+ let jobIndent = -1;
319
+ for (let i = start + 1; start >= 0 && i < lines.length; i++) {
320
+ if (blank(lines[i])) continue;
321
+ if (indent(lines[i]) === 0) break;
322
+ if (jobIndent < 0) jobIndent = indent(lines[i]);
323
+ if (indent(lines[i]) === jobIndent && /^\s*[A-Za-z_][\w-]*:\s*(#.*)?$/.test(lines[i])) jobs.push(i);
324
+ }
325
+ if (!jobs.length) throw new CliError({ code: "workflow_refused", error: "No block-style jobs: section found; add the if: line by hand", guard: TAKEOVER_GUARD });
326
+ const on = lines.findIndex(line => /^["']?on["']?:/.test(line));
327
+ const next = lines.findIndex((line, i) => i > on && !blank(line) && indent(line) === 0);
328
+ if (on < 0 || !/\b(push|pull_request)\b/.test(lines.slice(on, next < 0 ? undefined : next).join("\n"))) {
329
+ throw new CliError({ code: "workflow_refused", error: "GitHub-first needs the workflow to run on push or pull_request; add them to on:" });
330
+ }
331
+ if (text.includes("vars.NOTUSCI_TAKEOVER")) return { text, jobs: jobs.length };
332
+ for (const job of [...jobs].reverse()) {
333
+ let end = job + 1;
334
+ while (end < lines.length && (blank(lines[end]) || indent(lines[end]) > jobIndent)) end++;
335
+ const propIndent = lines.slice(job + 1, end).filter(line => !blank(line)).map(indent)[0] ?? jobIndent + 2;
336
+ const at = lines.findIndex((line, i) => i > job && i < end && indent(line) === propIndent && /^\s*if:/.test(line));
337
+ if (at < 0) { lines.splice(job + 1, 0, `${" ".repeat(propIndent)}if: ${TAKEOVER_GUARD}`); continue; }
338
+ const value = lines[at].trim().slice(3).trim().replace(/^\$\{\{\s*([\s\S]*?)\s*\}\}$/, "$1");
339
+ if (!value || /^["'|>]/.test(value) || value.includes("#")) throw new CliError({ code: "workflow_refused", error: `Line ${at + 1}: merge the job's if: with the guard by hand`, guard: TAKEOVER_GUARD });
340
+ lines[at] = `${" ".repeat(propIndent)}if: (${TAKEOVER_GUARD}) && (${value})`;
341
+ }
342
+ return { text: lines.join("\n"), jobs: jobs.length };
343
+ }
344
+
268
345
  /** @param {string[]} names files in .github/workflows */
269
346
  export function pickWorkflow(names) {
270
347
  const files = names.filter(name => /\.ya?ml$/.test(name)).sort();