@fabersep/memory 0.2.1 → 0.4.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/CHANGELOG.md +24 -1
- package/README.md +58 -32
- package/dist/src/bm25.d.ts +2 -0
- package/dist/src/bm25.js +6 -0
- package/dist/src/cli.js +221 -13
- package/dist/src/config.js +1 -0
- package/dist/src/doctor.js +98 -2
- package/dist/src/hygiene.js +10 -1
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +2 -0
- package/dist/src/mcp.d.ts +1 -0
- package/dist/src/mcp.js +27 -2
- package/dist/src/personal-remote.d.ts +48 -0
- package/dist/src/personal-remote.js +282 -0
- package/dist/src/proposals.d.ts +2 -0
- package/dist/src/proposals.js +11 -0
- package/dist/src/sync.js +3 -0
- package/dist/src/types.d.ts +8 -0
- package/dist/src/types.js +1 -0
- package/dist/src/web-assets.d.ts +4 -0
- package/dist/src/web-assets.js +1357 -0
- package/dist/src/web.d.ts +41 -0
- package/dist/src/web.js +959 -0
- package/package.json +1 -1
package/dist/src/doctor.js
CHANGED
|
@@ -2,10 +2,11 @@ import * as crypto from 'node:crypto';
|
|
|
2
2
|
import * as fs from 'node:fs';
|
|
3
3
|
import { estimateTokens, renderGlobalL0 } from './compiler.js';
|
|
4
4
|
import { getCompiledL0Path, getConfigPath, getHomeDir, loadConfig } from './config.js';
|
|
5
|
-
import { getHeadSha, getUncommittedFiles, isGitRepo, readHeadFile } from './git.js';
|
|
5
|
+
import { getDefaultBranch, getHeadSha, getUncommittedFiles, gitSync, hasRemote, isGitRepo, readHeadFile } from './git.js';
|
|
6
6
|
import { scanHygiene } from './hygiene.js';
|
|
7
7
|
import { BLOCK_END, BLOCK_START, getEngineSpecs, getUserHome } from './init.js';
|
|
8
8
|
import { readMetrics } from './metrics.js';
|
|
9
|
+
import { getAheadInfo, getUnpushedReminder, readPersonalRemoteState } from './personal-remote.js';
|
|
9
10
|
import { listAllProposals } from './proposals.js';
|
|
10
11
|
import { L0_CHURN_WARN_THRESHOLD } from './stats.js';
|
|
11
12
|
import { loadScopeFromHead, PROJECT_MEMORY_REL_DIR, resolveProjectRoot } from './store.js';
|
|
@@ -37,6 +38,31 @@ function hasFaberMemoryMcpEntry(filePath) {
|
|
|
37
38
|
return false;
|
|
38
39
|
}
|
|
39
40
|
}
|
|
41
|
+
// 02 FR-06 amendment: memory indexes an engine file loads outside the managed block.
|
|
42
|
+
function extraMemoryIndexes(filePath, engine) {
|
|
43
|
+
if (!fs.existsSync(filePath))
|
|
44
|
+
return [];
|
|
45
|
+
let content;
|
|
46
|
+
try {
|
|
47
|
+
content = fs.readFileSync(filePath, 'utf8');
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
const start = content.indexOf(BLOCK_START);
|
|
53
|
+
const end = start === -1 ? -1 : content.indexOf(BLOCK_END, start + BLOCK_START.length);
|
|
54
|
+
const outside = start !== -1 && end !== -1 ? content.slice(0, start) + content.slice(end + BLOCK_END.length) : content;
|
|
55
|
+
const found = new Set();
|
|
56
|
+
if (engine === 'claude-code') {
|
|
57
|
+
for (const m of outside.matchAll(/^\s*@(\S*MEMORY\.md)\s*$/gim))
|
|
58
|
+
found.add(m[1]);
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
for (const m of outside.matchAll(/(?:^|[\s`'"(])([~$\w./\\-]*[\/\\]MEMORY\.md)\b/gim))
|
|
62
|
+
found.add(m[1]);
|
|
63
|
+
}
|
|
64
|
+
return [...found];
|
|
65
|
+
}
|
|
40
66
|
export function runDoctor(options = {}) {
|
|
41
67
|
const homeDir = options.homeDir || getHomeDir();
|
|
42
68
|
const userHome = options.userHome || getUserHome();
|
|
@@ -265,6 +291,7 @@ export function runDoctor(options = {}) {
|
|
|
265
291
|
const specs = getEngineSpecs();
|
|
266
292
|
const wiredEngines = [];
|
|
267
293
|
const mismatchedEngines = [];
|
|
294
|
+
const extraIndexEngines = [];
|
|
268
295
|
for (const engineName of ['claude-code', 'claude-desktop', 'antigravity', 'cursor']) {
|
|
269
296
|
const spec = specs[engineName];
|
|
270
297
|
const mcpWired = spec.mcpConfigFile ? hasFaberMemoryMcpEntry(spec.mcpConfigFile(userHome)) : false;
|
|
@@ -296,6 +323,13 @@ export function runDoctor(options = {}) {
|
|
|
296
323
|
}
|
|
297
324
|
}
|
|
298
325
|
}
|
|
326
|
+
if (spec.instructionFile && (engineName === 'claude-code' || engineName === 'antigravity')) {
|
|
327
|
+
const extras = extraMemoryIndexes(spec.instructionFile(userHome), engineName);
|
|
328
|
+
if (extras.length > 0) {
|
|
329
|
+
extraIndexEngines.push(engineName);
|
|
330
|
+
wiringDetails.push(`${engineName}: loads another memory index outside the managed block: ${extras.join(', ')}.`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
299
333
|
if (instrMismatch) {
|
|
300
334
|
mismatchedEngines.push(engineName);
|
|
301
335
|
wiringDetails.push(`${engineName}: managed L0 block path does not match ${l0Path}.`);
|
|
@@ -309,9 +343,19 @@ export function runDoctor(options = {}) {
|
|
|
309
343
|
wiredEngines.push(`${engineName} (${parts.join('+')})`);
|
|
310
344
|
}
|
|
311
345
|
}
|
|
346
|
+
if (extraIndexEngines.length > 0) {
|
|
347
|
+
wiringStatus = 'WARN';
|
|
348
|
+
wiringHint =
|
|
349
|
+
'Remove the other memory index lines so only the faber-memory managed block loads memory.';
|
|
350
|
+
}
|
|
312
351
|
if (mismatchedEngines.length > 0) {
|
|
313
352
|
wiringStatus = 'WARN';
|
|
314
|
-
wiringHint = 'Run "faber-memory init" to update engine pointers to the current compiled MEMORY.md path.'
|
|
353
|
+
wiringHint = [wiringHint, 'Run "faber-memory init" to update engine pointers to the current compiled MEMORY.md path.']
|
|
354
|
+
.filter(Boolean)
|
|
355
|
+
.join(' ');
|
|
356
|
+
}
|
|
357
|
+
else if (extraIndexEngines.length > 0) {
|
|
358
|
+
// already WARN with its hint
|
|
315
359
|
}
|
|
316
360
|
else if (wiredEngines.length === 0) {
|
|
317
361
|
wiringStatus = 'WARN';
|
|
@@ -408,6 +452,58 @@ export function runDoctor(options = {}) {
|
|
|
408
452
|
details: stabilityDetails,
|
|
409
453
|
...(stabilityHint ? { hint: stabilityHint } : {}),
|
|
410
454
|
});
|
|
455
|
+
// 7. Personal remote (feature 03 FR-03, FR-05); only when a personal root is configured.
|
|
456
|
+
const personal = config?.roots.personal;
|
|
457
|
+
if (personal && isGitRepo(personal.path)) {
|
|
458
|
+
const details = [];
|
|
459
|
+
let status = 'PASS';
|
|
460
|
+
let hint;
|
|
461
|
+
const warn = (detail, fix) => {
|
|
462
|
+
status = 'WARN';
|
|
463
|
+
details.push(detail);
|
|
464
|
+
hint = hint ? `${hint} ${fix}` : fix;
|
|
465
|
+
};
|
|
466
|
+
if (personal.readOnly) {
|
|
467
|
+
details.push('Read-only host: this machine only pulls the personal memory.');
|
|
468
|
+
if (!hasRemote(personal.path))
|
|
469
|
+
warn('The read-only clone has no origin.', 'Re-run faber-memory setup --read-only <url>.');
|
|
470
|
+
if (getUncommittedFiles(personal.path).length > 0) {
|
|
471
|
+
warn('The read-only clone has local edits; sync will not pull it.', `Discard the edits in ${personal.path}.`);
|
|
472
|
+
}
|
|
473
|
+
const branch = gitSync(['--no-optional-locks', '-C', personal.path, 'rev-parse', '--abbrev-ref', 'HEAD']).stdout.trim();
|
|
474
|
+
const expected = personal.defaultBranch || getDefaultBranch(personal.path);
|
|
475
|
+
if (branch && branch !== expected) {
|
|
476
|
+
warn(`The read-only clone is on ${branch}, not ${expected}.`, `Run git -C ${personal.path} checkout ${expected}.`);
|
|
477
|
+
}
|
|
478
|
+
if (getAheadInfo(personal.path).ahead > 0) {
|
|
479
|
+
warn('The read-only clone has local commits.', 'Reset it to origin; a read-only host never commits.');
|
|
480
|
+
}
|
|
481
|
+
const lastPull = readPersonalRemoteState(homeDir).lastPullAt;
|
|
482
|
+
const ageDays = lastPull ? Math.floor((nowMs - Date.parse(lastPull)) / 86400000) : null;
|
|
483
|
+
if (ageDays === null) {
|
|
484
|
+
warn('No successful pull recorded yet.', 'Run faber-memory sync.');
|
|
485
|
+
}
|
|
486
|
+
else if (ageDays > 7) {
|
|
487
|
+
warn(`Last successful pull was ${ageDays} days ago.`, 'Run faber-memory sync and check the host can reach origin.');
|
|
488
|
+
}
|
|
489
|
+
else {
|
|
490
|
+
details.push(`Last successful pull ${ageDays} day(s) ago.`);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
else if (!hasRemote(personal.path)) {
|
|
494
|
+
warn('The personal root has no remote; approved memory stays on this machine.', 'Run faber-memory remote add <url> with a private repository.');
|
|
495
|
+
}
|
|
496
|
+
else {
|
|
497
|
+
const reminder = config ? getUnpushedReminder(config, homeDir) : null;
|
|
498
|
+
if (reminder) {
|
|
499
|
+
warn(reminder, 'Run faber-memory push.');
|
|
500
|
+
}
|
|
501
|
+
else {
|
|
502
|
+
details.push('The personal root is in step with origin.');
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
checks.push({ id: 'personal-remote', name: 'Personal remote', status, details, ...(hint ? { hint } : {}) });
|
|
506
|
+
}
|
|
411
507
|
const hasFail = checks.some((ch) => ch.status === 'FAIL');
|
|
412
508
|
const hasWarn = checks.some((ch) => ch.status === 'WARN');
|
|
413
509
|
const overall = hasFail ? 'FAIL' : hasWarn ? 'WARN' : 'PASS';
|
package/dist/src/hygiene.js
CHANGED
|
@@ -1,51 +1,60 @@
|
|
|
1
|
+
const SECRET_FIX = 'remove the value; store a pointer to where it lives instead';
|
|
1
2
|
const RULES = [
|
|
2
3
|
{
|
|
3
4
|
category: 'secret',
|
|
4
5
|
pattern: 'private-key',
|
|
5
6
|
regex: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
|
|
6
7
|
label: 'Private key header detected',
|
|
8
|
+
fix: SECRET_FIX,
|
|
7
9
|
},
|
|
8
10
|
{
|
|
9
11
|
category: 'secret',
|
|
10
12
|
pattern: 'jwt',
|
|
11
13
|
regex: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/,
|
|
12
14
|
label: 'JWT token detected',
|
|
15
|
+
fix: SECRET_FIX,
|
|
13
16
|
},
|
|
14
17
|
{
|
|
15
18
|
category: 'secret',
|
|
16
19
|
pattern: 'bearer-token',
|
|
17
20
|
regex: /\bBearer\s+[A-Za-z0-9._~+/-]{12,}/i,
|
|
18
21
|
label: 'Bearer token detected',
|
|
22
|
+
fix: SECRET_FIX,
|
|
19
23
|
},
|
|
20
24
|
{
|
|
21
25
|
category: 'secret',
|
|
22
26
|
pattern: 'api-key-prefix',
|
|
23
27
|
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
28
|
label: 'Known API key prefix detected',
|
|
29
|
+
fix: SECRET_FIX,
|
|
25
30
|
},
|
|
26
31
|
{
|
|
27
32
|
category: 'secret',
|
|
28
33
|
pattern: 'credential-assignment',
|
|
29
34
|
regex: /\b(?:api[_-]?key|secret[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|password|passwd)\s*[:=]\s*["']?[A-Za-z0-9._~+/=-]{12,}["']?/i,
|
|
30
35
|
label: 'Credential assignment detected',
|
|
36
|
+
fix: SECRET_FIX,
|
|
31
37
|
},
|
|
32
38
|
{
|
|
33
39
|
category: 'machine-path',
|
|
34
40
|
pattern: 'macos-user-path',
|
|
35
41
|
regex: /\/Users\/[A-Za-z0-9._-]+\//,
|
|
36
42
|
label: 'Machine-specific macOS home path detected',
|
|
43
|
+
fix: 'write ~/ or $HOME instead of /Users/<name>/',
|
|
37
44
|
},
|
|
38
45
|
{
|
|
39
46
|
category: 'machine-path',
|
|
40
47
|
pattern: 'linux-user-path',
|
|
41
48
|
regex: /\/home\/[A-Za-z0-9._-]+\//,
|
|
42
49
|
label: 'Machine-specific Linux home path detected',
|
|
50
|
+
fix: 'write ~/ or $HOME instead of /home/<name>/',
|
|
43
51
|
},
|
|
44
52
|
{
|
|
45
53
|
category: 'machine-path',
|
|
46
54
|
pattern: 'windows-user-path',
|
|
47
55
|
regex: /\b[A-Za-z]:\\Users\\[A-Za-z0-9._-]+\\/,
|
|
48
56
|
label: 'Machine-specific Windows home path detected',
|
|
57
|
+
fix: 'write ~\\ or %USERPROFILE% instead of C:\\Users\\<name>\\',
|
|
49
58
|
},
|
|
50
59
|
];
|
|
51
60
|
export function scanHygiene(content) {
|
|
@@ -64,7 +73,7 @@ export function scanHygiene(content) {
|
|
|
64
73
|
line: i + 1,
|
|
65
74
|
category: rule.category,
|
|
66
75
|
pattern: rule.pattern,
|
|
67
|
-
message: `${rule.label} (${rule.category}/${rule.pattern}) at line ${i + 1}`,
|
|
76
|
+
message: `${rule.label} (${rule.category}/${rule.pattern}) at line ${i + 1}; fix: ${rule.fix}`,
|
|
68
77
|
redactedSnippet,
|
|
69
78
|
});
|
|
70
79
|
break;
|
package/dist/src/index.d.ts
CHANGED
package/dist/src/index.js
CHANGED
package/dist/src/mcp.d.ts
CHANGED
package/dist/src/mcp.js
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import * as fs from 'node:fs';
|
|
2
2
|
import * as readline from 'node:readline';
|
|
3
|
-
import { BM25Index, findNearDuplicates } from './bm25.js';
|
|
3
|
+
import { BM25Index, findNearDuplicates, findRelatedEntries } from './bm25.js';
|
|
4
4
|
import { getCompiledL0Path, getHomeDir, loadConfig } from './config.js';
|
|
5
5
|
import { compileGlobalL0 } from './compiler.js';
|
|
6
6
|
import { getHeadSha } from './git.js';
|
|
7
7
|
import { formatHygieneErrors, scanHygiene } from './hygiene.js';
|
|
8
|
+
import { getUnpushedReminder, isReadOnlyRoot, READ_ONLY_MESSAGE } from './personal-remote.js';
|
|
8
9
|
import { appendMetric, MAX_GET_FOUND_IDS } from './metrics.js';
|
|
9
10
|
import { createProposal, reconcileAwaitingCommitProposals } from './proposals.js';
|
|
10
11
|
import { loadAllScopes, resolveProjectRoot } from './store.js';
|
|
11
12
|
import { syncAllRoots } from './sync.js';
|
|
12
13
|
import { getPackageVersion } from './version.js';
|
|
13
|
-
import { VALID_TYPES, } from './types.js';
|
|
14
|
+
import { DEFAULT_SIMILARITY_HINT_FLOOR, VALID_TYPES, } from './types.js';
|
|
14
15
|
export const MCP_TOOLS = [
|
|
15
16
|
{
|
|
16
17
|
name: 'memory_search',
|
|
@@ -67,6 +68,7 @@ export class FaberMemoryMcpServer {
|
|
|
67
68
|
lastHeadSignature = '';
|
|
68
69
|
lastLoaded = null;
|
|
69
70
|
startupWarnings = [];
|
|
71
|
+
unpushedReminderShown = false;
|
|
70
72
|
startupPullPromise = null;
|
|
71
73
|
constructor(options = {}) {
|
|
72
74
|
this.homeDir = options.homeDir || getHomeDir();
|
|
@@ -125,6 +127,13 @@ export class FaberMemoryMcpServer {
|
|
|
125
127
|
drainWarnings(loaded) {
|
|
126
128
|
const warnings = [...this.startupWarnings, ...loaded.uncommittedWarnings, ...loaded.shadowWarnings];
|
|
127
129
|
this.startupWarnings = [];
|
|
130
|
+
if (!this.unpushedReminderShown) {
|
|
131
|
+
// Feature 03 FR-03: once per server process, never in L0 or the tool list.
|
|
132
|
+
this.unpushedReminderShown = true;
|
|
133
|
+
const reminder = getUnpushedReminder(loadConfig(this.homeDir), this.homeDir);
|
|
134
|
+
if (reminder)
|
|
135
|
+
warnings.push(reminder);
|
|
136
|
+
}
|
|
128
137
|
return warnings;
|
|
129
138
|
}
|
|
130
139
|
listTools() {
|
|
@@ -270,6 +279,10 @@ export class FaberMemoryMcpServer {
|
|
|
270
279
|
recordPropose('validation_error');
|
|
271
280
|
return errorResponse('body is required.');
|
|
272
281
|
}
|
|
282
|
+
if (scope === 'personal' && isReadOnlyRoot(config.roots.personal)) {
|
|
283
|
+
recordPropose('validation_error');
|
|
284
|
+
return errorResponse(READ_ONLY_MESSAGE);
|
|
285
|
+
}
|
|
273
286
|
// Validate target_id for update / supersede (AC-08c1, AC-08c2)
|
|
274
287
|
if (action === 'update' || action === 'supersede') {
|
|
275
288
|
if (!targetId) {
|
|
@@ -329,6 +342,10 @@ export class FaberMemoryMcpServer {
|
|
|
329
342
|
projectRootPath: scope === 'project' ? loaded.projectResolution.projectRoot : undefined,
|
|
330
343
|
}, this.homeDir);
|
|
331
344
|
recordPropose('staged');
|
|
345
|
+
// 01 FR-04 amendment: say what the similarity check found, without blocking.
|
|
346
|
+
const similar = action === 'create'
|
|
347
|
+
? findRelatedEntries(summary, body, loaded.activeEntries, reconcileAwaitingCommitProposals(this.homeDir).filter((p) => p.id !== proposal.id), config.similarityHintFloor ?? DEFAULT_SIMILARITY_HINT_FLOOR, config.similarityThreshold).map((m) => ({ id: m.id, scope: m.scope, summary: m.summary, pending: m.pending, similarity: m.similarity }))
|
|
348
|
+
: [];
|
|
332
349
|
this.lastHeadSignature = '';
|
|
333
350
|
const warnings = this.drainWarnings(loaded);
|
|
334
351
|
return {
|
|
@@ -340,6 +357,14 @@ export class FaberMemoryMcpServer {
|
|
|
340
357
|
proposal_id: proposal.id,
|
|
341
358
|
entry_id: proposal.entryId,
|
|
342
359
|
scope: proposal.scope,
|
|
360
|
+
...(action === 'create'
|
|
361
|
+
? {
|
|
362
|
+
similar,
|
|
363
|
+
...(similar.length > 0
|
|
364
|
+
? { similar_note: 'a related entry exists; prefer update if it is the same fact' }
|
|
365
|
+
: {}),
|
|
366
|
+
}
|
|
367
|
+
: {}),
|
|
343
368
|
warnings,
|
|
344
369
|
}, null, 2),
|
|
345
370
|
},
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { PushMode, RootConfig, UserConfig } from './types.js';
|
|
2
|
+
export declare const READ_ONLY_MESSAGE = "read-only host: propose changes on a writing machine";
|
|
3
|
+
export declare const DEFAULT_READ_ONLY_PATH: string;
|
|
4
|
+
export declare function getPushMode(root: RootConfig | undefined): PushMode;
|
|
5
|
+
export declare function isReadOnlyRoot(root: RootConfig | undefined): boolean;
|
|
6
|
+
interface PersonalRemoteState {
|
|
7
|
+
pushFailed?: {
|
|
8
|
+
reason: string;
|
|
9
|
+
at: string;
|
|
10
|
+
};
|
|
11
|
+
lastPullAt?: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function readPersonalRemoteState(homeDir?: string): PersonalRemoteState;
|
|
14
|
+
export declare function recordPushFailure(reason: string, homeDir?: string): void;
|
|
15
|
+
export declare function clearPushFailure(homeDir?: string): void;
|
|
16
|
+
export declare function recordSuccessfulPull(homeDir?: string, at?: Date): void;
|
|
17
|
+
export interface AheadInfo {
|
|
18
|
+
hasRemote: boolean;
|
|
19
|
+
ahead: number;
|
|
20
|
+
oldest?: string;
|
|
21
|
+
}
|
|
22
|
+
export declare function getAheadInfo(repoDir: string): AheadInfo;
|
|
23
|
+
/** The one-line unpushed reminder (`FR-03`), or null when the personal root is in step. */
|
|
24
|
+
export declare function getUnpushedReminder(config: UserConfig, homeDir?: string): string | null;
|
|
25
|
+
export declare function pullRebaseBeforeCommit(root: RootConfig): Promise<string | null>;
|
|
26
|
+
export interface PushResult {
|
|
27
|
+
ok: boolean;
|
|
28
|
+
pushed: number;
|
|
29
|
+
message: string;
|
|
30
|
+
}
|
|
31
|
+
export declare function pushPersonalRoot(root: RootConfig, homeDir?: string): Promise<PushResult>;
|
|
32
|
+
export type Visibility = 'public' | 'private' | 'unknown';
|
|
33
|
+
export declare function parseHostedRepo(url: string): {
|
|
34
|
+
host: 'github.com' | 'gitlab.com';
|
|
35
|
+
repo: string;
|
|
36
|
+
} | null;
|
|
37
|
+
export declare function checkRepoVisibility(url: string, timeoutMs?: number): Promise<Visibility>;
|
|
38
|
+
export interface RemoteAddResult {
|
|
39
|
+
ok: boolean;
|
|
40
|
+
messages: string[];
|
|
41
|
+
errors: string[];
|
|
42
|
+
}
|
|
43
|
+
export declare function addPersonalRemote(config: UserConfig, url: string, options?: {
|
|
44
|
+
allowPublic?: boolean;
|
|
45
|
+
homeDir?: string;
|
|
46
|
+
}): Promise<RemoteAddResult>;
|
|
47
|
+
export declare function removePersonalRemote(config: UserConfig, homeDir?: string): RemoteAddResult;
|
|
48
|
+
export {};
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as os from 'node:os';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import { getStateDir, getHomeDir } from './config.js';
|
|
5
|
+
import { getDefaultBranch, gitAsync, gitSync, hasRemote, isDirty } from './git.js';
|
|
6
|
+
// Feature 03: personal remote, push after approve, unpushed reminder, many hosts, read-only hosts.
|
|
7
|
+
export const READ_ONLY_MESSAGE = 'read-only host: propose changes on a writing machine';
|
|
8
|
+
export const DEFAULT_READ_ONLY_PATH = path.join(os.homedir(), 'faber-memory');
|
|
9
|
+
const PUSH_TIMEOUT_MS = 15000;
|
|
10
|
+
const PULL_TIMEOUT_MS = 5000;
|
|
11
|
+
export function getPushMode(root) {
|
|
12
|
+
return root?.pushMode === 'auto' || root?.pushMode === 'never' ? root.pushMode : 'ask';
|
|
13
|
+
}
|
|
14
|
+
export function isReadOnlyRoot(root) {
|
|
15
|
+
return Boolean(root?.readOnly);
|
|
16
|
+
}
|
|
17
|
+
function statePath(homeDir) {
|
|
18
|
+
return path.join(getStateDir(homeDir), 'personal-remote.json');
|
|
19
|
+
}
|
|
20
|
+
export function readPersonalRemoteState(homeDir = getHomeDir()) {
|
|
21
|
+
try {
|
|
22
|
+
return JSON.parse(fs.readFileSync(statePath(homeDir), 'utf8'));
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function writePersonalRemoteState(state, homeDir) {
|
|
29
|
+
try {
|
|
30
|
+
fs.mkdirSync(getStateDir(homeDir), { recursive: true });
|
|
31
|
+
fs.writeFileSync(statePath(homeDir), `${JSON.stringify(state, null, 2)}\n`, 'utf8');
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// State is advisory; never fail a command for it.
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export function recordPushFailure(reason, homeDir = getHomeDir()) {
|
|
38
|
+
const state = readPersonalRemoteState(homeDir);
|
|
39
|
+
state.pushFailed = { reason, at: new Date().toISOString() };
|
|
40
|
+
writePersonalRemoteState(state, homeDir);
|
|
41
|
+
}
|
|
42
|
+
export function clearPushFailure(homeDir = getHomeDir()) {
|
|
43
|
+
const state = readPersonalRemoteState(homeDir);
|
|
44
|
+
if (!state.pushFailed)
|
|
45
|
+
return;
|
|
46
|
+
delete state.pushFailed;
|
|
47
|
+
writePersonalRemoteState(state, homeDir);
|
|
48
|
+
}
|
|
49
|
+
export function recordSuccessfulPull(homeDir = getHomeDir(), at = new Date()) {
|
|
50
|
+
const state = readPersonalRemoteState(homeDir);
|
|
51
|
+
state.lastPullAt = at.toISOString();
|
|
52
|
+
writePersonalRemoteState(state, homeDir);
|
|
53
|
+
}
|
|
54
|
+
function upstreamRef(repoDir) {
|
|
55
|
+
const up = gitSync(['-C', repoDir, 'rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
|
|
56
|
+
if (up.ok && up.stdout.trim())
|
|
57
|
+
return up.stdout.trim();
|
|
58
|
+
const branch = gitSync(['-C', repoDir, 'rev-parse', '--abbrev-ref', 'HEAD']).stdout.trim() || 'main';
|
|
59
|
+
const remoteBranch = `origin/${branch}`;
|
|
60
|
+
return gitSync(['-C', repoDir, 'rev-parse', '--verify', '--quiet', remoteBranch]).ok ? remoteBranch : null;
|
|
61
|
+
}
|
|
62
|
+
export function getAheadInfo(repoDir) {
|
|
63
|
+
if (!fs.existsSync(repoDir) || !hasRemote(repoDir))
|
|
64
|
+
return { hasRemote: false, ahead: 0 };
|
|
65
|
+
const upstream = upstreamRef(repoDir);
|
|
66
|
+
const range = upstream ? `${upstream}..HEAD` : 'HEAD';
|
|
67
|
+
const count = gitSync(['-C', repoDir, 'rev-list', '--count', range]);
|
|
68
|
+
const ahead = count.ok ? Number(count.stdout.trim()) || 0 : 0;
|
|
69
|
+
if (ahead === 0)
|
|
70
|
+
return { hasRemote: true, ahead: 0 };
|
|
71
|
+
const dates = gitSync(['-C', repoDir, 'log', '--reverse', '--format=%cs', range]);
|
|
72
|
+
const oldest = dates.ok ? dates.stdout.split('\n')[0]?.trim() : undefined;
|
|
73
|
+
return { hasRemote: true, ahead, oldest: oldest || undefined };
|
|
74
|
+
}
|
|
75
|
+
/** The one-line unpushed reminder (`FR-03`), or null when the personal root is in step. */
|
|
76
|
+
export function getUnpushedReminder(config, homeDir = getHomeDir()) {
|
|
77
|
+
const root = config.roots.personal;
|
|
78
|
+
if (!root || isReadOnlyRoot(root))
|
|
79
|
+
return null;
|
|
80
|
+
const info = getAheadInfo(root.path);
|
|
81
|
+
if (!info.hasRemote)
|
|
82
|
+
return null;
|
|
83
|
+
const state = readPersonalRemoteState(homeDir);
|
|
84
|
+
if (state.pushFailed && info.ahead > 0) {
|
|
85
|
+
return `personal memory: push failed (${state.pushFailed.reason}); ${info.ahead} commit(s) not pushed to origin; resolve it, then run faber-memory push`;
|
|
86
|
+
}
|
|
87
|
+
if (info.ahead === 0)
|
|
88
|
+
return null;
|
|
89
|
+
return `personal memory: ${info.ahead} commit(s) not pushed to origin (oldest ${info.oldest || 'unknown'}); run faber-memory push`;
|
|
90
|
+
}
|
|
91
|
+
// ---- pull before commit, push with one rebase retry (FR-04) ------------------------------
|
|
92
|
+
export async function pullRebaseBeforeCommit(root) {
|
|
93
|
+
if (!hasRemote(root.path) || isDirty(root.path))
|
|
94
|
+
return null;
|
|
95
|
+
if (!upstreamRef(root.path))
|
|
96
|
+
return null;
|
|
97
|
+
const res = await gitAsync(['-C', root.path, 'pull', '--rebase', '--quiet'], undefined, PULL_TIMEOUT_MS);
|
|
98
|
+
if (res.ok)
|
|
99
|
+
return null;
|
|
100
|
+
gitSync(['-C', root.path, 'rebase', '--abort']);
|
|
101
|
+
return `could not pull before commit (${res.timedOut ? 'timed out' : firstLine(res.stderr) || 'pull failed'}); committing locally`;
|
|
102
|
+
}
|
|
103
|
+
function firstLine(text) {
|
|
104
|
+
return (text
|
|
105
|
+
.split('\n')
|
|
106
|
+
.map((l) => l.replace(/^(error|fatal|hint|remote):\s*/i, '').trim())
|
|
107
|
+
.find((l) => l.length > 0) || '');
|
|
108
|
+
}
|
|
109
|
+
function conflictFiles(repoDir) {
|
|
110
|
+
const res = gitSync(['-C', repoDir, 'diff', '--name-only', '--diff-filter=U']);
|
|
111
|
+
return res.ok ? res.stdout.split('\n').map((s) => s.trim()).filter(Boolean) : [];
|
|
112
|
+
}
|
|
113
|
+
export async function pushPersonalRoot(root, homeDir = getHomeDir()) {
|
|
114
|
+
if (isReadOnlyRoot(root))
|
|
115
|
+
return { ok: false, pushed: 0, message: READ_ONLY_MESSAGE };
|
|
116
|
+
if (!hasRemote(root.path)) {
|
|
117
|
+
return { ok: false, pushed: 0, message: 'personal memory has no remote; run faber-memory remote add <url>' };
|
|
118
|
+
}
|
|
119
|
+
const before = getAheadInfo(root.path).ahead;
|
|
120
|
+
const branch = gitSync(['-C', root.path, 'rev-parse', '--abbrev-ref', 'HEAD']).stdout.trim() || 'main';
|
|
121
|
+
const push = () => gitAsync(['-C', root.path, 'push', '-u', 'origin', `HEAD:${branch}`], undefined, PUSH_TIMEOUT_MS);
|
|
122
|
+
let res = await push();
|
|
123
|
+
if (!res.ok && /non-fast-forward|fetch first|rejected/i.test(res.stderr)) {
|
|
124
|
+
const fetch = await gitAsync(['-C', root.path, 'fetch', 'origin'], undefined, PUSH_TIMEOUT_MS);
|
|
125
|
+
if (fetch.ok) {
|
|
126
|
+
const rebase = gitSync(['-C', root.path, 'rebase', `origin/${branch}`]);
|
|
127
|
+
if (!rebase.ok) {
|
|
128
|
+
const files = conflictFiles(root.path);
|
|
129
|
+
gitSync(['-C', root.path, 'rebase', '--abort']);
|
|
130
|
+
const reason = files.length > 0 ? `conflict in ${files.join(', ')}` : firstLine(rebase.stderr) || 'rebase failed';
|
|
131
|
+
recordPushFailure(reason, homeDir);
|
|
132
|
+
return {
|
|
133
|
+
ok: false,
|
|
134
|
+
pushed: 0,
|
|
135
|
+
message: `Push failed: ${reason}. Your commit is kept locally. Merge origin/${branch} by hand in ${root.path}, then run faber-memory push.`,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
res = await push();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (!res.ok) {
|
|
142
|
+
const reason = res.timedOut ? 'push timed out' : firstLine(res.stderr) || 'push failed';
|
|
143
|
+
recordPushFailure(reason, homeDir);
|
|
144
|
+
return { ok: false, pushed: 0, message: `Push failed: ${reason}. Your commit is kept locally; run faber-memory push later.` };
|
|
145
|
+
}
|
|
146
|
+
clearPushFailure(homeDir);
|
|
147
|
+
return { ok: true, pushed: before, message: `Pushed ${before} commit(s) to origin.` };
|
|
148
|
+
}
|
|
149
|
+
export function parseHostedRepo(url) {
|
|
150
|
+
const m = /^(?:https?:\/\/(?:[^@/]+@)?|git@|ssh:\/\/git@)(github\.com|gitlab\.com)[:/](.+?)(?:\.git)?\/?$/i.exec(url.trim());
|
|
151
|
+
if (!m)
|
|
152
|
+
return null;
|
|
153
|
+
return { host: m[1].toLowerCase(), repo: m[2] };
|
|
154
|
+
}
|
|
155
|
+
export async function checkRepoVisibility(url, timeoutMs = 5000) {
|
|
156
|
+
const forced = process.env.FABER_MEMORY_VISIBILITY_OVERRIDE;
|
|
157
|
+
if (forced === 'public' || forced === 'private' || forced === 'unknown')
|
|
158
|
+
return forced;
|
|
159
|
+
const hosted = parseHostedRepo(url);
|
|
160
|
+
if (!hosted)
|
|
161
|
+
return 'unknown';
|
|
162
|
+
const api = hosted.host === 'github.com'
|
|
163
|
+
? `https://api.github.com/repos/${hosted.repo}`
|
|
164
|
+
: `https://gitlab.com/api/v4/projects/${encodeURIComponent(hosted.repo)}`;
|
|
165
|
+
try {
|
|
166
|
+
const ctrl = new AbortController();
|
|
167
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
168
|
+
const res = await fetch(api, { signal: ctrl.signal, headers: { 'User-Agent': 'faber-memory' } });
|
|
169
|
+
clearTimeout(timer);
|
|
170
|
+
if (res.status === 404)
|
|
171
|
+
return 'private';
|
|
172
|
+
if (!res.ok)
|
|
173
|
+
return 'unknown';
|
|
174
|
+
const body = (await res.json());
|
|
175
|
+
if (hosted.host === 'github.com')
|
|
176
|
+
return body.private === false ? 'public' : 'private';
|
|
177
|
+
return body.visibility === 'public' ? 'public' : 'private';
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return 'unknown';
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
function remoteEntryFiles(repoDir, ref) {
|
|
184
|
+
const res = gitSync(['-C', repoDir, 'ls-tree', '-r', '--name-only', ref]);
|
|
185
|
+
if (!res.ok)
|
|
186
|
+
return [];
|
|
187
|
+
return res.stdout
|
|
188
|
+
.split('\n')
|
|
189
|
+
.map((s) => s.trim())
|
|
190
|
+
.filter((f) => f.toLowerCase().endsWith('.md') && path.basename(f).toLowerCase() !== 'readme.md');
|
|
191
|
+
}
|
|
192
|
+
export async function addPersonalRemote(config, url, options = {}) {
|
|
193
|
+
const homeDir = options.homeDir || getHomeDir();
|
|
194
|
+
const messages = [];
|
|
195
|
+
const root = config.roots.personal;
|
|
196
|
+
if (!root)
|
|
197
|
+
return { ok: false, messages, errors: ['Personal memory root is not configured; run faber-memory init first.'] };
|
|
198
|
+
if (isReadOnlyRoot(root))
|
|
199
|
+
return { ok: false, messages, errors: [READ_ONLY_MESSAGE] };
|
|
200
|
+
if (hasRemote(root.path)) {
|
|
201
|
+
return { ok: false, messages, errors: ['The personal root already has an origin; run faber-memory remote remove first.'] };
|
|
202
|
+
}
|
|
203
|
+
if (isDirty(root.path)) {
|
|
204
|
+
return { ok: false, messages, errors: [`The personal root has uncommitted edits in ${root.path}; commit or remove them first.`] };
|
|
205
|
+
}
|
|
206
|
+
const visibility = await checkRepoVisibility(url);
|
|
207
|
+
if (visibility === 'public' && !options.allowPublic) {
|
|
208
|
+
return {
|
|
209
|
+
ok: false,
|
|
210
|
+
messages,
|
|
211
|
+
errors: ['This repository is public: anyone can read your personal memory. Use a private repository, or pass --allow-public.'],
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
if (visibility === 'unknown')
|
|
215
|
+
messages.push('Repository visibility was not checked (unknown host or offline).');
|
|
216
|
+
const add = gitSync(['-C', root.path, 'remote', 'add', 'origin', url]);
|
|
217
|
+
if (!add.ok)
|
|
218
|
+
return { ok: false, messages, errors: [`git remote add failed: ${firstLine(add.stderr)}`] };
|
|
219
|
+
const undo = (error) => {
|
|
220
|
+
gitSync(['-C', root.path, 'remote', 'remove', 'origin']);
|
|
221
|
+
return { ok: false, messages, errors: [error] };
|
|
222
|
+
};
|
|
223
|
+
const fetch = await gitAsync(['-C', root.path, 'fetch', 'origin'], undefined, PUSH_TIMEOUT_MS);
|
|
224
|
+
if (!fetch.ok)
|
|
225
|
+
return undo(`git fetch failed: ${fetch.timedOut ? 'timed out' : firstLine(fetch.stderr)}`);
|
|
226
|
+
const branch = gitSync(['-C', root.path, 'rev-parse', '--abbrev-ref', 'HEAD']).stdout.trim() || 'main';
|
|
227
|
+
const remoteRef = `origin/${branch}`;
|
|
228
|
+
const remoteHasBranch = gitSync(['-C', root.path, 'rev-parse', '--verify', '--quiet', remoteRef]).ok;
|
|
229
|
+
if (remoteHasBranch) {
|
|
230
|
+
const base = gitSync(['-C', root.path, 'merge-base', 'HEAD', remoteRef]);
|
|
231
|
+
if (base.ok && base.stdout.trim()) {
|
|
232
|
+
const rebase = gitSync(['-C', root.path, 'rebase', remoteRef]);
|
|
233
|
+
if (!rebase.ok) {
|
|
234
|
+
gitSync(['-C', root.path, 'rebase', '--abort']);
|
|
235
|
+
return undo(`Your history and ${remoteRef} conflict; merge them by hand, then run faber-memory remote add again.`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
const entries = remoteEntryFiles(root.path, remoteRef);
|
|
240
|
+
if (entries.length > 0) {
|
|
241
|
+
return undo(`The remote already holds ${entries.length} memory entr${entries.length === 1 ? 'y' : 'ies'} with an unrelated history. ` +
|
|
242
|
+
`To merge by hand: cd ${root.path} && git remote add origin ${url} && git fetch origin && ` +
|
|
243
|
+
`git merge --allow-unrelated-histories ${remoteRef}, resolve any conflicts, then git push -u origin ${branch}.`);
|
|
244
|
+
}
|
|
245
|
+
const merge = gitSync([
|
|
246
|
+
'-C', root.path, 'merge', '--allow-unrelated-histories', '--no-edit',
|
|
247
|
+
'-m', `chore: join the personal root with ${remoteRef}`, remoteRef,
|
|
248
|
+
]);
|
|
249
|
+
if (!merge.ok) {
|
|
250
|
+
gitSync(['-C', root.path, 'merge', '--abort']);
|
|
251
|
+
return undo(`Could not join the remote's history: ${firstLine(merge.stderr)}`);
|
|
252
|
+
}
|
|
253
|
+
messages.push(`Joined ${remoteRef} (it held no memory entries).`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const push = await gitAsync(['-C', root.path, 'push', '-u', 'origin', `HEAD:${branch}`], undefined, PUSH_TIMEOUT_MS);
|
|
257
|
+
if (!push.ok) {
|
|
258
|
+
gitSync(['-C', root.path, 'config', `branch.${branch}.remote`, 'origin']);
|
|
259
|
+
gitSync(['-C', root.path, 'config', `branch.${branch}.merge`, `refs/heads/${branch}`]);
|
|
260
|
+
recordPushFailure(push.timedOut ? 'push timed out' : firstLine(push.stderr) || 'push failed', homeDir);
|
|
261
|
+
messages.push(`Linked origin, but the first push failed: ${firstLine(push.stderr) || 'timed out'}. Run faber-memory push later.`);
|
|
262
|
+
return { ok: true, messages, errors: [] };
|
|
263
|
+
}
|
|
264
|
+
clearPushFailure(homeDir);
|
|
265
|
+
root.defaultBranch = getDefaultBranch(root.path);
|
|
266
|
+
messages.push(`Linked the personal root to ${url} and pushed ${branch}.`);
|
|
267
|
+
return { ok: true, messages, errors: [] };
|
|
268
|
+
}
|
|
269
|
+
export function removePersonalRemote(config, homeDir = getHomeDir()) {
|
|
270
|
+
const root = config.roots.personal;
|
|
271
|
+
if (!root)
|
|
272
|
+
return { ok: false, messages: [], errors: ['Personal memory root is not configured.'] };
|
|
273
|
+
if (isReadOnlyRoot(root))
|
|
274
|
+
return { ok: false, messages: [], errors: [READ_ONLY_MESSAGE] };
|
|
275
|
+
if (!hasRemote(root.path))
|
|
276
|
+
return { ok: true, messages: ['The personal root has no origin.'], errors: [] };
|
|
277
|
+
const res = gitSync(['-C', root.path, 'remote', 'remove', 'origin']);
|
|
278
|
+
if (!res.ok)
|
|
279
|
+
return { ok: false, messages: [], errors: [`git remote remove failed: ${firstLine(res.stderr)}`] };
|
|
280
|
+
clearPushFailure(homeDir);
|
|
281
|
+
return { ok: true, messages: ['Removed origin from the personal root (files and history kept).'], errors: [] };
|
|
282
|
+
}
|
package/dist/src/proposals.d.ts
CHANGED
|
@@ -27,6 +27,8 @@ export interface ApproveOutcome {
|
|
|
27
27
|
errors: string[];
|
|
28
28
|
compareUrl?: string;
|
|
29
29
|
recompiledL0?: boolean;
|
|
30
|
+
/** True when approved entries were committed to the personal root (feature 03 push step). */
|
|
31
|
+
personalCommitted?: boolean;
|
|
30
32
|
}
|
|
31
33
|
export declare function approveProposalsBatch(config: UserConfig, proposals: Proposal[], options?: {
|
|
32
34
|
homeDir?: string;
|