@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.
Files changed (53) hide show
  1. package/CHANGES.md +26 -0
  2. package/README.md +117 -44
  3. package/dist/brain/built-in-skills.js +2 -0
  4. package/dist/brain/cli.js +8 -0
  5. package/dist/brain/config.js +7 -0
  6. package/dist/brain/connectors.js +2 -0
  7. package/dist/brain/consolidation.js +4 -0
  8. package/dist/brain/git.js +9 -2
  9. package/dist/brain/github-issues.js +332 -0
  10. package/dist/brain/github-reviews.js +38 -7
  11. package/dist/brain/issue-configuration.js +382 -0
  12. package/dist/brain/issue-tools.js +77 -0
  13. package/dist/brain/projects.js +4 -6
  14. package/dist/brain/remote-policy.js +16 -3
  15. package/dist/brain/remote-server.js +67 -12
  16. package/dist/brain/repositories.js +3 -0
  17. package/dist/brain/repository-discovery.js +22 -1
  18. package/dist/brain/server.js +17 -3
  19. package/dist/brain/skills.js +11 -0
  20. package/dist/brain/store.js +36 -1
  21. package/dist/brain/todos.js +10 -1
  22. package/dist/brain/windows-pipe.js +2 -1
  23. package/dist/version.js +1 -4
  24. package/examples/remote.jsonc +1 -1
  25. package/ops/brain-pipe-security.ps1 +40 -0
  26. package/ops/config-deploy-entry.sh +1 -1
  27. package/ops/config-deploy-root.cjs +14 -6
  28. package/ops/config-deploy.cjs +16 -8
  29. package/ops/config-policy.cjs +37 -1
  30. package/ops/config-sync.cjs +34 -1
  31. package/ops/layout.cjs +13 -0
  32. package/package.json +9 -6
  33. package/skills/brain-consolidate/README.md +5 -0
  34. package/skills/brain-import/README.md +5 -0
  35. package/skills/brain-memory/README.md +5 -0
  36. package/skills/brain-memory/SKILL.md +7 -3
  37. package/skills/code-review/README.md +7 -0
  38. package/skills/code-review/SKILL.md +58 -0
  39. package/skills/git-workflow/README.md +5 -0
  40. package/skills/git-workflow/SKILL.md +14 -0
  41. package/skills/node-cleanup/README.md +5 -0
  42. package/skills/node-cleanup/SKILL.md +239 -0
  43. package/skills/node-cleanup/agents/openai.yaml +4 -0
  44. package/skills/package-integrity-check/README.md +5 -0
  45. package/skills/package-integrity-check/SKILL.md +27 -0
  46. package/skills/todo-manager/README.md +5 -0
  47. package/skills/todo-manager/SKILL.md +13 -3
  48. package/skills/unslop/README.md +5 -0
  49. package/skills/unslop/SKILL.md +180 -0
  50. package/skills/unslop/agents/openai.yaml +4 -0
  51. package/skills/brain-review/SKILL.md +0 -38
  52. package/skills/code-review-organizer/SKILL.md +0 -150
  53. package/skills/review-items/SKILL.md +0 -43
package/CHANGES.md CHANGED
@@ -1,3 +1,29 @@
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
+
6
+ Version 0.1.3 (2026-10-23)
7
+ --------------------------
8
+ * Simplify internal helpers and add concise function and method comments.
9
+
10
+ Version 0.1.2 (2026-10-23)
11
+ --------------------------
12
+ * Preserve repeated sync exports, reversals and deletions before deployment.
13
+ * Sync skill support files and tracked skill/task deletions.
14
+ * Enforce shared-scope write permissions for legacy repository groups.
15
+ * Include the Windows pipe ACL helper in the package.
16
+ * Create severity labels when the GitHub Severity field is unavailable.
17
+ * Use fictional organization examples.
18
+ * Bundle unslop and merge personal-memory guidance into brain-memory.
19
+ * Serve node-cleanup from the agent-brain bundle and remove the pnmp typo rule.
20
+ * Bundle package-integrity-check in place of release-package-check.
21
+ * Bundle Git operations and commit policy in git-workflow.
22
+ * Load all Brain workflows directly from the package instead of installing configuration copies.
23
+ * Track reviews and tasks with GitHub issue types and structured severity.
24
+ * Serve one bundled code-review workflow using ordinary GitHub issues, with optional local overrides.
25
+ * Support plaintext or hashed remote login passwords.
26
+
1
27
  Version 0.1.1 (2026-10-22)
2
28
  --------------------------
3
29
  * Allow independent repositories without a pool in configuration deployment and Git sync.
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
 
@@ -49,11 +37,13 @@ Operational systemd and Windows installation scripts remain in agent-run, which
49
37
 
50
38
  ## MCP-owned skills
51
39
 
52
- The server owns the Markdown sources under `skills/`: `brain-consolidate`, `brain-import`, `brain-memory`, `brain-review`, `code-review-organizer`, `review-items`, and `todo-manager`. These were extracted from the current external shared skill set on 2026-10-16. The project-specific consolidation copy was identical and is represented once.
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/`.
53
41
 
54
- Initialization reads these packaged sources and installs missing skills into the external global skill directory. Existing customized installations are preserved. Consolidation’s CLI fallback also reads its packaged Markdown source; there is no separate embedded copy of that workflow. The existing ordinary-conversation retrieval and task-authorization guards are retained in the packaged memory and task skills.
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
- Keep MCP-owned skills and tools with this implementation. Independent reusable skills belong in the private catalog. The live configuration is unchanged by the source extraction; use initialization explicitly when installing missing packaged skills.
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.
45
+
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.
57
47
 
58
48
  ## Shared skill catalog
59
49
 
@@ -61,19 +51,15 @@ Keep MCP-owned skills and tools with this implementation. Independent reusable s
61
51
 
62
52
  ## Releases
63
53
 
64
- The release workflow publishes `@technomoron/agent-brain` on npm with public
65
- access. Tags use `@technomoron/agent-brain@<version>` and must match the package
66
- version. Run `pnpm release:preflight` before committing and tagging a release.
67
- The workflow checks the tag, runs the integration suite, and attaches the package
68
- tarball to its GitHub release. Configure `NPM_TOKEN` in the source repository for
69
- 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.
70
56
 
71
57
  ## Remote OAuth endpoint
72
58
 
73
59
  The remote endpoint uses the generic OAuth APIs in
74
60
  `@technomoron/apicore-server` 1.1.0 or newer. Normal npm installations include
75
61
  that dependency. When developing changes to apicore locally, build the sibling
76
- `../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
77
63
  dependencies replaces this development link.
78
64
 
79
65
  Copy `examples/remote.jsonc` outside the source tree and customize absolute paths.
@@ -81,8 +67,11 @@ Create each repository's separate configuration root using `agent-brain init
81
67
  --configdir <root> --cwd <checkout>`. Run the server as a dedicated OS user with a
82
68
  private runtime directory (0700). Supply two different random signing secrets of
83
69
  at least 32 characters through `MCP_OAUTH_ACCESS_SECRET` and
84
- `MCP_OAUTH_REFRESH_SECRET`. Human passwords are bcrypt hashes supplied through the
85
- configured environment variables; optional TOTP secrets are base32 values enrolled
70
+ `MCP_OAUTH_REFRESH_SECRET`. Set each human user's `passwordEnv` to a plaintext
71
+ password environment variable, or `passwordHashEnv` to a bcrypt hash variable;
72
+ choose one. Plaintext passwords are hashed in memory at startup. Keep the
73
+ environment file private and restart after password changes.
74
+ Optional TOTP secrets are base32 values enrolled
86
75
  in the user's authenticator. Enrolment and password management are administrator
87
76
  operations. Service accounts use confidential client secrets from the environment.
88
77
  Never put credentials in source control or client command arguments.
@@ -134,8 +123,86 @@ and unfinished login forms are deliberately lost on restart.
134
123
 
135
124
  ## Reviews as GitHub Issues
136
125
 
137
- Create `<active-profile>/review.jsonc` (or `default/review.jsonc`) inside the
138
- 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:
139
206
 
140
207
  ```json
141
208
  {"backend":"github","repository":"technomoron/agent-run","tokenEnv":"MCP_GITHUB_TOKEN","writesEnabled":true}
@@ -151,9 +218,7 @@ GitHub offers no atomic issue-create idempotency or conditional PATCH here: a
151
218
  crash between creation and saving the key, or separate MCP instances creating the
152
219
  same finding simultaneously, can still require manual reconciliation. Re-read
153
220
  before writes; revision checks cannot eliminate races with concurrent GitHub edits.
154
- Old internal findings are not migrated automatically. Packaged review skills
155
- select their backend through `brain_status`; existing customized installations
156
- must adopt that backend-selection section before using GitHub reviews.
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.
157
222
 
158
223
  The reusable private skill repository is separate from MCP-owned workflows.
159
224
  Automatic catalog cloning/polling and OAuth login in the local stdio bridge are
@@ -162,7 +227,7 @@ not implemented by this change.
162
227
  ## Repository groups
163
228
 
164
229
  A remote configuration can declare `groups: [{"id":"agent-tools",
165
- "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"`
166
231
  and that same `configRoot` on each member of `repositories`. Each member keeps
167
232
  its own repository ID and working directory. Register its project at
168
233
  `<configRoot>/projects/<owner>/<repo>/config.yaml` with `name: owner/repo` and
@@ -198,8 +263,9 @@ projects, hidden members, empty groups, credentials and internal paths are omitt
198
263
  Changes to access rules apply to subsequent requests.
199
264
 
200
265
  An authenticated client can call these tools at `/mcp` without
201
- `X-Agent-Repository`. Only the discovery tools are available until a repository
202
- 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
203
269
  review tools. Discovery remains available after selection. Request a token with
204
270
  `read` and the desired repository scopes, such as `repo:*`; a token narrowed to
205
271
  one repository will only discover that repository, even if the user can access
@@ -211,12 +277,12 @@ catalog; local access follows the existing OS-user trust model.
211
277
  Use one configuration root with three parallel directories:
212
278
 
213
279
  ```text
214
- global/ # knowledge and skills shared by all repositories
215
- pools/documentmedia/ # knowledge and skills shared by this pool
216
- projects/documentmedia/doc-api/ # repository knowledge, reviews and tasks
280
+ global/ # knowledge and skills shared by all repositories
281
+ pools/acme/ # knowledge and skills shared by this pool
282
+ projects/acme/catalog-api/ # repository knowledge, reviews and tasks
217
283
  ```
218
284
 
219
- Set `pool: documentmedia` in each member's `projects/<owner>/<repo>/config.yaml`.
285
+ Set `pool: acme` in each member's `projects/<owner>/<repo>/config.yaml`.
220
286
  The MCP reads only global, the active repository's pool, and that repository.
221
287
  Skills with the same name resolve in repository, pool, global order. A skill can
222
288
  extend an ancestor with `extends: global:name` or `extends: pool:name`.
@@ -254,8 +320,14 @@ compatibility; the application and package are named agent-brain.
254
320
 
255
321
  ### Export Brain changes to Git
256
322
 
257
- Configure `gitSync: {"catalog":"/var/lib/agent-mcp/catalogs/agent-brain-config",
258
- "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
259
331
  server configuration. The catalog origin must grant SSH write access, and its
260
332
  local `user.name` and `user.email` must identify the configured human author.
261
333
  The deployment state must contain its successful deployment baseline.
@@ -649,9 +721,7 @@ including template. Nunjucks variables remain available. Symlinks are rejected,
649
721
  and each file is limited to 1 MiB. Move snippets and skill overrides stored
650
722
  elsewhere into these directories before rendering or loading those skills.
651
723
 
652
- The installed `brain-memory`, `brain-consolidate`, `brain-review`, and `todo-manager`
653
- skills describe retrieval, persistence, consolidation, review learning, and task workflows. Review records use
654
- the knowledge tools and remain inferred unless confirmed by the user.
724
+ The packaged memory, consolidation, review and task skills document their workflows. New review findings belong in GitHub Issues through `code-review`.
655
725
 
656
726
  ### Tasks and connectors
657
727
 
@@ -746,6 +816,7 @@ not identify Brain as the target. Agents still need a user request or standing
746
816
  authorization to sync.
747
817
 
748
818
  Saving includes Markdown knowledge, skills, tasks, project metadata, and `.gitignore`.
819
+ Skill support files and tracked skill/task deletions are included.
749
820
  It also includes all regular files under each scope's `templates/` directory,
750
821
  including nested Nunjucks templates and supporting files. Template additions,
751
822
  edits, and deletions are synced; symlinks are rejected.
@@ -854,3 +925,5 @@ Transport and connector implementations follow the
854
925
  [Node MCP SDK server documentation](https://ts.sdk.modelcontextprotocol.io/server),
855
926
  [GitHub Issues REST API](https://docs.github.com/en/rest/issues/issues), and
856
927
  [Trello board API](https://developer.atlassian.com/cloud/trello/rest/api-group-boards/).
928
+
929
+ Personal preferences and context retrieval are covered by bundled `brain-memory`; the separate `personal-memory` skill is retired.
@@ -8,6 +8,7 @@ const zod_1 = require("zod");
8
8
  const store_1 = require("./store");
9
9
  const directory = path.resolve(__dirname, '..', '..', 'skills');
10
10
  const metadata = zod_1.z.object({ name: zod_1.z.string(), description: zod_1.z.string().min(1) });
11
+ // Read and validate a bundled skill by name.
11
12
  function readBuiltInSkill(name) {
12
13
  if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name))
13
14
  throw new Error(`Invalid built-in skill name: ${name}`);
@@ -17,6 +18,7 @@ function readBuiltInSkill(name) {
17
18
  throw new Error(`Built-in skill name must match directory: ${name}`);
18
19
  return { description: parsed.description, content: document.content };
19
20
  }
21
+ // Load all bundled skills in name order.
20
22
  function readBuiltInSkills() {
21
23
  return Object.fromEntries(fs.readdirSync(directory, { withFileTypes: true })
22
24
  .filter((entry) => entry.isDirectory()).sort((a, b) => a.name.localeCompare(b.name))
package/dist/brain/cli.js CHANGED
@@ -17,6 +17,7 @@ const todos_1 = require("./todos");
17
17
  const connectors_1 = require("./connectors");
18
18
  const git_1 = require("./git");
19
19
  const github_reviews_1 = require("./github-reviews");
20
+ // Parse CLI arguments and run the requested Brain command.
20
21
  async function brainMain(argv, wrapperCommand) {
21
22
  const { values, positionals } = (0, node_util_1.parseArgs)({ args: argv, allowPositionals: true, strict: true, options: {
22
23
  configdir: { type: 'string' }, cwd: { type: 'string' }, socket: { type: 'string' },
@@ -43,6 +44,7 @@ async function brainMain(argv, wrapperCommand) {
43
44
  }
44
45
  if (values.pull && command !== 'serve')
45
46
  throw new Error('--pull is only supported by serve');
47
+ // Print a JSON result to standard output.
46
48
  const print = (value) => { process.stdout.write(`${JSON.stringify(value, null, 2)}\n`); };
47
49
  if (values.help || command === 'help') {
48
50
  process.stdout.write([
@@ -102,6 +104,7 @@ async function brainMain(argv, wrapperCommand) {
102
104
  const service = await serveApiCore(root, socket);
103
105
  process.stderr.write(`agent-brain listening on ${socket}\n`);
104
106
  let closing = false;
107
+ // Close the local service once and report shutdown failures.
105
108
  const close = () => { if (!closing) {
106
109
  closing = true;
107
110
  void service.close().catch((error) => { process.stderr.write(`${String(error)}\n`); process.exitCode = 1; });
@@ -115,12 +118,16 @@ async function brainMain(argv, wrapperCommand) {
115
118
  return;
116
119
  }
117
120
  const store = new store_1.BrainStore(root, cwd);
121
+ // Require an item ID at the requested argument position.
118
122
  const requireId = (index = 0) => { const id = positionals[index]; if (!id)
119
123
  throw new Error('An item id is required'); return id; };
124
+ // Require the revision supplied for an update.
120
125
  const requireRevision = () => { if (!values.revision)
121
126
  throw new Error('--revision is required; read the item first'); return values.revision; };
127
+ // Parse the required JSON command argument.
122
128
  const json = () => { if (!values.json)
123
129
  throw new Error('--json is required'); return JSON.parse(values.json); };
130
+ // Print a result with any broken-file diagnostics.
124
131
  const report = (value) => print(store.withDiagnostics(value));
125
132
  try {
126
133
  switch (command) {
@@ -259,6 +266,7 @@ async function brainMain(argv, wrapperCommand) {
259
266
  store.close();
260
267
  }
261
268
  }
269
+ // Print a command failure and set the process exit status.
262
270
  function reportBrainError(error) {
263
271
  process.stderr.write(`agent-brain: ${error instanceof Error ? error.message : String(error)}\n`);
264
272
  process.exitCode = 1;
@@ -15,6 +15,7 @@ const jsonc_parser_1 = require("jsonc-parser");
15
15
  const yaml_1 = require("yaml");
16
16
  const zod_1 = require("zod");
17
17
  const utils_1 = require("@technomoron/agent-run/dist/utils");
18
+ // Choose a local socket or user-specific Windows pipe for this configuration.
18
19
  function defaultSocketPath(configRoot) {
19
20
  if (process.platform === 'win32') {
20
21
  const identity = `${os.homedir().toLowerCase()}\0${path.resolve(configRoot).toLowerCase()}`;
@@ -36,6 +37,7 @@ exports.brainConfigSchema = zod_1.z.object({
36
37
  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()
37
38
  ])).default({})
38
39
  }).strict();
40
+ // Read and validate optional Brain JSONC configuration.
39
41
  function readBrainConfig(root) {
40
42
  const file = path.join(root, 'brain.jsonc');
41
43
  if (!fs.existsSync(file))
@@ -55,10 +57,12 @@ exports.projectConfigSchema = zod_1.z.object({
55
57
  repository: zod_1.z.object({ url: zod_1.z.string() }).optional(),
56
58
  agent: zod_1.z.object({ default: zod_1.z.enum(['codex', 'claude', 'gemini', 'grok']).default('codex') }).default({ default: 'codex' })
57
59
  }).strict();
60
+ // Read registered projects from the configuration tree.
58
61
  function listBrainProjects(configRoot) {
59
62
  const directory = path.join(configRoot, 'projects');
60
63
  if (!fs.existsSync(directory))
61
64
  return [];
65
+ // Find project configurations beneath this directory.
62
66
  function scan(parent) {
63
67
  return fs.readdirSync(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory()).sort((a, b) => a.name.localeCompare(b.name)).flatMap((entry) => {
64
68
  const child = path.join(parent, entry.name);
@@ -75,12 +79,15 @@ function listBrainProjects(configRoot) {
75
79
  }
76
80
  return scan(directory);
77
81
  }
82
+ // Find the profile registered under a project name.
78
83
  function namedBrainProfile(configRoot, name) {
79
84
  return listBrainProjects(configRoot).find((project) => project.name === name || project.profile === name)?.profile ?? null;
80
85
  }
86
+ // Find the profile containing the current source directory.
81
87
  function registeredBrainProfile(configRoot, cwd) {
82
88
  return registeredBrainProject(configRoot, cwd)?.profile ?? null;
83
89
  }
90
+ // Select the most specific registered source root and reject ties.
84
91
  function registeredBrainProject(configRoot, cwd) {
85
92
  const matches = listBrainProjects(configRoot).flatMap((project) => project.roots
86
93
  .filter((root) => (0, utils_1.isSamePathOrDescendant)(path.resolve(cwd), path.resolve(root)))
@@ -8,6 +8,7 @@ const githubIssue = zod_1.z.object({ number: zod_1.z.number().int(), title: zod_
8
8
  html_url: zod_1.z.url(), pull_request: zod_1.z.unknown().optional(), labels: zod_1.z.array(zod_1.z.union([zod_1.z.string(), zod_1.z.object({ name: zod_1.z.string() })])) });
9
9
  const trelloCard = zod_1.z.object({ id: zod_1.z.string(), name: zod_1.z.string(), desc: zod_1.z.string(), closed: zod_1.z.boolean(), dueComplete: zod_1.z.boolean(), due: zod_1.z.string().nullable(),
10
10
  url: zod_1.z.url(), labels: zod_1.z.array(zod_1.z.object({ name: zod_1.z.string() })) });
11
+ // Fetch connector JSON with bounded requests and sanitized network errors.
11
12
  async function readRemote(url, headers) {
12
13
  let response;
13
14
  try {
@@ -20,6 +21,7 @@ async function readRemote(url, headers) {
20
21
  throw new Error(`Connector ${url.hostname} returned HTTP ${response.status}`);
21
22
  return response.json();
22
23
  }
24
+ // Import configured GitHub issues or Trello cards as local tasks.
23
25
  async function syncConnector(store, name, scope) {
24
26
  store.scopeDirectory(scope);
25
27
  const connector = (0, config_1.readBrainConfig)(store.configRoot)?.connectors[name];
@@ -22,6 +22,7 @@ exports.inventoryOptions = zod_1.z.object({
22
22
  scope: store_1.scopeSchema.optional(), types: zod_1.z.array(store_1.typeSchema).optional(), includeDeprecated: zod_1.z.boolean().optional(),
23
23
  offset: zod_1.z.number().int().min(0).default(0), limit: zod_1.z.number().int().min(1).max(100).default(50)
24
24
  }).strict();
25
+ // List filtered knowledge metadata with pagination and the context budget.
25
26
  function listKnowledge(store, input = {}) {
26
27
  const options = exports.inventoryOptions.parse(input);
27
28
  if (options.scope)
@@ -31,9 +32,11 @@ function listKnowledge(store, input = {}) {
31
32
  .sort((a, b) => a.source.localeCompare(b.source));
32
33
  return { total: items.length, contextBudget: store.budget, items: items.slice(options.offset, options.offset + options.limit).map(({ content, ...item }) => ({ ...item, characters: content.length })) };
33
34
  }
35
+ // Locate the archive history for an available scope.
34
36
  function historyFile(store, scope) {
35
37
  return store.safePath(store.scopeDirectory(scope), 'knowledge-history.jsonl');
36
38
  }
39
+ // Read archive records and verify their scope, IDs and content hashes.
37
40
  function readHistory(store, scope) {
38
41
  const file = historyFile(store, scope);
39
42
  if (!fs.existsSync(file))
@@ -52,6 +55,7 @@ exports.historyOptions = zod_1.z.object({
52
55
  scope: store_1.scopeSchema.optional(), id: reference.shape.id.optional(), query: zod_1.z.string().max(1000).optional(),
53
56
  offset: zod_1.z.number().int().min(0).default(0), limit: zod_1.z.number().int().min(1).max(100).default(50)
54
57
  }).strict();
58
+ // Search archived records and include original text when an ID is requested.
55
59
  function knowledgeHistory(store, input = {}) {
56
60
  const options = exports.historyOptions.parse(input);
57
61
  if (options.scope)
package/dist/brain/git.js CHANGED
@@ -9,6 +9,7 @@ const path = require("node:path");
9
9
  const node_child_process_1 = require("node:child_process");
10
10
  const store_1 = require("./store");
11
11
  const config_1 = require("./config");
12
+ // Run noninteractive Git commands and report failures.
12
13
  function git(root, args) {
13
14
  const result = (0, node_child_process_1.spawnSync)('git', ['-C', root, ...args], { encoding: 'utf8', shell: false, timeout: 60000,
14
15
  env: { ...process.env, PATH: process.env.AGENT_RUN_REAL_PATH ?? process.env.PATH, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 16 * 1024 * 1024 });
@@ -16,11 +17,13 @@ function git(root, args) {
16
17
  throw new Error(`git ${args[0]} failed: ${result.error?.message ?? result.stderr.trim()}`);
17
18
  return result.stdout.trimEnd();
18
19
  }
20
+ // Require the configuration directory to be the Git repository root.
19
21
  function requireRepository(store) {
20
22
  if (fs.realpathSync(git(store.configRoot, ['rev-parse', '--show-toplevel'])) !== fs.realpathSync(store.configRoot)) {
21
23
  throw new Error('Git sync requires the configuration directory itself to be the repository root.');
22
24
  }
23
25
  }
26
+ // Report configuration Git state, conflicts and branch.
24
27
  function gitStatus(store) {
25
28
  if (!fs.existsSync(path.join(store.configRoot, '.git')))
26
29
  return { state: 'uninitialized', files: [], conflicts: [], branch: '' };
@@ -30,6 +33,7 @@ function gitStatus(store) {
30
33
  return { state: conflicts.length ? 'conflicted' : files.length ? 'dirty' : 'clean', files, conflicts,
31
34
  branch: git(store.configRoot, ['branch', '--show-current']) };
32
35
  }
36
+ // Collect canonical files and tracked removals eligible for local Git sync.
33
37
  function syncableFiles(store) {
34
38
  const folders = new Set([...Object.values(store_1.knowledgeDirectories), 'skills', 'todo', 'notes']);
35
39
  const roots = [path.join(store.configRoot, 'global'), path.join(store.configRoot, 'default')];
@@ -39,7 +43,7 @@ function syncableFiles(store) {
39
43
  const files = [];
40
44
  for (const root of roots) {
41
45
  for (const folder of folders)
42
- files.push(...store.files(path.join(root, folder)));
46
+ files.push(...store.files(path.join(root, folder), { includeAllFiles: folder === 'skills' }));
43
47
  files.push(...store.files(path.join(root, 'templates'), { includeAllFiles: true }));
44
48
  for (const name of ['config.yaml', 'project.md', 'review-history.jsonl', 'review-counters.json', 'knowledge-history.jsonl']) {
45
49
  const file = store.safePath(root, name);
@@ -48,7 +52,7 @@ function syncableFiles(store) {
48
52
  }
49
53
  }
50
54
  if (fs.existsSync(path.join(store.configRoot, '.git'))) {
51
- const removable = roots.flatMap((root) => ['templates', 'notes', ...Object.values(store_1.knowledgeDirectories)].map((folder) => path.relative(store.configRoot, path.join(root, folder))));
55
+ const removable = roots.flatMap((root) => ['templates', ...folders].map((folder) => path.relative(store.configRoot, path.join(root, folder))));
52
56
  const deleted = git(store.configRoot, ['ls-files', '--deleted', '-z', '--', ...removable]).split('\0').filter(Boolean);
53
57
  files.push(...deleted.map((file) => store.safePath(file)));
54
58
  }
@@ -57,6 +61,7 @@ function syncableFiles(store) {
57
61
  files.push(ignore);
58
62
  return [...new Set(files.map((file) => path.relative(store.configRoot, file)))].sort();
59
63
  }
64
+ // Save, pull or push canonical configuration under the Brain write lock.
60
65
  function syncGit(store, action, message) {
61
66
  return store.writeLocked(() => {
62
67
  const steps = [];
@@ -112,9 +117,11 @@ function syncGit(store, action, message) {
112
117
  }
113
118
  });
114
119
  }
120
+ // Show Git state and canonical files eligible for synchronization.
115
121
  function gitPreview(store) {
116
122
  return { status: gitStatus(store), files: syncableFiles(store) };
117
123
  }
124
+ // Fast-forward clean configuration at startup without blocking service availability.
118
125
  function pullOnStart(store) {
119
126
  try {
120
127
  return store.writeLocked(() => {