threadctx 0.5.0 → 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 +546 -81
- package/package.json +3 -3
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
|
|
@@ -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" };
|
|
@@ -15625,7 +15712,7 @@ function renderLiveBadge(fullName) {
|
|
|
15625
15712
|
}
|
|
15626
15713
|
|
|
15627
15714
|
// src/cli.ts
|
|
15628
|
-
import { execFileSync as
|
|
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: "
|
|
16276
|
+
var ACTION_PIN = { sha: "446c4025a766f288e992d85b98790ba25e21367e", tag: "v1.5.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
|
|
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.
|
|
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 =
|
|
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
|
-
|
|
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 =
|
|
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,148 @@ 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 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
|
+
|
|
16490
16935
|
// src/audit.ts
|
|
16491
|
-
import { existsSync as
|
|
16492
|
-
import { homedir } from "node:os";
|
|
16493
|
-
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";
|
|
16494
16939
|
import { createHash as createHash3 } from "node:crypto";
|
|
16495
16940
|
|
|
16496
16941
|
// src/remote.ts
|
|
16497
|
-
import { execFileSync as
|
|
16942
|
+
import { execFileSync as execFileSync5 } from "node:child_process";
|
|
16498
16943
|
function githubToken(env) {
|
|
16499
16944
|
if (env.GH_TOKEN || env.GITHUB_TOKEN) return env.GH_TOKEN ?? env.GITHUB_TOKEN;
|
|
16500
16945
|
try {
|
|
16501
|
-
return
|
|
16946
|
+
return execFileSync5("gh", ["auth", "token"], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim() || void 0;
|
|
16502
16947
|
} catch {
|
|
16503
16948
|
return void 0;
|
|
16504
16949
|
}
|
|
@@ -16509,22 +16954,22 @@ var AuditUsageError = class extends Error {
|
|
|
16509
16954
|
};
|
|
16510
16955
|
var ORG = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
|
|
16511
16956
|
function findLicense(arg, io) {
|
|
16512
|
-
const fromFile = (p) =>
|
|
16957
|
+
const fromFile = (p) => existsSync4(p) ? readFileSync3(p, "utf8").trim() : void 0;
|
|
16513
16958
|
if (arg) {
|
|
16514
16959
|
const file = resolve3(io.cwd, arg);
|
|
16515
16960
|
const key2 = arg.startsWith("tctx1.") ? arg : fromFile(file);
|
|
16516
16961
|
return key2 ? { key: key2, source: arg.startsWith("tctx1.") ? "--license" : arg } : { key: arg, source: "--license" };
|
|
16517
16962
|
}
|
|
16518
16963
|
if (io.env.THREADCTX_LICENSE) return { key: io.env.THREADCTX_LICENSE.trim(), source: "THREADCTX_LICENSE" };
|
|
16519
|
-
const home =
|
|
16964
|
+
const home = join5(io.env.THREADCTX_HOME ?? join5(homedir2(), ".threadctx"), "license");
|
|
16520
16965
|
const key = fromFile(home);
|
|
16521
16966
|
return key ? { key, source: home } : void 0;
|
|
16522
16967
|
}
|
|
16523
16968
|
function describeLicense(claims) {
|
|
16524
|
-
const
|
|
16969
|
+
const days2 = Math.max(0, Math.ceil((claims.exp * 1e3 - Date.now()) / 864e5));
|
|
16525
16970
|
const who = claims.orgs?.length ? claims.orgs.join(", ") : claims.org === "*" ? "any organisation" : claims.org;
|
|
16526
16971
|
const limit = claims.agentRepoLimit ? `, up to ${claims.agentRepoLimit} agent repositories` : "";
|
|
16527
|
-
return `${claims.plan} licence for ${who}${limit}, ${
|
|
16972
|
+
return `${claims.plan} licence for ${who}${limit}, ${days2} day${days2 === 1 ? "" : "s"} left (id ${claims.id})`;
|
|
16528
16973
|
}
|
|
16529
16974
|
async function runAudit(o, io) {
|
|
16530
16975
|
if (!ORG.test(o.org)) throw new AuditUsageError(`'${o.org}' is not a valid GitHub organisation or user name`);
|
|
@@ -16542,9 +16987,9 @@ async function runAudit(o, io) {
|
|
|
16542
16987
|
if (o.baseline) {
|
|
16543
16988
|
if (!claims) throw new AuditUsageError("--baseline compares two full audits and needs a licence (the free audit has no audit.json to compare).");
|
|
16544
16989
|
const file = resolve3(io.cwd, o.baseline);
|
|
16545
|
-
if (!
|
|
16990
|
+
if (!existsSync4(file)) throw new AuditUsageError(`baseline not found: ${o.baseline}`);
|
|
16546
16991
|
try {
|
|
16547
|
-
const parsed = JSON.parse(
|
|
16992
|
+
const parsed = JSON.parse(readFileSync3(file, "utf8"));
|
|
16548
16993
|
if (parsed.schema !== "threadctx.audit/v1") throw new Error("schema");
|
|
16549
16994
|
previous = parsed;
|
|
16550
16995
|
} catch {
|
|
@@ -16580,14 +17025,14 @@ async function runAudit(o, io) {
|
|
|
16580
17025
|
return { ...base, error: e.message.replace(/\s+/g, " ").slice(0, 160) };
|
|
16581
17026
|
}
|
|
16582
17027
|
});
|
|
16583
|
-
const
|
|
17028
|
+
const summary2 = summarizeFleet(repos, { org: o.org, generatedAt: io.now().toISOString(), engine: { version: ENGINE_VERSION, registry: REGISTRY_VERSION } });
|
|
16584
17029
|
if (previous) {
|
|
16585
17030
|
if (previous.org.toLowerCase() !== o.org.toLowerCase()) io.stderr(`note: the baseline is for ${previous.org}, not ${o.org}; comparing anyway.
|
|
16586
17031
|
`);
|
|
16587
|
-
|
|
17032
|
+
summary2.trend = fleetTrend(previous, summary2);
|
|
16588
17033
|
}
|
|
16589
|
-
const evidence = evidencePack(
|
|
16590
|
-
const agentRepos =
|
|
17034
|
+
const evidence = evidencePack(summary2, repos);
|
|
17035
|
+
const agentRepos = summary2.repos.withContext;
|
|
16591
17036
|
if (claims?.agentRepoLimit && agentRepos > claims.agentRepoLimit) {
|
|
16592
17037
|
io.stderr(`
|
|
16593
17038
|
This organisation has ${agentRepos} agent repositories; your ${claims.plan} licence covers up to ${claims.agentRepoLimit}.
|
|
@@ -16599,28 +17044,28 @@ Showing the free summary. Upgrade for the full report: https://threadctx.dev/pri
|
|
|
16599
17044
|
const files = [];
|
|
16600
17045
|
if (claims) {
|
|
16601
17046
|
const dir = resolve3(io.cwd, o.outDir ?? `threadctx-audit-${o.org}`);
|
|
16602
|
-
|
|
16603
|
-
const last =
|
|
16604
|
-
if (
|
|
16605
|
-
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);
|
|
16606
17051
|
const auditSha256 = createHash3("sha256").update(auditJson).digest("hex");
|
|
16607
17052
|
for (const [name, body] of [
|
|
16608
|
-
["report.html", renderAuditHtml(
|
|
16609
|
-
["repos.csv", renderAuditCsv(
|
|
17053
|
+
["report.html", renderAuditHtml(summary2, repos)],
|
|
17054
|
+
["repos.csv", renderAuditCsv(summary2)],
|
|
16610
17055
|
["audit.json", auditJson],
|
|
16611
17056
|
["evidence.html", renderEvidenceHtml(evidence, { auditSha256 })],
|
|
16612
17057
|
["controls.csv", renderControlsCsv(evidence)],
|
|
16613
17058
|
["inventory.csv", renderInventoryCsv(evidence)]
|
|
16614
17059
|
]) {
|
|
16615
|
-
|
|
16616
|
-
files.push(
|
|
17060
|
+
writeFileSync3(join5(dir, name), body);
|
|
17061
|
+
files.push(join5(dir, name));
|
|
16617
17062
|
}
|
|
16618
17063
|
io.stderr(`Using ${describeLicense(claims)}
|
|
16619
17064
|
`);
|
|
16620
17065
|
}
|
|
16621
|
-
if (o.json) io.stdout(claims ? renderAuditJson({ ...
|
|
17066
|
+
if (o.json) io.stdout(claims ? renderAuditJson({ ...summary2, evidence }, repos) : `${JSON.stringify(summary2, null, 2)}
|
|
16622
17067
|
`);
|
|
16623
|
-
else io.stdout(renderAuditText(
|
|
17068
|
+
else io.stdout(renderAuditText(summary2, { color: o.color, licensed: Boolean(claims), files, controls: controlHeadline(evidence) }));
|
|
16624
17069
|
return 0;
|
|
16625
17070
|
}
|
|
16626
17071
|
|
|
@@ -16681,8 +17126,13 @@ Usage:
|
|
|
16681
17126
|
threadctx compare <base.json> <head.json> [--format text|md|json] [--fail-on blocker|warning|info|none]
|
|
16682
17127
|
What a change introduced, from two 'scan --format json' files.
|
|
16683
17128
|
Existing findings never fail; only new ones do (net-new ratchet)
|
|
16684
|
-
threadctx mcp Run as
|
|
16685
|
-
|
|
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
|
|
16686
17136
|
threadctx audit --org <name> Grade every repository of a GitHub organisation or user, and find where
|
|
16687
17137
|
they disagree. Free: fleet grade and headline findings. With a licence:
|
|
16688
17138
|
full HTML report, CSV and JSON. Code never leaves your machine.
|
|
@@ -16733,6 +17183,8 @@ var OPTIONS = {
|
|
|
16733
17183
|
"no-badge": { type: "boolean" },
|
|
16734
17184
|
force: { type: "boolean" },
|
|
16735
17185
|
json: { type: "boolean" },
|
|
17186
|
+
team: { type: "boolean" },
|
|
17187
|
+
all: { type: "boolean" },
|
|
16736
17188
|
color: { type: "boolean" },
|
|
16737
17189
|
"no-color": { type: "boolean" },
|
|
16738
17190
|
"no-telemetry": { type: "boolean" },
|
|
@@ -16744,7 +17196,7 @@ async function main(argv, io) {
|
|
|
16744
17196
|
try {
|
|
16745
17197
|
return await run2(argv, io);
|
|
16746
17198
|
} catch (e) {
|
|
16747
|
-
if (e instanceof UsageError || e instanceof ConfigError || e instanceof PackError) {
|
|
17199
|
+
if (e instanceof UsageError || e instanceof ConfigError || e instanceof PackError || e instanceof MemoryUsageError) {
|
|
16748
17200
|
io.stderr(`threadctx: ${e.message}
|
|
16749
17201
|
`);
|
|
16750
17202
|
return 2;
|
|
@@ -16782,8 +17234,17 @@ Run 'threadctx --help' for usage.`);
|
|
|
16782
17234
|
return cmdBadge(args[0], v, io);
|
|
16783
17235
|
case "mcp":
|
|
16784
17236
|
if (!io.stdin) throw new UsageError("mcp needs standard input");
|
|
16785
|
-
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 });
|
|
16786
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);
|
|
16787
17248
|
case "audit":
|
|
16788
17249
|
return cmdAudit(v, io, color);
|
|
16789
17250
|
case "license":
|
|
@@ -16811,7 +17272,7 @@ Run 'threadctx --help' for usage.`);
|
|
|
16811
17272
|
}
|
|
16812
17273
|
function openRoot(pathArg, io) {
|
|
16813
17274
|
const target = resolve4(io.cwd, pathArg ?? ".");
|
|
16814
|
-
if (!
|
|
17275
|
+
if (!existsSync5(target)) throw new UsageError(`path not found: ${pathArg}`);
|
|
16815
17276
|
if (!statSync3(target).isDirectory()) throw new UsageError(`not a directory: ${pathArg} (scan takes a repository or directory)`);
|
|
16816
17277
|
return openRepo(target);
|
|
16817
17278
|
}
|
|
@@ -16860,8 +17321,8 @@ async function cmdScan(pathArg, v, io, color) {
|
|
|
16860
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 });
|
|
16861
17322
|
if (v.output) {
|
|
16862
17323
|
const dest = resolve4(io.cwd, v.output);
|
|
16863
|
-
|
|
16864
|
-
|
|
17324
|
+
mkdirSync4(dirname3(dest), { recursive: true });
|
|
17325
|
+
writeFileSync4(dest, out);
|
|
16865
17326
|
io.stderr(`Wrote ${format} report to ${relative3(io.cwd, dest) || dest} \u2014 grade ${result.grade}, ${result.counts.blocker} blocker, ${result.counts.warning} warning
|
|
16866
17327
|
`);
|
|
16867
17328
|
} else {
|
|
@@ -16886,9 +17347,9 @@ function cmdCompare(baseFile, headFile, v, io) {
|
|
|
16886
17347
|
if (!["text", "md", "json"].includes(format)) throw new UsageError("--format must be text, md or json");
|
|
16887
17348
|
const readScan = (file) => {
|
|
16888
17349
|
const abs = resolve4(io.cwd, file);
|
|
16889
|
-
if (!
|
|
17350
|
+
if (!existsSync5(abs)) throw new UsageError(`file not found: ${file}`);
|
|
16890
17351
|
try {
|
|
16891
|
-
return parseScanJson(
|
|
17352
|
+
return parseScanJson(readFileSync4(abs, "utf8"), file);
|
|
16892
17353
|
} catch (e) {
|
|
16893
17354
|
if (e instanceof CompareError) throw new UsageError(e.message);
|
|
16894
17355
|
throw e;
|
|
@@ -16916,15 +17377,15 @@ function cmdCompare(baseFile, headFile, v, io) {
|
|
|
16916
17377
|
}
|
|
16917
17378
|
if (v.output) {
|
|
16918
17379
|
const dest = resolve4(io.cwd, v.output);
|
|
16919
|
-
|
|
16920
|
-
|
|
17380
|
+
mkdirSync4(dirname3(dest), { recursive: true });
|
|
17381
|
+
writeFileSync4(dest, out);
|
|
16921
17382
|
} else io.stdout(out);
|
|
16922
17383
|
return compareExitCode(c, failOn);
|
|
16923
17384
|
}
|
|
16924
17385
|
function defaultBaseline(org, outDir, license, io) {
|
|
16925
17386
|
if (!/^[A-Za-z0-9-]{1,39}$/.test(org)) return void 0;
|
|
16926
|
-
const file =
|
|
16927
|
-
return
|
|
17387
|
+
const file = join6(resolve4(io.cwd, outDir ?? `threadctx-audit-${org}`), "audit.json");
|
|
17388
|
+
return existsSync5(file) && findLicense(license, io) ? file : void 0;
|
|
16928
17389
|
}
|
|
16929
17390
|
async function cmdAudit(v, io, color) {
|
|
16930
17391
|
if (!v.org) throw new UsageError("usage: threadctx audit --org <github-org-or-user>");
|
|
@@ -16967,17 +17428,17 @@ function cmdBadge(pathArg, v, io) {
|
|
|
16967
17428
|
function locate(fileArg, io) {
|
|
16968
17429
|
const real = (p) => {
|
|
16969
17430
|
try {
|
|
16970
|
-
return
|
|
17431
|
+
return realpathSync3(p);
|
|
16971
17432
|
} catch {
|
|
16972
17433
|
return p;
|
|
16973
17434
|
}
|
|
16974
17435
|
};
|
|
16975
17436
|
const given = resolve4(io.cwd, fileArg);
|
|
16976
|
-
const abs =
|
|
16977
|
-
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);
|
|
16978
17439
|
const rel = relative3(root, abs).split(sep3).join("/");
|
|
16979
17440
|
if (rel.startsWith("..")) throw new UsageError(`${fileArg} is outside the repository at ${root}`);
|
|
16980
|
-
const isDir =
|
|
17441
|
+
const isDir = existsSync5(abs) && statSync3(abs).isDirectory();
|
|
16981
17442
|
return { repo: openRepo(root), target: { path: rel === "" ? "" : rel, isDir } };
|
|
16982
17443
|
}
|
|
16983
17444
|
function contextsFor(repo, target, toolArg, surface) {
|
|
@@ -17068,13 +17529,13 @@ function cmdFix(pathArg, v, io) {
|
|
|
17068
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);
|
|
17069
17530
|
}
|
|
17070
17531
|
if (v.apply) {
|
|
17071
|
-
for (const [p, { after }] of plan.files)
|
|
17532
|
+
for (const [p, { after }] of plan.files) writeFileSync4(join6(repo.root, p), after);
|
|
17072
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.
|
|
17073
17534
|
`);
|
|
17074
17535
|
return 0;
|
|
17075
17536
|
}
|
|
17076
17537
|
if (v.output) {
|
|
17077
|
-
|
|
17538
|
+
writeFileSync4(resolve4(io.cwd, v.output), plan.patch);
|
|
17078
17539
|
io.stderr(`Wrote ${plan.applied.length} fix${plan.applied.length === 1 ? "" : "es"} to ${v.output}. Apply with: git apply ${v.output}
|
|
17079
17540
|
`);
|
|
17080
17541
|
} else {
|
|
@@ -17098,7 +17559,7 @@ function withPr(open, io) {
|
|
|
17098
17559
|
}
|
|
17099
17560
|
function isPublicOnGitHub(root, env) {
|
|
17100
17561
|
try {
|
|
17101
|
-
return
|
|
17562
|
+
return execFileSync6("gh", ["repo", "view", "--json", "visibility", "--jq", ".visibility"], { cwd: root, env, stdio: ["ignore", "pipe", "ignore"], timeout: 15e3 }).toString().trim() === "PUBLIC";
|
|
17102
17563
|
} catch {
|
|
17103
17564
|
return false;
|
|
17104
17565
|
}
|
|
@@ -17107,17 +17568,17 @@ function cmdInit(pathArg, v, io) {
|
|
|
17107
17568
|
const repo = openRoot(pathArg, io);
|
|
17108
17569
|
const files = /* @__PURE__ */ new Map();
|
|
17109
17570
|
const notes = [];
|
|
17110
|
-
if (
|
|
17571
|
+
if (existsSync5(join6(repo.root, WORKFLOW_PATH)) && !v.force) notes.push(`${WORKFLOW_PATH} already exists (use --force to replace it)`);
|
|
17111
17572
|
else files.set(WORKFLOW_PATH, workflowYaml());
|
|
17112
17573
|
if (!v["no-badge"]) {
|
|
17113
17574
|
const result = doScan(repo, v, io);
|
|
17114
17575
|
const fullName = githubRemote(repo.root);
|
|
17115
17576
|
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) =>
|
|
17577
|
+
const readmeName = ["README.md", "readme.md", "Readme.md"].find((n2) => existsSync5(join6(repo.root, n2)));
|
|
17117
17578
|
if (!readmeName) notes.push(`no README.md; add this badge where you like:
|
|
17118
17579
|
${badge.markdown}`);
|
|
17119
17580
|
else {
|
|
17120
|
-
const before =
|
|
17581
|
+
const before = readFileSync4(join6(repo.root, readmeName), "utf8");
|
|
17121
17582
|
const after = withBadge(before, badge.markdown);
|
|
17122
17583
|
if (after === before) notes.push(`${readmeName} already has an agent context badge`);
|
|
17123
17584
|
else files.set(readmeName, after);
|
|
@@ -17141,8 +17602,8 @@ function cmdInit(pathArg, v, io) {
|
|
|
17141
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);
|
|
17142
17603
|
}
|
|
17143
17604
|
for (const [p, content] of files) {
|
|
17144
|
-
|
|
17145
|
-
|
|
17605
|
+
mkdirSync4(dirname3(join6(repo.root, p)), { recursive: true });
|
|
17606
|
+
writeFileSync4(join6(repo.root, p), content);
|
|
17146
17607
|
io.stderr(`wrote ${p}
|
|
17147
17608
|
`);
|
|
17148
17609
|
}
|
|
@@ -17187,8 +17648,8 @@ function cmdTools(v, io) {
|
|
|
17187
17648
|
}
|
|
17188
17649
|
function cmdPackValidate(file, io) {
|
|
17189
17650
|
const abs = resolve4(io.cwd, file);
|
|
17190
|
-
if (!
|
|
17191
|
-
const pack = parsePack(
|
|
17651
|
+
if (!existsSync5(abs)) throw new UsageError(`file not found: ${file}`);
|
|
17652
|
+
const pack = parsePack(readFileSync4(abs, "utf8"), file);
|
|
17192
17653
|
io.stdout(`${pack.pack}: ${pack.rules.length} rule${pack.rules.length === 1 ? "" : "s"} valid
|
|
17193
17654
|
`);
|
|
17194
17655
|
for (const r of pack.rules) io.stdout(` ${pack.pack}/${r.id} ${r.severity} ${r.title}
|
|
@@ -17214,10 +17675,10 @@ function nextSteps(result, v, io) {
|
|
|
17214
17675
|
var UPGRADE_URL = "https://threadctx.dev/pricing";
|
|
17215
17676
|
function maybeUpgradeLine(result, io, remote) {
|
|
17216
17677
|
if (!UPGRADE_URL || !io.isTTY || io.env.CI || io.env.THREADCTX_NO_UPSELL) return;
|
|
17217
|
-
const stateFile =
|
|
17678
|
+
const stateFile = join6(io.env.THREADCTX_HOME ?? join6(homedir3(), ".threadctx"), "state.json");
|
|
17218
17679
|
let state = {};
|
|
17219
17680
|
try {
|
|
17220
|
-
state = JSON.parse(
|
|
17681
|
+
state = JSON.parse(readFileSync4(stateFile, "utf8"));
|
|
17221
17682
|
} catch {
|
|
17222
17683
|
}
|
|
17223
17684
|
const today = io.now().toISOString().slice(0, 10);
|
|
@@ -17228,13 +17689,17 @@ function maybeUpgradeLine(result, io, remote) {
|
|
|
17228
17689
|
${msg}
|
|
17229
17690
|
`);
|
|
17230
17691
|
try {
|
|
17231
|
-
|
|
17232
|
-
|
|
17692
|
+
mkdirSync4(dirname3(stateFile), { recursive: true });
|
|
17693
|
+
writeFileSync4(stateFile, JSON.stringify({ ...state, lastUpsell: today }));
|
|
17233
17694
|
} catch {
|
|
17234
17695
|
}
|
|
17235
17696
|
}
|
|
17236
17697
|
|
|
17237
17698
|
// src/bin.ts
|
|
17699
|
+
process.stdout.on("error", (e) => {
|
|
17700
|
+
if (e.code === "EPIPE") process.exit(process.exitCode ?? 0);
|
|
17701
|
+
throw e;
|
|
17702
|
+
});
|
|
17238
17703
|
var code = await main(process.argv.slice(2), {
|
|
17239
17704
|
cwd: process.cwd(),
|
|
17240
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",
|
|
@@ -56,10 +56,10 @@
|
|
|
56
56
|
"dependencies": {},
|
|
57
57
|
"devDependencies": {
|
|
58
58
|
"diff": "^9.0.0",
|
|
59
|
+
"@threadctx/core": "0.1.0",
|
|
60
|
+
"@threadctx/adapters": "0.1.0",
|
|
59
61
|
"@threadctx/report": "0.1.0",
|
|
60
62
|
"@threadctx/rules": "0.1.0",
|
|
61
|
-
"@threadctx/adapters": "0.1.0",
|
|
62
|
-
"@threadctx/core": "0.1.0",
|
|
63
63
|
"@threadctx/discovery": "0.1.0"
|
|
64
64
|
},
|
|
65
65
|
"scripts": {
|