@technomoron/agent-brain 0.0.0-stage → 0.1.1

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 (39) hide show
  1. package/CHANGES.md +18 -0
  2. package/LICENSE +21 -0
  3. package/README.md +855 -2
  4. package/dist/agent-brain.js +6 -0
  5. package/dist/brain/built-in-skills.js +24 -0
  6. package/dist/brain/cli.js +265 -0
  7. package/dist/brain/config.js +92 -0
  8. package/dist/brain/connectors.js +63 -0
  9. package/dist/brain/consolidation-skill.js +5 -0
  10. package/dist/brain/consolidation.js +134 -0
  11. package/dist/brain/git.js +139 -0
  12. package/dist/brain/github-reviews.js +174 -0
  13. package/dist/brain/projects.js +136 -0
  14. package/dist/brain/remote-policy.js +126 -0
  15. package/dist/brain/remote-server.js +211 -0
  16. package/dist/brain/repositories.js +28 -0
  17. package/dist/brain/repository-discovery.js +76 -0
  18. package/dist/brain/server.js +283 -0
  19. package/dist/brain/skills.js +54 -0
  20. package/dist/brain/store.js +499 -0
  21. package/dist/brain/todos.js +155 -0
  22. package/dist/brain/windows-pipe.js +19 -0
  23. package/dist/version.js +22 -0
  24. package/examples/brain.jsonc +7 -0
  25. package/examples/remote.jsonc +22 -0
  26. package/ops/config-deploy-entry.sh +3 -0
  27. package/ops/config-deploy-root.cjs +111 -0
  28. package/ops/config-deploy.cjs +176 -0
  29. package/ops/config-policy.cjs +220 -0
  30. package/ops/config-sync.cjs +72 -0
  31. package/ops/systemd/agent-brain.service +14 -0
  32. package/package.json +55 -4
  33. package/skills/brain-consolidate/SKILL.md +42 -0
  34. package/skills/brain-import/SKILL.md +56 -0
  35. package/skills/brain-memory/SKILL.md +73 -0
  36. package/skills/brain-review/SKILL.md +38 -0
  37. package/skills/code-review-organizer/SKILL.md +150 -0
  38. package/skills/review-items/SKILL.md +43 -0
  39. package/skills/todo-manager/SKILL.md +8 -0
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.gitStatus = gitStatus;
4
+ exports.syncGit = syncGit;
5
+ exports.gitPreview = gitPreview;
6
+ exports.pullOnStart = pullOnStart;
7
+ const fs = require("node:fs");
8
+ const path = require("node:path");
9
+ const node_child_process_1 = require("node:child_process");
10
+ const store_1 = require("./store");
11
+ const config_1 = require("./config");
12
+ function git(root, args) {
13
+ const result = (0, node_child_process_1.spawnSync)('git', ['-C', root, ...args], { encoding: 'utf8', shell: false, timeout: 60000,
14
+ env: { ...process.env, PATH: process.env.AGENT_RUN_REAL_PATH ?? process.env.PATH, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 16 * 1024 * 1024 });
15
+ if (result.error || result.status !== 0)
16
+ throw new Error(`git ${args[0]} failed: ${result.error?.message ?? result.stderr.trim()}`);
17
+ return result.stdout.trimEnd();
18
+ }
19
+ function requireRepository(store) {
20
+ if (fs.realpathSync(git(store.configRoot, ['rev-parse', '--show-toplevel'])) !== fs.realpathSync(store.configRoot)) {
21
+ throw new Error('Git sync requires the configuration directory itself to be the repository root.');
22
+ }
23
+ }
24
+ function gitStatus(store) {
25
+ if (!fs.existsSync(path.join(store.configRoot, '.git')))
26
+ return { state: 'uninitialized', files: [], conflicts: [], branch: '' };
27
+ requireRepository(store);
28
+ const conflicts = git(store.configRoot, ['diff', '--name-only', '--diff-filter=U', '-z']).split('\0').filter(Boolean);
29
+ const files = git(store.configRoot, ['status', '--porcelain', '-z']).split('\0').filter(Boolean);
30
+ return { state: conflicts.length ? 'conflicted' : files.length ? 'dirty' : 'clean', files, conflicts,
31
+ branch: git(store.configRoot, ['branch', '--show-current']) };
32
+ }
33
+ function syncableFiles(store) {
34
+ const folders = new Set([...Object.values(store_1.knowledgeDirectories), 'skills', 'todo', 'notes']);
35
+ const roots = [path.join(store.configRoot, 'global'), path.join(store.configRoot, 'default')];
36
+ roots.push(...(0, config_1.listBrainProjects)(store.configRoot).flatMap((project) => [store.safePath(project.profile), ...(project.pool ? [store.safePath('pools', project.pool)] : [])]));
37
+ if (store.profile && !store.profile.startsWith('projects/'))
38
+ roots.push(store.scopeDirectory('project'));
39
+ const files = [];
40
+ for (const root of roots) {
41
+ for (const folder of folders)
42
+ files.push(...store.files(path.join(root, folder)));
43
+ files.push(...store.files(path.join(root, 'templates'), { includeAllFiles: true }));
44
+ for (const name of ['config.yaml', 'project.md', 'review-history.jsonl', 'review-counters.json', 'knowledge-history.jsonl']) {
45
+ const file = store.safePath(root, name);
46
+ if (fs.existsSync(file))
47
+ files.push(file);
48
+ }
49
+ }
50
+ if (fs.existsSync(path.join(store.configRoot, '.git'))) {
51
+ const removable = roots.flatMap((root) => ['templates', 'notes', ...Object.values(store_1.knowledgeDirectories)].map((folder) => path.relative(store.configRoot, path.join(root, folder))));
52
+ const deleted = git(store.configRoot, ['ls-files', '--deleted', '-z', '--', ...removable]).split('\0').filter(Boolean);
53
+ files.push(...deleted.map((file) => store.safePath(file)));
54
+ }
55
+ const ignore = store.safePath('.gitignore');
56
+ if (fs.existsSync(ignore))
57
+ files.push(ignore);
58
+ return [...new Set(files.map((file) => path.relative(store.configRoot, file)))].sort();
59
+ }
60
+ function syncGit(store, action, message) {
61
+ return store.writeLocked(() => {
62
+ const steps = [];
63
+ try {
64
+ if (action === 'init') {
65
+ if (!fs.existsSync(path.join(store.configRoot, '.git')))
66
+ git(store.configRoot, ['init', '--initial-branch=main']);
67
+ return { ...gitStatus(store), steps: ['Configuration Git repository initialized.'] };
68
+ }
69
+ requireRepository(store);
70
+ const status = gitStatus(store);
71
+ if (status.state === 'conflicted')
72
+ throw new Error(`Resolve Git conflicts before syncing: ${status.conflicts.join(', ')}`);
73
+ if (action === 'save' || action === 'sync') {
74
+ if (message !== undefined && !message.trim())
75
+ throw new Error('The commit message must not be empty.');
76
+ if (git(store.configRoot, ['diff', '--cached', '--name-only']))
77
+ throw new Error('The Git index already has staged changes. Commit or unstage them before saving brain knowledge.');
78
+ const files = syncableFiles(store);
79
+ if (files.length)
80
+ git(store.configRoot, ['add', '--', ...files]);
81
+ const changed = git(store.configRoot, ['diff', '--cached', '--name-only', '-z']).split('\0').filter(Boolean);
82
+ if (changed.length) {
83
+ const commitMessage = message ?? `Update brain knowledge (${changed.length} ${changed.length === 1 ? 'file' : 'files'})`;
84
+ git(store.configRoot, ['commit', '-m', commitMessage]);
85
+ steps.push(`Saved ${changed.length} ${changed.length === 1 ? 'file' : 'files'} in commit ${git(store.configRoot, ['rev-parse', '--short', 'HEAD'])}: ${commitMessage}`);
86
+ }
87
+ else
88
+ steps.push('No local brain changes to save.');
89
+ }
90
+ if (action === 'pull' || action === 'sync') {
91
+ if (git(store.configRoot, ['diff', '--name-only']) || git(store.configRoot, ['diff', '--cached', '--name-only']))
92
+ throw new Error('Save or resolve local tracked configuration changes before pulling.');
93
+ try {
94
+ git(store.configRoot, ['-c', 'merge.autoStash=false', '-c', 'rebase.autoStash=false', 'pull', '--rebase']);
95
+ }
96
+ catch (error) {
97
+ const after = gitStatus(store);
98
+ if (after.state === 'conflicted')
99
+ throw new Error(`Pull stopped with conflicts: ${after.conflicts.join(', ')}. Resolve the rebase before syncing again.`);
100
+ throw new Error(`Pull failed: ${error instanceof Error ? error.message : String(error)}`);
101
+ }
102
+ steps.push('Pulled remote changes.');
103
+ }
104
+ if (action === 'push' || action === 'save' || action === 'sync') {
105
+ git(store.configRoot, ['push']);
106
+ steps.push('Push completed; remote is up to date.');
107
+ }
108
+ return { ...gitStatus(store), steps };
109
+ }
110
+ catch (error) {
111
+ throw new Error([...steps, error instanceof Error ? error.message : String(error)].join('\n'));
112
+ }
113
+ });
114
+ }
115
+ function gitPreview(store) {
116
+ return { status: gitStatus(store), files: syncableFiles(store) };
117
+ }
118
+ function pullOnStart(store) {
119
+ try {
120
+ return store.writeLocked(() => {
121
+ const status = gitStatus(store);
122
+ if (status.state !== 'clean')
123
+ return `Startup pull skipped: configuration is ${status.state}.`;
124
+ if (!status.branch)
125
+ return 'Startup pull skipped: detached HEAD.';
126
+ try {
127
+ git(store.configRoot, ['rev-parse', '--verify', '@{upstream}']);
128
+ }
129
+ catch {
130
+ return 'Startup pull skipped: no upstream branch.';
131
+ }
132
+ git(store.configRoot, ['-c', 'merge.autoStash=false', '-c', 'rebase.autoStash=false', 'pull', '--ff-only', '--no-rebase']);
133
+ return 'Startup pull completed.';
134
+ });
135
+ }
136
+ catch (error) {
137
+ return `Startup pull failed; using local configuration: ${error instanceof Error ? error.message : String(error)}`;
138
+ }
139
+ }
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GithubReviews = exports.reviewInput = void 0;
4
+ exports.githubReviews = githubReviews;
5
+ const fs = require("node:fs");
6
+ const node_crypto_1 = require("node:crypto");
7
+ const jsonc_parser_1 = require("jsonc-parser");
8
+ const zod_1 = require("zod");
9
+ const repositories_1 = require("./repositories");
10
+ const config_1 = require("./config");
11
+ const store_1 = require("./store");
12
+ const configSchema = zod_1.z.object({ backend: zod_1.z.literal('github'), repository: repositories_1.repositoryId.optional(),
13
+ tokenEnv: zod_1.z.string().regex(/^[A-Z_][A-Z0-9_]*$/).default('GITHUB_TOKEN'), writesEnabled: zod_1.z.boolean().default(false) }).strict();
14
+ exports.reviewInput = zod_1.z.object({ key: zod_1.z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/).max(200),
15
+ title: zod_1.z.string().trim().min(1).max(250), content: zod_1.z.string().trim().min(1).max(40000), severity: store_1.severitySchema,
16
+ applies_to: zod_1.z.array(zod_1.z.string().max(500)).max(100).default([]), confirmed: zod_1.z.literal(true) }).strict();
17
+ const metadata = zod_1.z.object({ key: zod_1.z.string(), severity: store_1.severitySchema, applies_to: zod_1.z.array(zod_1.z.string()) });
18
+ const issueSchema = zod_1.z.object({ number: zod_1.z.number().int().positive(), title: zod_1.z.string(), body: zod_1.z.string().nullable(),
19
+ state: zod_1.z.enum(['open', 'closed']), state_reason: zod_1.z.string().nullable().optional(), html_url: zod_1.z.string().url(),
20
+ updated_at: zod_1.z.string(), pull_request: zod_1.z.unknown().optional() });
21
+ const hash = (value) => (0, node_crypto_1.createHash)('sha256').update(value).digest('hex');
22
+ const start = '<!-- agent-mcp-review:start -->';
23
+ const end = '<!-- agent-mcp-review:end -->';
24
+ class GithubReviews {
25
+ constructor(store, config, repository) {
26
+ this.store = store;
27
+ this.config = config;
28
+ this.repository = repository;
29
+ }
30
+ async request(route, method = 'GET', body) {
31
+ const token = process.env[this.config.tokenEnv];
32
+ if (!token)
33
+ throw new Error('Set ' + this.config.tokenEnv + ' for GitHub reviews');
34
+ const response = await fetch('https://api.github.com/repos/' + this.repository + '/issues' + route, {
35
+ method, redirect: 'error', signal: AbortSignal.timeout(30000), headers: { accept: 'application/vnd.github+json',
36
+ 'content-type': 'application/json', 'user-agent': 'agent-brain', authorization: 'Bearer ' + token,
37
+ 'X-GitHub-Api-Version': '2026-03-10' }, ...(body ? { body: JSON.stringify(body) } : {})
38
+ });
39
+ if (!response.ok)
40
+ throw new Error('GitHub review request failed with HTTP ' + response.status);
41
+ const text = await response.text();
42
+ if (text.length > 4 * 1024 * 1024)
43
+ throw new Error('GitHub response exceeds 4 MiB');
44
+ return JSON.parse(text);
45
+ }
46
+ data(issue) {
47
+ if (issue.pull_request)
48
+ return null;
49
+ const body = issue.body ?? '';
50
+ const match = /<!-- agent-mcp-meta:([A-Za-z0-9_-]+) -->/.exec(body);
51
+ if (!match || !body.includes(start) || !body.includes(end))
52
+ return null;
53
+ let decoded;
54
+ try {
55
+ decoded = JSON.parse(Buffer.from(match[1], 'base64url').toString('utf8'));
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ const parsed = metadata.safeParse(decoded);
61
+ if (!parsed.success)
62
+ return null;
63
+ return { ...parsed.data, id: 'github:' + this.repository + '#' + issue.number, finding: '#' + issue.number,
64
+ title: issue.title, content: body, state: issue.state === 'open' ? 'open' : issue.state_reason === 'not_planned' ? 'wontfix' : 'fixed',
65
+ url: issue.html_url, revision: hash(JSON.stringify(issue)), backend: 'github' };
66
+ }
67
+ async list(state = 'open') {
68
+ const found = [];
69
+ for (let page = 1; page <= 100; page++) {
70
+ const issues = zod_1.z.array(issueSchema).parse(await this.request('?state=' + state + '&per_page=100&page=' + page));
71
+ for (const issue of issues) {
72
+ const item = this.data(issue);
73
+ if (item)
74
+ found.push(item);
75
+ }
76
+ if (issues.length < 100)
77
+ return found.sort((a, b) => ['critical', 'high', 'medium', 'low'].indexOf(a.severity) - ['critical', 'high', 'medium', 'low'].indexOf(b.severity));
78
+ }
79
+ throw new Error('GitHub review listing exceeds 100 pages; narrow the repository backlog before retrying');
80
+ }
81
+ number(id) {
82
+ const prefix = 'github:' + this.repository + '#';
83
+ const number = id.startsWith(prefix) ? id.slice(prefix.length) : id.replace(/^#/, '');
84
+ if (!/^[1-9][0-9]*$/.test(number))
85
+ throw new Error('Issue must belong to the configured repository');
86
+ return number;
87
+ }
88
+ async get(id) {
89
+ const item = this.data(issueSchema.parse(await this.request('/' + this.number(id))));
90
+ if (!item)
91
+ throw new Error('Issue is not an agent-mcp review finding');
92
+ return item;
93
+ }
94
+ async locked(work) {
95
+ if (!this.config.writesEnabled)
96
+ throw new Error('GitHub review writes are disabled; configure writesEnabled explicitly');
97
+ const lock = this.store.safePath('runtime', 'github-review.lock');
98
+ const descriptor = fs.openSync(lock, 'wx', 0o600);
99
+ try {
100
+ return await work();
101
+ }
102
+ finally {
103
+ fs.closeSync(descriptor);
104
+ fs.unlinkSync(lock);
105
+ }
106
+ }
107
+ block(input) {
108
+ if (input.content.includes('<!-- agent-mcp-'))
109
+ throw new Error('Finding content contains a reserved marker');
110
+ const encoded = Buffer.from(JSON.stringify({ key: input.key, severity: input.severity, applies_to: input.applies_to })).toString('base64url');
111
+ return start + '\n<!-- agent-mcp-meta:' + encoded + ' -->\nSeverity: ' + input.severity + '\n\n' + input.content + '\n' + end;
112
+ }
113
+ async create(input) {
114
+ input = exports.reviewInput.parse(input);
115
+ return this.locked(async () => {
116
+ const file = this.store.safePath('runtime', 'github-review-keys-' + hash(this.repository) + '.json');
117
+ const keys = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
118
+ if (Object.prototype.hasOwnProperty.call(keys, input.key)) {
119
+ const existing = await this.get(keys[input.key]);
120
+ if (existing.key !== input.key)
121
+ throw new Error('Stored review retry key does not match its GitHub issue');
122
+ return { ...existing, created: false };
123
+ }
124
+ const existing = (await this.list('all')).find((item) => item.key === input.key);
125
+ if (existing)
126
+ return { ...existing, created: false };
127
+ const item = this.data(issueSchema.parse(await this.request('', 'POST', { title: input.title, body: this.block(input) })));
128
+ if (!item)
129
+ throw new Error('GitHub returned an invalid review finding');
130
+ Object.defineProperty(keys, input.key, { value: item.id, enumerable: true, configurable: true, writable: true });
131
+ fs.writeFileSync(file + '.tmp', JSON.stringify(keys), { mode: 0o600 });
132
+ fs.renameSync(file + '.tmp', file);
133
+ return { ...item, created: true };
134
+ });
135
+ }
136
+ async update(id, revision, changes) {
137
+ return this.locked(async () => {
138
+ const current = await this.get(id);
139
+ if (current.revision !== revision)
140
+ throw new Error('GitHub finding changed; read it again before updating');
141
+ const managed = current.content.slice(current.content.indexOf(start), current.content.indexOf(end));
142
+ const block = this.block({ ...current, ...changes, content: changes.content ?? managed.slice(managed.indexOf('\n\n') + 2).trim() });
143
+ const body = current.content.slice(0, current.content.indexOf(start)) + block + current.content.slice(current.content.indexOf(end) + end.length);
144
+ const issue = issueSchema.parse(await this.request('/' + this.number(id), 'PATCH', { title: changes.title ?? current.title, body }));
145
+ return this.data(issue);
146
+ });
147
+ }
148
+ async resolve(id, revision, state, reason) {
149
+ return this.locked(async () => {
150
+ const current = await this.get(id);
151
+ if (current.revision !== revision)
152
+ throw new Error('GitHub finding changed; read it again before closing');
153
+ const issue = issueSchema.parse(await this.request('/' + this.number(id), 'PATCH', {
154
+ state: 'closed', state_reason: state === 'fixed' ? 'completed' : 'not_planned', body: current.content + '\n\nResolution: ' + reason
155
+ }));
156
+ return this.data(issue);
157
+ });
158
+ }
159
+ }
160
+ exports.GithubReviews = GithubReviews;
161
+ function githubReviews(store) {
162
+ const file = store.safePath(store.profile ?? 'default', 'review.jsonc');
163
+ if (!fs.existsSync(file))
164
+ return null;
165
+ const errors = [];
166
+ const config = configSchema.parse((0, jsonc_parser_1.parse)(store.read(file), errors));
167
+ if (errors.length)
168
+ throw new Error('Invalid review.jsonc');
169
+ const project = (0, config_1.listBrainProjects)(store.configRoot).find((item) => item.profile === store.profile);
170
+ const repository = config.repository ?? (project?.repository?.url ? (0, repositories_1.githubRepository)(project.repository.url) : null);
171
+ if (!repository)
172
+ throw new Error('GitHub reviews need an explicit repository or a registered GitHub remote');
173
+ return new GithubReviews(store, config, repository);
174
+ }
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initializeBrain = initializeBrain;
4
+ exports.inspectProject = inspectProject;
5
+ exports.createBrainProject = createBrainProject;
6
+ const fs = require("node:fs");
7
+ const path = require("node:path");
8
+ const node_child_process_1 = require("node:child_process");
9
+ const promises_1 = require("node:readline/promises");
10
+ const yaml_1 = require("yaml");
11
+ const config_tree_1 = require("@technomoron/agent-run/dist/config-tree");
12
+ const manifest_1 = require("@technomoron/agent-run/dist/manifest");
13
+ const project_1 = require("@technomoron/agent-run/dist/project");
14
+ const utils_1 = require("@technomoron/agent-run/dist/utils");
15
+ const config_1 = require("./config");
16
+ const store_1 = require("./store");
17
+ const built_in_skills_1 = require("./built-in-skills");
18
+ function initializeBrain(configRoot, cwd) {
19
+ if ((0, utils_1.isSamePathOrDescendant)(path.resolve(configRoot), (0, project_1.findProjectRoot)(cwd)))
20
+ throw new Error('Brain configuration must live outside the source repository.');
21
+ (0, config_tree_1.ensureConfigRootLayout)(configRoot);
22
+ const file = path.join(configRoot, 'brain.jsonc');
23
+ if (!fs.existsSync(file))
24
+ fs.writeFileSync(file, '{\n "enabled": true,\n "contextBudget": 16000\n}\n', { mode: 0o600, flag: 'wx' });
25
+ (0, config_tree_1.ensureDefaultGlobalTemplates)(configRoot);
26
+ (0, config_tree_1.ensureConfigRootGitignore)(configRoot);
27
+ (0, manifest_1.ensureRootDefaultsFile)(configRoot);
28
+ (0, manifest_1.createProfileMarker)(path.join(configRoot, 'default'));
29
+ for (const project of (0, config_1.listBrainProjects)(configRoot))
30
+ (0, manifest_1.createProfileMarker)(path.join(configRoot, project.profile));
31
+ const store = new store_1.BrainStore(configRoot, cwd);
32
+ try {
33
+ store.writeLocked(() => {
34
+ const directories = new Set([
35
+ store.safePath('global'), store.safePath('default'),
36
+ ...(0, config_1.listBrainProjects)(configRoot).map((project) => store.safePath(project.profile)),
37
+ ...(0, config_1.listBrainProjects)(configRoot).flatMap((project) => project.pool ? [store.safePath('pools', project.pool)] : []),
38
+ ...store.scopes.map((scope) => scope.directory)
39
+ ]);
40
+ for (const directory of directories)
41
+ initializeScopeDirectories(store, directory);
42
+ });
43
+ for (const [name, skill] of Object.entries((0, built_in_skills_1.readBuiltInSkills)())) {
44
+ const destination = store.safePath('global', 'skills', name, 'SKILL.md');
45
+ if (!fs.existsSync(destination))
46
+ store.atomicWrite(destination, `---\n${(0, yaml_1.stringify)({ name, description: skill.description })}---\n\n${skill.content}\n`);
47
+ }
48
+ }
49
+ finally {
50
+ store.close();
51
+ }
52
+ }
53
+ function initializeScopeDirectories(store, directory) {
54
+ for (const folder of [...Object.values(store_1.knowledgeDirectories), 'skills', 'todo', 'templates']) {
55
+ store.directory(directory, folder);
56
+ }
57
+ }
58
+ function inspectProject(cwd) {
59
+ const root = (0, project_1.findProjectRoot)(cwd);
60
+ const git = (0, node_child_process_1.spawnSync)('git', ['-C', root, 'config', '--get', 'remote.origin.url'], { encoding: 'utf8', shell: false });
61
+ const languages = [['package.json', 'JavaScript/TypeScript'], ['pyproject.toml', 'Python'], ['go.mod', 'Go'], ['Cargo.toml', 'Rust']]
62
+ .filter(([file]) => fs.existsSync(path.join(root, file))).map(([, language]) => language);
63
+ let scripts = {};
64
+ const pkg = path.join(root, 'package.json');
65
+ if (fs.existsSync(pkg))
66
+ scripts = JSON.parse(fs.readFileSync(pkg, 'utf8')).scripts ?? {};
67
+ return { root, repository: git.status === 0 ? git.stdout.trim() : undefined, languages,
68
+ packageManager: fs.existsSync(path.join(root, 'pnpm-lock.yaml')) ? 'pnpm' : fs.existsSync(pkg) ? 'npm' : undefined,
69
+ documents: ['README.md', 'AGENTS.md', 'CLAUDE.md'].filter((file) => fs.existsSync(path.join(root, file))), scripts };
70
+ }
71
+ async function createBrainProject(configRoot, cwd, name, mode) {
72
+ config_1.projectConfigSchema.shape.name.parse(name);
73
+ const detected = inspectProject(cwd);
74
+ let root = String(detected.root);
75
+ let description = '';
76
+ let displayName = name;
77
+ let agent = 'codex';
78
+ let conventions = '';
79
+ let constraints = '';
80
+ let architecture = '';
81
+ if (mode !== 'quick') {
82
+ if (!process.stdin.isTTY)
83
+ throw new Error('Interactive project creation requires a terminal; use --quick for detected defaults.');
84
+ process.stdout.write(`${JSON.stringify(detected, null, 2)}\n`);
85
+ const prompt = (0, promises_1.createInterface)({ input: process.stdin, output: process.stdout });
86
+ try {
87
+ root = path.resolve((await prompt.question(`Source root [${root}]: `)).trim() || root);
88
+ description = (await prompt.question('Description (optional): ')).trim();
89
+ if (mode === 'guided') {
90
+ displayName = (await prompt.question(`Display name [${name}]: `)).trim() || name;
91
+ agent = (await prompt.question('Default agent [codex]: ')).trim() || 'codex';
92
+ architecture = (await prompt.question('Architecture summary (optional): ')).trim();
93
+ constraints = (await prompt.question('Constraints (optional): ')).trim();
94
+ conventions = (await prompt.question('Conventions and review rules (optional): ')).trim();
95
+ }
96
+ if (/^n/i.test((await prompt.question('Create project with these values? [Y/n]: ')).trim()))
97
+ return;
98
+ }
99
+ finally {
100
+ prompt.close();
101
+ }
102
+ }
103
+ if (!fs.statSync(root, { throwIfNoEntry: false })?.isDirectory())
104
+ throw new Error(`Source root does not exist: ${root}`);
105
+ const config = config_1.projectConfigSchema.parse({ name, display_name: displayName, roots: [root], description,
106
+ ...(detected.repository && root === detected.root ? { repository: { url: detected.repository } } : {}), agent: { default: agent } });
107
+ if ((0, config_1.listBrainProjects)(configRoot).some((project) => project.name === name || project.roots.some((existing) => path.resolve(existing) === root)))
108
+ throw new Error('A project with this name or source root already exists.');
109
+ const directory = path.join(configRoot, 'projects', name);
110
+ if (fs.existsSync(directory))
111
+ throw new Error(`Project directory already exists: ${directory}`);
112
+ initializeBrain(configRoot, cwd);
113
+ const store = new store_1.BrainStore(configRoot, cwd);
114
+ try {
115
+ store.writeLocked(() => {
116
+ initializeScopeDirectories(store, directory);
117
+ (0, manifest_1.createProfileMarker)(directory);
118
+ store.atomicWrite(path.join(directory, 'config.yaml'), (0, yaml_1.stringify)(config));
119
+ store.atomicWrite(path.join(directory, 'project.md'), `# ${displayName}\n\n${description}\n`);
120
+ });
121
+ }
122
+ finally {
123
+ store.close();
124
+ }
125
+ const projectStore = new store_1.BrainStore(configRoot, root);
126
+ try {
127
+ for (const [type, title, content] of [['observation', 'Architecture summary', architecture], ['constraint', 'Project constraints', constraints], ['convention', 'Conventions and review rules', conventions]]) {
128
+ if (content)
129
+ projectStore.remember({ scope: 'project', type, title, content, authority: 'user' });
130
+ }
131
+ }
132
+ finally {
133
+ projectStore.close();
134
+ }
135
+ process.stdout.write(`Created ${name} at ${directory}\n`);
136
+ }
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.remoteConfigSchema = exports.permission = void 0;
4
+ exports.readRemoteConfig = readRemoteConfig;
5
+ exports.validateRepositoryRoots = validateRepositoryRoots;
6
+ exports.allowedGrant = allowedGrant;
7
+ exports.repositoryPermissions = repositoryPermissions;
8
+ exports.toolPermission = toolPermission;
9
+ const fs = require("node:fs");
10
+ const path = require("node:path");
11
+ const jsonc_parser_1 = require("jsonc-parser");
12
+ const zod_1 = require("zod");
13
+ const repositories_1 = require("./repositories");
14
+ const envName = zod_1.z.string().regex(/^[A-Z_][A-Z0-9_]*$/);
15
+ const absolute = zod_1.z.string().refine(path.isAbsolute, 'Use an absolute path');
16
+ const https = zod_1.z.string().url().refine((value) => { const u = new URL(value); return u.protocol === 'https:' && !u.username && !u.password && !u.search && !u.hash; });
17
+ exports.permission = zod_1.z.enum(['read', 'write', 'review']);
18
+ exports.remoteConfigSchema = zod_1.z.object({
19
+ issuer: https, resource: https, runtime: absolute,
20
+ dataRoot: absolute.optional(),
21
+ gitSync: zod_1.z.object({ catalog: absolute, state: absolute }).strict().optional(),
22
+ accessSecretEnv: envName.default('MCP_OAUTH_ACCESS_SECRET'), refreshSecretEnv: envName.default('MCP_OAUTH_REFRESH_SECRET'),
23
+ listen: zod_1.z.object({ host: zod_1.z.literal('127.0.0.1').default('127.0.0.1'), port: zod_1.z.number().int().min(1).max(65535).default(3000), socket: absolute.optional() }).strict().default({ host: '127.0.0.1', port: 3000 }),
24
+ users: zod_1.z.array(zod_1.z.object({ subject: zod_1.z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/), login: zod_1.z.string().min(1).max(200),
25
+ kind: zod_1.z.enum(['human', 'service']).default('human'), passwordHashEnv: envName.optional(), totpSecretEnv: envName.optional(), disabled: zod_1.z.boolean().default(false) }).strict()),
26
+ clients: zod_1.z.array(zod_1.z.object({ id: zod_1.z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/), kind: zod_1.z.enum(['public', 'confidential', 'service']).default('public'),
27
+ secretEnv: envName.optional(), subject: zod_1.z.string().optional(), redirectUris: zod_1.z.array(zod_1.z.string().url()).default([]),
28
+ repos: zod_1.z.array(repositories_1.repositoryPattern).min(1), permissions: zod_1.z.array(exports.permission).min(1) }).strict()),
29
+ access: zod_1.z.array(zod_1.z.object({ subject: zod_1.z.string(), repos: zod_1.z.array(repositories_1.repositoryPattern).min(1), permissions: zod_1.z.array(exports.permission).min(1) }).strict()),
30
+ groups: zod_1.z.array(zod_1.z.object({ id: zod_1.z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/), configRoot: absolute }).strict()).default([]),
31
+ repositories: zod_1.z.array(zod_1.z.object({ id: repositories_1.repositoryId, configRoot: absolute, cwd: absolute, group: zod_1.z.string().optional() }).strict())
32
+ }).strict();
33
+ function readRemoteConfig(file) {
34
+ const errors = [];
35
+ const value = (0, jsonc_parser_1.parse)(fs.readFileSync(file, 'utf8'), errors, { allowTrailingComma: true });
36
+ if (errors.length)
37
+ throw new Error('Invalid remote config JSONC');
38
+ const config = exports.remoteConfigSchema.parse(value);
39
+ for (const values of [config.users.map((u) => u.subject), config.users.map((u) => u.login), config.clients.map((c) => c.id), config.repositories.map((r) => r.id)]) {
40
+ if (new Set(values).size !== values.length)
41
+ throw new Error('Remote identities, logins, clients and repository IDs must be unique');
42
+ }
43
+ for (const user of config.users) {
44
+ if (config.users.some((other) => other.subject !== user.subject && other.subject === user.login))
45
+ throw new Error('Logins must not alias another subject');
46
+ if (!user.disabled && user.kind === 'human' && !user.passwordHashEnv)
47
+ throw new Error('Human users require passwordHashEnv');
48
+ }
49
+ for (const client of config.clients) {
50
+ if (client.kind !== 'public' && !client.secretEnv)
51
+ throw new Error('Confidential and service clients require secretEnv');
52
+ if (client.kind === 'public' && client.secretEnv)
53
+ throw new Error('Public clients cannot hold a secret');
54
+ if (client.kind !== 'service' && !client.redirectUris.length)
55
+ throw new Error('Interactive clients need a registered redirect URI');
56
+ if (client.kind === 'service' && !config.users.some((u) => u.subject === client.subject && u.kind === 'service'))
57
+ throw new Error('Service client needs a configured service subject');
58
+ }
59
+ validateRepositoryRoots(config);
60
+ if (config.access.some((rule) => !config.users.some((user) => user.subject === rule.subject)))
61
+ throw new Error('Access rule references an unknown subject');
62
+ return config;
63
+ }
64
+ /** A declared group may share a root; unrelated groups and repositories must remain isolated. */
65
+ function validateRepositoryRoots(config, canonical = false) {
66
+ if (config.dataRoot) {
67
+ const resolve = (value) => canonical ? fs.realpathSync(value) : path.resolve(value);
68
+ if (config.repositories.some((repo) => resolve(repo.configRoot) !== resolve(config.dataRoot)) || config.groups.some((group) => resolve(group.configRoot) !== resolve(config.dataRoot)))
69
+ throw new Error('All repositories and pools must use the central dataRoot');
70
+ if (new Set(config.groups.map((group) => group.id)).size !== config.groups.length || config.repositories.some((repo) => repo.group && !config.groups.some((group) => group.id === repo.group)))
71
+ throw new Error('Pool registration is invalid');
72
+ return;
73
+ }
74
+ if (new Set(config.groups.map((g) => g.id)).size !== config.groups.length)
75
+ throw new Error('Group IDs must be unique');
76
+ const resolve = (value) => canonical ? fs.realpathSync(value) : path.resolve(value);
77
+ for (const repo of config.repositories)
78
+ if (repo.group !== undefined) {
79
+ const group = config.groups.find((g) => g.id === repo.group);
80
+ if (!group || resolve(repo.configRoot) !== resolve(group.configRoot))
81
+ throw new Error('Grouped repository must use its declared group data root');
82
+ }
83
+ const roots = [...config.groups.map((g) => ({ identity: 'group:' + g.id, root: resolve(g.configRoot) })),
84
+ ...config.repositories.filter((r) => !r.group).map((r) => ({ identity: 'repo:' + r.id, root: resolve(r.configRoot) }))];
85
+ for (let i = 0; i < roots.length; i++)
86
+ for (let j = i + 1; j < roots.length; j++) {
87
+ const a = roots[i].root, b = roots[j].root;
88
+ const overlaps = (from, to) => { const relative = path.relative(from, to); return !relative || (relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative)); };
89
+ if (overlaps(a, b) || overlaps(b, a))
90
+ throw new Error('Repository and group data roots must be separate and non-overlapping');
91
+ }
92
+ }
93
+ function allowedGrant(config, subject, clientId, scopes) {
94
+ const user = config.users.find((u) => u.subject === subject && !u.disabled);
95
+ const client = config.clients.find((c) => c.id === clientId);
96
+ if (!user || !client || (user.kind === 'service' ? client.kind !== 'service' || client.subject !== subject : client.kind === 'service'))
97
+ return false;
98
+ const operations = scopes.filter((scope) => exports.permission.safeParse(scope).success);
99
+ const repos = scopes.filter((scope) => scope.startsWith('repo:')).map((scope) => scope.slice(5));
100
+ if (!operations.includes('read') || !repos.length || scopes.length !== operations.length + repos.length)
101
+ return false;
102
+ return repos.every((repo) => repositories_1.repositoryPattern.safeParse(repo).success && client.repos.some((pattern) => (0, repositories_1.coversPattern)(pattern, repo)) &&
103
+ operations.every((operation) => client.permissions.includes(operation) && config.access.some((rule) => rule.subject === subject &&
104
+ rule.permissions.includes(operation) && rule.repos.some((pattern) => (0, repositories_1.coversPattern)(pattern, repo)))));
105
+ }
106
+ function repositoryPermissions(config, subject, clientId, scopes, repo) {
107
+ const client = config.clients.find((c) => c.id === clientId);
108
+ const user = config.users.find((u) => u.subject === subject && !u.disabled);
109
+ if (!config.repositories.some((r) => r.id === repo) || !user || !client ||
110
+ (user.kind === 'service' ? client.kind !== 'service' || client.subject !== subject : client.kind === 'service') ||
111
+ !client.repos.some((p) => (0, repositories_1.matchesRepository)(p, repo)) || !scopes.some((scope) => scope.startsWith('repo:') && (0, repositories_1.matchesRepository)(scope.slice(5), repo)))
112
+ return new Set();
113
+ return new Set(config.access.filter((rule) => rule.subject === subject && rule.repos.some((p) => (0, repositories_1.matchesRepository)(p, repo)))
114
+ .flatMap((rule) => rule.permissions).filter((op) => scopes.includes(op) && client.permissions.includes(op)));
115
+ }
116
+ const readTools = new Set(['list_repositories', 'list_repository_groups', 'brain_status', 'get_context', 'search_knowledge', 'list_knowledge', 'knowledge_history', 'get_knowledge', 'list_skills', 'get_skill', 'review_context', 'review_list', 'review_get', 'review_history', 'todo_list', 'todo_get']);
117
+ const reviewTools = new Set(['review_create', 'review_update', 'resolve_review']);
118
+ function toolPermission(name) {
119
+ if (readTools.has(name))
120
+ return 'read';
121
+ if (reviewTools.has(name))
122
+ return 'review';
123
+ if (['sync_status', 'todo_import', 'todo_sync', 'review_archive'].includes(name))
124
+ return null;
125
+ return ['brain_sync', 'brain_flush', 'sync', 'flush', 'remember', 'amend_knowledge', 'promote', 'deprecate_knowledge', 'todo_add', 'todo_update', 'todo_complete'].includes(name) ? 'write' : null;
126
+ }