@technomoron/agent-brain 0.0.0-stage → 0.1.0

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 (39) hide show
  1. package/CHANGES.md +14 -0
  2. package/LICENSE +21 -0
  3. package/README.md +852 -2
  4. package/dist/agent-brain.js +6 -0
  5. package/dist/brain/built-in-skills.js +24 -0
  6. package/dist/brain/cli.js +265 -0
  7. package/dist/brain/config.js +92 -0
  8. package/dist/brain/connectors.js +63 -0
  9. package/dist/brain/consolidation-skill.js +5 -0
  10. package/dist/brain/consolidation.js +134 -0
  11. package/dist/brain/git.js +139 -0
  12. package/dist/brain/github-reviews.js +174 -0
  13. package/dist/brain/projects.js +136 -0
  14. package/dist/brain/remote-policy.js +126 -0
  15. package/dist/brain/remote-server.js +211 -0
  16. package/dist/brain/repositories.js +28 -0
  17. package/dist/brain/repository-discovery.js +76 -0
  18. package/dist/brain/server.js +283 -0
  19. package/dist/brain/skills.js +54 -0
  20. package/dist/brain/store.js +499 -0
  21. package/dist/brain/todos.js +155 -0
  22. package/dist/brain/windows-pipe.js +19 -0
  23. package/dist/version.js +22 -0
  24. package/examples/brain.jsonc +7 -0
  25. package/examples/remote.jsonc +22 -0
  26. package/ops/config-deploy-entry.sh +3 -0
  27. package/ops/config-deploy-root.cjs +111 -0
  28. package/ops/config-deploy.cjs +176 -0
  29. package/ops/config-policy.cjs +220 -0
  30. package/ops/config-sync.cjs +72 -0
  31. package/ops/systemd/agent-brain.service +14 -0
  32. package/package.json +55 -4
  33. package/skills/brain-consolidate/SKILL.md +42 -0
  34. package/skills/brain-import/SKILL.md +56 -0
  35. package/skills/brain-memory/SKILL.md +73 -0
  36. package/skills/brain-review/SKILL.md +38 -0
  37. package/skills/code-review-organizer/SKILL.md +150 -0
  38. package/skills/review-items/SKILL.md +43 -0
  39. package/skills/todo-manager/SKILL.md +8 -0
package/README.md CHANGED
@@ -1,3 +1,853 @@
1
- # Temporary Holding Version
1
+ # agent-brain
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Project knowledge, skills, reviews and tasks through MCP. Extracted from agent-run. Requires Node.js 24 or newer.
4
+
5
+ The package provides the `agent-brain` command, with `agent-mcp` retained as a compatibility alias. Existing `brain.jsonc`, source-root registrations, Markdown storage, MCP server names and per-user sockets remain compatible. No knowledge or profile files are moved by installing this package.
6
+
7
+ ## Installation
8
+
9
+ ```sh
10
+ npm install --global @technomoron/agent-brain
11
+ ```
12
+
13
+ The npm package is public. The source repository and private skill catalogs keep
14
+ their own access controls. Node.js 24 or newer is required.
15
+
16
+ ## Development
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.
33
+
34
+ ## Running
35
+
36
+ [examples/brain.jsonc](examples/brain.jsonc) shows the optional configuration
37
+ root settings. Save it as brain.jsonc outside the source checkout. The packaged
38
+ [local service unit](ops/systemd/agent-brain.service) supports a per-user service.
39
+
40
+
41
+ ```sh
42
+ agent-brain init --configdir /path/to/agent-config
43
+ agent-brain serve --configdir /path/to/agent-config
44
+ ```
45
+
46
+ Agents continue to use `agent-brain mcp --configdir ... --cwd ...`. Agent-run’s `mcp`, `create` and `project` commands delegate to `agent-brain` on PATH. Install the server separately before using those commands or knowledge compression.
47
+
48
+ Operational systemd and Windows installation scripts remain in agent-run, which orchestrates the native agent environment. See agent-run’s README for the storage model, CLI operations, permissions and service installation.
49
+
50
+ ## MCP-owned skills
51
+
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.
53
+
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.
55
+
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.
57
+
58
+ ## Shared skill catalog
59
+
60
+ `technomoron/agent-mcp-skills` is the private source catalog for reusable skills. This extraction does not implement Git catalog fetching, refresh schedules, grouped selection or customer-level scopes. Existing skills continue to load from external global and project profile directories.
61
+
62
+ ## Releases
63
+
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.
70
+
71
+ ## Remote OAuth endpoint
72
+
73
+ The remote endpoint uses the generic OAuth APIs in
74
+ `@technomoron/apicore-server` 1.1.0 or newer. Normal npm installations include
75
+ that dependency. When developing changes to apicore locally, build the sibling
76
+ `../apicore` checkout and run `node scripts/link-apicore.cjs`; reinstalling
77
+ dependencies replaces this development link.
78
+
79
+ Copy `examples/remote.jsonc` outside the source tree and customize absolute paths.
80
+ Create each repository's separate configuration root using `agent-brain init
81
+ --configdir <root> --cwd <checkout>`. Run the server as a dedicated OS user with a
82
+ private runtime directory (0700). Supply two different random signing secrets of
83
+ 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
86
+ in the user's authenticator. Enrolment and password management are administrator
87
+ operations. Service accounts use confidential client secrets from the environment.
88
+ Never put credentials in source control or client command arguments.
89
+
90
+ Start `agent-brain serve-remote --remote-config /private/remote.jsonc`. It binds only
91
+ to loopback, or the configured private Unix socket. Nginx terminates HTTPS and can
92
+ proxy the issuer, discovery and resource paths to this process:
93
+
94
+ ```nginx
95
+ server {
96
+ listen 443 ssl;
97
+ server_name mcp.example.com;
98
+ ssl_certificate /etc/letsencrypt/live/mcp.example.com/fullchain.pem;
99
+ ssl_certificate_key /etc/letsencrypt/live/mcp.example.com/privkey.pem;
100
+ location / {
101
+ proxy_pass http://127.0.0.1:3000;
102
+ proxy_set_header Host $host;
103
+ proxy_set_header Authorization $http_authorization;
104
+ proxy_buffering off;
105
+ }
106
+ }
107
+ ```
108
+
109
+ Use an OAuth-capable MCP HTTP client with the configured client ID and exact
110
+ registered redirect URI. Interactive grants require S256 PKCE, password login and
111
+ explicit consent; TOTP is checked when configured. Discovery is at
112
+ `/.well-known/oauth-authorization-server/oauth` and
113
+ `/.well-known/oauth-protected-resource/mcp` for the example URLs. Dynamic client
114
+ registration is not supported. Request scopes such as
115
+ `read write review repo:technomoron/agent-run`; send `X-Agent-Repository:
116
+ technomoron/agent-run` with every MCP POST. Configure a separate client connection
117
+ for each repository. Service clients use `client_credentials` with `resource` and
118
+ `scope`; they receive an access token and request a new grant after expiry.
119
+ The existing local stdio bridge continues to use the private local socket and is
120
+ not an OAuth login client.
121
+
122
+ Every request intersects current user grants, client grants and token scopes.
123
+ Patterns are `owner/repo`, `owner/*`, or `*`; only explicitly configured repository
124
+ IDs are served. Ungrouped repositories have isolated data roots; declared groups share common
125
+ knowledge and keep separate project profiles.
126
+ Clients cannot select filesystem paths. `write` permits knowledge/task changes;
127
+ `review` permits finding changes. Git synchronization requires write permission; connector imports, archival
128
+ and unknown tools are unavailable remotely. Policy edits take effect on the next
129
+ request; endpoint/path changes fail closed until restart. Restart after changing
130
+ client registrations or secrets. Persistent sessions survive restarts; revoke a
131
+ session through the token store, or disable its user/remove access to deny it
132
+ immediately. Run one process per runtime directory; browser authorization codes
133
+ and unfinished login forms are deliberately lost on restart.
134
+
135
+ ## Reviews as GitHub Issues
136
+
137
+ Create `<active-profile>/review.jsonc` (or `default/review.jsonc`) inside the
138
+ repository's private configuration root:
139
+
140
+ ```json
141
+ {"backend":"github","repository":"technomoron/agent-run","tokenEnv":"MCP_GITHUB_TOKEN","writesEnabled":true}
142
+ ```
143
+
144
+ The token needs issue access to that private repository. Prefer a narrowly scoped
145
+ GitHub App installation token or fine-grained token; token rotation is managed by
146
+ the operator. Without `writesEnabled: true`, GitHub writes fail closed. The
147
+ `review_*` tools use repository issue IDs and revision checks, preserve discussion
148
+ outside their managed block, and deduplicate creation by a stable finding `key`.
149
+ Retry keys are persisted locally to handle GitHub's delayed issue listings.
150
+ GitHub offers no atomic issue-create idempotency or conditional PATCH here: a
151
+ crash between creation and saving the key, or separate MCP instances creating the
152
+ same finding simultaneously, can still require manual reconciliation. Re-read
153
+ 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.
157
+
158
+ The reusable private skill repository is separate from MCP-owned workflows.
159
+ Automatic catalog cloning/polling and OAuth login in the local stdio bridge are
160
+ not implemented by this change.
161
+
162
+ ## Repository groups
163
+
164
+ A remote configuration can declare `groups: [{"id":"agent-tools",
165
+ "configRoot":"/var/lib/agent-mcp/groups/agent-tools"}]`. Set `group: "agent-tools"`
166
+ and that same `configRoot` on each member of `repositories`. Each member keeps
167
+ its own repository ID and working directory. Register its project at
168
+ `<configRoot>/projects/<owner>/<repo>/config.yaml` with `name: owner/repo` and
169
+ `roots: [<working-directory>]`; initialize the Brain root to install profile
170
+ markers and built-in skills. The server refuses grouped members without their
171
+ own matching project profile.
172
+
173
+ Members share the root's `global` knowledge and skills. In this context, that
174
+ scope means **shared within this group**, not shared across the server. Project
175
+ notes, tasks and review configuration remain in each member's project profile.
176
+ A grant to any member permits reading common group knowledge; keep material that
177
+ must remain repository-private in project scope. Repository and token permission
178
+ checks still apply to every request; group membership does not grant access to a
179
+ sibling repository. `brain_status` reports the repository and group. Unrelated
180
+ repositories and groups must have separate, non-overlapping roots. Restart after
181
+ changing group membership or paths.
182
+
183
+ Git authentication is independent of groups. The service may use its own private
184
+ SSH key under its OS user's `.ssh` directory; do not copy keys into project roots
185
+ or configuration Git. GitHub account SSH keys inherit that account's repository
186
+ access. Deploy keys are repository-specific; GitHub has no organization-wide SSH
187
+ key. A GitHub App can instead provide organization-scoped HTTPS/API access.
188
+
189
+ ## Repository discovery
190
+
191
+ Call `list_repositories` to see repositories available to the current identity,
192
+ with display names, group IDs and effective read/write/review permissions.
193
+ `list_repository_groups` returns only groups with visible member repositories.
194
+ The server scans project configuration and intersects it with the explicit served
195
+ repository registry, current user grants, client grants and token scopes. It does
196
+ not enumerate everything the server's GitHub SSH identity can access. Unregistered
197
+ projects, hidden members, empty groups, credentials and internal paths are omitted.
198
+ Changes to access rules apply to subsequent requests.
199
+
200
+ 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
203
+ review tools. Discovery remains available after selection. Request a token with
204
+ `read` and the desired repository scopes, such as `repo:*`; a token narrowed to
205
+ one repository will only discover that repository, even if the user can access
206
+ others. Local stdio clients can also use these tools to list their local project
207
+ catalog; local access follows the existing OS-user trust model.
208
+
209
+ ### Global knowledge and repository pools
210
+
211
+ Use one configuration root with three parallel directories:
212
+
213
+ ```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
217
+ ```
218
+
219
+ Set `pool: documentmedia` in each member's `projects/<owner>/<repo>/config.yaml`.
220
+ The MCP reads only global, the active repository's pool, and that repository.
221
+ Skills with the same name resolve in repository, pool, global order. A skill can
222
+ extend an ancestor with `extends: global:name` or `extends: pool:name`.
223
+ Knowledge keeps its scope and authority; a more specific inferred observation
224
+ does not replace an explicit user constraint.
225
+
226
+ For a remote server, set `dataRoot` to this shared configuration root and use
227
+ that same `configRoot` for its groups and repositories. The existing `group`
228
+ registration identifies the pool and must match the project's `pool` field.
229
+ Legacy separate group roots remain supported when `dataRoot` is absent.
230
+ Global writes require a wildcard token and current wildcard write permission.
231
+ Pool writes require write permission for every registered member. Reading a
232
+ repository includes its global and pool knowledge. Reviews, their counters and
233
+ history, tasks, and GitHub issue targets stay with the individual repository.
234
+
235
+ ### Configuration push deployment
236
+
237
+ `ops/config-policy.cjs` and `ops/config-deploy.cjs` support the private configuration
238
+ repository's push workflow. `.brain-deploy.json` explicitly lists pools and served
239
+ repositories; source-machine roots are replaced by server checkout roots. Core
240
+ skills remain owned by this package. A three-way comparison preserves independent
241
+ MCP writes and rejects conflicting Git edits before changing live data.
242
+
243
+ The installed forced-command entry accepts only `deploy <full-main-SHA>`. The
244
+ root-owned controller runs Git and data operations as `agent-mcp`, stops the
245
+ service only after validation, updates repository/group registration without
246
+ changing users or client grants, and restarts with health checks and rollback.
247
+ The controller uses root-owned packaged deployment code; it never runs the
248
+ configuration checkout's validation or deployment scripts on the server.
249
+ The existing `agent-mcp` service account and on-disk paths are retained for
250
+ compatibility; the application and package are named agent-brain.
251
+
252
+ ### Export Brain changes to Git
253
+
254
+ Configure `gitSync: {"catalog":"/var/lib/agent-mcp/catalogs/agent-brain-config",
255
+ "state":"/var/lib/agent-mcp/config-deploy"}` alongside `dataRoot` in the remote
256
+ server configuration. The catalog origin must grant SSH write access, and its
257
+ local `user.name` and `user.email` must identify the configured human author.
258
+ The deployment state must contain its successful deployment baseline.
259
+
260
+ The authenticated MCP `brain_sync` and `brain_flush` tools (chat commands `brain sync` and
261
+ `brain flush`) default to committing and pushing
262
+ canonical changes. The active repository is exported; pools and global data are
263
+ added only with full write access to those scopes. Review data additionally
264
+ requires review permission. The command never commits project source code.
265
+ Git-only edits are preserved; competing edits fail with paths for reconciliation.
266
+ Generated metadata, client/server configuration, credentials, runtime files and
267
+ bundled core skills are excluded.
268
+
269
+ Exports and configuration deployments share `state/catalog.lock`. Sync snapshots
270
+ canonical data under the Brain write lock, then commits in a private temporary
271
+ clone and pushes main without force. Failed exports are retained under
272
+ `state/exports`; live data remains intact. Retry after correcting access, network
273
+ or conflicts. Successful exports are deleted; unchanged data creates no commit.
274
+ A lock left by a killed process requires an operator to verify the process has
275
+ stopped before removing it.
276
+
277
+ Agent-run flushes remote Brain when a wrapped agent exits, including signal exits
278
+ when the launcher can finish cleanup. Failures warn on stderr without changing
279
+ the agent status. SIGKILL, power loss and a forcibly closed terminal cannot
280
+ guarantee cleanup; explicit chat `brain sync` is available throughout a session.
281
+
282
+ The older MCP tool names `sync` and `flush` remain compatibility aliases.
283
+ New clients and instructions use `brain_sync` and `brain_flush`. Bare chat
284
+ “sync” or “flush” does not by itself select Brain as the target.
285
+
286
+ ## Local service and knowledge guide
287
+
288
+ Agent-brain owns canonical knowledge, specifications, skills, reviews, tasks,
289
+ connectors, retrieval and configuration synchronization. Its project profile is
290
+ `projects/technomoron/agent-brain` under the external configuration root;
291
+ agent-run owns launcher configuration, native adapters and the client connection.
292
+ Both projects remain members of the `agent-tools` pool. Source registrations and
293
+ private runtime credentials remain outside both source repositories.
294
+
295
+ The local service uses the official Node MCP SDK and apicore-server, with Node's
296
+ built-in SQLite and FTS. It uses a private per-user Unix socket or Windows named
297
+ pipe. The remote OAuth endpoint is configured separately above.
298
+
299
+ ### Start using it
300
+
301
+ ```sh
302
+ agent-brain init
303
+ agent-brain serve
304
+ ```
305
+
306
+ Keep the service running, or enable the systemd user service described below.
307
+ In another terminal:
308
+
309
+ ```sh
310
+ cd ~/code/my-project
311
+ agent-run create my-project --quick
312
+ agent-run codex
313
+ ```
314
+
315
+ Omit `--quick` for the short interactive setup, or use `--guided` to add an
316
+ architecture summary, constraints, conventions, and a preferred agent.
317
+ Creation detects the source root, Git remote, languages, package manager,
318
+ documentation, and package scripts. It writes configuration outside the source
319
+ repository. Existing directories and duplicate project registrations are rejected.
320
+
321
+ `agent-run project list` lists registrations. `project info` shows the current
322
+ project, and `project bootstrap` returns detected information for the agent to
323
+ inspect and turn into proposals. Bootstrap does not invent or save architectural
324
+ facts; the agent can use the knowledge tools after the user confirms its proposals.
325
+
326
+ All commands accept `--configdir PATH`. Brain commands also accept `--cwd PATH`.
327
+ `agent-brain --help` lists the commands.
328
+
329
+ ### Scopes and existing profiles
330
+
331
+ ```text
332
+ ~/.agent-run/
333
+ brain.jsonc
334
+ global/skills/<name>/SKILL.md
335
+ global/constraints/*.md
336
+ projects/my-project/
337
+ agent-run.jsonc
338
+ config.yaml
339
+ project.md
340
+ memory/*.md
341
+ todo/*.md
342
+ live/
343
+ default/
344
+ agent-run.jsonc
345
+ skills/
346
+ preferences/
347
+ constraints/
348
+ conventions/
349
+ reviews/
350
+ memory/*.md
351
+ todo/
352
+ templates/
353
+ live/
354
+ index/knowledge.sqlite
355
+ runtime/
356
+ ```
357
+
358
+ Inside a registered or existing configured project, retrieval includes global
359
+ and project knowledge. Elsewhere it includes global and default knowledge.
360
+ Default knowledge never appears in a configured project. Among registered
361
+ source roots, the most specific matching root wins; equal matches are rejected.
362
+ An explicit `AGENT_RUN_PROFILE` in `.agent-run.env` keeps precedence over registration.
363
+
364
+ Project names can include a namespace: `technomoron/agent-run` lives under
365
+ `projects/technomoron/agent-run`. The original name also works in
366
+ `AGENT_RUN_PROFILE`; no alias is needed.
367
+
368
+ Existing JSONC manifests, Nunjucks templates, and `org/repo` profiles remain
369
+ supported. Brain reads existing `notes/memory` directories in place, including
370
+ the config root's global notes. It does not move or delete them. New knowledge
371
+ uses the directories above. Existing files without metadata are treated as
372
+ inferred, relevant-only knowledge; adding metadata gives you explicit control.
373
+ Legacy review metadata is preserved, and reviews marked addressed or resolved
374
+ are excluded from active recall. Canonical `global/skills/<name>/SKILL.md` files
375
+ also support existing Nunjucks variables when served or rendered for native agents.
376
+
377
+ `agent-brain init` installs the shared brain skills and a default profile, and
378
+ creates `brain.jsonc` only if it does not exist. It preserves existing files.
379
+ It creates the topic directories shown above in global, default, and registered
380
+ project scopes, plus `rules/`, `decisions/`, `specs/`, and `observations/` for
381
+ the other knowledge types. Project creation uses the same layout. Empty topic
382
+ directories stay empty until there is relevant content to store.
383
+ Normal profile rendering then adds the brain MCP server and shared instructions
384
+ to Codex, Claude, Gemini, and Grok. An explicitly configured `agent-brain` MCP
385
+ entry takes precedence. Set `enabled` to `false` to stop automatic integration
386
+ and restore the previous unconfigured-project behavior.
387
+
388
+ ```jsonc
389
+ {
390
+ "enabled": true,
391
+ "contextBudget": 16000,
392
+ "connectors": {}
393
+ }
394
+ ```
395
+
396
+ `contextBudget` counts serialized characters, not model tokens. A context result
397
+ reports omitted items. Use `get_knowledge` to read complete items when necessary.
398
+ Always-recalled knowledge is considered first, then matching file patterns,
399
+ then lexical results. Search uses FTS ranking with extra weight for titles and tags.
400
+ Queries compare the current files with the index and write only added, changed,
401
+ or removed entries. Unchanged queries do not take a database write lock. Context
402
+ retrieval scans the files once. Search and context MCP tools declare that they
403
+ may write because they can refresh this derived index.
404
+ Symbols contribute search terms. Manual Markdown changes are read on every query;
405
+ the index can be deleted while the service is stopped and rebuilt on the next query.
406
+
407
+ ### Knowledge and skills
408
+
409
+ Malformed knowledge and task files do not block other entries. When a scan finds
410
+ problems, MCP and CLI list/search responses contain `items` and `brokenFiles`;
411
+ object responses, including context, gain a `brokenFiles` field. Each error lists
412
+ the source path, `status: "broken"`, a reason, and an ID when it can be parsed.
413
+ Responses without errors keep their existing format. Broken entries are excluded
414
+ from search and context, and reads or updates of those entries are refused.
415
+ Correct the file on disk; the next scan picks up the repair automatically.
416
+ Duplicate IDs flag all matching files. External task imports and new review
417
+ numbering stop when broken files would make deduplication or numbering unreliable.
418
+
419
+ Knowledge is one Markdown file per item, with YAML metadata:
420
+
421
+ ```markdown
422
+ ---
423
+ id: auth-refresh-single-use
424
+ type: constraint
425
+ scope: project
426
+ authority: user
427
+ status: active
428
+ recall: always
429
+ tags: [auth]
430
+ applies_to: ["src/auth/**"]
431
+ created: 2026-09-06
432
+ ---
433
+
434
+ # Refresh tokens are single-use
435
+
436
+ A successfully consumed refresh token must never be accepted again.
437
+ ```
438
+
439
+ The storage directories are `rules`, `preferences`, `conventions`, `constraints`,
440
+ `decisions`, `specs`, `reviews`, `memory`, and `observations`. Scope metadata must
441
+ match the file's directory. IDs must be unique across the active scopes.
442
+ Invalid metadata produces an error identifying the file. Symlinked storage
443
+ paths are rejected. Individual Markdown files are limited to 1 MiB.
444
+
445
+ Choose the scope and singular knowledge type when calling `remember`; MCP writes
446
+ the file into the corresponding directory. User preferences belong in
447
+ `preferences/`, requirements in `constraints/`, established practices in
448
+ `conventions/`, confirmed specifications in `specs/`, and confirmed choices in
449
+ `decisions/`. Code-derived facts remain inferred `observations/`; source
450
+ references and history belong in `memory/`, with planned features labeled as
451
+ plans. An import request does not make inferred content authoritative.
452
+ Use the todo tools for tasks. Reusable workflows are `skills/<name>/SKILL.md`
453
+ files, and reusable templates belong in `templates/`; `remember` does not
454
+ install either. Global skills remain available without copying them into each
455
+ project. The brain-memory skill explains these choices to native agents.
456
+
457
+ Available MCP tools include `get_context`, `search_knowledge`, `get_knowledge`,
458
+ `remember`, `amend_knowledge`, `list_knowledge`, `archive_knowledge`,
459
+ `knowledge_history`, `promote`, `deprecate_knowledge`, `review_context`,
460
+ `review_list`, `resolve_review`, `review_history`, and `review_archive`.
461
+ Writes use atomic file replacement and a shared lock; concurrent writes either
462
+ complete or report that the caller should retry. After a crashed writer, stop
463
+ the service, verify the PID in `runtime/brain-write.lock` is no longer running,
464
+ and remove that lock before restarting.
465
+
466
+ ```sh
467
+ agent-brain remember --json '{"scope":"project","type":"observation","title":"Refresh handling","content":"Investigate concurrent refresh requests."}'
468
+ agent-brain search "refresh"
469
+ agent-brain get ITEM_ID
470
+ agent-brain amend ITEM_ID --revision REVISION --json '{"content":"Corrected text."}'
471
+ agent-brain deprecate ITEM_ID --revision REVISION "No longer applies"
472
+ agent-brain promote ITEM_ID --scope global --revision REVISION --confirmed
473
+ ```
474
+
475
+ `amend_knowledge` revises an active item in place, keeping its id, file name, scope,
476
+ type, authority, and history, and updating only the fields you pass. Use it to correct
477
+ or extend knowledge instead of writing a near-duplicate. Scope, type, authority, and
478
+ review severity are not amendable; if one of those is wrong, deprecate the item and
479
+ write a corrected one.
480
+
481
+ #### Knowledge consolidation
482
+
483
+ Run the consolidation skill from the current project's directory:
484
+
485
+ ```sh
486
+ agent-run compress
487
+ agent-run compress --dry-run
488
+ agent-run compress --agent claude
489
+ agent-run compress --scope global
490
+ ```
491
+
492
+ This opens the selected agent with the consolidation task and its normal generated
493
+ configuration and permission settings. It uses project scope when configured,
494
+ otherwise default scope. Global knowledge changes require `--scope global`.
495
+ `--dry-run` asks the agent to inspect and propose changes without modifying knowledge.
496
+ Agent-brain must be initialized and its service available.
497
+
498
+ Choose the user default in `<config-root>/agent-run.defaults.jsonc`:
499
+
500
+ ```jsonc
501
+ {
502
+ "agent": {
503
+ "default": "codex"
504
+ }
505
+ }
506
+ ```
507
+
508
+ The same field in a profile's `agent-run.jsonc` overrides the user default;
509
+ `--agent` overrides both. Supported values are `codex`, `claude`, `gemini`, and
510
+ `grok`. Older manifests without this field use Codex, and initialization preserves
511
+ existing configuration and customized skills. Explicit commands such as
512
+ `agent-run claude` continue to select that agent directly.
513
+
514
+ The `brain-consolidate` skill removes repetition, combines focused topic records,
515
+ and extracts appropriately classified knowledge from memory. It preserves
516
+ requirements, exceptions, authority, sources and useful history. Historical plans
517
+ and inferred observations do not become confirmed requirements through compression.
518
+ Unresolved contradictions remain visible. Reviews and tasks have separate workflows.
519
+
520
+ Clear, authoritative corrections in supplied comments or memory are reconciled
521
+ into the affected spec sections, preserving unrelated requirements and source
522
+ references. A newer timestamp or code comment alone does not establish authority.
523
+ Sections explicitly marked immutable or locked are preserved verbatim unless the
524
+ user explicitly authorizes changing them. Conflicts with locked sections are
525
+ reported while independent updates can proceed. These are skill instructions;
526
+ the storage API does not enforce section-level locks.
527
+
528
+ The command uses an installed skill override when present, otherwise the bundled
529
+ skill; `agent-brain init` installs missing built-in skills without replacing existing ones.
530
+
531
+ `list_knowledge` provides a complete paginated inventory of metadata and content
532
+ character counts, with `scope`, `types`, `includeDeprecated`, `offset`, and `limit`
533
+ (default 50, maximum 100). It also reports `contextBudget`. Fetch complete records
534
+ with `get_knowledge` before editing; search and context results are not inventories.
535
+
536
+ After writing and verifying replacements with `remember` or `amend_knowledge`,
537
+ `archive_knowledge` accepts a request such as:
538
+
539
+ ```json
540
+ {
541
+ "sources": [{
542
+ "id": "old-id",
543
+ "revision": "<last-read SHA-256>",
544
+ "replacements": [{"id": "surviving-id", "revision": "<verified SHA-256>"}]
545
+ }],
546
+ "reason": "Combined duplicate requirements; verified all exceptions survive."
547
+ }
548
+ ```
549
+
550
+ Each source can point to multiple replacements when extracting different categories.
551
+ The tool checks all sources and replacements before writing, requires matching scope
552
+ and authority, preserves recall coverage, and excludes reviews. The agent verifies
553
+ semantic coverage; the tool cannot prove that a summary preserves every fact.
554
+ Exact original files and replacement IDs/revisions go into one
555
+ `knowledge-history.jsonl` per scope before source files are removed. If deletion
556
+ fails, originals remain in history and an identical request can finish deletion
557
+ while the supplied revisions still match. History and removed knowledge paths
558
+ participate in authorized brain Git sync; compression itself never commits or pushes.
559
+
560
+ Use `knowledge_history` with an old `id` to retrieve the original file text and
561
+ replacement references. Without `id`, it returns compact metadata; optional
562
+ `scope`, `query`, `offset`, and `limit` support browsing. Follow replacement IDs
563
+ through history if those records were later consolidated. Archived originals stay
564
+ out of normal retrieval. This reduces active files and context text, while retaining
565
+ archive bytes on disk.
566
+
567
+ The corresponding CLI commands accept the same JSON options:
568
+
569
+ ```sh
570
+ agent-brain list --json '{"scope":"project","offset":0,"limit":50}'
571
+ agent-brain history --json '{"id":"old-id"}'
572
+ agent-brain archive --json '<sources-and-replacements-object>'
573
+ ```
574
+
575
+ #### File names
576
+
577
+ `remember` names each file after the item id. Pass `filename` to choose the name
578
+ instead, as lower-case words separated by single dashes and no extension:
579
+
580
+ ```sh
581
+ agent-brain remember --json '{"scope":"project","type":"observation","title":"Build flow","content":"...","filename":"build-flow"}'
582
+ ```
583
+
584
+ If that name is taken, the item id is appended rather than overwriting anything. The
585
+ name is storage only and is never written into the metadata: the `id` in the front
586
+ matter is the identity, so files stay safe to rename by hand and the item is still found
587
+ by id afterwards.
588
+
589
+ #### Review findings
590
+
591
+ Review knowledge is a numbered, prioritized list. `remember` requires a
592
+ `severity` of `critical`, `high`, `medium`, or `low` when the type is `review`,
593
+ and rejects `severity` for every other type. The store assigns the finding
594
+ label itself: `C1`, `H1`, `M1`, `L1`, counting up per severity within the scope.
595
+ Resolved numbers are never handed out again, so a label always refers to the
596
+ same finding.
597
+
598
+ Each finding also carries a `state` of `open`, `fixed`, or `wontfix`, separate
599
+ from the `active` and `deprecated` status that controls recall. New findings
600
+ start `open`.
601
+
602
+ ```sh
603
+ agent-brain review list
604
+ agent-brain review list --severity high --state open
605
+ agent-brain review resolve ITEM_ID --revision REVISION --state fixed "Fixed by using a stable command name"
606
+ ```
607
+
608
+ `review_list` returns findings in severity then number order, open ones only
609
+ unless states are given, each with the revision needed to resolve it.
610
+ `resolve_review` records the state and reason and takes the finding out of active
611
+ recall. It writes a short record (label, title, outcome, date, reason, and original
612
+ file/revision) to the scope's `review-history.jsonl`, then deletes the full finding
613
+ file. `review-counters.json` preserves numbering. These files participate in brain
614
+ Git sync but are excluded from normal knowledge retrieval.
615
+
616
+ Use MCP `review_history` to recall old fixes, with optional `query`, `scope`, `state`,
617
+ `offset`, and `limit` (default 100). The CLI equivalent is
618
+ `agent-brain review history [query]`. Git retains full details only when the original
619
+ files were committed before cleanup; the MCP history is sufficient for the short fix list.
620
+ Use `review_archive` with a scope, or `agent-brain review archive --scope project`,
621
+ to compact existing files already marked `fixed` or `wontfix`. Deferred findings
622
+ remain open. Mark a finding `wontfix` only when the user explicitly drops it or
623
+ confirms it is intentional. A request to postpone an issue does not close it.
624
+
625
+ Finding labels are indexed, so `search_knowledge` for `H2` finds that finding.
626
+ Review files written before these fields existed keep parsing; they simply carry
627
+ no label and stay out of the finding list.
628
+
629
+ Remembered deductions default to inferred authority and must remain observations,
630
+ memories, or review records. Global writes require explicit user authority.
631
+ Promotion copies an item, records its origin, preserves the original, and requires
632
+ confirmation. Deprecation and promotion require the last-read revision so stale
633
+ requests cannot overwrite newer work. An agent's authority claim is an instruction
634
+ contract, not a separate authentication system; the Unix account owns the data.
635
+
636
+ Skills use YAML `name` and `description` metadata in `skills/<name>/SKILL.md`.
637
+ `list_skills` returns descriptions, and `get_skill` loads the body on demand.
638
+ A project/default skill overrides a global skill with the same name. Add
639
+ `extends: global:NAME` to include the global skill's instructions before the local
640
+ instructions. The existing native skill-template system continues to work.
641
+
642
+ Skill templates and their includes must stay under `global/skills/` or the active
643
+ project/default profile's `skills/` directory. Use config-root-relative paths such
644
+ as `{% include "global/skills/shared/checks.md" %}`, or `./` paths relative to the
645
+ including template. Nunjucks variables remain available. Symlinks are rejected,
646
+ and each file is limited to 1 MiB. Move snippets and skill overrides stored
647
+ elsewhere into these directories before rendering or loading those skills.
648
+
649
+ The installed `brain-memory`, `brain-consolidate`, `brain-review`, and `todo-manager`
650
+ skills describe retrieval, persistence, consolidation, review learning, and task workflows. Review records use
651
+ the knowledge tools and remain inferred unless confirmed by the user.
652
+
653
+ ### Tasks and connectors
654
+
655
+ Tasks are separate from knowledge and stored in `todo/<id>.md`. Supported states
656
+ are `todo`, `doing`, `blocked`, `done`, and `cancelled`. Tasks have titles,
657
+ descriptions, priorities, owners, due dates, labels, notes, and optional external
658
+ source identities.
659
+
660
+ ```sh
661
+ agent-brain todo add --json '{"scope":"project","title":"Check refresh handling","priority":"high"}'
662
+ agent-brain todo list
663
+ agent-brain todo get ITEM_ID
664
+ agent-brain todo complete ITEM_ID --revision REVISION
665
+ ```
666
+
667
+ MCP exposes `todo_list`, `todo_get`, `todo_add`, `todo_update`, `todo_complete`,
668
+ `todo_import`, and `todo_sync`. Update requests require the current revision.
669
+
670
+ Configure optional connectors in `brain.jsonc`:
671
+
672
+ ```jsonc
673
+ {
674
+ "enabled": true,
675
+ "connectors": {
676
+ "issues": {
677
+ "type": "github",
678
+ "repository": "my-org/my-project",
679
+ "tokenEnv": "GITHUB_TOKEN"
680
+ },
681
+ "board": {
682
+ "type": "trello",
683
+ "board": "BOARD_ID",
684
+ "keyEnv": "TRELLO_API_KEY",
685
+ "tokenEnv": "TRELLO_TOKEN"
686
+ }
687
+ }
688
+ }
689
+ ```
690
+
691
+ ```sh
692
+ agent-brain todo import issues --scope project
693
+ agent-brain todo sync issues --scope project
694
+ ```
695
+
696
+ Credentials are read from the process environment and never written to task files.
697
+ Set credentials in the service's environment.
698
+ GitHub imports paginate and exclude pull requests. Trello maps due-complete cards
699
+ to done, archived cards to cancelled, and other cards to todo; it does not guess
700
+ workflow states from list names.
701
+
702
+ Imports deduplicate by source identity and scope. Synchronization compares local
703
+ and remote fields against the last imported version, preserves local-only edits,
704
+ and reports conflicting task IDs without replacing those tasks. Deleted remote
705
+ items are retained locally. These connectors only read remote systems; completing
706
+ a local task does not close a GitHub issue or modify a Trello card.
707
+
708
+ ### Git portability
709
+
710
+ For remote Brain, asking “brain sync” or “brain flush” invokes the MCP tool to export, commit
711
+ and push canonical knowledge to the configured private repository. Exiting a
712
+ wrapped agent session invokes the same flush automatically. Failures produce a
713
+ warning and preserve live data; they do not change the agent exit status. A new
714
+ sync retries from the latest Git revision. Force-killed processes cannot flush;
715
+ use `brain sync` in chat before disconnecting when needed.
716
+
717
+ Remote export covers the active repository and shared scopes for which the token
718
+ has full write access. Findings additionally require review permission. Client
719
+ settings, server paths, credentials, generated files and MCP-owned skills are
720
+ excluded. Competing Git edits are reported without overwriting either side.
721
+
722
+ The following commands describe the separate local configuration Git workflow.
723
+
724
+ ```sh
725
+ agent-brain sync status # Preview Git status and eligible files
726
+ agent-brain sync init # Initialize the configuration Git repository
727
+ agent-brain save # Commit local brain changes and push
728
+ agent-brain pull # Pull remote changes with rebase
729
+ agent-brain push # Push existing commits
730
+ agent-brain sync # Commit local changes, pull, then push
731
+ ```
732
+
733
+ Commands need no `--confirmed` flag. Saving generates a commit message from the
734
+ number of changed files; use `--message "Your message"` to override it. Output
735
+ reports completed steps, including a local commit if a later pull or push fails.
736
+ Existing `agent-brain sync save|pull|push` forms remain supported. Bare
737
+ `agent-brain sync` now performs synchronization; use `sync status` for a preview.
738
+
739
+ From an agent prompt, use `brain sync` or `brain flush`. The MCP tools
740
+ `brain_sync` and `brain_flush` accept an optional message; older `sync` and
741
+ `flush` tool names remain compatibility aliases. A bare “sync” or “flush” does
742
+ not identify Brain as the target. Agents still need a user request or standing
743
+ authorization to sync.
744
+
745
+ Saving includes Markdown knowledge, skills, tasks, project metadata, and `.gitignore`.
746
+ It also includes all regular files under each scope's `templates/` directory,
747
+ including nested Nunjucks templates and supporting files. Template additions,
748
+ edits, and deletions are synced; symlinks are rejected.
749
+ It excludes indexes, runtime state, secrets, `brain.jsonc`, and native agent
750
+ configuration. Existing staged changes block a save. Configure the remote and
751
+ upstream with normal Git commands using your existing credentials.
752
+ Brain Git operations use `AGENT_RUN_REAL_PATH` when available, so agent-session
753
+ Git guards do not intercept configuration sync.
754
+ After cloning onto another machine, run `agent-brain init` to restore generated
755
+ profile markers and shared templates, then update source roots in `config.yaml`
756
+ to match that machine.
757
+
758
+ The configuration directory must itself be the repository root. Pull uses rebase
759
+ and reports conflicted files; resolve the rebase before syncing again. Sync stops
760
+ on failure without pushing. Commands apply across all scopes in the configuration
761
+ repository, not just the current code project. Background commits and pushes are
762
+ not performed; the service can optionally pull at startup as described below.
763
+
764
+ ### Persistent service under apicore-server
765
+
766
+ All native agents connect to the same long-lived service for the current user.
767
+ Start it on Linux, macOS, or Windows:
768
+
769
+ ```sh
770
+ agent-brain serve
771
+ ```
772
+
773
+ The service hosts SDK Streamable HTTP at `/mcp` using apicore's Fastify instance.
774
+ It listens on `<config-root>/runtime/agent-brain.sock`, which defaults to
775
+ `~/.agent-run/runtime/agent-brain.sock`. Both the service and clients use the
776
+ configured root regardless of their environment. The socket
777
+ directory must belong to the current user and have mode `0700`; the socket has
778
+ mode `0600`. No TCP listener or application user database is created.
779
+
780
+ Generated native-agent configurations run `agent-brain mcp` through `PATH`, so
781
+ `agent-brain` must be installed and available there. The bridge selects the socket
782
+ when it starts; generated files do not depend on the installation or runtime
783
+ directory used to render them. Re-render existing profiles with `agent-run update`
784
+ to replace older commands that contain absolute installation paths. After
785
+ upgrading from a version that used a different socket location, restart the service and
786
+ agent sessions so they use the socket under the configuration root.
787
+
788
+ `agent-run mcp` also bridges native-agent stdio to this socket. Use `--socket PATH`
789
+ for a particular service. The bridge verifies the socket's ownership and private
790
+ permissions. A missing or unreachable socket is an error; start the service
791
+ before connecting. There is no standalone stdio server or TCP fallback. Apicore
792
+ supports Unix sockets directly, so localhost binding is unnecessary. The brain
793
+ service supports Linux, macOS, and native Windows.
794
+
795
+ On Windows the default endpoint is `\\.\pipe\agent-brain-<hash>`, derived from
796
+ the user's home and configuration root. No TCP port is opened. Windows
797
+ PowerShell applies a private pipe ACL before requests are accepted; each bridge
798
+ checks the pipe owner and ACL before connecting. `--socket` can select another
799
+ local named pipe. Windows removes the pipe automatically when its server exits.
800
+
801
+ To start it automatically at Windows sign-in, initialize the desired config root
802
+ and run the packaged installer in PowerShell:
803
+
804
+ ```powershell
805
+ agent-brain init --configdir "$env:USERPROFILE\.agent-run"
806
+ $prefix = npm.cmd prefix -g
807
+ & "$prefix\node_modules\@technomoron\agent-run\scripts\install-windows-brain.ps1" -ConfigRoot "$env:USERPROFILE\.agent-run"
808
+ ```
809
+
810
+ The `Agent Brain` scheduled task runs hidden as the signed-in user, without
811
+ elevation, and retries failures. Its log is `<config-root>/runtime/service.log`.
812
+ After upgrading the package, restart it with `Stop-ScheduledTask` followed by
813
+ `Start-ScheduledTask` for task name `Agent Brain`.
814
+
815
+ After a crash, remove a stale socket only after checking that its service is
816
+ stopped. Starting a second service on an existing socket fails without replacing
817
+ the first service's socket.
818
+
819
+ For a user service, copy `ops/systemd/agent-brain.service` to
820
+ `~/.config/systemd/user/` and adjust `ExecStart` if your executable is elsewhere.
821
+ Add `--configdir PATH` to `ExecStart` if you use a custom configuration root.
822
+ Run `systemctl --user daemon-reload` followed by
823
+ `systemctl --user enable --now agent-brain`. Installation is explicit.
824
+
825
+ The supplied service uses `serve --pull`. On startup this pulls the configuration
826
+ repository with `--ff-only --no-rebase` when it is clean and has an upstream.
827
+ Dirty checkouts and missing upstreams are skipped. Divergence or network failures
828
+ are reported in the service journal and the service continues with local files.
829
+ Before launching any configured agent, agent-run initializes its enabled brain MCP connection and calls `brain_status`. If this fails, launch stops with the underlying error. A disabled brain MCP connection also blocks launch when brain is enabled. Run the agent and brain service as the same user; private socket ownership is enforced. `--none` remains an explicit configuration bypass.
830
+
831
+ Startup never commits, pushes, stashes, or rebases local work. Omit `--pull` to
832
+ disable this behavior for a manually launched service.
833
+
834
+ The AI tools updater can install and restart the service for explicitly selected
835
+ accounts; see [agent-run Systemd Jobs](https://github.com/technomoron/agent-run#systemd-jobs). Existing user unit
836
+ overrides still take precedence over the installed system-wide user unit.
837
+
838
+ Each HTTP request resolves the proxy's source directory through agent-run's
839
+ resolver. Tools cannot select another project's scope through arguments. The
840
+ service shares canonical files and the SQLite index; it does not keep a watcher
841
+ or a separate authoritative cache.
842
+
843
+ ### Remaining roadmap
844
+
845
+ The initial implementation uses lexical retrieval and path matching. Embeddings,
846
+ vector ranking, background watchers, debounced automatic Git synchronization,
847
+ remote task writes, and additional connectors remain future work. No model
848
+ provider or external account is required for the local features.
849
+
850
+ Transport and connector implementations follow the
851
+ [Node MCP SDK server documentation](https://ts.sdk.modelcontextprotocol.io/server),
852
+ [GitHub Issues REST API](https://docs.github.com/en/rest/issues/issues), and
853
+ [Trello board API](https://developer.atlassian.com/cloud/trello/rest/api-group-boards/).