@technomoron/agent-brain 0.1.3 → 0.1.6

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.
@@ -5,6 +5,7 @@ exports.serveRemote = serveRemote;
5
5
  const fs = require("node:fs");
6
6
  const path = require("node:path");
7
7
  const node_child_process_1 = require("node:child_process");
8
+ const zod_1 = require("zod");
8
9
  const node_crypto_1 = require("node:crypto");
9
10
  const apicore_server_1 = require("@technomoron/apicore-server");
10
11
  const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
@@ -97,26 +98,28 @@ async function createRemoteApi(configFile) {
97
98
  scope: [...client.permissions, ...new Set([...initial.clients.flatMap((c) => c.repos), ...initial.repositories.map((r) => r.id)]
98
99
  .filter((repo) => client.repos.some((pattern) => (0, repositories_1.coversPattern)(pattern, repo))).map((repo) => 'repo:' + repo))] });
99
100
  }
100
- const api = new apicore_server_1.ApiServer({ authApi: false, origins: [], devMode: false }).authStorage(new ConfigAuth()).setTokenStore(sessions);
101
+ const adapter = new ConfigAuth();
102
+ const api = new apicore_server_1.ApiServer({ authApi: false, origins: [], devMode: false }).authStorage(adapter).setTokenStore(sessions);
103
+ // Verify TOTP and persist its counter to prevent reuse.
104
+ function verifyMfa(value, code) {
105
+ const user = value;
106
+ if (!user.totpSecretEnv)
107
+ return true;
108
+ const file = path.join(initial.runtime, 'mfa.json');
109
+ const counters = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
110
+ const counter = (0, apicore_server_1.verifyTotp)(secret(user.totpSecretEnv), code, { after: counters[user.subject] });
111
+ if (counter === null)
112
+ return false;
113
+ counters[user.subject] = counter;
114
+ const temporary = file + '.' + (0, node_crypto_1.randomUUID)();
115
+ fs.writeFileSync(temporary, JSON.stringify(counters), { flag: 'wx', mode: 0o600 });
116
+ fs.renameSync(temporary, file);
117
+ return true;
118
+ }
101
119
  const login = new apicore_server_1.OAuthPasswordLogin(api, { issuer: initial.issuer,
102
120
  // Authorize the requested resource and OAuth scopes against current policy.
103
121
  allow: (subject, client, scopes, resources) => resources.length === 1 && resources[0] === initial.resource && (0, remote_policy_1.allowedGrant)(policy(), String(subject), client, scopes),
104
- // Verify TOTP and persist its counter to prevent reuse.
105
- verifySecondFactor: (value, code) => {
106
- const user = value;
107
- if (!user.totpSecretEnv)
108
- return true;
109
- const file = path.join(initial.runtime, 'mfa.json');
110
- const counters = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
111
- const counter = (0, apicore_server_1.verifyTotp)(secret(user.totpSecretEnv), code, { after: counters[user.subject] });
112
- if (counter === null)
113
- return false;
114
- counters[user.subject] = counter;
115
- const temporary = file + '.' + (0, node_crypto_1.randomUUID)();
116
- fs.writeFileSync(temporary, JSON.stringify(counters), { flag: 'wx', mode: 0o600 });
117
- fs.renameSync(temporary, file);
118
- return true;
119
- }
122
+ verifySecondFactor: verifyMfa
120
123
  }).register();
121
124
  const attempts = new Map();
122
125
  const provider = new apicore_server_1.OAuthAuthorizationServer(api, { issuer: initial.issuer, resources: [initial.resource],
@@ -137,6 +140,76 @@ async function createRemoteApi(configFile) {
137
140
  serviceAccounts: Object.fromEntries(initial.clients.filter((c) => c.kind === 'service').map((c) => [c.id, c.subject])),
138
141
  // Recheck the resource and current grants before issuing tokens.
139
142
  validateGrant: (grant) => grant.resources.length === 1 && grant.resources[0] === initial.resource && (0, remote_policy_1.allowedGrant)(policy(), grant.userId, grant.clientId, grant.scopes) }).register();
143
+ const consolePath = new URL(initial.issuer).pathname.replace(/\/$/, '') + '/console';
144
+ const challenges = new Map();
145
+ const consoleInput = zod_1.z.object({ client_id: zod_1.z.string(), redirect_uri: zod_1.z.string(), scope: zod_1.z.string(), code_challenge: zod_1.z.string().regex(/^[A-Za-z0-9_-]{43}$/), user: zod_1.z.string().max(256).optional(), password: zod_1.z.string().max(4096).optional(), challenge: zod_1.z.string().optional(), code: zod_1.z.string().max(32).optional() }).strict();
146
+ // Authenticate console users and issue a PKCE-bound authorization code.
147
+ api.fastify.post(consolePath + '/login', { bodyLimit: 16384 }, async (request, reply) => {
148
+ reply.header('Cache-Control', 'no-store');
149
+ if (request.headers.origin)
150
+ return reply.code(403).send({ error: 'access_denied' });
151
+ for (const [key, entry] of challenges)
152
+ if (entry.expires <= Date.now())
153
+ challenges.delete(key);
154
+ for (const [key, entry] of attempts)
155
+ if (entry.expires <= Date.now())
156
+ attempts.delete(key);
157
+ const rateKey = 'console:' + request.ip;
158
+ const rate = attempts.get(rateKey) ?? { count: 0, expires: Date.now() + 300000 };
159
+ if (!attempts.has(rateKey) && attempts.size >= 10000)
160
+ return reply.code(429).send({ error: 'slow_down' });
161
+ rate.count++;
162
+ attempts.set(rateKey, rate);
163
+ if (rate.count > 20)
164
+ return reply.code(429).send({ error: 'slow_down' });
165
+ const parsed = consoleInput.safeParse(request.body);
166
+ if (!parsed.success)
167
+ return reply.code(400).send({ error: 'invalid_request' });
168
+ const input = parsed.data, current = policy();
169
+ const client = current.clients.find(c => c.id === input.client_id && c.kind === 'public' && !c.secretEnv);
170
+ const scopes = input.scope.split(/\s+/).filter(Boolean);
171
+ if (!client || !client.redirectUris.includes(input.redirect_uri))
172
+ return reply.code(400).send({ error: 'invalid_client' });
173
+ let user;
174
+ if (input.challenge) {
175
+ const pending = challenges.get(input.challenge);
176
+ challenges.delete(input.challenge);
177
+ if (!pending || pending.client !== client.id || pending.redirect !== input.redirect_uri || pending.challenge !== input.code_challenge || JSON.stringify(pending.scope) !== JSON.stringify(scopes))
178
+ return reply.code(401).send({ error: 'invalid_grant' });
179
+ user = await adapter.getUser(pending.subject);
180
+ if (!user || !verifyMfa(user, input.code ?? ''))
181
+ return reply.code(401).send({ error: 'invalid_grant' });
182
+ }
183
+ else {
184
+ user = await adapter.getUser(input.user ?? '');
185
+ if (!user || user.kind !== 'human' || !await adapter.verifyPassword(input.password ?? '', adapter.getUserPasswordHash(user)))
186
+ return reply.code(401).send({ error: 'invalid_grant' });
187
+ if (user.totpSecretEnv) {
188
+ if (challenges.size >= 1000)
189
+ return reply.code(429).send({ error: 'slow_down' });
190
+ const challenge = (0, node_crypto_1.randomUUID)();
191
+ challenges.set(challenge, { subject: user.subject, client: client.id, redirect: input.redirect_uri, scope: scopes, challenge: input.code_challenge, expires: Date.now() + 180000 });
192
+ return reply.send({ mfa_required: true, challenge });
193
+ }
194
+ }
195
+ if (user.kind !== 'human' || !(0, remote_policy_1.allowedGrant)(current, user.subject, client.id, scopes))
196
+ return reply.code(403).send({ error: 'access_denied' });
197
+ const record = await credentials.createAuthCode({ clientId: client.id, userId: user.subject, redirectUri: input.redirect_uri, scope: scopes, codeChallenge: input.code_challenge, codeChallengeMethod: 'S256', expiresInSeconds: 60, metadata: { oauthIssuer: initial.issuer, oauthResources: [initial.resource] } });
198
+ return reply.send({ code: record.code });
199
+ });
200
+ // Revoke the session identified by its refresh token, including expired access tokens.
201
+ api.fastify.post(consolePath + '/logout', { bodyLimit: 16384 }, async (request, reply) => {
202
+ reply.header('Cache-Control', 'no-store');
203
+ if (request.headers.origin)
204
+ return reply.code(403).send({ error: 'access_denied' });
205
+ const parsed = zod_1.z.object({ refresh_token: zod_1.z.string().min(1).max(8192), client_id: zod_1.z.string() }).strict().safeParse(request.body);
206
+ if (!parsed.success)
207
+ return reply.code(400).send({ error: 'invalid_request' });
208
+ const stored = await sessions.get({ refreshToken: parsed.data.refresh_token }, { includeExpired: true });
209
+ if (stored?.clientId === parsed.data.client_id)
210
+ await sessions.delete({ refreshToken: parsed.data.refresh_token });
211
+ return reply.code(204).send();
212
+ });
140
213
  const resource = new URL(initial.resource);
141
214
  const endpoint = resource.pathname || '/';
142
215
  const metadataPath = '/.well-known/oauth-protected-resource' + (endpoint === '/' ? '' : endpoint);
@@ -169,7 +242,10 @@ async function createRemoteApi(configFile) {
169
242
  let store;
170
243
  let server;
171
244
  if (repository === undefined) {
172
- server = (0, repository_discovery_1.createRepositoryDiscoveryServer)(catalog);
245
+ server = (0, repository_discovery_1.createRepositoryDiscoveryServer)(catalog, () => {
246
+ const visible = new Set(catalog().map((repo) => repo.id));
247
+ return policy().repositories.filter((repo) => visible.has(repo.id)).map((repo) => repo.configRoot);
248
+ });
173
249
  }
174
250
  else {
175
251
  const permissions = (0, remote_policy_1.repositoryPermissions)(current, claims.sub, claims.client_id, claims.scope.split(' '), repository);
@@ -219,10 +295,23 @@ async function createRemoteApi(configFile) {
219
295
  child.stdin?.end(JSON.stringify({ ...initial.gitSync, dataRoot: initial.dataRoot, scopes, reviews: permissions.has('review'), message }));
220
296
  });
221
297
  }, repository, group: repo.group, repositories: catalog,
298
+ // Authorize both ends of cross-repository issue relationships.
299
+ allowIssueRepository: (target, write) => {
300
+ const granted = (0, remote_policy_1.repositoryPermissions)(policy(), claims.sub, claims.client_id, claims.scope.split(' '), target);
301
+ return granted.has('read') && (!write || (granted.has('write') && granted.has('review')));
302
+ },
303
+ // Require an explicit organisation-wide grant before examining or modifying shared definitions.
304
+ allowIssueOrganisation: (owner) => (0, remote_policy_1.allowedGrant)(policy(), claims.sub, claims.client_id, ['read', 'write', 'review', 'repo:' + owner + '/*']) &&
305
+ claims.scope.split(' ').some(scope => scope === 'repo:*' || scope === 'repo:' + owner + '/*') &&
306
+ ['read', 'write', 'review'].every(scope => claims.scope.split(' ').includes(scope)),
222
307
  // Check whether this request may change the target storage scope.
223
308
  allowScopeWrite: (scope) => scope === 'project' || (scope === 'default' ? !initial.dataRoot : canWriteScope(scope)),
224
309
  // Check whether this token permits the requested tool operation.
225
- allowTool: (name) => { const required = (0, remote_policy_1.toolPermission)(name); return required !== null && permissions.has(required); }
310
+ allowTool: (name) => {
311
+ const required = (0, remote_policy_1.toolPermission)(name);
312
+ return required !== null && permissions.has(required) &&
313
+ (!name.startsWith('issue_') || required === 'read' || permissions.has('review'));
314
+ }
226
315
  });
227
316
  }
228
317
  const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
@@ -10,6 +10,9 @@ const version_1 = require("../version");
10
10
  const config_1 = require("./config");
11
11
  const remote_policy_1 = require("./remote-policy");
12
12
  const repositories_1 = require("./repositories");
13
+ const zod_1 = require("zod");
14
+ const built_in_skills_1 = require("./built-in-skills");
15
+ const skills_1 = require("./skills");
13
16
  // List local projects and their OS-user permissions.
14
17
  function localRepositoryCatalog(configRoot) {
15
18
  return (0, config_1.listBrainProjects)(configRoot).map((project) => ({
@@ -71,9 +74,40 @@ function registerRepositoryTools(server, catalog, allow = () => true) {
71
74
  });
72
75
  }
73
76
  }
74
- // Create an MCP server limited to repository discovery.
75
- function createRepositoryDiscoveryServer(catalog) {
77
+ // Create an MCP server with repository discovery and authorized shared skills.
78
+ function createRepositoryDiscoveryServer(catalog, globalRoots = () => []) {
76
79
  const server = new mcp_js_1.McpServer({ name: 'agent-brain', version: (0, version_1.packageVersion)() });
77
80
  registerRepositoryTools(server, catalog);
81
+ // Merge only global overrides from authorized roots; conflicting roots require selection.
82
+ const skills = () => {
83
+ const bundled = Object.entries((0, built_in_skills_1.readBuiltInSkills)()).map(([name, skill]) => ({
84
+ name, ...skill, tags: [], scope: 'global', source: `builtin:${name}`
85
+ }));
86
+ const resolved = new Map(bundled.map((skill) => [skill.name, skill]));
87
+ const overrides = new Map();
88
+ for (const root of new Set(globalRoots())) {
89
+ for (const skill of (0, skills_1.getGlobalSkills)(root).filter((skill) => !skill.source.startsWith('builtin:'))) {
90
+ const previous = overrides.get(skill.name);
91
+ if (previous && (previous.content !== skill.content || previous.description !== skill.description)) {
92
+ throw new Error(`Conflicting global skill ${skill.name}; select a repository`);
93
+ }
94
+ overrides.set(skill.name, skill);
95
+ resolved.set(skill.name, { ...skill, scope: 'global' });
96
+ }
97
+ }
98
+ return [...resolved.values()];
99
+ };
100
+ const annotations = { readOnlyHint: true, destructiveHint: false, openWorldHint: false };
101
+ server.registerTool('list_skills', {
102
+ description: 'List bundled and authorized global skills without repository selection.', inputSchema: {}, annotations
103
+ }, async () => ({ content: [{ type: 'text', text: JSON.stringify(skills().map(({ content: _content, ...skill }) => skill)) }] }));
104
+ server.registerTool('get_skill', {
105
+ description: 'Load a bundled or authorized global skill without repository selection.', inputSchema: { name: zod_1.z.string().max(100) }, annotations
106
+ }, async ({ name }) => {
107
+ const skill = skills().find((item) => item.name === name);
108
+ return skill
109
+ ? { content: [{ type: 'text', text: JSON.stringify(skill) }] }
110
+ : { isError: true, content: [{ type: 'text', text: 'Skill not found' }] };
111
+ });
78
112
  return server;
79
113
  }
@@ -17,21 +17,21 @@ const version_1 = require("../version");
17
17
  const store_1 = require("./store");
18
18
  const consolidation_1 = require("./consolidation");
19
19
  const skills_1 = require("./skills");
20
- const todos_1 = require("./todos");
21
- const connectors_1 = require("./connectors");
22
20
  const git_1 = require("./git");
23
- const github_reviews_1 = require("./github-reviews");
21
+ const github_client_1 = require("./github-client");
22
+ const issue_tools_1 = require("./issue-tools");
24
23
  const windows_pipe_1 = require("./windows-pipe");
25
24
  const repository_discovery_1 = require("./repository-discovery");
26
25
  var config_1 = require("./config");
27
26
  Object.defineProperty(exports, "defaultSocketPath", { enumerable: true, get: function () { return config_1.defaultSocketPath; } });
28
27
  // Register Brain tools with backend selection and scope permissions.
29
28
  function createBrainServer(store, options = {}) {
30
- const github = (0, github_reviews_1.githubReviews)(store);
29
+ const github = (0, github_client_1.githubIssueConfig)(store, options.repository);
31
30
  if (github && options.repository && github.repository !== options.repository)
32
- throw new Error('Review backend repository does not match the authenticated repository');
31
+ throw new Error('Issue backend repository does not match the authenticated repository');
33
32
  const server = new mcp_js_1.McpServer({ name: 'agent-brain', version: (0, version_1.packageVersion)() });
34
33
  (0, repository_discovery_1.registerRepositoryTools)(server, options.repositories ?? (() => (0, repository_discovery_1.localRepositoryCatalog)(store.configRoot)), options.allowTool);
34
+ (0, issue_tools_1.registerIssueTools)(server, store, options);
35
35
  // Register a validated tool with permission checks and broken-file diagnostics.
36
36
  function tool(name, description, shape, readOnly, handler) {
37
37
  if (options.allowTool && !options.allowTool(name))
@@ -43,14 +43,14 @@ function createBrainServer(store, options = {}) {
43
43
  try {
44
44
  if (!readOnly && options.allowScopeWrite) {
45
45
  const data = input;
46
- const scopes = [data.scope, ...((['amend_knowledge', 'promote', 'deprecate_knowledge'].includes(name) || (!github && ['resolve_review', 'review_update'].includes(name))) && data.id ? [store.get(data.id).scope] : [])].filter(Boolean);
46
+ const scopes = [data.scope, ...(['amend_knowledge', 'promote', 'deprecate_knowledge'].includes(name) && data.id ? [store.get(data.id).scope] : [])].filter(Boolean);
47
47
  if (scopes.some((scope) => !options.allowScopeWrite(scope)))
48
48
  throw new Error('Write access to the entire target scope is required');
49
49
  }
50
- if (!readOnly && options.allowTool && !options.allowTool('review_update')) {
50
+ if (!readOnly) {
51
51
  const data = input;
52
52
  if (data.type === 'review' || (data.id && ['amend_knowledge', 'promote', 'deprecate_knowledge'].includes(name) && store.get(data.id).type === 'review')) {
53
- throw new Error('Review permission is required to change findings');
53
+ throw new Error('Review tracking uses issue_* tools; historical local findings are read-only');
54
54
  }
55
55
  }
56
56
  const result = await handler(zod_1.z.object(shape).strict().parse(input));
@@ -63,7 +63,7 @@ function createBrainServer(store, options = {}) {
63
63
  }
64
64
  const id = zod_1.z.string().min(1).max(200);
65
65
  const revision = zod_1.z.string().regex(/^[a-f0-9]{64}$/);
66
- tool('brain_status', 'Show the active project and available scopes. Global is server-wide; pool is shared only by members of the active pool.', {}, true, () => ({ profile: store.profile, pool: store.pool, scopes: store.scopes.map((entry) => entry.scope), reviewBackend: github ? 'github' : 'internal', repository: github?.repository ?? options.repository, group: options.group }));
66
+ tool('brain_status', 'Show the active project and available scopes. Global is server-wide; pool is shared only by members of the active pool.', {}, true, () => ({ profile: store.profile, pool: store.pool, scopes: store.scopes.map((entry) => entry.scope), issueBackend: github ? 'github' : null, repository: github?.repository ?? options.repository, group: options.group }));
67
67
  tool('sync_status', 'Preview Git state and the canonical files eligible for saving. Runtime files, indexes, credentials, and native agent state are excluded.', {}, true, () => (0, git_1.gitPreview)(store));
68
68
  for (const name of ['brain_sync', 'brain_flush', 'sync', 'flush']) {
69
69
  if (options.allowTool && !options.allowTool(name))
@@ -94,8 +94,7 @@ function createBrainServer(store, options = {}) {
94
94
  tool('knowledge_history', 'Look up archived knowledge and replacement IDs. Pass an old id to retrieve its exact original file text. Excluded from normal retrieval.', consolidation_1.historyOptions.shape, true, (input) => (0, consolidation_1.knowledgeHistory)(store, input));
95
95
  tool('archive_knowledge', 'After authorized consolidation and verified coverage, archive exact source files and replacement references before removing the files. Same scope and authority only; revisions are required for sources and replacements. Identical retries finish interrupted deletion.', consolidation_1.archiveInput.shape, false, (input) => (0, consolidation_1.archiveKnowledge)(store, input));
96
96
  tool('get_knowledge', 'Read a complete knowledge item and its current revision.', { id }, true, ({ id }) => store.get(id));
97
- tool('remember', 'Persist durable knowledge when authorized by the user. Choose scope and a singular type; the server stores it in the matching directory (for example constraint in constraints/, preference in preferences/). Explicit user instructions have authority=user; deductions remain inferred observations. Global writes require explicit global intent. Use todo tools for tasks; skills and templates are separate files.', store_1.knowledgeInput.shape, false, (input) => { if (github && input.type === 'review')
98
- throw new Error('Use review_create for the configured GitHub review backend'); return store.remember(input); });
97
+ tool('remember', 'Persist durable knowledge when authorized by the user. Choose scope and a singular type; the server stores it in the matching directory (for example constraint in constraints/, preference in preferences/). Explicit user instructions have authority=user; deductions remain inferred observations. Global writes require explicit global intent. Use issue_* tools and the code-review skill for findings; skills and templates are separate files.', store_1.knowledgeInput.shape, false, (input) => store.remember(input));
99
98
  tool('amend_knowledge', 'Revise an active item in place using its last-read revision, keeping its id, file name, scope, type, authority, and history. Use this to correct or extend existing knowledge instead of writing a near-duplicate. Scope, type, authority, and review severity cannot be changed this way.', {
100
99
  id, revision, changes: store_1.knowledgeChanges
101
100
  }, false, ({ id, revision, changes }) => store.amend(id, revision, changes));
@@ -105,60 +104,9 @@ function createBrainServer(store, options = {}) {
105
104
  tool('deprecate_knowledge', 'Deprecate outdated knowledge without deleting its history.', { id, revision, reason: zod_1.z.string().max(2000).optional() }, false, ({ id, revision, reason }) => store.deprecate(id, revision, reason));
106
105
  tool('list_skills', 'List available skills and descriptions. Local skills override global skills with the same name.', {}, true, () => (0, skills_1.listSkills)(store));
107
106
  tool('get_skill', 'Load a full skill only when it applies to the current task.', { name: zod_1.z.string().max(100) }, true, ({ name }) => (0, skills_1.getSkill)(store, name));
108
- tool('review_context', 'Retrieve constraints, decisions, prior review findings, and path-specific knowledge for a code review.', {
107
+ tool('review_context', 'Retrieve review constraints, decisions and path-specific knowledge. Use issue_list/issue_search and issue_comments for current findings and discussion; load code-review for reporting and resolution instructions.', {
109
108
  task: zod_1.z.string().max(10000), files: zod_1.z.array(zod_1.z.string()).max(100).optional()
110
109
  }, false, ({ task, files }) => store.context(`review constraint decision ${task}`, files));
111
- tool('review_get', 'Read a finding from the configured internal or per-repository GitHub backend.', { id }, true, ({ id }) => github ? github.get(id) : store.get(id));
112
- tool('review_create', 'Record an authorized review finding in the configured backend. GitHub requires enabled writes and explicit confirmation; key deduplicates retries.', github_reviews_1.reviewInput.shape, false, (input) => github ? github.create(input) : store.remember({ scope: store.profile ? 'project' : 'default', type: 'review', authority: 'inferred', title: input.title, content: input.content, severity: input.severity, applies_to: input.applies_to }));
113
- tool('review_update', 'Revise a finding using its last-read revision. GitHub preserves text outside its managed block.', {
114
- id, revision, confirmed: zod_1.z.literal(true), changes: zod_1.z.object({ title: zod_1.z.string().min(1).max(250).optional(), content: zod_1.z.string().min(1).max(40000).optional(), severity: store_1.severitySchema.optional(), applies_to: zod_1.z.array(zod_1.z.string().max(500)).max(100).optional() }).strict()
115
- }, false, ({ id, revision, changes }) => {
116
- if (github)
117
- return github.update(id, revision, changes);
118
- if (changes.severity)
119
- throw new Error('Internal finding severity changes require the existing review workflow');
120
- return store.amend(id, revision, changes);
121
- });
122
- tool('review_list', 'List open findings from the configured backend. GitHub issues belong to this repository; PRs are excluded.', {
123
- severity: zod_1.z.array(store_1.severitySchema).optional(), state: zod_1.z.array(store_1.reviewStateSchema).optional()
124
- }, true, async ({ severity, state }) => {
125
- if (github)
126
- return (await github.list(state ? 'all' : 'open')).filter((item) => (!severity || severity.includes(item.severity)) && (!state || state.includes(item.state)));
127
- return store.reviews({ severity, state }).map((item) => ({ finding: item.finding, severity: item.severity, state: item.state ?? 'open', title: item.title, applies_to: item.applies_to, id: item.id, revision: item.revision }));
128
- });
129
- tool('review_history', 'Recall closed findings from the configured backend, with pagination.', {
130
- scope: store_1.scopeSchema.optional(), query: zod_1.z.string().max(1000).optional(), state: zod_1.z.enum(['fixed', 'wontfix']).optional(),
131
- offset: zod_1.z.number().int().min(0).optional(), limit: zod_1.z.number().int().min(1).max(1000).optional()
132
- }, true, async (options) => {
133
- if (!github)
134
- return store.reviewHistory(options);
135
- const items = (await github.list('closed')).filter((item) => (!options.state || item.state === options.state) && (!options.query || JSON.stringify(item).toLowerCase().includes(options.query.toLowerCase())));
136
- return { total: items.length, items: items.slice(options.offset ?? 0, (options.offset ?? 0) + (options.limit ?? 50)) };
137
- });
138
- tool('review_archive', 'Compact internal closed finding files. GitHub retains its own issue history.', { scope: store_1.scopeSchema }, false, ({ scope }) => { if (github)
139
- throw new Error('GitHub owns review history; no internal archive is needed'); return store.archiveReviews(scope); });
140
- tool('resolve_review', 'Close an authorized fix or explicitly dropped finding in the configured backend. GitHub writes must be enabled. Deferred findings stay open.', {
141
- id, revision, state: zod_1.z.enum(['fixed', 'wontfix']), reason: zod_1.z.string().min(1).max(2000).optional()
142
- }, false, ({ id, revision, state, reason }) => github ? github.resolve(id, revision, state, reason ?? state) : store.resolveReview(id, revision, state, reason));
143
- tool('todo_list', 'List structured tasks in the active scopes.', { status: todos_1.todoInput.shape.status.optional() }, true, ({ status }) => (0, todos_1.listTodos)(store).filter((item) => !status || item.status === status));
144
- tool('todo_get', 'Read a task and its revision.', { id }, true, ({ id }) => (0, todos_1.getTodo)(store, id));
145
- tool('todo_add', 'Create a local task. Reimporting the same external task returns the existing task.', todos_1.todoInput.shape, false, (input) => (0, todos_1.addTodo)(store, input));
146
- tool('todo_update', 'Update a local task using its last-read revision. Does not change remote tasks.', { id, revision, changes: todos_1.todoChanges }, false, ({ id, revision, changes }) => (0, todos_1.updateTodo)(store, id, revision, changes));
147
- tool('todo_complete', 'Mark a local task done. Does not change remote tasks.', { id, revision }, false, ({ id, revision }) => (0, todos_1.updateTodo)(store, id, revision, { status: 'done' }));
148
- for (const name of ['todo_import', 'todo_sync']) {
149
- if (options.allowTool && !options.allowTool(name))
150
- continue;
151
- server.registerTool(name, { description: 'Import tasks from a configured connector. Merge remote changes only when they do not conflict with local edits; report conflicting task IDs. Remote tasks are never modified.',
152
- inputSchema: { source: zod_1.z.string().max(100), scope: store_1.scopeSchema }, annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
153
- }, async ({ source, scope }) => {
154
- try {
155
- return { content: [{ type: 'text', text: JSON.stringify(await (0, connectors_1.syncConnector)(store, source, scope)) }] };
156
- }
157
- catch (error) {
158
- return { isError: true, content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }] };
159
- }
160
- });
161
- }
162
110
  return server;
163
111
  }
164
112
  // Require a private socket directory owned by the current user.
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getSkills = getSkills;
4
+ exports.getGlobalSkills = getGlobalSkills;
4
5
  exports.listSkills = listSkills;
5
6
  exports.getSkill = getSkill;
6
7
  const path = require("node:path");
@@ -16,12 +17,12 @@ const metadata = zod_1.z.object({
16
17
  extends: zod_1.z.string().regex(/^(?:global|pool):[a-zA-Z0-9][a-zA-Z0-9._-]*$/).optional()
17
18
  });
18
19
  // Resolve bundled workflows and scope-specific skill overrides.
19
- function getSkills(store) {
20
- const profile = store.profile ?? 'default';
21
- const directory = store.scopeDirectory(store.profile ? 'project' : 'default');
20
+ function getSkills(store, globalOnly = false) {
21
+ const profile = globalOnly ? 'default' : store.profile ?? 'default';
22
+ const directory = globalOnly ? path.join(store.configRoot, 'default') : store.scopeDirectory(store.profile ? 'project' : 'default');
22
23
  const env = (0, templates_1.createNunjucksEnv)(store.configRoot);
23
- const context = (0, templates_1.buildRenderContext)(store.projectRoot, directory, store.configRoot, (0, manifest_1.normalizeManifest)((0, manifest_1.loadManifest)(store.configRoot, directory, profile), profile), env);
24
- const skillEnv = (0, templates_1.createSkillNunjucksEnv)(store.configRoot, directory, undefined, store.pool);
24
+ const context = (0, templates_1.buildRenderContext)(globalOnly ? store.configRoot : store.projectRoot, directory, store.configRoot, (0, manifest_1.normalizeManifest)((0, manifest_1.loadManifest)(store.configRoot, directory, profile), profile), env);
25
+ const skillEnv = (0, templates_1.createSkillNunjucksEnv)(store.configRoot, directory, undefined, globalOnly ? undefined : store.pool);
25
26
  const skills = new Map();
26
27
  const parentSkills = new Map();
27
28
  for (const [name, packaged] of Object.entries((0, built_in_skills_1.readBuiltInSkills)())) {
@@ -30,6 +31,8 @@ function getSkills(store) {
30
31
  parentSkills.set(`global:${name}`, skill);
31
32
  }
32
33
  for (const { scope, directory } of store.scopes) {
34
+ if (globalOnly && scope !== 'global')
35
+ continue;
33
36
  for (const file of store.files(path.join(directory, 'skills')).filter((file) => path.basename(file) === 'SKILL.md')) {
34
37
  const text = skillEnv.render(path.relative(store.configRoot, file), context);
35
38
  const document = (0, store_1.readMarkdown)(text);
@@ -52,6 +55,16 @@ function getSkills(store) {
52
55
  }
53
56
  return [...skills.values()];
54
57
  }
58
+ // Resolve shared skills without applying default, pool or repository overrides.
59
+ function getGlobalSkills(configRoot) {
60
+ const store = new store_1.BrainStore(configRoot, configRoot);
61
+ try {
62
+ return getSkills(store, true);
63
+ }
64
+ finally {
65
+ store.close();
66
+ }
67
+ }
55
68
  // List resolved skill metadata without loading content into the response.
56
69
  function listSkills(store) {
57
70
  return getSkills(store).map(({ content: _content, ...skill }) => skill);
@@ -1,17 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.todoChanges = exports.todoInput = void 0;
4
3
  exports.listTodos = listTodos;
5
4
  exports.getTodo = getTodo;
6
- exports.addTodo = addTodo;
7
- exports.updateTodo = updateTodo;
8
- exports.importTodos = importTodos;
9
5
  const path = require("node:path");
10
6
  const node_crypto_1 = require("node:crypto");
11
- const yaml_1 = require("yaml");
12
7
  const zod_1 = require("zod");
13
8
  const store_1 = require("./store");
14
- exports.todoInput = zod_1.z.object({
9
+ const todoInput = zod_1.z.object({
15
10
  scope: store_1.scopeSchema,
16
11
  title: zod_1.z.string().trim().min(1).max(300),
17
12
  description: zod_1.z.string().trim().max(200000).default(''),
@@ -23,8 +18,8 @@ exports.todoInput = zod_1.z.object({
23
18
  notes: zod_1.z.string().default(''),
24
19
  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
20
  }).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() });
21
+ const remoteTask = todoInput.pick({ title: true, description: true, status: true, labels: true, due: true }).strip();
22
+ const todoMetadata = todoInput.omit({ description: true }).extend({ id: zod_1.z.uuid(), created: zod_1.z.string(), updated: zod_1.z.string(), remote: remoteTask.optional() });
28
23
  // Read scoped tasks and report malformed or duplicate records.
29
24
  function listTodos(store) {
30
25
  store.todoErrors.length = 0;
@@ -71,94 +66,3 @@ function getTodo(store, id) {
71
66
  throw new Error(`Todo not found: ${id}`);
72
67
  return todo;
73
68
  }
74
- // Write task metadata and description and return its new revision.
75
- function writeTodo(store, todo) {
76
- const { description, ...metadata } = todo;
77
- const text = `---\n${(0, yaml_1.stringify)(metadata)}---\n\n${description}\n`;
78
- store.atomicWrite(path.join(store.scopeDirectory(todo.scope), 'todo', `${todo.id}.md`), text);
79
- return { ...todo, revision: (0, node_crypto_1.createHash)('sha256').update(text).digest('hex') };
80
- }
81
- // Create a repository task or reuse its existing external identity.
82
- function addTodo(store, input) {
83
- const value = exports.todoInput.parse(input);
84
- if (value.scope === 'pool' || (store.pool && value.scope !== 'project'))
85
- throw new Error('Tasks must belong to an individual repository');
86
- return store.writeLocked(() => {
87
- if (value.source) {
88
- const existing = listTodos(store).find((item) => item.scope === value.scope && item.source?.type === value.source?.type && item.source?.external_id === value.source?.external_id);
89
- if (existing)
90
- return existing;
91
- if (store.todoErrors.length)
92
- throw new Error('Cannot deduplicate an external task while todo files are broken. List tasks and correct the reported files first.');
93
- }
94
- const now = new Date().toISOString();
95
- return writeTodo(store, { ...value, id: (0, node_crypto_1.randomUUID)(), created: now, updated: now });
96
- });
97
- }
98
- // Spelled out rather than todoInput.omit(...).partial(): .partial() keeps .default(), so
99
- // updating one field would reset description, priority, labels, and notes to their defaults.
100
- exports.todoChanges = zod_1.z.object({
101
- title: zod_1.z.string().trim().min(1).max(300).optional(),
102
- description: zod_1.z.string().trim().max(200000).optional(),
103
- status: zod_1.z.enum(['todo', 'doing', 'blocked', 'done', 'cancelled']).optional(),
104
- priority: zod_1.z.enum(['low', 'medium', 'high', 'critical']).optional(),
105
- owner: zod_1.z.string().optional(),
106
- due: zod_1.z.iso.date().optional(),
107
- labels: zod_1.z.array(zod_1.z.string()).optional(),
108
- notes: zod_1.z.string().optional()
109
- }).strict();
110
- // Apply validated task changes only to the expected revision.
111
- function updateTodo(store, id, revision, changes) {
112
- const parsed = exports.todoChanges.parse(changes);
113
- return store.writeLocked(() => {
114
- const todo = getTodo(store, id);
115
- if (todo.revision !== revision)
116
- throw new Error('Todo changed; read the current revision before updating.');
117
- const { revision: _revision, ...value } = todo;
118
- return writeTodo(store, { ...value, ...parsed, updated: new Date().toISOString() });
119
- });
120
- }
121
- // Merge external task changes while retaining local edits and reporting conflicts.
122
- function importTodos(store, input) {
123
- const incoming = input.map((item) => exports.todoInput.parse(item));
124
- return store.writeLocked(() => {
125
- const result = { imported: [], updated: [], conflicts: [] };
126
- const existing = listTodos(store);
127
- if (store.todoErrors.length)
128
- throw new Error('Cannot import tasks while todo files are broken. List tasks and correct the reported files first.');
129
- for (const item of incoming) {
130
- if (!item.source)
131
- throw new Error('Imported tasks require an external source');
132
- const prior = existing.find((todo) => todo.scope === item.scope && todo.source?.type === item.source.type && todo.source?.external_id === item.source.external_id);
133
- const remote = remoteTask.parse(item);
134
- const now = new Date().toISOString();
135
- if (!prior) {
136
- const task = writeTodo(store, { ...item, remote, id: (0, node_crypto_1.randomUUID)(), created: now, updated: now });
137
- existing.push(task);
138
- result.imported.push(task.id);
139
- continue;
140
- }
141
- if (JSON.stringify(prior.remote) === JSON.stringify(remote))
142
- continue;
143
- const changes = {};
144
- let conflicted = !prior.remote;
145
- for (const key of ['title', 'description', 'status', 'labels', 'due']) {
146
- const current = JSON.stringify(prior[key]);
147
- const base = JSON.stringify(prior.remote?.[key]);
148
- const next = JSON.stringify(remote[key]);
149
- if (current !== base && next !== base && current !== next)
150
- conflicted = true;
151
- if (current === base)
152
- changes[key] = remote[key];
153
- }
154
- if (conflicted) {
155
- result.conflicts.push(prior.id);
156
- continue;
157
- }
158
- const { revision: _revision, ...metadata } = prior;
159
- writeTodo(store, { ...metadata, ...changes, remote, updated: now });
160
- result.updated.push(prior.id);
161
- }
162
- return result;
163
- });
164
- }
@@ -1,3 +1,3 @@
1
1
  #!/bin/sh
2
2
  # Installed root-owned and referenced by the restricted GitHub Actions SSH key.
3
- exec sudo -n /usr/local/bin/node /opt/agent-mcp/current/node_modules/@technomoron/agent-brain/ops/config-deploy-root.cjs "${SSH_ORIGINAL_COMMAND:-}"
3
+ exec sudo -n /usr/local/bin/node /usr/local/agent-brain/current/node_modules/@technomoron/agent-brain/ops/config-deploy-root.cjs "${SSH_ORIGINAL_COMMAND:-}"
@@ -3,10 +3,11 @@
3
3
  const fs = require('node:fs'),
4
4
  { execFileSync } = require('node:child_process');
5
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';
6
+ const layout = require('./layout.cjs');
7
+ const worker = layout.worker;
8
+ const file = layout.configFile,
9
+ lock = require('node:path').join(layout.state, 'catalog.lock'),
10
+ maintenance = layout.maintenance;
10
11
  let interrupted = false;
11
12
  // Let deployment checkpoints detect termination requests and restore service availability.
12
13
  for (const signal of ['SIGTERM', 'SIGHUP', 'SIGINT'])
@@ -18,7 +19,8 @@ function run(action, value) {
18
19
  return execFileSync(
19
20
  '/usr/sbin/runuser',
20
21
  ['-u', 'agent-mcp', '--', '/usr/local/bin/node', worker, action, ...(value ? [value] : [])],
21
- { encoding: 'utf8', timeout: 120000, maxBuffer: 1024 * 1024 }
22
+ { encoding: 'utf8', timeout: 120000, maxBuffer: 1024 * 1024,
23
+ env: { ...process.env, GIT_SSH_COMMAND: '/usr/bin/ssh -F ' + layout.sshConfig } }
22
24
  );
23
25
  }
24
26
  // Control the Brain service through systemd.
@@ -77,7 +79,7 @@ async function healthy(config) {
77
79
  id: repo.id,
78
80
  group: repo.pool,
79
81
  configRoot: config.dataRoot,
80
- cwd: '/var/lib/agent-mcp/checkouts/' + repo.id
82
+ cwd: layout.checkouts + '/' + repo.id
81
83
  }))
82
84
  };
83
85
  fs.copyFileSync(file, file + '.before-config-push-' + Date.now());
@@ -6,14 +6,15 @@ const fs = require('node:fs'),
6
6
  { execFileSync } = require('node:child_process');
7
7
  const { manifest, readSnapshot, mergeSnapshots, fileContents } = require('./config-policy.cjs');
8
8
  const { BrainStore } = require('../dist/brain/store');
9
- const { githubReviews } = require('../dist/brain/github-reviews');
9
+ const { githubIssueConfig } = require('../dist/brain/github-client');
10
10
  const { listTodos } = require('../dist/brain/todos');
11
11
  const { getSkills } = require('../dist/brain/skills');
12
12
  const { createProfileMarker } = require('@technomoron/agent-run/dist/manifest');
13
- const config = require('../dist/brain/remote-policy').readRemoteConfig('/etc/agent-mcp/remote.jsonc');
13
+ const layout = require('./layout.cjs');
14
+ const config = require('../dist/brain/remote-policy').readRemoteConfig(layout.configFile);
14
15
  const data = config.dataRoot,
15
- state = '/var/lib/agent-mcp/config-deploy',
16
- catalog = '/var/lib/agent-mcp/catalogs/agent-brain-config';
16
+ state = config.gitSync?.state ?? layout.state,
17
+ catalog = config.gitSync?.catalog ?? layout.catalog;
17
18
  fs.mkdirSync(state, { recursive: true, mode: 0o700 });
18
19
  // Run a Git command against the private configuration catalog.
19
20
  function git(args) {
@@ -63,7 +64,7 @@ function copyData(destination) {
63
64
  // Check staged knowledge, skills, tasks and per-repository registrations.
64
65
  function validate(candidate, selection) {
65
66
  for (const repo of selection.repositories) {
66
- const cwd = path.join('/var/lib/agent-mcp/checkouts', ...repo.id.split('/'));
67
+ const cwd = path.join(layout.checkouts, ...repo.id.split('/'));
67
68
  fs.mkdirSync(cwd, { recursive: true, mode: 0o700 });
68
69
  createProfileMarker(path.join(candidate, 'projects', repo.id));
69
70
  const store = new BrainStore(candidate, cwd);
@@ -72,7 +73,7 @@ function validate(candidate, selection) {
72
73
  if (store.knowledgeErrors.length)
73
74
  throw Error('Invalid staged knowledge: ' + JSON.stringify(store.knowledgeErrors));
74
75
  getSkills(store);
75
- const reviews = githubReviews(store);
76
+ const reviews = githubIssueConfig(store);
76
77
  if (reviews && reviews.repository !== repo.id)
77
78
  throw Error('GitHub issue target does not match its repository');
78
79
  listTodos(store);