-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnexus_map_codebase.py
More file actions
12061 lines (10749 loc) · 480 KB
/
nexus_map_codebase.py
File metadata and controls
12061 lines (10749 loc) · 480 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ast
import json
import os
import sys
import argparse
import tempfile
import random
import string
from datetime import datetime
from typing import List, Dict, Any, Optional, Tuple
import re
import unicodedata
from markdown_it import MarkdownIt
import mdformat
try:
from tree_sitter import Parser
from tree_sitter_language_pack import get_language, get_parser
_HAVE_TREE_SITTER = True
except Exception:
Parser = None # type: ignore[assignment]
get_language = None # type: ignore[assignment]
get_parser = None # type: ignore[assignment]
_HAVE_TREE_SITTER = False
# Force UTF-8 output for Windows console
if sys.platform == 'win32':
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
sys.stderr.reconfigure(encoding='utf-8', errors='replace')
# CARTOGRAPHER CORE PLAN:
# This file is the heart of Cartographer: portable file-note generation,
# multi-language outline parsing, beacon parsing/application, and on-disk beacon
# update helpers. Preserve it in Core v1 alongside the snippet engine.
# @beacon[
# id=nmcv1@file-core,
# role=core keeper: cartographer mapping, beacon parsing, and beacon-update engine,
# slice_labels=nexus-portability,nexus-core-v1,
# kind=span,
# show_span=false,
# ]
# CORE V1 KEEPER:
# Preserve the portable note/header model, MD_PATH identity machinery, semantic
# whitening, and Cartographer-aware reconcile semantics. These are central to
# transferable installs and stable F12 refresh behavior.
# @beacon[
# id=nmcv1@portable-note-and-identity-core,
# role=core keeper: portable note format plus markdown and identity reconciliation semantics,
# slice_labels=nexus-portability,nexus-core-v1,
# kind=span,
# show_span=false,
# ]
# @beacon[
# id=auto-beacon@_warn_name-ts8n,
# role=ƒ _warn_name(base: str),
# slice_labels=f9-f12-handlers,ra-reconcile,carto-js-ts,carto-fwd-source,
# kind=ast,
# ]
def _warn_name(base: str) -> str:
"""Append generation timestamp so stale warning nodes are visibly old."""
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return f"{base} [{ts}]"
# --- Configuration (Synced) ---
# @beacon[
# id=auto-beacon@EMOJI_FOLDER-1o5m,
# role=EMOJI_FOLDER — 📂 folder,
# slice_labels=ra-notes,ra-notes-salvage,
# kind=span,
# ]
EMOJI_FOLDER = "📂"
# @beacon-close[
# id=auto-beacon@EMOJI_FOLDER-1o5m,
# ]
# @beacon[
# id=auto-beacon@EMOJI_FILE-0c0j,
# role=EMOJI_FILE — 📄 file,
# slice_labels=ra-notes,ra-notes-salvage,
# kind=span,
# ]
EMOJI_FILE = "📄"
# @beacon-close[
# id=auto-beacon@EMOJI_FILE-0c0j,
# ]
# @beacon[
# id=auto-beacon@EMOJI_PYTHON-pp3q,
# role=EMOJI_PYTHON — 🐍 .py,
# slice_labels=ra-notes,ra-notes-salvage,
# kind=span,
# ]
EMOJI_PYTHON = "🐍"
# @beacon-close[
# id=auto-beacon@EMOJI_PYTHON-pp3q,
# ]
# @beacon[
# id=auto-beacon@EMOJI_MARKDOWN-nq2i,
# role=EMOJI_MARKDOWN — 📘 .md,
# slice_labels=ra-notes,ra-notes-salvage,
# kind=span,
# ]
EMOJI_MARKDOWN = "📘"
# @beacon-close[
# id=auto-beacon@EMOJI_MARKDOWN-nq2i,
# ]
# @beacon[
# id=auto-beacon@EMOJI_SQL-1x3e,
# role=EMOJI_SQL — 🗄️ .sql,
# slice_labels=ra-notes,ra-notes-salvage,
# kind=span,
# ]
EMOJI_SQL = "🗄️"
# @beacon-close[
# id=auto-beacon@EMOJI_SQL-1x3e,
# ]
# @beacon[
# id=auto-beacon@EMOJI_SHELL-n7l1,
# role=EMOJI_SHELL — 🐚 shell,
# slice_labels=ra-notes,ra-notes-salvage,
# kind=span,
# ]
EMOJI_SHELL = "🐚"
# @beacon-close[
# id=auto-beacon@EMOJI_SHELL-n7l1,
# ]
# @beacon[
# id=auto-beacon@EMOJI_CLASS-td8j,
# role=EMOJI_CLASS — 📦 class,
# slice_labels=ra-notes,ra-notes-salvage,
# kind=span,
# ]
EMOJI_CLASS = "📦"
# @beacon-close[
# id=auto-beacon@EMOJI_CLASS-td8j,
# ]
# @beacon[
# id=auto-beacon@EMOJI_FUNC-l9m0,
# role=EMOJI_FUNC — ƒ function,
# slice_labels=ra-notes,ra-notes-salvage,
# kind=span,
# ]
EMOJI_FUNC = "ƒ"
# @beacon-close[
# id=auto-beacon@EMOJI_FUNC-l9m0,
# ]
# @beacon[
# id=auto-beacon@EMOJI_ASYNC-zx2s,
# role=EMOJI_ASYNC — ⚡ async,
# slice_labels=ra-notes,ra-notes-salvage,
# kind=span,
# ]
EMOJI_ASYNC = "⚡"
# @beacon-close[
# id=auto-beacon@EMOJI_ASYNC-zx2s,
# ]
# @beacon[
# id=auto-beacon@EMOJI_CONST-4qzz,
# role=EMOJI_CONST — 💎 const,
# slice_labels=ra-notes,ra-notes-salvage,
# kind=span,
# ]
EMOJI_CONST = "💎"
# @beacon-close[
# id=auto-beacon@EMOJI_CONST-4qzz,
# ]
# @beacon[
# id=auto-beacon@EMOJI_JS-y6yc,
# role=EMOJI_JS — 🟨 .js,
# slice_labels=ra-notes,ra-notes-salvage,
# kind=span,
# ]
EMOJI_JS = "🟨"
# @beacon-close[
# id=auto-beacon@EMOJI_JS-y6yc,
# ]
# @beacon[
# id=auto-beacon@EMOJI_TS-98pq,
# role=EMOJI_TS — 🟦 .ts,
# slice_labels=ra-notes,ra-notes-salvage,
# kind=span,
# ]
EMOJI_TS = "🟦"
# @beacon-close[
# id=auto-beacon@EMOJI_TS-98pq,
# ]
# @beacon[
# id=auto-beacon@EMOJI_VUE-m8x1,
# role=EMOJI_VUE — 🟩 .vue,
# slice_labels=ra-notes,ra-notes-salvage,
# kind=span,
# ]
EMOJI_VUE = "🟩"
# @beacon-close[
# id=auto-beacon@EMOJI_VUE-m8x1,
# ]
# Debug flags (controlled via environment variables)
DEBUG_MD_BEACONS = bool(os.environ.get("CARTOGRAPHER_MD_BEACONS"))
# @beacon[
# id=auto-beacon@_get_line_count-8i2t,
# role=ƒ _get_line_count(path: str),
# slice_labels=test-beacon,carto-fwd-source,
# kind=ast,
# ]
def _get_line_count(path: str) -> Optional[int]:
"""Return number of lines in a text file, or None on error.
Used to annotate FILE nodes with LINE COUNT in their Workflowy notes.
"""
try:
with open(path, "r", encoding="utf-8") as f:
return sum(1 for _ in f)
except Exception:
return None
# @beacon[
# id=auto-beacon@_portable_relpath-cg4h,
# role=_portable_relpath,
# slice_labels=carto-fwd-source,
# kind=ast,
# ]
def _portable_relpath(abs_path: str, repo_root: str) -> str | None:
"""Return a portable (forward-slash) relpath, or None if not safe/possible."""
try:
# Normalize separators but keep semantics.
abs_norm = os.path.normpath(abs_path)
root_norm = os.path.normpath(repo_root)
# os.path.commonpath throws on Windows when drives differ.
common = os.path.commonpath([abs_norm, root_norm])
if os.path.normcase(common) != os.path.normcase(root_norm):
return None
rel = os.path.relpath(abs_norm, root_norm)
rel = rel.replace("\\", "/")
if not rel or rel.startswith(".."):
return None
return rel
except Exception:
return None
# @beacon[
# id=carto-path@format_file_note,
# role=format_file_note,
# slice_labels=nexus-md-header-path,nexus-path-resolution-logic,
# kind=ast,
# comment=Emit Cartographer FILE-node Path headers under the current portability and segments model,
# ]
def format_file_note(
path: str,
line_count: int | None = None,
sha1: str | None = None,
*,
repo_root: str | None = None,
) -> str:
"""Format the standard FILE-node note header.
Shared between Cartographer (map_codebase) and per-file beacon refresh
(refresh_file_node_beacons) so that FILE nodes always expose a consistent
header block.
Portability policy (PR2 - segments mode):
- When repo_root is provided and `path` is under repo_root, store ONLY the
final path segment in the note (folder name or filename). This makes
Cartographer Workflowy trees portable and robust under folder moves.
- Otherwise (no Root context), store the raw absolute path.
Path: ...
LINE COUNT: N
Source-SHA1: ...
LINE COUNT and Source-SHA1 are optional and omitted when not provided.
"""
used_path = path
# Segments mode: when we are in a Root-mapped tree (repo_root provided)
# and this path is under repo_root, store ONLY the final segment.
if repo_root and isinstance(path, str) and isinstance(repo_root, str):
try:
if os.path.isabs(path) and os.path.isabs(repo_root):
root_norm = os.path.normcase(os.path.normpath(repo_root))
path_norm = os.path.normcase(os.path.normpath(path))
if os.path.commonpath([path_norm, root_norm]) == root_norm:
# Strip trailing separators so basename works for directories.
seg = os.path.basename(path.rstrip("\\/"))
if seg:
used_path = seg
except Exception:
# Fail closed: if any path math goes sideways, keep raw path.
used_path = path
lines: list[str] = [f"Path: {used_path}"]
if line_count is not None:
lines.append(f"LINE COUNT: {line_count}")
if sha1 is not None:
lines.append(f"Source-SHA1: {sha1}")
return "\n".join(lines)
# --- Parsers ---
# @beacon[
# id=auto-beacon@tokens_to_nexus_tree-fcan,
# role=ƒ tokens_to_nexus_tree(tokens, source_lines, source_line_offset: int),
# slice_labels=nexus-md-header-path,ra-snippet-range-ast-md,carto-fwd-markdown,
# kind=ast,
# ]
def tokens_to_nexus_tree(
tokens,
source_lines: Optional[List[str]] = None,
source_line_offset: int = 0,
) -> List[Dict[str, Any]]:
"""Convert markdown-it-py token stream to NEXUS hierarchical tree.
Assigns priority values based on document order (100, 200, 300, ...).
Lower priority = appears first in document.
v2.2: For each Markdown heading node, writes an explicit MD_PATH block into
the note:
MD_PATH:
# Top
## Section
### Subsection
---
<existing heading content>
v2.3: When ``source_lines`` are provided, each heading node's note body is
taken from the exact raw Markdown lines that belong *directly* to that
heading (after the heading line and before the next heading of any level).
This preserves nested ordered/bullet lists, indentation, fenced code
blocks, and numbering verbatim instead of reconstructing them token by
token.
This mirrors Python's AST_QUALNAME header and is consumed by
get_snippet_for_md_path in beacon_obtain_code_snippet.py.
"""
root_children: List[Dict[str, Any]] = []
# Stack of (heading_level, nexus_node)
stack: List[tuple[int, Dict[str, Any]]] = []
priority_counter = 100
heading_entries: List[Dict[str, Any]] = []
excluded_body_lines: set[int] = set()
# Bug fix (Dan, May 2026): track containment depth so we ignore
# headings that occur INSIDE a Markdown construct that represents body
# content rather than document structure. Specifically:
#
# - Blockquotes ('>'-prefixed lines, e.g. quoted PDFs, emails, or any
# verbatim transcript). A heading inside a blockquote is part of the
# quoted material, not part of the enclosing document's outline.
#
# - List items. A heading nested inside a bullet or numbered list item
# is body content belonging to the enclosing real heading, not its
# own document-level section.
#
# Without these guards, a quoted/listed '# Some Title' line was being
# promoted to a top-level Workflowy heading node, gathering subsequent
# real document content as its 'children', and corrupting the MD_PATH
# ancestor chain for everything that followed.
#
# Markdown-it-py emits matched open/close token pairs around blockquoted
# and list-item content; nested instances nest the pairs cleanly, so
# simple integer depth counters are sufficient. Note that we track
# ``list_item_*`` rather than ``bullet_list_*`` / ``ordered_list_*``
# because the meaningful containment is the individual list item, not
# the surrounding list wrapper.
blockquote_depth: int = 0
list_item_depth: int = 0
i = 0
while i < len(tokens):
token = tokens[i]
if token.type == "blockquote_open":
blockquote_depth += 1
i += 1
continue
if token.type == "blockquote_close":
if blockquote_depth > 0:
blockquote_depth -= 1
i += 1
continue
if token.type == "list_item_open":
list_item_depth += 1
i += 1
continue
if token.type == "list_item_close":
if list_item_depth > 0:
list_item_depth -= 1
i += 1
continue
if token.type == "html_block" and (
"@beacon[" in (token.content or "") or "@beacon-close[" in (token.content or "")
):
token_map = getattr(token, "map", None)
if token_map:
start0, end0 = token_map
for line_no in range(start0 + 1, end0 + 1):
excluded_body_lines.add(line_no)
i += 1
continue
if token.type != "heading_open":
i += 1
continue
# Skip headings that live inside a blockquote OR list item: they are
# body content, not document structure. Advance the loop counter by
# ONE so the natural token-by-token walk handles the following
# ``inline`` and ``heading_close`` tokens through their own normal
# type checks. (We deliberately do NOT advance by 3 to skip the
# whole heading triple; that would assume markdown-it always emits
# heading_open + inline + heading_close as a strict three-token
# group, which is true today but a fragile contract to depend on.
# Letting the loop fall through is strictly more robust.)
if blockquote_depth > 0 or list_item_depth > 0:
i += 1
continue
# Start of a heading
heading_level = int(token.tag[1:]) # h1 -> 1, h12 -> 12, etc.
# Get the heading text from next token (should be inline)
heading_text = ""
if i + 1 < len(tokens) and tokens[i + 1].type == "inline":
heading_text = tokens[i + 1].content
# Pop stack until we find the correct parent level for this heading
while stack and stack[-1][0] >= heading_level:
stack.pop()
# Build MD_PATH lines from current ancestor stack + this heading.
#
# Layer (3) sanitizer (Dan, 2026-05-01, Bug #3 hardening):
# Collapse any internal whitespace/newlines in ancestor names and
# in the current heading text to a single line before embedding
# into MD_PATH. Also replace meta-blocky names (BEACON metadata
# that may have leaked into a node's name field) with a clearly
# flagged placeholder so the MD_PATH structure survives even if
# the in-memory tree was corrupted upstream. The level (number of
# '#'s) is always preserved; only the visible text is sanitized.
def _md_path_sanitize(name: str) -> str:
single = " ".join((name or "").split()).strip()
if not single:
return "..."
head = single.lstrip()
if head.startswith("BEACON ("):
return "⚠️ corrupt-heading"
meta_markers = ("id:", "role:", "slice_labels:", "kind:")
hits = sum(1 for m in meta_markers if m in single)
if hits >= 2:
return "⚠️ corrupt-heading"
return single
md_path_lines: List[str] = []
for lvl, ancestor_node in stack:
ancestor_name = _md_path_sanitize(ancestor_node.get("name") or "")
md_path_lines.append(f"{('#' * lvl)} {ancestor_name}".rstrip())
this_heading_name = _md_path_sanitize(heading_text or "")
md_path_lines.append(f"{('#' * heading_level)} {this_heading_name}".rstrip())
note_lines: List[str] = ["MD_PATH:"]
note_lines.extend(md_path_lines)
note_lines.append("---")
note_text = "\n".join(note_lines)
# Determine source line span for the heading itself so we can attach the
# raw body that follows it verbatim and stamp the parsed node with a
# concrete full-file heading line for beacon attachment.
token_map = getattr(token, "map", None)
if token_map:
heading_start0, heading_end0 = token_map
elif i + 1 < len(tokens) and getattr(tokens[i + 1], "map", None):
heading_start0, heading_end0 = tokens[i + 1].map
else:
heading_start0 = 0
heading_end0 = 0
# Create NEXUS node.
# _md_heading_line is an internal Cartographer-only source coordinate
# used by apply_markdown_beacons(...) to attach Markdown AST beacons
# by actual parser line number rather than by raw heading-name search.
# This removes duplicate-heading ambiguity while keeping MD_PATH as
# the durable identity shown in Workflowy notes.
nexus_node: Dict[str, Any] = {
"name": this_heading_name,
"priority": priority_counter,
"note": note_text,
"children": [],
"_md_heading_line": int(heading_start0) + 1 + int(source_line_offset or 0),
}
priority_counter += 100
# Add to parent (or root if stack empty)
if stack:
stack[-1][1]["children"].append(nexus_node)
else:
root_children.append(nexus_node)
heading_entries.append(
{
"node": nexus_node,
"heading_start_line": heading_start0 + 1,
"body_start_line": heading_end0 + 1,
}
)
# Push this heading onto stack
stack.append((heading_level, nexus_node))
# Skip the inline and heading_close tokens
i += 3 # heading_open, inline, heading_close
if source_lines is not None and heading_entries:
total_lines = len(source_lines)
for idx, entry in enumerate(heading_entries):
body_start_line = int(entry["body_start_line"])
next_heading_start = (
int(heading_entries[idx + 1]["heading_start_line"])
if idx + 1 < len(heading_entries)
else total_lines + 1
)
body_end_line = next_heading_start - 1
body_lines: List[str] = []
if body_end_line >= body_start_line:
for line_no in range(body_start_line, body_end_line + 1):
if line_no in excluded_body_lines:
continue
body_lines.append(source_lines[line_no - 1])
while body_lines and not body_lines[0].strip():
body_lines.pop(0)
while body_lines and not body_lines[-1].strip():
body_lines.pop()
if body_lines:
entry["node"]["note"] = (
f"{entry['node']['note']}\n\n" + "\n".join(body_lines)
)
return root_children
# @beacon[
# id=auto-beacon@markdown_it_heading_arbitrary_depth-7a3t,
# role=markdown_it_heading_arbitrary_depth,
# slice_labels=carto-fwd-markdown,
# kind=ast,
# ]
def markdown_it_heading_arbitrary_depth(state, startLine: int, endLine: int, silent: bool) -> bool:
"""markdown-it block rule for ATX headings with arbitrary hash depth.
This is a minimal fork of markdown_it.rules_block.heading.heading with the
CommonMark 6-hash cap lifted to 64. Keeping this as a markdown-it rule lets
the parser retain its existing block-context intelligence (fences, indented
code, HTML blocks, blockquote recursion, source maps, etc.) instead of
replacing the whole outline parse with a raw line scanner.
"""
from markdown_it.common.utils import isStrSpace
pos = state.bMarks[startLine] + state.tShift[startLine]
maximum = state.eMarks[startLine]
if pos >= maximum:
return False
if state.is_code_block(startLine):
return False
if state.src[pos] != "#":
return False
level = 0
while pos < maximum and state.src[pos] == "#" and level < 64:
level += 1
pos += 1
if level == 0 or level > 64:
return False
if pos < maximum and not isStrSpace(state.src[pos]):
return False
if silent:
return True
maximum = state.skipSpacesBack(maximum, pos)
tmp = state.skipCharsStrBack(maximum, "#", pos)
if tmp > pos and isStrSpace(state.src[tmp - 1]):
maximum = tmp
state.line = startLine + 1
token = state.push("heading_open", "h" + str(level), 1)
token.markup = "#" * level
token.map = [startLine, state.line]
token = state.push("inline", "", 0)
token.content = state.src[pos:maximum].strip()
token.map = [startLine, state.line]
token.children = []
token = state.push("heading_close", "h" + str(level), -1)
token.markup = "#" * level
return True
# @beacon[
# id=auto-beacon@arbitrary_hash_markdown_lines_to_nexus_tree-kj1r,
# role=arbitrary_hash_markdown_lines_to_nexus_tree,
# slice_labels=carto-fwd-markdown,
# kind=ast,
# ]
def arbitrary_hash_markdown_lines_to_nexus_tree(
source_lines: List[str],
source_line_offset: int = 0,
*,
max_hash_depth: int = 64,
) -> List[Dict[str, Any]]:
"""Parse Markdown headings with arbitrary hash depth into a NEXUS tree.
This is the Workflowy-first Markdown heading parser used by Cartographer.
CommonMark / markdown-it only recognizes ATX headings with 1..6 hashes;
Dan's 99-file curation workflow deliberately uses 7, 8, 9+ hash headings
as real Workflowy child nodes. Therefore heading recognition here is a
simple source-line rule: any line matching ``^#{1,max_hash_depth}\\s+`` is
a heading node, regardless of the official Markdown 6-level cap.
The function preserves the same shape as tokens_to_nexus_tree(...):
each heading node gets name/note/priority/children and an internal
``_md_heading_line`` full-file coordinate for apply_markdown_beacons(...).
The durable Workflowy-visible identity remains MD_PATH in the note.
"""
root_children: List[Dict[str, Any]] = []
stack: List[tuple[int, Dict[str, Any]]] = []
priority_counter = 100
heading_entries: List[Dict[str, Any]] = []
excluded_body_lines: set[int] = set()
# Exclude @beacon[...] / @beacon-close[...] HTML comment blocks from the
# body text attached to heading notes. They are metadata, not prose.
i = 0
while i < len(source_lines):
raw = source_lines[i]
if "<!--" in raw:
j = i
block_lines: list[str] = []
while j < len(source_lines):
block_lines.append(source_lines[j])
if "-->" in source_lines[j]:
break
j += 1
if any("@beacon[" in x or "@beacon-close[" in x for x in block_lines):
for line_no in range(i + 1, min(j + 1, len(source_lines)) + 1):
excluded_body_lines.add(line_no)
i = j + 1
continue
i += 1
heading_re = re.compile(rf"^(#{{1,{int(max_hash_depth)}}})\s+(.*)$")
def _md_path_sanitize(name: str) -> str:
single = " ".join((name or "").split()).strip()
if not single:
return "..."
head = single.lstrip()
if head.startswith("BEACON ("):
return "⚠️ corrupt-heading"
meta_markers = ("id:", "role:", "slice_labels:", "kind:")
hits = sum(1 for m in meta_markers if m in single)
if hits >= 2:
return "⚠️ corrupt-heading"
return single
for idx, raw in enumerate(source_lines, start=1):
if idx in excluded_body_lines:
continue
stripped = raw.strip()
m = heading_re.match(stripped)
if not m:
continue
heading_level = len(m.group(1))
heading_text = m.group(2).strip()
# Trim optional closing ATX hashes ("### Title ###") when present.
heading_text = re.sub(r"\s+#+\s*$", "", heading_text).strip()
while stack and stack[-1][0] >= heading_level:
stack.pop()
md_path_lines: List[str] = []
for lvl, ancestor_node in stack:
ancestor_name = _md_path_sanitize(ancestor_node.get("name") or "")
md_path_lines.append(f"{('#' * lvl)} {ancestor_name}".rstrip())
this_heading_name = _md_path_sanitize(heading_text or "")
md_path_lines.append(f"{('#' * heading_level)} {this_heading_name}".rstrip())
note_lines: List[str] = ["MD_PATH:"]
note_lines.extend(md_path_lines)
note_lines.append("---")
note_text = "\n".join(note_lines)
nexus_node: Dict[str, Any] = {
"name": this_heading_name,
"priority": priority_counter,
"note": note_text,
"children": [],
"_md_heading_line": int(idx) + int(source_line_offset or 0),
}
priority_counter += 100
if stack:
stack[-1][1]["children"].append(nexus_node)
else:
root_children.append(nexus_node)
heading_entries.append(
{
"node": nexus_node,
"heading_start_line": idx,
"body_start_line": idx + 1,
}
)
stack.append((heading_level, nexus_node))
if heading_entries:
total_lines = len(source_lines)
for idx, entry in enumerate(heading_entries):
body_start_line = int(entry["body_start_line"])
next_heading_start = (
int(heading_entries[idx + 1]["heading_start_line"])
if idx + 1 < len(heading_entries)
else total_lines + 1
)
body_end_line = next_heading_start - 1
body_lines: List[str] = []
if body_end_line >= body_start_line:
for line_no in range(body_start_line, body_end_line + 1):
if line_no in excluded_body_lines:
continue
body_lines.append(source_lines[line_no - 1])
while body_lines and not body_lines[0].strip():
body_lines.pop(0)
while body_lines and not body_lines[-1].strip():
body_lines.pop()
if body_lines:
entry["node"]["note"] = (
f"{entry['node']['note']}\n\n" + "\n".join(body_lines)
)
return root_children
# @beacon[
# id=carto-js-ts@parse_markdown_beacon_blocks,
# role=🔱 carto-js-ts,
# slice_labels=carto-js-ts,carto-js-ts-beacons,f9-f12-handlers,ra-reconcile,nexus-md-header-path,carto-fwd-source,
# kind=span,
# ]
# Phase 2 JS/TS: Markdown beacon parser template.
# Reference for JS/TS block-comment beacons (/* @beacon[...] */),
# which use the same metadata fields and parsing pattern.
# @beacon[
# id=auto-beacon@parse_markdown_beacon_blocks-t69i,
# role=parse_markdown_beacon_blocks,
# slice_labels=carto-fwd-markdown,
# kind=ast,
# ]
def parse_markdown_beacon_blocks(lines: list[str]) -> list[dict[str, Any]]:
"""Parse @beacon[...] HTML comment blocks from Markdown source.
Expected form (we control this schema):
<!--
@beacon[
id=docs:intro@1234,
role=doc:intro,
slice_labels=DOC,
kind=span,
start_snippet="# Heading text",
comment=One-line human note,
]
-->
Returns a list of dicts with keys:
id, role, slice_labels, kind, start_snippet, end_snippet,
comment, comment_line, span_lineno_start, span_lineno_end,
kind_explicit.
"""
beacons: list[dict[str, Any]] = []
n = len(lines)
i = 0
while i < n:
line = lines[i]
if "@beacon[" in line:
comment_line = i + 1 # 1-based
block_lines = [line]
i += 1
# Collect until a line containing ']' (inclusive)
while i < n:
block_lines.append(lines[i])
if "]" in lines[i]:
i += 1
break
i += 1
# Parse block_lines into key/value pairs (skip first/last structural lines)
fields: dict[str, str] = {}
inner_lines = block_lines[1:-1] if len(block_lines) >= 2 else []
for raw in inner_lines:
text = raw.strip()
if not text or text.startswith("@beacon"):
continue
if text.startswith("<!--") or text.startswith("-->"):
continue
# Drop trailing ',' or '],' or ']'
while text and text[-1] in ",]":
text = text[:-1].rstrip()
if not text or "=" not in text:
continue
key, val = text.split("=", 1)
key = key.strip()
val = val.strip()
# Strip surrounding quotes if present
if (val.startswith("\"") and val.endswith("\"")) or (
val.startswith("'") and val.endswith("'")
):
val = val[1:-1]
fields[key] = val
kind_raw = fields.get("kind")
kind = (kind_raw or "span").strip().lower() or "span"
if kind not in {"ast", "span"}:
continue
show_span, show_span_explicit = _parse_show_span_fields(fields)
start_snippet = fields.get("start_snippet")
end_snippet = fields.get("end_snippet")
span_start: Optional[int] = None
span_end: Optional[int] = None
if kind == "span" and start_snippet:
norm_snip = normalize_for_match(start_snippet)
if norm_snip:
# Find candidate start lines (global search), but IGNORE
# lines that are clearly part of the beacon metadata
# itself (the @beacon block and its key/value lines).
start_candidates: list[int] = []
for idx, src_line in enumerate(lines, start=1):
# Skip any line that looks like part of a @beacon
# comment block so we never anchor spans to their
# own metadata.
if "@beacon[" in src_line or "start_snippet=" in src_line or "end_snippet=" in src_line:
continue
if norm_snip in normalize_for_match(src_line):
start_candidates.append(idx)
if start_candidates:
if len(start_candidates) == 1:
span_start = start_candidates[0]
else:
after = [ln for ln in start_candidates if ln > comment_line]
if len(after) == 1:
span_start = after[0]
else:
# Ambiguous; require refinement
span_start = None
if span_start is not None:
if end_snippet:
norm_end = normalize_for_match(end_snippet)
for idx in range(span_start, len(lines) + 1):
if norm_end in normalize_for_match(lines[idx - 1]):
span_end = idx
break
if span_end is None:
# Explicit end_snippet but no match – leave span unset
span_start = None
else:
# Default: until just before next header (any level)
span_end = len(lines)
for idx in range(span_start + 1, len(lines) + 1):
if re.match(r"^#{1,64}\s", lines[idx - 1]):
span_end = idx - 1
break
beacon = {
"id": fields.get("id"),
"role": fields.get("role"),
"slice_labels": fields.get("slice_labels"),
"kind": kind,
"start_snippet": start_snippet,
"end_snippet": end_snippet,
"comment": (fields.get("comment") if fields.get("comment") not in (None, "") else fields.get("comments")),
"comment_line": comment_line,
"span_lineno_start": span_start,
"span_lineno_end": span_end,
"kind_explicit": bool(kind_raw),
"show_span": show_span,
"show_span_explicit": show_span_explicit,
}
beacons.append(beacon)
else:
i += 1
# Second pass: compute span ranges for Markdown span beacons using @beacon-close[...]
for beacon in beacons:
if beacon.get("kind") != "span":
continue
# Only override when no span was set by start_snippet/end_snippet
if beacon.get("span_lineno_start") is not None and beacon.get("span_lineno_end") is not None:
continue
b_id = (beacon.get("id") or "").strip()
if not b_id:
continue
comment_line = beacon.get("comment_line")
if not isinstance(comment_line, int) or not (1 <= comment_line <= n):
continue
# Find end of opener's metadata block (first line containing ']')
j = comment_line
open_end = comment_line
while j <= n:
raw = lines[j - 1]
if "]" in raw:
open_end = j
break
j += 1
# Scan forward for matching @beacon-close[...] with same id
close_comment_line = None
k = open_end + 1
while k <= n:
raw = lines[k - 1]
if "@beacon-close[" in raw:
close_lines = [raw]
k += 1
while k <= n:
next_raw = lines[k - 1]
close_lines.append(next_raw)
if next_raw.strip().lstrip("#").lstrip().startswith("]"):
k += 1
break
k += 1
close_id = None
for cl in close_lines:
text = cl.strip()
# Strip HTML comment wrappers
if text.startswith("<!--"):
text = text[4:].lstrip()
if text.endswith("-->"):
text = text[:-3].rstrip()
# Drop trailing ',' and ']'
while text and text[-1] in ",]":
text = text[:-1].rstrip()
if "id=" in text:
_, val = text.split("=", 1)
close_id = val.strip()
break
if close_id == b_id:
close_comment_line = k - len(close_lines)
break
k += 1
if close_comment_line is not None:
inner_start = open_end + 1
inner_end = close_comment_line - 1
if inner_start <= inner_end:
beacon["span_lineno_start"] = inner_start