@technomoron/agent-brain 0.1.4 → 0.1.6

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,13 @@
1
+ Version 0.1.6 (2026-11-16)
2
+ --------------------------
3
+ * Support console password login, MFA challenges and session revocation.
4
+ * Use agent-run 0.99.49.
5
+
6
+ Version 0.1.5 (2026-10-28)
7
+ --------------------------
8
+ * Bundle shared changelog and release skills for project and default sessions.
9
+ * Expose authorized global skills in authenticated default sessions.
10
+
1
11
  Version 0.1.4 (2026-10-26)
2
12
  --------------------------
3
13
  * Move to the shared monorepo with independent package releases.
package/README.md CHANGED
@@ -37,11 +37,13 @@ Operational systemd and Windows installation scripts remain in agent-run, which
37
37
 
38
38
  ## MCP-owned skills
39
39
 
40
- The server bundles `brain-consolidate`, `brain-import`, `brain-memory`, `code-review`, `todo-manager`, `git-workflow`, `package-integrity-check`, `node-cleanup`, and `unslop` under `skills/`.
40
+ The server bundles `brain-consolidate`, `brain-import`, `brain-memory`, `code-review`, `todo-manager`, `git-workflow`, `changelog`, `github-release`, `package-integrity-check`, `node-cleanup`, and `unslop` under `skills/`.
41
+
42
+ Use `changelog` for CHANGES formatting and entries. `github-release` and `package-integrity-check` load the same rules. These bundled skills are also available in default sessions without repository selection. Remove old configured `github-release` copies to use the bundled version; intentional overrides remain supported.
41
43
 
42
44
  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`.
43
45
 
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.
46
+ 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. Review tracking uses only `issue_*`; `review_context` retrieves review guidance. The `code-review` skill retains reporting, severity mapping, attribution and resolution instructions.
45
47
 
46
48
  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.
47
49
 
@@ -211,14 +213,11 @@ must be selected before using issue tools. Existing `<active-profile>/review.jso
211
213
  The token needs issue access to that private repository. Prefer a narrowly scoped
212
214
  GitHub App installation token or fine-grained token; token rotation is managed by
213
215
  the operator. Without `writesEnabled: true`, GitHub writes fail closed. The
214
- `review_*` tools use repository issue IDs and revision checks, preserve discussion
215
- outside their managed block, and deduplicate creation by a stable finding `key`.
216
- Retry keys are persisted locally to handle GitHub's delayed issue listings.
217
- GitHub offers no atomic issue-create idempotency or conditional PATCH here: a
218
- crash between creation and saving the key, or separate MCP instances creating the
219
- same finding simultaneously, can still require manual reconciliation. Re-read
220
- before writes; revision checks cannot eliminate races with concurrent GitHub edits.
221
- Old internal findings are not migrated automatically. This compatibility adapter uses its own managed metadata format; the bundled `code-review` skill instead uses ordinary GitHub issues directly.
216
+ `issue_*` tools use revision checks and persistent retry keys. Re-read before
217
+ writes; GitHub offers no atomic conditional PATCH, so concurrent edits can still
218
+ race. Existing GitHub finding bodies and discussion remain readable through
219
+ `issue_get` and `issue_comments`, including legacy managed blocks. No issues or
220
+ local historical records are migrated or deleted automatically.
222
221
 
223
222
  The reusable private skill repository is separate from MCP-owned workflows.
224
223
  Automatic catalog cloning/polling and OAuth login in the local stdio bridge are
@@ -263,8 +262,10 @@ projects, hidden members, empty groups, credentials and internal paths are omitt
263
262
  Changes to access rules apply to subsequent requests.
264
263
 
265
264
  An authenticated client can call these tools at `/mcp` without
266
- `X-Agent-Repository`. Discovery tools and bundled `list_skills`/`get_skill` are
267
- available before repository selection. Private skill overrides require selection.
265
+ `X-Agent-Repository`. `list_skills` and `get_skill` expose bundled skills and
266
+ configured global skills from roots containing repositories the caller can read.
267
+ Default, pool and project skill overrides require repository selection. Conflicting
268
+ global skills across accessible roots require selecting a repository.
268
269
  Send `X-Agent-Repository: owner/repo` for knowledge, scoped skills, task and
269
270
  review tools. Discovery remains available after selection. Request a token with
270
271
  `read` and the desired repository scopes, such as `repo:*`; a token narrowed to
@@ -361,7 +362,7 @@ New clients and instructions use `brain_sync` and `brain_flush`. Bare chat
361
362
  ## Local service and knowledge guide
362
363
 
363
364
  Agent-brain owns canonical knowledge, specifications, skills, reviews, tasks,
364
- connectors, retrieval and configuration synchronization. Its project profile is
365
+ retrieval and configuration synchronization. Its project profile is
365
366
  `projects/technomoron/agent-brain` under the external configuration root;
366
367
  agent-run owns launcher configuration, native adapters and the client connection.
367
368
  Both projects remain members of the `agent-tools` pool. Source registrations and
@@ -524,15 +525,15 @@ the file into the corresponding directory. User preferences belong in
524
525
  `decisions/`. Code-derived facts remain inferred `observations/`; source
525
526
  references and history belong in `memory/`, with planned features labeled as
526
527
  plans. An import request does not make inferred content authoritative.
527
- Use the todo tools for tasks. Reusable workflows are `skills/<name>/SKILL.md`
528
+ Use `issue_*` and the `todo-manager` skill for tasks. Reusable workflows are `skills/<name>/SKILL.md`
528
529
  files, and reusable templates belong in `templates/`; `remember` does not
529
530
  install either. Global skills remain available without copying them into each
530
531
  project. The brain-memory skill explains these choices to native agents.
531
532
 
532
533
  Available MCP tools include `get_context`, `search_knowledge`, `get_knowledge`,
533
534
  `remember`, `amend_knowledge`, `list_knowledge`, `archive_knowledge`,
534
- `knowledge_history`, `promote`, `deprecate_knowledge`, `review_context`,
535
- `review_list`, `resolve_review`, `review_history`, and `review_archive`.
535
+ `knowledge_history`, `promote`, `deprecate_knowledge`, `review_context`, and
536
+ the `issue_*` tools.
536
537
  Writes use atomic file replacement and a shared lock; concurrent writes either
537
538
  complete or report that the caller should retry. After a crashed writer, stop
538
539
  the service, verify the PID in `runtime/brain-write.lock` is no longer running,
@@ -663,46 +664,20 @@ by id afterwards.
663
664
 
664
665
  #### Review findings
665
666
 
666
- Review knowledge is a numbered, prioritized list. `remember` requires a
667
- `severity` of `critical`, `high`, `medium`, or `low` when the type is `review`,
668
- and rejects `severity` for every other type. The store assigns the finding
669
- label itself: `C1`, `H1`, `M1`, `L1`, counting up per severity within the scope.
670
- Resolved numbers are never handed out again, so a label always refers to the
671
- same finding.
672
-
673
- Each finding also carries a `state` of `open`, `fixed`, or `wontfix`, separate
674
- from the `active` and `deprecated` status that controls recall. New findings
675
- start `open`.
676
-
677
- ```sh
678
- agent-brain review list
679
- agent-brain review list --severity high --state open
680
- agent-brain review resolve ITEM_ID --revision REVISION --state fixed "Fixed by using a stable command name"
681
- ```
667
+ Use the `code-review` skill and `issue_*` tools for findings, discussion and
668
+ history. `review_context` retrieves constraints and decisions for a review.
669
+ Close completed fixes only after validation and a linked fix comment; deferred
670
+ findings stay open. The skill retains severity mapping and reporting attribution.
682
671
 
683
- `review_list` returns findings in severity then number order, open ones only
684
- unless states are given, each with the revision needed to resolve it.
685
- `resolve_review` records the state and reason and takes the finding out of active
686
- recall. It writes a short record (label, title, outcome, date, reason, and original
687
- file/revision) to the scope's `review-history.jsonl`, then deletes the full finding
688
- file. `review-counters.json` preserves numbering. These files participate in brain
689
- Git sync but are excluded from normal knowledge retrieval.
690
-
691
- Use MCP `review_history` to recall old fixes, with optional `query`, `scope`, `state`,
692
- `offset`, and `limit` (default 100). The CLI equivalent is
693
- `agent-brain review history [query]`. Git retains full details only when the original
694
- files were committed before cleanup; the MCP history is sufficient for the short fix list.
695
- Use `review_archive` with a scope, or `agent-brain review archive --scope project`,
696
- to compact existing files already marked `fixed` or `wontfix`. Deferred findings
697
- remain open. Mark a finding `wontfix` only when the user explicitly drops it or
698
- confirms it is intentional. A request to postpone an issue does not close it.
699
-
700
- Finding labels are indexed, so `search_knowledge` for `H2` finds that finding.
701
- Review files written before these fields existed keep parsing; they simply carry
702
- no label and stay out of the finding list.
672
+ The legacy review tracking MCP tools and GitHub adapter have been removed.
673
+ `remember` rejects new review records. Existing local records remain readable
674
+ through knowledge tools and `agent-brain review list`; archived closures remain
675
+ available through `agent-brain review history [query]`. These CLI commands read
676
+ local history only; they do not query GitHub. Historical files and counters are
677
+ preserved, without automatic migration or deletion.
703
678
 
704
679
  Remembered deductions default to inferred authority and must remain observations,
705
- memories, or review records. Global writes require explicit user authority.
680
+ or memories. Global writes require explicit user authority.
706
681
  Promotion copies an item, records its origin, preserves the original, and requires
707
682
  confirmation. Deprecation and promotion require the last-read revision so stale
708
683
  requests cannot overwrite newer work. An agent's authority claim is an instruction
@@ -723,60 +698,17 @@ elsewhere into these directories before rendering or loading those skills.
723
698
 
724
699
  The packaged memory, consolidation, review and task skills document their workflows. New review findings belong in GitHub Issues through `code-review`.
725
700
 
726
- ### Tasks and connectors
727
-
728
- Tasks are separate from knowledge and stored in `todo/<id>.md`. Supported states
729
- are `todo`, `doing`, `blocked`, `done`, and `cancelled`. Tasks have titles,
730
- descriptions, priorities, owners, due dates, labels, notes, and optional external
731
- source identities.
701
+ ### Tasks
732
702
 
733
- ```sh
734
- agent-brain todo add --json '{"scope":"project","title":"Check refresh handling","priority":"high"}'
735
- agent-brain todo list
736
- agent-brain todo get ITEM_ID
737
- agent-brain todo complete ITEM_ID --revision REVISION
738
- ```
739
-
740
- MCP exposes `todo_list`, `todo_get`, `todo_add`, `todo_update`, `todo_complete`,
741
- `todo_import`, and `todo_sync`. Update requests require the current revision.
703
+ Manage todos through `issue_*` and the bundled `todo-manager` skill. Manual tasks
704
+ use origin label `ToDo`, normally work type `Task`, and the existing `Priority`
705
+ field. GitHub owns task identity, discussion, state and history.
742
706
 
743
- Configure optional connectors in `brain.jsonc`:
744
-
745
- ```jsonc
746
- {
747
- "enabled": true,
748
- "connectors": {
749
- "issues": {
750
- "type": "github",
751
- "repository": "my-org/my-project",
752
- "tokenEnv": "GITHUB_TOKEN"
753
- },
754
- "board": {
755
- "type": "trello",
756
- "board": "BOARD_ID",
757
- "keyEnv": "TRELLO_API_KEY",
758
- "tokenEnv": "TRELLO_TOKEN"
759
- }
760
- }
761
- }
762
- ```
763
-
764
- ```sh
765
- agent-brain todo import issues --scope project
766
- agent-brain todo sync issues --scope project
767
- ```
768
-
769
- Credentials are read from the process environment and never written to task files.
770
- Set credentials in the service's environment.
771
- GitHub imports paginate and exclude pull requests. Trello maps due-complete cards
772
- to done, archived cards to cancelled, and other cards to todo; it does not guess
773
- workflow states from list names.
774
-
775
- Imports deduplicate by source identity and scope. Synchronization compares local
776
- and remote fields against the last imported version, preserves local-only edits,
777
- and reports conflicting task IDs without replacing those tasks. Deleted remote
778
- items are retained locally. These connectors only read remote systems; completing
779
- a local task does not close a GitHub issue or modify a Trello card.
707
+ The legacy `todo_*` MCP tools, local task writes and GitHub/Trello imports are
708
+ retired. Existing `todo/<id>.md` files remain untouched and readable through
709
+ `agent-brain todo list` and `agent-brain todo get ITEM_ID`. These commands read
710
+ local history only. Old `brain.jsonc` connector settings are accepted but unused.
711
+ No automatic migration or deletion is performed.
780
712
 
781
713
  ### Git portability
782
714
 
@@ -918,12 +850,16 @@ or a separate authoritative cache.
918
850
 
919
851
  The initial implementation uses lexical retrieval and path matching. Embeddings,
920
852
  vector ranking, background watchers, debounced automatic Git synchronization,
921
- remote task writes, and additional connectors remain future work. No model
853
+ and additional retrieval methods remain future work. No model
922
854
  provider or external account is required for the local features.
923
855
 
924
- Transport and connector implementations follow the
856
+ Transport and issue implementations follow the
925
857
  [Node MCP SDK server documentation](https://ts.sdk.modelcontextprotocol.io/server),
926
- [GitHub Issues REST API](https://docs.github.com/en/rest/issues/issues), and
927
- [Trello board API](https://developer.atlassian.com/cloud/trello/rest/api-group-boards/).
858
+ [GitHub Issues REST API](https://docs.github.com/en/rest/issues/issues).
928
859
 
929
860
  Personal preferences and context retrieval are covered by bundled `brain-memory`; the separate `personal-memory` skill is retired.
861
+
862
+ Console login: `agent-run brain-login --user USER --password PASSWORD` prompts
863
+ for MFA when required. `agent-run brain-logout` revokes the session. Public
864
+ clients use the issuer’s `/console/login` and `/console/logout` endpoints; login
865
+ returns a PKCE-bound authorization code for the standard token exchange.
package/dist/brain/cli.js CHANGED
@@ -14,9 +14,7 @@ const consolidation_1 = require("./consolidation");
14
14
  const consolidation_skill_1 = require("./consolidation-skill");
15
15
  const skills_1 = require("./skills");
16
16
  const todos_1 = require("./todos");
17
- const connectors_1 = require("./connectors");
18
17
  const git_1 = require("./git");
19
- const github_reviews_1 = require("./github-reviews");
20
18
  // Parse CLI arguments and run the requested Brain command.
21
19
  async function brainMain(argv, wrapperCommand) {
22
20
  const { values, positionals } = (0, node_util_1.parseArgs)({ args: argv, allowPositionals: true, strict: true, options: {
@@ -59,12 +57,7 @@ async function brainMain(argv, wrapperCommand) {
59
57
  'agent-brain skills [name]',
60
58
  'agent-brain review list [--severity <level>] [--state <state>]',
61
59
  'agent-brain review history [query] [--scope <scope>] [--state fixed|wontfix]',
62
- 'agent-brain review archive --scope <scope>',
63
- 'agent-brain review resolve <id> --revision <hash> --state fixed|wontfix [reason]',
64
- 'agent-brain todo list | get <id> | add --json <task-object>',
65
- 'agent-brain todo update <id> --revision <hash> --json <changes>',
66
- 'agent-brain todo complete <id> --revision <hash>',
67
- 'agent-brain todo import|sync <connector> --scope <scope>',
60
+ 'agent-brain todo list | get <id> (local history only)',
68
61
  'agent-brain pull | push | save | sync [--message <commit-message>]',
69
62
  'agent-brain sync status | init',
70
63
  'agent-brain serve [--pull] [--socket <path>] | mcp [--socket <path>]',
@@ -130,6 +123,9 @@ async function brainMain(argv, wrapperCommand) {
130
123
  // Print a result with any broken-file diagnostics.
131
124
  const report = (value) => print(store.withDiagnostics(value));
132
125
  try {
126
+ if (['amend', 'promote', 'deprecate'].includes(command) && store.get(requireId()).type === 'review') {
127
+ throw new Error('Historical local findings are read-only; use MCP issue_* tools for review tracking');
128
+ }
133
129
  switch (command) {
134
130
  case 'status':
135
131
  report({ configRoot: root, enabled: (0, config_1.readBrainConfig)(root)?.enabled ?? false, profile: store.profile, scopes: store.scopes, knowledge: store.allKnowledge().length, todos: (0, todos_1.listTodos)(store).length });
@@ -143,9 +139,13 @@ async function brainMain(argv, wrapperCommand) {
143
139
  case 'get':
144
140
  report(store.get(requireId()));
145
141
  break;
146
- case 'remember':
147
- report(store.remember(store_1.knowledgeInput.parse(json())));
142
+ case 'remember': {
143
+ const input = store_1.knowledgeInput.parse(json());
144
+ if (input.type === 'review')
145
+ throw new Error('Use MCP issue_create and the code-review skill for findings');
146
+ report(store.remember(input));
148
147
  break;
148
+ }
149
149
  case 'promote':
150
150
  if (!values.confirmed)
151
151
  throw new Error('Promotion requires --confirmed after explicit user approval');
@@ -174,22 +174,6 @@ async function brainMain(argv, wrapperCommand) {
174
174
  break;
175
175
  case 'review': {
176
176
  const operation = positionals.shift() ?? 'list';
177
- const github = (0, github_reviews_1.githubReviews)(store);
178
- if (github) {
179
- if (operation === 'list' || operation === 'history') {
180
- const items = await github.list(operation === 'history' ? 'closed' : values.state && values.state !== 'open' ? 'closed' : 'open');
181
- report(items.filter((item) => (!values.severity || item.severity === values.severity) && (!values.state || item.state === values.state)));
182
- }
183
- else if (operation === 'get')
184
- report(await github.get(requireId()));
185
- else if (operation === 'create')
186
- report(await github.create(github_reviews_1.reviewInput.parse(json())));
187
- else if (operation === 'resolve')
188
- report(await github.resolve(requireId(), requireRevision(), zod_1.z.enum(['fixed', 'wontfix']).parse(values.state), positionals.slice(1).join(' ') || 'Resolved after verification'));
189
- else
190
- throw new Error('GitHub reviews support list, history, get, create and resolve; use review_update over MCP for edits');
191
- break;
192
- }
193
177
  if (operation === 'list') {
194
178
  report(store.reviews({
195
179
  ...(values.severity ? { severity: [store_1.severitySchema.parse(values.severity)] } : {}),
@@ -199,15 +183,8 @@ async function brainMain(argv, wrapperCommand) {
199
183
  else if (operation === 'history') {
200
184
  report(store.reviewHistory({ query: positionals.join(' '), ...(values.scope ? { scope: store_1.scopeSchema.parse(values.scope) } : {}), ...(values.state ? { state: zod_1.z.enum(['fixed', 'wontfix']).parse(values.state) } : {}), limit: Number.MAX_SAFE_INTEGER }));
201
185
  }
202
- else if (operation === 'archive') {
203
- report(store.archiveReviews(store_1.scopeSchema.parse(values.scope)));
204
- }
205
- else if (operation === 'resolve') {
206
- const state = zod_1.z.enum(['fixed', 'wontfix']).parse(values.state);
207
- report(store.resolveReview(requireId(), requireRevision(), state, positionals.slice(1).join(' ') || undefined));
208
- }
209
186
  else
210
- throw new Error('Usage: agent-brain review list | resolve <id> --revision <hash> --state fixed|wontfix');
187
+ throw new Error('Legacy review tracking is retired; use MCP issue_* tools. Local history: agent-brain review list | history');
211
188
  break;
212
189
  }
213
190
  case 'pull':
@@ -235,16 +212,8 @@ async function brainMain(argv, wrapperCommand) {
235
212
  report((0, todos_1.listTodos)(store));
236
213
  else if (operation === 'get')
237
214
  report((0, todos_1.getTodo)(store, requireId()));
238
- else if (operation === 'add')
239
- report((0, todos_1.addTodo)(store, todos_1.todoInput.parse(json())));
240
- else if (operation === 'update')
241
- report((0, todos_1.updateTodo)(store, requireId(), requireRevision(), todos_1.todoChanges.parse(json())));
242
- else if (operation === 'complete')
243
- report((0, todos_1.updateTodo)(store, requireId(), requireRevision(), { status: 'done' }));
244
- else if (operation === 'import' || operation === 'sync')
245
- report(await (0, connectors_1.syncConnector)(store, requireId(), store_1.scopeSchema.parse(values.scope)));
246
215
  else
247
- throw new Error('Unknown todo command; use agent-brain --help');
216
+ throw new Error('Legacy todo tracking is retired; use MCP issue_* tools and the todo-manager skill. Local history: agent-brain todo list | get <id>');
248
217
  break;
249
218
  }
250
219
  case 'project': {
@@ -32,6 +32,7 @@ exports.brainConfigSchema = zod_1.z.object({
32
32
  scope: zod_1.z.string().default('read write review repo:*')
33
33
  }).strict().optional(),
34
34
  contextBudget: zod_1.z.number().int().min(1000).max(100000).default(16000),
35
+ // Accept old connector settings without importing tasks into a parallel store.
35
36
  connectors: zod_1.z.record(zod_1.z.string().regex(/^[a-zA-Z0-9_-]+$/), zod_1.z.discriminatedUnion('type', [
36
37
  zod_1.z.object({ type: zod_1.z.literal('github'), repository: zod_1.z.string().regex(/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/), tokenEnv: zod_1.z.string().regex(/^[A-Z_][A-Z0-9_]*$/).default('GITHUB_TOKEN') }).strict(),
37
38
  zod_1.z.object({ type: zod_1.z.literal('trello'), board: zod_1.z.string().regex(/^[a-zA-Z0-9]+$/), keyEnv: zod_1.z.string().regex(/^[A-Z_][A-Z0-9_]*$/).default('TRELLO_API_KEY'), tokenEnv: zod_1.z.string().regex(/^[A-Z_][A-Z0-9_]*$/).default('TRELLO_TOKEN') }).strict()
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GithubClient = void 0;
4
+ exports.githubIssueConfig = githubIssueConfig;
5
+ const fs = require("node:fs");
6
+ const jsonc_parser_1 = require("jsonc-parser");
7
+ const zod_1 = require("zod");
8
+ const repositories_1 = require("./repositories");
9
+ const config_1 = require("./config");
10
+ const configSchema = zod_1.z.object({ backend: zod_1.z.literal('github'), repository: repositories_1.repositoryId.optional(),
11
+ tokenEnv: zod_1.z.string().regex(/^[A-Z_][A-Z0-9_]*$/).default('GITHUB_TOKEN'), writesEnabled: zod_1.z.boolean().default(false) }).strict();
12
+ class GithubClient {
13
+ // Bind the issue client to its store, configuration and GitHub repository.
14
+ constructor(store, config, repository) {
15
+ this.store = store;
16
+ this.config = config;
17
+ this.repository = repository;
18
+ }
19
+ // Send an authenticated GitHub issue request with time and size limits.
20
+ async request(route, method = 'GET', body) {
21
+ return this.requestApi('/repos/' + this.repository + '/issues' + route, method, body);
22
+ }
23
+ // Send a bounded request to a fixed GitHub API path.
24
+ async requestApi(route, method = 'GET', body) {
25
+ const token = process.env[this.config.tokenEnv];
26
+ if (!token)
27
+ throw new Error('Set ' + this.config.tokenEnv + ' for GitHub issues');
28
+ const response = await fetch('https://api.github.com' + route, {
29
+ method, redirect: 'error', signal: AbortSignal.timeout(30000), headers: { accept: 'application/vnd.github+json',
30
+ 'content-type': 'application/json', 'user-agent': 'agent-brain', authorization: 'Bearer ' + token,
31
+ 'X-GitHub-Api-Version': '2026-03-10' }, ...(body ? { body: JSON.stringify(body) } : {})
32
+ });
33
+ if (!response.ok)
34
+ throw new Error('GitHub request failed with HTTP ' + response.status + (response.status === 403 ? '; check token permissions, organisation policy and rate limits' : ''));
35
+ if (response.status === 204)
36
+ return null;
37
+ const text = await response.text();
38
+ if (text.length > 4 * 1024 * 1024)
39
+ throw new Error('GitHub response exceeds 4 MiB');
40
+ return JSON.parse(text);
41
+ }
42
+ // Serialize GitHub writes and enforce the explicit write gate.
43
+ async locked(work) {
44
+ if (!this.config.writesEnabled)
45
+ throw new Error('GitHub issue writes are disabled; configure writesEnabled explicitly');
46
+ const lock = this.store.safePath('runtime', 'github-review.lock');
47
+ const descriptor = fs.openSync(lock, 'wx', 0o600);
48
+ try {
49
+ return await work();
50
+ }
51
+ finally {
52
+ fs.closeSync(descriptor);
53
+ fs.unlinkSync(lock);
54
+ }
55
+ }
56
+ }
57
+ exports.GithubClient = GithubClient;
58
+ // Resolve the repository-bound GitHub configuration used by issue tools.
59
+ function githubIssueConfig(store, selectedRepository) {
60
+ const local = store.safePath(store.profile ?? 'default', 'review.jsonc');
61
+ const global = !fs.existsSync(local);
62
+ const file = global ? store.safePath('global', 'review.jsonc') : local;
63
+ if (!fs.existsSync(file))
64
+ return null;
65
+ const errors = [];
66
+ const document = (0, jsonc_parser_1.parse)(store.read(file), errors);
67
+ if (errors.length)
68
+ throw new Error('Invalid review.jsonc');
69
+ const config = global ? configSchema.omit({ repository: true }).parse(document) : configSchema.parse(document);
70
+ const project = (0, config_1.listBrainProjects)(store.configRoot).find((item) => item.profile === store.profile);
71
+ const registered = project?.repository?.url ? (0, repositories_1.githubRepository)(project.repository.url) : null;
72
+ const repository = global
73
+ ? selectedRepository ?? registered ?? (repositories_1.repositoryId.safeParse(project?.name).success ? project.name : null)
74
+ : ('repository' in config ? config.repository : undefined) ?? registered;
75
+ if (!repository)
76
+ throw new Error('GitHub issues need an explicit repository or a registered GitHub remote');
77
+ return { config, repository: repositories_1.repositoryId.parse(repository) };
78
+ }
@@ -5,7 +5,7 @@ exports.githubIssues = githubIssues;
5
5
  const fs = require("node:fs");
6
6
  const node_crypto_1 = require("node:crypto");
7
7
  const zod_1 = require("zod");
8
- const github_reviews_1 = require("./github-reviews");
8
+ const github_client_1 = require("./github-client");
9
9
  exports.issueOrigin = zod_1.z.enum(['Code Review', 'Bug Report', 'Feature Request', 'ToDo', 'Question']);
10
10
  exports.issueType = zod_1.z.enum(['Bug', 'Security', 'Feature', 'Task', 'Inconsistency', 'Question', 'Documentation']);
11
11
  exports.issuePriority = zod_1.z.enum(['Urgent', 'High', 'Medium', 'Low']);
@@ -31,7 +31,7 @@ const comment = zod_1.z.object({ id: exports.issueNumber, body: zod_1.z.string()
31
31
  const hash = (value) => (0, node_crypto_1.createHash)('sha256').update(JSON.stringify(value)).digest('hex');
32
32
  // Add a revision without discarding GitHub metadata.
33
33
  const snapshot = (value) => ({ ...value, revision: hash(value) });
34
- class GithubIssues extends github_reviews_1.GithubReviews {
34
+ class GithubIssues extends github_client_1.GithubClient {
35
35
  // Keep cross-repository operations subject to the requesting MCP identity's grants.
36
36
  constructor(store, config, repository, access, organisationAccess) {
37
37
  super(store, config, repository);
@@ -40,7 +40,7 @@ class GithubIssues extends github_reviews_1.GithubReviews {
40
40
  }
41
41
  // Share the bounded authenticated transport with deterministic configuration reconciliation.
42
42
  configurationRequest(route, method = 'GET', body) { return this.requestApi(route, method, body); }
43
- // Serialize configuration changes with ordinary issue and legacy review writes.
43
+ // Serialize configuration changes with issue writes.
44
44
  configurationLock(work) { return this.locked(work); }
45
45
  // Request repository metadata without accepting caller-supplied URLs.
46
46
  async metadata(kind, page, per_page) {
@@ -327,6 +327,6 @@ class GithubIssues extends github_reviews_1.GithubReviews {
327
327
  exports.GithubIssues = GithubIssues;
328
328
  // Load ordinary issue tools using the existing repository-bound GitHub backend configuration.
329
329
  function githubIssues(store, access, organisationAccess, selectedRepository) {
330
- const settings = (0, github_reviews_1.githubReviewConfig)(store, selectedRepository);
330
+ const settings = (0, github_client_1.githubIssueConfig)(store, selectedRepository);
331
331
  return settings ? new GithubIssues(store, settings.config, settings.repository, access, organisationAccess) : null;
332
332
  }
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerIssueConfigurationTools = registerIssueConfigurationTools;
4
+ const fs = require("node:fs");
5
+ const jsonc_parser_1 = require("jsonc-parser");
6
+ const zod_1 = require("zod");
7
+ const github_issues_1 = require("./github-issues");
8
+ const issue_configuration_1 = require("./issue-configuration");
9
+ // Register configuration cleanup separately, retaining the repository-bound issue tool permissions.
10
+ function registerIssueConfigurationTools(tool, store) {
11
+ // Load optional presentation metadata while retaining the exhaustive built-in taxonomy.
12
+ function configuration(github) {
13
+ const file = store.safePath(store.profile ?? 'default', 'issue-standard.jsonc');
14
+ const errors = [];
15
+ const standard = fs.existsSync(file) ? (0, jsonc_parser_1.parse)(store.read(file), errors, { allowTrailingComma: true }) : {};
16
+ if (errors.length)
17
+ throw new Error('Invalid issue-standard.jsonc');
18
+ return new issue_configuration_1.IssueConfiguration(github, standard);
19
+ }
20
+ tool('issue_label_ensure', 'Create one missing allowed origin label in the selected repository and verify it. Existing labels are preserved; no issues, organisation types or fields are changed.', {
21
+ origin: github_issues_1.issueOrigin, confirmed: zod_1.z.literal(true)
22
+ }, false, ({ origin }, github) => configuration(github).ensureLabel(origin));
23
+ tool('issue_config_preview', 'Preview deterministic issue-standard reconciliation, migrations and blockers. No writes. Check the returned affected issues and revision before applying.', {
24
+ settings: issue_configuration_1.reconciliationSettings.prefault({})
25
+ }, true, async ({ settings }, github) => { const config = configuration(github); return config.publicPreview(await config.preview(settings)); });
26
+ 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.', {
27
+ settings: issue_configuration_1.reconciliationSettings.prefault({}), revision: github_issues_1.issueRevision, confirmed: zod_1.z.literal(true)
28
+ }, false, ({ settings, revision }, github) => configuration(github).apply(settings, revision));
29
+ }
@@ -74,6 +74,22 @@ class IssueConfiguration {
74
74
  this.standard = exports.issueStandardSchema.parse(standard);
75
75
  this.owner = github.repository.split('/')[0];
76
76
  }
77
+ // Create one missing allowed origin label without reconciling any other definitions or issues.
78
+ async ensureLabel(input) {
79
+ const name = github_issues_1.issueOrigin.parse(input);
80
+ return this.github.configurationLock(async () => {
81
+ const route = '/repos/' + this.github.repository + '/labels';
82
+ const labels = zod_1.z.array(labelSchema).parse(await this.all(route));
83
+ const existing = labels.find(value => value.name.toLowerCase() === name.toLowerCase());
84
+ if (existing)
85
+ return { repository: this.github.repository, created: false, label: existing };
86
+ await this.github.configurationRequest(route, 'POST', { name, ...this.standard.labels[name] });
87
+ const saved = zod_1.z.array(labelSchema).parse(await this.all(route)).find(value => value.name === name);
88
+ if (!saved)
89
+ throw new Error('GitHub did not save origin label ' + name + '; read labels before retrying');
90
+ return { repository: this.github.repository, created: true, label: saved };
91
+ });
92
+ }
77
93
  // Page without silent truncation; an incomplete inventory must never authorize a removal.
78
94
  async all(route) {
79
95
  const result = [];
@@ -2,10 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.registerIssueTools = registerIssueTools;
4
4
  const zod_1 = require("zod");
5
- const fs = require("node:fs");
6
- const jsonc_parser_1 = require("jsonc-parser");
7
5
  const github_issues_1 = require("./github-issues");
8
- const issue_configuration_1 = require("./issue-configuration");
6
+ const issue_configuration_tools_1 = require("./issue-configuration-tools");
9
7
  const repositories_1 = require("./repositories");
10
8
  // Register ordinary issue tools against the existing repository-bound GitHub configuration.
11
9
  function registerIssueTools(server, store, options) {
@@ -29,15 +27,7 @@ function registerIssueTools(server, store, options) {
29
27
  }
30
28
  });
31
29
  }
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
- }
30
+ (0, issue_configuration_tools_1.registerIssueConfigurationTools)(tool, store);
41
31
  tool('issue_search', 'Search only the configured repository using literal text and structured filters. Reports incomplete results and the GitHub 1000-result cap.', {
42
32
  ...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
33
  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(),
@@ -52,19 +42,13 @@ function registerIssueTools(server, store, options) {
52
42
  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
43
  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
44
  }, 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
45
  tool('issue_list', 'List ordinary GitHub issues in the configured repository. PRs are excluded; next_page follows upstream pagination.', {
62
46
  ...github_issues_1.issuePage, state: zod_1.z.enum(['open', 'closed', 'all']).default('open'), origin: github_issues_1.issueOrigin.optional(),
63
47
  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
48
  }, true, (input, github) => github.listIssues(input));
65
49
  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.', {
50
+ tool('issue_create', 'Create an authorized issue with origin, work type and Priority. For review findings load code-review and include severity, evidence and affected paths in body. 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));
51
+ 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. Validate completed fixes and add a linked fix comment before closure; deferred findings stay open.', {
68
52
  number: github_issues_1.issueNumber, revision: github_issues_1.issueRevision, confirmed: zod_1.z.literal(true), changes: github_issues_1.issueChanges
69
53
  }, false, ({ number, revision, changes }, github) => github.updateIssue(number, revision, changes));
70
54
  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));
@@ -121,19 +121,16 @@ function repositoryPermissions(config, subject, clientId, scopes, repo) {
121
121
  return new Set(config.access.filter((rule) => rule.subject === subject && rule.repos.some((p) => (0, repositories_1.matchesRepository)(p, repo)))
122
122
  .flatMap((rule) => rule.permissions).filter((op) => scopes.includes(op) && client.permissions.includes(op)));
123
123
  }
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']);
125
- const reviewTools = new Set(['review_create', 'review_update', 'resolve_review']);
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']);
126
125
  // Classify a tool by required permission and reject unsupported remote tools.
127
126
  function toolPermission(name) {
128
127
  if (['issue_list', 'issue_get', 'issue_comments', 'issue_search', 'issue_metadata', 'issue_relations', 'issue_config_preview'].includes(name))
129
128
  return 'read';
130
- if (['issue_create', 'issue_update', 'issue_comment', 'issue_comment_update', 'issue_relation_update', 'issue_config_reconcile'].includes(name))
129
+ if (['issue_create', 'issue_update', 'issue_comment', 'issue_comment_update', 'issue_relation_update', 'issue_config_reconcile', 'issue_label_ensure'].includes(name))
131
130
  return 'write';
132
131
  if (readTools.has(name))
133
132
  return 'read';
134
- if (reviewTools.has(name))
135
- return 'review';
136
- if (['sync_status', 'todo_import', 'todo_sync', 'review_archive'].includes(name))
133
+ if (['sync_status'].includes(name))
137
134
  return null;
138
- return ['brain_sync', 'brain_flush', 'sync', 'flush', 'remember', 'amend_knowledge', 'promote', 'deprecate_knowledge', 'todo_add', 'todo_update', 'todo_complete'].includes(name) ? 'write' : null;
135
+ return ['brain_sync', 'brain_flush', 'sync', 'flush', 'remember', 'amend_knowledge', 'promote', 'deprecate_knowledge'].includes(name) ? 'write' : null;
139
136
  }