ctxmedic 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -1
- package/dist/index.js +326 -210
- package/package.json +18 -7
- package/public/assets/index-DIUIzBMS.js +15 -0
- package/public/assets/index-DLwaDGT3.css +1 -0
- package/public/index.html +2 -2
- package/public/assets/index-Bqo1oFYC.css +0 -1
- package/public/assets/index-CuWHlsFL.js +0 -130
package/dist/index.js
CHANGED
|
@@ -32,13 +32,32 @@ var FixOp = z.discriminatedUnion("kind", [
|
|
|
32
32
|
z.object({ kind: z.literal("symlink"), path: z.string(), target: z.string() })
|
|
33
33
|
]);
|
|
34
34
|
var FixPlan = z.object({ title: z.string(), ops: z.array(FixOp).min(1) });
|
|
35
|
+
var FixAfter = z.discriminatedUnion("kind", [
|
|
36
|
+
z.object({ kind: z.literal("write"), sha256: z.string() }),
|
|
37
|
+
z.object({ kind: z.literal("symlink"), target: z.string() })
|
|
38
|
+
]);
|
|
39
|
+
var BackupManifest = z.object({
|
|
40
|
+
title: z.string(),
|
|
41
|
+
createdAt: z.string(),
|
|
42
|
+
entries: z.array(
|
|
43
|
+
z.object({
|
|
44
|
+
path: z.string(),
|
|
45
|
+
existed: z.boolean(),
|
|
46
|
+
/** Copy of the original, relative to the backup folder. */
|
|
47
|
+
backup: z.string().optional(),
|
|
48
|
+
/** Original symlink target. */
|
|
49
|
+
symlink: z.string().optional(),
|
|
50
|
+
after: FixAfter.optional()
|
|
51
|
+
})
|
|
52
|
+
)
|
|
53
|
+
});
|
|
35
54
|
var Finding = z.object({
|
|
36
55
|
ruleId: RuleId,
|
|
37
56
|
severity: Severity,
|
|
38
57
|
message: z.string(),
|
|
39
58
|
files: z.array(z.string()).default([]),
|
|
40
59
|
/** Raw lab values used by the clinical layer (token counts, ratios, $). */
|
|
41
|
-
data: z.record(z.unknown()).default({}),
|
|
60
|
+
data: z.record(z.string(), z.unknown()).default({}),
|
|
42
61
|
monthlySavingsUsd: z.number().nonnegative().optional(),
|
|
43
62
|
fix: FixPlan.optional()
|
|
44
63
|
});
|
|
@@ -54,9 +73,10 @@ var HarnessProfile = z.object({
|
|
|
54
73
|
contextLimit: z.number().int().positive(),
|
|
55
74
|
files: z.object({
|
|
56
75
|
instructions: PathSet,
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
76
|
+
// prefault, not default: zod 4 returns a default as is, without the inner array defaults.
|
|
77
|
+
rules: PathSet.prefault({}),
|
|
78
|
+
skill: PathSet.prefault({}),
|
|
79
|
+
mcp: PathSet.prefault({})
|
|
60
80
|
}),
|
|
61
81
|
/** Directives this harness understands: "@import", "alwaysApply", "globs", "applyTo", "trigger". */
|
|
62
82
|
syntax: z.array(z.string()).default([]),
|
|
@@ -82,7 +102,7 @@ var PatientVitals = z.object({
|
|
|
82
102
|
scannedAt: z.string(),
|
|
83
103
|
filesScanned: z.number().int(),
|
|
84
104
|
harnesses: z.array(z.string()),
|
|
85
|
-
startupTokens: z.record(z.number())
|
|
105
|
+
startupTokens: z.record(z.string(), z.number())
|
|
86
106
|
});
|
|
87
107
|
var ModelUsage = z.object({
|
|
88
108
|
model: z.string(),
|
|
@@ -100,9 +120,9 @@ var FinOpsReport = z.object({
|
|
|
100
120
|
costUsd: z.number(),
|
|
101
121
|
monthlyRunRateUsd: z.number(),
|
|
102
122
|
cacheHitRatio: z.number().min(0).max(1).nullable(),
|
|
103
|
-
byHarness: z.record(z.object({ sessions: z.number(), costUsd: z.number() })),
|
|
123
|
+
byHarness: z.record(z.string(), z.object({ sessions: z.number(), costUsd: z.number() })),
|
|
104
124
|
byModel: z.array(ModelUsage),
|
|
105
|
-
mcpCalls: z.record(z.number()),
|
|
125
|
+
mcpCalls: z.record(z.string(), z.number()),
|
|
106
126
|
findings: z.array(Finding),
|
|
107
127
|
potentialMonthlySavingsUsd: z.number(),
|
|
108
128
|
pricingAsOf: z.string()
|
|
@@ -676,46 +696,52 @@ async function runRules(ctx2, list = rules) {
|
|
|
676
696
|
}
|
|
677
697
|
|
|
678
698
|
// ../core/src/fix.ts
|
|
699
|
+
import crypto from "crypto";
|
|
679
700
|
import fs5 from "fs/promises";
|
|
680
701
|
import path8 from "path";
|
|
681
702
|
var FixRefusedError = class extends Error {
|
|
682
703
|
};
|
|
683
704
|
var stamp = () => (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
705
|
+
var sha256 = (data) => crypto.createHash("sha256").update(data).digest("hex");
|
|
706
|
+
var outside = (root, p3) => {
|
|
707
|
+
const rel = path8.relative(root, p3);
|
|
708
|
+
return rel.startsWith("..") || path8.isAbsolute(rel);
|
|
709
|
+
};
|
|
710
|
+
var backupsDir = (root) => path8.join(path8.resolve(root), ".ctxmedic", "backups");
|
|
684
711
|
async function applyFix(planIn, opts) {
|
|
685
712
|
const plan = FixPlan.parse(planIn);
|
|
686
713
|
const root = path8.resolve(opts.root);
|
|
687
714
|
const targets = plan.ops.map((o2) => path8.resolve(o2.path));
|
|
688
715
|
for (const t2 of targets)
|
|
689
|
-
if (
|
|
716
|
+
if (outside(root, t2) && !opts.global)
|
|
690
717
|
throw new FixRefusedError(`refusing to modify ${t2}: outside ${root} (use --global)`);
|
|
691
718
|
if (!opts.force) {
|
|
692
|
-
const dirty = dirtyFiles(root, targets.filter((t2) => !
|
|
719
|
+
const dirty = dirtyFiles(root, targets.filter((t2) => !outside(root, t2)));
|
|
693
720
|
if (dirty.length) throw new FixRefusedError(`uncommitted changes in ${dirty.join(", ")}; commit them or use --force`);
|
|
694
721
|
}
|
|
695
|
-
const backupDir = path8.join(root,
|
|
722
|
+
const backupDir = path8.join(backupsDir(root), stamp());
|
|
696
723
|
const describe = plan.ops.map((o2) => o2.kind === "write" ? `write ${o2.path}` : `symlink ${o2.path} -> ${o2.target}`);
|
|
697
724
|
if (opts.dryRun) return { backupDir, applied: describe, dryRun: true };
|
|
698
|
-
const
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
};
|
|
725
|
+
const after = new Map(
|
|
726
|
+
plan.ops.map((o2) => [path8.resolve(o2.path), o2.kind === "write" ? { kind: "write", sha256: sha256(o2.content) } : { kind: "symlink", target: o2.target }])
|
|
727
|
+
);
|
|
728
|
+
const manifest = { title: plan.title, createdAt: (/* @__PURE__ */ new Date()).toISOString(), entries: [] };
|
|
703
729
|
await fs5.mkdir(backupDir, { recursive: true });
|
|
704
|
-
for (const t2 of targets) {
|
|
705
|
-
const rel =
|
|
730
|
+
for (const t2 of new Set(targets)) {
|
|
731
|
+
const rel = outside(root, t2) ? path8.join("_outside", t2) : path8.relative(root, t2);
|
|
706
732
|
let st;
|
|
707
733
|
try {
|
|
708
734
|
st = await fs5.lstat(t2);
|
|
709
735
|
} catch {
|
|
710
|
-
manifest.entries.push({ path: t2, existed: false });
|
|
736
|
+
manifest.entries.push({ path: t2, existed: false, after: after.get(t2) });
|
|
711
737
|
continue;
|
|
712
738
|
}
|
|
713
|
-
if (st.isSymbolicLink()) manifest.entries.push({ path: t2, existed: true, symlink: await fs5.readlink(t2) });
|
|
739
|
+
if (st.isSymbolicLink()) manifest.entries.push({ path: t2, existed: true, symlink: await fs5.readlink(t2), after: after.get(t2) });
|
|
714
740
|
else {
|
|
715
741
|
const dest = path8.join(backupDir, rel);
|
|
716
742
|
await fs5.mkdir(path8.dirname(dest), { recursive: true });
|
|
717
743
|
await fs5.copyFile(t2, dest);
|
|
718
|
-
manifest.entries.push({ path: t2, existed: true, backup: rel });
|
|
744
|
+
manifest.entries.push({ path: t2, existed: true, backup: rel, after: after.get(t2) });
|
|
719
745
|
}
|
|
720
746
|
}
|
|
721
747
|
await fs5.writeFile(path8.join(backupDir, "manifest.json"), JSON.stringify(manifest, null, 2));
|
|
@@ -727,6 +753,47 @@ async function applyFix(planIn, opts) {
|
|
|
727
753
|
}
|
|
728
754
|
return { backupDir, applied: describe, dryRun: false };
|
|
729
755
|
}
|
|
756
|
+
async function listBackups(root) {
|
|
757
|
+
const ids = await fs5.readdir(backupsDir(root)).catch(() => []);
|
|
758
|
+
const out = [];
|
|
759
|
+
for (const id of ids) {
|
|
760
|
+
const m = await readManifest(root, id).catch(() => null);
|
|
761
|
+
if (m) out.push({ id, title: m.title, createdAt: m.createdAt });
|
|
762
|
+
}
|
|
763
|
+
return out.sort((a2, b) => b.createdAt.localeCompare(a2.createdAt) || b.id.localeCompare(a2.id));
|
|
764
|
+
}
|
|
765
|
+
var readManifest = async (root, id) => BackupManifest.parse(JSON.parse(await fs5.readFile(path8.join(backupsDir(root), id, "manifest.json"), "utf8")));
|
|
766
|
+
async function unchanged(p3, after) {
|
|
767
|
+
const st = await fs5.lstat(p3).catch(() => null);
|
|
768
|
+
if (!st) return false;
|
|
769
|
+
if (after.kind === "symlink") return st.isSymbolicLink() && await fs5.readlink(p3) === after.target;
|
|
770
|
+
return st.isFile() && sha256(await fs5.readFile(p3)) === after.sha256;
|
|
771
|
+
}
|
|
772
|
+
async function restoreBackup(idIn, opts) {
|
|
773
|
+
const root = path8.resolve(opts.root);
|
|
774
|
+
const all = await listBackups(root);
|
|
775
|
+
const info = idIn === "latest" ? all[0] : all.find((b) => b.id === idIn);
|
|
776
|
+
if (!info) throw new FixRefusedError(all.length ? `backup ${idIn} not found; run \`ctxmedic restore\` to list backups` : "no backups to restore");
|
|
777
|
+
const dir = path8.join(backupsDir(root), info.id);
|
|
778
|
+
const manifest = await readManifest(root, info.id);
|
|
779
|
+
for (const e of manifest.entries) {
|
|
780
|
+
if (outside(root, e.path)) throw new FixRefusedError(`refusing to restore ${e.path}: outside ${root}`);
|
|
781
|
+
if (e.backup && outside(dir, path8.resolve(dir, e.backup))) throw new FixRefusedError(`invalid backup entry ${e.backup}`);
|
|
782
|
+
if (opts.force) continue;
|
|
783
|
+
if (!e.after) throw new FixRefusedError(`backup ${info.id} does not record what the fix wrote; use --force to restore anyway`);
|
|
784
|
+
if (!await unchanged(e.path, e.after)) throw new FixRefusedError(`${path8.relative(root, e.path)} changed after the fix; use --force to overwrite it`);
|
|
785
|
+
}
|
|
786
|
+
const restored = manifest.entries.map((e) => `${e.existed ? "restore" : "remove "} ${path8.relative(root, e.path)}`);
|
|
787
|
+
if (opts.dryRun) return { id: info.id, title: info.title, restored, dryRun: true };
|
|
788
|
+
for (const e of manifest.entries) {
|
|
789
|
+
await fs5.rm(e.path, { force: true });
|
|
790
|
+
if (!e.existed) continue;
|
|
791
|
+
await fs5.mkdir(path8.dirname(e.path), { recursive: true });
|
|
792
|
+
if (e.symlink !== void 0) await fs5.symlink(e.symlink, e.path);
|
|
793
|
+
else if (e.backup) await fs5.copyFile(path8.join(dir, e.backup), e.path);
|
|
794
|
+
}
|
|
795
|
+
return { id: info.id, title: info.title, restored, dryRun: false };
|
|
796
|
+
}
|
|
730
797
|
|
|
731
798
|
// ../core/src/examine.ts
|
|
732
799
|
import path9 from "path";
|
|
@@ -773,9 +840,13 @@ var Anamnesis = z2.object({
|
|
|
773
840
|
primaryHarness: z2.string().optional(),
|
|
774
841
|
monthlyBudgetUsd: z2.number().nonnegative().optional()
|
|
775
842
|
});
|
|
843
|
+
var ScanSettings = z2.object({ global: z2.boolean(), finops: z2.boolean(), days: z2.number() });
|
|
844
|
+
var DEFAULT_SCAN = { global: true, finops: true, days: 30 };
|
|
776
845
|
var Visit = z2.object({
|
|
777
846
|
at: z2.string(),
|
|
778
847
|
root: z2.string(),
|
|
848
|
+
/** Missing in history written by v0.1.0: those runs are assumed to use the defaults. */
|
|
849
|
+
scan: ScanSettings.default(DEFAULT_SCAN),
|
|
779
850
|
healthScore: z2.number(),
|
|
780
851
|
counts: Counts,
|
|
781
852
|
monthlySpendUsd: z2.number().optional(),
|
|
@@ -796,187 +867,23 @@ var ClinicalReport = z2.object({
|
|
|
796
867
|
potentialMonthlySavingsUsd: z2.number()
|
|
797
868
|
});
|
|
798
869
|
|
|
799
|
-
// ../
|
|
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
|
|
870
|
+
// ../finops/src/cache.ts
|
|
928
871
|
import fs6 from "fs";
|
|
929
872
|
import path10 from "path";
|
|
930
|
-
var
|
|
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");
|
|
873
|
+
var file = () => path10.join(stateDir(), "cache.json");
|
|
967
874
|
function loadCache() {
|
|
968
875
|
try {
|
|
969
|
-
const c = JSON.parse(
|
|
970
|
-
if (c?.v ===
|
|
876
|
+
const c = JSON.parse(fs6.readFileSync(file(), "utf8"));
|
|
877
|
+
if (c?.v === 3 && c.files) return c;
|
|
971
878
|
} catch {
|
|
972
879
|
}
|
|
973
|
-
return { v:
|
|
880
|
+
return { v: 3, files: {} };
|
|
974
881
|
}
|
|
975
882
|
function saveCache(c) {
|
|
976
|
-
|
|
883
|
+
fs6.mkdirSync(stateDir(), { recursive: true });
|
|
977
884
|
const tmp = file() + ".tmp";
|
|
978
|
-
|
|
979
|
-
|
|
885
|
+
fs6.writeFileSync(tmp, JSON.stringify(c));
|
|
886
|
+
fs6.renameSync(tmp, file());
|
|
980
887
|
}
|
|
981
888
|
async function cachedParse(paths, parse, cache) {
|
|
982
889
|
const stats = [];
|
|
@@ -984,7 +891,7 @@ async function cachedParse(paths, parse, cache) {
|
|
|
984
891
|
for (const p3 of paths) {
|
|
985
892
|
let st;
|
|
986
893
|
try {
|
|
987
|
-
st =
|
|
894
|
+
st = fs6.statSync(p3);
|
|
988
895
|
} catch {
|
|
989
896
|
continue;
|
|
990
897
|
}
|
|
@@ -1002,7 +909,7 @@ async function cachedParse(paths, parse, cache) {
|
|
|
1002
909
|
}
|
|
1003
910
|
|
|
1004
911
|
// ../finops/src/detectors.ts
|
|
1005
|
-
import
|
|
912
|
+
import path11 from "path";
|
|
1006
913
|
|
|
1007
914
|
// ../finops/src/pricing.ts
|
|
1008
915
|
var PRICING_AS_OF = "2026-11-03";
|
|
@@ -1082,14 +989,16 @@ function unusedMcp({ sessions, days, files, root }) {
|
|
|
1082
989
|
const model = dominant(hs) ?? "claude-sonnet-5-5";
|
|
1083
990
|
const idle = Object.keys(mcpServers(f.path, f.text, root)).filter((name) => !calls[name] && !calls[name.replace(/[^\w]/g, "_")]);
|
|
1084
991
|
if (!idle.length) continue;
|
|
1085
|
-
const
|
|
992
|
+
const measured = idle.map((name) => Math.max(0, ...hs.map((s) => s.mcpSchemaTokens?.[name] ?? s.mcpSchemaTokens?.[name.replace(/[^\w]/g, "_")] ?? 0)) || null);
|
|
993
|
+
const schemaTokens = measured.reduce((n2, t2) => n2 + (t2 ?? MCP_SCHEMA_TOKENS), 0);
|
|
994
|
+
const estimated = measured.some((t2) => t2 === null);
|
|
1086
995
|
const usd3 = monthly(schemaTokens * steps * priceOf(model).price.cacheRead / 1e6, days);
|
|
1087
996
|
out.push({
|
|
1088
997
|
ruleId: "FIN_UNUSED_MCP",
|
|
1089
998
|
severity: sev(usd3),
|
|
1090
999
|
message: `${idle.length} MCP server(s) in ${f.rel} were called 0 times in ${days} days across ${steps.toLocaleString("en")} requests: ${idle.join(", ")}`,
|
|
1091
1000
|
files: [f.rel],
|
|
1092
|
-
data: { server: idle.join(", "), harness: hid, scope: f.scope, steps, schemaTokens, days },
|
|
1001
|
+
data: { server: idle.join(", "), harness: hid, scope: f.scope, steps, schemaTokens, estimated, days },
|
|
1093
1002
|
monthlySavingsUsd: round(usd3)
|
|
1094
1003
|
});
|
|
1095
1004
|
}
|
|
@@ -1137,7 +1046,7 @@ function contextSnowball({ sessions, days }) {
|
|
|
1137
1046
|
ruleId: "FIN_CONTEXT_SNOWBALL",
|
|
1138
1047
|
severity: sev(usd3),
|
|
1139
1048
|
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 ${
|
|
1049
|
+
files: bad.slice(0, 5).map((s) => `session ${path11.basename(s.file, ".jsonl")}`),
|
|
1141
1050
|
data: { sessions: bad.length, worstSteps: worst.steps, worstMaxContext: worst.maxContext, days },
|
|
1142
1051
|
monthlySavingsUsd: round(usd3)
|
|
1143
1052
|
}
|
|
@@ -1171,14 +1080,14 @@ function cacheMiss({ sessions, days }) {
|
|
|
1171
1080
|
var detectors = [unusedMcp, modelOverkill, contextSnowball, cacheMiss];
|
|
1172
1081
|
|
|
1173
1082
|
// ../finops/src/parsers.ts
|
|
1174
|
-
import
|
|
1175
|
-
import
|
|
1083
|
+
import fs7 from "fs";
|
|
1084
|
+
import path12 from "path";
|
|
1176
1085
|
import readline from "readline";
|
|
1177
1086
|
var SNOWBALL_CONTEXT = 1e5;
|
|
1178
1087
|
var HEALTHY_CONTEXT = 4e4;
|
|
1179
1088
|
var MCP = /^mcp__(.+?)(?:__|$)/;
|
|
1180
1089
|
function blank(file2, harness) {
|
|
1181
|
-
return { file: file2, harness, steps: 0, models: {}, mcpCalls: {}, compactions: 0, maxContext: 0, heavySteps: 0, heavyExcessTokens: 0 };
|
|
1090
|
+
return { file: file2, harness, steps: 0, models: {}, mcpCalls: {}, mcpSchemaTokens: {}, compactions: 0, maxContext: 0, heavySteps: 0, heavyExcessTokens: 0 };
|
|
1182
1091
|
}
|
|
1183
1092
|
function addStep(s, model, u) {
|
|
1184
1093
|
const m = s.models[model] ??= { steps: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, costUsd: 0 };
|
|
@@ -1198,8 +1107,12 @@ var mcp = (s, name) => {
|
|
|
1198
1107
|
if (m) s.mcpCalls[m[1]] = (s.mcpCalls[m[1]] ?? 0) + 1;
|
|
1199
1108
|
return Boolean(m);
|
|
1200
1109
|
};
|
|
1110
|
+
var server = (name) => typeof name === "string" ? MCP.exec(name)?.[1] : void 0;
|
|
1111
|
+
function schemas(s, defs) {
|
|
1112
|
+
for (const [name, d2] of Object.entries(defs)) s.mcpSchemaTokens[name] = Math.max(s.mcpSchemaTokens[name] ?? 0, countTokens(JSON.stringify(d2)));
|
|
1113
|
+
}
|
|
1201
1114
|
async function* lines(file2) {
|
|
1202
|
-
const rl = readline.createInterface({ input:
|
|
1115
|
+
const rl = readline.createInterface({ input: fs7.createReadStream(file2), crlfDelay: Infinity });
|
|
1203
1116
|
for await (const line of rl) {
|
|
1204
1117
|
if (!line) continue;
|
|
1205
1118
|
try {
|
|
@@ -1219,6 +1132,14 @@ async function parseClaude(file2) {
|
|
|
1219
1132
|
for await (const l of lines(file2)) {
|
|
1220
1133
|
stamp2(s, l.timestamp);
|
|
1221
1134
|
if (l.type === "system" && l.subtype === "compact_boundary" || l.isCompactSummary) s.compactions++;
|
|
1135
|
+
if (l.type === "api-request-shape" && Array.isArray(l.shape?.tools)) {
|
|
1136
|
+
const defs = {};
|
|
1137
|
+
for (const t2 of l.shape.tools) {
|
|
1138
|
+
const name = server(t2?.name);
|
|
1139
|
+
if (name) (defs[name] ??= []).push(t2);
|
|
1140
|
+
}
|
|
1141
|
+
schemas(s, defs);
|
|
1142
|
+
}
|
|
1222
1143
|
if (l.type !== "assistant" || !l.message?.usage) continue;
|
|
1223
1144
|
const msg = l.message;
|
|
1224
1145
|
if (msg.model === "<synthetic>") continue;
|
|
@@ -1244,6 +1165,8 @@ async function parseCodex(file2) {
|
|
|
1244
1165
|
const p3 = l.payload ?? {};
|
|
1245
1166
|
if (l.type === "turn_context" && typeof p3.model === "string") model = p3.model;
|
|
1246
1167
|
else if (l.type === "compacted") s.compactions++;
|
|
1168
|
+
else if (l.type === "response_item" && p3.type === "additional_tools" && Array.isArray(p3.tools))
|
|
1169
|
+
schemas(s, Object.fromEntries(p3.tools.flatMap((ns) => ns?.type === "namespace" && server(ns.name) ? [[server(ns.name), ns.tools ?? []]] : [])));
|
|
1247
1170
|
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
1171
|
else if (l.type === "event_msg" && p3.type === "token_count" && p3.info?.last_token_usage) {
|
|
1249
1172
|
const total = p3.info.total_token_usage?.total_tokens ?? -2;
|
|
@@ -1268,7 +1191,7 @@ async function parseCursor(file2) {
|
|
|
1268
1191
|
for (const c of Array.isArray(content) ? content : []) if (c?.type === "tool_use" || c?.type === "tool-call") mcp(s, c.name ?? c.toolName);
|
|
1269
1192
|
}
|
|
1270
1193
|
if (!s.end) {
|
|
1271
|
-
const t2 =
|
|
1194
|
+
const t2 = fs7.statSync(file2).mtime.toISOString();
|
|
1272
1195
|
s.start ??= t2;
|
|
1273
1196
|
s.end = t2;
|
|
1274
1197
|
}
|
|
@@ -1343,6 +1266,174 @@ async function analyze(opts) {
|
|
|
1343
1266
|
return buildReport(await loadSessions(days, opts.now), { ...opts, days });
|
|
1344
1267
|
}
|
|
1345
1268
|
|
|
1269
|
+
// ../clinical/src/i18n.ts
|
|
1270
|
+
var d = (f, k) => f.data[k];
|
|
1271
|
+
var n = (x) => Number(x ?? 0).toLocaleString("en");
|
|
1272
|
+
var usd = (x) => `$${Number(x ?? 0).toFixed(2)}`;
|
|
1273
|
+
var pct = (x) => `${Math.round(Number(x ?? 0) * 100)}%`;
|
|
1274
|
+
var en = {
|
|
1275
|
+
cards: {
|
|
1276
|
+
ERR_BROKEN_LINK: {
|
|
1277
|
+
name: "Symlink Necrosis",
|
|
1278
|
+
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.",
|
|
1279
|
+
action: (f) => f.fix ? "Rewrite the link as a relative symlink." : `Restore the target or delete the dead link: ${f.files[0]}`
|
|
1280
|
+
},
|
|
1281
|
+
WARN_CONTEXT_BLOAT: {
|
|
1282
|
+
name: "Context Obesity",
|
|
1283
|
+
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.`,
|
|
1284
|
+
action: () => "Move rarely-needed sections into skills or path-scoped rules; keep the always-on core under 3,500 tokens."
|
|
1285
|
+
},
|
|
1286
|
+
WARN_DUPLICATE_RULES: {
|
|
1287
|
+
name: "Instruction Duplication Syndrome",
|
|
1288
|
+
prognosis: (f) => `${n(d(f, "wastedTokens"))} duplicated tokens. The copies drift apart and the agents get contradictory orders.`,
|
|
1289
|
+
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."
|
|
1290
|
+
},
|
|
1291
|
+
ERR_INVALID_SKILL: {
|
|
1292
|
+
name: "Skill Amnesia",
|
|
1293
|
+
prognosis: () => "The harness cannot discover or trigger this skill reliably. It costs tokens and never helps.",
|
|
1294
|
+
action: (f) => `Fix the SKILL.md frontmatter: ${d(f, "problem")}.`
|
|
1295
|
+
},
|
|
1296
|
+
CRIT_SECRET_LEAK: {
|
|
1297
|
+
name: "Credential Hemorrhage",
|
|
1298
|
+
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.",
|
|
1299
|
+
action: () => "Rotate the key now, then reference it through an environment variable (`${VAR}`) and git-ignore the file."
|
|
1300
|
+
},
|
|
1301
|
+
INFO_UNSUPPORTED_SYNTAX: {
|
|
1302
|
+
name: "Cross-Harness Allergy",
|
|
1303
|
+
prognosis: (f) => `${d(f, "harness")} reads ${(d(f, "directives") ?? []).join(", ")} as plain text: noise at best, wrong instructions at worst.`,
|
|
1304
|
+
action: () => "Move tool-specific directives into that tool's own file, or keep shared files directive-free."
|
|
1305
|
+
},
|
|
1306
|
+
FIN_BLOAT_IGNORE: {
|
|
1307
|
+
name: "Indexing Bloat",
|
|
1308
|
+
prognosis: (f) => `${d(f, "harness")} indexes build output and lockfiles. Search results fill with junk and retrieval burns tokens.`,
|
|
1309
|
+
action: (f) => `Create ${d(f, "ignoreFile")} with the standard exclusions.`
|
|
1310
|
+
},
|
|
1311
|
+
FIN_UNUSED_MCP: {
|
|
1312
|
+
name: "Toxic MCP Syndrome",
|
|
1313
|
+
prognosis: (f) => `${n(d(f, "schemaTokens"))} tokens of tool schemas (${d(f, "estimated") === false ? "measured from session logs" : `estimated at ${n(MCP_SCHEMA_TOKENS)} per server`}) in every request for a server nobody calls.`,
|
|
1314
|
+
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.`
|
|
1315
|
+
},
|
|
1316
|
+
FIN_MODEL_OVERKILL: {
|
|
1317
|
+
name: "Model Overkill",
|
|
1318
|
+
prognosis: (f) => `${d(f, "sessions")} trivial sessions paid frontier prices (${usd(d(f, "costUsd"))} in ${d(f, "days")} days).`,
|
|
1319
|
+
action: (f) => `Route one-shot tasks, routine skills and subagents to ${d(f, "suggested")} (set \`model:\` in the skill/agent frontmatter).`
|
|
1320
|
+
},
|
|
1321
|
+
FIN_CONTEXT_SNOWBALL: {
|
|
1322
|
+
name: "Context Snowball",
|
|
1323
|
+
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.`,
|
|
1324
|
+
action: () => "Run /compact at task milestones and /clear between unrelated tasks; enable auto-compact."
|
|
1325
|
+
},
|
|
1326
|
+
FIN_CACHE_MISS: {
|
|
1327
|
+
name: "Prompt Cache Thrashing",
|
|
1328
|
+
prognosis: (f) => `Cache hit ratio ${pct(d(f, "cacheHitRatio"))}: you pay full price for context the provider could serve at ~10%.`,
|
|
1329
|
+
action: () => "Keep instructions static: no dates, branch names or random IDs at the top; avoid switching models mid-session."
|
|
1330
|
+
}
|
|
1331
|
+
},
|
|
1332
|
+
ui: {
|
|
1333
|
+
triage: { resuscitation: "\u{1F534} Resuscitation", therapy: "\u{1F7E1} Therapy", preventive: "\u{1F7E2} Preventive" },
|
|
1334
|
+
labs: "Vitals",
|
|
1335
|
+
prognosis: "Prognosis",
|
|
1336
|
+
health: "Health Score",
|
|
1337
|
+
savings: "Potential savings",
|
|
1338
|
+
perMonth: "/mo",
|
|
1339
|
+
healthy: "No complaints. The patient is healthy.",
|
|
1340
|
+
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.",
|
|
1341
|
+
since: (x) => x === 0 ? "unchanged since the last visit" : x > 0 ? `+${x} since the last visit` : `${x} since the last visit`,
|
|
1342
|
+
manual: "manual treatment",
|
|
1343
|
+
noLogs: "No session logs found: FinOps analysis skipped.",
|
|
1344
|
+
spend: "Spend",
|
|
1345
|
+
runRate: "run rate"
|
|
1346
|
+
},
|
|
1347
|
+
cli: {
|
|
1348
|
+
noBackups: "No backups in .ctxmedic/backups: nothing to restore.",
|
|
1349
|
+
restoreHint: "Undo a fix: ctxmedic restore <backup> (or latest)",
|
|
1350
|
+
restored: (id) => `Restored backup ${id}`,
|
|
1351
|
+
noAutoFix: "No auto-fix: follow the prescription by hand.",
|
|
1352
|
+
confirmApply: "Apply? (originals are backed up to .ctxmedic/backups)",
|
|
1353
|
+
consultTitle: "\u{1FA7A} ctxmedic consultation",
|
|
1354
|
+
askPriority: "What matters most to you?",
|
|
1355
|
+
priority: { economy: "Saving tokens and money", balanced: "Balanced", quality: "Maximum answer quality" },
|
|
1356
|
+
askHarness: "Your main AI tool?",
|
|
1357
|
+
askBudget: "Monthly AI budget in $ (empty = no limit)",
|
|
1358
|
+
enterNumber: "Enter a number",
|
|
1359
|
+
examining: "Examining the patient",
|
|
1360
|
+
treatmentPlan: "Treatment plan",
|
|
1361
|
+
overBudget: (x) => `Over budget by $${x.toFixed(2)}/mo`,
|
|
1362
|
+
withinBudget: "Within budget",
|
|
1363
|
+
noAiProvider: "No Ollama, ANTHROPIC_API_KEY or OPENAI_API_KEY: AI review skipped.",
|
|
1364
|
+
confirmSend: (chars, provider) => `Send ${chars.toLocaleString("en")} characters of your instructions (secrets redacted) to ${provider}?`,
|
|
1365
|
+
nothingSent: "Nothing was sent.",
|
|
1366
|
+
consulting: (provider) => `Consulting ${provider}`,
|
|
1367
|
+
secondOpinion: "Second opinion",
|
|
1368
|
+
goodbye: "Get well soon! Follow-up: ctxmedic checkup",
|
|
1369
|
+
cancelled: "Cancelled"
|
|
1370
|
+
}
|
|
1371
|
+
};
|
|
1372
|
+
var catalogs = { en };
|
|
1373
|
+
var messages = (lang) => catalogs[lang];
|
|
1374
|
+
var cards = (lang) => catalogs[lang].cards;
|
|
1375
|
+
var t = (lang) => catalogs[lang].ui;
|
|
1376
|
+
var resolveLang = (x) => {
|
|
1377
|
+
const r = Lang.safeParse((x ?? process.env.CTXMEDIC_LANG ?? "en").slice(0, 2).toLowerCase());
|
|
1378
|
+
return r.success ? r.data : "en";
|
|
1379
|
+
};
|
|
1380
|
+
|
|
1381
|
+
// ../clinical/src/score.ts
|
|
1382
|
+
var PENALTY = { critical: 25, warning: 8, info: 2 };
|
|
1383
|
+
function healthScore(findings) {
|
|
1384
|
+
const byRule = /* @__PURE__ */ new Map();
|
|
1385
|
+
for (const f of findings) {
|
|
1386
|
+
const p3 = PENALTY[f.severity];
|
|
1387
|
+
const e = byRule.get(f.ruleId) ?? { sum: 0, max: 0 };
|
|
1388
|
+
e.sum += p3;
|
|
1389
|
+
e.max = Math.max(e.max, p3);
|
|
1390
|
+
byRule.set(f.ruleId, e);
|
|
1391
|
+
}
|
|
1392
|
+
let total = 0;
|
|
1393
|
+
for (const e of byRule.values()) total += Math.min(e.sum, e.max * 2);
|
|
1394
|
+
return Math.max(0, Math.min(100, 100 - total));
|
|
1395
|
+
}
|
|
1396
|
+
function healthGain(findings, f) {
|
|
1397
|
+
return healthScore(findings.filter((x) => x !== f)) - healthScore(findings);
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
// ../clinical/src/store.ts
|
|
1401
|
+
import fs8 from "fs";
|
|
1402
|
+
import path13 from "path";
|
|
1403
|
+
var MAX_VISITS = 200;
|
|
1404
|
+
var historyFile = () => path13.join(stateDir(), "history.json");
|
|
1405
|
+
var profileFile = () => path13.join(stateDir(), "profile.json");
|
|
1406
|
+
function readJson(file2) {
|
|
1407
|
+
try {
|
|
1408
|
+
return JSON.parse(fs8.readFileSync(file2, "utf8"));
|
|
1409
|
+
} catch {
|
|
1410
|
+
return void 0;
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
function writeJson(file2, v) {
|
|
1414
|
+
fs8.mkdirSync(path13.dirname(file2), { recursive: true });
|
|
1415
|
+
fs8.writeFileSync(file2 + ".tmp", JSON.stringify(v, null, 2));
|
|
1416
|
+
fs8.renameSync(file2 + ".tmp", file2);
|
|
1417
|
+
}
|
|
1418
|
+
var sameScan = (a2, b) => a2.global === b.global && a2.finops === b.finops && (!a2.finops || a2.days === b.days);
|
|
1419
|
+
function loadHistory(root, scan2) {
|
|
1420
|
+
const raw = readJson(historyFile());
|
|
1421
|
+
const visits = Array.isArray(raw) ? raw.flatMap((v) => {
|
|
1422
|
+
const r = Visit.safeParse(v);
|
|
1423
|
+
return r.success ? [r.data] : [];
|
|
1424
|
+
}) : [];
|
|
1425
|
+
return visits.filter((v) => (!root || v.root === root) && (!scan2 || sameScan(v.scan, scan2)));
|
|
1426
|
+
}
|
|
1427
|
+
function recordVisit(v) {
|
|
1428
|
+
writeJson(historyFile(), [...loadHistory(), Visit.parse(v)].slice(-MAX_VISITS));
|
|
1429
|
+
}
|
|
1430
|
+
function loadAnamnesis() {
|
|
1431
|
+
return Anamnesis.safeParse(readJson(profileFile())).data ?? Anamnesis.parse({});
|
|
1432
|
+
}
|
|
1433
|
+
function saveAnamnesis(a2) {
|
|
1434
|
+
writeJson(profileFile(), Anamnesis.parse(a2));
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1346
1437
|
// ../harnesses/src/index.ts
|
|
1347
1438
|
var p = (x) => HarnessProfile.parse(x);
|
|
1348
1439
|
var harnesses = [
|
|
@@ -1426,7 +1517,7 @@ var harnesses = [
|
|
|
1426
1517
|
];
|
|
1427
1518
|
|
|
1428
1519
|
// ../clinical/src/engine.ts
|
|
1429
|
-
var VERSION = true ? "0.1
|
|
1520
|
+
var VERSION = true ? "0.2.1" : "0.0.0-dev";
|
|
1430
1521
|
var TRIAGE = { critical: "resuscitation", warning: "therapy", info: "preventive" };
|
|
1431
1522
|
var ORDER = ["resuscitation", "therapy", "preventive"];
|
|
1432
1523
|
var human = (k) => k.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());
|
|
@@ -1479,6 +1570,11 @@ function diagnose(findings, lang, anamnesis = Anamnesis.parse({})) {
|
|
|
1479
1570
|
};
|
|
1480
1571
|
});
|
|
1481
1572
|
}
|
|
1573
|
+
var scanSettings = (opts) => ({
|
|
1574
|
+
global: opts.global !== false,
|
|
1575
|
+
finops: opts.finops !== false,
|
|
1576
|
+
days: opts.days ?? 30
|
|
1577
|
+
});
|
|
1482
1578
|
async function checkup(opts) {
|
|
1483
1579
|
const ex = await examine(opts.root, harnesses, { global: opts.global });
|
|
1484
1580
|
let finops = null;
|
|
@@ -1489,7 +1585,8 @@ async function checkup(opts) {
|
|
|
1489
1585
|
const counts = { resuscitation: 0, therapy: 0, preventive: 0 };
|
|
1490
1586
|
for (const d2 of diagnoses) counts[d2.triage]++;
|
|
1491
1587
|
const savings = findings.reduce((n2, f) => n2 + (f.monthlySavingsUsd ?? 0), 0);
|
|
1492
|
-
const
|
|
1588
|
+
const scan2 = scanSettings(opts);
|
|
1589
|
+
const previous = loadHistory(ex.vitals.root, scan2).at(-1) ?? null;
|
|
1493
1590
|
const report2 = ClinicalReport.parse({
|
|
1494
1591
|
tool: "ctxmedic",
|
|
1495
1592
|
version: VERSION,
|
|
@@ -1508,6 +1605,7 @@ async function checkup(opts) {
|
|
|
1508
1605
|
recordVisit({
|
|
1509
1606
|
at: report2.generatedAt,
|
|
1510
1607
|
root: ex.vitals.root,
|
|
1608
|
+
scan: scan2,
|
|
1511
1609
|
healthScore: score,
|
|
1512
1610
|
counts,
|
|
1513
1611
|
monthlySpendUsd: finops?.monthlyRunRateUsd,
|
|
@@ -1596,7 +1694,7 @@ async function askAi(provider, prompt) {
|
|
|
1596
1694
|
}
|
|
1597
1695
|
|
|
1598
1696
|
// ../server/src/index.ts
|
|
1599
|
-
import
|
|
1697
|
+
import crypto2 from "crypto";
|
|
1600
1698
|
import fs9 from "fs";
|
|
1601
1699
|
import path14 from "path";
|
|
1602
1700
|
import { serve } from "@hono/node-server";
|
|
@@ -1614,7 +1712,7 @@ function createApp(opts) {
|
|
|
1614
1712
|
const lang = c.req.query("lang") ? resolveLang(c.req.query("lang")) : opts.lang;
|
|
1615
1713
|
return c.json(await checkup({ root, lang, days: opts.days, record: c.req.query("record") === "1" }));
|
|
1616
1714
|
});
|
|
1617
|
-
app.get("/api/history", (c) => c.json(loadHistory(root)));
|
|
1715
|
+
app.get("/api/history", (c) => c.json(loadHistory(root, scanSettings({ days: opts.days }))));
|
|
1618
1716
|
app.get("/api/graph", async (c) => {
|
|
1619
1717
|
const ex = await examine(root, harnesses);
|
|
1620
1718
|
const nodes = [
|
|
@@ -1652,12 +1750,12 @@ function createApp(opts) {
|
|
|
1652
1750
|
return app;
|
|
1653
1751
|
}
|
|
1654
1752
|
async function startServer(opts) {
|
|
1655
|
-
const token =
|
|
1753
|
+
const token = crypto2.randomBytes(16).toString("hex");
|
|
1656
1754
|
const app = createApp({ ...opts, token });
|
|
1657
1755
|
return new Promise((resolve) => {
|
|
1658
|
-
const
|
|
1756
|
+
const server2 = serve(
|
|
1659
1757
|
{ 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: () =>
|
|
1758
|
+
(info) => resolve({ url: `http://127.0.0.1:${info.port}/#token=${token}`, close: () => server2.close() })
|
|
1661
1759
|
);
|
|
1662
1760
|
});
|
|
1663
1761
|
}
|
|
@@ -1728,9 +1826,13 @@ function header(r) {
|
|
|
1728
1826
|
function report(r) {
|
|
1729
1827
|
return [header(r), ...r.diagnoses.map((d2) => card(d2, r.lang) + "\n"), r.finops ? finopsSummary(r.finops, r.lang) : ""].join("\n");
|
|
1730
1828
|
}
|
|
1829
|
+
var scanFlags = ({ scan: s }) => {
|
|
1830
|
+
const f = [!s.global && "--no-global", !s.finops && "--no-finops", s.finops && s.days !== DEFAULT_SCAN.days && `--days ${s.days}`].filter(Boolean);
|
|
1831
|
+
return f.length ? pc.yellow(` ${f.join(" ")}`) : "";
|
|
1832
|
+
};
|
|
1731
1833
|
function history(visits) {
|
|
1732
1834
|
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");
|
|
1835
|
+
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)}${scanFlags(v)}`).join("\n");
|
|
1734
1836
|
}
|
|
1735
1837
|
|
|
1736
1838
|
// src/index.ts
|
|
@@ -1773,6 +1875,20 @@ common(program.command("treat [rx]").description("apply a prescription (e.g. RX-
|
|
|
1773
1875
|
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
1876
|
}
|
|
1775
1877
|
});
|
|
1878
|
+
program.command("restore [backup]").description("undo a fix: list backups, or restore one by id (or latest)").option("--lang <lang>", "interface language (only en for now)").option("--dry-run", "show what would change without writing").option("--force", "restore even if files changed after the fix").action(async (id, o2) => {
|
|
1879
|
+
const root = path15.resolve(".");
|
|
1880
|
+
const m = messages(resolveLang(o2.lang)).cli;
|
|
1881
|
+
if (!id) {
|
|
1882
|
+
const all = await listBackups(root);
|
|
1883
|
+
if (!all.length) return console.log(m.noBackups);
|
|
1884
|
+
for (const b of all) console.log(`${pc2.cyan(b.id)} ${b.title}`);
|
|
1885
|
+
return console.log(pc2.dim(`
|
|
1886
|
+
${m.restoreHint}`));
|
|
1887
|
+
}
|
|
1888
|
+
const r = await restoreBackup(id, { root, dryRun: o2.dryRun, force: o2.force }).catch(fail);
|
|
1889
|
+
for (const line of r.restored) console.log(pc2.dim(` ${line}`));
|
|
1890
|
+
console.log(`${r.dryRun ? pc2.yellow("dry-run") : pc2.green("\u2714")} ${m.restored(r.id)}: ${r.title}`);
|
|
1891
|
+
});
|
|
1776
1892
|
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
1893
|
const c = ctx(dir, o2);
|
|
1778
1894
|
const ex = await examine(c.root, harnesses, { global: c.global });
|