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.
package/src/imports.js ADDED
@@ -0,0 +1,107 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { blankSpans } from './text.js';
5
+ import { KNOWN_EXT, extOf, isFile } from './util.js';
6
+
7
+ // Import syntax, from https://code.claude.com/docs/en/memory#import-additional-files (fetched 2026-12-03):
8
+ // - `@path/to/import`; relative paths resolve against the importing file;
9
+ // - "maximum depth of four hops" (the SPEC said 5; the docs win, configurable);
10
+ // - parsing skips code spans and fenced code blocks;
11
+ // - spaces in a path are written with a backslash.
12
+ export const DEFAULT_MAX_IMPORT_DEPTH = 4;
13
+
14
+ /**
15
+ * Extract `@path` import candidates from a file's prose lines.
16
+ * @param {string[]} lines
17
+ * @param {boolean[]} fence
18
+ * @param {number} bodyStart
19
+ */
20
+ export function extractImports(lines, fence, bodyStart = 0) {
21
+ const out = [];
22
+ for (let i = bodyStart; i < lines.length; i++) {
23
+ if (fence[i]) continue;
24
+ const text = blankSpans(lines[i]);
25
+ const re = /(^|\s)@((?:\\ |[^\s])+)/g;
26
+ let m;
27
+ while ((m = re.exec(text))) {
28
+ let tok = m[2].replace(/[.,;:!?)\]}>'"]+$/, '');
29
+ if (!/^[\w./~-]/.test(tok)) continue;
30
+ const raw = tok;
31
+ tok = tok.replace(/\\ /g, ' ');
32
+ out.push({ raw: `@${raw}`, token: tok, line: i + 1, atLineStart: text.trimStart().startsWith(`@${raw}`) });
33
+ }
34
+ }
35
+ return out;
36
+ }
37
+
38
+ /** Heuristic: is this `@token` plausibly meant as a file import? (avoids @mentions, @scope/pkg) */
39
+ export function looksLikePath(token) {
40
+ if (/^(\.{1,2}\/|~\/|\/)/.test(token)) return true;
41
+ const last = token.split('/').pop();
42
+ return KNOWN_EXT.has(extOf(last));
43
+ }
44
+
45
+ function isInside(abs, root) {
46
+ const rel = path.relative(root, abs);
47
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
48
+ }
49
+
50
+ export function resolveImport(token, fromFile, home) {
51
+ if (token.startsWith('~/')) return path.join(home || os.homedir(), token.slice(2));
52
+ if (path.isAbsolute(token)) return token;
53
+ return path.resolve(path.dirname(fromFile), token);
54
+ }
55
+
56
+ /**
57
+ * Follow imports breadth-first from the given roots.
58
+ * Mutates each root source's `imports`; returns newly discovered source stubs.
59
+ * @param {any[]} roots sources that may contain imports
60
+ * @param {{ maxDepth: number, home: string, load: (abs:string)=>any, known: Map<string, any> }} o
61
+ */
62
+ export function followImports(roots, o) {
63
+ const added = [];
64
+ const queue = roots.map((s) => ({ src: s, depth: 0, chain: [s.realpath] }));
65
+ while (queue.length) {
66
+ const { src, depth, chain } = queue.shift();
67
+ src.imports = src.imports || [];
68
+ for (const imp of src.importCandidates || []) {
69
+ const abs = resolveImport(imp.token, src.abs, o.home);
70
+ const entry = { raw: imp.raw, line: imp.line, atLineStart: imp.atLineStart, resolved: abs, status: 'ok', depth: depth + 1 };
71
+ const exists = isFile(abs);
72
+ if (!exists) {
73
+ // Only report as broken when it plausibly was meant as a path.
74
+ if (!looksLikePath(imp.token)) continue;
75
+ entry.status = 'missing';
76
+ } else if (src.scope === 'project' && !isInside(abs, o.root)) {
77
+ // Claude Code asks for approval before loading imports outside the project, so memfresh does
78
+ // not read them (they could be any file on disk, including on an untrusted checkout).
79
+ entry.status = 'external';
80
+ } else if (depth + 1 > o.maxDepth) {
81
+ entry.status = 'too-deep';
82
+ } else {
83
+ let real = abs;
84
+ try {
85
+ real = fs.realpathSync(abs);
86
+ } catch {}
87
+ if (chain.includes(real)) entry.status = 'cycle';
88
+ else {
89
+ let target = o.known.get(real);
90
+ if (!target) {
91
+ target = o.load(abs, { importedFrom: src });
92
+ if (target) {
93
+ o.known.set(real, target);
94
+ added.push(target);
95
+ }
96
+ }
97
+ if (target) {
98
+ entry.target = target;
99
+ queue.push({ src: target, depth: depth + 1, chain: [...chain, real] });
100
+ }
101
+ }
102
+ }
103
+ src.imports.push(entry);
104
+ }
105
+ }
106
+ return added;
107
+ }
package/src/init.js ADDED
@@ -0,0 +1,46 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { UserError } from './limits.js';
4
+ import { VERSION } from './version.js';
5
+
6
+ export const WORKFLOW_PATH = path.join('.github', 'workflows', 'memfresh.yml');
7
+
8
+ export const WORKFLOW = `# Generated by \`memfresh init --ci\`.
9
+ # The job fails only on errors (near-certain problems). Add \`--fail-on warn\` for a stricter gate;
10
+ # warnings are heuristic and can be wrong on unusual wording.
11
+ # fetch-depth: 0 matters: stale-reference and stale-age read git history.
12
+ # The version is pinned. memfresh is NOT published to npm yet, so until it is the npx line below
13
+ # will fail: install it from a tarball or a git checkout instead, then keep the pinned version
14
+ # in step with the one you installed.
15
+ name: memfresh
16
+ on:
17
+ push:
18
+ pull_request:
19
+ jobs:
20
+ memfresh:
21
+ runs-on: ubuntu-latest
22
+ steps:
23
+ - uses: actions/checkout@v4
24
+ with:
25
+ fetch-depth: 0
26
+ - uses: actions/setup-node@v4
27
+ with:
28
+ node-version: 22
29
+ - run: npx --yes memfresh@${VERSION} check --ci --no-user --fail-on error
30
+ `;
31
+
32
+ /**
33
+ * Plan (and optionally perform) writing the workflow. Never overwrites without force.
34
+ * @returns {{ target: string, exists: boolean, wrote: boolean }}
35
+ */
36
+ export function initCi(root, { force = false, dryRun = false } = {}) {
37
+ const target = path.join(root, WORKFLOW_PATH);
38
+ const exists = fs.existsSync(target);
39
+ if (exists && !force && !dryRun) {
40
+ throw new UserError(`${WORKFLOW_PATH} already exists; not overwriting. Re-run with --force to replace it, or --dry-run to see the new content.`);
41
+ }
42
+ if (dryRun) return { target, exists, wrote: false };
43
+ fs.mkdirSync(path.dirname(target), { recursive: true });
44
+ fs.writeFileSync(target, WORKFLOW);
45
+ return { target, exists, wrote: true };
46
+ }
package/src/limits.js ADDED
@@ -0,0 +1,49 @@
1
+ // Load limits. Every default here is tied to an official page; anything that
2
+ // could not be confirmed has NO default (null) and is opt-in via --limit.
3
+
4
+ export const LIMITS = {
5
+ // https://code.claude.com/docs/en/memory#how-it-works (fetched 2026-12-03):
6
+ // "the first 200 lines or 25KB of MEMORY.md, whichever comes first, load at session start".
7
+ // The page says "25KB" without defining KB vs KiB; we use 25*1024 (the larger reading) so we
8
+ // never claim truncation that might not happen.
9
+ 'claude.memory.lines': { value: 200, doc: 'https://code.claude.com/docs/en/memory#how-it-works' },
10
+ 'claude.memory.bytes': { value: 25 * 1024, doc: 'https://code.claude.com/docs/en/memory#how-it-works', note: 'docs say "25KB"; unit assumed KiB' },
11
+ // Same page: "Claude Code skips a file over 4 MiB and loads none of it."
12
+ 'claude.file.bytes': { value: 4 * 1024 * 1024, doc: 'https://code.claude.com/docs/en/memory#how-it-works' },
13
+ // Same page: "target under 200 lines per CLAUDE.md file" (a recommendation, not a load limit).
14
+ 'claude.file.recommended-lines': { value: 200, doc: 'https://code.claude.com/docs/en/memory#write-effective-instructions' },
15
+ // Same page, troubleshooting: on-demand files (subdirectory CLAUDE.md, rules) are cut at
16
+ // 40,000 characters with a 200K context window (150,000-200,000 on 1M-context models).
17
+ 'claude.ondemand.chars': { value: 40000, doc: 'https://code.claude.com/docs/en/memory#claude-ignores-the-end-of-my-subdirectory-claude-md', note: 'applies to 200K-context sessions' },
18
+ // https://developers.openai.com/codex/guides/agents-md (redirects to learn.chatgpt.com, fetched 2026-12-03):
19
+ // project_doc_max_bytes default 32 KiB; combined size of the AGENTS.md chain.
20
+ 'codex.agents.bytes': { value: 32 * 1024, doc: 'https://developers.openai.com/codex/guides/agents-md' },
21
+ // Unconfirmed from the tool's own docs: no default. Opt in with --limit cursor.rule.lines=N.
22
+ 'cursor.rule.lines': { value: null, doc: null, note: 'unverified: Cursor docs could not be fetched' },
23
+ 'file.lines': { value: null, doc: null, note: 'generic per-file line limit, opt-in' },
24
+ 'file.bytes': { value: null, doc: null, note: 'generic per-file byte limit, opt-in' },
25
+ };
26
+
27
+ /** @param {Record<string, number>} overrides */
28
+ export function resolveLimits(overrides = {}) {
29
+ const out = {};
30
+ for (const [k, v] of Object.entries(LIMITS)) out[k] = v.value;
31
+ for (const [k, v] of Object.entries(overrides)) {
32
+ if (!(k in LIMITS)) throw new UserError(`unknown limit "${k}". Known: ${Object.keys(LIMITS).join(', ')}`);
33
+ out[k] = v;
34
+ }
35
+ return out;
36
+ }
37
+
38
+ export class UserError extends Error {}
39
+
40
+ /** Parse repeated `--limit key=value` flags (value `off` disables). */
41
+ export function parseLimitFlags(list = []) {
42
+ const o = {};
43
+ for (const item of list) {
44
+ const m = /^([\w.-]+)=(\d+|off)$/.exec(item);
45
+ if (!m) throw new UserError(`bad --limit "${item}"; expected key=number or key=off`);
46
+ o[m[1]] = m[2] === 'off' ? null : Number(m[2]);
47
+ }
48
+ return o;
49
+ }
package/src/refs.js ADDED
@@ -0,0 +1,260 @@
1
+ import { blankSpans, codeSpans } from './text.js';
2
+ import { KNOWN_EXT, PRODUCT_NAMES, extOf } from './util.js';
3
+
4
+ // Line-level guards. Guard words are tested against the line with code spans blanked,
5
+ // so a path like `docs/examples/x.md` does not suppress itself.
6
+ const EXAMPLE_RE = /(\be\.g\.|\bi\.e\.|\bexamples?\b|\bfor instance\b|\bsuch as\b|\bsample\b|\bplaceholders?\b)/i;
7
+ // `touch` is the shell command only when a path follows it (or a code span, blanked to spaces):
8
+ // "the module most people touch: `x`" and "a PR that touches ..." are English.
9
+ const CREATE_RE = /\b(creates?|creating|generates?|generated|outputs? (?:to|in|into)|writes? to|written to|will be (?:created|written|generated)|new file|mkdir|touch(?=\s+(?:-\w+\s+)*[\w.~$-]*(?:\/|\.\w)|\s{2})|saves? (?:to|in)|emits?|produces?|gitignored?|ignored?)\b/i;
10
+ const NEG_CMD_RE = /\b(never|don'?t|do not|avoid|instead of|deprecated|removed|no longer|replaced|obsolete)\b/i;
11
+ // For path mentions the net is wider: "there is no `package.json`", "without `x`", "doesn't exist".
12
+ const NEG_RE = /\b(never|don'?t|do not|avoid|instead of|deprecated|removed|no longer|replaced|obsolete|there (?:is|are) no|no|without|not (?:a|an|any|have|use|using|needed|required)|(?:does|did|do|is|are)n'?t|isn'?t|lacks?)\b/i;
13
+
14
+ /** Inline `<!-- memfresh-ignore ... -->` comments are instructions to memfresh, not content. */
15
+ export const stripDirectives = (line) => line.replace(/<!--\s*memfresh-ignore[^>]*-->/g, ' ');
16
+
17
+ // A line that talks about the past ("renamed from `x`", "was in `x` before the split", "formerly
18
+ // `x`", "in 2024"): its paths are history, not claims about the present.
19
+ // A bare year counts only after a preposition of time ("in 2024", "until 2024", "before 2024-05"):
20
+ // "Since the 2024 rewrite, auth lives in `x`" is still a present-tense claim.
21
+ const HISTORY_RE = /\b(moved|renamed|migrated|formerly|previously|used to|was|were|split|merged|old|older|legacy|dropped|retired|gone|deleted|became|superseded|in favou?r of|(?:in|until|till|before|during|by|as of|back in|up to)\s+(?:19|20)\d\d)\b/i;
22
+ export const lineIsHistory = (line) => HISTORY_RE.test(blankSpans(stripDirectives(line)));
23
+
24
+ export function lineIsGuarded(line) {
25
+ const t = blankSpans(stripDirectives(line));
26
+ return EXAMPLE_RE.test(t) || CREATE_RE.test(t) || NEG_RE.test(t);
27
+ }
28
+
29
+ export const COMMON_DIRS = new Set([
30
+ 'src', 'lib', 'app', 'apps', 'packages', 'docs', 'doc', 'test', 'tests', 'spec', 'scripts', 'bin',
31
+ 'config', 'configs', 'public', 'assets', 'static', 'components', 'pages', 'server', 'client', 'cmd',
32
+ 'internal', 'pkg', 'crates', 'examples', 'example', 'tools', 'utils', 'services', 'modules',
33
+ 'migrations', '.github', '.vscode', '.cursor', '.claude', '.husky',
34
+ ]);
35
+
36
+ const TLDS = new Set(['com', 'org', 'io', 'net', 'dev', 'app', 'co', 'uk', 'ai', 'sh', 'so', 'me', 'edu', 'gov', 'info', 'xyz']);
37
+ const SLASH_WORDS = new Set(['and/or', 'client/server', 'input/output', 'read/write', 'yes/no', 'true/false', 'on/off', 'pass/fail', 'i/o', 'either/or', 'he/she', 'tcp/ip', 'ci/cd', 'w/o', 'n/a', 'ui/ux', 'frontend/backend', 'front/back']);
38
+
39
+ /**
40
+ * Turn raw text into a path candidate, or null if it is not obviously a path.
41
+ * @returns {{ path: string, isDir: boolean, isGlob: boolean, explicitRel: boolean } | null}
42
+ */
43
+ export function pathCandidate(raw, { fromCodeSpan }) {
44
+ let t = raw.trim();
45
+ if (!t || /\s/.test(t)) return null;
46
+ t = t.replace(/[.,;:!?]+$/, '');
47
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(t) || /^(mailto|tel|data):/i.test(t)) return null;
48
+ if (/^[-$~@/#<>|&=!%^]/.test(t) && !t.startsWith('!')) return null;
49
+ if (t.startsWith('!')) return null;
50
+ if (/[<>|;$=(),`"']/.test(t) && !/[{}]/.test(t)) return null;
51
+ if (/\.\.\.|…|\$\{/.test(t)) return null;
52
+ // template placeholders such as YYYY-MM-DD-slug.md, NNNN-title.md, XXX
53
+ // (also runs such as YYYYMMDD, YYYYMMDDHHMMSS and YYYYMMDDA-name.ts)
54
+ if (/(^|[-_/.])(?:YYYY|MM|DD|HH|SS|NNN+|XXX+|TIMESTAMP|UUID)+[A-Za-z]?(?=[-_/.]|$)/.test(t)) return null;
55
+ t = t.replace(/(?::\d+(?::\d+)?|#L?\d+(?:-L?\d+)?)$/, '');
56
+ if (/^\d+(\.\d+)*$/.test(t) || /^\d+\/\d+$/.test(t)) return null;
57
+ const explicitRel = /^\.{1,2}\//.test(t);
58
+ const isDir = t.endsWith('/');
59
+ const bare = t.replace(/^\.\//, '').replace(/\/+$/, '');
60
+ if (!bare || bare === '.' || bare === '..') return null;
61
+ if (SLASH_WORDS.has(bare.toLowerCase()) || PRODUCT_NAMES.has(bare.toLowerCase())) return null;
62
+ const isGlob = /[*?[{]/.test(bare);
63
+ if (/^[[{]/.test(bare) || (isGlob && /[[]/.test(bare))) return null;
64
+ const segs = bare.split('/');
65
+ const last = segs[segs.length - 1];
66
+ const first = segs[0];
67
+ const ext = extOf(last);
68
+ if (segs.length > 1 && first.includes('.') && !first.startsWith('.') && TLDS.has(first.split('.').pop().toLowerCase())) return null;
69
+ if (!segs.every((s) => /^[\p{L}\p{N}_.@+{},*?-]+$/u.test(s))) return null;
70
+ const hasKnownExt = KNOWN_EXT.has(ext);
71
+ if (segs.length === 1) {
72
+ if (isGlob) return hasKnownExt ? { path: bare, isDir: false, isGlob: true, explicitRel } : null;
73
+ if (isDir) return fromCodeSpan ? { path: bare, isDir: true, isGlob, explicitRel } : null;
74
+ if (!hasKnownExt || !fromCodeSpan) return null;
75
+ return { path: bare, isDir: false, isGlob, explicitRel };
76
+ }
77
+ // multi-segment
78
+ if (!fromCodeSpan && !explicitRel && !hasKnownExt) return null;
79
+ return { path: bare, isDir, isGlob, explicitRel };
80
+ }
81
+
82
+ /**
83
+ * Scan prose + code spans (not fenced blocks) for path references.
84
+ * @returns {{ raw: string, cand: NonNullable<ReturnType<typeof pathCandidate>>, line: number }[]}
85
+ */
86
+ export function scanPaths(src) {
87
+ const out = [];
88
+ for (let i = src.bodyStart; i < src.lines.length; i++) {
89
+ if (src.fence[i]) continue;
90
+ const line = stripDirectives(src.lines[i]);
91
+ if (lineIsGuarded(line)) continue;
92
+ const history = lineIsHistory(line);
93
+ const seen = new Set();
94
+ const push = (raw, fromCodeSpan) => {
95
+ const cand = pathCandidate(raw, { fromCodeSpan });
96
+ if (cand && !seen.has(cand.path + (cand.isDir ? '/' : ''))) {
97
+ seen.add(cand.path + (cand.isDir ? '/' : ''));
98
+ out.push({ raw, cand, line: i + 1, history });
99
+ }
100
+ };
101
+ for (const s of codeSpans(line)) push(s.text, true);
102
+ let rest = blankSpans(line);
103
+ // markdown link destinations
104
+ rest = rest.replace(/\]\(([^)\s]+)\)/g, (_m, dest) => {
105
+ if (!/^(https?:|mailto:|#)/i.test(dest)) push(dest.replace(/#.*$/, '').replace(/\?.*$/, ''), true);
106
+ return ' ';
107
+ });
108
+ for (const tok of rest.split(/\s+/)) {
109
+ const t = tok.replace(/^[([{"']+/, '').replace(/[)\]}"',;:]+$/, '');
110
+ if (t.includes('/') || /^\.\.?\//.test(t)) push(t, false);
111
+ }
112
+ }
113
+ return out;
114
+ }
115
+
116
+ // ---------------------------------------------------------------- commands
117
+ const NPM_RUN = /^(npm|pnpm|yarn|bun)\s+(?:run|run-script)\s+(.*)$/;
118
+ const NO_VERIFY_FLAG = /^(-w|--workspace|--workspaces|-ws|--prefix|-C|--filter|-F|--cwd|--dir|-r|--recursive)(=|$)/;
119
+
120
+ // https://pnpm.io/cli/add etc.; commands that are NOT package.json scripts. Anything not listed is
121
+ // treated as a script name for `pnpm X` / `yarn X`.
122
+ const PNPM_BUILTINS = new Set('add audit bin config create dedupe deploy dlx doctor env exec fetch i import init install install-test it licenses link list ln ls outdated pack patch patch-commit patch-remove prune publish rebuild recursive remove rm root run self-update server setup store uninstall unlink up update why view help -v --version -h'.split(' '));
123
+ const YARN_BUILTINS = new Set('add audit autoclean bin cache check config constraints create dedupe dlx exec explain generate-lock-entry global help import info init install licenses link list login logout node npm outdated owner pack patch patch-commit plugin policies publish rebuild remove run search set stage tag team unlink unplug up upgrade upgrade-interactive version versions why workspace workspaces -v --version -h --help'.split(' '));
124
+
125
+ const cleanName = (s) => s.replace(/[.,;:)`'"]+$/, '');
126
+ const validScript = (s) => /^[A-Za-z0-9][A-Za-z0-9_:.-]*$/.test(s) && !/^(x|name|script|task|cmd|command|foo|bar)$/i.test(s) && !s.includes('*');
127
+
128
+ /** Parse one shell-ish segment into a command reference, or null. */
129
+ function segmentCommand(seg) {
130
+ let s = seg.trim().replace(/^[$>]\s+/, '');
131
+ for (;;) {
132
+ const n = s.replace(/^(?:sudo|time|command|env)\s+/, '').replace(/^[A-Za-z_][A-Za-z0-9_]*=\S+\s+/, '');
133
+ if (n === s) break;
134
+ s = n;
135
+ }
136
+ let m = NPM_RUN.exec(s);
137
+ if (m) {
138
+ for (const tok of m[2].split(/\s+/)) {
139
+ if (!tok) continue;
140
+ if (tok.startsWith('-')) {
141
+ if (NO_VERIFY_FLAG.test(tok)) return null;
142
+ continue;
143
+ }
144
+ const name = cleanName(tok);
145
+ if (!validScript(name) || /\.\w{1,4}$/.test(name) && m[1] === 'bun') return null;
146
+ if (m[1] === 'bun' && /[/]/.test(name)) return null;
147
+ return { tool: m[1], kind: 'script', name, runForm: m[1] === 'yarn' };
148
+ }
149
+ return null;
150
+ }
151
+ // `(?=\s|$)`, not `\b`: `\b` also matches before `:` and `-`, which made `pnpm test:unit` and
152
+ // `pnpm test-ci` look like plain `pnpm test`.
153
+ m = /^(npm|pnpm|yarn)\s+(test|t)(?=\s|$|[.,)]+$)/.exec(s);
154
+ if (m) return { tool: m[1], kind: 'script', name: 'test' };
155
+ m = /^(pnpm|yarn)\s+([^\s]+)/.exec(s);
156
+ if (m && !m[2].startsWith('-')) {
157
+ const name = cleanName(m[2]);
158
+ const builtins = m[1] === 'pnpm' ? PNPM_BUILTINS : YARN_BUILTINS;
159
+ // bare form: pnpm/yarn fall back to running a dependency's binary when no script has this name
160
+ if (!builtins.has(name) && validScript(name) && !/\.\w{1,4}$/.test(name)) return { tool: m[1], kind: 'script', name, bare: true };
161
+ return null;
162
+ }
163
+ m = /^make\s+(.*)$/.exec(s);
164
+ if (m) {
165
+ const toks = m[1].split(/\s+/).filter(Boolean);
166
+ if (toks.some((t) => /^(-C|-f|--directory|--file|-j\d*|-k|-s|-n)/.test(t) && /^-(C|f|-directory|-file)/.test(t))) return null;
167
+ const goal = toks.find((t) => !t.startsWith('-'));
168
+ if (goal && /^[A-Za-z0-9_.-]+$/.test(cleanName(goal)) && !/^[A-Z_]+=/.test(goal)) return { tool: 'make', kind: 'target', name: cleanName(goal) };
169
+ return null;
170
+ }
171
+ m = /^just\s+(.*)$/.exec(s);
172
+ if (m) {
173
+ const toks = m[1].split(/\s+/).filter(Boolean);
174
+ if (toks[0] && !toks[0].startsWith('-') && /^[A-Za-z_][A-Za-z0-9_-]*$/.test(cleanName(toks[0])) && !toks[0].includes('=')) {
175
+ if (toks.some((t) => /^(-f|--justfile|-d|--working-directory)/.test(t))) return null;
176
+ return { tool: 'just', kind: 'recipe', name: cleanName(toks[0]) };
177
+ }
178
+ }
179
+ return null;
180
+ }
181
+
182
+ /** Split a code string on shell separators, tracking `cd <dir>`. */
183
+ export function commandsInCode(text) {
184
+ const out = [];
185
+ let cwd = null;
186
+ for (const seg of text.split(/&&|\|\||;|\|/)) {
187
+ const cd = /^\s*(?:[$>]\s+)?cd\s+(\S+)/.exec(seg);
188
+ if (cd) {
189
+ cwd = cd[1].replace(/^\.\//, '').replace(/\/$/, '');
190
+ continue;
191
+ }
192
+ const c = segmentCommand(seg);
193
+ if (c) out.push({ ...c, cwd });
194
+ }
195
+ return out;
196
+ }
197
+
198
+ /**
199
+ * Find script/target references in code spans, fenced blocks and (for `<tool> run X` only) prose.
200
+ * @returns {{ tool: string, kind: string, name: string, cwd: string|null, line: number }[]}
201
+ */
202
+ export function scanCommands(src) {
203
+ const out = [];
204
+ for (let i = src.bodyStart; i < src.lines.length; i++) {
205
+ const line = stripDirectives(src.lines[i]);
206
+ if (EXAMPLE_RE.test(blankSpans(line)) && !src.fence[i]) continue;
207
+ if (NEG_CMD_RE.test(blankSpans(line)) && !src.fence[i]) continue;
208
+ if (src.fence[i]) {
209
+ if (/^ {0,3}[`~]{3,}/.test(line) || EXAMPLE_RE.test(line)) continue;
210
+ for (const c of commandsInCode(line)) out.push({ ...c, line: i + 1 });
211
+ continue;
212
+ }
213
+ for (const s of codeSpans(line)) {
214
+ for (const c of commandsInCode(s.text)) out.push({ ...c, line: i + 1 });
215
+ }
216
+ const prose = blankSpans(line);
217
+ const re = /\b((?:npm|pnpm|yarn|bun)\s+(?:run|run-script)\s+[^\s]+)/g;
218
+ let m;
219
+ while ((m = re.exec(prose))) {
220
+ for (const c of commandsInCode(m[1])) out.push({ ...c, line: i + 1 });
221
+ }
222
+ }
223
+ return out;
224
+ }
225
+
226
+ export function parseMakeTargets(text) {
227
+ const targets = new Set();
228
+ const patterns = [];
229
+ let hasInclude = false;
230
+ for (const line of text.split(/\r?\n/)) {
231
+ // `$(LOCALBIN):` (Kubebuilder, Operator SDK) is an ordinary rule whose target is a path held in
232
+ // a variable, not an include. Other leading `$(...)` lines, eval and foreach can define targets.
233
+ const varRule = /^\$[({][\w.-]+[)}][^:=]*:(?![=:])/.test(line);
234
+ if (/^-?include\s/.test(line) || (/^\$[({]/.test(line) && !varRule) || /\$\((eval|foreach)\b/.test(line)) hasInclude = true;
235
+ if (/^\s/.test(line) || line.startsWith('#')) continue;
236
+ const m = /^\.PHONY\s*:\s*(.*)$/.exec(line) || /^([^\s#:=][^:=]*?)\s*:(?![=:])/.exec(line);
237
+ if (m) {
238
+ for (const t of m[1].split(/\s+/)) {
239
+ if (!t) continue;
240
+ if (t.includes('%')) patterns.push(new RegExp(`^${t.split('%').map((x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('.+')}$`));
241
+ else if (!t.includes('$')) targets.add(t);
242
+ }
243
+ }
244
+ }
245
+ return { targets, patterns, hasInclude };
246
+ }
247
+
248
+ export function parseJustRecipes(text) {
249
+ const recipes = new Set();
250
+ let hasImport = false;
251
+ for (const line of text.split(/\r?\n/)) {
252
+ if (/^(import|mod)\s/.test(line)) hasImport = true;
253
+ if (/^\s/.test(line) || line.startsWith('#')) continue;
254
+ const m = /^(?:@|\[[^\]]*\]\s*)?([A-Za-z_][\w-]*)(?:\s+[^:]*?)?:(?!=)/.exec(line);
255
+ if (m && !/^(?:@|\[[^\]]*\]\s*)?[A-Za-z_][\w-]*\s*=/.test(line)) recipes.add(m[1]);
256
+ const a = /^alias\s+([\w-]+)\s*:=/.exec(line);
257
+ if (a) recipes.add(a[1]);
258
+ }
259
+ return { recipes, hasImport };
260
+ }
package/src/report.js ADDED
@@ -0,0 +1,76 @@
1
+ import { plural } from './util.js';
2
+
3
+ export const SCHEMA_VERSION = 1;
4
+
5
+ export function useColour(stream, env) {
6
+ if (env.NO_COLOR !== undefined && env.NO_COLOR !== '') return false;
7
+ if (env.FORCE_COLOR && env.FORCE_COLOR !== '0') return true;
8
+ return Boolean(stream && stream.isTTY);
9
+ }
10
+
11
+ const paint = (on) => (code, s) => (on ? `\u001b[${code}m${s}\u001b[0m` : s);
12
+
13
+ /** @returns {object} stable JSON document (schemaVersion 1) */
14
+ export function toJson({ version, root, sources, findings, summary, notes }) {
15
+ return {
16
+ schemaVersion: SCHEMA_VERSION,
17
+ tool: 'memfresh',
18
+ version,
19
+ root,
20
+ files: sources.map((s) => ({
21
+ path: s.display,
22
+ scope: s.scope,
23
+ kind: s.kind,
24
+ tools: s.tools,
25
+ bytes: s.bytes,
26
+ lines: s.lineCount,
27
+ importedFrom: s.importedFrom ? s.importedFrom.display : null,
28
+ })),
29
+ findings: findings.map((f) => ({
30
+ id: f.id,
31
+ severity: f.severity,
32
+ file: f.file,
33
+ line: f.line,
34
+ message: f.message,
35
+ fix: f.fix,
36
+ related: f.related,
37
+ })),
38
+ summary,
39
+ notes,
40
+ };
41
+ }
42
+
43
+ export function renderText({ sources, findings, summary, notes }, { colour }) {
44
+ const c = paint(colour);
45
+ const lines = [];
46
+ const project = sources.filter((s) => s.scope === 'project').length;
47
+ const user = sources.length - project;
48
+ lines.push(c(1, `memfresh: checked ${plural(sources.length, 'file')} (${project} project, ${user} user scope)`));
49
+ lines.push('');
50
+ if (!sources.length) lines.push('No memory or instruction files found.');
51
+ else if (!findings.length) lines.push(c(32, 'No findings.'));
52
+ let current;
53
+ for (const f of findings) {
54
+ if (f.file !== current) {
55
+ current = f.file;
56
+ const src = sources.find((s) => s.display === f.file);
57
+ lines.push(c(4, f.file ?? '(general)') + (src && src.scope === 'user' ? c(2, ' [user scope]') : ''));
58
+ }
59
+ const sev = f.severity === 'error' ? c(31, 'error') : f.severity === 'warn' ? c(33, 'warn ') : c(36, 'info ');
60
+ lines.push(` ${f.line ? `${f.line}`.padStart(4) : ' -'} ${sev} ${c(2, f.id.padEnd(17))} ${f.message}`);
61
+ if (f.fix) lines.push(` ${c(2, `fix: ${f.fix}`)}`);
62
+ }
63
+ lines.push('');
64
+ lines.push(`${plural(summary.total, 'finding')}: ${plural(summary.errors, 'error')}, ${plural(summary.warnings, 'warning')}, ${summary.info} info`);
65
+ for (const n of notes) lines.push(`note: ${n}`);
66
+ return lines.join('\n');
67
+ }
68
+
69
+ export function renderList(rows, { colour }) {
70
+ const c = paint(colour);
71
+ const head = ['FILE', 'READ BY', 'SCOPE', 'BYTES', 'LINES', 'MODIFIED', 'BUDGET'];
72
+ const body = rows.map((r) => [r.aliases && r.aliases.length ? `${r.path} (also ${r.aliases.join(', ')})` : r.path, r.tools.join(', '), r.scope, String(r.bytes), String(r.lines), r.modified, r.overBudget ? 'OVER' : 'ok']);
73
+ const widths = head.map((h, i) => Math.max(h.length, ...body.map((b) => b[i].length)));
74
+ const fmt = (row) => row.map((cell, i) => (i === 3 || i === 4 ? cell.padStart(widths[i]) : cell.padEnd(widths[i]))).join(' ').trimEnd();
75
+ return [c(1, fmt(head)), ...body.map(fmt)].join('\n');
76
+ }
@@ -0,0 +1,84 @@
1
+ import { UserError } from './limits.js';
2
+ import crypto from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { posix } from './util.js';
6
+
7
+ export const SNAP_DIR = path.join('.memfresh', 'snapshots');
8
+
9
+ /** Storage key for a source inside a snapshot (stable across runs). */
10
+ export function snapshotKey(src) {
11
+ if (src.scope === 'project') return `project/${src.display}`;
12
+ const d = src.display.replace(/^claude-memory:/, 'claude-memory/').replace(/^~\//, 'home/').replace(/^\//, 'abs/');
13
+ return `user/${d}`;
14
+ }
15
+
16
+ export function timestampName(now = new Date()) {
17
+ return now.toISOString().replace(/\.\d+Z$/, 'Z').replace(/:/g, '-');
18
+ }
19
+
20
+ /** What a snapshot would write (no side effects). */
21
+ export function planSnapshot(d, now = new Date()) {
22
+ const base = timestampName(now);
23
+ const snapRoot = path.join(d.root, SNAP_DIR);
24
+ let name = base;
25
+ for (let i = 2; fs.existsSync(path.join(snapRoot, name)); i++) name = `${base}-${i}`;
26
+ return {
27
+ name,
28
+ dir: path.join(snapRoot, name),
29
+ files: d.sources.map((s) => ({ key: snapshotKey(s), src: s })),
30
+ };
31
+ }
32
+
33
+ /** Write a snapshot. Never overwrites: each snapshot gets a fresh directory. */
34
+ export function writeSnapshot(d, plan, now = new Date()) {
35
+ fs.mkdirSync(path.join(plan.dir, 'files'), { recursive: true });
36
+ const gi = path.join(d.root, '.memfresh', '.gitignore');
37
+ if (!fs.existsSync(gi)) fs.writeFileSync(gi, '*\n');
38
+ const manifest = {
39
+ version: 1,
40
+ createdAt: now.toISOString(),
41
+ root: d.root,
42
+ files: [],
43
+ };
44
+ for (const { key, src } of plan.files) {
45
+ const dest = path.join(plan.dir, 'files', key);
46
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
47
+ fs.copyFileSync(src.abs, dest);
48
+ manifest.files.push({
49
+ key,
50
+ path: src.display,
51
+ abs: src.abs,
52
+ scope: src.scope,
53
+ kind: src.kind,
54
+ bytes: src.bytes,
55
+ sha256: crypto.createHash('sha256').update(fs.readFileSync(src.abs)).digest('hex'),
56
+ mtime: new Date(src.mtimeMs).toISOString(),
57
+ });
58
+ }
59
+ fs.writeFileSync(path.join(plan.dir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
60
+ return manifest;
61
+ }
62
+
63
+ export function listSnapshots(root) {
64
+ const dir = path.join(root, SNAP_DIR);
65
+ try {
66
+ return fs.readdirSync(dir).filter((n) => fs.existsSync(path.join(dir, n, 'manifest.json'))).sort();
67
+ } catch {
68
+ return [];
69
+ }
70
+ }
71
+
72
+ export function readSnapshot(root, name) {
73
+ const dir = path.join(root, SNAP_DIR, name);
74
+ let manifest;
75
+ try {
76
+ manifest = JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf8'));
77
+ if (!manifest || !Array.isArray(manifest.files)) throw new Error('no files list');
78
+ } catch (e) {
79
+ throw new UserError(`snapshot ${name} has an unreadable manifest.json (${e.message}); delete ${path.join(SNAP_DIR, name)} or pick another snapshot with --since`);
80
+ }
81
+ return { name, dir, manifest, read: (key) => fs.readFileSync(path.join(dir, 'files', key), 'utf8') };
82
+ }
83
+
84
+ export const relDisplay = (root, p) => posix(path.relative(root, p));