ctxmedic 0.0.0 → 0.1.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/LICENSE +110 -0
- package/NOTICE +19 -0
- package/README.md +80 -5
- package/dist/index.js +1850 -0
- package/package.json +61 -7
- package/public/assets/index-Bqo1oFYC.css +1 -0
- package/public/assets/index-CuWHlsFL.js +130 -0
- package/public/index.html +14 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1850 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { spawn } from "child_process";
|
|
5
|
+
import path15 from "path";
|
|
6
|
+
import { fileURLToPath } from "url";
|
|
7
|
+
import * as p2 from "@clack/prompts";
|
|
8
|
+
import { Command } from "commander";
|
|
9
|
+
import pc2 from "picocolors";
|
|
10
|
+
|
|
11
|
+
// ../clinical/src/schema.ts
|
|
12
|
+
import { z as z2 } from "zod";
|
|
13
|
+
|
|
14
|
+
// ../core/src/schema.ts
|
|
15
|
+
import { z } from "zod";
|
|
16
|
+
var Severity = z.enum(["critical", "warning", "info"]);
|
|
17
|
+
var RuleId = z.enum([
|
|
18
|
+
"ERR_BROKEN_LINK",
|
|
19
|
+
"WARN_CONTEXT_BLOAT",
|
|
20
|
+
"WARN_DUPLICATE_RULES",
|
|
21
|
+
"ERR_INVALID_SKILL",
|
|
22
|
+
"CRIT_SECRET_LEAK",
|
|
23
|
+
"INFO_UNSUPPORTED_SYNTAX",
|
|
24
|
+
"FIN_BLOAT_IGNORE",
|
|
25
|
+
"FIN_UNUSED_MCP",
|
|
26
|
+
"FIN_MODEL_OVERKILL",
|
|
27
|
+
"FIN_CONTEXT_SNOWBALL",
|
|
28
|
+
"FIN_CACHE_MISS"
|
|
29
|
+
]);
|
|
30
|
+
var FixOp = z.discriminatedUnion("kind", [
|
|
31
|
+
z.object({ kind: z.literal("write"), path: z.string(), content: z.string() }),
|
|
32
|
+
z.object({ kind: z.literal("symlink"), path: z.string(), target: z.string() })
|
|
33
|
+
]);
|
|
34
|
+
var FixPlan = z.object({ title: z.string(), ops: z.array(FixOp).min(1) });
|
|
35
|
+
var Finding = z.object({
|
|
36
|
+
ruleId: RuleId,
|
|
37
|
+
severity: Severity,
|
|
38
|
+
message: z.string(),
|
|
39
|
+
files: z.array(z.string()).default([]),
|
|
40
|
+
/** Raw lab values used by the clinical layer (token counts, ratios, $). */
|
|
41
|
+
data: z.record(z.unknown()).default({}),
|
|
42
|
+
monthlySavingsUsd: z.number().nonnegative().optional(),
|
|
43
|
+
fix: FixPlan.optional()
|
|
44
|
+
});
|
|
45
|
+
var FileRole = z.enum(["instructions", "rules", "skill", "mcp", "ignore"]);
|
|
46
|
+
var PathSet = z.object({
|
|
47
|
+
project: z.array(z.string()).default([]),
|
|
48
|
+
/** Paths starting with `~/` resolve from CTXMEDIC_HOME or the home dir. */
|
|
49
|
+
global: z.array(z.string()).default([])
|
|
50
|
+
});
|
|
51
|
+
var HarnessProfile = z.object({
|
|
52
|
+
id: z.string(),
|
|
53
|
+
name: z.string(),
|
|
54
|
+
contextLimit: z.number().int().positive(),
|
|
55
|
+
files: z.object({
|
|
56
|
+
instructions: PathSet,
|
|
57
|
+
rules: PathSet.default({}),
|
|
58
|
+
skill: PathSet.default({}),
|
|
59
|
+
mcp: PathSet.default({})
|
|
60
|
+
}),
|
|
61
|
+
/** Directives this harness understands: "@import", "alwaysApply", "globs", "applyTo", "trigger". */
|
|
62
|
+
syntax: z.array(z.string()).default([]),
|
|
63
|
+
ignoreFile: z.string().optional(),
|
|
64
|
+
logs: z.array(z.string()).default([])
|
|
65
|
+
});
|
|
66
|
+
var ScannedFile = z.object({
|
|
67
|
+
path: z.string(),
|
|
68
|
+
rel: z.string(),
|
|
69
|
+
scope: z.enum(["project", "global"]),
|
|
70
|
+
role: FileRole,
|
|
71
|
+
harnesses: z.array(z.string()),
|
|
72
|
+
isSymlink: z.boolean(),
|
|
73
|
+
linkTarget: z.string().optional(),
|
|
74
|
+
broken: z.boolean(),
|
|
75
|
+
loop: z.boolean().default(false),
|
|
76
|
+
realpath: z.string().optional(),
|
|
77
|
+
text: z.string().optional(),
|
|
78
|
+
tokens: z.number().int().nonnegative()
|
|
79
|
+
});
|
|
80
|
+
var PatientVitals = z.object({
|
|
81
|
+
root: z.string(),
|
|
82
|
+
scannedAt: z.string(),
|
|
83
|
+
filesScanned: z.number().int(),
|
|
84
|
+
harnesses: z.array(z.string()),
|
|
85
|
+
startupTokens: z.record(z.number())
|
|
86
|
+
});
|
|
87
|
+
var ModelUsage = z.object({
|
|
88
|
+
model: z.string(),
|
|
89
|
+
steps: z.number().int(),
|
|
90
|
+
inputTokens: z.number(),
|
|
91
|
+
outputTokens: z.number(),
|
|
92
|
+
cacheReadTokens: z.number(),
|
|
93
|
+
cacheWriteTokens: z.number(),
|
|
94
|
+
costUsd: z.number()
|
|
95
|
+
});
|
|
96
|
+
var FinOpsReport = z.object({
|
|
97
|
+
periodDays: z.number().int().positive(),
|
|
98
|
+
sessions: z.number().int(),
|
|
99
|
+
steps: z.number().int(),
|
|
100
|
+
costUsd: z.number(),
|
|
101
|
+
monthlyRunRateUsd: z.number(),
|
|
102
|
+
cacheHitRatio: z.number().min(0).max(1).nullable(),
|
|
103
|
+
byHarness: z.record(z.object({ sessions: z.number(), costUsd: z.number() })),
|
|
104
|
+
byModel: z.array(ModelUsage),
|
|
105
|
+
mcpCalls: z.record(z.number()),
|
|
106
|
+
findings: z.array(Finding),
|
|
107
|
+
potentialMonthlySavingsUsd: z.number(),
|
|
108
|
+
pricingAsOf: z.string()
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
// ../core/src/paths.ts
|
|
112
|
+
import os from "os";
|
|
113
|
+
import path from "path";
|
|
114
|
+
var homeDir = () => process.env.CTXMEDIC_HOME || os.homedir();
|
|
115
|
+
var stateDir = () => path.join(homeDir(), ".ctxmedic");
|
|
116
|
+
|
|
117
|
+
// ../core/src/tokens.ts
|
|
118
|
+
import { getEncoding } from "js-tiktoken";
|
|
119
|
+
var enc;
|
|
120
|
+
function countTokens(text2) {
|
|
121
|
+
if (!text2) return 0;
|
|
122
|
+
enc ??= getEncoding("cl100k_base");
|
|
123
|
+
return enc.encode(text2, [], []).length;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ../core/src/parse.ts
|
|
127
|
+
import { parse as parseYaml } from "yaml";
|
|
128
|
+
import { parse as parseJsonc } from "jsonc-parser";
|
|
129
|
+
import { parse as parseToml } from "smol-toml";
|
|
130
|
+
function parseFrontmatter(text2) {
|
|
131
|
+
const m = /^?---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text2);
|
|
132
|
+
if (!m) return { data: null, body: text2 };
|
|
133
|
+
const body = text2.slice(m[0].length);
|
|
134
|
+
try {
|
|
135
|
+
const data = parseYaml(m[1]);
|
|
136
|
+
if (data && typeof data === "object" && !Array.isArray(data)) return { data, body };
|
|
137
|
+
return { data: {}, body, error: "frontmatter is not a mapping" };
|
|
138
|
+
} catch (e) {
|
|
139
|
+
return { data: {}, body, error: e.message.split("\n")[0] };
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
function parseJsonLoose(text2) {
|
|
143
|
+
const errors = [];
|
|
144
|
+
const v = parseJsonc(text2, errors, { allowTrailingComma: true });
|
|
145
|
+
return errors.length && v === void 0 ? void 0 : v;
|
|
146
|
+
}
|
|
147
|
+
function parseConfig(file2, text2) {
|
|
148
|
+
try {
|
|
149
|
+
return file2.endsWith(".toml") ? parseToml(text2) : parseJsonLoose(text2);
|
|
150
|
+
} catch {
|
|
151
|
+
return void 0;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
function mcpServers(file2, text2, projectRoot) {
|
|
155
|
+
const cfg = parseConfig(file2, text2);
|
|
156
|
+
if (!cfg || typeof cfg !== "object") return {};
|
|
157
|
+
const out = {};
|
|
158
|
+
const add = (o2) => {
|
|
159
|
+
if (o2 && typeof o2 === "object") for (const [k, v] of Object.entries(o2)) out[k] = v ?? {};
|
|
160
|
+
};
|
|
161
|
+
add(cfg.mcpServers);
|
|
162
|
+
add(cfg.mcp_servers);
|
|
163
|
+
add(cfg.mcp);
|
|
164
|
+
if (projectRoot && cfg.projects?.[projectRoot]) add(cfg.projects[projectRoot].mcpServers);
|
|
165
|
+
return out;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ../core/src/scan.ts
|
|
169
|
+
import fs from "fs/promises";
|
|
170
|
+
import path2 from "path";
|
|
171
|
+
import picomatch from "picomatch";
|
|
172
|
+
var MAX_DEPTH = 6;
|
|
173
|
+
var MAX_BYTES = 2 * 1024 * 1024;
|
|
174
|
+
var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
|
|
175
|
+
var isGlob = (s) => /[*?[\]{}]/.test(s);
|
|
176
|
+
async function inspect(abs) {
|
|
177
|
+
let l;
|
|
178
|
+
try {
|
|
179
|
+
l = await fs.lstat(abs);
|
|
180
|
+
} catch {
|
|
181
|
+
return void 0;
|
|
182
|
+
}
|
|
183
|
+
const e = { abs, isSymlink: l.isSymbolicLink(), broken: false, loop: false, isFile: l.isFile() };
|
|
184
|
+
if (e.isSymlink) {
|
|
185
|
+
e.linkTarget = await fs.readlink(abs);
|
|
186
|
+
try {
|
|
187
|
+
const s = await fs.stat(abs);
|
|
188
|
+
e.isFile = s.isFile();
|
|
189
|
+
e.realpath = await fs.realpath(abs);
|
|
190
|
+
} catch (err) {
|
|
191
|
+
if (err.code === "ELOOP") e.loop = true;
|
|
192
|
+
else e.broken = true;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return e;
|
|
196
|
+
}
|
|
197
|
+
async function walk(dir, depth, seen, out) {
|
|
198
|
+
if (depth > MAX_DEPTH) return;
|
|
199
|
+
let real;
|
|
200
|
+
try {
|
|
201
|
+
real = await fs.realpath(dir);
|
|
202
|
+
} catch {
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (seen.has(real)) return;
|
|
206
|
+
seen.add(real);
|
|
207
|
+
let names;
|
|
208
|
+
try {
|
|
209
|
+
names = await fs.readdir(dir);
|
|
210
|
+
} catch {
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
for (const name of names) {
|
|
214
|
+
if (SKIP_DIRS.has(name)) continue;
|
|
215
|
+
const e = await inspect(path2.join(dir, name));
|
|
216
|
+
if (!e) continue;
|
|
217
|
+
if (e.broken || e.loop || e.isFile) out.push(e);
|
|
218
|
+
else await walk(e.abs, depth + 1, seen, out);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
async function expand(base, pattern) {
|
|
222
|
+
if (!isGlob(pattern)) {
|
|
223
|
+
const e = await inspect(path2.join(base, pattern));
|
|
224
|
+
return e && (e.isFile || e.broken || e.loop) ? [e] : [];
|
|
225
|
+
}
|
|
226
|
+
const segs = pattern.split("/");
|
|
227
|
+
const i = segs.findIndex(isGlob);
|
|
228
|
+
const prefix = segs.slice(0, i).join("/");
|
|
229
|
+
const found = [];
|
|
230
|
+
await walk(path2.join(base, prefix), 0, /* @__PURE__ */ new Set(), found);
|
|
231
|
+
const match = picomatch(pattern, { dot: true });
|
|
232
|
+
return found.filter((e) => e.broken || e.loop || match(path2.relative(base, e.abs).split(path2.sep).join("/")));
|
|
233
|
+
}
|
|
234
|
+
async function scan(root, profiles, opts = {}) {
|
|
235
|
+
root = path2.resolve(root);
|
|
236
|
+
const home = homeDir();
|
|
237
|
+
const byPath = /* @__PURE__ */ new Map();
|
|
238
|
+
for (const h of profiles) {
|
|
239
|
+
for (const [role, set] of Object.entries(h.files)) {
|
|
240
|
+
const scopes = [["project", set.project, root]];
|
|
241
|
+
if (opts.global !== false) scopes.push(["global", set.global.map((g) => g.replace(/^~\//, "")), home]);
|
|
242
|
+
for (const [scope, patterns, base] of scopes) {
|
|
243
|
+
for (const pattern of patterns) {
|
|
244
|
+
for (const e of await expand(base, pattern)) {
|
|
245
|
+
const prev = byPath.get(e.abs);
|
|
246
|
+
if (prev) {
|
|
247
|
+
if (!prev.harnesses.includes(h.id)) prev.harnesses.push(h.id);
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
let text2;
|
|
251
|
+
if (e.isFile && !e.broken) {
|
|
252
|
+
try {
|
|
253
|
+
const st = await fs.stat(e.abs);
|
|
254
|
+
if (st.size <= MAX_BYTES) text2 = await fs.readFile(e.abs, "utf8");
|
|
255
|
+
} catch {
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
const inRoot = !path2.relative(root, e.abs).startsWith("..");
|
|
259
|
+
byPath.set(e.abs, {
|
|
260
|
+
path: e.abs,
|
|
261
|
+
rel: inRoot ? path2.relative(root, e.abs) : "~/" + path2.relative(home, e.abs),
|
|
262
|
+
scope,
|
|
263
|
+
role,
|
|
264
|
+
harnesses: [h.id],
|
|
265
|
+
isSymlink: e.isSymlink,
|
|
266
|
+
linkTarget: e.linkTarget,
|
|
267
|
+
broken: e.broken,
|
|
268
|
+
loop: e.loop,
|
|
269
|
+
realpath: e.realpath,
|
|
270
|
+
text: text2,
|
|
271
|
+
tokens: role === "mcp" ? 0 : countTokens(text2 ?? "")
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return [...byPath.values()].sort((a2, b) => a2.rel.localeCompare(b.rel));
|
|
279
|
+
}
|
|
280
|
+
async function findFiles(pattern) {
|
|
281
|
+
const base = pattern.startsWith("~/") ? homeDir() : "/";
|
|
282
|
+
const rel = pattern.replace(/^~\//, "").replace(/^\//, "");
|
|
283
|
+
return (await expand(base, rel)).filter((e) => e.isFile && !e.broken).map((e) => e.abs);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// ../core/src/git.ts
|
|
287
|
+
import { execFileSync } from "child_process";
|
|
288
|
+
import path3 from "path";
|
|
289
|
+
function git(cwd, args) {
|
|
290
|
+
try {
|
|
291
|
+
return { code: 0, out: execFileSync("git", args, { cwd, stdio: ["ignore", "pipe", "ignore"], encoding: "utf8" }) };
|
|
292
|
+
} catch (e) {
|
|
293
|
+
const err = e;
|
|
294
|
+
return { code: err.status ?? 128, out: err.stdout ?? "" };
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
var isGitRepo = (root) => git(root, ["rev-parse", "--is-inside-work-tree"]).code === 0;
|
|
298
|
+
function isGitIgnored(file2) {
|
|
299
|
+
const dir = path3.dirname(file2);
|
|
300
|
+
if (!isGitRepo(dir)) return null;
|
|
301
|
+
return git(dir, ["check-ignore", "-q", file2]).code === 0;
|
|
302
|
+
}
|
|
303
|
+
function dirtyFiles(root, files) {
|
|
304
|
+
if (!files.length || !isGitRepo(root)) return [];
|
|
305
|
+
const { out } = git(root, ["status", "--porcelain", "--", ...files]);
|
|
306
|
+
const top = git(root, ["rev-parse", "--show-toplevel"]).out.trim();
|
|
307
|
+
return out.split("\n").filter(Boolean).map((l) => path3.join(top, l.slice(3).trim()));
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// ../core/src/vitals.ts
|
|
311
|
+
import fs2 from "fs";
|
|
312
|
+
import path4 from "path";
|
|
313
|
+
function alwaysOn(text2) {
|
|
314
|
+
const { data } = parseFrontmatter(text2);
|
|
315
|
+
if (!data) return true;
|
|
316
|
+
if (data.alwaysApply === true || data.trigger === "always_on" || data.applyTo === "**") return true;
|
|
317
|
+
return !["globs", "paths", "applyTo", "trigger", "description", "alwaysApply"].some((k) => k in data);
|
|
318
|
+
}
|
|
319
|
+
function importTokens(file2) {
|
|
320
|
+
const out = [];
|
|
321
|
+
for (const m of (file2.text ?? "").matchAll(/^@([~\w./-]+\.\w+)\s*$/gm)) {
|
|
322
|
+
const p3 = path4.resolve(path4.dirname(file2.path), m[1]);
|
|
323
|
+
try {
|
|
324
|
+
out.push({ rel: m[1], tokens: countTokens(fs2.readFileSync(p3, "utf8")) });
|
|
325
|
+
} catch {
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
return out;
|
|
329
|
+
}
|
|
330
|
+
function startupLoad(files, profiles) {
|
|
331
|
+
const res = {};
|
|
332
|
+
for (const h of profiles) {
|
|
333
|
+
const load = { tokens: 0, files: [] };
|
|
334
|
+
for (const f of files) {
|
|
335
|
+
if (!f.harnesses.includes(h.id) || !f.text) continue;
|
|
336
|
+
let t2 = 0;
|
|
337
|
+
if (f.role === "instructions") {
|
|
338
|
+
t2 = f.tokens;
|
|
339
|
+
if (h.syntax.includes("@import")) for (const imp of importTokens(f)) load.files.push(imp), load.tokens += imp.tokens;
|
|
340
|
+
} else if (f.role === "rules" && alwaysOn(f.text)) t2 = f.tokens;
|
|
341
|
+
else if (f.role === "skill") {
|
|
342
|
+
const { data } = parseFrontmatter(f.text);
|
|
343
|
+
t2 = countTokens(`${data?.name ?? ""} ${data?.description ?? ""}`);
|
|
344
|
+
}
|
|
345
|
+
if (t2) load.files.push({ rel: f.rel, tokens: t2 }), load.tokens += t2;
|
|
346
|
+
}
|
|
347
|
+
if (load.files.length) res[h.id] = load;
|
|
348
|
+
}
|
|
349
|
+
return res;
|
|
350
|
+
}
|
|
351
|
+
var detectedHarnesses = (files) => [...new Set(files.flatMap((f) => f.harnesses))].sort();
|
|
352
|
+
|
|
353
|
+
// ../core/src/secrets.ts
|
|
354
|
+
var PATTERNS = [
|
|
355
|
+
["Anthropic API key", /\bsk-ant-[A-Za-z0-9_-]{20,}/g],
|
|
356
|
+
["OpenAI API key", /\bsk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{32,}/g],
|
|
357
|
+
["GitHub token", /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}|\bgithub_pat_[A-Za-z0-9_]{40,}/g],
|
|
358
|
+
["AWS access key", /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g],
|
|
359
|
+
["Slack token", /\bxox[abposr]-[A-Za-z0-9-]{10,}/g],
|
|
360
|
+
["Google API key", /\bAIza[0-9A-Za-z_-]{35}\b/g],
|
|
361
|
+
["Stripe key", /\b(?:sk|rk)_live_[A-Za-z0-9]{20,}/g]
|
|
362
|
+
];
|
|
363
|
+
var GENERIC = /["']?([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))["']?\s*[:=]\s*["']([^"'\s$]{16,})["']/gi;
|
|
364
|
+
var mask = (s) => s.length <= 8 ? "****" : `${s.slice(0, 6)}\u2026${s.slice(-2)} (${s.length} chars)`;
|
|
365
|
+
function entropy(s) {
|
|
366
|
+
const freq = /* @__PURE__ */ new Map();
|
|
367
|
+
for (const c of s) freq.set(c, (freq.get(c) ?? 0) + 1);
|
|
368
|
+
let h = 0;
|
|
369
|
+
for (const n2 of freq.values()) h -= n2 / s.length * Math.log2(n2 / s.length);
|
|
370
|
+
return h;
|
|
371
|
+
}
|
|
372
|
+
function findSecrets(text2) {
|
|
373
|
+
const hits = [];
|
|
374
|
+
const seen = /* @__PURE__ */ new Set();
|
|
375
|
+
const lineOf = (i) => text2.slice(0, i).split("\n").length;
|
|
376
|
+
for (const [kind, re] of PATTERNS)
|
|
377
|
+
for (const m of text2.matchAll(re))
|
|
378
|
+
if (!seen.has(m[0])) seen.add(m[0]), hits.push({ kind, masked: mask(m[0]), line: lineOf(m.index) });
|
|
379
|
+
for (const m of text2.matchAll(GENERIC)) {
|
|
380
|
+
const v = m[2];
|
|
381
|
+
if (seen.has(v) || [...seen].some((s) => s.includes(v) || v.includes(s)) || entropy(v) < 3.5) continue;
|
|
382
|
+
seen.add(v);
|
|
383
|
+
hits.push({ kind: `${m[1]} value`, masked: mask(v), line: lineOf(m.index) });
|
|
384
|
+
}
|
|
385
|
+
return hits;
|
|
386
|
+
}
|
|
387
|
+
function redactSecrets(text2) {
|
|
388
|
+
let out = text2;
|
|
389
|
+
for (const [, re] of PATTERNS) out = out.replace(re, (s) => `[REDACTED ${mask(s)}]`);
|
|
390
|
+
return out.replace(GENERIC, (all, _k, v) => entropy(v) < 3.5 ? all : all.replace(v, "[REDACTED]"));
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// ../core/src/rules/bloatIgnore.ts
|
|
394
|
+
import fs3 from "fs";
|
|
395
|
+
import path5 from "path";
|
|
396
|
+
var HEAVY = [
|
|
397
|
+
"node_modules/",
|
|
398
|
+
"dist/",
|
|
399
|
+
"build/",
|
|
400
|
+
"out/",
|
|
401
|
+
".next/",
|
|
402
|
+
".nuxt/",
|
|
403
|
+
"coverage/",
|
|
404
|
+
"target/",
|
|
405
|
+
"vendor/",
|
|
406
|
+
".venv/",
|
|
407
|
+
"__pycache__/",
|
|
408
|
+
"*.min.js",
|
|
409
|
+
"*.map",
|
|
410
|
+
"package-lock.json",
|
|
411
|
+
"pnpm-lock.yaml",
|
|
412
|
+
"yarn.lock",
|
|
413
|
+
"bun.lockb",
|
|
414
|
+
"Cargo.lock",
|
|
415
|
+
"poetry.lock",
|
|
416
|
+
"composer.lock"
|
|
417
|
+
];
|
|
418
|
+
var bloatIgnore = {
|
|
419
|
+
id: "FIN_BLOAT_IGNORE",
|
|
420
|
+
check: ({ root, files, profiles }) => {
|
|
421
|
+
const out = [];
|
|
422
|
+
for (const h of profiles) {
|
|
423
|
+
if (!h.ignoreFile) continue;
|
|
424
|
+
const used = files.some((f) => f.scope === "project" && f.harnesses.includes(h.id)) || fs3.existsSync(path5.join(root, `.${h.id}`));
|
|
425
|
+
if (!used || fs3.existsSync(path5.join(root, h.ignoreFile))) continue;
|
|
426
|
+
const present = HEAVY.filter((p3) => !p3.includes("*") && fs3.existsSync(path5.join(root, p3)));
|
|
427
|
+
if (!present.length) continue;
|
|
428
|
+
out.push({
|
|
429
|
+
ruleId: "FIN_BLOAT_IGNORE",
|
|
430
|
+
severity: "warning",
|
|
431
|
+
message: `${h.name} indexes ${present.join(", ")} because ${h.ignoreFile} is missing`,
|
|
432
|
+
files: present,
|
|
433
|
+
data: { harness: h.id, ignoreFile: h.ignoreFile, present },
|
|
434
|
+
fix: {
|
|
435
|
+
title: `Create ${h.ignoreFile}`,
|
|
436
|
+
ops: [
|
|
437
|
+
{
|
|
438
|
+
kind: "write",
|
|
439
|
+
path: path5.join(root, h.ignoreFile),
|
|
440
|
+
content: `# Generated by ctxmedic: keep build output and lockfiles out of the AI index.
|
|
441
|
+
${HEAVY.join("\n")}
|
|
442
|
+
`
|
|
443
|
+
}
|
|
444
|
+
]
|
|
445
|
+
}
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
return out;
|
|
449
|
+
}
|
|
450
|
+
};
|
|
451
|
+
|
|
452
|
+
// ../core/src/rules/brokenLink.ts
|
|
453
|
+
import path6 from "path";
|
|
454
|
+
var brokenLink = {
|
|
455
|
+
id: "ERR_BROKEN_LINK",
|
|
456
|
+
check: ({ files }) => files.flatMap((f) => {
|
|
457
|
+
if (f.broken || f.loop)
|
|
458
|
+
return [
|
|
459
|
+
{
|
|
460
|
+
ruleId: "ERR_BROKEN_LINK",
|
|
461
|
+
severity: "critical",
|
|
462
|
+
message: f.loop ? `${f.rel} is a circular symlink` : `${f.rel} points to a missing target: ${f.linkTarget}`,
|
|
463
|
+
files: [f.rel],
|
|
464
|
+
data: { target: f.linkTarget, loop: f.loop, harnesses: f.harnesses }
|
|
465
|
+
}
|
|
466
|
+
];
|
|
467
|
+
if (f.isSymlink && f.linkTarget && path6.isAbsolute(f.linkTarget) && f.scope === "project")
|
|
468
|
+
return [
|
|
469
|
+
{
|
|
470
|
+
ruleId: "ERR_BROKEN_LINK",
|
|
471
|
+
severity: "info",
|
|
472
|
+
message: `${f.rel} uses an absolute symlink; it breaks on other machines and in CI`,
|
|
473
|
+
files: [f.rel],
|
|
474
|
+
data: { target: f.linkTarget, absolute: true },
|
|
475
|
+
fix: {
|
|
476
|
+
title: `Make ${f.rel} a relative symlink`,
|
|
477
|
+
ops: [{ kind: "symlink", path: f.path, target: path6.relative(path6.dirname(f.path), f.linkTarget) }]
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
];
|
|
481
|
+
return [];
|
|
482
|
+
})
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
// ../core/src/rules/types.ts
|
|
486
|
+
var BLOAT_TOKENS = 3500;
|
|
487
|
+
var DUPLICATE_SIMILARITY = 0.75;
|
|
488
|
+
|
|
489
|
+
// ../core/src/rules/contextBloat.ts
|
|
490
|
+
var contextBloat = {
|
|
491
|
+
id: "WARN_CONTEXT_BLOAT",
|
|
492
|
+
check: ({ startup, profiles }) => Object.entries(startup).filter(([, l]) => l.tokens > BLOAT_TOKENS).map(([id, l]) => {
|
|
493
|
+
const top = [...l.files].sort((a2, b) => b.tokens - a2.tokens).slice(0, 5);
|
|
494
|
+
const limit = profiles.find((p3) => p3.id === id)?.contextLimit ?? 2e5;
|
|
495
|
+
return {
|
|
496
|
+
ruleId: "WARN_CONTEXT_BLOAT",
|
|
497
|
+
severity: l.tokens > BLOAT_TOKENS * 3 ? "critical" : "warning",
|
|
498
|
+
message: `${id} loads ${l.tokens.toLocaleString("en")} tokens at session start (threshold ${BLOAT_TOKENS.toLocaleString("en")})`,
|
|
499
|
+
files: top.map((f) => f.rel),
|
|
500
|
+
data: { harness: id, tokens: l.tokens, threshold: BLOAT_TOKENS, contextShare: l.tokens / limit, top }
|
|
501
|
+
};
|
|
502
|
+
})
|
|
503
|
+
};
|
|
504
|
+
|
|
505
|
+
// ../core/src/rules/duplicates.ts
|
|
506
|
+
import fs4 from "fs";
|
|
507
|
+
import path7 from "path";
|
|
508
|
+
var norm = (text2) => new Set(
|
|
509
|
+
text2.split("\n").map((l) => l.toLowerCase().replace(/\s+/g, " ").trim()).filter((l) => l.length >= 8)
|
|
510
|
+
);
|
|
511
|
+
function similarity(a2, b) {
|
|
512
|
+
const A = norm(a2);
|
|
513
|
+
const B = norm(b);
|
|
514
|
+
if (!A.size || !B.size) return 0;
|
|
515
|
+
let inter = 0;
|
|
516
|
+
for (const l of A) if (B.has(l)) inter++;
|
|
517
|
+
return inter / (A.size + B.size - inter);
|
|
518
|
+
}
|
|
519
|
+
var HUB = ".ai/INSTRUCTIONS.md";
|
|
520
|
+
function hubFix(root, a2, b) {
|
|
521
|
+
const [big, small] = a2.text.length >= b.text.length ? [a2, b] : [b, a2];
|
|
522
|
+
const have = norm(big.text);
|
|
523
|
+
const extra = small.text.split("\n").filter((l) => {
|
|
524
|
+
const n2 = l.toLowerCase().replace(/\s+/g, " ").trim();
|
|
525
|
+
return n2.length >= 8 && !have.has(n2);
|
|
526
|
+
});
|
|
527
|
+
let content = big.text;
|
|
528
|
+
if (extra.length) content += `
|
|
529
|
+
|
|
530
|
+
## Merged from ${small.rel}
|
|
531
|
+
|
|
532
|
+
${extra.join("\n")}
|
|
533
|
+
`;
|
|
534
|
+
const hub = path7.join(root, HUB);
|
|
535
|
+
if (fs4.existsSync(hub)) return [];
|
|
536
|
+
return [
|
|
537
|
+
{ kind: "write", path: hub, content },
|
|
538
|
+
...[big, small].map((f) => ({ kind: "symlink", path: f.path, target: path7.relative(path7.dirname(f.path), hub) }))
|
|
539
|
+
];
|
|
540
|
+
}
|
|
541
|
+
var duplicates = {
|
|
542
|
+
id: "WARN_DUPLICATE_RULES",
|
|
543
|
+
check: ({ root, files }) => {
|
|
544
|
+
const docs = files.filter((f) => f.role === "instructions" && f.text && !f.broken);
|
|
545
|
+
const out = [];
|
|
546
|
+
const seen = /* @__PURE__ */ new Set();
|
|
547
|
+
for (let i = 0; i < docs.length; i++)
|
|
548
|
+
for (let j = i + 1; j < docs.length; j++) {
|
|
549
|
+
const a2 = docs[i];
|
|
550
|
+
const b = docs[j];
|
|
551
|
+
if ((a2.realpath ?? a2.path) === (b.realpath ?? b.path)) continue;
|
|
552
|
+
const key = [a2.realpath ?? a2.path, b.realpath ?? b.path].sort().join("|");
|
|
553
|
+
if (seen.has(key)) continue;
|
|
554
|
+
seen.add(key);
|
|
555
|
+
const sim = similarity(a2.text, b.text);
|
|
556
|
+
if (sim <= DUPLICATE_SIMILARITY) continue;
|
|
557
|
+
const ops = a2.scope === "project" && b.scope === "project" && !a2.isSymlink && !b.isSymlink ? hubFix(root, a2, b) : [];
|
|
558
|
+
out.push({
|
|
559
|
+
ruleId: "WARN_DUPLICATE_RULES",
|
|
560
|
+
severity: "warning",
|
|
561
|
+
message: `${a2.rel} and ${b.rel} are ${Math.round(sim * 100)}% identical`,
|
|
562
|
+
files: [a2.rel, b.rel],
|
|
563
|
+
data: { similarity: sim, wastedTokens: Math.min(a2.tokens, b.tokens), hub: HUB },
|
|
564
|
+
fix: ops.length ? { title: `Merge into ${HUB} and symlink both files to it`, ops } : void 0
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
return out;
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
|
|
571
|
+
// ../core/src/rules/secretLeak.ts
|
|
572
|
+
var secretLeak = {
|
|
573
|
+
id: "CRIT_SECRET_LEAK",
|
|
574
|
+
check: ({ files }) => files.flatMap((f) => {
|
|
575
|
+
if (!f.text) return [];
|
|
576
|
+
const hits = findSecrets(f.text);
|
|
577
|
+
if (!hits.length) return [];
|
|
578
|
+
const ignored = isGitIgnored(f.path);
|
|
579
|
+
const exposed = f.scope === "project" && ignored === false;
|
|
580
|
+
return [
|
|
581
|
+
{
|
|
582
|
+
ruleId: "CRIT_SECRET_LEAK",
|
|
583
|
+
severity: exposed ? "critical" : "info",
|
|
584
|
+
message: exposed ? `${f.rel} contains ${hits.length} secret(s) and is not git-ignored` : `${f.rel} stores ${hits.length} secret(s) in plain text`,
|
|
585
|
+
files: [f.rel],
|
|
586
|
+
data: { hits, exposed, ignored }
|
|
587
|
+
}
|
|
588
|
+
];
|
|
589
|
+
})
|
|
590
|
+
};
|
|
591
|
+
|
|
592
|
+
// ../core/src/rules/skills.ts
|
|
593
|
+
var NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
594
|
+
var TRIGGER = /\b(use|when|whenever|triggers?|invoke)\b/i;
|
|
595
|
+
var skills = {
|
|
596
|
+
id: "ERR_INVALID_SKILL",
|
|
597
|
+
check: ({ files }) => {
|
|
598
|
+
const out = [];
|
|
599
|
+
const names = /* @__PURE__ */ new Map();
|
|
600
|
+
const bad = (f, severity, problem) => out.push({ ruleId: "ERR_INVALID_SKILL", severity, message: `${f.rel}: ${problem}`, files: [f.rel], data: { problem } });
|
|
601
|
+
for (const f of files) {
|
|
602
|
+
if (f.role !== "skill" || f.text === void 0) continue;
|
|
603
|
+
const { data, error } = parseFrontmatter(f.text);
|
|
604
|
+
if (!data) {
|
|
605
|
+
bad(f, "warning", "no YAML frontmatter; the harness cannot discover this skill");
|
|
606
|
+
continue;
|
|
607
|
+
}
|
|
608
|
+
if (error) {
|
|
609
|
+
bad(f, "warning", `invalid YAML frontmatter (${error})`);
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
const name = typeof data.name === "string" ? data.name : "";
|
|
613
|
+
const desc = typeof data.description === "string" ? data.description : "";
|
|
614
|
+
if (!name) bad(f, "warning", "missing `name`");
|
|
615
|
+
else if (!NAME.test(name)) bad(f, "warning", `name "${name}" must be lowercase letters, digits and hyphens (max 64)`);
|
|
616
|
+
if (!desc) bad(f, "warning", "missing `description`; the model never knows when to load it");
|
|
617
|
+
else if (desc.length > 1024) bad(f, "warning", `description is ${desc.length} chars (max 1024)`);
|
|
618
|
+
else if (desc.length < 40 || !TRIGGER.test(desc))
|
|
619
|
+
bad(f, "info", 'description has no clear trigger ("Use when \u2026"); the skill will rarely activate');
|
|
620
|
+
if (name) names.set(`${f.scope}:${name}`, [...names.get(`${f.scope}:${name}`) ?? [], f.rel]);
|
|
621
|
+
}
|
|
622
|
+
for (const [key, rels] of names)
|
|
623
|
+
if (rels.length > 1)
|
|
624
|
+
out.push({
|
|
625
|
+
ruleId: "ERR_INVALID_SKILL",
|
|
626
|
+
severity: "warning",
|
|
627
|
+
message: `skill name "${key.split(":")[1]}" is used by ${rels.length} skills`,
|
|
628
|
+
files: rels,
|
|
629
|
+
data: { problem: "duplicate name" }
|
|
630
|
+
});
|
|
631
|
+
return out;
|
|
632
|
+
}
|
|
633
|
+
};
|
|
634
|
+
|
|
635
|
+
// ../core/src/rules/syntax.ts
|
|
636
|
+
function directives(text2) {
|
|
637
|
+
const found = /* @__PURE__ */ new Set();
|
|
638
|
+
if (/^@[~\w./-]+\.\w+\s*$/m.test(text2)) found.add("@import");
|
|
639
|
+
const { data } = parseFrontmatter(text2);
|
|
640
|
+
if (data) {
|
|
641
|
+
for (const k of ["alwaysApply", "globs", "applyTo", "trigger"]) if (k in data) found.add(k);
|
|
642
|
+
}
|
|
643
|
+
return [...found];
|
|
644
|
+
}
|
|
645
|
+
var syntax = {
|
|
646
|
+
id: "INFO_UNSUPPORTED_SYNTAX",
|
|
647
|
+
check: ({ files, profiles }) => {
|
|
648
|
+
const out = [];
|
|
649
|
+
for (const f of files) {
|
|
650
|
+
if (!f.text || f.role !== "instructions" && f.role !== "rules") continue;
|
|
651
|
+
const used = directives(f.text);
|
|
652
|
+
if (!used.length) continue;
|
|
653
|
+
for (const hid of f.harnesses) {
|
|
654
|
+
const h = profiles.find((p3) => p3.id === hid);
|
|
655
|
+
const missing = used.filter((d2) => !h?.syntax.includes(d2));
|
|
656
|
+
if (missing.length)
|
|
657
|
+
out.push({
|
|
658
|
+
ruleId: "INFO_UNSUPPORTED_SYNTAX",
|
|
659
|
+
severity: "info",
|
|
660
|
+
message: `${f.rel} uses ${missing.join(", ")}, which ${h?.name ?? hid} ignores (it sees the raw text)`,
|
|
661
|
+
files: [f.rel],
|
|
662
|
+
data: { harness: hid, directives: missing }
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
return out;
|
|
667
|
+
}
|
|
668
|
+
};
|
|
669
|
+
|
|
670
|
+
// ../core/src/rules/index.ts
|
|
671
|
+
var rules = [brokenLink, contextBloat, duplicates, skills, secretLeak, syntax, bloatIgnore];
|
|
672
|
+
async function runRules(ctx2, list = rules) {
|
|
673
|
+
const out = [];
|
|
674
|
+
for (const r of list) for (const f of await r.check(ctx2)) out.push(Finding.parse(f));
|
|
675
|
+
return out;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
// ../core/src/fix.ts
|
|
679
|
+
import fs5 from "fs/promises";
|
|
680
|
+
import path8 from "path";
|
|
681
|
+
var FixRefusedError = class extends Error {
|
|
682
|
+
};
|
|
683
|
+
var stamp = () => (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
684
|
+
async function applyFix(planIn, opts) {
|
|
685
|
+
const plan = FixPlan.parse(planIn);
|
|
686
|
+
const root = path8.resolve(opts.root);
|
|
687
|
+
const targets = plan.ops.map((o2) => path8.resolve(o2.path));
|
|
688
|
+
for (const t2 of targets)
|
|
689
|
+
if (path8.relative(root, t2).startsWith("..") && !opts.global)
|
|
690
|
+
throw new FixRefusedError(`refusing to modify ${t2}: outside ${root} (use --global)`);
|
|
691
|
+
if (!opts.force) {
|
|
692
|
+
const dirty = dirtyFiles(root, targets.filter((t2) => !path8.relative(root, t2).startsWith("..")));
|
|
693
|
+
if (dirty.length) throw new FixRefusedError(`uncommitted changes in ${dirty.join(", ")}; commit them or use --force`);
|
|
694
|
+
}
|
|
695
|
+
const backupDir = path8.join(root, ".ctxmedic", "backups", stamp());
|
|
696
|
+
const describe = plan.ops.map((o2) => o2.kind === "write" ? `write ${o2.path}` : `symlink ${o2.path} -> ${o2.target}`);
|
|
697
|
+
if (opts.dryRun) return { backupDir, applied: describe, dryRun: true };
|
|
698
|
+
const manifest = {
|
|
699
|
+
title: plan.title,
|
|
700
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
701
|
+
entries: []
|
|
702
|
+
};
|
|
703
|
+
await fs5.mkdir(backupDir, { recursive: true });
|
|
704
|
+
for (const t2 of targets) {
|
|
705
|
+
const rel = path8.relative(root, t2).startsWith("..") ? path8.join("_outside", t2) : path8.relative(root, t2);
|
|
706
|
+
let st;
|
|
707
|
+
try {
|
|
708
|
+
st = await fs5.lstat(t2);
|
|
709
|
+
} catch {
|
|
710
|
+
manifest.entries.push({ path: t2, existed: false });
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
if (st.isSymbolicLink()) manifest.entries.push({ path: t2, existed: true, symlink: await fs5.readlink(t2) });
|
|
714
|
+
else {
|
|
715
|
+
const dest = path8.join(backupDir, rel);
|
|
716
|
+
await fs5.mkdir(path8.dirname(dest), { recursive: true });
|
|
717
|
+
await fs5.copyFile(t2, dest);
|
|
718
|
+
manifest.entries.push({ path: t2, existed: true, backup: rel });
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
await fs5.writeFile(path8.join(backupDir, "manifest.json"), JSON.stringify(manifest, null, 2));
|
|
722
|
+
for (const op of plan.ops) {
|
|
723
|
+
await fs5.mkdir(path8.dirname(op.path), { recursive: true });
|
|
724
|
+
await fs5.rm(op.path, { force: true });
|
|
725
|
+
if (op.kind === "write") await fs5.writeFile(op.path, op.content);
|
|
726
|
+
else await fs5.symlink(op.target, op.path);
|
|
727
|
+
}
|
|
728
|
+
return { backupDir, applied: describe, dryRun: false };
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
// ../core/src/examine.ts
|
|
732
|
+
import path9 from "path";
|
|
733
|
+
async function examine(root, profiles, opts = {}) {
|
|
734
|
+
root = path9.resolve(root);
|
|
735
|
+
const files = await scan(root, profiles, opts);
|
|
736
|
+
const startup = startupLoad(files, profiles);
|
|
737
|
+
const findings = await runRules({ root, files, profiles, startup });
|
|
738
|
+
const vitals2 = PatientVitals.parse({
|
|
739
|
+
root,
|
|
740
|
+
scannedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
741
|
+
filesScanned: files.length,
|
|
742
|
+
harnesses: detectedHarnesses(files),
|
|
743
|
+
startupTokens: Object.fromEntries(Object.entries(startup).map(([k, v]) => [k, v.tokens]))
|
|
744
|
+
});
|
|
745
|
+
return { vitals: vitals2, files, startup, findings };
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// ../clinical/src/schema.ts
|
|
749
|
+
var Lang = z2.enum(["en"]);
|
|
750
|
+
var Triage = z2.enum(["resuscitation", "therapy", "preventive"]);
|
|
751
|
+
var PrescriptionRx = z2.object({
|
|
752
|
+
id: z2.string().regex(/^RX-\d{2,}$/),
|
|
753
|
+
action: z2.string(),
|
|
754
|
+
command: z2.string().optional(),
|
|
755
|
+
autoFix: z2.boolean(),
|
|
756
|
+
healthGain: z2.number().nonnegative(),
|
|
757
|
+
monthlySavingsUsd: z2.number().nonnegative().optional()
|
|
758
|
+
});
|
|
759
|
+
var ClinicalDiagnosis = z2.object({
|
|
760
|
+
code: RuleId,
|
|
761
|
+
triage: Triage,
|
|
762
|
+
diagnosis: z2.string(),
|
|
763
|
+
summary: z2.string(),
|
|
764
|
+
vitals: z2.array(z2.object({ label: z2.string(), value: z2.string() })),
|
|
765
|
+
prognosis: z2.string(),
|
|
766
|
+
rx: PrescriptionRx,
|
|
767
|
+
files: z2.array(z2.string()),
|
|
768
|
+
finding: Finding
|
|
769
|
+
});
|
|
770
|
+
var Counts = z2.object({ resuscitation: z2.number(), therapy: z2.number(), preventive: z2.number() });
|
|
771
|
+
var Anamnesis = z2.object({
|
|
772
|
+
priority: z2.enum(["economy", "balanced", "quality"]).default("balanced"),
|
|
773
|
+
primaryHarness: z2.string().optional(),
|
|
774
|
+
monthlyBudgetUsd: z2.number().nonnegative().optional()
|
|
775
|
+
});
|
|
776
|
+
var Visit = z2.object({
|
|
777
|
+
at: z2.string(),
|
|
778
|
+
root: z2.string(),
|
|
779
|
+
healthScore: z2.number(),
|
|
780
|
+
counts: Counts,
|
|
781
|
+
monthlySpendUsd: z2.number().optional(),
|
|
782
|
+
potentialMonthlySavingsUsd: z2.number()
|
|
783
|
+
});
|
|
784
|
+
var ClinicalReport = z2.object({
|
|
785
|
+
tool: z2.literal("ctxmedic"),
|
|
786
|
+
version: z2.string(),
|
|
787
|
+
lang: Lang,
|
|
788
|
+
generatedAt: z2.string(),
|
|
789
|
+
patient: PatientVitals,
|
|
790
|
+
healthScore: z2.number().min(0).max(100),
|
|
791
|
+
previous: Visit.nullable(),
|
|
792
|
+
opinion: z2.string(),
|
|
793
|
+
counts: Counts,
|
|
794
|
+
diagnoses: z2.array(ClinicalDiagnosis),
|
|
795
|
+
finops: FinOpsReport.nullable(),
|
|
796
|
+
potentialMonthlySavingsUsd: z2.number()
|
|
797
|
+
});
|
|
798
|
+
|
|
799
|
+
// ../clinical/src/i18n.ts
|
|
800
|
+
var d = (f, k) => f.data[k];
|
|
801
|
+
var n = (x) => Number(x ?? 0).toLocaleString("en");
|
|
802
|
+
var usd = (x) => `$${Number(x ?? 0).toFixed(2)}`;
|
|
803
|
+
var pct = (x) => `${Math.round(Number(x ?? 0) * 100)}%`;
|
|
804
|
+
var en = {
|
|
805
|
+
cards: {
|
|
806
|
+
ERR_BROKEN_LINK: {
|
|
807
|
+
name: "Symlink Necrosis",
|
|
808
|
+
prognosis: (f) => d(f, "absolute") ? "Works on this machine only. Teammates and CI silently lose these instructions." : "The agent silently loses these instructions and runs without them. You will see it ignore rules you think are active.",
|
|
809
|
+
action: (f) => f.fix ? "Rewrite the link as a relative symlink." : `Restore the target or delete the dead link: ${f.files[0]}`
|
|
810
|
+
},
|
|
811
|
+
WARN_CONTEXT_BLOAT: {
|
|
812
|
+
name: "Context Obesity",
|
|
813
|
+
prognosis: (f) => `${n(d(f, "tokens"))} tokens ride along with every request. Rules in the middle get "lost in the middle", attention drifts and the bill grows with each turn.`,
|
|
814
|
+
action: () => "Move rarely-needed sections into skills or path-scoped rules; keep the always-on core under 3,500 tokens."
|
|
815
|
+
},
|
|
816
|
+
WARN_DUPLICATE_RULES: {
|
|
817
|
+
name: "Instruction Duplication Syndrome",
|
|
818
|
+
prognosis: (f) => `${n(d(f, "wastedTokens"))} duplicated tokens. The copies drift apart and the agents get contradictory orders.`,
|
|
819
|
+
action: (f) => f.fix ? `Merge into ${d(f, "hub")} (hub) and symlink every tool's file to it (spokes).` : "Keep one canonical file and symlink the others to it."
|
|
820
|
+
},
|
|
821
|
+
ERR_INVALID_SKILL: {
|
|
822
|
+
name: "Skill Amnesia",
|
|
823
|
+
prognosis: () => "The harness cannot discover or trigger this skill reliably. It costs tokens and never helps.",
|
|
824
|
+
action: (f) => `Fix the SKILL.md frontmatter: ${d(f, "problem")}.`
|
|
825
|
+
},
|
|
826
|
+
CRIT_SECRET_LEAK: {
|
|
827
|
+
name: "Credential Hemorrhage",
|
|
828
|
+
prognosis: (f) => d(f, "exposed") ? "One `git add .` away from a public leak. Leaked keys are found by scanners within minutes." : "Plain-text keys in config files end up in backups, screenshots and support bundles.",
|
|
829
|
+
action: () => "Rotate the key now, then reference it through an environment variable (`${VAR}`) and git-ignore the file."
|
|
830
|
+
},
|
|
831
|
+
INFO_UNSUPPORTED_SYNTAX: {
|
|
832
|
+
name: "Cross-Harness Allergy",
|
|
833
|
+
prognosis: (f) => `${d(f, "harness")} reads ${(d(f, "directives") ?? []).join(", ")} as plain text: noise at best, wrong instructions at worst.`,
|
|
834
|
+
action: () => "Move tool-specific directives into that tool's own file, or keep shared files directive-free."
|
|
835
|
+
},
|
|
836
|
+
FIN_BLOAT_IGNORE: {
|
|
837
|
+
name: "Indexing Bloat",
|
|
838
|
+
prognosis: (f) => `${d(f, "harness")} indexes build output and lockfiles. Search results fill with junk and retrieval burns tokens.`,
|
|
839
|
+
action: (f) => `Create ${d(f, "ignoreFile")} with the standard exclusions.`
|
|
840
|
+
},
|
|
841
|
+
FIN_UNUSED_MCP: {
|
|
842
|
+
name: "Toxic MCP Syndrome",
|
|
843
|
+
prognosis: (f) => `~${n(d(f, "schemaTokens"))} tokens of tool schemas in every request for a server nobody calls.`,
|
|
844
|
+
action: (f) => d(f, "scope") === "global" ? `Move "${d(f, "server")}" from the global config into the project-level MCP config of the projects that need it.` : `Remove "${d(f, "server")}" from ${f.files[0]} or disable it until needed.`
|
|
845
|
+
},
|
|
846
|
+
FIN_MODEL_OVERKILL: {
|
|
847
|
+
name: "Model Overkill",
|
|
848
|
+
prognosis: (f) => `${d(f, "sessions")} trivial sessions paid frontier prices (${usd(d(f, "costUsd"))} in ${d(f, "days")} days).`,
|
|
849
|
+
action: (f) => `Route one-shot tasks, routine skills and subagents to ${d(f, "suggested")} (set \`model:\` in the skill/agent frontmatter).`
|
|
850
|
+
},
|
|
851
|
+
FIN_CONTEXT_SNOWBALL: {
|
|
852
|
+
name: "Context Snowball",
|
|
853
|
+
prognosis: (f) => `Worst case: ${d(f, "worstSteps")} steps, peak context ${n(d(f, "worstMaxContext"))} tokens. Each step re-reads the whole history; quality drops as it grows.`,
|
|
854
|
+
action: () => "Run /compact at task milestones and /clear between unrelated tasks; enable auto-compact."
|
|
855
|
+
},
|
|
856
|
+
FIN_CACHE_MISS: {
|
|
857
|
+
name: "Prompt Cache Thrashing",
|
|
858
|
+
prognosis: (f) => `Cache hit ratio ${pct(d(f, "cacheHitRatio"))}: you pay full price for context the provider could serve at ~10%.`,
|
|
859
|
+
action: () => "Keep instructions static: no dates, branch names or random IDs at the top; avoid switching models mid-session."
|
|
860
|
+
}
|
|
861
|
+
},
|
|
862
|
+
ui: {
|
|
863
|
+
triage: { resuscitation: "\u{1F534} Resuscitation", therapy: "\u{1F7E1} Therapy", preventive: "\u{1F7E2} Preventive" },
|
|
864
|
+
labs: "Vitals",
|
|
865
|
+
prognosis: "Prognosis",
|
|
866
|
+
health: "Health Score",
|
|
867
|
+
savings: "Potential savings",
|
|
868
|
+
perMonth: "/mo",
|
|
869
|
+
healthy: "No complaints. The patient is healthy.",
|
|
870
|
+
opinion: (s) => s >= 90 ? "Excellent condition. Only preventive care needed." : s >= 70 ? "Stable, but a few conditions need therapy." : s >= 40 ? "The patient needs treatment soon." : "Critical condition. Start with the red cards right now.",
|
|
871
|
+
since: (x) => x === 0 ? "unchanged since the last visit" : x > 0 ? `+${x} since the last visit` : `${x} since the last visit`,
|
|
872
|
+
manual: "manual treatment",
|
|
873
|
+
noLogs: "No session logs found: FinOps analysis skipped.",
|
|
874
|
+
spend: "Spend",
|
|
875
|
+
runRate: "run rate"
|
|
876
|
+
},
|
|
877
|
+
cli: {
|
|
878
|
+
noAutoFix: "No auto-fix: follow the prescription by hand.",
|
|
879
|
+
confirmApply: "Apply? (originals are backed up to .ctxmedic/backups)",
|
|
880
|
+
consultTitle: "\u{1FA7A} ctxmedic consultation",
|
|
881
|
+
askPriority: "What matters most to you?",
|
|
882
|
+
priority: { economy: "Saving tokens and money", balanced: "Balanced", quality: "Maximum answer quality" },
|
|
883
|
+
askHarness: "Your main AI tool?",
|
|
884
|
+
askBudget: "Monthly AI budget in $ (empty = no limit)",
|
|
885
|
+
enterNumber: "Enter a number",
|
|
886
|
+
examining: "Examining the patient",
|
|
887
|
+
treatmentPlan: "Treatment plan",
|
|
888
|
+
overBudget: (x) => `Over budget by $${x.toFixed(2)}/mo`,
|
|
889
|
+
withinBudget: "Within budget",
|
|
890
|
+
noAiProvider: "No Ollama, ANTHROPIC_API_KEY or OPENAI_API_KEY: AI review skipped.",
|
|
891
|
+
confirmSend: (chars, provider) => `Send ${chars.toLocaleString("en")} characters of your instructions (secrets redacted) to ${provider}?`,
|
|
892
|
+
nothingSent: "Nothing was sent.",
|
|
893
|
+
consulting: (provider) => `Consulting ${provider}`,
|
|
894
|
+
secondOpinion: "Second opinion",
|
|
895
|
+
goodbye: "Get well soon! Follow-up: ctxmedic checkup",
|
|
896
|
+
cancelled: "Cancelled"
|
|
897
|
+
}
|
|
898
|
+
};
|
|
899
|
+
var catalogs = { en };
|
|
900
|
+
var messages = (lang) => catalogs[lang];
|
|
901
|
+
var cards = (lang) => catalogs[lang].cards;
|
|
902
|
+
var t = (lang) => catalogs[lang].ui;
|
|
903
|
+
var resolveLang = (x) => {
|
|
904
|
+
const r = Lang.safeParse((x ?? process.env.CTXMEDIC_LANG ?? "en").slice(0, 2).toLowerCase());
|
|
905
|
+
return r.success ? r.data : "en";
|
|
906
|
+
};
|
|
907
|
+
|
|
908
|
+
// ../clinical/src/score.ts
|
|
909
|
+
var PENALTY = { critical: 25, warning: 8, info: 2 };
|
|
910
|
+
function healthScore(findings) {
|
|
911
|
+
const byRule = /* @__PURE__ */ new Map();
|
|
912
|
+
for (const f of findings) {
|
|
913
|
+
const p3 = PENALTY[f.severity];
|
|
914
|
+
const e = byRule.get(f.ruleId) ?? { sum: 0, max: 0 };
|
|
915
|
+
e.sum += p3;
|
|
916
|
+
e.max = Math.max(e.max, p3);
|
|
917
|
+
byRule.set(f.ruleId, e);
|
|
918
|
+
}
|
|
919
|
+
let total = 0;
|
|
920
|
+
for (const e of byRule.values()) total += Math.min(e.sum, e.max * 2);
|
|
921
|
+
return Math.max(0, Math.min(100, 100 - total));
|
|
922
|
+
}
|
|
923
|
+
function healthGain(findings, f) {
|
|
924
|
+
return healthScore(findings.filter((x) => x !== f)) - healthScore(findings);
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// ../clinical/src/store.ts
|
|
928
|
+
import fs6 from "fs";
|
|
929
|
+
import path10 from "path";
|
|
930
|
+
var MAX_VISITS = 200;
|
|
931
|
+
var historyFile = () => path10.join(stateDir(), "history.json");
|
|
932
|
+
var profileFile = () => path10.join(stateDir(), "profile.json");
|
|
933
|
+
function readJson(file2) {
|
|
934
|
+
try {
|
|
935
|
+
return JSON.parse(fs6.readFileSync(file2, "utf8"));
|
|
936
|
+
} catch {
|
|
937
|
+
return void 0;
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
function writeJson(file2, v) {
|
|
941
|
+
fs6.mkdirSync(path10.dirname(file2), { recursive: true });
|
|
942
|
+
fs6.writeFileSync(file2 + ".tmp", JSON.stringify(v, null, 2));
|
|
943
|
+
fs6.renameSync(file2 + ".tmp", file2);
|
|
944
|
+
}
|
|
945
|
+
function loadHistory(root) {
|
|
946
|
+
const raw = readJson(historyFile());
|
|
947
|
+
const visits = Array.isArray(raw) ? raw.flatMap((v) => {
|
|
948
|
+
const r = Visit.safeParse(v);
|
|
949
|
+
return r.success ? [r.data] : [];
|
|
950
|
+
}) : [];
|
|
951
|
+
return root ? visits.filter((v) => v.root === root) : visits;
|
|
952
|
+
}
|
|
953
|
+
function recordVisit(v) {
|
|
954
|
+
writeJson(historyFile(), [...loadHistory(), Visit.parse(v)].slice(-MAX_VISITS));
|
|
955
|
+
}
|
|
956
|
+
function loadAnamnesis() {
|
|
957
|
+
return Anamnesis.safeParse(readJson(profileFile())).data ?? Anamnesis.parse({});
|
|
958
|
+
}
|
|
959
|
+
function saveAnamnesis(a2) {
|
|
960
|
+
writeJson(profileFile(), Anamnesis.parse(a2));
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
// ../finops/src/cache.ts
|
|
964
|
+
import fs7 from "fs";
|
|
965
|
+
import path11 from "path";
|
|
966
|
+
var file = () => path11.join(stateDir(), "cache.json");
|
|
967
|
+
function loadCache() {
|
|
968
|
+
try {
|
|
969
|
+
const c = JSON.parse(fs7.readFileSync(file(), "utf8"));
|
|
970
|
+
if (c?.v === 2 && c.files) return c;
|
|
971
|
+
} catch {
|
|
972
|
+
}
|
|
973
|
+
return { v: 2, files: {} };
|
|
974
|
+
}
|
|
975
|
+
function saveCache(c) {
|
|
976
|
+
fs7.mkdirSync(stateDir(), { recursive: true });
|
|
977
|
+
const tmp = file() + ".tmp";
|
|
978
|
+
fs7.writeFileSync(tmp, JSON.stringify(c));
|
|
979
|
+
fs7.renameSync(tmp, file());
|
|
980
|
+
}
|
|
981
|
+
async function cachedParse(paths, parse, cache) {
|
|
982
|
+
const stats = [];
|
|
983
|
+
let parsed = 0;
|
|
984
|
+
for (const p3 of paths) {
|
|
985
|
+
let st;
|
|
986
|
+
try {
|
|
987
|
+
st = fs7.statSync(p3);
|
|
988
|
+
} catch {
|
|
989
|
+
continue;
|
|
990
|
+
}
|
|
991
|
+
const hit = cache.files[p3];
|
|
992
|
+
if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) {
|
|
993
|
+
stats.push(hit.stats);
|
|
994
|
+
continue;
|
|
995
|
+
}
|
|
996
|
+
const s = await parse(p3);
|
|
997
|
+
parsed++;
|
|
998
|
+
cache.files[p3] = { mtimeMs: st.mtimeMs, size: st.size, stats: s };
|
|
999
|
+
stats.push(s);
|
|
1000
|
+
}
|
|
1001
|
+
return { stats, parsed };
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
// ../finops/src/detectors.ts
|
|
1005
|
+
import path12 from "path";
|
|
1006
|
+
|
|
1007
|
+
// ../finops/src/pricing.ts
|
|
1008
|
+
var PRICING_AS_OF = "2026-11-03";
|
|
1009
|
+
var a = (input, output, cacheRead = input / 10) => ({ input, output, cacheRead, cacheWrite: input * 1.25 });
|
|
1010
|
+
var o = (input, output, cacheRead = input / 10) => ({ input, output, cacheRead, cacheWrite: input });
|
|
1011
|
+
var TABLE = [
|
|
1012
|
+
["fable-5-2", a(8, 40, 0.2)],
|
|
1013
|
+
["mythos-5-2", a(8, 40, 0.2)],
|
|
1014
|
+
["fable", a(10, 50)],
|
|
1015
|
+
["mythos", a(10, 50)],
|
|
1016
|
+
["opus-5-5", a(4, 20, 0.2)],
|
|
1017
|
+
["opus-4-1", a(15, 75)],
|
|
1018
|
+
["opus-4-0", a(15, 75)],
|
|
1019
|
+
["opus-4-2025", a(15, 75)],
|
|
1020
|
+
["opus", a(5, 25)],
|
|
1021
|
+
["sonnet-5-5", a(2, 10, 0.1)],
|
|
1022
|
+
["sonnet-5", a(2, 10)],
|
|
1023
|
+
["sonnet", a(3, 15)],
|
|
1024
|
+
["haiku-5-5", a(0.1, 0.5, 0.01)],
|
|
1025
|
+
["haiku-4", a(1, 5)],
|
|
1026
|
+
["haiku", a(0.8, 4)],
|
|
1027
|
+
["gpt-5-nano", o(0.05, 0.4)],
|
|
1028
|
+
["gpt-5-mini", o(0.25, 2)],
|
|
1029
|
+
["gpt-5", o(1.25, 10)],
|
|
1030
|
+
["o4-mini", o(1.1, 4.4, 0.275)],
|
|
1031
|
+
["o3", o(2, 8, 0.5)],
|
|
1032
|
+
["gpt-4.1-mini", o(0.4, 1.6)],
|
|
1033
|
+
["gpt-4.1", o(2, 8, 0.5)],
|
|
1034
|
+
["gpt-4o-mini", o(0.15, 0.6)],
|
|
1035
|
+
["gpt-4o", o(2.5, 10)]
|
|
1036
|
+
];
|
|
1037
|
+
var FALLBACK = a(3, 15);
|
|
1038
|
+
function priceOf(model) {
|
|
1039
|
+
const m = model.toLowerCase();
|
|
1040
|
+
const hit = TABLE.find(([k]) => m.includes(k));
|
|
1041
|
+
return hit ? { price: hit[1], estimated: false } : { price: FALLBACK, estimated: true };
|
|
1042
|
+
}
|
|
1043
|
+
function lighterModel(model) {
|
|
1044
|
+
const m = model.toLowerCase();
|
|
1045
|
+
if (/fable|mythos|opus/.test(m)) return "claude-sonnet-5-5";
|
|
1046
|
+
if (/^o3|gpt-5(\.\d+)?-pro|gpt-5(\.\d+)?$|gpt-5(\.\d+)?-codex$/.test(m)) return "gpt-5-mini";
|
|
1047
|
+
return void 0;
|
|
1048
|
+
}
|
|
1049
|
+
function costOf(model, u) {
|
|
1050
|
+
const { price: p3 } = priceOf(model);
|
|
1051
|
+
const w1h = u.cacheWrite1h ?? 0;
|
|
1052
|
+
return (u.input * p3.input + u.output * p3.output + u.cacheRead * p3.cacheRead + (u.cacheWrite - w1h) * p3.cacheWrite + w1h * p3.input * 2) / 1e6;
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
// ../finops/src/detectors.ts
|
|
1056
|
+
var MCP_SCHEMA_TOKENS = 1500;
|
|
1057
|
+
var SNOWBALL_STEPS = 35;
|
|
1058
|
+
var SNOWBALL_HEAVY_STEPS = 10;
|
|
1059
|
+
var CACHE_HIT_MIN = 0.4;
|
|
1060
|
+
var CACHE_HIT_TARGET = 0.7;
|
|
1061
|
+
var CACHE_MIN_TOKENS = 1e6;
|
|
1062
|
+
var OVERKILL_MAX_STEPS = 2;
|
|
1063
|
+
var OVERKILL_MIN_SESSIONS = 3;
|
|
1064
|
+
var monthly = (usd3, days) => usd3 * 30 / days;
|
|
1065
|
+
var round = (n2) => Math.round(n2 * 100) / 100;
|
|
1066
|
+
var dominant = (sessions) => {
|
|
1067
|
+
const m = {};
|
|
1068
|
+
for (const s of sessions) for (const [k, u] of Object.entries(s.models)) m[k] = (m[k] ?? 0) + u.steps;
|
|
1069
|
+
return Object.entries(m).sort((a2, b) => b[1] - a2[1])[0]?.[0];
|
|
1070
|
+
};
|
|
1071
|
+
var sev = (usd3) => usd3 >= 1 ? "warning" : "info";
|
|
1072
|
+
function unusedMcp({ sessions, days, files, root }) {
|
|
1073
|
+
const out = [];
|
|
1074
|
+
const calls = {};
|
|
1075
|
+
for (const s of sessions) for (const [k, n2] of Object.entries(s.mcpCalls)) calls[k] = (calls[k] ?? 0) + n2;
|
|
1076
|
+
for (const f of files) {
|
|
1077
|
+
if (f.role !== "mcp" || !f.text) continue;
|
|
1078
|
+
for (const hid of f.harnesses) {
|
|
1079
|
+
const hs = sessions.filter((s) => s.harness === hid);
|
|
1080
|
+
if (!hs.length) continue;
|
|
1081
|
+
const steps = hs.reduce((n2, s) => n2 + s.steps, 0);
|
|
1082
|
+
const model = dominant(hs) ?? "claude-sonnet-5-5";
|
|
1083
|
+
const idle = Object.keys(mcpServers(f.path, f.text, root)).filter((name) => !calls[name] && !calls[name.replace(/[^\w]/g, "_")]);
|
|
1084
|
+
if (!idle.length) continue;
|
|
1085
|
+
const schemaTokens = MCP_SCHEMA_TOKENS * idle.length;
|
|
1086
|
+
const usd3 = monthly(schemaTokens * steps * priceOf(model).price.cacheRead / 1e6, days);
|
|
1087
|
+
out.push({
|
|
1088
|
+
ruleId: "FIN_UNUSED_MCP",
|
|
1089
|
+
severity: sev(usd3),
|
|
1090
|
+
message: `${idle.length} MCP server(s) in ${f.rel} were called 0 times in ${days} days across ${steps.toLocaleString("en")} requests: ${idle.join(", ")}`,
|
|
1091
|
+
files: [f.rel],
|
|
1092
|
+
data: { server: idle.join(", "), harness: hid, scope: f.scope, steps, schemaTokens, days },
|
|
1093
|
+
monthlySavingsUsd: round(usd3)
|
|
1094
|
+
});
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
return out;
|
|
1098
|
+
}
|
|
1099
|
+
function modelOverkill({ sessions, days }) {
|
|
1100
|
+
const byModel = /* @__PURE__ */ new Map();
|
|
1101
|
+
for (const s of sessions) {
|
|
1102
|
+
if (s.steps === 0 || s.steps > OVERKILL_MAX_STEPS) continue;
|
|
1103
|
+
for (const [model, u] of Object.entries(s.models)) {
|
|
1104
|
+
const to = lighterModel(model);
|
|
1105
|
+
if (!to) continue;
|
|
1106
|
+
const e = byModel.get(model) ?? { n: 0, cost: 0, cheaper: 0, to };
|
|
1107
|
+
e.n++;
|
|
1108
|
+
e.cost += u.costUsd;
|
|
1109
|
+
e.cheaper += costOf(to, u);
|
|
1110
|
+
byModel.set(model, e);
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
return [...byModel].filter(([, e]) => e.n >= OVERKILL_MIN_SESSIONS).map(([model, e]) => {
|
|
1114
|
+
const usd3 = monthly(e.cost - e.cheaper, days);
|
|
1115
|
+
return {
|
|
1116
|
+
ruleId: "FIN_MODEL_OVERKILL",
|
|
1117
|
+
severity: sev(usd3),
|
|
1118
|
+
message: `${e.n} one-shot sessions ran on ${model}; ${e.to} would handle them`,
|
|
1119
|
+
files: [],
|
|
1120
|
+
data: { model, suggested: e.to, sessions: e.n, costUsd: round(e.cost), days },
|
|
1121
|
+
monthlySavingsUsd: round(usd3)
|
|
1122
|
+
};
|
|
1123
|
+
});
|
|
1124
|
+
}
|
|
1125
|
+
function contextSnowball({ sessions, days }) {
|
|
1126
|
+
const bad = sessions.filter((s) => s.steps > SNOWBALL_STEPS && s.heavySteps >= SNOWBALL_HEAVY_STEPS && s.compactions === 0);
|
|
1127
|
+
if (!bad.length) return [];
|
|
1128
|
+
let usd3 = 0;
|
|
1129
|
+
for (const s of bad) {
|
|
1130
|
+
const model = Object.keys(s.models)[0] ?? "claude-sonnet-5-5";
|
|
1131
|
+
usd3 += s.heavyExcessTokens * priceOf(model).price.cacheRead / 1e6;
|
|
1132
|
+
}
|
|
1133
|
+
usd3 = monthly(usd3, days);
|
|
1134
|
+
const worst = [...bad].sort((a2, b) => b.heavyExcessTokens - a2.heavyExcessTokens)[0];
|
|
1135
|
+
return [
|
|
1136
|
+
{
|
|
1137
|
+
ruleId: "FIN_CONTEXT_SNOWBALL",
|
|
1138
|
+
severity: sev(usd3),
|
|
1139
|
+
message: `${bad.length} session(s) ran >${SNOWBALL_STEPS} steps with 100k+ context and no /clear or /compact`,
|
|
1140
|
+
files: bad.slice(0, 5).map((s) => `session ${path12.basename(s.file, ".jsonl")}`),
|
|
1141
|
+
data: { sessions: bad.length, worstSteps: worst.steps, worstMaxContext: worst.maxContext, days },
|
|
1142
|
+
monthlySavingsUsd: round(usd3)
|
|
1143
|
+
}
|
|
1144
|
+
];
|
|
1145
|
+
}
|
|
1146
|
+
function cacheMiss({ sessions, days }) {
|
|
1147
|
+
const out = [];
|
|
1148
|
+
for (const h of ["claude-code", "codex"]) {
|
|
1149
|
+
const hs = sessions.filter((s) => s.harness === h);
|
|
1150
|
+
let input = 0;
|
|
1151
|
+
let read = 0;
|
|
1152
|
+
let write = 0;
|
|
1153
|
+
for (const s of hs) for (const u of Object.values(s.models)) input += u.input, read += u.cacheRead, write += u.cacheWrite;
|
|
1154
|
+
const total = input + read + write;
|
|
1155
|
+
if (total < CACHE_MIN_TOKENS) continue;
|
|
1156
|
+
const ratio = read / total;
|
|
1157
|
+
if (ratio >= CACHE_HIT_MIN) continue;
|
|
1158
|
+
const p3 = priceOf(dominant(hs) ?? "claude-sonnet-5-5").price;
|
|
1159
|
+
const usd3 = monthly((CACHE_HIT_TARGET - ratio) * total * (p3.input - p3.cacheRead) / 1e6, days);
|
|
1160
|
+
out.push({
|
|
1161
|
+
ruleId: "FIN_CACHE_MISS",
|
|
1162
|
+
severity: sev(usd3),
|
|
1163
|
+
message: `${h} prompt-cache hit ratio is ${Math.round(ratio * 100)}% (healthy: \u2265${CACHE_HIT_MIN * 100}%)`,
|
|
1164
|
+
files: [],
|
|
1165
|
+
data: { harness: h, cacheHitRatio: ratio, totalInputTokens: total, days },
|
|
1166
|
+
monthlySavingsUsd: round(Math.max(0, usd3))
|
|
1167
|
+
});
|
|
1168
|
+
}
|
|
1169
|
+
return out;
|
|
1170
|
+
}
|
|
1171
|
+
var detectors = [unusedMcp, modelOverkill, contextSnowball, cacheMiss];
|
|
1172
|
+
|
|
1173
|
+
// ../finops/src/parsers.ts
|
|
1174
|
+
import fs8 from "fs";
|
|
1175
|
+
import path13 from "path";
|
|
1176
|
+
import readline from "readline";
|
|
1177
|
+
var SNOWBALL_CONTEXT = 1e5;
|
|
1178
|
+
var HEALTHY_CONTEXT = 4e4;
|
|
1179
|
+
var MCP = /^mcp__(.+?)(?:__|$)/;
|
|
1180
|
+
function blank(file2, harness) {
|
|
1181
|
+
return { file: file2, harness, steps: 0, models: {}, mcpCalls: {}, compactions: 0, maxContext: 0, heavySteps: 0, heavyExcessTokens: 0 };
|
|
1182
|
+
}
|
|
1183
|
+
function addStep(s, model, u) {
|
|
1184
|
+
const m = s.models[model] ??= { steps: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, costUsd: 0 };
|
|
1185
|
+
m.steps++;
|
|
1186
|
+
m.input += u.input;
|
|
1187
|
+
m.output += u.output;
|
|
1188
|
+
m.cacheRead += u.cacheRead;
|
|
1189
|
+
m.cacheWrite += u.cacheWrite;
|
|
1190
|
+
m.costUsd += costOf(model, u);
|
|
1191
|
+
s.steps++;
|
|
1192
|
+
const ctx2 = u.input + u.cacheRead + u.cacheWrite;
|
|
1193
|
+
s.maxContext = Math.max(s.maxContext, ctx2);
|
|
1194
|
+
if (ctx2 > SNOWBALL_CONTEXT) s.heavySteps++, s.heavyExcessTokens += ctx2 - HEALTHY_CONTEXT;
|
|
1195
|
+
}
|
|
1196
|
+
var mcp = (s, name) => {
|
|
1197
|
+
const m = typeof name === "string" && MCP.exec(name);
|
|
1198
|
+
if (m) s.mcpCalls[m[1]] = (s.mcpCalls[m[1]] ?? 0) + 1;
|
|
1199
|
+
return Boolean(m);
|
|
1200
|
+
};
|
|
1201
|
+
async function* lines(file2) {
|
|
1202
|
+
const rl = readline.createInterface({ input: fs8.createReadStream(file2), crlfDelay: Infinity });
|
|
1203
|
+
for await (const line of rl) {
|
|
1204
|
+
if (!line) continue;
|
|
1205
|
+
try {
|
|
1206
|
+
yield JSON.parse(line);
|
|
1207
|
+
} catch {
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
var stamp2 = (s, ts) => {
|
|
1212
|
+
if (typeof ts !== "string") return;
|
|
1213
|
+
if (!s.start || ts < s.start) s.start = ts;
|
|
1214
|
+
if (!s.end || ts > s.end) s.end = ts;
|
|
1215
|
+
};
|
|
1216
|
+
async function parseClaude(file2) {
|
|
1217
|
+
const s = blank(file2, "claude-code");
|
|
1218
|
+
const steps = /* @__PURE__ */ new Map();
|
|
1219
|
+
for await (const l of lines(file2)) {
|
|
1220
|
+
stamp2(s, l.timestamp);
|
|
1221
|
+
if (l.type === "system" && l.subtype === "compact_boundary" || l.isCompactSummary) s.compactions++;
|
|
1222
|
+
if (l.type !== "assistant" || !l.message?.usage) continue;
|
|
1223
|
+
const msg = l.message;
|
|
1224
|
+
if (msg.model === "<synthetic>") continue;
|
|
1225
|
+
steps.set(msg.id ?? l.uuid, { model: msg.model ?? "unknown", usage: msg.usage });
|
|
1226
|
+
for (const c of Array.isArray(msg.content) ? msg.content : []) if (c?.type === "tool_use") mcp(s, c.name);
|
|
1227
|
+
}
|
|
1228
|
+
for (const { model, usage: u } of steps.values())
|
|
1229
|
+
addStep(s, model, {
|
|
1230
|
+
input: u.input_tokens ?? 0,
|
|
1231
|
+
output: u.output_tokens ?? 0,
|
|
1232
|
+
cacheRead: u.cache_read_input_tokens ?? 0,
|
|
1233
|
+
cacheWrite: u.cache_creation_input_tokens ?? 0,
|
|
1234
|
+
cacheWrite1h: u.cache_creation?.ephemeral_1h_input_tokens ?? 0
|
|
1235
|
+
});
|
|
1236
|
+
return s;
|
|
1237
|
+
}
|
|
1238
|
+
async function parseCodex(file2) {
|
|
1239
|
+
const s = blank(file2, "codex");
|
|
1240
|
+
let model = "gpt-5";
|
|
1241
|
+
let lastTotal = -1;
|
|
1242
|
+
for await (const l of lines(file2)) {
|
|
1243
|
+
stamp2(s, l.timestamp);
|
|
1244
|
+
const p3 = l.payload ?? {};
|
|
1245
|
+
if (l.type === "turn_context" && typeof p3.model === "string") model = p3.model;
|
|
1246
|
+
else if (l.type === "compacted") s.compactions++;
|
|
1247
|
+
else if (l.type === "response_item" && /function_call|custom_tool_call|mcp_tool_call/.test(p3.type ?? "")) mcp(s, p3.namespace) || mcp(s, p3.name);
|
|
1248
|
+
else if (l.type === "event_msg" && p3.type === "token_count" && p3.info?.last_token_usage) {
|
|
1249
|
+
const total = p3.info.total_token_usage?.total_tokens ?? -2;
|
|
1250
|
+
if (total === lastTotal) continue;
|
|
1251
|
+
lastTotal = total;
|
|
1252
|
+
const u = p3.info.last_token_usage;
|
|
1253
|
+
const cached = u.cached_input_tokens ?? 0;
|
|
1254
|
+
const write = u.cache_write_input_tokens ?? 0;
|
|
1255
|
+
addStep(s, model, { input: Math.max(0, (u.input_tokens ?? 0) - cached - write), output: u.output_tokens ?? 0, cacheRead: cached, cacheWrite: write });
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
return s;
|
|
1259
|
+
}
|
|
1260
|
+
async function parseCursor(file2) {
|
|
1261
|
+
const s = blank(file2, "cursor");
|
|
1262
|
+
for await (const l of lines(file2)) {
|
|
1263
|
+
stamp2(s, l.timestamp);
|
|
1264
|
+
const role = l.role ?? l.message?.role;
|
|
1265
|
+
if (role !== "assistant") continue;
|
|
1266
|
+
s.steps++;
|
|
1267
|
+
const content = l.content ?? l.message?.content;
|
|
1268
|
+
for (const c of Array.isArray(content) ? content : []) if (c?.type === "tool_use" || c?.type === "tool-call") mcp(s, c.name ?? c.toolName);
|
|
1269
|
+
}
|
|
1270
|
+
if (!s.end) {
|
|
1271
|
+
const t2 = fs8.statSync(file2).mtime.toISOString();
|
|
1272
|
+
s.start ??= t2;
|
|
1273
|
+
s.end = t2;
|
|
1274
|
+
}
|
|
1275
|
+
return s;
|
|
1276
|
+
}
|
|
1277
|
+
var LOG_SOURCES = [
|
|
1278
|
+
{ harness: "claude-code", glob: "~/.claude/projects/**/*.jsonl", parse: parseClaude },
|
|
1279
|
+
{ harness: "codex", glob: "~/.codex/sessions/**/rollout-*.jsonl", parse: parseCodex },
|
|
1280
|
+
{ harness: "cursor", glob: "~/.cursor/projects/*/agent-transcripts/*.jsonl", parse: parseCursor }
|
|
1281
|
+
];
|
|
1282
|
+
|
|
1283
|
+
// ../finops/src/index.ts
|
|
1284
|
+
async function loadSessions(days, now = /* @__PURE__ */ new Date()) {
|
|
1285
|
+
const cache = loadCache();
|
|
1286
|
+
const all = [];
|
|
1287
|
+
for (const src of LOG_SOURCES) {
|
|
1288
|
+
const paths = await findFiles(src.glob);
|
|
1289
|
+
all.push(...(await cachedParse(paths, src.parse, cache)).stats);
|
|
1290
|
+
}
|
|
1291
|
+
const live = new Set(all.map((s) => s.file));
|
|
1292
|
+
for (const k of Object.keys(cache.files)) if (!live.has(k)) delete cache.files[k];
|
|
1293
|
+
saveCache(cache);
|
|
1294
|
+
const since = new Date(now.getTime() - days * 864e5).toISOString();
|
|
1295
|
+
return all.filter((s) => (s.end ?? "") >= since);
|
|
1296
|
+
}
|
|
1297
|
+
function buildReport(sessions, { days = 30, root, files }) {
|
|
1298
|
+
const byModel = /* @__PURE__ */ new Map();
|
|
1299
|
+
const byHarness = {};
|
|
1300
|
+
const mcpCalls = {};
|
|
1301
|
+
let cost = 0;
|
|
1302
|
+
let steps = 0;
|
|
1303
|
+
let input = 0;
|
|
1304
|
+
let read = 0;
|
|
1305
|
+
for (const s of sessions) {
|
|
1306
|
+
const h = byHarness[s.harness] ??= { sessions: 0, costUsd: 0 };
|
|
1307
|
+
h.sessions++;
|
|
1308
|
+
steps += s.steps;
|
|
1309
|
+
for (const [k, n2] of Object.entries(s.mcpCalls)) mcpCalls[k] = (mcpCalls[k] ?? 0) + n2;
|
|
1310
|
+
for (const [model, u] of Object.entries(s.models)) {
|
|
1311
|
+
const m = byModel.get(model) ?? { model, steps: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, costUsd: 0 };
|
|
1312
|
+
m.steps += u.steps;
|
|
1313
|
+
m.inputTokens += u.input;
|
|
1314
|
+
m.outputTokens += u.output;
|
|
1315
|
+
m.cacheReadTokens += u.cacheRead;
|
|
1316
|
+
m.cacheWriteTokens += u.cacheWrite;
|
|
1317
|
+
m.costUsd += u.costUsd;
|
|
1318
|
+
byModel.set(model, m);
|
|
1319
|
+
h.costUsd += u.costUsd;
|
|
1320
|
+
cost += u.costUsd;
|
|
1321
|
+
input += u.input + u.cacheWrite;
|
|
1322
|
+
read += u.cacheRead;
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
const findings = detectors.flatMap((d2) => d2({ sessions, days, files, root }));
|
|
1326
|
+
return FinOpsReport.parse({
|
|
1327
|
+
periodDays: days,
|
|
1328
|
+
sessions: sessions.length,
|
|
1329
|
+
steps,
|
|
1330
|
+
costUsd: cost,
|
|
1331
|
+
monthlyRunRateUsd: cost * 30 / days,
|
|
1332
|
+
cacheHitRatio: input + read ? read / (input + read) : null,
|
|
1333
|
+
byHarness,
|
|
1334
|
+
byModel: [...byModel.values()].sort((a2, b) => b.costUsd - a2.costUsd),
|
|
1335
|
+
mcpCalls,
|
|
1336
|
+
findings,
|
|
1337
|
+
potentialMonthlySavingsUsd: findings.reduce((n2, f) => n2 + (f.monthlySavingsUsd ?? 0), 0),
|
|
1338
|
+
pricingAsOf: PRICING_AS_OF
|
|
1339
|
+
});
|
|
1340
|
+
}
|
|
1341
|
+
async function analyze(opts) {
|
|
1342
|
+
const days = opts.days ?? 30;
|
|
1343
|
+
return buildReport(await loadSessions(days, opts.now), { ...opts, days });
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
// ../harnesses/src/index.ts
|
|
1347
|
+
var p = (x) => HarnessProfile.parse(x);
|
|
1348
|
+
var harnesses = [
|
|
1349
|
+
p({
|
|
1350
|
+
id: "claude-code",
|
|
1351
|
+
name: "Claude Code",
|
|
1352
|
+
contextLimit: 2e5,
|
|
1353
|
+
files: {
|
|
1354
|
+
instructions: { project: ["CLAUDE.md", "CLAUDE.local.md", ".claude/CLAUDE.md"], global: ["~/.claude/CLAUDE.md"] },
|
|
1355
|
+
rules: { project: [".claude/rules/**/*.md"], global: ["~/.claude/rules/**/*.md"] },
|
|
1356
|
+
skill: { project: [".claude/skills/*/SKILL.md"], global: ["~/.claude/skills/*/SKILL.md"] },
|
|
1357
|
+
mcp: { project: [".mcp.json"], global: ["~/.claude.json"] }
|
|
1358
|
+
},
|
|
1359
|
+
syntax: ["@import"],
|
|
1360
|
+
logs: ["~/.claude/projects/**/*.jsonl"]
|
|
1361
|
+
}),
|
|
1362
|
+
p({
|
|
1363
|
+
id: "cursor",
|
|
1364
|
+
name: "Cursor",
|
|
1365
|
+
contextLimit: 2e5,
|
|
1366
|
+
files: {
|
|
1367
|
+
instructions: { project: [".cursorrules"] },
|
|
1368
|
+
rules: { project: [".cursor/rules/**/*.mdc"] },
|
|
1369
|
+
mcp: { project: [".cursor/mcp.json"], global: ["~/.cursor/mcp.json"] }
|
|
1370
|
+
},
|
|
1371
|
+
syntax: ["alwaysApply", "globs", "description"],
|
|
1372
|
+
ignoreFile: ".cursorignore",
|
|
1373
|
+
logs: ["~/.cursor/projects/*/agent-transcripts/*.jsonl"]
|
|
1374
|
+
}),
|
|
1375
|
+
p({
|
|
1376
|
+
id: "windsurf",
|
|
1377
|
+
name: "Windsurf",
|
|
1378
|
+
contextLimit: 2e5,
|
|
1379
|
+
files: {
|
|
1380
|
+
instructions: { project: [".windsurfrules"], global: ["~/.codeium/windsurf/memories/global_rules.md"] },
|
|
1381
|
+
rules: { project: [".windsurf/rules/**/*.md"] },
|
|
1382
|
+
mcp: { global: ["~/.codeium/windsurf/mcp_config.json"] }
|
|
1383
|
+
},
|
|
1384
|
+
syntax: ["trigger", "globs", "description"],
|
|
1385
|
+
ignoreFile: ".codeiumignore"
|
|
1386
|
+
}),
|
|
1387
|
+
p({
|
|
1388
|
+
id: "codex",
|
|
1389
|
+
name: "Codex CLI",
|
|
1390
|
+
contextLimit: 272e3,
|
|
1391
|
+
files: {
|
|
1392
|
+
instructions: { project: ["AGENTS.md", "AGENTS.override.md"], global: ["~/.codex/AGENTS.md"] },
|
|
1393
|
+
mcp: { global: ["~/.codex/config.toml"] }
|
|
1394
|
+
},
|
|
1395
|
+
syntax: [],
|
|
1396
|
+
logs: ["~/.codex/sessions/**/rollout-*.jsonl"]
|
|
1397
|
+
}),
|
|
1398
|
+
p({
|
|
1399
|
+
id: "opencode",
|
|
1400
|
+
name: "OpenCode",
|
|
1401
|
+
contextLimit: 2e5,
|
|
1402
|
+
files: {
|
|
1403
|
+
instructions: { project: ["AGENTS.md"], global: ["~/.config/opencode/AGENTS.md"] },
|
|
1404
|
+
mcp: { project: ["opencode.json"], global: ["~/.config/opencode/opencode.json"] }
|
|
1405
|
+
},
|
|
1406
|
+
syntax: []
|
|
1407
|
+
}),
|
|
1408
|
+
p({
|
|
1409
|
+
id: "copilot",
|
|
1410
|
+
name: "GitHub Copilot",
|
|
1411
|
+
contextLimit: 128e3,
|
|
1412
|
+
files: {
|
|
1413
|
+
instructions: { project: [".github/copilot-instructions.md"] },
|
|
1414
|
+
rules: { project: [".github/instructions/**/*.instructions.md"] },
|
|
1415
|
+
mcp: { project: [".vscode/mcp.json"] }
|
|
1416
|
+
},
|
|
1417
|
+
syntax: ["applyTo"]
|
|
1418
|
+
}),
|
|
1419
|
+
p({
|
|
1420
|
+
id: "cline",
|
|
1421
|
+
name: "Cline",
|
|
1422
|
+
contextLimit: 2e5,
|
|
1423
|
+
files: { instructions: { project: [".clinerules"] }, rules: { project: [".clinerules/**/*.md"] } },
|
|
1424
|
+
syntax: []
|
|
1425
|
+
})
|
|
1426
|
+
];
|
|
1427
|
+
|
|
1428
|
+
// ../clinical/src/engine.ts
|
|
1429
|
+
var VERSION = true ? "0.1.0" : "0.0.0-dev";
|
|
1430
|
+
var TRIAGE = { critical: "resuscitation", warning: "therapy", info: "preventive" };
|
|
1431
|
+
var ORDER = ["resuscitation", "therapy", "preventive"];
|
|
1432
|
+
var human = (k) => k.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());
|
|
1433
|
+
function vitals(f) {
|
|
1434
|
+
const out = [];
|
|
1435
|
+
if (f.files.length) out.push({ label: "Files", value: f.files.slice(0, 3).join(", ") + (f.files.length > 3 ? ` +${f.files.length - 3}` : "") });
|
|
1436
|
+
for (const [k, v] of Object.entries(f.data)) {
|
|
1437
|
+
if (typeof v === "number")
|
|
1438
|
+
out.push({
|
|
1439
|
+
label: human(k),
|
|
1440
|
+
value: /ratio|similarity|share/i.test(k) ? `${Math.round(v * 100)}%` : /usd/i.test(k) ? `$${v.toFixed(2)}` : v.toLocaleString("en")
|
|
1441
|
+
});
|
|
1442
|
+
else if (typeof v === "string" || typeof v === "boolean") out.push({ label: human(k), value: String(v) });
|
|
1443
|
+
else if (k === "hits" && Array.isArray(v))
|
|
1444
|
+
out.push({ label: "Secrets", value: v.map((h) => `${h.kind} ${h.masked} (line ${h.line})`).join("; ") });
|
|
1445
|
+
}
|
|
1446
|
+
if (f.monthlySavingsUsd) out.push({ label: "Savings", value: `$${f.monthlySavingsUsd.toFixed(2)}/mo` });
|
|
1447
|
+
return out;
|
|
1448
|
+
}
|
|
1449
|
+
function diagnose(findings, lang, anamnesis = Anamnesis.parse({})) {
|
|
1450
|
+
const cat = cards(lang);
|
|
1451
|
+
const weight = (f) => {
|
|
1452
|
+
const gain = healthGain(findings, f);
|
|
1453
|
+
const usd3 = f.monthlySavingsUsd ?? 0;
|
|
1454
|
+
return anamnesis.priority === "economy" ? usd3 * 10 + gain : anamnesis.priority === "quality" ? gain * 10 + usd3 : gain + usd3 / 5;
|
|
1455
|
+
};
|
|
1456
|
+
const sorted = [...findings].sort(
|
|
1457
|
+
(a2, b) => ORDER.indexOf(TRIAGE[a2.severity]) - ORDER.indexOf(TRIAGE[b.severity]) || weight(b) - weight(a2) || a2.message.localeCompare(b.message)
|
|
1458
|
+
);
|
|
1459
|
+
return sorted.map((f, i) => {
|
|
1460
|
+
const id = `RX-${String(i + 1).padStart(2, "0")}`;
|
|
1461
|
+
const card2 = cat[f.ruleId];
|
|
1462
|
+
return {
|
|
1463
|
+
code: f.ruleId,
|
|
1464
|
+
triage: TRIAGE[f.severity],
|
|
1465
|
+
diagnosis: card2.name,
|
|
1466
|
+
summary: f.message,
|
|
1467
|
+
vitals: vitals(f),
|
|
1468
|
+
prognosis: card2.prognosis(f),
|
|
1469
|
+
rx: {
|
|
1470
|
+
id,
|
|
1471
|
+
action: card2.action(f),
|
|
1472
|
+
command: f.fix ? `ctxmedic treat ${id}` : void 0,
|
|
1473
|
+
autoFix: Boolean(f.fix),
|
|
1474
|
+
healthGain: healthGain(findings, f),
|
|
1475
|
+
monthlySavingsUsd: f.monthlySavingsUsd
|
|
1476
|
+
},
|
|
1477
|
+
files: f.files,
|
|
1478
|
+
finding: f
|
|
1479
|
+
};
|
|
1480
|
+
});
|
|
1481
|
+
}
|
|
1482
|
+
async function checkup(opts) {
|
|
1483
|
+
const ex = await examine(opts.root, harnesses, { global: opts.global });
|
|
1484
|
+
let finops = null;
|
|
1485
|
+
if (opts.finops !== false) finops = await analyze({ root: ex.vitals.root, files: ex.files, days: opts.days ?? 30 });
|
|
1486
|
+
const findings = [...ex.findings, ...finops?.findings ?? []];
|
|
1487
|
+
const diagnoses = diagnose(findings, opts.lang, loadAnamnesis());
|
|
1488
|
+
const score = healthScore(findings);
|
|
1489
|
+
const counts = { resuscitation: 0, therapy: 0, preventive: 0 };
|
|
1490
|
+
for (const d2 of diagnoses) counts[d2.triage]++;
|
|
1491
|
+
const savings = findings.reduce((n2, f) => n2 + (f.monthlySavingsUsd ?? 0), 0);
|
|
1492
|
+
const previous = loadHistory(ex.vitals.root).at(-1) ?? null;
|
|
1493
|
+
const report2 = ClinicalReport.parse({
|
|
1494
|
+
tool: "ctxmedic",
|
|
1495
|
+
version: VERSION,
|
|
1496
|
+
lang: opts.lang,
|
|
1497
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1498
|
+
patient: ex.vitals,
|
|
1499
|
+
healthScore: score,
|
|
1500
|
+
previous,
|
|
1501
|
+
opinion: diagnoses.length ? t(opts.lang).opinion(score) : t(opts.lang).healthy,
|
|
1502
|
+
counts,
|
|
1503
|
+
diagnoses,
|
|
1504
|
+
finops,
|
|
1505
|
+
potentialMonthlySavingsUsd: Math.round(savings * 100) / 100
|
|
1506
|
+
});
|
|
1507
|
+
if (opts.record !== false)
|
|
1508
|
+
recordVisit({
|
|
1509
|
+
at: report2.generatedAt,
|
|
1510
|
+
root: ex.vitals.root,
|
|
1511
|
+
healthScore: score,
|
|
1512
|
+
counts,
|
|
1513
|
+
monthlySpendUsd: finops?.monthlyRunRateUsd,
|
|
1514
|
+
potentialMonthlySavingsUsd: report2.potentialMonthlySavingsUsd
|
|
1515
|
+
});
|
|
1516
|
+
return report2;
|
|
1517
|
+
}
|
|
1518
|
+
async function treat(rxId, opts) {
|
|
1519
|
+
const report2 = await checkup({ ...opts, record: false });
|
|
1520
|
+
const dx = report2.diagnoses.find((d2) => d2.rx.id === rxId.toUpperCase());
|
|
1521
|
+
if (!dx) throw new FixRefusedError(`${rxId} not found; run \`ctxmedic checkup\` to see current prescriptions`);
|
|
1522
|
+
if (!dx.finding.fix) return { diagnosis: dx, manual: dx.rx.action };
|
|
1523
|
+
const result = await applyFix(dx.finding.fix, { root: opts.root, dryRun: opts.dryRun, force: opts.force, global: opts.global });
|
|
1524
|
+
return { diagnosis: dx, result };
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
// ../clinical/src/ai.ts
|
|
1528
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
1529
|
+
var OLLAMA = process.env.OLLAMA_HOST ?? "http://127.0.0.1:11434";
|
|
1530
|
+
var MAX_CHARS = 12e4;
|
|
1531
|
+
var SYSTEM = `You are a senior reviewer of AI coding-agent configuration (CLAUDE.md, AGENTS.md, Cursor rules, skills).
|
|
1532
|
+
Find: (1) rules that contradict each other, (2) outdated prompt workarounds written for older models (ALL-CAPS threats, "you are an expert", repeated "IMPORTANT"), (3) vague rules an agent cannot act on.
|
|
1533
|
+
Answer as a short list. For each item: the file(s), the problem in one sentence, the fix in one sentence. If nothing is wrong, say so.`;
|
|
1534
|
+
async function detectProvider() {
|
|
1535
|
+
try {
|
|
1536
|
+
const r = await fetch(`${OLLAMA}/api/tags`, { signal: AbortSignal.timeout(800) });
|
|
1537
|
+
if (r.ok) return "ollama";
|
|
1538
|
+
} catch {
|
|
1539
|
+
}
|
|
1540
|
+
if (process.env.ANTHROPIC_API_KEY) return "anthropic";
|
|
1541
|
+
if (process.env.OPENAI_API_KEY) return "openai";
|
|
1542
|
+
return void 0;
|
|
1543
|
+
}
|
|
1544
|
+
async function buildConsultPrompt(root, report2) {
|
|
1545
|
+
const ex = await examine(root, harnesses);
|
|
1546
|
+
const docs = ex.files.filter((f) => f.text && (f.role === "instructions" || f.role === "rules" || f.role === "skill")).map((f) => `<file path="${f.rel}">
|
|
1547
|
+
${redactSecrets(f.text)}
|
|
1548
|
+
</file>`).join("\n\n");
|
|
1549
|
+
const known = report2.diagnoses.map((d2) => `- [${d2.code}] ${d2.summary}`).join("\n") || "- none";
|
|
1550
|
+
return `Static checks already found:
|
|
1551
|
+
${known}
|
|
1552
|
+
|
|
1553
|
+
Configuration files:
|
|
1554
|
+
${docs}`.slice(0, MAX_CHARS);
|
|
1555
|
+
}
|
|
1556
|
+
async function askAi(provider, prompt) {
|
|
1557
|
+
if (provider === "ollama") {
|
|
1558
|
+
const r2 = await fetch(`${OLLAMA}/api/chat`, {
|
|
1559
|
+
method: "POST",
|
|
1560
|
+
body: JSON.stringify({
|
|
1561
|
+
model: process.env.CTXMEDIC_OLLAMA_MODEL ?? "llama3.1",
|
|
1562
|
+
stream: false,
|
|
1563
|
+
messages: [
|
|
1564
|
+
{ role: "system", content: SYSTEM },
|
|
1565
|
+
{ role: "user", content: prompt }
|
|
1566
|
+
]
|
|
1567
|
+
})
|
|
1568
|
+
});
|
|
1569
|
+
if (!r2.ok) throw new Error(`Ollama: HTTP ${r2.status}`);
|
|
1570
|
+
return (await r2.json()).message?.content ?? "";
|
|
1571
|
+
}
|
|
1572
|
+
if (provider === "anthropic") {
|
|
1573
|
+
const client = new Anthropic();
|
|
1574
|
+
const res = await client.messages.create({
|
|
1575
|
+
model: process.env.CTXMEDIC_AI_MODEL ?? "claude-opus-5-5",
|
|
1576
|
+
max_tokens: 16e3,
|
|
1577
|
+
system: SYSTEM,
|
|
1578
|
+
messages: [{ role: "user", content: prompt }]
|
|
1579
|
+
});
|
|
1580
|
+
if (res.stop_reason === "refusal") return "The model declined to review this configuration.";
|
|
1581
|
+
return res.content.flatMap((b) => b.type === "text" ? [b.text] : []).join("\n");
|
|
1582
|
+
}
|
|
1583
|
+
const r = await fetch("https://api.openai.com/v1/chat/completions", {
|
|
1584
|
+
method: "POST",
|
|
1585
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${process.env.OPENAI_API_KEY}` },
|
|
1586
|
+
body: JSON.stringify({
|
|
1587
|
+
model: process.env.CTXMEDIC_AI_MODEL ?? "gpt-5-mini",
|
|
1588
|
+
messages: [
|
|
1589
|
+
{ role: "system", content: SYSTEM },
|
|
1590
|
+
{ role: "user", content: prompt }
|
|
1591
|
+
]
|
|
1592
|
+
})
|
|
1593
|
+
});
|
|
1594
|
+
if (!r.ok) throw new Error(`OpenAI: HTTP ${r.status}`);
|
|
1595
|
+
return (await r.json()).choices?.[0]?.message?.content ?? "";
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
// ../server/src/index.ts
|
|
1599
|
+
import crypto from "crypto";
|
|
1600
|
+
import fs9 from "fs";
|
|
1601
|
+
import path14 from "path";
|
|
1602
|
+
import { serve } from "@hono/node-server";
|
|
1603
|
+
import { serveStatic } from "@hono/node-server/serve-static";
|
|
1604
|
+
import { Hono } from "hono";
|
|
1605
|
+
function createApp(opts) {
|
|
1606
|
+
const app = new Hono();
|
|
1607
|
+
const root = path14.resolve(opts.root);
|
|
1608
|
+
app.use("/api/*", async (c, next) => {
|
|
1609
|
+
c.header("cache-control", "no-store");
|
|
1610
|
+
if (c.req.method !== "GET" && c.req.header("x-ctxmedic-token") !== opts.token) return c.json({ error: "invalid session token" }, 403);
|
|
1611
|
+
await next();
|
|
1612
|
+
});
|
|
1613
|
+
app.get("/api/checkup", async (c) => {
|
|
1614
|
+
const lang = c.req.query("lang") ? resolveLang(c.req.query("lang")) : opts.lang;
|
|
1615
|
+
return c.json(await checkup({ root, lang, days: opts.days, record: c.req.query("record") === "1" }));
|
|
1616
|
+
});
|
|
1617
|
+
app.get("/api/history", (c) => c.json(loadHistory(root)));
|
|
1618
|
+
app.get("/api/graph", async (c) => {
|
|
1619
|
+
const ex = await examine(root, harnesses);
|
|
1620
|
+
const nodes = [
|
|
1621
|
+
...ex.vitals.harnesses.map((h) => ({ id: `h:${h}`, kind: "harness", label: harnesses.find((x) => x.id === h)?.name ?? h })),
|
|
1622
|
+
...ex.files.map((f) => ({ id: f.path, kind: f.role, label: f.rel, tokens: f.tokens, broken: f.broken || f.loop, scope: f.scope }))
|
|
1623
|
+
];
|
|
1624
|
+
const edges = [];
|
|
1625
|
+
for (const f of ex.files) {
|
|
1626
|
+
for (const h of f.harnesses) edges.push({ source: `h:${h}`, target: f.path, kind: "loads" });
|
|
1627
|
+
if (f.isSymlink && f.realpath) {
|
|
1628
|
+
if (!nodes.some((n2) => n2.id === f.realpath)) nodes.push({ id: f.realpath, kind: "target", label: path14.relative(root, f.realpath), tokens: f.tokens, broken: false, scope: f.scope });
|
|
1629
|
+
edges.push({ source: f.path, target: f.realpath, kind: "symlink" });
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
const docs = ex.files.filter((f) => f.role === "instructions" && f.text && !f.isSymlink);
|
|
1633
|
+
for (let i = 0; i < docs.length; i++)
|
|
1634
|
+
for (let j = i + 1; j < docs.length; j++)
|
|
1635
|
+
if (similarity(docs[i].text, docs[j].text) > 0.75) edges.push({ source: docs[i].path, target: docs[j].path, kind: "duplicate" });
|
|
1636
|
+
return c.json({ nodes, edges });
|
|
1637
|
+
});
|
|
1638
|
+
app.post("/api/treat/:rx", async (c) => {
|
|
1639
|
+
const dryRun = c.req.query("dryRun") === "1";
|
|
1640
|
+
try {
|
|
1641
|
+
const r = await treat(c.req.param("rx"), { root, lang: opts.lang, days: opts.days, dryRun });
|
|
1642
|
+
return c.json({ rx: r.diagnosis.rx.id, applied: r.result?.applied ?? [], backupDir: r.result?.backupDir, dryRun, manual: r.manual });
|
|
1643
|
+
} catch (e) {
|
|
1644
|
+
return c.json({ error: e.message }, e instanceof FixRefusedError ? 409 : 500);
|
|
1645
|
+
}
|
|
1646
|
+
});
|
|
1647
|
+
if (opts.publicDir && fs9.existsSync(path14.join(opts.publicDir, "index.html"))) {
|
|
1648
|
+
const rel = path14.relative(process.cwd(), opts.publicDir) || ".";
|
|
1649
|
+
app.use("/*", serveStatic({ root: rel }));
|
|
1650
|
+
app.get("*", serveStatic({ path: path14.join(rel, "index.html") }));
|
|
1651
|
+
} else app.get("/", (c) => c.text("ctxmedic UI is not built. Run `pnpm build` in the repository."));
|
|
1652
|
+
return app;
|
|
1653
|
+
}
|
|
1654
|
+
async function startServer(opts) {
|
|
1655
|
+
const token = crypto.randomBytes(16).toString("hex");
|
|
1656
|
+
const app = createApp({ ...opts, token });
|
|
1657
|
+
return new Promise((resolve) => {
|
|
1658
|
+
const server = serve(
|
|
1659
|
+
{ fetch: app.fetch, hostname: "127.0.0.1", port: opts.port ?? 7337 },
|
|
1660
|
+
(info) => resolve({ url: `http://127.0.0.1:${info.port}/#token=${token}`, close: () => server.close() })
|
|
1661
|
+
);
|
|
1662
|
+
});
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
// src/render.ts
|
|
1666
|
+
import pc from "picocolors";
|
|
1667
|
+
var COLOR = { resuscitation: pc.red, therapy: pc.yellow, preventive: pc.green };
|
|
1668
|
+
var usd2 = (n2) => `$${n2.toFixed(2)}`;
|
|
1669
|
+
function wrap(text2, width, indent) {
|
|
1670
|
+
const words = text2.split(/\s+/);
|
|
1671
|
+
const lines2 = [];
|
|
1672
|
+
let line = "";
|
|
1673
|
+
for (const w of words) {
|
|
1674
|
+
if ((line + " " + w).trim().length > width) lines2.push(line.trim()), line = "";
|
|
1675
|
+
line += " " + w;
|
|
1676
|
+
}
|
|
1677
|
+
if (line.trim()) lines2.push(line.trim());
|
|
1678
|
+
return lines2.join("\n" + indent);
|
|
1679
|
+
}
|
|
1680
|
+
function bar(score) {
|
|
1681
|
+
const full = Math.round(score / 5);
|
|
1682
|
+
const color = score >= 90 ? pc.green : score >= 70 ? pc.yellow : pc.red;
|
|
1683
|
+
return color("\u2588".repeat(full)) + pc.dim("\u2591".repeat(20 - full));
|
|
1684
|
+
}
|
|
1685
|
+
function card(d2, lang) {
|
|
1686
|
+
const tx = t(lang);
|
|
1687
|
+
const c = COLOR[d2.triage];
|
|
1688
|
+
const side = c("\u2502");
|
|
1689
|
+
const w = Math.min(process.stdout.columns ?? 100, 110) - 16;
|
|
1690
|
+
const label = (s) => pc.dim(s.padEnd(11));
|
|
1691
|
+
const out = [
|
|
1692
|
+
c("\u256D\u2500 ") + c(pc.bold(`${tx.triage[d2.triage]} \xB7 ${d2.rx.id}`)) + " " + pc.bold(d2.diagnosis) + pc.dim(` [${d2.code}]`),
|
|
1693
|
+
`${side} ${wrap(d2.summary, w + 11, `${side} `)}`
|
|
1694
|
+
];
|
|
1695
|
+
d2.vitals.forEach((v, i) => out.push(`${side} ${label(i === 0 ? tx.labs.split(" ")[0] : "")}${pc.cyan(v.label)}: ${wrap(v.value, w - v.label.length, `${side} ${" ".repeat(11)}`)}`));
|
|
1696
|
+
out.push(`${side} ${label(tx.prognosis)}${wrap(d2.prognosis, w, `${side} ${" ".repeat(11)}`)}`);
|
|
1697
|
+
const gains = [d2.rx.healthGain ? pc.green(`+${d2.rx.healthGain} health`) : "", d2.rx.monthlySavingsUsd ? pc.green(`${usd2(d2.rx.monthlySavingsUsd)}${tx.perMonth}`) : ""].filter(Boolean).join(", ");
|
|
1698
|
+
out.push(`${side} ${label("Rx")}${wrap(d2.rx.action, w, `${side} ${" ".repeat(11)}`)}${gains ? ` ${pc.dim("(")}${gains}${pc.dim(")")}` : ""}`);
|
|
1699
|
+
out.push(`${side} ${" ".repeat(11)}${d2.rx.command ? pc.bold(pc.magenta(`\u2192 ${d2.rx.command}`)) : pc.dim(tx.manual)}`);
|
|
1700
|
+
out.push(c("\u2570\u2500"));
|
|
1701
|
+
return out.join("\n");
|
|
1702
|
+
}
|
|
1703
|
+
function finopsSummary(f, lang) {
|
|
1704
|
+
const tx = t(lang);
|
|
1705
|
+
if (!f.sessions) return pc.dim(tx.noLogs);
|
|
1706
|
+
const top = f.byModel.slice(0, 4).map((m) => `${m.model} ${usd2(m.costUsd)}`).join(pc.dim(" \xB7 "));
|
|
1707
|
+
return [
|
|
1708
|
+
`${pc.bold("FinOps")} ${pc.dim(`(${f.periodDays}d, ${f.sessions} sessions, ${f.steps.toLocaleString("en")} requests, prices as of ${f.pricingAsOf})`)}`,
|
|
1709
|
+
` ${tx.spend}: ${pc.bold(usd2(f.costUsd))} \xB7 ${tx.runRate} ${usd2(f.monthlyRunRateUsd)}${tx.perMonth} \xB7 cache hit ${f.cacheHitRatio === null ? "n/a" : `${Math.round(f.cacheHitRatio * 100)}%`}`,
|
|
1710
|
+
top ? ` ${top}` : ""
|
|
1711
|
+
].filter(Boolean).join("\n");
|
|
1712
|
+
}
|
|
1713
|
+
function header(r) {
|
|
1714
|
+
const tx = t(r.lang);
|
|
1715
|
+
const delta = r.previous ? r.healthScore - r.previous.healthScore : null;
|
|
1716
|
+
const trend = delta === null ? "" : pc.dim(` (${tx.since(delta)})`);
|
|
1717
|
+
return [
|
|
1718
|
+
"",
|
|
1719
|
+
pc.bold(`\u{1FA7A} ctxmedic ${r.version}`) + pc.dim(` \xB7 ${r.patient.root}`),
|
|
1720
|
+
pc.dim(` ${r.patient.filesScanned} files \xB7 ${r.patient.harnesses.join(", ") || "no AI harness detected"}`),
|
|
1721
|
+
"",
|
|
1722
|
+
` ${tx.health}: ${bar(r.healthScore)} ${pc.bold(String(r.healthScore))}/100${trend}`,
|
|
1723
|
+
` ${pc.italic(r.opinion)}`,
|
|
1724
|
+
` ${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))}` : ""),
|
|
1725
|
+
""
|
|
1726
|
+
].join("\n");
|
|
1727
|
+
}
|
|
1728
|
+
function report(r) {
|
|
1729
|
+
return [header(r), ...r.diagnoses.map((d2) => card(d2, r.lang) + "\n"), r.finops ? finopsSummary(r.finops, r.lang) : ""].join("\n");
|
|
1730
|
+
}
|
|
1731
|
+
function history(visits) {
|
|
1732
|
+
if (!visits.length) return pc.dim("No visits yet. Run `ctxmedic checkup`.");
|
|
1733
|
+
return visits.slice(-20).map((v) => `${v.at.slice(0, 16).replace("T", " ")} ${bar(v.healthScore)} ${String(v.healthScore).padStart(3)} \u{1F534}${v.counts.resuscitation} \u{1F7E1}${v.counts.therapy} \u{1F7E2}${v.counts.preventive} ${pc.dim(v.root)}`).join("\n");
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
// src/index.ts
|
|
1737
|
+
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");
|
|
1738
|
+
var ctx = (dir, o2) => ({
|
|
1739
|
+
root: path15.resolve(dir ?? "."),
|
|
1740
|
+
lang: resolveLang(o2.lang),
|
|
1741
|
+
days: Math.max(1, Number.parseInt(o2.days, 10) || 30),
|
|
1742
|
+
finops: o2.finops,
|
|
1743
|
+
global: o2.global
|
|
1744
|
+
});
|
|
1745
|
+
function fail(e) {
|
|
1746
|
+
console.error(pc2.red(`\u2716 ${e instanceof FixRefusedError ? e.message : e.stack ?? e}`));
|
|
1747
|
+
process.exit(2);
|
|
1748
|
+
}
|
|
1749
|
+
var program = new Command().name("ctxmedic").description("The context medic for your AI coding setup: checkup, treat, savings.").version(VERSION);
|
|
1750
|
+
common(program.command("checkup [path]").description("examine AI configs and session logs, print clinical cards")).option("--json", "print the full report as JSON").action(async (dir, o2) => {
|
|
1751
|
+
const r = await checkup(ctx(dir, o2)).catch(fail);
|
|
1752
|
+
console.log(o2.json ? JSON.stringify(r, null, 2) : report(r));
|
|
1753
|
+
if (r.counts.resuscitation > 0) process.exitCode = 1;
|
|
1754
|
+
});
|
|
1755
|
+
common(program.command("treat [rx]").description("apply a prescription (e.g. RX-01), or --all auto-fixes")).option("--all", "apply every auto-fixable prescription").option("--dry-run", "show what would change without writing").option("--force", "allow changes to files with uncommitted git edits").option("-y, --yes", "do not ask for confirmation").action(async (rx, o2) => {
|
|
1756
|
+
const c = ctx(void 0, o2);
|
|
1757
|
+
if (!rx && !o2.all) fail(new FixRefusedError("name a prescription (ctxmedic treat RX-01) or pass --all"));
|
|
1758
|
+
const report2 = await checkup({ ...c, record: false }).catch(fail);
|
|
1759
|
+
const picked = o2.all ? report2.diagnoses.filter((d2) => d2.rx.autoFix) : report2.diagnoses.filter((d2) => d2.rx.id === rx.toUpperCase());
|
|
1760
|
+
if (!picked.length) fail(new FixRefusedError(o2.all ? "nothing to auto-fix" : `${rx} not found; run \`ctxmedic checkup\``));
|
|
1761
|
+
for (const d2 of picked) console.log(card(d2, c.lang) + "\n");
|
|
1762
|
+
const manual = picked.filter((d2) => !d2.rx.autoFix);
|
|
1763
|
+
const m = messages(c.lang).cli;
|
|
1764
|
+
if (manual.length === picked.length) return console.log(pc2.yellow(m.noAutoFix));
|
|
1765
|
+
const plans = picked.flatMap((d2) => d2.finding.fix ? [d2.finding.fix] : []);
|
|
1766
|
+
for (const plan of plans) for (const op of plan.ops) console.log(pc2.dim(` ${op.kind === "write" ? "write " : "symlink"} ${path15.relative(c.root, op.path)}${op.kind === "symlink" ? ` \u2192 ${op.target}` : ""}`));
|
|
1767
|
+
if (!o2.dryRun && !o2.yes) {
|
|
1768
|
+
const ok = await p2.confirm({ message: m.confirmApply });
|
|
1769
|
+
if (p2.isCancel(ok) || !ok) return p2.cancel(m.cancelled);
|
|
1770
|
+
}
|
|
1771
|
+
for (const plan of plans) {
|
|
1772
|
+
const res = await applyFix(plan, { root: c.root, dryRun: o2.dryRun, force: o2.force, global: false }).catch(fail);
|
|
1773
|
+
console.log(`${o2.dryRun ? pc2.yellow("dry-run") : pc2.green("\u2714")} ${plan.title}${res.dryRun ? "" : pc2.dim(` backup: ${path15.relative(c.root, res.backupDir)}`)}`);
|
|
1774
|
+
}
|
|
1775
|
+
});
|
|
1776
|
+
common(program.command("savings [path]").description("FinOps: token spend, cache hit ratio and savings prescriptions")).option("--json", "print the FinOps report as JSON").action(async (dir, o2) => {
|
|
1777
|
+
const c = ctx(dir, o2);
|
|
1778
|
+
const ex = await examine(c.root, harnesses, { global: c.global });
|
|
1779
|
+
const f = await analyze({ root: c.root, files: ex.files, days: c.days }).catch(fail);
|
|
1780
|
+
if (o2.json) return console.log(JSON.stringify(f, null, 2));
|
|
1781
|
+
console.log("\n" + finopsSummary(f, c.lang) + "\n");
|
|
1782
|
+
const r = await checkup({ ...c, record: false });
|
|
1783
|
+
for (const d2 of r.diagnoses.filter((d3) => d3.code.startsWith("FIN_"))) console.log(card(d2, c.lang) + "\n");
|
|
1784
|
+
console.log(pc2.bold(`Total: ${pc2.green(`$${f.potentialMonthlySavingsUsd.toFixed(2)}/mo`)}`));
|
|
1785
|
+
});
|
|
1786
|
+
common(program.command("consult [path]").description("interactive appointment: anamnesis, personal treatment plan, optional AI review")).option("--ai", "ask an LLM (local Ollama, or your Anthropic/OpenAI key) to look for contradictions").action(async (dir, o2) => {
|
|
1787
|
+
const c = ctx(dir, o2);
|
|
1788
|
+
const m = messages(c.lang).cli;
|
|
1789
|
+
p2.intro(pc2.bold(m.consultTitle));
|
|
1790
|
+
const prev = loadAnamnesis();
|
|
1791
|
+
const priority = await p2.select({
|
|
1792
|
+
message: m.askPriority,
|
|
1793
|
+
initialValue: prev.priority,
|
|
1794
|
+
options: ["economy", "balanced", "quality"].map((value) => ({ value, label: m.priority[value] }))
|
|
1795
|
+
});
|
|
1796
|
+
if (p2.isCancel(priority)) return p2.cancel(m.cancelled);
|
|
1797
|
+
const primaryHarness = await p2.select({
|
|
1798
|
+
message: m.askHarness,
|
|
1799
|
+
initialValue: prev.primaryHarness ?? "claude-code",
|
|
1800
|
+
options: harnesses.map((h) => ({ value: h.id, label: h.name }))
|
|
1801
|
+
});
|
|
1802
|
+
if (p2.isCancel(primaryHarness)) return p2.cancel(m.cancelled);
|
|
1803
|
+
const budget = await p2.text({
|
|
1804
|
+
message: m.askBudget,
|
|
1805
|
+
initialValue: prev.monthlyBudgetUsd?.toString() ?? "",
|
|
1806
|
+
validate: (v) => v && !(Number(v) >= 0) ? m.enterNumber : void 0
|
|
1807
|
+
});
|
|
1808
|
+
if (p2.isCancel(budget)) return p2.cancel(m.cancelled);
|
|
1809
|
+
const a2 = { priority, primaryHarness, monthlyBudgetUsd: budget ? Number(budget) : void 0 };
|
|
1810
|
+
saveAnamnesis(a2);
|
|
1811
|
+
const s = p2.spinner();
|
|
1812
|
+
s.start(m.examining);
|
|
1813
|
+
const r = await checkup(c).catch(fail);
|
|
1814
|
+
s.stop(`${t(c.lang).health}: ${r.healthScore}/100`);
|
|
1815
|
+
const course = r.diagnoses.filter((d2) => !a2.primaryHarness || !d2.finding.data.harness || d2.finding.data.harness === a2.primaryHarness || d2.triage === "resuscitation").slice(0, 5);
|
|
1816
|
+
p2.note(course.map((d2, i) => `${i + 1}. ${d2.rx.id} ${d2.diagnosis}: ${d2.rx.action}${d2.rx.command ? `
|
|
1817
|
+
\u2192 ${d2.rx.command}` : ""}`).join("\n") || r.opinion, m.treatmentPlan);
|
|
1818
|
+
if (a2.monthlyBudgetUsd !== void 0 && r.finops?.sessions) {
|
|
1819
|
+
const over = r.finops.monthlyRunRateUsd - a2.monthlyBudgetUsd;
|
|
1820
|
+
p2.log.message(over > 0 ? pc2.red(m.overBudget(over)) : pc2.green(m.withinBudget));
|
|
1821
|
+
}
|
|
1822
|
+
if (o2.ai) {
|
|
1823
|
+
const provider = await detectProvider();
|
|
1824
|
+
if (!provider) return p2.outro(m.noAiProvider);
|
|
1825
|
+
const prompt = await buildConsultPrompt(c.root, r);
|
|
1826
|
+
if (provider !== "ollama") {
|
|
1827
|
+
const ok = await p2.confirm({ message: m.confirmSend(prompt.length, provider), initialValue: false });
|
|
1828
|
+
if (p2.isCancel(ok) || !ok) return p2.outro(m.nothingSent);
|
|
1829
|
+
}
|
|
1830
|
+
s.start(m.consulting(provider));
|
|
1831
|
+
const answer = await askAi(provider, prompt).catch((e) => `Error: ${e.message}`);
|
|
1832
|
+
s.stop(m.secondOpinion);
|
|
1833
|
+
console.log(answer);
|
|
1834
|
+
}
|
|
1835
|
+
p2.outro(m.goodbye);
|
|
1836
|
+
});
|
|
1837
|
+
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 : path15.resolve(dir ?? ".")))));
|
|
1838
|
+
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) => {
|
|
1839
|
+
const c = ctx(dir, o2);
|
|
1840
|
+
const publicDir = path15.join(path15.dirname(fileURLToPath(import.meta.url)), "..", "public");
|
|
1841
|
+
const { url } = await startServer({ root: c.root, lang: c.lang, days: c.days, port: Number(o2.port), publicDir }).catch(fail);
|
|
1842
|
+
console.log(`${pc2.bold("\u{1FA7A} ctxmedic UI")} ${pc2.cyan(url)}
|
|
1843
|
+
${pc2.dim("Ctrl+C to stop. Listening on 127.0.0.1 only.")}`);
|
|
1844
|
+
if (o2.open) {
|
|
1845
|
+
const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
|
|
1846
|
+
spawn(cmd, [url], { stdio: "ignore", detached: true }).on("error", () => {
|
|
1847
|
+
}).unref();
|
|
1848
|
+
}
|
|
1849
|
+
});
|
|
1850
|
+
program.parseAsync().catch(fail);
|