@technomoron/agent-brain 0.1.3 → 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 CHANGED
@@ -1,3 +1,8 @@
1
+ Version 0.1.4 (2026-10-26)
2
+ --------------------------
3
+ * Move to the shared monorepo with independent package releases.
4
+ * Use agent-run 0.99.48.
5
+
1
6
  Version 0.1.3 (2026-10-23)
2
7
  --------------------------
3
8
  * Simplify internal helpers and add concise function and method comments.
package/README.md CHANGED
@@ -15,21 +15,9 @@ their own access controls. Node.js 24 or newer is required.
15
15
 
16
16
  ## Development
17
17
 
18
- Keep the agent-run and agent-brain checkouts next to each other. Build agent-run first, then install this package’s dependencies and link the local agent-run checkout:
19
-
20
- ```sh
21
- cd ../agent-run
22
- pnpm install
23
- pnpm build
24
- cd ../agent-brain
25
- pnpm install
26
- node scripts/link-agent-run.cjs
27
- pnpm build
28
- ```
29
-
30
- Run `pnpm test` for the server and agent-run integration suite. The test harness supplies this checkout’s executables through an isolated temporary PATH. Run `npm run build` to check the npm build path.
31
-
32
- The server currently depends on `@technomoron/agent-run` for profile resolution, initialization and Nunjucks skill rendering. This preserves existing behavior while moving server ownership into this repository; it does not yet make the server independent of the launcher’s profile format. Link the sibling launcher checkout when developing changes to those libraries; normal installations use the published dependency.
18
+ From the repository root, run `pnpm install`, `pnpm build`, and `pnpm test`.
19
+ The workspace links agent-run locally. Run `npm run build` inside this package
20
+ for the npm build path.
33
21
 
34
22
  ## Running
35
23
 
@@ -53,7 +41,7 @@ The server bundles `brain-consolidate`, `brain-import`, `brain-memory`, `code-re
53
41
 
54
42
  All bundled skills are served directly by `list_skills` and `get_skill`; no configuration copy is required. Explicit global, pool, or project overrides remain supported. Legacy `brain-review`, `code-review-organizer`, `review-items`, `commit-workflow`, `release-package-check`, and `personal-memory` copies are excluded from MCP discovery. Remove these copies from configurations. Route review callers to `code-review`, Git callers to `git-workflow`, and package checks to `package-integrity-check`.
55
43
 
56
- The review workflow uses ordinary GitHub Issues through GitHub tools or `gh`. Brain supplies project context; GitHub owns issue identity, metadata, discussion and history. Existing `review_*` tools remain a compatibility API for earlier installations, not a requirement of the bundled skill.
44
+ The task and review workflows use Brain MCP `issue_*` tools for ordinary GitHub Issues. Direct GitHub tools or `gh` are explicit fallbacks only when the Brain backend or a required capability is unavailable. Brain supplies project context; GitHub owns issue identity, metadata, discussion and history. Existing `review_*` tools remain a compatibility API for earlier installations, not a requirement of the bundled skill.
57
45
 
58
46
  Initialization does not copy bundled skills into configuration directories. Remove old bundled-skill copies to use the package versions; intentional overrides remain supported. Consolidation's CLI fallback reads the same packaged source.
59
47
 
@@ -63,19 +51,15 @@ Initialization does not copy bundled skills into configuration directories. Remo
63
51
 
64
52
  ## Releases
65
53
 
66
- The release workflow publishes `@technomoron/agent-brain` on npm with public
67
- access. Tags use `@technomoron/agent-brain@<version>` and must match the package
68
- version. Run `pnpm release:preflight` before committing and tagging a release.
69
- The workflow checks the tag, runs the integration suite, and attaches the package
70
- tarball to its GitHub release. Configure `NPM_TOKEN` in the source repository for
71
- npm publishing; private source repositories publish without provenance.
54
+ See [publishing](../../docs/publishing.md). This package uses
55
+ `agent-brain-v<version>` tags and publishes independently of agent-run.
72
56
 
73
57
  ## Remote OAuth endpoint
74
58
 
75
59
  The remote endpoint uses the generic OAuth APIs in
76
60
  `@technomoron/apicore-server` 1.1.0 or newer. Normal npm installations include
77
61
  that dependency. When developing changes to apicore locally, build the sibling
78
- `../apicore` checkout and run `node scripts/link-apicore.cjs`; reinstalling
62
+ `../apicore` checkout next to the monorepo and run `node scripts/link-apicore.cjs`; reinstalling
79
63
  dependencies replaces this development link.
80
64
 
81
65
  Copy `examples/remote.jsonc` outside the source tree and customize absolute paths.
@@ -139,8 +123,86 @@ and unfinished login forms are deliberately lost on restart.
139
123
 
140
124
  ## Reviews as GitHub Issues
141
125
 
142
- Create `<active-profile>/review.jsonc` (or `default/review.jsonc`) inside the
143
- repository's private configuration root:
126
+ ### Ordinary issue tools
127
+
128
+ `issue_list`, `issue_get`, `issue_create`, `issue_update`, `issue_comments`,
129
+ `issue_comment` and `issue_comment_update` manage ordinary issues, including ones
130
+ created outside Brain. They use the repository, token and write gate in
131
+ `review.jsonc` below. Remote reads require `read`; writes require both `write`
132
+ and `review`, since ordinary issues can include review findings. PRs are excluded.
133
+
134
+ Lists and comments use `page`/`per_page` and return `next_page`. `issue_get`
135
+ returns the full body and metadata; comments are read separately. Creation requires
136
+ one origin, work type and Priority; organisation definitions must already exist.
137
+ Updates can change classification, assignees and milestone, or close/reopen using
138
+ `state` and `state_reason`. Unspecified fields and unrelated labels are preserved.
139
+
140
+ Writes require `confirmed: true`; edits require the last-read `revision`.
141
+ Creation and comment retries reuse `key` and the original content. Retry state
142
+ blocks uncertain writes instead of posting duplicates; reconcile those outcomes
143
+ on GitHub. Multi-step classification failures report partial success and the issue
144
+ URL. Revisions detect stale reads but cannot prevent concurrent external edits.
145
+
146
+ `issue_search` adds literal text and structured state/origin/type/Priority,
147
+ assignee and milestone filters. It stays within the configured repository and
148
+ reports incomplete results and GitHub's 1000-result search limit. `issue_metadata`
149
+ discovers labels, types, fields, assignees and milestones. `issue_relations` reads
150
+ parents, sub-issues and dependencies; `issue_relation_update` adds/removes
151
+ sub-issues and blocking dependencies. Both ends require Brain access; mutations
152
+ require write/review access to both repositories. Unsupported GitHub endpoints
153
+ and missing permissions are reported explicitly.
154
+
155
+ ### Issue configuration reconciliation
156
+
157
+ Call `issue_config_preview(settings)` to inspect definition changes, affected
158
+ issues, legacy-value migrations and blockers. Then pass the same settings and
159
+ returned `revision` to `issue_config_reconcile`, with `confirmed: true`. A stale
160
+ preview or any blocker prevents writes. No LLM or client-side GitHub login is used.
161
+
162
+ The standard contains the five origin labels, seven work types and four Priority
163
+ options documented by the bundled skills. Optional `<active-profile>/issue-standard.jsonc`
164
+ can configure complete `labels`/`types` metadata records (description and color)
165
+ and `priority_description`; it cannot introduce additional taxonomy values.
166
+
167
+ Settings support `defaults`, per-number `issue_overrides`, `label_migrations`,
168
+ `type_migrations`, `priority_migrations`, `remove_fields` (default: `Severity`),
169
+ `field_migrations` and `prune_types` (default: true). Unknown or ambiguous values
170
+ block apply until mapped. Legacy Severity critical/high/medium/low maps to
171
+ Urgent/High/Medium/Low. An explicit null field mapping acknowledges discarding
172
+ that value. Unrelated fields such as Effort and dates remain unchanged.
173
+
174
+ ```json
175
+ {"label_migrations":{"enhancement":"Feature Request"},"type_migrations":{"Improvement":"Feature"},"defaults":{"priority":"Medium"}}
176
+ ```
177
+
178
+ Reconciliation creates/updates definitions, migrates and verifies issue values,
179
+ then removes obsolete definitions. Priority option IDs are retained. Label cleanup
180
+ also previews and migrates PR labels. Organisation-wide changes require an active
181
+ GitHub organisation owner token, complete repository visibility, and remote Brain
182
+ `read write review repo:OWNER/*` (or `repo:*`) grants. All organisation repositories
183
+ are checked; outside use blocks destructive changes. Disable `prune_types` to
184
+ retain unrelated types while migrating individual repositories first.
185
+
186
+ Apply returns the read-back configuration and completed actions. On a partial or
187
+ uncertain failure, preview again; changes already present are not recreated.
188
+ GitHub offers no cross-resource transaction, so concurrent external changes can
189
+ still interrupt reconciliation. Capability failures and inventory limits fail
190
+ closed rather than authorizing deletion from an incomplete view.
191
+
192
+ ### Backend configuration
193
+
194
+ Configure the shared connection once in `global/review.jsonc` inside the private
195
+ configuration root:
196
+
197
+ ```json
198
+ {"backend":"github","tokenEnv":"GITHUB_TOKEN","writesEnabled":true}
199
+ ```
200
+
201
+ The global configuration has no fixed repository: remote requests use the selected
202
+ Brain repository; local requests use the registered GitHub remote or owner/repo
203
+ project name. Brain grants and GitHub token permissions still apply. A repository
204
+ must be selected before using issue tools. Existing `<active-profile>/review.jsonc`
205
+ (or `default/review.jsonc`) takes precedence when present:
144
206
 
145
207
  ```json
146
208
  {"backend":"github","repository":"technomoron/agent-run","tokenEnv":"MCP_GITHUB_TOKEN","writesEnabled":true}
@@ -165,7 +227,7 @@ not implemented by this change.
165
227
  ## Repository groups
166
228
 
167
229
  A remote configuration can declare `groups: [{"id":"agent-tools",
168
- "configRoot":"/var/lib/agent-mcp/groups/agent-tools"}]`. Set `group: "agent-tools"`
230
+ "configRoot":"/usr/local/agent-brain/groups/agent-tools"}]`. Set `group: "agent-tools"`
169
231
  and that same `configRoot` on each member of `repositories`. Each member keeps
170
232
  its own repository ID and working directory. Register its project at
171
233
  `<configRoot>/projects/<owner>/<repo>/config.yaml` with `name: owner/repo` and
@@ -201,8 +263,9 @@ projects, hidden members, empty groups, credentials and internal paths are omitt
201
263
  Changes to access rules apply to subsequent requests.
202
264
 
203
265
  An authenticated client can call these tools at `/mcp` without
204
- `X-Agent-Repository`. Only the discovery tools are available until a repository
205
- is selected. Send `X-Agent-Repository: owner/repo` for knowledge, skill, task and
266
+ `X-Agent-Repository`. Discovery tools and bundled `list_skills`/`get_skill` are
267
+ available before repository selection. Private skill overrides require selection.
268
+ Send `X-Agent-Repository: owner/repo` for knowledge, scoped skills, task and
206
269
  review tools. Discovery remains available after selection. Request a token with
207
270
  `read` and the desired repository scopes, such as `repo:*`; a token narrowed to
208
271
  one repository will only discover that repository, even if the user can access
@@ -257,8 +320,14 @@ compatibility; the application and package are named agent-brain.
257
320
 
258
321
  ### Export Brain changes to Git
259
322
 
260
- Configure `gitSync: {"catalog":"/var/lib/agent-mcp/catalogs/agent-brain-config",
261
- "state":"/var/lib/agent-mcp/config-deploy"}` alongside `dataRoot` in the remote
323
+ The server base is `/usr/local/agent-brain`. Keep service settings and credentials
324
+ in `conf/` (`remote.jsonc`, `.env`, and `ssh/`), the configuration Git checkout in
325
+ `brain-config/`, live knowledge in `data/live/`, authentication state in `runtime/`,
326
+ packages in `releases/` with a `current` link, and deployment state in `deploy/`.
327
+ Keep the existing service account and keep user launcher state separate.
328
+
329
+ Configure `gitSync: {"catalog":"/usr/local/agent-brain/brain-config",
330
+ "state":"/usr/local/agent-brain/deploy"}` alongside `dataRoot` in the remote
262
331
  server configuration. The catalog origin must grant SSH write access, and its
263
332
  local `user.name` and `user.email` must identify the configured human author.
264
333
  The deployment state must contain its successful deployment baseline.
@@ -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");
@@ -31,16 +32,22 @@ class GithubReviews {
31
32
  }
32
33
  // Send an authenticated GitHub issue request with time and size limits.
33
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) {
34
39
  const token = process.env[this.config.tokenEnv];
35
40
  if (!token)
36
41
  throw new Error('Set ' + this.config.tokenEnv + ' for GitHub reviews');
37
- const response = await fetch('https://api.github.com/repos/' + this.repository + '/issues' + route, {
42
+ const response = await fetch('https://api.github.com' + route, {
38
43
  method, redirect: 'error', signal: AbortSignal.timeout(30000), headers: { accept: 'application/vnd.github+json',
39
44
  'content-type': 'application/json', 'user-agent': 'agent-brain', authorization: 'Bearer ' + token,
40
45
  'X-GitHub-Api-Version': '2026-03-10' }, ...(body ? { body: JSON.stringify(body) } : {})
41
46
  });
42
47
  if (!response.ok)
43
- throw new Error('GitHub review request failed with HTTP ' + response.status);
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;
44
51
  const text = await response.text();
45
52
  if (text.length > 4 * 1024 * 1024)
46
53
  throw new Error('GitHub response exceeds 4 MiB');
@@ -171,17 +178,28 @@ class GithubReviews {
171
178
  }
172
179
  exports.GithubReviews = GithubReviews;
173
180
  // Load the optional GitHub review backend for the active profile.
174
- function githubReviews(store) {
175
- const file = store.safePath(store.profile ?? 'default', 'review.jsonc');
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;
176
190
  if (!fs.existsSync(file))
177
191
  return null;
178
192
  const errors = [];
179
- const config = configSchema.parse((0, jsonc_parser_1.parse)(store.read(file), errors));
193
+ const document = (0, jsonc_parser_1.parse)(store.read(file), errors);
180
194
  if (errors.length)
181
195
  throw new Error('Invalid review.jsonc');
196
+ const config = global ? configSchema.omit({ repository: true }).parse(document) : configSchema.parse(document);
182
197
  const project = (0, config_1.listBrainProjects)(store.configRoot).find((item) => item.profile === store.profile);
183
- const repository = config.repository ?? (project?.repository?.url ? (0, repositories_1.githubRepository)(project.repository.url) : null);
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;
184
202
  if (!repository)
185
203
  throw new Error('GitHub reviews need an explicit repository or a registered GitHub remote');
186
- return new GithubReviews(store, config, repository);
204
+ return { config, repository: repositories_1.repositoryId.parse(repository) };
187
205
  }