sieve-notes 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.
sieve_notes.py ADDED
@@ -0,0 +1,1797 @@
1
+ #!/usr/bin/env python3
2
+ """sieve_notes.py — Sieve Notes 0.1.0 (stage 1: observation and conversion engine).
3
+
4
+ Command-line tool and library for Markdown note vaults.
5
+
6
+ - `index PATH` : observes the relations of a vault (notes, links, backlinks,
7
+ broken links, orphans).
8
+ - `blocks FILE` : the block tree (closed vocabulary; note bodies are not emitted).
9
+ - `convert FILE` : document <-> outline conversion (writes a new file;
10
+ the original file is never modified).
11
+ - `--self-check` : verifies the bundled small sample.
12
+
13
+ Principles: standard library only, deterministic, observation rather than judgment,
14
+ original files are never modified, closed vocabulary, exit codes 0 / 1 / 2.
15
+ Text decoding: UTF-8 with BOM, then strict UTF-8, then strict CP932, then reject;
16
+ implemented with the standard library alone.
17
+ """
18
+
19
+ import json
20
+ import os
21
+ import re
22
+ import sys
23
+ import tempfile
24
+ import unicodedata
25
+ from pathlib import Path
26
+
27
+ __version__ = "0.1.0"
28
+ NOTES_VERSION = 1
29
+
30
+ # ---------------------------------------------------------------- vocabulary
31
+ LINK_TYPES = ("wikilink", "embed", "markdown_link", "block_ref")
32
+ LINK_STATES = ("resolved", "broken", "ambiguous", "fragment_missing")
33
+ BLOCK_TYPES = ("heading", "paragraph", "list_item", "code", "quote",
34
+ "callout", "table", "html", "rule", "frontmatter",
35
+ "comment", "properties")
36
+ DIALECTS = ("document", "outline")
37
+ SKIP_REASONS = ("symlink_skipped", "too_large", "unreadable",
38
+ "unsupported_encoding", "file_limit")
39
+ KEPT_WORDS = ("kept_as_text_fold_state", "kept_as_text_block_id",
40
+ "kept_as_text_properties", "kept_as_text_frontmatter",
41
+ "kept_as_text_unsupported")
42
+ SHAPE_WORDS = ("list_became_paragraphs", "ordered_list_became_bullets",
43
+ "lists_merged")
44
+
45
+ DEFAULT_EXCLUDED_DIR_NAMES = frozenset({".obsidian", ".trash", "logseq",
46
+ ".git"})
47
+ DEFAULT_MAX_FILE_BYTES = 5_000_000
48
+ DEFAULT_MAX_FILES = 20_000
49
+
50
+ ERROR_WORDS = ("input_not_found", "not_a_directory", "output_exists",
51
+ "dialect_mismatch", "already_in_target", "read_failed")
52
+
53
+ # ---------------------------------------------------------------- reading
54
+
55
+
56
+ def _decode_policy(data: bytes):
57
+ """Text decoding policy.
58
+
59
+ UTF-8 with BOM, then strict UTF-8, then strict CP932, then rejection.
60
+ A UTF-16/32 BOM is rejected immediately. errors="replace" / "ignore" are
61
+ never used. Returns (text, None) or (None, "unsupported_encoding").
62
+ """
63
+ if data[:4] in (b"\xff\xfe\x00\x00", b"\x00\x00\xfe\xff") or \
64
+ data[:2] in (b"\xff\xfe", b"\xfe\xff"):
65
+ return None, "unsupported_encoding"
66
+ for encoding in ("utf-8-sig", "utf-8", "cp932"):
67
+ try:
68
+ return data.decode(encoding), None
69
+ except UnicodeDecodeError:
70
+ continue
71
+ return None, "unsupported_encoding"
72
+
73
+
74
+ def _read_note_bytes(path: Path, max_bytes: int):
75
+ """Read a note up to max_bytes+1 bytes; returns (data|None, reason|None)."""
76
+ try:
77
+ with open(path, "rb") as fh:
78
+ chunk = fh.read(max_bytes + 1)
79
+ except OSError:
80
+ return None, "unreadable"
81
+ if len(chunk) > max_bytes:
82
+ return None, "too_large"
83
+ return chunk, None
84
+
85
+
86
+ # ---------------------------------------------------------------- line basics
87
+
88
+ _PROP_RE = re.compile(
89
+ r"^([A-Za-z0-9][A-Za-z0-9_.*+\-!?$%&=<>]*)::([ ].*)?$")
90
+ _HEADING_RE = re.compile(r"^(#{1,6}) (.*)$")
91
+ _FENCE_OPEN_RE = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$")
92
+ _RULE_RE = re.compile(r"^ {0,3}(-{3,}|\*{3,}|_{3,})\s*$")
93
+ _BULLET_RE = re.compile(r"^(\s*)-( .*)?$")
94
+ _ORDERED_RE = re.compile(r"^(\s*)(\d{1,9}[.)]) (.*)$")
95
+ _BLOCK_ID_TAIL_RE = re.compile(r"\^([A-Za-z0-9][A-Za-z0-9-]*)\s*$")
96
+ _CALLOUT_RE = re.compile(r"^>\s*\[!([A-Za-z][A-Za-z0-9-]*)\]([+-]?)")
97
+ _SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.\-]*:")
98
+
99
+
100
+ def _indent_units(line: str) -> int:
101
+ """One indentation level is one tab or two spaces."""
102
+ units = 0
103
+ spaces = 0
104
+ for ch in line:
105
+ if ch == " ":
106
+ spaces += 1
107
+ elif ch == "\t":
108
+ units += 1
109
+ spaces = 0
110
+ else:
111
+ break
112
+ units += spaces // 2
113
+ return units
114
+
115
+
116
+ def _strip_units(line: str, units: int) -> str:
117
+ """Strip exactly `units` indentation levels from the line start (all of them if fewer)."""
118
+ i = 0
119
+ got = 0
120
+ spaces = 0
121
+ while i < len(line) and got < units:
122
+ ch = line[i]
123
+ if ch == " ":
124
+ spaces += 1
125
+ i += 1
126
+ if spaces == 2:
127
+ got += 1
128
+ spaces = 0
129
+ elif ch == "\t":
130
+ got += 1
131
+ spaces = 0
132
+ i += 1
133
+ else:
134
+ break
135
+ if spaces:
136
+ i -= spaces
137
+ return line[i:]
138
+
139
+
140
+ def _normalize_text(text: str) -> str:
141
+ """Normalize CRLF to LF at the reading entry point. The original file is not modified."""
142
+ return text.replace("\r\n", "\n").replace("\r", "\n")
143
+
144
+
145
+ def _fold_key(s: str) -> str:
146
+ """Common key for name matching: NFC-normalized and case-insensitive."""
147
+ return unicodedata.normalize("NFC", s).casefold()
148
+
149
+
150
+ def _is_property(line: str):
151
+ m = _PROP_RE.match(line)
152
+ if not m:
153
+ return None
154
+ return m.group(1), (m.group(2) or "")[1:]
155
+
156
+
157
+ def _property_kept_word(key: str) -> str:
158
+ k = key.casefold()
159
+ if k == "collapsed":
160
+ return "kept_as_text_fold_state"
161
+ if k == "id":
162
+ return "kept_as_text_block_id"
163
+ return "kept_as_text_properties"
164
+
165
+
166
+ # ---------------------------------------------------------------- block parsing
167
+ #
168
+ # Node: {"type", "depth", "start", "end" (1-based, inclusive),
169
+ # "lines": [line strings], ... auxiliary fields for conversion}
170
+
171
+
172
+ def _new_node(node_type, depth, start, lines):
173
+ return {"type": node_type, "depth": depth, "start": start,
174
+ "end": start + len(lines) - 1, "lines": list(lines)}
175
+
176
+
177
+ def _parse_document(text: str):
178
+ """Line parsing for the document dialect. Returns a flat list of nodes with depth."""
179
+ lines = _normalize_text(text).split("\n")
180
+ n = len(lines)
181
+ if n and lines[-1] == "":
182
+ lines = lines[:-1]
183
+ n -= 1
184
+ nodes = []
185
+ heading_stack = [] # (level, depth)
186
+ item_stack = [] # (nesting, depth)
187
+ para_depth = None # previous paragraph (within the same section)
188
+ prev_was_para = False
189
+ last_item_parent_children = None
190
+ i = 0
191
+
192
+ # frontmatter: starts with --- and has a closing --- before any blank line
193
+ if n and lines[0] == "---":
194
+ j = 1
195
+ while j < n and lines[j] != "---" and lines[j].strip() != "":
196
+ j += 1
197
+ if j < n and lines[j] == "---":
198
+ nodes.append(_new_node("frontmatter", 0, 1, lines[0:j + 1]))
199
+ i = j + 1
200
+
201
+ while i < n:
202
+ line = lines[i]
203
+ stripped = line.strip()
204
+ if stripped == "":
205
+ i += 1
206
+ prev_was_para = False
207
+ continue
208
+ m = _FENCE_OPEN_RE.match(line)
209
+ if m:
210
+ fence_char = m.group(1)[0]
211
+ fence_len = len(m.group(1))
212
+ block = [line]
213
+ j = i + 1
214
+ close_re = re.compile(
215
+ r"^ {0,3}" + re.escape(fence_char) + r"{%d,}\s*$" % fence_len)
216
+ while j < n and not close_re.match(lines[j]):
217
+ block.append(lines[j])
218
+ j += 1
219
+ if j < n:
220
+ block.append(lines[j])
221
+ j += 1
222
+ depth = len(heading_stack)
223
+ nodes.append(_new_node("code", depth, i + 1, block))
224
+ i = j
225
+ prev_was_para = False
226
+ para_depth = None
227
+ continue
228
+ m = _HEADING_RE.match(line)
229
+ if m:
230
+ level = len(m.group(1))
231
+ while heading_stack and heading_stack[-1][0] >= level:
232
+ heading_stack.pop()
233
+ depth = len(heading_stack)
234
+ heading_stack.append((level, depth))
235
+ nodes.append(_new_node("heading", depth, i + 1, [line]))
236
+ nodes[-1]["level"] = level
237
+ nodes[-1]["heading_text"] = line
238
+ i += 1
239
+ item_stack = []
240
+ prev_was_para = False
241
+ para_depth = None
242
+ continue
243
+ if line.startswith("%%"):
244
+ block = [line]
245
+ j = i + 1
246
+ if not (line.rstrip().endswith("%%") and len(line.rstrip()) > 2):
247
+ while j < n and not lines[j].rstrip().endswith("%%"):
248
+ block.append(lines[j])
249
+ j += 1
250
+ if j < n:
251
+ block.append(lines[j])
252
+ j += 1
253
+ nodes.append(_new_node("comment", len(heading_stack), i + 1,
254
+ block))
255
+ i = j
256
+ prev_was_para = False
257
+ para_depth = None
258
+ continue
259
+ if line.startswith("<!--"):
260
+ block = [line]
261
+ j = i + 1
262
+ if "-->" not in line:
263
+ while j < n and "-->" not in lines[j]:
264
+ block.append(lines[j])
265
+ j += 1
266
+ if j < n:
267
+ block.append(lines[j])
268
+ j += 1
269
+ nodes.append(_new_node("comment", len(heading_stack), i + 1,
270
+ block))
271
+ i = j
272
+ prev_was_para = False
273
+ para_depth = None
274
+ continue
275
+ if line.startswith(">"):
276
+ block = [line]
277
+ j = i + 1
278
+ while j < n and lines[j].startswith(">"):
279
+ block.append(lines[j])
280
+ j += 1
281
+ is_callout = bool(_CALLOUT_RE.match(line))
282
+ node_type = "callout" if is_callout else "quote"
283
+ node = _new_node(node_type, len(heading_stack), i + 1, block)
284
+ if is_callout:
285
+ cm = _CALLOUT_RE.match(line)
286
+ node["folded"] = cm.group(2) == "-"
287
+ nodes.append(node)
288
+ i = j
289
+ prev_was_para = False
290
+ para_depth = None
291
+ continue
292
+ if line.startswith("|"):
293
+ block = [line]
294
+ j = i + 1
295
+ while j < n and lines[j].startswith("|"):
296
+ block.append(lines[j])
297
+ j += 1
298
+ nodes.append(_new_node("table", len(heading_stack), i + 1, block))
299
+ i = j
300
+ prev_was_para = False
301
+ para_depth = None
302
+ continue
303
+ if line[0] == "<" and len(line) > 1 and \
304
+ (line[1].isascii() and line[1].isalpha()):
305
+ block = [line]
306
+ j = i + 1
307
+ while j < n and lines[j].strip() != "":
308
+ block.append(lines[j])
309
+ j += 1
310
+ nodes.append(_new_node("html", len(heading_stack), i + 1, block))
311
+ i = j
312
+ prev_was_para = False
313
+ para_depth = None
314
+ continue
315
+ if _RULE_RE.match(line):
316
+ nodes.append(_new_node("rule", len(heading_stack), i + 1, [line]))
317
+ i += 1
318
+ prev_was_para = False
319
+ para_depth = None
320
+ continue
321
+ prop = _is_property(line)
322
+ if prop:
323
+ nodes.append(_new_node("properties", len(heading_stack), i + 1,
324
+ [line]))
325
+ nodes[-1]["prop_key"] = prop[0]
326
+ i += 1
327
+ prev_was_para = False
328
+ para_depth = None
329
+ continue
330
+ ob = _BULLET_RE.match(line)
331
+ od = _ORDERED_RE.match(line)
332
+ if ob or od:
333
+ if od:
334
+ indent_raw, marker, content = od.group(1), od.group(2), \
335
+ od.group(3)
336
+ ordered = True
337
+ else:
338
+ indent_raw = ob.group(1)
339
+ content = (ob.group(2)[1:] if ob.group(2) else "")
340
+ ordered = False
341
+ nesting = _indent_units(indent_raw)
342
+ while item_stack and item_stack[-1][0] >= nesting:
343
+ item_stack.pop()
344
+ after_blank = i > 0 and lines[i - 1].strip() == ""
345
+ if item_stack:
346
+ depth = item_stack[-1][1] + 1
347
+ elif prev_was_para:
348
+ depth = para_depth + 1
349
+ else:
350
+ depth = len(heading_stack)
351
+ item_stack.append((nesting, depth))
352
+ node = _new_node("list_item", depth, i + 1, [line])
353
+ node["nesting"] = nesting
354
+ node["ordered"] = ordered
355
+ node["content"] = content
356
+ node["indent_raw"] = indent_raw
357
+ node["after_blank"] = bool(after_blank)
358
+ node["marker_len"] = len(indent_raw) + 1 # "- " or "1. "
359
+ nodes.append(node)
360
+ i += 1
361
+ prev_was_para = False
362
+ continue
363
+ # paragraph (up to a blank line or another block)
364
+ block = [line]
365
+ j = i + 1
366
+ while j < n:
367
+ nxt = lines[j]
368
+ if nxt.strip() == "" or _FENCE_OPEN_RE.match(nxt) or \
369
+ _HEADING_RE.match(nxt) or nxt.startswith(">") or \
370
+ nxt.startswith("|") or nxt.startswith("%%") or \
371
+ nxt.startswith("<!--") or _RULE_RE.match(nxt) or \
372
+ _is_property(nxt) or _BULLET_RE.match(nxt) or \
373
+ _ORDERED_RE.match(nxt) or \
374
+ (nxt[0] == "<" and len(nxt) > 1 and nxt[1].isalpha()):
375
+ break
376
+ block.append(nxt)
377
+ j += 1
378
+ depth = len(heading_stack)
379
+ node = _new_node("paragraph", depth, i + 1, block)
380
+ node["prev_was_para"] = True
381
+ nodes.append(node)
382
+ i = j
383
+ prev_was_para = True
384
+ para_depth = depth
385
+ continue
386
+ return nodes, lines
387
+
388
+
389
+ def _blank_before(lines, idx):
390
+ """Whether the line before idx (0-based) is blank (the line before line 0 counts as non-blank)."""
391
+ while idx >= 0:
392
+ if lines[idx].strip() == "":
393
+ return True
394
+ return False
395
+ return False
396
+
397
+
398
+ def _parse_outline(text: str):
399
+ """Line parsing for the outline dialect. Returns a flat list of nodes."""
400
+ lines = _normalize_text(text).split("\n")
401
+ n = len(lines)
402
+ if n and lines[-1] == "":
403
+ lines = lines[:-1]
404
+ n -= 1
405
+ nodes = []
406
+ stack = [] # open item nodes
407
+ fence = None # (item_node, fence_char, fence_len, close_re)
408
+ i = 0
409
+ while i < n:
410
+ line = lines[i]
411
+ stripped = line.strip()
412
+ if stripped == "":
413
+ i += 1
414
+ continue
415
+ units = _indent_units(line)
416
+ if fence is not None:
417
+ item_node, close_re = fence
418
+ if close_re.match(stripped):
419
+ item_node["lines"].append(line)
420
+ item_node["end"] = i + 1
421
+ fence = None
422
+ else:
423
+ item_node["lines"].append(line)
424
+ item_node["end"] = i + 1
425
+ i += 1
426
+ continue
427
+ is_marker = line.lstrip(" \t").startswith("- ") or \
428
+ line.lstrip(" \t") == "-"
429
+ if units == 0 and not is_marker:
430
+ # raw root line (such as a kept line): passed through unchanged
431
+ nodes.append({"type": "bare", "depth": 0, "start": i + 1,
432
+ "end": i + 1, "lines": [line]})
433
+ i += 1
434
+ continue
435
+ if is_marker:
436
+ prefix = _indent_prefix_len(line)
437
+ content = line[prefix + 2:]
438
+ node = {"type": "list_item", "depth": units, "start": i + 1,
439
+ "end": i + 1, "lines": [line], "content": content,
440
+ "depth_val": units}
441
+ m = _HEADING_RE.match(content)
442
+ if m:
443
+ node["type"] = "heading"
444
+ node["heading_text"] = content
445
+ elif content.startswith("%%") or content.startswith("<!--"):
446
+ node["type"] = "comment"
447
+ elif _CALLOUT_RE.match(content):
448
+ node["type"] = "callout"
449
+ node["folded"] = _CALLOUT_RE.match(content).group(2) == "-"
450
+ elif content.startswith(">"):
451
+ node["type"] = "quote"
452
+ elif content.startswith("|"):
453
+ node["type"] = "table"
454
+ elif content[:1] == "<" and len(content) > 1 and \
455
+ content[1].isascii() and content[1].isalpha():
456
+ node["type"] = "html"
457
+ elif _RULE_RE.match(content):
458
+ node["type"] = "rule"
459
+ else:
460
+ fm = _FENCE_OPEN_RE.match(content)
461
+ if fm:
462
+ node["type"] = "code"
463
+ fence = (node,
464
+ re.compile(r"^" + re.escape(fm.group(1)[0]) +
465
+ r"{%d,}\s*$" % len(fm.group(1))))
466
+ else:
467
+ prop = _is_property(content)
468
+ if prop:
469
+ node["type"] = "properties"
470
+ node["prop_key"] = prop[0]
471
+ while stack and stack[-1]["depth_val"] >= units:
472
+ stack.pop()
473
+ if stack:
474
+ stack[-1].setdefault("children", []).append(node)
475
+ else:
476
+ nodes.append(node)
477
+ stack.append(node)
478
+ i += 1
479
+ continue
480
+ # not a marker line: a property, a continuation line, or a raw root line
481
+ target = None
482
+ for cand in reversed(stack):
483
+ if units > cand["depth_val"]:
484
+ target = cand
485
+ break
486
+ if target is not None:
487
+ prop = _is_property(stripped)
488
+ if prop:
489
+ pnode = {"type": "properties", "depth": units,
490
+ "start": i + 1, "end": i + 1, "lines": [line],
491
+ "prop_key": prop[0], "depth_val": units}
492
+ target.setdefault("children", []).append(pnode)
493
+ else:
494
+ target["lines"].append(line)
495
+ target["end"] = i + 1
496
+ else:
497
+ nodes.append({"type": "bare", "depth": units, "start": i + 1,
498
+ "end": i + 1, "lines": [line]})
499
+ i += 1
500
+ return nodes, lines
501
+
502
+
503
+ def _indent_prefix_len(line: str) -> int:
504
+ for k, ch in enumerate(line):
505
+ if ch not in (" ", "\t"):
506
+ return k
507
+ return len(line)
508
+
509
+
510
+ def _flatten_outline(nodes):
511
+ """Flatten the outline tree into a list of (node, parent)."""
512
+ out = []
513
+
514
+ def rec(node, parent):
515
+ out.append((node, parent))
516
+ for child in node.get("children", []):
517
+ rec(child, node)
518
+
519
+ for node in nodes:
520
+ rec(node, None)
521
+ return out
522
+
523
+
524
+ def detect_dialect(text: str) -> str:
525
+ """Dialect detection (see docs/vocabulary.md).
526
+
527
+ After removing a leading frontmatter block, the input is outline when every
528
+ non-blank top-level (indent 0) line is a `- ` item or a kept line (property,
529
+ `%%` / `<!--` comment, or rule); otherwise it is document.
530
+ """
531
+ lines = _normalize_text(text).split("\n")
532
+ if lines and lines[-1] == "":
533
+ lines = lines[:-1]
534
+ n = len(lines)
535
+ i = 0
536
+ if n and lines[0] == "---":
537
+ j = 1
538
+ while j < n and lines[j] != "---" and lines[j].strip() != "":
539
+ j += 1
540
+ if j < n and lines[j] == "---":
541
+ i = j + 1
542
+ in_comment = None # "%%" or "<!--"
543
+ for k in range(i, n):
544
+ line = lines[k]
545
+ if not line.strip():
546
+ continue
547
+ units = _indent_units(line)
548
+ if in_comment is not None:
549
+ if in_comment == "%%" and line.rstrip().endswith("%%"):
550
+ in_comment = None
551
+ elif in_comment == "<!--" and "-->" in line:
552
+ in_comment = None
553
+ continue
554
+ if units == 0:
555
+ if line.startswith("- "):
556
+ continue
557
+ if line.startswith("%%"):
558
+ if not (line.rstrip().endswith("%%") and
559
+ len(line.rstrip()) > 2):
560
+ in_comment = "%%"
561
+ continue
562
+ if line.startswith("<!--"):
563
+ if "-->" not in line:
564
+ in_comment = "<!--"
565
+ continue
566
+ if _RULE_RE.match(line) or _is_property(line):
567
+ continue
568
+ return "document"
569
+ # an indented line may be an item or a continuation line
570
+ continue
571
+ return "outline"
572
+
573
+
574
+ def parse_blocks(text: str, dialect: str):
575
+ """For blocks output: (dialect, [flat list of nodes])."""
576
+ if dialect == "outline":
577
+ nodes, _ = _parse_outline(text)
578
+ flat = _flatten_outline(nodes)
579
+ return [(node["type"], node["depth"], node["start"], node["end"])
580
+ for node, _parent in flat]
581
+ nodes, _ = _parse_document(text)
582
+ return [(node["type"], node["depth"], node["start"], node["end"])
583
+ for node in nodes]
584
+
585
+
586
+ # ---------------------------------------------------------------- links
587
+
588
+ _LINK_RE = re.compile(
589
+ r"(!\[\[[^\[\]]*\]\])" # 1 embed
590
+ r"|\[\[([^\[\]]*)\]\]" # 2 wikilink target
591
+ r"|!\[([^\]]*)\]\(([^)\s]*)\)" # 3,4 image markdown
592
+ r"|\[([^\]]*)\]\(([^)\s]*)\)" # 5,6 markdown link
593
+ r"|\(\(([^()]+)\)\)" # 7 block ref
594
+ )
595
+ _INLINE_COMMENT_RE = re.compile(r"%%[^%].*?%%|%%%%|<!--.*?-->")
596
+
597
+
598
+ def _mask_inline_code(line: str) -> str:
599
+ out = list(line)
600
+ i = 0
601
+ while i < len(line):
602
+ if line[i] == "`":
603
+ j = line.find("`", i + 1)
604
+ if j == -1:
605
+ break
606
+ for k in range(i, j + 1):
607
+ out[k] = " "
608
+ i = j + 1
609
+ else:
610
+ i += 1
611
+ return "".join(out)
612
+
613
+
614
+ def _scan_lines(lines):
615
+ """Collect (link candidates, comment count, set of block IDs) line by line.
616
+
617
+ Text inside code blocks and inline code is not counted.
618
+ """
619
+ links = [] # (line_no, type, target)
620
+ comments = 0
621
+ block_ids = set()
622
+ fence = None
623
+ close_re = None
624
+ for idx, line in enumerate(lines, 1):
625
+ if fence is None:
626
+ m = _FENCE_OPEN_RE.match(line)
627
+ if m:
628
+ fence = m.group(1)[0]
629
+ close_re = re.compile(
630
+ r"^ {0,3}" + re.escape(m.group(1)[0]) +
631
+ r"{%d,}\s*$" % len(m.group(1)))
632
+ continue
633
+ else:
634
+ if close_re.match(line):
635
+ fence = None
636
+ continue
637
+ masked = _mask_inline_code(line)
638
+ for m in _LINK_RE.finditer(masked):
639
+ if m.group(1) is not None:
640
+ links.append((idx, "embed", m.group(1)[3:-2]))
641
+ elif m.group(2) is not None:
642
+ links.append((idx, "wikilink", m.group(2)))
643
+ elif m.group(4) is not None:
644
+ links.append((idx, "markdown_link", m.group(4)))
645
+ elif m.group(6) is not None:
646
+ links.append((idx, "markdown_link", m.group(6)))
647
+ elif m.group(7) is not None:
648
+ links.append((idx, "block_ref", m.group(7)))
649
+ # comment count: inline pairs (%%…%% and <!--…-->)
650
+ comments += len(_INLINE_COMMENT_RE.findall(masked))
651
+ # block ID: a trailing ^id
652
+ bm = _BLOCK_ID_TAIL_RE.search(masked.rstrip())
653
+ if bm:
654
+ block_ids.add(bm.group(1))
655
+ # an `id:: <value>` line is a block property (used to resolve ((id)))
656
+ prop = _is_property(line.strip())
657
+ if prop and prop[0].casefold() == "id":
658
+ value = prop[1].strip()
659
+ if value:
660
+ block_ids.add(value)
661
+ return links, comments, block_ids
662
+
663
+
664
+ def _url_decode(path: str) -> str:
665
+ def repl(m):
666
+ try:
667
+ return bytes([int(m.group(1), 16)]).decode("utf-8")
668
+ except (ValueError, UnicodeDecodeError):
669
+ return m.group(0)
670
+ return re.sub(r"%([0-9A-Fa-f]{2})", repl, path)
671
+
672
+
673
+ def _normalize_link_path(path: str, source_rel: str):
674
+ """Normalize the path part of a link to a vault-relative form.
675
+
676
+ In Markdown-form links, `./` and `../` resolve relative to the note's folder.
677
+ Wikilink-form targets are matched by path suffix from the vault root.
678
+ """
679
+ path = path.strip()
680
+ if path.startswith("<") and path.endswith(">") and len(path) >= 2:
681
+ path = path[1:-1]
682
+ path = _url_decode(path)
683
+ return path
684
+
685
+
686
+ def _path_segments(path: str):
687
+ return [seg for seg in path.split("/") if seg not in ("", ".")]
688
+
689
+
690
+ def _resolve_segments(segs, source_folder_segs):
691
+ """Resolve ./ and ../ relative to the note folder."""
692
+ out = list(source_folder_segs)
693
+ for seg in segs:
694
+ if seg == "..":
695
+ if out:
696
+ out.pop()
697
+ else:
698
+ out.append(seg)
699
+ return out
700
+
701
+
702
+ class _VaultIndex:
703
+ """Result of scanning a vault (notes, attachments, and resolution inputs)."""
704
+
705
+ def __init__(self):
706
+ self.notes = [] # {"rel", "lines", "nodes", ...}
707
+ self.attachments = [] # {"rel"}
708
+ self.block_ids = {} # id value -> [note rel]
709
+
710
+ def note_keys(self):
711
+ for note in self.notes:
712
+ yield note
713
+
714
+ def resolve_note_target(self, path_part, source_rel):
715
+ """Match a note name (NFC, case-insensitive, path matched by suffix)."""
716
+ if not path_part:
717
+ return []
718
+ key = _fold_key(path_part)
719
+ hits = []
720
+ for note in self.notes:
721
+ rel_no_ext = note["rel"][:-3] if note["rel"].lower().endswith(
722
+ ".md") else note["rel"]
723
+ if _fold_key(rel_no_ext) == key:
724
+ hits.append(note)
725
+ if hits:
726
+ return hits
727
+ # match at the end of the path (on component boundaries)
728
+ for note in self.notes:
729
+ rel_no_ext = note["rel"][:-3] if note["rel"].lower().endswith(
730
+ ".md") else note["rel"]
731
+ rel_key = _fold_key(rel_no_ext)
732
+ if rel_key.endswith("/" + key):
733
+ hits.append(note)
734
+ return hits
735
+
736
+ def resolve_attachment_target(self, path_part):
737
+ if not path_part:
738
+ return []
739
+ key = _fold_key(path_part)
740
+ hits = []
741
+ for att in self.attachments:
742
+ if _fold_key(att["rel"]) == key:
743
+ hits.append(att)
744
+ if hits:
745
+ return hits
746
+ for att in self.attachments:
747
+ if _fold_key(att["rel"]).endswith("/" + key):
748
+ hits.append(att)
749
+ return hits
750
+
751
+ def resolve_attachment_basename(self, base):
752
+ key = _fold_key(base)
753
+ return [a for a in self.attachments if _fold_key(
754
+ a["rel"].rsplit("/", 1)[-1]) == key]
755
+
756
+ def resolve_note_basename(self, base):
757
+ key = _fold_key(base)
758
+ hits = []
759
+ for note in self.notes:
760
+ base_rel = note["rel"].rsplit("/", 1)[-1]
761
+ if base_rel.lower().endswith(".md"):
762
+ base_rel = base_rel[:-3]
763
+ if _fold_key(base_rel) == key:
764
+ hits.append(note)
765
+ return hits
766
+
767
+
768
+ def _classify_link_target(target: str):
769
+ """Return (kind, path_part, fragment). kind: note|attach|none.
770
+
771
+ Text after `|` is an alias (display name) and is ignored. Text after `#` is the fragment.
772
+ Fragments on attachments (such as #page=3) are not checked.
773
+ """
774
+ t = target.split("|", 1)[0].strip()
775
+ if not t:
776
+ return "none", "", ""
777
+ if "#" in t:
778
+ path_part, fragment = t.split("#", 1)
779
+ else:
780
+ path_part, fragment = t, ""
781
+ base = path_part.rsplit("/", 1)[-1]
782
+ if base.lower().endswith(".md"):
783
+ return "note", path_part[:-3], fragment
784
+ if "." in base:
785
+ return "attach", path_part, fragment
786
+ return "note", path_part, fragment
787
+
788
+
789
+ def _resolve_one(link_type, raw_target, source_rel, vault: _VaultIndex):
790
+ """Resolve one link and return (state, target_note_rel|None)."""
791
+ if link_type == "block_ref":
792
+ target = raw_target.strip()
793
+ if not target:
794
+ return "broken", None
795
+ owners = vault.block_ids.get(target, [])
796
+ if len(owners) == 1:
797
+ return "resolved", owners[0]
798
+ if not owners:
799
+ return "broken", None
800
+ return "ambiguous", None
801
+
802
+ kind, path_part, fragment = _classify_link_target(raw_target)
803
+ if kind == "none":
804
+ return "broken", None
805
+ path_part = _normalize_link_path(path_part, source_rel)
806
+ if _SCHEME_RE.match(path_part):
807
+ # external URLs are not counted (a safeguard; callers exclude them)
808
+ return "broken", None
809
+ source_folder = source_rel.rsplit("/", 1)[0] if "/" in source_rel else ""
810
+ segs = _path_segments(path_part)
811
+ if path_part.startswith(("./", "../")) or path_part in (".", ".."):
812
+ segs = _resolve_segments(segs, _path_segments(source_folder))
813
+ joined = "/".join(segs)
814
+ else:
815
+ joined = "/".join(segs)
816
+
817
+ if kind == "attach":
818
+ if "/" in joined:
819
+ hits = vault.resolve_attachment_target(joined)
820
+ else:
821
+ hits = vault.resolve_attachment_basename(joined)
822
+ if len(hits) == 1:
823
+ return "resolved", None # attachment: fragment not checked
824
+ if not hits:
825
+ return "broken", None
826
+ return "ambiguous", None
827
+
828
+ # note
829
+ if not joined:
830
+ # the [[#section]] form: a fragment within the same note
831
+ hits = [n for n in vault.notes if n["rel"] == source_rel]
832
+ elif "/" in joined:
833
+ hits = vault.resolve_note_target(joined, source_rel)
834
+ else:
835
+ hits = vault.resolve_note_basename(joined)
836
+ if len(hits) == 1:
837
+ note = hits[0]
838
+ if fragment:
839
+ if fragment.startswith("^"):
840
+ bid = fragment[1:]
841
+ if bid in note["block_ids"]:
842
+ return "resolved", note["rel"]
843
+ return "fragment_missing", note["rel"]
844
+ parts = [p for p in fragment.split("#") if p]
845
+ headings = {_fold_key(h) for h in note["headings"]}
846
+ if parts and all(_fold_key(p) in headings for p in parts):
847
+ return "resolved", note["rel"]
848
+ return "fragment_missing", note["rel"]
849
+ return "resolved", note["rel"]
850
+ if not hits:
851
+ return "broken", None
852
+ return "ambiguous", None
853
+
854
+
855
+ # ---------------------------------------------------------------- index
856
+
857
+
858
+ def _walk_vault(root: Path, include_hidden_dirs: bool):
859
+ """Return (files, excluded_dirs, symlink_skipped).
860
+
861
+ files are relative paths (POSIX form) in Unicode code point order.
862
+ By default only the four folders in DEFAULT_EXCLUDED_DIR_NAMES are excluded.
863
+ When include_hidden_dirs=True, those four folders are
864
+ included as well.
865
+ """
866
+ excluded_dirs = 0
867
+ symlink_skipped = 0
868
+ files = []
869
+
870
+ def rec(dirpath: Path, rel_parts):
871
+ nonlocal excluded_dirs, symlink_skipped
872
+ try:
873
+ entries = list(os.scandir(dirpath))
874
+ except OSError:
875
+ return
876
+ entries.sort(key=lambda e: e.name)
877
+ for entry in entries:
878
+ name = entry.name
879
+ try:
880
+ is_dir = entry.is_dir(follow_symlinks=False)
881
+ is_link = entry.is_symlink()
882
+ except OSError:
883
+ continue
884
+ if is_link:
885
+ symlink_skipped += 1
886
+ continue
887
+ excluded = (not include_hidden_dirs) and \
888
+ (name in DEFAULT_EXCLUDED_DIR_NAMES)
889
+ if is_dir:
890
+ if excluded:
891
+ excluded_dirs += 1
892
+ continue
893
+ rec(Path(entry.path), rel_parts + [name])
894
+ else:
895
+ if excluded:
896
+ continue
897
+ files.append("/".join(rel_parts + [name]))
898
+
899
+ rec(root, [])
900
+ files.sort()
901
+ return files, excluded_dirs, symlink_skipped
902
+
903
+
904
+ def _heading_texts(nodes):
905
+ out = []
906
+ for node in nodes:
907
+ if node["type"] == "heading":
908
+ text = node.get("heading_text") or ""
909
+ m = _HEADING_RE.match(text)
910
+ if m:
911
+ out.append(m.group(2))
912
+ return out
913
+
914
+
915
+ def index_vault(path, *, include_hidden_dirs=False,
916
+ max_file_bytes=DEFAULT_MAX_FILE_BYTES,
917
+ max_files=DEFAULT_MAX_FILES, no_names=False):
918
+ """Observe a vault and return a dict in the same shape as the CLI (notes_version: 1)."""
919
+ root = Path(path)
920
+ if not root.exists():
921
+ return _error_dict("index", "input_not_found")
922
+ if not root.is_dir():
923
+ return _error_dict("index", "not_a_directory")
924
+
925
+ files, excluded_dirs, symlink_skipped = _walk_vault(
926
+ root, include_hidden_dirs)
927
+ skipped = {reason: 0 for reason in SKIP_REASONS}
928
+ skipped["symlink_skipped"] = symlink_skipped
929
+ if len(files) > max_files:
930
+ skipped["file_limit"] = len(files) - max_files
931
+ files = files[:max_files]
932
+
933
+ vault = _VaultIndex()
934
+ notes_data = []
935
+ for rel_path in files:
936
+ if rel_path.lower().endswith(".md"):
937
+ vault.notes.append({"rel": rel_path})
938
+ else:
939
+ vault.attachments.append({"rel": rel_path})
940
+
941
+ notes_sorted = {n["rel"]: n for n in vault.notes}
942
+ for rel_path in files:
943
+ if not rel_path.lower().endswith(".md"):
944
+ continue
945
+ p = root.joinpath(*rel_path.split("/"))
946
+ data, reason = _read_note_bytes(p, max_file_bytes)
947
+ if reason == "too_large":
948
+ skipped["too_large"] += 1
949
+ continue
950
+ if reason == "unreadable":
951
+ skipped["unreadable"] += 1
952
+ continue
953
+ text, decode_reason = _decode_policy(data)
954
+ if decode_reason is not None:
955
+ skipped["unsupported_encoding"] += 1
956
+ continue
957
+ text = _normalize_text(text)
958
+ lines = text.split("\n")
959
+ if lines and lines[-1] == "":
960
+ lines = lines[:-1]
961
+ dialect = detect_dialect(text)
962
+ if dialect == "outline":
963
+ nodes, _ = _parse_outline(text)
964
+ flat = _flatten_outline(nodes)
965
+ headings = []
966
+ for node, _parent in flat:
967
+ if node["type"] == "heading":
968
+ m = _HEADING_RE.match(node.get("heading_text") or "")
969
+ if m:
970
+ headings.append(m.group(2))
971
+ else:
972
+ nodes, _ = _parse_document(text)
973
+ headings = _heading_texts(nodes)
974
+ links, inline_comments, block_ids = _scan_lines(lines)
975
+ if dialect == "outline":
976
+ node_view = [node for node, _parent in flat]
977
+ else:
978
+ node_view = nodes
979
+ folded = 0
980
+ for node in node_view:
981
+ if node["type"] == "callout" and node.get("folded"):
982
+ folded += 1
983
+ if node["type"] == "properties" and \
984
+ node.get("prop_key", "").casefold() == "collapsed":
985
+ folded += 1
986
+ comments = inline_comments
987
+ for node in node_view:
988
+ if node["type"] == "comment":
989
+ comments += 1
990
+ info = {"rel": rel_path, "lines": lines, "headings": headings,
991
+ "block_ids": block_ids, "links": links,
992
+ "collapsed": folded, "comments": comments}
993
+ notes_sorted[rel_path].update(info)
994
+
995
+ vault.block_ids = {}
996
+ for note in vault.notes:
997
+ for bid in note.get("block_ids", set()):
998
+ vault.block_ids.setdefault(bid, []).append(note["rel"])
999
+
1000
+ link_rows = []
1001
+ per_note = {}
1002
+ for note in vault.notes:
1003
+ if "links" not in note:
1004
+ continue
1005
+ counts = {state: 0 for state in LINK_STATES}
1006
+ by_type = {lt: 0 for lt in LINK_TYPES}
1007
+ for line_no, link_type, raw_target in note["links"]:
1008
+ state, target_rel = _resolve_one(link_type, raw_target,
1009
+ note["rel"], vault)
1010
+ counts[state] += 1
1011
+ by_type[link_type] += 1
1012
+ if state != "resolved":
1013
+ name = raw_target.split("|", 1)[0].strip()
1014
+ row = {"note": note["rel"], "line": line_no,
1015
+ "link_type": link_type, "state": state}
1016
+ if not no_names and name:
1017
+ row["name"] = name
1018
+ link_rows.append(row)
1019
+ elif target_rel and target_rel != note["rel"]:
1020
+ target = notes_sorted.get(target_rel)
1021
+ if target is not None:
1022
+ target["backlinks"] = target.get("backlinks", 0) + 1
1023
+ per_note[note["rel"]] = (counts, by_type)
1024
+
1025
+ notes_out = []
1026
+ for note in vault.notes:
1027
+ if "links" not in note:
1028
+ continue
1029
+ counts, by_type = per_note[note["rel"]]
1030
+ notes_out.append({
1031
+ "path": note["rel"],
1032
+ "links": counts,
1033
+ "links_by_type": by_type,
1034
+ "backlinks": note.get("backlinks", 0),
1035
+ "collapsed_blocks": note.get("collapsed", 0),
1036
+ "comments": note.get("comments", 0),
1037
+ })
1038
+
1039
+ totals_links = {lt: 0 for lt in LINK_TYPES}
1040
+ totals_states = {st: 0 for st in LINK_STATES}
1041
+ for note in vault.notes:
1042
+ if "links" not in note:
1043
+ continue
1044
+ counts, by_type = per_note[note["rel"]]
1045
+ for lt, c in by_type.items():
1046
+ totals_links[lt] += c
1047
+ for st, c in counts.items():
1048
+ totals_states[st] += c
1049
+
1050
+ orphan_count = sum(1 for n in notes_out if n["backlinks"] == 0)
1051
+ link_rows.sort(key=lambda r: (r["note"], r["line"], r["link_type"],
1052
+ r["state"], r.get("name", "")))
1053
+
1054
+ return {
1055
+ "notes_version": NOTES_VERSION,
1056
+ "command": "index",
1057
+ "totals": {
1058
+ "notes": len(notes_out),
1059
+ "links": totals_links,
1060
+ "link_states": totals_states,
1061
+ "orphan_notes": orphan_count,
1062
+ "excluded_dirs": excluded_dirs,
1063
+ "skipped": skipped,
1064
+ },
1065
+ "notes": notes_out,
1066
+ "broken_links": link_rows,
1067
+ "exit_code": 0,
1068
+ }
1069
+
1070
+
1071
+ # ---------------------------------------------------------------- blocks
1072
+
1073
+
1074
+ def block_tree(text=None, *, path=None, dialect="auto"):
1075
+ """Return the block tree in the same shape as the CLI (notes_version: 1).
1076
+
1077
+ Exit codes are 0 / 2. Note bodies are not emitted.
1078
+ """
1079
+ if text is None:
1080
+ if path is None:
1081
+ return _error_dict("blocks", "input_not_found")
1082
+ p = Path(path)
1083
+ if not p.exists():
1084
+ return _error_dict("blocks", "input_not_found")
1085
+ data, reason = _read_note_bytes(p, DEFAULT_MAX_FILE_BYTES)
1086
+ if reason is not None:
1087
+ return _error_dict("blocks", reason if reason != "too_large"
1088
+ else "too_large")
1089
+ text, decode_reason = _decode_policy(data)
1090
+ if decode_reason is not None:
1091
+ return _error_dict("blocks", "unsupported_encoding")
1092
+ if dialect not in ("auto", "document", "outline"):
1093
+ return _error_dict("blocks", "invalid_option")
1094
+ if dialect == "auto":
1095
+ dialect = detect_dialect(text)
1096
+ else:
1097
+ detected = detect_dialect(text)
1098
+ if detected != dialect:
1099
+ return _error_dict("blocks", "dialect_mismatch")
1100
+ rows = parse_blocks(text, dialect)
1101
+ blocks = [{"type": t, "depth": d, "lines": [s, e]}
1102
+ for t, d, s, e in rows]
1103
+ return {
1104
+ "notes_version": NOTES_VERSION,
1105
+ "command": "blocks",
1106
+ "dialect": dialect,
1107
+ "blocks": blocks,
1108
+ "exit_code": 0,
1109
+ }
1110
+
1111
+
1112
+ # ---------------------------------------------------------------- convert
1113
+
1114
+
1115
+ def _doc_to_outline_rows(text: str, indent_unit: str):
1116
+ """Build the line sequence for document -> outline.
1117
+
1118
+ rows: (kind, depth, text) where kind is "item" / "cont" / "bare".
1119
+ Also returns the counts of kept items and shape changes.
1120
+ """
1121
+ nodes, lines = _parse_document(text)
1122
+ rows = []
1123
+ kept = {word: 0 for word in KEPT_WORDS}
1124
+ shape = {word: 0 for word in SHAPE_WORDS}
1125
+ heading_stack = [] # (level, item_depth, row_id)
1126
+ heading_row_id = -1 # row number of the current heading item (-1 for the root)
1127
+ item_stack = [] # (nesting, item_depth, parent_node)
1128
+ parents_with_items = set() # identities of parents that already received an item
1129
+ para_node = None # previous paragraph (within the same section)
1130
+ prev_was_para = False
1131
+ para_depth = None
1132
+
1133
+ for node in nodes:
1134
+ ntype = node["type"]
1135
+ if ntype == "frontmatter":
1136
+ kept["kept_as_text_frontmatter"] += 1
1137
+ for ln in node["lines"]:
1138
+ rows.append(("bare", 0, ln))
1139
+ prev_was_para = False
1140
+ para_depth = None
1141
+ para_node = None
1142
+ item_stack = []
1143
+ continue
1144
+ if ntype == "heading":
1145
+ m = _HEADING_RE.match(node["heading_text"])
1146
+ level = len(m.group(1))
1147
+ while heading_stack and heading_stack[-1][0] >= level:
1148
+ heading_stack.pop()
1149
+ item_depth = len(heading_stack)
1150
+ heading_row_id = len(rows)
1151
+ heading_stack.append((level, item_depth, heading_row_id))
1152
+ rows.append(("item", item_depth, node["heading_text"]))
1153
+ item_stack = []
1154
+ prev_was_para = False
1155
+ para_depth = None
1156
+ para_node = None
1157
+ continue
1158
+ if ntype == "properties":
1159
+ key = node.get("prop_key", "")
1160
+ kept[_property_kept_word(key)] += 1
1161
+ rows.append(("bare", 0, node["lines"][0]))
1162
+ prev_was_para = False
1163
+ para_depth = None
1164
+ para_node = None
1165
+ continue
1166
+ if ntype == "comment":
1167
+ kept["kept_as_text_unsupported"] += 1
1168
+ for ln in node["lines"]:
1169
+ rows.append(("bare", 0, ln))
1170
+ prev_was_para = False
1171
+ para_depth = None
1172
+ para_node = None
1173
+ continue
1174
+ if ntype == "rule":
1175
+ kept["kept_as_text_unsupported"] += 1
1176
+ rows.append(("bare", 0, node["lines"][0]))
1177
+ prev_was_para = False
1178
+ para_depth = None
1179
+ para_node = None
1180
+ continue
1181
+ if ntype in ("code", "quote", "table", "html", "callout"):
1182
+ if ntype == "callout":
1183
+ kept["kept_as_text_unsupported"] += 1
1184
+ d = len(heading_stack)
1185
+ rows.append(("item", d, node["lines"][0]))
1186
+ for ln in node["lines"][1:]:
1187
+ rows.append(("cont", d + 1, ln))
1188
+ prev_was_para = False
1189
+ para_depth = None
1190
+ para_node = None
1191
+ item_stack = []
1192
+ continue
1193
+ if ntype == "paragraph":
1194
+ content = node["lines"][0]
1195
+ if _BLOCK_ID_TAIL_RE.search(content.rstrip()):
1196
+ kept["kept_as_text_block_id"] += 1
1197
+ d = len(heading_stack)
1198
+ rows.append(("item", d, content))
1199
+ for ln in node["lines"][1:]:
1200
+ rows.append(("cont", d + 1, ln))
1201
+ prev_was_para = True
1202
+ para_depth = d
1203
+ para_node = node
1204
+ item_stack = []
1205
+ continue
1206
+ if ntype == "list_item":
1207
+ nesting = node["nesting"]
1208
+ while item_stack and item_stack[-1][0] >= nesting:
1209
+ item_stack.pop()
1210
+ content = node["content"]
1211
+ if node.get("ordered"):
1212
+ shape["ordered_list_became_bullets"] += 1
1213
+ if _BLOCK_ID_TAIL_RE.search(content.rstrip()):
1214
+ kept["kept_as_text_block_id"] += 1
1215
+ if item_stack:
1216
+ my_depth = item_stack[-1][1] + 1
1217
+ parent_id = ("item", id(item_stack[-1][2]))
1218
+ elif prev_was_para:
1219
+ my_depth = para_depth + 1
1220
+ parent_id = ("para", id(para_node))
1221
+ else:
1222
+ # a list directly under a heading (or the root): becomes a paragraph on return
1223
+ my_depth = len(heading_stack)
1224
+ parent_id = ("heading", heading_row_id)
1225
+ shape["list_became_paragraphs"] += 1
1226
+ if node.get("after_blank") and \
1227
+ parent_id in parents_with_items:
1228
+ shape["lists_merged"] += 1
1229
+ parents_with_items.add(parent_id)
1230
+ rows.append(("item", my_depth, content))
1231
+ item_stack.append((nesting, my_depth, node))
1232
+ # paragraph context persists across list items (another run separated by
1233
+ # blank lines also attaches to the same paragraph -> counted in lists_merged)
1234
+ continue
1235
+ return rows, kept, shape
1236
+
1237
+
1238
+ def _rows_to_text(rows, indent_unit: str) -> str:
1239
+ out = []
1240
+ for kind, depth, text in rows:
1241
+ if kind == "item":
1242
+ out.append(indent_unit * depth + "- " + text)
1243
+ elif kind == "cont":
1244
+ out.append(indent_unit * depth + text)
1245
+ else:
1246
+ out.append(text)
1247
+ if not out:
1248
+ return ""
1249
+ return "\n".join(out) + "\n"
1250
+
1251
+
1252
+ def _outline_to_document_rows(text: str):
1253
+ """Build the block sequence for outline -> document.
1254
+
1255
+ blocks: [list of lines] (blocks are joined by one blank line).
1256
+ """
1257
+ nodes, lines = _parse_outline(text)
1258
+ blocks = []
1259
+ kept = {word: 0 for word in KEPT_WORDS}
1260
+ shape = {word: 0 for word in SHAPE_WORDS}
1261
+
1262
+ def item_continuation_lines(node):
1263
+ """Return the continuation lines of an item (raw lines that are not child nodes)."""
1264
+ child_starts = set()
1265
+ for child in node.get("children", []):
1266
+ child_starts.add(child["start"])
1267
+ out = []
1268
+ for k, ln in enumerate(node["lines"][1:], node["start"] + 1):
1269
+ if k in child_starts:
1270
+ continue
1271
+ out.append(ln)
1272
+ return out
1273
+
1274
+ def item_text(node):
1275
+ """Return the item text (the string after the marker). Raw lines pass through."""
1276
+ if node.get("heading_text") is not None:
1277
+ return node["heading_text"]
1278
+ if "content" in node:
1279
+ return node["content"]
1280
+ return node["lines"][0]
1281
+
1282
+ _VERBATIM_PREFIXES = ("```", "~~~", ">", "|", "%%", "<!--")
1283
+
1284
+ def is_verbatim_text(t):
1285
+ if t.startswith(_VERBATIM_PREFIXES):
1286
+ return True
1287
+ return t[:1] == "<" and len(t) > 1 and t[1].isascii() and \
1288
+ t[1].isalpha()
1289
+
1290
+ def emit_item(node):
1291
+ """Emit one item in content context into the block sequence."""
1292
+ prop_children = [c for c in node.get("children", [])
1293
+ if c["type"] == "properties"]
1294
+ item_children = [c for c in node.get("children", [])
1295
+ if c["type"] != "properties"]
1296
+
1297
+ def flush_own_block():
1298
+ conts = [item_continuation_lines(node)]
1299
+ block = [item_text(node)]
1300
+ for ln in conts[0]:
1301
+ block.append(_strip_units(ln, node["depth"] + 1))
1302
+ if _BLOCK_ID_TAIL_RE.search(block[-1].rstrip()) or \
1303
+ any(_BLOCK_ID_TAIL_RE.search(
1304
+ _strip_units(ln, node["depth"] + 1).rstrip())
1305
+ for ln in conts[0]):
1306
+ kept["kept_as_text_block_id"] += 1
1307
+ return block
1308
+
1309
+ def emit_list_lines(children, indent):
1310
+ lines_out = []
1311
+ for child in children:
1312
+ lines_out.append(indent + "- " + item_text(child))
1313
+ for ln in item_continuation_lines(child):
1314
+ lines_out.append(indent + " " +
1315
+ _strip_units(ln, child["depth"] + 1))
1316
+ sub_items = [c for c in child.get("children", [])
1317
+ if c["type"] != "properties"]
1318
+ if sub_items:
1319
+ lines_out.extend(emit_list_lines(
1320
+ sub_items, indent + " "))
1321
+ for pc in [c for c in child.get("children", [])
1322
+ if c["type"] == "properties"]:
1323
+ for ln in pc["lines"]:
1324
+ lines_out.append(ln)
1325
+ return lines_out
1326
+
1327
+ if node["type"] == "properties":
1328
+ blocks.append(list(node["lines"]))
1329
+ kept[_property_kept_word(node.get("prop_key", ""))] += 1
1330
+ return
1331
+
1332
+ if node["type"] == "heading":
1333
+ blocks.append([node["heading_text"]])
1334
+ for child in item_children:
1335
+ emit_item(child)
1336
+ for pc in prop_children:
1337
+ for ln in pc["lines"]:
1338
+ blocks.append([ln])
1339
+ return
1340
+
1341
+ text0 = item_text(node)
1342
+ if is_verbatim_text(text0):
1343
+ blocks.append(flush_own_block())
1344
+ for pc in prop_children:
1345
+ for ln in pc["lines"]:
1346
+ blocks.append([ln])
1347
+ return
1348
+
1349
+ if item_children:
1350
+ blocks.append(flush_own_block())
1351
+ blocks.append(emit_list_lines(item_children, ""))
1352
+ else:
1353
+ blocks.append(flush_own_block())
1354
+ for pc in prop_children:
1355
+ for ln in pc["lines"]:
1356
+ blocks.append([ln])
1357
+
1358
+ i = 0
1359
+ while i < len(nodes):
1360
+ node = nodes[i]
1361
+ if node["type"] == "bare":
1362
+ rows_ = list(node["lines"])
1363
+ while i + 1 < len(nodes) and nodes[i + 1]["type"] == "bare":
1364
+ i += 1
1365
+ rows_.extend(nodes[i]["lines"])
1366
+ blocks.append(rows_)
1367
+ if rows_[0].strip() == "---" and any(
1368
+ ln.strip() == "---" for ln in rows_[1:]):
1369
+ kept["kept_as_text_frontmatter"] += 1
1370
+ elif rows_[0].startswith("%%") or rows_[0].startswith("<!--"):
1371
+ kept["kept_as_text_unsupported"] += 1
1372
+ elif _RULE_RE.match(rows_[0]):
1373
+ kept["kept_as_text_unsupported"] += 1
1374
+ elif _is_property(rows_[0].strip()):
1375
+ kept[_property_kept_word(
1376
+ _is_property(rows_[0].strip())[0])] += 1
1377
+ else:
1378
+ emit_item(node)
1379
+ i += 1
1380
+ return blocks, kept, shape
1381
+
1382
+
1383
+ def _blocks_to_text(blocks) -> str:
1384
+ if not blocks:
1385
+ return ""
1386
+ return "\n\n".join("\n".join(b) for b in blocks) + "\n"
1387
+
1388
+
1389
+ def convert_text(text, to, *, indent="2", strict=False):
1390
+ """Convert text (a pure function; the result is written to a new file).
1391
+
1392
+ Returns the same shape as the CLI (notes_version: 1) plus output_text.
1393
+ Exit codes: 0 = converted / 1 = kept or shape change under --strict /
1394
+ 2 = cannot run.
1395
+ """
1396
+ if to not in ("outline", "document"):
1397
+ return _error_dict("convert", "invalid_option")
1398
+ if indent not in ("tab", "2", "4"):
1399
+ return _error_dict("convert", "invalid_option")
1400
+ indent_unit = {"tab": "\t", "2": " ", "4": " "}[indent]
1401
+ input_dialect = detect_dialect(text)
1402
+ if input_dialect == to:
1403
+ return _error_dict("convert", "already_in_target")
1404
+ if to == "outline":
1405
+ rows, kept, shape = _doc_to_outline_rows(text, indent_unit)
1406
+ output_text = _rows_to_text(rows, indent_unit)
1407
+ else:
1408
+ blocks, kept, shape = _outline_to_document_rows(text)
1409
+ output_text = _blocks_to_text(blocks)
1410
+ exit_code = 0
1411
+ if strict and (any(kept.values()) or any(shape.values())):
1412
+ exit_code = 1
1413
+ result = {
1414
+ "notes_version": NOTES_VERSION,
1415
+ "command": "convert",
1416
+ "input_dialect": input_dialect,
1417
+ "to": to,
1418
+ "indent": indent if to == "outline" else "2",
1419
+ "kept": kept,
1420
+ "shape_changes": shape,
1421
+ "output_text": output_text,
1422
+ "exit_code": exit_code,
1423
+ }
1424
+ return result
1425
+
1426
+
1427
+ def convert_file(path, to, out_path, *, indent="2", strict=False):
1428
+ """Convert a file and write the result to a new file. The original is not modified."""
1429
+ src = Path(path)
1430
+ if not src.exists():
1431
+ return _error_dict("convert", "input_not_found")
1432
+ out = Path(out_path)
1433
+ if out.exists():
1434
+ return _error_dict("convert", "output_exists")
1435
+ data, reason = _read_note_bytes(src, DEFAULT_MAX_FILE_BYTES)
1436
+ if reason == "too_large":
1437
+ return _error_dict("convert", "too_large")
1438
+ if reason == "unreadable":
1439
+ return _error_dict("convert", "unreadable")
1440
+ text, decode_reason = _decode_policy(data)
1441
+ if decode_reason is not None:
1442
+ return _error_dict("convert", "unsupported_encoding")
1443
+ result = convert_text(_normalize_text(text), to, indent=indent,
1444
+ strict=strict)
1445
+ if result.get("error"):
1446
+ return result
1447
+ if result["exit_code"] == 0:
1448
+ out.write_bytes(result["output_text"].encode("utf-8"))
1449
+ if not os.path.isabs(str(out_path)):
1450
+ # no absolute path in the output (shown only when given as relative)
1451
+ result["output"] = str(out_path)
1452
+ return result
1453
+
1454
+
1455
+ # ---------------------------------------------------------------- self-check
1456
+
1457
+ _SELF_CHECK_VAULT = {
1458
+ "a.md": (
1459
+ "# a\n"
1460
+ "- [[b]]\n"
1461
+ "- [[ghost]]\n"
1462
+ "- ![[fig.png]]\n"
1463
+ "本文 %%コメント%% 付き\n"
1464
+ ),
1465
+ "b.md": (
1466
+ "# b\n"
1467
+ "id:: bid-1\n"
1468
+ "((bid-1)) への自己参照\n"
1469
+ "^bid-1\n"
1470
+ ),
1471
+ }
1472
+ _SELF_CHECK_ATTACHMENT = {"fig.png": b"\x89PNG self-check"}
1473
+
1474
+ _SELF_CHECK_CANONICAL = (
1475
+ "# 題\n"
1476
+ "\n"
1477
+ "導入の段落です。\n"
1478
+ "\n"
1479
+ "- 項目 A\n"
1480
+ " - 子 A1\n"
1481
+ "- 項目 B\n"
1482
+ "\n"
1483
+ "```py\n"
1484
+ "code = 1\n"
1485
+ "```\n"
1486
+ "\n"
1487
+ "| 列 A | 列 B |\n"
1488
+ "| --- | --- |\n"
1489
+ "| 1 | 2 |\n"
1490
+ "\n"
1491
+ "> 引用 1 行目\n"
1492
+ )
1493
+
1494
+
1495
+ def _self_check():
1496
+ """Verify the bundled small sample against expectations (0 / 1 / 2)."""
1497
+ try:
1498
+ with tempfile.TemporaryDirectory() as td:
1499
+ root = Path(td)
1500
+ write_vault_files(root, _SELF_CHECK_VAULT,
1501
+ _SELF_CHECK_ATTACHMENT)
1502
+ idx = index_vault(root)
1503
+ if idx["exit_code"] != 0:
1504
+ return 1, "index failed"
1505
+ t = idx["totals"]
1506
+ if t["notes"] != 2:
1507
+ return 1, f"notes {t['notes']} != 2"
1508
+ if t["links"] != {"wikilink": 2, "embed": 1, "markdown_link": 0,
1509
+ "block_ref": 1}:
1510
+ return 1, f"links {t['links']}"
1511
+ if t["link_states"] != {"resolved": 3, "broken": 1,
1512
+ "ambiguous": 0, "fragment_missing": 0}:
1513
+ return 1, f"link_states {t['link_states']}"
1514
+ if t["excluded_dirs"] != 0:
1515
+ return 1, "excluded_dirs"
1516
+ a_note = [n for n in idx["notes"] if n["path"] == "a.md"][0]
1517
+ if a_note["comments"] != 1:
1518
+ return 1, f"comments {a_note['comments']}"
1519
+ if idx["broken_links"][0]["state"] != "broken":
1520
+ return 1, "broken row"
1521
+ blocks = block_tree(_SELF_CHECK_OUTLINE_SAMPLE)
1522
+ if blocks["exit_code"] != 0 or blocks["dialect"] != "outline":
1523
+ return 1, "blocks dialect"
1524
+ types = [b["type"] for b in blocks["blocks"]]
1525
+ if types != ["list_item", "list_item", "properties",
1526
+ "list_item", "properties", "list_item"]:
1527
+ return 1, f"blocks types {types}"
1528
+ conv1 = convert_text(_SELF_CHECK_CANONICAL, "outline")
1529
+ if conv1["exit_code"] != 0:
1530
+ return 1, "convert outline failed"
1531
+ back = convert_text(conv1["output_text"], "document")
1532
+ if back["exit_code"] != 0:
1533
+ return 1, "convert document failed"
1534
+ if back["output_text"].encode("utf-8") != \
1535
+ _SELF_CHECK_CANONICAL.encode("utf-8"):
1536
+ return 1, "P1 round trip mismatch"
1537
+ again = convert_text(back["output_text"], "outline")
1538
+ again_back = convert_text(again["output_text"], "document")
1539
+ if again_back["output_text"].encode("utf-8") != \
1540
+ back["output_text"].encode("utf-8"):
1541
+ return 1, "P2 fixed point mismatch"
1542
+ except Exception as exc: # noqa: BLE001 — the self-check also reports unexpected defects
1543
+ return 1, f"unexpected: {exc.__class__.__name__}"
1544
+ return 0, "self-check ok"
1545
+
1546
+
1547
+ _SELF_CHECK_OUTLINE_SAMPLE = (
1548
+ "- 項目 1\n"
1549
+ "\t- 子ブロック\n"
1550
+ "\t collapsed:: true\n"
1551
+ "\t- 項目 2\n"
1552
+ "\t id:: abc-123\n"
1553
+ "- 項目 3\n"
1554
+ )
1555
+
1556
+
1557
+ def write_vault_files(root: Path, files, binaries=None):
1558
+ for rel_key, text in files.items():
1559
+ p = root.joinpath(*rel_key.split("/"))
1560
+ p.parent.mkdir(parents=True, exist_ok=True)
1561
+ p.write_bytes(text.encode("utf-8"))
1562
+ for rel_key, data in (binaries or {}).items():
1563
+ p = root.joinpath(*rel_key.split("/"))
1564
+ p.parent.mkdir(parents=True, exist_ok=True)
1565
+ p.write_bytes(data)
1566
+
1567
+
1568
+ # ---------------------------------------------------------------- output and CLI
1569
+
1570
+
1571
+ def _error_dict(command, word):
1572
+ return {"notes_version": NOTES_VERSION, "command": command,
1573
+ "error": word, "exit_code": 2}
1574
+
1575
+
1576
+ def _dump_json(data) -> bytes:
1577
+ payload = {k: v for k, v in data.items() if k != "output_text"}
1578
+ return (json.dumps(payload, ensure_ascii=False, sort_keys=True,
1579
+ indent=2) + "\n").encode("utf-8")
1580
+
1581
+
1582
+ def _write_out(data) -> None:
1583
+ sys.stdout.buffer.write(data)
1584
+ sys.stdout.buffer.flush()
1585
+
1586
+
1587
+ def _index_text(data) -> str:
1588
+ t = data["totals"]
1589
+ lines = [
1590
+ f"notes {t['notes']}",
1591
+ "links " + " ".join(f"{k}={t['links'][k]}" for k in LINK_TYPES),
1592
+ "link_states " + " ".join(f"{k}={t['link_states'][k]}"
1593
+ for k in LINK_STATES),
1594
+ f"orphan_notes {t['orphan_notes']}",
1595
+ f"excluded_dirs {t['excluded_dirs']}",
1596
+ "skipped " + " ".join(f"{k}={t['skipped'][k]}"
1597
+ for k in SKIP_REASONS),
1598
+ ]
1599
+ for n in data["notes"]:
1600
+ lines.append(
1601
+ f"note {n['path']} "
1602
+ + " ".join(f"{k}={n['links'][k]}" for k in LINK_STATES)
1603
+ + f" backlinks={n['backlinks']}"
1604
+ + f" collapsed={n['collapsed_blocks']}"
1605
+ + f" comments={n['comments']}")
1606
+ for row in data["broken_links"]:
1607
+ base = f"broken {row['note']}:{row['line']} {row['link_type']} " \
1608
+ f"{row['state']}"
1609
+ if "name" in row:
1610
+ base += f" {row['name']}"
1611
+ lines.append(base)
1612
+ return "\n".join(lines) + "\n"
1613
+
1614
+
1615
+ def _blocks_text(data) -> str:
1616
+ lines = [f"dialect {data['dialect']}"]
1617
+ for b in data["blocks"]:
1618
+ lines.append(f"block {b['type']} depth={b['depth']} "
1619
+ f"lines={b['lines'][0]}-{b['lines'][1]}")
1620
+ return "\n".join(lines) + "\n"
1621
+
1622
+
1623
+ def _convert_text(data) -> str:
1624
+ lines = []
1625
+ for word in KEPT_WORDS:
1626
+ lines.append(f"{word} {data['kept'][word]}")
1627
+ for word in SHAPE_WORDS:
1628
+ lines.append(f"{word} {data['shape_changes'][word]}")
1629
+ if "output" in data:
1630
+ lines.append(f"output {data['output']}")
1631
+ return "\n".join(lines) + "\n"
1632
+
1633
+
1634
+ def main(argv=None) -> int:
1635
+ argv = list(sys.argv[1:] if argv is None else argv)
1636
+ if "--version" in argv:
1637
+ _write_out(f"sieve-notes {__version__}\n".encode("utf-8"))
1638
+ return 0
1639
+ if "--self-check" in argv:
1640
+ code, message = _self_check()
1641
+ _write_out((message + "\n").encode("utf-8"))
1642
+ return code
1643
+ if not argv or argv[0] in ("-h", "--help"):
1644
+ _write_out(__doc__.encode("utf-8"))
1645
+ return 0 if argv else 2
1646
+
1647
+ cmd = argv[0]
1648
+ rest = argv[1:]
1649
+
1650
+ def need_value(args, flag):
1651
+ if flag in args:
1652
+ i = args.index(flag)
1653
+ if i + 1 >= len(args):
1654
+ return None
1655
+ return args[i + 1]
1656
+ return None
1657
+
1658
+ def has_flag(args, flag):
1659
+ return flag in args
1660
+
1661
+ def opt_value(args, flag, default):
1662
+ v = need_value(args, flag)
1663
+ return v if v is not None else default
1664
+
1665
+ fmt = opt_value(rest, "--format", "text")
1666
+ if fmt not in ("text", "json"):
1667
+ data = _error_dict(cmd, "invalid_option")
1668
+ _emit(data, "json", None)
1669
+ return 2
1670
+
1671
+ def _emit(data, fmt, text_fn):
1672
+ """Print the result (or a closed-vocabulary error) in the requested format."""
1673
+ if data.get("error"):
1674
+ if fmt == "json":
1675
+ _write_out(_dump_json(data))
1676
+ else:
1677
+ _write_out((f"sieve-notes: error: {data['error']}\n"
1678
+ ).encode("utf-8"))
1679
+ return
1680
+ if fmt == "json":
1681
+ _write_out(_dump_json(data))
1682
+ else:
1683
+ _write_out(text_fn(data).encode("utf-8"))
1684
+
1685
+ if cmd == "index":
1686
+ cleaned = []
1687
+ skip_next = False
1688
+ for a in rest:
1689
+ if skip_next:
1690
+ skip_next = False
1691
+ continue
1692
+ if a == "--format":
1693
+ skip_next = True
1694
+ continue
1695
+ if a.startswith("--"):
1696
+ continue
1697
+ cleaned.append(a)
1698
+ if not cleaned:
1699
+ data = _error_dict("index", "invalid_option")
1700
+ _emit(data, fmt, None)
1701
+ return 2
1702
+ vault_path = cleaned[0]
1703
+ data = index_vault(
1704
+ vault_path,
1705
+ include_hidden_dirs=has_flag(rest, "--include-hidden-dirs"),
1706
+ max_file_bytes=int(opt_value(rest, "--max-file-bytes",
1707
+ str(DEFAULT_MAX_FILE_BYTES))),
1708
+ max_files=int(opt_value(rest, "--max-files",
1709
+ str(DEFAULT_MAX_FILES))),
1710
+ no_names=has_flag(rest, "--no-names"),
1711
+ )
1712
+ code = data["exit_code"]
1713
+ if code == 0 and has_flag(rest, "--strict"):
1714
+ states = data["totals"]["link_states"]
1715
+ if any(states[s] > 0 for s in ("broken", "ambiguous",
1716
+ "fragment_missing")):
1717
+ code = 1
1718
+ data = dict(data)
1719
+ data["exit_code"] = 1
1720
+ _emit(data, fmt, _index_text)
1721
+ return code
1722
+
1723
+ if cmd == "blocks":
1724
+ cleaned = []
1725
+ skip_next = False
1726
+ dialect = "auto"
1727
+ for a in rest:
1728
+ if skip_next:
1729
+ skip_next = False
1730
+ continue
1731
+ if a == "--format":
1732
+ skip_next = True
1733
+ continue
1734
+ if a == "--dialect":
1735
+ dialect = opt_value(rest, "--dialect", "auto")
1736
+ skip_next = True
1737
+ continue
1738
+ if a.startswith("--"):
1739
+ continue
1740
+ cleaned.append(a)
1741
+ if not cleaned:
1742
+ data = _error_dict("blocks", "invalid_option")
1743
+ _emit(data, fmt, None)
1744
+ return 2
1745
+ data = block_tree(path=cleaned[0], dialect=dialect)
1746
+ _emit(data, fmt, _blocks_text)
1747
+ return data["exit_code"]
1748
+
1749
+ if cmd == "convert":
1750
+ cleaned = []
1751
+ skip_next = False
1752
+ to = None
1753
+ out_path = None
1754
+ indent = "2"
1755
+ strict = False
1756
+ i = 0
1757
+ while i < len(rest):
1758
+ a = rest[i]
1759
+ if a == "--format":
1760
+ i += 2
1761
+ continue
1762
+ if a == "--to":
1763
+ to = rest[i + 1] if i + 1 < len(rest) else None
1764
+ i += 2
1765
+ continue
1766
+ if a == "-o":
1767
+ out_path = rest[i + 1] if i + 1 < len(rest) else None
1768
+ i += 2
1769
+ continue
1770
+ if a == "--indent":
1771
+ indent = rest[i + 1] if i + 1 < len(rest) else None
1772
+ i += 2
1773
+ continue
1774
+ if a == "--strict":
1775
+ strict = True
1776
+ i += 1
1777
+ continue
1778
+ if a.startswith("--") or a == "-o":
1779
+ i += 1
1780
+ continue
1781
+ cleaned.append(a)
1782
+ i += 1
1783
+ if not cleaned or to is None or out_path is None:
1784
+ data = _error_dict("convert", "invalid_option")
1785
+ _emit(data, fmt, None)
1786
+ return 2
1787
+ data = convert_file(cleaned[0], to, out_path, indent=indent,
1788
+ strict=strict)
1789
+ _emit(data, fmt, _convert_text)
1790
+ return data["exit_code"]
1791
+
1792
+ _write_out(_dump_json(_error_dict(cmd, "invalid_option")))
1793
+ return 2
1794
+
1795
+
1796
+ if __name__ == "__main__":
1797
+ sys.exit(main())