@fabersep/memory 0.2.0 → 0.3.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 +46 -0
- package/README.md +63 -324
- package/dist/src/bm25.d.ts +2 -0
- package/dist/src/bm25.js +6 -0
- package/dist/src/cli.js +245 -25
- package/dist/src/config.js +1 -0
- package/dist/src/doctor.js +99 -3
- package/dist/src/hygiene.js +10 -1
- package/dist/src/importer.js +7 -2
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.js +1 -0
- package/dist/src/init.d.ts +1 -0
- package/dist/src/init.js +4 -3
- package/dist/src/mcp.d.ts +3 -2
- package/dist/src/mcp.js +30 -4
- 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/stats.d.ts +2 -1
- package/dist/src/stats.js +2 -16
- package/dist/src/sync.js +3 -0
- package/dist/src/types.d.ts +9 -1
- package/dist/src/types.js +3 -1
- package/dist/src/version.d.ts +2 -0
- package/dist/src/version.js +22 -0
- package/package.json +3 -2
package/dist/src/importer.js
CHANGED
|
@@ -44,6 +44,11 @@ function inferSummary(raw, body, fallbackName) {
|
|
|
44
44
|
.find((l) => l.length > 0);
|
|
45
45
|
return (firstLine || fallbackName).slice(0, 140);
|
|
46
46
|
}
|
|
47
|
+
// A heading with nothing under it but the next heading (e.g. a "# Rules" title
|
|
48
|
+
// above "## ..." sections) is not an entry of its own.
|
|
49
|
+
function hasSectionBody(section) {
|
|
50
|
+
return section.lines.slice(1).join('\n').trim().length > 0;
|
|
51
|
+
}
|
|
47
52
|
function splitTopLevelHeadings(content) {
|
|
48
53
|
const lines = content.replace(/\r\n/g, '\n').split('\n');
|
|
49
54
|
const sections = [];
|
|
@@ -51,7 +56,7 @@ function splitTopLevelHeadings(content) {
|
|
|
51
56
|
for (const line of lines) {
|
|
52
57
|
const m = line.match(/^#{1,2}\s+(.+)$/);
|
|
53
58
|
if (m) {
|
|
54
|
-
if (current && current
|
|
59
|
+
if (current && hasSectionBody(current)) {
|
|
55
60
|
sections.push(current);
|
|
56
61
|
}
|
|
57
62
|
current = { title: m[1].trim(), lines: [line] };
|
|
@@ -60,7 +65,7 @@ function splitTopLevelHeadings(content) {
|
|
|
60
65
|
current.lines.push(line);
|
|
61
66
|
}
|
|
62
67
|
}
|
|
63
|
-
if (current && current
|
|
68
|
+
if (current && hasSectionBody(current)) {
|
|
64
69
|
sections.push(current);
|
|
65
70
|
}
|
|
66
71
|
return sections.map((s) => ({ title: s.title, body: s.lines.join('\n').trim() }));
|
package/dist/src/index.d.ts
CHANGED
package/dist/src/index.js
CHANGED
package/dist/src/init.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { UserConfig } from './types.js';
|
|
2
2
|
export declare const BLOCK_START = "<!-- faber-memory:start -->";
|
|
3
3
|
export declare const BLOCK_END = "<!-- faber-memory:end -->";
|
|
4
|
+
export declare const TOOL_GUIDANCE_LINE = "Use the faber-memory MCP tools: memory_search and memory_get for the details behind these lines; when you learn a durable rule, decision, lesson or preference, call memory_propose (the user approves it later; never edit memory files directly).";
|
|
4
5
|
export declare const PROJECT_HINT_LINE = "Project memory: run npx @fabersep/memory init";
|
|
5
6
|
export type EngineName = 'claude-code' | 'claude-desktop' | 'antigravity' | 'cursor' | 'codex';
|
|
6
7
|
export interface EngineSpec {
|
package/dist/src/init.js
CHANGED
|
@@ -6,6 +6,7 @@ import { compileGlobalL0 } from './compiler.js';
|
|
|
6
6
|
import { c, hr, shouldUseColor } from './ui.js';
|
|
7
7
|
export const BLOCK_START = '<!-- faber-memory:start -->';
|
|
8
8
|
export const BLOCK_END = '<!-- faber-memory:end -->';
|
|
9
|
+
export const TOOL_GUIDANCE_LINE = 'Use the faber-memory MCP tools: memory_search and memory_get for the details behind these lines; when you learn a durable rule, decision, lesson or preference, call memory_propose (the user approves it later; never edit memory files directly).';
|
|
9
10
|
export const PROJECT_HINT_LINE = 'Project memory: run npx @fabersep/memory init';
|
|
10
11
|
export function getEngineSpecs() {
|
|
11
12
|
return {
|
|
@@ -15,7 +16,7 @@ export function getEngineSpecs() {
|
|
|
15
16
|
gap: false,
|
|
16
17
|
instructionFile: (home) => path.join(home, '.claude', 'CLAUDE.md'),
|
|
17
18
|
mcpConfigFile: (home) => path.join(home, '.claude.json'),
|
|
18
|
-
renderBlock: (l0Path) => `${BLOCK_START}\n@${l0Path}\n${BLOCK_END}`,
|
|
19
|
+
renderBlock: (l0Path) => `${BLOCK_START}\n@${l0Path}\n${TOOL_GUIDANCE_LINE}\n${BLOCK_END}`,
|
|
19
20
|
},
|
|
20
21
|
'claude-desktop': {
|
|
21
22
|
name: 'claude-desktop',
|
|
@@ -31,7 +32,7 @@ export function getEngineSpecs() {
|
|
|
31
32
|
gap: false,
|
|
32
33
|
instructionFile: (home) => path.join(home, '.gemini', 'GEMINI.md'),
|
|
33
34
|
mcpConfigFile: (home) => path.join(home, '.gemini', 'config', 'mcp_config.json'),
|
|
34
|
-
renderBlock: (l0Path) => `${BLOCK_START}\nAt session start, read ${l0Path}
|
|
35
|
+
renderBlock: (l0Path) => `${BLOCK_START}\nAt session start, read ${l0Path} (global L0 memory).\n${TOOL_GUIDANCE_LINE}\n${BLOCK_END}`,
|
|
35
36
|
},
|
|
36
37
|
cursor: {
|
|
37
38
|
name: 'cursor',
|
|
@@ -139,7 +140,7 @@ export function planOrApplyInit(config, options = {}) {
|
|
|
139
140
|
// Always compile L0 BEFORE writing any user-level pointer (AC-19b1)
|
|
140
141
|
const comp = compileGlobalL0(config, { homeDir, trigger: 'init' });
|
|
141
142
|
if (!comp.ok) {
|
|
142
|
-
throw new Error(`L0 compilation failed before init
|
|
143
|
+
throw new Error(`L0 compilation failed before init:\n${comp.errors.join('\n')}`);
|
|
143
144
|
}
|
|
144
145
|
}
|
|
145
146
|
for (const engineName of engines) {
|
package/dist/src/mcp.d.ts
CHANGED
|
@@ -46,7 +46,7 @@ export declare const MCP_TOOLS: readonly [{
|
|
|
46
46
|
};
|
|
47
47
|
}, {
|
|
48
48
|
readonly name: "memory_propose";
|
|
49
|
-
readonly description: "
|
|
49
|
+
readonly description: "Propose a durable rule, decision, lesson or preference you learned (or a fix to an existing entry). Goes to pre-memory for human approval; never edits active memory.";
|
|
50
50
|
readonly inputSchema: {
|
|
51
51
|
readonly type: "object";
|
|
52
52
|
readonly properties: {
|
|
@@ -103,6 +103,7 @@ export declare class FaberMemoryMcpServer {
|
|
|
103
103
|
private lastHeadSignature;
|
|
104
104
|
private lastLoaded;
|
|
105
105
|
private startupWarnings;
|
|
106
|
+
private unpushedReminderShown;
|
|
106
107
|
private startupPullPromise;
|
|
107
108
|
constructor(options?: {
|
|
108
109
|
homeDir?: string;
|
|
@@ -157,7 +158,7 @@ export declare class FaberMemoryMcpServer {
|
|
|
157
158
|
};
|
|
158
159
|
}, {
|
|
159
160
|
readonly name: "memory_propose";
|
|
160
|
-
readonly description: "
|
|
161
|
+
readonly description: "Propose a durable rule, decision, lesson or preference you learned (or a fix to an existing entry). Goes to pre-memory for human approval; never edits active memory.";
|
|
161
162
|
readonly inputSchema: {
|
|
162
163
|
readonly type: "object";
|
|
163
164
|
readonly properties: {
|
package/dist/src/mcp.js
CHANGED
|
@@ -1,15 +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
|
-
import {
|
|
13
|
+
import { getPackageVersion } from './version.js';
|
|
14
|
+
import { DEFAULT_SIMILARITY_HINT_FLOOR, VALID_TYPES, } from './types.js';
|
|
13
15
|
export const MCP_TOOLS = [
|
|
14
16
|
{
|
|
15
17
|
name: 'memory_search',
|
|
@@ -37,7 +39,7 @@ export const MCP_TOOLS = [
|
|
|
37
39
|
},
|
|
38
40
|
{
|
|
39
41
|
name: 'memory_propose',
|
|
40
|
-
description: '
|
|
42
|
+
description: 'Propose a durable rule, decision, lesson or preference you learned (or a fix to an existing entry). Goes to pre-memory for human approval; never edits active memory.',
|
|
41
43
|
inputSchema: {
|
|
42
44
|
type: 'object',
|
|
43
45
|
properties: {
|
|
@@ -66,6 +68,7 @@ export class FaberMemoryMcpServer {
|
|
|
66
68
|
lastHeadSignature = '';
|
|
67
69
|
lastLoaded = null;
|
|
68
70
|
startupWarnings = [];
|
|
71
|
+
unpushedReminderShown = false;
|
|
69
72
|
startupPullPromise = null;
|
|
70
73
|
constructor(options = {}) {
|
|
71
74
|
this.homeDir = options.homeDir || getHomeDir();
|
|
@@ -124,6 +127,13 @@ export class FaberMemoryMcpServer {
|
|
|
124
127
|
drainWarnings(loaded) {
|
|
125
128
|
const warnings = [...this.startupWarnings, ...loaded.uncommittedWarnings, ...loaded.shadowWarnings];
|
|
126
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
|
+
}
|
|
127
137
|
return warnings;
|
|
128
138
|
}
|
|
129
139
|
listTools() {
|
|
@@ -269,6 +279,10 @@ export class FaberMemoryMcpServer {
|
|
|
269
279
|
recordPropose('validation_error');
|
|
270
280
|
return errorResponse('body is required.');
|
|
271
281
|
}
|
|
282
|
+
if (scope === 'personal' && isReadOnlyRoot(config.roots.personal)) {
|
|
283
|
+
recordPropose('validation_error');
|
|
284
|
+
return errorResponse(READ_ONLY_MESSAGE);
|
|
285
|
+
}
|
|
272
286
|
// Validate target_id for update / supersede (AC-08c1, AC-08c2)
|
|
273
287
|
if (action === 'update' || action === 'supersede') {
|
|
274
288
|
if (!targetId) {
|
|
@@ -328,6 +342,10 @@ export class FaberMemoryMcpServer {
|
|
|
328
342
|
projectRootPath: scope === 'project' ? loaded.projectResolution.projectRoot : undefined,
|
|
329
343
|
}, this.homeDir);
|
|
330
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
|
+
: [];
|
|
331
349
|
this.lastHeadSignature = '';
|
|
332
350
|
const warnings = this.drainWarnings(loaded);
|
|
333
351
|
return {
|
|
@@ -339,6 +357,14 @@ export class FaberMemoryMcpServer {
|
|
|
339
357
|
proposal_id: proposal.id,
|
|
340
358
|
entry_id: proposal.entryId,
|
|
341
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
|
+
: {}),
|
|
342
368
|
warnings,
|
|
343
369
|
}, null, 2),
|
|
344
370
|
},
|
|
@@ -364,7 +390,7 @@ export class FaberMemoryMcpServer {
|
|
|
364
390
|
},
|
|
365
391
|
serverInfo: {
|
|
366
392
|
name: '@fabersep/memory',
|
|
367
|
-
version:
|
|
393
|
+
version: getPackageVersion(),
|
|
368
394
|
},
|
|
369
395
|
},
|
|
370
396
|
};
|
|
@@ -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;
|
package/dist/src/proposals.js
CHANGED
|
@@ -5,6 +5,7 @@ import { compileGlobalL0 } from './compiler.js';
|
|
|
5
5
|
import { parseMarkdownWithFrontmatter, serializeEntryMarkdown, slugify, } from './frontmatter.js';
|
|
6
6
|
import { buildCompareUrl, createThrowawayWorktree, getDefaultBranch, getRemoteUrl, gitCommitFiles, gitPullFfOnly, gitSync, isBranchProtectionRejection, readHeadFile, removeThrowawayWorktree, } from './git.js';
|
|
7
7
|
import { formatHygieneErrors, scanHygiene } from './hygiene.js';
|
|
8
|
+
import { isReadOnlyRoot, pullRebaseBeforeCommit, READ_ONLY_MESSAGE } from './personal-remote.js';
|
|
8
9
|
import { appendMetric } from './metrics.js';
|
|
9
10
|
import { PROJECT_MEMORY_REL_DIR } from './store.js';
|
|
10
11
|
export const CACHE_GUIDANCE_NOTE = 'Note: Updated L0 applies to new sessions; batching reviews at session end maximizes prompt-cache reuse.';
|
|
@@ -179,6 +180,7 @@ export async function approveProposalsBatch(config, proposals, options = {}) {
|
|
|
179
180
|
const approvedIds = [];
|
|
180
181
|
let compareUrl;
|
|
181
182
|
let recompiledL0 = false;
|
|
183
|
+
let personalCommitted = false;
|
|
182
184
|
if (proposals.length === 0) {
|
|
183
185
|
return { ok: true, approvedIds: [], messages: ['No proposals to approve.'], errors: [] };
|
|
184
186
|
}
|
|
@@ -207,6 +209,13 @@ export async function approveProposalsBatch(config, proposals, options = {}) {
|
|
|
207
209
|
errors.push('Personal memory root is not configured.');
|
|
208
210
|
return { ok: false, approvedIds, messages, errors };
|
|
209
211
|
}
|
|
212
|
+
if (isReadOnlyRoot(root)) {
|
|
213
|
+
errors.push(READ_ONLY_MESSAGE);
|
|
214
|
+
return { ok: false, approvedIds, messages, errors };
|
|
215
|
+
}
|
|
216
|
+
const pullWarning = await pullRebaseBeforeCommit(root);
|
|
217
|
+
if (pullWarning)
|
|
218
|
+
messages.push(pullWarning);
|
|
210
219
|
const touched = [];
|
|
211
220
|
for (const p of personalProps) {
|
|
212
221
|
touched.push(...applyProposalFilesToDir(root.path, '', p));
|
|
@@ -231,6 +240,7 @@ export async function approveProposalsBatch(config, proposals, options = {}) {
|
|
|
231
240
|
return { ok: false, approvedIds, messages, errors };
|
|
232
241
|
}
|
|
233
242
|
recompiledL0 = true;
|
|
243
|
+
personalCommitted = true;
|
|
234
244
|
messages.push(`Approved ${personalProps.length} personal proposal(s) in 1 commit and recompiled L0 (${comp.estimatedTokens}/${comp.budget} tokens).`);
|
|
235
245
|
}
|
|
236
246
|
// 2. Project scope: write uncommitted file(s) and mark awaiting_commit
|
|
@@ -288,6 +298,7 @@ export async function approveProposalsBatch(config, proposals, options = {}) {
|
|
|
288
298
|
errors: [],
|
|
289
299
|
compareUrl,
|
|
290
300
|
recompiledL0,
|
|
301
|
+
personalCommitted,
|
|
291
302
|
};
|
|
292
303
|
}
|
|
293
304
|
async function approveTeamBatch(config, root, teamProps, homeDir, overrideMode) {
|
package/dist/src/stats.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { CacheAnalysisResult, CacheEngineOption } from './cache-logs.js';
|
|
2
|
+
import { getPackageVersion } from './version.js';
|
|
3
|
+
export { getPackageVersion };
|
|
2
4
|
export declare const STATS_SCHEMA_VERSION = 1;
|
|
3
5
|
export declare const MCP_SCHEMA_TOKEN_TARGET = 500;
|
|
4
6
|
export declare const STALE_VERIFIED_DAYS = 90;
|
|
5
7
|
export declare const L0_CHURN_WARN_THRESHOLD = 5;
|
|
6
|
-
export declare function getPackageVersion(): string;
|
|
7
8
|
export declare function validateDaysArg(raw: unknown): {
|
|
8
9
|
ok: true;
|
|
9
10
|
days: number;
|
package/dist/src/stats.js
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import * as fs from 'node:fs';
|
|
2
|
-
import * as path from 'node:path';
|
|
3
|
-
import { fileURLToPath } from 'node:url';
|
|
4
2
|
import { analyzeCacheLogs } from './cache-logs.js';
|
|
5
3
|
import { estimateCorpusTokens, estimateTokens, renderGlobalL0 } from './compiler.js';
|
|
6
4
|
import { getCompiledL0Path, getConfigPath, getHomeDir, loadConfig } from './config.js';
|
|
@@ -8,24 +6,12 @@ import { MCP_TOOLS } from './mcp.js';
|
|
|
8
6
|
import { readMetrics, } from './metrics.js';
|
|
9
7
|
import { loadScopeFromHead, PROJECT_MEMORY_REL_DIR, resolveProjectRoot } from './store.js';
|
|
10
8
|
import { c, hr } from './ui.js';
|
|
9
|
+
import { getPackageVersion } from './version.js';
|
|
10
|
+
export { getPackageVersion };
|
|
11
11
|
export const STATS_SCHEMA_VERSION = 1;
|
|
12
12
|
export const MCP_SCHEMA_TOKEN_TARGET = 500;
|
|
13
13
|
export const STALE_VERIFIED_DAYS = 90;
|
|
14
14
|
export const L0_CHURN_WARN_THRESHOLD = 5;
|
|
15
|
-
export function getPackageVersion() {
|
|
16
|
-
try {
|
|
17
|
-
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
18
|
-
const pkgPath = path.resolve(__dirname, '../../package.json');
|
|
19
|
-
const raw = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
|
|
20
|
-
if (typeof raw.version === 'string' && raw.version.trim()) {
|
|
21
|
-
return raw.version.trim();
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
catch {
|
|
25
|
-
// Fallback below
|
|
26
|
-
}
|
|
27
|
-
return '0.2.0';
|
|
28
|
-
}
|
|
29
15
|
export function validateDaysArg(raw) {
|
|
30
16
|
if (raw === undefined || raw === false) {
|
|
31
17
|
return { ok: true, days: 30 };
|
package/dist/src/sync.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getHomeDir } from './config.js';
|
|
2
2
|
import { compileGlobalL0 } from './compiler.js';
|
|
3
3
|
import { getHeadSha, gitPullFfOnly, hasRemote } from './git.js';
|
|
4
|
+
import { recordSuccessfulPull } from './personal-remote.js';
|
|
4
5
|
export async function syncAllRoots(config, options = {}) {
|
|
5
6
|
const homeDir = options.homeDir || getHomeDir();
|
|
6
7
|
const timeoutMs = options.timeoutMs ?? 5000;
|
|
@@ -22,6 +23,8 @@ export async function syncAllRoots(config, options = {}) {
|
|
|
22
23
|
warnings.push(msg);
|
|
23
24
|
continue;
|
|
24
25
|
}
|
|
26
|
+
if (root.scope === 'personal')
|
|
27
|
+
recordSuccessfulPull(homeDir);
|
|
25
28
|
const afterSha = getHeadSha(root.path);
|
|
26
29
|
if (beforeSha !== afterSha) {
|
|
27
30
|
advanced = true;
|