brainx-skill 1.0.13 → 1.0.14
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/README.md +26 -0
- package/installation/lib/cli.js +16 -4
- package/installation/lib/literature-mcp.js +536 -0
- package/manifest.json +2 -0
- package/mcp-servers/codex/README.md +24 -4
- package/mcp-servers/codex/UPSTREAM.md +3 -1
- package/mcp-servers/codex/server.mjs +2 -0
- package/mcp-servers/codex/system-prompt.md +30 -19
- package/mcp-servers/codex/test/server.test.mjs +12 -1
- package/mcp-servers/fulltext-resolver/README.md +136 -0
- package/mcp-servers/fulltext-resolver/REUSE.md +32 -0
- package/mcp-servers/fulltext-resolver/THIRD_PARTY_NOTICES.md +57 -0
- package/mcp-servers/fulltext-resolver/server.mjs +128 -0
- package/mcp-servers/fulltext-resolver/src/document.mjs +253 -0
- package/mcp-servers/fulltext-resolver/src/http.mjs +173 -0
- package/mcp-servers/fulltext-resolver/src/identifiers.mjs +123 -0
- package/mcp-servers/fulltext-resolver/src/model.mjs +105 -0
- package/mcp-servers/fulltext-resolver/src/resolver.mjs +305 -0
- package/mcp-servers/fulltext-resolver/src/sources/biorxiv.mjs +135 -0
- package/mcp-servers/fulltext-resolver/src/sources/europe-pmc.mjs +132 -0
- package/mcp-servers/fulltext-resolver/src/sources/openalex.mjs +165 -0
- package/mcp-servers/fulltext-resolver/test/document.test.mjs +82 -0
- package/mcp-servers/fulltext-resolver/test/resolver.test.mjs +287 -0
- package/mcp-servers/fulltext-resolver/test/server.test.mjs +63 -0
- package/mcp-servers/fulltext-resolver/test/sources.test.mjs +229 -0
- package/package.json +10 -3
- package/skills/bio-neuro-lit/SKILL.md +206 -0
- package/skills/bio-neuro-lit/THIRD_PARTY_NOTICES.md +34 -0
- package/skills/bio-neuro-lit/agents/openai.yaml +4 -0
- package/skills/bio-neuro-lit/references/tool-contracts.md +73 -0
- package/skills/bio-neuro-lit/scripts/deepxiv_fetch.py +110 -0
- package/skills/bio-neuro-lit/scripts/exa_search.py +190 -0
- package/skills/brainx-general-guard/SKILL.md +17 -0
- package/skills/brainx-modeling-loop/SKILL.md +33 -20
- package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +47 -7
- package/skills/brainx-visualization/SKILL.md +157 -0
- package/skills/brainx-visualization/agents/openai.yaml +4 -0
- package/skills/brainx-visualization/references/interactive-and-visualization-styling.md +155 -0
- package/skills/brainx-visualization/references/neural-data-visualization.md +141 -0
- package/skills/brainx-visualization/references/statistical-and-model-visualization.md +133 -0
- package/skills/package-skills/braincell/SKILL.md +16 -6
- package/skills/package-skills/braincell/references/braintools/input-current.md +200 -0
- package/skills/package-skills/braincell/references/braintools/metric.md +152 -0
- package/skills/package-skills/braincell/references/braintools/optimizer.md +179 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Thin progressive-reading adapter around the installed DeepXiv CLI.
|
|
3
|
+
|
|
4
|
+
Adapted from wanshuiyin/Auto-claude-code-research-in-sleep at commit
|
|
5
|
+
e59008d7a42eea50a2797e55dd0d85bbbf6572f5 (MIT). See
|
|
6
|
+
../THIRD_PARTY_NOTICES.md.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
from typing import Sequence
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
INSTALL_MESSAGE = "deepxiv CLI not found. Install it with: pip install deepxiv-sdk"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def ensure_deepxiv_installed() -> dict[str, object]:
|
|
23
|
+
"""Return the installed DeepXiv binary, if available."""
|
|
24
|
+
binary = shutil.which("deepxiv")
|
|
25
|
+
if binary:
|
|
26
|
+
return {"ok": True, "binary": binary, "message": ""}
|
|
27
|
+
return {"ok": False, "binary": None, "message": INSTALL_MESSAGE}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def run_cli_json(args: Sequence[str]) -> dict | list:
|
|
31
|
+
"""Run DeepXiv and decode its JSON output."""
|
|
32
|
+
install = ensure_deepxiv_installed()
|
|
33
|
+
if not install["ok"]:
|
|
34
|
+
raise RuntimeError(str(install["message"]))
|
|
35
|
+
|
|
36
|
+
process = subprocess.run(
|
|
37
|
+
[str(install["binary"]), *args],
|
|
38
|
+
capture_output=True,
|
|
39
|
+
text=True,
|
|
40
|
+
encoding="utf-8",
|
|
41
|
+
check=False,
|
|
42
|
+
)
|
|
43
|
+
if process.returncode != 0:
|
|
44
|
+
message = (process.stderr or process.stdout or "deepxiv command failed").strip()
|
|
45
|
+
raise RuntimeError(message)
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
return json.loads(process.stdout)
|
|
49
|
+
except json.JSONDecodeError as exc:
|
|
50
|
+
raise RuntimeError("deepxiv returned invalid JSON output") from exc
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
54
|
+
parser = argparse.ArgumentParser(
|
|
55
|
+
description="Progressively read a known arXiv paper through DeepXiv."
|
|
56
|
+
)
|
|
57
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
58
|
+
|
|
59
|
+
brief = subparsers.add_parser(
|
|
60
|
+
"paper-brief", help="Fetch brief paper metadata and TLDR."
|
|
61
|
+
)
|
|
62
|
+
brief.add_argument("arxiv_id")
|
|
63
|
+
|
|
64
|
+
head = subparsers.add_parser(
|
|
65
|
+
"paper-head", help="Fetch paper metadata and the section overview."
|
|
66
|
+
)
|
|
67
|
+
head.add_argument("arxiv_id")
|
|
68
|
+
|
|
69
|
+
section = subparsers.add_parser(
|
|
70
|
+
"paper-section", help="Fetch one named paper section."
|
|
71
|
+
)
|
|
72
|
+
section.add_argument("arxiv_id")
|
|
73
|
+
section.add_argument("section_name")
|
|
74
|
+
|
|
75
|
+
return parser
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def dispatch(args: argparse.Namespace) -> dict | list:
|
|
79
|
+
if args.command == "paper-brief":
|
|
80
|
+
return run_cli_json(["paper", args.arxiv_id, "--brief", "--format", "json"])
|
|
81
|
+
if args.command == "paper-head":
|
|
82
|
+
return run_cli_json(["paper", args.arxiv_id, "--head", "--format", "json"])
|
|
83
|
+
if args.command == "paper-section":
|
|
84
|
+
return run_cli_json(
|
|
85
|
+
[
|
|
86
|
+
"paper",
|
|
87
|
+
args.arxiv_id,
|
|
88
|
+
"--section",
|
|
89
|
+
args.section_name,
|
|
90
|
+
"--format",
|
|
91
|
+
"json",
|
|
92
|
+
]
|
|
93
|
+
)
|
|
94
|
+
raise RuntimeError(f"Unsupported command: {args.command}")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
98
|
+
args = build_parser().parse_args(argv)
|
|
99
|
+
try:
|
|
100
|
+
payload = dispatch(args)
|
|
101
|
+
except RuntimeError as exc:
|
|
102
|
+
print(str(exc), file=sys.stderr)
|
|
103
|
+
return 1
|
|
104
|
+
|
|
105
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
106
|
+
return 0
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
if __name__ == "__main__":
|
|
110
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Thin Exa recall-expansion helper for research-paper search.
|
|
3
|
+
|
|
4
|
+
Adapted from wanshuiyin/Auto-claude-code-research-in-sleep at commit
|
|
5
|
+
e59008d7a42eea50a2797e55dd0d85bbbf6572f5 (MIT). See
|
|
6
|
+
../THIRD_PARTY_NOTICES.md.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
INSTALL_MESSAGE = "exa-py not found. Install it with: pip install exa-py"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def get_client() -> Any:
|
|
22
|
+
"""Create an Exa client without making Exa a required dependency."""
|
|
23
|
+
api_key = os.getenv("EXA_API_KEY", "").strip()
|
|
24
|
+
if not api_key:
|
|
25
|
+
raise RuntimeError(
|
|
26
|
+
"EXA_API_KEY environment variable is required. Get a key from: https://exa.ai"
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
from exa_py import Exa
|
|
31
|
+
except ImportError as exc:
|
|
32
|
+
raise RuntimeError(INSTALL_MESSAGE) from exc
|
|
33
|
+
|
|
34
|
+
client = Exa(api_key=api_key)
|
|
35
|
+
client.headers["x-exa-integration"] = "brainx-skill-bio-neuro-lit"
|
|
36
|
+
return client
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def parse_list(value: str | None) -> list[str] | None:
|
|
40
|
+
if not value:
|
|
41
|
+
return None
|
|
42
|
+
return [item.strip() for item in value.split(",") if item.strip()]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def content_kwargs(content_mode: str, max_chars: int) -> dict[str, Any]:
|
|
46
|
+
if content_mode == "none":
|
|
47
|
+
return {}
|
|
48
|
+
if content_mode == "text":
|
|
49
|
+
return {"text": {"max_characters": max_chars}}
|
|
50
|
+
if content_mode == "summary":
|
|
51
|
+
return {"summary": True}
|
|
52
|
+
return {"highlights": {"max_characters": max_chars}}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def process_result(result: Any, content_mode: str) -> dict[str, Any]:
|
|
56
|
+
entry: dict[str, Any] = {
|
|
57
|
+
"title": getattr(result, "title", None) or "No Title",
|
|
58
|
+
"url": getattr(result, "url", None) or "",
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
for source_field, target_field in (
|
|
62
|
+
("published_date", "published_date"),
|
|
63
|
+
("author", "author"),
|
|
64
|
+
):
|
|
65
|
+
value = getattr(result, source_field, None)
|
|
66
|
+
if value:
|
|
67
|
+
entry[target_field] = value
|
|
68
|
+
|
|
69
|
+
if content_mode == "highlights":
|
|
70
|
+
value = getattr(result, "highlights", None)
|
|
71
|
+
elif content_mode == "text":
|
|
72
|
+
value = getattr(result, "text", None)
|
|
73
|
+
elif content_mode == "summary":
|
|
74
|
+
value = getattr(result, "summary", None)
|
|
75
|
+
else:
|
|
76
|
+
value = None
|
|
77
|
+
|
|
78
|
+
if value:
|
|
79
|
+
entry[content_mode] = value
|
|
80
|
+
return entry
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def search(
|
|
84
|
+
query: str,
|
|
85
|
+
max_results: int = 10,
|
|
86
|
+
search_type: str = "auto",
|
|
87
|
+
content_mode: str = "highlights",
|
|
88
|
+
max_chars: int = 4000,
|
|
89
|
+
category: str = "research paper",
|
|
90
|
+
include_domains: list[str] | None = None,
|
|
91
|
+
exclude_domains: list[str] | None = None,
|
|
92
|
+
include_text: list[str] | None = None,
|
|
93
|
+
exclude_text: list[str] | None = None,
|
|
94
|
+
start_published_date: str | None = None,
|
|
95
|
+
end_published_date: str | None = None,
|
|
96
|
+
) -> dict[str, Any]:
|
|
97
|
+
"""Search Exa and return lightweight recall-expansion records."""
|
|
98
|
+
client = get_client()
|
|
99
|
+
kwargs: dict[str, Any] = {
|
|
100
|
+
"query": query,
|
|
101
|
+
"num_results": max_results,
|
|
102
|
+
"type": search_type,
|
|
103
|
+
"category": category,
|
|
104
|
+
}
|
|
105
|
+
kwargs.update(content_kwargs(content_mode, max_chars))
|
|
106
|
+
|
|
107
|
+
optional = {
|
|
108
|
+
"include_domains": include_domains,
|
|
109
|
+
"exclude_domains": exclude_domains,
|
|
110
|
+
"include_text": include_text,
|
|
111
|
+
"exclude_text": exclude_text,
|
|
112
|
+
"start_published_date": start_published_date,
|
|
113
|
+
"end_published_date": end_published_date,
|
|
114
|
+
}
|
|
115
|
+
kwargs.update({key: value for key, value in optional.items() if value})
|
|
116
|
+
|
|
117
|
+
response = client.search_and_contents(**kwargs)
|
|
118
|
+
return {
|
|
119
|
+
"mode": "search",
|
|
120
|
+
"query": query,
|
|
121
|
+
"type": search_type,
|
|
122
|
+
"category": category,
|
|
123
|
+
"returned": len(response.results),
|
|
124
|
+
"data": [process_result(result, content_mode) for result in response.results],
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
129
|
+
parser = argparse.ArgumentParser(
|
|
130
|
+
description="Expand biology or neuroscience paper recall through Exa."
|
|
131
|
+
)
|
|
132
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
133
|
+
search_parser = subparsers.add_parser("search", help="Search Exa.")
|
|
134
|
+
search_parser.add_argument("query")
|
|
135
|
+
search_parser.add_argument("--max", type=int, default=10, metavar="N")
|
|
136
|
+
search_parser.add_argument(
|
|
137
|
+
"--type",
|
|
138
|
+
default="auto",
|
|
139
|
+
dest="search_type",
|
|
140
|
+
choices=("auto", "neural", "fast", "instant"),
|
|
141
|
+
)
|
|
142
|
+
search_parser.add_argument(
|
|
143
|
+
"--category", default="research paper", help="Exa category filter."
|
|
144
|
+
)
|
|
145
|
+
search_parser.add_argument(
|
|
146
|
+
"--content",
|
|
147
|
+
default="highlights",
|
|
148
|
+
dest="content_mode",
|
|
149
|
+
choices=("highlights", "text", "summary", "none"),
|
|
150
|
+
)
|
|
151
|
+
search_parser.add_argument("--max-chars", type=int, default=4000, metavar="N")
|
|
152
|
+
search_parser.add_argument("--include-domains")
|
|
153
|
+
search_parser.add_argument("--exclude-domains")
|
|
154
|
+
search_parser.add_argument("--include-text")
|
|
155
|
+
search_parser.add_argument("--exclude-text")
|
|
156
|
+
search_parser.add_argument("--start-date")
|
|
157
|
+
search_parser.add_argument("--end-date")
|
|
158
|
+
return parser
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def main(argv: list[str] | None = None) -> int:
|
|
162
|
+
args = build_parser().parse_args(argv)
|
|
163
|
+
try:
|
|
164
|
+
result = search(
|
|
165
|
+
query=args.query,
|
|
166
|
+
max_results=args.max,
|
|
167
|
+
search_type=args.search_type,
|
|
168
|
+
content_mode=args.content_mode,
|
|
169
|
+
max_chars=args.max_chars,
|
|
170
|
+
category=args.category,
|
|
171
|
+
include_domains=parse_list(args.include_domains),
|
|
172
|
+
exclude_domains=parse_list(args.exclude_domains),
|
|
173
|
+
include_text=parse_list(args.include_text),
|
|
174
|
+
exclude_text=parse_list(args.exclude_text),
|
|
175
|
+
start_published_date=args.start_date,
|
|
176
|
+
end_published_date=args.end_date,
|
|
177
|
+
)
|
|
178
|
+
except KeyboardInterrupt:
|
|
179
|
+
print("Interrupted.", file=sys.stderr)
|
|
180
|
+
return 130
|
|
181
|
+
except Exception as exc:
|
|
182
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
183
|
+
return 1
|
|
184
|
+
|
|
185
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
186
|
+
return 0
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
if __name__ == "__main__":
|
|
190
|
+
raise SystemExit(main())
|
|
@@ -75,6 +75,22 @@ Write custom logic only when it expresses model behavior that the ecosystem does
|
|
|
75
75
|
|
|
76
76
|
Use the highest-level API in the selected owning package that preserves the scientific operation. Open lower-level BrainState control flow only when the package orchestrator cannot express the required inputs, monitors, State effects, or stable compilation boundary.
|
|
77
77
|
|
|
78
|
+
### Verify external infrastructure gaps
|
|
79
|
+
|
|
80
|
+
Before replacing a BrainTools-owned input, metric, optimizer, integration, encoding, or other infrastructure operation with SciPy, raw JAX, or custom code, record a compact API-gap artifact:
|
|
81
|
+
|
|
82
|
+
```markdown
|
|
83
|
+
## BrainTools API gap
|
|
84
|
+
- Operation and required capability:
|
|
85
|
+
- BrainTools APIs checked:
|
|
86
|
+
- Observed limitation or unavailable dependency:
|
|
87
|
+
- Why another routed BrainTools API does not satisfy the contract:
|
|
88
|
+
- Smallest external boundary:
|
|
89
|
+
- Unit, State, shape, and numerical parity evidence:
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
An unavailable optional backend does not establish a general BrainTools gap when another routed BrainTools API covers the operation. Keep host Python for file formats, serialization, statistics, or observation logic that no routed BrainX API owns; do not manufacture BrainTools use at those legitimate boundaries.
|
|
93
|
+
|
|
78
94
|
## Validate scientific claims
|
|
79
95
|
|
|
80
96
|
Derive claims from observables that distinguish the claimed mechanism; validate the baseline and mechanism before calibration, and mark unsourced calibrated regimes as phenomenological.
|
|
@@ -129,6 +145,7 @@ Use raw JAX transformations only for pure array or PyTree functions that do not
|
|
|
129
145
|
- Point-neuron and aggregate population mechanisms mixed without selecting both owning skills or declaring the multiscale boundary.
|
|
130
146
|
- A custom BrainState loop that duplicates the selected package's runner, inputs, monitoring, initialization, or sampling.
|
|
131
147
|
- Manual array or mathematical machinery that duplicates BrainUnit or BrainTools.
|
|
148
|
+
- Generic infrastructure replacing a BrainTools-owned operation without a recorded capability gap and parity evidence.
|
|
132
149
|
- Python timestep loops or host loops inside a stable logical rollout.
|
|
133
150
|
- Raw `jax.jit`, `jax.grad`, or `jax.vmap` applied to State-aware code.
|
|
134
151
|
- Host-side statistics, serialization, timing, device reporting, or custom presentation forced into BrainX without an owning API.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: brainx-modeling-loop
|
|
3
|
-
description: Use first for an end-to-end BrainX modeling project. Start fresh or resume from brainmodeling-memory.md, write a compact NeuroSpecification.md, study the relevant BrainX skills deeply, implement and accelerate the model, run experiments, send code and results to Codex through MCP,
|
|
3
|
+
description: Use first for an end-to-end BrainX modeling project. Start fresh or resume from brainmodeling-memory.md, write a compact NeuroSpecification.md, study the relevant BrainX skills deeply, implement and accelerate the model, run experiments, send code and results to Codex through MCP, restudy the affected BrainX skills when review refuses, and visualize only after review passes.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# BrainX modeling loop
|
|
@@ -30,6 +30,12 @@ Use this complete append-only memory contract:
|
|
|
30
30
|
|
|
31
31
|
### Important milestones
|
|
32
32
|
- <decision, review outcome, blocker, or completed result with its evidence pointer>
|
|
33
|
+
|
|
34
|
+
## Literature evidence: <topic> - <YYYY-MM-DD>
|
|
35
|
+
- Research question: <question addressed>
|
|
36
|
+
- Review artifact: <path or stable identifier>
|
|
37
|
+
- Essential papers and modeling consequences: <concise evidence records>
|
|
38
|
+
- Cross-paper synthesis: <supported decisions, uncertainty, and required tests>
|
|
33
39
|
```
|
|
34
40
|
|
|
35
41
|
For `fresh-new`, create the file with its title, start iteration 1 at step 0, and
|
|
@@ -46,7 +52,7 @@ and continue from the first unfinished action after the latest valid checkpoint.
|
|
|
46
52
|
```text
|
|
47
53
|
fresh-new -> step 0 -> step 1 -> step 2 -> step 3 -> step 4 -> step 5
|
|
48
54
|
^ |
|
|
49
|
-
|
|
55
|
+
|--------- REFUSE ---------|
|
|
50
56
|
|
|
51
57
|
step 5 PASS -> step 6 -> complete
|
|
52
58
|
```
|
|
@@ -55,6 +61,8 @@ Each checkpoint contains the artifacts created or updated by that step and the
|
|
|
55
61
|
important milestones reached during it. Keep full code, logs, results, and
|
|
56
62
|
reviews in their owning artifacts and point to them from the checkpoint.
|
|
57
63
|
|
|
64
|
+
The `bio-neuro-lit` skill may append repeatable `## Literature evidence` blocks when selected papers materially affect the model. Treat these blocks as evidence records, not checkpoints: they do not change the current iteration or step. Read them before step 0 specification decisions and during step 1 study, and preserve their source identifiers, evidence depth, publication version, modeling implications, and limitations.
|
|
65
|
+
|
|
58
66
|
## Step 0: Write the specification
|
|
59
67
|
|
|
60
68
|
Turn the researcher's request and inspected data into a short `NeuroSpecification.md`. Ask the researcher only for missing decisions that would change the model, data interpretation, or acceptance boundary. Do not infer them.
|
|
@@ -113,6 +121,10 @@ Study before implementing. Understand the selected BrainX abstractions, exact AP
|
|
|
113
121
|
|
|
114
122
|
Do not write the implementation during step 1. Finish the study record first.
|
|
115
123
|
|
|
124
|
+
When step 5 returns `REFUSE`, increment the iteration and return here before changing code. Map every reviewer finding to the owning BrainX package or workflow skill, reopen `brainx-general-guard`, and restudy every affected package skill, routed reference, and canonical script that can change the correction. Recheck high-level BrainX and BrainTools APIs before retaining custom or external infrastructure. Open the active training or fitting reference during this restudy when a finding concerns its objective, architecture, optimizer, input, metric, recovery, or evidence contract.
|
|
125
|
+
|
|
126
|
+
Preserve the original study artifact. For iteration 1, use `brainx-study-record.md`; after a refusal, write `brainx-study-record-iteration-<N>.md` with the reviewer-finding map, newly studied sources, changed or reaffirmed API decisions, and the resulting implementation design. Append a step-1 memory checkpoint pointing to the new artifact. Do not begin step 2 until this iteration-specific restudy is complete.
|
|
127
|
+
|
|
116
128
|
**Step result:** a complete BrainX study record and an implementation design grounded in the selected skills, then a memory checkpoint pointing to step 2.
|
|
117
129
|
|
|
118
130
|
## Optional training and fitting coverage for steps 2-5
|
|
@@ -139,8 +151,6 @@ Implement from the step-1 study record and the locked specification. Open the se
|
|
|
139
151
|
5. Run only small implementation checks needed to prove the code is ready for acceleration and the experiment runner. Leave production execution to step 4.
|
|
140
152
|
6. Record the code and test artifacts plus any important implementation milestone.
|
|
141
153
|
|
|
142
|
-
When step 5 returns `REFUSE`, begin a new iteration here. Read every reviewer finding, preserve the locked specification, make the smallest sufficient implementation or experiment-design correction, update memory, and then repeat steps 3, 4, and 5.
|
|
143
|
-
|
|
144
154
|
**Step result:** BrainX-native model and experiment code with focused checks, then a memory checkpoint pointing to step 3.
|
|
145
155
|
|
|
146
156
|
## Step 3: Accelerate the code
|
|
@@ -175,12 +185,13 @@ Start one fresh `mcp__codex__codex` call for each completed iteration. Send the
|
|
|
175
185
|
locked specification, step-1 study record, implementation and tests, acceleration
|
|
176
186
|
evidence, experiment configuration, raw run artifacts, metrics, deterministic
|
|
177
187
|
result assessment, claim-evidence matrix, proposed next action, and all evidence
|
|
178
|
-
required by active training/fitting coverage.
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
188
|
+
required by active training/fitting coverage. The returned `content` is the
|
|
189
|
+
reviewer's Markdown report in the calling agent's current turn. Before
|
|
190
|
+
classifying it, save it verbatim as `reviews/iteration-<N>.md`; do not reformat,
|
|
191
|
+
summarize, or mix the main agent's analysis into that file. Then read its verdict,
|
|
192
|
+
update the loop checkpoint with the report path, and report or act on it without
|
|
193
|
+
asking the researcher to open another context. Preserve the returned `threadId`
|
|
194
|
+
in the checkpoint for reviewer follow-up; it is not needed to read the report.
|
|
184
195
|
|
|
185
196
|
Before calling, verify that every listed path exists. Set the MCP call's working
|
|
186
197
|
directory to the project root when the tool exposes a working-directory argument,
|
|
@@ -199,7 +210,7 @@ LOOP_MEMORY:
|
|
|
199
210
|
- <path>/brainmodeling-memory.md
|
|
200
211
|
|
|
201
212
|
BRAINX_STUDY_RECORD:
|
|
202
|
-
- <path to
|
|
213
|
+
- <path to every step-1 study artifact through this iteration>
|
|
203
214
|
|
|
204
215
|
IMPLEMENTATION:
|
|
205
216
|
- <path to each model, data-processing, and experiment source file>
|
|
@@ -228,7 +239,7 @@ PRIOR_REVIEW_EVIDENCE:
|
|
|
228
239
|
- <path to prior raw reviews and addressed findings, or none>
|
|
229
240
|
|
|
230
241
|
Read every listed artifact and review this iteration using the injected reviewer
|
|
231
|
-
contract. Do not edit files. Return the required
|
|
242
|
+
contract. Do not edit files. Return only the required Markdown report.
|
|
232
243
|
```
|
|
233
244
|
|
|
234
245
|
List concrete files, not only directories. Keep large data in place and provide
|
|
@@ -241,21 +252,23 @@ Do not start an iteration review with `mcp__codex__codex-reply`; only a fresh
|
|
|
241
252
|
unavailable, record step 5 as blocked in `brainmodeling-memory.md` and preserve
|
|
242
253
|
all completed experiment artifacts.
|
|
243
254
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
255
|
+
For a non-interactive Codex host, configure the MCP registration with
|
|
256
|
+
`default_tools_approval_mode = "approve"`; otherwise the host cannot present an
|
|
257
|
+
MCP approval prompt and may report the denied call as `user cancelled MCP tool
|
|
258
|
+
call`. Also set `tool_timeout_sec = 1800`, or another explicit budget longer than
|
|
259
|
+
the largest expected review. When no `threadId` or response is returned, verify
|
|
260
|
+
approval first and timeout second before treating it as researcher cancellation.
|
|
248
261
|
|
|
249
|
-
Record the
|
|
262
|
+
Record the verbatim Markdown report path, `threadId`, and one of two outcomes:
|
|
250
263
|
|
|
251
264
|
| Outcome | Transition |
|
|
252
265
|
|---|---|
|
|
253
|
-
| `REFUSE` | Record every finding and required correction, increment the iteration, set the current step to
|
|
266
|
+
| `REFUSE` | Record every finding and required correction, increment the iteration, set the current step to 1, restudy the affected BrainX package and workflow skills, and repeat steps 1-5 with the same optional coverage. |
|
|
254
267
|
| `PASS` | Record the accepted code/result scope and set the current step to 6. |
|
|
255
268
|
|
|
256
|
-
Do not argue with a refusal inside step 5 and do not substitute self-review for the MCP Codex call. The next Codex call occurs only after the
|
|
269
|
+
Do not argue with a refusal inside step 5 and do not substitute self-review for the MCP Codex call. The next Codex call occurs only after the refusal has passed through package restudy, revised implementation, acceleration, and experiment execution.
|
|
257
270
|
|
|
258
|
-
**Step result:** a preserved
|
|
271
|
+
**Step result:** a preserved `reviews/iteration-<N>.md` report and either a return to step 1 or a memory checkpoint pointing to step 6.
|
|
259
272
|
|
|
260
273
|
## Step 6: Visualize the accepted result
|
|
261
274
|
|
|
@@ -27,7 +27,8 @@ Parameter recovery represents the interpretation gate. A fitted value may suppor
|
|
|
27
27
|
| Aggregate population, region, or whole-brain fitting | Open `brainmass`. Prefer `brainmass.Fitter` and its routed fitting reference before building a custom optimizer loop. |
|
|
28
28
|
| Physical parameters or observations | Open `brainunit`. Preserve quantities through parameter application, simulation, observation, and unit-compatible comparison. |
|
|
29
29
|
| Constrained parameters or regularization | Open the active package's BrainState parameter reference. Record both the unconstrained optimizer value and constrained physical value. |
|
|
30
|
-
|
|
|
30
|
+
| BrainCell input, objective, or optimizer selection | Open `braincell/references/braintools/input-current.md`, `metric.md`, or `optimizer.md` for the operation being selected. |
|
|
31
|
+
| BrainPy-State or BrainMass objective or optimizer selection | Open the active package's routed Braintools metric or optimizer reference. Prefer package-owned BrainMass objectives when they express the scientific comparison. |
|
|
31
32
|
|
|
32
33
|
Study the selected package skills and their fitting-related examples before implementing. Trace construction, initialization, parameter application, runtime State reset, protocol execution, observation, and reduction end to end.
|
|
33
34
|
|
|
@@ -55,20 +56,24 @@ Never rely on dictionary order or an unlabeled vector to preserve scientific mea
|
|
|
55
56
|
|
|
56
57
|
## Select the fitting backend
|
|
57
58
|
|
|
58
|
-
Choose the simplest backend supported by the simulator
|
|
59
|
+
Choose the simplest BrainX backend supported by the complete simulator-to-objective path. Check required optional dependencies before locking the estimator.
|
|
59
60
|
|
|
60
61
|
| Condition | Use | Required checks |
|
|
61
62
|
|---|---|---|
|
|
62
63
|
| The complete simulator-to-objective path is differentiable and numerically stable | `brainmass.Fitter(..., backend="grad")` or `brainstate.transform.grad` with a Braintools gradient optimizer | Finite and nonzero gradients, a small finite-difference comparison, multiple starts, exact-pipeline recovery, and held-out prediction. |
|
|
63
|
-
| A
|
|
64
|
+
| A package-owned fitter supports the required gradient-free objective | Its bounded gradient-free backend | Finite bounds, full budget, multiple starts, landscape or sensitivity evidence, recovery, and held-out prediction. |
|
|
65
|
+
| One scalar bounded or constrained objective matches a documented SciPy method | `braintools.optim.ScipyOptimizer` | Parameter order and unit reconstruction, method compatibility, finite bounds, stopping behavior, multiple starts, recovery, and held-out prediction. |
|
|
66
|
+
| The objective is discontinuous, discrete, black-box, or benefits from population-batched candidates | `braintools.optim.NevergradOptimizer` when its optional dependency is available | One loss per candidate, candidate independence, unit-bearing bounds, total evaluation count, multiple starts, recovery, and held-out prediction. |
|
|
64
67
|
|
|
65
|
-
Prefer gradients when they are valid. Do not select derivative-free fitting merely because the BrainCell example uses Nevergrad; that example establishes a custom candidate-evaluation pattern, not a universal backend choice.
|
|
68
|
+
Prefer gradients when they are valid. Do not select derivative-free fitting merely because the BrainCell example uses Nevergrad; that example establishes a custom candidate-evaluation pattern, not a universal backend choice. If Nevergrad is unavailable, test whether `braintools.optim.ScipyOptimizer` satisfies the locked objective before changing libraries or requesting dependency installation.
|
|
69
|
+
|
|
70
|
+
Use raw SciPy or another generic optimizer only when no routed BrainTools backend provides a required estimator strategy, vectorized candidate contract, callback, constraint, or stopping rule. Before implementation, save the `brainx-general-guard` API-gap artifact naming the checked BrainTools APIs, exact missing capability, smallest external boundary, and parity evidence. A missing optional Nevergrad dependency alone is not a BrainTools capability gap.
|
|
66
71
|
|
|
67
72
|
## Apply the scale-specific pattern
|
|
68
73
|
|
|
69
74
|
| Route | Pattern to preserve |
|
|
70
75
|
|---|---|
|
|
71
|
-
| BrainCell | The HH fitting example constructs and initializes one cell rollout for each unit-bearing conductance and capacitance candidate, evaluates time-major current protocols, and batches derivative-free candidates. Preserve candidate independence and unit-bounded search; reconcile exact channel and State APIs
|
|
76
|
+
| BrainCell | The HH fitting example constructs and initializes one cell rollout for each unit-bearing conductance and capacitance candidate, evaluates time-major current protocols, scores voltage with Braintools metrics, and batches derivative-free candidates. Preserve candidate independence and unit-bounded search; open the BrainCell Braintools input, metric, and optimizer references and reconcile exact channel and State APIs before adapting it. |
|
|
72
77
|
| BrainPy-State | The training examples initialize runtime State at each independent sequence, differentiate only the selected `ParamState` collection, transform the complete loss step, and update parameters outside the temporal loop. Reuse that lifecycle for an inverse objective; task loss itself is not parameter fitting. |
|
|
73
78
|
| BrainMass | The fitting examples prefer `Fitter`, mark fitted values with `brainstate.nn.Param(..., fit=True)`, and fit phase-appropriate observations such as settled amplitude rather than an unaligned oscillatory waveform. Use gradient fitting first and change backends only when the objective requires it. |
|
|
74
79
|
| Braintools | Gradient optimizers register trainable State and consume matching gradient trees. `ScipyOptimizer` and `NevergradOptimizer` instead own a complete objective and do not use the register/update lifecycle; Nevergrad requires one loss per candidate. |
|
|
@@ -83,8 +88,37 @@ One candidate evaluation must apply parameters, reset independent runtime State,
|
|
|
83
88
|
| `brainstate.nn.init_all_states(model, ...)` | Use at an independent rollout boundary when the selected model route requires model-wide runtime State initialization. Do not reset fitted parameter State. |
|
|
84
89
|
| `brainstate.transform.grad(loss_fn, grad_states=..., return_value=True)` | Use for a custom stateful differentiable objective. Select only intended parameter State and transform the complete loss evaluation. |
|
|
85
90
|
| `brainmass.Fitter(...)` | Use when BrainMass owns the simulator and its loss, prediction, objective, and backend interfaces express the inverse problem. |
|
|
91
|
+
| `braintools.input.Constant(...)` | Use when the fitted cellular protocol contains timed constant sections; generate the unit-aware time-major current under the rollout `dt`. |
|
|
92
|
+
| `braintools.metric.squared_error(...)` | Use for a standard waveform discrepancy; preserve time and candidate axes until the declared reduction and keep custom observation features separate. |
|
|
93
|
+
| `braintools.optim.ScipyOptimizer(...)` | Use when one scalar objective and a documented SciPy method satisfy the fitting contract; it owns the standalone optimization and returns the SciPy result. |
|
|
86
94
|
| `braintools.optim.NevergradOptimizer(...)` | Use for a custom black-box objective that accepts candidate-stacked parameters and returns one loss per candidate. Preserve unit-bearing bounds and independent runtime State. |
|
|
87
|
-
|
|
95
|
+
|
|
96
|
+
For a BrainCell current-clamp fit, keep custom file parsing at the host boundary but generate the inferred protocol and standard waveform loss through BrainTools:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
import brainstate
|
|
100
|
+
import braintools
|
|
101
|
+
import brainunit as u
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
with brainstate.environ.context(dt=0.1 * u.ms):
|
|
105
|
+
current = braintools.input.Constant([
|
|
106
|
+
(0.0 * u.pA, 50.0 * u.ms),
|
|
107
|
+
(25.0 * u.pA, 250.0 * u.ms),
|
|
108
|
+
(0.0 * u.pA, 200.0 * u.ms),
|
|
109
|
+
])()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def waveform_rmse_mV(predicted, observed):
|
|
113
|
+
mse = braintools.metric.squared_error(
|
|
114
|
+
predicted.to_decimal(u.mV),
|
|
115
|
+
observed.to_decimal(u.mV),
|
|
116
|
+
reduction="mean",
|
|
117
|
+
)
|
|
118
|
+
return u.math.sqrt(mse)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Keep a custom voltage-peak detector, observation transform, or domain penalty only when no routed BrainTools metric expresses the declared feature. Do not reimplement standard waveform losses merely because one objective component is custom.
|
|
88
122
|
|
|
89
123
|
Use the BrainMass path as the canonical high-level workflow:
|
|
90
124
|
|
|
@@ -158,6 +192,7 @@ This proves only that one synthetic target is mechanically recoverable. It does
|
|
|
158
192
|
5. For gradient fitting, compare autodiff with finite differences on a small stable case and inspect zero, exploding, `NaN`, or parameter-missing gradients.
|
|
159
193
|
6. For derivative-free fitting, verify candidate-axis shape, one loss per candidate, unit reconstruction, bounds, invalid-candidate behavior, and total evaluation count.
|
|
160
194
|
7. Inspect sensitivity, tradeoffs, flat directions, discontinuities, and numerical boundaries before running the full fit.
|
|
195
|
+
8. When a generic optimizer, input generator, metric, or integration utility replaces BrainTools, verify the saved API-gap artifact and its unit, State, shape, and numerical parity evidence.
|
|
161
196
|
|
|
162
197
|
## Run exact-pipeline parameter recovery
|
|
163
198
|
|
|
@@ -203,7 +238,10 @@ Fit observed data only after recovery passes the locked parameter-specific crite
|
|
|
203
238
|
|
|
204
239
|
| Route | Open when |
|
|
205
240
|
|---|---|
|
|
206
|
-
| `parameter-fitting-workflow/scripts/fitting_hh_neuron.py` | Studying the official complete BrainCell HH derivative-free fitting composition: custom channels, unit-bearing bounds, per-candidate cell initialization, time-major rollout, voltage loss, candidate `vmap`, and Nevergrad.
|
|
241
|
+
| `parameter-fitting-workflow/scripts/fitting_hh_neuron.py` | Studying the official complete BrainCell HH derivative-free fitting composition: custom channels, unit-bearing bounds, per-candidate cell initialization, time-major rollout, voltage loss, candidate `vmap`, and Nevergrad. Also open the three BrainCell Braintools references below; supply the upstream trace CSVs and reconcile source-version APIs before adapting it. |
|
|
242
|
+
| `braincell` -> `references/braintools/input-current.md` | Generating timed current sections, pulses, waveforms, or stochastic stimulation for a cellular fit. |
|
|
243
|
+
| `braincell` -> `references/braintools/metric.md` | Selecting standard waveform losses or neuroscience metrics while separating custom observation features. |
|
|
244
|
+
| `braincell` -> `references/braintools/optimizer.md` | Selecting gradient optimizers, `ScipyOptimizer`, or `NevergradOptimizer` and checking their lifecycle, unit, and dependency boundaries. |
|
|
207
245
|
| `brainmass` -> `references/fitting-with-objectives-api.md` | Selecting `Fitter` interfaces, objectives, callbacks, `FitResult` fields, or gradient versus gradient-free backends. |
|
|
208
246
|
| `brainmass` -> `references/scripts/eeg-fitting-with-gradients.py` | Studying a complete phase-insensitive EEG fitting and synthetic-recovery example. |
|
|
209
247
|
| `brainmass` -> `references/scripts/gradient-free-fitting.py` | A bounded non-differentiable or black-box BrainMass objective requires Nevergrad or SciPy. |
|
|
@@ -219,6 +257,8 @@ Fit observed data only after recovery passes the locked parameter-specific crite
|
|
|
219
257
|
- Treating a surrogate gradient as evidence that a fitted spiking parameter is identifiable.
|
|
220
258
|
- Fitting raw oscillatory waveforms when phase is not experimentally aligned.
|
|
221
259
|
- Selecting derivative-free fitting before checking whether gradients are valid.
|
|
260
|
+
- Treating an unavailable optional Nevergrad dependency as permission to bypass another suitable BrainTools optimizer.
|
|
261
|
+
- Replacing a BrainTools-owned optimizer, metric, input, or integrator without a recorded capability gap and parity evidence.
|
|
222
262
|
- Changing bounds, summaries, exclusions, weights, or recovery criteria after inspecting observed-data results.
|
|
223
263
|
- Running recovery with longer, cleaner, denser, or easier data than the real protocol.
|
|
224
264
|
- Interpreting aggregate fit quality as parameter recovery.
|