Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion docs/PROJECT_CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions docs/START_WORKSPACE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions docs/START_WORKSPACE.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 会产生诊断提示,其余索引链接仍继续识别。

本次任务交付什么、边界在哪里、何时完成或交接,由用户决定。
先从对话和项目入口恢复已经明确的决定。只有影响当前工作的关键事项不清楚时,才简短询问,
例如“这次希望交付什么?”或“有哪些内容明确不在本次范围内?”。
Expand Down
6 changes: 3 additions & 3 deletions docs/archive/v0.1.0-release-candidate.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
106 changes: 106 additions & 0 deletions mining_research_kernel/markdown_navigation.py
Original file line number Diff line number Diff line change
@@ -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<fence>^[ \t]{0,3}(?P<marker>`{3,}|~{3,}))|(?P<comment><!--)|(?P<ticks>`+)", re.M
)


def mask_comments_and_fences(text: str) -> str:
"""Mask comments and fenced examples without changing offsets or newlines.

Process delimiters in source order: fences inside comments and comment
delimiters inside code are literal. An unclosed comment/fence masks the
remaining bounded input, including when a read cuts off its closing marker.
"""
ticks, closers = _tick_closers(text)
code_ends = {ticks[index].start(): ticks[closer].end()
for index, closer in closers.items()}
output, copied_until, covered_until = [], 0, 0
for token in _TOKENS.finditer(text):
if token.start() < covered_until:
continue
mask_end = None
if token.group("fence") is not None:
fence = token.group("marker")
line_end = text.find("\n", token.end())
info = text[token.end():line_end if line_end >= 0 else len(text)]
if fence[0] != "`" or "`" not in info:
closing = re.compile(
r"^[ \t]{0,3}" + re.escape(fence[0]) + "{" + str(len(fence)) + r",}[ \t]*\r?$",
re.M,
).search(text, token.end())
mask_end = closing.end() if closing else len(text)
elif token.group("comment") is not None:
if not _escaped(text, token.start()):
closing = text.find("-->", 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]+)\]\((<[^>\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
23 changes: 14 additions & 9 deletions mining_research_kernel/project_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -94,30 +95,34 @@ 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]+)\]\((<[^>\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)
linked_paths.add(relative.replace("\\", "/").removeprefix("./"))
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"(?<!`)`([^`\n]+)`(?!`)", prose):
if any(start <= match.start() < end for start, end in link_spans):
for code_start, code_end, width in inline_code_spans(prose):
if width != 1 or any(start <= code_start < end for start, end in link_spans):
continue
relative = _inline_file_path(match[1])
relative = _inline_file_path(prose[code_start + 1:code_end - 1])
if relative is None or relative in linked_paths:
continue
linked_paths.add(relative)
materials.append({"kind": "material", "id": f"{name}:inline:{match.start()}",
materials.append({"kind": "material", "id": f"{name}:inline:{code_start}",
"title": _preview(relative), "basis": f"explicit inline file path in {name}",
"entry_line": text.count("\n", 0, match.start()) + 1,
"entry_line": text.count("\n", 0, code_start) + 1,
"location": _location(root, (Path(name).parent / relative).as_posix())})
if not entries:
warnings.append("No configured entry, START.md or README.md; no project purpose inferred.")
Expand Down
30 changes: 5 additions & 25 deletions mining_research_kernel/workspace_context.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
"""Bounded navigation from an explicit lightweight workspace INDEX.md."""
from __future__ import annotations

import re
import stat
import sys
from pathlib import Path
from urllib.parse import unquote, urlsplit

from .markdown_navigation import inline_links, mask_comments_and_fences

MAX_INDEX_BYTES = 65536
_REPARSE = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)

Expand Down Expand Up @@ -35,27 +36,6 @@ def _argv(project_root: Path) -> 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:
Expand All @@ -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]+\]\((<[^>\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:
Expand Down
43 changes: 43 additions & 0 deletions tests/test_markdown_navigation.py
Original file line number Diff line number Diff line change
@@ -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 = "前言 <!-- 隐藏\r\n[旧资料](old.csv) --> [当前](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```md\n[Hidden](hidden.csv)\n-->\n[Visible](visible.csv)\n",
"```md\n<!-- unfinished literal comment\n```\n[Visible](visible.csv)\n",
"``example ` <!-- literal comment`` [Visible](visible.csv)\n",
"<!-- unmatched ` --> `<!--` [Visible](visible.csv)\n",
"Unmatched `\n```md\n<!-- literal comment\n```\n[Visible](visible.csv)\n",
"<!-- one --><!-- two -->[Visible](visible.csv)<!-- unfinished [Hidden](hidden.csv)",
r"\<!-- literal [Visible](visible.csv)",
)
for text in cases:
with self.subTest(text=text):
self.assertEqual(["Visible"], self.titles(text))

def test_literal_comment_in_invalid_backtick_fence_info_is_not_an_opener(self):
self.assertEqual(["Visible"], self.titles(
"```example `<!--`\n[Visible](visible.csv)\n"))


if __name__ == "__main__":
unittest.main()
63 changes: 63 additions & 0 deletions tests/test_project_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,69 @@ def test_empty_project_and_explicit_manifest(self):
with self.assertRaisesRegex(ValueError, r"materials\[0\].path"):
project_context(self.root, manifest="list.json")

def test_malformed_link_warns_without_hiding_valid_materials(self):
(self.root / "START.md").write_text(
"[Broken](http://[)\n[Evidence](inputs/evidence.csv)\n`notes.txt`\n",
encoding="utf-8")
before = self.snapshot()
view = project_context(self.root, limit=20)
materials = [row for row in view["items"] if row["kind"] == "material"]
self.assertEqual(["Evidence", "notes.txt"], [row["title"]["text"] for row in materials])
self.assertTrue(any("START.md: malformed link ignored" in warning for warning in view["warnings"]))
self.assertEqual(before, self.snapshot())

def test_comments_do_not_become_materials_or_shift_visible_path_lines(self):
text = (
"<!-- [Old](old.csv)\n`hidden.txt` -->\n"
"<!--\n```md\n[Archived](archived.csv)\n-->\n"
"[Evidence](evidence.csv)\n`notes.txt`\n"
"<!-- unfinished [Hidden](hidden.csv)\n`other.txt`\n"
)
(self.root / "START.md").write_text(text, encoding="utf-8")
before = self.snapshot()
view = project_context(self.root, limit=20)
materials = [row for row in view["items"] if row["kind"] == "material"]
self.assertEqual(["Evidence", "notes.txt"], [row["title"]["text"] for row in materials])
self.assertEqual(8, materials[-1]["entry_line"])
self.assertEqual(before, self.snapshot())

def test_fenced_examples_do_not_become_materials(self):
cases = (
"```md\n[Example](inputs/example.csv)\n`hidden.txt`\n",
"````md\n```\n[Example](inputs/example.csv)\n`hidden.txt`\n````\n",
"~~~md\n```\n[Example](inputs/example.csv)\n`hidden.txt`\n~~~\n",
"\t```md\n[Example](inputs/example.csv)\n`hidden.txt`\n",
)
entry = self.root / "START.md"
for example in cases:
with self.subTest(example=example):
entry.write_text("[Evidence](inputs/evidence.csv)\n" + example, encoding="utf-8")
view = project_context(self.root, limit=20)
materials = [row for row in view["items"] if row["kind"] == "material"]
self.assertEqual(["Evidence"], [row["title"]["text"] for row in materials])
# Bounded reads can cut off the closing fence of an otherwise valid file.
text = "[Evidence](inputs/evidence.csv)\n```md\n[Example](inputs/example.csv)\n```\n"
entry.write_text(text, encoding="utf-8")
with patch("mining_research_kernel.project_context.MAX_ENTRY_BYTES", len(text) - 4):
view = project_context(self.root, limit=20)
self.assertEqual(1, view["counts"]["materials"])
self.assertTrue(any("only first" in warning for warning in view["warnings"]))

def test_inline_link_examples_are_ignored_and_file_paths_keep_line_numbers(self):
text = (
"# Entry\n`[Example](inputs/example.csv)`\n"
"``[Nested `example`](inputs/nested.csv)``\n"
r"\[Escaped](inputs/escaped.csv)" + "\n"
"[Evidence](inputs/evidence.csv)\n````md\n```\n`hidden.txt`\n````\n"
"`notes.txt`\n"
"``outer `nested.txt` example``\n"
r"\`escaped.txt`" + "\n"
)
(self.root / "START.md").write_text(text, encoding="utf-8")
materials = [row for row in self.all_items() if row["kind"] == "material"]
self.assertEqual(["Evidence", "notes.txt"], [row["title"]["text"] for row in materials])
self.assertEqual(10, materials[-1]["entry_line"])

def test_configured_nested_entry_resolves_links_without_opening_sources(self):
from research_project import enable_research
enable_research(self.root, "nested-entry")
Expand Down
Loading
Loading