ctxmedic 0.10.0 → 0.12.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 +11 -0
- package/dist/index.js +304 -133
- package/package.json +1 -1
- package/schema.json +98 -1
package/README.md
CHANGED
|
@@ -145,6 +145,17 @@ telemetry, no update checks.
|
|
|
145
145
|
- The UI server (`ctxmedic ui`) listens on `127.0.0.1` only and requires a
|
|
146
146
|
per-run token for writes.
|
|
147
147
|
|
|
148
|
+
**Plugins**
|
|
149
|
+
- `"plugins": ["ctxmedic-plugin-foo"]` in `ctxmedic.config.json` adds rules from
|
|
150
|
+
npm packages in your project's own `node_modules`. ctxmedic never installs or
|
|
151
|
+
downloads them.
|
|
152
|
+
- They load only when you pass `--plugins` (or set `CTXMEDIC_PLUGINS=1`) on that
|
|
153
|
+
run; a checked-in config alone never runs plugin code. Without the flag, the
|
|
154
|
+
report names the plugins it skipped.
|
|
155
|
+
- A loaded plugin runs with ctxmedic's own rights: it can read files and open
|
|
156
|
+
network connections, and ctxmedic does not sandbox it. Load only plugins you
|
|
157
|
+
trust. The report lists every loaded plugin with its version (ADR-027).
|
|
158
|
+
|
|
148
159
|
Secrets found in configs are always masked in output. To verify that the npm
|
|
149
160
|
package was built from this repo by CI, run `npm audit signatures`.
|
|
150
161
|
|
package/dist/index.js
CHANGED
|
@@ -2,31 +2,35 @@
|
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
4
|
import { spawn } from "child_process";
|
|
5
|
-
import
|
|
5
|
+
import path17 from "path";
|
|
6
6
|
import { fileURLToPath } from "url";
|
|
7
7
|
import * as p2 from "@clack/prompts";
|
|
8
8
|
import { Command } from "commander";
|
|
9
9
|
import pc2 from "picocolors";
|
|
10
10
|
|
|
11
11
|
// ../clinical/src/schema.ts
|
|
12
|
-
import { z as
|
|
12
|
+
import { z as z7 } from "zod";
|
|
13
13
|
|
|
14
14
|
// ../core/src/schema.ts
|
|
15
15
|
import { z } from "zod";
|
|
16
16
|
var Severity = z.enum(["critical", "warning", "info"]);
|
|
17
|
-
var
|
|
17
|
+
var BuiltinRuleId = z.enum([
|
|
18
18
|
"ERR_BROKEN_LINK",
|
|
19
19
|
"WARN_CONTEXT_BLOAT",
|
|
20
20
|
"WARN_DUPLICATE_RULES",
|
|
21
21
|
"ERR_INVALID_SKILL",
|
|
22
22
|
"CRIT_SECRET_LEAK",
|
|
23
23
|
"INFO_UNSUPPORTED_SYNTAX",
|
|
24
|
+
"INFO_UNUSED_DISABLE",
|
|
24
25
|
"FIN_BLOAT_IGNORE",
|
|
25
26
|
"FIN_UNUSED_MCP",
|
|
26
27
|
"FIN_MODEL_OVERKILL",
|
|
27
28
|
"FIN_CONTEXT_SNOWBALL",
|
|
28
29
|
"FIN_CACHE_MISS"
|
|
29
30
|
]);
|
|
31
|
+
var EXTERNAL_RULE_ID = /^[a-z][a-z0-9-]*\/[A-Z][A-Z0-9_]*$/;
|
|
32
|
+
var ExternalRuleId = z.string().regex(EXTERNAL_RULE_ID, "external rule ids look like plugin/RULE_NAME").transform((s) => s);
|
|
33
|
+
var RuleId = z.union([BuiltinRuleId, ExternalRuleId]);
|
|
30
34
|
var FixOp = z.discriminatedUnion("kind", [
|
|
31
35
|
z.object({ kind: z.literal("write"), path: z.string(), content: z.string() }),
|
|
32
36
|
z.object({ kind: z.literal("symlink"), path: z.string(), target: z.string() })
|
|
@@ -56,6 +60,8 @@ var Finding = z.object({
|
|
|
56
60
|
severity: Severity,
|
|
57
61
|
message: z.string(),
|
|
58
62
|
files: z.array(z.string()).default([]),
|
|
63
|
+
/** 1-based line in `files[0]`, when the finding points at one line (line-level disable comments use it). */
|
|
64
|
+
line: z.number().int().positive().optional(),
|
|
59
65
|
/** Raw lab values used by the clinical layer (token counts, ratios, $). */
|
|
60
66
|
data: z.record(z.string(), z.unknown()).default({}),
|
|
61
67
|
monthlySavingsUsd: z.number().nonnegative().optional(),
|
|
@@ -142,6 +148,12 @@ var ConfigGraph = z.object({
|
|
|
142
148
|
nodes: z.array(GraphNode),
|
|
143
149
|
edges: z.array(z.object({ source: z.string(), target: z.string(), kind: z.enum(["loads", "symlink", "duplicate"]) }))
|
|
144
150
|
});
|
|
151
|
+
var PluginInfo = z.object({
|
|
152
|
+
name: z.string(),
|
|
153
|
+
version: z.string().optional(),
|
|
154
|
+
loaded: z.boolean(),
|
|
155
|
+
rules: z.array(RuleId)
|
|
156
|
+
});
|
|
145
157
|
|
|
146
158
|
// ../core/src/paths.ts
|
|
147
159
|
import os from "os";
|
|
@@ -787,6 +799,17 @@ var finopsMeta = {
|
|
|
787
799
|
|
|
788
800
|
// ../core/src/rules/index.ts
|
|
789
801
|
var rules = [brokenLink, contextBloat, duplicates, skills, secretLeak, syntax, bloatIgnore];
|
|
802
|
+
var unusedDisableMeta = {
|
|
803
|
+
description: "Remove ctxmedic-disable comments that silence nothing",
|
|
804
|
+
type: "suggestion",
|
|
805
|
+
docs: docsUrl("INFO_UNUSED_DISABLE"),
|
|
806
|
+
fixable: false
|
|
807
|
+
};
|
|
808
|
+
var allRuleMeta = (extraRules = []) => [
|
|
809
|
+
...[...rules, ...extraRules].map((r) => [r.id, r.meta, "config"]),
|
|
810
|
+
["INFO_UNUSED_DISABLE", unusedDisableMeta, "config"],
|
|
811
|
+
...Object.entries(finopsMeta).map(([id, meta2]) => [id, meta2, "session-logs"])
|
|
812
|
+
];
|
|
790
813
|
async function runRules(ctx2, list = rules, options = {}, off = /* @__PURE__ */ new Set()) {
|
|
791
814
|
const out = [];
|
|
792
815
|
for (const r of list) {
|
|
@@ -906,19 +929,59 @@ import fs6 from "fs";
|
|
|
906
929
|
import path9 from "path";
|
|
907
930
|
import picomatch2 from "picomatch";
|
|
908
931
|
import { z as z5 } from "zod";
|
|
932
|
+
|
|
933
|
+
// ../core/src/presets.ts
|
|
934
|
+
var PRESET_NAMES = ["ctxmedic:recommended", "ctxmedic:strict"];
|
|
935
|
+
var PRESETS = {
|
|
936
|
+
// Today's defaults, spelled out so a project can say it chose them.
|
|
937
|
+
"ctxmedic:recommended": { rules: {} },
|
|
938
|
+
// Stricter thresholds, and info-only rules raised to warnings. Rules that grade their own findings
|
|
939
|
+
// (secrets, broken links, bloat) keep "on": forcing a severity would demote their critical findings.
|
|
940
|
+
"ctxmedic:strict": {
|
|
941
|
+
rules: {
|
|
942
|
+
WARN_CONTEXT_BLOAT: ["on", { tokens: 2e3 }],
|
|
943
|
+
WARN_DUPLICATE_RULES: ["on", { similarity: 0.6 }],
|
|
944
|
+
INFO_UNSUPPORTED_SYNTAX: "warning",
|
|
945
|
+
INFO_UNUSED_DISABLE: "warning",
|
|
946
|
+
FIN_CONTEXT_SNOWBALL: ["on", { steps: 25 }],
|
|
947
|
+
FIN_CACHE_MISS: ["on", { minHitRatio: 0.5 }],
|
|
948
|
+
FIN_MODEL_OVERKILL: ["on", { minSessions: 2 }]
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
};
|
|
952
|
+
|
|
953
|
+
// ../core/src/config.ts
|
|
909
954
|
var CONFIG_FILE = "ctxmedic.config.json";
|
|
910
955
|
var RuleLevel = z5.union([z5.literal("off"), z5.literal("on"), Severity]);
|
|
911
956
|
var RuleEntry = z5.union([RuleLevel, z5.tuple([RuleLevel]), z5.tuple([RuleLevel, z5.record(z5.string(), z5.unknown())])]);
|
|
957
|
+
var Preset = z5.enum(PRESET_NAMES);
|
|
912
958
|
var CtxmedicConfig = z5.object({
|
|
913
959
|
$schema: z5.string().optional(),
|
|
960
|
+
/** Built-in presets applied in order before this file's own `rules` and `ignores`. */
|
|
961
|
+
extends: z5.union([Preset, z5.array(Preset)]).optional(),
|
|
914
962
|
rules: z5.partialRecord(RuleId, RuleEntry).default({}),
|
|
915
963
|
/** Globs over finding paths (project-relative, or `~/` for global files). */
|
|
916
|
-
ignores: z5.array(z5.string()).default([])
|
|
964
|
+
ignores: z5.array(z5.string()).default([]),
|
|
965
|
+
/** npm packages in the project's node_modules that add rules; loaded only with `--plugins` (ADR-027). */
|
|
966
|
+
plugins: z5.array(z5.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/, "an npm package name")).default([])
|
|
917
967
|
});
|
|
918
968
|
var ConfigError = class extends Error {
|
|
919
969
|
};
|
|
920
970
|
var levelOf = (e) => e === void 0 ? "on" : typeof e === "string" ? e : e[0];
|
|
921
971
|
var optionsOf = (e) => Array.isArray(e) && e[1] || {};
|
|
972
|
+
function resolveConfig(c) {
|
|
973
|
+
const names = c.extends === void 0 ? [] : typeof c.extends === "string" ? [c.extends] : c.extends;
|
|
974
|
+
const rules3 = {};
|
|
975
|
+
const ignores = [];
|
|
976
|
+
for (const layer of [...names.map((n2) => PRESETS[n2]), { rules: c.rules, ignores: c.ignores }]) {
|
|
977
|
+
for (const [id, entry] of Object.entries(layer.rules)) {
|
|
978
|
+
const before = optionsOf(rules3[id]);
|
|
979
|
+
rules3[id] = !Object.keys(optionsOf(entry)).length && Object.keys(before).length ? [levelOf(entry), before] : entry;
|
|
980
|
+
}
|
|
981
|
+
ignores.push(...layer.ignores ?? []);
|
|
982
|
+
}
|
|
983
|
+
return { ...c, rules: rules3, ignores };
|
|
984
|
+
}
|
|
922
985
|
var RuleInfo = z5.object({
|
|
923
986
|
id: RuleId,
|
|
924
987
|
/** "config": reads config files; "session-logs": a FIN_* detector that reads session logs. */
|
|
@@ -933,12 +996,8 @@ var RuleInfo = z5.object({
|
|
|
933
996
|
/** Options the config set to a value other than the default. */
|
|
934
997
|
changed: z5.record(z5.string(), z5.unknown())
|
|
935
998
|
});
|
|
936
|
-
function describeRules(config) {
|
|
937
|
-
|
|
938
|
-
...rules.map((r) => [r.id, r.meta, "config"]),
|
|
939
|
-
...Object.entries(finopsMeta).map(([id, meta2]) => [id, meta2, "session-logs"])
|
|
940
|
-
];
|
|
941
|
-
return all.map(([id, meta2, source]) => {
|
|
999
|
+
function describeRules(config, extraRules = []) {
|
|
1000
|
+
return allRuleMeta(extraRules).map(([id, meta2, source]) => {
|
|
942
1001
|
const entry = config.rules[id];
|
|
943
1002
|
const options = meta2.options?.parse(optionsOf(entry)) ?? {};
|
|
944
1003
|
const defaults = meta2.options?.parse({}) ?? {};
|
|
@@ -946,7 +1005,7 @@ function describeRules(config) {
|
|
|
946
1005
|
return RuleInfo.parse({ id, source, level: levelOf(entry), type: meta2.type, fixable: meta2.fixable, description: meta2.description, docs: meta2.docs, options, changed });
|
|
947
1006
|
});
|
|
948
1007
|
}
|
|
949
|
-
function loadConfig(root) {
|
|
1008
|
+
function loadConfig(root, extraRules = []) {
|
|
950
1009
|
const file2 = path9.join(root, CONFIG_FILE);
|
|
951
1010
|
if (!fs6.existsSync(file2)) return CtxmedicConfig.parse({});
|
|
952
1011
|
let raw;
|
|
@@ -957,53 +1016,80 @@ function loadConfig(root) {
|
|
|
957
1016
|
}
|
|
958
1017
|
const r = CtxmedicConfig.safeParse(raw);
|
|
959
1018
|
if (!r.success) throw new ConfigError(`${CONFIG_FILE}: ${z5.prettifyError(r.error)}`);
|
|
960
|
-
|
|
1019
|
+
const config = resolveConfig(r.data);
|
|
1020
|
+
for (const [id, entry] of Object.entries(config.rules)) {
|
|
961
1021
|
const opts = optionsOf(entry);
|
|
962
1022
|
if (!Object.keys(opts).length) continue;
|
|
963
|
-
const
|
|
1023
|
+
const known = allRuleMeta(extraRules).find(([x]) => x === id);
|
|
1024
|
+
if (!known && id.includes("/")) continue;
|
|
1025
|
+
const schema = known?.[1].options;
|
|
964
1026
|
if (!schema) throw new ConfigError(`${CONFIG_FILE}: rule ${id} takes no options`);
|
|
965
1027
|
const o2 = schema.safeParse(opts);
|
|
966
1028
|
if (!o2.success) throw new ConfigError(`${CONFIG_FILE}: rule ${id}: ${z5.prettifyError(o2.error)}`);
|
|
967
1029
|
}
|
|
968
|
-
return
|
|
1030
|
+
return config;
|
|
969
1031
|
}
|
|
970
1032
|
function configHash(c) {
|
|
971
1033
|
if (!Object.keys(c.rules).length && !c.ignores.length) return "";
|
|
972
1034
|
const rulesSorted = Object.fromEntries(Object.entries(c.rules).sort(([a2], [b]) => a2.localeCompare(b)));
|
|
973
1035
|
return crypto2.createHash("sha256").update(JSON.stringify([rulesSorted, c.ignores])).digest("hex").slice(0, 12);
|
|
974
1036
|
}
|
|
975
|
-
var DIRECTIVE = /<!--\s*ctxmedic-disable
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
const
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
1037
|
+
var DIRECTIVE = /<!--\s*ctxmedic-disable(-next-line|-line)?(?!\w|-(?!->))([\s\S]*?)-->/g;
|
|
1038
|
+
var lineAt = (text2, i) => text2.slice(0, i).split("\n").length;
|
|
1039
|
+
function directivesIn(text2) {
|
|
1040
|
+
return [...text2.matchAll(DIRECTIVE)].map((m) => {
|
|
1041
|
+
const kind = m[1] === "-next-line" ? "next-line" : m[1] === "-line" ? "line" : "file";
|
|
1042
|
+
const line = lineAt(text2, m.index);
|
|
1043
|
+
const ids = new Set(m[2].split("--")[0].split(/[\s,]+/).filter(Boolean));
|
|
1044
|
+
const target = kind === "line" ? line : kind === "next-line" ? lineAt(text2, m.index + m[0].length) + 1 : void 0;
|
|
1045
|
+
return { kind, ids, line, target };
|
|
1046
|
+
});
|
|
984
1047
|
}
|
|
985
|
-
function applyConfig(findings, files, config) {
|
|
1048
|
+
function applyConfig(findings, files, config, opts = {}) {
|
|
986
1049
|
const ignored = config.ignores.length ? picomatch2(config.ignores, { dot: true }) : () => false;
|
|
987
|
-
const
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
if (f.files.length && f.files.every((p3) => ignored(p3))) return
|
|
992
|
-
|
|
993
|
-
|
|
1050
|
+
const comments = new Map(files.filter((f) => f.text?.includes("ctxmedic-disable")).map((f) => [f.rel, directivesIn(f.text)]));
|
|
1051
|
+
const used = /* @__PURE__ */ new Set();
|
|
1052
|
+
const level = (f) => {
|
|
1053
|
+
const l = levelOf(config.rules[f.ruleId]);
|
|
1054
|
+
if (l === "off" || f.files.length && f.files.every((p3) => ignored(p3))) return null;
|
|
1055
|
+
return l === "on" ? f : { ...f, severity: l };
|
|
1056
|
+
};
|
|
1057
|
+
const out = findings.flatMap((f) => {
|
|
1058
|
+
const kept = level(f);
|
|
1059
|
+
if (!kept) return [];
|
|
1060
|
+
const hits = f.files.flatMap(
|
|
1061
|
+
(p3, i) => (comments.get(p3) ?? []).filter(
|
|
1062
|
+
(d2) => (!d2.ids.size || d2.ids.has(f.ruleId)) && (d2.kind === "file" || i === 0 && f.line !== void 0 && d2.target === f.line)
|
|
1063
|
+
)
|
|
1064
|
+
);
|
|
1065
|
+
for (const d2 of hits) used.add(d2);
|
|
1066
|
+
return hits.length ? [] : [kept];
|
|
994
1067
|
});
|
|
1068
|
+
if (!opts.reportUnused) return out;
|
|
1069
|
+
const unused = [...comments].flatMap(
|
|
1070
|
+
([rel, ds]) => ds.filter((d2) => !used.has(d2)).map((d2) => ({
|
|
1071
|
+
ruleId: "INFO_UNUSED_DISABLE",
|
|
1072
|
+
severity: "info",
|
|
1073
|
+
message: `${rel}:${d2.line}: ctxmedic-disable${d2.kind === "file" ? "" : `-${d2.kind}`} silences nothing`,
|
|
1074
|
+
files: [rel],
|
|
1075
|
+
line: d2.line,
|
|
1076
|
+
data: { ids: [...d2.ids], kind: d2.kind }
|
|
1077
|
+
}))
|
|
1078
|
+
);
|
|
1079
|
+
return [...out, ...unused.flatMap((f) => level(f) ?? [])];
|
|
995
1080
|
}
|
|
996
1081
|
|
|
997
1082
|
// ../core/src/examine.ts
|
|
998
1083
|
async function examine(root, profiles, opts = {}) {
|
|
999
1084
|
root = path10.resolve(root);
|
|
1000
|
-
const
|
|
1085
|
+
const extraRules = opts.extraRules ?? [];
|
|
1086
|
+
const config = loadConfig(root, extraRules);
|
|
1001
1087
|
const files = await scan(root, profiles, opts);
|
|
1002
1088
|
const startup = startupLoad(files, profiles);
|
|
1003
1089
|
const entries = Object.entries(config.rules);
|
|
1004
1090
|
const off = new Set(entries.filter(([, e]) => levelOf(e) === "off").map(([id]) => id));
|
|
1005
1091
|
const options = Object.fromEntries(entries.map(([id, e]) => [id, optionsOf(e)]));
|
|
1006
|
-
const findings = applyConfig(await runRules({ root, files, profiles, startup },
|
|
1092
|
+
const findings = applyConfig(await runRules({ root, files, profiles, startup }, [...rules, ...extraRules], options, off), files, config, { reportUnused: true });
|
|
1007
1093
|
const vitals2 = PatientVitals.parse({
|
|
1008
1094
|
root,
|
|
1009
1095
|
scannedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -1014,84 +1100,131 @@ async function examine(root, profiles, opts = {}) {
|
|
|
1014
1100
|
return { vitals: vitals2, files, startup, findings, config };
|
|
1015
1101
|
}
|
|
1016
1102
|
|
|
1103
|
+
// ../core/src/plugins.ts
|
|
1104
|
+
import fs7 from "fs";
|
|
1105
|
+
import path11 from "path";
|
|
1106
|
+
import { pathToFileURL } from "url";
|
|
1107
|
+
import { z as z6 } from "zod";
|
|
1108
|
+
var fn = z6.custom((v) => typeof v === "function", "a function");
|
|
1109
|
+
var PluginRule = z6.object({
|
|
1110
|
+
id: z6.string().regex(EXTERNAL_RULE_ID, "a namespaced id like plugin/RULE_NAME"),
|
|
1111
|
+
meta: z6.object({
|
|
1112
|
+
description: z6.string().min(1),
|
|
1113
|
+
type: z6.enum(["problem", "suggestion"]),
|
|
1114
|
+
docs: z6.string(),
|
|
1115
|
+
fixable: z6.boolean(),
|
|
1116
|
+
options: z6.custom((v) => v === void 0 || typeof v?.safeParse === "function", "a zod schema").optional(),
|
|
1117
|
+
card: z6.object({ name: z6.string(), prognosis: fn, action: fn }).optional()
|
|
1118
|
+
}),
|
|
1119
|
+
check: fn
|
|
1120
|
+
});
|
|
1121
|
+
var PluginModule = z6.object({ namespace: z6.string().regex(/^[a-z][a-z0-9-]*$/), rules: z6.array(PluginRule) });
|
|
1122
|
+
function entryOf(dir, pkg) {
|
|
1123
|
+
const pick = (e) => typeof e === "string" ? e : e && typeof e === "object" ? pick(e.import ?? e.default ?? e.node) : void 0;
|
|
1124
|
+
const ex = pkg.exports;
|
|
1125
|
+
const dot = typeof ex === "string" || ex && !Object.keys(ex).some((k) => k.startsWith(".")) ? ex : ex?.["."];
|
|
1126
|
+
return path11.resolve(dir, pick(dot) ?? pkg.module ?? pkg.main ?? "index.js");
|
|
1127
|
+
}
|
|
1128
|
+
async function loadPlugins(root, names) {
|
|
1129
|
+
const out = [];
|
|
1130
|
+
for (const name of names) {
|
|
1131
|
+
const dir = path11.join(path11.resolve(root), "node_modules", name);
|
|
1132
|
+
const pkgFile = path11.join(dir, "package.json");
|
|
1133
|
+
if (!fs7.existsSync(pkgFile)) throw new ConfigError(`plugin ${name} is not installed in ${path11.join(root, "node_modules")}`);
|
|
1134
|
+
const pkg = JSON.parse(fs7.readFileSync(pkgFile, "utf8"));
|
|
1135
|
+
const entry = entryOf(dir, pkg);
|
|
1136
|
+
if (path11.relative(dir, entry).startsWith("..")) throw new ConfigError(`plugin ${name}: its entry point is outside the package`);
|
|
1137
|
+
const mod = await import(pathToFileURL(entry).href);
|
|
1138
|
+
const parsed = PluginModule.safeParse(mod.default ?? mod);
|
|
1139
|
+
if (!parsed.success) throw new ConfigError(`plugin ${name}: ${z6.prettifyError(parsed.error)}`);
|
|
1140
|
+
const { namespace, rules: rules3 } = parsed.data;
|
|
1141
|
+
const foreign = rules3.find((r) => !r.id.startsWith(`${namespace}/`));
|
|
1142
|
+
if (foreign) throw new ConfigError(`plugin ${name}: rule ${foreign.id} is outside its namespace ${namespace}/`);
|
|
1143
|
+
out.push({ name, version: pkg.version, rules: (mod.default ?? mod).rules });
|
|
1144
|
+
}
|
|
1145
|
+
return out;
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1017
1148
|
// ../clinical/src/schema.ts
|
|
1018
|
-
var Lang =
|
|
1019
|
-
var Triage =
|
|
1020
|
-
var PrescriptionRx =
|
|
1021
|
-
id:
|
|
1022
|
-
action:
|
|
1023
|
-
command:
|
|
1024
|
-
autoFix:
|
|
1025
|
-
healthGain:
|
|
1026
|
-
monthlySavingsUsd:
|
|
1149
|
+
var Lang = z7.enum(["en"]);
|
|
1150
|
+
var Triage = z7.enum(["resuscitation", "therapy", "preventive"]);
|
|
1151
|
+
var PrescriptionRx = z7.object({
|
|
1152
|
+
id: z7.string().regex(/^RX-\d{2,}$/),
|
|
1153
|
+
action: z7.string(),
|
|
1154
|
+
command: z7.string().optional(),
|
|
1155
|
+
autoFix: z7.boolean(),
|
|
1156
|
+
healthGain: z7.number().nonnegative(),
|
|
1157
|
+
monthlySavingsUsd: z7.number().nonnegative().optional()
|
|
1027
1158
|
});
|
|
1028
|
-
var ClinicalDiagnosis =
|
|
1159
|
+
var ClinicalDiagnosis = z7.object({
|
|
1029
1160
|
code: RuleId,
|
|
1030
1161
|
triage: Triage,
|
|
1031
|
-
diagnosis:
|
|
1032
|
-
summary:
|
|
1033
|
-
vitals:
|
|
1034
|
-
prognosis:
|
|
1162
|
+
diagnosis: z7.string(),
|
|
1163
|
+
summary: z7.string(),
|
|
1164
|
+
vitals: z7.array(z7.object({ label: z7.string(), value: z7.string() })),
|
|
1165
|
+
prognosis: z7.string(),
|
|
1035
1166
|
rx: PrescriptionRx,
|
|
1036
|
-
files:
|
|
1167
|
+
files: z7.array(z7.string()),
|
|
1037
1168
|
finding: Finding
|
|
1038
1169
|
});
|
|
1039
|
-
var Counts =
|
|
1040
|
-
var Anamnesis =
|
|
1041
|
-
priority:
|
|
1042
|
-
primaryHarness:
|
|
1043
|
-
monthlyBudgetUsd:
|
|
1170
|
+
var Counts = z7.object({ resuscitation: z7.number(), therapy: z7.number(), preventive: z7.number() });
|
|
1171
|
+
var Anamnesis = z7.object({
|
|
1172
|
+
priority: z7.enum(["economy", "balanced", "quality"]).default("balanced"),
|
|
1173
|
+
primaryHarness: z7.string().optional(),
|
|
1174
|
+
monthlyBudgetUsd: z7.number().nonnegative().optional()
|
|
1044
1175
|
});
|
|
1045
|
-
var ScanSettings =
|
|
1046
|
-
global:
|
|
1047
|
-
finops:
|
|
1048
|
-
days:
|
|
1176
|
+
var ScanSettings = z7.object({
|
|
1177
|
+
global: z7.boolean(),
|
|
1178
|
+
finops: z7.boolean(),
|
|
1179
|
+
days: z7.number(),
|
|
1049
1180
|
/** `configHash` of ctxmedic.config.json; "" without one, and in history written before v0.3. */
|
|
1050
|
-
config:
|
|
1181
|
+
config: z7.string().default("")
|
|
1051
1182
|
});
|
|
1052
1183
|
var DEFAULT_SCAN = { global: true, finops: true, days: 30, config: "" };
|
|
1053
|
-
var Visit =
|
|
1054
|
-
at:
|
|
1055
|
-
root:
|
|
1184
|
+
var Visit = z7.object({
|
|
1185
|
+
at: z7.string(),
|
|
1186
|
+
root: z7.string(),
|
|
1056
1187
|
/** Missing in history written by v0.1.0: those runs are assumed to use the defaults. */
|
|
1057
1188
|
scan: ScanSettings.default(DEFAULT_SCAN),
|
|
1058
|
-
healthScore:
|
|
1189
|
+
healthScore: z7.number(),
|
|
1059
1190
|
counts: Counts,
|
|
1060
|
-
monthlySpendUsd:
|
|
1061
|
-
potentialMonthlySavingsUsd:
|
|
1191
|
+
monthlySpendUsd: z7.number().optional(),
|
|
1192
|
+
potentialMonthlySavingsUsd: z7.number()
|
|
1062
1193
|
});
|
|
1063
|
-
var ClinicalReport =
|
|
1064
|
-
tool:
|
|
1065
|
-
version:
|
|
1194
|
+
var ClinicalReport = z7.object({
|
|
1195
|
+
tool: z7.literal("ctxmedic"),
|
|
1196
|
+
version: z7.string(),
|
|
1066
1197
|
lang: Lang,
|
|
1067
|
-
generatedAt:
|
|
1198
|
+
generatedAt: z7.string(),
|
|
1068
1199
|
patient: PatientVitals,
|
|
1069
|
-
healthScore:
|
|
1200
|
+
healthScore: z7.number().min(0).max(100),
|
|
1070
1201
|
previous: Visit.nullable(),
|
|
1071
|
-
opinion:
|
|
1202
|
+
opinion: z7.string(),
|
|
1072
1203
|
counts: Counts,
|
|
1073
|
-
diagnoses:
|
|
1204
|
+
diagnoses: z7.array(ClinicalDiagnosis),
|
|
1074
1205
|
finops: FinOpsReport.nullable(),
|
|
1075
|
-
potentialMonthlySavingsUsd:
|
|
1206
|
+
potentialMonthlySavingsUsd: z7.number(),
|
|
1207
|
+
/** Plugins listed in the config and whether this run loaded them (ADR-027). */
|
|
1208
|
+
plugins: z7.array(PluginInfo).default([])
|
|
1076
1209
|
});
|
|
1077
1210
|
|
|
1078
1211
|
// ../finops/src/cache.ts
|
|
1079
|
-
import
|
|
1080
|
-
import
|
|
1081
|
-
var file = () =>
|
|
1212
|
+
import fs8 from "fs";
|
|
1213
|
+
import path12 from "path";
|
|
1214
|
+
var file = () => path12.join(stateDir(), "cache.json");
|
|
1082
1215
|
function loadCache() {
|
|
1083
1216
|
try {
|
|
1084
|
-
const c = JSON.parse(
|
|
1217
|
+
const c = JSON.parse(fs8.readFileSync(file(), "utf8"));
|
|
1085
1218
|
if (c?.v === 3 && c.files) return c;
|
|
1086
1219
|
} catch {
|
|
1087
1220
|
}
|
|
1088
1221
|
return { v: 3, files: {} };
|
|
1089
1222
|
}
|
|
1090
1223
|
function saveCache(c) {
|
|
1091
|
-
|
|
1224
|
+
fs8.mkdirSync(stateDir(), { recursive: true });
|
|
1092
1225
|
const tmp = file() + ".tmp";
|
|
1093
|
-
|
|
1094
|
-
|
|
1226
|
+
fs8.writeFileSync(tmp, JSON.stringify(c));
|
|
1227
|
+
fs8.renameSync(tmp, file());
|
|
1095
1228
|
}
|
|
1096
1229
|
async function cachedParse(paths, parse, cache) {
|
|
1097
1230
|
const stats = [];
|
|
@@ -1099,7 +1232,7 @@ async function cachedParse(paths, parse, cache) {
|
|
|
1099
1232
|
for (const p3 of paths) {
|
|
1100
1233
|
let st;
|
|
1101
1234
|
try {
|
|
1102
|
-
st =
|
|
1235
|
+
st = fs8.statSync(p3);
|
|
1103
1236
|
} catch {
|
|
1104
1237
|
continue;
|
|
1105
1238
|
}
|
|
@@ -1117,7 +1250,7 @@ async function cachedParse(paths, parse, cache) {
|
|
|
1117
1250
|
}
|
|
1118
1251
|
|
|
1119
1252
|
// ../finops/src/detectors.ts
|
|
1120
|
-
import
|
|
1253
|
+
import path13 from "path";
|
|
1121
1254
|
|
|
1122
1255
|
// ../finops/src/pricing.ts
|
|
1123
1256
|
var PRICING_AS_OF = "2026-11-03";
|
|
@@ -1247,7 +1380,7 @@ var contextSnowball = detector("FIN_CONTEXT_SNOWBALL", ({ sessions, days }, { st
|
|
|
1247
1380
|
ruleId: "FIN_CONTEXT_SNOWBALL",
|
|
1248
1381
|
severity: sev(usd3),
|
|
1249
1382
|
message: `${bad.length} session(s) ran >${steps} steps with 100k+ context and no /clear or /compact`,
|
|
1250
|
-
files: bad.slice(0, 5).map((s) => `session ${
|
|
1383
|
+
files: bad.slice(0, 5).map((s) => `session ${path13.basename(s.file, ".jsonl")}`),
|
|
1251
1384
|
data: { sessions: bad.length, worstSteps: worst.steps, worstMaxContext: worst.maxContext, days },
|
|
1252
1385
|
monthlySavingsUsd: round(usd3)
|
|
1253
1386
|
}
|
|
@@ -1281,8 +1414,8 @@ var cacheMiss = detector("FIN_CACHE_MISS", ({ sessions, days }, { minHitRatio, t
|
|
|
1281
1414
|
var detectors = [unusedMcp, modelOverkill, contextSnowball, cacheMiss];
|
|
1282
1415
|
|
|
1283
1416
|
// ../finops/src/parsers.ts
|
|
1284
|
-
import
|
|
1285
|
-
import
|
|
1417
|
+
import fs9 from "fs";
|
|
1418
|
+
import path14 from "path";
|
|
1286
1419
|
import readline from "readline";
|
|
1287
1420
|
var SNOWBALL_CONTEXT = 1e5;
|
|
1288
1421
|
var HEALTHY_CONTEXT = 4e4;
|
|
@@ -1313,7 +1446,7 @@ function schemas(s, defs) {
|
|
|
1313
1446
|
for (const [name, d2] of Object.entries(defs)) s.mcpSchemaTokens[name] = Math.max(s.mcpSchemaTokens[name] ?? 0, countTokens(JSON.stringify(d2)));
|
|
1314
1447
|
}
|
|
1315
1448
|
async function* lines(file2) {
|
|
1316
|
-
const rl = readline.createInterface({ input:
|
|
1449
|
+
const rl = readline.createInterface({ input: fs9.createReadStream(file2), crlfDelay: Infinity });
|
|
1317
1450
|
for await (const line of rl) {
|
|
1318
1451
|
if (!line) continue;
|
|
1319
1452
|
try {
|
|
@@ -1392,7 +1525,7 @@ async function parseCursor(file2) {
|
|
|
1392
1525
|
for (const c of Array.isArray(content) ? content : []) if (c?.type === "tool_use" || c?.type === "tool-call") mcp(s, c.name ?? c.toolName);
|
|
1393
1526
|
}
|
|
1394
1527
|
if (!s.end) {
|
|
1395
|
-
const t2 =
|
|
1528
|
+
const t2 = fs9.statSync(file2).mtime.toISOString();
|
|
1396
1529
|
s.start ??= t2;
|
|
1397
1530
|
s.end = t2;
|
|
1398
1531
|
}
|
|
@@ -1505,6 +1638,11 @@ var en = {
|
|
|
1505
1638
|
prognosis: (f) => `${d(f, "harness")} reads ${(d(f, "directives") ?? []).join(", ")} as plain text: noise at best, wrong instructions at worst.`,
|
|
1506
1639
|
action: () => "Move tool-specific directives into that tool's own file, or keep shared files directive-free."
|
|
1507
1640
|
},
|
|
1641
|
+
INFO_UNUSED_DISABLE: {
|
|
1642
|
+
name: "Phantom Prescription",
|
|
1643
|
+
prognosis: (f) => `${f.files[0]}:${f.line} silences ${(d(f, "ids") ?? []).join(", ") || "every rule"}, but nothing there needed it. A stale disable hides the next real problem.`,
|
|
1644
|
+
action: (f) => `Delete the ctxmedic-disable comment on line ${f.line} of ${f.files[0]}.`
|
|
1645
|
+
},
|
|
1508
1646
|
FIN_BLOAT_IGNORE: {
|
|
1509
1647
|
name: "Indexing Bloat",
|
|
1510
1648
|
prognosis: (f) => `${d(f, "harness")} indexes build output and lockfiles. Search results fill with junk and retrieval burns tokens.`,
|
|
@@ -1531,6 +1669,10 @@ var en = {
|
|
|
1531
1669
|
action: () => "Keep instructions static: no dates, branch names or random IDs at the top; avoid switching models mid-session."
|
|
1532
1670
|
}
|
|
1533
1671
|
},
|
|
1672
|
+
externalCard: {
|
|
1673
|
+
prognosis: (description) => `Reported by a rule from outside ctxmedic: ${description}.`,
|
|
1674
|
+
action: (docs) => docs ? `See the rule's docs: ${docs}` : "See the docs of the plugin that provides this rule."
|
|
1675
|
+
},
|
|
1534
1676
|
ui: {
|
|
1535
1677
|
triage: { resuscitation: "\u{1F534} Resuscitation", therapy: "\u{1F7E1} Therapy", preventive: "\u{1F7E2} Preventive" },
|
|
1536
1678
|
labs: "Vitals",
|
|
@@ -1545,7 +1687,9 @@ var en = {
|
|
|
1545
1687
|
noLogs: "No session logs found: FinOps analysis skipped.",
|
|
1546
1688
|
spend: "Spend",
|
|
1547
1689
|
runRate: "run rate",
|
|
1548
|
-
estimatedPrice: "\u2248 model not in the price table: estimated at Sonnet-class rates"
|
|
1690
|
+
estimatedPrice: "\u2248 model not in the price table: estimated at Sonnet-class rates",
|
|
1691
|
+
pluginsLoaded: (list) => `plugins: ${list}`,
|
|
1692
|
+
pluginsSkipped: (names) => `plugins not loaded: ${names}. Run with --plugins to load them (their code runs with ctxmedic's rights).`
|
|
1549
1693
|
},
|
|
1550
1694
|
cli: {
|
|
1551
1695
|
noBackups: "No backups in .ctxmedic/backups: nothing to restore.",
|
|
@@ -1607,22 +1751,22 @@ function healthGain(findings, f) {
|
|
|
1607
1751
|
}
|
|
1608
1752
|
|
|
1609
1753
|
// ../clinical/src/store.ts
|
|
1610
|
-
import
|
|
1611
|
-
import
|
|
1754
|
+
import fs10 from "fs";
|
|
1755
|
+
import path15 from "path";
|
|
1612
1756
|
var MAX_VISITS = 200;
|
|
1613
|
-
var historyFile = () =>
|
|
1614
|
-
var profileFile = () =>
|
|
1757
|
+
var historyFile = () => path15.join(stateDir(), "history.json");
|
|
1758
|
+
var profileFile = () => path15.join(stateDir(), "profile.json");
|
|
1615
1759
|
function readJson(file2) {
|
|
1616
1760
|
try {
|
|
1617
|
-
return JSON.parse(
|
|
1761
|
+
return JSON.parse(fs10.readFileSync(file2, "utf8"));
|
|
1618
1762
|
} catch {
|
|
1619
1763
|
return void 0;
|
|
1620
1764
|
}
|
|
1621
1765
|
}
|
|
1622
1766
|
function writeJson(file2, v) {
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1767
|
+
fs10.mkdirSync(path15.dirname(file2), { recursive: true });
|
|
1768
|
+
fs10.writeFileSync(file2 + ".tmp", JSON.stringify(v, null, 2));
|
|
1769
|
+
fs10.renameSync(file2 + ".tmp", file2);
|
|
1626
1770
|
}
|
|
1627
1771
|
var sameScan = (a2, b) => a2.global === b.global && a2.finops === b.finops && (!a2.finops || a2.days === b.days) && a2.config === b.config;
|
|
1628
1772
|
function loadHistory(root, scan2) {
|
|
@@ -1726,13 +1870,14 @@ var harnesses = [
|
|
|
1726
1870
|
];
|
|
1727
1871
|
|
|
1728
1872
|
// ../clinical/src/engine.ts
|
|
1729
|
-
var VERSION = true ? "0.
|
|
1873
|
+
var VERSION = true ? "0.12.0" : "0.0.0-dev";
|
|
1730
1874
|
var TRIAGE = { critical: "resuscitation", warning: "therapy", info: "preventive" };
|
|
1731
1875
|
var ORDER = ["resuscitation", "therapy", "preventive"];
|
|
1732
1876
|
var human = (k) => k.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());
|
|
1733
1877
|
function vitals(f) {
|
|
1734
1878
|
const out = [];
|
|
1735
|
-
|
|
1879
|
+
const shown = f.files.slice(0, 3).map((p3, i) => i === 0 && f.line ? `${p3}:${f.line}` : p3);
|
|
1880
|
+
if (f.files.length) out.push({ label: "Files", value: shown.join(", ") + (f.files.length > 3 ? ` +${f.files.length - 3}` : "") });
|
|
1736
1881
|
for (const [k, v] of Object.entries(f.data)) {
|
|
1737
1882
|
if (typeof v === "number")
|
|
1738
1883
|
out.push({
|
|
@@ -1746,8 +1891,15 @@ function vitals(f) {
|
|
|
1746
1891
|
if (f.monthlySavingsUsd) out.push({ label: "Savings", value: `$${f.monthlySavingsUsd.toFixed(2)}/mo` });
|
|
1747
1892
|
return out;
|
|
1748
1893
|
}
|
|
1749
|
-
function diagnose(findings, lang, anamnesis = Anamnesis.parse({})) {
|
|
1894
|
+
function diagnose(findings, lang, anamnesis = Anamnesis.parse({}), extraRules = []) {
|
|
1750
1895
|
const cat = cards(lang);
|
|
1896
|
+
const cardFor = (f) => {
|
|
1897
|
+
if (cat[f.ruleId]) return cat[f.ruleId];
|
|
1898
|
+
const meta2 = extraRules.find((r) => r.id === f.ruleId)?.meta;
|
|
1899
|
+
if (meta2?.card) return meta2.card;
|
|
1900
|
+
const ext = messages(lang).externalCard;
|
|
1901
|
+
return { name: f.ruleId, prognosis: () => ext.prognosis(meta2?.description ?? f.message), action: () => ext.action(meta2?.docs) };
|
|
1902
|
+
};
|
|
1751
1903
|
const weight = (f) => {
|
|
1752
1904
|
const gain = healthGain(findings, f);
|
|
1753
1905
|
const usd3 = f.monthlySavingsUsd ?? 0;
|
|
@@ -1758,7 +1910,7 @@ function diagnose(findings, lang, anamnesis = Anamnesis.parse({})) {
|
|
|
1758
1910
|
);
|
|
1759
1911
|
return sorted.map((f, i) => {
|
|
1760
1912
|
const id = `RX-${String(i + 1).padStart(2, "0")}`;
|
|
1761
|
-
const card2 =
|
|
1913
|
+
const card2 = cardFor(f);
|
|
1762
1914
|
return {
|
|
1763
1915
|
code: f.ruleId,
|
|
1764
1916
|
triage: TRIAGE[f.severity],
|
|
@@ -1786,11 +1938,18 @@ var scanSettings = (opts) => ({
|
|
|
1786
1938
|
config: opts.config ?? ""
|
|
1787
1939
|
});
|
|
1788
1940
|
async function checkup(opts) {
|
|
1789
|
-
const
|
|
1941
|
+
const listed = loadConfig(opts.root).plugins;
|
|
1942
|
+
const loaded = opts.plugins ? await loadPlugins(opts.root, listed) : [];
|
|
1943
|
+
const extraRules = [...opts.extraRules ?? [], ...loaded.flatMap((p3) => p3.rules)];
|
|
1944
|
+
const plugins2 = listed.map((name) => {
|
|
1945
|
+
const p3 = loaded.find((x) => x.name === name);
|
|
1946
|
+
return { name, version: p3?.version, loaded: Boolean(p3), rules: p3?.rules.map((r) => r.id) ?? [] };
|
|
1947
|
+
});
|
|
1948
|
+
const ex = await examine(opts.root, harnesses, { global: opts.global, extraRules });
|
|
1790
1949
|
let finops = null;
|
|
1791
1950
|
if (opts.finops !== false) finops = await analyze({ root: ex.vitals.root, files: ex.files, days: opts.days ?? 30, config: ex.config });
|
|
1792
1951
|
const findings = [...ex.findings, ...finops?.findings ?? []];
|
|
1793
|
-
const diagnoses = diagnose(findings, opts.lang, loadAnamnesis());
|
|
1952
|
+
const diagnoses = diagnose(findings, opts.lang, loadAnamnesis(), extraRules);
|
|
1794
1953
|
const score = healthScore(findings);
|
|
1795
1954
|
const counts = { resuscitation: 0, therapy: 0, preventive: 0 };
|
|
1796
1955
|
for (const d2 of diagnoses) counts[d2.triage]++;
|
|
@@ -1809,7 +1968,8 @@ async function checkup(opts) {
|
|
|
1809
1968
|
counts,
|
|
1810
1969
|
diagnoses,
|
|
1811
1970
|
finops,
|
|
1812
|
-
potentialMonthlySavingsUsd: Math.round(savings * 100) / 100
|
|
1971
|
+
potentialMonthlySavingsUsd: Math.round(savings * 100) / 100,
|
|
1972
|
+
plugins: plugins2
|
|
1813
1973
|
});
|
|
1814
1974
|
if (opts.record !== false)
|
|
1815
1975
|
recordVisit({
|
|
@@ -1971,8 +2131,8 @@ async function askAnthropic(prompt, onProgress) {
|
|
|
1971
2131
|
|
|
1972
2132
|
// ../server/src/index.ts
|
|
1973
2133
|
import crypto3 from "crypto";
|
|
1974
|
-
import
|
|
1975
|
-
import
|
|
2134
|
+
import fs11 from "fs";
|
|
2135
|
+
import path16 from "path";
|
|
1976
2136
|
import { serve } from "@hono/node-server";
|
|
1977
2137
|
import { serveStatic } from "@hono/node-server/serve-static";
|
|
1978
2138
|
import { Hono } from "hono";
|
|
@@ -1992,14 +2152,14 @@ function configWatcher(root) {
|
|
|
1992
2152
|
if (!subs.size) return;
|
|
1993
2153
|
const dirs = /* @__PURE__ */ new Map();
|
|
1994
2154
|
for (const f of ex.files) {
|
|
1995
|
-
const dir =
|
|
1996
|
-
if (dirs.get(dir) !== null) dirs.set(dir, (dirs.get(dir) ?? /* @__PURE__ */ new Set()).add(
|
|
1997
|
-
if (f.role === "skill") dirs.set(
|
|
2155
|
+
const dir = path16.dirname(f.path);
|
|
2156
|
+
if (dirs.get(dir) !== null) dirs.set(dir, (dirs.get(dir) ?? /* @__PURE__ */ new Set()).add(path16.basename(f.path)));
|
|
2157
|
+
if (f.role === "skill") dirs.set(path16.dirname(dir), null);
|
|
1998
2158
|
}
|
|
1999
2159
|
const sig = (p3, isDir) => {
|
|
2000
2160
|
try {
|
|
2001
|
-
if (isDir) return
|
|
2002
|
-
const st =
|
|
2161
|
+
if (isDir) return fs11.readdirSync(p3).sort().join("/");
|
|
2162
|
+
const st = fs11.statSync(p3);
|
|
2003
2163
|
return `${st.mtimeMs}:${st.size}`;
|
|
2004
2164
|
} catch {
|
|
2005
2165
|
return "gone";
|
|
@@ -2008,10 +2168,10 @@ function configWatcher(root) {
|
|
|
2008
2168
|
const seen = /* @__PURE__ */ new Map();
|
|
2009
2169
|
for (const [dir, names] of dirs) {
|
|
2010
2170
|
if (!names) seen.set(dir, sig(dir, true));
|
|
2011
|
-
else for (const n2 of names) seen.set(
|
|
2171
|
+
else for (const n2 of names) seen.set(path16.join(dir, n2), sig(path16.join(dir, n2), false));
|
|
2012
2172
|
}
|
|
2013
2173
|
const onEvent = (dir, names, name) => {
|
|
2014
|
-
const p3 = names ? name && names.has(name) ?
|
|
2174
|
+
const p3 = names ? name && names.has(name) ? path16.join(dir, name) : null : dir;
|
|
2015
2175
|
if (!p3) return;
|
|
2016
2176
|
const now = sig(p3, !names);
|
|
2017
2177
|
if (now === seen.get(p3)) return;
|
|
@@ -2020,7 +2180,7 @@ function configWatcher(root) {
|
|
|
2020
2180
|
};
|
|
2021
2181
|
for (const [dir, names] of dirs) {
|
|
2022
2182
|
try {
|
|
2023
|
-
const w =
|
|
2183
|
+
const w = fs11.watch(dir, (_, name) => onEvent(dir, names, name === null ? null : String(name)));
|
|
2024
2184
|
w.unref();
|
|
2025
2185
|
watchers.push(w);
|
|
2026
2186
|
} catch {
|
|
@@ -2035,13 +2195,13 @@ function configWatcher(root) {
|
|
|
2035
2195
|
}, 300);
|
|
2036
2196
|
};
|
|
2037
2197
|
return {
|
|
2038
|
-
subscribe(
|
|
2039
|
-
subs.add(
|
|
2198
|
+
subscribe(fn2) {
|
|
2199
|
+
subs.add(fn2);
|
|
2040
2200
|
if (subs.size === 1) ready = watch();
|
|
2041
2201
|
return {
|
|
2042
2202
|
ready,
|
|
2043
2203
|
off: () => {
|
|
2044
|
-
subs.delete(
|
|
2204
|
+
subs.delete(fn2);
|
|
2045
2205
|
if (!subs.size) {
|
|
2046
2206
|
clearTimeout(timer);
|
|
2047
2207
|
close();
|
|
@@ -2053,7 +2213,7 @@ function configWatcher(root) {
|
|
|
2053
2213
|
}
|
|
2054
2214
|
function createApp(opts) {
|
|
2055
2215
|
const app = new Hono();
|
|
2056
|
-
const root =
|
|
2216
|
+
const root = path16.resolve(opts.root);
|
|
2057
2217
|
app.use("/api/*", async (c, next) => {
|
|
2058
2218
|
c.header("cache-control", "no-store");
|
|
2059
2219
|
if (c.req.method !== "GET" && c.req.header("x-ctxmedic-token") !== opts.token) return c.json({ error: "invalid session token" }, 403);
|
|
@@ -2075,7 +2235,7 @@ function createApp(opts) {
|
|
|
2075
2235
|
);
|
|
2076
2236
|
app.get("/api/checkup", async (c) => {
|
|
2077
2237
|
const lang = c.req.query("lang") ? resolveLang(c.req.query("lang")) : opts.lang;
|
|
2078
|
-
return c.json(await checkup({ root, lang, days: opts.days, record: c.req.query("record") === "1" }));
|
|
2238
|
+
return c.json(await checkup({ root, lang, days: opts.days, plugins: opts.plugins, record: c.req.query("record") === "1" }));
|
|
2079
2239
|
});
|
|
2080
2240
|
app.get("/api/history", (c) => c.json(loadHistory(root, scanSettings({ days: opts.days, config: configHash(loadConfig(root)) }))));
|
|
2081
2241
|
app.get("/api/graph", async (c) => {
|
|
@@ -2088,7 +2248,7 @@ function createApp(opts) {
|
|
|
2088
2248
|
for (const f of ex.files) {
|
|
2089
2249
|
for (const h of f.harnesses) edges.push({ source: `h:${h}`, target: f.path, kind: "loads" });
|
|
2090
2250
|
if (f.isSymlink && f.realpath) {
|
|
2091
|
-
if (!nodes.some((n2) => n2.id === f.realpath)) nodes.push({ id: f.realpath, kind: "target", label:
|
|
2251
|
+
if (!nodes.some((n2) => n2.id === f.realpath)) nodes.push({ id: f.realpath, kind: "target", label: path16.relative(root, f.realpath), tokens: f.tokens, broken: false, scope: f.scope });
|
|
2092
2252
|
edges.push({ source: f.path, target: f.realpath, kind: "symlink" });
|
|
2093
2253
|
}
|
|
2094
2254
|
}
|
|
@@ -2101,16 +2261,16 @@ function createApp(opts) {
|
|
|
2101
2261
|
app.post("/api/treat/:rx", async (c) => {
|
|
2102
2262
|
const dryRun = c.req.query("dryRun") === "1";
|
|
2103
2263
|
try {
|
|
2104
|
-
const r = await treat(c.req.param("rx"), { root, lang: opts.lang, days: opts.days, dryRun });
|
|
2264
|
+
const r = await treat(c.req.param("rx"), { root, lang: opts.lang, days: opts.days, plugins: opts.plugins, dryRun });
|
|
2105
2265
|
return c.json({ rx: r.diagnosis.rx.id, applied: r.result?.applied ?? [], backupDir: r.result?.backupDir, dryRun, manual: r.manual });
|
|
2106
2266
|
} catch (e) {
|
|
2107
2267
|
return c.json({ error: e.message }, e instanceof FixRefusedError ? 409 : 500);
|
|
2108
2268
|
}
|
|
2109
2269
|
});
|
|
2110
|
-
if (opts.publicDir &&
|
|
2111
|
-
const rel =
|
|
2270
|
+
if (opts.publicDir && fs11.existsSync(path16.join(opts.publicDir, "index.html"))) {
|
|
2271
|
+
const rel = path16.relative(process.cwd(), opts.publicDir) || ".";
|
|
2112
2272
|
app.use("/*", serveStatic({ root: rel }));
|
|
2113
|
-
app.get("*", serveStatic({ path:
|
|
2273
|
+
app.get("*", serveStatic({ path: path16.join(rel, "index.html") }));
|
|
2114
2274
|
} else app.get("/", (c) => c.text("ctxmedic UI is not built. Run `pnpm build` in the repository."));
|
|
2115
2275
|
return app;
|
|
2116
2276
|
}
|
|
@@ -2175,6 +2335,12 @@ function finopsSummary(f, lang) {
|
|
|
2175
2335
|
estimated ? pc.dim(` ${tx.estimatedPrice}`) : ""
|
|
2176
2336
|
].filter(Boolean).join("\n");
|
|
2177
2337
|
}
|
|
2338
|
+
function plugins(r) {
|
|
2339
|
+
const tx = t(r.lang);
|
|
2340
|
+
const loaded = r.plugins.filter((p3) => p3.loaded).map((p3) => `${p3.name}${p3.version ? `@${p3.version}` : ""}`);
|
|
2341
|
+
const skipped = r.plugins.filter((p3) => !p3.loaded).map((p3) => p3.name);
|
|
2342
|
+
return [loaded.length ? pc.dim(` ${tx.pluginsLoaded(loaded.join(", "))}`) : "", skipped.length ? pc.yellow(` ${tx.pluginsSkipped(skipped.join(", "))}`) : ""].filter(Boolean);
|
|
2343
|
+
}
|
|
2178
2344
|
function header(r) {
|
|
2179
2345
|
const tx = t(r.lang);
|
|
2180
2346
|
const delta = r.previous ? r.healthScore - r.previous.healthScore : null;
|
|
@@ -2186,6 +2352,7 @@ function header(r) {
|
|
|
2186
2352
|
"",
|
|
2187
2353
|
` ${tx.health}: ${bar(r.healthScore)} ${pc.bold(String(r.healthScore))}/100${trend}`,
|
|
2188
2354
|
` ${pc.italic(r.opinion)}`,
|
|
2355
|
+
...plugins(r),
|
|
2189
2356
|
` ${tx.triage.resuscitation} ${r.counts.resuscitation} ${tx.triage.therapy} ${r.counts.therapy} ${tx.triage.preventive} ${r.counts.preventive}` + (r.potentialMonthlySavingsUsd ? ` \xB7 ${tx.savings}: ${pc.green(pc.bold(usd2(r.potentialMonthlySavingsUsd) + tx.perMonth))}` : ""),
|
|
2190
2357
|
""
|
|
2191
2358
|
].join("\n");
|
|
@@ -2215,13 +2382,15 @@ function rules2(list, lang, configFile) {
|
|
|
2215
2382
|
}
|
|
2216
2383
|
|
|
2217
2384
|
// src/index.ts
|
|
2218
|
-
var common = (cmd) => cmd.option("--lang <lang>", "interface language (only en for now)").option("--days <n>", "how many days of session logs to analyze", "30").option("--no-finops", "skip session-log (cost) analysis").option("--no-global", "skip global configs in the home directory");
|
|
2385
|
+
var common = (cmd) => cmd.option("--lang <lang>", "interface language (only en for now)").option("--days <n>", "how many days of session logs to analyze", "30").option("--no-finops", "skip session-log (cost) analysis").option("--no-global", "skip global configs in the home directory").option("--plugins", "load the plugins listed in ctxmedic.config.json (runs their code; or CTXMEDIC_PLUGINS=1)");
|
|
2386
|
+
var pluginsAllowed = (o2) => Boolean(o2.plugins) || process.env.CTXMEDIC_PLUGINS === "1";
|
|
2219
2387
|
var ctx = (dir, o2) => ({
|
|
2220
|
-
root:
|
|
2388
|
+
root: path17.resolve(dir ?? "."),
|
|
2221
2389
|
lang: resolveLang(o2.lang),
|
|
2222
2390
|
days: Math.max(1, Number.parseInt(o2.days, 10) || 30),
|
|
2223
2391
|
finops: o2.finops,
|
|
2224
|
-
global: o2.global
|
|
2392
|
+
global: o2.global,
|
|
2393
|
+
plugins: pluginsAllowed(o2)
|
|
2225
2394
|
});
|
|
2226
2395
|
function fail(e) {
|
|
2227
2396
|
console.error(pc2.red(`\u2716 ${e instanceof FixRefusedError || e instanceof ConfigError ? e.message : e.stack ?? e}`));
|
|
@@ -2244,18 +2413,18 @@ common(program.command("treat [rx]").description("apply a prescription (e.g. RX-
|
|
|
2244
2413
|
const m = messages(c.lang).cli;
|
|
2245
2414
|
if (manual.length === picked.length) return console.log(pc2.yellow(m.noAutoFix));
|
|
2246
2415
|
const plans = picked.flatMap((d2) => d2.finding.fix ? [d2.finding.fix] : []);
|
|
2247
|
-
for (const plan of plans) for (const op of plan.ops) console.log(pc2.dim(` ${op.kind === "write" ? "write " : "symlink"} ${
|
|
2416
|
+
for (const plan of plans) for (const op of plan.ops) console.log(pc2.dim(` ${op.kind === "write" ? "write " : "symlink"} ${path17.relative(c.root, op.path)}${op.kind === "symlink" ? ` \u2192 ${op.target}` : ""}`));
|
|
2248
2417
|
if (!o2.dryRun && !o2.yes) {
|
|
2249
2418
|
const ok = await p2.confirm({ message: m.confirmApply });
|
|
2250
2419
|
if (p2.isCancel(ok) || !ok) return p2.cancel(m.cancelled);
|
|
2251
2420
|
}
|
|
2252
2421
|
for (const plan of plans) {
|
|
2253
2422
|
const res = await applyFix(plan, { root: c.root, dryRun: o2.dryRun, force: o2.force, global: false }).catch(fail);
|
|
2254
|
-
console.log(`${o2.dryRun ? pc2.yellow("dry-run") : pc2.green("\u2714")} ${plan.title}${res.dryRun ? "" : pc2.dim(` backup: ${
|
|
2423
|
+
console.log(`${o2.dryRun ? pc2.yellow("dry-run") : pc2.green("\u2714")} ${plan.title}${res.dryRun ? "" : pc2.dim(` backup: ${path17.relative(c.root, res.backupDir)}`)}`);
|
|
2255
2424
|
}
|
|
2256
2425
|
});
|
|
2257
2426
|
program.command("restore [backup]").description("undo a fix: list backups, or restore one by id (or latest)").option("--lang <lang>", "interface language (only en for now)").option("--dry-run", "show what would change without writing").option("--force", "restore even if files changed after the fix").action(async (id, o2) => {
|
|
2258
|
-
const root =
|
|
2427
|
+
const root = path17.resolve(".");
|
|
2259
2428
|
const m = messages(resolveLang(o2.lang)).cli;
|
|
2260
2429
|
if (!id) {
|
|
2261
2430
|
const all = await listBackups(root);
|
|
@@ -2268,10 +2437,12 @@ ${m.restoreHint}`));
|
|
|
2268
2437
|
for (const line of r.restored) console.log(pc2.dim(` ${line}`));
|
|
2269
2438
|
console.log(`${r.dryRun ? pc2.yellow("dry-run") : pc2.green("\u2714")} ${m.restored(r.id)}: ${r.title}`);
|
|
2270
2439
|
});
|
|
2271
|
-
program.command("rules [path]").description("list rules with their effective level and options from ctxmedic.config.json").option("--lang <lang>", "interface language (only en for now)").option("--json", "print the rules as JSON").action((dir, o2) => {
|
|
2440
|
+
program.command("rules [path]").description("list rules with their effective level and options from ctxmedic.config.json").option("--lang <lang>", "interface language (only en for now)").option("--json", "print the rules as JSON").option("--plugins", "also list rules from the plugins in ctxmedic.config.json (runs their code)").action(async (dir, o2) => {
|
|
2441
|
+
const root = path17.resolve(dir ?? ".");
|
|
2272
2442
|
let list;
|
|
2273
2443
|
try {
|
|
2274
|
-
|
|
2444
|
+
const extra = pluginsAllowed(o2) ? (await loadPlugins(root, loadConfig(root).plugins)).flatMap((p3) => p3.rules) : [];
|
|
2445
|
+
list = describeRules(loadConfig(root, extra), extra);
|
|
2275
2446
|
} catch (e) {
|
|
2276
2447
|
fail(e);
|
|
2277
2448
|
}
|
|
@@ -2345,11 +2516,11 @@ common(program.command("consult [path]").description("interactive appointment: a
|
|
|
2345
2516
|
}
|
|
2346
2517
|
p2.outro(m.goodbye);
|
|
2347
2518
|
});
|
|
2348
|
-
program.command("history [path]").description("Health Score history for a project (or all with --all)").option("--all", "show every project").action((dir, o2) => console.log(history(loadHistory(o2.all ? void 0 :
|
|
2519
|
+
program.command("history [path]").description("Health Score history for a project (or all with --all)").option("--all", "show every project").action((dir, o2) => console.log(history(loadHistory(o2.all ? void 0 : path17.resolve(dir ?? ".")))));
|
|
2349
2520
|
common(program.command("ui [path]").description("open the local Web UI (127.0.0.1 only)")).option("--port <n>", "port", "7337").option("--no-open", "do not open the browser").action(async (dir, o2) => {
|
|
2350
2521
|
const c = ctx(dir, o2);
|
|
2351
|
-
const publicDir =
|
|
2352
|
-
const { url } = await startServer({ root: c.root, lang: c.lang, days: c.days, port: Number(o2.port), publicDir }).catch(fail);
|
|
2522
|
+
const publicDir = path17.join(path17.dirname(fileURLToPath(import.meta.url)), "..", "public");
|
|
2523
|
+
const { url } = await startServer({ root: c.root, lang: c.lang, days: c.days, plugins: c.plugins, port: Number(o2.port), publicDir }).catch(fail);
|
|
2353
2524
|
console.log(`${pc2.bold("\u{1FA7A} ctxmedic UI")} ${pc2.cyan(url)}
|
|
2354
2525
|
${pc2.dim("Ctrl+C to stop. Listening on 127.0.0.1 only.")}`);
|
|
2355
2526
|
if (o2.open) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ctxmedic",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "The context medic for your AI coding setup: checkup, treat, savings for Claude Code, Cursor, Windsurf, Codex CLI, OpenCode, Cline and Copilot.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "FSL-1.1-MIT",
|
package/schema.json
CHANGED
|
@@ -5,6 +5,35 @@
|
|
|
5
5
|
"$schema": {
|
|
6
6
|
"type": "string"
|
|
7
7
|
},
|
|
8
|
+
"plugins": {
|
|
9
|
+
"type": "array",
|
|
10
|
+
"items": {
|
|
11
|
+
"type": "string"
|
|
12
|
+
},
|
|
13
|
+
"description": "npm packages in node_modules that add rules. They run only with --plugins (their code can do anything ctxmedic can)."
|
|
14
|
+
},
|
|
15
|
+
"extends": {
|
|
16
|
+
"anyOf": [
|
|
17
|
+
{
|
|
18
|
+
"type": "string",
|
|
19
|
+
"enum": [
|
|
20
|
+
"ctxmedic:recommended",
|
|
21
|
+
"ctxmedic:strict"
|
|
22
|
+
]
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
"type": "array",
|
|
26
|
+
"items": {
|
|
27
|
+
"type": "string",
|
|
28
|
+
"enum": [
|
|
29
|
+
"ctxmedic:recommended",
|
|
30
|
+
"ctxmedic:strict"
|
|
31
|
+
]
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
],
|
|
35
|
+
"description": "Built-in presets applied before this file's rules: ctxmedic:recommended, ctxmedic:strict."
|
|
36
|
+
},
|
|
8
37
|
"rules": {
|
|
9
38
|
"type": "object",
|
|
10
39
|
"properties": {
|
|
@@ -265,6 +294,41 @@
|
|
|
265
294
|
],
|
|
266
295
|
"description": "Keep build output and lockfiles out of the AI index with an ignore file. https://github.com/ponomarenko/ctxmedic/blob/main/docs/rules/FIN_BLOAT_IGNORE.md"
|
|
267
296
|
},
|
|
297
|
+
"INFO_UNUSED_DISABLE": {
|
|
298
|
+
"anyOf": [
|
|
299
|
+
{
|
|
300
|
+
"$ref": "#/definitions/RuleLevel"
|
|
301
|
+
},
|
|
302
|
+
{
|
|
303
|
+
"type": "array",
|
|
304
|
+
"items": [
|
|
305
|
+
{
|
|
306
|
+
"$ref": "#/definitions/RuleLevel"
|
|
307
|
+
}
|
|
308
|
+
],
|
|
309
|
+
"additionalItems": false,
|
|
310
|
+
"minItems": 1,
|
|
311
|
+
"maxItems": 1
|
|
312
|
+
},
|
|
313
|
+
{
|
|
314
|
+
"type": "array",
|
|
315
|
+
"items": [
|
|
316
|
+
{
|
|
317
|
+
"$ref": "#/definitions/RuleLevel"
|
|
318
|
+
},
|
|
319
|
+
{
|
|
320
|
+
"type": "object",
|
|
321
|
+
"properties": {},
|
|
322
|
+
"additionalProperties": false
|
|
323
|
+
}
|
|
324
|
+
],
|
|
325
|
+
"additionalItems": false,
|
|
326
|
+
"minItems": 2,
|
|
327
|
+
"maxItems": 2
|
|
328
|
+
}
|
|
329
|
+
],
|
|
330
|
+
"description": "Remove ctxmedic-disable comments that silence nothing. https://github.com/ponomarenko/ctxmedic/blob/main/docs/rules/INFO_UNUSED_DISABLE.md"
|
|
331
|
+
},
|
|
268
332
|
"FIN_UNUSED_MCP": {
|
|
269
333
|
"anyOf": [
|
|
270
334
|
{
|
|
@@ -455,7 +519,40 @@
|
|
|
455
519
|
}
|
|
456
520
|
},
|
|
457
521
|
"additionalProperties": false,
|
|
458
|
-
"description": "Rule levels and options: \"off\", \"on\", a severity, or [level, options]."
|
|
522
|
+
"description": "Rule levels and options: \"off\", \"on\", a severity, or [level, options].",
|
|
523
|
+
"patternProperties": {
|
|
524
|
+
"^[a-z][a-z0-9-]*\\/[A-Z][A-Z0-9_]*$": {
|
|
525
|
+
"description": "A rule from a plugin: plugin/RULE_NAME.",
|
|
526
|
+
"anyOf": [
|
|
527
|
+
{
|
|
528
|
+
"$ref": "#/definitions/RuleLevel"
|
|
529
|
+
},
|
|
530
|
+
{
|
|
531
|
+
"type": "array",
|
|
532
|
+
"items": [
|
|
533
|
+
{
|
|
534
|
+
"$ref": "#/definitions/RuleLevel"
|
|
535
|
+
}
|
|
536
|
+
],
|
|
537
|
+
"minItems": 1,
|
|
538
|
+
"maxItems": 1
|
|
539
|
+
},
|
|
540
|
+
{
|
|
541
|
+
"type": "array",
|
|
542
|
+
"items": [
|
|
543
|
+
{
|
|
544
|
+
"$ref": "#/definitions/RuleLevel"
|
|
545
|
+
},
|
|
546
|
+
{
|
|
547
|
+
"type": "object"
|
|
548
|
+
}
|
|
549
|
+
],
|
|
550
|
+
"minItems": 2,
|
|
551
|
+
"maxItems": 2
|
|
552
|
+
}
|
|
553
|
+
]
|
|
554
|
+
}
|
|
555
|
+
}
|
|
459
556
|
},
|
|
460
557
|
"ignores": {
|
|
461
558
|
"type": "array",
|