alkonost 0.1.0__py3-none-any.whl

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.
alkonost/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
alkonost/__main__.py ADDED
@@ -0,0 +1,36 @@
1
+ """alkonost CLI entry point — mirrors vyrii's own __main__.py pattern:
2
+ argparse -> flask_api.create_app() -> waitress.serve() (never app.run())."""
3
+ import argparse
4
+ import os
5
+
6
+ from .flask_api import create_app
7
+ from . import discovery
8
+
9
+
10
+ def main() -> None:
11
+ parser = argparse.ArgumentParser(prog="alkonost", description=__doc__)
12
+ parser.add_argument("-p", "--port", type=int, default=8090)
13
+ parser.add_argument("--bind", default="0.0.0.0")
14
+ parser.add_argument("--root", default=os.getcwd(),
15
+ help="directory to scan for .1bcoder/ projects (default: cwd)")
16
+ parser.add_argument("--max-depth", type=int, default=6,
17
+ help="max recursion depth when scanning for .1bcoder/ (default: 6)")
18
+ args = parser.parse_args()
19
+
20
+ root = os.path.abspath(args.root)
21
+ projects = discovery.discover_projects(root, args.max_depth)
22
+
23
+ app = create_app(root=root, max_depth=args.max_depth)
24
+ print(f"alkonost -> http://localhost:{args.port} (UI: /ui/)")
25
+ print(f" root : {root}")
26
+ print(f" max-depth : {args.max_depth}")
27
+ print(f" projects : {len(projects)} found")
28
+ for info in sorted(projects.values(), key=lambda i: i['name']):
29
+ print(f" - {info['name']} ({info['plan_count']} plan(s)) — {info['root']}")
30
+
31
+ from waitress import serve
32
+ serve(app, host=args.bind, port=args.port, threads=8)
33
+
34
+
35
+ if __name__ == "__main__":
36
+ main()
alkonost/colors.py ADDED
@@ -0,0 +1,32 @@
1
+ """colors.py — read/write .1bcoder/tasks/colors.md.
2
+
3
+ One shared file per project (not per-plan) — "@module=color" lines,
4
+ one @module -> hex-color legend used across every plan's board.
5
+ deepagent_task creates this file with generic starter defaults the first
6
+ time it's missing and never touches it again; alkonost is the file's
7
+ actual owner (add/edit/remove entries through its own UI).
8
+ """
9
+ import os
10
+ import re
11
+
12
+ _LINE_RE = re.compile(r'^@(\S+)=(\S+)$')
13
+
14
+
15
+ def parse_colors(path: str) -> dict:
16
+ """{"backend": "#4A90D9", ...} — module name without the leading '@'."""
17
+ colors = {}
18
+ if not os.path.isfile(path):
19
+ return colors
20
+ with open(path, encoding="utf-8") as f:
21
+ for line in f:
22
+ m = _LINE_RE.match(line.strip())
23
+ if m:
24
+ colors[m.group(1)] = m.group(2)
25
+ return colors
26
+
27
+
28
+ def write_colors(path: str, colors: dict) -> None:
29
+ """One "@module=color" line per entry, insertion order preserved."""
30
+ lines = [f"@{name}={color}" for name, color in colors.items()]
31
+ with open(path, "w", encoding="utf-8") as f:
32
+ f.write("\n".join(lines) + ("\n" if lines else ""))
alkonost/config.py ADDED
@@ -0,0 +1,43 @@
1
+ """config.py — read/write ~/.alkonost/config.json.
2
+
3
+ Unlike everything else in alkonost (which reads/writes files inside a
4
+ scanned project's own .1bcoder/), this is the one piece of state that
5
+ belongs to the alkonost installation itself, not to any project: which
6
+ project/plan were last selected, so the next launch can restore them
7
+ instead of starting back at "Select project…" every time. Same
8
+ ~/.<tool>/config.json convention vyrii already uses.
9
+
10
+ A flat, merge-updatable JSON blob — POST /api/config merges into whatever
11
+ is already there rather than replacing it wholesale, so unrelated keys
12
+ added later don't require touching this module.
13
+ """
14
+ import json
15
+ import os
16
+
17
+ _FILENAME = "config.json"
18
+
19
+
20
+ def _config_dir() -> str:
21
+ return os.path.join(os.path.expanduser("~"), ".alkonost")
22
+
23
+
24
+ def _config_path() -> str:
25
+ return os.path.join(_config_dir(), _FILENAME)
26
+
27
+
28
+ def read_config() -> dict:
29
+ path = _config_path()
30
+ if not os.path.isfile(path):
31
+ return {}
32
+ try:
33
+ with open(path, encoding="utf-8") as f:
34
+ data = json.load(f)
35
+ return data if isinstance(data, dict) else {}
36
+ except (OSError, json.JSONDecodeError):
37
+ return {}
38
+
39
+
40
+ def write_config(data: dict) -> None:
41
+ os.makedirs(_config_dir(), exist_ok=True)
42
+ with open(_config_path(), "w", encoding="utf-8") as f:
43
+ json.dump(data, f, indent=2)
alkonost/dashboard.py ADDED
@@ -0,0 +1,35 @@
1
+ """dashboard.py — read/write .1bcoder/tasks/dashboard_flow.md.
2
+
3
+ One shared file per project (not per-plan), same convention as colors.md —
4
+ a single ordered, comma-separated list of "+flag" lane names to show on
5
+ the board, e.g.:
6
+
7
+ +selected, +active, +paused, +testing, +done, +releasing
8
+
9
+ This is the mechanism for hiding lanes like +backlog/+complete/+canceled/
10
+ +closed from the dashboard board without hiding their rows from the
11
+ Backlog table (which always shows every row regardless of this filter).
12
+ Missing/empty file -> empty list, meaning "no filter configured" — the
13
+ board falls back to showing every distinct lane found in the data (the
14
+ original, pre-filter behavior), not an empty board.
15
+ """
16
+ import os
17
+
18
+ _FILENAME = "dashboard_flow.md"
19
+
20
+
21
+ def parse_dashboard_flow(path: str) -> list:
22
+ """Ordered list of bare lane names (no leading '+')."""
23
+ if not os.path.isfile(path):
24
+ return []
25
+ with open(path, encoding="utf-8") as f:
26
+ line = f.readline().strip()
27
+ if not line:
28
+ return []
29
+ return [tok.strip().lstrip("+") for tok in line.split(",") if tok.strip()]
30
+
31
+
32
+ def write_dashboard_flow(path: str, flow: list) -> None:
33
+ line = ", ".join(f"+{name}" for name in flow if name)
34
+ with open(path, "w", encoding="utf-8") as f:
35
+ f.write(line + "\n" if line else "")
alkonost/discovery.py ADDED
@@ -0,0 +1,130 @@
1
+ """discovery.py — bounded recursive search for .1bcoder project roots.
2
+
3
+ Alkonost is started from a common ancestor directory that may contain
4
+ several independent projects (each with its own project-local .1bcoder/).
5
+ This module walks that ancestor directory looking for every .1bcoder/ it
6
+ can find, treating the directory that directly contains it as a "project
7
+ root". Recursion is bounded (max_depth) and prunes a fixed ignore-list of
8
+ directory names, since walking an entire home directory or drive root
9
+ would otherwise be slow or simply wrong (see concepts/ALKONOST.md open
10
+ question 5).
11
+
12
+ Once a .1bcoder/ is found, its own contents are read directly via
13
+ os.listdir (see list_plans) — never walked further by this module; only
14
+ sibling/cousin directories elsewhere in the tree keep being searched for
15
+ other projects.
16
+ """
17
+ import hashlib
18
+ import os
19
+
20
+ IGNORE_DIRS = {
21
+ ".git", "node_modules", "venv", ".venv", "__pycache__",
22
+ "dist", "build", ".idea", ".vscode",
23
+ }
24
+
25
+ _DOT1BCODER = ".1bcoder"
26
+
27
+
28
+ def project_id(root_path: str) -> str:
29
+ """Deterministic id for a project root — same path always yields the
30
+ same id, so re-scanning never needs cache-invalidation logic."""
31
+ return hashlib.sha1(os.path.abspath(root_path).encode("utf-8")).hexdigest()[:12]
32
+
33
+
34
+ def _should_descend(name: str) -> bool:
35
+ if name in IGNORE_DIRS:
36
+ return False
37
+ if name.startswith(".") and name != _DOT1BCODER:
38
+ return False
39
+ return True
40
+
41
+
42
+ def _walk(dir_path: str, depth: int, max_depth: int, found: list) -> None:
43
+ try:
44
+ entries = list(os.scandir(dir_path))
45
+ except OSError:
46
+ return
47
+
48
+ for entry in entries:
49
+ if not entry.is_dir(follow_symlinks=False):
50
+ continue
51
+ if entry.name == _DOT1BCODER:
52
+ found.append(dir_path)
53
+ continue
54
+ if depth >= max_depth:
55
+ continue
56
+ if not _should_descend(entry.name):
57
+ continue
58
+ _walk(entry.path, depth + 1, max_depth, found)
59
+
60
+
61
+ def _count_plans(project_root: str) -> int:
62
+ planmd_dir = os.path.join(project_root, _DOT1BCODER, "planMD")
63
+ if not os.path.isdir(planmd_dir):
64
+ return 0
65
+ return sum(1 for e in os.scandir(planmd_dir) if e.is_dir())
66
+
67
+
68
+ def discover_projects(root: str, max_depth: int = 6) -> dict:
69
+ """{id: {"root": abs_path, "name": basename, "plan_count": n}}."""
70
+ root = os.path.abspath(root)
71
+ found = []
72
+ _walk(root, 0, max_depth, found)
73
+
74
+ result = {}
75
+ for proj_root in found:
76
+ pid = project_id(proj_root)
77
+ result[pid] = {
78
+ "root": proj_root,
79
+ "name": os.path.basename(proj_root),
80
+ "plan_count": _count_plans(proj_root),
81
+ }
82
+ return result
83
+
84
+
85
+ def list_plans(project_root: str) -> list:
86
+ """[{"name","item_count","has_spec","spec_count","has_tasks","task_count"}, ...]
87
+ Reads .1bcoder/planMD/<name>/ directly; spec/tasks are optional/sparse
88
+ relative to planMD (not every plan has a spec/ or tasks/ counterpart —
89
+ confirmed against a real project's .1bcoder/ layout)."""
90
+ dot1bcoder = os.path.join(project_root, _DOT1BCODER)
91
+ planmd_root = os.path.join(dot1bcoder, "planMD")
92
+ spec_root = os.path.join(dot1bcoder, "spec")
93
+ tasks_root = os.path.join(dot1bcoder, "tasks")
94
+
95
+ if not os.path.isdir(planmd_root):
96
+ return []
97
+
98
+ plans = []
99
+ for entry in sorted(os.scandir(planmd_root), key=lambda e: e.name):
100
+ if not entry.is_dir():
101
+ continue
102
+ name = entry.name
103
+ item_count = sum(
104
+ 1 for f in os.listdir(entry.path)
105
+ if f.startswith("item_") and f.endswith(".md")
106
+ )
107
+
108
+ spec_dir = os.path.join(spec_root, name)
109
+ has_spec = os.path.isdir(spec_dir)
110
+ spec_count = (
111
+ sum(1 for f in os.listdir(spec_dir) if f.startswith("spec_") and f.endswith(".md"))
112
+ if has_spec else 0
113
+ )
114
+
115
+ tasks_path = os.path.join(tasks_root, name, "tasks.md")
116
+ has_tasks = os.path.isfile(tasks_path)
117
+ task_count = 0
118
+ if has_tasks:
119
+ with open(tasks_path, encoding="utf-8") as f:
120
+ task_count = sum(1 for line in f if line.strip().startswith("["))
121
+
122
+ plans.append({
123
+ "name": name,
124
+ "item_count": item_count,
125
+ "has_spec": has_spec,
126
+ "spec_count": spec_count,
127
+ "has_tasks": has_tasks,
128
+ "task_count": task_count,
129
+ })
130
+ return plans
alkonost/flask_api.py ADDED
@@ -0,0 +1,276 @@
1
+ """flask_api.py — Alkonost's Flask app: static UI + JSON API.
2
+
3
+ No LLM calls anywhere — pure read/render/edit over already-generated
4
+ 1bcoder deepagent_md/deepagent_spec/deepagent_task artifacts (same
5
+ "deterministic compiler, not a generator" principle already established
6
+ for deepagent_task itself).
7
+
8
+ Project ids are opaque (sha1-derived, see discovery.project_id) rather
9
+ than raw filesystem paths in URLs, since project roots are absolute
10
+ Windows paths containing ':' and '\\'. Every route resolves `project=<id>`
11
+ by re-running discovery.discover_projects() fresh — cheap given the
12
+ depth cap + ignore-list, and sidesteps any stale-cache invalidation
13
+ question since ids are a pure function of path.
14
+ """
15
+ import os
16
+
17
+ from flask import Flask, jsonify, request, redirect, send_from_directory
18
+
19
+ from . import colors as colors_mod
20
+ from . import config as config_mod
21
+ from . import dashboard as dashboard_mod
22
+ from . import discovery
23
+ from . import planmd
24
+ from . import spec as spec_mod
25
+ from . import tasks as tasks_mod
26
+
27
+ _DOT1BCODER = ".1bcoder"
28
+
29
+
30
+ def _plan_dir(root: str, plan: str) -> str:
31
+ return os.path.join(root, _DOT1BCODER, "planMD", plan)
32
+
33
+
34
+ def _spec_dir(root: str, plan: str) -> str:
35
+ return os.path.join(root, _DOT1BCODER, "spec", plan)
36
+
37
+
38
+ def _tasks_dir(root: str, plan: str) -> str:
39
+ return os.path.join(root, _DOT1BCODER, "tasks", plan)
40
+
41
+
42
+ def _tasks_path(root: str, plan: str) -> str:
43
+ return os.path.join(_tasks_dir(root, plan), "tasks.md")
44
+
45
+
46
+ def _colors_path(root: str) -> str:
47
+ return os.path.join(root, _DOT1BCODER, "tasks", "colors.md")
48
+
49
+
50
+ def _dashboard_flow_path(root: str) -> str:
51
+ return os.path.join(root, _DOT1BCODER, "tasks", "dashboard_flow.md")
52
+
53
+
54
+ def create_app(root: str, max_depth: int = 6) -> Flask:
55
+ app = Flask(__name__, static_folder=None)
56
+ root = os.path.abspath(root)
57
+
58
+ def _resolve_project(project_id: str):
59
+ projects = discovery.discover_projects(root, max_depth)
60
+ entry = projects.get(project_id)
61
+ return entry["root"] if entry else None
62
+
63
+ def _unknown_project():
64
+ return jsonify({"error": "unknown project id — refresh /api/projects"}), 404
65
+
66
+ # ── API ──────────────────────────────────────────────────────────────
67
+
68
+ @app.route("/api/config", methods=["GET"])
69
+ def api_config_get():
70
+ return jsonify(config_mod.read_config())
71
+
72
+ @app.route("/api/config", methods=["POST"])
73
+ def api_config_post():
74
+ body = request.get_json(force=True, silent=True) or {}
75
+ cfg = config_mod.read_config()
76
+ cfg.update(body)
77
+ config_mod.write_config(cfg)
78
+ return jsonify({"ok": True})
79
+
80
+ @app.route("/api/themes")
81
+ def api_themes():
82
+ themes_dir = os.path.join(os.path.dirname(__file__), "ui", "themes")
83
+ if not os.path.isdir(themes_dir):
84
+ return jsonify({"themes": ["ocean"]})
85
+ themes = sorted(
86
+ os.path.splitext(f)[0] for f in os.listdir(themes_dir) if f.endswith(".css")
87
+ )
88
+ return jsonify({"themes": themes or ["ocean"]})
89
+
90
+ @app.route("/api/projects")
91
+ def api_projects():
92
+ projects = discovery.discover_projects(root, max_depth)
93
+ return jsonify([
94
+ {"id": pid, "root": info["root"], "name": info["name"], "plan_count": info["plan_count"]}
95
+ for pid, info in sorted(projects.items(), key=lambda kv: kv[1]["name"])
96
+ ])
97
+
98
+ @app.route("/api/plans")
99
+ def api_plans():
100
+ project_root = _resolve_project(request.args.get("project", ""))
101
+ if project_root is None:
102
+ return _unknown_project()
103
+ return jsonify(discovery.list_plans(project_root))
104
+
105
+ @app.route("/api/planmd/tree")
106
+ def api_planmd_tree():
107
+ project_root = _resolve_project(request.args.get("project", ""))
108
+ if project_root is None:
109
+ return _unknown_project()
110
+ plan = request.args.get("plan", "")
111
+ plan_dir = _plan_dir(project_root, plan)
112
+ return jsonify(planmd.build_tree(plan_dir))
113
+
114
+ @app.route("/api/item", methods=["GET", "POST"])
115
+ def api_item():
116
+ project_root = _resolve_project(request.args.get("project", ""))
117
+ if project_root is None:
118
+ return _unknown_project()
119
+ plan = request.args.get("plan", "")
120
+ item_id = request.args.get("item_id", "")
121
+ plan_dir = _plan_dir(project_root, plan)
122
+ all_ids = planmd.collect_node_ids(plan_dir)
123
+ if item_id not in all_ids:
124
+ return jsonify({"error": "item not found"}), 404
125
+
126
+ if request.method == "POST":
127
+ body = request.get_json(force=True, silent=True) or {}
128
+ planmd.write_item_raw(plan_dir, item_id, body.get("raw", ""))
129
+ return jsonify({"ok": True})
130
+
131
+ return jsonify({
132
+ "id": item_id,
133
+ "title": planmd.read_title(plan_dir, item_id),
134
+ "raw": planmd.read_item(plan_dir, item_id),
135
+ "children": planmd.child_ids(item_id, all_ids),
136
+ "is_leaf": planmd.is_leaf(item_id, all_ids),
137
+ })
138
+
139
+ @app.route("/api/spec", methods=["GET", "POST"])
140
+ def api_spec():
141
+ project_root = _resolve_project(request.args.get("project", ""))
142
+ if project_root is None:
143
+ return _unknown_project()
144
+ plan = request.args.get("plan", "")
145
+ spec_id = request.args.get("spec_id", "")
146
+ spec_dir = _spec_dir(project_root, plan)
147
+ path = spec_mod.find_spec_file(spec_dir, spec_id)
148
+ if not path:
149
+ return jsonify({"error": "spec not found"}), 404
150
+
151
+ if request.method == "POST":
152
+ body = request.get_json(force=True, silent=True) or {}
153
+ spec_mod.write_spec_raw(path, body.get("raw", ""))
154
+ return jsonify({"ok": True})
155
+
156
+ parsed = spec_mod.parse_spec(path)
157
+ if not parsed:
158
+ return jsonify({"error": "spec not found"}), 404
159
+ return jsonify(parsed)
160
+
161
+ @app.route("/api/spec_index")
162
+ def api_spec_index():
163
+ project_root = _resolve_project(request.args.get("project", ""))
164
+ if project_root is None:
165
+ return _unknown_project()
166
+ plan = request.args.get("plan", "")
167
+ spec_dir = _spec_dir(project_root, plan)
168
+ return jsonify({"spec_ids": spec_mod.list_spec_ids(spec_dir)})
169
+
170
+ @app.route("/api/spec/create", methods=["POST"])
171
+ def api_spec_create():
172
+ project_root = _resolve_project(request.args.get("project", ""))
173
+ if project_root is None:
174
+ return _unknown_project()
175
+ plan = request.args.get("plan", "")
176
+ body = request.get_json(force=True, silent=True) or {}
177
+ task_id = body.get("task_id", "")
178
+ title = body.get("title") or task_id
179
+ if not task_id:
180
+ return jsonify({"error": "task_id required"}), 400
181
+
182
+ spec_dir = _spec_dir(project_root, plan)
183
+ project_name = spec_mod.project_name(project_root)
184
+ path = spec_mod.create_spec_if_missing(spec_dir, task_id, title, project_name)
185
+ parsed = spec_mod.parse_spec(path)
186
+ if not parsed:
187
+ return jsonify({"error": "failed to create spec"}), 500
188
+ return jsonify(parsed)
189
+
190
+ @app.route("/api/tasks", methods=["GET"])
191
+ def api_tasks_get():
192
+ project_root = _resolve_project(request.args.get("project", ""))
193
+ if project_root is None:
194
+ return _unknown_project()
195
+ plan = request.args.get("plan", "")
196
+ path = _tasks_path(project_root, plan)
197
+ if not os.path.isfile(path):
198
+ return jsonify({"plan": plan, "exists": False, "rows": []})
199
+ return jsonify({"plan": plan, "exists": True, "rows": tasks_mod.parse_tasks_md(path)})
200
+
201
+ @app.route("/api/tasks", methods=["POST"])
202
+ def api_tasks_post():
203
+ project_root = _resolve_project(request.args.get("project", ""))
204
+ if project_root is None:
205
+ return _unknown_project()
206
+ plan = request.args.get("plan", "")
207
+ path = _tasks_path(project_root, plan)
208
+
209
+ body = request.get_json(force=True, silent=True) or {}
210
+ submitted_rows = body.get("rows", [])
211
+ for row in submitted_rows:
212
+ row.setdefault("depth", row["id"].count(".") + 1)
213
+ row.setdefault("tags", {})
214
+
215
+ existing_rows = tasks_mod.parse_tasks_md(path) if os.path.isfile(path) else []
216
+ if not tasks_mod.validate_row_ids(existing_rows, submitted_rows):
217
+ return jsonify({"error": "row id set does not match tasks.md on disk — reload and retry"}), 409
218
+
219
+ os.makedirs(_tasks_dir(project_root, plan), exist_ok=True)
220
+ tasks_mod.rewrite_tasks_md(path, plan, submitted_rows)
221
+ return jsonify({"ok": True, "row_count": len(submitted_rows)})
222
+
223
+ @app.route("/api/colors", methods=["GET"])
224
+ def api_colors_get():
225
+ project_root = _resolve_project(request.args.get("project", ""))
226
+ if project_root is None:
227
+ return _unknown_project()
228
+ return jsonify({"colors": colors_mod.parse_colors(_colors_path(project_root))})
229
+
230
+ @app.route("/api/colors", methods=["POST"])
231
+ def api_colors_post():
232
+ project_root = _resolve_project(request.args.get("project", ""))
233
+ if project_root is None:
234
+ return _unknown_project()
235
+ body = request.get_json(force=True, silent=True) or {}
236
+ colors = body.get("colors", {})
237
+ os.makedirs(os.path.join(project_root, _DOT1BCODER, "tasks"), exist_ok=True)
238
+ colors_mod.write_colors(_colors_path(project_root), colors)
239
+ return jsonify({"ok": True})
240
+
241
+ @app.route("/api/dashboard_flow", methods=["GET"])
242
+ def api_dashboard_flow_get():
243
+ project_root = _resolve_project(request.args.get("project", ""))
244
+ if project_root is None:
245
+ return _unknown_project()
246
+ return jsonify({"flow": dashboard_mod.parse_dashboard_flow(_dashboard_flow_path(project_root))})
247
+
248
+ @app.route("/api/dashboard_flow", methods=["POST"])
249
+ def api_dashboard_flow_post():
250
+ project_root = _resolve_project(request.args.get("project", ""))
251
+ if project_root is None:
252
+ return _unknown_project()
253
+ body = request.get_json(force=True, silent=True) or {}
254
+ flow = body.get("flow", [])
255
+ os.makedirs(os.path.join(project_root, _DOT1BCODER, "tasks"), exist_ok=True)
256
+ dashboard_mod.write_dashboard_flow(_dashboard_flow_path(project_root), flow)
257
+ return jsonify({"ok": True})
258
+
259
+ # ── static UI ────────────────────────────────────────────────────────
260
+
261
+ _ui_dir = os.path.join(os.path.dirname(__file__), "ui")
262
+
263
+ if os.path.isdir(_ui_dir):
264
+ @app.route("/")
265
+ def _ui_root():
266
+ return redirect("/ui/")
267
+
268
+ @app.route("/ui/")
269
+ def _ui_index():
270
+ return send_from_directory(_ui_dir, "index.html")
271
+
272
+ @app.route("/ui/<path:filename>")
273
+ def _ui_static(filename):
274
+ return send_from_directory(_ui_dir, filename)
275
+
276
+ return app
alkonost/planmd.py ADDED
@@ -0,0 +1,87 @@
1
+ """planmd.py — read-only parsing of deepagent_md's item_<id>.md tree.
2
+
3
+ Independent re-implementation (no import dependency on 1bcoder) against the
4
+ same on-disk convention: item_<id>.md files live directly in a plan
5
+ directory (.1bcoder/planMD/<plan_name>/), <id> is a dot-separated integer
6
+ path (e.g. item_1.2.3.md), first line is "# {title}", and a node's children
7
+ are ids one level deeper sharing its own id as a dotted prefix.
8
+ """
9
+ import os
10
+ import re
11
+
12
+ _ITEM_RE = re.compile(r'^item_([\d.]+)\.md$')
13
+
14
+
15
+ def _item_path(plan_dir: str, node_id: str) -> str:
16
+ return os.path.join(plan_dir, f"item_{node_id}.md")
17
+
18
+
19
+ def collect_node_ids(plan_dir: str) -> set:
20
+ ids = set()
21
+ if not os.path.isdir(plan_dir):
22
+ return ids
23
+ for fname in os.listdir(plan_dir):
24
+ m = _ITEM_RE.match(fname)
25
+ if m:
26
+ ids.add(m.group(1))
27
+ return ids
28
+
29
+
30
+ def read_title(plan_dir: str, node_id: str) -> str:
31
+ try:
32
+ with open(_item_path(plan_dir, node_id), encoding="utf-8") as f:
33
+ first_line = f.readline()
34
+ return first_line.lstrip("#").strip()
35
+ except OSError:
36
+ return node_id
37
+
38
+
39
+ def read_item(plan_dir: str, node_id: str) -> str:
40
+ """Raw file content, or "" if missing."""
41
+ try:
42
+ with open(_item_path(plan_dir, node_id), encoding="utf-8") as f:
43
+ return f.read()
44
+ except OSError:
45
+ return ""
46
+
47
+
48
+ def write_item_raw(plan_dir: str, node_id: str, raw: str) -> None:
49
+ """Writes user-edited raw text verbatim — same "trust the human editing
50
+ an already-generated file" convention as tasks.md/colors.md/spec files.
51
+ A malformed title line just means read_title()'s next call falls back
52
+ to the bare node_id, no different from any other missing/odd file."""
53
+ with open(_item_path(plan_dir, node_id), "w", encoding="utf-8") as f:
54
+ f.write(raw)
55
+
56
+
57
+ def child_ids(node_id: str, all_ids: set) -> list:
58
+ prefix = node_id + "."
59
+ depth = node_id.count(".") + 2
60
+ kids = [i for i in all_ids if i.startswith(prefix) and i.count(".") == depth - 1]
61
+ return sorted(kids, key=lambda x: tuple(int(p) for p in x.split(".")))
62
+
63
+
64
+ def is_leaf(node_id: str, all_ids: set) -> bool:
65
+ return not child_ids(node_id, all_ids)
66
+
67
+
68
+ def build_tree(plan_dir: str) -> list:
69
+ """[{"id","title","children":[...nested...]}, ...] — top-level nodes
70
+ (single-segment ids), each recursively populated with its children.
71
+ Powers the "direct planMD browsing" requirement (concepts/ALKONOST.md
72
+ §4) independent of any task row."""
73
+ all_ids = collect_node_ids(plan_dir)
74
+
75
+ def _node(node_id: str) -> dict:
76
+ return {
77
+ "id": node_id,
78
+ "title": read_title(plan_dir, node_id),
79
+ "is_leaf": is_leaf(node_id, all_ids),
80
+ "children": [_node(c) for c in child_ids(node_id, all_ids)],
81
+ }
82
+
83
+ roots = sorted(
84
+ (i for i in all_ids if "." not in i),
85
+ key=lambda x: int(x),
86
+ )
87
+ return [_node(r) for r in roots]