threadctx 0.4.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -0
- package/dist/threadctx.mjs +574 -88
- package/package.json +13 -5
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
|
package/dist/threadctx.mjs
CHANGED
|
@@ -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
|
|
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 ?
|
|
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
|
|
9990
|
-
import { homedir as
|
|
9991
|
-
import { basename, dirname as
|
|
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
|
-
"
|
|
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
|
-
"
|
|
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.
|
|
14742
|
+
var ENGINE_VERSION = "0.6.0";
|
|
14743
14743
|
var REGISTRY_VERSION = "2026.10.1";
|
|
14744
14744
|
|
|
14745
14745
|
// ../rules/dist/engine.js
|
|
@@ -14910,7 +14910,7 @@ function scan(fs, opts = {}) {
|
|
|
14910
14910
|
findings: unique,
|
|
14911
14911
|
diagnostics,
|
|
14912
14912
|
artifacts: artifacts.map((a) => ({ path: a.artifact.path, tool: a.artifact.tool, kind: a.artifact.kind, tokenEstimate: a.artifact.tokenEstimate, contentHash: a.artifact.contentHash, origin: a.artifact.origin })),
|
|
14913
|
-
tools: ADAPTERS.map((a, i) => ({ id: a.id, label: a.label, status: a.status, verified: a.verifiedAgainst.date, alwaysTokenEstimate: state.rootContexts[i].alwaysTokenEstimate, layers: state.rootContexts[i].layers.length })),
|
|
14913
|
+
tools: ADAPTERS.map((a, i) => ({ id: a.id, label: a.label, status: a.status, verified: a.verifiedAgainst.date, alwaysTokenEstimate: state.rootContexts[i].alwaysTokenEstimate, layers: state.rootContexts[i].layers.length, alwaysLoaded: [...new Set(state.rootContexts[i].layers.filter((l) => l.loading === "always").map((l) => l.path))] })),
|
|
14914
14914
|
mcpServers: state.mcp.map((s) => ({ client: s.client, name: s.name, source: s.sourcePath, transport: s.transport })),
|
|
14915
14915
|
rules: [...metas.values()].filter((m) => checks.some((c) => c.meta.id === m.id)),
|
|
14916
14916
|
facts: statedFacts(ctx)
|
|
@@ -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(
|
|
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(
|
|
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 =
|
|
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:
|
|
15296
|
-
generatedAt:
|
|
15297
|
-
engine:
|
|
15298
|
-
scope: { repositoriesListed:
|
|
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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
15320
15407
|
var TOOL_LABEL2 = { "agents-md": "AGENTS.md", "claude-code": "Claude Code", cursor: "Cursor", copilot: "GitHub Copilot", gemini: "Gemini CLI" };
|
|
@@ -15477,6 +15564,27 @@ function painter(color) {
|
|
|
15477
15564
|
return { red: wrap("31"), yellow: wrap("33"), blue: wrap("34"), green: wrap("32"), dim: wrap("2"), bold: wrap("1"), cyan: wrap("36") };
|
|
15478
15565
|
}
|
|
15479
15566
|
var GRADE_COLOR = { A: "green", B: "green", C: "yellow", D: "yellow", F: "red" };
|
|
15567
|
+
var SHORT_LABEL = { "agents-md": "Codex / AGENTS.md" };
|
|
15568
|
+
function renderAgentMap(result, p) {
|
|
15569
|
+
const tools = result.tools;
|
|
15570
|
+
if (!tools.some((t) => t.layers > 0))
|
|
15571
|
+
return [];
|
|
15572
|
+
const label2 = (t) => SHORT_LABEL[t.id] ?? t.label.split(" (")[0];
|
|
15573
|
+
const width = Math.max(...tools.map((t) => label2(t).length));
|
|
15574
|
+
const sharedExists = result.artifacts.some((a) => a.path === "AGENTS.md");
|
|
15575
|
+
const lines = ["", p.bold("What each agent loads at session start")];
|
|
15576
|
+
for (const t of tools) {
|
|
15577
|
+
const files = t.alwaysLoaded ?? [];
|
|
15578
|
+
const name = label2(t).padEnd(width);
|
|
15579
|
+
if (!files.length) {
|
|
15580
|
+
lines.push(` ${name} ${p.dim("nothing: this agent starts with no repository instructions")}`);
|
|
15581
|
+
continue;
|
|
15582
|
+
}
|
|
15583
|
+
const missesShared = sharedExists && t.id !== "agents-md" && !files.includes("AGENTS.md");
|
|
15584
|
+
lines.push(` ${name} ${files.join(" \u2192 ")} ${p.dim(`\u2248${t.alwaysTokenEstimate.toLocaleString("en-US")} tokens`)}` + (missesShared ? ` ${p.yellow("does not see AGENTS.md")}` : ""));
|
|
15585
|
+
}
|
|
15586
|
+
return lines;
|
|
15587
|
+
}
|
|
15480
15588
|
function renderText(result, opts) {
|
|
15481
15589
|
const p = painter(opts.color);
|
|
15482
15590
|
const out = [];
|
|
@@ -15502,10 +15610,7 @@ function renderText(result, opts) {
|
|
|
15502
15610
|
const fixable = open.filter((f) => f.fix?.kind === "safe").length;
|
|
15503
15611
|
if (fixable)
|
|
15504
15612
|
out.push(p.dim(`${fixable} finding${fixable === 1 ? "" : "s"} can be fixed automatically: threadctx fix`));
|
|
15505
|
-
|
|
15506
|
-
if (tools.length) {
|
|
15507
|
-
out.push(p.dim(`Always-loaded context (estimated tokens): ${tools.map((t) => `${t.label.split(" (")[0]} \u2248${t.alwaysTokenEstimate.toLocaleString("en-US")}`).join(" \xB7 ")}`));
|
|
15508
|
-
}
|
|
15613
|
+
out.push(...renderAgentMap(result, p));
|
|
15509
15614
|
if (opts.next?.length) {
|
|
15510
15615
|
const width = Math.max(...opts.next.map(([cmd]) => cmd.length));
|
|
15511
15616
|
out.push("", p.bold("Next"), ...opts.next.map(([cmd, why]) => ` ${p.cyan(cmd.padEnd(width))} ${p.dim(why)}`));
|
|
@@ -15607,7 +15712,7 @@ function renderLiveBadge(fullName) {
|
|
|
15607
15712
|
}
|
|
15608
15713
|
|
|
15609
15714
|
// src/cli.ts
|
|
15610
|
-
import { execFileSync as
|
|
15715
|
+
import { execFileSync as execFileSync6 } from "node:child_process";
|
|
15611
15716
|
|
|
15612
15717
|
// ../../node_modules/.pnpm/diff@9.0.0/node_modules/diff/libesm/diff/base.js
|
|
15613
15718
|
var Diff = class {
|
|
@@ -16168,7 +16273,7 @@ function planFixes(fs, findings, kinds = ["safe"]) {
|
|
|
16168
16273
|
}
|
|
16169
16274
|
|
|
16170
16275
|
// src/init.ts
|
|
16171
|
-
var ACTION_PIN = { sha: "
|
|
16276
|
+
var ACTION_PIN = { sha: "446c4025a766f288e992d85b98790ba25e21367e", tag: "v1.5.0" };
|
|
16172
16277
|
var CHECKOUT_PIN = { sha: "3d3c42e5aac5ba805825da76410c181273ba90b1", tag: "v7.0.1" };
|
|
16173
16278
|
var WORKFLOW_PATH = ".github/workflows/agent-context.yml";
|
|
16174
16279
|
function workflowYaml() {
|
|
@@ -16304,19 +16409,169 @@ function githubRemote(dir) {
|
|
|
16304
16409
|
}
|
|
16305
16410
|
|
|
16306
16411
|
// src/mcp.ts
|
|
16307
|
-
import { existsSync as
|
|
16412
|
+
import { existsSync as existsSync3, realpathSync, statSync as statSync2 } from "node:fs";
|
|
16308
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
|
|
16309
16562
|
var SUPPORTED_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
|
|
16310
16563
|
var MAX_TEXT = 2e4;
|
|
16311
16564
|
var TOOLS = [
|
|
16312
16565
|
{
|
|
16313
16566
|
name: "check_context",
|
|
16567
|
+
title: "Check agent context",
|
|
16314
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.",
|
|
16315
16569
|
inputSchema: { type: "object", properties: { path: { type: "string", description: "Directory to check, relative to the project root. Defaults to the root." } }, additionalProperties: false },
|
|
16316
16570
|
annotations: { readOnlyHint: true, openWorldHint: false }
|
|
16317
16571
|
},
|
|
16318
16572
|
{
|
|
16319
16573
|
name: "get_effective_context",
|
|
16574
|
+
title: "Show what each agent loads",
|
|
16320
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.",
|
|
16321
16576
|
inputSchema: {
|
|
16322
16577
|
type: "object",
|
|
@@ -16331,12 +16586,61 @@ var TOOLS = [
|
|
|
16331
16586
|
},
|
|
16332
16587
|
{
|
|
16333
16588
|
name: "explain_rule",
|
|
16589
|
+
title: "Explain a threadctx rule",
|
|
16334
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.",
|
|
16335
16591
|
inputSchema: { type: "object", properties: { id: { type: "string", description: "Rule id, for example CTX-C001." } }, required: ["id"], additionalProperties: false },
|
|
16336
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 }
|
|
16337
16641
|
}
|
|
16338
16642
|
];
|
|
16339
|
-
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.
|
|
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.";
|
|
16340
16644
|
function clip(text) {
|
|
16341
16645
|
return text.length > MAX_TEXT ? `${text.slice(0, MAX_TEXT)}
|
|
16342
16646
|
\u2026(truncated)` : text;
|
|
@@ -16344,7 +16648,7 @@ function clip(text) {
|
|
|
16344
16648
|
function confine(root, input) {
|
|
16345
16649
|
const realRoot = realpathSync(root);
|
|
16346
16650
|
const abs = resolve2(realRoot, input);
|
|
16347
|
-
const real =
|
|
16651
|
+
const real = existsSync3(abs) ? realpathSync(abs) : abs;
|
|
16348
16652
|
const rel = relative2(realRoot, real);
|
|
16349
16653
|
if (rel === ".." || rel.startsWith(`..${sep2}`) || isAbsolute(rel)) throw new Error("path is outside the project");
|
|
16350
16654
|
return real;
|
|
@@ -16354,12 +16658,43 @@ function summarize(result) {
|
|
|
16354
16658
|
const lines = [`Grade ${result.grade} (${result.score}/100): ${result.counts.blocker} blockers, ${result.counts.warning} warnings, ${result.counts.info} info.`];
|
|
16355
16659
|
for (const f of open.slice(0, 25)) lines.push(`- ${f.severity} ${f.ruleId} ${f.path || "."}${f.line ? `:${f.line}` : ""}: ${f.message}${f.fix?.kind === "safe" ? " (fixable: threadctx fix)" : ""}`);
|
|
16356
16660
|
if (open.length > 25) lines.push(`\u2026and ${open.length - 25} more.`);
|
|
16357
|
-
const loaded = result.tools.filter((t) => t.layers > 0)
|
|
16358
|
-
if (loaded.length)
|
|
16661
|
+
const loaded = result.tools.filter((t) => t.layers > 0);
|
|
16662
|
+
if (loaded.length) {
|
|
16663
|
+
lines.push("Loaded at session start (estimates):");
|
|
16664
|
+
for (const t of result.tools) lines.push(`- ${t.label.split(" (")[0]}: ${t.alwaysLoaded.length ? `${t.alwaysLoaded.join(" \u2192 ")} (\u2248${t.alwaysTokenEstimate} tokens)` : "nothing"}`);
|
|
16665
|
+
}
|
|
16359
16666
|
return lines.join("\n");
|
|
16360
16667
|
}
|
|
16361
|
-
|
|
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 });
|
|
16362
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
|
+
}
|
|
16363
16698
|
case "check_context": {
|
|
16364
16699
|
const dir = confine(root, typeof args.path === "string" ? args.path : ".");
|
|
16365
16700
|
if (!statSync2(dir).isDirectory()) throw new Error("path must be a directory");
|
|
@@ -16369,7 +16704,7 @@ function callTool(name, args, root) {
|
|
|
16369
16704
|
if (typeof args.file !== "string" || !args.file) throw new Error("file is required");
|
|
16370
16705
|
const abs = confine(root, args.file);
|
|
16371
16706
|
const rel = relative2(realpathSync(root), abs).split(sep2).join("/");
|
|
16372
|
-
const isDir =
|
|
16707
|
+
const isDir = existsSync3(abs) && statSync2(abs).isDirectory();
|
|
16373
16708
|
const repo = openRepo(root);
|
|
16374
16709
|
const state = prepare(repo);
|
|
16375
16710
|
const tool = typeof args.tool === "string" && args.tool !== "all" ? args.tool : void 0;
|
|
@@ -16392,7 +16727,7 @@ Source: ${r.citation}`;
|
|
|
16392
16727
|
throw new Error(`unknown tool '${name}'`);
|
|
16393
16728
|
}
|
|
16394
16729
|
}
|
|
16395
|
-
function handleMessage(raw, root) {
|
|
16730
|
+
function handleMessage(raw, root, menv) {
|
|
16396
16731
|
const msg = raw;
|
|
16397
16732
|
if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0" || typeof msg.method !== "string") {
|
|
16398
16733
|
return { jsonrpc: "2.0", id: msg?.id ?? null, error: { code: -32600, message: "Invalid Request" } };
|
|
@@ -16420,7 +16755,7 @@ function handleMessage(raw, root) {
|
|
|
16420
16755
|
if (typeof name !== "string" || !TOOLS.some((t) => t.name === name)) return fail2(-32602, `Unknown tool: ${String(name)}`);
|
|
16421
16756
|
const args = msg.params?.arguments ?? {};
|
|
16422
16757
|
try {
|
|
16423
|
-
return ok({ content: [{ type: "text", text: clip(callTool(name, args, root)) }] });
|
|
16758
|
+
return ok({ content: [{ type: "text", text: clip(callTool(name, args, root, menv)) }] });
|
|
16424
16759
|
} catch (e) {
|
|
16425
16760
|
return ok({ isError: true, content: [{ type: "text", text: `Error: ${e.message}` }] });
|
|
16426
16761
|
}
|
|
@@ -16431,6 +16766,7 @@ function handleMessage(raw, root) {
|
|
|
16431
16766
|
}
|
|
16432
16767
|
}
|
|
16433
16768
|
async function serveMcp(io) {
|
|
16769
|
+
const menv = { env: io.env ?? process.env, now: io.now ?? (() => /* @__PURE__ */ new Date()) };
|
|
16434
16770
|
let buffer = "";
|
|
16435
16771
|
const handle = (line) => {
|
|
16436
16772
|
if (!line.trim()) return;
|
|
@@ -16444,7 +16780,7 @@ async function serveMcp(io) {
|
|
|
16444
16780
|
}
|
|
16445
16781
|
const batch = Array.isArray(parsed) ? parsed : [parsed];
|
|
16446
16782
|
for (const m of batch) {
|
|
16447
|
-
const res = handleMessage(m, io.root);
|
|
16783
|
+
const res = handleMessage(m, io.root, menv);
|
|
16448
16784
|
if (res) io.write(`${JSON.stringify(res)}
|
|
16449
16785
|
`);
|
|
16450
16786
|
}
|
|
@@ -16466,18 +16802,148 @@ async function serveMcp(io) {
|
|
|
16466
16802
|
});
|
|
16467
16803
|
}
|
|
16468
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 cmdSessionStart(flags, io) {
|
|
16925
|
+
try {
|
|
16926
|
+
const root = rootOf(io);
|
|
16927
|
+
const result = scan(openRepo(root), { now: io.now() });
|
|
16928
|
+
const s = store(io);
|
|
16929
|
+
io.stdout(sessionStartText(root, result, s.checked(), s.repo, flags.tool ?? "claude-code"));
|
|
16930
|
+
} catch {
|
|
16931
|
+
}
|
|
16932
|
+
return 0;
|
|
16933
|
+
}
|
|
16934
|
+
|
|
16469
16935
|
// src/audit.ts
|
|
16470
|
-
import { existsSync as
|
|
16471
|
-
import { homedir } from "node:os";
|
|
16472
|
-
import { join as
|
|
16936
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
|
|
16937
|
+
import { homedir as homedir2 } from "node:os";
|
|
16938
|
+
import { join as join5, resolve as resolve3 } from "node:path";
|
|
16473
16939
|
import { createHash as createHash3 } from "node:crypto";
|
|
16474
16940
|
|
|
16475
16941
|
// src/remote.ts
|
|
16476
|
-
import { execFileSync as
|
|
16942
|
+
import { execFileSync as execFileSync5 } from "node:child_process";
|
|
16477
16943
|
function githubToken(env) {
|
|
16478
16944
|
if (env.GH_TOKEN || env.GITHUB_TOKEN) return env.GH_TOKEN ?? env.GITHUB_TOKEN;
|
|
16479
16945
|
try {
|
|
16480
|
-
return
|
|
16946
|
+
return execFileSync5("gh", ["auth", "token"], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim() || void 0;
|
|
16481
16947
|
} catch {
|
|
16482
16948
|
return void 0;
|
|
16483
16949
|
}
|
|
@@ -16488,22 +16954,22 @@ var AuditUsageError = class extends Error {
|
|
|
16488
16954
|
};
|
|
16489
16955
|
var ORG = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
|
|
16490
16956
|
function findLicense(arg, io) {
|
|
16491
|
-
const fromFile = (p) =>
|
|
16957
|
+
const fromFile = (p) => existsSync4(p) ? readFileSync3(p, "utf8").trim() : void 0;
|
|
16492
16958
|
if (arg) {
|
|
16493
16959
|
const file = resolve3(io.cwd, arg);
|
|
16494
16960
|
const key2 = arg.startsWith("tctx1.") ? arg : fromFile(file);
|
|
16495
16961
|
return key2 ? { key: key2, source: arg.startsWith("tctx1.") ? "--license" : arg } : { key: arg, source: "--license" };
|
|
16496
16962
|
}
|
|
16497
16963
|
if (io.env.THREADCTX_LICENSE) return { key: io.env.THREADCTX_LICENSE.trim(), source: "THREADCTX_LICENSE" };
|
|
16498
|
-
const home =
|
|
16964
|
+
const home = join5(io.env.THREADCTX_HOME ?? join5(homedir2(), ".threadctx"), "license");
|
|
16499
16965
|
const key = fromFile(home);
|
|
16500
16966
|
return key ? { key, source: home } : void 0;
|
|
16501
16967
|
}
|
|
16502
16968
|
function describeLicense(claims) {
|
|
16503
|
-
const
|
|
16969
|
+
const days2 = Math.max(0, Math.ceil((claims.exp * 1e3 - Date.now()) / 864e5));
|
|
16504
16970
|
const who = claims.orgs?.length ? claims.orgs.join(", ") : claims.org === "*" ? "any organisation" : claims.org;
|
|
16505
16971
|
const limit = claims.agentRepoLimit ? `, up to ${claims.agentRepoLimit} agent repositories` : "";
|
|
16506
|
-
return `${claims.plan} licence for ${who}${limit}, ${
|
|
16972
|
+
return `${claims.plan} licence for ${who}${limit}, ${days2} day${days2 === 1 ? "" : "s"} left (id ${claims.id})`;
|
|
16507
16973
|
}
|
|
16508
16974
|
async function runAudit(o, io) {
|
|
16509
16975
|
if (!ORG.test(o.org)) throw new AuditUsageError(`'${o.org}' is not a valid GitHub organisation or user name`);
|
|
@@ -16521,9 +16987,9 @@ async function runAudit(o, io) {
|
|
|
16521
16987
|
if (o.baseline) {
|
|
16522
16988
|
if (!claims) throw new AuditUsageError("--baseline compares two full audits and needs a licence (the free audit has no audit.json to compare).");
|
|
16523
16989
|
const file = resolve3(io.cwd, o.baseline);
|
|
16524
|
-
if (!
|
|
16990
|
+
if (!existsSync4(file)) throw new AuditUsageError(`baseline not found: ${o.baseline}`);
|
|
16525
16991
|
try {
|
|
16526
|
-
const parsed = JSON.parse(
|
|
16992
|
+
const parsed = JSON.parse(readFileSync3(file, "utf8"));
|
|
16527
16993
|
if (parsed.schema !== "threadctx.audit/v1") throw new Error("schema");
|
|
16528
16994
|
previous = parsed;
|
|
16529
16995
|
} catch {
|
|
@@ -16559,14 +17025,14 @@ async function runAudit(o, io) {
|
|
|
16559
17025
|
return { ...base, error: e.message.replace(/\s+/g, " ").slice(0, 160) };
|
|
16560
17026
|
}
|
|
16561
17027
|
});
|
|
16562
|
-
const
|
|
17028
|
+
const summary2 = summarizeFleet(repos, { org: o.org, generatedAt: io.now().toISOString(), engine: { version: ENGINE_VERSION, registry: REGISTRY_VERSION } });
|
|
16563
17029
|
if (previous) {
|
|
16564
17030
|
if (previous.org.toLowerCase() !== o.org.toLowerCase()) io.stderr(`note: the baseline is for ${previous.org}, not ${o.org}; comparing anyway.
|
|
16565
17031
|
`);
|
|
16566
|
-
|
|
17032
|
+
summary2.trend = fleetTrend(previous, summary2);
|
|
16567
17033
|
}
|
|
16568
|
-
const evidence = evidencePack(
|
|
16569
|
-
const agentRepos =
|
|
17034
|
+
const evidence = evidencePack(summary2, repos);
|
|
17035
|
+
const agentRepos = summary2.repos.withContext;
|
|
16570
17036
|
if (claims?.agentRepoLimit && agentRepos > claims.agentRepoLimit) {
|
|
16571
17037
|
io.stderr(`
|
|
16572
17038
|
This organisation has ${agentRepos} agent repositories; your ${claims.plan} licence covers up to ${claims.agentRepoLimit}.
|
|
@@ -16578,28 +17044,28 @@ Showing the free summary. Upgrade for the full report: https://threadctx.dev/pri
|
|
|
16578
17044
|
const files = [];
|
|
16579
17045
|
if (claims) {
|
|
16580
17046
|
const dir = resolve3(io.cwd, o.outDir ?? `threadctx-audit-${o.org}`);
|
|
16581
|
-
|
|
16582
|
-
const last =
|
|
16583
|
-
if (
|
|
16584
|
-
const auditJson = renderAuditJson({ ...
|
|
17047
|
+
mkdirSync3(dir, { recursive: true });
|
|
17048
|
+
const last = join5(dir, "audit.json");
|
|
17049
|
+
if (existsSync4(last)) writeFileSync3(join5(dir, "previous-audit.json"), readFileSync3(last));
|
|
17050
|
+
const auditJson = renderAuditJson({ ...summary2, evidence }, repos);
|
|
16585
17051
|
const auditSha256 = createHash3("sha256").update(auditJson).digest("hex");
|
|
16586
17052
|
for (const [name, body] of [
|
|
16587
|
-
["report.html", renderAuditHtml(
|
|
16588
|
-
["repos.csv", renderAuditCsv(
|
|
17053
|
+
["report.html", renderAuditHtml(summary2, repos)],
|
|
17054
|
+
["repos.csv", renderAuditCsv(summary2)],
|
|
16589
17055
|
["audit.json", auditJson],
|
|
16590
17056
|
["evidence.html", renderEvidenceHtml(evidence, { auditSha256 })],
|
|
16591
17057
|
["controls.csv", renderControlsCsv(evidence)],
|
|
16592
17058
|
["inventory.csv", renderInventoryCsv(evidence)]
|
|
16593
17059
|
]) {
|
|
16594
|
-
|
|
16595
|
-
files.push(
|
|
17060
|
+
writeFileSync3(join5(dir, name), body);
|
|
17061
|
+
files.push(join5(dir, name));
|
|
16596
17062
|
}
|
|
16597
17063
|
io.stderr(`Using ${describeLicense(claims)}
|
|
16598
17064
|
`);
|
|
16599
17065
|
}
|
|
16600
|
-
if (o.json) io.stdout(claims ? renderAuditJson({ ...
|
|
17066
|
+
if (o.json) io.stdout(claims ? renderAuditJson({ ...summary2, evidence }, repos) : `${JSON.stringify(summary2, null, 2)}
|
|
16601
17067
|
`);
|
|
16602
|
-
else io.stdout(renderAuditText(
|
|
17068
|
+
else io.stdout(renderAuditText(summary2, { color: o.color, licensed: Boolean(claims), files, controls: controlHeadline(evidence) }));
|
|
16603
17069
|
return 0;
|
|
16604
17070
|
}
|
|
16605
17071
|
|
|
@@ -16660,8 +17126,13 @@ Usage:
|
|
|
16660
17126
|
threadctx compare <base.json> <head.json> [--format text|md|json] [--fail-on blocker|warning|info|none]
|
|
16661
17127
|
What a change introduced, from two 'scan --format json' files.
|
|
16662
17128
|
Existing findings never fail; only new ones do (net-new ratchet)
|
|
16663
|
-
threadctx mcp Run as
|
|
16664
|
-
|
|
17129
|
+
threadctx mcp Run as an MCP server (stdio): agents check their own instructions
|
|
17130
|
+
(check_context, get_effective_context, explain_rule) and use checked
|
|
17131
|
+
memory (memory_query, memory_write, memory_review)
|
|
17132
|
+
threadctx memory <list|check|add|renew|forget>
|
|
17133
|
+
Checked memory: every entry is verified against the repository
|
|
17134
|
+
before an agent sees it. 'threadctx memory help' for details
|
|
17135
|
+
threadctx session-start Context grade, tokens loaded and memory health, for a SessionStart hook
|
|
16665
17136
|
threadctx audit --org <name> Grade every repository of a GitHub organisation or user, and find where
|
|
16666
17137
|
they disagree. Free: fleet grade and headline findings. With a licence:
|
|
16667
17138
|
full HTML report, CSV and JSON. Code never leaves your machine.
|
|
@@ -16712,6 +17183,8 @@ var OPTIONS = {
|
|
|
16712
17183
|
"no-badge": { type: "boolean" },
|
|
16713
17184
|
force: { type: "boolean" },
|
|
16714
17185
|
json: { type: "boolean" },
|
|
17186
|
+
team: { type: "boolean" },
|
|
17187
|
+
all: { type: "boolean" },
|
|
16715
17188
|
color: { type: "boolean" },
|
|
16716
17189
|
"no-color": { type: "boolean" },
|
|
16717
17190
|
"no-telemetry": { type: "boolean" },
|
|
@@ -16723,7 +17196,7 @@ async function main(argv, io) {
|
|
|
16723
17196
|
try {
|
|
16724
17197
|
return await run2(argv, io);
|
|
16725
17198
|
} catch (e) {
|
|
16726
|
-
if (e instanceof UsageError || e instanceof ConfigError || e instanceof PackError) {
|
|
17199
|
+
if (e instanceof UsageError || e instanceof ConfigError || e instanceof PackError || e instanceof MemoryUsageError) {
|
|
16727
17200
|
io.stderr(`threadctx: ${e.message}
|
|
16728
17201
|
`);
|
|
16729
17202
|
return 2;
|
|
@@ -16761,8 +17234,17 @@ Run 'threadctx --help' for usage.`);
|
|
|
16761
17234
|
return cmdBadge(args[0], v, io);
|
|
16762
17235
|
case "mcp":
|
|
16763
17236
|
if (!io.stdin) throw new UsageError("mcp needs standard input");
|
|
16764
|
-
await serveMcp({ stdin: io.stdin, write: io.stdout, root: io.cwd });
|
|
17237
|
+
await serveMcp({ stdin: io.stdin, write: io.stdout, root: io.cwd, env: io.env, now: io.now });
|
|
16765
17238
|
return 0;
|
|
17239
|
+
case "memory":
|
|
17240
|
+
try {
|
|
17241
|
+
return cmdMemory(args, { team: v.team, all: v.all, json: v.json }, io);
|
|
17242
|
+
} catch (e) {
|
|
17243
|
+
if (e instanceof MemoryUsageError) throw e;
|
|
17244
|
+
throw new UsageError(e.message);
|
|
17245
|
+
}
|
|
17246
|
+
case "session-start":
|
|
17247
|
+
return cmdSessionStart({ tool: v.tool }, io);
|
|
16766
17248
|
case "audit":
|
|
16767
17249
|
return cmdAudit(v, io, color);
|
|
16768
17250
|
case "license":
|
|
@@ -16790,7 +17272,7 @@ Run 'threadctx --help' for usage.`);
|
|
|
16790
17272
|
}
|
|
16791
17273
|
function openRoot(pathArg, io) {
|
|
16792
17274
|
const target = resolve4(io.cwd, pathArg ?? ".");
|
|
16793
|
-
if (!
|
|
17275
|
+
if (!existsSync5(target)) throw new UsageError(`path not found: ${pathArg}`);
|
|
16794
17276
|
if (!statSync3(target).isDirectory()) throw new UsageError(`not a directory: ${pathArg} (scan takes a repository or directory)`);
|
|
16795
17277
|
return openRepo(target);
|
|
16796
17278
|
}
|
|
@@ -16839,8 +17321,8 @@ async function cmdScan(pathArg, v, io, color) {
|
|
|
16839
17321
|
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 });
|
|
16840
17322
|
if (v.output) {
|
|
16841
17323
|
const dest = resolve4(io.cwd, v.output);
|
|
16842
|
-
|
|
16843
|
-
|
|
17324
|
+
mkdirSync4(dirname3(dest), { recursive: true });
|
|
17325
|
+
writeFileSync4(dest, out);
|
|
16844
17326
|
io.stderr(`Wrote ${format} report to ${relative3(io.cwd, dest) || dest} \u2014 grade ${result.grade}, ${result.counts.blocker} blocker, ${result.counts.warning} warning
|
|
16845
17327
|
`);
|
|
16846
17328
|
} else {
|
|
@@ -16865,9 +17347,9 @@ function cmdCompare(baseFile, headFile, v, io) {
|
|
|
16865
17347
|
if (!["text", "md", "json"].includes(format)) throw new UsageError("--format must be text, md or json");
|
|
16866
17348
|
const readScan = (file) => {
|
|
16867
17349
|
const abs = resolve4(io.cwd, file);
|
|
16868
|
-
if (!
|
|
17350
|
+
if (!existsSync5(abs)) throw new UsageError(`file not found: ${file}`);
|
|
16869
17351
|
try {
|
|
16870
|
-
return parseScanJson(
|
|
17352
|
+
return parseScanJson(readFileSync4(abs, "utf8"), file);
|
|
16871
17353
|
} catch (e) {
|
|
16872
17354
|
if (e instanceof CompareError) throw new UsageError(e.message);
|
|
16873
17355
|
throw e;
|
|
@@ -16895,15 +17377,15 @@ function cmdCompare(baseFile, headFile, v, io) {
|
|
|
16895
17377
|
}
|
|
16896
17378
|
if (v.output) {
|
|
16897
17379
|
const dest = resolve4(io.cwd, v.output);
|
|
16898
|
-
|
|
16899
|
-
|
|
17380
|
+
mkdirSync4(dirname3(dest), { recursive: true });
|
|
17381
|
+
writeFileSync4(dest, out);
|
|
16900
17382
|
} else io.stdout(out);
|
|
16901
17383
|
return compareExitCode(c, failOn);
|
|
16902
17384
|
}
|
|
16903
17385
|
function defaultBaseline(org, outDir, license, io) {
|
|
16904
17386
|
if (!/^[A-Za-z0-9-]{1,39}$/.test(org)) return void 0;
|
|
16905
|
-
const file =
|
|
16906
|
-
return
|
|
17387
|
+
const file = join6(resolve4(io.cwd, outDir ?? `threadctx-audit-${org}`), "audit.json");
|
|
17388
|
+
return existsSync5(file) && findLicense(license, io) ? file : void 0;
|
|
16907
17389
|
}
|
|
16908
17390
|
async function cmdAudit(v, io, color) {
|
|
16909
17391
|
if (!v.org) throw new UsageError("usage: threadctx audit --org <github-org-or-user>");
|
|
@@ -16946,17 +17428,17 @@ function cmdBadge(pathArg, v, io) {
|
|
|
16946
17428
|
function locate(fileArg, io) {
|
|
16947
17429
|
const real = (p) => {
|
|
16948
17430
|
try {
|
|
16949
|
-
return
|
|
17431
|
+
return realpathSync3(p);
|
|
16950
17432
|
} catch {
|
|
16951
17433
|
return p;
|
|
16952
17434
|
}
|
|
16953
17435
|
};
|
|
16954
17436
|
const given = resolve4(io.cwd, fileArg);
|
|
16955
|
-
const abs =
|
|
16956
|
-
const root = real(gitRoot(
|
|
17437
|
+
const abs = existsSync5(given) ? real(given) : join6(real(dirname3(given)), basename2(given));
|
|
17438
|
+
const root = real(gitRoot(existsSync5(abs) && statSync3(abs).isDirectory() ? abs : dirname3(abs)) ?? io.cwd);
|
|
16957
17439
|
const rel = relative3(root, abs).split(sep3).join("/");
|
|
16958
17440
|
if (rel.startsWith("..")) throw new UsageError(`${fileArg} is outside the repository at ${root}`);
|
|
16959
|
-
const isDir =
|
|
17441
|
+
const isDir = existsSync5(abs) && statSync3(abs).isDirectory();
|
|
16960
17442
|
return { repo: openRepo(root), target: { path: rel === "" ? "" : rel, isDir } };
|
|
16961
17443
|
}
|
|
16962
17444
|
function contextsFor(repo, target, toolArg, surface) {
|
|
@@ -17047,13 +17529,13 @@ function cmdFix(pathArg, v, io) {
|
|
|
17047
17529
|
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);
|
|
17048
17530
|
}
|
|
17049
17531
|
if (v.apply) {
|
|
17050
|
-
for (const [p, { after }] of plan.files)
|
|
17532
|
+
for (const [p, { after }] of plan.files) writeFileSync4(join6(repo.root, p), after);
|
|
17051
17533
|
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.
|
|
17052
17534
|
`);
|
|
17053
17535
|
return 0;
|
|
17054
17536
|
}
|
|
17055
17537
|
if (v.output) {
|
|
17056
|
-
|
|
17538
|
+
writeFileSync4(resolve4(io.cwd, v.output), plan.patch);
|
|
17057
17539
|
io.stderr(`Wrote ${plan.applied.length} fix${plan.applied.length === 1 ? "" : "es"} to ${v.output}. Apply with: git apply ${v.output}
|
|
17058
17540
|
`);
|
|
17059
17541
|
} else {
|
|
@@ -17077,7 +17559,7 @@ function withPr(open, io) {
|
|
|
17077
17559
|
}
|
|
17078
17560
|
function isPublicOnGitHub(root, env) {
|
|
17079
17561
|
try {
|
|
17080
|
-
return
|
|
17562
|
+
return execFileSync6("gh", ["repo", "view", "--json", "visibility", "--jq", ".visibility"], { cwd: root, env, stdio: ["ignore", "pipe", "ignore"], timeout: 15e3 }).toString().trim() === "PUBLIC";
|
|
17081
17563
|
} catch {
|
|
17082
17564
|
return false;
|
|
17083
17565
|
}
|
|
@@ -17086,17 +17568,17 @@ function cmdInit(pathArg, v, io) {
|
|
|
17086
17568
|
const repo = openRoot(pathArg, io);
|
|
17087
17569
|
const files = /* @__PURE__ */ new Map();
|
|
17088
17570
|
const notes = [];
|
|
17089
|
-
if (
|
|
17571
|
+
if (existsSync5(join6(repo.root, WORKFLOW_PATH)) && !v.force) notes.push(`${WORKFLOW_PATH} already exists (use --force to replace it)`);
|
|
17090
17572
|
else files.set(WORKFLOW_PATH, workflowYaml());
|
|
17091
17573
|
if (!v["no-badge"]) {
|
|
17092
17574
|
const result = doScan(repo, v, io);
|
|
17093
17575
|
const fullName = githubRemote(repo.root);
|
|
17094
17576
|
const badge = fullName && isPublicOnGitHub(repo.root, io.env) ? renderLiveBadge(fullName) : renderBadge(result, badgeLinkFor(fullName));
|
|
17095
|
-
const readmeName = ["README.md", "readme.md", "Readme.md"].find((n2) =>
|
|
17577
|
+
const readmeName = ["README.md", "readme.md", "Readme.md"].find((n2) => existsSync5(join6(repo.root, n2)));
|
|
17096
17578
|
if (!readmeName) notes.push(`no README.md; add this badge where you like:
|
|
17097
17579
|
${badge.markdown}`);
|
|
17098
17580
|
else {
|
|
17099
|
-
const before =
|
|
17581
|
+
const before = readFileSync4(join6(repo.root, readmeName), "utf8");
|
|
17100
17582
|
const after = withBadge(before, badge.markdown);
|
|
17101
17583
|
if (after === before) notes.push(`${readmeName} already has an agent context badge`);
|
|
17102
17584
|
else files.set(readmeName, after);
|
|
@@ -17120,8 +17602,8 @@ function cmdInit(pathArg, v, io) {
|
|
|
17120
17602
|
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);
|
|
17121
17603
|
}
|
|
17122
17604
|
for (const [p, content] of files) {
|
|
17123
|
-
|
|
17124
|
-
|
|
17605
|
+
mkdirSync4(dirname3(join6(repo.root, p)), { recursive: true });
|
|
17606
|
+
writeFileSync4(join6(repo.root, p), content);
|
|
17125
17607
|
io.stderr(`wrote ${p}
|
|
17126
17608
|
`);
|
|
17127
17609
|
}
|
|
@@ -17166,8 +17648,8 @@ function cmdTools(v, io) {
|
|
|
17166
17648
|
}
|
|
17167
17649
|
function cmdPackValidate(file, io) {
|
|
17168
17650
|
const abs = resolve4(io.cwd, file);
|
|
17169
|
-
if (!
|
|
17170
|
-
const pack = parsePack(
|
|
17651
|
+
if (!existsSync5(abs)) throw new UsageError(`file not found: ${file}`);
|
|
17652
|
+
const pack = parsePack(readFileSync4(abs, "utf8"), file);
|
|
17171
17653
|
io.stdout(`${pack.pack}: ${pack.rules.length} rule${pack.rules.length === 1 ? "" : "s"} valid
|
|
17172
17654
|
`);
|
|
17173
17655
|
for (const r of pack.rules) io.stdout(` ${pack.pack}/${r.id} ${r.severity} ${r.title}
|
|
@@ -17193,10 +17675,10 @@ function nextSteps(result, v, io) {
|
|
|
17193
17675
|
var UPGRADE_URL = "https://threadctx.dev/pricing";
|
|
17194
17676
|
function maybeUpgradeLine(result, io, remote) {
|
|
17195
17677
|
if (!UPGRADE_URL || !io.isTTY || io.env.CI || io.env.THREADCTX_NO_UPSELL) return;
|
|
17196
|
-
const stateFile =
|
|
17678
|
+
const stateFile = join6(io.env.THREADCTX_HOME ?? join6(homedir3(), ".threadctx"), "state.json");
|
|
17197
17679
|
let state = {};
|
|
17198
17680
|
try {
|
|
17199
|
-
state = JSON.parse(
|
|
17681
|
+
state = JSON.parse(readFileSync4(stateFile, "utf8"));
|
|
17200
17682
|
} catch {
|
|
17201
17683
|
}
|
|
17202
17684
|
const today = io.now().toISOString().slice(0, 10);
|
|
@@ -17207,13 +17689,17 @@ function maybeUpgradeLine(result, io, remote) {
|
|
|
17207
17689
|
${msg}
|
|
17208
17690
|
`);
|
|
17209
17691
|
try {
|
|
17210
|
-
|
|
17211
|
-
|
|
17692
|
+
mkdirSync4(dirname3(stateFile), { recursive: true });
|
|
17693
|
+
writeFileSync4(stateFile, JSON.stringify({ ...state, lastUpsell: today }));
|
|
17212
17694
|
} catch {
|
|
17213
17695
|
}
|
|
17214
17696
|
}
|
|
17215
17697
|
|
|
17216
17698
|
// src/bin.ts
|
|
17699
|
+
process.stdout.on("error", (e) => {
|
|
17700
|
+
if (e.code === "EPIPE") process.exit(process.exitCode ?? 0);
|
|
17701
|
+
throw e;
|
|
17702
|
+
});
|
|
17217
17703
|
var code = await main(process.argv.slice(2), {
|
|
17218
17704
|
cwd: process.cwd(),
|
|
17219
17705
|
env: process.env,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "threadctx",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"mcpName": "io.github.threadctx-dev/threadctx",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"threadctx": "dist/threadctx.mjs",
|
|
19
19
|
"ctx": "dist/threadctx.mjs"
|
|
20
20
|
},
|
|
21
|
-
"description": "
|
|
21
|
+
"description": "See exactly what each coding agent is told. Maps which AGENTS.md, CLAUDE.md, Cursor, Copilot and Gemini files every agent loads, flags stale paths, duplication and unpinned MCP servers, and fixes the mechanical ones. Offline, zero dependencies.",
|
|
22
22
|
"homepage": "https://threadctx.dev",
|
|
23
23
|
"repository": {
|
|
24
24
|
"type": "git",
|
|
@@ -39,7 +39,15 @@
|
|
|
39
39
|
"context",
|
|
40
40
|
"lint",
|
|
41
41
|
"mcp",
|
|
42
|
-
"sarif"
|
|
42
|
+
"sarif",
|
|
43
|
+
"claude-md",
|
|
44
|
+
"cursor-rules",
|
|
45
|
+
"copilot-instructions",
|
|
46
|
+
"codex",
|
|
47
|
+
"linter",
|
|
48
|
+
"ai-agents",
|
|
49
|
+
"mcp-server",
|
|
50
|
+
"context-engineering"
|
|
43
51
|
],
|
|
44
52
|
"author": "threadctx",
|
|
45
53
|
"publishConfig": {
|
|
@@ -50,9 +58,9 @@
|
|
|
50
58
|
"diff": "^9.0.0",
|
|
51
59
|
"@threadctx/core": "0.1.0",
|
|
52
60
|
"@threadctx/adapters": "0.1.0",
|
|
61
|
+
"@threadctx/report": "0.1.0",
|
|
53
62
|
"@threadctx/rules": "0.1.0",
|
|
54
|
-
"@threadctx/discovery": "0.1.0"
|
|
55
|
-
"@threadctx/report": "0.1.0"
|
|
63
|
+
"@threadctx/discovery": "0.1.0"
|
|
56
64
|
},
|
|
57
65
|
"scripts": {
|
|
58
66
|
"build": "tsc -b && node build.mjs"
|