rh-cli 0.1.0__tar.gz

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.
rh_cli-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hitaishi V
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
rh_cli-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,217 @@
1
+ Metadata-Version: 2.4
2
+ Name: rh-cli
3
+ Version: 0.1.0
4
+ Summary: rh — orchestrate an AI research project end to end from the terminal
5
+ Author-email: Hitaishi V <hitaishi2222@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/hitaishi2222/research-helper
8
+ Project-URL: Repository, https://github.com/hitaishi2222/research-helper
9
+ Project-URL: Issues, https://github.com/hitaishi2222/research-helper/issues
10
+ Project-URL: Roadmap, https://github.com/hitaishi2222/research-helper/blob/main/ROADMAP.md
11
+ Keywords: research,cli,orchestration,agents,skill,literature
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Topic :: Scientific/Engineering
20
+ Classifier: Topic :: Utilities
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: rich>=13
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=8; extra == "dev"
27
+ Requires-Dist: build>=1; extra == "dev"
28
+ Dynamic: license-file
29
+
30
+ # research-helper
31
+
32
+ **`rh` — orchestrate an AI research project end to end from the terminal.**
33
+
34
+ [![CI](https://github.com/hitaishi2222/research-helper/actions/workflows/ci.yml/badge.svg)](https://github.com/hitaishi2222/research-helper/actions/workflows/ci.yml)
35
+ [![PyPI](https://img.shields.io/pypi/v/rh-cli.svg)](https://pypi.org/project/rh-cli/)
36
+ [![Python](https://img.shields.io/pypi/pyversions/rh-cli.svg)](https://pypi.org/project/rh-cli/)
37
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
38
+
39
+ `rh` turns a research idea into a gated pipeline — config → intake → environment →
40
+ literature → plan → state → implement → critique → manuscript → close — with every
41
+ artifact, task, and decision kept in files an agent can read.
42
+
43
+ The **CLI is the product**. The **skill is additive**: it teaches an AI agent (pi,
44
+ Claude, Codex, …) how to drive `rh`, ask the user the right questions, and respect the
45
+ gates. Install the CLI, then optionally install the skill globally.
46
+
47
+ ---
48
+
49
+ ## Install
50
+
51
+ ```bash
52
+ # once published to PyPI (distribution name: rh-cli, command: rh)
53
+ uv tool install rh-cli
54
+
55
+ # or straight from git
56
+ uv tool install git+https://github.com/hitaishi2222/research-helper
57
+
58
+ # or from a clone
59
+ git clone https://github.com/hitaishi2222/research-helper
60
+ cd research-helper
61
+ uv tool install .
62
+ ```
63
+
64
+ `pipx install rh-cli` and `pip install --user rh-cli` work too.
65
+ Verify with:
66
+
67
+ ```bash
68
+ rh --version
69
+ rh describe
70
+ ```
71
+
72
+ ### Install the skill (optional)
73
+
74
+ ```bash
75
+ rh skill install # ~/.agents/skills/research-helper/
76
+ rh skill install --dest ~/.pi/agent/skills/research-helper # pi-specific location
77
+ ```
78
+
79
+ Pi and other [Agent Skills](https://agentskills.io/specification) clients discover
80
+ `~/.agents/skills/` automatically. The skill is bundled in the wheel, so there is
81
+ nothing else to download.
82
+
83
+ ---
84
+
85
+ ## Quickstart
86
+
87
+ ```bash
88
+ rh init --slug my-project
89
+ rh env set agents.count=2 agents.backend=tmux \
90
+ literature.search=crw project.git=true
91
+ rh env show # config as a table, validated
92
+ rh phase 4 # gated: refuses to skip unmet exits
93
+ rh describe # the map an agent reads
94
+ ```
95
+
96
+ The Orchestrator (your agent) interviews you for the environment and writes the
97
+ `## Environment` section of `ENV.md`; `rh` never probes or auto-fills binaries.
98
+ A tool on `PATH` does not mean this project should use it.
99
+
100
+ ---
101
+
102
+ ## Commands
103
+
104
+ | Command | What it does |
105
+ |---|---|
106
+ | `rh init [--slug NAME] [--clean]` | create the `.rh/` workspace |
107
+ | `rh env show` | print config as a table + environment notes, validate |
108
+ | `rh env set KEY=VALUE ...` | set any key from the §2 schema (`rh env list`) |
109
+ | `rh env list` | every settable key, type, choices, help |
110
+ | `rh add note <heading> [-m BODY] [--file NAME]` | create/append a note file |
111
+ | `rh add literature <DOI-or-heading> [-m BODY]` | append under that DOI/heading in `LITERATURE.md` |
112
+ | `rh add layout <heading> [-m BODY]` | append to `OUTPUT_LAYOUT.md` (patterns + our layout) |
113
+ | `rh add gaps\|problem\|plan\|status\|manuscript <heading> [-m BODY]` | same for the other artifacts |
114
+ | `rh add log --role R --title T [-m BODY]` | §7 log file |
115
+ | `rh add task "title" [--id S01] [--phase N] [--owner ROLE] [--state idle\|working\|complete] [--verify CMD] [--deliverable FILE] [--depends-on S01,S02] [--kind build\|spike]` | add a board task |
116
+ | `rh search <query> [--max N]` | rg-first local search over `.rh/` + artifacts |
117
+ | `rh task set <id> <idle\|working\|complete>` | change a task state |
118
+ | `rh task list [--phase N] [--state S]` | filter the board |
119
+ | `rh tasks [--phase N]` | lanes + progress bars + table |
120
+ | `rh status` | header, phase rail, per-phase progress |
121
+ | `rh workflow` | display the agent-authored `.rh/workflow.mmd` as ASCII (`--tools`, `--example`, `--png`, `--svg`) |
122
+ | `rh phase <0-9>` | set the current phase — **gated**; `--force` records a waiver |
123
+ | `rh plan import [--dry-run]` | mirror `PLAN.md` steps into `tasks.json` |
124
+ | `rh resume` / `rh -r` | open the agent harness with a go-forward prompt |
125
+ | `rh skill install [--dest DIR] [--force]` | install the bundled skill globally |
126
+ | `rh describe [--json]` | the AI map: layout, phases, env keys, budget |
127
+
128
+ Global flags (before the subcommand): `--root DIR`, `--json`, `--version`.
129
+ Every command supports `--json` for agent reads — never parse the pretty UI.
130
+
131
+ ---
132
+
133
+ ## How it works
134
+
135
+ ```
136
+ 0 CONFIG → 1 INTAKE → 2 ENVIRONMENT → 3 LITERATURE → 4 PLAN → 5 STATE
137
+ → 6 IMPLEMENT → 7 CRITIQUE → 8 MANUSCRIPT → 9 CLOSE
138
+ ↑ │
139
+ └── replan ──┘
140
+ ```
141
+
142
+ Each phase has an **exit gate**; `rh phase` refuses to advance past an unmet one.
143
+ State lives in plain files, not a database:
144
+
145
+ ```
146
+ <project>/
147
+ .rh/ machine mirror + logs, notes, managed PDFs, tasks
148
+ src/ implementation
149
+ results/ every number + the script that produced it
150
+ papers/ unmanaged PDFs
151
+ ENV.md config block + Orchestrator-written environment notes
152
+ PROBLEM.md goal, scope, success criteria, falsifier
153
+ OUTPUT_LAYOUT.md output skeleton + patterns from comparable papers
154
+ PLAN.md approved steps
155
+ STATUS.md truth
156
+ LITERATURE.md paper takes with DOI
157
+ GAPS.md implementation sourcing + upstream gaps
158
+ MANUSCRIPT.md write-up
159
+ ```
160
+
161
+ `ENV.md` is the single config source; `.rh/env.json` mirrors it. `rh env set`
162
+ rewrites the JSON block and preserves whatever the Orchestrator wrote below it.
163
+
164
+ ---
165
+
166
+ ## The skill (additive)
167
+
168
+ `src/rh/skills/research-helper/SKILL.md` is the agent-facing half of the project.
169
+ It defines the phases, roles, gates, templates, and the ask-before list. The CLI
170
+ does not need it; the skill does not need to reimplement the CLI.
171
+
172
+ ```bash
173
+ rh skill install
174
+ ```
175
+
176
+ What the skill adds:
177
+
178
+ - **Roles** — Orchestrator, Literature, Researcher, Reviewer, Critique, Writer,
179
+ with a budget mapping for 1–4 agents.
180
+ - **Gates** — user approves the plan, critique veto, "no result without a file".
181
+ - **Templates** — `ENV.md`, `STATUS.md`, `OUTPUT_LAYOUT.md`, `PLAN.md` steps, logs.
182
+ - **Reading discipline** — one layout, a pattern tally, DOI anchors, no paraphrasing
183
+ unread papers.
184
+
185
+ ---
186
+
187
+ ## Development
188
+
189
+ ```bash
190
+ uv venv
191
+ uv pip install -e ".[dev]"
192
+ uv run pytest -q
193
+ uv build # sdist + wheel in dist/
194
+ uv tool install dist/*.whl # smoke-test the installed command
195
+ ```
196
+
197
+ Layout:
198
+
199
+ ```
200
+ pyproject.toml
201
+ src/rh/ the CLI package
202
+ src/rh/skills/ the bundled skill (package data)
203
+ tests/ pytest smoke tests
204
+ docs/IDEA.md original design notes
205
+ ROADMAP.md where this is going
206
+ ```
207
+
208
+ ---
209
+
210
+ ## Roadmap
211
+
212
+ See [ROADMAP.md](ROADMAP.md). Short version: publish to PyPI, harden the CLI,
213
+ then add real agent orchestration.
214
+
215
+ ## License
216
+
217
+ [MIT](LICENSE) © 2026 Hitaishi V
rh_cli-0.1.0/README.md ADDED
@@ -0,0 +1,188 @@
1
+ # research-helper
2
+
3
+ **`rh` — orchestrate an AI research project end to end from the terminal.**
4
+
5
+ [![CI](https://github.com/hitaishi2222/research-helper/actions/workflows/ci.yml/badge.svg)](https://github.com/hitaishi2222/research-helper/actions/workflows/ci.yml)
6
+ [![PyPI](https://img.shields.io/pypi/v/rh-cli.svg)](https://pypi.org/project/rh-cli/)
7
+ [![Python](https://img.shields.io/pypi/pyversions/rh-cli.svg)](https://pypi.org/project/rh-cli/)
8
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
9
+
10
+ `rh` turns a research idea into a gated pipeline — config → intake → environment →
11
+ literature → plan → state → implement → critique → manuscript → close — with every
12
+ artifact, task, and decision kept in files an agent can read.
13
+
14
+ The **CLI is the product**. The **skill is additive**: it teaches an AI agent (pi,
15
+ Claude, Codex, …) how to drive `rh`, ask the user the right questions, and respect the
16
+ gates. Install the CLI, then optionally install the skill globally.
17
+
18
+ ---
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ # once published to PyPI (distribution name: rh-cli, command: rh)
24
+ uv tool install rh-cli
25
+
26
+ # or straight from git
27
+ uv tool install git+https://github.com/hitaishi2222/research-helper
28
+
29
+ # or from a clone
30
+ git clone https://github.com/hitaishi2222/research-helper
31
+ cd research-helper
32
+ uv tool install .
33
+ ```
34
+
35
+ `pipx install rh-cli` and `pip install --user rh-cli` work too.
36
+ Verify with:
37
+
38
+ ```bash
39
+ rh --version
40
+ rh describe
41
+ ```
42
+
43
+ ### Install the skill (optional)
44
+
45
+ ```bash
46
+ rh skill install # ~/.agents/skills/research-helper/
47
+ rh skill install --dest ~/.pi/agent/skills/research-helper # pi-specific location
48
+ ```
49
+
50
+ Pi and other [Agent Skills](https://agentskills.io/specification) clients discover
51
+ `~/.agents/skills/` automatically. The skill is bundled in the wheel, so there is
52
+ nothing else to download.
53
+
54
+ ---
55
+
56
+ ## Quickstart
57
+
58
+ ```bash
59
+ rh init --slug my-project
60
+ rh env set agents.count=2 agents.backend=tmux \
61
+ literature.search=crw project.git=true
62
+ rh env show # config as a table, validated
63
+ rh phase 4 # gated: refuses to skip unmet exits
64
+ rh describe # the map an agent reads
65
+ ```
66
+
67
+ The Orchestrator (your agent) interviews you for the environment and writes the
68
+ `## Environment` section of `ENV.md`; `rh` never probes or auto-fills binaries.
69
+ A tool on `PATH` does not mean this project should use it.
70
+
71
+ ---
72
+
73
+ ## Commands
74
+
75
+ | Command | What it does |
76
+ |---|---|
77
+ | `rh init [--slug NAME] [--clean]` | create the `.rh/` workspace |
78
+ | `rh env show` | print config as a table + environment notes, validate |
79
+ | `rh env set KEY=VALUE ...` | set any key from the §2 schema (`rh env list`) |
80
+ | `rh env list` | every settable key, type, choices, help |
81
+ | `rh add note <heading> [-m BODY] [--file NAME]` | create/append a note file |
82
+ | `rh add literature <DOI-or-heading> [-m BODY]` | append under that DOI/heading in `LITERATURE.md` |
83
+ | `rh add layout <heading> [-m BODY]` | append to `OUTPUT_LAYOUT.md` (patterns + our layout) |
84
+ | `rh add gaps\|problem\|plan\|status\|manuscript <heading> [-m BODY]` | same for the other artifacts |
85
+ | `rh add log --role R --title T [-m BODY]` | §7 log file |
86
+ | `rh add task "title" [--id S01] [--phase N] [--owner ROLE] [--state idle\|working\|complete] [--verify CMD] [--deliverable FILE] [--depends-on S01,S02] [--kind build\|spike]` | add a board task |
87
+ | `rh search <query> [--max N]` | rg-first local search over `.rh/` + artifacts |
88
+ | `rh task set <id> <idle\|working\|complete>` | change a task state |
89
+ | `rh task list [--phase N] [--state S]` | filter the board |
90
+ | `rh tasks [--phase N]` | lanes + progress bars + table |
91
+ | `rh status` | header, phase rail, per-phase progress |
92
+ | `rh workflow` | display the agent-authored `.rh/workflow.mmd` as ASCII (`--tools`, `--example`, `--png`, `--svg`) |
93
+ | `rh phase <0-9>` | set the current phase — **gated**; `--force` records a waiver |
94
+ | `rh plan import [--dry-run]` | mirror `PLAN.md` steps into `tasks.json` |
95
+ | `rh resume` / `rh -r` | open the agent harness with a go-forward prompt |
96
+ | `rh skill install [--dest DIR] [--force]` | install the bundled skill globally |
97
+ | `rh describe [--json]` | the AI map: layout, phases, env keys, budget |
98
+
99
+ Global flags (before the subcommand): `--root DIR`, `--json`, `--version`.
100
+ Every command supports `--json` for agent reads — never parse the pretty UI.
101
+
102
+ ---
103
+
104
+ ## How it works
105
+
106
+ ```
107
+ 0 CONFIG → 1 INTAKE → 2 ENVIRONMENT → 3 LITERATURE → 4 PLAN → 5 STATE
108
+ → 6 IMPLEMENT → 7 CRITIQUE → 8 MANUSCRIPT → 9 CLOSE
109
+ ↑ │
110
+ └── replan ──┘
111
+ ```
112
+
113
+ Each phase has an **exit gate**; `rh phase` refuses to advance past an unmet one.
114
+ State lives in plain files, not a database:
115
+
116
+ ```
117
+ <project>/
118
+ .rh/ machine mirror + logs, notes, managed PDFs, tasks
119
+ src/ implementation
120
+ results/ every number + the script that produced it
121
+ papers/ unmanaged PDFs
122
+ ENV.md config block + Orchestrator-written environment notes
123
+ PROBLEM.md goal, scope, success criteria, falsifier
124
+ OUTPUT_LAYOUT.md output skeleton + patterns from comparable papers
125
+ PLAN.md approved steps
126
+ STATUS.md truth
127
+ LITERATURE.md paper takes with DOI
128
+ GAPS.md implementation sourcing + upstream gaps
129
+ MANUSCRIPT.md write-up
130
+ ```
131
+
132
+ `ENV.md` is the single config source; `.rh/env.json` mirrors it. `rh env set`
133
+ rewrites the JSON block and preserves whatever the Orchestrator wrote below it.
134
+
135
+ ---
136
+
137
+ ## The skill (additive)
138
+
139
+ `src/rh/skills/research-helper/SKILL.md` is the agent-facing half of the project.
140
+ It defines the phases, roles, gates, templates, and the ask-before list. The CLI
141
+ does not need it; the skill does not need to reimplement the CLI.
142
+
143
+ ```bash
144
+ rh skill install
145
+ ```
146
+
147
+ What the skill adds:
148
+
149
+ - **Roles** — Orchestrator, Literature, Researcher, Reviewer, Critique, Writer,
150
+ with a budget mapping for 1–4 agents.
151
+ - **Gates** — user approves the plan, critique veto, "no result without a file".
152
+ - **Templates** — `ENV.md`, `STATUS.md`, `OUTPUT_LAYOUT.md`, `PLAN.md` steps, logs.
153
+ - **Reading discipline** — one layout, a pattern tally, DOI anchors, no paraphrasing
154
+ unread papers.
155
+
156
+ ---
157
+
158
+ ## Development
159
+
160
+ ```bash
161
+ uv venv
162
+ uv pip install -e ".[dev]"
163
+ uv run pytest -q
164
+ uv build # sdist + wheel in dist/
165
+ uv tool install dist/*.whl # smoke-test the installed command
166
+ ```
167
+
168
+ Layout:
169
+
170
+ ```
171
+ pyproject.toml
172
+ src/rh/ the CLI package
173
+ src/rh/skills/ the bundled skill (package data)
174
+ tests/ pytest smoke tests
175
+ docs/IDEA.md original design notes
176
+ ROADMAP.md where this is going
177
+ ```
178
+
179
+ ---
180
+
181
+ ## Roadmap
182
+
183
+ See [ROADMAP.md](ROADMAP.md). Short version: publish to PyPI, harden the CLI,
184
+ then add real agent orchestration.
185
+
186
+ ## License
187
+
188
+ [MIT](LICENSE) © 2026 Hitaishi V
@@ -0,0 +1,52 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "rh-cli"
7
+ version = "0.1.0"
8
+ description = "rh — orchestrate an AI research project end to end from the terminal"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Hitaishi V", email = "hitaishi2222@gmail.com" }]
13
+ keywords = ["research", "cli", "orchestration", "agents", "skill", "literature"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Environment :: Console",
17
+ "Intended Audience :: Science/Research",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Topic :: Scientific/Engineering",
23
+ "Topic :: Utilities",
24
+ ]
25
+ dependencies = ["rich>=13"]
26
+
27
+ [project.optional-dependencies]
28
+ dev = ["pytest>=8", "build>=1"]
29
+
30
+ [project.scripts]
31
+ rh = "rh.cli:main"
32
+
33
+ [project.urls]
34
+ Homepage = "https://github.com/hitaishi2222/research-helper"
35
+ Repository = "https://github.com/hitaishi2222/research-helper"
36
+ Issues = "https://github.com/hitaishi2222/research-helper/issues"
37
+ Roadmap = "https://github.com/hitaishi2222/research-helper/blob/main/ROADMAP.md"
38
+
39
+ [tool.setuptools]
40
+ include-package-data = true
41
+
42
+ [tool.setuptools.packages.find]
43
+ where = ["src"]
44
+
45
+ [tool.setuptools.package-dir]
46
+ "" = "src"
47
+
48
+ [tool.setuptools.package-data]
49
+ rh = ["skills/research-helper/SKILL.md"]
50
+
51
+ [tool.pytest.ini_options]
52
+ testpaths = ["tests"]
rh_cli-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,12 @@
1
+ """research-helper CLI — makes SKILL.md easy for AI agents to adopt.
2
+
3
+ Storage: everything lives under `.rh/` in a project root (or $RH_HOME /
4
+ $XDG_CONFIG_HOME/rh as a global default). ENV.md remains the single config
5
+ source; .rh/env.json is the machine-readable mirror of the SKILL.md config
6
+ block, .rh/tasks.json is the machine-readable task board, and the SKILL.md
7
+ artifacts (PROBLEM.md, PLAN.md, ...) are kept at the root or inside .rh/ when
8
+ the user asked for a clean workspace.
9
+ """
10
+
11
+ __version__ = "0.1.0"
12
+ __all__ = ["__version__"]
@@ -0,0 +1,105 @@
1
+ """`rh add` — append under a heading/DOI, creating it if missing.
2
+
3
+ Targets:
4
+ note -> .rh/notes/<slug>.md (heading-created files)
5
+ literature -> LITERATURE.md (SKILL.md §3: citation + DOI + take/reject)
6
+ layout -> OUTPUT_LAYOUT.md (SKILL.md §3: output skeleton + paper patterns)
7
+ gaps -> GAPS.md
8
+ problem -> PROBLEM.md
9
+ plan -> PLAN.md
10
+ status -> STATUS.md
11
+ manuscript -> MANUSCRIPT.md
12
+ log -> .rh/logs/YYYY-MM-DD-HHMM-<role>-<slug>.md
13
+ task -> .rh/tasks.json via TaskStore
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ import unicodedata
19
+ from datetime import datetime
20
+ from pathlib import Path
21
+
22
+ from . import paths
23
+
24
+ ADD_TARGETS = {
25
+ "note": "notes",
26
+ "literature": "LITERATURE.md",
27
+ "layout": "OUTPUT_LAYOUT.md",
28
+ "gaps": "GAPS.md",
29
+ "problem": "PROBLEM.md",
30
+ "plan": "PLAN.md",
31
+ "status": "STATUS.md",
32
+ "manuscript": "MANUSCRIPT.md",
33
+ "log": "log",
34
+ "task": "task",
35
+ }
36
+
37
+
38
+ def slugify(text: str) -> str:
39
+ text = unicodedata.normalize("NFKD", text).lower().strip()
40
+ text = re.sub(r"[^a-z0-9]+", "-", text).strip("-")
41
+ return text or "untitled"
42
+
43
+
44
+ def _heading_re(heading: str) -> re.Pattern:
45
+ # match `## <heading>` exactly (case-insensitive)
46
+ return re.compile(rf"^##\s+{re.escape(heading)}\s*$", re.MULTILINE | re.IGNORECASE)
47
+
48
+
49
+ def _doi_re(doi: str) -> re.Pattern:
50
+ clean = doi.strip().removeprefix("https://doi.org/")
51
+ return re.compile(rf"doi[:\s]*{re.escape(clean)}", re.IGNORECASE)
52
+
53
+
54
+ def append_under(artifact: Path, heading: str, body: str, *, use_doi: bool = False) -> str:
55
+ """Append `body` under `heading` (or create it). Returns 'created'|'appended'."""
56
+ artifact.parent.mkdir(parents=True, exist_ok=True)
57
+ text = artifact.read_text(encoding="utf-8") if artifact.exists() else ""
58
+ pattern = _doi_re(heading) if use_doi else _heading_re(heading)
59
+ m = pattern.search(text)
60
+ block = body.strip("\n") + "\n"
61
+ if m:
62
+ # append at end of that section: before next ## heading or EOF
63
+ nxt = re.search(r"\n## ", text[m.end():])
64
+ if nxt:
65
+ insert_at = m.end() + nxt.start()
66
+ text = text[:insert_at].rstrip() + "\n\n" + block + text[insert_at:].lstrip("\n")
67
+ else:
68
+ text = text.rstrip() + "\n\n" + block
69
+ result = "appended"
70
+ else:
71
+ title = heading if use_doi else f"## {heading}"
72
+ if use_doi:
73
+ title = f"## {heading}\n\nDOI: {heading}"
74
+ text = (text.rstrip() + "\n\n" if text.strip() else "") + title + "\n\n" + block
75
+ result = "created"
76
+ artifact.write_text(text, encoding="utf-8")
77
+ return result
78
+
79
+
80
+ def add_note(root: Path, heading_or_file: str, body: str, *, file: str | None = None) -> tuple[Path, str]:
81
+ """Note: file defaults to kebab of heading; heading is the ## section."""
82
+ name = file or f"{slugify(heading_or_file)}.md"
83
+ target = paths.notes_dir(root) / name
84
+ result = append_under(target, heading_or_file, body)
85
+ return target, result
86
+
87
+
88
+ def add_log(root: Path, role: str, title: str, body: str) -> Path:
89
+ ts = datetime.now().strftime("%Y-%m-%d-%H%M")
90
+ target = paths.logs_dir(root) / f"{ts}-{slugify(role)}-{slugify(title)}.md"
91
+ target.parent.mkdir(parents=True, exist_ok=True)
92
+ text = f"# {title}\n- phase / step: \n- what was tried: \n- outcome: \n- evidence: \n- decision taken + why: \n- what a future agent must not redo: \n\n{body.strip()}\n"
93
+ target.write_text(text, encoding="utf-8")
94
+ return target
95
+
96
+
97
+ def add_text(root: Path, target_kind: str, heading_or_doi: str, body: str) -> tuple[Path, str]:
98
+ if target_kind not in ADD_TARGETS or target_kind in ("note", "log", "task"):
99
+ raise ValueError(f"unknown add target {target_kind!r}; choices: {sorted(ADD_TARGETS)}")
100
+ artifact = paths.artifact_path(root, ADD_TARGETS[target_kind])
101
+ use_doi = target_kind == "literature" and re.search(
102
+ r"\b10\.\d{4,9}/", heading_or_doi, re.IGNORECASE
103
+ ) is not None
104
+ result = append_under(artifact, heading_or_doi, body, use_doi=use_doi)
105
+ return artifact, result