-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
192 lines (166 loc) · 6.91 KB
/
index.js
File metadata and controls
192 lines (166 loc) · 6.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
const fs = require('fs');
const path = require('path');
const { getBrainRoot } = require('./scripts/config');
const { formatCompact } = require('./scripts/build-index');
const MAX_EVIDENCE_LINES = 20;
function truncateEvidence(persona) {
const evidenceHeader = /^###?\s*Evidence\s*Log/im;
const match = persona.match(evidenceHeader);
if (!match) return persona;
const headerIdx = persona.indexOf(match[0]);
const beforeEvidence = persona.slice(0, headerIdx + match[0].length);
const afterHeader = persona.slice(headerIdx + match[0].length);
const nextSection = afterHeader.match(/^##\s/m);
const evidenceBlock = nextSection ? afterHeader.slice(0, nextSection.index) : afterHeader;
const afterEvidence = nextSection ? afterHeader.slice(nextSection.index) : '';
const lines = evidenceBlock.split('\n').filter(l => l.trim().startsWith('-') || l.trim().startsWith('['));
if (lines.length <= MAX_EVIDENCE_LINES) return persona;
const truncated = lines.slice(-MAX_EVIDENCE_LINES);
return beforeEvidence + '\n' + truncated.join('\n') + '\n\n' + afterEvidence;
}
const plugin = {
id: 'remember',
name: 'Remember',
description: 'Portable knowledge base — one brain, every AI tool. Extract decisions, people, and insights from your AI sessions into organized local markdown.',
version: '2.0.6',
configSchema: {
type: 'object',
properties: {
brainPath: {
type: 'string',
default: '~/remember',
description: 'Path to your Remember brain (markdown knowledge base)',
},
},
additionalProperties: false,
},
register(api) {
// Read plugin config and set environment for scripts
const pluginCfg = api.pluginConfig || {};
const brainPath = pluginCfg.brainPath || process.env.REMEMBER_BRAIN_PATH || '~/remember';
const expandedPath = brainPath.startsWith('~')
? path.join(require('os').homedir(), brainPath.slice(1))
: path.resolve(brainPath);
process.env.REMEMBER_BRAIN_PATH = expandedPath;
// Hook: Inject Persona.md on session_start
// (migrated from openclaw-hooks/persona-loader/handler.js)
api.on('session_start', async (event) => {
const brain = getBrainRoot();
if (!brain || !fs.existsSync(brain)) return;
const personaPath = path.join(brain, 'Persona.md');
let persona;
try {
persona = fs.readFileSync(personaPath, 'utf-8');
} catch {
return;
}
if (!persona || !persona.trim()) return;
persona = truncateEvidence(persona);
return {
prependContext:
`# REMEMBER BRAIN LOADED\nBrain: ${brain}\n\n` +
`## PERSONA\n${persona}\n\n` +
`Commands: /remember:process, /remember:status, 'remember this: ...'`,
};
});
// Tool: remember_brain_dump_context
// Returns brain index + processing instructions when the agent needs to save knowledge
api.registerTool({
name: 'remember_brain_dump_context',
description: 'Get brain dump context with index and processing instructions. Call this when the user says "remember this", "save this", "brain dump", or similar.',
parameters: {
type: 'object',
properties: {
userMessage: {
type: 'string',
description: 'The user message that triggered the brain dump',
},
},
required: ['userMessage'],
},
async execute(_id, params) {
const brain = getBrainRoot();
if (!fs.existsSync(brain)) {
return { content: [{ type: 'text', text: 'Brain not found. Run /remember:init first.' }] };
}
let compactIndex;
try {
compactIndex = formatCompact(brain);
} catch {
compactIndex = `BRAIN INDEX (${brain})\n(index unavailable)`;
}
const pluginRoot = __dirname;
const templatePath = path.join(pluginRoot, 'assets', 'templates', 'brain-dump-context.md');
const today = new Date().toISOString().slice(0, 10);
let instructions;
try {
instructions = fs.readFileSync(templatePath, 'utf-8').replace(/\{\{TODAY\}\}/g, today);
} catch {
instructions = '(template missing)';
}
// Load REMEMBER.md — cascading: global (brain) + project (cwd)
const sectionsToExtract = ['Capture Rules', 'Processing', 'Custom Types', 'Language'];
function extractSections(filePath, sections) {
let text;
try { text = fs.readFileSync(filePath, 'utf-8'); } catch { return {}; }
const result = {};
for (const name of sections) {
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(`^## ${escaped}\\s*\\n(.*?)(?=^## |$)`, 'ms');
const match = text.match(re);
if (match) {
const content = match[1].trim();
if (content) result[name] = content;
}
}
return result;
}
const globalSections = extractSections(path.join(brain, 'REMEMBER.md'), sectionsToExtract);
const projectSections = extractSections(path.join(process.cwd(), 'REMEMBER.md'), sectionsToExtract);
const merged = {};
for (const name of sectionsToExtract) {
const parts = [];
if (globalSections[name]) parts.push(globalSections[name]);
if (projectSections[name]) parts.push(projectSections[name]);
if (parts.length) merged[name] = parts.join('\n\n');
}
let rememberContext = '';
if (Object.keys(merged).length) {
const extracted = Object.entries(merged).map(([name, content]) => `## ${name}\n${content}`);
rememberContext = '\n\nUSER OVERRIDES (these take precedence over defaults above):\n' + extracted.join('\n\n');
}
const context =
`BRAIN DUMP — Full processing instructions. Brain: ${brain}. Today: ${today}.\n\n` +
`${compactIndex}\n\n` +
`${instructions}` +
`${rememberContext}`;
return { content: [{ type: 'text', text: context }] };
},
});
// Tool: remember_brain_index
// Returns compact brain index for quick lookups
api.registerTool({
name: 'remember_brain_index',
description: 'Get the brain index showing all tracked people, projects, areas, notes, tasks, and journal entries.',
parameters: {
type: 'object',
properties: {},
additionalProperties: false,
},
async execute() {
const brain = getBrainRoot();
if (!fs.existsSync(brain)) {
return { content: [{ type: 'text', text: 'Brain not found. Run /remember:init first.' }] };
}
try {
const index = formatCompact(brain);
return { content: [{ type: 'text', text: index }] };
} catch (err) {
return { content: [{ type: 'text', text: `Error building index: ${err.message}` }] };
}
},
});
},
};
module.exports = plugin;
module.exports.default = plugin;