brainx-skill 1.0.13 → 1.0.15

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 (44) hide show
  1. package/README.md +26 -0
  2. package/installation/lib/cli.js +16 -4
  3. package/installation/lib/literature-mcp.js +536 -0
  4. package/manifest.json +2 -0
  5. package/mcp-servers/codex/README.md +24 -4
  6. package/mcp-servers/codex/UPSTREAM.md +3 -1
  7. package/mcp-servers/codex/server.mjs +2 -0
  8. package/mcp-servers/codex/system-prompt.md +30 -19
  9. package/mcp-servers/codex/test/server.test.mjs +12 -1
  10. package/mcp-servers/fulltext-resolver/README.md +136 -0
  11. package/mcp-servers/fulltext-resolver/REUSE.md +32 -0
  12. package/mcp-servers/fulltext-resolver/THIRD_PARTY_NOTICES.md +57 -0
  13. package/mcp-servers/fulltext-resolver/server.mjs +128 -0
  14. package/mcp-servers/fulltext-resolver/src/document.mjs +253 -0
  15. package/mcp-servers/fulltext-resolver/src/http.mjs +173 -0
  16. package/mcp-servers/fulltext-resolver/src/identifiers.mjs +123 -0
  17. package/mcp-servers/fulltext-resolver/src/model.mjs +105 -0
  18. package/mcp-servers/fulltext-resolver/src/resolver.mjs +305 -0
  19. package/mcp-servers/fulltext-resolver/src/sources/biorxiv.mjs +135 -0
  20. package/mcp-servers/fulltext-resolver/src/sources/europe-pmc.mjs +132 -0
  21. package/mcp-servers/fulltext-resolver/src/sources/openalex.mjs +165 -0
  22. package/mcp-servers/fulltext-resolver/test/document.test.mjs +82 -0
  23. package/mcp-servers/fulltext-resolver/test/resolver.test.mjs +287 -0
  24. package/mcp-servers/fulltext-resolver/test/server.test.mjs +63 -0
  25. package/mcp-servers/fulltext-resolver/test/sources.test.mjs +229 -0
  26. package/package.json +10 -3
  27. package/skills/bio-neuro-lit/SKILL.md +206 -0
  28. package/skills/bio-neuro-lit/THIRD_PARTY_NOTICES.md +34 -0
  29. package/skills/bio-neuro-lit/agents/openai.yaml +4 -0
  30. package/skills/bio-neuro-lit/references/tool-contracts.md +73 -0
  31. package/skills/bio-neuro-lit/scripts/deepxiv_fetch.py +110 -0
  32. package/skills/bio-neuro-lit/scripts/exa_search.py +190 -0
  33. package/skills/brainx-general-guard/SKILL.md +17 -0
  34. package/skills/brainx-modeling-loop/SKILL.md +63 -24
  35. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +47 -7
  36. package/skills/brainx-visualization/SKILL.md +157 -0
  37. package/skills/brainx-visualization/agents/openai.yaml +4 -0
  38. package/skills/brainx-visualization/references/interactive-and-visualization-styling.md +155 -0
  39. package/skills/brainx-visualization/references/neural-data-visualization.md +141 -0
  40. package/skills/brainx-visualization/references/statistical-and-model-visualization.md +133 -0
  41. package/skills/package-skills/braincell/SKILL.md +16 -6
  42. package/skills/package-skills/braincell/references/braintools/input-current.md +200 -0
  43. package/skills/package-skills/braincell/references/braintools/metric.md +152 -0
  44. 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, repeat from implementation when review refuses, and visualize only after review passes.
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, optionally research unknown, unverified, or controversial scientific mechanisms, 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
@@ -44,9 +50,9 @@ For `resume`, read the checkpoints in order, verify the latest artifact pointers
44
50
  and continue from the first unfinished action after the latest valid checkpoint.
45
51
 
46
52
  ```text
47
- fresh-new -> step 0 -> step 1 -> step 2 -> step 3 -> step 4 -> step 5
48
- ^ |
49
- |-------- REFUSE ----------|
53
+ fresh-new -> step 0 -> optional literature gate -> step 1 -> step 2 -> step 3 -> step 4 -> step 5
54
+ ^ |
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.
@@ -88,9 +96,35 @@ Use only this core structure:
88
96
  - Allowed claims and explicit non-claims:
89
97
  ```
90
98
 
91
- Inspect supplied data before completing its contract. Keep raw data read-only, preserve units and axis meaning, and prevent preprocessing leakage. Lock the specification with researcher approval before step 1.
99
+ Inspect supplied data before completing its contract. Keep raw data read-only, preserve units and axis meaning, and prevent preprocessing leakage. Obtain researcher approval for the initial specification, then evaluate the literature gate before proceeding to step 1.
100
+
101
+ ### Optional literature gate after the NeuroSpecification
102
+
103
+ Use literature research only when unresolved scientific evidence could change the model, experiment, validation, or allowed claims; do not use it for ordinary BrainX implementation uncertainty.
104
+
105
+ | Trigger case | Use `bio-neuro-lit` when |
106
+ |---|---|
107
+ | Unknown mechanism | The requested phenomenon is clear, but the responsible biological mechanism, represented scale, causal pathway, or defensible model abstraction is not established. |
108
+ | Unverified premise | The specification depends on an unsupported causal direction, cell type or circuit role, parameter regime, species transfer, scale mapping, intervention effect, or biological-realism claim. |
109
+ | Controversial explanation | Multiple credible mechanisms or model families explain the headline observation but imply different state variables, equations, interventions, controls, or observables. |
110
+ | Evidence-dependent design choice | Choosing a model family, component, coupling sign, timescale, input protocol, control, validation metric, or acceptance criterion requires experimental or computational-neuroscience evidence. |
111
+ | Ambiguous reproduction target | A target paper, preprint, or supplied description omits decisive methods, conflicts across versions, or claims a mechanism that its reported experiment may not isolate. |
112
+ | Recency-sensitive claim | The researcher asks for the current state of evidence, or recent findings could reasonably change the mechanism or model choice. |
113
+
114
+ Skip the literature gate when the researcher supplies an agreed authoritative mechanism and requests faithful implementation, when a standard model is already fixed, or when the uncertainty concerns only BrainX APIs, software architecture, optimization, debugging, or fitting parameters from supplied data. Open the owning BrainX skills for those cases. A topic being unfamiliar to the agent is not by itself a trigger.
92
115
 
93
- **Step result:** a locked `NeuroSpecification.md` and a memory checkpoint pointing to step 1.
116
+ When the gate triggers:
117
+
118
+ 1. Name each unresolved scientific claim and the modeling decision it controls. Keep the search scoped to those decisions.
119
+ 2. Invoke `bio-neuro-lit` and require it to distinguish full-text from abstract-only evidence, publication versions, consensus, disagreement, and non-claims.
120
+ 3. Have `bio-neuro-lit` append its essential modeling consequences to `brainmodeling-memory.md` as `## Literature evidence`, without changing the current checkpoint.
121
+ 4. Reconcile the evidence with `NeuroSpecification.md`. Preserve supported choices, encode unresolved alternatives and discriminating controls, and narrow claims that the evidence does not justify.
122
+ 5. Do not silently change an approved specification. If the evidence changes a model, experiment, acceptance boundary, or allowed claim, mark the revision `draft`, obtain researcher approval, relock it, and append a corrected step-0 checkpoint that names the earlier checkpoint it supersedes.
123
+ 6. If the evidence remains inconclusive and the alternatives would produce materially different studies, ask the researcher to choose or approve a comparison design before step 1. Otherwise preserve the uncertainty as an explicit limitation and required test.
124
+
125
+ When the gate does not trigger, record the skip and its reason as a step-0 milestone. Do not perform a broad background review merely to make the study record look comprehensive.
126
+
127
+ **Step result:** a locked or evidence-reconciled `NeuroSpecification.md`, a resolved or explicitly skipped literature gate, and a memory checkpoint pointing to step 1.
94
128
 
95
129
  ## Step 1: Study the relevant BrainX modeling skills
96
130
 
@@ -113,6 +147,10 @@ Study before implementing. Understand the selected BrainX abstractions, exact AP
113
147
 
114
148
  Do not write the implementation during step 1. Finish the study record first.
115
149
 
150
+ 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.
151
+
152
+ 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.
153
+
116
154
  **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
155
 
118
156
  ## Optional training and fitting coverage for steps 2-5
@@ -139,8 +177,6 @@ Implement from the step-1 study record and the locked specification. Open the se
139
177
  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
178
  6. Record the code and test artifacts plus any important implementation milestone.
141
179
 
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
180
  **Step result:** BrainX-native model and experiment code with focused checks, then a memory checkpoint pointing to step 3.
145
181
 
146
182
  ## Step 3: Accelerate the code
@@ -175,12 +211,13 @@ Start one fresh `mcp__codex__codex` call for each completed iteration. Send the
175
211
  locked specification, step-1 study record, implementation and tests, acceleration
176
212
  evidence, experiment configuration, raw run artifacts, metrics, deterministic
177
213
  result assessment, claim-evidence matrix, proposed next action, and all evidence
178
- required by active training/fitting coverage. Preserve the returned raw response
179
- and `threadId` as review artifacts. Treat the returned `content` as the reviewer
180
- response in the calling agent's current turn: classify it immediately, update
181
- the loop checkpoint, and report or act on the verdict without asking the
182
- researcher to open another context. Preserve `threadId` for reviewer follow-up;
183
- it is not needed for the calling agent to read the initial response.
214
+ required by active training/fitting coverage. The returned `content` is the
215
+ reviewer's Markdown report in the calling agent's current turn. Before
216
+ classifying it, save it verbatim as `reviews/iteration-<N>.md`; do not reformat,
217
+ summarize, or mix the main agent's analysis into that file. Then read its verdict,
218
+ update the loop checkpoint with the report path, and report or act on it without
219
+ asking the researcher to open another context. Preserve the returned `threadId`
220
+ in the checkpoint for reviewer follow-up; it is not needed to read the report.
184
221
 
185
222
  Before calling, verify that every listed path exists. Set the MCP call's working
186
223
  directory to the project root when the tool exposes a working-directory argument,
@@ -199,7 +236,7 @@ LOOP_MEMORY:
199
236
  - <path>/brainmodeling-memory.md
200
237
 
201
238
  BRAINX_STUDY_RECORD:
202
- - <path to the step-1 study artifact>
239
+ - <path to every step-1 study artifact through this iteration>
203
240
 
204
241
  IMPLEMENTATION:
205
242
  - <path to each model, data-processing, and experiment source file>
@@ -228,7 +265,7 @@ PRIOR_REVIEW_EVIDENCE:
228
265
  - <path to prior raw reviews and addressed findings, or none>
229
266
 
230
267
  Read every listed artifact and review this iteration using the injected reviewer
231
- contract. Do not edit files. Return the required structured outcome.
268
+ contract. Do not edit files. Return only the required Markdown report.
232
269
  ```
233
270
 
234
271
  List concrete files, not only directories. Keep large data in place and provide
@@ -241,21 +278,23 @@ Do not start an iteration review with `mcp__codex__codex-reply`; only a fresh
241
278
  unavailable, record step 5 as blocked in `brainmodeling-memory.md` and preserve
242
279
  all completed experiment artifacts.
243
280
 
244
- Configure the Codex MCP registration with `tool_timeout_sec = 1800`, or another
245
- explicit budget longer than the largest expected review. A host timeout may be
246
- reported as `user cancelled MCP tool call`; when no `threadId` or response is
247
- returned, diagnose the MCP budget before treating it as researcher cancellation.
281
+ For a non-interactive Codex host, configure the MCP registration with
282
+ `default_tools_approval_mode = "approve"`; otherwise the host cannot present an
283
+ MCP approval prompt and may report the denied call as `user cancelled MCP tool
284
+ call`. Also set `tool_timeout_sec = 1800`, or another explicit budget longer than
285
+ the largest expected review. When no `threadId` or response is returned, verify
286
+ approval first and timeout second before treating it as researcher cancellation.
248
287
 
249
- Record the full Codex response and one of two outcomes:
288
+ Record the verbatim Markdown report path, `threadId`, and one of two outcomes:
250
289
 
251
290
  | Outcome | Transition |
252
291
  |---|---|
253
- | `REFUSE` | Record every finding and required correction, increment the iteration, set the current step to 2, and repeat steps 2-5 with the same optional coverage. |
292
+ | `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
293
  | `PASS` | Record the accepted code/result scope and set the current step to 6. |
255
294
 
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 revised implementation has passed again through acceleration and experiment execution.
295
+ 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
296
 
258
- **Step result:** a preserved Codex response and either a return to step 2 or a memory checkpoint pointing to step 6.
297
+ **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
298
 
260
299
  ## Step 6: Visualize the accepted result
261
300
 
@@ -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
- | Objective or optimizer selection | Open the active package's Braintools metric or optimizer reference. Prefer package-owned BrainMass objectives when they express the scientific comparison. |
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 and objective.
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 required branch, observation, or objective is discontinuous, discrete, black-box, or has unreliable gradients | Bounded `brainmass.Fitter` gradient-free backend or the routed Braintools `NevergradOptimizer` or `ScipyOptimizer` | Finite bounds, correct candidate-batch semantics, full evaluation budget, multiple starts, landscape or sensitivity evidence, recovery, and held-out prediction. |
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 with the current BrainCell skill. |
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
- | `braintools.metric.*` | Use when the selected model package has no owning objective. Declare orientation and reduction because many metrics return arrays. |
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. Supply the upstream `input_traces_hh.csv` and `output_traces_hh.csv` files, and reconcile its source-version BrainCell and BrainState APIs with the current package skills before adapting it. |
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.