ctxmedic 0.7.0 → 0.8.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/dist/index.js +104 -79
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -9,7 +9,7 @@ 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 z6 } from "zod";
|
|
13
13
|
|
|
14
14
|
// ../core/src/schema.ts
|
|
15
15
|
import { z } from "zod";
|
|
@@ -753,6 +753,38 @@ var syntax = {
|
|
|
753
753
|
}
|
|
754
754
|
};
|
|
755
755
|
|
|
756
|
+
// ../core/src/rules/finopsMeta.ts
|
|
757
|
+
import { z as z4 } from "zod";
|
|
758
|
+
var MCP_SCHEMA_TOKENS = 1500;
|
|
759
|
+
var SNOWBALL_STEPS = 35;
|
|
760
|
+
var SNOWBALL_HEAVY_STEPS = 10;
|
|
761
|
+
var CACHE_HIT_MIN = 0.4;
|
|
762
|
+
var CACHE_HIT_TARGET = 0.7;
|
|
763
|
+
var CACHE_MIN_TOKENS = 1e6;
|
|
764
|
+
var OVERKILL_MAX_STEPS = 2;
|
|
765
|
+
var OVERKILL_MIN_SESSIONS = 3;
|
|
766
|
+
var posInt = (d2) => z4.number().int().positive().default(d2);
|
|
767
|
+
var ratio = (d2) => z4.number().min(0).max(1).default(d2);
|
|
768
|
+
var FinOptions = {
|
|
769
|
+
FIN_UNUSED_MCP: z4.object({ schemaTokens: posInt(MCP_SCHEMA_TOKENS) }),
|
|
770
|
+
FIN_MODEL_OVERKILL: z4.object({ maxSteps: posInt(OVERKILL_MAX_STEPS), minSessions: posInt(OVERKILL_MIN_SESSIONS) }),
|
|
771
|
+
FIN_CONTEXT_SNOWBALL: z4.object({ steps: posInt(SNOWBALL_STEPS), heavySteps: posInt(SNOWBALL_HEAVY_STEPS) }),
|
|
772
|
+
FIN_CACHE_MISS: z4.object({ minHitRatio: ratio(CACHE_HIT_MIN), targetHitRatio: ratio(CACHE_HIT_TARGET), minTokens: posInt(CACHE_MIN_TOKENS) }).refine((o2) => o2.targetHitRatio >= o2.minHitRatio, { message: "targetHitRatio must be at least minHitRatio" })
|
|
773
|
+
};
|
|
774
|
+
var meta = (id, description) => ({
|
|
775
|
+
description,
|
|
776
|
+
type: "suggestion",
|
|
777
|
+
docs: docsUrl(id),
|
|
778
|
+
fixable: false,
|
|
779
|
+
options: FinOptions[id]
|
|
780
|
+
});
|
|
781
|
+
var finopsMeta = {
|
|
782
|
+
FIN_UNUSED_MCP: meta("FIN_UNUSED_MCP", "Remove MCP servers that are never called"),
|
|
783
|
+
FIN_MODEL_OVERKILL: meta("FIN_MODEL_OVERKILL", "Route one-shot tasks to a cheaper model"),
|
|
784
|
+
FIN_CONTEXT_SNOWBALL: meta("FIN_CONTEXT_SNOWBALL", "Compact or clear long sessions"),
|
|
785
|
+
FIN_CACHE_MISS: meta("FIN_CACHE_MISS", "Keep the prompt cache warm")
|
|
786
|
+
};
|
|
787
|
+
|
|
756
788
|
// ../core/src/rules/index.ts
|
|
757
789
|
var rules = [brokenLink, contextBloat, duplicates, skills, secretLeak, syntax, bloatIgnore];
|
|
758
790
|
async function runRules(ctx2, list = rules, options = {}, off = /* @__PURE__ */ new Set()) {
|
|
@@ -873,15 +905,15 @@ import crypto2 from "crypto";
|
|
|
873
905
|
import fs6 from "fs";
|
|
874
906
|
import path9 from "path";
|
|
875
907
|
import picomatch2 from "picomatch";
|
|
876
|
-
import { z as
|
|
908
|
+
import { z as z5 } from "zod";
|
|
877
909
|
var CONFIG_FILE = "ctxmedic.config.json";
|
|
878
|
-
var RuleLevel =
|
|
879
|
-
var RuleEntry =
|
|
880
|
-
var CtxmedicConfig =
|
|
881
|
-
$schema:
|
|
882
|
-
rules:
|
|
910
|
+
var RuleLevel = z5.union([z5.literal("off"), z5.literal("on"), Severity]);
|
|
911
|
+
var RuleEntry = z5.union([RuleLevel, z5.tuple([RuleLevel]), z5.tuple([RuleLevel, z5.record(z5.string(), z5.unknown())])]);
|
|
912
|
+
var CtxmedicConfig = z5.object({
|
|
913
|
+
$schema: z5.string().optional(),
|
|
914
|
+
rules: z5.partialRecord(RuleId, RuleEntry).default({}),
|
|
883
915
|
/** Globs over finding paths (project-relative, or `~/` for global files). */
|
|
884
|
-
ignores:
|
|
916
|
+
ignores: z5.array(z5.string()).default([])
|
|
885
917
|
});
|
|
886
918
|
var ConfigError = class extends Error {
|
|
887
919
|
};
|
|
@@ -897,14 +929,14 @@ function loadConfig(root) {
|
|
|
897
929
|
throw new ConfigError(`${CONFIG_FILE}: ${e.message}`);
|
|
898
930
|
}
|
|
899
931
|
const r = CtxmedicConfig.safeParse(raw);
|
|
900
|
-
if (!r.success) throw new ConfigError(`${CONFIG_FILE}: ${
|
|
932
|
+
if (!r.success) throw new ConfigError(`${CONFIG_FILE}: ${z5.prettifyError(r.error)}`);
|
|
901
933
|
for (const [id, entry] of Object.entries(r.data.rules)) {
|
|
902
934
|
const opts = optionsOf(entry);
|
|
903
935
|
if (!Object.keys(opts).length) continue;
|
|
904
|
-
const schema = rules.find((x) => x.id === id)?.meta
|
|
936
|
+
const schema = (rules.find((x) => x.id === id)?.meta ?? finopsMeta[id])?.options;
|
|
905
937
|
if (!schema) throw new ConfigError(`${CONFIG_FILE}: rule ${id} takes no options`);
|
|
906
938
|
const o2 = schema.safeParse(opts);
|
|
907
|
-
if (!o2.success) throw new ConfigError(`${CONFIG_FILE}: rule ${id}: ${
|
|
939
|
+
if (!o2.success) throw new ConfigError(`${CONFIG_FILE}: rule ${id}: ${z5.prettifyError(o2.error)}`);
|
|
908
940
|
}
|
|
909
941
|
return r.data;
|
|
910
942
|
}
|
|
@@ -956,64 +988,64 @@ async function examine(root, profiles, opts = {}) {
|
|
|
956
988
|
}
|
|
957
989
|
|
|
958
990
|
// ../clinical/src/schema.ts
|
|
959
|
-
var Lang =
|
|
960
|
-
var Triage =
|
|
961
|
-
var PrescriptionRx =
|
|
962
|
-
id:
|
|
963
|
-
action:
|
|
964
|
-
command:
|
|
965
|
-
autoFix:
|
|
966
|
-
healthGain:
|
|
967
|
-
monthlySavingsUsd:
|
|
991
|
+
var Lang = z6.enum(["en"]);
|
|
992
|
+
var Triage = z6.enum(["resuscitation", "therapy", "preventive"]);
|
|
993
|
+
var PrescriptionRx = z6.object({
|
|
994
|
+
id: z6.string().regex(/^RX-\d{2,}$/),
|
|
995
|
+
action: z6.string(),
|
|
996
|
+
command: z6.string().optional(),
|
|
997
|
+
autoFix: z6.boolean(),
|
|
998
|
+
healthGain: z6.number().nonnegative(),
|
|
999
|
+
monthlySavingsUsd: z6.number().nonnegative().optional()
|
|
968
1000
|
});
|
|
969
|
-
var ClinicalDiagnosis =
|
|
1001
|
+
var ClinicalDiagnosis = z6.object({
|
|
970
1002
|
code: RuleId,
|
|
971
1003
|
triage: Triage,
|
|
972
|
-
diagnosis:
|
|
973
|
-
summary:
|
|
974
|
-
vitals:
|
|
975
|
-
prognosis:
|
|
1004
|
+
diagnosis: z6.string(),
|
|
1005
|
+
summary: z6.string(),
|
|
1006
|
+
vitals: z6.array(z6.object({ label: z6.string(), value: z6.string() })),
|
|
1007
|
+
prognosis: z6.string(),
|
|
976
1008
|
rx: PrescriptionRx,
|
|
977
|
-
files:
|
|
1009
|
+
files: z6.array(z6.string()),
|
|
978
1010
|
finding: Finding
|
|
979
1011
|
});
|
|
980
|
-
var Counts =
|
|
981
|
-
var Anamnesis =
|
|
982
|
-
priority:
|
|
983
|
-
primaryHarness:
|
|
984
|
-
monthlyBudgetUsd:
|
|
1012
|
+
var Counts = z6.object({ resuscitation: z6.number(), therapy: z6.number(), preventive: z6.number() });
|
|
1013
|
+
var Anamnesis = z6.object({
|
|
1014
|
+
priority: z6.enum(["economy", "balanced", "quality"]).default("balanced"),
|
|
1015
|
+
primaryHarness: z6.string().optional(),
|
|
1016
|
+
monthlyBudgetUsd: z6.number().nonnegative().optional()
|
|
985
1017
|
});
|
|
986
|
-
var ScanSettings =
|
|
987
|
-
global:
|
|
988
|
-
finops:
|
|
989
|
-
days:
|
|
1018
|
+
var ScanSettings = z6.object({
|
|
1019
|
+
global: z6.boolean(),
|
|
1020
|
+
finops: z6.boolean(),
|
|
1021
|
+
days: z6.number(),
|
|
990
1022
|
/** `configHash` of ctxmedic.config.json; "" without one, and in history written before v0.3. */
|
|
991
|
-
config:
|
|
1023
|
+
config: z6.string().default("")
|
|
992
1024
|
});
|
|
993
1025
|
var DEFAULT_SCAN = { global: true, finops: true, days: 30, config: "" };
|
|
994
|
-
var Visit =
|
|
995
|
-
at:
|
|
996
|
-
root:
|
|
1026
|
+
var Visit = z6.object({
|
|
1027
|
+
at: z6.string(),
|
|
1028
|
+
root: z6.string(),
|
|
997
1029
|
/** Missing in history written by v0.1.0: those runs are assumed to use the defaults. */
|
|
998
1030
|
scan: ScanSettings.default(DEFAULT_SCAN),
|
|
999
|
-
healthScore:
|
|
1031
|
+
healthScore: z6.number(),
|
|
1000
1032
|
counts: Counts,
|
|
1001
|
-
monthlySpendUsd:
|
|
1002
|
-
potentialMonthlySavingsUsd:
|
|
1033
|
+
monthlySpendUsd: z6.number().optional(),
|
|
1034
|
+
potentialMonthlySavingsUsd: z6.number()
|
|
1003
1035
|
});
|
|
1004
|
-
var ClinicalReport =
|
|
1005
|
-
tool:
|
|
1006
|
-
version:
|
|
1036
|
+
var ClinicalReport = z6.object({
|
|
1037
|
+
tool: z6.literal("ctxmedic"),
|
|
1038
|
+
version: z6.string(),
|
|
1007
1039
|
lang: Lang,
|
|
1008
|
-
generatedAt:
|
|
1040
|
+
generatedAt: z6.string(),
|
|
1009
1041
|
patient: PatientVitals,
|
|
1010
|
-
healthScore:
|
|
1042
|
+
healthScore: z6.number().min(0).max(100),
|
|
1011
1043
|
previous: Visit.nullable(),
|
|
1012
|
-
opinion:
|
|
1044
|
+
opinion: z6.string(),
|
|
1013
1045
|
counts: Counts,
|
|
1014
|
-
diagnoses:
|
|
1046
|
+
diagnoses: z6.array(ClinicalDiagnosis),
|
|
1015
1047
|
finops: FinOpsReport.nullable(),
|
|
1016
|
-
potentialMonthlySavingsUsd:
|
|
1048
|
+
potentialMonthlySavingsUsd: z6.number()
|
|
1017
1049
|
});
|
|
1018
1050
|
|
|
1019
1051
|
// ../finops/src/cache.ts
|
|
@@ -1109,14 +1141,6 @@ function costOf(model, u) {
|
|
|
1109
1141
|
}
|
|
1110
1142
|
|
|
1111
1143
|
// ../finops/src/detectors.ts
|
|
1112
|
-
var MCP_SCHEMA_TOKENS = 1500;
|
|
1113
|
-
var SNOWBALL_STEPS = 35;
|
|
1114
|
-
var SNOWBALL_HEAVY_STEPS = 10;
|
|
1115
|
-
var CACHE_HIT_MIN = 0.4;
|
|
1116
|
-
var CACHE_HIT_TARGET = 0.7;
|
|
1117
|
-
var CACHE_MIN_TOKENS = 1e6;
|
|
1118
|
-
var OVERKILL_MAX_STEPS = 2;
|
|
1119
|
-
var OVERKILL_MIN_SESSIONS = 3;
|
|
1120
1144
|
var monthly = (usd3, days) => usd3 * 30 / days;
|
|
1121
1145
|
var round = (n2) => Math.round(n2 * 100) / 100;
|
|
1122
1146
|
var dominant = (sessions) => {
|
|
@@ -1125,7 +1149,8 @@ var dominant = (sessions) => {
|
|
|
1125
1149
|
return Object.entries(m).sort((a2, b) => b[1] - a2[1])[0]?.[0];
|
|
1126
1150
|
};
|
|
1127
1151
|
var sev = (usd3) => usd3 >= 1 ? "warning" : "info";
|
|
1128
|
-
|
|
1152
|
+
var detector = (id, check) => ({ id, meta: finopsMeta[id], check });
|
|
1153
|
+
var unusedMcp = detector("FIN_UNUSED_MCP", ({ sessions, days, files, root }, { schemaTokens: fallback }) => {
|
|
1129
1154
|
const out = [];
|
|
1130
1155
|
const calls = {};
|
|
1131
1156
|
for (const s of sessions) for (const [k, n2] of Object.entries(s.mcpCalls)) calls[k] = (calls[k] ?? 0) + n2;
|
|
@@ -1139,7 +1164,7 @@ function unusedMcp({ sessions, days, files, root }) {
|
|
|
1139
1164
|
const idle = Object.keys(mcpServers(f.path, f.text, root)).filter((name) => !calls[name] && !calls[name.replace(/[^\w]/g, "_")]);
|
|
1140
1165
|
if (!idle.length) continue;
|
|
1141
1166
|
const measured = idle.map((name) => Math.max(0, ...hs.map((s) => s.mcpSchemaTokens?.[name] ?? s.mcpSchemaTokens?.[name.replace(/[^\w]/g, "_")] ?? 0)) || null);
|
|
1142
|
-
const schemaTokens = measured.reduce((n2, t2) => n2 + (t2 ??
|
|
1167
|
+
const schemaTokens = measured.reduce((n2, t2) => n2 + (t2 ?? fallback), 0);
|
|
1143
1168
|
const estimated = measured.some((t2) => t2 === null);
|
|
1144
1169
|
const usd3 = monthly(schemaTokens * steps * priceOf(model).price.cacheRead / 1e6, days);
|
|
1145
1170
|
out.push({
|
|
@@ -1153,11 +1178,11 @@ function unusedMcp({ sessions, days, files, root }) {
|
|
|
1153
1178
|
}
|
|
1154
1179
|
}
|
|
1155
1180
|
return out;
|
|
1156
|
-
}
|
|
1157
|
-
|
|
1181
|
+
});
|
|
1182
|
+
var modelOverkill = detector("FIN_MODEL_OVERKILL", ({ sessions, days }, { maxSteps, minSessions }) => {
|
|
1158
1183
|
const byModel = /* @__PURE__ */ new Map();
|
|
1159
1184
|
for (const s of sessions) {
|
|
1160
|
-
if (s.steps === 0 || s.steps >
|
|
1185
|
+
if (s.steps === 0 || s.steps > maxSteps) continue;
|
|
1161
1186
|
for (const [model, u] of Object.entries(s.models)) {
|
|
1162
1187
|
const to = lighterModel(model);
|
|
1163
1188
|
if (!to) continue;
|
|
@@ -1168,7 +1193,7 @@ function modelOverkill({ sessions, days }) {
|
|
|
1168
1193
|
byModel.set(model, e);
|
|
1169
1194
|
}
|
|
1170
1195
|
}
|
|
1171
|
-
return [...byModel].filter(([, e]) => e.n >=
|
|
1196
|
+
return [...byModel].filter(([, e]) => e.n >= minSessions).map(([model, e]) => {
|
|
1172
1197
|
const usd3 = monthly(e.cost - e.cheaper, days);
|
|
1173
1198
|
return {
|
|
1174
1199
|
ruleId: "FIN_MODEL_OVERKILL",
|
|
@@ -1179,9 +1204,9 @@ function modelOverkill({ sessions, days }) {
|
|
|
1179
1204
|
monthlySavingsUsd: round(usd3)
|
|
1180
1205
|
};
|
|
1181
1206
|
});
|
|
1182
|
-
}
|
|
1183
|
-
|
|
1184
|
-
const bad = sessions.filter((s) => s.steps >
|
|
1207
|
+
});
|
|
1208
|
+
var contextSnowball = detector("FIN_CONTEXT_SNOWBALL", ({ sessions, days }, { steps, heavySteps }) => {
|
|
1209
|
+
const bad = sessions.filter((s) => s.steps > steps && s.heavySteps >= heavySteps && s.compactions === 0);
|
|
1185
1210
|
if (!bad.length) return [];
|
|
1186
1211
|
let usd3 = 0;
|
|
1187
1212
|
for (const s of bad) {
|
|
@@ -1194,14 +1219,14 @@ function contextSnowball({ sessions, days }) {
|
|
|
1194
1219
|
{
|
|
1195
1220
|
ruleId: "FIN_CONTEXT_SNOWBALL",
|
|
1196
1221
|
severity: sev(usd3),
|
|
1197
|
-
message: `${bad.length} session(s) ran >${
|
|
1222
|
+
message: `${bad.length} session(s) ran >${steps} steps with 100k+ context and no /clear or /compact`,
|
|
1198
1223
|
files: bad.slice(0, 5).map((s) => `session ${path12.basename(s.file, ".jsonl")}`),
|
|
1199
1224
|
data: { sessions: bad.length, worstSteps: worst.steps, worstMaxContext: worst.maxContext, days },
|
|
1200
1225
|
monthlySavingsUsd: round(usd3)
|
|
1201
1226
|
}
|
|
1202
1227
|
];
|
|
1203
|
-
}
|
|
1204
|
-
|
|
1228
|
+
});
|
|
1229
|
+
var cacheMiss = detector("FIN_CACHE_MISS", ({ sessions, days }, { minHitRatio, targetHitRatio, minTokens }) => {
|
|
1205
1230
|
const out = [];
|
|
1206
1231
|
for (const h of ["claude-code", "codex"]) {
|
|
1207
1232
|
const hs = sessions.filter((s) => s.harness === h);
|
|
@@ -1210,22 +1235,22 @@ function cacheMiss({ sessions, days }) {
|
|
|
1210
1235
|
let write = 0;
|
|
1211
1236
|
for (const s of hs) for (const u of Object.values(s.models)) input += u.input, read += u.cacheRead, write += u.cacheWrite;
|
|
1212
1237
|
const total = input + read + write;
|
|
1213
|
-
if (total <
|
|
1214
|
-
const
|
|
1215
|
-
if (
|
|
1238
|
+
if (total < minTokens) continue;
|
|
1239
|
+
const ratio2 = read / total;
|
|
1240
|
+
if (ratio2 >= minHitRatio) continue;
|
|
1216
1241
|
const p3 = priceOf(dominant(hs) ?? "claude-sonnet-5-5").price;
|
|
1217
|
-
const usd3 = monthly((
|
|
1242
|
+
const usd3 = monthly((targetHitRatio - ratio2) * total * (p3.input - p3.cacheRead) / 1e6, days);
|
|
1218
1243
|
out.push({
|
|
1219
1244
|
ruleId: "FIN_CACHE_MISS",
|
|
1220
1245
|
severity: sev(usd3),
|
|
1221
|
-
message: `${h} prompt-cache hit ratio is ${Math.round(
|
|
1246
|
+
message: `${h} prompt-cache hit ratio is ${Math.round(ratio2 * 100)}% (healthy: \u2265${Math.round(minHitRatio * 100)}%)`,
|
|
1222
1247
|
files: [],
|
|
1223
|
-
data: { harness: h, cacheHitRatio:
|
|
1248
|
+
data: { harness: h, cacheHitRatio: ratio2, totalInputTokens: total, days },
|
|
1224
1249
|
monthlySavingsUsd: round(Math.max(0, usd3))
|
|
1225
1250
|
});
|
|
1226
1251
|
}
|
|
1227
1252
|
return out;
|
|
1228
|
-
}
|
|
1253
|
+
});
|
|
1229
1254
|
var detectors = [unusedMcp, modelOverkill, contextSnowball, cacheMiss];
|
|
1230
1255
|
|
|
1231
1256
|
// ../finops/src/parsers.ts
|
|
@@ -1394,7 +1419,7 @@ function buildReport(sessions, { days = 30, root, files, config }) {
|
|
|
1394
1419
|
read += u.cacheRead;
|
|
1395
1420
|
}
|
|
1396
1421
|
}
|
|
1397
|
-
const raw = detectors.flatMap((d2) => d2({ sessions, days, files, root }));
|
|
1422
|
+
const raw = detectors.filter((d2) => levelOf(config?.rules[d2.id]) !== "off").flatMap((d2) => d2.check({ sessions, days, files, root }, d2.meta.options.parse(optionsOf(config?.rules[d2.id]))));
|
|
1398
1423
|
const findings = config ? applyConfig(raw, files, config) : raw;
|
|
1399
1424
|
return FinOpsReport.parse({
|
|
1400
1425
|
periodDays: days,
|
|
@@ -1672,7 +1697,7 @@ var harnesses = [
|
|
|
1672
1697
|
];
|
|
1673
1698
|
|
|
1674
1699
|
// ../clinical/src/engine.ts
|
|
1675
|
-
var VERSION = true ? "0.
|
|
1700
|
+
var VERSION = true ? "0.8.0" : "0.0.0-dev";
|
|
1676
1701
|
var TRIAGE = { critical: "resuscitation", warning: "therapy", info: "preventive" };
|
|
1677
1702
|
var ORDER = ["resuscitation", "therapy", "preventive"];
|
|
1678
1703
|
var human = (k) => k.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ctxmedic",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.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",
|