@technomoron/agent-brain 0.1.1 → 0.1.4

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.
Files changed (53) hide show
  1. package/CHANGES.md +26 -0
  2. package/README.md +117 -44
  3. package/dist/brain/built-in-skills.js +2 -0
  4. package/dist/brain/cli.js +8 -0
  5. package/dist/brain/config.js +7 -0
  6. package/dist/brain/connectors.js +2 -0
  7. package/dist/brain/consolidation.js +4 -0
  8. package/dist/brain/git.js +9 -2
  9. package/dist/brain/github-issues.js +332 -0
  10. package/dist/brain/github-reviews.js +38 -7
  11. package/dist/brain/issue-configuration.js +382 -0
  12. package/dist/brain/issue-tools.js +77 -0
  13. package/dist/brain/projects.js +4 -6
  14. package/dist/brain/remote-policy.js +16 -3
  15. package/dist/brain/remote-server.js +67 -12
  16. package/dist/brain/repositories.js +3 -0
  17. package/dist/brain/repository-discovery.js +22 -1
  18. package/dist/brain/server.js +17 -3
  19. package/dist/brain/skills.js +11 -0
  20. package/dist/brain/store.js +36 -1
  21. package/dist/brain/todos.js +10 -1
  22. package/dist/brain/windows-pipe.js +2 -1
  23. package/dist/version.js +1 -4
  24. package/examples/remote.jsonc +1 -1
  25. package/ops/brain-pipe-security.ps1 +40 -0
  26. package/ops/config-deploy-entry.sh +1 -1
  27. package/ops/config-deploy-root.cjs +14 -6
  28. package/ops/config-deploy.cjs +16 -8
  29. package/ops/config-policy.cjs +37 -1
  30. package/ops/config-sync.cjs +34 -1
  31. package/ops/layout.cjs +13 -0
  32. package/package.json +9 -6
  33. package/skills/brain-consolidate/README.md +5 -0
  34. package/skills/brain-import/README.md +5 -0
  35. package/skills/brain-memory/README.md +5 -0
  36. package/skills/brain-memory/SKILL.md +7 -3
  37. package/skills/code-review/README.md +7 -0
  38. package/skills/code-review/SKILL.md +58 -0
  39. package/skills/git-workflow/README.md +5 -0
  40. package/skills/git-workflow/SKILL.md +14 -0
  41. package/skills/node-cleanup/README.md +5 -0
  42. package/skills/node-cleanup/SKILL.md +239 -0
  43. package/skills/node-cleanup/agents/openai.yaml +4 -0
  44. package/skills/package-integrity-check/README.md +5 -0
  45. package/skills/package-integrity-check/SKILL.md +27 -0
  46. package/skills/todo-manager/README.md +5 -0
  47. package/skills/todo-manager/SKILL.md +13 -3
  48. package/skills/unslop/README.md +5 -0
  49. package/skills/unslop/SKILL.md +180 -0
  50. package/skills/unslop/agents/openai.yaml +4 -0
  51. package/skills/brain-review/SKILL.md +0 -38
  52. package/skills/code-review-organizer/SKILL.md +0 -150
  53. package/skills/review-items/SKILL.md +0 -43
@@ -13,12 +13,14 @@ const server_1 = require("./server");
13
13
  const remote_policy_1 = require("./remote-policy");
14
14
  const repositories_1 = require("./repositories");
15
15
  const repository_discovery_1 = require("./repository-discovery");
16
+ // Require a configured secret from the server environment.
16
17
  function secret(name) {
17
18
  const value = process.env[name];
18
19
  if (!value)
19
20
  throw new Error('Missing environment variable ' + name);
20
21
  return value;
21
22
  }
23
+ // Create a private runtime directory and verify its ownership.
22
24
  function privateDirectory(directory) {
23
25
  fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
24
26
  const stat = fs.lstatSync(directory);
@@ -54,15 +56,39 @@ async function createRemoteApi(configFile) {
54
56
  };
55
57
  const sessions = new apicore_server_1.JsonTokenStore(path.join(initial.runtime, 'sessions.json'));
56
58
  const credentials = new apicore_server_1.MemAuthStore({ passkeys: false, tokenStore: sessions });
59
+ const passwordHashes = new Map();
60
+ for (const user of initial.users) {
61
+ if (user.kind !== 'human' || user.disabled || !user.passwordEnv)
62
+ continue;
63
+ const stored = await credentials.userStore.createUser({ login: user.subject, email: user.subject + '@brain.invalid', password: secret(user.passwordEnv) });
64
+ passwordHashes.set(user.passwordEnv, credentials.getUserPasswordHash(stored));
65
+ }
57
66
  class ConfigAuth extends apicore_server_1.BaseAuthAdapter {
67
+ // Find an enabled user by subject or login.
58
68
  async getUser(identifier) { return policy().users.find((u) => !u.disabled && (u.subject === String(identifier) || u.login === identifier)) ?? null; }
69
+ // Use the configured subject as the authentication identity.
59
70
  getUserId(user) { return user.subject; }
60
- getUserPasswordHash(user) { return user.kind === 'human' && user.passwordHashEnv ? secret(user.passwordHashEnv) : ''; }
71
+ // Resolve the configured password to the existing bcrypt verifier.
72
+ getUserPasswordHash(user) {
73
+ if (user.kind !== 'human')
74
+ return '';
75
+ if (user.passwordHashEnv)
76
+ return secret(user.passwordHashEnv);
77
+ if (user.passwordEnv && passwordHashes.has(user.passwordEnv))
78
+ return passwordHashes.get(user.passwordEnv);
79
+ throw new Error('Restart the remote server after changing password environment settings');
80
+ }
81
+ // Expose only the configured subject in authentication responses.
61
82
  filterUser(user) { return { subject: user.subject }; }
83
+ // Verify a password through the configured authentication store.
62
84
  verifyPassword(password, hash) { return credentials.verifyPassword(password, hash); }
85
+ // Read an OAuth client from the authentication store.
63
86
  getClient(id) { return credentials.getClient(id); }
87
+ // Verify a confidential client secret through the authentication store.
64
88
  verifyClientSecret(client, value) { return credentials.verifyClientSecret(client, value); }
89
+ // Store an authorization code for the OAuth exchange.
65
90
  createAuthCode(input) { return credentials.createAuthCode(input); }
91
+ // Consume an authorization code for its registered client.
66
92
  consumeAuthCode(code, client) { return credentials.consumeAuthCode(code, client); }
67
93
  }
68
94
  for (const client of initial.clients) {
@@ -73,7 +99,9 @@ async function createRemoteApi(configFile) {
73
99
  }
74
100
  const api = new apicore_server_1.ApiServer({ authApi: false, origins: [], devMode: false }).authStorage(new ConfigAuth()).setTokenStore(sessions);
75
101
  const login = new apicore_server_1.OAuthPasswordLogin(api, { issuer: initial.issuer,
102
+ // Authorize the requested resource and OAuth scopes against current policy.
76
103
  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.
77
105
  verifySecondFactor: (value, code) => {
78
106
  const user = value;
79
107
  if (!user.totpSecretEnv)
@@ -92,6 +120,7 @@ async function createRemoteApi(configFile) {
92
120
  }).register();
93
121
  const attempts = new Map();
94
122
  const provider = new apicore_server_1.OAuthAuthorizationServer(api, { issuer: initial.issuer, resources: [initial.resource],
123
+ // Limit authorization attempts per IP and bound the attempt cache.
95
124
  rateLimit: (request) => {
96
125
  for (const [key, entry] of attempts)
97
126
  if (entry.expires <= Date.now())
@@ -106,11 +135,14 @@ async function createRemoteApi(configFile) {
106
135
  accessSecret: secret(initial.accessSecretEnv), refreshSecret: secret(initial.refreshSecretEnv),
107
136
  authorize: login.authorize,
108
137
  serviceAccounts: Object.fromEntries(initial.clients.filter((c) => c.kind === 'service').map((c) => [c.id, c.subject])),
138
+ // Recheck the resource and current grants before issuing tokens.
109
139
  validateGrant: (grant) => grant.resources.length === 1 && grant.resources[0] === initial.resource && (0, remote_policy_1.allowedGrant)(policy(), grant.userId, grant.clientId, grant.scopes) }).register();
110
140
  const resource = new URL(initial.resource);
111
141
  const endpoint = resource.pathname || '/';
112
142
  const metadataPath = '/.well-known/oauth-protected-resource' + (endpoint === '/' ? '' : endpoint);
143
+ // Publish the OAuth metadata for the configured MCP resource.
113
144
  api.fastify.get(metadataPath, async () => provider.resourceMetadata(initial.resource));
145
+ // Authenticate each request and expose only its authorized repository tools.
114
146
  api.fastify.post(endpoint, async (request, reply) => {
115
147
  if (request.headers.origin && request.headers.origin !== resource.origin)
116
148
  return reply.code(403).send({ error: 'Invalid origin' });
@@ -132,6 +164,7 @@ async function createRemoteApi(configFile) {
132
164
  const client = current.clients.find((c) => c.id === claims.client_id);
133
165
  if (!user || !client || (user.kind === 'service' ? client.kind !== 'service' || client.subject !== user.subject : client.kind === 'service'))
134
166
  return reply.code(403).send({ error: 'Identity access denied' });
167
+ // List repositories visible to the authenticated identity and token.
135
168
  const catalog = () => (0, repository_discovery_1.remoteRepositoryCatalog)(policy(), claims.sub, claims.client_id, claims.scope.split(' '));
136
169
  let store;
137
170
  let server;
@@ -148,15 +181,21 @@ async function createRemoteApi(configFile) {
148
181
  store.close();
149
182
  return reply.code(503).send({ error: 'Repository profile changed; restore its registration before continuing' });
150
183
  }
184
+ // Require write access to every repository affected by a shared scope.
151
185
  const canWriteScope = (scope) => {
152
186
  const scopes = claims.scope.split(' ');
153
187
  if (scope === 'project')
154
188
  return permissions.has('write');
189
+ if (scope === 'global' && !initial.dataRoot)
190
+ return initial.repositories.filter(member => repo.group ? member.group === repo.group : member.id === repo.id)
191
+ .every(member => (0, remote_policy_1.repositoryPermissions)(policy(), claims.sub, claims.client_id, scopes, member.id).has('write'));
155
192
  if (scope === 'global')
156
193
  return scopes.includes('repo:*') && (0, remote_policy_1.allowedGrant)(policy(), claims.sub, claims.client_id, ['read', 'write', 'repo:*']);
157
194
  return !!repo.group && initial.repositories.filter(member => member.group === repo.group).every(member => (0, remote_policy_1.repositoryPermissions)(policy(), claims.sub, claims.client_id, scopes, member.id).has('write'));
158
195
  };
159
- server = (0, server_1.createBrainServer)(store, { sync: async (message) => {
196
+ server = (0, server_1.createBrainServer)(store, {
197
+ // Export authorized scopes through the configured Git synchronization worker.
198
+ sync: async (message) => {
160
199
  if (!initial.gitSync || !initial.dataRoot)
161
200
  throw new Error('Brain Git synchronization is not configured; changes remain on the server.');
162
201
  const scopes = ['projects/' + repository];
@@ -179,14 +218,25 @@ async function createRemoteApi(configFile) {
179
218
  });
180
219
  child.stdin?.end(JSON.stringify({ ...initial.gitSync, dataRoot: initial.dataRoot, scopes, reviews: permissions.has('review'), message }));
181
220
  });
182
- }, repository, group: repo.group, repositories: catalog, allowScopeWrite: (scope) => {
183
- if (!initial.dataRoot || scope === 'project')
184
- return true;
185
- const scopes = claims.scope.split(' ');
186
- if (scope === 'global')
187
- return scopes.includes('repo:*') && (0, remote_policy_1.allowedGrant)(policy(), claims.sub, claims.client_id, ['read', 'write', 'repo:*']);
188
- return scope === 'pool' && initial.repositories.filter((member) => member.group === repo.group).every((member) => (0, remote_policy_1.repositoryPermissions)(policy(), claims.sub, claims.client_id, scopes, member.id).has('write'));
189
- }, allowTool: (name) => { const required = (0, remote_policy_1.toolPermission)(name); return required !== null && permissions.has(required); } });
221
+ }, repository, group: repo.group, repositories: catalog,
222
+ // Authorize both ends of cross-repository issue relationships.
223
+ allowIssueRepository: (target, write) => {
224
+ const granted = (0, remote_policy_1.repositoryPermissions)(policy(), claims.sub, claims.client_id, claims.scope.split(' '), target);
225
+ return granted.has('read') && (!write || (granted.has('write') && granted.has('review')));
226
+ },
227
+ // Require an explicit organisation-wide grant before examining or modifying shared definitions.
228
+ allowIssueOrganisation: (owner) => (0, remote_policy_1.allowedGrant)(policy(), claims.sub, claims.client_id, ['read', 'write', 'review', 'repo:' + owner + '/*']) &&
229
+ claims.scope.split(' ').some(scope => scope === 'repo:*' || scope === 'repo:' + owner + '/*') &&
230
+ ['read', 'write', 'review'].every(scope => claims.scope.split(' ').includes(scope)),
231
+ // Check whether this request may change the target storage scope.
232
+ allowScopeWrite: (scope) => scope === 'project' || (scope === 'default' ? !initial.dataRoot : canWriteScope(scope)),
233
+ // Check whether this token permits the requested tool operation.
234
+ allowTool: (name) => {
235
+ const required = (0, remote_policy_1.toolPermission)(name);
236
+ return required !== null && permissions.has(required) &&
237
+ (!name.startsWith('issue_') || required === 'read' || permissions.has('review'));
238
+ }
239
+ });
190
240
  }
191
241
  const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
192
242
  reply.hijack();
@@ -199,9 +249,14 @@ async function createRemoteApi(configFile) {
199
249
  store?.close();
200
250
  }
201
251
  });
202
- api.fastify.route({ method: ['GET', 'DELETE'], url: endpoint, handler: async (_request, reply) => reply.code(405).send() });
203
- return { api, provider, config: initial, close: () => api.fastify.close() };
252
+ api.fastify.route({ method: ['GET', 'DELETE'], url: endpoint,
253
+ // Reject unsupported HTTP methods on the MCP endpoint.
254
+ handler: async (_request, reply) => reply.code(405).send() });
255
+ return { api, provider, config: initial,
256
+ // Close the remote API listener.
257
+ close: () => api.fastify.close() };
204
258
  }
259
+ // Start the configured remote API listener.
205
260
  async function serveRemote(configFile) {
206
261
  const service = await createRemoteApi(configFile);
207
262
  await service.api.fastify.listen(service.config.listen.socket ? { path: service.config.listen.socket } : { host: '127.0.0.1', port: service.config.listen.port });
@@ -10,9 +10,11 @@ exports.repositoryId = zod_1.z.string().max(200).regex(/^[a-zA-Z0-9][a-zA-Z0-9-]
10
10
  exports.repositoryPattern = zod_1.z.string().refine((value) => value === '*' ||
11
11
  (value.endsWith('/*') ? exports.repositoryId.safeParse(value.slice(0, -1) + 'repository').success : exports.repositoryId.safeParse(value).success), 'Use owner/repo, owner/* or *')
12
12
  .transform((value) => value.toLowerCase());
13
+ // Match a repository against an exact, owner-wide or wildcard grant.
13
14
  function matchesRepository(pattern, repository) {
14
15
  return pattern === '*' || pattern === repository || (pattern.endsWith('/*') && repository.startsWith(pattern.slice(0, -1)));
15
16
  }
17
+ // Check whether one repository grant fully covers another.
16
18
  function coversPattern(allowed, requested) {
17
19
  if (requested === '*')
18
20
  return allowed === '*';
@@ -20,6 +22,7 @@ function coversPattern(allowed, requested) {
20
22
  return allowed === '*' || allowed === requested;
21
23
  return matchesRepository(allowed, requested);
22
24
  }
25
+ // Extract and normalize a repository ID from a GitHub remote URL.
23
26
  function githubRepository(remote) {
24
27
  const match = /^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/)([^?#]+?)(?:\.git)?\/?$/.exec(remote);
25
28
  if (!match)
@@ -10,9 +10,12 @@ 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
+ // List local projects and their OS-user permissions.
13
16
  function localRepositoryCatalog(configRoot) {
14
17
  return (0, config_1.listBrainProjects)(configRoot).map((project) => ({
15
- id: (project.repository?.url ? (0, repositories_1.githubRepository)(project.repository.url) : null) ?? project.name,
18
+ id: project.repository?.url ? (0, repositories_1.githubRepository)(project.repository.url) : project.name,
16
19
  name: project.display_name ?? project.name, group: project.pool,
17
20
  permissions: ['read', 'write', 'review'], configuration: 'project'
18
21
  }));
@@ -44,6 +47,7 @@ function remoteRepositoryCatalog(config, subject, clientId, scopes) {
44
47
  }
45
48
  }).sort((a, b) => a.id.localeCompare(b.id));
46
49
  }
50
+ // Register repository and group discovery tools with permission filtering.
47
51
  function registerRepositoryTools(server, catalog, allow = () => true) {
48
52
  for (const name of ['list_repositories', 'list_repository_groups']) {
49
53
  if (!allow(name))
@@ -69,8 +73,25 @@ function registerRepositoryTools(server, catalog, allow = () => true) {
69
73
  });
70
74
  }
71
75
  }
76
+ // Create an MCP server with repository discovery and public bundled skills.
72
77
  function createRepositoryDiscoveryServer(catalog) {
73
78
  const server = new mcp_js_1.McpServer({ name: 'agent-brain', version: (0, version_1.packageVersion)() });
74
79
  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
+ }));
84
+ const annotations = { readOnlyHint: true, destructiveHint: false, openWorldHint: false };
85
+ server.registerTool('list_skills', {
86
+ description: 'List bundled skills available without repository selection.', inputSchema: {}, annotations
87
+ }, async () => ({ content: [{ type: 'text', text: JSON.stringify(skills().map(({ content: _content, ...skill }) => skill)) }] }));
88
+ server.registerTool('get_skill', {
89
+ description: 'Load a bundled skill by name without repository selection.', inputSchema: { name: zod_1.z.string().max(100) }, annotations
90
+ }, async ({ name }) => {
91
+ const skill = skills().find((item) => item.name === name);
92
+ return skill
93
+ ? { content: [{ type: 'text', text: JSON.stringify(skill) }] }
94
+ : { isError: true, content: [{ type: 'text', text: 'Skill not found' }] };
95
+ });
75
96
  return server;
76
97
  }
@@ -21,16 +21,20 @@ const todos_1 = require("./todos");
21
21
  const connectors_1 = require("./connectors");
22
22
  const git_1 = require("./git");
23
23
  const github_reviews_1 = require("./github-reviews");
24
+ const issue_tools_1 = require("./issue-tools");
24
25
  const windows_pipe_1 = require("./windows-pipe");
25
26
  const repository_discovery_1 = require("./repository-discovery");
26
27
  var config_1 = require("./config");
27
28
  Object.defineProperty(exports, "defaultSocketPath", { enumerable: true, get: function () { return config_1.defaultSocketPath; } });
29
+ // Register Brain tools with backend selection and scope permissions.
28
30
  function createBrainServer(store, options = {}) {
29
- const github = (0, github_reviews_1.githubReviews)(store);
31
+ const github = (0, github_reviews_1.githubReviews)(store, options.repository);
30
32
  if (github && options.repository && github.repository !== options.repository)
31
33
  throw new Error('Review backend repository does not match the authenticated repository');
32
34
  const server = new mcp_js_1.McpServer({ name: 'agent-brain', version: (0, version_1.packageVersion)() });
33
35
  (0, repository_discovery_1.registerRepositoryTools)(server, options.repositories ?? (() => (0, repository_discovery_1.localRepositoryCatalog)(store.configRoot)), options.allowTool);
36
+ (0, issue_tools_1.registerIssueTools)(server, store, options);
37
+ // Register a validated tool with permission checks and broken-file diagnostics.
34
38
  function tool(name, description, shape, readOnly, handler) {
35
39
  if (options.allowTool && !options.allowTool(name))
36
40
  return;
@@ -159,11 +163,13 @@ function createBrainServer(store, options = {}) {
159
163
  }
160
164
  return server;
161
165
  }
166
+ // Require a private socket directory owned by the current user.
162
167
  function requirePrivateSocketDirectory(socketPath) {
163
168
  const stat = fs.lstatSync(path.dirname(socketPath));
164
169
  if (!stat.isDirectory() || stat.uid !== process.getuid() || (stat.mode & 0o077) !== 0)
165
170
  throw new Error(`The socket directory ${path.dirname(socketPath)} must be owned by the current user with mode 0700 (current uid ${process.getuid()}, owner uid ${stat.uid}, mode ${(stat.mode & 0o777).toString(8)}). Run agent-run and agent-brain as the same user.`);
166
171
  }
172
+ // Serve local MCP requests through a private socket or Windows pipe.
167
173
  async function serveApiCore(configRoot, socketPath) {
168
174
  if (process.platform !== 'win32') {
169
175
  const directory = path.dirname(socketPath);
@@ -209,7 +215,9 @@ async function serveApiCore(configRoot, socketPath) {
209
215
  store.close();
210
216
  }
211
217
  });
212
- api.fastify.route({ method: ['GET', 'DELETE'], url: '/mcp', handler: async (_request, reply) => reply.code(405).send() });
218
+ api.fastify.route({ method: ['GET', 'DELETE'], url: '/mcp',
219
+ // Reject unsupported HTTP methods on the local MCP endpoint.
220
+ handler: async (_request, reply) => reply.code(405).send() });
213
221
  await api.fastify.listen({ path: socketPath });
214
222
  try {
215
223
  if (process.platform === 'win32')
@@ -222,8 +230,12 @@ async function serveApiCore(configRoot, socketPath) {
222
230
  await api.fastify.close();
223
231
  throw error;
224
232
  }
225
- return { close: () => api.fastify.close() };
233
+ return {
234
+ // Close the local API listener.
235
+ close: () => api.fastify.close()
236
+ };
226
237
  }
238
+ // Bridge MCP standard input and output to the private local service.
227
239
  async function proxyStdio(socketPath, cwd, configRoot) {
228
240
  if (process.platform === 'win32') {
229
241
  try {
@@ -243,6 +255,7 @@ async function proxyStdio(socketPath, cwd, configRoot) {
243
255
  }
244
256
  const stdio = new stdio_js_1.StdioServerTransport();
245
257
  let protocolVersion;
258
+ // Forward one MCP message and relay its validated response.
246
259
  async function send(message) {
247
260
  const response = await new Promise((resolve, reject) => {
248
261
  const request = http.request({ socketPath, path: '/mcp', method: 'POST', headers: {
@@ -271,6 +284,7 @@ async function proxyStdio(socketPath, cwd, configRoot) {
271
284
  await stdio.send(parsed);
272
285
  }
273
286
  }
287
+ // Relay client messages and report forwarding failures through JSON-RPC or stderr.
274
288
  stdio.onmessage = (message) => {
275
289
  void send(message).catch(async (error) => {
276
290
  if ('id' in message && 'method' in message)
@@ -4,6 +4,7 @@ exports.getSkills = getSkills;
4
4
  exports.listSkills = listSkills;
5
5
  exports.getSkill = getSkill;
6
6
  const path = require("node:path");
7
+ const built_in_skills_1 = require("./built-in-skills");
7
8
  const zod_1 = require("zod");
8
9
  const store_1 = require("./store");
9
10
  const templates_1 = require("@technomoron/agent-run/dist/templates");
@@ -14,6 +15,7 @@ const metadata = zod_1.z.object({
14
15
  tags: zod_1.z.array(zod_1.z.string()).default([]),
15
16
  extends: zod_1.z.string().regex(/^(?:global|pool):[a-zA-Z0-9][a-zA-Z0-9._-]*$/).optional()
16
17
  });
18
+ // Resolve bundled workflows and scope-specific skill overrides.
17
19
  function getSkills(store) {
18
20
  const profile = store.profile ?? 'default';
19
21
  const directory = store.scopeDirectory(store.profile ? 'project' : 'default');
@@ -22,11 +24,18 @@ function getSkills(store) {
22
24
  const skillEnv = (0, templates_1.createSkillNunjucksEnv)(store.configRoot, directory, undefined, store.pool);
23
25
  const skills = new Map();
24
26
  const parentSkills = new Map();
27
+ for (const [name, packaged] of Object.entries((0, built_in_skills_1.readBuiltInSkills)())) {
28
+ const skill = { name, ...packaged, tags: [], scope: 'global', source: `builtin:${name}` };
29
+ skills.set(name, skill);
30
+ parentSkills.set(`global:${name}`, skill);
31
+ }
25
32
  for (const { scope, directory } of store.scopes) {
26
33
  for (const file of store.files(path.join(directory, 'skills')).filter((file) => path.basename(file) === 'SKILL.md')) {
27
34
  const text = skillEnv.render(path.relative(store.configRoot, file), context);
28
35
  const document = (0, store_1.readMarkdown)(text);
29
36
  const parsed = metadata.parse(document.metadata);
37
+ if (['brain-review', 'code-review-organizer', 'review-items', 'commit-workflow', 'release-package-check', 'personal-memory'].includes(parsed.name))
38
+ continue;
30
39
  if (path.basename(path.dirname(file)) !== parsed.name)
31
40
  throw new Error(`Skill name must match directory: ${file}`);
32
41
  let content = document.content;
@@ -43,9 +52,11 @@ function getSkills(store) {
43
52
  }
44
53
  return [...skills.values()];
45
54
  }
55
+ // List resolved skill metadata without loading content into the response.
46
56
  function listSkills(store) {
47
57
  return getSkills(store).map(({ content: _content, ...skill }) => skill);
48
58
  }
59
+ // Read a resolved skill by name or report that it is unavailable.
49
60
  function getSkill(store, name) {
50
61
  const skill = getSkills(store).find((item) => item.name === name);
51
62
  if (!skill)
@@ -60,6 +60,7 @@ exports.knowledgeDirectories = {
60
60
  rule: 'rules', preference: 'preferences', convention: 'conventions', constraint: 'constraints',
61
61
  decision: 'decisions', spec: 'specs', review: 'reviews', memory: 'memory', observation: 'observations'
62
62
  };
63
+ // Parse optional YAML front matter and normalize Markdown line endings.
63
64
  function readMarkdown(text) {
64
65
  const normalized = text.replace(/\r\n/g, '\n');
65
66
  const match = /^---\n([\s\S]*?)\n---(?:\n|$)/.exec(normalized);
@@ -68,25 +69,30 @@ function readMarkdown(text) {
68
69
  return match ? { metadata: (0, yaml_1.parse)(match[1], { maxAliasCount: 50 }), content: normalized.slice(match[0].length).trim() }
69
70
  : { metadata: null, content: normalized.trim() };
70
71
  }
72
+ // Hash file text for stable revisions and legacy record IDs.
71
73
  function hash(text) { return (0, node_crypto_1.createHash)('sha256').update(text).digest('hex'); }
72
74
  class BrainStore {
75
+ // Describe an unreadable record without losing its source or known ID.
73
76
  brokenFile(file, error, id) {
74
77
  const message = error instanceof zod_1.z.ZodError
75
78
  ? error.issues.map((issue) => `${issue.path.join('.') || 'metadata'}: ${issue.message}`).join('; ')
76
79
  : error instanceof Error ? error.message.split('\n')[0] : String(error);
77
80
  return { source: path.relative(this.configRoot, file), status: 'broken', error: message, ...(id ? { id } : {}) };
78
81
  }
82
+ // Attach broken-file diagnostics to a tool result when needed.
79
83
  withDiagnostics(value) {
80
84
  const brokenFiles = [...this.knowledgeErrors, ...this.todoErrors];
81
85
  if (!brokenFiles.length)
82
86
  return value;
83
87
  return Array.isArray(value) ? { items: value, brokenFiles } : { ...value, brokenFiles };
84
88
  }
89
+ // Reject access to records with matching broken-file diagnostics.
85
90
  assertReadable(id, errors) {
86
91
  const matches = errors.filter((item) => item.id === id || item.source === id || path.basename(item.source, '.md') === id);
87
92
  if (matches.length)
88
93
  throw new Error(`Cannot read or update broken file: ${matches.map((item) => `${item.source}: ${item.error}`).join('; ')}. Correct the file on disk first.`);
89
94
  }
95
+ // Resolve active scopes and open the local knowledge search index.
90
96
  constructor(configRoot, cwd) {
91
97
  this.configRoot = configRoot;
92
98
  this.cwd = cwd;
@@ -107,7 +113,9 @@ class BrainStore {
107
113
  this.db = new node_sqlite_1.DatabaseSync(this.safePath('index', 'knowledge.sqlite'));
108
114
  this.db.exec('PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; CREATE VIRTUAL TABLE IF NOT EXISTS knowledge USING fts5(source UNINDEXED, environment UNINDEXED, title, content, tags);');
109
115
  }
116
+ // Close the knowledge search database.
110
117
  close() { this.db.close(); }
118
+ // Resolve a path inside Brain storage and reject symlink traversal.
111
119
  safePath(...parts) {
112
120
  const target = path.resolve(this.configRoot, ...parts);
113
121
  if (!(0, utils_1.isSamePathOrDescendant)(target, this.configRoot))
@@ -126,17 +134,20 @@ class BrainStore {
126
134
  }
127
135
  return target;
128
136
  }
137
+ // Create a private directory inside Brain storage.
129
138
  directory(...parts) {
130
139
  const directory = this.safePath(...parts);
131
140
  fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
132
141
  return directory;
133
142
  }
143
+ // Resolve an available scope to its storage directory.
134
144
  scopeDirectory(scope) {
135
145
  const directory = this.scopes.find((entry) => entry.scope === scope)?.directory;
136
146
  if (!directory)
137
147
  throw new Error(`Scope ${scope} is not available in this environment`);
138
148
  return this.safePath(directory);
139
149
  }
150
+ // List allowed files recursively and optionally collect unreadable paths.
140
151
  files(directory, options = {}) {
141
152
  const { onError } = options;
142
153
  try {
@@ -163,12 +174,14 @@ class BrainStore {
163
174
  return [];
164
175
  }
165
176
  }
177
+ // Read a storage file with a one-MiB limit.
166
178
  read(file) {
167
179
  const target = this.safePath(file);
168
180
  if (fs.statSync(target).size > 1024 * 1024)
169
181
  throw new Error(`Markdown file exceeds 1 MiB: ${file}`);
170
182
  return fs.readFileSync(target, 'utf8');
171
183
  }
184
+ // Replace a storage file atomically with private permissions.
172
185
  atomicWrite(file, text) {
173
186
  const target = this.safePath(file);
174
187
  this.directory(path.dirname(target));
@@ -181,6 +194,7 @@ class BrainStore {
181
194
  fs.rmSync(temporary, { force: true });
182
195
  }
183
196
  }
197
+ // Serialize storage writes and release the lock after completion.
184
198
  writeLocked(fn) {
185
199
  const file = this.safePath('runtime', 'brain-write.lock');
186
200
  let descriptor;
@@ -201,6 +215,7 @@ class BrainStore {
201
215
  fs.unlinkSync(file);
202
216
  }
203
217
  }
218
+ // Load scoped knowledge and report malformed or duplicate records.
204
219
  allKnowledge() {
205
220
  this.knowledgeErrors.length = 0;
206
221
  const result = [];
@@ -209,7 +224,10 @@ class BrainStore {
209
224
  if (scope === 'global')
210
225
  directories.push(['memory', path.relative(directory, path.join(this.configRoot, 'notes', 'memory'))]);
211
226
  for (const [type, folder] of directories) {
212
- for (const file of this.files(path.join(directory, folder), { onError: (file, error) => this.knowledgeErrors.push(this.brokenFile(file, error)) })) {
227
+ for (const file of this.files(path.join(directory, folder), {
228
+ // Collect unreadable knowledge paths for the current scan.
229
+ onError: (file, error) => this.knowledgeErrors.push(this.brokenFile(file, error))
230
+ })) {
213
231
  let id;
214
232
  try {
215
233
  const text = this.read(file);
@@ -250,9 +268,11 @@ class BrainStore {
250
268
  }
251
269
  return result.filter((item) => counts.get(item.id) === 1);
252
270
  }
271
+ // Search current knowledge with scope, type and status filters.
253
272
  search(query, options = {}) {
254
273
  return this.searchItems(this.allKnowledge(), query, options);
255
274
  }
275
+ // Rank supplied knowledge through full-text search and apply result filters.
256
276
  searchItems(items, query, options = {}) {
257
277
  const environment = this.profile ?? 'default';
258
278
  this.refreshIndex(items, environment);
@@ -263,10 +283,12 @@ class BrainStore {
263
283
  return ranked.map((source) => bySource.get(source)).filter((item) => item !== undefined).filter((item) => (options.includeDeprecated || item.status === 'active') && (!options.scopes || options.scopes.includes(item.scope)) &&
264
284
  (!options.types || options.types.includes(item.type))).slice(0, options.limit ?? 50);
265
285
  }
286
+ // Update changed search rows transactionally while retaining unchanged rows.
266
287
  refreshIndex(items, environment) {
267
288
  const desired = new Map(items.map((item) => [item.source, {
268
289
  source: item.source, title: item.title, content: item.content, tags: [...item.tags, item.finding ?? ''].join(' ').trim()
269
290
  }]));
291
+ // Compare current search rows with the desired knowledge snapshot.
270
292
  const changes = () => {
271
293
  const current = this.db.prepare('SELECT rowid, source, title, content, tags FROM knowledge WHERE environment = ?').all(environment);
272
294
  const unchanged = new Set();
@@ -300,6 +322,7 @@ class BrainStore {
300
322
  throw error;
301
323
  }
302
324
  }
325
+ // Select relevant and always-recalled knowledge within the context budget.
303
326
  context(task, files = [], symbols = []) {
304
327
  const scanned = this.allKnowledge();
305
328
  const all = scanned.filter((item) => item.status === 'active');
@@ -319,6 +342,7 @@ class BrainStore {
319
342
  });
320
343
  return { items, omitted: selected.length - items.length, profile: this.profile, scopes: this.scopes.map((scope) => scope.scope) };
321
344
  }
345
+ // Validate and save a new knowledge record in its authorized scope.
322
346
  remember(input) {
323
347
  const value = exports.knowledgeInput.parse(input);
324
348
  if (value.type === 'review' && (value.scope === 'pool' || (this.pool && value.scope !== 'project')))
@@ -383,6 +407,7 @@ class BrainStore {
383
407
  }
384
408
  /** Review findings in severity then sequence order. Open findings only unless states are given. */
385
409
  reviews(options = {}) {
410
+ // Read the numeric sequence from a numbered finding.
386
411
  const sequence = (item) => Number.parseInt(item.finding.slice(1), 10);
387
412
  return this.allKnowledge()
388
413
  .filter((item) => (!this.pool || item.scope === 'project') && item.type === 'review' && item.finding && item.severity)
@@ -390,10 +415,12 @@ class BrainStore {
390
415
  .filter((item) => (options.state ?? ['open']).includes(item.state ?? 'open'))
391
416
  .sort((left, right) => severityOrder[left.severity] - severityOrder[right.severity] || sequence(left) - sequence(right));
392
417
  }
418
+ // Read saved severity counters or initialize empty counters.
393
419
  reviewCounters(scope) {
394
420
  const file = this.safePath(this.scopeDirectory(scope), 'review-counters.json');
395
421
  return fs.existsSync(file) ? reviewCountersSchema.parse(JSON.parse(fs.readFileSync(file, 'utf8'))) : { C: 0, H: 0, M: 0, L: 0 };
396
422
  }
423
+ // Persist the highest used sequence for a severity.
397
424
  reserveFinding(scope, finding) {
398
425
  const counters = this.reviewCounters(scope);
399
426
  const prefix = finding[0];
@@ -403,6 +430,7 @@ class BrainStore {
403
430
  counters[prefix] = Math.max(counters[prefix], number);
404
431
  this.atomicWrite(path.join(this.scopeDirectory(scope), 'review-counters.json'), JSON.stringify(counters) + '\n');
405
432
  }
433
+ // Read and validate a scope’s archived review closures.
406
434
  closedReviews(scope) {
407
435
  const file = this.safePath(this.scopeDirectory(scope), 'review-history.jsonl');
408
436
  if (!fs.existsSync(file))
@@ -414,6 +442,7 @@ class BrainStore {
414
442
  return record;
415
443
  });
416
444
  }
445
+ // Search archived review closures with filters and pagination.
417
446
  reviewHistory(options = {}) {
418
447
  const query = options.query?.toLowerCase();
419
448
  const items = this.scopes.filter((entry) => (!this.pool || entry.scope === 'project') && (!options.scope || entry.scope === options.scope))
@@ -423,6 +452,7 @@ class BrainStore {
423
452
  const offset = options.offset ?? 0;
424
453
  return { items: items.slice(offset, offset + (options.limit ?? 100)), total: items.length };
425
454
  }
455
+ // Preserve a finding number and closure before deleting the full record.
426
456
  archiveReview(item, state, reason, closed) {
427
457
  if (!item.finding || !item.severity)
428
458
  throw new Error('Only numbered review findings can be archived.');
@@ -438,6 +468,7 @@ class BrainStore {
438
468
  fs.unlinkSync(this.safePath(item.source));
439
469
  return record;
440
470
  }
471
+ // Archive resolved findings and finish interrupted archive deletions.
441
472
  archiveReviews(scope) {
442
473
  return this.writeLocked(() => {
443
474
  const history = this.closedReviews(scope);
@@ -449,6 +480,7 @@ class BrainStore {
449
480
  });
450
481
  });
451
482
  }
483
+ // Close a current review finding and archive its resolution.
452
484
  resolveReview(id, revision, state, reason) {
453
485
  return this.writeLocked(() => {
454
486
  const item = this.get(id);
@@ -459,6 +491,7 @@ class BrainStore {
459
491
  return this.archiveReview(item, state, reason ?? '', new Date().toISOString());
460
492
  });
461
493
  }
494
+ // Mark a current knowledge record deprecated without deleting it.
462
495
  deprecate(id, revision, reason) {
463
496
  return this.writeLocked(() => {
464
497
  const item = this.get(id);
@@ -469,6 +502,7 @@ class BrainStore {
469
502
  return this.get(id);
470
503
  });
471
504
  }
505
+ // Copy current knowledge into another scope with provenance and a new ID.
472
506
  promote(id, scope, revision) {
473
507
  if (this.get(id).type === 'review' && (scope === 'pool' || (this.pool && scope !== 'project')))
474
508
  throw new Error('Review findings must belong to an individual repository');
@@ -488,6 +522,7 @@ class BrainStore {
488
522
  return this.get(promoted.id);
489
523
  });
490
524
  }
525
+ // Read one record from active scopes and reject broken or missing records.
491
526
  get(id) {
492
527
  const item = this.allKnowledge().find((entry) => entry.id === id);
493
528
  this.assertReadable(id, this.knowledgeErrors);
@@ -25,10 +25,14 @@ exports.todoInput = zod_1.z.object({
25
25
  }).strict();
26
26
  const remoteTask = exports.todoInput.pick({ title: true, description: true, status: true, labels: true, due: true }).strip();
27
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
+ // Read scoped tasks and report malformed or duplicate records.
28
29
  function listTodos(store) {
29
30
  store.todoErrors.length = 0;
30
31
  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
+ const todos = store.scopes.filter((entry) => !store.pool || entry.scope === 'project').flatMap(({ scope, directory }) => store.files(path.join(directory, 'todo'), {
33
+ // Collect unreadable task paths for the current scan.
34
+ onError: (file, error) => store.todoErrors.push(store.brokenFile(file, error))
35
+ }).flatMap((file) => {
32
36
  let id;
33
37
  try {
34
38
  const text = store.read(file);
@@ -59,6 +63,7 @@ function listTodos(store) {
59
63
  return false;
60
64
  });
61
65
  }
66
+ // Read a task by ID and reject broken or missing records.
62
67
  function getTodo(store, id) {
63
68
  const todo = listTodos(store).find((item) => item.id === id);
64
69
  store.assertReadable(id, store.todoErrors);
@@ -66,12 +71,14 @@ function getTodo(store, id) {
66
71
  throw new Error(`Todo not found: ${id}`);
67
72
  return todo;
68
73
  }
74
+ // Write task metadata and description and return its new revision.
69
75
  function writeTodo(store, todo) {
70
76
  const { description, ...metadata } = todo;
71
77
  const text = `---\n${(0, yaml_1.stringify)(metadata)}---\n\n${description}\n`;
72
78
  store.atomicWrite(path.join(store.scopeDirectory(todo.scope), 'todo', `${todo.id}.md`), text);
73
79
  return { ...todo, revision: (0, node_crypto_1.createHash)('sha256').update(text).digest('hex') };
74
80
  }
81
+ // Create a repository task or reuse its existing external identity.
75
82
  function addTodo(store, input) {
76
83
  const value = exports.todoInput.parse(input);
77
84
  if (value.scope === 'pool' || (store.pool && value.scope !== 'project'))
@@ -100,6 +107,7 @@ exports.todoChanges = zod_1.z.object({
100
107
  labels: zod_1.z.array(zod_1.z.string()).optional(),
101
108
  notes: zod_1.z.string().optional()
102
109
  }).strict();
110
+ // Apply validated task changes only to the expected revision.
103
111
  function updateTodo(store, id, revision, changes) {
104
112
  const parsed = exports.todoChanges.parse(changes);
105
113
  return store.writeLocked(() => {
@@ -110,6 +118,7 @@ function updateTodo(store, id, revision, changes) {
110
118
  return writeTodo(store, { ...value, ...parsed, updated: new Date().toISOString() });
111
119
  });
112
120
  }
121
+ // Merge external task changes while retaining local edits and reporting conflicts.
113
122
  function importTodos(store, input) {
114
123
  const incoming = input.map((item) => exports.todoInput.parse(item));
115
124
  return store.writeLocked(() => {