@fabersep/memory 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,134 @@
1
+ import * as crypto from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import * as os from 'node:os';
4
+ import * as path from 'node:path';
5
+ import { DEFAULT_SIMILARITY_THRESHOLD, DEFAULT_STALE_DAYS, DEFAULT_TOKEN_BUDGET, } from './types.js';
6
+ export function getHomeDir() {
7
+ return process.env.FABER_MEMORY_HOME || path.join(os.homedir(), '.config', 'faber-memory');
8
+ }
9
+ export function getConfigPath(homeDir = getHomeDir()) {
10
+ return path.join(homeDir, 'config.json');
11
+ }
12
+ export function getStateDir(homeDir = getHomeDir()) {
13
+ return path.join(homeDir, 'state');
14
+ }
15
+ export function getCompiledL0Path(homeDir = getHomeDir()) {
16
+ return path.join(getStateDir(homeDir), 'MEMORY.md');
17
+ }
18
+ export function getPreMemoryRootDir(rootUuid, homeDir = getHomeDir()) {
19
+ return path.join(getStateDir(homeDir), 'pre-memory', rootUuid);
20
+ }
21
+ export function getAllPreMemoryBaseDir(homeDir = getHomeDir()) {
22
+ return path.join(getStateDir(homeDir), 'pre-memory');
23
+ }
24
+ export function getDefaultPersonalPath() {
25
+ return path.join(os.homedir(), '.faber', 'memory');
26
+ }
27
+ export function getProjectRootUuid(projectRootPath) {
28
+ const normalized = path.resolve(projectRootPath);
29
+ const hash = crypto.createHash('sha256').update(normalized).digest('hex').slice(0, 16);
30
+ return `proj-${hash}`;
31
+ }
32
+ export function sanitizeUserTag(raw) {
33
+ const source = raw || safeUsername();
34
+ const cleaned = source.toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 8);
35
+ return cleaned || 'dev';
36
+ }
37
+ function safeUsername() {
38
+ try {
39
+ return os.userInfo().username || 'dev';
40
+ }
41
+ catch {
42
+ return process.env.USER || process.env.USERNAME || 'dev';
43
+ }
44
+ }
45
+ export function defaultConfig() {
46
+ return {
47
+ version: 1,
48
+ userTag: sanitizeUserTag(),
49
+ tokenBudget: DEFAULT_TOKEN_BUDGET,
50
+ staleDays: DEFAULT_STALE_DAYS,
51
+ similarityThreshold: DEFAULT_SIMILARITY_THRESHOLD,
52
+ roots: {},
53
+ };
54
+ }
55
+ export function loadConfig(homeDir = getHomeDir()) {
56
+ const cfgPath = getConfigPath(homeDir);
57
+ if (!fs.existsSync(cfgPath)) {
58
+ return defaultConfig();
59
+ }
60
+ const raw = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
61
+ return {
62
+ version: 1,
63
+ userTag: raw.userTag || sanitizeUserTag(),
64
+ tokenBudget: typeof raw.tokenBudget === 'number' ? raw.tokenBudget : DEFAULT_TOKEN_BUDGET,
65
+ staleDays: typeof raw.staleDays === 'number' ? raw.staleDays : DEFAULT_STALE_DAYS,
66
+ similarityThreshold: typeof raw.similarityThreshold === 'number'
67
+ ? raw.similarityThreshold
68
+ : DEFAULT_SIMILARITY_THRESHOLD,
69
+ roots: raw.roots || {},
70
+ };
71
+ }
72
+ export function saveConfig(config, homeDir = getHomeDir()) {
73
+ fs.mkdirSync(homeDir, { recursive: true });
74
+ const cfgPath = getConfigPath(homeDir);
75
+ const tmpPath = `${cfgPath}.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`;
76
+ fs.writeFileSync(tmpPath, JSON.stringify(config, null, 2) + '\n', 'utf8');
77
+ fs.renameSync(tmpPath, cfgPath);
78
+ }
79
+ export function generateUuid() {
80
+ return crypto.randomUUID();
81
+ }
82
+ export function generateProposalId(userTag) {
83
+ const tag = sanitizeUserTag(userTag);
84
+ const suffix = crypto.randomBytes(2).toString('hex');
85
+ return `p-${tag}-${suffix}`;
86
+ }
87
+ /**
88
+ * Per-state-directory advisory lock using atomic mkdir with bounded retry.
89
+ * Ensures concurrent compile/approve calls never interleave writes.
90
+ */
91
+ export function withStateLock(fn, homeDir = getHomeDir(), timeoutMs = 10000) {
92
+ const stateDir = getStateDir(homeDir);
93
+ fs.mkdirSync(stateDir, { recursive: true });
94
+ const lockDir = path.join(stateDir, '.state.lock');
95
+ const deadline = Date.now() + timeoutMs;
96
+ while (true) {
97
+ try {
98
+ fs.mkdirSync(lockDir);
99
+ fs.writeFileSync(path.join(lockDir, 'pid'), String(process.pid), 'utf8');
100
+ break;
101
+ }
102
+ catch (err) {
103
+ const code = err.code;
104
+ if (code !== 'EEXIST')
105
+ throw err;
106
+ // Clear stale locks older than 30s
107
+ try {
108
+ const stat = fs.statSync(lockDir);
109
+ if (Date.now() - stat.mtimeMs > 30000) {
110
+ fs.rmSync(lockDir, { recursive: true, force: true });
111
+ continue;
112
+ }
113
+ }
114
+ catch {
115
+ continue;
116
+ }
117
+ if (Date.now() >= deadline) {
118
+ throw new Error(`Timed out waiting for state lock at ${lockDir}`);
119
+ }
120
+ sleepSync(15 + Math.floor(Math.random() * 25));
121
+ }
122
+ }
123
+ try {
124
+ return fn();
125
+ }
126
+ finally {
127
+ fs.rmSync(lockDir, { recursive: true, force: true });
128
+ }
129
+ }
130
+ function sleepSync(ms) {
131
+ const buf = new SharedArrayBuffer(4);
132
+ const arr = new Int32Array(buf);
133
+ Atomics.wait(arr, 0, 0, ms);
134
+ }
@@ -0,0 +1,22 @@
1
+ import { EntryFrontmatter, EntryStatus, EntryType, L0Mode, Scope } from './types.js';
2
+ export interface ParsedMarkdown {
3
+ rawFrontmatter: Record<string, unknown>;
4
+ hasFrontmatter: boolean;
5
+ body: string;
6
+ }
7
+ export declare function parseMarkdownWithFrontmatter(content: string): ParsedMarkdown;
8
+ export declare function validateFrontmatter(raw: Record<string, unknown>, scope: Scope): {
9
+ frontmatter?: EntryFrontmatter;
10
+ errors: string[];
11
+ };
12
+ export declare function serializeEntryMarkdown(fm: {
13
+ summary: string;
14
+ type: EntryType;
15
+ tags?: string[];
16
+ status?: EntryStatus;
17
+ superseded_by?: string;
18
+ l0?: L0Mode;
19
+ last_verified?: string;
20
+ }, body: string): string;
21
+ export declare function extractLinks(body: string): string[];
22
+ export declare function slugify(input: string): string;
@@ -0,0 +1,199 @@
1
+ import { VALID_L0_MODES, VALID_STATUSES, VALID_TYPES, } from './types.js';
2
+ export function parseMarkdownWithFrontmatter(content) {
3
+ const normalized = content.replace(/\r\n/g, '\n');
4
+ if (!normalized.startsWith('---\n')) {
5
+ return { rawFrontmatter: {}, hasFrontmatter: false, body: normalized };
6
+ }
7
+ const endIdx = normalized.indexOf('\n---', 3);
8
+ if (endIdx === -1) {
9
+ return { rawFrontmatter: {}, hasFrontmatter: false, body: normalized };
10
+ }
11
+ const afterClose = endIdx + 4;
12
+ if (afterClose < normalized.length &&
13
+ normalized[afterClose] !== '\n' &&
14
+ normalized[afterClose] !== ' ') {
15
+ return { rawFrontmatter: {}, hasFrontmatter: false, body: normalized };
16
+ }
17
+ const yamlBlock = normalized.slice(4, endIdx);
18
+ const rest = normalized.slice(afterClose).replace(/^\n/, '');
19
+ return {
20
+ rawFrontmatter: parseSimpleYaml(yamlBlock),
21
+ hasFrontmatter: true,
22
+ body: rest,
23
+ };
24
+ }
25
+ function parseSimpleYaml(yamlText) {
26
+ const result = {};
27
+ const lines = yamlText.split('\n');
28
+ let i = 0;
29
+ while (i < lines.length) {
30
+ const line = lines[i];
31
+ if (!line.trim() || line.trim().startsWith('#')) {
32
+ i++;
33
+ continue;
34
+ }
35
+ const keyMatch = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
36
+ if (!keyMatch) {
37
+ i++;
38
+ continue;
39
+ }
40
+ const key = keyMatch[1];
41
+ const valStr = keyMatch[2].trim();
42
+ if (valStr === '' || valStr === '|' || valStr === '>') {
43
+ // Check indented block: array, nested map, or multiline scalar
44
+ const blockLines = [];
45
+ let j = i + 1;
46
+ while (j < lines.length && (/^\s+/.test(lines[j]) || lines[j].trim() === '')) {
47
+ if (lines[j].trim() === '' && valStr === '') {
48
+ j++;
49
+ continue;
50
+ }
51
+ blockLines.push(lines[j]);
52
+ j++;
53
+ }
54
+ if (valStr === '|' || valStr === '>') {
55
+ const cleaned = blockLines.map((l) => l.replace(/^\s{2}/, ''));
56
+ result[key] = (valStr === '>' ? cleaned.join(' ') : cleaned.join('\n')).trim();
57
+ }
58
+ else if (blockLines.length > 0 && blockLines.every((l) => /^\s*-\s+/.test(l))) {
59
+ result[key] = blockLines.map((l) => unquote(l.replace(/^\s*-\s+/, '').trim()));
60
+ }
61
+ else if (blockLines.length > 0 && blockLines.some((l) => /^\s+[A-Za-z0-9_-]+:/.test(l))) {
62
+ const nested = {};
63
+ for (const bl of blockLines) {
64
+ const nm = bl.match(/^\s+([A-Za-z0-9_-]+):\s*(.*)$/);
65
+ if (nm)
66
+ nested[nm[1]] = unquote(nm[2].trim());
67
+ }
68
+ result[key] = nested;
69
+ }
70
+ else {
71
+ result[key] = '';
72
+ }
73
+ i = j;
74
+ continue;
75
+ }
76
+ if (valStr.startsWith('[') && valStr.endsWith(']')) {
77
+ const inner = valStr.slice(1, -1).trim();
78
+ result[key] = inner
79
+ ? inner.split(',').map((item) => unquote(item.trim())).filter(Boolean)
80
+ : [];
81
+ }
82
+ else {
83
+ result[key] = unquote(valStr);
84
+ }
85
+ i++;
86
+ }
87
+ return result;
88
+ }
89
+ function unquote(val) {
90
+ if ((val.startsWith('"') && val.endsWith('"') && val.length >= 2) ||
91
+ (val.startsWith("'") && val.endsWith("'") && val.length >= 2)) {
92
+ return val.slice(1, -1).replace(/\\"/g, '"').replace(/\\n/g, '\n');
93
+ }
94
+ return val;
95
+ }
96
+ export function validateFrontmatter(raw, scope) {
97
+ const errors = [];
98
+ const summary = typeof raw.summary === 'string' ? raw.summary.trim() : '';
99
+ if (!summary) {
100
+ errors.push('missing required frontmatter field "summary"');
101
+ }
102
+ else if (summary.includes('\n')) {
103
+ errors.push('"summary" must be a single line');
104
+ }
105
+ const rawType = typeof raw.type === 'string' ? raw.type.trim() : '';
106
+ if (!rawType) {
107
+ errors.push('missing required frontmatter field "type"');
108
+ }
109
+ else if (!VALID_TYPES.includes(rawType)) {
110
+ errors.push(`invalid "type" "${rawType}" (expected one of: ${VALID_TYPES.join(', ')})`);
111
+ }
112
+ const rawStatus = typeof raw.status === 'string' && raw.status.trim() ? raw.status.trim() : 'active';
113
+ if (!VALID_STATUSES.includes(rawStatus)) {
114
+ errors.push(`invalid "status" "${rawStatus}" (expected one of: ${VALID_STATUSES.join(', ')})`);
115
+ }
116
+ const defaultL0 = scope === 'project' ? 'none' : 'line';
117
+ const rawL0 = typeof raw.l0 === 'string' && raw.l0.trim() ? raw.l0.trim() : defaultL0;
118
+ if (!VALID_L0_MODES.includes(rawL0)) {
119
+ errors.push(`invalid "l0" "${rawL0}" (expected one of: ${VALID_L0_MODES.join(', ')})`);
120
+ }
121
+ let tags = [];
122
+ if (Array.isArray(raw.tags)) {
123
+ tags = raw.tags.map((t) => String(t).trim()).filter(Boolean);
124
+ }
125
+ else if (typeof raw.tags === 'string' && raw.tags.trim()) {
126
+ tags = raw.tags.split(',').map((t) => t.trim()).filter(Boolean);
127
+ }
128
+ const superseded_by = typeof raw.superseded_by === 'string' && raw.superseded_by.trim()
129
+ ? raw.superseded_by.trim()
130
+ : undefined;
131
+ const last_verified = typeof raw.last_verified === 'string' && raw.last_verified.trim()
132
+ ? raw.last_verified.trim()
133
+ : undefined;
134
+ if (errors.length > 0) {
135
+ return { errors };
136
+ }
137
+ return {
138
+ frontmatter: {
139
+ summary,
140
+ type: rawType,
141
+ tags,
142
+ status: rawStatus,
143
+ superseded_by,
144
+ l0: rawL0,
145
+ last_verified,
146
+ },
147
+ errors: [],
148
+ };
149
+ }
150
+ function quoteIfNeeded(value) {
151
+ if (/[:#[\]{}&*!|>'"%@`,?]/.test(value) || value.trim() !== value) {
152
+ return JSON.stringify(value);
153
+ }
154
+ return value;
155
+ }
156
+ export function serializeEntryMarkdown(fm, body) {
157
+ const lines = ['---'];
158
+ lines.push(`summary: ${quoteIfNeeded(fm.summary.replace(/\s+/g, ' ').trim())}`);
159
+ lines.push(`type: ${fm.type}`);
160
+ if (fm.tags && fm.tags.length > 0) {
161
+ lines.push(`tags: [${fm.tags.map((t) => quoteIfNeeded(t)).join(', ')}]`);
162
+ }
163
+ if (fm.status && fm.status !== 'active') {
164
+ lines.push(`status: ${fm.status}`);
165
+ }
166
+ if (fm.superseded_by) {
167
+ lines.push(`superseded_by: ${fm.superseded_by}`);
168
+ }
169
+ if (fm.l0) {
170
+ lines.push(`l0: ${fm.l0}`);
171
+ }
172
+ if (fm.last_verified) {
173
+ lines.push(`last_verified: ${fm.last_verified}`);
174
+ }
175
+ lines.push('---');
176
+ const trimmedBody = body.replace(/\r\n/g, '\n').trim();
177
+ return `${lines.join('\n')}\n\n${trimmedBody}\n`;
178
+ }
179
+ export function extractLinks(body) {
180
+ const links = new Set();
181
+ const mdLinkRegex = /\[[^\]]+\]\(([^)\s]+)\)/g;
182
+ let m;
183
+ while ((m = mdLinkRegex.exec(body)) !== null) {
184
+ links.add(m[1]);
185
+ }
186
+ const urlRegex = /https?:\/\/[^\s)>\]]+/g;
187
+ while ((m = urlRegex.exec(body)) !== null) {
188
+ links.add(m[0].replace(/[.,;:!?]+$/, ''));
189
+ }
190
+ return Array.from(links);
191
+ }
192
+ export function slugify(input) {
193
+ return (input
194
+ .toLowerCase()
195
+ .replace(/\.md$/i, '')
196
+ .replace(/[^a-z0-9]+/g, '-')
197
+ .replace(/^-+|-+$/g, '')
198
+ .slice(0, 64) || 'memory-entry');
199
+ }
@@ -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;
@@ -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 = ['-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,3 @@
1
+ import { HygieneFinding } from './types.js';
2
+ export declare function scanHygiene(content: string): HygieneFinding[];
3
+ export declare function formatHygieneErrors(findings: HygieneFinding[], sourceName?: string): string;