threadctx 0.2.1 → 0.4.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.
@@ -1076,14 +1076,14 @@ var require_parse = __commonJS({
1076
1076
  };
1077
1077
  if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
1078
1078
  let backslashes = false;
1079
- let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc2, chars, first, rest, index) => {
1079
+ let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc3, chars, first, rest, index) => {
1080
1080
  if (first === "\\") {
1081
1081
  backslashes = true;
1082
1082
  return m;
1083
1083
  }
1084
1084
  if (first === "?") {
1085
- if (esc2) {
1086
- return esc2 + first + (rest ? QMARK.repeat(rest.length) : "");
1085
+ if (esc3) {
1086
+ return esc3 + first + (rest ? QMARK.repeat(rest.length) : "");
1087
1087
  }
1088
1088
  if (index === 0) {
1089
1089
  return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : "");
@@ -1094,12 +1094,12 @@ var require_parse = __commonJS({
1094
1094
  return DOT_LITERAL.repeat(chars.length);
1095
1095
  }
1096
1096
  if (first === "*") {
1097
- if (esc2) {
1098
- return esc2 + first + (rest ? star : "");
1097
+ if (esc3) {
1098
+ return esc3 + first + (rest ? star : "");
1099
1099
  }
1100
1100
  return star;
1101
1101
  }
1102
- return esc2 ? m : `\\${m}`;
1102
+ return esc3 ? m : `\\${m}`;
1103
1103
  });
1104
1104
  if (backslashes === true) {
1105
1105
  if (opts.unescape === true) {
@@ -9337,7 +9337,7 @@ var require_ignore = __commonJS({
9337
9337
  // ever starts again inside it -- `(\\+?) ` did, which made a long run
9338
9338
  // quadratic.
9339
9339
  /(\\+)( ?)/g,
9340
- (_, run2, space) => space ? run2.slice(0, run2.length - run2.length % 2) + SPACE : run2,
9340
+ (_, run3, space) => space ? run3.slice(0, run3.length - run3.length % 2) + SPACE : run3,
9341
9341
  ESCAPE + SPACE
9342
9342
  ],
9343
9343
  // Escape metacharacters
@@ -9510,10 +9510,10 @@ var require_ignore = __commonJS({
9510
9510
  var REGEX_REPLACE_TRAILING_DOUBLESTAR = /\uE001$/;
9511
9511
  var replaceTrailingDoublestar = () => ".+(?=$|\\/$)";
9512
9512
  var WILDCARD = "[^\\/]*";
9513
- var separatorAfter = (run2, at) => {
9513
+ var separatorAfter = (run3, at) => {
9514
9514
  let separator = EMPTY;
9515
- for (let index = at + 1; index < run2.length && !run2[index].wildcard; index++) {
9516
- separator += run2[index].single;
9515
+ for (let index = at + 1; index < run3.length && !run3[index].wildcard; index++) {
9516
+ separator += run3[index].single;
9517
9517
  }
9518
9518
  return separator;
9519
9519
  };
@@ -9573,26 +9573,26 @@ var require_ignore = __commonJS({
9573
9573
  }
9574
9574
  }
9575
9575
  let out = EMPTY;
9576
- let run2 = [];
9576
+ let run3 = [];
9577
9577
  const flush = () => {
9578
9578
  let lastWildcard;
9579
- run2.forEach((token, at) => {
9579
+ run3.forEach((token, at) => {
9580
9580
  if (token.wildcard) {
9581
9581
  lastWildcard = at;
9582
9582
  }
9583
9583
  });
9584
- run2.forEach((token, at) => {
9584
+ run3.forEach((token, at) => {
9585
9585
  if (!token.wildcard) {
9586
9586
  out += token.single;
9587
9587
  return;
9588
9588
  }
9589
- out += at === lastWildcard ? WILDCARD : `(?:(?!${separatorAfter(run2, at)})[^\\/])*`;
9589
+ out += at === lastWildcard ? WILDCARD : `(?:(?!${separatorAfter(run3, at)})[^\\/])*`;
9590
9590
  });
9591
- run2 = [];
9591
+ run3 = [];
9592
9592
  };
9593
9593
  tokens.forEach((token) => {
9594
9594
  if (token.boundary === void 0) {
9595
- run2.push(token);
9595
+ run3.push(token);
9596
9596
  return;
9597
9597
  }
9598
9598
  flush();
@@ -9986,9 +9986,9 @@ var require_ignore = __commonJS({
9986
9986
  });
9987
9987
 
9988
9988
  // src/cli.ts
9989
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, realpathSync as realpathSync2, statSync as statSync3, writeFileSync as writeFileSync2 } from "node:fs";
9989
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync3, realpathSync as realpathSync2, statSync as statSync3, writeFileSync as writeFileSync3 } from "node:fs";
9990
9990
  import { homedir as homedir2 } from "node:os";
9991
- import { basename, dirname, join as join4, relative as relative3, resolve as resolve4, sep as sep3 } from "node:path";
9991
+ import { basename, dirname as dirname2, join as join5, relative as relative3, resolve as resolve4, sep as sep3 } from "node:path";
9992
9992
  import { parseArgs } from "node:util";
9993
9993
 
9994
9994
  // ../adapters/dist/common.js
@@ -10852,6 +10852,7 @@ var LICENSE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
10852
10852
  MCowBQYDK2VwAyEAjxD7a4Ug5yVw5+Ra8bY1IZVLobxeiCS9dtrVwekYjqw=
10853
10853
  -----END PUBLIC KEY-----
10854
10854
  `;
10855
+ var LICENSE_PLANS = ["audit", "team", "business", "agency"];
10855
10856
  var PREFIX = "tctx1";
10856
10857
  function verifyLicense(key, opts = {}) {
10857
10858
  const parts = key.trim().split(".");
@@ -10866,11 +10867,18 @@ function verifyLicense(key, opts = {}) {
10866
10867
  } catch {
10867
10868
  return { ok: false, reason: "malformed" };
10868
10869
  }
10869
- if (claims.v !== 1 || typeof claims.exp !== "number" || typeof claims.org !== "string" || !["audit", "team", "business"].includes(claims.plan))
10870
+ if (claims.v !== 1 || typeof claims.exp !== "number" || typeof claims.org !== "string" || !LICENSE_PLANS.includes(claims.plan))
10871
+ return { ok: false, reason: "unsupported" };
10872
+ if (claims.agentRepoLimit !== void 0 && (!Number.isInteger(claims.agentRepoLimit) || claims.agentRepoLimit < 1))
10873
+ return { ok: false, reason: "unsupported" };
10874
+ if (claims.orgs !== void 0 && (!Array.isArray(claims.orgs) || claims.orgs.some((o) => typeof o !== "string")))
10870
10875
  return { ok: false, reason: "unsupported" };
10871
10876
  if (claims.exp * 1e3 < (opts.now ?? /* @__PURE__ */ new Date()).getTime())
10872
10877
  return { ok: false, reason: "expired" };
10873
- if (opts.org && claims.org !== "*" && claims.org !== opts.org.trim().toLowerCase())
10878
+ const want = opts.org?.trim().toLowerCase();
10879
+ if (want && claims.orgs?.length && !claims.orgs.includes(want))
10880
+ return { ok: false, reason: "wrong-org" };
10881
+ if (want && !claims.orgs?.length && claims.org !== "*" && claims.org !== want)
10874
10882
  return { ok: false, reason: "wrong-org" };
10875
10883
  return { ok: true, claims };
10876
10884
  }
@@ -12208,11 +12216,15 @@ function renderAuditText(s, opts) {
12208
12216
  for (const r of worst)
12209
12217
  out.push(` ${r.grade} ${String(r.score).padStart(3)} ${r.repo}`);
12210
12218
  }
12219
+ if (opts.controls) {
12220
+ const c = opts.controls;
12221
+ out.push("", `${p.bold("AI governance controls (SOC 2, ISO 27001, ISO 42001, NIST AI RMF):")} ${c.met}/${c.total} met${c.attention ? ` \xB7 ${c.attention} need attention` : ""}${c.gap ? ` \xB7 ${p.red(`${c.gap} gap${c.gap === 1 ? "" : "s"}`)}` : ""}`);
12222
+ }
12211
12223
  out.push("");
12212
12224
  if (opts.licensed) {
12213
12225
  out.push(p.green("Full report written:"), ...(opts.files ?? []).map((f) => ` ${f}`));
12214
12226
  } else {
12215
- out.push(p.bold("The full report is a paid feature."), `It adds every finding by repository, a ranked remediation plan, security findings, the token-cost estimate and`, `an executive one-pager you can forward. It includes ${s.repos.withContext} repositories and the ${s.plan.length} fixes ranked above.`, `Get a licence for ${s.org}: https://threadctx.dev/audit?org=${encodeURIComponent(s.org)}`, p.dim(`Then: threadctx audit --org ${s.org} --license <key>`));
12227
+ out.push(p.bold("The full report is a paid feature."), `It adds every finding by repository, a ranked remediation plan, security findings, the token-cost estimate,`, `an executive one-pager, and a compliance evidence pack (controls, framework cross-reference, agent and MCP`, `inventory) for SOC 2 and ISO auditors. It covers ${s.repos.withContext} repositories and the ${s.plan.length} fixes ranked above.`, `Get a licence for ${s.org}: https://threadctx.dev/audit?org=${encodeURIComponent(s.org)}`, p.dim(`Then: threadctx audit --org ${s.org} --license <key>`));
12216
12228
  }
12217
12229
  return `${out.join("\n")}
12218
12230
  `;
@@ -12305,7 +12317,8 @@ function renderAuditHtml(s, repos) {
12305
12317
  ${t.improved.length ? `<h3>Improved (${t.improved.length})</h3><table><tr><th>Repository</th><th>Score</th><th>Change</th></tr>${t.improved.map(row).join("")}</table>` : ""}
12306
12318
  ${t.added.length ? `<p class="small muted">New since then: ${t.added.map(esc).join(", ")}</p>` : ""}`);
12307
12319
  }
12308
- sections.push(`<h2>Summary</h2><ul>${takeaways(s).map((t) => `<li>${t.includes("<code>") ? t : esc(t)}</li>`).join("")}</ul>`);
12320
+ sections.push(`<h2>Summary</h2><ul>${takeaways(s).map((t) => `<li>${t.includes("<code>") ? t : esc(t)}</li>`).join("")}</ul>
12321
+ <div class="callout">For security and compliance reviews: <a href="evidence.html">evidence.html</a> maps these findings to SOC 2, ISO/IEC 27001, ISO/IEC 42001 and NIST AI RMF controls, with a full agent and MCP server inventory (also in <code>controls.csv</code> and <code>inventory.csv</code>).</div>`);
12309
12322
  if (s.plan.length) {
12310
12323
  sections.push(`<h2>Fix these first</h2><p class="muted small">Ranked by score gained per unit of effort. \u201CAutomatic\u201D fixes are mechanical and safe; \u201Cquick\u201D ones need a one-line decision; \u201Cmanual\u201D ones need a person.</p>
12311
12324
  <table><tr><th>#</th><th>Problem</th><th>Severity</th><th>Where</th><th>Effort</th><th>What to do</th></tr>${s.plan.slice(0, 10).map((p, i) => `<tr><td>${i + 1}</td><td><code>${esc(p.ruleId)}</code> ${esc(p.title)}</td><td>${sev(p.severity)}</td><td>${plural(p.findings, "finding")} in ${plural(p.repos, "repo")}</td><td>${esc(p.effort)}</td><td>${p.effort === "automatic" ? "Run <code>threadctx fix --apply</code> and review the diff." : esc(p.action)}</td></tr>`).join("")}</table>`);
@@ -12348,197 +12361,6 @@ function renderAuditHtml(s, repos) {
12348
12361
  `;
12349
12362
  }
12350
12363
 
12351
- // ../report/dist/index.js
12352
- var RULE_DOCS = "https://threadctx.dev/rules";
12353
- function renderJson(result) {
12354
- return `${JSON.stringify(result, null, 2)}
12355
- `;
12356
- }
12357
- var SARIF_LEVEL = { blocker: "error", warning: "warning", info: "note" };
12358
- var SECURITY_SEVERITY = { blocker: "9.0", warning: "5.0", info: "2.0" };
12359
- function renderSarif(result) {
12360
- const rules = [...result.rules].sort((a, b) => a.id < b.id ? -1 : 1);
12361
- const index = new Map(rules.map((r, i) => [r.id, i]));
12362
- const sarif = {
12363
- $schema: "https://json.schemastore.org/sarif-2.1.0.json",
12364
- version: "2.1.0",
12365
- runs: [
12366
- {
12367
- tool: {
12368
- driver: {
12369
- name: "threadctx",
12370
- semanticVersion: result.engine.version,
12371
- informationUri: "https://threadctx.dev",
12372
- rules: rules.map((r) => sarifRule(r))
12373
- }
12374
- },
12375
- automationDetails: { id: "threadctx/agent-context/" },
12376
- results: result.findings.map((f) => sarifResult(f, index.get(f.ruleId))),
12377
- properties: { grade: result.grade, score: result.score, registry: result.engine.registry }
12378
- }
12379
- ]
12380
- };
12381
- return `${JSON.stringify(sarif, null, 2)}
12382
- `;
12383
- }
12384
- function sarifRule(r) {
12385
- const tags = [.../* @__PURE__ */ new Set(["agent-context", r.family, r.determinism])];
12386
- return {
12387
- id: r.id,
12388
- name: r.id.replace(/[^A-Za-z0-9]/g, ""),
12389
- shortDescription: { text: r.title },
12390
- fullDescription: { text: r.rationale },
12391
- helpUri: r.id.startsWith("CTX-") ? `${RULE_DOCS}/${r.id}` : void 0,
12392
- help: { text: `${r.remediation}
12393
-
12394
- Source: ${r.citation}`, markdown: `${r.remediation}
12395
-
12396
- Source: ${r.citation}` },
12397
- defaultConfiguration: { level: SARIF_LEVEL[r.severity] },
12398
- properties: { tags, precision: r.determinism === "deterministic" ? "high" : "medium", ...r.family === "security" ? { "security-severity": SECURITY_SEVERITY[r.severity] } : {} }
12399
- };
12400
- }
12401
- function sarifResult(f, ruleIndex) {
12402
- const location = (path, line, endLine) => ({
12403
- physicalLocation: {
12404
- // Repository-level findings point at the root so code scanning still accepts them.
12405
- artifactLocation: { uri: path || ".", uriBaseId: "%SRCROOT%" },
12406
- ...line ? { region: { startLine: line, ...endLine && endLine > line ? { endLine } : {} } } : {}
12407
- }
12408
- });
12409
- return {
12410
- ruleId: f.ruleId,
12411
- ...ruleIndex !== void 0 ? { ruleIndex } : {},
12412
- level: SARIF_LEVEL[f.severity],
12413
- message: { text: f.evidence ? `${f.message}
12414
-
12415
- Evidence: ${f.evidence}` : f.message },
12416
- locations: [location(f.path, f.line, f.endLine)],
12417
- ...f.related?.length ? { relatedLocations: f.related.map((r, i) => ({ id: i + 1, ...location(r.path, r.line), message: { text: r.message ?? "related" } })) } : {},
12418
- partialFingerprints: { "threadctx/v1": f.fingerprint },
12419
- ...f.suppressed ? { suppressions: [{ kind: f.suppressed.source === "inline" ? "inSource" : "external", justification: f.suppressed.reason }] } : {}
12420
- };
12421
- }
12422
- function painter(color) {
12423
- const wrap = (code2) => (s) => color ? `\x1B[${code2}m${s}\x1B[0m` : s;
12424
- return { red: wrap("31"), yellow: wrap("33"), blue: wrap("34"), green: wrap("32"), dim: wrap("2"), bold: wrap("1"), cyan: wrap("36") };
12425
- }
12426
- var GRADE_COLOR = { A: "green", B: "green", C: "yellow", D: "yellow", F: "red" };
12427
- function renderText(result, opts) {
12428
- const p = painter(opts.color);
12429
- const out = [];
12430
- const open = result.findings.filter((f) => !f.suppressed);
12431
- const shown = opts.verbose ? open : open.filter((f) => f.severity !== "info");
12432
- const sev2 = { blocker: p.red("blocker"), warning: p.yellow("warning"), info: p.blue("info ") };
12433
- let lastPath;
12434
- for (const f of shown) {
12435
- if (f.path !== lastPath) {
12436
- out.push("", p.bold(f.path || "(repository)"));
12437
- lastPath = f.path;
12438
- }
12439
- const loc = f.line ? p.dim(`${String(f.line).padStart(4)}:`) : p.dim(" ");
12440
- const fix = f.fix?.kind === "safe" ? p.green(" [fixable]") : "";
12441
- out.push(`${loc} ${sev2[f.severity]} ${f.message} ${p.dim(f.ruleId)}${fix}`);
12442
- if (f.evidence)
12443
- out.push(` ${p.dim(`> ${f.evidence}`)}`);
12444
- }
12445
- const hiddenInfo = open.length - shown.length;
12446
- const { blocker, warning, info, suppressed } = result.counts;
12447
- out.push("");
12448
- out.push(`${p[GRADE_COLOR[result.grade]](p.bold(`Grade ${result.grade}`))} ${p.dim(`(${result.score}/100)`)} ${blocker} blocker${blocker === 1 ? "" : "s"}, ${warning} warning${warning === 1 ? "" : "s"}, ${info} info` + (suppressed ? p.dim(`, ${suppressed} suppressed`) : "") + (hiddenInfo ? p.dim(` (${hiddenInfo} info hidden; --verbose shows them)`) : ""));
12449
- const fixable = open.filter((f) => f.fix?.kind === "safe").length;
12450
- if (fixable)
12451
- out.push(p.dim(`${fixable} finding${fixable === 1 ? "" : "s"} can be fixed automatically: threadctx fix`));
12452
- const tools = result.tools.filter((t) => t.layers > 0);
12453
- if (tools.length) {
12454
- out.push(p.dim(`Always-loaded context (estimated tokens): ${tools.map((t) => `${t.label.split(" (")[0]} \u2248${t.alwaysTokenEstimate.toLocaleString("en-US")}`).join(" \xB7 ")}`));
12455
- }
12456
- for (const d of result.diagnostics) {
12457
- const tag = d.level === "error" ? p.red("error") : d.level === "warning" ? p.yellow("note") : p.dim("note");
12458
- out.push(`${tag} ${d.path ? `${d.path}${d.line ? `:${d.line}` : ""}: ` : ""}${d.message}`);
12459
- }
12460
- return `${out.join("\n").replace(/^\n/, "")}
12461
- `;
12462
- }
12463
- var SEV_ICON = { blocker: "\u{1F534}", warning: "\u{1F7E1}", info: "\u{1F535}" };
12464
- function mdEscape(s) {
12465
- return s.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
12466
- }
12467
- function renderMarkdown(result, opts = {}) {
12468
- const out = [];
12469
- const open = result.findings.filter((f) => !f.suppressed);
12470
- const delta = opts.baseline ? result.score === opts.baseline.score ? " (unchanged)" : ` (${opts.baseline.grade} \u2192 ${result.grade}, ${result.score - opts.baseline.score > 0 ? "+" : ""}${result.score - opts.baseline.score})` : "";
12471
- out.push(`### Agent context: grade **${result.grade}** \xB7 ${result.score}/100${delta}`);
12472
- out.push("");
12473
- out.push(`${result.counts.blocker} blocker${result.counts.blocker === 1 ? "" : "s"} \xB7 ${result.counts.warning} warning${result.counts.warning === 1 ? "" : "s"} \xB7 ${result.counts.info} info${result.counts.suppressed ? ` \xB7 ${result.counts.suppressed} suppressed` : ""}`);
12474
- const list = opts.newFingerprints ? open.filter((f) => opts.newFingerprints.has(f.fingerprint)) : open;
12475
- if (opts.newFingerprints)
12476
- out.push("", `**${list.length} new** in this change${open.length > list.length ? ` (${open.length - list.length} existing not shown)` : ""}.`);
12477
- const max = opts.maxFindings ?? 50;
12478
- if (list.length) {
12479
- out.push("", "| | Rule | Location | Finding |", "|---|---|---|---|");
12480
- for (const f of list.slice(0, max)) {
12481
- const rule = f.ruleId.startsWith("CTX-") ? `[${f.ruleId}](${RULE_DOCS}/${f.ruleId})` : f.ruleId;
12482
- out.push(`| ${SEV_ICON[f.severity]} | ${rule} | \`${mdEscape(f.path || ".")}${f.line ? `:${f.line}` : ""}\` | ${mdEscape(f.message)} |`);
12483
- }
12484
- if (list.length > max)
12485
- out.push("", `\u2026and ${list.length - max} more. Run \`npx threadctx scan\` locally for the full list.`);
12486
- }
12487
- const tools = result.tools.filter((t) => t.layers > 0);
12488
- if (tools.length) {
12489
- out.push("", "<details><summary>What each agent loads at the repository root (estimated tokens)</summary>", "");
12490
- for (const t of tools)
12491
- out.push(`- ${t.label}: \u2248${t.alwaysTokenEstimate.toLocaleString("en-US")} tokens across ${t.layers} file${t.layers === 1 ? "" : "s"}`);
12492
- out.push("", "</details>");
12493
- }
12494
- out.push("", `<sub>[threadctx](https://threadctx.dev) ${result.engine.version}${opts.footerUrl ? ` \xB7 [history and badge](${opts.footerUrl})` : ""} \xB7 [how grades work](https://threadctx.dev/methodology)</sub>`);
12495
- return `${out.join("\n")}
12496
- `;
12497
- }
12498
- var LOAD_LABEL = { always: "always", "on-demand": "on demand", conditional: "matches", "agent-decides": "agent decides" };
12499
- function renderEffective(contexts, opts) {
12500
- const p = painter(opts.color);
12501
- const out = [];
12502
- for (const { label: label2, ctx } of contexts) {
12503
- out.push(p.bold(`${label2}`) + p.dim(` ${ctx.targetPath} \u2248${ctx.tokenEstimate.toLocaleString("en-US")} tokens (estimate)`));
12504
- if (!ctx.layers.length)
12505
- out.push(p.dim(" (loads nothing from this repository)"));
12506
- for (const l of ctx.layers) {
12507
- out.push(` ${String(l.precedence).padStart(2)}. ${l.path.padEnd(44)} ${p.cyan(LOAD_LABEL[l.loading].padEnd(13))} ${p.dim(`\u2248${l.tokenEstimate}`.padStart(6))} ${p.dim(l.reason)}`);
12508
- }
12509
- for (const n2 of ctx.notes)
12510
- out.push(p.dim(` note: ${n2}`));
12511
- out.push("");
12512
- }
12513
- return out.join("\n");
12514
- }
12515
- function renderFactTable(rows, tools, opts) {
12516
- const p = painter(opts.color);
12517
- if (!rows.length)
12518
- return p.dim("No comparable facts (commands, package manager, versions) found.\n");
12519
- const width = 26;
12520
- const head = `${"".padEnd(18)}${tools.map((t) => t.padEnd(width)).join("")}`;
12521
- const lines = [p.bold(head)];
12522
- for (const r of rows) {
12523
- const vals = tools.map((t) => r.values[t]?.length ? r.values[t].join(", ") : "\u2014");
12524
- const differ = new Set(vals.filter((v) => v !== "\u2014")).size > 1;
12525
- const cells = vals.map((v) => (v.length > width - 2 ? `${v.slice(0, width - 3)}\u2026` : v).padEnd(width));
12526
- lines.push(`${differ ? p.red(r.topic.padEnd(18)) : r.topic.padEnd(18)}${cells.join("")}${differ ? p.red(" \u2190 differs") : ""}`);
12527
- }
12528
- return `${lines.join("\n")}
12529
- `;
12530
- }
12531
- var BADGE_COLOR = { A: "brightgreen", B: "green", C: "yellow", D: "orange", F: "red" };
12532
- var BADGE_LINK = "https://threadctx.dev";
12533
- function badgeLinkFor(fullName) {
12534
- return fullName && /^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9_.-]{1,100}$/.test(fullName) ? `https://threadctx.dev/r/${fullName}` : BADGE_LINK;
12535
- }
12536
- function renderBadge(result, link = BADGE_LINK) {
12537
- const url = `https://img.shields.io/badge/agent%20context-${result.grade}%20%C2%B7%20${result.score}-${BADGE_COLOR[result.grade]}`;
12538
- const alt = `Agent context grade ${result.grade}`;
12539
- return { url, markdown: `[![${alt}](${url})](${link})`, html: `<a href="${link}"><img src="${url}" alt="${alt}"></a>` };
12540
- }
12541
-
12542
12364
  // ../rules/dist/benchmark.js
12543
12365
  var BENCHMARK = {
12544
12366
  "CTX-B001": {
@@ -14762,7 +14584,7 @@ var S002 = {
14762
14584
  report({
14763
14585
  path: first.artifact.path,
14764
14586
  line: 1,
14765
- message: hasAgents ? `${tools.length} tools have their own context files (${names}), and ${isolatedNames.join(" and ")} ${isolatedNames.length === 1 ? "does" : "do"} not read AGENTS.md. Their copies will drift.` : `${tools.length} tools have their own context files (${names}) with no shared source. Their copies will drift.`,
14587
+ message: hasAgents ? `${tools.length} tools have their own context files (${names}), and ${isolatedNames.join(" and ")} ${isolatedNames.length === 1 ? "does" : "do"} not read AGENTS.md. Their copies can drift apart.` : `${tools.length} tools have their own context files (${names}) with no shared source. Their copies can drift apart.`,
14766
14588
  evidence: isolated.map((t) => t.files.map((f) => f.artifact.path).join(", ")).join("; "),
14767
14589
  fingerprintKey: names,
14768
14590
  fix: hasAgents && isolated.some((t) => t.tool === "claude-code") && ctx.catalog.get("CLAUDE.md") ? { kind: "suggested", description: "Import AGENTS.md from CLAUDE.md so Claude Code reads the shared instructions.", edits: [{ path: "CLAUDE.md", startLine: 1, endLine: 0, replacement: "@AGENTS.md\n" }] } : void 0
@@ -14917,7 +14739,7 @@ function applySuppressions(findings, inline, config, now, diagnostics) {
14917
14739
  }
14918
14740
 
14919
14741
  // ../rules/dist/version.js
14920
- var ENGINE_VERSION = "0.2.1";
14742
+ var ENGINE_VERSION = "0.4.0";
14921
14743
  var REGISTRY_VERSION = "2026.10.1";
14922
14744
 
14923
14745
  // ../rules/dist/engine.js
@@ -15314,39 +15136,508 @@ function summarizeFleet(repos, meta2) {
15314
15136
  };
15315
15137
  }
15316
15138
 
15317
- // ../../node_modules/.pnpm/diff@9.0.0/node_modules/diff/libesm/diff/base.js
15318
- var Diff = class {
15319
- diff(oldStr, newStr, options = {}) {
15320
- let callback;
15321
- if (typeof options === "function") {
15322
- callback = options;
15323
- options = {};
15324
- } else if ("callback" in options) {
15325
- callback = options.callback;
15326
- }
15327
- const oldString = this.castInput(oldStr, options);
15328
- const newString = this.castInput(newStr, options);
15329
- const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
15330
- const newTokens = this.removeEmpty(this.tokenize(newString, options));
15331
- return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
15139
+ // ../rules/dist/compliance.js
15140
+ var FRAMEWORKS = ["SOC 2", "ISO/IEC 27001:2022", "ISO/IEC 42001:2023", "NIST AI RMF 1.0"];
15141
+ var CONTROLS = [
15142
+ {
15143
+ id: "TC-01",
15144
+ title: "AI coding agents and their tools are inventoried",
15145
+ objective: "The organisation knows which repositories give instructions to which AI coding agents, and which MCP servers those agents can call.",
15146
+ rules: [],
15147
+ refs: [
15148
+ { framework: "SOC 2", ref: "CC6.1", name: "Logical access: inventory of information assets" },
15149
+ { framework: "ISO/IEC 27001:2022", ref: "A.5.9", name: "Inventory of information and other associated assets" },
15150
+ { framework: "ISO/IEC 42001:2023", ref: "A.4.4", name: "Tooling resources" },
15151
+ { framework: "NIST AI RMF 1.0", ref: "GOVERN 1.6", name: "Mechanisms are in place to inventory AI systems" }
15152
+ ]
15153
+ },
15154
+ {
15155
+ id: "TC-02",
15156
+ title: "Secrets are kept out of agent instructions and tool configuration",
15157
+ objective: "No credential, token or key is written into a file that AI agents read or into an MCP server configuration.",
15158
+ rules: ["CTX-X005"],
15159
+ refs: [
15160
+ { framework: "SOC 2", ref: "CC6.1", name: "Logical access: protection of credentials" },
15161
+ { framework: "ISO/IEC 27001:2022", ref: "A.5.17", name: "Authentication information" },
15162
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.12", name: "Data leakage prevention" },
15163
+ { framework: "NIST AI RMF 1.0", ref: "MEASURE 2.7", name: "AI system security and resilience are evaluated" }
15164
+ ]
15165
+ },
15166
+ {
15167
+ id: "TC-03",
15168
+ title: "Agent instructions are free of hidden or injected content",
15169
+ objective: "Instruction files contain no invisible or bidirectional characters, encoded payloads, or instructions to download and run remote code.",
15170
+ rules: ["CTX-X001", "CTX-X002", "CTX-X003"],
15171
+ refs: [
15172
+ { framework: "SOC 2", ref: "CC6.8", name: "Prevent or detect unauthorised or malicious software" },
15173
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.7", name: "Protection against malware" },
15174
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.28", name: "Secure coding" },
15175
+ { framework: "NIST AI RMF 1.0", ref: "MEASURE 2.7", name: "AI system security and resilience are evaluated" }
15176
+ ]
15177
+ },
15178
+ {
15179
+ id: "TC-04",
15180
+ title: "Agents are not told to bypass quality and security checks",
15181
+ objective: "No instruction tells an agent to skip tests, disable linters or checks, or hide changes from review.",
15182
+ rules: ["CTX-X004"],
15183
+ refs: [
15184
+ { framework: "SOC 2", ref: "CC8.1", name: "Change management: changes are tested before implementation" },
15185
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.29", name: "Security testing in development and acceptance" },
15186
+ { framework: "ISO/IEC 42001:2023", ref: "A.6.2.4", name: "AI system verification and validation" }
15187
+ ]
15188
+ },
15189
+ {
15190
+ id: "TC-05",
15191
+ title: "Third-party agent tools are pinned and authenticated",
15192
+ objective: "MCP servers, skills and rule packs are pinned to a version or hash, and remote servers use TLS and authentication.",
15193
+ rules: ["CTX-X006", "CTX-X007", "CTX-X009"],
15194
+ refs: [
15195
+ { framework: "SOC 2", ref: "CC9.2", name: "Risks from vendors and business partners are assessed and managed" },
15196
+ { framework: "ISO/IEC 27001:2022", ref: "A.5.21", name: "Managing information security in the ICT supply chain" },
15197
+ { framework: "ISO/IEC 42001:2023", ref: "A.10.3", name: "Suppliers" },
15198
+ { framework: "NIST AI RMF 1.0", ref: "GOVERN 6.1", name: "Policies address risks from third-party entities" }
15199
+ ]
15200
+ },
15201
+ {
15202
+ id: "TC-06",
15203
+ title: "Agent instructions have owners and reviewed changes",
15204
+ objective: "Every instruction file is covered by CODEOWNERS, and generated files are changed only at their source.",
15205
+ rules: ["CTX-G001", "CTX-G002", "CTX-G003"],
15206
+ refs: [
15207
+ { framework: "SOC 2", ref: "CC8.1", name: "Change management: changes are authorised and approved" },
15208
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.32", name: "Change management" },
15209
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.4", name: "Access to source code" },
15210
+ { framework: "NIST AI RMF 1.0", ref: "GOVERN 2.1", name: "Roles and responsibilities are documented" }
15211
+ ]
15212
+ },
15213
+ {
15214
+ id: "TC-07",
15215
+ title: "Agent instructions are accurate and consistent",
15216
+ objective: "Instructions match the repository (paths, scripts, package manager, versions) and do not contradict each other across files and tools.",
15217
+ rules: ["CTX-S003", "CTX-S004", "CTX-D001", "CTX-D002", "CTX-D003", "CTX-D005", "CTX-C001", "CTX-C002", "CTX-C003"],
15218
+ refs: [
15219
+ { framework: "SOC 2", ref: "CC2.1", name: "Relevant, quality information supports internal control" },
15220
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.9", name: "Configuration management" },
15221
+ { framework: "ISO/IEC 42001:2023", ref: "A.6.2.7", name: "AI system technical documentation" },
15222
+ { framework: "NIST AI RMF 1.0", ref: "MAP 2.2", name: "Knowledge limits and how outputs are used are documented" }
15223
+ ]
15224
+ },
15225
+ {
15226
+ id: "TC-08",
15227
+ title: "Agent context is monitored over time",
15228
+ objective: "The audit is repeated and compared with the previous run, so regressions are found and followed up.",
15229
+ rules: [],
15230
+ refs: [
15231
+ { framework: "SOC 2", ref: "CC4.1", name: "Ongoing and separate evaluations" },
15232
+ { framework: "SOC 2", ref: "CC7.1", name: "Detection of configuration changes and vulnerabilities" },
15233
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.16", name: "Monitoring activities" },
15234
+ { framework: "NIST AI RMF 1.0", ref: "MANAGE 4.1", name: "Post-deployment monitoring plans are implemented" }
15235
+ ]
15332
15236
  }
15333
- diffWithOptionsObj(oldTokens, newTokens, options, callback) {
15334
- var _a;
15335
- const done = (value) => {
15336
- value = this.postProcess(value, options);
15337
- if (callback) {
15338
- setTimeout(function() {
15339
- callback(value);
15340
- }, 0);
15341
- return void 0;
15342
- } else {
15343
- return value;
15344
- }
15237
+ ];
15238
+ var EVIDENCE_DISCLAIMER = "threadctx produces evidence about AI coding agent configuration. It is not an attestation, certification or audit opinion. Framework references show where the evidence is commonly relevant; your auditor decides whether it is sufficient for a control.";
15239
+ var plural2 = (n2, one, many = `${one}s`) => `${n2} ${n2 === 1 ? one : many}`;
15240
+ function evidencePack(summary, repos) {
15241
+ const withContext = repos.filter((r) => r.result && r.result.artifacts.length > 0).sort((a, b) => a.fullName < b.fullName ? -1 : 1);
15242
+ const tested = withContext.length;
15243
+ const inventory = withContext.map((r) => {
15244
+ const res = r.result;
15245
+ return {
15246
+ repo: r.fullName,
15247
+ url: r.url,
15248
+ private: Boolean(r.private),
15249
+ agents: res.tools.filter((t) => t.layers > 0).map((t) => t.id),
15250
+ files: res.artifacts.map((a) => ({ path: a.path, tool: a.tool, kind: a.kind })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0),
15251
+ mcpServers: res.mcpServers.map((m) => ({ client: m.client, name: m.name, transport: m.transport, source: m.source })),
15252
+ grade: res.grade,
15253
+ score: res.score
15345
15254
  };
15346
- const newLen = newTokens.length, oldLen = oldTokens.length;
15347
- let editLength = 1;
15348
- let maxEditLength = newLen + oldLen;
15349
- if (options.maxEditLength != null) {
15255
+ });
15256
+ const controls = CONTROLS.map((c) => {
15257
+ if (c.id === "TC-01") {
15258
+ const files = inventory.reduce((n2, r) => n2 + r.files.length, 0);
15259
+ const servers = inventory.reduce((n2, r) => n2 + r.mcpServers.length, 0);
15260
+ return {
15261
+ ...base(c),
15262
+ status: "evidenced",
15263
+ tested,
15264
+ statement: `${plural2(summary.repos.scanned, "repository", "repositories")} scanned; ${plural2(files, "agent instruction or configuration file")} and ${plural2(servers, "MCP server")} inventoried across ${plural2(tested, "repository", "repositories")} (see the inventory).`
15265
+ };
15266
+ }
15267
+ if (c.id === "TC-08") {
15268
+ const t = summary.trend;
15269
+ return t ? { ...base(c), status: "evidenced", tested, statement: `Compared with the audit of ${t.since.slice(0, 10)}: fleet score ${t.before.score} \u2192 ${t.after.score}, blockers ${t.before.blockers} \u2192 ${t.after.blockers}, ${t.regressed.length} repositories regressed.` } : { ...base(c), status: "not-evidenced", tested, statement: "This is the first audit in this folder, so there is no earlier run to compare with. Run the audit on a schedule (Team plan) to evidence ongoing monitoring." };
15270
+ }
15271
+ const ids = new Set(c.rules);
15272
+ let findings = 0;
15273
+ let blockers = 0;
15274
+ const hit = /* @__PURE__ */ new Set();
15275
+ for (const r of withContext) {
15276
+ for (const f of r.result.findings) {
15277
+ if (f.suppressed || !ids.has(f.ruleId))
15278
+ continue;
15279
+ findings++;
15280
+ if (f.severity === "blocker")
15281
+ blockers++;
15282
+ hit.add(r.fullName);
15283
+ }
15284
+ }
15285
+ const status = tested === 0 ? "not-evidenced" : blockers > 0 ? "gap" : findings > 0 ? "attention" : "met";
15286
+ const statement = tested === 0 ? "No repository has agent context files, so there was nothing to test." : findings === 0 ? `Tested on ${plural2(tested, "repository", "repositories")} with agent context; no open findings.` : `Tested on ${plural2(tested, "repository", "repositories")}; ${plural2(findings, "open finding")}${blockers ? ` (${blockers} blocking)` : ""} in ${plural2(hit.size, "repository", "repositories")}.`;
15287
+ return { ...base(c), status, findings, blockers, repos: [...hit].sort(), tested, statement };
15288
+ });
15289
+ const agents = {};
15290
+ for (const r of inventory)
15291
+ for (const a of r.agents)
15292
+ agents[a] = (agents[a] ?? 0) + 1;
15293
+ return {
15294
+ schema: "threadctx.evidence/v1",
15295
+ org: summary.org,
15296
+ generatedAt: summary.generatedAt,
15297
+ engine: summary.engine,
15298
+ scope: { repositoriesListed: summary.repos.listed, repositoriesScanned: summary.repos.scanned, withAgentContext: summary.repos.withContext, withoutAgentContext: summary.repos.withoutContext, unreadable: summary.repos.failed },
15299
+ totals: { agentFiles: inventory.reduce((n2, r) => n2 + r.files.length, 0), mcpServers: inventory.reduce((n2, r) => n2 + r.mcpServers.length, 0), agents },
15300
+ controls,
15301
+ inventory,
15302
+ disclaimer: EVIDENCE_DISCLAIMER
15303
+ };
15304
+ function base(c) {
15305
+ return { id: c.id, title: c.title, objective: c.objective, refs: c.refs, findings: 0, blockers: 0, repos: [] };
15306
+ }
15307
+ }
15308
+ function controlHeadline(pack) {
15309
+ const c = pack.controls;
15310
+ return {
15311
+ total: c.length,
15312
+ met: c.filter((x) => x.status === "met" || x.status === "evidenced").length,
15313
+ attention: c.filter((x) => x.status === "attention" || x.status === "not-evidenced").length,
15314
+ gap: c.filter((x) => x.status === "gap").length
15315
+ };
15316
+ }
15317
+
15318
+ // ../report/dist/evidence.js
15319
+ var esc2 = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
15320
+ var TOOL_LABEL2 = { "agents-md": "AGENTS.md", "claude-code": "Claude Code", cursor: "Cursor", copilot: "GitHub Copilot", gemini: "Gemini CLI" };
15321
+ var STATUS_LABEL = { met: "Met", evidenced: "Evidenced", attention: "Needs attention", gap: "Gap", "not-evidenced": "Not evidenced" };
15322
+ var csvCell2 = (v) => {
15323
+ let s = String(v);
15324
+ if (/^[=+\-@\t\r]/.test(s))
15325
+ s = `'${s}`;
15326
+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
15327
+ };
15328
+ var csv = (rows) => `${rows.map((r) => r.map(csvCell2).join(",")).join("\n")}
15329
+ `;
15330
+ function renderInventoryCsv(p) {
15331
+ const rows = [["repository", "visibility", "item_type", "path_or_name", "agent_or_client", "kind_or_transport", "source", "repository_grade"]];
15332
+ for (const r of p.inventory) {
15333
+ const vis = r.private ? "private" : "public";
15334
+ for (const f of r.files)
15335
+ rows.push([r.repo, vis, "instruction_file", f.path, TOOL_LABEL2[f.tool] ?? f.tool, f.kind, "", r.grade]);
15336
+ for (const m of r.mcpServers)
15337
+ rows.push([r.repo, vis, "mcp_server", m.name, m.client, m.transport, m.source, r.grade]);
15338
+ }
15339
+ return csv(rows);
15340
+ }
15341
+ function renderControlsCsv(p) {
15342
+ const rows = [["control_id", "control", "status", "framework", "reference", "reference_name", "open_findings", "blocking_findings", "repositories_affected", "repositories_tested", "statement", "generated_at"]];
15343
+ for (const c of p.controls) {
15344
+ for (const r of c.refs)
15345
+ rows.push([c.id, c.title, STATUS_LABEL[c.status], r.framework, r.ref, r.name, String(c.findings), String(c.blockers), String(c.repos.length), String(c.tested), c.statement, p.generatedAt]);
15346
+ }
15347
+ return csv(rows);
15348
+ }
15349
+ var CSS2 = `
15350
+ :root{--fg:#111418;--muted:#5b6370;--line:#e2e5ea;--card:#f6f7f9;--accent:#1f4fd1;--met:#1a7f37;--att:#9a6700;--gap:#c62828;--na:#5b6370}
15351
+ *{box-sizing:border-box}body{margin:0;background:#fff;color:var(--fg);font:14px/1.55 -apple-system,"Segoe UI",Roboto,system-ui,sans-serif}
15352
+ main{max-width:900px;margin:0 auto;padding:40px 28px 64px}
15353
+ h1{font-size:30px;letter-spacing:-.02em;margin:0 0 6px}h2{font-size:19px;margin:36px 0 10px;padding-top:12px;border-top:1px solid var(--line)}h3{font-size:15px;margin:18px 0 4px}
15354
+ .muted{color:var(--muted)}.small{font-size:12.5px}code{font:12.5px ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--card);padding:1px 5px;border-radius:4px;word-break:break-all}
15355
+ .cover{border:1px solid var(--line);border-radius:14px;padding:28px;margin:8px 0 24px;background:linear-gradient(180deg,#f8faff,#fff)}
15356
+ .eyebrow{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--accent);font-weight:700}
15357
+ .meta{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:10px 24px;margin-top:18px}.meta div b{display:block;font-size:12px;color:var(--muted);font-weight:600}
15358
+ .kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px;margin:16px 0}.kpi{border:1px solid var(--line);border-radius:10px;padding:12px}.kpi b{display:block;font-size:24px;letter-spacing:-.01em}
15359
+ table{width:100%;border-collapse:collapse;margin:8px 0 14px;font-size:13px}th,td{text-align:left;padding:7px 9px;border-bottom:1px solid var(--line);vertical-align:top}th{color:var(--muted);font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.05em}
15360
+ .st{display:inline-block;border-radius:999px;padding:1px 9px;font-size:12px;font-weight:700;white-space:nowrap}
15361
+ .st-met,.st-evidenced{background:#e6f4ea;color:var(--met)}.st-attention,.st-not-evidenced{background:#fff4d6;color:var(--att)}.st-gap{background:#fde8e8;color:var(--gap)}
15362
+ .control{border:1px solid var(--line);border-radius:12px;padding:14px 16px;margin:12px 0;break-inside:avoid}.control h3{margin:0 0 4px;display:flex;gap:10px;align-items:baseline;flex-wrap:wrap}
15363
+ .refs{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}.ref{font-size:11.5px;border:1px solid var(--line);border-radius:6px;padding:1px 7px;color:var(--muted)}
15364
+ .note{border-left:3px solid var(--accent);background:var(--card);padding:10px 14px;border-radius:0 8px 8px 0;margin:14px 0;font-size:13px}
15365
+ .sign{display:grid;grid-template-columns:1fr 1fr;gap:28px;margin-top:20px}.sign div{border-top:1px solid var(--fg);padding-top:6px;font-size:12px;color:var(--muted)}
15366
+ .toolbar{position:sticky;top:0;background:#fff;border-bottom:1px solid var(--line);padding:10px 28px;display:flex;gap:10px;justify-content:flex-end}.toolbar button{font:600 13px system-ui;border:1px solid var(--line);background:#fff;border-radius:8px;padding:6px 12px;cursor:pointer}
15367
+ footer{margin-top:40px;color:var(--muted);font-size:12px;border-top:1px solid var(--line);padding-top:12px}
15368
+ @media print{.toolbar{display:none}main{padding:0;max-width:none}h2{break-after:avoid}tr,.control{break-inside:avoid}.pb{break-before:page}@page{margin:16mm 14mm}}
15369
+ `;
15370
+ function renderEvidenceHtml(p, opts = {}) {
15371
+ const date = p.generatedAt.slice(0, 10);
15372
+ const st = (s) => `<span class="st st-${s}">${STATUS_LABEL[s]}</span>`;
15373
+ const count = (s) => p.controls.filter((c) => s.includes(c.status)).length;
15374
+ const agents = Object.entries(p.totals.agents).sort((a, b) => b[1] - a[1]).map(([id, n2]) => `${esc2(TOOL_LABEL2[id] ?? id)} (${n2})`).join(", ") || "none";
15375
+ const out = [];
15376
+ out.push(`<div class="cover"><div class="eyebrow">AI coding agent governance \xB7 evidence pack</div>
15377
+ <h1>${esc2(p.org)}</h1><div class="muted">Configuration of AI coding agents across the organisation's GitHub repositories</div>
15378
+ <div class="meta"><div><b>Generated</b>${esc2(p.generatedAt.replace("T", " ").slice(0, 16))} UTC</div><div><b>Tool</b>threadctx ${esc2(p.engine.version)} \xB7 rules ${esc2(p.engine.registry)}</div>
15379
+ <div><b>Scope</b>${p.scope.repositoriesScanned} of ${p.scope.repositoriesListed} repositories</div><div><b>Frameworks referenced</b>${FRAMEWORKS.map(esc2).join(", ")}</div></div></div>`);
15380
+ out.push(`<h2>Summary</h2><div class="kpis">
15381
+ <div class="kpi"><b>${count(["met", "evidenced"])}/${p.controls.length}</b><span class="muted small">controls met or evidenced</span></div>
15382
+ <div class="kpi"><b>${count(["attention", "not-evidenced"])}</b><span class="muted small">need attention</span></div>
15383
+ <div class="kpi"><b>${count(["gap"])}</b><span class="muted small">gaps (blocking findings)</span></div>
15384
+ <div class="kpi"><b>${p.totals.agentFiles}</b><span class="muted small">agent files inventoried</span></div>
15385
+ <div class="kpi"><b>${p.totals.mcpServers}</b><span class="muted small">MCP servers inventoried</span></div></div>
15386
+ <p>${p.scope.withAgentContext} repositories give instructions to AI coding agents (${agents}); ${p.scope.withoutAgentContext} have none${p.scope.unreadable ? `; ${p.scope.unreadable} could not be read and are outside the tested population` : ""}.</p>
15387
+ <table><tr><th>Control</th><th>Status</th><th>Result</th></tr>${p.controls.map((c) => `<tr><td><b>${esc2(c.id)}</b> ${esc2(c.title)}</td><td>${st(c.status)}</td><td class="small">${esc2(c.statement)}</td></tr>`).join("")}</table>`);
15388
+ out.push(`<h2>Method</h2><p class="small">The repositories of <b>${esc2(p.org)}</b> were listed through the GitHub API with the operator's own token. For each repository, the files that AI coding agents read (AGENTS.md, CLAUDE.md, Cursor rules, GitHub Copilot instructions, Gemini files, MCP configuration) and the manifests they refer to were fetched and analysed on the operator's machine. No repository content was sent to threadctx or any third party. Each control is tested against the deterministic rules listed under it; a rule's false-positive rate is published at threadctx.dev/rules. Findings that the repository owners suppressed in configuration are excluded and remain visible in audit.json.</p>
15389
+ <p class="small"><b>Status meanings.</b> <i>Met</i>: tested, no open findings. <i>Evidenced</i>: the audit itself provides the evidence. <i>Needs attention</i>: non-blocking findings, or not yet evidenced. <i>Gap</i>: at least one blocking finding.</p>`);
15390
+ out.push(`<h2 class="pb">Controls</h2>${p.controls.map((c) => `<div class="control"><h3>${esc2(c.id)} ${esc2(c.title)} ${st(c.status)}</h3>
15391
+ <div class="small muted">${esc2(c.objective)}</div><p class="small" style="margin:8px 0 0">${esc2(c.statement)}</p>
15392
+ ${c.repos.length ? `<p class="small" style="margin:6px 0 0"><b>Repositories with findings:</b> ${c.repos.slice(0, 25).map(esc2).join(", ")}${c.repos.length > 25 ? ` and ${c.repos.length - 25} more (see controls.csv)` : ""}</p>` : ""}
15393
+ <div class="refs">${c.refs.map((r) => `<span class="ref" title="${esc2(r.name)}">${esc2(r.framework)} ${esc2(r.ref)}</span>`).join("")}</div></div>`).join("")}`);
15394
+ out.push(`<h2 class="pb">Framework cross-reference</h2><table><tr><th>Framework</th><th>Reference</th><th>Name</th><th>Control</th><th>Status</th></tr>${FRAMEWORKS.flatMap((fw) => p.controls.flatMap((c) => c.refs.filter((r) => r.framework === fw).map((r) => `<tr><td>${esc2(fw)}</td><td><b>${esc2(r.ref)}</b></td><td class="small">${esc2(r.name)}</td><td>${esc2(c.id)}</td><td>${st(c.status)}</td></tr>`))).join("")}</table>`);
15395
+ out.push(`<h2 class="pb">Inventory</h2><p class="small muted">Every agent instruction or configuration file and MCP server found. The same data is in inventory.csv.</p>
15396
+ <table><tr><th>Repository</th><th>Agents</th><th>Files</th><th>MCP servers</th></tr>${p.inventory.map((r) => `<tr><td>${esc2(r.repo)}${r.private ? ' <span class="muted small">private</span>' : ""}</td><td class="small">${esc2(r.agents.map((a) => TOOL_LABEL2[a] ?? a).join(", "))}</td><td class="small">${r.files.map((f) => `<code>${esc2(f.path)}</code>`).join(" ")}</td><td class="small">${r.mcpServers.length ? r.mcpServers.map((m) => `${esc2(m.name)} <span class="muted">(${esc2(m.transport)})</span>`).join(", ") : "\u2014"}</td></tr>`).join("")}</table>`);
15397
+ out.push(`<h2>Review and sign-off</h2><p class="small muted">For the control owner's records.</p><div class="sign"><div>Reviewed by (name, role)</div><div>Date</div><div>Follow-up ticket(s)</div><div>Next review due</div></div>`);
15398
+ out.push(`<div class="note"><b>Important.</b> ${esc2(p.disclaimer)}</div>
15399
+ <footer>Integrity: ${opts.auditSha256 ? `SHA-256 of the accompanying audit.json is <code>${esc2(opts.auditSha256)}</code>. Recompute it with <code>shasum -a 256 audit.json</code> to confirm this pack matches its raw data.` : "see audit.json for the raw data."} Generated locally by threadctx ${esc2(p.engine.version)} on ${esc2(date)}. Methodology: https://threadctx.dev/methodology \xB7 Controls: https://threadctx.dev/security</footer>`);
15400
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>AI agent governance evidence: ${esc2(p.org)} (${esc2(date)})</title><style>${CSS2}</style></head><body><div class="toolbar"><button onclick="window.print()">Save as PDF</button></div><main>${out.join("\n")}</main></body></html>
15401
+ `;
15402
+ }
15403
+
15404
+ // ../report/dist/index.js
15405
+ var RULE_DOCS = "https://threadctx.dev/rules";
15406
+ function renderJson(result) {
15407
+ return `${JSON.stringify(result, null, 2)}
15408
+ `;
15409
+ }
15410
+ var SARIF_LEVEL = { blocker: "error", warning: "warning", info: "note" };
15411
+ var SECURITY_SEVERITY = { blocker: "9.0", warning: "5.0", info: "2.0" };
15412
+ function renderSarif(result) {
15413
+ const rules = [...result.rules].sort((a, b) => a.id < b.id ? -1 : 1);
15414
+ const index = new Map(rules.map((r, i) => [r.id, i]));
15415
+ const sarif = {
15416
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
15417
+ version: "2.1.0",
15418
+ runs: [
15419
+ {
15420
+ tool: {
15421
+ driver: {
15422
+ name: "threadctx",
15423
+ semanticVersion: result.engine.version,
15424
+ informationUri: "https://threadctx.dev",
15425
+ rules: rules.map((r) => sarifRule(r))
15426
+ }
15427
+ },
15428
+ automationDetails: { id: "threadctx/agent-context/" },
15429
+ results: result.findings.map((f) => sarifResult(f, index.get(f.ruleId))),
15430
+ properties: { grade: result.grade, score: result.score, registry: result.engine.registry }
15431
+ }
15432
+ ]
15433
+ };
15434
+ return `${JSON.stringify(sarif, null, 2)}
15435
+ `;
15436
+ }
15437
+ function sarifRule(r) {
15438
+ const tags = [.../* @__PURE__ */ new Set(["agent-context", r.family, r.determinism])];
15439
+ return {
15440
+ id: r.id,
15441
+ name: r.id.replace(/[^A-Za-z0-9]/g, ""),
15442
+ shortDescription: { text: r.title },
15443
+ fullDescription: { text: r.rationale },
15444
+ helpUri: r.id.startsWith("CTX-") ? `${RULE_DOCS}/${r.id}` : void 0,
15445
+ help: { text: `${r.remediation}
15446
+
15447
+ Source: ${r.citation}`, markdown: `${r.remediation}
15448
+
15449
+ Source: ${r.citation}` },
15450
+ defaultConfiguration: { level: SARIF_LEVEL[r.severity] },
15451
+ properties: { tags, precision: r.determinism === "deterministic" ? "high" : "medium", ...r.family === "security" ? { "security-severity": SECURITY_SEVERITY[r.severity] } : {} }
15452
+ };
15453
+ }
15454
+ function sarifResult(f, ruleIndex) {
15455
+ const location = (path, line, endLine) => ({
15456
+ physicalLocation: {
15457
+ // Repository-level findings point at the root so code scanning still accepts them.
15458
+ artifactLocation: { uri: path || ".", uriBaseId: "%SRCROOT%" },
15459
+ ...line ? { region: { startLine: line, ...endLine && endLine > line ? { endLine } : {} } } : {}
15460
+ }
15461
+ });
15462
+ return {
15463
+ ruleId: f.ruleId,
15464
+ ...ruleIndex !== void 0 ? { ruleIndex } : {},
15465
+ level: SARIF_LEVEL[f.severity],
15466
+ message: { text: f.evidence ? `${f.message}
15467
+
15468
+ Evidence: ${f.evidence}` : f.message },
15469
+ locations: [location(f.path, f.line, f.endLine)],
15470
+ ...f.related?.length ? { relatedLocations: f.related.map((r, i) => ({ id: i + 1, ...location(r.path, r.line), message: { text: r.message ?? "related" } })) } : {},
15471
+ partialFingerprints: { "threadctx/v1": f.fingerprint },
15472
+ ...f.suppressed ? { suppressions: [{ kind: f.suppressed.source === "inline" ? "inSource" : "external", justification: f.suppressed.reason }] } : {}
15473
+ };
15474
+ }
15475
+ function painter(color) {
15476
+ const wrap = (code2) => (s) => color ? `\x1B[${code2}m${s}\x1B[0m` : s;
15477
+ return { red: wrap("31"), yellow: wrap("33"), blue: wrap("34"), green: wrap("32"), dim: wrap("2"), bold: wrap("1"), cyan: wrap("36") };
15478
+ }
15479
+ var GRADE_COLOR = { A: "green", B: "green", C: "yellow", D: "yellow", F: "red" };
15480
+ function renderText(result, opts) {
15481
+ const p = painter(opts.color);
15482
+ const out = [];
15483
+ const open = result.findings.filter((f) => !f.suppressed);
15484
+ const shown = opts.verbose ? open : open.filter((f) => f.severity !== "info");
15485
+ const sev2 = { blocker: p.red("blocker"), warning: p.yellow("warning"), info: p.blue("info ") };
15486
+ let lastPath;
15487
+ for (const f of shown) {
15488
+ if (f.path !== lastPath) {
15489
+ out.push("", p.bold(f.path || "(repository)"));
15490
+ lastPath = f.path;
15491
+ }
15492
+ const loc = f.line ? p.dim(`${String(f.line).padStart(4)}:`) : p.dim(" ");
15493
+ const fix = f.fix?.kind === "safe" ? p.green(" [fixable]") : "";
15494
+ out.push(`${loc} ${sev2[f.severity]} ${f.message} ${p.dim(f.ruleId)}${fix}`);
15495
+ if (f.evidence)
15496
+ out.push(` ${p.dim(`> ${f.evidence}`)}`);
15497
+ }
15498
+ const hiddenInfo = open.length - shown.length;
15499
+ const { blocker, warning, info, suppressed } = result.counts;
15500
+ out.push("");
15501
+ out.push(`${p[GRADE_COLOR[result.grade]](p.bold(`Grade ${result.grade}`))} ${p.dim(`(${result.score}/100)`)} ${blocker} blocker${blocker === 1 ? "" : "s"}, ${warning} warning${warning === 1 ? "" : "s"}, ${info} info` + (suppressed ? p.dim(`, ${suppressed} suppressed`) : "") + (hiddenInfo ? p.dim(` (${hiddenInfo} info hidden; --verbose shows them)`) : ""));
15502
+ const fixable = open.filter((f) => f.fix?.kind === "safe").length;
15503
+ if (fixable)
15504
+ out.push(p.dim(`${fixable} finding${fixable === 1 ? "" : "s"} can be fixed automatically: threadctx fix`));
15505
+ const tools = result.tools.filter((t) => t.layers > 0);
15506
+ if (tools.length) {
15507
+ out.push(p.dim(`Always-loaded context (estimated tokens): ${tools.map((t) => `${t.label.split(" (")[0]} \u2248${t.alwaysTokenEstimate.toLocaleString("en-US")}`).join(" \xB7 ")}`));
15508
+ }
15509
+ for (const d of result.diagnostics) {
15510
+ const tag = d.level === "error" ? p.red("error") : d.level === "warning" ? p.yellow("note") : p.dim("note");
15511
+ out.push(`${tag} ${d.path ? `${d.path}${d.line ? `:${d.line}` : ""}: ` : ""}${d.message}`);
15512
+ }
15513
+ return `${out.join("\n").replace(/^\n/, "")}
15514
+ `;
15515
+ }
15516
+ var SEV_ICON = { blocker: "\u{1F534}", warning: "\u{1F7E1}", info: "\u{1F535}" };
15517
+ function mdEscape(s) {
15518
+ return s.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
15519
+ }
15520
+ function renderMarkdown(result, opts = {}) {
15521
+ const out = [];
15522
+ const open = result.findings.filter((f) => !f.suppressed);
15523
+ const delta = opts.baseline ? result.score === opts.baseline.score ? " (unchanged)" : ` (${opts.baseline.grade} \u2192 ${result.grade}, ${result.score - opts.baseline.score > 0 ? "+" : ""}${result.score - opts.baseline.score})` : "";
15524
+ out.push(`### Agent context: grade **${result.grade}** \xB7 ${result.score}/100${delta}`);
15525
+ out.push("");
15526
+ out.push(`${result.counts.blocker} blocker${result.counts.blocker === 1 ? "" : "s"} \xB7 ${result.counts.warning} warning${result.counts.warning === 1 ? "" : "s"} \xB7 ${result.counts.info} info${result.counts.suppressed ? ` \xB7 ${result.counts.suppressed} suppressed` : ""}`);
15527
+ const list = opts.newFingerprints ? open.filter((f) => opts.newFingerprints.has(f.fingerprint)) : open;
15528
+ if (opts.newFingerprints)
15529
+ out.push("", `**${list.length} new** in this change${open.length > list.length ? ` (${open.length - list.length} existing not shown)` : ""}.`);
15530
+ const max = opts.maxFindings ?? 50;
15531
+ if (list.length) {
15532
+ out.push("", "| | Rule | Location | Finding |", "|---|---|---|---|");
15533
+ for (const f of list.slice(0, max)) {
15534
+ const rule = f.ruleId.startsWith("CTX-") ? `[${f.ruleId}](${RULE_DOCS}/${f.ruleId})` : f.ruleId;
15535
+ out.push(`| ${SEV_ICON[f.severity]} | ${rule} | \`${mdEscape(f.path || ".")}${f.line ? `:${f.line}` : ""}\` | ${mdEscape(f.message)} |`);
15536
+ }
15537
+ if (list.length > max)
15538
+ out.push("", `\u2026and ${list.length - max} more. Run \`npx threadctx scan\` locally for the full list.`);
15539
+ }
15540
+ const tools = result.tools.filter((t) => t.layers > 0);
15541
+ if (tools.length) {
15542
+ out.push("", "<details><summary>What each agent loads at the repository root (estimated tokens)</summary>", "");
15543
+ for (const t of tools)
15544
+ out.push(`- ${t.label}: \u2248${t.alwaysTokenEstimate.toLocaleString("en-US")} tokens across ${t.layers} file${t.layers === 1 ? "" : "s"}`);
15545
+ out.push("", "</details>");
15546
+ }
15547
+ if (opts.orgAuditOwner !== void 0) {
15548
+ const owner = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/.test(opts.orgAuditOwner) ? opts.orgAuditOwner : "<your-org>";
15549
+ out.push("", `See every repository in your organisation: \`npx threadctx audit --org ${owner}\` (free summary).`);
15550
+ }
15551
+ out.push("", `<sub>[threadctx](https://threadctx.dev) ${result.engine.version}${opts.footerUrl ? ` \xB7 [history and badge](${opts.footerUrl})` : ""} \xB7 [how grades work](https://threadctx.dev/methodology)</sub>`);
15552
+ return `${out.join("\n")}
15553
+ `;
15554
+ }
15555
+ var LOAD_LABEL = { always: "always", "on-demand": "on demand", conditional: "matches", "agent-decides": "agent decides" };
15556
+ function renderEffective(contexts, opts) {
15557
+ const p = painter(opts.color);
15558
+ const out = [];
15559
+ for (const { label: label2, ctx } of contexts) {
15560
+ out.push(p.bold(`${label2}`) + p.dim(` ${ctx.targetPath} \u2248${ctx.tokenEstimate.toLocaleString("en-US")} tokens (estimate)`));
15561
+ if (!ctx.layers.length)
15562
+ out.push(p.dim(" (loads nothing from this repository)"));
15563
+ for (const l of ctx.layers) {
15564
+ out.push(` ${String(l.precedence).padStart(2)}. ${l.path.padEnd(44)} ${p.cyan(LOAD_LABEL[l.loading].padEnd(13))} ${p.dim(`\u2248${l.tokenEstimate}`.padStart(6))} ${p.dim(l.reason)}`);
15565
+ }
15566
+ for (const n2 of ctx.notes)
15567
+ out.push(p.dim(` note: ${n2}`));
15568
+ out.push("");
15569
+ }
15570
+ return out.join("\n");
15571
+ }
15572
+ function renderFactTable(rows, tools, opts) {
15573
+ const p = painter(opts.color);
15574
+ if (!rows.length)
15575
+ return p.dim("No comparable facts (commands, package manager, versions) found.\n");
15576
+ const width = 26;
15577
+ const head = `${"".padEnd(18)}${tools.map((t) => t.padEnd(width)).join("")}`;
15578
+ const lines = [p.bold(head)];
15579
+ for (const r of rows) {
15580
+ const vals = tools.map((t) => r.values[t]?.length ? r.values[t].join(", ") : "\u2014");
15581
+ const differ = new Set(vals.filter((v) => v !== "\u2014")).size > 1;
15582
+ const cells = vals.map((v) => (v.length > width - 2 ? `${v.slice(0, width - 3)}\u2026` : v).padEnd(width));
15583
+ lines.push(`${differ ? p.red(r.topic.padEnd(18)) : r.topic.padEnd(18)}${cells.join("")}${differ ? p.red(" \u2190 differs") : ""}`);
15584
+ }
15585
+ return `${lines.join("\n")}
15586
+ `;
15587
+ }
15588
+ var BADGE_COLOR = { A: "brightgreen", B: "green", C: "yellow", D: "orange", F: "red" };
15589
+ var BADGE_LINK = "https://threadctx.dev";
15590
+ function badgeLinkFor(fullName) {
15591
+ return fullName && /^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9_.-]{1,100}$/.test(fullName) ? `https://threadctx.dev/r/${fullName}` : BADGE_LINK;
15592
+ }
15593
+ function renderBadge(result, link = BADGE_LINK) {
15594
+ const url = `https://img.shields.io/badge/agent%20context-${result.grade}%20%C2%B7%20${result.score}-${BADGE_COLOR[result.grade]}`;
15595
+ const alt = `Agent context grade ${result.grade}`;
15596
+ return { url, markdown: `[![${alt}](${url})](${link})`, html: `<a href="${link}"><img src="${url}" alt="${alt}"></a>` };
15597
+ }
15598
+ function renderLiveBadge(fullName) {
15599
+ const link = badgeLinkFor(fullName);
15600
+ const url = `https://img.shields.io/endpoint?url=${encodeURIComponent(`https://threadctx.dev/badge/${fullName}`)}`;
15601
+ const alt = "Agent context grade";
15602
+ return { url, markdown: `[![${alt}](${url})](${link})`, html: `<a href="${link}"><img src="${url}" alt="${alt}"></a>` };
15603
+ }
15604
+
15605
+ // src/cli.ts
15606
+ import { execFileSync as execFileSync5 } from "node:child_process";
15607
+
15608
+ // ../../node_modules/.pnpm/diff@9.0.0/node_modules/diff/libesm/diff/base.js
15609
+ var Diff = class {
15610
+ diff(oldStr, newStr, options = {}) {
15611
+ let callback;
15612
+ if (typeof options === "function") {
15613
+ callback = options;
15614
+ options = {};
15615
+ } else if ("callback" in options) {
15616
+ callback = options.callback;
15617
+ }
15618
+ const oldString = this.castInput(oldStr, options);
15619
+ const newString = this.castInput(newStr, options);
15620
+ const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
15621
+ const newTokens = this.removeEmpty(this.tokenize(newString, options));
15622
+ return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
15623
+ }
15624
+ diffWithOptionsObj(oldTokens, newTokens, options, callback) {
15625
+ var _a;
15626
+ const done = (value) => {
15627
+ value = this.postProcess(value, options);
15628
+ if (callback) {
15629
+ setTimeout(function() {
15630
+ callback(value);
15631
+ }, 0);
15632
+ return void 0;
15633
+ } else {
15634
+ return value;
15635
+ }
15636
+ };
15637
+ const newLen = newTokens.length, oldLen = oldTokens.length;
15638
+ let editLength = 1;
15639
+ let maxEditLength = newLen + oldLen;
15640
+ if (options.maxEditLength != null) {
15350
15641
  maxEditLength = Math.min(maxEditLength, options.maxEditLength);
15351
15642
  }
15352
15643
  const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity;
@@ -15872,11 +16163,116 @@ function planFixes(fs, findings, kinds = ["safe"]) {
15872
16163
  return { files, applied: [...applied], skipped, patch };
15873
16164
  }
15874
16165
 
15875
- // src/git.ts
16166
+ // src/init.ts
16167
+ var ACTION_PIN = { sha: "380c9b3cf45a7fd3dd086cdd13dd3c8c075ff811", tag: "v1.3.0" };
16168
+ var CHECKOUT_PIN = { sha: "3d3c42e5aac5ba805825da76410c181273ba90b1", tag: "v7.0.1" };
16169
+ var WORKFLOW_PATH = ".github/workflows/agent-context.yml";
16170
+ function workflowYaml() {
16171
+ return `# Grades what AI coding agents are told (AGENTS.md, CLAUDE.md, Cursor, Copilot, Gemini, MCP).
16172
+ # Only problems a pull request introduces can fail it. https://threadctx.dev
16173
+ name: Agent context
16174
+ on:
16175
+ pull_request:
16176
+ push:
16177
+ branches: [main, master]
16178
+ permissions:
16179
+ contents: read
16180
+ pull-requests: write
16181
+ security-events: write
16182
+ jobs:
16183
+ agent-context:
16184
+ runs-on: ubuntu-latest
16185
+ steps:
16186
+ - uses: actions/checkout@${CHECKOUT_PIN.sha} # ${CHECKOUT_PIN.tag}
16187
+ - uses: threadctx-dev/action@${ACTION_PIN.sha} # ${ACTION_PIN.tag}
16188
+ `;
16189
+ }
16190
+ var BADGE_LINE = /\[!\[agent context[^\]]*\]\([^)]*\)\]\([^)]*\)/i;
16191
+ function withBadge(readme, markdown) {
16192
+ if (BADGE_LINE.test(readme) || readme.includes("img.shields.io/badge/agent%20context-") || readme.includes("threadctx.dev%2Fbadge%2F")) return readme;
16193
+ const lines = readme.split("\n");
16194
+ const h1 = lines.findIndex((l) => /^#\s/.test(l));
16195
+ if (h1 === -1) return `${markdown}
16196
+
16197
+ ${readme}`;
16198
+ const next = lines[h1 + 1];
16199
+ lines.splice(h1 + 1, 0, "", markdown, ...next === void 0 || next === "" ? [] : [""]);
16200
+ return lines.join("\n");
16201
+ }
16202
+
16203
+ // src/pr.ts
15876
16204
  import { execFileSync as execFileSync2 } from "node:child_process";
16205
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
16206
+ import { dirname, join as join3 } from "node:path";
16207
+ var PrError = class extends Error {
16208
+ };
16209
+ function run(cmd, args, root, env, input) {
16210
+ try {
16211
+ return execFileSync2(cmd, args, { cwd: root, env, input, stdio: ["pipe", "pipe", "pipe"], timeout: 12e4 }).toString().trim();
16212
+ } catch (e) {
16213
+ const err = e;
16214
+ if (err.code === "ENOENT") throw new PrError(cmd === "gh" ? "the GitHub CLI (gh) is not installed. Install it from https://cli.github.com and run 'gh auth login', or use --apply and open the pull request yourself." : `${cmd} is not installed`);
16215
+ throw new PrError(`${cmd} ${args[0]} failed: ${(err.stderr?.toString() || err.message).trim().split("\n").slice(-3).join(" ")}`);
16216
+ }
16217
+ }
16218
+ function openPullRequest(r) {
16219
+ const git2 = (...args) => run("git", args, r.root, r.env);
16220
+ run("gh", ["--version"], r.root, r.env);
16221
+ if (git2("status", "--porcelain", "--untracked-files=no")) throw new PrError("you have uncommitted changes. Commit or stash them first, so the pull request contains only threadctx's changes.");
16222
+ for (const p of r.files.keys()) {
16223
+ if (git2("status", "--porcelain", "--", p)) throw new PrError(`${p} has uncommitted changes or is untracked. Commit, stash or remove it first.`);
16224
+ }
16225
+ const original = git2("rev-parse", "--abbrev-ref", "HEAD");
16226
+ if (original === "HEAD") throw new PrError("you are on a detached HEAD. Check out a branch first.");
16227
+ const existing = new Set(git2("branch", "--list", "--format=%(refname:short)").split("\n"));
16228
+ let branch = r.branch;
16229
+ for (let i = 2; existing.has(branch); i++) branch = `${r.branch}-${i}`;
16230
+ const tracked = new Set([...r.files.keys()].filter((p) => existsSync(join3(r.root, p))));
16231
+ git2("switch", "-c", branch);
16232
+ let committed = false;
16233
+ try {
16234
+ for (const [p, content] of r.files) {
16235
+ mkdirSync(dirname(join3(r.root, p)), { recursive: true });
16236
+ writeFileSync(join3(r.root, p), content);
16237
+ }
16238
+ git2("add", "--", ...r.files.keys());
16239
+ git2("commit", "-q", "-m", r.title);
16240
+ committed = true;
16241
+ r.log(`Committed on ${branch}. Pushing\u2026
16242
+ `);
16243
+ git2("push", "-q", "-u", "origin", branch);
16244
+ const url = run("gh", ["pr", "create", "--head", branch, "--title", r.title, "--body-file", "-"], r.root, r.env, r.body).split("\n").pop() ?? "";
16245
+ return url;
16246
+ } catch (e) {
16247
+ if (!committed) {
16248
+ try {
16249
+ git2("reset", "-q");
16250
+ } catch {
16251
+ }
16252
+ for (const p of r.files.keys()) {
16253
+ if (tracked.has(p)) git2("checkout", "-q", "--", p);
16254
+ else rmSync(join3(r.root, p), { force: true });
16255
+ }
16256
+ } else {
16257
+ r.log(`note: the commit is on local branch ${branch}; push it and open the pull request yourself.
16258
+ `);
16259
+ }
16260
+ throw e;
16261
+ } finally {
16262
+ try {
16263
+ git2("switch", "-q", original);
16264
+ } catch {
16265
+ r.log(`note: could not switch back to ${original}; you are on ${branch}.
16266
+ `);
16267
+ }
16268
+ }
16269
+ }
16270
+
16271
+ // src/git.ts
16272
+ import { execFileSync as execFileSync3 } from "node:child_process";
15877
16273
  function git(root, args) {
15878
16274
  try {
15879
- return execFileSync2("git", args, { cwd: root, stdio: ["ignore", "pipe", "ignore"], timeout: 1e4 }).toString().trim();
16275
+ return execFileSync3("git", args, { cwd: root, stdio: ["ignore", "pipe", "ignore"], timeout: 1e4 }).toString().trim();
15880
16276
  } catch {
15881
16277
  return void 0;
15882
16278
  }
@@ -15904,7 +16300,7 @@ function githubRemote(dir) {
15904
16300
  }
15905
16301
 
15906
16302
  // src/mcp.ts
15907
- import { existsSync, realpathSync, statSync as statSync2 } from "node:fs";
16303
+ import { existsSync as existsSync2, realpathSync, statSync as statSync2 } from "node:fs";
15908
16304
  import { isAbsolute, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
15909
16305
  var SUPPORTED_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
15910
16306
  var MAX_TEXT = 2e4;
@@ -15944,7 +16340,7 @@ function clip(text) {
15944
16340
  function confine(root, input) {
15945
16341
  const realRoot = realpathSync(root);
15946
16342
  const abs = resolve2(realRoot, input);
15947
- const real = existsSync(abs) ? realpathSync(abs) : abs;
16343
+ const real = existsSync2(abs) ? realpathSync(abs) : abs;
15948
16344
  const rel = relative2(realRoot, real);
15949
16345
  if (rel === ".." || rel.startsWith(`..${sep2}`) || isAbsolute(rel)) throw new Error("path is outside the project");
15950
16346
  return real;
@@ -15969,7 +16365,7 @@ function callTool(name, args, root) {
15969
16365
  if (typeof args.file !== "string" || !args.file) throw new Error("file is required");
15970
16366
  const abs = confine(root, args.file);
15971
16367
  const rel = relative2(realpathSync(root), abs).split(sep2).join("/");
15972
- const isDir = existsSync(abs) && statSync2(abs).isDirectory();
16368
+ const isDir = existsSync2(abs) && statSync2(abs).isDirectory();
15973
16369
  const repo = openRepo(root);
15974
16370
  const state = prepare(repo);
15975
16371
  const tool = typeof args.tool === "string" && args.tool !== "all" ? args.tool : void 0;
@@ -16067,16 +16463,17 @@ async function serveMcp(io) {
16067
16463
  }
16068
16464
 
16069
16465
  // src/audit.ts
16070
- import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
16466
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
16071
16467
  import { homedir } from "node:os";
16072
- import { join as join3, resolve as resolve3 } from "node:path";
16468
+ import { join as join4, resolve as resolve3 } from "node:path";
16469
+ import { createHash as createHash3 } from "node:crypto";
16073
16470
 
16074
16471
  // src/remote.ts
16075
- import { execFileSync as execFileSync3 } from "node:child_process";
16472
+ import { execFileSync as execFileSync4 } from "node:child_process";
16076
16473
  function githubToken(env) {
16077
16474
  if (env.GH_TOKEN || env.GITHUB_TOKEN) return env.GH_TOKEN ?? env.GITHUB_TOKEN;
16078
16475
  try {
16079
- return execFileSync3("gh", ["auth", "token"], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim() || void 0;
16476
+ return execFileSync4("gh", ["auth", "token"], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim() || void 0;
16080
16477
  } catch {
16081
16478
  return void 0;
16082
16479
  }
@@ -16087,20 +16484,22 @@ var AuditUsageError = class extends Error {
16087
16484
  };
16088
16485
  var ORG = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
16089
16486
  function findLicense(arg, io) {
16090
- const fromFile = (p) => existsSync2(p) ? readFileSync2(p, "utf8").trim() : void 0;
16487
+ const fromFile = (p) => existsSync3(p) ? readFileSync2(p, "utf8").trim() : void 0;
16091
16488
  if (arg) {
16092
16489
  const file = resolve3(io.cwd, arg);
16093
16490
  const key2 = arg.startsWith("tctx1.") ? arg : fromFile(file);
16094
16491
  return key2 ? { key: key2, source: arg.startsWith("tctx1.") ? "--license" : arg } : { key: arg, source: "--license" };
16095
16492
  }
16096
16493
  if (io.env.THREADCTX_LICENSE) return { key: io.env.THREADCTX_LICENSE.trim(), source: "THREADCTX_LICENSE" };
16097
- const home = join3(io.env.THREADCTX_HOME ?? join3(homedir(), ".threadctx"), "license");
16494
+ const home = join4(io.env.THREADCTX_HOME ?? join4(homedir(), ".threadctx"), "license");
16098
16495
  const key = fromFile(home);
16099
16496
  return key ? { key, source: home } : void 0;
16100
16497
  }
16101
16498
  function describeLicense(claims) {
16102
16499
  const days = Math.max(0, Math.ceil((claims.exp * 1e3 - Date.now()) / 864e5));
16103
- return `${claims.plan} licence for ${claims.org === "*" ? "any organisation" : claims.org}, ${days} day${days === 1 ? "" : "s"} left (id ${claims.id})`;
16500
+ const who = claims.orgs?.length ? claims.orgs.join(", ") : claims.org === "*" ? "any organisation" : claims.org;
16501
+ const limit = claims.agentRepoLimit ? `, up to ${claims.agentRepoLimit} agent repositories` : "";
16502
+ return `${claims.plan} licence for ${who}${limit}, ${days} day${days === 1 ? "" : "s"} left (id ${claims.id})`;
16104
16503
  }
16105
16504
  async function runAudit(o, io) {
16106
16505
  if (!ORG.test(o.org)) throw new AuditUsageError(`'${o.org}' is not a valid GitHub organisation or user name`);
@@ -16118,7 +16517,7 @@ async function runAudit(o, io) {
16118
16517
  if (o.baseline) {
16119
16518
  if (!claims) throw new AuditUsageError("--baseline compares two full audits and needs a licence (the free audit has no audit.json to compare).");
16120
16519
  const file = resolve3(io.cwd, o.baseline);
16121
- if (!existsSync2(file)) throw new AuditUsageError(`baseline not found: ${o.baseline}`);
16520
+ if (!existsSync3(file)) throw new AuditUsageError(`baseline not found: ${o.baseline}`);
16122
16521
  try {
16123
16522
  const parsed = JSON.parse(readFileSync2(file, "utf8"));
16124
16523
  if (parsed.schema !== "threadctx.audit/v1") throw new Error("schema");
@@ -16162,22 +16561,41 @@ async function runAudit(o, io) {
16162
16561
  `);
16163
16562
  summary.trend = fleetTrend(previous, summary);
16164
16563
  }
16564
+ const evidence = evidencePack(summary, repos);
16565
+ const agentRepos = summary.repos.withContext;
16566
+ if (claims?.agentRepoLimit && agentRepos > claims.agentRepoLimit) {
16567
+ io.stderr(`
16568
+ This organisation has ${agentRepos} agent repositories; your ${claims.plan} licence covers up to ${claims.agentRepoLimit}.
16569
+ Showing the free summary. Upgrade for the full report: https://threadctx.dev/pricing?org=${encodeURIComponent(o.org)}&repos=${agentRepos}
16570
+
16571
+ `);
16572
+ claims = void 0;
16573
+ }
16165
16574
  const files = [];
16166
16575
  if (claims) {
16167
16576
  const dir = resolve3(io.cwd, o.outDir ?? `threadctx-audit-${o.org}`);
16168
- mkdirSync(dir, { recursive: true });
16169
- const last = join3(dir, "audit.json");
16170
- if (existsSync2(last)) writeFileSync(join3(dir, "previous-audit.json"), readFileSync2(last));
16171
- for (const [name, body] of [["report.html", renderAuditHtml(summary, repos)], ["repos.csv", renderAuditCsv(summary)], ["audit.json", renderAuditJson(summary, repos)]]) {
16172
- writeFileSync(join3(dir, name), body);
16173
- files.push(join3(dir, name));
16577
+ mkdirSync2(dir, { recursive: true });
16578
+ const last = join4(dir, "audit.json");
16579
+ if (existsSync3(last)) writeFileSync2(join4(dir, "previous-audit.json"), readFileSync2(last));
16580
+ const auditJson = renderAuditJson({ ...summary, evidence }, repos);
16581
+ const auditSha256 = createHash3("sha256").update(auditJson).digest("hex");
16582
+ for (const [name, body] of [
16583
+ ["report.html", renderAuditHtml(summary, repos)],
16584
+ ["repos.csv", renderAuditCsv(summary)],
16585
+ ["audit.json", auditJson],
16586
+ ["evidence.html", renderEvidenceHtml(evidence, { auditSha256 })],
16587
+ ["controls.csv", renderControlsCsv(evidence)],
16588
+ ["inventory.csv", renderInventoryCsv(evidence)]
16589
+ ]) {
16590
+ writeFileSync2(join4(dir, name), body);
16591
+ files.push(join4(dir, name));
16174
16592
  }
16175
16593
  io.stderr(`Using ${describeLicense(claims)}
16176
16594
  `);
16177
16595
  }
16178
- if (o.json) io.stdout(claims ? renderAuditJson(summary, repos) : `${JSON.stringify(summary, null, 2)}
16596
+ if (o.json) io.stdout(claims ? renderAuditJson({ ...summary, evidence }, repos) : `${JSON.stringify(summary, null, 2)}
16179
16597
  `);
16180
- else io.stdout(renderAuditText(summary, { color: o.color, licensed: Boolean(claims), files }));
16598
+ else io.stdout(renderAuditText(summary, { color: o.color, licensed: Boolean(claims), files, controls: controlHeadline(evidence) }));
16181
16599
  return 0;
16182
16600
  }
16183
16601
 
@@ -16253,8 +16671,12 @@ Usage:
16253
16671
  threadctx explain <file> [--tool <id>|all] [--surface cloud-agent|code-review|chat]
16254
16672
  What each agent loads for this file, in precedence order
16255
16673
  threadctx diff [--path <dir>] What each agent believes about the same directory
16256
- threadctx fix [path] [--apply] [--output <patch>]
16257
- Safe fixes as a patch (never commits; --apply writes files)
16674
+ threadctx fix [path] [--apply] [--output <patch>] [--pr]
16675
+ Safe fixes as a patch (never commits; --apply writes files;
16676
+ --pr opens a pull request with them, using git and gh)
16677
+ threadctx init [path] [--pr] [--no-badge] [--force]
16678
+ Add the GitHub Action workflow and a README grade badge
16679
+ (--pr opens a pull request instead of writing files)
16258
16680
  threadctx rules [id] List rules, or show one
16259
16681
  threadctx tools List tool adapters and when each was verified
16260
16682
  threadctx pack validate <file> Check a rule pack before using it
@@ -16282,6 +16704,9 @@ var OPTIONS = {
16282
16704
  surface: { type: "string" },
16283
16705
  path: { type: "string" },
16284
16706
  apply: { type: "boolean" },
16707
+ pr: { type: "boolean" },
16708
+ "no-badge": { type: "boolean" },
16709
+ force: { type: "boolean" },
16285
16710
  json: { type: "boolean" },
16286
16711
  color: { type: "boolean" },
16287
16712
  "no-color": { type: "boolean" },
@@ -16292,7 +16717,7 @@ var OPTIONS = {
16292
16717
  };
16293
16718
  async function main(argv, io) {
16294
16719
  try {
16295
- return await run(argv, io);
16720
+ return await run2(argv, io);
16296
16721
  } catch (e) {
16297
16722
  if (e instanceof UsageError || e instanceof ConfigError || e instanceof PackError) {
16298
16723
  io.stderr(`threadctx: ${e.message}
@@ -16300,12 +16725,12 @@ async function main(argv, io) {
16300
16725
  return 2;
16301
16726
  }
16302
16727
  io.stderr(`threadctx: unexpected error: ${e.stack ?? e}
16303
- Please report this at https://github.com/threadctx-dev/ctx/issues
16728
+ Please report this to hello@threadctx.dev
16304
16729
  `);
16305
16730
  return 2;
16306
16731
  }
16307
16732
  }
16308
- async function run(argv, io) {
16733
+ async function run2(argv, io) {
16309
16734
  let parsed;
16310
16735
  try {
16311
16736
  parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
@@ -16346,6 +16771,8 @@ Run 'threadctx --help' for usage.`);
16346
16771
  return cmdDiff(v, io, color);
16347
16772
  case "fix":
16348
16773
  return cmdFix(args[0], v, io);
16774
+ case "init":
16775
+ return cmdInit(args[0], v, io);
16349
16776
  case "rules":
16350
16777
  return cmdRules(args[0], v, io);
16351
16778
  case "tools":
@@ -16359,7 +16786,7 @@ Run 'threadctx --help' for usage.`);
16359
16786
  }
16360
16787
  function openRoot(pathArg, io) {
16361
16788
  const target = resolve4(io.cwd, pathArg ?? ".");
16362
- if (!existsSync3(target)) throw new UsageError(`path not found: ${pathArg}`);
16789
+ if (!existsSync4(target)) throw new UsageError(`path not found: ${pathArg}`);
16363
16790
  if (!statSync3(target).isDirectory()) throw new UsageError(`not a directory: ${pathArg} (scan takes a repository or directory)`);
16364
16791
  return openRepo(target);
16365
16792
  }
@@ -16408,8 +16835,8 @@ async function cmdScan(pathArg, v, io, color) {
16408
16835
  const out = format === "json" ? renderJson(result) : format === "sarif" ? renderSarif(result) : format === "md" ? renderMarkdown(result) : renderText(result, { color: v.output ? false : color, verbose: Boolean(v.verbose) });
16409
16836
  if (v.output) {
16410
16837
  const dest = resolve4(io.cwd, v.output);
16411
- mkdirSync2(dirname(dest), { recursive: true });
16412
- writeFileSync2(dest, out);
16838
+ mkdirSync3(dirname2(dest), { recursive: true });
16839
+ writeFileSync3(dest, out);
16413
16840
  io.stderr(`Wrote ${format} report to ${relative3(io.cwd, dest) || dest} \u2014 grade ${result.grade}, ${result.counts.blocker} blocker, ${result.counts.warning} warning
16414
16841
  `);
16415
16842
  } else {
@@ -16434,7 +16861,7 @@ function cmdCompare(baseFile, headFile, v, io) {
16434
16861
  if (!["text", "md", "json"].includes(format)) throw new UsageError("--format must be text, md or json");
16435
16862
  const readScan = (file) => {
16436
16863
  const abs = resolve4(io.cwd, file);
16437
- if (!existsSync3(abs)) throw new UsageError(`file not found: ${file}`);
16864
+ if (!existsSync4(abs)) throw new UsageError(`file not found: ${file}`);
16438
16865
  try {
16439
16866
  return parseScanJson(readFileSync3(abs, "utf8"), file);
16440
16867
  } catch (e) {
@@ -16450,7 +16877,8 @@ function cmdCompare(baseFile, headFile, v, io) {
16450
16877
  if (format === "json") out = `${JSON.stringify({ base: c.base, head: c.head, added: c.added, fixed: c.fixed, existing: c.existing }, null, 2)}
16451
16878
  `;
16452
16879
  else if (format === "md") {
16453
- const md = renderMarkdown(head, { baseline: { grade: base.grade, score: base.score }, newFingerprints: new Set(c.added.map((f) => f.fingerprint)) });
16880
+ const owner = io.env.GITHUB_REPOSITORY_OWNER ?? io.env.GITHUB_REPOSITORY?.split("/")[0] ?? "";
16881
+ const md = renderMarkdown(head, { baseline: { grade: base.grade, score: base.score }, newFingerprints: new Set(c.added.map((f) => f.fingerprint)), orgAuditOwner: owner });
16454
16882
  out = c.fixed.length ? md.replace("\n<sub>", `
16455
16883
  \u2705 **${c.fixed.length} fixed** by this change.
16456
16884
 
@@ -16463,15 +16891,15 @@ function cmdCompare(baseFile, headFile, v, io) {
16463
16891
  }
16464
16892
  if (v.output) {
16465
16893
  const dest = resolve4(io.cwd, v.output);
16466
- mkdirSync2(dirname(dest), { recursive: true });
16467
- writeFileSync2(dest, out);
16894
+ mkdirSync3(dirname2(dest), { recursive: true });
16895
+ writeFileSync3(dest, out);
16468
16896
  } else io.stdout(out);
16469
16897
  return compareExitCode(c, failOn);
16470
16898
  }
16471
16899
  function defaultBaseline(org, outDir, license, io) {
16472
16900
  if (!/^[A-Za-z0-9-]{1,39}$/.test(org)) return void 0;
16473
- const file = join4(resolve4(io.cwd, outDir ?? `threadctx-audit-${org}`), "audit.json");
16474
- return existsSync3(file) && findLicense(license, io) ? file : void 0;
16901
+ const file = join5(resolve4(io.cwd, outDir ?? `threadctx-audit-${org}`), "audit.json");
16902
+ return existsSync4(file) && findLicense(license, io) ? file : void 0;
16475
16903
  }
16476
16904
  async function cmdAudit(v, io, color) {
16477
16905
  if (!v.org) throw new UsageError("usage: threadctx audit --org <github-org-or-user>");
@@ -16520,11 +16948,11 @@ function locate(fileArg, io) {
16520
16948
  }
16521
16949
  };
16522
16950
  const given = resolve4(io.cwd, fileArg);
16523
- const abs = existsSync3(given) ? real(given) : join4(real(dirname(given)), basename(given));
16524
- const root = real(gitRoot(existsSync3(abs) && statSync3(abs).isDirectory() ? abs : dirname(abs)) ?? io.cwd);
16951
+ const abs = existsSync4(given) ? real(given) : join5(real(dirname2(given)), basename(given));
16952
+ const root = real(gitRoot(existsSync4(abs) && statSync3(abs).isDirectory() ? abs : dirname2(abs)) ?? io.cwd);
16525
16953
  const rel = relative3(root, abs).split(sep3).join("/");
16526
16954
  if (rel.startsWith("..")) throw new UsageError(`${fileArg} is outside the repository at ${root}`);
16527
- const isDir = existsSync3(abs) && statSync3(abs).isDirectory();
16955
+ const isDir = existsSync4(abs) && statSync3(abs).isDirectory();
16528
16956
  return { repo: openRepo(root), target: { path: rel === "" ? "" : rel, isDir } };
16529
16957
  }
16530
16958
  function contextsFor(repo, target, toolArg, surface) {
@@ -16596,14 +17024,32 @@ function cmdFix(pathArg, v, io) {
16596
17024
  io.stderr("No safe fixes to apply.\n");
16597
17025
  return 0;
16598
17026
  }
17027
+ if (v.pr) {
17028
+ const after = new Map([...plan.files].map(([p, f]) => [p, f.after]));
17029
+ const byRule = /* @__PURE__ */ new Map();
17030
+ for (const f of plan.applied) byRule.set(f.ruleId, (byRule.get(f.ruleId) ?? 0) + 1);
17031
+ const n2 = plan.applied.length;
17032
+ const body = [
17033
+ `This pull request applies ${n2} safe, mechanical fix${n2 === 1 ? "" : "es"} to the instructions AI coding agents read in this repository.`,
17034
+ "",
17035
+ "| Rule | Fixes | What it fixes |",
17036
+ "|---|---|---|",
17037
+ ...[...byRule].sort().map(([id, c]) => `| [${id}](https://threadctx.dev/rules/${id}) | ${c} | ${RULES.find((r) => r.id === id)?.title ?? ""} |`),
17038
+ "",
17039
+ `Grade before: **${result.grade}** (${result.score}/100). Every change is a deterministic edit; review the diff as usual.`,
17040
+ "",
17041
+ "<sub>Generated with [threadctx](https://threadctx.dev), which grades what every coding agent is told. Run `npx threadctx scan` to check locally.</sub>"
17042
+ ].join("\n");
17043
+ return withPr(() => openPullRequest({ root: repo.root, env: io.env, branch: "threadctx/fix-agent-context", files: after, title: `Fix agent context: ${n2} safe fix${n2 === 1 ? "" : "es"}`, body, log: io.stderr }), io);
17044
+ }
16599
17045
  if (v.apply) {
16600
- for (const [p, { after }] of plan.files) writeFileSync2(join4(repo.root, p), after);
17046
+ for (const [p, { after }] of plan.files) writeFileSync3(join5(repo.root, p), after);
16601
17047
  io.stderr(`Applied ${plan.applied.length} fix${plan.applied.length === 1 ? "" : "es"} to ${plan.files.size} file${plan.files.size === 1 ? "" : "s"}. Review with git diff; nothing was committed.
16602
17048
  `);
16603
17049
  return 0;
16604
17050
  }
16605
17051
  if (v.output) {
16606
- writeFileSync2(resolve4(io.cwd, v.output), plan.patch);
17052
+ writeFileSync3(resolve4(io.cwd, v.output), plan.patch);
16607
17053
  io.stderr(`Wrote ${plan.applied.length} fix${plan.applied.length === 1 ? "" : "es"} to ${v.output}. Apply with: git apply ${v.output}
16608
17054
  `);
16609
17055
  } else {
@@ -16613,6 +17059,71 @@ function cmdFix(pathArg, v, io) {
16613
17059
  }
16614
17060
  return 0;
16615
17061
  }
17062
+ function withPr(open, io) {
17063
+ try {
17064
+ const url = open();
17065
+ io.stdout(`${url}
17066
+ `);
17067
+ io.stderr("Pull request opened. Nothing else in your working tree was changed.\n");
17068
+ return 0;
17069
+ } catch (e) {
17070
+ if (e instanceof PrError) throw new UsageError(e.message);
17071
+ throw e;
17072
+ }
17073
+ }
17074
+ function isPublicOnGitHub(root, env) {
17075
+ try {
17076
+ return execFileSync5("gh", ["repo", "view", "--json", "visibility", "--jq", ".visibility"], { cwd: root, env, stdio: ["ignore", "pipe", "ignore"], timeout: 15e3 }).toString().trim() === "PUBLIC";
17077
+ } catch {
17078
+ return false;
17079
+ }
17080
+ }
17081
+ function cmdInit(pathArg, v, io) {
17082
+ const repo = openRoot(pathArg, io);
17083
+ const files = /* @__PURE__ */ new Map();
17084
+ const notes = [];
17085
+ if (existsSync4(join5(repo.root, WORKFLOW_PATH)) && !v.force) notes.push(`${WORKFLOW_PATH} already exists (use --force to replace it)`);
17086
+ else files.set(WORKFLOW_PATH, workflowYaml());
17087
+ if (!v["no-badge"]) {
17088
+ const result = doScan(repo, v, io);
17089
+ const fullName = githubRemote(repo.root);
17090
+ const badge = fullName && isPublicOnGitHub(repo.root, io.env) ? renderLiveBadge(fullName) : renderBadge(result, badgeLinkFor(fullName));
17091
+ const readmeName = ["README.md", "readme.md", "Readme.md"].find((n2) => existsSync4(join5(repo.root, n2)));
17092
+ if (!readmeName) notes.push(`no README.md; add this badge where you like:
17093
+ ${badge.markdown}`);
17094
+ else {
17095
+ const before = readFileSync3(join5(repo.root, readmeName), "utf8");
17096
+ const after = withBadge(before, badge.markdown);
17097
+ if (after === before) notes.push(`${readmeName} already has an agent context badge`);
17098
+ else files.set(readmeName, after);
17099
+ }
17100
+ }
17101
+ for (const n2 of notes) io.stderr(`note: ${n2}
17102
+ `);
17103
+ if (files.size === 0) {
17104
+ io.stderr("Nothing to add.\n");
17105
+ return 0;
17106
+ }
17107
+ if (v.pr) {
17108
+ const body = [
17109
+ "Adds an agent context check to this repository:",
17110
+ "",
17111
+ ...files.has(WORKFLOW_PATH) ? [`- \`${WORKFLOW_PATH}\`: on every pull request, grades what AI coding agents are told (AGENTS.md, CLAUDE.md, Cursor, Copilot, Gemini, MCP config) and comments with the change. Only problems a pull request introduces can fail it. Pinned by commit.`] : [],
17112
+ ...[...files.keys()].some((p) => p !== WORKFLOW_PATH) ? ["- A README badge showing the current grade."] : [],
17113
+ "",
17114
+ "No code or secrets leave the runner. <sub>[threadctx](https://threadctx.dev)</sub>"
17115
+ ].join("\n");
17116
+ return withPr(() => openPullRequest({ root: repo.root, env: io.env, branch: "threadctx/agent-context-check", files, title: "Add agent context check", body, log: io.stderr }), io);
17117
+ }
17118
+ for (const [p, content] of files) {
17119
+ mkdirSync3(dirname2(join5(repo.root, p)), { recursive: true });
17120
+ writeFileSync3(join5(repo.root, p), content);
17121
+ io.stderr(`wrote ${p}
17122
+ `);
17123
+ }
17124
+ io.stderr("Commit these files to turn on the check. Nothing was committed.\n");
17125
+ return 0;
17126
+ }
16616
17127
  function cmdRules(id, v, io) {
16617
17128
  if (id) {
16618
17129
  const r = RULES.find((x) => x.id.toLowerCase() === id.toLowerCase());
@@ -16651,7 +17162,7 @@ function cmdTools(v, io) {
16651
17162
  }
16652
17163
  function cmdPackValidate(file, io) {
16653
17164
  const abs = resolve4(io.cwd, file);
16654
- if (!existsSync3(abs)) throw new UsageError(`file not found: ${file}`);
17165
+ if (!existsSync4(abs)) throw new UsageError(`file not found: ${file}`);
16655
17166
  const pack = parsePack(readFileSync3(abs, "utf8"), file);
16656
17167
  io.stdout(`${pack.pack}: ${pack.rules.length} rule${pack.rules.length === 1 ? "" : "s"} valid
16657
17168
  `);
@@ -16662,7 +17173,7 @@ function cmdPackValidate(file, io) {
16662
17173
  var UPGRADE_URL = "https://threadctx.dev/pricing";
16663
17174
  function maybeUpgradeLine(result, io, remote) {
16664
17175
  if (!UPGRADE_URL || !io.isTTY || io.env.CI || io.env.THREADCTX_NO_UPSELL) return;
16665
- const stateFile = join4(io.env.THREADCTX_HOME ?? join4(homedir2(), ".threadctx"), "state.json");
17176
+ const stateFile = join5(io.env.THREADCTX_HOME ?? join5(homedir2(), ".threadctx"), "state.json");
16666
17177
  let state = {};
16667
17178
  try {
16668
17179
  state = JSON.parse(readFileSync3(stateFile, "utf8"));
@@ -16676,8 +17187,8 @@ function maybeUpgradeLine(result, io, remote) {
16676
17187
  ${msg}
16677
17188
  `);
16678
17189
  try {
16679
- mkdirSync2(dirname(stateFile), { recursive: true });
16680
- writeFileSync2(stateFile, JSON.stringify({ ...state, lastUpsell: today }));
17190
+ mkdirSync3(dirname2(stateFile), { recursive: true });
17191
+ writeFileSync3(stateFile, JSON.stringify({ ...state, lastUpsell: today }));
16681
17192
  } catch {
16682
17193
  }
16683
17194
  }