@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.
- package/CHANGES.md +26 -0
- package/README.md +117 -44
- package/dist/brain/built-in-skills.js +2 -0
- package/dist/brain/cli.js +8 -0
- package/dist/brain/config.js +7 -0
- package/dist/brain/connectors.js +2 -0
- package/dist/brain/consolidation.js +4 -0
- package/dist/brain/git.js +9 -2
- package/dist/brain/github-issues.js +332 -0
- package/dist/brain/github-reviews.js +38 -7
- package/dist/brain/issue-configuration.js +382 -0
- package/dist/brain/issue-tools.js +77 -0
- package/dist/brain/projects.js +4 -6
- package/dist/brain/remote-policy.js +16 -3
- package/dist/brain/remote-server.js +67 -12
- package/dist/brain/repositories.js +3 -0
- package/dist/brain/repository-discovery.js +22 -1
- package/dist/brain/server.js +17 -3
- package/dist/brain/skills.js +11 -0
- package/dist/brain/store.js +36 -1
- package/dist/brain/todos.js +10 -1
- package/dist/brain/windows-pipe.js +2 -1
- package/dist/version.js +1 -4
- package/examples/remote.jsonc +1 -1
- package/ops/brain-pipe-security.ps1 +40 -0
- package/ops/config-deploy-entry.sh +1 -1
- package/ops/config-deploy-root.cjs +14 -6
- package/ops/config-deploy.cjs +16 -8
- package/ops/config-policy.cjs +37 -1
- package/ops/config-sync.cjs +34 -1
- package/ops/layout.cjs +13 -0
- package/package.json +9 -6
- package/skills/brain-consolidate/README.md +5 -0
- package/skills/brain-import/README.md +5 -0
- package/skills/brain-memory/README.md +5 -0
- package/skills/brain-memory/SKILL.md +7 -3
- package/skills/code-review/README.md +7 -0
- package/skills/code-review/SKILL.md +58 -0
- package/skills/git-workflow/README.md +5 -0
- package/skills/git-workflow/SKILL.md +14 -0
- package/skills/node-cleanup/README.md +5 -0
- package/skills/node-cleanup/SKILL.md +239 -0
- package/skills/node-cleanup/agents/openai.yaml +4 -0
- package/skills/package-integrity-check/README.md +5 -0
- package/skills/package-integrity-check/SKILL.md +27 -0
- package/skills/todo-manager/README.md +5 -0
- package/skills/todo-manager/SKILL.md +13 -3
- package/skills/unslop/README.md +5 -0
- package/skills/unslop/SKILL.md +180 -0
- package/skills/unslop/agents/openai.yaml +4 -0
- package/skills/brain-review/SKILL.md +0 -38
- package/skills/code-review-organizer/SKILL.md +0 -150
- package/skills/review-items/SKILL.md +0 -43
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.IssueConfiguration = exports.reconciliationSettings = exports.issueStandardSchema = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const zod_1 = require("zod");
|
|
6
|
+
const github_issues_1 = require("./github-issues");
|
|
7
|
+
const repositories_1 = require("./repositories");
|
|
8
|
+
const metadata = zod_1.z.object({ description: zod_1.z.string().max(1000), color: zod_1.z.string() }).strict();
|
|
9
|
+
const labelDefaults = {
|
|
10
|
+
'Code Review': { description: 'Finding discovered during code review', color: '5319e7' },
|
|
11
|
+
'Bug Report': { description: 'Reported defect', color: 'd73a4a' },
|
|
12
|
+
'Feature Request': { description: 'Requested new capability', color: 'a2eeef' },
|
|
13
|
+
'ToDo': { description: 'Manual task or follow-up work', color: '0075ca' },
|
|
14
|
+
'Question': { description: 'Question requiring clarification', color: 'd876e3' }
|
|
15
|
+
};
|
|
16
|
+
const typeDefaults = {
|
|
17
|
+
Bug: { description: 'A defect', color: 'red' }, Security: { description: 'A vulnerability or security weakness', color: 'red' },
|
|
18
|
+
Feature: { description: 'A requested capability', color: 'blue' }, Task: { description: 'A specific piece of work', color: 'yellow' },
|
|
19
|
+
Inconsistency: { description: 'Contradictory behavior or configuration', color: 'orange' },
|
|
20
|
+
Question: { description: 'A question requiring an answer', color: 'purple' }, Documentation: { description: 'Work to correct or improve documentation', color: 'blue' }
|
|
21
|
+
};
|
|
22
|
+
const colors = ['pink', 'red', 'yellow', 'green'];
|
|
23
|
+
const priorityOptions = github_issues_1.issuePriority.options.map((name, index) => ({ name, color: colors[index], priority: index + 1 }));
|
|
24
|
+
exports.issueStandardSchema = zod_1.z.object({
|
|
25
|
+
labels: zod_1.z.record(github_issues_1.issueOrigin, metadata.extend({ color: zod_1.z.string().regex(/^[a-fA-F0-9]{6}$/) })).default(labelDefaults),
|
|
26
|
+
types: zod_1.z.record(github_issues_1.issueType, metadata.extend({ color: zod_1.z.enum(['gray', 'blue', 'green', 'yellow', 'orange', 'red', 'pink', 'purple']) })).default(typeDefaults),
|
|
27
|
+
priority_description: zod_1.z.string().max(1000).default('Current importance of the issue')
|
|
28
|
+
}).strict();
|
|
29
|
+
const classification = zod_1.z.object({ origin: github_issues_1.issueOrigin.optional(), type: github_issues_1.issueType.optional(), priority: github_issues_1.issuePriority.optional() }).strict();
|
|
30
|
+
exports.reconciliationSettings = zod_1.z.object({
|
|
31
|
+
defaults: classification.default({}),
|
|
32
|
+
issue_overrides: zod_1.z.record(zod_1.z.string().regex(/^[1-9][0-9]*$/), classification).default({}),
|
|
33
|
+
label_migrations: zod_1.z.record(zod_1.z.string(), github_issues_1.issueOrigin.nullable()).default({}),
|
|
34
|
+
type_migrations: zod_1.z.record(zod_1.z.string(), github_issues_1.issueType).default({}),
|
|
35
|
+
priority_migrations: zod_1.z.record(zod_1.z.string(), github_issues_1.issuePriority).default({}),
|
|
36
|
+
remove_fields: zod_1.z.array(zod_1.z.string().min(1)).max(25).default(['Severity']).refine(values => !values.some(value => value.toLowerCase() === 'priority'), 'Priority cannot be removed'),
|
|
37
|
+
field_migrations: zod_1.z.record(zod_1.z.string(), zod_1.z.record(zod_1.z.string(), github_issues_1.issuePriority.nullable())).default({}),
|
|
38
|
+
prune_types: zod_1.z.boolean().default(true)
|
|
39
|
+
}).strict();
|
|
40
|
+
const labelSchema = zod_1.z.object({ id: zod_1.z.number().int().optional(), name: zod_1.z.string(), color: zod_1.z.string(), description: zod_1.z.string().nullable() });
|
|
41
|
+
const typeSchema = labelSchema.extend({ id: zod_1.z.number().int(), is_enabled: zod_1.z.boolean().optional() });
|
|
42
|
+
const optionSchema = zod_1.z.object({ id: zod_1.z.number().int(), name: zod_1.z.string(), color: zod_1.z.string(), priority: zod_1.z.number().optional() });
|
|
43
|
+
const fieldSchema = zod_1.z.object({ id: zod_1.z.number().int(), node_id: zod_1.z.string(), name: zod_1.z.string(), description: zod_1.z.string().nullable().optional(),
|
|
44
|
+
data_type: zod_1.z.string(), options: zod_1.z.array(optionSchema).optional() });
|
|
45
|
+
const fieldValue = zod_1.z.object({ issue_field_id: zod_1.z.number().optional(), issue_field_name: zod_1.z.string(), value: zod_1.z.unknown().optional(),
|
|
46
|
+
single_select_option: zod_1.z.object({ id: zod_1.z.number().optional(), name: zod_1.z.string() }).nullable().optional() }).passthrough();
|
|
47
|
+
// Read only explicit record entries, including when a GitHub name resembles an Object prototype property.
|
|
48
|
+
const own = (record, name) => Object.prototype.hasOwnProperty.call(record, name) ? record[name] : undefined;
|
|
49
|
+
// Canonicalize objects so preview revisions do not depend on API property order.
|
|
50
|
+
function canonical(value) {
|
|
51
|
+
if (Array.isArray(value))
|
|
52
|
+
return value.map(canonical);
|
|
53
|
+
if (value && typeof value === 'object')
|
|
54
|
+
return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)]));
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
// Hash a deterministic preview or relevant issue values.
|
|
58
|
+
const digest = (value) => (0, node_crypto_1.createHash)('sha256').update(JSON.stringify(canonical(value))).digest('hex');
|
|
59
|
+
// Normalize only case-insensitive classifications changed by definition renames during apply.
|
|
60
|
+
const migrationRevision = (row) => digest({ ...issueState(row), labels: row.labels.map(value => value.name.toLowerCase()).sort(), type: row.type?.name.toLowerCase() ?? null,
|
|
61
|
+
fields: zod_1.z.array(fieldValue).parse(row.issue_field_values ?? []).map(value => ({ name: value.issue_field_name.toLowerCase() === 'priority' ? 'Priority' : value.issue_field_name,
|
|
62
|
+
value: value.issue_field_name.toLowerCase() === 'priority' ? storedValue(value).toLowerCase() : storedValue(value) })).sort((a, b) => a.name.localeCompare(b.name)) });
|
|
63
|
+
// Restrict issue comparisons to data this reconciliation may change.
|
|
64
|
+
const issueState = (row) => ({ number: row.number, labels: row.labels.map(value => value.name).sort(), type: row.type?.name ?? null,
|
|
65
|
+
fields: zod_1.z.array(fieldValue).parse(row.issue_field_values ?? []).map(value => ({ name: value.issue_field_name, value: storedValue(value) })).sort((a, b) => a.name.localeCompare(b.name)) });
|
|
66
|
+
// Interpret a stored custom field value without losing the source value shown in a preview.
|
|
67
|
+
function storedValue(value) {
|
|
68
|
+
return value.single_select_option?.name ?? (typeof value.value === 'string' ? value.value : JSON.stringify(value.value) ?? 'null');
|
|
69
|
+
}
|
|
70
|
+
class IssueConfiguration {
|
|
71
|
+
// Bind deterministic reconciliation to a repository and an exhaustive supported standard.
|
|
72
|
+
constructor(github, standard = {}) {
|
|
73
|
+
this.github = github;
|
|
74
|
+
this.standard = exports.issueStandardSchema.parse(standard);
|
|
75
|
+
this.owner = github.repository.split('/')[0];
|
|
76
|
+
}
|
|
77
|
+
// Page without silent truncation; an incomplete inventory must never authorize a removal.
|
|
78
|
+
async all(route) {
|
|
79
|
+
const result = [];
|
|
80
|
+
for (let page = 1; page <= 100; page++) {
|
|
81
|
+
const rows = zod_1.z.array(zod_1.z.unknown()).parse(await this.github.configurationRequest(route + (route.includes('?') ? '&' : '?') + 'per_page=100&page=' + page));
|
|
82
|
+
result.push(...rows);
|
|
83
|
+
if (rows.length < 100)
|
|
84
|
+
return result;
|
|
85
|
+
}
|
|
86
|
+
throw new Error('Inventory exceeds 100 pages: ' + route);
|
|
87
|
+
}
|
|
88
|
+
// Reject duplicate issue pages instead of treating a moving pagination window as a complete inventory.
|
|
89
|
+
async allIssues(repository) {
|
|
90
|
+
const rows = zod_1.z.array(github_issues_1.githubIssueSchema).parse(await this.all('/repos/' + repository + '/issues?state=all&sort=created&direction=asc'));
|
|
91
|
+
if (new Set(rows.map(value => value.number)).size !== rows.length)
|
|
92
|
+
throw new Error('Issue inventory changed during pagination; preview again');
|
|
93
|
+
return rows.sort((a, b) => a.number - b.number);
|
|
94
|
+
}
|
|
95
|
+
// Read repository definitions and all issue states, recording capability failures explicitly.
|
|
96
|
+
async inventory() {
|
|
97
|
+
const state = { labels: [], types: [], fields: [], issues: [], outside: [], errors: [] };
|
|
98
|
+
try {
|
|
99
|
+
state.labels = zod_1.z.array(labelSchema).parse(await this.all('/repos/' + this.github.repository + '/labels')).sort((a, b) => a.name.localeCompare(b.name));
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
state.errors.push('Repository labels unavailable: ' + String(error));
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
state.types = zod_1.z.array(typeSchema).parse(await this.github.configurationRequest('/orgs/' + this.owner + '/issue-types')).sort((a, b) => a.name.localeCompare(b.name));
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
state.errors.push('Organisation issue types unavailable: ' + String(error));
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
state.fields = zod_1.z.array(fieldSchema).parse(await this.github.configurationRequest('/orgs/' + this.owner + '/issue-fields')).sort((a, b) => a.name.localeCompare(b.name));
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
state.errors.push('Organisation issue fields unavailable: ' + String(error));
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
state.issues = await this.allIssues(this.github.repository);
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
state.errors.push('Repository issue inventory unavailable: ' + String(error));
|
|
121
|
+
}
|
|
122
|
+
return state;
|
|
123
|
+
}
|
|
124
|
+
// Compare definitions without changing unrelated organisation fields or field visibility.
|
|
125
|
+
operations(state, settings) {
|
|
126
|
+
const result = [];
|
|
127
|
+
for (const [name, desired] of Object.entries(this.standard.labels)) {
|
|
128
|
+
const current = state.labels.find(value => value.name.toLowerCase() === name.toLowerCase());
|
|
129
|
+
if (!current || current.name !== name || current.color.toLowerCase() !== desired.color.toLowerCase() || current.description !== desired.description)
|
|
130
|
+
result.push({ resource: 'label', action: current ? 'update' : 'create', name, before: current, after: { name, ...desired } });
|
|
131
|
+
}
|
|
132
|
+
for (const current of state.labels)
|
|
133
|
+
if (!github_issues_1.issueOrigin.options.some(name => name.toLowerCase() === current.name.toLowerCase()))
|
|
134
|
+
result.push({ resource: 'label', action: 'delete', name: current.name, before: current });
|
|
135
|
+
for (const [name, desired] of Object.entries(this.standard.types)) {
|
|
136
|
+
const current = state.types.find(value => value.name.toLowerCase() === name.toLowerCase());
|
|
137
|
+
if (!current || current.name !== name || current.is_enabled === false || current.color !== desired.color || current.description !== desired.description)
|
|
138
|
+
result.push({ resource: 'type', action: current ? 'update' : 'create', name, before: current, after: { name, ...desired, is_enabled: true } });
|
|
139
|
+
}
|
|
140
|
+
if (settings.prune_types)
|
|
141
|
+
for (const current of state.types)
|
|
142
|
+
if (!github_issues_1.issueType.options.some(name => name.toLowerCase() === current.name.toLowerCase()))
|
|
143
|
+
result.push({ resource: 'type', action: 'delete', name: current.name, before: current });
|
|
144
|
+
const priority = state.fields.find(value => value.name.toLowerCase() === 'priority');
|
|
145
|
+
if (!priority)
|
|
146
|
+
result.push({ resource: 'field', action: 'create', name: 'Priority', after: { name: 'Priority', description: this.standard.priority_description, data_type: 'single_select', options: priorityOptions } });
|
|
147
|
+
else {
|
|
148
|
+
if (priority.name !== 'Priority' || priority.description !== this.standard.priority_description)
|
|
149
|
+
result.push({ resource: 'field', action: 'update', name: 'Priority', before: priority, after: { name: 'Priority', description: this.standard.priority_description } });
|
|
150
|
+
for (const desired of priorityOptions) {
|
|
151
|
+
const current = priority.options?.find(value => value.name.toLowerCase() === desired.name.toLowerCase());
|
|
152
|
+
if (!current || current.name !== desired.name || current.color !== desired.color || current.priority !== desired.priority)
|
|
153
|
+
result.push({ resource: 'option', action: current ? 'update' : 'create', name: desired.name, before: current, after: desired });
|
|
154
|
+
}
|
|
155
|
+
for (const current of priority.options ?? [])
|
|
156
|
+
if (!github_issues_1.issuePriority.options.some(name => name.toLowerCase() === current.name.toLowerCase()))
|
|
157
|
+
result.push({ resource: 'option', action: 'delete', name: current.name, before: current });
|
|
158
|
+
}
|
|
159
|
+
for (const current of state.fields)
|
|
160
|
+
if (settings.remove_fields.includes(current.name))
|
|
161
|
+
result.push({ resource: 'field', action: 'delete', name: current.name, before: current });
|
|
162
|
+
return result;
|
|
163
|
+
}
|
|
164
|
+
// Verify complete organisation visibility before inspecting usage outside the selected repository.
|
|
165
|
+
async outsideUsage(state) {
|
|
166
|
+
try {
|
|
167
|
+
if (this.github.organisationAccess && !this.github.organisationAccess(this.owner))
|
|
168
|
+
throw new Error('Organisation-wide Brain grants are required');
|
|
169
|
+
const membership = zod_1.z.object({ role: zod_1.z.string(), state: zod_1.z.string() }).parse(await this.github.configurationRequest('/user/memberships/orgs/' + this.owner));
|
|
170
|
+
if (membership.role !== 'admin' || membership.state !== 'active')
|
|
171
|
+
throw new Error('An active organisation owner is required for definition changes');
|
|
172
|
+
const counts = zod_1.z.object({ public_repos: zod_1.z.number().int(), total_private_repos: zod_1.z.number().int() }).parse(await this.github.configurationRequest('/orgs/' + this.owner));
|
|
173
|
+
const repositories = zod_1.z.array(zod_1.z.object({ full_name: repositories_1.repositoryId })).parse(await this.all('/orgs/' + this.owner + '/repos?type=all&sort=full_name&direction=asc')).sort((a, b) => a.full_name.localeCompare(b.full_name));
|
|
174
|
+
if (repositories.length !== counts.public_repos + counts.total_private_repos || new Set(repositories.map(value => value.full_name)).size !== repositories.length ||
|
|
175
|
+
!repositories.some(value => value.full_name === this.github.repository) || repositories.some(value => value.full_name.split('/')[0] !== this.owner))
|
|
176
|
+
throw new Error('Token cannot prove visibility of every organisation repository');
|
|
177
|
+
for (const repo of repositories) {
|
|
178
|
+
const name = repo.full_name.toLowerCase();
|
|
179
|
+
if (name === this.github.repository)
|
|
180
|
+
continue;
|
|
181
|
+
const issues = await this.allIssues(name);
|
|
182
|
+
state.outside.push({ repository: name, issues });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
state.errors.push('Organisation usage check unavailable: ' + String(error));
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
// Plan classification and explicit legacy-value migrations without guessing ambiguous issue origins.
|
|
190
|
+
migrations(state, settings, blockers) {
|
|
191
|
+
const result = [];
|
|
192
|
+
for (const row of state.issues) {
|
|
193
|
+
const labels = row.labels.map(value => value.name);
|
|
194
|
+
if (row.pull_request) {
|
|
195
|
+
const retained = labels.flatMap(name => { const canonical = github_issues_1.issueOrigin.options.find(value => value.toLowerCase() === name.toLowerCase()); return canonical ? [canonical] : []; });
|
|
196
|
+
if (JSON.stringify(retained) !== JSON.stringify(labels))
|
|
197
|
+
result.push({ number: row.number, url: row.html_url, revision: migrationRevision(row), before: issueState(row), labels: retained, drops: labels.filter(name => !retained.some(value => value === name)) });
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const override = own(settings.issue_overrides, String(row.number)) ?? {};
|
|
201
|
+
const origins = [...new Set(labels.flatMap(name => { const standard = github_issues_1.issueOrigin.options.find(value => value.toLowerCase() === name.toLowerCase()); return standard ? [standard] : own(settings.label_migrations, name) ? [own(settings.label_migrations, name)] : []; }))];
|
|
202
|
+
const origin = override.origin ?? (origins.length === 1 ? origins[0] : origins.length === 0 ? settings.defaults.origin : undefined);
|
|
203
|
+
const currentType = row.type?.name;
|
|
204
|
+
const type = override.type ?? (github_issues_1.issueType.options.find(value => value.toLowerCase() === currentType?.toLowerCase()) ?? (currentType ? own(settings.type_migrations, currentType) ?? settings.defaults.type : settings.defaults.type));
|
|
205
|
+
const values = zod_1.z.array(fieldValue).parse(row.issue_field_values ?? []);
|
|
206
|
+
const priorityValue = values.find(value => value.issue_field_name.toLowerCase() === 'priority');
|
|
207
|
+
const currentPriority = priorityValue ? storedValue(priorityValue) : undefined;
|
|
208
|
+
let priority = override.priority ?? (github_issues_1.issuePriority.options.find(value => value.toLowerCase() === currentPriority?.toLowerCase()) ?? (currentPriority ? own(settings.priority_migrations, currentPriority) : undefined));
|
|
209
|
+
const drops = [];
|
|
210
|
+
for (const value of values.filter(value => settings.remove_fields.includes(value.issue_field_name))) {
|
|
211
|
+
const source = storedValue(value);
|
|
212
|
+
const explicit = own(settings.field_migrations, value.issue_field_name);
|
|
213
|
+
const legacy = value.issue_field_name === 'Severity' ? { critical: 'Urgent', high: 'High', medium: 'Medium', low: 'Low' } : {};
|
|
214
|
+
const mapped = explicit ? own(explicit, source) : own(legacy, source.toLowerCase());
|
|
215
|
+
if (mapped === undefined)
|
|
216
|
+
blockers.push(row.html_url + ': supply field_migrations for ' + value.issue_field_name + '=' + source);
|
|
217
|
+
else if (mapped === null)
|
|
218
|
+
drops.push(value.issue_field_name + '=' + source);
|
|
219
|
+
else if (priority && priority !== mapped && !override.priority)
|
|
220
|
+
blockers.push(row.html_url + ': conflicting Priority and ' + value.issue_field_name + '; supply an issue override');
|
|
221
|
+
else if (!priority)
|
|
222
|
+
priority = mapped;
|
|
223
|
+
}
|
|
224
|
+
priority ?? (priority = settings.defaults.priority);
|
|
225
|
+
if (!origin)
|
|
226
|
+
blockers.push(row.html_url + ': supply origin default/override or label migration');
|
|
227
|
+
if (!type)
|
|
228
|
+
blockers.push(row.html_url + ': supply type default/override or type migration');
|
|
229
|
+
if (!priority)
|
|
230
|
+
blockers.push(row.html_url + ': supply Priority default/override or value migration');
|
|
231
|
+
const change = { number: row.number, url: row.html_url, revision: migrationRevision(row), before: issueState(row), drops };
|
|
232
|
+
if (origin && (labels.length !== 1 || labels[0] !== origin))
|
|
233
|
+
change.labels = [origin];
|
|
234
|
+
if (type && type !== currentType)
|
|
235
|
+
change.type = github_issues_1.issueType.parse(type);
|
|
236
|
+
if (priority && priority !== currentPriority)
|
|
237
|
+
change.priority = github_issues_1.issuePriority.parse(priority);
|
|
238
|
+
if (change.labels || change.type || change.priority || drops.length || values.some(value => settings.remove_fields.includes(value.issue_field_name)))
|
|
239
|
+
result.push(change);
|
|
240
|
+
}
|
|
241
|
+
return result;
|
|
242
|
+
}
|
|
243
|
+
// Build a deterministic preview, including outside usages that prevent destructive definition changes.
|
|
244
|
+
async preview(input) {
|
|
245
|
+
const settings = exports.reconciliationSettings.parse(input);
|
|
246
|
+
const state = await this.inventory();
|
|
247
|
+
const operations = this.operations(state, settings);
|
|
248
|
+
if (operations.some(value => value.resource !== 'label'))
|
|
249
|
+
await this.outsideUsage(state);
|
|
250
|
+
const blockers = [...state.errors];
|
|
251
|
+
const priority = state.fields.find(value => value.name.toLowerCase() === 'priority');
|
|
252
|
+
if (priority && priority.data_type !== 'single_select')
|
|
253
|
+
blockers.push('Priority has an incompatible field type; rename/migrate it before reconciliation');
|
|
254
|
+
const organisationImpact = [];
|
|
255
|
+
for (const outside of state.outside)
|
|
256
|
+
for (const row of outside.issues) {
|
|
257
|
+
const values = zod_1.z.array(fieldValue).parse(row.issue_field_values ?? []);
|
|
258
|
+
for (const operation of operations.filter(value => value.resource !== 'label')) {
|
|
259
|
+
const used = operation.resource === 'type' ? row.type?.name.toLowerCase() === operation.name.toLowerCase() : operation.resource === 'field' ? values.some(value => value.issue_field_name.toLowerCase() === operation.name.toLowerCase()) : values.some(value => value.issue_field_name.toLowerCase() === 'priority' && storedValue(value).toLowerCase() === operation.name.toLowerCase());
|
|
260
|
+
if (used) {
|
|
261
|
+
organisationImpact.push({ repository: outside.repository, url: row.html_url, resource: operation.resource, name: operation.name, action: operation.action });
|
|
262
|
+
if (operation.action === 'delete')
|
|
263
|
+
blockers.push('Definition ' + operation.name + ' is used outside the selected repository: ' + row.html_url);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
const migrations = this.migrations(state, settings, blockers);
|
|
268
|
+
const revision = digest({ repository: this.github.repository, standard: this.standard, settings, state: { ...state, issues: state.issues.map(issueState), outside: state.outside.map(value => ({ repository: value.repository, issues: value.issues.map(issueState) })) } });
|
|
269
|
+
return { repository: this.github.repository, revision, standard: this.standard, operations, affected_issues: migrations, organisation_impact: organisationImpact,
|
|
270
|
+
checked_repositories: [this.github.repository, ...state.outside.map(value => value.repository)], blockers: [...new Set(blockers)].sort(), state };
|
|
271
|
+
}
|
|
272
|
+
// Update Priority options while retaining legacy identities until all migrations are verified.
|
|
273
|
+
async priorityOptions(final, expected) {
|
|
274
|
+
const fields = zod_1.z.array(fieldSchema).parse(await this.github.configurationRequest('/orgs/' + this.owner + '/issue-fields'));
|
|
275
|
+
const field = fields.find(value => value.name.toLowerCase() === 'priority');
|
|
276
|
+
if (!field)
|
|
277
|
+
throw new Error('Priority field disappeared; preview again');
|
|
278
|
+
if (final && digest(field.options) !== digest(expected))
|
|
279
|
+
throw new Error('Priority options changed before removal; preview again');
|
|
280
|
+
const desired = priorityOptions.map(value => {
|
|
281
|
+
const existing = field.options?.find(option => option.name.toLowerCase() === value.name.toLowerCase());
|
|
282
|
+
return { ...value, ...(existing ? { id: existing.id } : {}) };
|
|
283
|
+
});
|
|
284
|
+
const legacy = final ? [] : (field.options ?? []).filter(value => !github_issues_1.issuePriority.options.some(name => name.toLowerCase() === value.name.toLowerCase())).map((value, index) => ({ ...value, priority: value.priority ?? priorityOptions.length + index + 1 }));
|
|
285
|
+
await this.github.configurationRequest('/orgs/' + this.owner + '/issue-fields/' + field.id, 'PATCH', { options: [...desired, ...legacy] });
|
|
286
|
+
}
|
|
287
|
+
// Apply a fresh preview under the write gate, migrate before removals, and verify the final configuration.
|
|
288
|
+
async apply(input, revision) {
|
|
289
|
+
return this.github.configurationLock(async () => {
|
|
290
|
+
const plan = await this.preview(input);
|
|
291
|
+
if (plan.revision !== revision)
|
|
292
|
+
throw new Error('Configuration or affected issues changed; preview again before applying');
|
|
293
|
+
if (plan.blockers.length)
|
|
294
|
+
throw new Error('Reconciliation is blocked: ' + plan.blockers.join('; '));
|
|
295
|
+
const completed = [];
|
|
296
|
+
let attempted = false;
|
|
297
|
+
try {
|
|
298
|
+
for (const operation of plan.operations.filter(value => value.action !== 'delete' && value.resource !== 'option')) {
|
|
299
|
+
const prefix = operation.resource === 'label' ? '/repos/' + this.github.repository + '/labels' : '/orgs/' + this.owner + '/issue-' + (operation.resource === 'type' ? 'types' : 'fields');
|
|
300
|
+
const before = operation.resource === 'label' ? labelSchema.parse(operation.before ?? operation.after) : operation.resource === 'type' ? typeSchema.partial().parse(operation.before ?? {}) : fieldSchema.partial().parse(operation.before ?? {});
|
|
301
|
+
const suffix = operation.action === 'create' ? '' : '/' + (operation.resource === 'label' ? encodeURIComponent(before.name) : 'id' in before ? before.id : '');
|
|
302
|
+
let payload = operation.after;
|
|
303
|
+
if (operation.resource === 'label' && operation.action === 'update') {
|
|
304
|
+
const { name, ...rest } = zod_1.z.object({ name: zod_1.z.string() }).passthrough().parse(payload);
|
|
305
|
+
payload = { new_name: name, ...rest };
|
|
306
|
+
}
|
|
307
|
+
attempted = true;
|
|
308
|
+
await this.github.configurationRequest(prefix + suffix, operation.action === 'create' ? 'POST' : operation.resource === 'type' ? 'PUT' : 'PATCH', payload);
|
|
309
|
+
completed.push(operation.action + ' ' + operation.resource + ' ' + operation.name);
|
|
310
|
+
}
|
|
311
|
+
if (plan.operations.some(value => value.resource === 'option' && value.action !== 'delete')) {
|
|
312
|
+
attempted = true;
|
|
313
|
+
await this.priorityOptions(false);
|
|
314
|
+
completed.push('prepare Priority options');
|
|
315
|
+
}
|
|
316
|
+
for (const migration of plan.affected_issues) {
|
|
317
|
+
const route = '/repos/' + this.github.repository + '/issues/' + migration.number;
|
|
318
|
+
const current = github_issues_1.githubIssueSchema.parse(await this.github.configurationRequest(route));
|
|
319
|
+
if (migrationRevision(current) !== migration.revision)
|
|
320
|
+
throw new Error('Issue changed during reconciliation: ' + migration.url);
|
|
321
|
+
if (migration.labels || migration.type || migration.priority)
|
|
322
|
+
attempted = true;
|
|
323
|
+
if (migration.labels || migration.type)
|
|
324
|
+
await this.github.configurationRequest(route, 'PATCH', { ...(migration.labels ? { labels: migration.labels } : {}), ...(migration.type ? { type: migration.type } : {}) });
|
|
325
|
+
if (migration.priority)
|
|
326
|
+
await this.github.setIssuePriority(current.node_id, migration.priority);
|
|
327
|
+
const saved = github_issues_1.githubIssueSchema.parse(await this.github.configurationRequest(route));
|
|
328
|
+
const values = zod_1.z.array(fieldValue).parse(saved.issue_field_values ?? []);
|
|
329
|
+
if ((migration.labels && JSON.stringify(saved.labels.map(value => value.name).sort()) !== JSON.stringify([...migration.labels].sort())) || (migration.type && saved.type?.name !== migration.type) ||
|
|
330
|
+
(migration.priority && !values.some(value => value.issue_field_name === 'Priority' && storedValue(value) === migration.priority)))
|
|
331
|
+
throw new Error('GitHub did not save migration: ' + migration.url);
|
|
332
|
+
completed.push('migrate ' + migration.url);
|
|
333
|
+
}
|
|
334
|
+
// Recheck every repository before any definition deletion to catch new external usage.
|
|
335
|
+
const beforeDelete = await this.preview(input);
|
|
336
|
+
if (beforeDelete.blockers.length)
|
|
337
|
+
throw new Error('Removal preflight failed: ' + beforeDelete.blockers.join('; '));
|
|
338
|
+
if (beforeDelete.affected_issues.some(value => value.labels || value.type || value.priority))
|
|
339
|
+
throw new Error('Issue values changed during reconciliation; preview again');
|
|
340
|
+
if (beforeDelete.operations.some(value => value.action !== 'delete'))
|
|
341
|
+
throw new Error('Definitions changed or writes were ignored; preview again before removals');
|
|
342
|
+
const removedFields = exports.reconciliationSettings.parse(input).remove_fields;
|
|
343
|
+
// Bind acknowledged value loss to the exact source values shown in the approved preview.
|
|
344
|
+
const removedValues = (migration) => digest(migration.before.fields.filter(value => removedFields.includes(value.name)));
|
|
345
|
+
const approvedValues = new Map(plan.affected_issues.map(value => [value.number, removedValues(value)]));
|
|
346
|
+
if (beforeDelete.affected_issues.some(value => approvedValues.get(value.number) !== removedValues(value)))
|
|
347
|
+
throw new Error('Field values changed before removal; preview again');
|
|
348
|
+
// Never expand approved removals to definitions created by another writer during apply.
|
|
349
|
+
const identity = (operation) => JSON.stringify([operation.resource, operation.name,
|
|
350
|
+
operation.resource === 'label' ? labelSchema.parse(operation.before).id ?? null : zod_1.z.object({ id: zod_1.z.number() }).parse(operation.before).id]);
|
|
351
|
+
const approved = new Set(plan.operations.filter(value => value.action === 'delete').map(identity));
|
|
352
|
+
if (beforeDelete.operations.some(value => value.action === 'delete' && !approved.has(identity(value))))
|
|
353
|
+
throw new Error('New unreviewed removals appeared; preview again');
|
|
354
|
+
for (const operation of beforeDelete.operations.filter(value => value.action === 'delete' && value.resource !== 'option')) {
|
|
355
|
+
const prefix = operation.resource === 'label' ? '/repos/' + this.github.repository + '/labels/' : '/orgs/' + this.owner + '/issue-' + (operation.resource === 'type' ? 'types/' : 'fields/');
|
|
356
|
+
const id = operation.resource === 'label' ? encodeURIComponent(operation.name) : zod_1.z.object({ id: zod_1.z.number() }).parse(operation.before).id;
|
|
357
|
+
attempted = true;
|
|
358
|
+
await this.github.configurationRequest(prefix + id, 'DELETE');
|
|
359
|
+
completed.push('delete ' + operation.resource + ' ' + operation.name);
|
|
360
|
+
}
|
|
361
|
+
if (beforeDelete.operations.some(value => value.resource === 'option' && value.action === 'delete')) {
|
|
362
|
+
attempted = true;
|
|
363
|
+
await this.priorityOptions(true, beforeDelete.state.fields.find(value => value.name === 'Priority')?.options);
|
|
364
|
+
completed.push('remove obsolete Priority options');
|
|
365
|
+
}
|
|
366
|
+
const verified = await this.preview(input);
|
|
367
|
+
if (verified.blockers.length || verified.operations.length || verified.affected_issues.length)
|
|
368
|
+
throw new Error('Final configuration verification failed; preview remaining changes');
|
|
369
|
+
return { applied: true, completed, ...this.publicPreview(verified) };
|
|
370
|
+
}
|
|
371
|
+
catch (error) {
|
|
372
|
+
return { applied: false, partial: attempted, completed, error: String(error), recovery: 'Preview again; completed changes are read from GitHub and will not be repeated.' };
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
// Return the reviewable plan without exposing unrelated issue bodies from inventory.
|
|
377
|
+
publicPreview(plan) {
|
|
378
|
+
const { state, ...result } = plan;
|
|
379
|
+
return { ...result, configuration: { labels: state.labels, types: state.types, fields: state.fields } };
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
exports.IssueConfiguration = IssueConfiguration;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerIssueTools = registerIssueTools;
|
|
4
|
+
const zod_1 = require("zod");
|
|
5
|
+
const fs = require("node:fs");
|
|
6
|
+
const jsonc_parser_1 = require("jsonc-parser");
|
|
7
|
+
const github_issues_1 = require("./github-issues");
|
|
8
|
+
const issue_configuration_1 = require("./issue-configuration");
|
|
9
|
+
const repositories_1 = require("./repositories");
|
|
10
|
+
// Register ordinary issue tools against the existing repository-bound GitHub configuration.
|
|
11
|
+
function registerIssueTools(server, store, options) {
|
|
12
|
+
const backend = (0, github_issues_1.githubIssues)(store, options.allowIssueRepository, options.allowIssueOrganisation, options.repository);
|
|
13
|
+
if (backend && options.repository && backend.repository !== options.repository)
|
|
14
|
+
throw new Error('Issue backend repository does not match the authenticated repository');
|
|
15
|
+
// Validate inputs and report backend errors without falling back to a local task store.
|
|
16
|
+
function tool(name, description, shape, readOnly, handler) {
|
|
17
|
+
if (options.allowTool && !options.allowTool(name))
|
|
18
|
+
return;
|
|
19
|
+
const schema = zod_1.z.object(shape).strict();
|
|
20
|
+
server.registerTool(name, { description, inputSchema: schema, annotations: { readOnlyHint: readOnly, destructiveHint: false, openWorldHint: true } }, async (input) => {
|
|
21
|
+
try {
|
|
22
|
+
if (!backend)
|
|
23
|
+
throw new Error('GitHub issues are not configured; configure global/review.jsonc or the active profile review.jsonc backend');
|
|
24
|
+
const result = await handler(zod_1.z.object(shape).strict().parse(input), backend);
|
|
25
|
+
return { content: [{ type: 'text', text: JSON.stringify(result) }] };
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
return { isError: true, content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }] };
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
// Load optional presentation metadata while retaining the exhaustive built-in taxonomy.
|
|
33
|
+
function configuration(github) {
|
|
34
|
+
const file = store.safePath(store.profile ?? 'default', 'issue-standard.jsonc');
|
|
35
|
+
const errors = [];
|
|
36
|
+
const standard = fs.existsSync(file) ? (0, jsonc_parser_1.parse)(store.read(file), errors, { allowTrailingComma: true }) : {};
|
|
37
|
+
if (errors.length)
|
|
38
|
+
throw new Error('Invalid issue-standard.jsonc');
|
|
39
|
+
return new issue_configuration_1.IssueConfiguration(github, standard);
|
|
40
|
+
}
|
|
41
|
+
tool('issue_search', 'Search only the configured repository using literal text and structured filters. Reports incomplete results and the GitHub 1000-result cap.', {
|
|
42
|
+
...github_issues_1.issuePage, text: zod_1.z.string().max(500).regex(/^[^"\\\r\n]*$/).optional(), state: zod_1.z.enum(['open', 'closed', 'all']).default('open'),
|
|
43
|
+
origin: github_issues_1.issueOrigin.optional(), type: github_issues_1.issueType.optional(), priority: github_issues_1.issuePriority.optional(), assignee: zod_1.z.string().regex(/^[a-zA-Z0-9-]+$/).optional(),
|
|
44
|
+
milestone: zod_1.z.string().max(200).regex(/^[^"\\\r\n]+$/).optional(), sort: zod_1.z.enum(['created', 'updated', 'comments']).default('updated'), order: zod_1.z.enum(['asc', 'desc']).default('desc')
|
|
45
|
+
}, true, (input, github) => github.searchIssues(input));
|
|
46
|
+
tool('issue_metadata', 'Inspect repository labels, assignees or milestones, and organisation issue type/field definitions. Permission and capability failures are explicit.', {
|
|
47
|
+
kind: zod_1.z.enum(['labels', 'types', 'fields', 'assignees', 'milestones']), ...github_issues_1.issuePage
|
|
48
|
+
}, true, ({ kind, page, per_page }, github) => github.metadata(kind, page, per_page));
|
|
49
|
+
tool('issue_relations', 'Read a page of parent, sub-issue or dependency relationships. Related issues outside Brain grants are hidden; GitHub capability errors are explicit.', {
|
|
50
|
+
number: github_issues_1.issueNumber, kind: zod_1.z.enum(['parent', 'sub_issues', 'blocked_by', 'blocking']), ...github_issues_1.issuePage
|
|
51
|
+
}, true, ({ number, kind, page, per_page }, github) => github.relations(number, kind, page, per_page));
|
|
52
|
+
tool('issue_relation_update', 'Add/remove a sub-issue or blocking dependency, checking access to both repositories and verifying the result. Repeated operations are idempotent.', {
|
|
53
|
+
number: github_issues_1.issueNumber, target_number: github_issues_1.issueNumber, target_repository: repositories_1.repositoryId.optional(), kind: zod_1.z.enum(['sub_issue', 'blocked_by']), action: zod_1.z.enum(['add', 'remove']), confirmed: zod_1.z.literal(true)
|
|
54
|
+
}, false, ({ number, target_number, target_repository, kind, action }, github) => github.changeRelation(number, target_repository ?? github.repository, target_number, kind, action));
|
|
55
|
+
tool('issue_config_preview', 'Preview deterministic issue-standard reconciliation, migrations and blockers. No writes. Check the returned affected issues and revision before applying.', {
|
|
56
|
+
settings: issue_configuration_1.reconciliationSettings.prefault({})
|
|
57
|
+
}, true, async ({ settings }, github) => { const config = configuration(github); return config.publicPreview(await config.preview(settings)); });
|
|
58
|
+
tool('issue_config_reconcile', 'Apply a reviewed configuration preview by revision. Migrate values before removing definitions; stop on ambiguous mappings, outside usage or incomplete access. Partial results require a fresh preview.', {
|
|
59
|
+
settings: issue_configuration_1.reconciliationSettings.prefault({}), revision: github_issues_1.issueRevision, confirmed: zod_1.z.literal(true)
|
|
60
|
+
}, false, ({ settings, revision }, github) => configuration(github).apply(settings, revision));
|
|
61
|
+
tool('issue_list', 'List ordinary GitHub issues in the configured repository. PRs are excluded; next_page follows upstream pagination.', {
|
|
62
|
+
...github_issues_1.issuePage, state: zod_1.z.enum(['open', 'closed', 'all']).default('open'), origin: github_issues_1.issueOrigin.optional(),
|
|
63
|
+
assignee: zod_1.z.string().regex(/^(?:[a-zA-Z0-9-]+|\*|none)$/).optional(), milestone: zod_1.z.string().regex(/^(?:[1-9][0-9]*|\*|none)$/).optional()
|
|
64
|
+
}, true, (input, github) => github.listIssues(input));
|
|
65
|
+
tool('issue_get', 'Read a full GitHub issue, metadata and revision. Read comments separately with issue_comments.', { number: github_issues_1.issueNumber }, true, ({ number }, github) => github.readIssue(number));
|
|
66
|
+
tool('issue_create', 'Create an authorized issue with origin, work type and Priority. Requires enabled writes. Reuse the same key and content on retries; uncertain outcomes require reconciliation.', github_issues_1.issueCreate.shape, false, (input, github) => github.createIssue(input));
|
|
67
|
+
tool('issue_update', 'Update supplied fields or classification; close/reopen with state and state_reason. Requires the last-read revision and enabled writes. Read again after partial failures.', {
|
|
68
|
+
number: github_issues_1.issueNumber, revision: github_issues_1.issueRevision, confirmed: zod_1.z.literal(true), changes: github_issues_1.issueChanges
|
|
69
|
+
}, false, ({ number, revision, changes }, github) => github.updateIssue(number, revision, changes));
|
|
70
|
+
tool('issue_comments', 'Read a page of issue comments with authors, timestamps and revisions.', { number: github_issues_1.issueNumber, ...github_issues_1.issuePage }, true, ({ number, page, per_page }, github) => github.listComments(number, page, per_page));
|
|
71
|
+
tool('issue_comment', 'Append an authorized comment. Reuse the same key and content on retries; uncertain outcomes require reconciliation.', {
|
|
72
|
+
number: github_issues_1.issueNumber, key: zod_1.z.string().min(1).max(200), body: zod_1.z.string().trim().min(1).max(40000), confirmed: zod_1.z.literal(true)
|
|
73
|
+
}, false, ({ number, key, body }, github) => github.addComment(number, key, body));
|
|
74
|
+
tool('issue_comment_update', 'Edit an authorized comment belonging to this issue using its last-read revision.', {
|
|
75
|
+
number: github_issues_1.issueNumber, comment_id: github_issues_1.issueNumber, revision: github_issues_1.issueRevision, body: zod_1.z.string().trim().min(1).max(40000), confirmed: zod_1.z.literal(true)
|
|
76
|
+
}, false, ({ number, comment_id, revision, body }, github) => github.editComment(number, comment_id, revision, body));
|
|
77
|
+
}
|
package/dist/brain/projects.js
CHANGED
|
@@ -14,7 +14,7 @@ const project_1 = require("@technomoron/agent-run/dist/project");
|
|
|
14
14
|
const utils_1 = require("@technomoron/agent-run/dist/utils");
|
|
15
15
|
const config_1 = require("./config");
|
|
16
16
|
const store_1 = require("./store");
|
|
17
|
-
|
|
17
|
+
// Initialize external Brain storage, templates and profile directories.
|
|
18
18
|
function initializeBrain(configRoot, cwd) {
|
|
19
19
|
if ((0, utils_1.isSamePathOrDescendant)(path.resolve(configRoot), (0, project_1.findProjectRoot)(cwd)))
|
|
20
20
|
throw new Error('Brain configuration must live outside the source repository.');
|
|
@@ -40,21 +40,18 @@ function initializeBrain(configRoot, cwd) {
|
|
|
40
40
|
for (const directory of directories)
|
|
41
41
|
initializeScopeDirectories(store, directory);
|
|
42
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
43
|
}
|
|
49
44
|
finally {
|
|
50
45
|
store.close();
|
|
51
46
|
}
|
|
52
47
|
}
|
|
48
|
+
// Create the knowledge, skill, task and template directories for a scope.
|
|
53
49
|
function initializeScopeDirectories(store, directory) {
|
|
54
50
|
for (const folder of [...Object.values(store_1.knowledgeDirectories), 'skills', 'todo', 'templates']) {
|
|
55
51
|
store.directory(directory, folder);
|
|
56
52
|
}
|
|
57
53
|
}
|
|
54
|
+
// Detect source languages, package scripts and the Git origin.
|
|
58
55
|
function inspectProject(cwd) {
|
|
59
56
|
const root = (0, project_1.findProjectRoot)(cwd);
|
|
60
57
|
const git = (0, node_child_process_1.spawnSync)('git', ['-C', root, 'config', '--get', 'remote.origin.url'], { encoding: 'utf8', shell: false });
|
|
@@ -68,6 +65,7 @@ function inspectProject(cwd) {
|
|
|
68
65
|
packageManager: fs.existsSync(path.join(root, 'pnpm-lock.yaml')) ? 'pnpm' : fs.existsSync(pkg) ? 'npm' : undefined,
|
|
69
66
|
documents: ['README.md', 'AGENTS.md', 'CLAUDE.md'].filter((file) => fs.existsSync(path.join(root, file))), scripts };
|
|
70
67
|
}
|
|
68
|
+
// Register a source project using detected or interactively supplied settings.
|
|
71
69
|
async function createBrainProject(configRoot, cwd, name, mode) {
|
|
72
70
|
config_1.projectConfigSchema.shape.name.parse(name);
|
|
73
71
|
const detected = inspectProject(cwd);
|
|
@@ -22,7 +22,7 @@ exports.remoteConfigSchema = zod_1.z.object({
|
|
|
22
22
|
accessSecretEnv: envName.default('MCP_OAUTH_ACCESS_SECRET'), refreshSecretEnv: envName.default('MCP_OAUTH_REFRESH_SECRET'),
|
|
23
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
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()),
|
|
25
|
+
kind: zod_1.z.enum(['human', 'service']).default('human'), passwordEnv: envName.optional(), passwordHashEnv: envName.optional(), totpSecretEnv: envName.optional(), disabled: zod_1.z.boolean().default(false) }).strict()),
|
|
26
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
27
|
secretEnv: envName.optional(), subject: zod_1.z.string().optional(), redirectUris: zod_1.z.array(zod_1.z.string().url()).default([]),
|
|
28
28
|
repos: zod_1.z.array(repositories_1.repositoryPattern).min(1), permissions: zod_1.z.array(exports.permission).min(1) }).strict()),
|
|
@@ -30,6 +30,7 @@ exports.remoteConfigSchema = zod_1.z.object({
|
|
|
30
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
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
32
|
}).strict();
|
|
33
|
+
// Validate remote configuration and its identity and repository relationships.
|
|
33
34
|
function readRemoteConfig(file) {
|
|
34
35
|
const errors = [];
|
|
35
36
|
const value = (0, jsonc_parser_1.parse)(fs.readFileSync(file, 'utf8'), errors, { allowTrailingComma: true });
|
|
@@ -43,8 +44,10 @@ function readRemoteConfig(file) {
|
|
|
43
44
|
for (const user of config.users) {
|
|
44
45
|
if (config.users.some((other) => other.subject !== user.subject && other.subject === user.login))
|
|
45
46
|
throw new Error('Logins must not alias another subject');
|
|
46
|
-
if (
|
|
47
|
-
throw new Error('
|
|
47
|
+
if (user.passwordEnv && user.passwordHashEnv)
|
|
48
|
+
throw new Error('Choose passwordEnv or passwordHashEnv, not both');
|
|
49
|
+
if (!user.disabled && user.kind === 'human' && !user.passwordHashEnv && !user.passwordEnv)
|
|
50
|
+
throw new Error('Human users require passwordEnv or passwordHashEnv');
|
|
48
51
|
}
|
|
49
52
|
for (const client of config.clients) {
|
|
50
53
|
if (client.kind !== 'public' && !client.secretEnv)
|
|
@@ -64,6 +67,7 @@ function readRemoteConfig(file) {
|
|
|
64
67
|
/** A declared group may share a root; unrelated groups and repositories must remain isolated. */
|
|
65
68
|
function validateRepositoryRoots(config, canonical = false) {
|
|
66
69
|
if (config.dataRoot) {
|
|
70
|
+
// Resolve a configured root, following symlinks only for canonical validation.
|
|
67
71
|
const resolve = (value) => canonical ? fs.realpathSync(value) : path.resolve(value);
|
|
68
72
|
if (config.repositories.some((repo) => resolve(repo.configRoot) !== resolve(config.dataRoot)) || config.groups.some((group) => resolve(group.configRoot) !== resolve(config.dataRoot)))
|
|
69
73
|
throw new Error('All repositories and pools must use the central dataRoot');
|
|
@@ -73,6 +77,7 @@ function validateRepositoryRoots(config, canonical = false) {
|
|
|
73
77
|
}
|
|
74
78
|
if (new Set(config.groups.map((g) => g.id)).size !== config.groups.length)
|
|
75
79
|
throw new Error('Group IDs must be unique');
|
|
80
|
+
// Resolve a configured root, following symlinks only for canonical validation.
|
|
76
81
|
const resolve = (value) => canonical ? fs.realpathSync(value) : path.resolve(value);
|
|
77
82
|
for (const repo of config.repositories)
|
|
78
83
|
if (repo.group !== undefined) {
|
|
@@ -85,11 +90,13 @@ function validateRepositoryRoots(config, canonical = false) {
|
|
|
85
90
|
for (let i = 0; i < roots.length; i++)
|
|
86
91
|
for (let j = i + 1; j < roots.length; j++) {
|
|
87
92
|
const a = roots[i].root, b = roots[j].root;
|
|
93
|
+
// Check whether one storage root contains another.
|
|
88
94
|
const overlaps = (from, to) => { const relative = path.relative(from, to); return !relative || (relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative)); };
|
|
89
95
|
if (overlaps(a, b) || overlaps(b, a))
|
|
90
96
|
throw new Error('Repository and group data roots must be separate and non-overlapping');
|
|
91
97
|
}
|
|
92
98
|
}
|
|
99
|
+
// Check requested OAuth scopes against the current user and client grants.
|
|
93
100
|
function allowedGrant(config, subject, clientId, scopes) {
|
|
94
101
|
const user = config.users.find((u) => u.subject === subject && !u.disabled);
|
|
95
102
|
const client = config.clients.find((c) => c.id === clientId);
|
|
@@ -103,6 +110,7 @@ function allowedGrant(config, subject, clientId, scopes) {
|
|
|
103
110
|
operations.every((operation) => client.permissions.includes(operation) && config.access.some((rule) => rule.subject === subject &&
|
|
104
111
|
rule.permissions.includes(operation) && rule.repos.some((pattern) => (0, repositories_1.coversPattern)(pattern, repo)))));
|
|
105
112
|
}
|
|
113
|
+
// Intersect current user, client and token permissions for one repository.
|
|
106
114
|
function repositoryPermissions(config, subject, clientId, scopes, repo) {
|
|
107
115
|
const client = config.clients.find((c) => c.id === clientId);
|
|
108
116
|
const user = config.users.find((u) => u.subject === subject && !u.disabled);
|
|
@@ -115,7 +123,12 @@ function repositoryPermissions(config, subject, clientId, scopes, repo) {
|
|
|
115
123
|
}
|
|
116
124
|
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
125
|
const reviewTools = new Set(['review_create', 'review_update', 'resolve_review']);
|
|
126
|
+
// Classify a tool by required permission and reject unsupported remote tools.
|
|
118
127
|
function toolPermission(name) {
|
|
128
|
+
if (['issue_list', 'issue_get', 'issue_comments', 'issue_search', 'issue_metadata', 'issue_relations', 'issue_config_preview'].includes(name))
|
|
129
|
+
return 'read';
|
|
130
|
+
if (['issue_create', 'issue_update', 'issue_comment', 'issue_comment_update', 'issue_relation_update', 'issue_config_reconcile'].includes(name))
|
|
131
|
+
return 'write';
|
|
119
132
|
if (readTools.has(name))
|
|
120
133
|
return 'read';
|
|
121
134
|
if (reviewTools.has(name))
|