@technomoron/agent-brain 0.1.4 → 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);
@@ -12,6 +12,7 @@ const remote_policy_1 = require("./remote-policy");
12
12
  const repositories_1 = require("./repositories");
13
13
  const zod_1 = require("zod");
14
14
  const built_in_skills_1 = require("./built-in-skills");
15
+ const skills_1 = require("./skills");
15
16
  // List local projects and their OS-user permissions.
16
17
  function localRepositoryCatalog(configRoot) {
17
18
  return (0, config_1.listBrainProjects)(configRoot).map((project) => ({
@@ -73,20 +74,35 @@ function registerRepositoryTools(server, catalog, allow = () => true) {
73
74
  });
74
75
  }
75
76
  }
76
- // Create an MCP server with repository discovery and public bundled skills.
77
- function createRepositoryDiscoveryServer(catalog) {
77
+ // Create an MCP server with repository discovery and authorized shared skills.
78
+ function createRepositoryDiscoveryServer(catalog, globalRoots = () => []) {
78
79
  const server = new mcp_js_1.McpServer({ name: 'agent-brain', version: (0, version_1.packageVersion)() });
79
80
  registerRepositoryTools(server, catalog);
80
- // Read only packaged skills, without loading configuration or private overrides.
81
- const skills = () => Object.entries((0, built_in_skills_1.readBuiltInSkills)()).map(([name, skill]) => ({
82
- name, ...skill, tags: [], scope: 'global', source: `builtin:${name}`
83
- }));
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
+ };
84
100
  const annotations = { readOnlyHint: true, destructiveHint: false, openWorldHint: false };
85
101
  server.registerTool('list_skills', {
86
- description: 'List bundled skills available without repository selection.', inputSchema: {}, annotations
102
+ description: 'List bundled and authorized global skills without repository selection.', inputSchema: {}, annotations
87
103
  }, async () => ({ content: [{ type: 'text', text: JSON.stringify(skills().map(({ content: _content, ...skill }) => skill)) }] }));
88
104
  server.registerTool('get_skill', {
89
- description: 'Load a bundled skill by name without repository selection.', inputSchema: { name: zod_1.z.string().max(100) }, annotations
105
+ description: 'Load a bundled or authorized global skill without repository selection.', inputSchema: { name: zod_1.z.string().max(100) }, annotations
90
106
  }, async ({ name }) => {
91
107
  const skill = skills().find((item) => item.name === name);
92
108
  return skill
@@ -17,10 +17,8 @@ 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");
24
22
  const issue_tools_1 = require("./issue-tools");
25
23
  const windows_pipe_1 = require("./windows-pipe");
26
24
  const repository_discovery_1 = require("./repository-discovery");
@@ -28,9 +26,9 @@ var config_1 = require("./config");
28
26
  Object.defineProperty(exports, "defaultSocketPath", { enumerable: true, get: function () { return config_1.defaultSocketPath; } });
29
27
  // Register Brain tools with backend selection and scope permissions.
30
28
  function createBrainServer(store, options = {}) {
31
- const github = (0, github_reviews_1.githubReviews)(store, options.repository);
29
+ const github = (0, github_client_1.githubIssueConfig)(store, options.repository);
32
30
  if (github && options.repository && github.repository !== options.repository)
33
- 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');
34
32
  const server = new mcp_js_1.McpServer({ name: 'agent-brain', version: (0, version_1.packageVersion)() });
35
33
  (0, repository_discovery_1.registerRepositoryTools)(server, options.repositories ?? (() => (0, repository_discovery_1.localRepositoryCatalog)(store.configRoot)), options.allowTool);
36
34
  (0, issue_tools_1.registerIssueTools)(server, store, options);
@@ -45,14 +43,14 @@ function createBrainServer(store, options = {}) {
45
43
  try {
46
44
  if (!readOnly && options.allowScopeWrite) {
47
45
  const data = input;
48
- 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);
49
47
  if (scopes.some((scope) => !options.allowScopeWrite(scope)))
50
48
  throw new Error('Write access to the entire target scope is required');
51
49
  }
52
- if (!readOnly && options.allowTool && !options.allowTool('review_update')) {
50
+ if (!readOnly) {
53
51
  const data = input;
54
52
  if (data.type === 'review' || (data.id && ['amend_knowledge', 'promote', 'deprecate_knowledge'].includes(name) && store.get(data.id).type === 'review')) {
55
- 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');
56
54
  }
57
55
  }
58
56
  const result = await handler(zod_1.z.object(shape).strict().parse(input));
@@ -65,7 +63,7 @@ function createBrainServer(store, options = {}) {
65
63
  }
66
64
  const id = zod_1.z.string().min(1).max(200);
67
65
  const revision = zod_1.z.string().regex(/^[a-f0-9]{64}$/);
68
- 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 }));
69
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));
70
68
  for (const name of ['brain_sync', 'brain_flush', 'sync', 'flush']) {
71
69
  if (options.allowTool && !options.allowTool(name))
@@ -96,8 +94,7 @@ function createBrainServer(store, options = {}) {
96
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));
97
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));
98
96
  tool('get_knowledge', 'Read a complete knowledge item and its current revision.', { id }, true, ({ id }) => store.get(id));
99
- 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')
100
- 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));
101
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.', {
102
99
  id, revision, changes: store_1.knowledgeChanges
103
100
  }, false, ({ id, revision, changes }) => store.amend(id, revision, changes));
@@ -107,60 +104,9 @@ function createBrainServer(store, options = {}) {
107
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));
108
105
  tool('list_skills', 'List available skills and descriptions. Local skills override global skills with the same name.', {}, true, () => (0, skills_1.listSkills)(store));
109
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));
110
- 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.', {
111
108
  task: zod_1.z.string().max(10000), files: zod_1.z.array(zod_1.z.string()).max(100).optional()
112
109
  }, false, ({ task, files }) => store.context(`review constraint decision ${task}`, files));
113
- 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));
114
- 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 }));
115
- tool('review_update', 'Revise a finding using its last-read revision. GitHub preserves text outside its managed block.', {
116
- 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()
117
- }, false, ({ id, revision, changes }) => {
118
- if (github)
119
- return github.update(id, revision, changes);
120
- if (changes.severity)
121
- throw new Error('Internal finding severity changes require the existing review workflow');
122
- return store.amend(id, revision, changes);
123
- });
124
- tool('review_list', 'List open findings from the configured backend. GitHub issues belong to this repository; PRs are excluded.', {
125
- severity: zod_1.z.array(store_1.severitySchema).optional(), state: zod_1.z.array(store_1.reviewStateSchema).optional()
126
- }, true, async ({ severity, state }) => {
127
- if (github)
128
- return (await github.list(state ? 'all' : 'open')).filter((item) => (!severity || severity.includes(item.severity)) && (!state || state.includes(item.state)));
129
- 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 }));
130
- });
131
- tool('review_history', 'Recall closed findings from the configured backend, with pagination.', {
132
- scope: store_1.scopeSchema.optional(), query: zod_1.z.string().max(1000).optional(), state: zod_1.z.enum(['fixed', 'wontfix']).optional(),
133
- offset: zod_1.z.number().int().min(0).optional(), limit: zod_1.z.number().int().min(1).max(1000).optional()
134
- }, true, async (options) => {
135
- if (!github)
136
- return store.reviewHistory(options);
137
- const items = (await github.list('closed')).filter((item) => (!options.state || item.state === options.state) && (!options.query || JSON.stringify(item).toLowerCase().includes(options.query.toLowerCase())));
138
- return { total: items.length, items: items.slice(options.offset ?? 0, (options.offset ?? 0) + (options.limit ?? 50)) };
139
- });
140
- tool('review_archive', 'Compact internal closed finding files. GitHub retains its own issue history.', { scope: store_1.scopeSchema }, false, ({ scope }) => { if (github)
141
- throw new Error('GitHub owns review history; no internal archive is needed'); return store.archiveReviews(scope); });
142
- tool('resolve_review', 'Close an authorized fix or explicitly dropped finding in the configured backend. GitHub writes must be enabled. Deferred findings stay open.', {
143
- id, revision, state: zod_1.z.enum(['fixed', 'wontfix']), reason: zod_1.z.string().min(1).max(2000).optional()
144
- }, false, ({ id, revision, state, reason }) => github ? github.resolve(id, revision, state, reason ?? state) : store.resolveReview(id, revision, state, reason));
145
- 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));
146
- tool('todo_get', 'Read a task and its revision.', { id }, true, ({ id }) => (0, todos_1.getTodo)(store, id));
147
- 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));
148
- 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));
149
- 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' }));
150
- for (const name of ['todo_import', 'todo_sync']) {
151
- if (options.allowTool && !options.allowTool(name))
152
- continue;
153
- 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.',
154
- inputSchema: { source: zod_1.z.string().max(100), scope: store_1.scopeSchema }, annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
155
- }, async ({ source, scope }) => {
156
- try {
157
- return { content: [{ type: 'text', text: JSON.stringify(await (0, connectors_1.syncConnector)(store, source, scope)) }] };
158
- }
159
- catch (error) {
160
- return { isError: true, content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }] };
161
- }
162
- });
163
- }
164
110
  return server;
165
111
  }
166
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
- }
@@ -6,7 +6,7 @@ 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');
@@ -73,7 +73,7 @@ function validate(candidate, selection) {
73
73
  if (store.knowledgeErrors.length)
74
74
  throw Error('Invalid staged knowledge: ' + JSON.stringify(store.knowledgeErrors));
75
75
  getSkills(store);
76
- const reviews = githubReviews(store);
76
+ const reviews = githubIssueConfig(store);
77
77
  if (reviews && reviews.repository !== repo.id)
78
78
  throw Error('GitHub issue target does not match its repository');
79
79
  listTodos(store);
@@ -31,6 +31,8 @@ const coreSkills = new Set([
31
31
  'brain-consolidate',
32
32
  'code-review',
33
33
  'git-workflow',
34
+ 'changelog',
35
+ 'github-release',
34
36
  'package-integrity-check',
35
37
  'node-cleanup',
36
38
  'unslop',
package/package.json CHANGED
@@ -7,7 +7,7 @@
7
7
  "license": "MIT",
8
8
  "copyright": "Copyright (c) 2026 Bjørn Erik Jacobsen / Technomoron.com",
9
9
  "name": "@technomoron/agent-brain",
10
- "version": "0.1.4",
10
+ "version": "0.1.6",
11
11
  "description": "Project knowledge and skills MCP server extracted from agent-run",
12
12
  "bin": {
13
13
  "agent-brain": "dist/agent-brain.js",
@@ -37,7 +37,7 @@
37
37
  "@technomoron/apicore-server": "^1.1.0",
38
38
  "yaml": "^2.9.0",
39
39
  "zod": "^4.5.4",
40
- "@technomoron/agent-run": "^0.99.48",
40
+ "@technomoron/agent-run": "^0.99.49",
41
41
  "jsonc-parser": "^3.3.1"
42
42
  },
43
43
  "devDependencies": {
@@ -15,7 +15,7 @@ Remote Brain source paths identify server files, not paths on the client filesys
15
15
 
16
16
  Do not create, edit, rename, move, or delete files inside the agent-run configuration directory yourself whenever a brain tool can do it. The tools keep the metadata, ids, revisions, index, and write lock consistent; direct file writes bypass those checks and can leave individual records unreadable.
17
17
 
18
- Use remember to add knowledge, amend_knowledge to revise it, deprecate_knowledge to retire it, promote to copy it to another scope, resolve_review to close a review finding, and the bundled todo-manager workflow for tasks. If you want a specific file name, pass filename to remember rather than writing or renaming the file afterwards; the id in the front matter is the identity, so the name is free to change but the tools should be the ones changing it.
18
+ Use remember to add knowledge, amend_knowledge to revise it, deprecate_knowledge to retire it, promote to copy it to another scope, issue_update to close a GitHub review issue, and the bundled todo-manager workflow for tasks. If you want a specific file name, pass filename to remember rather than writing or renaming the file afterwards; the id in the front matter is the identity, so the name is free to change but the tools should be the ones changing it.
19
19
 
20
20
  This covers generated runtime state as well: never hand-edit anything under a profile's live/ directory. Regenerate it with agent-run instead.
21
21
 
@@ -54,13 +54,13 @@ Do not begin a historical import merely because a correction was saved.
54
54
 
55
55
  Use remember for durable knowledge when the user asks to remember it or authorizes a workflow that records it. Use global scope only for explicit intent that applies everywhere; otherwise use the active project or default scope. Preserve uncertainty with authority=inferred and type=observation. Never persist secrets, raw transcripts, or temporary task state. Load complete skills with get_skill when needed. Promotion requires explicit confirmation.
56
56
 
57
- Search before writing so you do not create a near-duplicate. When existing knowledge is nearly right, amend it with amend_knowledge and its last-read revision instead of adding a second item that says almost the same thing. Amending keeps the id, file name, and history; scope, type, authority, and review severity are deliberately not amendable, so if one of those is wrong, deprecate the item and write a corrected one.
57
+ Search before writing so you do not create a near-duplicate. When existing knowledge is nearly right, amend it with amend_knowledge and its last-read revision instead of adding a second item that says almost the same thing. Amending keeps the id, file name, and history; scope, type, and authority are deliberately not amendable, so if one of those is wrong, deprecate the item and write a corrected one.
58
58
 
59
- Choose the knowledge type by content: preferences for user choices, constraints for requirements, conventions for established practices, decisions for confirmed choices, specs for confirmed specifications, reviews for review findings, memory for durable reference and history, and observations for code-derived facts or deductions. Rules use type=rule. Only explicit user instructions or confirmation justify authority=user; an import request alone does not make source documents authoritative. MCP maps the singular type to the matching storage directory, so pass scope and type rather than choosing a file path.
59
+ Choose the knowledge type by content: preferences for user choices, constraints for requirements, conventions for established practices, decisions for confirmed choices, specs for confirmed specifications, memory for durable reference and history, and observations for code-derived facts or deductions. Rules use type=rule. Only explicit user instructions or confirmation justify authority=user; an import request alone does not make source documents authoritative. MCP maps the singular type to the matching storage directory, so pass scope and type rather than choosing a file path.
60
60
 
61
- Use the bundled code-review skill for code reviews and saved findings. Track new findings in GitHub Issues; do not create duplicate brain knowledge records.
61
+ Use review_context for review guidance and the bundled code-review skill for reporting, severity mapping, attribution, validation and resolution. Use issue_* tools for findings and history. Track new findings in GitHub Issues; do not create duplicate brain knowledge records.
62
62
 
63
- Use the bundled todo-manager skill for tasks and preserve their external identities. Reusable workflows belong in skills/<name>/SKILL.md; actual reusable templates belong in templates/. These are separate from knowledge items, and remember does not install skills or templates. Keep source references and distinguish current behavior from historical notes and planned features. Keep project-specific content in project scope; default is only for work outside configured projects.
63
+ Use the bundled todo-manager skill and issue_* tools for tasks; manual todos use origin ToDo, normally type Task, and Priority. Preserve external identities and historical task data. Reusable workflows belong in skills/<name>/SKILL.md; actual reusable templates belong in templates/. These are separate from knowledge items, and remember does not install skills or templates. Keep source references and distinguish current behavior from historical notes and planned features. Keep project-specific content in project scope; default is only for work outside configured projects.
64
64
 
65
65
  Pool scope: `global/` is server-wide, `pools/<name>/` is shared by the active pool, and `projects/<owner>/<repo>/` belongs to one repository. Use `scope: pool` only for deliberately shared pool knowledge. Keep review findings and tasks in their individual repository. Global intent must still be explicit.
66
66
 
@@ -0,0 +1,25 @@
1
+ ---
2
+ name: changelog
3
+ description: Create, update or validate CHANGES and CHANGES.md entries and formatting, including release notes.
4
+ ---
5
+
6
+ # Changelog
7
+
8
+ Use the configured changelog path in the active working tree; otherwise use the package-local CHANGES.md or CHANGES. Use CHANGES.md for new changelogs, preserve an existing CHANGES filename, and never keep both in one package.
9
+
10
+ Use this format for a new changelog:
11
+
12
+ ```text
13
+ CHANGES
14
+ ========
15
+
16
+ vX.Y.Z (YYYY-MM-DD)
17
+ -------------------
18
+ * Concise description of the change.
19
+ ```
20
+
21
+ Keep a blank line between headings and entries. Underline the title with equals signs and version headings with dashes. Put the newest version first, use ISO dates and `*` bullets, and keep entries to the minimum useful description of changed behavior. Group related changes; omit implementation narration.
22
+
23
+ Preserve an existing `Version X.Y.Z (YYYY-MM-DD)` heading convention and historical entries. For package releases, the newest version must match package.json and its date must be the release date. Do not invent a release version or date for unreleased work.
24
+
25
+ Before pushing, ensure the relevant changelog covers the changes. If it is missing, report that and ask to create it unless creation is already authorized. Updating release notes does not authorize version bumps, commits, tags, pushes, publishing or GitHub Releases; use github-release for release work.