diff --git a/docs/PROJECT_CONTEXT.md b/docs/PROJECT_CONTEXT.md index 41c8838..49bb50f 100644 --- a/docs/PROJECT_CONTEXT.md +++ b/docs/PROJECT_CONTEXT.md @@ -54,7 +54,12 @@ DAT/FIS/Python files), contain only letters/numbers/underscore/dot/hyphen and directory separators, and are deduplicated within each entry. Spaces, commands, expressions, directories without filenames, absolute paths and parent traversal are not recognized as inline material paths; use a Markdown link or explicit -manifest for other valid filenames. Fenced examples are excluded. `entry_line` +manifest for other valid filenames. HTML comments and fenced examples (including +an unclosed or truncated final comment/fence), links quoted as inline code, and escaped link syntax +are excluded. Single-backtick filenames nested inside a longer code span are +also examples rather than material entries. Comment delimiters inside code are +literal; fences inside comments do not hide links after the comment closes. +Malformed link URLs produce a warning while other materials remain navigable. `entry_line` locates the mention in the entry, not a verified location inside the source. Bare filenames are literal entry-relative candidates only: prose may describe a filename used inside several case folders. No existence or contextual location diff --git a/docs/START_WORKSPACE.md b/docs/START_WORKSPACE.md index e09e836..69b7eff 100644 --- a/docs/START_WORKSPACE.md +++ b/docs/START_WORKSPACE.md @@ -33,6 +33,12 @@ root index, reports every recognized project candidate, and returns a python -B -X utf8 .\mining_kernel.py project-context --project-root (Join-Path $starterRoot 'projects\roadway-support') ``` +HTML comments, fenced examples, links quoted as inline code, and escaped link +syntax are excluded from project candidates. An unclosed or truncated final +comment/fence hides its remaining content. Comment delimiters inside code stay +literal. A malformed URL produces a diagnostic and +does not prevent other index links from being recognized. + The user decides what this task should deliver, its boundaries, and when to finish or hand it off. First recover what they have already said in the conversation or project entry. If a consequential point is unclear, ask a diff --git a/docs/START_WORKSPACE.zh-CN.md b/docs/START_WORKSPACE.zh-CN.md index aa17cc6..16a0796 100644 --- a/docs/START_WORKSPACE.zh-CN.md +++ b/docs/START_WORKSPACE.zh-CN.md @@ -27,6 +27,10 @@ python -B -X utf8 .\mining_kernel.py workspace-context --workspace-root $starter python -B -X utf8 .\mining_kernel.py project-context --project-root (Join-Path $starterRoot 'projects\roadway-support') ``` +HTML 注释、代码块、行内代码中的示例链接及被反斜杠转义的链接语法不计入项目候选。 +未闭合或被读取上限截断的末尾注释、代码块会隐藏其剩余内容;代码里的注释标记按普通文本处理。 +畸形 URL 会产生诊断提示,其余索引链接仍继续识别。 + 本次任务交付什么、边界在哪里、何时完成或交接,由用户决定。 先从对话和项目入口恢复已经明确的决定。只有影响当前工作的关键事项不清楚时,才简短询问, 例如“这次希望交付什么?”或“有哪些内容明确不在本次范围内?”。 diff --git a/docs/archive/v0.1.0-release-candidate.md b/docs/archive/v0.1.0-release-candidate.md index 696c1f5..45e7adf 100644 --- a/docs/archive/v0.1.0-release-candidate.md +++ b/docs/archive/v0.1.0-release-candidate.md @@ -2,7 +2,7 @@ > Archived 2026-09-09 after the public v0.1.0 release. This is the > pre-publication candidate draft, kept for history. Current notes are in -> [RELEASE_NOTES.md](../RELEASE_NOTES.md) and the +> [RELEASE_NOTES.md](../../RELEASE_NOTES.md) and the > [v0.1.0 GitHub Release](https://github.com/NoxGarnet/mining-research-kernel/releases/tag/v0.1.0). > The draft's original status line said: local candidate draft; public > visibility, tag and Release creation remain separate decisions. Those @@ -69,8 +69,8 @@ Itasca documentation is claimed. Public visibility, a version tag and a GitHub Release require separate decisions after this local candidate review. -See the [public acceptance summary](ACCEPTANCE_SUMMARY.md) for the sanitized -baseline results and [distribution scope](PUBLIC_DISTRIBUTION_SCOPE.md) for +See the [public acceptance summary](../ACCEPTANCE_SUMMARY.md) for the sanitized +baseline results and [distribution scope](../PUBLIC_DISTRIBUTION_SCOPE.md) for included and excluded materials. The included material/example work also makes the first-use path diff --git a/mining_research_kernel/markdown_navigation.py b/mining_research_kernel/markdown_navigation.py new file mode 100644 index 0000000..2821e07 --- /dev/null +++ b/mining_research_kernel/markdown_navigation.py @@ -0,0 +1,106 @@ +"""Small lexical helpers for Markdown entry navigation, preserving offsets.""" +from __future__ import annotations + +import re + + +_FENCE_START = re.compile(r"^[ \t]{0,3}(?:`{3,}|~{3,})", re.M) +_TOKENS = re.compile( + r"(?P^[ \t]{0,3}(?P`{3,}|~{3,}))|(?P", token.end()) + mask_end = closing + 3 if closing >= 0 else len(text) + if mask_end is not None: + output.append(text[copied_until:token.start()]) + output.append(re.sub(r"[^\r\n]", " ", text[token.start():mask_end])) + copied_until = covered_until = mask_end + elif token.group("comment") is None: + tick_start = token.end() - len(token.group("marker") or token.group("ticks")) + code_end = code_ends.get(tick_start) + if (code_end is not None and not _escaped(text, tick_start) + and not _FENCE_START.search(text, token.end(), code_end)): + covered_until = code_end + output.append(text[copied_until:]) + return "".join(output) + + +def _escaped(text: str, offset: int) -> bool: + start = offset + while start and text[start - 1] == "\\": + start -= 1 + return (offset - start) % 2 == 1 + + +def _tick_closers(prose: str): + """Index possible same-width closing delimiters within each paragraph.""" + ticks = list(re.finditer(r"`+", prose)) + next_width, closers = {}, {} + for index in range(len(ticks) - 1, -1, -1): + # Inline code cannot join otherwise separate Markdown paragraphs. + if index + 1 < len(ticks) and re.search( + r"\r?\n[ \t]*\r?\n", prose[ticks[index].end():ticks[index + 1].start()]): + next_width.clear() + width = len(ticks[index][0]) + if width in next_width: + closers[index] = next_width[width] + next_width[width] = index + return ticks, closers + + +def inline_code_spans(prose: str) -> list[tuple[int, int, int]]: + """Return non-overlapping (start, end, tick-width) spans in bounded prose.""" + ticks, closers = _tick_closers(prose) + spans, covered_until = [], 0 + for index, tick in enumerate(ticks): + if tick.start() < covered_until or _escaped(prose, tick.start()): + continue + if index in closers: + covered_until = ticks[closers[index]].end() + spans.append((tick.start(), covered_until, len(tick[0]))) + return spans + + +def inline_links(prose: str): + """Yield simple inline links, excluding images, escapes and code examples. + + The caller masks comments and fenced blocks first. This is deliberately lexical; it does + not resolve reference-style links or implement a full Markdown renderer. + """ + spans = inline_code_spans(prose) + span_index = 0 + for match in re.finditer(r"(?\n]+>|[^\s()]+)\)", prose): + while span_index < len(spans) and spans[span_index][1] <= match.start(): + span_index += 1 + if span_index < len(spans) and spans[span_index][0] <= match.start() < spans[span_index][1]: + continue + if not _escaped(prose, match.start()): + yield match diff --git a/mining_research_kernel/project_context.py b/mining_research_kernel/project_context.py index 7e0b865..5fa4415 100644 --- a/mining_research_kernel/project_context.py +++ b/mining_research_kernel/project_context.py @@ -8,6 +8,7 @@ from urllib.parse import unquote, urlsplit from .core import safe_path +from .markdown_navigation import inline_code_spans, inline_links, mask_comments_and_fences from .on_demand import ( _continuation_parent, _decision_bound_to_task_state, _decision_records, _decision_selection, _judgment, _latest_records, _question_and_routes, @@ -94,13 +95,17 @@ def project_context(project_root: str | Path, *, manifest: str | None = None, "read_location": {"path": str(path)}, "entry_scan_truncated": clipped}) if clipped: warnings.append(f"{name}: only first {MAX_ENTRY_BYTES} bytes inspected for links") - # Fenced examples are not an entry's material catalogue. - prose = re.sub(r"```.*?```|~~~.*?~~~", lambda m: re.sub(r"[^\n]", " ", m[0]), text, flags=re.S) + # Comments and fenced examples are not an entry's material catalogue. + prose = mask_comments_and_fences(text) linked_paths, link_spans = set(), [] - for match in re.finditer(r"(?\n]+>|[^\s()]+)\)", prose): + for match in inline_links(prose): link_spans.append(match.span()) title, target = match.groups() - url = urlsplit(target.strip("<>")) + try: + url = urlsplit(target.strip("<>")) + except ValueError as exc: + warnings.append(f"{name}: malformed link ignored: {exc}") + continue if url.scheme or url.netloc or not url.path: continue relative = unquote(url.path) @@ -108,16 +113,16 @@ def project_context(project_root: str | Path, *, manifest: str | None = None, materials.append({"kind": "material", "id": f"{name}:{match.start()}", "title": _preview(title), "basis": f"explicit link in {name}", "location": _location(root, (Path(name).parent / relative).as_posix()), "anchor": unquote(url.fragment)}) - for match in re.finditer(r"(? list[str]: "--project-root", str(project_root)] -def _strip_fences(text: str) -> str: - """Mask fenced Markdown examples, including an unclosed final fence.""" - lines = text.splitlines(keepends=True) - output, marker, width = [], None, 0 - for line in lines: - match = re.match(r"^[ \t]{0,3}(\x60{3,}|~{3,})(.*?)(?:\r?\n)?$", line) - if marker is None: - if match: - fence = match.group(1) - marker, width = fence[0], len(fence) - output.append(re.sub(r"[^\r\n]", " ", line)) - else: - output.append(line) - else: - output.append(re.sub(r"[^\r\n]", " ", line)) - closing = re.match(r"^[ \t]{0,3}(\x60{3,}|~{3,})[ \t]*(?:\r?\n)?$", line) - if closing and closing.group(1)[0] == marker and len(closing.group(1)) >= width: - marker = None - return "".join(output) - - def workspace_context(workspace_root: str | Path, *, max_index_bytes: int = MAX_INDEX_BYTES) -> dict: supplied = Path(workspace_root).expanduser().absolute() if max_index_bytes < 1: @@ -82,10 +62,10 @@ def workspace_context(workspace_root: str | Path, *, max_index_bytes: int = MAX_ return _empty(root, "INDEX.md is missing") clipped = len(raw) > max_index_bytes text = raw[:max_index_bytes].decode("utf-8-sig", errors="replace") - prose = _strip_fences(text) + prose = mask_comments_and_fences(text) rows, seen, diagnostics = [], set(), [] - for match in re.finditer(r"(?\n]+>|[^\s()]+)\)", prose): - target = match.group(1).strip("<>") + for match in inline_links(prose): + target = match.group(2).strip("<>") try: url = urlsplit(target) except ValueError as exc: diff --git a/tests/test_markdown_navigation.py b/tests/test_markdown_navigation.py new file mode 100644 index 0000000..e304eb7 --- /dev/null +++ b/tests/test_markdown_navigation.py @@ -0,0 +1,43 @@ +import unittest + +from mining_research_kernel.markdown_navigation import ( + inline_links, + mask_comments_and_fences, +) + + +class MarkdownNavigationTests(unittest.TestCase): + def titles(self, text): + return [match[1] for match in inline_links(mask_comments_and_fences(text))] + + def test_comment_mask_preserves_unicode_offsets_and_crlf_lines(self): + text = "前言 [当前](current.csv)\r\n" + prose = mask_comments_and_fences(text) + self.assertEqual(len(text), len(prose)) + self.assertEqual([i for i, char in enumerate(text) if char in "\r\n"], + [i for i, char in enumerate(prose) if char in "\r\n"]) + link = list(inline_links(prose)) + self.assertEqual(["当前"], [match[1] for match in link]) + self.assertEqual(text.index("[当前]"), link[0].start()) + + def test_delimiter_precedence_keeps_visible_links(self): + cases = ( + "\n[Visible](visible.csv)\n", + "```md\n `[Visible](visible.csv)\n" + "\n" + "[Evidence](evidence.csv)\n`notes.txt`\n" + "\n" + "\n" + "[Real](projects/real/START.md)\n" + "\n" + (root / "INDEX.md").write_text(text, encoding="utf-8") + view = workspace_context(root, max_index_bytes=len(text) - 5) + self.assertTrue(view["index"]["truncated"]) + self.assertEqual(["real"], [row["project_id"] for row in view["projects"]]) + def test_navigation_reports_missing_malformed_truncated_and_unsafe(self): missing = workspace_context(self.base / "absent") self.assertIn("does not exist", missing["diagnostics"][0]) @@ -191,6 +253,10 @@ def test_unclosed_fences_and_malformed_links_do_not_hide_valid_links(self): (root / "INDEX.md").write_text(bounded, encoding="utf-8") clipped = workspace_context(root, max_index_bytes=60) self.assertEqual(["ok"], [row["project_id"] for row in clipped["projects"]]) + (root / "INDEX.md").write_text( + "[ok](projects/ok/START.md)\n\t```md\n[fake](projects/fake/START.md)\n", + encoding="utf-8") + self.assertEqual(["ok"], [row["project_id"] for row in workspace_context(root)["projects"]]) def test_cli_argv_works_and_old_project_context_remains_compatible(self): root = self.base / "legacy"