@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,332 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GithubIssues = exports.githubIssueSchema = exports.issueCreate = exports.issueChanges = exports.issuePage = exports.issueRevision = exports.issueNumber = exports.issuePriority = exports.issueType = exports.issueOrigin = void 0;
|
|
4
|
+
exports.githubIssues = githubIssues;
|
|
5
|
+
const fs = require("node:fs");
|
|
6
|
+
const node_crypto_1 = require("node:crypto");
|
|
7
|
+
const zod_1 = require("zod");
|
|
8
|
+
const github_reviews_1 = require("./github-reviews");
|
|
9
|
+
exports.issueOrigin = zod_1.z.enum(['Code Review', 'Bug Report', 'Feature Request', 'ToDo', 'Question']);
|
|
10
|
+
exports.issueType = zod_1.z.enum(['Bug', 'Security', 'Feature', 'Task', 'Inconsistency', 'Question', 'Documentation']);
|
|
11
|
+
exports.issuePriority = zod_1.z.enum(['Urgent', 'High', 'Medium', 'Low']);
|
|
12
|
+
exports.issueNumber = zod_1.z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
|
|
13
|
+
exports.issueRevision = zod_1.z.string().regex(/^[a-f0-9]{64}$/);
|
|
14
|
+
exports.issuePage = { page: zod_1.z.number().int().min(1).max(10000).default(1), per_page: zod_1.z.number().int().min(1).max(100).default(30) };
|
|
15
|
+
const title = zod_1.z.string().trim().min(1).max(250);
|
|
16
|
+
const body = zod_1.z.string().max(40000);
|
|
17
|
+
const key = zod_1.z.string().min(1).max(200);
|
|
18
|
+
exports.issueChanges = zod_1.z.object({ title: title.optional(), body: body.optional(), origin: exports.issueOrigin.optional(),
|
|
19
|
+
type: exports.issueType.optional(), priority: exports.issuePriority.optional(), assignees: zod_1.z.array(zod_1.z.string().regex(/^[a-zA-Z0-9-]+$/)).max(10).optional(),
|
|
20
|
+
milestone: exports.issueNumber.nullable().optional(), state: zod_1.z.enum(['open', 'closed']).optional(),
|
|
21
|
+
state_reason: zod_1.z.enum(['completed', 'not_planned', 'reopened']).optional() }).strict().refine(value => Object.keys(value).length > 0, 'Supply at least one change');
|
|
22
|
+
exports.issueCreate = zod_1.z.object({ key, title, body, origin: exports.issueOrigin, type: exports.issueType, priority: exports.issuePriority,
|
|
23
|
+
assignees: zod_1.z.array(zod_1.z.string().regex(/^[a-zA-Z0-9-]+$/)).max(10).optional(), milestone: exports.issueNumber.optional(), confirmed: zod_1.z.literal(true) }).strict();
|
|
24
|
+
exports.githubIssueSchema = zod_1.z.object({ number: exports.issueNumber, node_id: zod_1.z.string(), title: zod_1.z.string(), body: zod_1.z.string().nullable(),
|
|
25
|
+
state: zod_1.z.enum(['open', 'closed']), html_url: zod_1.z.string().url(), updated_at: zod_1.z.string(), pull_request: zod_1.z.unknown().optional(),
|
|
26
|
+
labels: zod_1.z.array(zod_1.z.object({ name: zod_1.z.string() }).passthrough()), type: zod_1.z.object({ name: zod_1.z.string() }).passthrough().nullable().optional(),
|
|
27
|
+
issue_field_values: zod_1.z.array(zod_1.z.unknown()).optional() }).passthrough();
|
|
28
|
+
const issue = exports.githubIssueSchema;
|
|
29
|
+
const comment = zod_1.z.object({ id: exports.issueNumber, body: zod_1.z.string(), html_url: zod_1.z.string().url(), issue_url: zod_1.z.string().url(), updated_at: zod_1.z.string() }).passthrough();
|
|
30
|
+
// Derive stable revisions and opaque retry markers without storing credential data.
|
|
31
|
+
const hash = (value) => (0, node_crypto_1.createHash)('sha256').update(JSON.stringify(value)).digest('hex');
|
|
32
|
+
// Add a revision without discarding GitHub metadata.
|
|
33
|
+
const snapshot = (value) => ({ ...value, revision: hash(value) });
|
|
34
|
+
class GithubIssues extends github_reviews_1.GithubReviews {
|
|
35
|
+
// Keep cross-repository operations subject to the requesting MCP identity's grants.
|
|
36
|
+
constructor(store, config, repository, access, organisationAccess) {
|
|
37
|
+
super(store, config, repository);
|
|
38
|
+
this.access = access;
|
|
39
|
+
this.organisationAccess = organisationAccess;
|
|
40
|
+
}
|
|
41
|
+
// Share the bounded authenticated transport with deterministic configuration reconciliation.
|
|
42
|
+
configurationRequest(route, method = 'GET', body) { return this.requestApi(route, method, body); }
|
|
43
|
+
// Serialize configuration changes with ordinary issue and legacy review writes.
|
|
44
|
+
configurationLock(work) { return this.locked(work); }
|
|
45
|
+
// Request repository metadata without accepting caller-supplied URLs.
|
|
46
|
+
async metadata(kind, page, per_page) {
|
|
47
|
+
const organisation = kind === 'types' || kind === 'fields';
|
|
48
|
+
const route = organisation ? '/orgs/' + this.repository.split('/')[0] + '/issue-' + kind : '/repos/' + this.repository + '/' + kind;
|
|
49
|
+
const rows = zod_1.z.array(zod_1.z.unknown()).parse(await this.requestApi(route + (organisation ? '' : '?state=all&page=' + page + '&per_page=' + per_page)));
|
|
50
|
+
return { repository: this.repository, items: rows, next_page: !organisation && rows.length === per_page ? page + 1 : null };
|
|
51
|
+
}
|
|
52
|
+
// Search with structured qualifiers and quoted literal words, never an unrestricted query scope.
|
|
53
|
+
async searchIssues(input) {
|
|
54
|
+
const tokens = ['repo:' + this.repository, 'is:issue'];
|
|
55
|
+
if (input.text) {
|
|
56
|
+
if (/["\\\r\n]/.test(input.text))
|
|
57
|
+
throw new Error('Search text must contain literal words without quotes or backslashes');
|
|
58
|
+
tokens.push(...input.text.trim().split(/\s+/).filter(Boolean).map(word => '"' + word + '"'), 'in:title,body');
|
|
59
|
+
}
|
|
60
|
+
if (input.state && input.state !== 'all')
|
|
61
|
+
tokens.push('is:' + input.state);
|
|
62
|
+
if (input.origin)
|
|
63
|
+
tokens.push('label:"' + exports.issueOrigin.parse(input.origin) + '"');
|
|
64
|
+
if (input.type)
|
|
65
|
+
tokens.push('type:"' + exports.issueType.parse(input.type) + '"');
|
|
66
|
+
if (input.priority)
|
|
67
|
+
tokens.push('field.priority:' + exports.issuePriority.parse(input.priority));
|
|
68
|
+
if (input.assignee)
|
|
69
|
+
tokens.push('assignee:' + zod_1.z.string().regex(/^[a-zA-Z0-9-]+$/).parse(input.assignee));
|
|
70
|
+
if (input.milestone)
|
|
71
|
+
tokens.push('milestone:"' + zod_1.z.string().regex(/^[^"\\\r\n]+$/).parse(input.milestone) + '"');
|
|
72
|
+
const query = new URLSearchParams({ q: tokens.join(' '), advanced_search: 'true', page: String(input.page), per_page: String(input.per_page), sort: input.sort ?? 'updated', order: input.order ?? 'desc' });
|
|
73
|
+
const response = zod_1.z.object({ total_count: zod_1.z.number(), incomplete_results: zod_1.z.boolean(), items: zod_1.z.array(issue) }).parse(await this.requestApi('/search/issues?' + query));
|
|
74
|
+
const items = response.items.filter(value => !value.pull_request && value.html_url.toLowerCase().startsWith('https://github.com/' + this.repository.toLowerCase() + '/issues/')).map(snapshot);
|
|
75
|
+
return { repository: this.repository, ...response, items, truncated: response.total_count > 1000,
|
|
76
|
+
next_page: input.page * input.per_page < Math.min(response.total_count, 1000) ? input.page + 1 : null };
|
|
77
|
+
}
|
|
78
|
+
// Page through supported relationships while hiding repositories outside the caller's grants.
|
|
79
|
+
async relations(number, kind, page, per_page) {
|
|
80
|
+
await this.readIssue(number);
|
|
81
|
+
const route = kind === 'parent' ? 'parent' : kind === 'sub_issues' ? 'sub_issues' : 'dependencies/' + kind;
|
|
82
|
+
const data = await this.request('/' + number + '/' + route + (kind === 'parent' ? '' : '?page=' + page + '&per_page=' + per_page));
|
|
83
|
+
const rows = kind === 'parent' ? [issue.parse(data)] : zod_1.z.array(issue).parse(data);
|
|
84
|
+
const visible = rows.filter(value => {
|
|
85
|
+
const match = /^https:\/\/github\.com\/([^/]+\/[^/]+)\/issues\/[0-9]+$/i.exec(value.html_url);
|
|
86
|
+
return !value.pull_request && match && (!this.access || this.access(match[1].toLowerCase(), false));
|
|
87
|
+
});
|
|
88
|
+
return { items: visible.map(snapshot), next_page: kind !== 'parent' && rows.length === per_page ? page + 1 : null, hidden: rows.length - visible.length };
|
|
89
|
+
}
|
|
90
|
+
// Add or remove a checked relationship and verify its resulting presence before returning.
|
|
91
|
+
async changeRelation(number, targetRepository, targetNumber, kind, action) {
|
|
92
|
+
if (this.access && !this.access(targetRepository, true))
|
|
93
|
+
throw new Error('Write and review access to the related repository is required');
|
|
94
|
+
return this.locked(async () => {
|
|
95
|
+
await this.readIssue(number);
|
|
96
|
+
const target = issue.extend({ id: exports.issueNumber }).parse(await this.requestApi('/repos/' + targetRepository + '/issues/' + targetNumber));
|
|
97
|
+
if (target.pull_request)
|
|
98
|
+
throw new Error('Relationships require an ordinary issue');
|
|
99
|
+
const suffix = kind === 'sub_issue' ? 'sub_issues' : 'dependencies/blocked_by';
|
|
100
|
+
const route = '/' + number + '/' + suffix;
|
|
101
|
+
// Inspect every relationship page to make repeated add/remove operations idempotent.
|
|
102
|
+
const contains = async () => {
|
|
103
|
+
for (let page = 1; page <= 100; page++) {
|
|
104
|
+
const rows = zod_1.z.array(issue.extend({ id: exports.issueNumber })).parse(await this.request(route + '?per_page=100&page=' + page));
|
|
105
|
+
if (rows.some(value => value.id === target.id))
|
|
106
|
+
return true;
|
|
107
|
+
if (rows.length < 100)
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
throw new Error('Relationship listing exceeds 100 pages');
|
|
111
|
+
};
|
|
112
|
+
if (await contains() !== (action === 'add')) {
|
|
113
|
+
if (kind === 'sub_issue')
|
|
114
|
+
await this.request(action === 'add' ? route : '/' + number + '/sub_issue', action === 'add' ? 'POST' : 'DELETE', { sub_issue_id: target.id });
|
|
115
|
+
else
|
|
116
|
+
await this.request(route + (action === 'remove' ? '/' + target.id : ''), action === 'add' ? 'POST' : 'DELETE', action === 'add' ? { issue_id: target.id } : undefined);
|
|
117
|
+
}
|
|
118
|
+
if (await contains() !== (action === 'add'))
|
|
119
|
+
throw new Error('GitHub did not save the requested relationship');
|
|
120
|
+
return { issue_url: 'https://github.com/' + this.repository + '/issues/' + number, related_url: target.html_url, kind, present: action === 'add' };
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
// Read an ordinary issue and reject pull requests before any mutation.
|
|
124
|
+
async readIssue(number) {
|
|
125
|
+
const value = issue.parse(await this.request('/' + exports.issueNumber.parse(number)));
|
|
126
|
+
if (value.pull_request)
|
|
127
|
+
throw new Error('Pull requests are not supported by issue tools');
|
|
128
|
+
return snapshot(value);
|
|
129
|
+
}
|
|
130
|
+
// List a bounded page of repository issues with GitHub filtering and explicit continuation.
|
|
131
|
+
async listIssues(input) {
|
|
132
|
+
const query = new URLSearchParams({ page: String(input.page), per_page: String(input.per_page), state: input.state ?? 'open' });
|
|
133
|
+
if (input.origin)
|
|
134
|
+
query.set('labels', input.origin);
|
|
135
|
+
if (input.assignee)
|
|
136
|
+
query.set('assignee', input.assignee);
|
|
137
|
+
if (input.milestone)
|
|
138
|
+
query.set('milestone', input.milestone);
|
|
139
|
+
const rows = zod_1.z.array(issue).parse(await this.request('?' + query));
|
|
140
|
+
return { repository: this.repository, items: rows.filter(value => !value.pull_request).map(snapshot),
|
|
141
|
+
next_page: rows.length === input.per_page ? input.page + 1 : null };
|
|
142
|
+
}
|
|
143
|
+
// List a bounded page of comments after verifying the parent is an issue.
|
|
144
|
+
async listComments(number, page, per_page) {
|
|
145
|
+
await this.readIssue(number);
|
|
146
|
+
const rows = zod_1.z.array(comment).parse(await this.request('/' + number + '/comments?page=' + page + '&per_page=' + per_page));
|
|
147
|
+
return { items: rows.map(snapshot), next_page: rows.length === per_page ? page + 1 : null };
|
|
148
|
+
}
|
|
149
|
+
// Resolve supported classification values before sending a write to GitHub.
|
|
150
|
+
async classification(type, priority, origin) {
|
|
151
|
+
const owner = this.repository.split('/')[0];
|
|
152
|
+
if (origin) {
|
|
153
|
+
let found = false;
|
|
154
|
+
for (let page = 1; page <= 100; page++) {
|
|
155
|
+
const labels = zod_1.z.array(zod_1.z.object({ name: zod_1.z.string() })).parse(await this.requestApi('/repos/' + this.repository + '/labels?per_page=100&page=' + page));
|
|
156
|
+
if (labels.some(value => value.name === origin)) {
|
|
157
|
+
found = true;
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
if (labels.length < 100)
|
|
161
|
+
break;
|
|
162
|
+
}
|
|
163
|
+
if (!found)
|
|
164
|
+
throw new Error('Origin label is unavailable in the configured repository: ' + origin);
|
|
165
|
+
}
|
|
166
|
+
if (type) {
|
|
167
|
+
const types = zod_1.z.array(zod_1.z.object({ name: zod_1.z.string(), is_enabled: zod_1.z.boolean().optional() })).parse(await this.requestApi('/orgs/' + owner + '/issue-types'));
|
|
168
|
+
if (!types.some(value => value.name === type && value.is_enabled !== false))
|
|
169
|
+
throw new Error('Issue type is unavailable in the configured organisation: ' + type);
|
|
170
|
+
}
|
|
171
|
+
if (!priority)
|
|
172
|
+
return null;
|
|
173
|
+
const fields = zod_1.z.array(zod_1.z.object({ node_id: zod_1.z.string(), name: zod_1.z.string() })).parse(await this.requestApi('/orgs/' + owner + '/issue-fields'));
|
|
174
|
+
const field = fields.find(value => value.name === 'Priority');
|
|
175
|
+
if (!field)
|
|
176
|
+
throw new Error('The configured organisation has no Priority field');
|
|
177
|
+
const result = await this.graphql('query($id:ID!){node(id:$id){... on IssueFieldSingleSelect{options{id name}}}}', { id: field.node_id });
|
|
178
|
+
const options = zod_1.z.object({ node: zod_1.z.object({ options: zod_1.z.array(zod_1.z.object({ id: zod_1.z.string(), name: zod_1.z.string() })) }) }).parse(result).node.options;
|
|
179
|
+
const option = options.find(value => value.name === priority);
|
|
180
|
+
if (!option)
|
|
181
|
+
throw new Error('Priority option is unavailable: ' + priority);
|
|
182
|
+
return { fieldId: field.node_id, singleSelectOptionId: option.id };
|
|
183
|
+
}
|
|
184
|
+
// Reject GraphQL errors even when GitHub returns HTTP success.
|
|
185
|
+
async graphql(query, variables) {
|
|
186
|
+
const response = zod_1.z.object({ data: zod_1.z.unknown().optional(), errors: zod_1.z.array(zod_1.z.unknown()).optional() }).parse(await this.requestApi('/graphql', 'POST', { query, variables }));
|
|
187
|
+
if (response.errors?.length || !response.data)
|
|
188
|
+
throw new Error('GitHub issue field operation failed; check organisation permissions and supported fields');
|
|
189
|
+
return response.data;
|
|
190
|
+
}
|
|
191
|
+
// Apply the organisation Priority field using its actual GraphQL option identity.
|
|
192
|
+
async setPriority(nodeId, field) {
|
|
193
|
+
if (field)
|
|
194
|
+
await this.graphql('mutation($id:ID!,$fields:[IssueFieldCreateOrUpdateInput!]!){setIssueFieldValue(input:{issueId:$id,issueFields:$fields}){clientMutationId}}', { id: nodeId, fields: [field] });
|
|
195
|
+
}
|
|
196
|
+
// Share GitHub's Priority identity resolution with configuration migrations.
|
|
197
|
+
async setIssuePriority(nodeId, priority) {
|
|
198
|
+
await this.setPriority(nodeId, await this.classification(undefined, exports.issuePriority.parse(priority)));
|
|
199
|
+
}
|
|
200
|
+
// Report silently ignored classification changes instead of claiming a successful write.
|
|
201
|
+
verifyClassification(current, expected) {
|
|
202
|
+
const origins = current.labels.filter(value => exports.issueOrigin.options.includes(value.name));
|
|
203
|
+
const fields = zod_1.z.array(zod_1.z.object({ issue_field_name: zod_1.z.string(), single_select_option: zod_1.z.object({ name: zod_1.z.string() }).nullable().optional() }).passthrough()).parse(current.issue_field_values ?? []);
|
|
204
|
+
if ((expected.origin && (origins.length !== 1 || origins[0].name !== expected.origin)) ||
|
|
205
|
+
(expected.type && current.type?.name !== expected.type) ||
|
|
206
|
+
(expected.priority && !fields.some(value => value.issue_field_name === 'Priority' && value.single_select_option?.name === expected.priority))) {
|
|
207
|
+
throw new Error('GitHub did not save the requested classification at ' + current.html_url + '; read the issue before retrying');
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
// Check fields that GitHub may silently ignore when the token lacks permission.
|
|
211
|
+
verifyChanges(current, expected) {
|
|
212
|
+
for (const name of ['title', 'body', 'state', 'state_reason']) {
|
|
213
|
+
if (expected[name] !== undefined && current[name] !== expected[name])
|
|
214
|
+
throw new Error('GitHub did not save ' + name + ' at ' + current.html_url);
|
|
215
|
+
}
|
|
216
|
+
if (expected.assignees) {
|
|
217
|
+
const actual = zod_1.z.array(zod_1.z.object({ login: zod_1.z.string() })).parse(current.assignees ?? []).map(value => value.login.toLowerCase()).sort();
|
|
218
|
+
if (JSON.stringify(actual) !== JSON.stringify(expected.assignees.map(value => value.toLowerCase()).sort()))
|
|
219
|
+
throw new Error('GitHub did not save assignees at ' + current.html_url);
|
|
220
|
+
}
|
|
221
|
+
if (expected.milestone !== undefined) {
|
|
222
|
+
const actual = zod_1.z.object({ number: exports.issueNumber }).nullable().parse(current.milestone ?? null);
|
|
223
|
+
if ((actual?.number ?? null) !== expected.milestone)
|
|
224
|
+
throw new Error('GitHub did not save milestone at ' + current.html_url);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
// Serialize retry state before writes so uncertain creates cannot silently duplicate issues or comments.
|
|
228
|
+
async retry(operation, input, create, finish) {
|
|
229
|
+
const file = this.store.safePath('runtime', 'github-issue-' + hash([this.repository, operation]) + '.json');
|
|
230
|
+
const digest = hash(input);
|
|
231
|
+
const saved = fs.existsSync(file) ? zod_1.z.object({ digest: zod_1.z.string(), number: exports.issueNumber.optional(), completed: zod_1.z.boolean().optional() }).parse(JSON.parse(fs.readFileSync(file, 'utf8'))) : null;
|
|
232
|
+
if (saved && saved.digest !== digest)
|
|
233
|
+
throw new Error('Retry key was already used with different content');
|
|
234
|
+
if (saved && !saved.number)
|
|
235
|
+
throw new Error('Previous GitHub write has an uncertain outcome; inspect GitHub before using a new retry key');
|
|
236
|
+
// Atomically save a retry record under the existing backend write lock.
|
|
237
|
+
const save = (value) => { fs.writeFileSync(file + '.tmp', JSON.stringify(value), { mode: 0o600 }); fs.renameSync(file + '.tmp', file); };
|
|
238
|
+
let number = saved?.number;
|
|
239
|
+
if (!number) {
|
|
240
|
+
save({ digest });
|
|
241
|
+
number = await create();
|
|
242
|
+
save({ digest, number });
|
|
243
|
+
}
|
|
244
|
+
const result = await finish(number, saved?.completed ?? false);
|
|
245
|
+
save({ digest, number, completed: true });
|
|
246
|
+
return result;
|
|
247
|
+
}
|
|
248
|
+
// Create an ordinary issue once and complete classification on retries after partial failure.
|
|
249
|
+
async createIssue(input) {
|
|
250
|
+
input = exports.issueCreate.parse(input);
|
|
251
|
+
return this.locked(async () => {
|
|
252
|
+
const field = await this.classification(input.type, input.priority, input.origin);
|
|
253
|
+
const { key, origin, priority, confirmed, ...data } = input;
|
|
254
|
+
return this.retry('create:' + key, input, async () => issue.parse(await this.request('', 'POST', { ...data, labels: [origin] })).number, async (number, completed) => {
|
|
255
|
+
const current = await this.readIssue(number);
|
|
256
|
+
if (completed)
|
|
257
|
+
return current;
|
|
258
|
+
try {
|
|
259
|
+
await this.setPriority(current.node_id, field);
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
throw new Error('Issue created at ' + current.html_url + ' but Priority was not saved; retry with the same key');
|
|
263
|
+
}
|
|
264
|
+
const saved = await this.readIssue(number);
|
|
265
|
+
this.verifyClassification(saved, input);
|
|
266
|
+
this.verifyChanges(saved, input);
|
|
267
|
+
return saved;
|
|
268
|
+
});
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
// Update only supplied fields after checking the current revision; preserve unrelated labels.
|
|
272
|
+
async updateIssue(number, revision, changes) {
|
|
273
|
+
changes = exports.issueChanges.parse(changes);
|
|
274
|
+
return this.locked(async () => {
|
|
275
|
+
const current = await this.readIssue(number);
|
|
276
|
+
if (current.revision !== revision)
|
|
277
|
+
throw new Error('Issue changed; read it again before updating');
|
|
278
|
+
if (changes.state_reason && !changes.state)
|
|
279
|
+
throw new Error('state_reason requires state');
|
|
280
|
+
if (changes.state === 'open' && changes.state_reason && changes.state_reason !== 'reopened')
|
|
281
|
+
throw new Error('Open issues require reopened state_reason');
|
|
282
|
+
if (changes.state === 'closed' && changes.state_reason === 'reopened')
|
|
283
|
+
throw new Error('Closed issues require completed or not_planned state_reason');
|
|
284
|
+
const field = await this.classification(changes.type, changes.priority, changes.origin);
|
|
285
|
+
const { origin, priority, ...data } = changes;
|
|
286
|
+
const labels = origin ? [...current.labels.map(value => value.name).filter(value => !exports.issueOrigin.options.includes(value)), origin] : undefined;
|
|
287
|
+
try {
|
|
288
|
+
if (Object.keys(data).length || labels)
|
|
289
|
+
await this.request('/' + number, 'PATCH', { ...data, ...(labels ? { labels } : {}) });
|
|
290
|
+
await this.setPriority(current.node_id, field);
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
throw new Error('Issue update may be partially saved at ' + current.html_url + '; read it again before retrying');
|
|
294
|
+
}
|
|
295
|
+
const saved = await this.readIssue(number);
|
|
296
|
+
this.verifyClassification(saved, changes);
|
|
297
|
+
this.verifyChanges(saved, changes);
|
|
298
|
+
return saved;
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
// Append a retry-safe comment to an ordinary issue.
|
|
302
|
+
async addComment(number, retryKey, text) {
|
|
303
|
+
return this.locked(async () => {
|
|
304
|
+
await this.readIssue(number);
|
|
305
|
+
return this.retry('comment:' + number + ':' + retryKey, { number, text }, async () => comment.parse(await this.request('/' + number + '/comments', 'POST', { body: text })).id, async (id) => snapshot(await this.readComment(number, id)));
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
// Verify a comment belongs to the selected repository and issue before returning or editing it.
|
|
309
|
+
async readComment(number, id) {
|
|
310
|
+
const value = comment.parse(await this.request('/comments/' + id));
|
|
311
|
+
if (value.issue_url.toLowerCase() !== 'https://api.github.com/repos/' + this.repository.toLowerCase() + '/issues/' + number)
|
|
312
|
+
throw new Error('Comment does not belong to the selected issue');
|
|
313
|
+
return value;
|
|
314
|
+
}
|
|
315
|
+
// Edit a current comment without allowing cross-issue comment identities.
|
|
316
|
+
async editComment(number, id, revision, text) {
|
|
317
|
+
return this.locked(async () => {
|
|
318
|
+
await this.readIssue(number);
|
|
319
|
+
const current = await this.readComment(number, id);
|
|
320
|
+
if (hash(current) !== revision)
|
|
321
|
+
throw new Error('Comment changed; read it again before updating');
|
|
322
|
+
await this.request('/comments/' + id, 'PATCH', { body: text });
|
|
323
|
+
return snapshot(await this.readComment(number, id));
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
exports.GithubIssues = GithubIssues;
|
|
328
|
+
// Load ordinary issue tools using the existing repository-bound GitHub backend configuration.
|
|
329
|
+
function githubIssues(store, access, organisationAccess, selectedRepository) {
|
|
330
|
+
const settings = (0, github_reviews_1.githubReviewConfig)(store, selectedRepository);
|
|
331
|
+
return settings ? new GithubIssues(store, settings.config, settings.repository, access, organisationAccess) : null;
|
|
332
|
+
}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.GithubReviews = exports.reviewInput = void 0;
|
|
4
4
|
exports.githubReviews = githubReviews;
|
|
5
|
+
exports.githubReviewConfig = githubReviewConfig;
|
|
5
6
|
const fs = require("node:fs");
|
|
6
7
|
const node_crypto_1 = require("node:crypto");
|
|
7
8
|
const jsonc_parser_1 = require("jsonc-parser");
|
|
@@ -18,31 +19,41 @@ const metadata = zod_1.z.object({ key: zod_1.z.string(), severity: store_1.sever
|
|
|
18
19
|
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
20
|
state: zod_1.z.enum(['open', 'closed']), state_reason: zod_1.z.string().nullable().optional(), html_url: zod_1.z.string().url(),
|
|
20
21
|
updated_at: zod_1.z.string(), pull_request: zod_1.z.unknown().optional() });
|
|
22
|
+
// Hash review content for revisions and repository-specific retry files.
|
|
21
23
|
const hash = (value) => (0, node_crypto_1.createHash)('sha256').update(value).digest('hex');
|
|
22
24
|
const start = '<!-- agent-mcp-review:start -->';
|
|
23
25
|
const end = '<!-- agent-mcp-review:end -->';
|
|
24
26
|
class GithubReviews {
|
|
27
|
+
// Bind the review backend to its store, configuration and GitHub repository.
|
|
25
28
|
constructor(store, config, repository) {
|
|
26
29
|
this.store = store;
|
|
27
30
|
this.config = config;
|
|
28
31
|
this.repository = repository;
|
|
29
32
|
}
|
|
33
|
+
// Send an authenticated GitHub issue request with time and size limits.
|
|
30
34
|
async request(route, method = 'GET', body) {
|
|
35
|
+
return this.requestApi('/repos/' + this.repository + '/issues' + route, method, body);
|
|
36
|
+
}
|
|
37
|
+
// Send a bounded request to a fixed GitHub API path.
|
|
38
|
+
async requestApi(route, method = 'GET', body) {
|
|
31
39
|
const token = process.env[this.config.tokenEnv];
|
|
32
40
|
if (!token)
|
|
33
41
|
throw new Error('Set ' + this.config.tokenEnv + ' for GitHub reviews');
|
|
34
|
-
const response = await fetch('https://api.github.com
|
|
42
|
+
const response = await fetch('https://api.github.com' + route, {
|
|
35
43
|
method, redirect: 'error', signal: AbortSignal.timeout(30000), headers: { accept: 'application/vnd.github+json',
|
|
36
44
|
'content-type': 'application/json', 'user-agent': 'agent-brain', authorization: 'Bearer ' + token,
|
|
37
45
|
'X-GitHub-Api-Version': '2026-03-10' }, ...(body ? { body: JSON.stringify(body) } : {})
|
|
38
46
|
});
|
|
39
47
|
if (!response.ok)
|
|
40
|
-
throw new Error('GitHub
|
|
48
|
+
throw new Error('GitHub request failed with HTTP ' + response.status + (response.status === 403 ? '; check token permissions, organisation policy and rate limits' : ''));
|
|
49
|
+
if (response.status === 204)
|
|
50
|
+
return null;
|
|
41
51
|
const text = await response.text();
|
|
42
52
|
if (text.length > 4 * 1024 * 1024)
|
|
43
53
|
throw new Error('GitHub response exceeds 4 MiB');
|
|
44
54
|
return JSON.parse(text);
|
|
45
55
|
}
|
|
56
|
+
// Extract managed review metadata from an ordinary GitHub issue.
|
|
46
57
|
data(issue) {
|
|
47
58
|
if (issue.pull_request)
|
|
48
59
|
return null;
|
|
@@ -64,6 +75,7 @@ class GithubReviews {
|
|
|
64
75
|
title: issue.title, content: body, state: issue.state === 'open' ? 'open' : issue.state_reason === 'not_planned' ? 'wontfix' : 'fixed',
|
|
65
76
|
url: issue.html_url, revision: hash(JSON.stringify(issue)), backend: 'github' };
|
|
66
77
|
}
|
|
78
|
+
// Page through managed findings and sort them by severity.
|
|
67
79
|
async list(state = 'open') {
|
|
68
80
|
const found = [];
|
|
69
81
|
for (let page = 1; page <= 100; page++) {
|
|
@@ -78,6 +90,7 @@ class GithubReviews {
|
|
|
78
90
|
}
|
|
79
91
|
throw new Error('GitHub review listing exceeds 100 pages; narrow the repository backlog before retrying');
|
|
80
92
|
}
|
|
93
|
+
// Extract an issue number belonging to the configured repository.
|
|
81
94
|
number(id) {
|
|
82
95
|
const prefix = 'github:' + this.repository + '#';
|
|
83
96
|
const number = id.startsWith(prefix) ? id.slice(prefix.length) : id.replace(/^#/, '');
|
|
@@ -85,12 +98,14 @@ class GithubReviews {
|
|
|
85
98
|
throw new Error('Issue must belong to the configured repository');
|
|
86
99
|
return number;
|
|
87
100
|
}
|
|
101
|
+
// Read a managed GitHub finding by its issue identity.
|
|
88
102
|
async get(id) {
|
|
89
103
|
const item = this.data(issueSchema.parse(await this.request('/' + this.number(id))));
|
|
90
104
|
if (!item)
|
|
91
105
|
throw new Error('Issue is not an agent-mcp review finding');
|
|
92
106
|
return item;
|
|
93
107
|
}
|
|
108
|
+
// Serialize GitHub writes and enforce the explicit write gate.
|
|
94
109
|
async locked(work) {
|
|
95
110
|
if (!this.config.writesEnabled)
|
|
96
111
|
throw new Error('GitHub review writes are disabled; configure writesEnabled explicitly');
|
|
@@ -104,12 +119,14 @@ class GithubReviews {
|
|
|
104
119
|
fs.unlinkSync(lock);
|
|
105
120
|
}
|
|
106
121
|
}
|
|
122
|
+
// Encode a finding inside the reserved GitHub review markers.
|
|
107
123
|
block(input) {
|
|
108
124
|
if (input.content.includes('<!-- agent-mcp-'))
|
|
109
125
|
throw new Error('Finding content contains a reserved marker');
|
|
110
126
|
const encoded = Buffer.from(JSON.stringify({ key: input.key, severity: input.severity, applies_to: input.applies_to })).toString('base64url');
|
|
111
127
|
return start + '\n<!-- agent-mcp-meta:' + encoded + ' -->\nSeverity: ' + input.severity + '\n\n' + input.content + '\n' + end;
|
|
112
128
|
}
|
|
129
|
+
// Create a finding or return the issue already associated with its retry key.
|
|
113
130
|
async create(input) {
|
|
114
131
|
input = exports.reviewInput.parse(input);
|
|
115
132
|
return this.locked(async () => {
|
|
@@ -133,6 +150,7 @@ class GithubReviews {
|
|
|
133
150
|
return { ...item, created: true };
|
|
134
151
|
});
|
|
135
152
|
}
|
|
153
|
+
// Revise the managed finding while preserving unrelated issue content.
|
|
136
154
|
async update(id, revision, changes) {
|
|
137
155
|
return this.locked(async () => {
|
|
138
156
|
const current = await this.get(id);
|
|
@@ -145,6 +163,7 @@ class GithubReviews {
|
|
|
145
163
|
return this.data(issue);
|
|
146
164
|
});
|
|
147
165
|
}
|
|
166
|
+
// Close a current finding with its resolution reason.
|
|
148
167
|
async resolve(id, revision, state, reason) {
|
|
149
168
|
return this.locked(async () => {
|
|
150
169
|
const current = await this.get(id);
|
|
@@ -158,17 +177,29 @@ class GithubReviews {
|
|
|
158
177
|
}
|
|
159
178
|
}
|
|
160
179
|
exports.GithubReviews = GithubReviews;
|
|
161
|
-
|
|
162
|
-
|
|
180
|
+
// Load the optional GitHub review backend for the active profile.
|
|
181
|
+
function githubReviews(store, selectedRepository) {
|
|
182
|
+
const settings = githubReviewConfig(store, selectedRepository);
|
|
183
|
+
return settings ? new GithubReviews(store, settings.config, settings.repository) : null;
|
|
184
|
+
}
|
|
185
|
+
// Resolve the repository-bound GitHub configuration shared by issue and review tools.
|
|
186
|
+
function githubReviewConfig(store, selectedRepository) {
|
|
187
|
+
const local = store.safePath(store.profile ?? 'default', 'review.jsonc');
|
|
188
|
+
const global = !fs.existsSync(local);
|
|
189
|
+
const file = global ? store.safePath('global', 'review.jsonc') : local;
|
|
163
190
|
if (!fs.existsSync(file))
|
|
164
191
|
return null;
|
|
165
192
|
const errors = [];
|
|
166
|
-
const
|
|
193
|
+
const document = (0, jsonc_parser_1.parse)(store.read(file), errors);
|
|
167
194
|
if (errors.length)
|
|
168
195
|
throw new Error('Invalid review.jsonc');
|
|
196
|
+
const config = global ? configSchema.omit({ repository: true }).parse(document) : configSchema.parse(document);
|
|
169
197
|
const project = (0, config_1.listBrainProjects)(store.configRoot).find((item) => item.profile === store.profile);
|
|
170
|
-
const
|
|
198
|
+
const registered = project?.repository?.url ? (0, repositories_1.githubRepository)(project.repository.url) : null;
|
|
199
|
+
const repository = global
|
|
200
|
+
? selectedRepository ?? registered ?? (repositories_1.repositoryId.safeParse(project?.name).success ? project.name : null)
|
|
201
|
+
: ('repository' in config ? config.repository : undefined) ?? registered;
|
|
171
202
|
if (!repository)
|
|
172
203
|
throw new Error('GitHub reviews need an explicit repository or a registered GitHub remote');
|
|
173
|
-
return
|
|
204
|
+
return { config, repository: repositories_1.repositoryId.parse(repository) };
|
|
174
205
|
}
|