threadctx 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -48,6 +48,30 @@ npx threadctx fix --apply # write them (never commits)
48
48
  npx threadctx fix --pr # open a pull request with them (uses your git and gh)
49
49
  ```
50
50
 
51
+ ## Checked memory
52
+
53
+ Agents forget everything between sessions, and the notes they keep go stale. threadctx gives them a
54
+ memory per repository and **checks every entry against the code before the agent sees it**:
55
+
56
+ - an entry naming a file or script that no longer exists is marked *may be stale*;
57
+ - an entry that contradicts the instruction files or the lockfile is marked *conflicts with repo*;
58
+ - an entry with a secret or an unsafe instruction is withheld (and refused when written);
59
+ - expired, superseded and unreviewed entries are hidden or flagged.
60
+
61
+ ```bash
62
+ claude mcp add threadctx -- npx -y threadctx mcp # memory_query, memory_write, memory_review + checks
63
+ npx threadctx memory list # what is stored, with each check result
64
+ npx threadctx memory check --team # CI: fail if team memory no longer matches the code
65
+ ```
66
+
67
+ Personal memory stays on your machine (`~/.threadctx/local.json`, the same file threadctx-mcp's local
68
+ mode uses, so existing notes carry over). Team memory is `.threadctx/memory.json` in the repository:
69
+ shared through git and reviewed in pull requests, with no server. Checks cover files, scripts, commands,
70
+ package manager, runtime versions and secrets in the repository; claims about outside systems are not verified.
71
+
72
+ The Claude Code plugin adds a session-start line: your grade, the tokens your instruction files cost
73
+ every session and how many are duplicated, and memory health.
74
+
51
75
  ## Keep it fixed
52
76
 
53
77
  ```bash
@@ -9829,13 +9829,13 @@ var require_ignore = __commonJS({
9829
9829
  const rules = this._rules;
9830
9830
  const { length } = rules;
9831
9831
  const shortcut = this._basenameCount * 2 >= length;
9832
- const basename2 = shortcut ? basenameOf(path) : path;
9832
+ const basename3 = shortcut ? basenameOf(path) : path;
9833
9833
  for (let index = 0; index < length; index++) {
9834
9834
  const rule = rules[index];
9835
9835
  const { negative } = rule;
9836
9836
  const skip = unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored;
9837
9837
  if (!skip && rule[mode].test(
9838
- shortcut && rule._basenameOnly ? basename2 : path
9838
+ shortcut && rule._basenameOnly ? basename3 : path
9839
9839
  )) {
9840
9840
  ignored = !negative;
9841
9841
  unignored = negative;
@@ -9986,9 +9986,9 @@ var require_ignore = __commonJS({
9986
9986
  });
9987
9987
 
9988
9988
  // src/cli.ts
9989
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync3, realpathSync as realpathSync2, statSync as statSync3, writeFileSync as writeFileSync3 } from "node:fs";
9990
- import { homedir as homedir2 } from "node:os";
9991
- import { basename, dirname as dirname2, join as join5, relative as relative3, resolve as resolve4, sep as sep3 } from "node:path";
9989
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync4, realpathSync as realpathSync3, statSync as statSync3, writeFileSync as writeFileSync4 } from "node:fs";
9990
+ import { homedir as homedir3 } from "node:os";
9991
+ import { basename as basename2, dirname as dirname3, join as join6, 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
@@ -12688,7 +12688,7 @@ var ROWS = [
12688
12688
  "warning",
12689
12689
  "deterministic",
12690
12690
  "none",
12691
- "cloud",
12691
+ "local",
12692
12692
  "Team memory entry contradicts an instruction file",
12693
12693
  "Memory served over MCP overrides reviewed instructions.",
12694
12694
  "spec \xA79.1",
@@ -12875,7 +12875,7 @@ var ROWS = [
12875
12875
  "warning",
12876
12876
  "deterministic",
12877
12877
  "none",
12878
- "cloud",
12878
+ "local",
12879
12879
  "Team memory entry expired or never reviewed",
12880
12880
  "Unreviewed or stale knowledge reaches agents.",
12881
12881
  "spec \xA79.1",
@@ -14739,7 +14739,7 @@ function applySuppressions(findings, inline, config, now, diagnostics) {
14739
14739
  }
14740
14740
 
14741
14741
  // ../rules/dist/version.js
14742
- var ENGINE_VERSION = "0.5.0";
14742
+ var ENGINE_VERSION = "0.6.1";
14743
14743
  var REGISTRY_VERSION = "2026.10.1";
14744
14744
 
14745
14745
  // ../rules/dist/engine.js
@@ -15237,7 +15237,7 @@ var CONTROLS = [
15237
15237
  ];
15238
15238
  var EVIDENCE_DISCLAIMER = "threadctx produces evidence about AI coding agent configuration. It is not an attestation, certification or audit opinion. Framework references show where the evidence is commonly relevant; your auditor decides whether it is sufficient for a control.";
15239
15239
  var plural2 = (n2, one, many = `${one}s`) => `${n2} ${n2 === 1 ? one : many}`;
15240
- function evidencePack(summary, repos) {
15240
+ function evidencePack(summary2, repos) {
15241
15241
  const withContext = repos.filter((r) => r.result && r.result.artifacts.length > 0).sort((a, b) => a.fullName < b.fullName ? -1 : 1);
15242
15242
  const tested = withContext.length;
15243
15243
  const inventory = withContext.map((r) => {
@@ -15261,11 +15261,11 @@ function evidencePack(summary, repos) {
15261
15261
  ...base(c),
15262
15262
  status: "evidenced",
15263
15263
  tested,
15264
- statement: `${plural2(summary.repos.scanned, "repository", "repositories")} scanned; ${plural2(files, "agent instruction or configuration file")} and ${plural2(servers, "MCP server")} inventoried across ${plural2(tested, "repository", "repositories")} (see the inventory).`
15264
+ statement: `${plural2(summary2.repos.scanned, "repository", "repositories")} scanned; ${plural2(files, "agent instruction or configuration file")} and ${plural2(servers, "MCP server")} inventoried across ${plural2(tested, "repository", "repositories")} (see the inventory).`
15265
15265
  };
15266
15266
  }
15267
15267
  if (c.id === "TC-08") {
15268
- const t = summary.trend;
15268
+ const t = summary2.trend;
15269
15269
  return t ? { ...base(c), status: "evidenced", tested, statement: `Compared with the audit of ${t.since.slice(0, 10)}: fleet score ${t.before.score} \u2192 ${t.after.score}, blockers ${t.before.blockers} \u2192 ${t.after.blockers}, ${t.regressed.length} repositories regressed.` } : { ...base(c), status: "not-evidenced", tested, statement: "This is the first audit in this folder, so there is no earlier run to compare with. Run the audit on a schedule (Team plan) to evidence ongoing monitoring." };
15270
15270
  }
15271
15271
  const ids = new Set(c.rules);
@@ -15292,10 +15292,10 @@ function evidencePack(summary, repos) {
15292
15292
  agents[a] = (agents[a] ?? 0) + 1;
15293
15293
  return {
15294
15294
  schema: "threadctx.evidence/v1",
15295
- org: summary.org,
15296
- generatedAt: summary.generatedAt,
15297
- engine: summary.engine,
15298
- scope: { repositoriesListed: summary.repos.listed, repositoriesScanned: summary.repos.scanned, withAgentContext: summary.repos.withContext, withoutAgentContext: summary.repos.withoutContext, unreadable: summary.repos.failed },
15295
+ org: summary2.org,
15296
+ generatedAt: summary2.generatedAt,
15297
+ engine: summary2.engine,
15298
+ scope: { repositoriesListed: summary2.repos.listed, repositoriesScanned: summary2.repos.scanned, withAgentContext: summary2.repos.withContext, withoutAgentContext: summary2.repos.withoutContext, unreadable: summary2.repos.failed },
15299
15299
  totals: { agentFiles: inventory.reduce((n2, r) => n2 + r.files.length, 0), mcpServers: inventory.reduce((n2, r) => n2 + r.mcpServers.length, 0), agents },
15300
15300
  controls,
15301
15301
  inventory,
@@ -15315,6 +15315,93 @@ function controlHeadline(pack) {
15315
15315
  };
15316
15316
  }
15317
15317
 
15318
+ // ../rules/dist/memory.js
15319
+ var DEFAULT_REVIEW_AFTER_DAYS = 90;
15320
+ var DRIFT = [D001, D002, D003, D004, D005];
15321
+ var SECURITY = [X001, X002, X003, X005, ...xFromPacks(["CTX-X004"])];
15322
+ function xFromPacks(ids) {
15323
+ const out = [];
15324
+ for (const pack of BUILTIN_PACKS)
15325
+ for (const rule of pack.rules)
15326
+ if (ids.includes(rule.id))
15327
+ out.push(packCheck(pack, rule));
15328
+ return out;
15329
+ }
15330
+ var virtualPath = (id) => `.threadctx-memory-${id.replace(/[^A-Za-z0-9-]/g, "").slice(0, 36) || "entry"}.md`;
15331
+ function overlay(fs, extra) {
15332
+ return {
15333
+ root: fs.root,
15334
+ files: fs.files,
15335
+ dirs: fs.dirs,
15336
+ readFile: (p) => extra.get(p) ?? fs.readFile(p),
15337
+ exists: (p) => fs.exists(p),
15338
+ symlinkTarget: (p) => fs.symlinkTarget(p)
15339
+ };
15340
+ }
15341
+ var days = (ms) => ms / 864e5;
15342
+ function checkMemories(fs, entries, opts = {}) {
15343
+ const now = opts.now ?? /* @__PURE__ */ new Date();
15344
+ const reviewAfter = opts.reviewAfterDays ?? DEFAULT_REVIEW_AFTER_DAYS;
15345
+ const state = prepare(fs);
15346
+ const texts2 = /* @__PURE__ */ new Map();
15347
+ const byPath = /* @__PURE__ */ new Map();
15348
+ for (const e of entries) {
15349
+ const p = virtualPath(e.id);
15350
+ texts2.set(p, e.content);
15351
+ byPath.set(p, e);
15352
+ }
15353
+ const view = overlay(fs, texts2);
15354
+ const memArtifacts = [];
15355
+ for (const p of texts2.keys()) {
15356
+ const a = parseArtifact(view, { tool: "neutral", path: p, kind: "instructions", frontmatter: false, origin: "repo" });
15357
+ if (a)
15358
+ memArtifacts.push(a);
15359
+ }
15360
+ const loaded = new Set(state.rootContexts.flatMap((c) => c.layers.map((l) => l.path)));
15361
+ const instructions = state.catalog.artifacts.filter((a) => loaded.has(a.artifact.path));
15362
+ const reasons = /* @__PURE__ */ new Map();
15363
+ const add = (path, ruleId, message) => {
15364
+ const e = byPath.get(path);
15365
+ if (e)
15366
+ reasons.set(e.id, [...reasons.get(e.id) ?? [], { ruleId, message }]);
15367
+ };
15368
+ const base = { fs: view, catalog: state.catalog, facts: state.facts, mcp: [], config: state.config, rootContexts: state.rootContexts, now };
15369
+ const run3 = (checks, artifacts, as) => {
15370
+ for (const check of checks) {
15371
+ try {
15372
+ check.run({ ...base, artifacts }, (f) => {
15373
+ if (byPath.has(f.path))
15374
+ add(f.path, as ?? check.ruleId, f.message.replaceAll(f.path, "this memory"));
15375
+ });
15376
+ } catch {
15377
+ }
15378
+ }
15379
+ };
15380
+ run3(SECURITY, memArtifacts);
15381
+ run3(DRIFT, memArtifacts);
15382
+ for (const m of memArtifacts) {
15383
+ run3([C001], [...instructions, m], "CTX-C005");
15384
+ }
15385
+ return entries.map((e) => {
15386
+ const r = reasons.get(e.id) ?? [];
15387
+ if (e.superseded_by)
15388
+ return { id: e.id, verdict: "superseded", serve: false, reasons: [{ ruleId: "CTX-G004", message: `Replaced by ${e.superseded_by}.` }] };
15389
+ if (e.expires_at && Date.parse(e.expires_at) <= now.getTime())
15390
+ return { id: e.id, verdict: "expired", serve: false, reasons: [{ ruleId: "CTX-G004", message: `Expired on ${e.expires_at.slice(0, 10)}.` }] };
15391
+ if (r.some((x) => x.ruleId.startsWith("CTX-X")))
15392
+ return { id: e.id, verdict: "unsafe", serve: false, reasons: r };
15393
+ if (r.some((x) => x.ruleId === "CTX-C005"))
15394
+ return { id: e.id, verdict: "conflict", serve: true, reasons: r };
15395
+ if (r.length)
15396
+ return { id: e.id, verdict: "stale", serve: true, reasons: r };
15397
+ const since = Date.parse(e.reviewed_at ?? e.created_at);
15398
+ if (Number.isFinite(since) && days(now.getTime() - since) > reviewAfter) {
15399
+ return { id: e.id, verdict: "review-due", serve: true, reasons: [{ ruleId: "CTX-G004", message: `Not reviewed for ${Math.floor(days(now.getTime() - since))} days.` }] };
15400
+ }
15401
+ return { id: e.id, verdict: "ok", serve: true, reasons: [] };
15402
+ });
15403
+ }
15404
+
15318
15405
  // ../report/dist/evidence.js
15319
15406
  var esc2 = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
15320
15407
  var TOOL_LABEL2 = { "agents-md": "AGENTS.md", "claude-code": "Claude Code", cursor: "Cursor", copilot: "GitHub Copilot", gemini: "Gemini CLI" };
@@ -15625,7 +15712,7 @@ function renderLiveBadge(fullName) {
15625
15712
  }
15626
15713
 
15627
15714
  // src/cli.ts
15628
- import { execFileSync as execFileSync5 } from "node:child_process";
15715
+ import { execFileSync as execFileSync6 } from "node:child_process";
15629
15716
 
15630
15717
  // ../../node_modules/.pnpm/diff@9.0.0/node_modules/diff/libesm/diff/base.js
15631
15718
  var Diff = class {
@@ -16186,7 +16273,7 @@ function planFixes(fs, findings, kinds = ["safe"]) {
16186
16273
  }
16187
16274
 
16188
16275
  // src/init.ts
16189
- var ACTION_PIN = { sha: "0fcf8348d004ae084b5e557dddd381da25a6db6a", tag: "v1.4.1" };
16276
+ var ACTION_PIN = { sha: "97cbb2f34f392f4f18dd9d95cfba3c4c87b231de", tag: "v1.6.0" };
16190
16277
  var CHECKOUT_PIN = { sha: "3d3c42e5aac5ba805825da76410c181273ba90b1", tag: "v7.0.1" };
16191
16278
  var WORKFLOW_PATH = ".github/workflows/agent-context.yml";
16192
16279
  function workflowYaml() {
@@ -16322,19 +16409,169 @@ function githubRemote(dir) {
16322
16409
  }
16323
16410
 
16324
16411
  // src/mcp.ts
16325
- import { existsSync as existsSync2, realpathSync, statSync as statSync2 } from "node:fs";
16412
+ import { existsSync as existsSync3, realpathSync, statSync as statSync2 } from "node:fs";
16326
16413
  import { isAbsolute, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
16414
+
16415
+ // src/memory.ts
16416
+ import { execFileSync as execFileSync4 } from "node:child_process";
16417
+ import { randomUUID } from "node:crypto";
16418
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
16419
+ import { homedir } from "node:os";
16420
+ import { basename, dirname as dirname2, join as join4 } from "node:path";
16421
+ var TEAM_FILE = ".threadctx/memory.json";
16422
+ var MAX_CONTENT = 4e3;
16423
+ function repoKey(root, env) {
16424
+ if (env.THREADCTX_REPO) return env.THREADCTX_REPO;
16425
+ try {
16426
+ const url = execFileSync4("git", ["config", "--get", "remote.origin.url"], { cwd: root, stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 }).toString().trim();
16427
+ const m = url.match(/[:/]([^/]+\/[^/]+?)(\.git)?$/);
16428
+ if (m) return m[1];
16429
+ } catch {
16430
+ }
16431
+ return `local/${basename(root)}`;
16432
+ }
16433
+ function personalPath(env) {
16434
+ return env.THREADCTX_DB_PATH ?? join4(env.HOME ?? homedir(), ".threadctx", "local.json");
16435
+ }
16436
+ function readArray(path) {
16437
+ if (!existsSync2(path)) return [];
16438
+ try {
16439
+ const v = JSON.parse(readFileSync2(path, "utf8"));
16440
+ return Array.isArray(v) ? v.filter((e) => e && typeof e.id === "string" && typeof e.content === "string").map((e) => ({ ...e, tags: Array.isArray(e.tags) ? e.tags : [] })) : [];
16441
+ } catch {
16442
+ return [];
16443
+ }
16444
+ }
16445
+ function writeArray(path, entries) {
16446
+ mkdirSync2(dirname2(path), { recursive: true });
16447
+ const tmp = `${path}.${process.pid}.tmp`;
16448
+ writeFileSync2(tmp, `${JSON.stringify(entries, null, 2)}
16449
+ `, "utf8");
16450
+ renameSync(tmp, path);
16451
+ }
16452
+ var MemoryStore = class {
16453
+ constructor(m) {
16454
+ this.m = m;
16455
+ this.repo = repoKey(m.root, m.env);
16456
+ this.personalFile = personalPath(m.env);
16457
+ this.teamFile = join4(m.root, TEAM_FILE);
16458
+ }
16459
+ m;
16460
+ repo;
16461
+ personalFile;
16462
+ teamFile;
16463
+ entries() {
16464
+ const personal = readArray(this.personalFile).filter((e) => e.repo === this.repo).map((e) => ({ ...e, scope: "personal" }));
16465
+ const team = readArray(this.teamFile).map((e) => ({ ...e, scope: "team" }));
16466
+ return [...team, ...personal];
16467
+ }
16468
+ checked(entries = this.entries()) {
16469
+ if (entries.length === 0) return [];
16470
+ const checks = new Map(checkMemories(openRepo(this.m.root), entries, { now: this.m.now() }).map((c) => [c.id, c]));
16471
+ return entries.map((e) => ({ ...e, check: checks.get(e.id) }));
16472
+ }
16473
+ /** Check text before storing it. Unsafe content (secrets, injections) is refused. */
16474
+ preview(content) {
16475
+ return checkMemories(openRepo(this.m.root), [{ id: "new", content, created_at: this.m.now().toISOString() }], { now: this.m.now() })[0];
16476
+ }
16477
+ write(input) {
16478
+ const content = input.content.trim();
16479
+ if (!content) throw new Error("content is required");
16480
+ if (content.length > MAX_CONTENT) throw new Error(`content is longer than ${MAX_CONTENT} characters; store the gist and point to the file or PR`);
16481
+ const check = this.preview(content);
16482
+ if (check.verdict === "unsafe") throw new Error(`not stored: ${check.reasons.map((r) => `${r.ruleId} ${r.message}`).join("; ")}`);
16483
+ const now = this.m.now();
16484
+ const scope = input.scope ?? "personal";
16485
+ const entry2 = { id: randomUUID(), content, tags: (input.tags ?? []).map(String).slice(0, 10), created_at: now.toISOString() };
16486
+ if (input.expiresInDays && input.expiresInDays > 0) entry2.expires_at = new Date(now.getTime() + input.expiresInDays * 864e5).toISOString();
16487
+ if (input.supersedes) this.update(input.supersedes, (e) => ({ ...e, superseded_by: entry2.id }));
16488
+ this.save(scope, (list) => [...list, scope === "personal" ? { ...entry2, repo: this.repo } : entry2]);
16489
+ return { entry: { ...entry2, scope }, check };
16490
+ }
16491
+ /** Mark an older entry as replaced by a newer one; the old one stops being served. */
16492
+ supersede(oldId, newId) {
16493
+ const replacement = this.entries().find((e) => e.id === newId || newId.length >= 8 && e.id.startsWith(newId));
16494
+ if (!replacement) throw new Error(`no memory '${newId}' for ${this.repo}`);
16495
+ if (replacement.id.startsWith(oldId) || oldId.startsWith(replacement.id)) throw new Error("an entry cannot supersede itself");
16496
+ return this.update(oldId, (e) => ({ ...e, superseded_by: replacement.id }));
16497
+ }
16498
+ renew(id) {
16499
+ return this.update(id, (e) => ({ ...e, reviewed_at: this.m.now().toISOString(), expires_at: void 0 }));
16500
+ }
16501
+ forget(id) {
16502
+ return this.update(id, (e) => ({ ...e, expires_at: this.m.now().toISOString() }));
16503
+ }
16504
+ update(id, fn) {
16505
+ const hit = this.entries().find((e) => e.id === id || id.length >= 8 && e.id.startsWith(id));
16506
+ if (!hit) throw new Error(`no memory '${id}' for ${this.repo}`);
16507
+ let updated;
16508
+ this.save(hit.scope, (list) => list.map((e) => e.id === hit.id ? updated = clean(fn(e)) : e));
16509
+ return { ...updated, scope: hit.scope };
16510
+ }
16511
+ save(scope, fn) {
16512
+ const path = scope === "team" ? this.teamFile : this.personalFile;
16513
+ writeArray(path, fn(readArray(path)));
16514
+ }
16515
+ };
16516
+ function clean(e) {
16517
+ return Object.fromEntries(Object.entries(e).filter(([, v]) => v !== void 0));
16518
+ }
16519
+ function rank(entries, query, max) {
16520
+ const words2 = [...new Set(query.toLowerCase().split(/\W+/).filter((w) => w.length > 3))];
16521
+ const scored = entries.map((e) => {
16522
+ const hay = `${e.content} ${e.tags.join(" ")}`.toLowerCase();
16523
+ return { e, score: words2.reduce((n2, w) => n2 + (hay.includes(w) ? 1 : 0), 0) };
16524
+ });
16525
+ return scored.filter((s) => words2.length === 0 || s.score > 0).sort((a, b) => b.score - a.score || (a.e.created_at < b.e.created_at ? 1 : -1)).slice(0, max).map((s) => s.e);
16526
+ }
16527
+ var LABEL = {
16528
+ ok: "checked",
16529
+ "review-due": "review due",
16530
+ stale: "may be stale",
16531
+ conflict: "conflicts with repo",
16532
+ unsafe: "withheld",
16533
+ expired: "expired",
16534
+ superseded: "superseded"
16535
+ };
16536
+ function short(id) {
16537
+ return id.slice(0, 8);
16538
+ }
16539
+ function formatEntry(e) {
16540
+ const head = `- [${e.scope} \xB7 ${LABEL[e.check.verdict]} \xB7 ${short(e.id)}] ${e.content.replace(/\s*\n\s*/g, " ")}`;
16541
+ if (e.check.verdict === "ok") return head;
16542
+ return `${head}
16543
+ \u21B3 ${e.check.reasons.map((r) => `${r.ruleId}: ${r.message}`).join(" | ")}`;
16544
+ }
16545
+ function answerQuery(store2, task, max = 5) {
16546
+ const all = store2.checked();
16547
+ const servable = all.filter((e) => e.check.serve);
16548
+ const order = { ok: 0, "review-due": 1, stale: 2, conflict: 3 };
16549
+ const hits = rank(servable, task, max).sort((a, b) => (order[a.check.verdict] ?? 9) - (order[b.check.verdict] ?? 9));
16550
+ const withheld = all.filter((e) => e.check.verdict === "unsafe").length;
16551
+ const lines = [];
16552
+ if (hits.length === 0) lines.push(`No relevant memory for ${store2.repo}.`);
16553
+ else lines.push(...hits.map(formatEntry));
16554
+ const flagged = hits.filter((e) => e.check.verdict !== "ok").length;
16555
+ if (flagged) lines.push("", "Entries marked 'may be stale' or 'conflicts with repo' were checked against the repository and failed: verify before relying on them, then call memory_review to renew, supersede or forget them.");
16556
+ if (withheld) lines.push("", `${withheld} entr${withheld === 1 ? "y was" : "ies were"} withheld because they contain a secret or an unsafe instruction. Run \`npx threadctx memory list\` to review.`);
16557
+ lines.push("", `\xB7 threadctx checked memory (${hits.length} served). Checks cover files, scripts, commands, package manager, runtime versions and secrets in this repository; claims about outside systems are not verified.`);
16558
+ return { text: lines.join("\n"), served: hits.length };
16559
+ }
16560
+
16561
+ // src/mcp.ts
16327
16562
  var SUPPORTED_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
16328
16563
  var MAX_TEXT = 2e4;
16329
16564
  var TOOLS = [
16330
16565
  {
16331
16566
  name: "check_context",
16567
+ title: "Check agent context",
16332
16568
  description: "Grade the repository's agent instructions (AGENTS.md, CLAUDE.md, Cursor rules, Copilot instructions, GEMINI.md, MCP configs) and list problems: dead paths, undefined scripts, wrong package manager, duplicated or conflicting instructions, hidden characters, secrets. Call this after you edit any context file, and before relying on instructions you did not write.",
16333
16569
  inputSchema: { type: "object", properties: { path: { type: "string", description: "Directory to check, relative to the project root. Defaults to the root." } }, additionalProperties: false },
16334
16570
  annotations: { readOnlyHint: true, openWorldHint: false }
16335
16571
  },
16336
16572
  {
16337
16573
  name: "get_effective_context",
16574
+ title: "Show what each agent loads",
16338
16575
  description: "Show exactly which instruction files each coding agent loads for a given file or directory, in precedence order, with estimated token counts. Call this when an instruction seems ignored, when two tools behave differently, or before restructuring context files.",
16339
16576
  inputSchema: {
16340
16577
  type: "object",
@@ -16349,12 +16586,61 @@ var TOOLS = [
16349
16586
  },
16350
16587
  {
16351
16588
  name: "explain_rule",
16589
+ title: "Explain a threadctx rule",
16352
16590
  description: "Explain a threadctx rule id such as CTX-D001: what it checks, why it matters, how to fix it, and how precise it is.",
16353
16591
  inputSchema: { type: "object", properties: { id: { type: "string", description: "Rule id, for example CTX-C001." } }, required: ["id"], additionalProperties: false },
16354
16592
  annotations: { readOnlyHint: true, openWorldHint: false }
16593
+ },
16594
+ {
16595
+ name: "memory_query",
16596
+ title: "Recall checked memory",
16597
+ description: "Retrieve past learnings, fixes, decisions and gotchas for this repository before starting non-trivial work. Every entry is checked against the repository first: entries whose files or scripts no longer exist, or that contradict the instructions or lockfile, are marked; entries with secrets or unsafe instructions are withheld; expired and superseded ones are hidden. Call this before, not after.",
16598
+ inputSchema: {
16599
+ type: "object",
16600
+ properties: {
16601
+ task_description: { type: "string", description: "What you are about to do, in plain language." },
16602
+ max_results: { type: "number", description: "Max number of memories to return (default 5)." }
16603
+ },
16604
+ required: ["task_description"],
16605
+ additionalProperties: false
16606
+ },
16607
+ annotations: { readOnlyHint: true, openWorldHint: false }
16608
+ },
16609
+ {
16610
+ name: "memory_write",
16611
+ title: "Save a memory",
16612
+ description: "Save a learning for this repository: a non-obvious fix, a decision and why, or a gotcha that would save the next session time. Write it so a future reader has full context, and name the files involved so it can be checked later. Use scope 'team' only for facts every teammate should get (stored in .threadctx/memory.json, shared through git); the default 'personal' stays on this machine. Content with secrets or unsafe instructions is refused.",
16613
+ inputSchema: {
16614
+ type: "object",
16615
+ properties: {
16616
+ content: { type: "string", description: "The learning, with enough context to act on." },
16617
+ tags: { type: "array", items: { type: "string" }, description: 'Optional short tags, e.g. ["billing", "flaky-test"].' },
16618
+ scope: { type: "string", enum: ["personal", "team"], description: "personal (default) or team." },
16619
+ expires_in_days: { type: "number", description: "For temporary facts (a workaround until a fix ships): hide after this many days." },
16620
+ supersedes: { type: "string", description: "Id of an older memory this one replaces; the old one stops being served." }
16621
+ },
16622
+ required: ["content"],
16623
+ additionalProperties: false
16624
+ },
16625
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
16626
+ },
16627
+ {
16628
+ name: "memory_review",
16629
+ title: "Renew or forget a memory",
16630
+ description: "Keep memory true. 'renew' confirms an entry is still correct (clears 'review due'); 'forget' stops serving an entry that is wrong or no longer useful. To correct an entry, call memory_write with supersedes instead. Use this when memory_query marked an entry as stale or conflicting and you have checked it.",
16631
+ inputSchema: {
16632
+ type: "object",
16633
+ properties: {
16634
+ id: { type: "string", description: "Memory id (the 8-character prefix shown by memory_query is enough)." },
16635
+ action: { type: "string", enum: ["renew", "forget"] }
16636
+ },
16637
+ required: ["id", "action"],
16638
+ additionalProperties: false
16639
+ },
16640
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
16355
16641
  }
16356
16642
  ];
16357
- var INSTRUCTIONS = "threadctx checks what AI coding agents are told. Use check_context after changing AGENTS.md, CLAUDE.md, .cursor/rules, Copilot instructions or MCP configs. Keep context minimal: remove stale, duplicated and generic instructions rather than adding more. All tools are read-only.";
16643
+ var INSTRUCTIONS = "threadctx checks what AI coding agents are told, and keeps a checked memory for this repository. Before non-trivial work, call memory_query. After a non-obvious fix or decision, call memory_write. Use check_context after changing AGENTS.md, CLAUDE.md, .cursor/rules, Copilot instructions or MCP configs. Keep context minimal: remove stale, duplicated and generic instructions rather than adding more.";
16358
16644
  function clip(text) {
16359
16645
  return text.length > MAX_TEXT ? `${text.slice(0, MAX_TEXT)}
16360
16646
  \u2026(truncated)` : text;
@@ -16362,7 +16648,7 @@ function clip(text) {
16362
16648
  function confine(root, input) {
16363
16649
  const realRoot = realpathSync(root);
16364
16650
  const abs = resolve2(realRoot, input);
16365
- const real = existsSync2(abs) ? realpathSync(abs) : abs;
16651
+ const real = existsSync3(abs) ? realpathSync(abs) : abs;
16366
16652
  const rel = relative2(realRoot, real);
16367
16653
  if (rel === ".." || rel.startsWith(`..${sep2}`) || isAbsolute(rel)) throw new Error("path is outside the project");
16368
16654
  return real;
@@ -16379,8 +16665,36 @@ function summarize(result) {
16379
16665
  }
16380
16666
  return lines.join("\n");
16381
16667
  }
16382
- function callTool(name, args, root) {
16668
+ var DEFAULT_ENV = { env: process.env, now: () => /* @__PURE__ */ new Date() };
16669
+ function callTool(name, args, root, menv = DEFAULT_ENV) {
16670
+ const store2 = () => new MemoryStore({ root: realpathSync(root), env: menv.env, now: menv.now });
16383
16671
  switch (name) {
16672
+ case "memory_query": {
16673
+ const task = String(args.task_description ?? "").trim();
16674
+ if (!task) throw new Error("task_description is required");
16675
+ const max = typeof args.max_results === "number" && args.max_results > 0 ? Math.min(Math.floor(args.max_results), 20) : 5;
16676
+ return answerQuery(store2(), task, max).text;
16677
+ }
16678
+ case "memory_write": {
16679
+ const scope = args.scope === "team" ? "team" : "personal";
16680
+ const { entry: entry2, check } = store2().write({
16681
+ content: String(args.content ?? ""),
16682
+ tags: Array.isArray(args.tags) ? args.tags.map(String) : [],
16683
+ scope,
16684
+ expiresInDays: typeof args.expires_in_days === "number" ? args.expires_in_days : void 0,
16685
+ supersedes: typeof args.supersedes === "string" && args.supersedes ? args.supersedes : void 0
16686
+ });
16687
+ const note = check.verdict === "ok" || check.verdict === "review-due" ? "" : `
16688
+ Warning, it does not match the repository: ${check.reasons.map((r) => `${r.ruleId}: ${r.message}`).join(" | ")}`;
16689
+ return `Stored ${scope} memory ${short(entry2.id)}${scope === "team" ? ` in ${TEAM_FILE} (commit it to share)` : ""}.${note}`;
16690
+ }
16691
+ case "memory_review": {
16692
+ const id = String(args.id ?? "").trim();
16693
+ if (!id) throw new Error("id is required");
16694
+ if (args.action === "renew") return `Renewed ${short(store2().renew(id).id)}: confirmed as still true.`;
16695
+ if (args.action === "forget") return `Forgot ${short(store2().forget(id).id)}: it will no longer be served.`;
16696
+ throw new Error("action must be renew or forget");
16697
+ }
16384
16698
  case "check_context": {
16385
16699
  const dir = confine(root, typeof args.path === "string" ? args.path : ".");
16386
16700
  if (!statSync2(dir).isDirectory()) throw new Error("path must be a directory");
@@ -16390,7 +16704,7 @@ function callTool(name, args, root) {
16390
16704
  if (typeof args.file !== "string" || !args.file) throw new Error("file is required");
16391
16705
  const abs = confine(root, args.file);
16392
16706
  const rel = relative2(realpathSync(root), abs).split(sep2).join("/");
16393
- const isDir = existsSync2(abs) && statSync2(abs).isDirectory();
16707
+ const isDir = existsSync3(abs) && statSync2(abs).isDirectory();
16394
16708
  const repo = openRepo(root);
16395
16709
  const state = prepare(repo);
16396
16710
  const tool = typeof args.tool === "string" && args.tool !== "all" ? args.tool : void 0;
@@ -16413,7 +16727,7 @@ Source: ${r.citation}`;
16413
16727
  throw new Error(`unknown tool '${name}'`);
16414
16728
  }
16415
16729
  }
16416
- function handleMessage(raw, root) {
16730
+ function handleMessage(raw, root, menv) {
16417
16731
  const msg = raw;
16418
16732
  if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0" || typeof msg.method !== "string") {
16419
16733
  return { jsonrpc: "2.0", id: msg?.id ?? null, error: { code: -32600, message: "Invalid Request" } };
@@ -16441,7 +16755,7 @@ function handleMessage(raw, root) {
16441
16755
  if (typeof name !== "string" || !TOOLS.some((t) => t.name === name)) return fail2(-32602, `Unknown tool: ${String(name)}`);
16442
16756
  const args = msg.params?.arguments ?? {};
16443
16757
  try {
16444
- return ok({ content: [{ type: "text", text: clip(callTool(name, args, root)) }] });
16758
+ return ok({ content: [{ type: "text", text: clip(callTool(name, args, root, menv)) }] });
16445
16759
  } catch (e) {
16446
16760
  return ok({ isError: true, content: [{ type: "text", text: `Error: ${e.message}` }] });
16447
16761
  }
@@ -16452,6 +16766,7 @@ function handleMessage(raw, root) {
16452
16766
  }
16453
16767
  }
16454
16768
  async function serveMcp(io) {
16769
+ const menv = { env: io.env ?? process.env, now: io.now ?? (() => /* @__PURE__ */ new Date()) };
16455
16770
  let buffer = "";
16456
16771
  const handle = (line) => {
16457
16772
  if (!line.trim()) return;
@@ -16465,7 +16780,7 @@ async function serveMcp(io) {
16465
16780
  }
16466
16781
  const batch = Array.isArray(parsed) ? parsed : [parsed];
16467
16782
  for (const m of batch) {
16468
- const res = handleMessage(m, io.root);
16783
+ const res = handleMessage(m, io.root, menv);
16469
16784
  if (res) io.write(`${JSON.stringify(res)}
16470
16785
  `);
16471
16786
  }
@@ -16487,18 +16802,177 @@ async function serveMcp(io) {
16487
16802
  });
16488
16803
  }
16489
16804
 
16805
+ // src/memory-cli.ts
16806
+ import { realpathSync as realpathSync2 } from "node:fs";
16807
+ var MemoryUsageError = class extends Error {
16808
+ };
16809
+ var MEMORY_HELP = `threadctx memory \u2014 checked memory for coding agents
16810
+
16811
+ threadctx memory list [--all] Entries for this repository with their check result
16812
+ (--all includes expired and superseded ones)
16813
+ threadctx memory check [--team] Check every entry against the repository; exit 1 if any is
16814
+ stale, conflicting or unsafe (--team: only ${TEAM_FILE}, for CI)
16815
+ threadctx memory add <text> [--team] Save a memory (personal by default; --team writes ${TEAM_FILE})
16816
+ threadctx memory renew <id> Confirm an entry is still true
16817
+ threadctx memory forget <id> Stop serving an entry
16818
+ threadctx memory supersede <old-id> <new-id>
16819
+ The newer entry replaces the older one
16820
+
16821
+ Agents use the same store through the MCP server (threadctx mcp): memory_query, memory_write, memory_review.
16822
+ Personal entries live in ~/.threadctx/local.json (shared with threadctx-mcp local mode).
16823
+ `;
16824
+ function rootOf(io) {
16825
+ return gitRoot(io.cwd) ?? realpathSync2(io.cwd);
16826
+ }
16827
+ var store = (io) => new MemoryStore({ root: rootOf(io), env: io.env, now: io.now });
16828
+ function summary(entries) {
16829
+ const out = {};
16830
+ for (const e of entries) out[e.check.verdict] = (out[e.check.verdict] ?? 0) + 1;
16831
+ return out;
16832
+ }
16833
+ function cmdMemory(args, flags, io) {
16834
+ const [sub, ...rest] = args;
16835
+ const s = store(io);
16836
+ switch (sub) {
16837
+ case void 0:
16838
+ case "help":
16839
+ io.stdout(MEMORY_HELP);
16840
+ return 0;
16841
+ case "list":
16842
+ case "check": {
16843
+ let entries = s.checked();
16844
+ if (flags.team) entries = entries.filter((e) => e.scope === "team");
16845
+ const shown = sub === "list" && !flags.all ? entries.filter((e) => e.check.verdict !== "expired" && e.check.verdict !== "superseded") : entries;
16846
+ const bad = entries.filter((e) => ["stale", "conflict", "unsafe"].includes(e.check.verdict));
16847
+ if (flags.json) {
16848
+ io.stdout(`${JSON.stringify({ repo: s.repo, entries: shown.map((e) => ({ id: e.id, scope: e.scope, content: e.content, created_at: e.created_at, verdict: e.check.verdict, serve: e.check.serve, reasons: e.check.reasons })) }, null, 2)}
16849
+ `);
16850
+ } else {
16851
+ const c = summary(entries);
16852
+ io.stdout(`Memory for ${s.repo}: ${entries.length} entr${entries.length === 1 ? "y" : "ies"}${Object.keys(c).length ? ` (${Object.entries(c).map(([k, n2]) => `${n2} ${k}`).join(", ")})` : ""}
16853
+ `);
16854
+ for (const e of sub === "check" ? bad : shown) io.stdout(`${formatEntry(e)}
16855
+ `);
16856
+ if (sub === "check" && bad.length === 0) io.stdout("All entries match the repository.\n");
16857
+ if (bad.length) io.stdout(`
16858
+ Fix with: threadctx memory renew <id> (still true) or threadctx memory forget <id> (wrong).
16859
+ `);
16860
+ }
16861
+ return sub === "check" && bad.length ? 1 : 0;
16862
+ }
16863
+ case "add": {
16864
+ const text = rest.join(" ").trim();
16865
+ if (!text) throw new MemoryUsageError("usage: threadctx memory add <text> [--team]");
16866
+ const { entry: entry2, check } = s.write({ content: text, scope: flags.team ? "team" : "personal" });
16867
+ io.stdout(`Stored ${entry2.scope} memory ${short(entry2.id)}${entry2.scope === "team" ? ` in ${TEAM_FILE}: commit it to share` : ""}.
16868
+ `);
16869
+ if (check.reasons.length && check.verdict !== "review-due") io.stdout(`Warning: ${check.reasons.map((r) => `${r.ruleId}: ${r.message}`).join(" | ")}
16870
+ `);
16871
+ return 0;
16872
+ }
16873
+ case "supersede": {
16874
+ if (!rest[0] || !rest[1]) throw new MemoryUsageError("usage: threadctx memory supersede <old-id> <new-id>");
16875
+ const e = s.supersede(rest[0], rest[1]);
16876
+ io.stdout(`${short(e.id)} is now superseded by ${short(e.superseded_by)} and will no longer be served.
16877
+ `);
16878
+ return 0;
16879
+ }
16880
+ case "renew":
16881
+ case "forget": {
16882
+ if (!rest[0]) throw new MemoryUsageError(`usage: threadctx memory ${sub} <id>`);
16883
+ const e = sub === "renew" ? s.renew(rest[0]) : s.forget(rest[0]);
16884
+ io.stdout(`${sub === "renew" ? "Renewed" : "Forgot"} ${short(e.id)}.
16885
+ `);
16886
+ return 0;
16887
+ }
16888
+ default:
16889
+ throw new MemoryUsageError(`unknown memory command '${sub}'. Run 'threadctx memory help'.`);
16890
+ }
16891
+ }
16892
+ var fmt = (n2) => n2.toLocaleString("en-US");
16893
+ function sessionStartText(root, result, entries, repo, tool = "claude-code") {
16894
+ const label2 = getAdapter(tool)?.label.split(" (")[0] ?? tool;
16895
+ const t = result.tools.find((x) => x.id === tool);
16896
+ const open = result.findings.filter((f) => !f.suppressed);
16897
+ const loaded = new Set(t?.alwaysLoaded ?? []);
16898
+ const inLoaded = open.filter((f) => loaded.has(f.path) && f.severity !== "info");
16899
+ const wasted = open.filter((f) => loaded.has(f.path)).reduce((n2, f) => n2 + (f.wasteTokens ?? 0), 0);
16900
+ const lines = [`threadctx: agent context grade ${result.grade} (${result.score}/100) for ${repo}.`];
16901
+ if (t && t.alwaysLoaded.length) {
16902
+ let s = `${label2} loads ${t.alwaysLoaded.length} instruction file${t.alwaysLoaded.length === 1 ? "" : "s"} every session (\u2248${fmt(t.alwaysTokenEstimate)} tokens)`;
16903
+ if (wasted) s += `, \u2248${fmt(wasted)} of them duplicated`;
16904
+ if (inLoaded.length) s += `; ${inLoaded.length} problem${inLoaded.length === 1 ? "" : "s"}: ${[...new Set(inLoaded.map((f) => f.title.toLowerCase()))].slice(0, 3).join("; ")}`;
16905
+ lines.push(`${s}.`);
16906
+ } else {
16907
+ lines.push(`${label2} loads no instruction files here. \`npx threadctx init\` creates a starting AGENTS.md.`);
16908
+ }
16909
+ const blockers = open.filter((f) => f.severity === "blocker");
16910
+ if (blockers.length) lines.push(`${blockers.length} blocker${blockers.length === 1 ? "" : "s"} (${[...new Set(blockers.map((f) => f.ruleId))].join(", ")}): treat the affected instructions with care and suggest running \`npx threadctx scan\`.`);
16911
+ if (entries.length) {
16912
+ const c = summary(entries);
16913
+ const served = entries.filter((e) => e.check.serve).length;
16914
+ const parts = [`${served} served`];
16915
+ for (const [k, word] of [["stale", "may be stale"], ["conflict", "conflict with the repo"], ["review-due", "due for review"], ["unsafe", "withheld as unsafe"]]) if (c[k]) parts.push(`${c[k]} ${word}`);
16916
+ lines.push(`Checked memory: ${entries.length} entr${entries.length === 1 ? "y" : "ies"} (${parts.join(", ")}). Call memory_query before non-trivial work and memory_write after a non-obvious fix.`);
16917
+ } else {
16918
+ lines.push("Checked memory is empty for this repository. After a non-obvious fix or decision, call memory_write so the next session starts with it.");
16919
+ }
16920
+ void root;
16921
+ return `${lines.join("\n")}
16922
+ `;
16923
+ }
16924
+ function sessionStartBanner(result, entries, tool = "claude-code") {
16925
+ const t = result.tools.find((x) => x.id === tool);
16926
+ const open = result.findings.filter((f) => !f.suppressed);
16927
+ const loaded = new Set(t?.alwaysLoaded ?? []);
16928
+ const wasted = open.filter((f) => loaded.has(f.path)).reduce((n2, f) => n2 + (f.wasteTokens ?? 0), 0);
16929
+ const parts = [`threadctx \xB7 context ${result.grade} (${result.score}/100)`];
16930
+ if (t && t.alwaysLoaded.length) parts.push(`\u2248${fmt(t.alwaysTokenEstimate)} tokens loaded every session${wasted ? `, \u2248${fmt(wasted)} duplicated` : ""}`);
16931
+ const blockers = open.filter((f) => f.severity === "blocker").length;
16932
+ if (blockers) parts.push(`${blockers} blocker${blockers === 1 ? "" : "s"}: run npx threadctx scan`);
16933
+ if (entries.length) {
16934
+ const c = summary(entries);
16935
+ const flagged = (c.stale ?? 0) + (c.conflict ?? 0) + (c.unsafe ?? 0);
16936
+ parts.push(`memory ${entries.filter((e) => e.check.serve).length}/${entries.length} served${flagged ? `, ${flagged} flagged: /memory-review` : ""}`);
16937
+ } else {
16938
+ parts.push("memory empty");
16939
+ }
16940
+ return parts.join(" \xB7 ");
16941
+ }
16942
+ function cmdSessionStart(flags, io) {
16943
+ try {
16944
+ const root = rootOf(io);
16945
+ const result = scan(openRepo(root), { now: io.now() });
16946
+ const s = store(io);
16947
+ const tool = flags.tool ?? "claude-code";
16948
+ const entries = s.checked();
16949
+ const text = sessionStartText(root, result, entries, s.repo, tool);
16950
+ if (flags.format === "hook") {
16951
+ io.stdout(`${JSON.stringify({
16952
+ systemMessage: sessionStartBanner(result, entries, tool),
16953
+ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: text }
16954
+ })}
16955
+ `);
16956
+ } else {
16957
+ io.stdout(text);
16958
+ }
16959
+ } catch {
16960
+ }
16961
+ return 0;
16962
+ }
16963
+
16490
16964
  // src/audit.ts
16491
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
16492
- import { homedir } from "node:os";
16493
- import { join as join4, resolve as resolve3 } from "node:path";
16965
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
16966
+ import { homedir as homedir2 } from "node:os";
16967
+ import { join as join5, resolve as resolve3 } from "node:path";
16494
16968
  import { createHash as createHash3 } from "node:crypto";
16495
16969
 
16496
16970
  // src/remote.ts
16497
- import { execFileSync as execFileSync4 } from "node:child_process";
16971
+ import { execFileSync as execFileSync5 } from "node:child_process";
16498
16972
  function githubToken(env) {
16499
16973
  if (env.GH_TOKEN || env.GITHUB_TOKEN) return env.GH_TOKEN ?? env.GITHUB_TOKEN;
16500
16974
  try {
16501
- return execFileSync4("gh", ["auth", "token"], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim() || void 0;
16975
+ return execFileSync5("gh", ["auth", "token"], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim() || void 0;
16502
16976
  } catch {
16503
16977
  return void 0;
16504
16978
  }
@@ -16509,22 +16983,22 @@ var AuditUsageError = class extends Error {
16509
16983
  };
16510
16984
  var ORG = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
16511
16985
  function findLicense(arg, io) {
16512
- const fromFile = (p) => existsSync3(p) ? readFileSync2(p, "utf8").trim() : void 0;
16986
+ const fromFile = (p) => existsSync4(p) ? readFileSync3(p, "utf8").trim() : void 0;
16513
16987
  if (arg) {
16514
16988
  const file = resolve3(io.cwd, arg);
16515
16989
  const key2 = arg.startsWith("tctx1.") ? arg : fromFile(file);
16516
16990
  return key2 ? { key: key2, source: arg.startsWith("tctx1.") ? "--license" : arg } : { key: arg, source: "--license" };
16517
16991
  }
16518
16992
  if (io.env.THREADCTX_LICENSE) return { key: io.env.THREADCTX_LICENSE.trim(), source: "THREADCTX_LICENSE" };
16519
- const home = join4(io.env.THREADCTX_HOME ?? join4(homedir(), ".threadctx"), "license");
16993
+ const home = join5(io.env.THREADCTX_HOME ?? join5(homedir2(), ".threadctx"), "license");
16520
16994
  const key = fromFile(home);
16521
16995
  return key ? { key, source: home } : void 0;
16522
16996
  }
16523
16997
  function describeLicense(claims) {
16524
- const days = Math.max(0, Math.ceil((claims.exp * 1e3 - Date.now()) / 864e5));
16998
+ const days2 = Math.max(0, Math.ceil((claims.exp * 1e3 - Date.now()) / 864e5));
16525
16999
  const who = claims.orgs?.length ? claims.orgs.join(", ") : claims.org === "*" ? "any organisation" : claims.org;
16526
17000
  const limit = claims.agentRepoLimit ? `, up to ${claims.agentRepoLimit} agent repositories` : "";
16527
- return `${claims.plan} licence for ${who}${limit}, ${days} day${days === 1 ? "" : "s"} left (id ${claims.id})`;
17001
+ return `${claims.plan} licence for ${who}${limit}, ${days2} day${days2 === 1 ? "" : "s"} left (id ${claims.id})`;
16528
17002
  }
16529
17003
  async function runAudit(o, io) {
16530
17004
  if (!ORG.test(o.org)) throw new AuditUsageError(`'${o.org}' is not a valid GitHub organisation or user name`);
@@ -16542,9 +17016,9 @@ async function runAudit(o, io) {
16542
17016
  if (o.baseline) {
16543
17017
  if (!claims) throw new AuditUsageError("--baseline compares two full audits and needs a licence (the free audit has no audit.json to compare).");
16544
17018
  const file = resolve3(io.cwd, o.baseline);
16545
- if (!existsSync3(file)) throw new AuditUsageError(`baseline not found: ${o.baseline}`);
17019
+ if (!existsSync4(file)) throw new AuditUsageError(`baseline not found: ${o.baseline}`);
16546
17020
  try {
16547
- const parsed = JSON.parse(readFileSync2(file, "utf8"));
17021
+ const parsed = JSON.parse(readFileSync3(file, "utf8"));
16548
17022
  if (parsed.schema !== "threadctx.audit/v1") throw new Error("schema");
16549
17023
  previous = parsed;
16550
17024
  } catch {
@@ -16580,14 +17054,14 @@ async function runAudit(o, io) {
16580
17054
  return { ...base, error: e.message.replace(/\s+/g, " ").slice(0, 160) };
16581
17055
  }
16582
17056
  });
16583
- const summary = summarizeFleet(repos, { org: o.org, generatedAt: io.now().toISOString(), engine: { version: ENGINE_VERSION, registry: REGISTRY_VERSION } });
17057
+ const summary2 = summarizeFleet(repos, { org: o.org, generatedAt: io.now().toISOString(), engine: { version: ENGINE_VERSION, registry: REGISTRY_VERSION } });
16584
17058
  if (previous) {
16585
17059
  if (previous.org.toLowerCase() !== o.org.toLowerCase()) io.stderr(`note: the baseline is for ${previous.org}, not ${o.org}; comparing anyway.
16586
17060
  `);
16587
- summary.trend = fleetTrend(previous, summary);
17061
+ summary2.trend = fleetTrend(previous, summary2);
16588
17062
  }
16589
- const evidence = evidencePack(summary, repos);
16590
- const agentRepos = summary.repos.withContext;
17063
+ const evidence = evidencePack(summary2, repos);
17064
+ const agentRepos = summary2.repos.withContext;
16591
17065
  if (claims?.agentRepoLimit && agentRepos > claims.agentRepoLimit) {
16592
17066
  io.stderr(`
16593
17067
  This organisation has ${agentRepos} agent repositories; your ${claims.plan} licence covers up to ${claims.agentRepoLimit}.
@@ -16599,28 +17073,28 @@ Showing the free summary. Upgrade for the full report: https://threadctx.dev/pri
16599
17073
  const files = [];
16600
17074
  if (claims) {
16601
17075
  const dir = resolve3(io.cwd, o.outDir ?? `threadctx-audit-${o.org}`);
16602
- mkdirSync2(dir, { recursive: true });
16603
- const last = join4(dir, "audit.json");
16604
- if (existsSync3(last)) writeFileSync2(join4(dir, "previous-audit.json"), readFileSync2(last));
16605
- const auditJson = renderAuditJson({ ...summary, evidence }, repos);
17076
+ mkdirSync3(dir, { recursive: true });
17077
+ const last = join5(dir, "audit.json");
17078
+ if (existsSync4(last)) writeFileSync3(join5(dir, "previous-audit.json"), readFileSync3(last));
17079
+ const auditJson = renderAuditJson({ ...summary2, evidence }, repos);
16606
17080
  const auditSha256 = createHash3("sha256").update(auditJson).digest("hex");
16607
17081
  for (const [name, body] of [
16608
- ["report.html", renderAuditHtml(summary, repos)],
16609
- ["repos.csv", renderAuditCsv(summary)],
17082
+ ["report.html", renderAuditHtml(summary2, repos)],
17083
+ ["repos.csv", renderAuditCsv(summary2)],
16610
17084
  ["audit.json", auditJson],
16611
17085
  ["evidence.html", renderEvidenceHtml(evidence, { auditSha256 })],
16612
17086
  ["controls.csv", renderControlsCsv(evidence)],
16613
17087
  ["inventory.csv", renderInventoryCsv(evidence)]
16614
17088
  ]) {
16615
- writeFileSync2(join4(dir, name), body);
16616
- files.push(join4(dir, name));
17089
+ writeFileSync3(join5(dir, name), body);
17090
+ files.push(join5(dir, name));
16617
17091
  }
16618
17092
  io.stderr(`Using ${describeLicense(claims)}
16619
17093
  `);
16620
17094
  }
16621
- if (o.json) io.stdout(claims ? renderAuditJson({ ...summary, evidence }, repos) : `${JSON.stringify(summary, null, 2)}
17095
+ if (o.json) io.stdout(claims ? renderAuditJson({ ...summary2, evidence }, repos) : `${JSON.stringify(summary2, null, 2)}
16622
17096
  `);
16623
- else io.stdout(renderAuditText(summary, { color: o.color, licensed: Boolean(claims), files, controls: controlHeadline(evidence) }));
17097
+ else io.stdout(renderAuditText(summary2, { color: o.color, licensed: Boolean(claims), files, controls: controlHeadline(evidence) }));
16624
17098
  return 0;
16625
17099
  }
16626
17100
 
@@ -16681,8 +17155,14 @@ Usage:
16681
17155
  threadctx compare <base.json> <head.json> [--format text|md|json] [--fail-on blocker|warning|info|none]
16682
17156
  What a change introduced, from two 'scan --format json' files.
16683
17157
  Existing findings never fail; only new ones do (net-new ratchet)
16684
- threadctx mcp Run as a read-only MCP server (stdio) so agents can check their own
16685
- instructions: check_context, get_effective_context, explain_rule
17158
+ threadctx mcp Run as an MCP server (stdio): agents check their own instructions
17159
+ (check_context, get_effective_context, explain_rule) and use checked
17160
+ memory (memory_query, memory_write, memory_review)
17161
+ threadctx memory <list|check|add|renew|forget>
17162
+ Checked memory: every entry is verified against the repository
17163
+ before an agent sees it. 'threadctx memory help' for details
17164
+ threadctx session-start [--format hook]
17165
+ Context grade, tokens loaded and memory health, for a SessionStart hook
16686
17166
  threadctx audit --org <name> Grade every repository of a GitHub organisation or user, and find where
16687
17167
  they disagree. Free: fleet grade and headline findings. With a licence:
16688
17168
  full HTML report, CSV and JSON. Code never leaves your machine.
@@ -16733,6 +17213,8 @@ var OPTIONS = {
16733
17213
  "no-badge": { type: "boolean" },
16734
17214
  force: { type: "boolean" },
16735
17215
  json: { type: "boolean" },
17216
+ team: { type: "boolean" },
17217
+ all: { type: "boolean" },
16736
17218
  color: { type: "boolean" },
16737
17219
  "no-color": { type: "boolean" },
16738
17220
  "no-telemetry": { type: "boolean" },
@@ -16744,7 +17226,7 @@ async function main(argv, io) {
16744
17226
  try {
16745
17227
  return await run2(argv, io);
16746
17228
  } catch (e) {
16747
- if (e instanceof UsageError || e instanceof ConfigError || e instanceof PackError) {
17229
+ if (e instanceof UsageError || e instanceof ConfigError || e instanceof PackError || e instanceof MemoryUsageError) {
16748
17230
  io.stderr(`threadctx: ${e.message}
16749
17231
  `);
16750
17232
  return 2;
@@ -16782,8 +17264,17 @@ Run 'threadctx --help' for usage.`);
16782
17264
  return cmdBadge(args[0], v, io);
16783
17265
  case "mcp":
16784
17266
  if (!io.stdin) throw new UsageError("mcp needs standard input");
16785
- await serveMcp({ stdin: io.stdin, write: io.stdout, root: io.cwd });
17267
+ await serveMcp({ stdin: io.stdin, write: io.stdout, root: io.cwd, env: io.env, now: io.now });
16786
17268
  return 0;
17269
+ case "memory":
17270
+ try {
17271
+ return cmdMemory(args, { team: v.team, all: v.all, json: v.json }, io);
17272
+ } catch (e) {
17273
+ if (e instanceof MemoryUsageError) throw e;
17274
+ throw new UsageError(e.message);
17275
+ }
17276
+ case "session-start":
17277
+ return cmdSessionStart({ tool: v.tool, format: v.format }, io);
16787
17278
  case "audit":
16788
17279
  return cmdAudit(v, io, color);
16789
17280
  case "license":
@@ -16811,7 +17302,7 @@ Run 'threadctx --help' for usage.`);
16811
17302
  }
16812
17303
  function openRoot(pathArg, io) {
16813
17304
  const target = resolve4(io.cwd, pathArg ?? ".");
16814
- if (!existsSync4(target)) throw new UsageError(`path not found: ${pathArg}`);
17305
+ if (!existsSync5(target)) throw new UsageError(`path not found: ${pathArg}`);
16815
17306
  if (!statSync3(target).isDirectory()) throw new UsageError(`not a directory: ${pathArg} (scan takes a repository or directory)`);
16816
17307
  return openRepo(target);
16817
17308
  }
@@ -16860,8 +17351,8 @@ async function cmdScan(pathArg, v, io, color) {
16860
17351
  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), next: !v.output && !remoteLabel ? nextSteps(result, v, io) : void 0 });
16861
17352
  if (v.output) {
16862
17353
  const dest = resolve4(io.cwd, v.output);
16863
- mkdirSync3(dirname2(dest), { recursive: true });
16864
- writeFileSync3(dest, out);
17354
+ mkdirSync4(dirname3(dest), { recursive: true });
17355
+ writeFileSync4(dest, out);
16865
17356
  io.stderr(`Wrote ${format} report to ${relative3(io.cwd, dest) || dest} \u2014 grade ${result.grade}, ${result.counts.blocker} blocker, ${result.counts.warning} warning
16866
17357
  `);
16867
17358
  } else {
@@ -16886,9 +17377,9 @@ function cmdCompare(baseFile, headFile, v, io) {
16886
17377
  if (!["text", "md", "json"].includes(format)) throw new UsageError("--format must be text, md or json");
16887
17378
  const readScan = (file) => {
16888
17379
  const abs = resolve4(io.cwd, file);
16889
- if (!existsSync4(abs)) throw new UsageError(`file not found: ${file}`);
17380
+ if (!existsSync5(abs)) throw new UsageError(`file not found: ${file}`);
16890
17381
  try {
16891
- return parseScanJson(readFileSync3(abs, "utf8"), file);
17382
+ return parseScanJson(readFileSync4(abs, "utf8"), file);
16892
17383
  } catch (e) {
16893
17384
  if (e instanceof CompareError) throw new UsageError(e.message);
16894
17385
  throw e;
@@ -16916,15 +17407,15 @@ function cmdCompare(baseFile, headFile, v, io) {
16916
17407
  }
16917
17408
  if (v.output) {
16918
17409
  const dest = resolve4(io.cwd, v.output);
16919
- mkdirSync3(dirname2(dest), { recursive: true });
16920
- writeFileSync3(dest, out);
17410
+ mkdirSync4(dirname3(dest), { recursive: true });
17411
+ writeFileSync4(dest, out);
16921
17412
  } else io.stdout(out);
16922
17413
  return compareExitCode(c, failOn);
16923
17414
  }
16924
17415
  function defaultBaseline(org, outDir, license, io) {
16925
17416
  if (!/^[A-Za-z0-9-]{1,39}$/.test(org)) return void 0;
16926
- const file = join5(resolve4(io.cwd, outDir ?? `threadctx-audit-${org}`), "audit.json");
16927
- return existsSync4(file) && findLicense(license, io) ? file : void 0;
17417
+ const file = join6(resolve4(io.cwd, outDir ?? `threadctx-audit-${org}`), "audit.json");
17418
+ return existsSync5(file) && findLicense(license, io) ? file : void 0;
16928
17419
  }
16929
17420
  async function cmdAudit(v, io, color) {
16930
17421
  if (!v.org) throw new UsageError("usage: threadctx audit --org <github-org-or-user>");
@@ -16967,17 +17458,17 @@ function cmdBadge(pathArg, v, io) {
16967
17458
  function locate(fileArg, io) {
16968
17459
  const real = (p) => {
16969
17460
  try {
16970
- return realpathSync2(p);
17461
+ return realpathSync3(p);
16971
17462
  } catch {
16972
17463
  return p;
16973
17464
  }
16974
17465
  };
16975
17466
  const given = resolve4(io.cwd, fileArg);
16976
- const abs = existsSync4(given) ? real(given) : join5(real(dirname2(given)), basename(given));
16977
- const root = real(gitRoot(existsSync4(abs) && statSync3(abs).isDirectory() ? abs : dirname2(abs)) ?? io.cwd);
17467
+ const abs = existsSync5(given) ? real(given) : join6(real(dirname3(given)), basename2(given));
17468
+ const root = real(gitRoot(existsSync5(abs) && statSync3(abs).isDirectory() ? abs : dirname3(abs)) ?? io.cwd);
16978
17469
  const rel = relative3(root, abs).split(sep3).join("/");
16979
17470
  if (rel.startsWith("..")) throw new UsageError(`${fileArg} is outside the repository at ${root}`);
16980
- const isDir = existsSync4(abs) && statSync3(abs).isDirectory();
17471
+ const isDir = existsSync5(abs) && statSync3(abs).isDirectory();
16981
17472
  return { repo: openRepo(root), target: { path: rel === "" ? "" : rel, isDir } };
16982
17473
  }
16983
17474
  function contextsFor(repo, target, toolArg, surface) {
@@ -17068,13 +17559,13 @@ function cmdFix(pathArg, v, io) {
17068
17559
  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);
17069
17560
  }
17070
17561
  if (v.apply) {
17071
- for (const [p, { after }] of plan.files) writeFileSync3(join5(repo.root, p), after);
17562
+ for (const [p, { after }] of plan.files) writeFileSync4(join6(repo.root, p), after);
17072
17563
  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.
17073
17564
  `);
17074
17565
  return 0;
17075
17566
  }
17076
17567
  if (v.output) {
17077
- writeFileSync3(resolve4(io.cwd, v.output), plan.patch);
17568
+ writeFileSync4(resolve4(io.cwd, v.output), plan.patch);
17078
17569
  io.stderr(`Wrote ${plan.applied.length} fix${plan.applied.length === 1 ? "" : "es"} to ${v.output}. Apply with: git apply ${v.output}
17079
17570
  `);
17080
17571
  } else {
@@ -17098,7 +17589,7 @@ function withPr(open, io) {
17098
17589
  }
17099
17590
  function isPublicOnGitHub(root, env) {
17100
17591
  try {
17101
- return execFileSync5("gh", ["repo", "view", "--json", "visibility", "--jq", ".visibility"], { cwd: root, env, stdio: ["ignore", "pipe", "ignore"], timeout: 15e3 }).toString().trim() === "PUBLIC";
17592
+ return execFileSync6("gh", ["repo", "view", "--json", "visibility", "--jq", ".visibility"], { cwd: root, env, stdio: ["ignore", "pipe", "ignore"], timeout: 15e3 }).toString().trim() === "PUBLIC";
17102
17593
  } catch {
17103
17594
  return false;
17104
17595
  }
@@ -17107,17 +17598,17 @@ function cmdInit(pathArg, v, io) {
17107
17598
  const repo = openRoot(pathArg, io);
17108
17599
  const files = /* @__PURE__ */ new Map();
17109
17600
  const notes = [];
17110
- if (existsSync4(join5(repo.root, WORKFLOW_PATH)) && !v.force) notes.push(`${WORKFLOW_PATH} already exists (use --force to replace it)`);
17601
+ if (existsSync5(join6(repo.root, WORKFLOW_PATH)) && !v.force) notes.push(`${WORKFLOW_PATH} already exists (use --force to replace it)`);
17111
17602
  else files.set(WORKFLOW_PATH, workflowYaml());
17112
17603
  if (!v["no-badge"]) {
17113
17604
  const result = doScan(repo, v, io);
17114
17605
  const fullName = githubRemote(repo.root);
17115
17606
  const badge = fullName && isPublicOnGitHub(repo.root, io.env) ? renderLiveBadge(fullName) : renderBadge(result, badgeLinkFor(fullName));
17116
- const readmeName = ["README.md", "readme.md", "Readme.md"].find((n2) => existsSync4(join5(repo.root, n2)));
17607
+ const readmeName = ["README.md", "readme.md", "Readme.md"].find((n2) => existsSync5(join6(repo.root, n2)));
17117
17608
  if (!readmeName) notes.push(`no README.md; add this badge where you like:
17118
17609
  ${badge.markdown}`);
17119
17610
  else {
17120
- const before = readFileSync3(join5(repo.root, readmeName), "utf8");
17611
+ const before = readFileSync4(join6(repo.root, readmeName), "utf8");
17121
17612
  const after = withBadge(before, badge.markdown);
17122
17613
  if (after === before) notes.push(`${readmeName} already has an agent context badge`);
17123
17614
  else files.set(readmeName, after);
@@ -17141,8 +17632,8 @@ function cmdInit(pathArg, v, io) {
17141
17632
  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);
17142
17633
  }
17143
17634
  for (const [p, content] of files) {
17144
- mkdirSync3(dirname2(join5(repo.root, p)), { recursive: true });
17145
- writeFileSync3(join5(repo.root, p), content);
17635
+ mkdirSync4(dirname3(join6(repo.root, p)), { recursive: true });
17636
+ writeFileSync4(join6(repo.root, p), content);
17146
17637
  io.stderr(`wrote ${p}
17147
17638
  `);
17148
17639
  }
@@ -17187,8 +17678,8 @@ function cmdTools(v, io) {
17187
17678
  }
17188
17679
  function cmdPackValidate(file, io) {
17189
17680
  const abs = resolve4(io.cwd, file);
17190
- if (!existsSync4(abs)) throw new UsageError(`file not found: ${file}`);
17191
- const pack = parsePack(readFileSync3(abs, "utf8"), file);
17681
+ if (!existsSync5(abs)) throw new UsageError(`file not found: ${file}`);
17682
+ const pack = parsePack(readFileSync4(abs, "utf8"), file);
17192
17683
  io.stdout(`${pack.pack}: ${pack.rules.length} rule${pack.rules.length === 1 ? "" : "s"} valid
17193
17684
  `);
17194
17685
  for (const r of pack.rules) io.stdout(` ${pack.pack}/${r.id} ${r.severity} ${r.title}
@@ -17214,10 +17705,10 @@ function nextSteps(result, v, io) {
17214
17705
  var UPGRADE_URL = "https://threadctx.dev/pricing";
17215
17706
  function maybeUpgradeLine(result, io, remote) {
17216
17707
  if (!UPGRADE_URL || !io.isTTY || io.env.CI || io.env.THREADCTX_NO_UPSELL) return;
17217
- const stateFile = join5(io.env.THREADCTX_HOME ?? join5(homedir2(), ".threadctx"), "state.json");
17708
+ const stateFile = join6(io.env.THREADCTX_HOME ?? join6(homedir3(), ".threadctx"), "state.json");
17218
17709
  let state = {};
17219
17710
  try {
17220
- state = JSON.parse(readFileSync3(stateFile, "utf8"));
17711
+ state = JSON.parse(readFileSync4(stateFile, "utf8"));
17221
17712
  } catch {
17222
17713
  }
17223
17714
  const today = io.now().toISOString().slice(0, 10);
@@ -17228,13 +17719,17 @@ function maybeUpgradeLine(result, io, remote) {
17228
17719
  ${msg}
17229
17720
  `);
17230
17721
  try {
17231
- mkdirSync3(dirname2(stateFile), { recursive: true });
17232
- writeFileSync3(stateFile, JSON.stringify({ ...state, lastUpsell: today }));
17722
+ mkdirSync4(dirname3(stateFile), { recursive: true });
17723
+ writeFileSync4(stateFile, JSON.stringify({ ...state, lastUpsell: today }));
17233
17724
  } catch {
17234
17725
  }
17235
17726
  }
17236
17727
 
17237
17728
  // src/bin.ts
17729
+ process.stdout.on("error", (e) => {
17730
+ if (e.code === "EPIPE") process.exit(process.exitCode ?? 0);
17731
+ throw e;
17732
+ });
17238
17733
  var code = await main(process.argv.slice(2), {
17239
17734
  cwd: process.cwd(),
17240
17735
  env: process.env,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "threadctx",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "mcpName": "io.github.threadctx-dev/threadctx",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -56,11 +56,11 @@
56
56
  "dependencies": {},
57
57
  "devDependencies": {
58
58
  "diff": "^9.0.0",
59
- "@threadctx/report": "0.1.0",
60
- "@threadctx/rules": "0.1.0",
61
- "@threadctx/adapters": "0.1.0",
62
59
  "@threadctx/core": "0.1.0",
63
- "@threadctx/discovery": "0.1.0"
60
+ "@threadctx/discovery": "0.1.0",
61
+ "@threadctx/adapters": "0.1.0",
62
+ "@threadctx/rules": "0.1.0",
63
+ "@threadctx/report": "0.1.0"
64
64
  },
65
65
  "scripts": {
66
66
  "build": "tsc -b && node build.mjs"