@technomoron/agent-brain 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.
- package/CHANGES.md +14 -0
- package/LICENSE +21 -0
- package/README.md +852 -2
- package/dist/agent-brain.js +6 -0
- package/dist/brain/built-in-skills.js +24 -0
- package/dist/brain/cli.js +265 -0
- package/dist/brain/config.js +92 -0
- package/dist/brain/connectors.js +63 -0
- package/dist/brain/consolidation-skill.js +5 -0
- package/dist/brain/consolidation.js +134 -0
- package/dist/brain/git.js +139 -0
- package/dist/brain/github-reviews.js +174 -0
- package/dist/brain/projects.js +136 -0
- package/dist/brain/remote-policy.js +126 -0
- package/dist/brain/remote-server.js +211 -0
- package/dist/brain/repositories.js +28 -0
- package/dist/brain/repository-discovery.js +76 -0
- package/dist/brain/server.js +283 -0
- package/dist/brain/skills.js +54 -0
- package/dist/brain/store.js +499 -0
- package/dist/brain/todos.js +155 -0
- package/dist/brain/windows-pipe.js +19 -0
- package/dist/version.js +22 -0
- package/examples/brain.jsonc +7 -0
- package/examples/remote.jsonc +22 -0
- package/ops/config-deploy-entry.sh +3 -0
- package/ops/config-deploy-root.cjs +111 -0
- package/ops/config-deploy.cjs +176 -0
- package/ops/config-policy.cjs +220 -0
- package/ops/config-sync.cjs +72 -0
- package/ops/systemd/agent-brain.service +14 -0
- package/package.json +55 -4
- package/skills/brain-consolidate/SKILL.md +42 -0
- package/skills/brain-import/SKILL.md +56 -0
- package/skills/brain-memory/SKILL.md +73 -0
- package/skills/brain-review/SKILL.md +38 -0
- package/skills/code-review-organizer/SKILL.md +150 -0
- package/skills/review-items/SKILL.md +43 -0
- package/skills/todo-manager/SKILL.md +8 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readBuiltInSkill = readBuiltInSkill;
|
|
4
|
+
exports.readBuiltInSkills = readBuiltInSkills;
|
|
5
|
+
const fs = require("node:fs");
|
|
6
|
+
const path = require("node:path");
|
|
7
|
+
const zod_1 = require("zod");
|
|
8
|
+
const store_1 = require("./store");
|
|
9
|
+
const directory = path.resolve(__dirname, '..', '..', 'skills');
|
|
10
|
+
const metadata = zod_1.z.object({ name: zod_1.z.string(), description: zod_1.z.string().min(1) });
|
|
11
|
+
function readBuiltInSkill(name) {
|
|
12
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name))
|
|
13
|
+
throw new Error(`Invalid built-in skill name: ${name}`);
|
|
14
|
+
const document = (0, store_1.readMarkdown)(fs.readFileSync(path.join(directory, name, 'SKILL.md'), 'utf8'));
|
|
15
|
+
const parsed = metadata.parse(document.metadata);
|
|
16
|
+
if (parsed.name !== name)
|
|
17
|
+
throw new Error(`Built-in skill name must match directory: ${name}`);
|
|
18
|
+
return { description: parsed.description, content: document.content };
|
|
19
|
+
}
|
|
20
|
+
function readBuiltInSkills() {
|
|
21
|
+
return Object.fromEntries(fs.readdirSync(directory, { withFileTypes: true })
|
|
22
|
+
.filter((entry) => entry.isDirectory()).sort((a, b) => a.name.localeCompare(b.name))
|
|
23
|
+
.map((entry) => [entry.name, readBuiltInSkill(entry.name)]));
|
|
24
|
+
}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.brainMain = brainMain;
|
|
4
|
+
exports.reportBrainError = reportBrainError;
|
|
5
|
+
const path = require("node:path");
|
|
6
|
+
const node_util_1 = require("node:util");
|
|
7
|
+
const constants_1 = require("@technomoron/agent-run/dist/constants");
|
|
8
|
+
const project_1 = require("@technomoron/agent-run/dist/project");
|
|
9
|
+
const config_1 = require("./config");
|
|
10
|
+
const projects_1 = require("./projects");
|
|
11
|
+
const zod_1 = require("zod");
|
|
12
|
+
const store_1 = require("./store");
|
|
13
|
+
const consolidation_1 = require("./consolidation");
|
|
14
|
+
const consolidation_skill_1 = require("./consolidation-skill");
|
|
15
|
+
const skills_1 = require("./skills");
|
|
16
|
+
const todos_1 = require("./todos");
|
|
17
|
+
const connectors_1 = require("./connectors");
|
|
18
|
+
const git_1 = require("./git");
|
|
19
|
+
const github_reviews_1 = require("./github-reviews");
|
|
20
|
+
async function brainMain(argv, wrapperCommand) {
|
|
21
|
+
const { values, positionals } = (0, node_util_1.parseArgs)({ args: argv, allowPositionals: true, strict: true, options: {
|
|
22
|
+
configdir: { type: 'string' }, cwd: { type: 'string' }, socket: { type: 'string' },
|
|
23
|
+
'remote-config': { type: 'string' },
|
|
24
|
+
quick: { type: 'boolean' }, guided: { type: 'boolean' },
|
|
25
|
+
pull: { type: 'boolean' },
|
|
26
|
+
json: { type: 'string' }, scope: { type: 'string' }, revision: { type: 'string' }, state: { type: 'string' }, severity: { type: 'string' },
|
|
27
|
+
confirmed: { type: 'boolean' }, message: { type: 'string' }, help: { type: 'boolean', short: 'h' }
|
|
28
|
+
} });
|
|
29
|
+
if (values.configdir)
|
|
30
|
+
process.env[constants_1.CONFIG_ROOT_OVERRIDE_ENV] = path.resolve(values.configdir);
|
|
31
|
+
const cwd = path.resolve(values.cwd ?? process.cwd());
|
|
32
|
+
const root = (0, project_1.defaultConfigRoot)(cwd);
|
|
33
|
+
const command = wrapperCommand ?? positionals.shift() ?? 'help';
|
|
34
|
+
if (command === 'serve-remote') {
|
|
35
|
+
if (!values['remote-config'])
|
|
36
|
+
throw new Error('serve-remote requires --remote-config <private JSONC file>');
|
|
37
|
+
const { serveRemote } = await Promise.resolve().then(() => require('./remote-server'));
|
|
38
|
+
const service = await serveRemote(path.resolve(values['remote-config']));
|
|
39
|
+
process.stderr.write('agent-brain remote endpoint listening behind HTTPS proxy\n');
|
|
40
|
+
for (const signal of ['SIGINT', 'SIGTERM'])
|
|
41
|
+
process.once(signal, () => { void service.close(); });
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (values.pull && command !== 'serve')
|
|
45
|
+
throw new Error('--pull is only supported by serve');
|
|
46
|
+
const print = (value) => { process.stdout.write(`${JSON.stringify(value, null, 2)}\n`); };
|
|
47
|
+
if (values.help || command === 'help') {
|
|
48
|
+
process.stdout.write([
|
|
49
|
+
'agent-brain init | status | search <query> | context <task> | get <id>',
|
|
50
|
+
'agent-brain remember --json <knowledge-object>',
|
|
51
|
+
'agent-brain amend <id> --revision <hash> --json <changes>',
|
|
52
|
+
'agent-brain promote <id> --scope <scope> --revision <hash> --confirmed',
|
|
53
|
+
'agent-brain deprecate <id> --revision <hash> [reason]',
|
|
54
|
+
'agent-brain list [--json <inventory-options>]',
|
|
55
|
+
'agent-brain history [--json <history-options>]',
|
|
56
|
+
'agent-brain archive --json <sources-and-replacements>',
|
|
57
|
+
'agent-brain skills [name]',
|
|
58
|
+
'agent-brain review list [--severity <level>] [--state <state>]',
|
|
59
|
+
'agent-brain review history [query] [--scope <scope>] [--state fixed|wontfix]',
|
|
60
|
+
'agent-brain review archive --scope <scope>',
|
|
61
|
+
'agent-brain review resolve <id> --revision <hash> --state fixed|wontfix [reason]',
|
|
62
|
+
'agent-brain todo list | get <id> | add --json <task-object>',
|
|
63
|
+
'agent-brain todo update <id> --revision <hash> --json <changes>',
|
|
64
|
+
'agent-brain todo complete <id> --revision <hash>',
|
|
65
|
+
'agent-brain todo import|sync <connector> --scope <scope>',
|
|
66
|
+
'agent-brain pull | push | save | sync [--message <commit-message>]',
|
|
67
|
+
'agent-brain sync status | init',
|
|
68
|
+
'agent-brain serve [--pull] [--socket <path>] | mcp [--socket <path>]',
|
|
69
|
+
'agent-mcp serve-remote --remote-config <private JSONC file>',
|
|
70
|
+
'agent-run create <name> [--quick | --guided]',
|
|
71
|
+
'agent-run project list | info | bootstrap',
|
|
72
|
+
'Common options: --configdir <path>, --cwd <path>', ''
|
|
73
|
+
].join('\n'));
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (command === 'init') {
|
|
77
|
+
(0, projects_1.initializeBrain)(root, cwd);
|
|
78
|
+
print({ enabled: (0, config_1.readBrainConfig)(root)?.enabled, configRoot: root });
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (command === 'create') {
|
|
82
|
+
if (positionals.length !== 1 || !positionals[0])
|
|
83
|
+
throw new Error('Usage: agent-run create <name> [--quick | --guided]');
|
|
84
|
+
if (values.quick && values.guided)
|
|
85
|
+
throw new Error('--quick and --guided cannot be combined');
|
|
86
|
+
await (0, projects_1.createBrainProject)(root, cwd, positionals[0], values.quick ? 'quick' : values.guided ? 'guided' : 'normal');
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (command === 'serve' || command === 'mcp') {
|
|
90
|
+
const { defaultSocketPath, proxyStdio, serveApiCore } = await Promise.resolve().then(() => require('./server'));
|
|
91
|
+
const socket = path.resolve(values.socket ?? defaultSocketPath(root));
|
|
92
|
+
if (command === 'serve') {
|
|
93
|
+
if (values.pull) {
|
|
94
|
+
const startupStore = new store_1.BrainStore(root, cwd);
|
|
95
|
+
try {
|
|
96
|
+
process.stderr.write(`${(0, git_1.pullOnStart)(startupStore)}\n`);
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
startupStore.close();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const service = await serveApiCore(root, socket);
|
|
103
|
+
process.stderr.write(`agent-brain listening on ${socket}\n`);
|
|
104
|
+
let closing = false;
|
|
105
|
+
const close = () => { if (!closing) {
|
|
106
|
+
closing = true;
|
|
107
|
+
void service.close().catch((error) => { process.stderr.write(`${String(error)}\n`); process.exitCode = 1; });
|
|
108
|
+
} };
|
|
109
|
+
process.once('SIGTERM', close);
|
|
110
|
+
process.once('SIGINT', close);
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
await proxyStdio(socket, cwd, root);
|
|
114
|
+
}
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
const store = new store_1.BrainStore(root, cwd);
|
|
118
|
+
const requireId = (index = 0) => { const id = positionals[index]; if (!id)
|
|
119
|
+
throw new Error('An item id is required'); return id; };
|
|
120
|
+
const requireRevision = () => { if (!values.revision)
|
|
121
|
+
throw new Error('--revision is required; read the item first'); return values.revision; };
|
|
122
|
+
const json = () => { if (!values.json)
|
|
123
|
+
throw new Error('--json is required'); return JSON.parse(values.json); };
|
|
124
|
+
const report = (value) => print(store.withDiagnostics(value));
|
|
125
|
+
try {
|
|
126
|
+
switch (command) {
|
|
127
|
+
case 'status':
|
|
128
|
+
report({ configRoot: root, enabled: (0, config_1.readBrainConfig)(root)?.enabled ?? false, profile: store.profile, scopes: store.scopes, knowledge: store.allKnowledge().length, todos: (0, todos_1.listTodos)(store).length });
|
|
129
|
+
break;
|
|
130
|
+
case 'search':
|
|
131
|
+
report(store.search(positionals.join(' ')));
|
|
132
|
+
break;
|
|
133
|
+
case 'context':
|
|
134
|
+
report(store.context(positionals.join(' ')));
|
|
135
|
+
break;
|
|
136
|
+
case 'get':
|
|
137
|
+
report(store.get(requireId()));
|
|
138
|
+
break;
|
|
139
|
+
case 'remember':
|
|
140
|
+
report(store.remember(store_1.knowledgeInput.parse(json())));
|
|
141
|
+
break;
|
|
142
|
+
case 'promote':
|
|
143
|
+
if (!values.confirmed)
|
|
144
|
+
throw new Error('Promotion requires --confirmed after explicit user approval');
|
|
145
|
+
report(store.promote(requireId(), store_1.scopeSchema.parse(values.scope), requireRevision()));
|
|
146
|
+
break;
|
|
147
|
+
case 'amend':
|
|
148
|
+
report(store.amend(requireId(), requireRevision(), store_1.knowledgeChanges.parse(json())));
|
|
149
|
+
break;
|
|
150
|
+
case 'deprecate':
|
|
151
|
+
report(store.deprecate(requireId(), requireRevision(), positionals.slice(1).join(' ')));
|
|
152
|
+
break;
|
|
153
|
+
case 'list':
|
|
154
|
+
report((0, consolidation_1.listKnowledge)(store, consolidation_1.inventoryOptions.parse(values.json ? json() : {})));
|
|
155
|
+
break;
|
|
156
|
+
case 'history':
|
|
157
|
+
report((0, consolidation_1.knowledgeHistory)(store, consolidation_1.historyOptions.parse(values.json ? json() : {})));
|
|
158
|
+
break;
|
|
159
|
+
case 'archive':
|
|
160
|
+
report((0, consolidation_1.archiveKnowledge)(store, consolidation_1.archiveInput.parse(json())));
|
|
161
|
+
break;
|
|
162
|
+
case 'consolidation-skill':
|
|
163
|
+
report((0, skills_1.getSkills)(store).find((skill) => skill.name === 'brain-consolidate') ?? consolidation_skill_1.consolidationSkill);
|
|
164
|
+
break;
|
|
165
|
+
case 'skills':
|
|
166
|
+
report(positionals[0] ? (0, skills_1.getSkill)(store, positionals[0]) : (0, skills_1.listSkills)(store));
|
|
167
|
+
break;
|
|
168
|
+
case 'review': {
|
|
169
|
+
const operation = positionals.shift() ?? 'list';
|
|
170
|
+
const github = (0, github_reviews_1.githubReviews)(store);
|
|
171
|
+
if (github) {
|
|
172
|
+
if (operation === 'list' || operation === 'history') {
|
|
173
|
+
const items = await github.list(operation === 'history' ? 'closed' : values.state && values.state !== 'open' ? 'closed' : 'open');
|
|
174
|
+
report(items.filter((item) => (!values.severity || item.severity === values.severity) && (!values.state || item.state === values.state)));
|
|
175
|
+
}
|
|
176
|
+
else if (operation === 'get')
|
|
177
|
+
report(await github.get(requireId()));
|
|
178
|
+
else if (operation === 'create')
|
|
179
|
+
report(await github.create(github_reviews_1.reviewInput.parse(json())));
|
|
180
|
+
else if (operation === 'resolve')
|
|
181
|
+
report(await github.resolve(requireId(), requireRevision(), zod_1.z.enum(['fixed', 'wontfix']).parse(values.state), positionals.slice(1).join(' ') || 'Resolved after verification'));
|
|
182
|
+
else
|
|
183
|
+
throw new Error('GitHub reviews support list, history, get, create and resolve; use review_update over MCP for edits');
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
if (operation === 'list') {
|
|
187
|
+
report(store.reviews({
|
|
188
|
+
...(values.severity ? { severity: [store_1.severitySchema.parse(values.severity)] } : {}),
|
|
189
|
+
...(values.state ? { state: [store_1.reviewStateSchema.parse(values.state)] } : {})
|
|
190
|
+
}).map((item) => ({ finding: item.finding, severity: item.severity, state: item.state ?? 'open', title: item.title, id: item.id, revision: item.revision })));
|
|
191
|
+
}
|
|
192
|
+
else if (operation === 'history') {
|
|
193
|
+
report(store.reviewHistory({ query: positionals.join(' '), ...(values.scope ? { scope: store_1.scopeSchema.parse(values.scope) } : {}), ...(values.state ? { state: zod_1.z.enum(['fixed', 'wontfix']).parse(values.state) } : {}), limit: Number.MAX_SAFE_INTEGER }));
|
|
194
|
+
}
|
|
195
|
+
else if (operation === 'archive') {
|
|
196
|
+
report(store.archiveReviews(store_1.scopeSchema.parse(values.scope)));
|
|
197
|
+
}
|
|
198
|
+
else if (operation === 'resolve') {
|
|
199
|
+
const state = zod_1.z.enum(['fixed', 'wontfix']).parse(values.state);
|
|
200
|
+
report(store.resolveReview(requireId(), requireRevision(), state, positionals.slice(1).join(' ') || undefined));
|
|
201
|
+
}
|
|
202
|
+
else
|
|
203
|
+
throw new Error('Usage: agent-brain review list | resolve <id> --revision <hash> --state fixed|wontfix');
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
case 'pull':
|
|
207
|
+
case 'push':
|
|
208
|
+
case 'save':
|
|
209
|
+
case 'sync': {
|
|
210
|
+
const action = command === 'sync' ? positionals.shift() ?? 'sync' : command;
|
|
211
|
+
if (positionals.length)
|
|
212
|
+
throw new Error('Unexpected arguments; use agent-brain --help');
|
|
213
|
+
if (action === 'status') {
|
|
214
|
+
report((0, git_1.gitPreview)(store));
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
217
|
+
if (!['init', 'save', 'pull', 'push', 'sync'].includes(action))
|
|
218
|
+
throw new Error('Unknown sync action');
|
|
219
|
+
const result = (0, git_1.syncGit)(store, action, values.message);
|
|
220
|
+
process.stdout.write(`${result.steps.join('\n')}\n`);
|
|
221
|
+
if (result.files.length)
|
|
222
|
+
process.stdout.write(`Other local changes remain. Use agent-brain sync status to inspect them.\n`);
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
case 'todo': {
|
|
226
|
+
const operation = positionals.shift();
|
|
227
|
+
if (operation === 'list')
|
|
228
|
+
report((0, todos_1.listTodos)(store));
|
|
229
|
+
else if (operation === 'get')
|
|
230
|
+
report((0, todos_1.getTodo)(store, requireId()));
|
|
231
|
+
else if (operation === 'add')
|
|
232
|
+
report((0, todos_1.addTodo)(store, todos_1.todoInput.parse(json())));
|
|
233
|
+
else if (operation === 'update')
|
|
234
|
+
report((0, todos_1.updateTodo)(store, requireId(), requireRevision(), todos_1.todoChanges.parse(json())));
|
|
235
|
+
else if (operation === 'complete')
|
|
236
|
+
report((0, todos_1.updateTodo)(store, requireId(), requireRevision(), { status: 'done' }));
|
|
237
|
+
else if (operation === 'import' || operation === 'sync')
|
|
238
|
+
report(await (0, connectors_1.syncConnector)(store, requireId(), store_1.scopeSchema.parse(values.scope)));
|
|
239
|
+
else
|
|
240
|
+
throw new Error('Unknown todo command; use agent-brain --help');
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
case 'project': {
|
|
244
|
+
const operation = positionals[0];
|
|
245
|
+
if (operation === 'list')
|
|
246
|
+
report((0, config_1.listBrainProjects)(root));
|
|
247
|
+
else if (operation === 'info')
|
|
248
|
+
report({ profile: store.profile, ...(0, projects_1.inspectProject)(cwd) });
|
|
249
|
+
else if (operation === 'bootstrap')
|
|
250
|
+
report({ status: 'proposal', message: 'Inspect the listed documents to propose architecture, constraints, conventions, and specs. Confirm proposals before saving authoritative knowledge.', ...(0, projects_1.inspectProject)(cwd) });
|
|
251
|
+
else
|
|
252
|
+
throw new Error('Usage: agent-run project list | info | bootstrap');
|
|
253
|
+
break;
|
|
254
|
+
}
|
|
255
|
+
default: throw new Error(`Unknown brain command: ${command}`);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
finally {
|
|
259
|
+
store.close();
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
function reportBrainError(error) {
|
|
263
|
+
process.stderr.write(`agent-brain: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
264
|
+
process.exitCode = 1;
|
|
265
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.projectConfigSchema = exports.brainConfigSchema = void 0;
|
|
4
|
+
exports.defaultSocketPath = defaultSocketPath;
|
|
5
|
+
exports.readBrainConfig = readBrainConfig;
|
|
6
|
+
exports.listBrainProjects = listBrainProjects;
|
|
7
|
+
exports.namedBrainProfile = namedBrainProfile;
|
|
8
|
+
exports.registeredBrainProfile = registeredBrainProfile;
|
|
9
|
+
exports.registeredBrainProject = registeredBrainProject;
|
|
10
|
+
const fs = require("node:fs");
|
|
11
|
+
const path = require("node:path");
|
|
12
|
+
const os = require("node:os");
|
|
13
|
+
const node_crypto_1 = require("node:crypto");
|
|
14
|
+
const jsonc_parser_1 = require("jsonc-parser");
|
|
15
|
+
const yaml_1 = require("yaml");
|
|
16
|
+
const zod_1 = require("zod");
|
|
17
|
+
const utils_1 = require("@technomoron/agent-run/dist/utils");
|
|
18
|
+
function defaultSocketPath(configRoot) {
|
|
19
|
+
if (process.platform === 'win32') {
|
|
20
|
+
const identity = `${os.homedir().toLowerCase()}\0${path.resolve(configRoot).toLowerCase()}`;
|
|
21
|
+
return `\\\\.\\pipe\\agent-brain-${(0, node_crypto_1.createHash)('sha256').update(identity).digest('hex').slice(0, 32)}`;
|
|
22
|
+
}
|
|
23
|
+
return path.join(configRoot, 'runtime', 'agent-brain.sock');
|
|
24
|
+
}
|
|
25
|
+
exports.brainConfigSchema = zod_1.z.object({
|
|
26
|
+
enabled: zod_1.z.boolean().default(true),
|
|
27
|
+
remote: zod_1.z.object({
|
|
28
|
+
url: zod_1.z.string().url().refine(value => { const u = new URL(value); return u.protocol === 'https:' && !u.username && !u.password && !u.search && !u.hash; }, 'Use an HTTPS MCP URL without credentials'),
|
|
29
|
+
clientId: zod_1.z.string().min(1),
|
|
30
|
+
redirectUrl: zod_1.z.string().url().default('http://127.0.0.1:8123/callback'),
|
|
31
|
+
scope: zod_1.z.string().default('read write review repo:*')
|
|
32
|
+
}).strict().optional(),
|
|
33
|
+
contextBudget: zod_1.z.number().int().min(1000).max(100000).default(16000),
|
|
34
|
+
connectors: zod_1.z.record(zod_1.z.string().regex(/^[a-zA-Z0-9_-]+$/), zod_1.z.discriminatedUnion('type', [
|
|
35
|
+
zod_1.z.object({ type: zod_1.z.literal('github'), repository: zod_1.z.string().regex(/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/), tokenEnv: zod_1.z.string().regex(/^[A-Z_][A-Z0-9_]*$/).default('GITHUB_TOKEN') }).strict(),
|
|
36
|
+
zod_1.z.object({ type: zod_1.z.literal('trello'), board: zod_1.z.string().regex(/^[a-zA-Z0-9]+$/), keyEnv: zod_1.z.string().regex(/^[A-Z_][A-Z0-9_]*$/).default('TRELLO_API_KEY'), tokenEnv: zod_1.z.string().regex(/^[A-Z_][A-Z0-9_]*$/).default('TRELLO_TOKEN') }).strict()
|
|
37
|
+
])).default({})
|
|
38
|
+
}).strict();
|
|
39
|
+
function readBrainConfig(root) {
|
|
40
|
+
const file = path.join(root, 'brain.jsonc');
|
|
41
|
+
if (!fs.existsSync(file))
|
|
42
|
+
return null;
|
|
43
|
+
const errors = [];
|
|
44
|
+
const value = (0, jsonc_parser_1.parse)(fs.readFileSync(file, 'utf8'), errors, { allowTrailingComma: true });
|
|
45
|
+
if (errors.length)
|
|
46
|
+
throw new Error(`Invalid JSONC in ${file}`);
|
|
47
|
+
return exports.brainConfigSchema.parse(value);
|
|
48
|
+
}
|
|
49
|
+
exports.projectConfigSchema = zod_1.z.object({
|
|
50
|
+
name: zod_1.z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)*$/),
|
|
51
|
+
display_name: zod_1.z.string().optional(),
|
|
52
|
+
pool: zod_1.z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/).optional(),
|
|
53
|
+
roots: zod_1.z.array(zod_1.z.string().refine(path.isAbsolute, 'Source roots must be absolute paths')).min(1),
|
|
54
|
+
description: zod_1.z.string().default(''),
|
|
55
|
+
repository: zod_1.z.object({ url: zod_1.z.string() }).optional(),
|
|
56
|
+
agent: zod_1.z.object({ default: zod_1.z.enum(['codex', 'claude', 'gemini', 'grok']).default('codex') }).default({ default: 'codex' })
|
|
57
|
+
}).strict();
|
|
58
|
+
function listBrainProjects(configRoot) {
|
|
59
|
+
const directory = path.join(configRoot, 'projects');
|
|
60
|
+
if (!fs.existsSync(directory))
|
|
61
|
+
return [];
|
|
62
|
+
function scan(parent) {
|
|
63
|
+
return fs.readdirSync(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory()).sort((a, b) => a.name.localeCompare(b.name)).flatMap((entry) => {
|
|
64
|
+
const child = path.join(parent, entry.name);
|
|
65
|
+
const file = path.join(child, 'config.yaml');
|
|
66
|
+
if (!fs.existsSync(file))
|
|
67
|
+
return scan(child);
|
|
68
|
+
if (fs.lstatSync(file).isSymbolicLink())
|
|
69
|
+
throw new Error(`Project configuration must not be a symlink: ${file}`);
|
|
70
|
+
const config = exports.projectConfigSchema.parse((0, yaml_1.parse)(fs.readFileSync(file, 'utf8')));
|
|
71
|
+
if (config.name !== path.relative(directory, child).split(path.sep).join('/'))
|
|
72
|
+
throw new Error(`Project name must match directory: ${file}`);
|
|
73
|
+
return [{ ...config, profile: `projects/${config.name}` }];
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
return scan(directory);
|
|
77
|
+
}
|
|
78
|
+
function namedBrainProfile(configRoot, name) {
|
|
79
|
+
return listBrainProjects(configRoot).find((project) => project.name === name || project.profile === name)?.profile ?? null;
|
|
80
|
+
}
|
|
81
|
+
function registeredBrainProfile(configRoot, cwd) {
|
|
82
|
+
return registeredBrainProject(configRoot, cwd)?.profile ?? null;
|
|
83
|
+
}
|
|
84
|
+
function registeredBrainProject(configRoot, cwd) {
|
|
85
|
+
const matches = listBrainProjects(configRoot).flatMap((project) => project.roots
|
|
86
|
+
.filter((root) => (0, utils_1.isSamePathOrDescendant)(path.resolve(cwd), path.resolve(root)))
|
|
87
|
+
.map((root) => ({ profile: project.profile, pool: project.pool, root: path.resolve(root), length: path.resolve(root).length }))).sort((a, b) => b.length - a.length);
|
|
88
|
+
if (matches[0] && matches[1] && matches[0].length === matches[1].length && matches[0].profile !== matches[1].profile) {
|
|
89
|
+
throw new Error(`More than one project is configured for ${cwd}`);
|
|
90
|
+
}
|
|
91
|
+
return matches[0] ?? null;
|
|
92
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.syncConnector = syncConnector;
|
|
4
|
+
const zod_1 = require("zod");
|
|
5
|
+
const config_1 = require("./config");
|
|
6
|
+
const todos_1 = require("./todos");
|
|
7
|
+
const githubIssue = zod_1.z.object({ number: zod_1.z.number().int(), title: zod_1.z.string(), body: zod_1.z.string().nullable(), state: zod_1.z.enum(['open', 'closed']),
|
|
8
|
+
html_url: zod_1.z.url(), pull_request: zod_1.z.unknown().optional(), labels: zod_1.z.array(zod_1.z.union([zod_1.z.string(), zod_1.z.object({ name: zod_1.z.string() })])) });
|
|
9
|
+
const trelloCard = zod_1.z.object({ id: zod_1.z.string(), name: zod_1.z.string(), desc: zod_1.z.string(), closed: zod_1.z.boolean(), dueComplete: zod_1.z.boolean(), due: zod_1.z.string().nullable(),
|
|
10
|
+
url: zod_1.z.url(), labels: zod_1.z.array(zod_1.z.object({ name: zod_1.z.string() })) });
|
|
11
|
+
async function readRemote(url, headers) {
|
|
12
|
+
let response;
|
|
13
|
+
try {
|
|
14
|
+
response = await fetch(url, { headers, redirect: 'error', signal: AbortSignal.timeout(30000) });
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
throw new Error(`Could not reach ${url.hostname}; check connector credentials and network access.`);
|
|
18
|
+
}
|
|
19
|
+
if (!response.ok)
|
|
20
|
+
throw new Error(`Connector ${url.hostname} returned HTTP ${response.status}`);
|
|
21
|
+
return response.json();
|
|
22
|
+
}
|
|
23
|
+
async function syncConnector(store, name, scope) {
|
|
24
|
+
store.scopeDirectory(scope);
|
|
25
|
+
const connector = (0, config_1.readBrainConfig)(store.configRoot)?.connectors[name];
|
|
26
|
+
if (!connector)
|
|
27
|
+
throw new Error(`Connector not configured: ${name}`);
|
|
28
|
+
const tasks = [];
|
|
29
|
+
if (connector.type === 'github') {
|
|
30
|
+
const token = process.env[connector.tokenEnv];
|
|
31
|
+
for (let page = 1;; page += 1) {
|
|
32
|
+
if (page > 100)
|
|
33
|
+
throw new Error('GitHub import exceeds 10000 issues; split the task source before importing.');
|
|
34
|
+
const url = new URL(`https://api.github.com/repos/${connector.repository}/issues`);
|
|
35
|
+
url.search = new URLSearchParams({ state: 'all', per_page: '100', page: String(page) }).toString();
|
|
36
|
+
const issues = zod_1.z.array(githubIssue).parse(await readRemote(url, { accept: 'application/vnd.github+json', 'user-agent': 'agent-brain', ...(token ? { authorization: `Bearer ${token}` } : {}) }));
|
|
37
|
+
for (const issue of issues.filter((issue) => !issue.pull_request))
|
|
38
|
+
tasks.push({
|
|
39
|
+
scope, title: issue.title, description: issue.body ?? '', status: issue.state === 'closed' ? 'done' : 'todo',
|
|
40
|
+
labels: issue.labels.map((label) => typeof label === 'string' ? label : label.name),
|
|
41
|
+
source: { type: 'github', external_id: `${connector.repository}#${issue.number}`, url: issue.html_url }
|
|
42
|
+
});
|
|
43
|
+
if (issues.length < 100)
|
|
44
|
+
break;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
const key = process.env[connector.keyEnv];
|
|
49
|
+
const token = process.env[connector.tokenEnv];
|
|
50
|
+
if (!key || !token)
|
|
51
|
+
throw new Error(`Set ${connector.keyEnv} and ${connector.tokenEnv} before importing Trello tasks.`);
|
|
52
|
+
const url = new URL(`https://api.trello.com/1/boards/${connector.board}/cards/all`);
|
|
53
|
+
url.search = new URLSearchParams({ key, token, fields: 'id,name,desc,closed,dueComplete,due,url,labels' }).toString();
|
|
54
|
+
const cards = zod_1.z.array(trelloCard).parse(await readRemote(url, {}));
|
|
55
|
+
for (const card of cards)
|
|
56
|
+
tasks.push({ scope, title: card.name, description: card.desc,
|
|
57
|
+
status: card.dueComplete ? 'done' : card.closed ? 'cancelled' : 'todo',
|
|
58
|
+
...(card.due ? { due: card.due.slice(0, 10) } : {}), labels: card.labels.map((label) => label.name),
|
|
59
|
+
source: { type: 'trello', external_id: card.id, url: card.url }
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return (0, todos_1.importTodos)(store, tasks);
|
|
63
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.historyOptions = exports.inventoryOptions = exports.archiveInput = void 0;
|
|
4
|
+
exports.listKnowledge = listKnowledge;
|
|
5
|
+
exports.knowledgeHistory = knowledgeHistory;
|
|
6
|
+
exports.archiveKnowledge = archiveKnowledge;
|
|
7
|
+
const fs = require("node:fs");
|
|
8
|
+
const path = require("node:path");
|
|
9
|
+
const node_crypto_1 = require("node:crypto");
|
|
10
|
+
const zod_1 = require("zod");
|
|
11
|
+
const store_1 = require("./store");
|
|
12
|
+
const reference = zod_1.z.object({ id: zod_1.z.string().min(1).max(200), revision: zod_1.z.string().regex(/^[a-f0-9]{64}$/) }).strict();
|
|
13
|
+
exports.archiveInput = zod_1.z.object({
|
|
14
|
+
sources: zod_1.z.array(reference.extend({ replacements: zod_1.z.array(reference).min(1).max(50) })).min(1).max(50),
|
|
15
|
+
reason: zod_1.z.string().trim().min(1).max(2000)
|
|
16
|
+
}).strict();
|
|
17
|
+
const archivedRecord = reference.extend({
|
|
18
|
+
scope: store_1.scopeSchema, title: zod_1.z.string(), source: zod_1.z.string(), text: zod_1.z.string(),
|
|
19
|
+
archived: zod_1.z.string(), reason: zod_1.z.string(), replacements: zod_1.z.array(reference).min(1)
|
|
20
|
+
}).strict();
|
|
21
|
+
exports.inventoryOptions = zod_1.z.object({
|
|
22
|
+
scope: store_1.scopeSchema.optional(), types: zod_1.z.array(store_1.typeSchema).optional(), includeDeprecated: zod_1.z.boolean().optional(),
|
|
23
|
+
offset: zod_1.z.number().int().min(0).default(0), limit: zod_1.z.number().int().min(1).max(100).default(50)
|
|
24
|
+
}).strict();
|
|
25
|
+
function listKnowledge(store, input = {}) {
|
|
26
|
+
const options = exports.inventoryOptions.parse(input);
|
|
27
|
+
if (options.scope)
|
|
28
|
+
store.scopeDirectory(options.scope);
|
|
29
|
+
const items = store.allKnowledge().filter((item) => (!options.scope || item.scope === options.scope)
|
|
30
|
+
&& (!options.types || options.types.includes(item.type)) && (options.includeDeprecated || item.status === 'active'))
|
|
31
|
+
.sort((a, b) => a.source.localeCompare(b.source));
|
|
32
|
+
return { total: items.length, contextBudget: store.budget, items: items.slice(options.offset, options.offset + options.limit).map(({ content, ...item }) => ({ ...item, characters: content.length })) };
|
|
33
|
+
}
|
|
34
|
+
function historyFile(store, scope) {
|
|
35
|
+
return store.safePath(store.scopeDirectory(scope), 'knowledge-history.jsonl');
|
|
36
|
+
}
|
|
37
|
+
function readHistory(store, scope) {
|
|
38
|
+
const file = historyFile(store, scope);
|
|
39
|
+
if (!fs.existsSync(file))
|
|
40
|
+
return [];
|
|
41
|
+
const records = fs.readFileSync(file, 'utf8').split('\n').filter((line) => line.trim()).map((line) => archivedRecord.parse(JSON.parse(line)));
|
|
42
|
+
const ids = new Set();
|
|
43
|
+
for (const record of records) {
|
|
44
|
+
if (record.scope !== scope || ids.has(record.id) || (0, node_crypto_1.createHash)('sha256').update(record.text).digest('hex') !== record.revision) {
|
|
45
|
+
throw new Error(`Invalid or duplicate knowledge history record: ${file}`);
|
|
46
|
+
}
|
|
47
|
+
ids.add(record.id);
|
|
48
|
+
}
|
|
49
|
+
return records;
|
|
50
|
+
}
|
|
51
|
+
exports.historyOptions = zod_1.z.object({
|
|
52
|
+
scope: store_1.scopeSchema.optional(), id: reference.shape.id.optional(), query: zod_1.z.string().max(1000).optional(),
|
|
53
|
+
offset: zod_1.z.number().int().min(0).default(0), limit: zod_1.z.number().int().min(1).max(100).default(50)
|
|
54
|
+
}).strict();
|
|
55
|
+
function knowledgeHistory(store, input = {}) {
|
|
56
|
+
const options = exports.historyOptions.parse(input);
|
|
57
|
+
if (options.scope)
|
|
58
|
+
store.scopeDirectory(options.scope);
|
|
59
|
+
const query = options.query?.toLowerCase();
|
|
60
|
+
const records = store.scopes.filter((entry) => !options.scope || entry.scope === options.scope).flatMap((entry) => readHistory(store, entry.scope))
|
|
61
|
+
.filter((record) => (!options.id || record.id === options.id) && (!query || [record.id, record.title, record.reason].some((value) => value.toLowerCase().includes(query))))
|
|
62
|
+
.sort((a, b) => b.archived.localeCompare(a.archived) || a.id.localeCompare(b.id));
|
|
63
|
+
return { total: records.length, items: records.slice(options.offset, options.offset + options.limit).map(({ text, ...record }) => ({ ...record, ...(options.id ? { text } : {}) })) };
|
|
64
|
+
}
|
|
65
|
+
/** Replacements are written and checked first. Preserve exact originals before any deletion. */
|
|
66
|
+
function archiveKnowledge(store, input) {
|
|
67
|
+
const options = exports.archiveInput.parse(input);
|
|
68
|
+
return store.writeLocked(() => {
|
|
69
|
+
const sourceIds = new Set(options.sources.map((item) => item.id));
|
|
70
|
+
if (sourceIds.size !== options.sources.length)
|
|
71
|
+
throw new Error('Duplicate archive source IDs.');
|
|
72
|
+
const all = store.allKnowledge();
|
|
73
|
+
const byId = new Map(all.map((item) => [item.id, item]));
|
|
74
|
+
const firstReplacement = options.sources[0].replacements[0];
|
|
75
|
+
store.assertReadable(firstReplacement.id, store.knowledgeErrors);
|
|
76
|
+
const scope = byId.get(firstReplacement.id)?.scope;
|
|
77
|
+
if (!scope)
|
|
78
|
+
throw new Error('Replacement not found in the active scopes.');
|
|
79
|
+
const history = readHistory(store, scope);
|
|
80
|
+
const pending = options.sources.map((source) => {
|
|
81
|
+
store.assertReadable(source.id, store.knowledgeErrors);
|
|
82
|
+
const item = byId.get(source.id);
|
|
83
|
+
const prior = history.find((record) => record.id === source.id);
|
|
84
|
+
const replacements = source.replacements.map((ref) => {
|
|
85
|
+
store.assertReadable(ref.id, store.knowledgeErrors);
|
|
86
|
+
const replacement = byId.get(ref.id);
|
|
87
|
+
if (sourceIds.has(ref.id))
|
|
88
|
+
throw new Error('An archive source cannot also be a replacement.');
|
|
89
|
+
if (!replacement || replacement.status !== 'active' || replacement.type === 'review')
|
|
90
|
+
throw new Error('Replacements must be active non-review knowledge.');
|
|
91
|
+
if (replacement.revision !== ref.revision)
|
|
92
|
+
throw new Error('Replacement changed; read the current revision.');
|
|
93
|
+
if (replacement.scope !== scope)
|
|
94
|
+
throw new Error('Archive sources and replacements must share one scope.');
|
|
95
|
+
return replacement;
|
|
96
|
+
});
|
|
97
|
+
if (prior && (prior.revision !== source.revision || JSON.stringify(prior.replacements) !== JSON.stringify(source.replacements)))
|
|
98
|
+
throw new Error('Archived knowledge conflicts with this request; inspect knowledge_history.');
|
|
99
|
+
if (!item) {
|
|
100
|
+
if (!prior)
|
|
101
|
+
throw new Error(`Knowledge not found: ${source.id}`);
|
|
102
|
+
return { record: prior, remove: false };
|
|
103
|
+
}
|
|
104
|
+
if (item.revision !== source.revision)
|
|
105
|
+
throw new Error('Knowledge changed; read the current revision before archiving.');
|
|
106
|
+
if (item.scope !== scope)
|
|
107
|
+
throw new Error('Archive sources and replacements must share one scope.');
|
|
108
|
+
if (item.type === 'review')
|
|
109
|
+
throw new Error('Use the review tools for review findings.');
|
|
110
|
+
if (replacements.some((replacement) => replacement.authority !== item.authority))
|
|
111
|
+
throw new Error('Consolidation must preserve authority; keep uncertain knowledge separate.');
|
|
112
|
+
if (item.recall === 'always' && !replacements.some((replacement) => replacement.recall === 'always'))
|
|
113
|
+
throw new Error('Preserve always recall in a replacement.');
|
|
114
|
+
if (item.applies_to.some((pattern) => !replacements.some((replacement) => replacement.applies_to.includes(pattern))))
|
|
115
|
+
throw new Error('Preserve applies_to patterns in the replacements.');
|
|
116
|
+
const text = store.read(item.source);
|
|
117
|
+
if ((0, node_crypto_1.createHash)('sha256').update(text).digest('hex') !== item.revision)
|
|
118
|
+
throw new Error('Knowledge changed while preparing the archive.');
|
|
119
|
+
const record = prior ?? { id: item.id, revision: item.revision, scope, title: item.title, source: item.source, text,
|
|
120
|
+
archived: new Date().toISOString(), reason: options.reason, replacements: source.replacements };
|
|
121
|
+
if (prior && prior.source !== item.source)
|
|
122
|
+
throw new Error('Archived source path changed; inspect knowledge_history.');
|
|
123
|
+
return { record, remove: true };
|
|
124
|
+
});
|
|
125
|
+
const added = pending.filter(({ record }) => !history.some((old) => old.id === record.id)).map(({ record }) => record);
|
|
126
|
+
if (added.length)
|
|
127
|
+
store.atomicWrite(historyFile(store, scope), [...history, ...added].map((record) => JSON.stringify(record)).join('\n') + '\n');
|
|
128
|
+
// If deletion fails, the archive and replacements survive. An identical retry finishes it.
|
|
129
|
+
for (const { record, remove } of pending)
|
|
130
|
+
if (remove)
|
|
131
|
+
fs.unlinkSync(store.safePath(record.source));
|
|
132
|
+
return { archived: pending.map(({ record }) => record.id), history: path.relative(store.configRoot, historyFile(store, scope)) };
|
|
133
|
+
});
|
|
134
|
+
}
|