@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,155 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.todoChanges = exports.todoInput = void 0;
|
|
4
|
+
exports.listTodos = listTodos;
|
|
5
|
+
exports.getTodo = getTodo;
|
|
6
|
+
exports.addTodo = addTodo;
|
|
7
|
+
exports.updateTodo = updateTodo;
|
|
8
|
+
exports.importTodos = importTodos;
|
|
9
|
+
const path = require("node:path");
|
|
10
|
+
const node_crypto_1 = require("node:crypto");
|
|
11
|
+
const yaml_1 = require("yaml");
|
|
12
|
+
const zod_1 = require("zod");
|
|
13
|
+
const store_1 = require("./store");
|
|
14
|
+
exports.todoInput = zod_1.z.object({
|
|
15
|
+
scope: store_1.scopeSchema,
|
|
16
|
+
title: zod_1.z.string().trim().min(1).max(300),
|
|
17
|
+
description: zod_1.z.string().trim().max(200000).default(''),
|
|
18
|
+
status: zod_1.z.enum(['todo', 'doing', 'blocked', 'done', 'cancelled']).default('todo'),
|
|
19
|
+
priority: zod_1.z.enum(['low', 'medium', 'high', 'critical']).default('medium'),
|
|
20
|
+
owner: zod_1.z.string().optional(),
|
|
21
|
+
due: zod_1.z.iso.date().optional(),
|
|
22
|
+
labels: zod_1.z.array(zod_1.z.string()).default([]),
|
|
23
|
+
notes: zod_1.z.string().default(''),
|
|
24
|
+
source: zod_1.z.object({ type: zod_1.z.enum(['local', 'github', 'trello']), external_id: zod_1.z.string(), url: zod_1.z.url().optional() }).optional()
|
|
25
|
+
}).strict();
|
|
26
|
+
const remoteTask = exports.todoInput.pick({ title: true, description: true, status: true, labels: true, due: true }).strip();
|
|
27
|
+
const todoMetadata = exports.todoInput.omit({ description: true }).extend({ id: zod_1.z.uuid(), created: zod_1.z.string(), updated: zod_1.z.string(), remote: remoteTask.optional() });
|
|
28
|
+
function listTodos(store) {
|
|
29
|
+
store.todoErrors.length = 0;
|
|
30
|
+
const sources = new Map();
|
|
31
|
+
const todos = store.scopes.filter((entry) => !store.pool || entry.scope === 'project').flatMap(({ scope, directory }) => store.files(path.join(directory, 'todo'), { onError: (file, error) => store.todoErrors.push(store.brokenFile(file, error)) }).flatMap((file) => {
|
|
32
|
+
let id;
|
|
33
|
+
try {
|
|
34
|
+
const text = store.read(file);
|
|
35
|
+
const document = (0, store_1.readMarkdown)(text);
|
|
36
|
+
if (document.metadata && typeof document.metadata === 'object' && 'id' in document.metadata && typeof document.metadata.id === 'string')
|
|
37
|
+
id = document.metadata.id;
|
|
38
|
+
const metadata = todoMetadata.parse(document.metadata);
|
|
39
|
+
if (metadata.scope !== scope || path.basename(file) !== `${metadata.id}.md`)
|
|
40
|
+
throw new Error(`Todo metadata does not match its location: ${file}`);
|
|
41
|
+
const todo = { ...metadata, description: document.content, revision: (0, node_crypto_1.createHash)('sha256').update(text).digest('hex') };
|
|
42
|
+
sources.set(todo, file);
|
|
43
|
+
return [todo];
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
store.todoErrors.push(store.brokenFile(file, error, id));
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
}));
|
|
50
|
+
const counts = new Map();
|
|
51
|
+
for (const item of [...todos, ...store.todoErrors]) {
|
|
52
|
+
if (item.id)
|
|
53
|
+
counts.set(item.id, (counts.get(item.id) ?? 0) + 1);
|
|
54
|
+
}
|
|
55
|
+
return todos.filter((todo) => {
|
|
56
|
+
if (counts.get(todo.id) === 1)
|
|
57
|
+
return true;
|
|
58
|
+
store.todoErrors.push(store.brokenFile(sources.get(todo), new Error(`Duplicate todo id: ${todo.id}`), todo.id));
|
|
59
|
+
return false;
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
function getTodo(store, id) {
|
|
63
|
+
const todo = listTodos(store).find((item) => item.id === id);
|
|
64
|
+
store.assertReadable(id, store.todoErrors);
|
|
65
|
+
if (!todo)
|
|
66
|
+
throw new Error(`Todo not found: ${id}`);
|
|
67
|
+
return todo;
|
|
68
|
+
}
|
|
69
|
+
function writeTodo(store, todo) {
|
|
70
|
+
const { description, ...metadata } = todo;
|
|
71
|
+
const text = `---\n${(0, yaml_1.stringify)(metadata)}---\n\n${description}\n`;
|
|
72
|
+
store.atomicWrite(path.join(store.scopeDirectory(todo.scope), 'todo', `${todo.id}.md`), text);
|
|
73
|
+
return { ...todo, revision: (0, node_crypto_1.createHash)('sha256').update(text).digest('hex') };
|
|
74
|
+
}
|
|
75
|
+
function addTodo(store, input) {
|
|
76
|
+
const value = exports.todoInput.parse(input);
|
|
77
|
+
if (value.scope === 'pool' || (store.pool && value.scope !== 'project'))
|
|
78
|
+
throw new Error('Tasks must belong to an individual repository');
|
|
79
|
+
return store.writeLocked(() => {
|
|
80
|
+
if (value.source) {
|
|
81
|
+
const existing = listTodos(store).find((item) => item.scope === value.scope && item.source?.type === value.source?.type && item.source?.external_id === value.source?.external_id);
|
|
82
|
+
if (existing)
|
|
83
|
+
return existing;
|
|
84
|
+
if (store.todoErrors.length)
|
|
85
|
+
throw new Error('Cannot deduplicate an external task while todo files are broken. List tasks and correct the reported files first.');
|
|
86
|
+
}
|
|
87
|
+
const now = new Date().toISOString();
|
|
88
|
+
return writeTodo(store, { ...value, id: (0, node_crypto_1.randomUUID)(), created: now, updated: now });
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
// Spelled out rather than todoInput.omit(...).partial(): .partial() keeps .default(), so
|
|
92
|
+
// updating one field would reset description, priority, labels, and notes to their defaults.
|
|
93
|
+
exports.todoChanges = zod_1.z.object({
|
|
94
|
+
title: zod_1.z.string().trim().min(1).max(300).optional(),
|
|
95
|
+
description: zod_1.z.string().trim().max(200000).optional(),
|
|
96
|
+
status: zod_1.z.enum(['todo', 'doing', 'blocked', 'done', 'cancelled']).optional(),
|
|
97
|
+
priority: zod_1.z.enum(['low', 'medium', 'high', 'critical']).optional(),
|
|
98
|
+
owner: zod_1.z.string().optional(),
|
|
99
|
+
due: zod_1.z.iso.date().optional(),
|
|
100
|
+
labels: zod_1.z.array(zod_1.z.string()).optional(),
|
|
101
|
+
notes: zod_1.z.string().optional()
|
|
102
|
+
}).strict();
|
|
103
|
+
function updateTodo(store, id, revision, changes) {
|
|
104
|
+
const parsed = exports.todoChanges.parse(changes);
|
|
105
|
+
return store.writeLocked(() => {
|
|
106
|
+
const todo = getTodo(store, id);
|
|
107
|
+
if (todo.revision !== revision)
|
|
108
|
+
throw new Error('Todo changed; read the current revision before updating.');
|
|
109
|
+
const { revision: _revision, ...value } = todo;
|
|
110
|
+
return writeTodo(store, { ...value, ...parsed, updated: new Date().toISOString() });
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
function importTodos(store, input) {
|
|
114
|
+
const incoming = input.map((item) => exports.todoInput.parse(item));
|
|
115
|
+
return store.writeLocked(() => {
|
|
116
|
+
const result = { imported: [], updated: [], conflicts: [] };
|
|
117
|
+
const existing = listTodos(store);
|
|
118
|
+
if (store.todoErrors.length)
|
|
119
|
+
throw new Error('Cannot import tasks while todo files are broken. List tasks and correct the reported files first.');
|
|
120
|
+
for (const item of incoming) {
|
|
121
|
+
if (!item.source)
|
|
122
|
+
throw new Error('Imported tasks require an external source');
|
|
123
|
+
const prior = existing.find((todo) => todo.scope === item.scope && todo.source?.type === item.source.type && todo.source?.external_id === item.source.external_id);
|
|
124
|
+
const remote = remoteTask.parse(item);
|
|
125
|
+
const now = new Date().toISOString();
|
|
126
|
+
if (!prior) {
|
|
127
|
+
const task = writeTodo(store, { ...item, remote, id: (0, node_crypto_1.randomUUID)(), created: now, updated: now });
|
|
128
|
+
existing.push(task);
|
|
129
|
+
result.imported.push(task.id);
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (JSON.stringify(prior.remote) === JSON.stringify(remote))
|
|
133
|
+
continue;
|
|
134
|
+
const changes = {};
|
|
135
|
+
let conflicted = !prior.remote;
|
|
136
|
+
for (const key of ['title', 'description', 'status', 'labels', 'due']) {
|
|
137
|
+
const current = JSON.stringify(prior[key]);
|
|
138
|
+
const base = JSON.stringify(prior.remote?.[key]);
|
|
139
|
+
const next = JSON.stringify(remote[key]);
|
|
140
|
+
if (current !== base && next !== base && current !== next)
|
|
141
|
+
conflicted = true;
|
|
142
|
+
if (current === base)
|
|
143
|
+
changes[key] = remote[key];
|
|
144
|
+
}
|
|
145
|
+
if (conflicted) {
|
|
146
|
+
result.conflicts.push(prior.id);
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const { revision: _revision, ...metadata } = prior;
|
|
150
|
+
writeTodo(store, { ...metadata, ...changes, remote, updated: now });
|
|
151
|
+
result.updated.push(prior.id);
|
|
152
|
+
}
|
|
153
|
+
return result;
|
|
154
|
+
});
|
|
155
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.checkWindowsPipe = checkWindowsPipe;
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
const node_child_process_1 = require("node:child_process");
|
|
6
|
+
const node_util_1 = require("node:util");
|
|
7
|
+
async function checkWindowsPipe(pipePath, secure = false) {
|
|
8
|
+
if (!/^\\\\\.\\pipe\\[a-zA-Z0-9._-]+$/.test(pipePath))
|
|
9
|
+
throw new Error('Expected a local Windows named pipe (\\\\.\\pipe\\name).');
|
|
10
|
+
const powershell = path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
11
|
+
const helper = path.resolve(__dirname, '../../scripts/brain-pipe-security.ps1');
|
|
12
|
+
try {
|
|
13
|
+
await (0, node_util_1.promisify)(node_child_process_1.execFile)(powershell, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', helper,
|
|
14
|
+
'-PipePath', pipePath, ...(secure ? ['-Secure'] : [])], { encoding: 'utf8', windowsHide: true, timeout: 15000 });
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
throw new Error(`Cannot ${secure ? 'secure' : 'verify'} the brain pipe: ${String(error)}`);
|
|
18
|
+
}
|
|
19
|
+
}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.packageVersion = packageVersion;
|
|
4
|
+
const fs = require("fs");
|
|
5
|
+
const path = require("path");
|
|
6
|
+
let cached = null;
|
|
7
|
+
/**
|
|
8
|
+
* The package version, read from package.json next to the compiled output.
|
|
9
|
+
* This is the single source; nothing else in the tree hardcodes a version.
|
|
10
|
+
*/
|
|
11
|
+
function packageVersion() {
|
|
12
|
+
if (cached === null) {
|
|
13
|
+
try {
|
|
14
|
+
const pkg = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', 'package.json'), 'utf8'));
|
|
15
|
+
cached = typeof pkg.version === 'string' && pkg.version ? pkg.version : '0.0.0';
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
cached = '0.0.0';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return cached;
|
|
22
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
// Keep this file and repository data outside source checkouts.
|
|
3
|
+
"issuer": "https://mcp.example.com/oauth",
|
|
4
|
+
"resource": "https://mcp.example.com/mcp",
|
|
5
|
+
"runtime": "/srv/agent-mcp/runtime",
|
|
6
|
+
"listen": { "host": "127.0.0.1", "port": 3000 },
|
|
7
|
+
"users": [
|
|
8
|
+
{ "subject": "bjorn", "login": "bjorn", "passwordHashEnv": "MCP_BJORN_PASSWORD_HASH", "totpSecretEnv": "MCP_BJORN_TOTP" },
|
|
9
|
+
{ "subject": "ci", "login": "ci", "kind": "service" }
|
|
10
|
+
],
|
|
11
|
+
"clients": [
|
|
12
|
+
{ "id": "desktop", "kind": "public", "redirectUris": ["http://127.0.0.1:8123/callback"], "repos": ["technomoron/*"], "permissions": ["read", "write", "review"] },
|
|
13
|
+
{ "id": "ci", "kind": "service", "subject": "ci", "secretEnv": "MCP_CI_SECRET", "repos": ["technomoron/agent-run"], "permissions": ["read"] }
|
|
14
|
+
],
|
|
15
|
+
"access": [
|
|
16
|
+
{ "subject": "bjorn", "repos": ["technomoron/*"], "permissions": ["read", "write", "review"] },
|
|
17
|
+
{ "subject": "ci", "repos": ["technomoron/agent-run"], "permissions": ["read"] }
|
|
18
|
+
],
|
|
19
|
+
"repositories": [
|
|
20
|
+
{ "id": "technomoron/agent-run", "configRoot": "/srv/agent-mcp/data/technomoron/agent-run", "cwd": "/srv/checkouts/technomoron/agent-run" }
|
|
21
|
+
]
|
|
22
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
const fs = require('node:fs'),
|
|
4
|
+
{ execFileSync } = require('node:child_process');
|
|
5
|
+
const { manifest } = require('./config-policy.cjs');
|
|
6
|
+
const worker = '/opt/agent-mcp/current/node_modules/@technomoron/agent-brain/ops/config-deploy.cjs';
|
|
7
|
+
const file = '/etc/agent-mcp/remote.jsonc',
|
|
8
|
+
lock = '/var/lib/agent-mcp/config-deploy/catalog.lock',
|
|
9
|
+
maintenance = '/run/agent-brain-config-deploy-maintenance';
|
|
10
|
+
let interrupted = false;
|
|
11
|
+
for (const signal of ['SIGTERM', 'SIGHUP', 'SIGINT'])
|
|
12
|
+
process.on(signal, () => {
|
|
13
|
+
interrupted = true;
|
|
14
|
+
});
|
|
15
|
+
function run(action, value) {
|
|
16
|
+
return execFileSync(
|
|
17
|
+
'/usr/sbin/runuser',
|
|
18
|
+
['-u', 'agent-mcp', '--', '/usr/local/bin/node', worker, action, ...(value ? [value] : [])],
|
|
19
|
+
{ encoding: 'utf8', timeout: 120000, maxBuffer: 1024 * 1024 }
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
function service(action) {
|
|
23
|
+
execFileSync('/usr/bin/systemctl', [action, 'agent-mcp'], { timeout: 60000 });
|
|
24
|
+
}
|
|
25
|
+
function save(text) {
|
|
26
|
+
const temporary = file + '.deploy.tmp';
|
|
27
|
+
fs.writeFileSync(temporary, text, { mode: 0o640 });
|
|
28
|
+
fs.chownSync(temporary, 0, fs.statSync(file).gid);
|
|
29
|
+
fs.renameSync(temporary, file);
|
|
30
|
+
}
|
|
31
|
+
async function healthy(config) {
|
|
32
|
+
const base = 'http://127.0.0.1:' + config.listen.port;
|
|
33
|
+
for (let attempt = 0; attempt < 40; attempt++) {
|
|
34
|
+
if (interrupted) throw Error('Deployment interrupted');
|
|
35
|
+
try {
|
|
36
|
+
const metadata = await fetch(base + '/.well-known/oauth-authorization-server/oauth', {
|
|
37
|
+
signal: AbortSignal.timeout(1000)
|
|
38
|
+
});
|
|
39
|
+
if (metadata.ok) {
|
|
40
|
+
const rejected = await fetch(base + '/mcp', {
|
|
41
|
+
method: 'POST',
|
|
42
|
+
headers: { 'Content-Type': 'application/json' },
|
|
43
|
+
body: '{"jsonrpc":"2.0","id":1,"method":"tools/list"}',
|
|
44
|
+
signal: AbortSignal.timeout(1000)
|
|
45
|
+
});
|
|
46
|
+
if (rejected.status === 401) return;
|
|
47
|
+
}
|
|
48
|
+
} catch {}
|
|
49
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
50
|
+
}
|
|
51
|
+
throw Error('Brain did not pass deployment health checks');
|
|
52
|
+
}
|
|
53
|
+
(async () => {
|
|
54
|
+
if (process.getuid?.() !== 0) throw Error('Deployment controller must run as root');
|
|
55
|
+
const match = /^deploy ([0-9a-f]{40})$/.exec(process.argv[2] ?? '');
|
|
56
|
+
if (!match) throw Error('Expected deploy followed by one full Git SHA');
|
|
57
|
+
fs.mkdirSync(lock, { mode: 0o700 });
|
|
58
|
+
let activated = false,
|
|
59
|
+
gated = false,
|
|
60
|
+
original;
|
|
61
|
+
try {
|
|
62
|
+
const staged = JSON.parse(run('prepare', match[1])),
|
|
63
|
+
selection = manifest(staged.selection);
|
|
64
|
+
original = fs.readFileSync(file, 'utf8');
|
|
65
|
+
const config = require('../dist/brain/remote-policy').readRemoteConfig(file);
|
|
66
|
+
if (!config.dataRoot) throw Error('Configuration deployment requires central dataRoot');
|
|
67
|
+
const next = {
|
|
68
|
+
...config,
|
|
69
|
+
groups: selection.pools.map((id) => ({ id, configRoot: config.dataRoot })),
|
|
70
|
+
repositories: selection.repositories.map((repo) => ({
|
|
71
|
+
id: repo.id,
|
|
72
|
+
group: repo.pool,
|
|
73
|
+
configRoot: config.dataRoot,
|
|
74
|
+
cwd: '/var/lib/agent-mcp/checkouts/' + repo.id
|
|
75
|
+
}))
|
|
76
|
+
};
|
|
77
|
+
fs.copyFileSync(file, file + '.before-config-push-' + Date.now());
|
|
78
|
+
if (interrupted) throw Error('Deployment interrupted');
|
|
79
|
+
fs.writeFileSync(maintenance, 'Configuration deployment in progress\n', { mode: 0o644 });
|
|
80
|
+
gated = true;
|
|
81
|
+
service('stop');
|
|
82
|
+
run('activate');
|
|
83
|
+
activated = true;
|
|
84
|
+
save(JSON.stringify(next, null, 2) + '\n');
|
|
85
|
+
service('start');
|
|
86
|
+
await healthy(next);
|
|
87
|
+
console.log(
|
|
88
|
+
'Deployed ' +
|
|
89
|
+
match[1] +
|
|
90
|
+
'; ' +
|
|
91
|
+
staged.changes +
|
|
92
|
+
' files changed; ' +
|
|
93
|
+
selection.repositories.length +
|
|
94
|
+
' repositories; Brain healthy'
|
|
95
|
+
);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (activated) {
|
|
98
|
+
service('stop');
|
|
99
|
+
run('rollback');
|
|
100
|
+
save(original);
|
|
101
|
+
}
|
|
102
|
+
service('start');
|
|
103
|
+
throw error;
|
|
104
|
+
} finally {
|
|
105
|
+
if (gated) fs.rmSync(maintenance, { force: true });
|
|
106
|
+
fs.rmdirSync(lock);
|
|
107
|
+
}
|
|
108
|
+
})().catch((error) => {
|
|
109
|
+
console.error(error.message);
|
|
110
|
+
process.exitCode = 1;
|
|
111
|
+
});
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
const fs = require('node:fs'),
|
|
4
|
+
path = require('node:path'),
|
|
5
|
+
crypto = require('node:crypto'),
|
|
6
|
+
{ execFileSync } = require('node:child_process');
|
|
7
|
+
const { manifest, readSnapshot, mergeSnapshots, fileContents } = require('./config-policy.cjs');
|
|
8
|
+
const { BrainStore } = require('../dist/brain/store');
|
|
9
|
+
const { githubReviews } = require('../dist/brain/github-reviews');
|
|
10
|
+
const { listTodos } = require('../dist/brain/todos');
|
|
11
|
+
const { getSkills } = require('../dist/brain/skills');
|
|
12
|
+
const { createProfileMarker } = require('@technomoron/agent-run/dist/manifest');
|
|
13
|
+
const config = require('../dist/brain/remote-policy').readRemoteConfig('/etc/agent-mcp/remote.jsonc');
|
|
14
|
+
const data = config.dataRoot,
|
|
15
|
+
state = '/var/lib/agent-mcp/config-deploy',
|
|
16
|
+
catalog = '/var/lib/agent-mcp/catalogs/agent-brain-config';
|
|
17
|
+
fs.mkdirSync(state, { recursive: true, mode: 0o700 });
|
|
18
|
+
function git(args) {
|
|
19
|
+
return execFileSync('git', ['-C', catalog, ...args], {
|
|
20
|
+
encoding: 'utf8',
|
|
21
|
+
maxBuffer: 100 * 1024 * 1024,
|
|
22
|
+
timeout: 60000
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
function digest(root) {
|
|
26
|
+
const hash = crypto.createHash('sha256');
|
|
27
|
+
function scan(directory) {
|
|
28
|
+
for (const entry of fs
|
|
29
|
+
.readdirSync(directory, { withFileTypes: true })
|
|
30
|
+
.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
31
|
+
const file = path.join(directory, entry.name),
|
|
32
|
+
relative = path.relative(root, file);
|
|
33
|
+
if (directory === root && ['index', 'runtime', '.git'].includes(entry.name)) continue;
|
|
34
|
+
if (entry.isSymbolicLink()) throw Error('Symlink in live data: ' + relative);
|
|
35
|
+
if (entry.isDirectory()) scan(file);
|
|
36
|
+
else if (entry.isFile()) hash.update(relative + '\0').update(fs.readFileSync(file));
|
|
37
|
+
else throw Error('Unexpected live data entry');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
scan(root);
|
|
41
|
+
return hash.digest('hex');
|
|
42
|
+
}
|
|
43
|
+
function extract(revision, directory) {
|
|
44
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
45
|
+
const archive = execFileSync('git', ['-C', catalog, 'archive', revision], {
|
|
46
|
+
maxBuffer: 100 * 1024 * 1024,
|
|
47
|
+
timeout: 60000
|
|
48
|
+
});
|
|
49
|
+
execFileSync('tar', ['-xf', '-', '--no-same-owner', '-C', directory], { input: archive, timeout: 60000 });
|
|
50
|
+
}
|
|
51
|
+
function snapshotLive(selection) {
|
|
52
|
+
return readSnapshot(data, selection, { required: false });
|
|
53
|
+
}
|
|
54
|
+
function copyData(destination) {
|
|
55
|
+
fs.cpSync(data, destination, {
|
|
56
|
+
recursive: true,
|
|
57
|
+
filter: (file) => !['index', 'runtime', '.git'].includes(path.relative(data, file).split(path.sep)[0])
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
function validate(candidate, selection) {
|
|
61
|
+
for (const repo of selection.repositories) {
|
|
62
|
+
const cwd = path.join('/var/lib/agent-mcp/checkouts', ...repo.id.split('/'));
|
|
63
|
+
fs.mkdirSync(cwd, { recursive: true, mode: 0o700 });
|
|
64
|
+
createProfileMarker(path.join(candidate, 'projects', repo.id));
|
|
65
|
+
const store = new BrainStore(candidate, cwd);
|
|
66
|
+
try {
|
|
67
|
+
store.allKnowledge();
|
|
68
|
+
if (store.knowledgeErrors.length)
|
|
69
|
+
throw Error('Invalid staged knowledge: ' + JSON.stringify(store.knowledgeErrors));
|
|
70
|
+
getSkills(store);
|
|
71
|
+
const reviews = githubReviews(store);
|
|
72
|
+
if (reviews && reviews.repository !== repo.id)
|
|
73
|
+
throw Error('GitHub issue target does not match its repository');
|
|
74
|
+
listTodos(store);
|
|
75
|
+
if (store.todoErrors.length) throw Error('Invalid staged tasks: ' + JSON.stringify(store.todoErrors));
|
|
76
|
+
if (store.profile !== 'projects/' + repo.id || store.pool !== repo.pool)
|
|
77
|
+
throw Error('Staged profile mismatch');
|
|
78
|
+
} finally {
|
|
79
|
+
store.close();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function prepare(source, label) {
|
|
84
|
+
const selection = manifest(JSON.parse(fs.readFileSync(path.join(source, '.brain-deploy.json'), 'utf8')));
|
|
85
|
+
const incoming = readSnapshot(source, selection);
|
|
86
|
+
const before = digest(data);
|
|
87
|
+
let baseline;
|
|
88
|
+
const baselineFile = path.join(state, 'baseline.json');
|
|
89
|
+
if (fs.existsSync(baselineFile)) baseline = JSON.parse(fs.readFileSync(baselineFile, 'utf8')).files;
|
|
90
|
+
else {
|
|
91
|
+
const old = path.join(state, 'original-source');
|
|
92
|
+
if (!fs.existsSync(old)) extract(git(['rev-parse', 'HEAD']).trim(), old);
|
|
93
|
+
baseline = readSnapshot(old, selection, { required: false });
|
|
94
|
+
}
|
|
95
|
+
const live = snapshotLive(selection),
|
|
96
|
+
plan = mergeSnapshots(baseline, live, incoming);
|
|
97
|
+
if (plan.conflicts.length)
|
|
98
|
+
throw Error(
|
|
99
|
+
'Live Brain changes conflict with Git; reconcile before deployment: ' + plan.conflicts.join(', ')
|
|
100
|
+
);
|
|
101
|
+
const candidate = path.join(state, 'candidate');
|
|
102
|
+
fs.rmSync(candidate, { recursive: true, force: true });
|
|
103
|
+
copyData(candidate);
|
|
104
|
+
for (const [name, text] of Object.entries(plan.changes)) {
|
|
105
|
+
const file = path.join(candidate, ...name.split('/'));
|
|
106
|
+
if (text === null) fs.rmSync(file, { force: true });
|
|
107
|
+
else {
|
|
108
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
109
|
+
fs.writeFileSync(file, fileContents(text), { mode: 0o600 });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
validate(candidate, selection);
|
|
113
|
+
if (before !== digest(data)) throw Error('Live Brain changed while staging; retry deployment');
|
|
114
|
+
const prepared = { label, selection, before, files: incoming, changes: Object.keys(plan.changes) };
|
|
115
|
+
fs.writeFileSync(path.join(state, 'prepared.json'), JSON.stringify(prepared), { mode: 0o600 });
|
|
116
|
+
console.log(JSON.stringify({ selection, changes: prepared.changes.length }));
|
|
117
|
+
}
|
|
118
|
+
function activate() {
|
|
119
|
+
const prepared = JSON.parse(fs.readFileSync(path.join(state, 'prepared.json'), 'utf8'));
|
|
120
|
+
if (digest(data) !== prepared.before) throw Error('Live Brain changed after validation; retry deployment');
|
|
121
|
+
const candidate = path.join(state, 'candidate'),
|
|
122
|
+
backup = path.join(state, 'backups', Date.now().toString()),
|
|
123
|
+
baseline = path.join(state, 'baseline.json');
|
|
124
|
+
fs.mkdirSync(backup, { recursive: true, mode: 0o700 });
|
|
125
|
+
if (fs.existsSync(path.join(data, 'runtime')))
|
|
126
|
+
fs.cpSync(path.join(data, 'runtime'), path.join(candidate, 'runtime'), { recursive: true });
|
|
127
|
+
const previous = fs.existsSync(baseline) ? fs.readFileSync(baseline, 'utf8') : null;
|
|
128
|
+
fs.writeFileSync(
|
|
129
|
+
path.join(state, 'rollback.json'),
|
|
130
|
+
JSON.stringify({ backup, previous: previous ? JSON.parse(previous) : null }),
|
|
131
|
+
{ mode: 0o600 }
|
|
132
|
+
);
|
|
133
|
+
const nextBaseline = path.join(state, 'baseline.next.json');
|
|
134
|
+
fs.writeFileSync(nextBaseline, JSON.stringify({ label: prepared.label, files: prepared.files }), {
|
|
135
|
+
mode: 0o600
|
|
136
|
+
});
|
|
137
|
+
fs.renameSync(data, path.join(backup, 'data'));
|
|
138
|
+
try {
|
|
139
|
+
fs.renameSync(candidate, data);
|
|
140
|
+
fs.renameSync(nextBaseline, baseline);
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (fs.existsSync(data)) fs.renameSync(data, candidate);
|
|
143
|
+
fs.renameSync(path.join(backup, 'data'), data);
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
console.log('Configuration activated; rollback retained');
|
|
147
|
+
}
|
|
148
|
+
function rollback() {
|
|
149
|
+
const record = JSON.parse(fs.readFileSync(path.join(state, 'rollback.json'), 'utf8'));
|
|
150
|
+
if (!fs.existsSync(path.join(record.backup, 'data'))) throw Error('No rollback data');
|
|
151
|
+
fs.renameSync(data, path.join(record.backup, 'failed'));
|
|
152
|
+
fs.renameSync(path.join(record.backup, 'data'), data);
|
|
153
|
+
if (record.previous)
|
|
154
|
+
fs.writeFileSync(path.join(state, 'baseline.json'), JSON.stringify(record.previous), { mode: 0o600 });
|
|
155
|
+
else fs.rmSync(path.join(state, 'baseline.json'), { force: true });
|
|
156
|
+
console.log('Configuration rolled back');
|
|
157
|
+
}
|
|
158
|
+
try {
|
|
159
|
+
const [action, value] = process.argv.slice(2);
|
|
160
|
+
if (action === 'prepare') {
|
|
161
|
+
if (!/^[0-9a-f]{40}$/.test(value ?? '')) throw Error('Invalid Git revision');
|
|
162
|
+
git(['fetch', '--no-tags', 'origin', 'main']);
|
|
163
|
+
if (git(['rev-parse', 'refs/remotes/origin/main']).trim() !== value)
|
|
164
|
+
throw Error('Only the current main revision may deploy');
|
|
165
|
+
const source = path.join(state, 'source');
|
|
166
|
+
fs.rmSync(source, { recursive: true, force: true });
|
|
167
|
+
extract(value, source);
|
|
168
|
+
prepare(source, value);
|
|
169
|
+
} else if (action === 'prepare-local') prepare(path.resolve(value), 'local-preview');
|
|
170
|
+
else if (action === 'activate') activate();
|
|
171
|
+
else if (action === 'rollback') rollback();
|
|
172
|
+
else throw Error('Unknown deployment action');
|
|
173
|
+
} catch (error) {
|
|
174
|
+
console.error(error.message);
|
|
175
|
+
process.exitCode = 1;
|
|
176
|
+
}
|