threadctx 0.2.0 → 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
@@ -12182,6 +12182,11 @@ function renderAuditText(s, opts) {
12182
12182
  const out = [];
12183
12183
  out.push(`${p.bold(`Agent context audit: ${s.org}`)}`, "");
12184
12184
  out.push(`${gradeColor(p.bold(`Fleet grade ${s.fleet.grade}`))} ${p.dim(`(${s.fleet.score}/100 average)`)}`);
12185
+ if (s.trend) {
12186
+ const t = s.trend;
12187
+ const d = t.after.score - t.before.score;
12188
+ out.push(`${p.bold(`Since ${t.since.slice(0, 10)}:`)} ${t.before.grade} \u2192 ${t.after.grade} (${d > 0 ? "+" : ""}${d}) \xB7 ${t.improved.length} improved \xB7 ${t.regressed.length} got worse \xB7 blockers ${t.before.blockers} \u2192 ${t.after.blockers}${t.added.length ? ` \xB7 ${t.added.length} new` : ""}`);
12189
+ }
12185
12190
  out.push(`${plural(s.repos.scanned, "repository", "repositories")} scanned \xB7 ${s.repos.withContext} with agent context \xB7 ${s.repos.withoutContext} without${s.repos.failed ? ` \xB7 ${s.repos.failed} could not be read` : ""}`);
12186
12191
  out.push(`${plural(s.fleet.counts.blocker, "blocker")} \xB7 ${plural(s.fleet.counts.warning, "warning")} \xB7 ${n(s.fleet.counts.info)} info`);
12187
12192
  if (s.repos.withContext)
@@ -12203,11 +12208,15 @@ function renderAuditText(s, opts) {
12203
12208
  for (const r of worst)
12204
12209
  out.push(` ${r.grade} ${String(r.score).padStart(3)} ${r.repo}`);
12205
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
+ }
12206
12215
  out.push("");
12207
12216
  if (opts.licensed) {
12208
12217
  out.push(p.green("Full report written:"), ...(opts.files ?? []).map((f) => ` ${f}`));
12209
12218
  } else {
12210
- 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>`));
12211
12220
  }
12212
12221
  return `${out.join("\n")}
12213
12222
  `;
@@ -12290,7 +12299,18 @@ function renderAuditHtml(s, repos) {
12290
12299
  <div class="stat"><b>${s.fleet.counts.warning}</b><span class="muted">warnings</span></div>
12291
12300
  <div class="stat"><b>${s.fleet.multiToolRepos}</b><span class="muted">maintain files for 2+ agents</span></div>
12292
12301
  <div class="stat"><b>${auto}</b><span class="muted">auto-fixable</span></div></div></div>`);
12293
- sections.push(`<h2>Summary</h2><ul>${takeaways(s).map((t) => `<li>${t.includes("<code>") ? t : esc(t)}</li>`).join("")}</ul>`);
12302
+ if (s.trend) {
12303
+ const t = s.trend;
12304
+ const d = t.after.score - t.before.score;
12305
+ const row = (x) => `<tr><td>${esc(x.repo)}</td><td>${x.from} \u2192 ${x.to}</td><td>${x.to - x.from > 0 ? "+" : ""}${x.to - x.from}</td></tr>`;
12306
+ sections.push(`<h2>Since the last audit (${esc(t.since.slice(0, 10))})</h2>
12307
+ <div class="stats"><div class="stat"><b>${esc(t.before.grade)} \u2192 ${esc(t.after.grade)}</b><span class="muted">fleet grade (${d > 0 ? "+" : ""}${d})</span></div><div class="stat"><b>${t.before.blockers} \u2192 ${t.after.blockers}</b><span class="muted">blockers</span></div><div class="stat"><b>${t.before.warnings} \u2192 ${t.after.warnings}</b><span class="muted">warnings</span></div><div class="stat"><b>${t.before.withContext} \u2192 ${t.after.withContext}</b><span class="muted">repos with context</span></div></div>
12308
+ ${t.regressed.length ? `<h3>Got worse (${t.regressed.length})</h3><table><tr><th>Repository</th><th>Score</th><th>Change</th></tr>${t.regressed.map(row).join("")}</table>` : ""}
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>` : ""}
12310
+ ${t.added.length ? `<p class="small muted">New since then: ${t.added.map(esc).join(", ")}</p>` : ""}`);
12311
+ }
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>`);
12294
12314
  if (s.plan.length) {
12295
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>
12296
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>`);
@@ -12333,194 +12353,6 @@ function renderAuditHtml(s, repos) {
12333
12353
  `;
12334
12354
  }
12335
12355
 
12336
- // ../report/dist/index.js
12337
- var RULE_DOCS = "https://threadctx.dev/rules";
12338
- function renderJson(result) {
12339
- return `${JSON.stringify(result, null, 2)}
12340
- `;
12341
- }
12342
- var SARIF_LEVEL = { blocker: "error", warning: "warning", info: "note" };
12343
- var SECURITY_SEVERITY = { blocker: "9.0", warning: "5.0", info: "2.0" };
12344
- function renderSarif(result) {
12345
- const rules = [...result.rules].sort((a, b) => a.id < b.id ? -1 : 1);
12346
- const index = new Map(rules.map((r, i) => [r.id, i]));
12347
- const sarif = {
12348
- $schema: "https://json.schemastore.org/sarif-2.1.0.json",
12349
- version: "2.1.0",
12350
- runs: [
12351
- {
12352
- tool: {
12353
- driver: {
12354
- name: "threadctx",
12355
- semanticVersion: result.engine.version,
12356
- informationUri: "https://threadctx.dev",
12357
- rules: rules.map((r) => sarifRule(r))
12358
- }
12359
- },
12360
- automationDetails: { id: "threadctx/agent-context/" },
12361
- results: result.findings.map((f) => sarifResult(f, index.get(f.ruleId))),
12362
- properties: { grade: result.grade, score: result.score, registry: result.engine.registry }
12363
- }
12364
- ]
12365
- };
12366
- return `${JSON.stringify(sarif, null, 2)}
12367
- `;
12368
- }
12369
- function sarifRule(r) {
12370
- const tags = [.../* @__PURE__ */ new Set(["agent-context", r.family, r.determinism])];
12371
- return {
12372
- id: r.id,
12373
- name: r.id.replace(/[^A-Za-z0-9]/g, ""),
12374
- shortDescription: { text: r.title },
12375
- fullDescription: { text: r.rationale },
12376
- helpUri: r.id.startsWith("CTX-") ? `${RULE_DOCS}/${r.id}` : void 0,
12377
- help: { text: `${r.remediation}
12378
-
12379
- Source: ${r.citation}`, markdown: `${r.remediation}
12380
-
12381
- Source: ${r.citation}` },
12382
- defaultConfiguration: { level: SARIF_LEVEL[r.severity] },
12383
- properties: { tags, precision: r.determinism === "deterministic" ? "high" : "medium", ...r.family === "security" ? { "security-severity": SECURITY_SEVERITY[r.severity] } : {} }
12384
- };
12385
- }
12386
- function sarifResult(f, ruleIndex) {
12387
- const location = (path, line, endLine) => ({
12388
- physicalLocation: {
12389
- // Repository-level findings point at the root so code scanning still accepts them.
12390
- artifactLocation: { uri: path || ".", uriBaseId: "%SRCROOT%" },
12391
- ...line ? { region: { startLine: line, ...endLine && endLine > line ? { endLine } : {} } } : {}
12392
- }
12393
- });
12394
- return {
12395
- ruleId: f.ruleId,
12396
- ...ruleIndex !== void 0 ? { ruleIndex } : {},
12397
- level: SARIF_LEVEL[f.severity],
12398
- message: { text: f.evidence ? `${f.message}
12399
-
12400
- Evidence: ${f.evidence}` : f.message },
12401
- locations: [location(f.path, f.line, f.endLine)],
12402
- ...f.related?.length ? { relatedLocations: f.related.map((r, i) => ({ id: i + 1, ...location(r.path, r.line), message: { text: r.message ?? "related" } })) } : {},
12403
- partialFingerprints: { "threadctx/v1": f.fingerprint },
12404
- ...f.suppressed ? { suppressions: [{ kind: f.suppressed.source === "inline" ? "inSource" : "external", justification: f.suppressed.reason }] } : {}
12405
- };
12406
- }
12407
- function painter(color) {
12408
- const wrap = (code2) => (s) => color ? `\x1B[${code2}m${s}\x1B[0m` : s;
12409
- return { red: wrap("31"), yellow: wrap("33"), blue: wrap("34"), green: wrap("32"), dim: wrap("2"), bold: wrap("1"), cyan: wrap("36") };
12410
- }
12411
- var GRADE_COLOR = { A: "green", B: "green", C: "yellow", D: "yellow", F: "red" };
12412
- function renderText(result, opts) {
12413
- const p = painter(opts.color);
12414
- const out = [];
12415
- const open = result.findings.filter((f) => !f.suppressed);
12416
- const shown = opts.verbose ? open : open.filter((f) => f.severity !== "info");
12417
- const sev2 = { blocker: p.red("blocker"), warning: p.yellow("warning"), info: p.blue("info ") };
12418
- let lastPath;
12419
- for (const f of shown) {
12420
- if (f.path !== lastPath) {
12421
- out.push("", p.bold(f.path || "(repository)"));
12422
- lastPath = f.path;
12423
- }
12424
- const loc = f.line ? p.dim(`${String(f.line).padStart(4)}:`) : p.dim(" ");
12425
- const fix = f.fix?.kind === "safe" ? p.green(" [fixable]") : "";
12426
- out.push(`${loc} ${sev2[f.severity]} ${f.message} ${p.dim(f.ruleId)}${fix}`);
12427
- if (f.evidence)
12428
- out.push(` ${p.dim(`> ${f.evidence}`)}`);
12429
- }
12430
- const hiddenInfo = open.length - shown.length;
12431
- const { blocker, warning, info, suppressed } = result.counts;
12432
- out.push("");
12433
- 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)`) : ""));
12434
- const fixable = open.filter((f) => f.fix?.kind === "safe").length;
12435
- if (fixable)
12436
- out.push(p.dim(`${fixable} finding${fixable === 1 ? "" : "s"} can be fixed automatically: threadctx fix`));
12437
- const tools = result.tools.filter((t) => t.layers > 0);
12438
- if (tools.length) {
12439
- out.push(p.dim(`Always-loaded context (estimated tokens): ${tools.map((t) => `${t.label.split(" (")[0]} \u2248${t.alwaysTokenEstimate.toLocaleString("en-US")}`).join(" \xB7 ")}`));
12440
- }
12441
- for (const d of result.diagnostics) {
12442
- const tag = d.level === "error" ? p.red("error") : d.level === "warning" ? p.yellow("note") : p.dim("note");
12443
- out.push(`${tag} ${d.path ? `${d.path}${d.line ? `:${d.line}` : ""}: ` : ""}${d.message}`);
12444
- }
12445
- return `${out.join("\n").replace(/^\n/, "")}
12446
- `;
12447
- }
12448
- var SEV_ICON = { blocker: "\u{1F534}", warning: "\u{1F7E1}", info: "\u{1F535}" };
12449
- function mdEscape(s) {
12450
- return s.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
12451
- }
12452
- function renderMarkdown(result, opts = {}) {
12453
- const out = [];
12454
- const open = result.findings.filter((f) => !f.suppressed);
12455
- 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})` : "";
12456
- out.push(`### Agent context: grade **${result.grade}** \xB7 ${result.score}/100${delta}`);
12457
- out.push("");
12458
- out.push(`${result.counts.blocker} blocker \xB7 ${result.counts.warning} warning \xB7 ${result.counts.info} info${result.counts.suppressed ? ` \xB7 ${result.counts.suppressed} suppressed` : ""}`);
12459
- const list = opts.newFingerprints ? open.filter((f) => opts.newFingerprints.has(f.fingerprint)) : open;
12460
- if (opts.newFingerprints)
12461
- out.push("", `**${list.length} new** in this change${open.length > list.length ? ` (${open.length - list.length} existing not shown)` : ""}.`);
12462
- const max = opts.maxFindings ?? 50;
12463
- if (list.length) {
12464
- out.push("", "| | Rule | Location | Finding |", "|---|---|---|---|");
12465
- for (const f of list.slice(0, max)) {
12466
- const rule = f.ruleId.startsWith("CTX-") ? `[${f.ruleId}](${RULE_DOCS}/${f.ruleId})` : f.ruleId;
12467
- out.push(`| ${SEV_ICON[f.severity]} | ${rule} | \`${mdEscape(f.path || ".")}${f.line ? `:${f.line}` : ""}\` | ${mdEscape(f.message)} |`);
12468
- }
12469
- if (list.length > max)
12470
- out.push("", `\u2026and ${list.length - max} more. Run \`npx threadctx scan\` locally for the full list.`);
12471
- }
12472
- const tools = result.tools.filter((t) => t.layers > 0);
12473
- if (tools.length) {
12474
- out.push("", "<details><summary>What each agent loads at the repository root (estimated tokens)</summary>", "");
12475
- for (const t of tools)
12476
- out.push(`- ${t.label}: \u2248${t.alwaysTokenEstimate.toLocaleString("en-US")} tokens across ${t.layers} file${t.layers === 1 ? "" : "s"}`);
12477
- out.push("", "</details>");
12478
- }
12479
- 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>`);
12480
- return `${out.join("\n")}
12481
- `;
12482
- }
12483
- var LOAD_LABEL = { always: "always", "on-demand": "on demand", conditional: "matches", "agent-decides": "agent decides" };
12484
- function renderEffective(contexts, opts) {
12485
- const p = painter(opts.color);
12486
- const out = [];
12487
- for (const { label: label2, ctx } of contexts) {
12488
- out.push(p.bold(`${label2}`) + p.dim(` ${ctx.targetPath} \u2248${ctx.tokenEstimate.toLocaleString("en-US")} tokens (estimate)`));
12489
- if (!ctx.layers.length)
12490
- out.push(p.dim(" (loads nothing from this repository)"));
12491
- for (const l of ctx.layers) {
12492
- 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)}`);
12493
- }
12494
- for (const n2 of ctx.notes)
12495
- out.push(p.dim(` note: ${n2}`));
12496
- out.push("");
12497
- }
12498
- return out.join("\n");
12499
- }
12500
- function renderFactTable(rows, tools, opts) {
12501
- const p = painter(opts.color);
12502
- if (!rows.length)
12503
- return p.dim("No comparable facts (commands, package manager, versions) found.\n");
12504
- const width = 26;
12505
- const head = `${"".padEnd(18)}${tools.map((t) => t.padEnd(width)).join("")}`;
12506
- const lines = [p.bold(head)];
12507
- for (const r of rows) {
12508
- const vals = tools.map((t) => r.values[t]?.length ? r.values[t].join(", ") : "\u2014");
12509
- const differ = new Set(vals.filter((v) => v !== "\u2014")).size > 1;
12510
- const cells = vals.map((v) => (v.length > width - 2 ? `${v.slice(0, width - 3)}\u2026` : v).padEnd(width));
12511
- lines.push(`${differ ? p.red(r.topic.padEnd(18)) : r.topic.padEnd(18)}${cells.join("")}${differ ? p.red(" \u2190 differs") : ""}`);
12512
- }
12513
- return `${lines.join("\n")}
12514
- `;
12515
- }
12516
- var BADGE_COLOR = { A: "brightgreen", B: "green", C: "yellow", D: "orange", F: "red" };
12517
- var BADGE_LINK = "https://www.npmjs.com/package/threadctx";
12518
- function renderBadge(result, link = BADGE_LINK) {
12519
- const url = `https://img.shields.io/badge/agent%20context-${result.grade}%20%C2%B7%20${result.score}-${BADGE_COLOR[result.grade]}`;
12520
- const alt = `Agent context grade ${result.grade}`;
12521
- return { url, markdown: `[![${alt}](${url})](${link})`, html: `<a href="${link}"><img src="${url}" alt="${alt}"></a>` };
12522
- }
12523
-
12524
12356
  // ../rules/dist/benchmark.js
12525
12357
  var BENCHMARK = {
12526
12358
  "CTX-B001": {
@@ -14899,7 +14731,7 @@ function applySuppressions(findings, inline, config, now, diagnostics) {
14899
14731
  }
14900
14732
 
14901
14733
  // ../rules/dist/version.js
14902
- var ENGINE_VERSION = "0.2.0";
14734
+ var ENGINE_VERSION = "0.3.0";
14903
14735
  var REGISTRY_VERSION = "2026.10.1";
14904
14736
 
14905
14737
  // ../rules/dist/engine.js
@@ -15084,6 +14916,29 @@ function exitCodeFor(result, failOn) {
15084
14916
  }
15085
14917
 
15086
14918
  // ../rules/dist/audit.js
14919
+ function fleetTrend(previous, current) {
14920
+ const prev = new Map(previous.repoTable.map((r) => [r.repo, r.score]));
14921
+ const cur = new Map(current.repoTable.map((r) => [r.repo, r.score]));
14922
+ const improved = [];
14923
+ const regressed = [];
14924
+ for (const [repo, to] of cur) {
14925
+ const from = prev.get(repo);
14926
+ if (from === void 0 || from === to)
14927
+ continue;
14928
+ (to > from ? improved : regressed).push({ repo, from, to });
14929
+ }
14930
+ const byDelta = (a, b) => Math.abs(b.to - b.from) - Math.abs(a.to - a.from) || (a.repo < b.repo ? -1 : 1);
14931
+ const snap = (s) => ({ grade: s.fleet.grade, score: s.fleet.score, blockers: s.fleet.counts.blocker, warnings: s.fleet.counts.warning, withContext: s.repos.withContext });
14932
+ return {
14933
+ since: previous.generatedAt,
14934
+ before: snap(previous),
14935
+ after: snap(current),
14936
+ improved: improved.sort(byDelta),
14937
+ regressed: regressed.sort(byDelta),
14938
+ added: [...cur.keys()].filter((r) => !prev.has(r)).sort(),
14939
+ removed: [...prev.keys()].filter((r) => !cur.has(r)).sort()
14940
+ };
14941
+ }
15087
14942
  var PENALTY = { blocker: 25, warning: 5, info: 1 };
15088
14943
  var EFFORT_COST = { automatic: 1, quick: 2, manual: 4 };
15089
14944
  var LABELS = {
@@ -15273,6 +15128,471 @@ function summarizeFleet(repos, meta2) {
15273
15128
  };
15274
15129
  }
15275
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
+
15276
15596
  // ../../node_modules/.pnpm/diff@9.0.0/node_modules/diff/libesm/diff/base.js
15277
15597
  var Diff = class {
15278
15598
  diff(oldStr, newStr, options = {}) {
@@ -15831,11 +16151,116 @@ function planFixes(fs, findings, kinds = ["safe"]) {
15831
16151
  return { files, applied: [...applied], skipped, patch };
15832
16152
  }
15833
16153
 
15834
- // 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
15835
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";
15836
16261
  function git(root, args) {
15837
16262
  try {
15838
- 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();
15839
16264
  } catch {
15840
16265
  return void 0;
15841
16266
  }
@@ -15856,9 +16281,14 @@ function gitHistory(root) {
15856
16281
  }
15857
16282
  };
15858
16283
  }
16284
+ function githubRemote(dir) {
16285
+ const url = git(dir, ["remote", "get-url", "origin"]);
16286
+ const m = url?.match(/github\.com[:/]([A-Za-z0-9-]{1,39})\/([A-Za-z0-9_.-]{1,100}?)(?:\.git)?$/);
16287
+ return m ? `${m[1]}/${m[2]}` : void 0;
16288
+ }
15859
16289
 
15860
16290
  // src/mcp.ts
15861
- import { existsSync, realpathSync, statSync as statSync2 } from "node:fs";
16291
+ import { existsSync as existsSync2, realpathSync, statSync as statSync2 } from "node:fs";
15862
16292
  import { isAbsolute, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
15863
16293
  var SUPPORTED_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
15864
16294
  var MAX_TEXT = 2e4;
@@ -15898,7 +16328,7 @@ function clip(text) {
15898
16328
  function confine(root, input) {
15899
16329
  const realRoot = realpathSync(root);
15900
16330
  const abs = resolve2(realRoot, input);
15901
- const real = existsSync(abs) ? realpathSync(abs) : abs;
16331
+ const real = existsSync2(abs) ? realpathSync(abs) : abs;
15902
16332
  const rel = relative2(realRoot, real);
15903
16333
  if (rel === ".." || rel.startsWith(`..${sep2}`) || isAbsolute(rel)) throw new Error("path is outside the project");
15904
16334
  return real;
@@ -15923,7 +16353,7 @@ function callTool(name, args, root) {
15923
16353
  if (typeof args.file !== "string" || !args.file) throw new Error("file is required");
15924
16354
  const abs = confine(root, args.file);
15925
16355
  const rel = relative2(realpathSync(root), abs).split(sep2).join("/");
15926
- const isDir = existsSync(abs) && statSync2(abs).isDirectory();
16356
+ const isDir = existsSync2(abs) && statSync2(abs).isDirectory();
15927
16357
  const repo = openRepo(root);
15928
16358
  const state = prepare(repo);
15929
16359
  const tool = typeof args.tool === "string" && args.tool !== "all" ? args.tool : void 0;
@@ -16021,16 +16451,17 @@ async function serveMcp(io) {
16021
16451
  }
16022
16452
 
16023
16453
  // src/audit.ts
16024
- 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";
16025
16455
  import { homedir } from "node:os";
16026
- 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";
16027
16458
 
16028
16459
  // src/remote.ts
16029
- import { execFileSync as execFileSync3 } from "node:child_process";
16460
+ import { execFileSync as execFileSync4 } from "node:child_process";
16030
16461
  function githubToken(env) {
16031
16462
  if (env.GH_TOKEN || env.GITHUB_TOKEN) return env.GH_TOKEN ?? env.GITHUB_TOKEN;
16032
16463
  try {
16033
- 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;
16034
16465
  } catch {
16035
16466
  return void 0;
16036
16467
  }
@@ -16041,14 +16472,14 @@ var AuditUsageError = class extends Error {
16041
16472
  };
16042
16473
  var ORG = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
16043
16474
  function findLicense(arg, io) {
16044
- const fromFile = (p) => existsSync2(p) ? readFileSync2(p, "utf8").trim() : void 0;
16475
+ const fromFile = (p) => existsSync3(p) ? readFileSync2(p, "utf8").trim() : void 0;
16045
16476
  if (arg) {
16046
16477
  const file = resolve3(io.cwd, arg);
16047
16478
  const key2 = arg.startsWith("tctx1.") ? arg : fromFile(file);
16048
16479
  return key2 ? { key: key2, source: arg.startsWith("tctx1.") ? "--license" : arg } : { key: arg, source: "--license" };
16049
16480
  }
16050
16481
  if (io.env.THREADCTX_LICENSE) return { key: io.env.THREADCTX_LICENSE.trim(), source: "THREADCTX_LICENSE" };
16051
- const home = join3(io.env.THREADCTX_HOME ?? join3(homedir(), ".threadctx"), "license");
16482
+ const home = join4(io.env.THREADCTX_HOME ?? join4(homedir(), ".threadctx"), "license");
16052
16483
  const key = fromFile(home);
16053
16484
  return key ? { key, source: home } : void 0;
16054
16485
  }
@@ -16068,6 +16499,19 @@ async function runAudit(o, io) {
16068
16499
  else io.stderr(`note: the licence from ${found.source} ${LICENSE_PROBLEM[check.reason]}; running the free audit.
16069
16500
  `);
16070
16501
  }
16502
+ let previous;
16503
+ if (o.baseline) {
16504
+ if (!claims) throw new AuditUsageError("--baseline compares two full audits and needs a licence (the free audit has no audit.json to compare).");
16505
+ const file = resolve3(io.cwd, o.baseline);
16506
+ if (!existsSync3(file)) throw new AuditUsageError(`baseline not found: ${o.baseline}`);
16507
+ try {
16508
+ const parsed = JSON.parse(readFileSync2(file, "utf8"));
16509
+ if (parsed.schema !== "threadctx.audit/v1") throw new Error("schema");
16510
+ previous = parsed;
16511
+ } catch {
16512
+ throw new AuditUsageError(`${o.baseline} is not a threadctx audit.json`);
16513
+ }
16514
+ }
16071
16515
  const token = githubToken(io.env);
16072
16516
  if (!token) io.stderr("note: no GitHub token found (set GH_TOKEN or run 'gh auth login'). Only public repositories will be read, with a low rate limit.\n");
16073
16517
  let listing;
@@ -16098,20 +16542,37 @@ async function runAudit(o, io) {
16098
16542
  }
16099
16543
  });
16100
16544
  const summary = summarizeFleet(repos, { org: o.org, generatedAt: io.now().toISOString(), engine: { version: ENGINE_VERSION, registry: REGISTRY_VERSION } });
16545
+ if (previous) {
16546
+ if (previous.org.toLowerCase() !== o.org.toLowerCase()) io.stderr(`note: the baseline is for ${previous.org}, not ${o.org}; comparing anyway.
16547
+ `);
16548
+ summary.trend = fleetTrend(previous, summary);
16549
+ }
16550
+ const evidence = evidencePack(summary, repos);
16101
16551
  const files = [];
16102
16552
  if (claims) {
16103
16553
  const dir = resolve3(io.cwd, o.outDir ?? `threadctx-audit-${o.org}`);
16104
- mkdirSync(dir, { recursive: true });
16105
- for (const [name, body] of [["report.html", renderAuditHtml(summary, repos)], ["repos.csv", renderAuditCsv(summary)], ["audit.json", renderAuditJson(summary, repos)]]) {
16106
- writeFileSync(join3(dir, name), body);
16107
- 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));
16108
16569
  }
16109
16570
  io.stderr(`Using ${describeLicense(claims)}
16110
16571
  `);
16111
16572
  }
16112
- 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)}
16113
16574
  `);
16114
- 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) }));
16115
16576
  return 0;
16116
16577
  }
16117
16578
 
@@ -16181,12 +16642,18 @@ Usage:
16181
16642
  --include-forks --include-archived
16182
16643
  --license <key|file> Licence key (or THREADCTX_LICENSE, or ~/.threadctx/license)
16183
16644
  --output-dir <dir> Where licensed reports are written
16645
+ --baseline <audit.json> Show what changed since a previous audit (automatic when
16646
+ re-running into the same folder)
16184
16647
  threadctx license [key|file] Check a licence offline
16185
16648
  threadctx explain <file> [--tool <id>|all] [--surface cloud-agent|code-review|chat]
16186
16649
  What each agent loads for this file, in precedence order
16187
16650
  threadctx diff [--path <dir>] What each agent believes about the same directory
16188
- threadctx fix [path] [--apply] [--output <patch>]
16189
- 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)
16190
16657
  threadctx rules [id] List rules, or show one
16191
16658
  threadctx tools List tool adapters and when each was verified
16192
16659
  threadctx pack validate <file> Check a rule pack before using it
@@ -16207,12 +16674,16 @@ var OPTIONS = {
16207
16674
  "include-forks": { type: "boolean" },
16208
16675
  "include-archived": { type: "boolean" },
16209
16676
  "output-dir": { type: "string" },
16677
+ baseline: { type: "string" },
16210
16678
  rule: { type: "string", multiple: true },
16211
16679
  verbose: { type: "boolean" },
16212
16680
  tool: { type: "string" },
16213
16681
  surface: { type: "string" },
16214
16682
  path: { type: "string" },
16215
16683
  apply: { type: "boolean" },
16684
+ pr: { type: "boolean" },
16685
+ "no-badge": { type: "boolean" },
16686
+ force: { type: "boolean" },
16216
16687
  json: { type: "boolean" },
16217
16688
  color: { type: "boolean" },
16218
16689
  "no-color": { type: "boolean" },
@@ -16223,7 +16694,7 @@ var OPTIONS = {
16223
16694
  };
16224
16695
  async function main(argv, io) {
16225
16696
  try {
16226
- return await run(argv, io);
16697
+ return await run2(argv, io);
16227
16698
  } catch (e) {
16228
16699
  if (e instanceof UsageError || e instanceof ConfigError || e instanceof PackError) {
16229
16700
  io.stderr(`threadctx: ${e.message}
@@ -16236,7 +16707,7 @@ Please report this at https://github.com/threadctx-dev/ctx/issues
16236
16707
  return 2;
16237
16708
  }
16238
16709
  }
16239
- async function run(argv, io) {
16710
+ async function run2(argv, io) {
16240
16711
  let parsed;
16241
16712
  try {
16242
16713
  parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
@@ -16277,6 +16748,8 @@ Run 'threadctx --help' for usage.`);
16277
16748
  return cmdDiff(v, io, color);
16278
16749
  case "fix":
16279
16750
  return cmdFix(args[0], v, io);
16751
+ case "init":
16752
+ return cmdInit(args[0], v, io);
16280
16753
  case "rules":
16281
16754
  return cmdRules(args[0], v, io);
16282
16755
  case "tools":
@@ -16290,7 +16763,7 @@ Run 'threadctx --help' for usage.`);
16290
16763
  }
16291
16764
  function openRoot(pathArg, io) {
16292
16765
  const target = resolve4(io.cwd, pathArg ?? ".");
16293
- if (!existsSync3(target)) throw new UsageError(`path not found: ${pathArg}`);
16766
+ if (!existsSync4(target)) throw new UsageError(`path not found: ${pathArg}`);
16294
16767
  if (!statSync3(target).isDirectory()) throw new UsageError(`not a directory: ${pathArg} (scan takes a repository or directory)`);
16295
16768
  return openRepo(target);
16296
16769
  }
@@ -16339,8 +16812,8 @@ async function cmdScan(pathArg, v, io, color) {
16339
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) });
16340
16813
  if (v.output) {
16341
16814
  const dest = resolve4(io.cwd, v.output);
16342
- mkdirSync2(dirname(dest), { recursive: true });
16343
- writeFileSync2(dest, out);
16815
+ mkdirSync3(dirname2(dest), { recursive: true });
16816
+ writeFileSync3(dest, out);
16344
16817
  io.stderr(`Wrote ${format} report to ${relative3(io.cwd, dest) || dest} \u2014 grade ${result.grade}, ${result.counts.blocker} blocker, ${result.counts.warning} warning
16345
16818
  `);
16346
16819
  } else {
@@ -16351,9 +16824,9 @@ async function cmdScan(pathArg, v, io, color) {
16351
16824
  }
16352
16825
  if (remoteLabel && format === "text" && !v.output) io.stdout(`
16353
16826
  README badge:
16354
- ${renderBadge(result).markdown}
16827
+ ${renderBadge(result, badgeLinkFor(parseGithubRef(v.github).fullName)).markdown}
16355
16828
  `);
16356
- if (format === "text" && !v.output && !remoteLabel) maybeUpgradeLine(result, io);
16829
+ if (format === "text" && !v.output && !remoteLabel) maybeUpgradeLine(result, io, githubRemote(view.root));
16357
16830
  const threshold = failOn ?? loadConfig(view).failOn;
16358
16831
  return exitCodeFor(result, threshold);
16359
16832
  }
@@ -16365,7 +16838,7 @@ function cmdCompare(baseFile, headFile, v, io) {
16365
16838
  if (!["text", "md", "json"].includes(format)) throw new UsageError("--format must be text, md or json");
16366
16839
  const readScan = (file) => {
16367
16840
  const abs = resolve4(io.cwd, file);
16368
- if (!existsSync3(abs)) throw new UsageError(`file not found: ${file}`);
16841
+ if (!existsSync4(abs)) throw new UsageError(`file not found: ${file}`);
16369
16842
  try {
16370
16843
  return parseScanJson(readFileSync3(abs, "utf8"), file);
16371
16844
  } catch (e) {
@@ -16394,15 +16867,20 @@ function cmdCompare(baseFile, headFile, v, io) {
16394
16867
  }
16395
16868
  if (v.output) {
16396
16869
  const dest = resolve4(io.cwd, v.output);
16397
- mkdirSync2(dirname(dest), { recursive: true });
16398
- writeFileSync2(dest, out);
16870
+ mkdirSync3(dirname2(dest), { recursive: true });
16871
+ writeFileSync3(dest, out);
16399
16872
  } else io.stdout(out);
16400
16873
  return compareExitCode(c, failOn);
16401
16874
  }
16875
+ function defaultBaseline(org, outDir, license, io) {
16876
+ if (!/^[A-Za-z0-9-]{1,39}$/.test(org)) return 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;
16879
+ }
16402
16880
  async function cmdAudit(v, io, color) {
16403
16881
  if (!v.org) throw new UsageError("usage: threadctx audit --org <github-org-or-user>");
16404
16882
  try {
16405
- return await runAudit({ org: v.org, max: v.max ? Number(v.max) : 200, includeForks: Boolean(v["include-forks"]), includeArchived: Boolean(v["include-archived"]), license: v.license, outDir: v["output-dir"], json: Boolean(v.json), color }, io);
16883
+ return await runAudit({ org: v.org, max: v.max ? Number(v.max) : 200, includeForks: Boolean(v["include-forks"]), includeArchived: Boolean(v["include-archived"]), license: v.license, outDir: v["output-dir"], baseline: v.baseline ?? defaultBaseline(v.org, v["output-dir"], v.license, io), json: Boolean(v.json), color }, io);
16406
16884
  } catch (e) {
16407
16885
  if (e instanceof AuditUsageError) throw new UsageError(e.message);
16408
16886
  throw e;
@@ -16428,7 +16906,7 @@ source: ${found.source}
16428
16906
  function cmdBadge(pathArg, v, io) {
16429
16907
  const repo = openRoot(pathArg, io);
16430
16908
  const result = doScan(repo, v, io);
16431
- const badge = renderBadge(result);
16909
+ const badge = renderBadge(result, badgeLinkFor(githubRemote(repo.root)));
16432
16910
  if (v.json) io.stdout(`${JSON.stringify({ grade: result.grade, score: result.score, ...badge }, null, 2)}
16433
16911
  `);
16434
16912
  else io.stdout(`${badge.markdown}
@@ -16446,11 +16924,11 @@ function locate(fileArg, io) {
16446
16924
  }
16447
16925
  };
16448
16926
  const given = resolve4(io.cwd, fileArg);
16449
- const abs = existsSync3(given) ? real(given) : join4(real(dirname(given)), basename(given));
16450
- 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);
16451
16929
  const rel = relative3(root, abs).split(sep3).join("/");
16452
16930
  if (rel.startsWith("..")) throw new UsageError(`${fileArg} is outside the repository at ${root}`);
16453
- const isDir = existsSync3(abs) && statSync3(abs).isDirectory();
16931
+ const isDir = existsSync4(abs) && statSync3(abs).isDirectory();
16454
16932
  return { repo: openRepo(root), target: { path: rel === "" ? "" : rel, isDir } };
16455
16933
  }
16456
16934
  function contextsFor(repo, target, toolArg, surface) {
@@ -16522,14 +17000,32 @@ function cmdFix(pathArg, v, io) {
16522
17000
  io.stderr("No safe fixes to apply.\n");
16523
17001
  return 0;
16524
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
+ }
16525
17021
  if (v.apply) {
16526
- 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);
16527
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.
16528
17024
  `);
16529
17025
  return 0;
16530
17026
  }
16531
17027
  if (v.output) {
16532
- writeFileSync2(resolve4(io.cwd, v.output), plan.patch);
17028
+ writeFileSync3(resolve4(io.cwd, v.output), plan.patch);
16533
17029
  io.stderr(`Wrote ${plan.applied.length} fix${plan.applied.length === 1 ? "" : "es"} to ${v.output}. Apply with: git apply ${v.output}
16534
17030
  `);
16535
17031
  } else {
@@ -16539,6 +17035,71 @@ function cmdFix(pathArg, v, io) {
16539
17035
  }
16540
17036
  return 0;
16541
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
+ }
16542
17103
  function cmdRules(id, v, io) {
16543
17104
  if (id) {
16544
17105
  const r = RULES.find((x) => x.id.toLowerCase() === id.toLowerCase());
@@ -16577,7 +17138,7 @@ function cmdTools(v, io) {
16577
17138
  }
16578
17139
  function cmdPackValidate(file, io) {
16579
17140
  const abs = resolve4(io.cwd, file);
16580
- if (!existsSync3(abs)) throw new UsageError(`file not found: ${file}`);
17141
+ if (!existsSync4(abs)) throw new UsageError(`file not found: ${file}`);
16581
17142
  const pack = parsePack(readFileSync3(abs, "utf8"), file);
16582
17143
  io.stdout(`${pack.pack}: ${pack.rules.length} rule${pack.rules.length === 1 ? "" : "s"} valid
16583
17144
  `);
@@ -16585,10 +17146,10 @@ function cmdPackValidate(file, io) {
16585
17146
  `);
16586
17147
  return 0;
16587
17148
  }
16588
- var UPGRADE_URL = void 0;
16589
- function maybeUpgradeLine(result, io) {
17149
+ var UPGRADE_URL = "https://threadctx.dev/pricing";
17150
+ function maybeUpgradeLine(result, io, remote) {
16590
17151
  if (!UPGRADE_URL || !io.isTTY || io.env.CI || io.env.THREADCTX_NO_UPSELL) return;
16591
- 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");
16592
17153
  let state = {};
16593
17154
  try {
16594
17155
  state = JSON.parse(readFileSync3(stateFile, "utf8"));
@@ -16596,14 +17157,14 @@ function maybeUpgradeLine(result, io) {
16596
17157
  }
16597
17158
  const today = io.now().toISOString().slice(0, 10);
16598
17159
  if (state.lastUpsell === today) return;
16599
- const toolsUsed = result.tools.filter((t) => t.layers > 0).length;
16600
- const msg = toolsUsed >= 2 ? `${toolsUsed} agents read this repository. Grade every pull request and keep them aligned: ${UPGRADE_URL}` : `Track this grade on every pull request: ${UPGRADE_URL}`;
17160
+ const owner = remote?.split("/")[0];
17161
+ const msg = owner ? `See every repository in ${owner} at once (free summary): npx threadctx audit --org ${owner} \xB7 ${UPGRADE_URL}` : `Add a README badge: npx threadctx badge \xB7 Whole-organisation audits: ${UPGRADE_URL}`;
16601
17162
  io.stderr(`
16602
17163
  ${msg}
16603
17164
  `);
16604
17165
  try {
16605
- mkdirSync2(dirname(stateFile), { recursive: true });
16606
- writeFileSync2(stateFile, JSON.stringify({ ...state, lastUpsell: today }));
17166
+ mkdirSync3(dirname2(stateFile), { recursive: true });
17167
+ writeFileSync3(stateFile, JSON.stringify({ ...state, lastUpsell: today }));
16607
17168
  } catch {
16608
17169
  }
16609
17170
  }