memfresh 0.0.0-stage → 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.
@@ -0,0 +1,140 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { finding } from '../context.js';
4
+
5
+ const kib = (n) => (n < 1024 ? `${n} byte${n === 1 ? '' : 's'}` : `${(n / 1024).toFixed(1)} KiB`);
6
+
7
+ /** Line number (1-based) whose end first exceeds `limit` bytes; null if the file fits. */
8
+ export function lineAtByteLimit(src, limit) {
9
+ let used = 0;
10
+ for (let i = 0; i < src.lines.length; i++) {
11
+ used += Buffer.byteLength(src.lines[i], 'utf8') + 1;
12
+ if (used > limit) return i + 1;
13
+ }
14
+ return null;
15
+ }
16
+
17
+ function codexMaxBytes(ctx) {
18
+ if (ctx.limitOverrides['codex.agents.bytes'] !== undefined) return { value: ctx.limits['codex.agents.bytes'], from: '--limit' };
19
+ // ~/.codex/config.toml `project_doc_max_bytes` (documented at the Codex AGENTS.md guide).
20
+ // Only the top-level key counts: a value inside a [profiles.x] table applies only when that
21
+ // profile is selected.
22
+ try {
23
+ const t = fs.readFileSync(path.join(ctx.codexHome, 'config.toml'), 'utf8').split(/^\s*\[/m)[0];
24
+ const m = /^\s*project_doc_max_bytes\s*=\s*(\d+)/m.exec(t);
25
+ if (m) return { value: Number(m[1]), from: 'config.toml project_doc_max_bytes' };
26
+ } catch {}
27
+ return { value: ctx.limits['codex.agents.bytes'], from: 'documented default' };
28
+ }
29
+
30
+ const isOnDemand = (src) => {
31
+ if (src.scope !== 'project') return false;
32
+ const rel = src.display;
33
+ if (src.kind === 'claude-rules') return Boolean(src.frontmatter.paths) || !rel.startsWith('.claude/rules/');
34
+ if (src.kind === 'claude-md' || src.kind === 'claude-local') return rel.includes('/') && rel !== '.claude/CLAUDE.md';
35
+ return false;
36
+ };
37
+
38
+ /** budget: files or parts of files that the owning tool will not load. */
39
+ export function checkBudget(ctx) {
40
+ const out = [];
41
+ const L = ctx.limits;
42
+ for (const src of ctx.sources) {
43
+ const lines = src.lineCount;
44
+ if (src.kind === 'claude-memory-index') {
45
+ const byLine = L['claude.memory.lines'] && lines > L['claude.memory.lines'] ? L['claude.memory.lines'] + 1 : null;
46
+ const byByte = L['claude.memory.bytes'] && src.bytes > L['claude.memory.bytes'] ? lineAtByteLimit(src, L['claude.memory.bytes']) : null;
47
+ const cut = [byLine, byByte].filter(Boolean).sort((a, b) => a - b)[0];
48
+ if (cut) {
49
+ const why = cut === byLine && (!byByte || byLine <= byByte)
50
+ ? `${L['claude.memory.lines']}-line limit` : `${kib(L['claude.memory.bytes'])} limit`;
51
+ out.push(finding('budget', 'error', src, cut,
52
+ `MEMORY.md has ${lines} lines / ${kib(src.bytes)}; Claude Code loads only the first ${L['claude.memory.lines']} lines or ${kib(L['claude.memory.bytes'])}, whichever comes first, so lines ${cut}-${lines} are never loaded (cut by the ${why})`,
53
+ 'Move detail into topic files and keep MEMORY.md to one line per entry (https://code.claude.com/docs/en/memory#how-it-works).'));
54
+ }
55
+ } else if (['claude-md', 'claude-local', 'claude-rules', 'import'].includes(src.kind)) {
56
+ if (L['claude.file.bytes'] && src.bytes > L['claude.file.bytes']) {
57
+ out.push(finding('budget', 'error', src, 1, `${kib(src.bytes)} is over Claude Code's ${kib(L['claude.file.bytes'])} file limit: the whole file is skipped`, 'Split the file or trim it.'));
58
+ } else if (L['claude.file.recommended-lines'] && lines > L['claude.file.recommended-lines']) {
59
+ out.push(finding('budget', 'info', src, L['claude.file.recommended-lines'] + 1,
60
+ `${lines} lines; Claude Code's guidance is under ${L['claude.file.recommended-lines']} lines per CLAUDE.md for adherence (a recommendation, not a load limit)`,
61
+ 'Move rarely-needed instructions into path-scoped rules or imports.'));
62
+ }
63
+ const chars = Array.from(src.text).length;
64
+ if (isOnDemand(src) && L['claude.ondemand.chars'] && chars > L['claude.ondemand.chars']) {
65
+ out.push(finding('budget', 'info', src, 1,
66
+ `${chars} characters; on-demand files (subdirectory CLAUDE.md, path-scoped rules) are cut to the start at ${L['claude.ondemand.chars']} characters in 200K-context sessions (150,000-200,000 on 1M-context models)`,
67
+ 'Shorten the file or split it into several rules files.'));
68
+ }
69
+ }
70
+ if (src.kind === 'cursor-rule' && L['cursor.rule.lines'] && lines > L['cursor.rule.lines']) {
71
+ out.push(finding('budget', 'warn', src, L['cursor.rule.lines'] + 1, `${lines} lines is over the configured cursor.rule.lines limit of ${L['cursor.rule.lines']} (user-configured; no verified Cursor default)`, 'Split the rule.'));
72
+ }
73
+ if (L['file.lines'] && lines > L['file.lines']) out.push(finding('budget', 'warn', src, L['file.lines'] + 1, `${lines} lines is over the configured file.lines limit of ${L['file.lines']}`, 'Shorten or split the file.'));
74
+ if (L['file.bytes'] && src.bytes > L['file.bytes']) out.push(finding('budget', 'warn', src, 1, `${kib(src.bytes)} is over the configured file.bytes limit of ${kib(L['file.bytes'])}`, 'Shorten or split the file.'));
75
+ }
76
+ out.push(...codexChains(ctx));
77
+ return out;
78
+ }
79
+
80
+ /**
81
+ * Codex reads one AGENTS file per directory from the project root down. Source of the behaviour
82
+ * (openai/codex, codex-rs/core/src/agents_md.rs, read 2026-12-03): `remaining` starts at
83
+ * project_doc_max_bytes and is reduced by each project file's length; the global ~/.codex file is
84
+ * NOT counted; separators are not counted; a file larger than `remaining` is truncated to it
85
+ * (data.truncate(remaining)); once `remaining` is 0 no further files are read.
86
+ */
87
+ function codexChains(ctx) {
88
+ const out = [];
89
+ const { value: max, from } = codexMaxBytes(ctx);
90
+ if (!max) return out;
91
+ // Codex looks at AGENTS.override.md, then AGENTS.md, in each directory from the project root down
92
+ // and takes the first that is a file, whatever its size. `.claude/AGENTS.md` is read by Claude
93
+ // Code, not by Codex, and nobody starts Codex inside `.claude/`, so it is left out.
94
+ const agents = ctx.sources.filter((s) => s.kind === 'agents-md' && !s.importedFrom && s.scope === 'project' && !s.display.split('/').includes('.claude'));
95
+ const dirOf = (s) => (path.dirname(s.display) === '.' ? '' : path.dirname(s.display));
96
+ const blank = (s) => s.text.trim() === '';
97
+ const byDir = new Map();
98
+ for (const s of agents) {
99
+ const cur = byDir.get(dirOf(s));
100
+ if (!cur || (path.basename(s.display) === 'AGENTS.override.md' && path.basename(cur.display) !== 'AGENTS.override.md')) byDir.set(dirOf(s), s);
101
+ }
102
+ const worst = new Map(); // src -> {sev, text, line}
103
+ for (const [dir, s] of byDir) {
104
+ // The result for a file depends only on the files above it, so evaluate each file once, for
105
+ // the chain that ends at its own directory.
106
+ const chain = [''];
107
+ if (dir) {
108
+ const parts = dir.split('/');
109
+ for (let i = 1; i <= parts.length; i++) chain.push(parts.slice(0, i).join('/'));
110
+ }
111
+ let remaining = max;
112
+ for (const above of chain.slice(0, -1).map((d) => byDir.get(d)).filter(Boolean)) {
113
+ if (!blank(above)) remaining -= above.bytes;
114
+ }
115
+ if (blank(s)) continue;
116
+ const where = dir ? `sessions started in ${dir}` : 'every session';
117
+ if (remaining <= 0) {
118
+ worst.set(s, { sev: 'error', line: 1, text: `is past Codex's ${kib(max)} project AGENTS.md limit (${from}) for ${where}: earlier files already use all of it, so Codex reads none of this file` });
119
+ } else if (s.bytes > remaining) {
120
+ const line = lineAtByteLimit({ lines: s.lines }, remaining) || 1;
121
+ worst.set(s, { sev: 'warn', line, text: `exceeds Codex's ${kib(max)} project AGENTS.md limit (${from}) for ${where}: Codex truncates it at ${kib(remaining)}, about line ${line}, so everything after that is never loaded` });
122
+ }
123
+ }
124
+ for (const [s, w] of worst) {
125
+ out.push(finding('budget', w.sev, s, w.line, `${kib(s.bytes)} file ${w.text}`, 'Shorten it, split instructions across nested directories, or raise project_doc_max_bytes in ~/.codex/config.toml.'));
126
+ }
127
+ // override shadowing (an empty override still wins: Codex picks the first candidate that is a file)
128
+ for (const s of agents) {
129
+ if (path.basename(s.display) !== 'AGENTS.md') continue;
130
+ const sib = byDir.get(dirOf(s));
131
+ if (sib && sib !== s) {
132
+ out.push(finding('agents-not-loaded', 'warn', s, 1,
133
+ blank(sib)
134
+ ? 'the empty AGENTS.override.md in the same directory hides this AGENTS.md: Codex reads only one file per directory, so it loads nothing from this directory'
135
+ : 'AGENTS.override.md in the same directory takes precedence, and Codex reads only one file per directory, so this AGENTS.md is not loaded by Codex',
136
+ blank(sib) ? 'Delete the empty override or put the instructions in it.' : 'Merge the two files or delete the override.'));
137
+ }
138
+ }
139
+ return out;
140
+ }