@fabersep/memory 0.0.0-stage → 0.2.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 +202 -0
- package/README.md +399 -2
- package/dist/src/bm25.d.ts +26 -0
- package/dist/src/bm25.js +183 -0
- package/dist/src/cache-logs.d.ts +47 -0
- package/dist/src/cache-logs.js +433 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +701 -0
- package/dist/src/compiler.d.ts +23 -0
- package/dist/src/compiler.js +211 -0
- package/dist/src/config.d.ts +20 -0
- package/dist/src/config.js +134 -0
- package/dist/src/doctor.d.ts +23 -0
- package/dist/src/doctor.js +447 -0
- package/dist/src/frontmatter.d.ts +22 -0
- package/dist/src/frontmatter.js +199 -0
- package/dist/src/git.d.ts +33 -0
- package/dist/src/git.js +251 -0
- package/dist/src/hygiene.d.ts +7 -0
- package/dist/src/hygiene.js +89 -0
- package/dist/src/importer.d.ts +34 -0
- package/dist/src/importer.js +261 -0
- package/dist/src/index.d.ts +18 -0
- package/dist/src/index.js +18 -0
- package/dist/src/init.d.ts +43 -0
- package/dist/src/init.js +280 -0
- package/dist/src/mcp.d.ts +218 -0
- package/dist/src/mcp.js +437 -0
- package/dist/src/metrics.d.ts +72 -0
- package/dist/src/metrics.js +179 -0
- package/dist/src/proposals.d.ts +34 -0
- package/dist/src/proposals.js +420 -0
- package/dist/src/stats.d.ts +165 -0
- package/dist/src/stats.js +579 -0
- package/dist/src/store.d.ts +23 -0
- package/dist/src/store.js +161 -0
- package/dist/src/sync.d.ts +15 -0
- package/dist/src/sync.js +47 -0
- package/dist/src/types.d.ts +100 -0
- package/dist/src/types.js +17 -0
- package/dist/src/ui.d.ts +19 -0
- package/dist/src/ui.js +74 -0
- package/package.json +50 -4
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export interface GitExecResult {
|
|
2
|
+
ok: boolean;
|
|
3
|
+
stdout: string;
|
|
4
|
+
stderr: string;
|
|
5
|
+
code: number | null;
|
|
6
|
+
timedOut?: boolean;
|
|
7
|
+
}
|
|
8
|
+
export declare function gitSync(args: string[], cwd?: string): GitExecResult;
|
|
9
|
+
export declare function gitAsync(args: string[], cwd?: string, timeoutMs?: number): Promise<GitExecResult>;
|
|
10
|
+
export declare function isGitRepo(dir: string): boolean;
|
|
11
|
+
export declare function findGitRoot(startDir: string): string | null;
|
|
12
|
+
export declare function ensureGitIdentity(repoDir: string): void;
|
|
13
|
+
export declare function gitInitSoloRepo(dir: string, defaultBranch?: string): void;
|
|
14
|
+
export declare function gitCloneTeamRepo(url: string, destDir: string): string;
|
|
15
|
+
export declare function getHeadSha(repoDir: string): string | null;
|
|
16
|
+
export declare function getDefaultBranch(repoDir: string): string;
|
|
17
|
+
export declare function hasRemote(repoDir: string, remote?: string): boolean;
|
|
18
|
+
export declare function getRemoteUrl(repoDir: string, remote?: string): string | null;
|
|
19
|
+
export declare function listHeadMarkdownFiles(repoDir: string, subPath?: string): string[];
|
|
20
|
+
export declare function readHeadFile(repoDir: string, relPath: string): string | null;
|
|
21
|
+
export declare function getUncommittedFiles(repoDir: string, subPath?: string): string[];
|
|
22
|
+
export declare function isDirty(repoDir: string, subPath?: string): boolean;
|
|
23
|
+
export declare function gitCommitFiles(repoDir: string, relPaths: string[], message: string): void;
|
|
24
|
+
export declare function gitPullFfOnly(repoDir: string, timeoutMs?: number): Promise<{
|
|
25
|
+
ok: boolean;
|
|
26
|
+
error?: string;
|
|
27
|
+
timedOut?: boolean;
|
|
28
|
+
dirty?: boolean;
|
|
29
|
+
}>;
|
|
30
|
+
export declare function createThrowawayWorktree(repoDir: string, defaultBranch: string): string;
|
|
31
|
+
export declare function removeThrowawayWorktree(repoDir: string, worktreeDir: string): void;
|
|
32
|
+
export declare function isBranchProtectionRejection(stderr: string): boolean;
|
|
33
|
+
export declare function buildCompareUrl(remoteUrl: string | null, defaultBranch: string, branchName: string): string;
|
package/dist/src/git.js
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { execFile, execFileSync } from 'node:child_process';
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import * as os from 'node:os';
|
|
4
|
+
import * as path from 'node:path';
|
|
5
|
+
import * as crypto from 'node:crypto';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
const execFileAsync = promisify(execFile);
|
|
8
|
+
export function gitSync(args, cwd) {
|
|
9
|
+
try {
|
|
10
|
+
const stdout = execFileSync('git', args, {
|
|
11
|
+
cwd,
|
|
12
|
+
encoding: 'utf8',
|
|
13
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
14
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
|
|
15
|
+
});
|
|
16
|
+
return { ok: true, stdout, stderr: '', code: 0 };
|
|
17
|
+
}
|
|
18
|
+
catch (err) {
|
|
19
|
+
const e = err;
|
|
20
|
+
return {
|
|
21
|
+
ok: false,
|
|
22
|
+
stdout: e.stdout ? String(e.stdout) : '',
|
|
23
|
+
stderr: e.stderr ? String(e.stderr) : e.message || '',
|
|
24
|
+
code: typeof e.status === 'number' ? e.status : 1,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export async function gitAsync(args, cwd, timeoutMs = 5000) {
|
|
29
|
+
try {
|
|
30
|
+
const { stdout, stderr } = await execFileAsync('git', args, {
|
|
31
|
+
cwd,
|
|
32
|
+
encoding: 'utf8',
|
|
33
|
+
timeout: timeoutMs,
|
|
34
|
+
killSignal: 'SIGKILL',
|
|
35
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
|
|
36
|
+
});
|
|
37
|
+
return { ok: true, stdout, stderr, code: 0 };
|
|
38
|
+
}
|
|
39
|
+
catch (err) {
|
|
40
|
+
const e = err;
|
|
41
|
+
const timedOut = Boolean(e.killed || e.signal === 'SIGKILL' || e.code === 'ETIMEDOUT');
|
|
42
|
+
return {
|
|
43
|
+
ok: false,
|
|
44
|
+
stdout: e.stdout ? String(e.stdout) : '',
|
|
45
|
+
stderr: e.stderr ? String(e.stderr) : e.message || '',
|
|
46
|
+
code: typeof e.code === 'number' ? e.code : 1,
|
|
47
|
+
timedOut,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export function isGitRepo(dir) {
|
|
52
|
+
if (!fs.existsSync(dir))
|
|
53
|
+
return false;
|
|
54
|
+
const res = gitSync(['-C', dir, 'rev-parse', '--is-inside-work-tree']);
|
|
55
|
+
return res.ok && res.stdout.trim() === 'true';
|
|
56
|
+
}
|
|
57
|
+
export function findGitRoot(startDir) {
|
|
58
|
+
if (!fs.existsSync(startDir))
|
|
59
|
+
return null;
|
|
60
|
+
const res = gitSync(['-C', startDir, 'rev-parse', '--show-toplevel']);
|
|
61
|
+
return res.ok ? res.stdout.trim() : null;
|
|
62
|
+
}
|
|
63
|
+
export function ensureGitIdentity(repoDir) {
|
|
64
|
+
const name = gitSync(['-C', repoDir, 'config', 'user.name']);
|
|
65
|
+
if (!name.ok || !name.stdout.trim()) {
|
|
66
|
+
gitSync(['-C', repoDir, 'config', 'user.name', 'Faber Memory']);
|
|
67
|
+
}
|
|
68
|
+
const email = gitSync(['-C', repoDir, 'config', 'user.email']);
|
|
69
|
+
if (!email.ok || !email.stdout.trim()) {
|
|
70
|
+
gitSync(['-C', repoDir, 'config', 'user.email', 'faber-memory@local']);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export function gitInitSoloRepo(dir, defaultBranch = 'main') {
|
|
74
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
75
|
+
if (!isGitRepo(dir)) {
|
|
76
|
+
const init = gitSync(['init', '-b', defaultBranch, dir]);
|
|
77
|
+
if (!init.ok) {
|
|
78
|
+
// Fallback for older git versions without -b
|
|
79
|
+
const fallback = gitSync(['init', dir]);
|
|
80
|
+
if (!fallback.ok) {
|
|
81
|
+
throw new Error(`git init failed: ${fallback.stderr}`);
|
|
82
|
+
}
|
|
83
|
+
gitSync(['-C', dir, 'checkout', '-b', defaultBranch]);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
ensureGitIdentity(dir);
|
|
87
|
+
if (!getHeadSha(dir)) {
|
|
88
|
+
const commit = gitSync([
|
|
89
|
+
'-C',
|
|
90
|
+
dir,
|
|
91
|
+
'commit',
|
|
92
|
+
'--allow-empty',
|
|
93
|
+
'-m',
|
|
94
|
+
'chore: initialize faber-memory repository',
|
|
95
|
+
]);
|
|
96
|
+
if (!commit.ok) {
|
|
97
|
+
throw new Error(`initial git commit failed: ${commit.stderr}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
export function gitCloneTeamRepo(url, destDir) {
|
|
102
|
+
fs.mkdirSync(path.dirname(destDir), { recursive: true });
|
|
103
|
+
const res = gitSync(['clone', url, destDir]);
|
|
104
|
+
if (!res.ok) {
|
|
105
|
+
throw new Error(`git clone failed: ${res.stderr.trim()}`);
|
|
106
|
+
}
|
|
107
|
+
ensureGitIdentity(destDir);
|
|
108
|
+
return getDefaultBranch(destDir);
|
|
109
|
+
}
|
|
110
|
+
export function getHeadSha(repoDir) {
|
|
111
|
+
if (!fs.existsSync(repoDir))
|
|
112
|
+
return null;
|
|
113
|
+
const res = gitSync(['-C', repoDir, 'rev-parse', 'HEAD']);
|
|
114
|
+
return res.ok ? res.stdout.trim() : null;
|
|
115
|
+
}
|
|
116
|
+
export function getDefaultBranch(repoDir) {
|
|
117
|
+
const sym = gitSync(['-C', repoDir, 'symbolic-ref', '--short', 'refs/remotes/origin/HEAD']);
|
|
118
|
+
if (sym.ok && sym.stdout.trim()) {
|
|
119
|
+
return sym.stdout.trim().replace(/^origin\//, '');
|
|
120
|
+
}
|
|
121
|
+
const head = gitSync(['-C', repoDir, 'rev-parse', '--abbrev-ref', 'HEAD']);
|
|
122
|
+
if (head.ok && head.stdout.trim() && head.stdout.trim() !== 'HEAD') {
|
|
123
|
+
return head.stdout.trim();
|
|
124
|
+
}
|
|
125
|
+
return 'main';
|
|
126
|
+
}
|
|
127
|
+
export function hasRemote(repoDir, remote = 'origin') {
|
|
128
|
+
const res = gitSync(['-C', repoDir, 'remote', 'get-url', remote]);
|
|
129
|
+
return res.ok && Boolean(res.stdout.trim());
|
|
130
|
+
}
|
|
131
|
+
export function getRemoteUrl(repoDir, remote = 'origin') {
|
|
132
|
+
const res = gitSync(['-C', repoDir, 'remote', 'get-url', remote]);
|
|
133
|
+
return res.ok ? res.stdout.trim() : null;
|
|
134
|
+
}
|
|
135
|
+
export function listHeadMarkdownFiles(repoDir, subPath = '') {
|
|
136
|
+
const args = ['-C', repoDir, 'ls-tree', '-r', '--name-only', 'HEAD'];
|
|
137
|
+
if (subPath)
|
|
138
|
+
args.push('--', subPath);
|
|
139
|
+
const res = gitSync(args);
|
|
140
|
+
if (!res.ok)
|
|
141
|
+
return [];
|
|
142
|
+
return res.stdout
|
|
143
|
+
.split('\n')
|
|
144
|
+
.map((line) => line.trim())
|
|
145
|
+
.filter((line) => line.length > 0 && line.endsWith('.md'));
|
|
146
|
+
}
|
|
147
|
+
export function readHeadFile(repoDir, relPath) {
|
|
148
|
+
const posixPath = relPath.split(path.sep).join('/');
|
|
149
|
+
const res = gitSync(['-C', repoDir, 'show', `HEAD:${posixPath}`]);
|
|
150
|
+
return res.ok ? res.stdout : null;
|
|
151
|
+
}
|
|
152
|
+
export function getUncommittedFiles(repoDir, subPath = '') {
|
|
153
|
+
const args = ['--no-optional-locks', '-C', repoDir, 'status', '--porcelain'];
|
|
154
|
+
if (subPath)
|
|
155
|
+
args.push('--', subPath);
|
|
156
|
+
const res = gitSync(args);
|
|
157
|
+
if (!res.ok)
|
|
158
|
+
return [];
|
|
159
|
+
return res.stdout
|
|
160
|
+
.split('\n')
|
|
161
|
+
.filter((line) => line.trim().length > 0)
|
|
162
|
+
.map((line) => line.slice(3).trim());
|
|
163
|
+
}
|
|
164
|
+
export function isDirty(repoDir, subPath = '') {
|
|
165
|
+
return getUncommittedFiles(repoDir, subPath).length > 0;
|
|
166
|
+
}
|
|
167
|
+
export function gitCommitFiles(repoDir, relPaths, message) {
|
|
168
|
+
ensureGitIdentity(repoDir);
|
|
169
|
+
const add = gitSync(['-C', repoDir, 'add', '--', ...relPaths]);
|
|
170
|
+
if (!add.ok) {
|
|
171
|
+
throw new Error(`git add failed: ${add.stderr.trim()}`);
|
|
172
|
+
}
|
|
173
|
+
const commit = gitSync(['-C', repoDir, 'commit', '-m', message]);
|
|
174
|
+
if (!commit.ok) {
|
|
175
|
+
throw new Error(`git commit failed: ${commit.stderr.trim()}`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
export async function gitPullFfOnly(repoDir, timeoutMs = 5000) {
|
|
179
|
+
if (isDirty(repoDir)) {
|
|
180
|
+
return {
|
|
181
|
+
ok: false,
|
|
182
|
+
dirty: true,
|
|
183
|
+
error: `Serving clone at ${repoDir} has uncommitted local edits; refusing git pull --ff-only.`,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
if (!hasRemote(repoDir)) {
|
|
187
|
+
return { ok: true };
|
|
188
|
+
}
|
|
189
|
+
const res = await gitAsync(['-C', repoDir, 'pull', '--ff-only'], undefined, timeoutMs);
|
|
190
|
+
if (res.ok)
|
|
191
|
+
return { ok: true };
|
|
192
|
+
if (res.timedOut) {
|
|
193
|
+
return { ok: false, timedOut: true, error: `git pull --ff-only timed out after ${timeoutMs}ms` };
|
|
194
|
+
}
|
|
195
|
+
return { ok: false, error: res.stderr.trim() || 'git pull --ff-only failed' };
|
|
196
|
+
}
|
|
197
|
+
export function createThrowawayWorktree(repoDir, defaultBranch) {
|
|
198
|
+
// Fetch latest remote refs if available (best effort)
|
|
199
|
+
if (hasRemote(repoDir)) {
|
|
200
|
+
gitSync(['-C', repoDir, 'fetch', 'origin', defaultBranch]);
|
|
201
|
+
}
|
|
202
|
+
const tmpDir = path.join(os.tmpdir(), `faber-mem-wt-${process.pid}-${crypto.randomBytes(4).toString('hex')}`);
|
|
203
|
+
const baseRef = gitSync(['-C', repoDir, 'rev-parse', '--verify', `origin/${defaultBranch}`]).ok
|
|
204
|
+
? `origin/${defaultBranch}`
|
|
205
|
+
: defaultBranch;
|
|
206
|
+
const add = gitSync(['-C', repoDir, 'worktree', 'add', '--detach', tmpDir, baseRef]);
|
|
207
|
+
if (!add.ok) {
|
|
208
|
+
throw new Error(`git worktree add failed: ${add.stderr.trim()}`);
|
|
209
|
+
}
|
|
210
|
+
ensureGitIdentity(tmpDir);
|
|
211
|
+
return tmpDir;
|
|
212
|
+
}
|
|
213
|
+
export function removeThrowawayWorktree(repoDir, worktreeDir) {
|
|
214
|
+
gitSync(['-C', repoDir, 'worktree', 'remove', '--force', worktreeDir]);
|
|
215
|
+
if (fs.existsSync(worktreeDir)) {
|
|
216
|
+
fs.rmSync(worktreeDir, { recursive: true, force: true });
|
|
217
|
+
}
|
|
218
|
+
gitSync(['-C', repoDir, 'worktree', 'prune']);
|
|
219
|
+
}
|
|
220
|
+
export function isBranchProtectionRejection(stderr) {
|
|
221
|
+
const lower = stderr.toLowerCase();
|
|
222
|
+
return (lower.includes('protected branch') ||
|
|
223
|
+
lower.includes('branch protection') ||
|
|
224
|
+
lower.includes('pre-receive hook declined') ||
|
|
225
|
+
lower.includes('gh006') ||
|
|
226
|
+
lower.includes('cannot push directly') ||
|
|
227
|
+
lower.includes('direct push'));
|
|
228
|
+
}
|
|
229
|
+
export function buildCompareUrl(remoteUrl, defaultBranch, branchName) {
|
|
230
|
+
if (!remoteUrl) {
|
|
231
|
+
return `branch:${branchName} (open a pull request against ${defaultBranch})`;
|
|
232
|
+
}
|
|
233
|
+
let webUrl = remoteUrl.trim();
|
|
234
|
+
const sshMatch = webUrl.match(/^git@([^:]+):(.+?)(?:\.git)?$/);
|
|
235
|
+
if (sshMatch) {
|
|
236
|
+
webUrl = `https://${sshMatch[1]}/${sshMatch[2]}`;
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
webUrl = webUrl.replace(/\.git$/, '');
|
|
240
|
+
}
|
|
241
|
+
if (webUrl.includes('gitlab')) {
|
|
242
|
+
return `${webUrl}/-/merge_requests/new?merge_request[source_branch]=${encodeURIComponent(branchName)}&merge_request[target_branch]=${encodeURIComponent(defaultBranch)}`;
|
|
243
|
+
}
|
|
244
|
+
if (webUrl.includes('bitbucket')) {
|
|
245
|
+
return `${webUrl}/pull-requests/new?source=${encodeURIComponent(branchName)}&dest=${encodeURIComponent(defaultBranch)}`;
|
|
246
|
+
}
|
|
247
|
+
if (webUrl.startsWith('http://') || webUrl.startsWith('https://')) {
|
|
248
|
+
return `${webUrl}/compare/${encodeURIComponent(defaultBranch)}...${encodeURIComponent(branchName)}?expand=1`;
|
|
249
|
+
}
|
|
250
|
+
return `${webUrl}/compare/${defaultBranch}...${branchName}`;
|
|
251
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { HygieneFinding } from './types.js';
|
|
2
|
+
export declare function scanHygiene(content: string): HygieneFinding[];
|
|
3
|
+
export declare function normalizeMachinePaths(content: string): {
|
|
4
|
+
content: string;
|
|
5
|
+
replacements: number;
|
|
6
|
+
};
|
|
7
|
+
export declare function formatHygieneErrors(findings: HygieneFinding[], sourceName?: string): string;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
const RULES = [
|
|
2
|
+
{
|
|
3
|
+
category: 'secret',
|
|
4
|
+
pattern: 'private-key',
|
|
5
|
+
regex: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
|
|
6
|
+
label: 'Private key header detected',
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
category: 'secret',
|
|
10
|
+
pattern: 'jwt',
|
|
11
|
+
regex: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/,
|
|
12
|
+
label: 'JWT token detected',
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
category: 'secret',
|
|
16
|
+
pattern: 'bearer-token',
|
|
17
|
+
regex: /\bBearer\s+[A-Za-z0-9._~+/-]{12,}/i,
|
|
18
|
+
label: 'Bearer token detected',
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
category: 'secret',
|
|
22
|
+
pattern: 'api-key-prefix',
|
|
23
|
+
regex: /\b(?:sk-[A-Za-z0-9_-]{16,}|sk_live_[A-Za-z0-9]{12,}|ghp_[A-Za-z0-9]{20,}|gho_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|xox[baprs]-[A-Za-z0-9-]{10,})\b/,
|
|
24
|
+
label: 'Known API key prefix detected',
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
category: 'secret',
|
|
28
|
+
pattern: 'credential-assignment',
|
|
29
|
+
regex: /\b(?:api[_-]?key|secret[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|password|passwd)\s*[:=]\s*["']?[A-Za-z0-9._~+/=-]{12,}["']?/i,
|
|
30
|
+
label: 'Credential assignment detected',
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
category: 'machine-path',
|
|
34
|
+
pattern: 'macos-user-path',
|
|
35
|
+
regex: /\/Users\/[A-Za-z0-9._-]+\//,
|
|
36
|
+
label: 'Machine-specific macOS home path detected',
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
category: 'machine-path',
|
|
40
|
+
pattern: 'linux-user-path',
|
|
41
|
+
regex: /\/home\/[A-Za-z0-9._-]+\//,
|
|
42
|
+
label: 'Machine-specific Linux home path detected',
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
category: 'machine-path',
|
|
46
|
+
pattern: 'windows-user-path',
|
|
47
|
+
regex: /\b[A-Za-z]:\\Users\\[A-Za-z0-9._-]+\\/,
|
|
48
|
+
label: 'Machine-specific Windows home path detected',
|
|
49
|
+
},
|
|
50
|
+
];
|
|
51
|
+
export function scanHygiene(content) {
|
|
52
|
+
const findings = [];
|
|
53
|
+
const lines = content.replace(/\r\n/g, '\n').split('\n');
|
|
54
|
+
for (let i = 0; i < lines.length; i++) {
|
|
55
|
+
const lineText = lines[i];
|
|
56
|
+
for (const rule of RULES) {
|
|
57
|
+
const match = rule.regex.exec(lineText);
|
|
58
|
+
if (match) {
|
|
59
|
+
const redactedSnippet = lineText
|
|
60
|
+
.replace(rule.regex, rule.category === 'secret' ? '[REDACTED]' : '[MACHINE_PATH]')
|
|
61
|
+
.trim()
|
|
62
|
+
.slice(0, 120);
|
|
63
|
+
findings.push({
|
|
64
|
+
line: i + 1,
|
|
65
|
+
category: rule.category,
|
|
66
|
+
pattern: rule.pattern,
|
|
67
|
+
message: `${rule.label} (${rule.category}/${rule.pattern}) at line ${i + 1}`,
|
|
68
|
+
redactedSnippet,
|
|
69
|
+
});
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return findings;
|
|
75
|
+
}
|
|
76
|
+
export function normalizeMachinePaths(content) {
|
|
77
|
+
let replacements = 0;
|
|
78
|
+
const next = content.replace(/(?:\/Users\/|\/home\/)[A-Za-z0-9._-]+\//g, () => {
|
|
79
|
+
replacements++;
|
|
80
|
+
return '~/';
|
|
81
|
+
});
|
|
82
|
+
return { content: next, replacements };
|
|
83
|
+
}
|
|
84
|
+
export function formatHygieneErrors(findings, sourceName) {
|
|
85
|
+
const prefix = sourceName ? `${sourceName}: ` : '';
|
|
86
|
+
return findings
|
|
87
|
+
.map((f) => `${prefix}line ${f.line} [${f.category}/${f.pattern}]: ${f.message} (${f.redactedSnippet})`)
|
|
88
|
+
.join('\n');
|
|
89
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Proposal, Scope, UserConfig } from './types.js';
|
|
2
|
+
export type ImportSourceType = 'markdown-dir' | 'claude-memory' | 'agents-md' | 'cursor-rules';
|
|
3
|
+
export declare const CLAUDE_DISABLE_AUTOMEMORY_GUIDANCE = "To disable Claude Code auto-memory so future writes do not bypass pre-memory, set \"autoMemoryEnabled\": false in ~/.claude/settings.json (or CLAUDE_CODE_DISABLE_AUTO_MEMORY=1).";
|
|
4
|
+
export interface ImportResult {
|
|
5
|
+
staged: Proposal[];
|
|
6
|
+
approvedIds: string[];
|
|
7
|
+
duplicates: {
|
|
8
|
+
source: string;
|
|
9
|
+
matchedId: string;
|
|
10
|
+
summary: string;
|
|
11
|
+
}[];
|
|
12
|
+
skippedHygiene: {
|
|
13
|
+
source: string;
|
|
14
|
+
reason: string;
|
|
15
|
+
snippet?: string;
|
|
16
|
+
anchor: string;
|
|
17
|
+
}[];
|
|
18
|
+
skippedIndex: string[];
|
|
19
|
+
normalizedPaths: {
|
|
20
|
+
source: string;
|
|
21
|
+
replacements: number;
|
|
22
|
+
}[];
|
|
23
|
+
notes: string[];
|
|
24
|
+
}
|
|
25
|
+
export declare function runImport(config: UserConfig, options: {
|
|
26
|
+
from: ImportSourceType;
|
|
27
|
+
sourcePath: string;
|
|
28
|
+
scope?: Scope;
|
|
29
|
+
splitHeadings?: boolean;
|
|
30
|
+
normalizePaths?: boolean;
|
|
31
|
+
approve?: boolean;
|
|
32
|
+
homeDir?: string;
|
|
33
|
+
cwd?: string;
|
|
34
|
+
}): Promise<ImportResult>;
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { findNearDuplicates } from './bm25.js';
|
|
4
|
+
import { getHomeDir } from './config.js';
|
|
5
|
+
import { parseMarkdownWithFrontmatter, slugify } from './frontmatter.js';
|
|
6
|
+
import { normalizeMachinePaths, scanHygiene } from './hygiene.js';
|
|
7
|
+
import { appendMetric } from './metrics.js';
|
|
8
|
+
import { approveProposalsBatch, createProposal, reconcileAwaitingCommitProposals, } from './proposals.js';
|
|
9
|
+
import { loadAllScopes, resolveProjectRoot } from './store.js';
|
|
10
|
+
import { VALID_TYPES } from './types.js';
|
|
11
|
+
export const CLAUDE_DISABLE_AUTOMEMORY_GUIDANCE = 'To disable Claude Code auto-memory so future writes do not bypass pre-memory, set "autoMemoryEnabled": false in ~/.claude/settings.json (or CLAUDE_CODE_DISABLE_AUTO_MEMORY=1).';
|
|
12
|
+
function inferType(raw, filename) {
|
|
13
|
+
if (typeof raw.type === 'string' && VALID_TYPES.includes(raw.type)) {
|
|
14
|
+
return raw.type;
|
|
15
|
+
}
|
|
16
|
+
const lower = filename.toLowerCase();
|
|
17
|
+
if (lower.includes('decision'))
|
|
18
|
+
return 'decision';
|
|
19
|
+
if (lower.includes('lesson') || lower.includes('mistake'))
|
|
20
|
+
return 'lesson';
|
|
21
|
+
if (lower.includes('pref') || lower.includes('style'))
|
|
22
|
+
return 'preference';
|
|
23
|
+
if (lower.includes('ref') || lower.includes('catalog'))
|
|
24
|
+
return 'reference';
|
|
25
|
+
return 'rule';
|
|
26
|
+
}
|
|
27
|
+
function inferSummary(raw, body, fallbackName) {
|
|
28
|
+
for (const key of ['summary', 'description', 'name', 'title']) {
|
|
29
|
+
const val = raw[key];
|
|
30
|
+
if (typeof val === 'string' && val.trim()) {
|
|
31
|
+
return val.replace(/\s+/g, ' ').trim();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const firstHeading = body
|
|
35
|
+
.split('\n')
|
|
36
|
+
.map((l) => l.trim())
|
|
37
|
+
.find((l) => l.startsWith('#'));
|
|
38
|
+
if (firstHeading) {
|
|
39
|
+
return firstHeading.replace(/^#+\s*/, '').trim();
|
|
40
|
+
}
|
|
41
|
+
const firstLine = body
|
|
42
|
+
.split('\n')
|
|
43
|
+
.map((l) => l.trim())
|
|
44
|
+
.find((l) => l.length > 0);
|
|
45
|
+
return (firstLine || fallbackName).slice(0, 140);
|
|
46
|
+
}
|
|
47
|
+
function splitTopLevelHeadings(content) {
|
|
48
|
+
const lines = content.replace(/\r\n/g, '\n').split('\n');
|
|
49
|
+
const sections = [];
|
|
50
|
+
let current = null;
|
|
51
|
+
for (const line of lines) {
|
|
52
|
+
const m = line.match(/^#{1,2}\s+(.+)$/);
|
|
53
|
+
if (m) {
|
|
54
|
+
if (current && current.lines.join('\n').trim()) {
|
|
55
|
+
sections.push(current);
|
|
56
|
+
}
|
|
57
|
+
current = { title: m[1].trim(), lines: [line] };
|
|
58
|
+
}
|
|
59
|
+
else if (current) {
|
|
60
|
+
current.lines.push(line);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (current && current.lines.join('\n').trim()) {
|
|
64
|
+
sections.push(current);
|
|
65
|
+
}
|
|
66
|
+
return sections.map((s) => ({ title: s.title, body: s.lines.join('\n').trim() }));
|
|
67
|
+
}
|
|
68
|
+
function collectMarkdownFiles(targetPath) {
|
|
69
|
+
const stat = fs.statSync(targetPath);
|
|
70
|
+
if (stat.isFile())
|
|
71
|
+
return [targetPath];
|
|
72
|
+
const results = [];
|
|
73
|
+
for (const entry of fs.readdirSync(targetPath, { withFileTypes: true })) {
|
|
74
|
+
const full = path.join(targetPath, entry.name);
|
|
75
|
+
if (entry.isDirectory()) {
|
|
76
|
+
if (entry.name.startsWith('.'))
|
|
77
|
+
continue;
|
|
78
|
+
results.push(...collectMarkdownFiles(full));
|
|
79
|
+
}
|
|
80
|
+
else if (entry.isFile() && /\.(md|mdc)$/i.test(entry.name)) {
|
|
81
|
+
results.push(full);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return results.sort();
|
|
85
|
+
}
|
|
86
|
+
export async function runImport(config, options) {
|
|
87
|
+
const homeDir = options.homeDir || getHomeDir();
|
|
88
|
+
const targetScope = options.scope || 'personal';
|
|
89
|
+
const cwd = options.cwd || process.cwd();
|
|
90
|
+
if (options.approve && targetScope !== 'personal') {
|
|
91
|
+
throw new Error('--approve during import is allowed in solo (personal) mode only.');
|
|
92
|
+
}
|
|
93
|
+
const projectRes = resolveProjectRoot(undefined, cwd);
|
|
94
|
+
const loaded = loadAllScopes(config, projectRes);
|
|
95
|
+
const pending = reconcileAwaitingCommitProposals(homeDir);
|
|
96
|
+
const staged = [];
|
|
97
|
+
const duplicates = [];
|
|
98
|
+
const skippedHygiene = [];
|
|
99
|
+
const skippedIndex = [];
|
|
100
|
+
const normalizedPaths = [];
|
|
101
|
+
const notes = [];
|
|
102
|
+
if (options.from === 'claude-memory') {
|
|
103
|
+
notes.push(CLAUDE_DISABLE_AUTOMEMORY_GUIDANCE);
|
|
104
|
+
}
|
|
105
|
+
const candidates = [];
|
|
106
|
+
if (options.from === 'markdown-dir' || options.from === 'claude-memory') {
|
|
107
|
+
const files = collectMarkdownFiles(options.sourcePath);
|
|
108
|
+
for (const filePath of files) {
|
|
109
|
+
const base = path.basename(filePath);
|
|
110
|
+
const lowerBase = base.toLowerCase();
|
|
111
|
+
if (lowerBase === 'memory.md' ||
|
|
112
|
+
lowerBase === 'catalog.md' ||
|
|
113
|
+
lowerBase === 'readme.md' ||
|
|
114
|
+
lowerBase === 'index.md') {
|
|
115
|
+
skippedIndex.push(filePath);
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
const raw = fs.readFileSync(filePath, 'utf8');
|
|
119
|
+
const parsed = parseMarkdownWithFrontmatter(raw);
|
|
120
|
+
const summary = inferSummary(parsed.rawFrontmatter, parsed.body, base);
|
|
121
|
+
const type = inferType(parsed.rawFrontmatter, base);
|
|
122
|
+
const tags = [];
|
|
123
|
+
if (Array.isArray(parsed.rawFrontmatter.tags)) {
|
|
124
|
+
tags.push(...parsed.rawFrontmatter.tags.map(String));
|
|
125
|
+
}
|
|
126
|
+
const meta = parsed.rawFrontmatter.metadata;
|
|
127
|
+
if (meta && typeof meta.scope === 'string' && meta.scope.trim()) {
|
|
128
|
+
tags.push(`legacy-scope:${meta.scope.trim()}`);
|
|
129
|
+
}
|
|
130
|
+
candidates.push({
|
|
131
|
+
source: filePath,
|
|
132
|
+
entryId: slugify(base),
|
|
133
|
+
summary,
|
|
134
|
+
type,
|
|
135
|
+
tags,
|
|
136
|
+
body: parsed.body.trim() || summary,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
// agents-md or cursor-rules
|
|
142
|
+
const files = collectMarkdownFiles(options.sourcePath);
|
|
143
|
+
for (const filePath of files) {
|
|
144
|
+
const base = path.basename(filePath);
|
|
145
|
+
const raw = fs.readFileSync(filePath, 'utf8');
|
|
146
|
+
const parsed = parseMarkdownWithFrontmatter(raw);
|
|
147
|
+
if (options.splitHeadings) {
|
|
148
|
+
const sections = splitTopLevelHeadings(parsed.body);
|
|
149
|
+
if (sections.length > 0) {
|
|
150
|
+
for (const sec of sections) {
|
|
151
|
+
candidates.push({
|
|
152
|
+
source: `${filePath}#${sec.title}`,
|
|
153
|
+
entryId: slugify(sec.title),
|
|
154
|
+
summary: sec.title,
|
|
155
|
+
type: 'rule',
|
|
156
|
+
tags: [options.from],
|
|
157
|
+
body: sec.body,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const summary = inferSummary(parsed.rawFrontmatter, parsed.body, base);
|
|
164
|
+
candidates.push({
|
|
165
|
+
source: filePath,
|
|
166
|
+
entryId: slugify(base),
|
|
167
|
+
summary,
|
|
168
|
+
type: 'rule',
|
|
169
|
+
tags: [options.from],
|
|
170
|
+
body: parsed.body.trim() || summary,
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
for (const c of candidates) {
|
|
175
|
+
let summary = c.summary;
|
|
176
|
+
let body = c.body;
|
|
177
|
+
if (options.normalizePaths) {
|
|
178
|
+
const sNorm = normalizeMachinePaths(summary);
|
|
179
|
+
const bNorm = normalizeMachinePaths(body);
|
|
180
|
+
summary = sNorm.content;
|
|
181
|
+
body = bNorm.content;
|
|
182
|
+
const total = sNorm.replacements + bNorm.replacements;
|
|
183
|
+
if (total > 0) {
|
|
184
|
+
normalizedPaths.push({ source: c.source, replacements: total });
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const hygiene = scanHygiene(`${summary}\n${body}`);
|
|
188
|
+
if (hygiene.length > 0) {
|
|
189
|
+
const hasSecret = hygiene.some((h) => h.category === 'secret');
|
|
190
|
+
appendMetric({
|
|
191
|
+
type: 'propose',
|
|
192
|
+
ts: new Date().toISOString(),
|
|
193
|
+
source: 'import',
|
|
194
|
+
scope: targetScope,
|
|
195
|
+
action: 'create',
|
|
196
|
+
outcome: 'hygiene_blocked',
|
|
197
|
+
hygiene_category: hasSecret ? 'secret' : 'machine-path',
|
|
198
|
+
}, homeDir);
|
|
199
|
+
skippedHygiene.push({
|
|
200
|
+
source: c.source,
|
|
201
|
+
reason: hygiene.map((h) => h.message).join('; '),
|
|
202
|
+
snippet: hygiene[0].redactedSnippet,
|
|
203
|
+
anchor: hasSecret ? 'secrets-detected' : 'machine-specific-paths',
|
|
204
|
+
});
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
const dupes = findNearDuplicates(summary, body, loaded.activeEntries, [...pending, ...staged], config.similarityThreshold);
|
|
208
|
+
if (dupes.length > 0) {
|
|
209
|
+
appendMetric({
|
|
210
|
+
type: 'propose',
|
|
211
|
+
ts: new Date().toISOString(),
|
|
212
|
+
source: 'import',
|
|
213
|
+
scope: targetScope,
|
|
214
|
+
action: 'create',
|
|
215
|
+
outcome: 'duplicate_blocked',
|
|
216
|
+
}, homeDir);
|
|
217
|
+
duplicates.push({
|
|
218
|
+
source: c.source,
|
|
219
|
+
matchedId: dupes[0].id,
|
|
220
|
+
summary: dupes[0].summary,
|
|
221
|
+
});
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const proposal = createProposal(config, {
|
|
225
|
+
scope: targetScope,
|
|
226
|
+
action: 'create',
|
|
227
|
+
entryId: c.entryId,
|
|
228
|
+
summary,
|
|
229
|
+
type: c.type,
|
|
230
|
+
tags: c.tags,
|
|
231
|
+
body,
|
|
232
|
+
projectRootPath: targetScope === 'project' ? projectRes.projectRoot : undefined,
|
|
233
|
+
}, homeDir);
|
|
234
|
+
appendMetric({
|
|
235
|
+
type: 'propose',
|
|
236
|
+
ts: new Date().toISOString(),
|
|
237
|
+
source: 'import',
|
|
238
|
+
scope: targetScope,
|
|
239
|
+
action: 'create',
|
|
240
|
+
outcome: 'staged',
|
|
241
|
+
}, homeDir);
|
|
242
|
+
staged.push(proposal);
|
|
243
|
+
}
|
|
244
|
+
const approvedIds = [];
|
|
245
|
+
if (options.approve && staged.length > 0) {
|
|
246
|
+
const outcome = await approveProposalsBatch(config, staged, { homeDir });
|
|
247
|
+
if (!outcome.ok) {
|
|
248
|
+
throw new Error(`Import --approve failed: ${outcome.errors.join('; ')}`);
|
|
249
|
+
}
|
|
250
|
+
approvedIds.push(...outcome.approvedIds);
|
|
251
|
+
}
|
|
252
|
+
return {
|
|
253
|
+
staged,
|
|
254
|
+
approvedIds,
|
|
255
|
+
duplicates,
|
|
256
|
+
skippedHygiene,
|
|
257
|
+
skippedIndex,
|
|
258
|
+
normalizedPaths,
|
|
259
|
+
notes,
|
|
260
|
+
};
|
|
261
|
+
}
|