nulladrift 0.9.0 → 0.10.0

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/README.md CHANGED
@@ -400,9 +400,9 @@ These are read, never required, and set by the CI provider rather than by you:
400
400
  | Variable | What it is used for |
401
401
  | --- | --- |
402
402
  | `CI` | Marks a reading as made in CI rather than locally, and keeps telemetry from asking a question nobody is there to answer. `CI=false` counts as unset. |
403
- | `GITHUB_REPOSITORY`, `CI_PROJECT_PATH`, `BUILD_REPOSITORY_NAME` | The project name `push` reports under (GitHub, GitLab, Azure Pipelines), unless `--project` names one. Outside CI it is the directory's name. |
404
- | `GITHUB_REF_NAME`, `CI_COMMIT_REF_NAME` | The branch or tag `push` reports. |
405
- | `GITHUB_SHA`, `CI_COMMIT_SHA` | The commit `push` reports. |
403
+ | `GITHUB_REPOSITORY`, `CI_PROJECT_PATH`, `BITBUCKET_REPO_FULL_NAME`, `BUILD_REPOSITORY_NAME`, `CIRCLE_PROJECT_USERNAME` with `CIRCLE_PROJECT_REPONAME`, `BUILDKITE_REPO` | The project `push` reports under, unless `--project` names one. Outside CI it comes from the git remote (`origin`), in the same `owner/repo` shape, so a laptop and its pipeline report to one project. Only with no remote is it the directory's name, and `push` says so. |
404
+ | `GITHUB_REF_NAME`, `CI_COMMIT_REF_NAME`, `BUILD_SOURCEBRANCH`, `BITBUCKET_BRANCH`, `BITBUCKET_TAG`, `CIRCLE_BRANCH`, `CIRCLE_TAG`, `BUILDKITE_BRANCH` | The branch or tag `push` reports, unless `--ref` names one. Outside CI, the checked-out branch. |
405
+ | `GITHUB_SHA`, `CI_COMMIT_SHA`, `BUILD_SOURCEVERSION`, `BITBUCKET_COMMIT`, `CIRCLE_SHA1`, `BUILDKITE_COMMIT` | The commit `push` reports, unless `--commit` names one. Outside CI, `HEAD`. The repository is read from `.git` directly; `git` is never run. |
406
406
  | `GITHUB_ACTIONS`, `ACTIONS_ID_TOKEN_REQUEST_URL`, `ACTIONS_ID_TOKEN_REQUEST_TOKEN` | How `push` asks GitHub for the job's identity token. The last two exist only when the job has `id-token: write`. |
407
407
  | `GITHUB_REF`, `GITHUB_API_URL` | Which pull request `check --comment` writes on, and the API to write through (GitHub Enterprise Server sets its own). |
408
408
 
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/index.ts
4
4
  import { parseArgs } from "util";
5
- import { resolve as resolve6 } from "path";
5
+ import { resolve as resolve7 } from "path";
6
6
 
7
7
  // ../core/src/changes.ts
8
8
  var CHANGE_KINDS = [
@@ -693,7 +693,6 @@ var RULES = [
693
693
  // execution, and `country_code`, `status_code` and `zip_code` are all waiting behind it.
694
694
  { kind: "code-eval", severity: "critical", name: /(^|_)(eval|evaluate|run_code|exec_code|interpret|compile)(_|$)/, arg: /^code$|(^|_)(source_code|code_to_run|js_code|python_code|expression|program|snippet)(_|$)/ },
695
695
  { kind: "credential-access", severity: "critical", name: /(^|_)(secret|secrets|credential|credentials|token|keychain|vault|password)(_|$)/, arg: /(^|_)(secret|credential|password|private_key|api_key|access_token)(_|$)/ },
696
- { kind: "file-write", severity: "high", name: /(^|_)(write|create_file|put_file|save|delete|remove|unlink|rename|move|copy|chmod|mkdir|rmdir|edit)(_|$)/, arg: /(^|_)(contents|content|data|destination|dest_path|target_path)(_|$)/ },
697
696
  { kind: "network-egress", severity: "high", name: /(^|_)(fetch|request|http|curl|download|upload|post|webhook|navigate|browse|send)(_|$)/, arg: /(^|_)(url|uri|endpoint|host|hostname|webhook|callback)(_|$)/ },
698
697
  // Narrowed to things that are actually SQL-shaped. `query`, `select` and `update` on their
699
698
  // own matched `simulate-research-query`, `browser_select_option` and `trigger-resource-update`,
@@ -702,8 +701,29 @@ var RULES = [
702
701
  { kind: "privilege", severity: "high", name: /(^|_)(sudo|root|admin|grant|revoke|permission|permissions|acl|policy)(_|$)/, arg: /(^|_)(role|scope|scopes|permission|permissions|privilege)(_|$)/ },
703
702
  { kind: "agent-control", severity: "high", name: /(^|_)(prompt|system_prompt|instruction|instructions|memory|context|persona)(_|$)/, arg: /(^|_)(system_prompt|instruction|instructions|persona)(_|$)/ },
704
703
  { kind: "env-access", severity: "medium", name: /(^|_)(env|environment|getenv|setenv|config|settings)(_|$)/, arg: /(^|_)(env|environment|env_var)(_|$)/ },
705
- { kind: "file-read", severity: "low", name: /(^|_)(read|read_file|cat|open|load|list_directory|ls|glob|search_files)(_|$)/, arg: /(^|_)(path|file|filename|filepath|directory|dir)(_|$)/ }
704
+ // `read`, `open` and `load` are not here; see `fileRead` below.
705
+ { kind: "file-read", severity: "low", name: /(^|_)(read_file|cat|list_directory|ls|glob|search_files)(_|$)/, arg: /(^|_)(path|file|filename|filepath|directory|dir)(_|$)/ }
706
706
  ];
707
+ var FILE_ONLY_VERBS = /(^|_)(write|create_file|put_file|unlink|chmod|chown|mkdir|rmdir|truncate)(_|$)/;
708
+ var CHANGING_VERBS = /(^|_)(create|save|delete|remove|rename|move|copy|edit|append|put|overwrite|replace|patch)(_|$)/;
709
+ var FILE_NOUNS = /(^|_)(file|files|filename|dir|dirs|directory|directories|folder|folders|path|paths)(_|$)/;
710
+ var PATH_ARGS = /^(path|paths|file|files|filename|filepath|file_path|directory|dir|folder|source_path)$|(^|_)(path|filepath|filename)$/;
711
+ var DESTINATION_ARGS = /(^|_)(destination|dest|dest_path|target_path|output_path|out_path)(_|$)/;
712
+ var CONTENT_ARGS = /(^|_)(contents|content|data|text|body)$/;
713
+ function fileWrite(name, args) {
714
+ if (FILE_ONLY_VERBS.test(name)) return "name";
715
+ const path = args.find(([, normalized]) => PATH_ARGS.test(normalized));
716
+ if (CHANGING_VERBS.test(name) && (FILE_NOUNS.test(name) || path)) return "name";
717
+ const destination = args.find(([, normalized]) => DESTINATION_ARGS.test(normalized));
718
+ if (destination) return `arg:${destination[0]}`;
719
+ const content = args.find(([, normalized]) => CONTENT_ARGS.test(normalized));
720
+ if (content && path) return `arg:${content[0]}`;
721
+ return void 0;
722
+ }
723
+ var READING_VERBS = /(^|_)(read|open|load)(_|$)/;
724
+ function fileRead(name) {
725
+ return READING_VERBS.test(name) && FILE_NOUNS.test(name);
726
+ }
707
727
  var CONFUSABLES = {
708
728
  "\u0430": "a",
709
729
  "\u0435": "e",
@@ -758,6 +778,9 @@ function toolCapabilities(tool2) {
758
778
  const hit = rule.arg ? args.find(([, normalized]) => rule.arg?.test(normalized)) : void 0;
759
779
  if (hit) found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: `arg:${hit[0]}` });
760
780
  }
781
+ if (!found.has("file-read") && fileRead(name)) found.set("file-read", { kind: "file-read", severity: "low", evidence: "name" });
782
+ const writes = fileWrite(name, args);
783
+ if (writes) found.set("file-write", { kind: "file-write", severity: "high", evidence: writes });
761
784
  return [...found.values()].sort(
762
785
  (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind)
763
786
  );
@@ -1386,29 +1409,29 @@ function surfaceText(subject) {
1386
1409
  };
1387
1410
  push("instructions", subject?.instructions);
1388
1411
  for (const tool2 of objectsIn(subject?.tools)) {
1389
- const where = stringOr(tool2.name) ?? "?";
1390
- push(`${where}.title`, tool2.title);
1391
- push(`${where}.description`, tool2.description);
1392
- schemaText(tool2.inputSchema, `${where}.inputSchema`, out);
1393
- schemaText(tool2.outputSchema, `${where}.outputSchema`, out);
1412
+ const where2 = stringOr(tool2.name) ?? "?";
1413
+ push(`${where2}.title`, tool2.title);
1414
+ push(`${where2}.description`, tool2.description);
1415
+ schemaText(tool2.inputSchema, `${where2}.inputSchema`, out);
1416
+ schemaText(tool2.outputSchema, `${where2}.outputSchema`, out);
1394
1417
  }
1395
1418
  for (const prompt2 of objectsIn(subject?.prompts)) {
1396
- const where = stringOr(prompt2.name) ?? "?";
1397
- push(`prompt:${where}.title`, prompt2.title);
1398
- push(`prompt:${where}.description`, prompt2.description);
1419
+ const where2 = stringOr(prompt2.name) ?? "?";
1420
+ push(`prompt:${where2}.title`, prompt2.title);
1421
+ push(`prompt:${where2}.description`, prompt2.description);
1399
1422
  for (const argument of objectsIn(prompt2.arguments)) {
1400
- push(`prompt:${where}.${stringOr(argument.name) ?? "?"}`, argument.description);
1423
+ push(`prompt:${where2}.${stringOr(argument.name) ?? "?"}`, argument.description);
1401
1424
  }
1402
1425
  }
1403
1426
  for (const resource2 of objectsIn(subject?.resources)) {
1404
- const where = stringOr(resource2.name) ?? stringOr(resource2.uri) ?? "?";
1405
- push(`resource:${where}.title`, resource2.title);
1406
- push(`resource:${where}.description`, resource2.description);
1427
+ const where2 = stringOr(resource2.name) ?? stringOr(resource2.uri) ?? "?";
1428
+ push(`resource:${where2}.title`, resource2.title);
1429
+ push(`resource:${where2}.description`, resource2.description);
1407
1430
  }
1408
1431
  for (const template of objectsIn(subject?.resourceTemplates)) {
1409
- const where = stringOr(template.name) ?? stringOr(template.uriTemplate) ?? "?";
1410
- push(`template:${where}.title`, template.title);
1411
- push(`template:${where}.description`, template.description);
1432
+ const where2 = stringOr(template.name) ?? stringOr(template.uriTemplate) ?? "?";
1433
+ push(`template:${where2}.title`, template.title);
1434
+ push(`template:${where2}.description`, template.description);
1412
1435
  }
1413
1436
  return out;
1414
1437
  }
@@ -1785,8 +1808,8 @@ function anchorCwd(server2, projectRoot) {
1785
1808
  return { ...server2, transport: { ...transport2, cwd: resolve2(projectRoot, transport2.cwd) } };
1786
1809
  }
1787
1810
  function describeSearch(searched, filesRead) {
1788
- const read = new Set(filesRead);
1789
- const lines = searched.map((path) => ` ${(read.has(path) ? "read" : "absent").padEnd(6)} ${path}`);
1811
+ const read2 = new Set(filesRead);
1812
+ const lines = searched.map((path) => ` ${(read2.has(path) ? "read" : "absent").padEnd(6)} ${path}`);
1790
1813
  return lines.join("\n");
1791
1814
  }
1792
1815
  async function discoverServers(projectRoot, extraFiles = [], options = {}) {
@@ -1805,18 +1828,18 @@ async function discoverServers(projectRoot, extraFiles = [], options = {}) {
1805
1828
  const problems = [];
1806
1829
  const requested = new Set(files.filter((file) => file.client === "generic").map((file) => file.path));
1807
1830
  for (const file of files) {
1808
- const read = await readJsonIfPresent(file.path);
1809
- if (!read.present) {
1831
+ const read2 = await readJsonIfPresent(file.path);
1832
+ if (!read2.present) {
1810
1833
  if (requested.has(file.path)) {
1811
1834
  problems.push({ file: portablePath(file.path, projectRoot), reason: "no such file; it was named with --config" });
1812
1835
  }
1813
1836
  continue;
1814
1837
  }
1815
- if (!read.ok) {
1816
- problems.push({ file: portablePath(file.path, projectRoot), reason: read.reason });
1838
+ if (!read2.ok) {
1839
+ problems.push({ file: portablePath(file.path, projectRoot), reason: read2.reason });
1817
1840
  continue;
1818
1841
  }
1819
- const raw = read.value;
1842
+ const raw = read2.value;
1820
1843
  filesRead.push(file.path);
1821
1844
  const source = { client: file.client, file: portablePath(file.path, projectRoot) };
1822
1845
  let mapKey = CLIENT_MAP_KEY[file.client];
@@ -2005,7 +2028,7 @@ import { readFile as readFile3 } from "fs/promises";
2005
2028
  import { isAbsolute as isAbsolute2, resolve as resolve3 } from "path";
2006
2029
 
2007
2030
  // src/lib/version.ts
2008
- var VERSION = "0.9.0";
2031
+ var VERSION = "0.10.0";
2009
2032
  var USER_AGENT = `nulladrift/${VERSION} (+https://github.com/Nulladrift/nulladrift)`;
2010
2033
 
2011
2034
  // src/lock/provenance.ts
@@ -2349,9 +2372,9 @@ function launchPinned(transport2, provenance2) {
2349
2372
  }
2350
2373
  function imageLocation(name) {
2351
2374
  const parts = name.split("/");
2352
- const first = parts[0];
2353
- const hasHost = parts.length > 1 && (first.includes(".") || first.includes(":") || first === "localhost");
2354
- let host = hasHost ? first : "registry-1.docker.io";
2375
+ const first2 = parts[0];
2376
+ const hasHost = parts.length > 1 && (first2.includes(".") || first2.includes(":") || first2 === "localhost");
2377
+ let host = hasHost ? first2 : "registry-1.docker.io";
2355
2378
  if (host === "docker.io" || host === "index.docker.io") host = "registry-1.docker.io";
2356
2379
  let repository = hasHost ? parts.slice(1).join("/") : name;
2357
2380
  if (host === "registry-1.docker.io" && !repository.includes("/")) repository = `library/${repository}`;
@@ -2846,6 +2869,61 @@ function isAuthFailure(error) {
2846
2869
  return /\b(401|403)\b|unauthorized|forbidden|invalid or missing[^\n]{0,80}?token|authentication required|invalid_client|dynamic client registration/.test(text);
2847
2870
  }
2848
2871
 
2872
+ // src/mcp/network.ts
2873
+ var MAX_DEPTH2 = 8;
2874
+ function networkError(error) {
2875
+ const pending = [{ value: error, depth: 0 }];
2876
+ while (pending.length > 0) {
2877
+ const { value, depth } = pending.shift();
2878
+ if (value === null || typeof value !== "object" || depth > MAX_DEPTH2) continue;
2879
+ const candidate = value;
2880
+ if (typeof candidate.code === "string" && /^(E[A-Z]+|UND_ERR_[A-Z_]+|CERT_[A-Z_]+|ERR_TLS_[A-Z_]+|UNABLE_TO_[A-Z_]+|[A-Z_]*SELF_SIGNED[A-Z_]*)$/.test(candidate.code)) {
2881
+ return {
2882
+ code: candidate.code,
2883
+ address: typeof candidate.address === "string" ? candidate.address : void 0,
2884
+ port: typeof candidate.port === "number" ? candidate.port : void 0,
2885
+ hostname: typeof candidate.hostname === "string" ? candidate.hostname : void 0
2886
+ };
2887
+ }
2888
+ pending.push({ value: candidate.cause, depth: depth + 1 });
2889
+ if (Array.isArray(candidate.errors)) for (const inner of candidate.errors.slice(0, 8)) pending.push({ value: inner, depth: depth + 1 });
2890
+ }
2891
+ return void 0;
2892
+ }
2893
+ function where(found) {
2894
+ const host = found.hostname ?? found.address;
2895
+ if (!host) return "";
2896
+ const shown = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
2897
+ return found.port !== void 0 ? `${shown}:${found.port}` : shown;
2898
+ }
2899
+ function describeNetworkFailure(error) {
2900
+ const found = networkError(error);
2901
+ if (!found) return void 0;
2902
+ const at = where(found);
2903
+ switch (found.code) {
2904
+ case "ECONNREFUSED":
2905
+ return `connection refused${at ? ` by ${at}` : ""}: nothing is listening there. Is the server running, and is the port right?`;
2906
+ case "ENOTFOUND":
2907
+ return `${at ? `the host name ${found.hostname ?? at}` : "the host name"} does not resolve. Check the URL for a typo, or the DNS this machine uses.`;
2908
+ case "EAI_AGAIN":
2909
+ return `looking up ${found.hostname ?? "the host name"} failed for now (EAI_AGAIN): DNS did not answer. Try again, or check this machine's network.`;
2910
+ case "ETIMEDOUT":
2911
+ case "UND_ERR_CONNECT_TIMEOUT":
2912
+ return `connecting${at ? ` to ${at}` : ""} timed out. A firewall may be dropping the traffic, or the host is down.`;
2913
+ case "ECONNRESET":
2914
+ case "UND_ERR_SOCKET":
2915
+ return `the connection${at ? ` to ${at}` : ""} was dropped before the server answered.`;
2916
+ case "EHOSTUNREACH":
2917
+ case "ENETUNREACH":
2918
+ return `there is no route to ${at || "the host"} from this machine (${found.code}).`;
2919
+ default:
2920
+ if (/CERT|TLS|SELF_SIGNED|UNABLE_TO/.test(found.code)) {
2921
+ return `the server's TLS certificate was not accepted (${found.code}). Fix the certificate, or set NODE_EXTRA_CA_CERTS to the CA that signed it.`;
2922
+ }
2923
+ return `${found.code}${at ? ` at ${at}` : ""}`;
2924
+ }
2925
+ }
2926
+
2849
2927
  // src/mcp/connect.ts
2850
2928
  var DEFAULT_TIMEOUT_MS2 = 3e4;
2851
2929
  var STDERR_KEEP_BYTES = 2e3;
@@ -3051,9 +3129,10 @@ async function connect(server2, timeoutMs = DEFAULT_TIMEOUT_MS2, options = {}) {
3051
3129
  });
3052
3130
  if (guard.refusal !== void 0) throw new UnreachableServerError(server2.name, guard.refusal, error);
3053
3131
  const detail = stderrBuffer.trim();
3132
+ const network = describeNetworkFailure(error);
3054
3133
  throw new UnreachableServerError(
3055
3134
  server2.name,
3056
- `${error.message}${detail ? `
3135
+ `${error.message}${network ? ` (${network})` : ""}${detail ? `
3057
3136
  server stderr: ${diagnosticLines(detail).join("\n ")}` : ""}`,
3058
3137
  error
3059
3138
  );
@@ -3083,11 +3162,11 @@ function describeValidationIssues(message) {
3083
3162
  return void 0;
3084
3163
  }
3085
3164
  if (!Array.isArray(issues) || issues.length === 0) return void 0;
3086
- const where = (issue) => (issue.path ?? []).map((part) => typeof part === "number" ? `[${part}]` : `.${String(part)}`).join("").replace(/^\./, "");
3165
+ const where2 = (issue) => (issue.path ?? []).map((part) => typeof part === "number" ? `[${part}]` : `.${String(part)}`).join("").replace(/^\./, "");
3087
3166
  const byMessage = /* @__PURE__ */ new Map();
3088
3167
  for (const issue of issues) {
3089
3168
  const text = issue.message ?? "did not validate";
3090
- byMessage.set(text, [...byMessage.get(text) ?? [], where(issue)]);
3169
+ byMessage.set(text, [...byMessage.get(text) ?? [], where2(issue)]);
3091
3170
  }
3092
3171
  const lines = [...byMessage].slice(0, 3).map(([text, paths]) => {
3093
3172
  const rest = paths.length > 1 ? ` (and ${paths.length - 1} more like it)` : "";
@@ -3674,9 +3753,9 @@ function parseLockfile(text, path) {
3674
3753
  }
3675
3754
  const parsed = lockfileSchema.safeParse(raw);
3676
3755
  if (!parsed.success) {
3677
- const first = parsed.error.issues[0];
3678
- const where = first && first.path.length > 0 ? ` at ${first.path.join(".")}` : "";
3679
- throw new LockfileError(`${path} is not a valid lockfile${where}: ${first?.message ?? "unknown error"}`);
3756
+ const first2 = parsed.error.issues[0];
3757
+ const where2 = first2 && first2.path.length > 0 ? ` at ${first2.path.join(".")}` : "";
3758
+ throw new LockfileError(`${path} is not a valid lockfile${where2}: ${first2?.message ?? "unknown error"}`);
3680
3759
  }
3681
3760
  return parsed.data;
3682
3761
  }
@@ -3745,8 +3824,8 @@ function renderTextChange(before, after) {
3745
3824
  return lines;
3746
3825
  }
3747
3826
  function renderChange(change2) {
3748
- const where = visibleControls(change2.member ? `${change2.server} \u203A ${change2.member}` : change2.server);
3749
- const lines = [` ${MARK[change2.severity](change2.severity.padEnd(6))} ${bold(where)} ${dim(change2.kind)}`, ` ${visibleControls(change2.summary)}`];
3827
+ const where2 = visibleControls(change2.member ? `${change2.server} \u203A ${change2.member}` : change2.server);
3828
+ const lines = [` ${MARK[change2.severity](change2.severity.padEnd(6))} ${bold(where2)} ${dim(change2.kind)}`, ` ${visibleControls(change2.summary)}`];
3750
3829
  if (change2.kind === "tool.description.changed" || change2.kind === "server.instructions.changed") {
3751
3830
  lines.push(...renderTextChange(change2.before, change2.after));
3752
3831
  }
@@ -4108,8 +4187,8 @@ function code(text) {
4108
4187
  return `${fence}${pad}${body}${pad}${fence}`;
4109
4188
  }
4110
4189
  function row(change2) {
4111
- const where = change2.member ? `${change2.server}/${change2.member}` : change2.server;
4112
- return `| ${MARK2[change2.severity]} ${change2.severity} | ${code(where)} | ${plain(change2.kind)} | ${plain(change2.summary)} |`;
4190
+ const where2 = change2.member ? `${change2.server}/${change2.member}` : change2.server;
4191
+ return `| ${MARK2[change2.severity]} ${change2.severity} | ${code(where2)} | ${plain(change2.kind)} | ${plain(change2.summary)} |`;
4113
4192
  }
4114
4193
  function renderMarkdownReport(report, options = {}) {
4115
4194
  const violations = report.violations ?? [];
@@ -4712,8 +4791,8 @@ async function awaitCallback(expectedState) {
4712
4791
  server2.listen(0, "127.0.0.1", ready);
4713
4792
  });
4714
4793
  const { port } = server2.address();
4715
- const received = new Promise((resolve7, reject) => {
4716
- settle = resolve7;
4794
+ const received = new Promise((resolve8, reject) => {
4795
+ settle = resolve8;
4717
4796
  fail = reject;
4718
4797
  setTimeout(() => reject(new Error(`no callback within ${CALLBACK_TIMEOUT_MS / 1e3}s`)), CALLBACK_TIMEOUT_MS).unref();
4719
4798
  });
@@ -4730,9 +4809,9 @@ async function findServer(projectRoot, configFiles, name) {
4730
4809
  const named = new Set(configFiles.map((file) => portablePath(resolve5(projectRoot, file), projectRoot)));
4731
4810
  const chosen = conflict.definitions.filter((definition) => named.has(definition.file));
4732
4811
  if (chosen.length === 1) return chosen[0].server;
4733
- const where = conflict.definitions.map((definition) => ` ${definition.file}: ${describeTarget(definition.server)}`).join("\n");
4812
+ const where2 = conflict.definitions.map((definition) => ` ${definition.file}: ${describeTarget(definition.server)}`).join("\n");
4734
4813
  return { error: `"${name}" is defined differently in more than one config:
4735
- ${where}
4814
+ ${where2}
4736
4815
  Name the one you mean with --config <file>.` };
4737
4816
  }
4738
4817
  const server2 = discovery.servers.find((candidate) => candidate.name === name);
@@ -4907,29 +4986,181 @@ async function fromGithubActions(audience, env, options) {
4907
4986
  }
4908
4987
  }
4909
4988
 
4989
+ // src/lib/origin.ts
4990
+ import { existsSync as existsSync2, readFileSync as readFileSync3, statSync as statSync2 } from "fs";
4991
+ import { dirname as dirname4, isAbsolute as isAbsolute4, join as join5, resolve as resolve6 } from "path";
4992
+ var MAX_PROJECT = 200;
4993
+ var MAX_REF = 200;
4994
+ function first(env, ...names) {
4995
+ for (const name of names) {
4996
+ const value = env[name]?.trim();
4997
+ if (value) return value;
4998
+ }
4999
+ return void 0;
5000
+ }
5001
+ function shortRef(ref) {
5002
+ return ref.replace(/^refs\/(heads|tags)\//, "");
5003
+ }
5004
+ function repositoryPath(remote) {
5005
+ const url = remote.trim();
5006
+ let path;
5007
+ const scp = /^(?:[^/@:\s]+@)?[^/:\s\\]{2,}:(?!\/)([^\\]+)$/.exec(url);
5008
+ if (scp) path = scp[1];
5009
+ else {
5010
+ try {
5011
+ path = new URL(url).pathname;
5012
+ } catch {
5013
+ return void 0;
5014
+ }
5015
+ }
5016
+ const azure = /\/_git\/([^/]+)/.exec(path ?? "");
5017
+ if (azure) path = azure[1];
5018
+ const cleaned = (path ?? "").replace(/^\/+|\/+$/g, "").replace(/\.git$/, "");
5019
+ return cleaned && !cleaned.includes("..") ? cleaned : void 0;
5020
+ }
5021
+ function projectFromCi(env) {
5022
+ const named = first(env, "GITHUB_REPOSITORY", "CI_PROJECT_PATH", "BITBUCKET_REPO_FULL_NAME", "BUILD_REPOSITORY_NAME");
5023
+ if (named) return named;
5024
+ const user = first(env, "CIRCLE_PROJECT_USERNAME");
5025
+ const repo = first(env, "CIRCLE_PROJECT_REPONAME");
5026
+ if (user && repo) return `${user}/${repo}`;
5027
+ const buildkite = first(env, "BUILDKITE_REPO");
5028
+ return buildkite ? repositoryPath(buildkite) : void 0;
5029
+ }
5030
+ function refFromCi(env) {
5031
+ const ref = first(
5032
+ env,
5033
+ "GITHUB_REF_NAME",
5034
+ "CI_COMMIT_REF_NAME",
5035
+ "BUILD_SOURCEBRANCH",
5036
+ "BITBUCKET_BRANCH",
5037
+ "BITBUCKET_TAG",
5038
+ "CIRCLE_BRANCH",
5039
+ "CIRCLE_TAG",
5040
+ "BUILDKITE_BRANCH"
5041
+ );
5042
+ return ref ? shortRef(ref) : void 0;
5043
+ }
5044
+ function commitFromCi(env) {
5045
+ return first(env, "GITHUB_SHA", "CI_COMMIT_SHA", "BUILD_SOURCEVERSION", "BITBUCKET_COMMIT", "CIRCLE_SHA1", "BUILDKITE_COMMIT");
5046
+ }
5047
+ function read(path) {
5048
+ try {
5049
+ if (!statSync2(path).isFile() || statSync2(path).size > 4 * 1024 * 1024) return void 0;
5050
+ return readFileSync3(path, "utf8");
5051
+ } catch {
5052
+ return void 0;
5053
+ }
5054
+ }
5055
+ function gitDirectories(start) {
5056
+ let dir = resolve6(start);
5057
+ for (let depth = 0; depth < 64; depth += 1) {
5058
+ const dotGit = join5(dir, ".git");
5059
+ if (existsSync2(dotGit)) {
5060
+ let gitDir = dotGit;
5061
+ try {
5062
+ if (statSync2(dotGit).isFile()) {
5063
+ const pointer = /^gitdir:\s*(.+)$/m.exec(read(dotGit) ?? "")?.[1]?.trim();
5064
+ if (!pointer) return void 0;
5065
+ gitDir = isAbsolute4(pointer) ? pointer : resolve6(dir, pointer);
5066
+ }
5067
+ } catch {
5068
+ return void 0;
5069
+ }
5070
+ const common = read(join5(gitDir, "commondir"))?.trim();
5071
+ return { gitDir, commonDir: common ? resolve6(gitDir, common) : gitDir };
5072
+ }
5073
+ const parent = dirname4(dir);
5074
+ if (parent === dir) return void 0;
5075
+ dir = parent;
5076
+ }
5077
+ return void 0;
5078
+ }
5079
+ function resolveRef(commonDir, ref) {
5080
+ if (!/^refs\/[\w./-]+$/.test(ref) || ref.includes("..")) return void 0;
5081
+ const loose = read(join5(commonDir, ref))?.trim();
5082
+ if (loose && /^[0-9a-f]{40,64}$/.test(loose)) return loose;
5083
+ for (const line of (read(join5(commonDir, "packed-refs")) ?? "").split("\n")) {
5084
+ const [sha, name] = line.trim().split(" ");
5085
+ if (name === ref && sha && /^[0-9a-f]{40,64}$/.test(sha)) return sha;
5086
+ }
5087
+ return void 0;
5088
+ }
5089
+ function remoteUrl(commonDir) {
5090
+ const config = read(join5(commonDir, "config"));
5091
+ if (!config) return void 0;
5092
+ const remotes = /* @__PURE__ */ new Map();
5093
+ let current;
5094
+ for (const raw of config.split("\n")) {
5095
+ const line = raw.trim();
5096
+ const section = /^\[\s*remote\s+"([^"]+)"\s*\]$/.exec(line);
5097
+ if (section) {
5098
+ current = section[1];
5099
+ continue;
5100
+ }
5101
+ if (line.startsWith("[")) {
5102
+ current = void 0;
5103
+ continue;
5104
+ }
5105
+ const url = /^url\s*=\s*(.+)$/.exec(line);
5106
+ if (current && url?.[1] && !remotes.has(current)) remotes.set(current, url[1].trim());
5107
+ }
5108
+ return remotes.get("origin") ?? remotes.values().next().value;
5109
+ }
5110
+ function repositoryFacts(root) {
5111
+ const dirs = gitDirectories(root);
5112
+ if (!dirs) return {};
5113
+ const head = read(join5(dirs.gitDir, "HEAD"))?.trim() ?? "";
5114
+ const symbolic = /^ref:\s*(refs\/\S+)$/.exec(head)?.[1];
5115
+ const commit = symbolic ? resolveRef(dirs.commonDir, symbolic) : /^[0-9a-f]{40,64}$/.test(head) ? head : void 0;
5116
+ const remote = remoteUrl(dirs.commonDir);
5117
+ return {
5118
+ project: remote ? repositoryPath(remote) : void 0,
5119
+ // A detached HEAD has a commit and no branch, which is what CI checkouts usually are.
5120
+ ref: symbolic?.startsWith("refs/heads/") ? shortRef(symbolic) : void 0,
5121
+ commit
5122
+ };
5123
+ }
5124
+ function readingOrigin(root, flags, env = process.env) {
5125
+ const repo = repositoryFacts(root);
5126
+ const usable = (value, max) => value && value.length <= max ? value : void 0;
5127
+ let project;
5128
+ let projectFrom;
5129
+ const ci = usable(projectFromCi(env), MAX_PROJECT);
5130
+ const fromRepo = usable(repo.project, MAX_PROJECT);
5131
+ if (flags.project) {
5132
+ project = flags.project;
5133
+ projectFrom = "flag";
5134
+ } else if (ci) {
5135
+ project = ci;
5136
+ projectFrom = "ci";
5137
+ } else if (fromRepo) {
5138
+ project = fromRepo;
5139
+ projectFrom = "repository";
5140
+ } else {
5141
+ project = resolve6(root).split(/[\\/]/).filter(Boolean).pop() ?? "default";
5142
+ projectFrom = "folder";
5143
+ }
5144
+ return {
5145
+ project,
5146
+ projectFrom,
5147
+ ref: flags.ref ?? usable(refFromCi(env), MAX_REF) ?? usable(repo.ref, MAX_REF),
5148
+ commit: flags.commit ?? commitFromCi(env) ?? repo.commit
5149
+ };
5150
+ }
5151
+
4910
5152
  // src/commands/push.ts
4911
5153
  function describeIdentity(identity3, hint) {
4912
5154
  const shown = (text) => visibleControls(text);
4913
- const where = shown(`${identity3?.repository ?? ""}${identity3?.ref ? ` @ ${identity3.ref}` : ""}`);
5155
+ const where2 = shown(`${identity3?.repository ?? ""}${identity3?.ref ? ` @ ${identity3.ref}` : ""}`);
4914
5156
  const contents = identity3?.boundToReading ? " \xB7 contents signed" : identity3?.bindingRefused ? ` \xB7 contents not signed: ${shown(identity3.bindingRefused)}` : "";
4915
- if (identity3?.trust === "trusted") return `${green("signed")} ${dim(`${where} \xB7 a trusted build${contents}`)}`;
5157
+ if (identity3?.trust === "trusted") return `${green("signed")} ${dim(`${where2} \xB7 a trusted build${contents}`)}`;
4916
5158
  if (identity3?.trust === "verified") {
4917
- return `${yellow("signed")} ${dim(`${where} \xB7 not a build this organization lists as trusted${contents}`)}`;
5159
+ return `${yellow("signed")} ${dim(`${where2} \xB7 not a build this organization lists as trusted${contents}`)}`;
4918
5160
  }
4919
5161
  if (identity3?.rejected) return `${red("build token refused")} ${dim(shown(identity3.rejected))}`;
4920
5162
  return hint ? dim(`unsigned: ${hint}`) : void 0;
4921
5163
  }
4922
- function inferProject(projectRoot) {
4923
- const fromCi = process.env["GITHUB_REPOSITORY"] ?? process.env["CI_PROJECT_PATH"] ?? process.env["BUILD_REPOSITORY_NAME"];
4924
- if (fromCi) return fromCi;
4925
- return projectRoot.split("/").filter(Boolean).pop() ?? "default";
4926
- }
4927
- function inferRef() {
4928
- return process.env["GITHUB_REF_NAME"] ?? process.env["CI_COMMIT_REF_NAME"] ?? void 0;
4929
- }
4930
- function inferCommit() {
4931
- return process.env["GITHUB_SHA"] ?? process.env["CI_COMMIT_SHA"] ?? void 0;
4932
- }
4933
5164
  function refuseApiUrl(apiUrl) {
4934
5165
  let url;
4935
5166
  try {
@@ -5005,10 +5236,29 @@ ${dim(`Looked in: ${looked}`)}
5005
5236
  promptCount: entry.prompts?.length ?? 0,
5006
5237
  surface: entry
5007
5238
  }));
5239
+ for (const [flag, value, max] of [
5240
+ ["--project", options.project, 200],
5241
+ ["--ref", options.ref, 200],
5242
+ ["--commit", options.commit, 100]
5243
+ ]) {
5244
+ const control = value !== void 0 && [...value].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127);
5245
+ if (value !== void 0 && (value.trim() === "" || value.length > max || control)) {
5246
+ process.stderr.write(`${red(`${flag} has to be 1 to ${max} characters, with no control characters.`)}
5247
+ `);
5248
+ return EXIT_INCOMPLETE;
5249
+ }
5250
+ }
5251
+ const origin = readingOrigin(options.projectRoot, { project: options.project, ref: options.ref, commit: options.commit });
5252
+ if (origin.projectFrom === "folder") {
5253
+ process.stderr.write(
5254
+ `${yellow("note:")} reporting as project "${visibleControls(origin.project)}", this folder's name: no --project, CI variable or git remote names it. Pass --project so every push names it the same way.
5255
+ `
5256
+ );
5257
+ }
5008
5258
  const body = {
5009
- project: options.project ?? inferProject(options.projectRoot),
5010
- ref: options.ref ?? inferRef(),
5011
- commit: options.commit ?? inferCommit(),
5259
+ project: origin.project,
5260
+ ref: origin.ref,
5261
+ commit: origin.commit,
5012
5262
  context: options.watch ? "watch" : process.env["CI"] !== void 0 && process.env["CI"] !== "false" ? "ci" : "local",
5013
5263
  collectorVersion: VERSION,
5014
5264
  servers,
@@ -5062,7 +5312,8 @@ ${dim(`Looked in: ${looked}`)}
5062
5312
  const lines = [""];
5063
5313
  const mark = verdict.verdict === "clean" ? green("\u2713") : verdict.verdict === "drift" ? yellow("!") : red("\u2717");
5064
5314
  const shown = (text) => visibleControls(String(text ?? ""));
5065
- lines.push(`${mark} ${bold(shown(verdict.verdict))} ${dim(`\xB7 ${servers.length} server(s) \xB7 reading ${shown(verdict.readingId).slice(0, 8)}`)}`);
5315
+ lines.push(`${mark} ${bold(shown(verdict.verdict))} ${dim(`\xB7 ${shown(origin.project)} \xB7 ${servers.length} server(s) \xB7 reading ${shown(verdict.readingId).slice(0, 8)}`)}`);
5316
+ if (origin.ref || origin.commit) lines.push(` ${dim(`at ${shown(origin.ref ?? "a detached commit")}${origin.commit ? ` @ ${shown(origin.commit).slice(0, 7)}` : ""}`)}`);
5066
5317
  const identity3 = describeIdentity(verdict.identity, build && "hint" in build ? build.hint : void 0);
5067
5318
  if (identity3) lines.push(` ${identity3}`);
5068
5319
  for (const change2 of verdict.changes) {
@@ -5240,7 +5491,9 @@ ${bold("Options")}
5240
5491
  --force re-pin over an existing lockfile, discarding it (init)
5241
5492
  --api <url> control plane to push to (push; or NULLADRIFT_API_URL)
5242
5493
  --token <token> collector token (push; or NULLADRIFT_TOKEN)
5243
- --project <name> project name to report under (push; inferred from CI otherwise)
5494
+ --project <name> project to report under (push; else from CI, then the git remote, then the folder)
5495
+ --ref <branch> branch or tag to record (push; else from CI, then the checked-out branch)
5496
+ --commit <sha> commit to record (push; else from CI, then HEAD)
5244
5497
  --watch mark this as a scheduled reading rather than one a build asked for (push)
5245
5498
  --comment post the findings on the pull request being reviewed (check; needs CI)
5246
5499
  -h, --help this text
@@ -5273,6 +5526,8 @@ async function main() {
5273
5526
  api: { type: "string" },
5274
5527
  token: { type: "string" },
5275
5528
  project: { type: "string" },
5529
+ ref: { type: "string" },
5530
+ commit: { type: "string" },
5276
5531
  watch: { type: "boolean", default: false },
5277
5532
  comment: { type: "boolean", default: false },
5278
5533
  help: { type: "boolean", short: "h", default: false },
@@ -5301,10 +5556,10 @@ async function main() {
5301
5556
  `);
5302
5557
  return EXIT_INCOMPLETE;
5303
5558
  }
5304
- const projectRoot = resolve6(values.cwd ?? process.cwd());
5559
+ const projectRoot = resolve7(values.cwd ?? process.cwd());
5305
5560
  const options = {
5306
5561
  projectRoot,
5307
- lockPath: resolve6(projectRoot, values.lock ?? DEFAULT_LOCK_FILENAME),
5562
+ lockPath: resolve7(projectRoot, values.lock ?? DEFAULT_LOCK_FILENAME),
5308
5563
  configFiles: values.config ?? [],
5309
5564
  timeoutMs,
5310
5565
  allowUnreachable: values["allow-unreachable"],
@@ -5321,7 +5576,7 @@ async function main() {
5321
5576
  case "check":
5322
5577
  return runCheck(options);
5323
5578
  case "push":
5324
- return runPush({ ...options, apiUrl: values.api, token: values.token, project: values.project, watch: values.watch });
5579
+ return runPush({ ...options, apiUrl: values.api, token: values.token, project: values.project, ref: values.ref, commit: values.commit, watch: values.watch });
5325
5580
  case "review":
5326
5581
  return runReview({ ...options, acceptAll: values["accept-all"] });
5327
5582
  case "login":