threadctx 0.2.1 → 0.3.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
@@ -12208,11 +12208,15 @@ function renderAuditText(s, opts) {
12208
12208
  for (const r of worst)
12209
12209
  out.push(` ${r.grade} ${String(r.score).padStart(3)} ${r.repo}`);
12210
12210
  }
12211
+ if (opts.controls) {
12212
+ const c = opts.controls;
12213
+ 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"}`)}` : ""}`);
12214
+ }
12211
12215
  out.push("");
12212
12216
  if (opts.licensed) {
12213
12217
  out.push(p.green("Full report written:"), ...(opts.files ?? []).map((f) => ` ${f}`));
12214
12218
  } 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>`));
12219
+ 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
12220
  }
12217
12221
  return `${out.join("\n")}
12218
12222
  `;
@@ -12305,7 +12309,8 @@ function renderAuditHtml(s, repos) {
12305
12309
  ${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
12310
  ${t.added.length ? `<p class="small muted">New since then: ${t.added.map(esc).join(", ")}</p>` : ""}`);
12307
12311
  }
12308
- sections.push(`<h2>Summary</h2><ul>${takeaways(s).map((t) => `<li>${t.includes("<code>") ? t : esc(t)}</li>`).join("")}</ul>`);
12312
+ sections.push(`<h2>Summary</h2><ul>${takeaways(s).map((t) => `<li>${t.includes("<code>") ? t : esc(t)}</li>`).join("")}</ul>
12313
+ <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
12314
  if (s.plan.length) {
12310
12315
  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
12316
  <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 +12353,6 @@ function renderAuditHtml(s, repos) {
12348
12353
  `;
12349
12354
  }
12350
12355
 
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
12356
  // ../rules/dist/benchmark.js
12543
12357
  var BENCHMARK = {
12544
12358
  "CTX-B001": {
@@ -14917,7 +14731,7 @@ function applySuppressions(findings, inline, config, now, diagnostics) {
14917
14731
  }
14918
14732
 
14919
14733
  // ../rules/dist/version.js
14920
- var ENGINE_VERSION = "0.2.1";
14734
+ var ENGINE_VERSION = "0.3.0";
14921
14735
  var REGISTRY_VERSION = "2026.10.1";
14922
14736
 
14923
14737
  // ../rules/dist/engine.js
@@ -15314,6 +15128,471 @@ function summarizeFleet(repos, meta2) {
15314
15128
  };
15315
15129
  }
15316
15130
 
15131
+ // ../rules/dist/compliance.js
15132
+ var FRAMEWORKS = ["SOC 2", "ISO/IEC 27001:2022", "ISO/IEC 42001:2023", "NIST AI RMF 1.0"];
15133
+ var CONTROLS = [
15134
+ {
15135
+ id: "TC-01",
15136
+ title: "AI coding agents and their tools are inventoried",
15137
+ objective: "The organisation knows which repositories give instructions to which AI coding agents, and which MCP servers those agents can call.",
15138
+ rules: [],
15139
+ refs: [
15140
+ { framework: "SOC 2", ref: "CC6.1", name: "Logical access: inventory of information assets" },
15141
+ { framework: "ISO/IEC 27001:2022", ref: "A.5.9", name: "Inventory of information and other associated assets" },
15142
+ { framework: "ISO/IEC 42001:2023", ref: "A.4.4", name: "Tooling resources" },
15143
+ { framework: "NIST AI RMF 1.0", ref: "GOVERN 1.6", name: "Mechanisms are in place to inventory AI systems" }
15144
+ ]
15145
+ },
15146
+ {
15147
+ id: "TC-02",
15148
+ title: "Secrets are kept out of agent instructions and tool configuration",
15149
+ objective: "No credential, token or key is written into a file that AI agents read or into an MCP server configuration.",
15150
+ rules: ["CTX-X005"],
15151
+ refs: [
15152
+ { framework: "SOC 2", ref: "CC6.1", name: "Logical access: protection of credentials" },
15153
+ { framework: "ISO/IEC 27001:2022", ref: "A.5.17", name: "Authentication information" },
15154
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.12", name: "Data leakage prevention" },
15155
+ { framework: "NIST AI RMF 1.0", ref: "MEASURE 2.7", name: "AI system security and resilience are evaluated" }
15156
+ ]
15157
+ },
15158
+ {
15159
+ id: "TC-03",
15160
+ title: "Agent instructions are free of hidden or injected content",
15161
+ objective: "Instruction files contain no invisible or bidirectional characters, encoded payloads, or instructions to download and run remote code.",
15162
+ rules: ["CTX-X001", "CTX-X002", "CTX-X003"],
15163
+ refs: [
15164
+ { framework: "SOC 2", ref: "CC6.8", name: "Prevent or detect unauthorised or malicious software" },
15165
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.7", name: "Protection against malware" },
15166
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.28", name: "Secure coding" },
15167
+ { framework: "NIST AI RMF 1.0", ref: "MEASURE 2.7", name: "AI system security and resilience are evaluated" }
15168
+ ]
15169
+ },
15170
+ {
15171
+ id: "TC-04",
15172
+ title: "Agents are not told to bypass quality and security checks",
15173
+ objective: "No instruction tells an agent to skip tests, disable linters or checks, or hide changes from review.",
15174
+ rules: ["CTX-X004"],
15175
+ refs: [
15176
+ { framework: "SOC 2", ref: "CC8.1", name: "Change management: changes are tested before implementation" },
15177
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.29", name: "Security testing in development and acceptance" },
15178
+ { framework: "ISO/IEC 42001:2023", ref: "A.6.2.4", name: "AI system verification and validation" }
15179
+ ]
15180
+ },
15181
+ {
15182
+ id: "TC-05",
15183
+ title: "Third-party agent tools are pinned and authenticated",
15184
+ objective: "MCP servers, skills and rule packs are pinned to a version or hash, and remote servers use TLS and authentication.",
15185
+ rules: ["CTX-X006", "CTX-X007", "CTX-X009"],
15186
+ refs: [
15187
+ { framework: "SOC 2", ref: "CC9.2", name: "Risks from vendors and business partners are assessed and managed" },
15188
+ { framework: "ISO/IEC 27001:2022", ref: "A.5.21", name: "Managing information security in the ICT supply chain" },
15189
+ { framework: "ISO/IEC 42001:2023", ref: "A.10.3", name: "Suppliers" },
15190
+ { framework: "NIST AI RMF 1.0", ref: "GOVERN 6.1", name: "Policies address risks from third-party entities" }
15191
+ ]
15192
+ },
15193
+ {
15194
+ id: "TC-06",
15195
+ title: "Agent instructions have owners and reviewed changes",
15196
+ objective: "Every instruction file is covered by CODEOWNERS, and generated files are changed only at their source.",
15197
+ rules: ["CTX-G001", "CTX-G002", "CTX-G003"],
15198
+ refs: [
15199
+ { framework: "SOC 2", ref: "CC8.1", name: "Change management: changes are authorised and approved" },
15200
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.32", name: "Change management" },
15201
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.4", name: "Access to source code" },
15202
+ { framework: "NIST AI RMF 1.0", ref: "GOVERN 2.1", name: "Roles and responsibilities are documented" }
15203
+ ]
15204
+ },
15205
+ {
15206
+ id: "TC-07",
15207
+ title: "Agent instructions are accurate and consistent",
15208
+ objective: "Instructions match the repository (paths, scripts, package manager, versions) and do not contradict each other across files and tools.",
15209
+ rules: ["CTX-S003", "CTX-S004", "CTX-D001", "CTX-D002", "CTX-D003", "CTX-D005", "CTX-C001", "CTX-C002", "CTX-C003"],
15210
+ refs: [
15211
+ { framework: "SOC 2", ref: "CC2.1", name: "Relevant, quality information supports internal control" },
15212
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.9", name: "Configuration management" },
15213
+ { framework: "ISO/IEC 42001:2023", ref: "A.6.2.7", name: "AI system technical documentation" },
15214
+ { framework: "NIST AI RMF 1.0", ref: "MAP 2.2", name: "Knowledge limits and how outputs are used are documented" }
15215
+ ]
15216
+ },
15217
+ {
15218
+ id: "TC-08",
15219
+ title: "Agent context is monitored over time",
15220
+ objective: "The audit is repeated and compared with the previous run, so regressions are found and followed up.",
15221
+ rules: [],
15222
+ refs: [
15223
+ { framework: "SOC 2", ref: "CC4.1", name: "Ongoing and separate evaluations" },
15224
+ { framework: "SOC 2", ref: "CC7.1", name: "Detection of configuration changes and vulnerabilities" },
15225
+ { framework: "ISO/IEC 27001:2022", ref: "A.8.16", name: "Monitoring activities" },
15226
+ { framework: "NIST AI RMF 1.0", ref: "MANAGE 4.1", name: "Post-deployment monitoring plans are implemented" }
15227
+ ]
15228
+ }
15229
+ ];
15230
+ 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.";
15231
+ var plural2 = (n2, one, many = `${one}s`) => `${n2} ${n2 === 1 ? one : many}`;
15232
+ function evidencePack(summary, repos) {
15233
+ const withContext = repos.filter((r) => r.result && r.result.artifacts.length > 0).sort((a, b) => a.fullName < b.fullName ? -1 : 1);
15234
+ const tested = withContext.length;
15235
+ const inventory = withContext.map((r) => {
15236
+ const res = r.result;
15237
+ return {
15238
+ repo: r.fullName,
15239
+ url: r.url,
15240
+ private: Boolean(r.private),
15241
+ agents: res.tools.filter((t) => t.layers > 0).map((t) => t.id),
15242
+ 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),
15243
+ mcpServers: res.mcpServers.map((m) => ({ client: m.client, name: m.name, transport: m.transport, source: m.source })),
15244
+ grade: res.grade,
15245
+ score: res.score
15246
+ };
15247
+ });
15248
+ const controls = CONTROLS.map((c) => {
15249
+ if (c.id === "TC-01") {
15250
+ const files = inventory.reduce((n2, r) => n2 + r.files.length, 0);
15251
+ const servers = inventory.reduce((n2, r) => n2 + r.mcpServers.length, 0);
15252
+ return {
15253
+ ...base(c),
15254
+ status: "evidenced",
15255
+ tested,
15256
+ 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).`
15257
+ };
15258
+ }
15259
+ if (c.id === "TC-08") {
15260
+ const t = summary.trend;
15261
+ 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." };
15262
+ }
15263
+ const ids = new Set(c.rules);
15264
+ let findings = 0;
15265
+ let blockers = 0;
15266
+ const hit = /* @__PURE__ */ new Set();
15267
+ for (const r of withContext) {
15268
+ for (const f of r.result.findings) {
15269
+ if (f.suppressed || !ids.has(f.ruleId))
15270
+ continue;
15271
+ findings++;
15272
+ if (f.severity === "blocker")
15273
+ blockers++;
15274
+ hit.add(r.fullName);
15275
+ }
15276
+ }
15277
+ const status = tested === 0 ? "not-evidenced" : blockers > 0 ? "gap" : findings > 0 ? "attention" : "met";
15278
+ 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")}.`;
15279
+ return { ...base(c), status, findings, blockers, repos: [...hit].sort(), tested, statement };
15280
+ });
15281
+ const agents = {};
15282
+ for (const r of inventory)
15283
+ for (const a of r.agents)
15284
+ agents[a] = (agents[a] ?? 0) + 1;
15285
+ return {
15286
+ schema: "threadctx.evidence/v1",
15287
+ org: summary.org,
15288
+ generatedAt: summary.generatedAt,
15289
+ engine: summary.engine,
15290
+ scope: { repositoriesListed: summary.repos.listed, repositoriesScanned: summary.repos.scanned, withAgentContext: summary.repos.withContext, withoutAgentContext: summary.repos.withoutContext, unreadable: summary.repos.failed },
15291
+ totals: { agentFiles: inventory.reduce((n2, r) => n2 + r.files.length, 0), mcpServers: inventory.reduce((n2, r) => n2 + r.mcpServers.length, 0), agents },
15292
+ controls,
15293
+ inventory,
15294
+ disclaimer: EVIDENCE_DISCLAIMER
15295
+ };
15296
+ function base(c) {
15297
+ return { id: c.id, title: c.title, objective: c.objective, refs: c.refs, findings: 0, blockers: 0, repos: [] };
15298
+ }
15299
+ }
15300
+ function controlHeadline(pack) {
15301
+ const c = pack.controls;
15302
+ return {
15303
+ total: c.length,
15304
+ met: c.filter((x) => x.status === "met" || x.status === "evidenced").length,
15305
+ attention: c.filter((x) => x.status === "attention" || x.status === "not-evidenced").length,
15306
+ gap: c.filter((x) => x.status === "gap").length
15307
+ };
15308
+ }
15309
+
15310
+ // ../report/dist/evidence.js
15311
+ var esc2 = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
15312
+ var TOOL_LABEL2 = { "agents-md": "AGENTS.md", "claude-code": "Claude Code", cursor: "Cursor", copilot: "GitHub Copilot", gemini: "Gemini CLI" };
15313
+ var STATUS_LABEL = { met: "Met", evidenced: "Evidenced", attention: "Needs attention", gap: "Gap", "not-evidenced": "Not evidenced" };
15314
+ var csvCell2 = (v) => {
15315
+ let s = String(v);
15316
+ if (/^[=+\-@\t\r]/.test(s))
15317
+ s = `'${s}`;
15318
+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
15319
+ };
15320
+ var csv = (rows) => `${rows.map((r) => r.map(csvCell2).join(",")).join("\n")}
15321
+ `;
15322
+ function renderInventoryCsv(p) {
15323
+ const rows = [["repository", "visibility", "item_type", "path_or_name", "agent_or_client", "kind_or_transport", "source", "repository_grade"]];
15324
+ for (const r of p.inventory) {
15325
+ const vis = r.private ? "private" : "public";
15326
+ for (const f of r.files)
15327
+ rows.push([r.repo, vis, "instruction_file", f.path, TOOL_LABEL2[f.tool] ?? f.tool, f.kind, "", r.grade]);
15328
+ for (const m of r.mcpServers)
15329
+ rows.push([r.repo, vis, "mcp_server", m.name, m.client, m.transport, m.source, r.grade]);
15330
+ }
15331
+ return csv(rows);
15332
+ }
15333
+ function renderControlsCsv(p) {
15334
+ const rows = [["control_id", "control", "status", "framework", "reference", "reference_name", "open_findings", "blocking_findings", "repositories_affected", "repositories_tested", "statement", "generated_at"]];
15335
+ for (const c of p.controls) {
15336
+ for (const r of c.refs)
15337
+ 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]);
15338
+ }
15339
+ return csv(rows);
15340
+ }
15341
+ var CSS2 = `
15342
+ :root{--fg:#111418;--muted:#5b6370;--line:#e2e5ea;--card:#f6f7f9;--accent:#1f4fd1;--met:#1a7f37;--att:#9a6700;--gap:#c62828;--na:#5b6370}
15343
+ *{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}
15344
+ main{max-width:900px;margin:0 auto;padding:40px 28px 64px}
15345
+ 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}
15346
+ .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}
15347
+ .cover{border:1px solid var(--line);border-radius:14px;padding:28px;margin:8px 0 24px;background:linear-gradient(180deg,#f8faff,#fff)}
15348
+ .eyebrow{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--accent);font-weight:700}
15349
+ .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}
15350
+ .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}
15351
+ 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}
15352
+ .st{display:inline-block;border-radius:999px;padding:1px 9px;font-size:12px;font-weight:700;white-space:nowrap}
15353
+ .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)}
15354
+ .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}
15355
+ .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)}
15356
+ .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}
15357
+ .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)}
15358
+ .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}
15359
+ footer{margin-top:40px;color:var(--muted);font-size:12px;border-top:1px solid var(--line);padding-top:12px}
15360
+ @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}}
15361
+ `;
15362
+ function renderEvidenceHtml(p, opts = {}) {
15363
+ const date = p.generatedAt.slice(0, 10);
15364
+ const st = (s) => `<span class="st st-${s}">${STATUS_LABEL[s]}</span>`;
15365
+ const count = (s) => p.controls.filter((c) => s.includes(c.status)).length;
15366
+ 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";
15367
+ const out = [];
15368
+ out.push(`<div class="cover"><div class="eyebrow">AI coding agent governance \xB7 evidence pack</div>
15369
+ <h1>${esc2(p.org)}</h1><div class="muted">Configuration of AI coding agents across the organisation's GitHub repositories</div>
15370
+ <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>
15371
+ <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>`);
15372
+ out.push(`<h2>Summary</h2><div class="kpis">
15373
+ <div class="kpi"><b>${count(["met", "evidenced"])}/${p.controls.length}</b><span class="muted small">controls met or evidenced</span></div>
15374
+ <div class="kpi"><b>${count(["attention", "not-evidenced"])}</b><span class="muted small">need attention</span></div>
15375
+ <div class="kpi"><b>${count(["gap"])}</b><span class="muted small">gaps (blocking findings)</span></div>
15376
+ <div class="kpi"><b>${p.totals.agentFiles}</b><span class="muted small">agent files inventoried</span></div>
15377
+ <div class="kpi"><b>${p.totals.mcpServers}</b><span class="muted small">MCP servers inventoried</span></div></div>
15378
+ <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>
15379
+ <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>`);
15380
+ 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>
15381
+ <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>`);
15382
+ 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>
15383
+ <div class="small muted">${esc2(c.objective)}</div><p class="small" style="margin:8px 0 0">${esc2(c.statement)}</p>
15384
+ ${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>` : ""}
15385
+ <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("")}`);
15386
+ 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>`);
15387
+ 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>
15388
+ <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>`);
15389
+ 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>`);
15390
+ out.push(`<div class="note"><b>Important.</b> ${esc2(p.disclaimer)}</div>
15391
+ <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>`);
15392
+ 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>
15393
+ `;
15394
+ }
15395
+
15396
+ // ../report/dist/index.js
15397
+ var RULE_DOCS = "https://threadctx.dev/rules";
15398
+ function renderJson(result) {
15399
+ return `${JSON.stringify(result, null, 2)}
15400
+ `;
15401
+ }
15402
+ var SARIF_LEVEL = { blocker: "error", warning: "warning", info: "note" };
15403
+ var SECURITY_SEVERITY = { blocker: "9.0", warning: "5.0", info: "2.0" };
15404
+ function renderSarif(result) {
15405
+ const rules = [...result.rules].sort((a, b) => a.id < b.id ? -1 : 1);
15406
+ const index = new Map(rules.map((r, i) => [r.id, i]));
15407
+ const sarif = {
15408
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
15409
+ version: "2.1.0",
15410
+ runs: [
15411
+ {
15412
+ tool: {
15413
+ driver: {
15414
+ name: "threadctx",
15415
+ semanticVersion: result.engine.version,
15416
+ informationUri: "https://threadctx.dev",
15417
+ rules: rules.map((r) => sarifRule(r))
15418
+ }
15419
+ },
15420
+ automationDetails: { id: "threadctx/agent-context/" },
15421
+ results: result.findings.map((f) => sarifResult(f, index.get(f.ruleId))),
15422
+ properties: { grade: result.grade, score: result.score, registry: result.engine.registry }
15423
+ }
15424
+ ]
15425
+ };
15426
+ return `${JSON.stringify(sarif, null, 2)}
15427
+ `;
15428
+ }
15429
+ function sarifRule(r) {
15430
+ const tags = [.../* @__PURE__ */ new Set(["agent-context", r.family, r.determinism])];
15431
+ return {
15432
+ id: r.id,
15433
+ name: r.id.replace(/[^A-Za-z0-9]/g, ""),
15434
+ shortDescription: { text: r.title },
15435
+ fullDescription: { text: r.rationale },
15436
+ helpUri: r.id.startsWith("CTX-") ? `${RULE_DOCS}/${r.id}` : void 0,
15437
+ help: { text: `${r.remediation}
15438
+
15439
+ Source: ${r.citation}`, markdown: `${r.remediation}
15440
+
15441
+ Source: ${r.citation}` },
15442
+ defaultConfiguration: { level: SARIF_LEVEL[r.severity] },
15443
+ properties: { tags, precision: r.determinism === "deterministic" ? "high" : "medium", ...r.family === "security" ? { "security-severity": SECURITY_SEVERITY[r.severity] } : {} }
15444
+ };
15445
+ }
15446
+ function sarifResult(f, ruleIndex) {
15447
+ const location = (path, line, endLine) => ({
15448
+ physicalLocation: {
15449
+ // Repository-level findings point at the root so code scanning still accepts them.
15450
+ artifactLocation: { uri: path || ".", uriBaseId: "%SRCROOT%" },
15451
+ ...line ? { region: { startLine: line, ...endLine && endLine > line ? { endLine } : {} } } : {}
15452
+ }
15453
+ });
15454
+ return {
15455
+ ruleId: f.ruleId,
15456
+ ...ruleIndex !== void 0 ? { ruleIndex } : {},
15457
+ level: SARIF_LEVEL[f.severity],
15458
+ message: { text: f.evidence ? `${f.message}
15459
+
15460
+ Evidence: ${f.evidence}` : f.message },
15461
+ locations: [location(f.path, f.line, f.endLine)],
15462
+ ...f.related?.length ? { relatedLocations: f.related.map((r, i) => ({ id: i + 1, ...location(r.path, r.line), message: { text: r.message ?? "related" } })) } : {},
15463
+ partialFingerprints: { "threadctx/v1": f.fingerprint },
15464
+ ...f.suppressed ? { suppressions: [{ kind: f.suppressed.source === "inline" ? "inSource" : "external", justification: f.suppressed.reason }] } : {}
15465
+ };
15466
+ }
15467
+ function painter(color) {
15468
+ const wrap = (code2) => (s) => color ? `\x1B[${code2}m${s}\x1B[0m` : s;
15469
+ return { red: wrap("31"), yellow: wrap("33"), blue: wrap("34"), green: wrap("32"), dim: wrap("2"), bold: wrap("1"), cyan: wrap("36") };
15470
+ }
15471
+ var GRADE_COLOR = { A: "green", B: "green", C: "yellow", D: "yellow", F: "red" };
15472
+ function renderText(result, opts) {
15473
+ const p = painter(opts.color);
15474
+ const out = [];
15475
+ const open = result.findings.filter((f) => !f.suppressed);
15476
+ const shown = opts.verbose ? open : open.filter((f) => f.severity !== "info");
15477
+ const sev2 = { blocker: p.red("blocker"), warning: p.yellow("warning"), info: p.blue("info ") };
15478
+ let lastPath;
15479
+ for (const f of shown) {
15480
+ if (f.path !== lastPath) {
15481
+ out.push("", p.bold(f.path || "(repository)"));
15482
+ lastPath = f.path;
15483
+ }
15484
+ const loc = f.line ? p.dim(`${String(f.line).padStart(4)}:`) : p.dim(" ");
15485
+ const fix = f.fix?.kind === "safe" ? p.green(" [fixable]") : "";
15486
+ out.push(`${loc} ${sev2[f.severity]} ${f.message} ${p.dim(f.ruleId)}${fix}`);
15487
+ if (f.evidence)
15488
+ out.push(` ${p.dim(`> ${f.evidence}`)}`);
15489
+ }
15490
+ const hiddenInfo = open.length - shown.length;
15491
+ const { blocker, warning, info, suppressed } = result.counts;
15492
+ out.push("");
15493
+ 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)`) : ""));
15494
+ const fixable = open.filter((f) => f.fix?.kind === "safe").length;
15495
+ if (fixable)
15496
+ out.push(p.dim(`${fixable} finding${fixable === 1 ? "" : "s"} can be fixed automatically: threadctx fix`));
15497
+ const tools = result.tools.filter((t) => t.layers > 0);
15498
+ if (tools.length) {
15499
+ out.push(p.dim(`Always-loaded context (estimated tokens): ${tools.map((t) => `${t.label.split(" (")[0]} \u2248${t.alwaysTokenEstimate.toLocaleString("en-US")}`).join(" \xB7 ")}`));
15500
+ }
15501
+ for (const d of result.diagnostics) {
15502
+ const tag = d.level === "error" ? p.red("error") : d.level === "warning" ? p.yellow("note") : p.dim("note");
15503
+ out.push(`${tag} ${d.path ? `${d.path}${d.line ? `:${d.line}` : ""}: ` : ""}${d.message}`);
15504
+ }
15505
+ return `${out.join("\n").replace(/^\n/, "")}
15506
+ `;
15507
+ }
15508
+ var SEV_ICON = { blocker: "\u{1F534}", warning: "\u{1F7E1}", info: "\u{1F535}" };
15509
+ function mdEscape(s) {
15510
+ return s.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
15511
+ }
15512
+ function renderMarkdown(result, opts = {}) {
15513
+ const out = [];
15514
+ const open = result.findings.filter((f) => !f.suppressed);
15515
+ 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})` : "";
15516
+ out.push(`### Agent context: grade **${result.grade}** \xB7 ${result.score}/100${delta}`);
15517
+ out.push("");
15518
+ 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` : ""}`);
15519
+ const list = opts.newFingerprints ? open.filter((f) => opts.newFingerprints.has(f.fingerprint)) : open;
15520
+ if (opts.newFingerprints)
15521
+ out.push("", `**${list.length} new** in this change${open.length > list.length ? ` (${open.length - list.length} existing not shown)` : ""}.`);
15522
+ const max = opts.maxFindings ?? 50;
15523
+ if (list.length) {
15524
+ out.push("", "| | Rule | Location | Finding |", "|---|---|---|---|");
15525
+ for (const f of list.slice(0, max)) {
15526
+ const rule = f.ruleId.startsWith("CTX-") ? `[${f.ruleId}](${RULE_DOCS}/${f.ruleId})` : f.ruleId;
15527
+ out.push(`| ${SEV_ICON[f.severity]} | ${rule} | \`${mdEscape(f.path || ".")}${f.line ? `:${f.line}` : ""}\` | ${mdEscape(f.message)} |`);
15528
+ }
15529
+ if (list.length > max)
15530
+ out.push("", `\u2026and ${list.length - max} more. Run \`npx threadctx scan\` locally for the full list.`);
15531
+ }
15532
+ const tools = result.tools.filter((t) => t.layers > 0);
15533
+ if (tools.length) {
15534
+ out.push("", "<details><summary>What each agent loads at the repository root (estimated tokens)</summary>", "");
15535
+ for (const t of tools)
15536
+ out.push(`- ${t.label}: \u2248${t.alwaysTokenEstimate.toLocaleString("en-US")} tokens across ${t.layers} file${t.layers === 1 ? "" : "s"}`);
15537
+ out.push("", "</details>");
15538
+ }
15539
+ 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>`);
15540
+ return `${out.join("\n")}
15541
+ `;
15542
+ }
15543
+ var LOAD_LABEL = { always: "always", "on-demand": "on demand", conditional: "matches", "agent-decides": "agent decides" };
15544
+ function renderEffective(contexts, opts) {
15545
+ const p = painter(opts.color);
15546
+ const out = [];
15547
+ for (const { label: label2, ctx } of contexts) {
15548
+ out.push(p.bold(`${label2}`) + p.dim(` ${ctx.targetPath} \u2248${ctx.tokenEstimate.toLocaleString("en-US")} tokens (estimate)`));
15549
+ if (!ctx.layers.length)
15550
+ out.push(p.dim(" (loads nothing from this repository)"));
15551
+ for (const l of ctx.layers) {
15552
+ 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)}`);
15553
+ }
15554
+ for (const n2 of ctx.notes)
15555
+ out.push(p.dim(` note: ${n2}`));
15556
+ out.push("");
15557
+ }
15558
+ return out.join("\n");
15559
+ }
15560
+ function renderFactTable(rows, tools, opts) {
15561
+ const p = painter(opts.color);
15562
+ if (!rows.length)
15563
+ return p.dim("No comparable facts (commands, package manager, versions) found.\n");
15564
+ const width = 26;
15565
+ const head = `${"".padEnd(18)}${tools.map((t) => t.padEnd(width)).join("")}`;
15566
+ const lines = [p.bold(head)];
15567
+ for (const r of rows) {
15568
+ const vals = tools.map((t) => r.values[t]?.length ? r.values[t].join(", ") : "\u2014");
15569
+ const differ = new Set(vals.filter((v) => v !== "\u2014")).size > 1;
15570
+ const cells = vals.map((v) => (v.length > width - 2 ? `${v.slice(0, width - 3)}\u2026` : v).padEnd(width));
15571
+ lines.push(`${differ ? p.red(r.topic.padEnd(18)) : r.topic.padEnd(18)}${cells.join("")}${differ ? p.red(" \u2190 differs") : ""}`);
15572
+ }
15573
+ return `${lines.join("\n")}
15574
+ `;
15575
+ }
15576
+ var BADGE_COLOR = { A: "brightgreen", B: "green", C: "yellow", D: "orange", F: "red" };
15577
+ var BADGE_LINK = "https://threadctx.dev";
15578
+ function badgeLinkFor(fullName) {
15579
+ return fullName && /^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9_.-]{1,100}$/.test(fullName) ? `https://threadctx.dev/r/${fullName}` : BADGE_LINK;
15580
+ }
15581
+ function renderBadge(result, link = BADGE_LINK) {
15582
+ const url = `https://img.shields.io/badge/agent%20context-${result.grade}%20%C2%B7%20${result.score}-${BADGE_COLOR[result.grade]}`;
15583
+ const alt = `Agent context grade ${result.grade}`;
15584
+ return { url, markdown: `[![${alt}](${url})](${link})`, html: `<a href="${link}"><img src="${url}" alt="${alt}"></a>` };
15585
+ }
15586
+ function renderLiveBadge(fullName) {
15587
+ const link = badgeLinkFor(fullName);
15588
+ const url = `https://img.shields.io/endpoint?url=${encodeURIComponent(`https://threadctx.dev/badge/${fullName}`)}`;
15589
+ const alt = "Agent context grade";
15590
+ return { url, markdown: `[![${alt}](${url})](${link})`, html: `<a href="${link}"><img src="${url}" alt="${alt}"></a>` };
15591
+ }
15592
+
15593
+ // src/cli.ts
15594
+ import { execFileSync as execFileSync5 } from "node:child_process";
15595
+
15317
15596
  // ../../node_modules/.pnpm/diff@9.0.0/node_modules/diff/libesm/diff/base.js
15318
15597
  var Diff = class {
15319
15598
  diff(oldStr, newStr, options = {}) {
@@ -15872,11 +16151,116 @@ function planFixes(fs, findings, kinds = ["safe"]) {
15872
16151
  return { files, applied: [...applied], skipped, patch };
15873
16152
  }
15874
16153
 
15875
- // src/git.ts
16154
+ // src/init.ts
16155
+ var ACTION_PIN = { sha: "0c480a0bede1629f6156e04ae0d047b171ddc1f2", tag: "v1.2.1" };
16156
+ var CHECKOUT_PIN = { sha: "3d3c42e5aac5ba805825da76410c181273ba90b1", tag: "v7.0.1" };
16157
+ var WORKFLOW_PATH = ".github/workflows/agent-context.yml";
16158
+ function workflowYaml() {
16159
+ return `# Grades what AI coding agents are told (AGENTS.md, CLAUDE.md, Cursor, Copilot, Gemini, MCP).
16160
+ # Only problems a pull request introduces can fail it. https://threadctx.dev
16161
+ name: Agent context
16162
+ on:
16163
+ pull_request:
16164
+ push:
16165
+ branches: [main, master]
16166
+ permissions:
16167
+ contents: read
16168
+ pull-requests: write
16169
+ security-events: write
16170
+ jobs:
16171
+ agent-context:
16172
+ runs-on: ubuntu-latest
16173
+ steps:
16174
+ - uses: actions/checkout@${CHECKOUT_PIN.sha} # ${CHECKOUT_PIN.tag}
16175
+ - uses: threadctx-dev/action@${ACTION_PIN.sha} # ${ACTION_PIN.tag}
16176
+ `;
16177
+ }
16178
+ var BADGE_LINE = /\[!\[agent context[^\]]*\]\([^)]*\)\]\([^)]*\)/i;
16179
+ function withBadge(readme, markdown) {
16180
+ if (BADGE_LINE.test(readme) || readme.includes("img.shields.io/badge/agent%20context-") || readme.includes("threadctx.dev%2Fbadge%2F")) return readme;
16181
+ const lines = readme.split("\n");
16182
+ const h1 = lines.findIndex((l) => /^#\s/.test(l));
16183
+ if (h1 === -1) return `${markdown}
16184
+
16185
+ ${readme}`;
16186
+ const next = lines[h1 + 1];
16187
+ lines.splice(h1 + 1, 0, "", markdown, ...next === void 0 || next === "" ? [] : [""]);
16188
+ return lines.join("\n");
16189
+ }
16190
+
16191
+ // src/pr.ts
15876
16192
  import { execFileSync as execFileSync2 } from "node:child_process";
16193
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
16194
+ import { dirname, join as join3 } from "node:path";
16195
+ var PrError = class extends Error {
16196
+ };
16197
+ function run(cmd, args, root, env, input) {
16198
+ try {
16199
+ return execFileSync2(cmd, args, { cwd: root, env, input, stdio: ["pipe", "pipe", "pipe"], timeout: 12e4 }).toString().trim();
16200
+ } catch (e) {
16201
+ const err = e;
16202
+ 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`);
16203
+ throw new PrError(`${cmd} ${args[0]} failed: ${(err.stderr?.toString() || err.message).trim().split("\n").slice(-3).join(" ")}`);
16204
+ }
16205
+ }
16206
+ function openPullRequest(r) {
16207
+ const git2 = (...args) => run("git", args, r.root, r.env);
16208
+ run("gh", ["--version"], r.root, r.env);
16209
+ 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.");
16210
+ for (const p of r.files.keys()) {
16211
+ if (git2("status", "--porcelain", "--", p)) throw new PrError(`${p} has uncommitted changes or is untracked. Commit, stash or remove it first.`);
16212
+ }
16213
+ const original = git2("rev-parse", "--abbrev-ref", "HEAD");
16214
+ if (original === "HEAD") throw new PrError("you are on a detached HEAD. Check out a branch first.");
16215
+ const existing = new Set(git2("branch", "--list", "--format=%(refname:short)").split("\n"));
16216
+ let branch = r.branch;
16217
+ for (let i = 2; existing.has(branch); i++) branch = `${r.branch}-${i}`;
16218
+ const tracked = new Set([...r.files.keys()].filter((p) => existsSync(join3(r.root, p))));
16219
+ git2("switch", "-c", branch);
16220
+ let committed = false;
16221
+ try {
16222
+ for (const [p, content] of r.files) {
16223
+ mkdirSync(dirname(join3(r.root, p)), { recursive: true });
16224
+ writeFileSync(join3(r.root, p), content);
16225
+ }
16226
+ git2("add", "--", ...r.files.keys());
16227
+ git2("commit", "-q", "-m", r.title);
16228
+ committed = true;
16229
+ r.log(`Committed on ${branch}. Pushing\u2026
16230
+ `);
16231
+ git2("push", "-q", "-u", "origin", branch);
16232
+ const url = run("gh", ["pr", "create", "--head", branch, "--title", r.title, "--body-file", "-"], r.root, r.env, r.body).split("\n").pop() ?? "";
16233
+ return url;
16234
+ } catch (e) {
16235
+ if (!committed) {
16236
+ try {
16237
+ git2("reset", "-q");
16238
+ } catch {
16239
+ }
16240
+ for (const p of r.files.keys()) {
16241
+ if (tracked.has(p)) git2("checkout", "-q", "--", p);
16242
+ else rmSync(join3(r.root, p), { force: true });
16243
+ }
16244
+ } else {
16245
+ r.log(`note: the commit is on local branch ${branch}; push it and open the pull request yourself.
16246
+ `);
16247
+ }
16248
+ throw e;
16249
+ } finally {
16250
+ try {
16251
+ git2("switch", "-q", original);
16252
+ } catch {
16253
+ r.log(`note: could not switch back to ${original}; you are on ${branch}.
16254
+ `);
16255
+ }
16256
+ }
16257
+ }
16258
+
16259
+ // src/git.ts
16260
+ import { execFileSync as execFileSync3 } from "node:child_process";
15877
16261
  function git(root, args) {
15878
16262
  try {
15879
- return execFileSync2("git", args, { cwd: root, stdio: ["ignore", "pipe", "ignore"], timeout: 1e4 }).toString().trim();
16263
+ return execFileSync3("git", args, { cwd: root, stdio: ["ignore", "pipe", "ignore"], timeout: 1e4 }).toString().trim();
15880
16264
  } catch {
15881
16265
  return void 0;
15882
16266
  }
@@ -15904,7 +16288,7 @@ function githubRemote(dir) {
15904
16288
  }
15905
16289
 
15906
16290
  // src/mcp.ts
15907
- import { existsSync, realpathSync, statSync as statSync2 } from "node:fs";
16291
+ import { existsSync as existsSync2, realpathSync, statSync as statSync2 } from "node:fs";
15908
16292
  import { isAbsolute, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
15909
16293
  var SUPPORTED_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
15910
16294
  var MAX_TEXT = 2e4;
@@ -15944,7 +16328,7 @@ function clip(text) {
15944
16328
  function confine(root, input) {
15945
16329
  const realRoot = realpathSync(root);
15946
16330
  const abs = resolve2(realRoot, input);
15947
- const real = existsSync(abs) ? realpathSync(abs) : abs;
16331
+ const real = existsSync2(abs) ? realpathSync(abs) : abs;
15948
16332
  const rel = relative2(realRoot, real);
15949
16333
  if (rel === ".." || rel.startsWith(`..${sep2}`) || isAbsolute(rel)) throw new Error("path is outside the project");
15950
16334
  return real;
@@ -15969,7 +16353,7 @@ function callTool(name, args, root) {
15969
16353
  if (typeof args.file !== "string" || !args.file) throw new Error("file is required");
15970
16354
  const abs = confine(root, args.file);
15971
16355
  const rel = relative2(realpathSync(root), abs).split(sep2).join("/");
15972
- const isDir = existsSync(abs) && statSync2(abs).isDirectory();
16356
+ const isDir = existsSync2(abs) && statSync2(abs).isDirectory();
15973
16357
  const repo = openRepo(root);
15974
16358
  const state = prepare(repo);
15975
16359
  const tool = typeof args.tool === "string" && args.tool !== "all" ? args.tool : void 0;
@@ -16067,16 +16451,17 @@ async function serveMcp(io) {
16067
16451
  }
16068
16452
 
16069
16453
  // src/audit.ts
16070
- import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
16454
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
16071
16455
  import { homedir } from "node:os";
16072
- import { join as join3, resolve as resolve3 } from "node:path";
16456
+ import { join as join4, resolve as resolve3 } from "node:path";
16457
+ import { createHash as createHash3 } from "node:crypto";
16073
16458
 
16074
16459
  // src/remote.ts
16075
- import { execFileSync as execFileSync3 } from "node:child_process";
16460
+ import { execFileSync as execFileSync4 } from "node:child_process";
16076
16461
  function githubToken(env) {
16077
16462
  if (env.GH_TOKEN || env.GITHUB_TOKEN) return env.GH_TOKEN ?? env.GITHUB_TOKEN;
16078
16463
  try {
16079
- return execFileSync3("gh", ["auth", "token"], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim() || void 0;
16464
+ return execFileSync4("gh", ["auth", "token"], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim() || void 0;
16080
16465
  } catch {
16081
16466
  return void 0;
16082
16467
  }
@@ -16087,14 +16472,14 @@ var AuditUsageError = class extends Error {
16087
16472
  };
16088
16473
  var ORG = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
16089
16474
  function findLicense(arg, io) {
16090
- const fromFile = (p) => existsSync2(p) ? readFileSync2(p, "utf8").trim() : void 0;
16475
+ const fromFile = (p) => existsSync3(p) ? readFileSync2(p, "utf8").trim() : void 0;
16091
16476
  if (arg) {
16092
16477
  const file = resolve3(io.cwd, arg);
16093
16478
  const key2 = arg.startsWith("tctx1.") ? arg : fromFile(file);
16094
16479
  return key2 ? { key: key2, source: arg.startsWith("tctx1.") ? "--license" : arg } : { key: arg, source: "--license" };
16095
16480
  }
16096
16481
  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");
16482
+ const home = join4(io.env.THREADCTX_HOME ?? join4(homedir(), ".threadctx"), "license");
16098
16483
  const key = fromFile(home);
16099
16484
  return key ? { key, source: home } : void 0;
16100
16485
  }
@@ -16118,7 +16503,7 @@ async function runAudit(o, io) {
16118
16503
  if (o.baseline) {
16119
16504
  if (!claims) throw new AuditUsageError("--baseline compares two full audits and needs a licence (the free audit has no audit.json to compare).");
16120
16505
  const file = resolve3(io.cwd, o.baseline);
16121
- if (!existsSync2(file)) throw new AuditUsageError(`baseline not found: ${o.baseline}`);
16506
+ if (!existsSync3(file)) throw new AuditUsageError(`baseline not found: ${o.baseline}`);
16122
16507
  try {
16123
16508
  const parsed = JSON.parse(readFileSync2(file, "utf8"));
16124
16509
  if (parsed.schema !== "threadctx.audit/v1") throw new Error("schema");
@@ -16162,22 +16547,32 @@ async function runAudit(o, io) {
16162
16547
  `);
16163
16548
  summary.trend = fleetTrend(previous, summary);
16164
16549
  }
16550
+ const evidence = evidencePack(summary, repos);
16165
16551
  const files = [];
16166
16552
  if (claims) {
16167
16553
  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));
16554
+ mkdirSync2(dir, { recursive: true });
16555
+ const last = join4(dir, "audit.json");
16556
+ if (existsSync3(last)) writeFileSync2(join4(dir, "previous-audit.json"), readFileSync2(last));
16557
+ const auditJson = renderAuditJson({ ...summary, evidence }, repos);
16558
+ const auditSha256 = createHash3("sha256").update(auditJson).digest("hex");
16559
+ for (const [name, body] of [
16560
+ ["report.html", renderAuditHtml(summary, repos)],
16561
+ ["repos.csv", renderAuditCsv(summary)],
16562
+ ["audit.json", auditJson],
16563
+ ["evidence.html", renderEvidenceHtml(evidence, { auditSha256 })],
16564
+ ["controls.csv", renderControlsCsv(evidence)],
16565
+ ["inventory.csv", renderInventoryCsv(evidence)]
16566
+ ]) {
16567
+ writeFileSync2(join4(dir, name), body);
16568
+ files.push(join4(dir, name));
16174
16569
  }
16175
16570
  io.stderr(`Using ${describeLicense(claims)}
16176
16571
  `);
16177
16572
  }
16178
- if (o.json) io.stdout(claims ? renderAuditJson(summary, repos) : `${JSON.stringify(summary, null, 2)}
16573
+ if (o.json) io.stdout(claims ? renderAuditJson({ ...summary, evidence }, repos) : `${JSON.stringify(summary, null, 2)}
16179
16574
  `);
16180
- else io.stdout(renderAuditText(summary, { color: o.color, licensed: Boolean(claims), files }));
16575
+ else io.stdout(renderAuditText(summary, { color: o.color, licensed: Boolean(claims), files, controls: controlHeadline(evidence) }));
16181
16576
  return 0;
16182
16577
  }
16183
16578
 
@@ -16253,8 +16648,12 @@ Usage:
16253
16648
  threadctx explain <file> [--tool <id>|all] [--surface cloud-agent|code-review|chat]
16254
16649
  What each agent loads for this file, in precedence order
16255
16650
  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)
16651
+ threadctx fix [path] [--apply] [--output <patch>] [--pr]
16652
+ Safe fixes as a patch (never commits; --apply writes files;
16653
+ --pr opens a pull request with them, using git and gh)
16654
+ threadctx init [path] [--pr] [--no-badge] [--force]
16655
+ Add the GitHub Action workflow and a README grade badge
16656
+ (--pr opens a pull request instead of writing files)
16258
16657
  threadctx rules [id] List rules, or show one
16259
16658
  threadctx tools List tool adapters and when each was verified
16260
16659
  threadctx pack validate <file> Check a rule pack before using it
@@ -16282,6 +16681,9 @@ var OPTIONS = {
16282
16681
  surface: { type: "string" },
16283
16682
  path: { type: "string" },
16284
16683
  apply: { type: "boolean" },
16684
+ pr: { type: "boolean" },
16685
+ "no-badge": { type: "boolean" },
16686
+ force: { type: "boolean" },
16285
16687
  json: { type: "boolean" },
16286
16688
  color: { type: "boolean" },
16287
16689
  "no-color": { type: "boolean" },
@@ -16292,7 +16694,7 @@ var OPTIONS = {
16292
16694
  };
16293
16695
  async function main(argv, io) {
16294
16696
  try {
16295
- return await run(argv, io);
16697
+ return await run2(argv, io);
16296
16698
  } catch (e) {
16297
16699
  if (e instanceof UsageError || e instanceof ConfigError || e instanceof PackError) {
16298
16700
  io.stderr(`threadctx: ${e.message}
@@ -16305,7 +16707,7 @@ Please report this at https://github.com/threadctx-dev/ctx/issues
16305
16707
  return 2;
16306
16708
  }
16307
16709
  }
16308
- async function run(argv, io) {
16710
+ async function run2(argv, io) {
16309
16711
  let parsed;
16310
16712
  try {
16311
16713
  parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
@@ -16346,6 +16748,8 @@ Run 'threadctx --help' for usage.`);
16346
16748
  return cmdDiff(v, io, color);
16347
16749
  case "fix":
16348
16750
  return cmdFix(args[0], v, io);
16751
+ case "init":
16752
+ return cmdInit(args[0], v, io);
16349
16753
  case "rules":
16350
16754
  return cmdRules(args[0], v, io);
16351
16755
  case "tools":
@@ -16359,7 +16763,7 @@ Run 'threadctx --help' for usage.`);
16359
16763
  }
16360
16764
  function openRoot(pathArg, io) {
16361
16765
  const target = resolve4(io.cwd, pathArg ?? ".");
16362
- if (!existsSync3(target)) throw new UsageError(`path not found: ${pathArg}`);
16766
+ if (!existsSync4(target)) throw new UsageError(`path not found: ${pathArg}`);
16363
16767
  if (!statSync3(target).isDirectory()) throw new UsageError(`not a directory: ${pathArg} (scan takes a repository or directory)`);
16364
16768
  return openRepo(target);
16365
16769
  }
@@ -16408,8 +16812,8 @@ async function cmdScan(pathArg, v, io, color) {
16408
16812
  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
16813
  if (v.output) {
16410
16814
  const dest = resolve4(io.cwd, v.output);
16411
- mkdirSync2(dirname(dest), { recursive: true });
16412
- writeFileSync2(dest, out);
16815
+ mkdirSync3(dirname2(dest), { recursive: true });
16816
+ writeFileSync3(dest, out);
16413
16817
  io.stderr(`Wrote ${format} report to ${relative3(io.cwd, dest) || dest} \u2014 grade ${result.grade}, ${result.counts.blocker} blocker, ${result.counts.warning} warning
16414
16818
  `);
16415
16819
  } else {
@@ -16434,7 +16838,7 @@ function cmdCompare(baseFile, headFile, v, io) {
16434
16838
  if (!["text", "md", "json"].includes(format)) throw new UsageError("--format must be text, md or json");
16435
16839
  const readScan = (file) => {
16436
16840
  const abs = resolve4(io.cwd, file);
16437
- if (!existsSync3(abs)) throw new UsageError(`file not found: ${file}`);
16841
+ if (!existsSync4(abs)) throw new UsageError(`file not found: ${file}`);
16438
16842
  try {
16439
16843
  return parseScanJson(readFileSync3(abs, "utf8"), file);
16440
16844
  } catch (e) {
@@ -16463,15 +16867,15 @@ function cmdCompare(baseFile, headFile, v, io) {
16463
16867
  }
16464
16868
  if (v.output) {
16465
16869
  const dest = resolve4(io.cwd, v.output);
16466
- mkdirSync2(dirname(dest), { recursive: true });
16467
- writeFileSync2(dest, out);
16870
+ mkdirSync3(dirname2(dest), { recursive: true });
16871
+ writeFileSync3(dest, out);
16468
16872
  } else io.stdout(out);
16469
16873
  return compareExitCode(c, failOn);
16470
16874
  }
16471
16875
  function defaultBaseline(org, outDir, license, io) {
16472
16876
  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;
16877
+ const file = join5(resolve4(io.cwd, outDir ?? `threadctx-audit-${org}`), "audit.json");
16878
+ return existsSync4(file) && findLicense(license, io) ? file : void 0;
16475
16879
  }
16476
16880
  async function cmdAudit(v, io, color) {
16477
16881
  if (!v.org) throw new UsageError("usage: threadctx audit --org <github-org-or-user>");
@@ -16520,11 +16924,11 @@ function locate(fileArg, io) {
16520
16924
  }
16521
16925
  };
16522
16926
  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);
16927
+ const abs = existsSync4(given) ? real(given) : join5(real(dirname2(given)), basename(given));
16928
+ const root = real(gitRoot(existsSync4(abs) && statSync3(abs).isDirectory() ? abs : dirname2(abs)) ?? io.cwd);
16525
16929
  const rel = relative3(root, abs).split(sep3).join("/");
16526
16930
  if (rel.startsWith("..")) throw new UsageError(`${fileArg} is outside the repository at ${root}`);
16527
- const isDir = existsSync3(abs) && statSync3(abs).isDirectory();
16931
+ const isDir = existsSync4(abs) && statSync3(abs).isDirectory();
16528
16932
  return { repo: openRepo(root), target: { path: rel === "" ? "" : rel, isDir } };
16529
16933
  }
16530
16934
  function contextsFor(repo, target, toolArg, surface) {
@@ -16596,14 +17000,32 @@ function cmdFix(pathArg, v, io) {
16596
17000
  io.stderr("No safe fixes to apply.\n");
16597
17001
  return 0;
16598
17002
  }
17003
+ if (v.pr) {
17004
+ const after = new Map([...plan.files].map(([p, f]) => [p, f.after]));
17005
+ const byRule = /* @__PURE__ */ new Map();
17006
+ for (const f of plan.applied) byRule.set(f.ruleId, (byRule.get(f.ruleId) ?? 0) + 1);
17007
+ const n2 = plan.applied.length;
17008
+ const body = [
17009
+ `This pull request applies ${n2} safe, mechanical fix${n2 === 1 ? "" : "es"} to the instructions AI coding agents read in this repository.`,
17010
+ "",
17011
+ "| Rule | Fixes | What it fixes |",
17012
+ "|---|---|---|",
17013
+ ...[...byRule].sort().map(([id, c]) => `| [${id}](https://threadctx.dev/rules/${id}) | ${c} | ${RULES.find((r) => r.id === id)?.title ?? ""} |`),
17014
+ "",
17015
+ `Grade before: **${result.grade}** (${result.score}/100). Every change is a deterministic edit; review the diff as usual.`,
17016
+ "",
17017
+ "<sub>Generated with [threadctx](https://threadctx.dev), which grades what every coding agent is told. Run `npx threadctx scan` to check locally.</sub>"
17018
+ ].join("\n");
17019
+ 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);
17020
+ }
16599
17021
  if (v.apply) {
16600
- for (const [p, { after }] of plan.files) writeFileSync2(join4(repo.root, p), after);
17022
+ for (const [p, { after }] of plan.files) writeFileSync3(join5(repo.root, p), after);
16601
17023
  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
17024
  `);
16603
17025
  return 0;
16604
17026
  }
16605
17027
  if (v.output) {
16606
- writeFileSync2(resolve4(io.cwd, v.output), plan.patch);
17028
+ writeFileSync3(resolve4(io.cwd, v.output), plan.patch);
16607
17029
  io.stderr(`Wrote ${plan.applied.length} fix${plan.applied.length === 1 ? "" : "es"} to ${v.output}. Apply with: git apply ${v.output}
16608
17030
  `);
16609
17031
  } else {
@@ -16613,6 +17035,71 @@ function cmdFix(pathArg, v, io) {
16613
17035
  }
16614
17036
  return 0;
16615
17037
  }
17038
+ function withPr(open, io) {
17039
+ try {
17040
+ const url = open();
17041
+ io.stdout(`${url}
17042
+ `);
17043
+ io.stderr("Pull request opened. Nothing else in your working tree was changed.\n");
17044
+ return 0;
17045
+ } catch (e) {
17046
+ if (e instanceof PrError) throw new UsageError(e.message);
17047
+ throw e;
17048
+ }
17049
+ }
17050
+ function isPublicOnGitHub(root, env) {
17051
+ try {
17052
+ return execFileSync5("gh", ["repo", "view", "--json", "visibility", "--jq", ".visibility"], { cwd: root, env, stdio: ["ignore", "pipe", "ignore"], timeout: 15e3 }).toString().trim() === "PUBLIC";
17053
+ } catch {
17054
+ return false;
17055
+ }
17056
+ }
17057
+ function cmdInit(pathArg, v, io) {
17058
+ const repo = openRoot(pathArg, io);
17059
+ const files = /* @__PURE__ */ new Map();
17060
+ const notes = [];
17061
+ if (existsSync4(join5(repo.root, WORKFLOW_PATH)) && !v.force) notes.push(`${WORKFLOW_PATH} already exists (use --force to replace it)`);
17062
+ else files.set(WORKFLOW_PATH, workflowYaml());
17063
+ if (!v["no-badge"]) {
17064
+ const result = doScan(repo, v, io);
17065
+ const fullName = githubRemote(repo.root);
17066
+ const badge = fullName && isPublicOnGitHub(repo.root, io.env) ? renderLiveBadge(fullName) : renderBadge(result, badgeLinkFor(fullName));
17067
+ const readmeName = ["README.md", "readme.md", "Readme.md"].find((n2) => existsSync4(join5(repo.root, n2)));
17068
+ if (!readmeName) notes.push(`no README.md; add this badge where you like:
17069
+ ${badge.markdown}`);
17070
+ else {
17071
+ const before = readFileSync3(join5(repo.root, readmeName), "utf8");
17072
+ const after = withBadge(before, badge.markdown);
17073
+ if (after === before) notes.push(`${readmeName} already has an agent context badge`);
17074
+ else files.set(readmeName, after);
17075
+ }
17076
+ }
17077
+ for (const n2 of notes) io.stderr(`note: ${n2}
17078
+ `);
17079
+ if (files.size === 0) {
17080
+ io.stderr("Nothing to add.\n");
17081
+ return 0;
17082
+ }
17083
+ if (v.pr) {
17084
+ const body = [
17085
+ "Adds an agent context check to this repository:",
17086
+ "",
17087
+ ...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.`] : [],
17088
+ ...[...files.keys()].some((p) => p !== WORKFLOW_PATH) ? ["- A README badge showing the current grade."] : [],
17089
+ "",
17090
+ "No code or secrets leave the runner. <sub>[threadctx](https://threadctx.dev)</sub>"
17091
+ ].join("\n");
17092
+ 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);
17093
+ }
17094
+ for (const [p, content] of files) {
17095
+ mkdirSync3(dirname2(join5(repo.root, p)), { recursive: true });
17096
+ writeFileSync3(join5(repo.root, p), content);
17097
+ io.stderr(`wrote ${p}
17098
+ `);
17099
+ }
17100
+ io.stderr("Commit these files to turn on the check. Nothing was committed.\n");
17101
+ return 0;
17102
+ }
16616
17103
  function cmdRules(id, v, io) {
16617
17104
  if (id) {
16618
17105
  const r = RULES.find((x) => x.id.toLowerCase() === id.toLowerCase());
@@ -16651,7 +17138,7 @@ function cmdTools(v, io) {
16651
17138
  }
16652
17139
  function cmdPackValidate(file, io) {
16653
17140
  const abs = resolve4(io.cwd, file);
16654
- if (!existsSync3(abs)) throw new UsageError(`file not found: ${file}`);
17141
+ if (!existsSync4(abs)) throw new UsageError(`file not found: ${file}`);
16655
17142
  const pack = parsePack(readFileSync3(abs, "utf8"), file);
16656
17143
  io.stdout(`${pack.pack}: ${pack.rules.length} rule${pack.rules.length === 1 ? "" : "s"} valid
16657
17144
  `);
@@ -16662,7 +17149,7 @@ function cmdPackValidate(file, io) {
16662
17149
  var UPGRADE_URL = "https://threadctx.dev/pricing";
16663
17150
  function maybeUpgradeLine(result, io, remote) {
16664
17151
  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");
17152
+ const stateFile = join5(io.env.THREADCTX_HOME ?? join5(homedir2(), ".threadctx"), "state.json");
16666
17153
  let state = {};
16667
17154
  try {
16668
17155
  state = JSON.parse(readFileSync3(stateFile, "utf8"));
@@ -16676,8 +17163,8 @@ function maybeUpgradeLine(result, io, remote) {
16676
17163
  ${msg}
16677
17164
  `);
16678
17165
  try {
16679
- mkdirSync2(dirname(stateFile), { recursive: true });
16680
- writeFileSync2(stateFile, JSON.stringify({ ...state, lastUpsell: today }));
17166
+ mkdirSync3(dirname2(stateFile), { recursive: true });
17167
+ writeFileSync3(stateFile, JSON.stringify({ ...state, lastUpsell: today }));
16681
17168
  } catch {
16682
17169
  }
16683
17170
  }