Repository navigation
fix: ignore headings inside code fences in rule sections, and clear Test Rule's loading text - #373
Conversation
… Test Rule's loading text parseSection and the Rule Editor form's section reader treated every `# ...` line as a heading, even inside a fenced example, so a fenced `# When Triggered` line cut the Description short and was read as the When Triggered section. Both now skip lines inside a closed code fence, using a shared fencedLines helper. Test Rule wrote its loading text with textContent into the element preact renders into. Preact doesn't own that text node, so it stayed above the result, and for a rule without thresholds every run after the first showed only the loading text. It's rendered through preact now. Fixes microsoft#343
Sanjay Singh (san360)
left a comment
There was a problem hiding this comment.
Thank you thelastbackspace for taking on #343 and fixing both halves of it! The shared fencedLines helper that keeps parseSection and the Rule Editor's sectionBlocks reading sections the same way is exactly what the issue asked for. Rendering the loading text through preact is a small, clean fix, and the test that runs Test Rule twice on a rule without thresholds is a great regression test.
What we checked
- We reproduced both problems on current
mainwith a personal rule whose Description contains a fenced# When Triggeredexample. The Rules list summary stops at the fence, the trigger message is the fenced text, and the second Test Rule run shows only "Running rule against your data...". - With this PR merged onto current
main, the same rule shows the full Description and the real When Triggered text, and Test Rule replaces the loading text on every run. - Your new tests fail against
main's source (6 of them) and pass with the change. - All 45 built-in rules parse identically on
mainand with this PR, with both LF and CRLF line endings. We compared the parser output, the rule summary and the Rule Editor form fields. - On current
mainplus this PR, these all pass: typecheck, lint, knip, lockfile-lint, the full vitest suite (163 files, 3,696 tests), the build and the bundle-size check. The 8 failing tests you mention no longer fail on currentmain. They were probably the time-zone date-range tests that #363 fixed. - The PR merges cleanly with #361, which also touches the rule engine, and the two pass their tests together.
Three things we'd like to sort out before merging
-
CRLF rules still get the old behaviour from the rule parser.
FENCE_MARKERends in(.*)$, and.doesn't match\r.parseRulekeeps CRLF line endings, so in a CRLF rule no line counts as a fence. The Rule Editor form normalizes line endings first, so it does see the fence. We saved the same rule with CRLF endings, as a personal rule written on Windows would be:- The Rules list and the rule detail still cut the Description at the fence and use the fenced text as the trigger message.
- The Rule Editor form and Test Rule now show the real When Triggered text.
So the editor and the saved rule now disagree; on
mainthey at least agreed. An optional\rbefore the end of the pattern fixes it (suggestion inline). A CRLF variant of your first test would cover it:rule-parser.test.tsalready runs thereadFrontmattertests for both line endings withdescribe.each. -
fencedLinesgets slow when markers don't close. For each marker without a closer, the inner loop scans to the end of the text, andparseRulecallsfencedLinesonce per section, so four times. A rule with many lines like```xand no bare closing fence after them slows down quickly. We measuredparseRuleat about 0.5 s for a 10 KB rule, 10 s for 50 KB and over 3 minutes for 200 KB;maintakes 1–2 ms for each. In the webview,readRuleFieldstook 2.6 s for 50 KB.parseRuleruns on the extension host when rules load and on Test Rule and Save, so one large or unusual personal or project rule could block it.Precomputing, for each fence character, the longest closing marker from each line on keeps the same results in linear time (suggestion inline). We checked it against your version on 300,000 random fence-heavy bodies and got identical output with LF and CRLF. It handles 200,000 lines in about 60 ms. A regression test could be:
it('reads a long rule with many fence markers that never close quickly', () => { const rule = parseRule([...head, '# Description', ...Array<string>(20000).fill('```x'), '', '# When Triggered', 'Real text.', ''].join('\n')); expect(rule?.descriptionTemplate).toBe('Real text.'); });
With the current loop this test times out; with the suggestion it runs in a few milliseconds.
-
The detect block's closing fence closes a stray
```before the Detection Logic section. The docblock and the "never closes" test say a stray marker can't swallow the rest of the rule. That holds for the test's~~~. But every rule closes its detect block with a bare```line, and that line also closes an earlier stray```. The Description might contain a lone```line, a one-line```js```, or a line like``` not a close. Then When Triggered, How to Improve and Examples all become part of the Description, and the rule falls back to "{{count}} occurrences detected." and "Review your practices.". The Rules list summary then shows the rest of the rule, detection logic included. Onmain, these rules keep their sections.For a lone
```, this matches how a Markdown renderer reads the file, so keeping it may be fine. If so, could the docblock and test say so? Two small ideas:- Follow CommonMark for backtick fences: an opening
```line whose info string contains a backtick (such as```js```) isn't a fence. That's one extra check on the opener. - Add a test with a stray
```in the Description and the usual detect block, to pin whichever behaviour we choose (comment inline).
- Follow CommonMark for backtick fences: an opening
Next steps: once these are addressed, a maintainer will approve the CI run. Please ask if anything here is unclear.
Thanks again for a careful, well-tested fix. We'd love to see more contributions from you!
| * Licensed under the MIT License. See LICENSE in the project root for license information. | ||
| *--------------------------------------------------------------------------------------------*/ | ||
|
|
||
| const FENCE_MARKER = /^ {0,3}(`{3,}|~{3,})(.*)$/; |
There was a problem hiding this comment.
parseRule reads the body with its CRLF line endings kept, so lines end in \r, and . doesn't match \r. As a result (.*)$ never matches a fence line in a CRLF rule: the parser finds no fences, while the Rule Editor form (which normalizes line endings first) does. Allowing an optional \r before the end fixes it. .*? stops before the \r, so a bare closing fence still has an empty info string:
| const FENCE_MARKER = /^ {0,3}(`{3,}|~{3,})(.*)$/; | |
| const FENCE_MARKER = /^ {0,3}(`{3,}|~{3,})(.*?)\r?$/; |
There was a problem hiding this comment.
Thanks, applied in cea8b74. I added the optional \r and the sections tests now run for both LF and CRLF with describe.each, like the readFrontmatter ones. The CRLF variants fail on the previous commit.
| export function fencedLines(lines: readonly string[]): boolean[] { | ||
| const fenced = lines.map(() => false); | ||
| for (let open = 0; open < lines.length; open++) { | ||
| const opener = FENCE_MARKER.exec(lines[open]); | ||
| if (!opener) continue; | ||
| const fence = opener[1]; | ||
| for (let close = open + 1; close < lines.length; close++) { | ||
| const closer = FENCE_MARKER.exec(lines[close]); | ||
| if (closer && closer[1][0] === fence[0] && closer[1].length >= fence.length && !closer[2].trim()) { | ||
| fenced.fill(true, open, close + 1); | ||
| open = close; | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| return fenced; | ||
| } |
There was a problem hiding this comment.
When a marker has no closer, this loop scans to the end of the text for it, so many unclosed markers cost O(n²). parseRule calls this once per section. A 50 KB rule made of ```x lines takes about 10 s in parseRule (1–2 ms on main), and a 200 KB one over 3 minutes.
One idea: precompute, for each fence character, the longest closing marker from each line on. Then a marker that can't close is skipped without a scan, and a marker that can close is scanned only up to its closer, which the loop then jumps past. On 300,000 random fence-heavy bodies this gave the same output as the current loop, with LF and CRLF:
| export function fencedLines(lines: readonly string[]): boolean[] { | |
| const fenced = lines.map(() => false); | |
| for (let open = 0; open < lines.length; open++) { | |
| const opener = FENCE_MARKER.exec(lines[open]); | |
| if (!opener) continue; | |
| const fence = opener[1]; | |
| for (let close = open + 1; close < lines.length; close++) { | |
| const closer = FENCE_MARKER.exec(lines[close]); | |
| if (closer && closer[1][0] === fence[0] && closer[1].length >= fence.length && !closer[2].trim()) { | |
| fenced.fill(true, open, close + 1); | |
| open = close; | |
| break; | |
| } | |
| } | |
| } | |
| return fenced; | |
| } | |
| export function fencedLines(lines: readonly string[]): boolean[] { | |
| const markers = lines.map(line => FENCE_MARKER.exec(line)); | |
| const closes = (at: number, fence: string) => { | |
| const marker = markers[at]; | |
| return !!marker && marker[1][0] === fence[0] && marker[1].length >= fence.length && !marker[2].trim(); | |
| }; | |
| // The longest closing marker of each character from each line on, so a marker that never closes is skipped | |
| // without scanning the rest of the text again. | |
| const longest: Record<string, number[]> = { '`': Array<number>(lines.length + 1).fill(0), '~': Array<number>(lines.length + 1).fill(0) }; | |
| for (let at = lines.length - 1; at >= 0; at--) { | |
| longest['`'][at] = longest['`'][at + 1]; | |
| longest['~'][at] = longest['~'][at + 1]; | |
| const marker = markers[at]; | |
| if (marker && !marker[2].trim()) longest[marker[1][0]][at] = Math.max(longest[marker[1][0]][at], marker[1].length); | |
| } | |
| const fenced = lines.map(() => false); | |
| for (let open = 0; open < lines.length; open++) { | |
| const fence = markers[open]?.[1]; | |
| if (!fence || longest[fence[0]][open + 1] < fence.length) continue; | |
| let close = open + 1; | |
| while (!closes(close, fence)) close++; | |
| fenced.fill(true, open, close + 1); | |
| open = close; | |
| } | |
| return fenced; | |
| } |
There was a problem hiding this comment.
Took your approach in cea8b74, with the longest closing marker per character precomputed from the end. I added your regression test (20,000 ```x lines). It took about 125 s on the previous commit and runs in ~70 ms now. I also checked the new version against the old one on 200k random fence-heavy bodies (LF and CRLF) and got identical output.
| }); | ||
|
|
||
| it('still ends a section at a heading after a fence marker that never closes', () => { | ||
| const rule = parseRule([...head, '# Description', 'Text', '~~~', '', '# When Triggered', 'Real text.', '', ...detect].join('\n')); |
There was a problem hiding this comment.
This covers an unclosed ~~~. With '```' in its place, the detect block's closing ``` closes the stray marker. description then runs up to the end of the detect block, and descriptionTemplate falls back to '{{count}} occurrences detected.'. A stray ``` (or a one-line ```js```) is probably the more common case in a rule. Could we add it here, so whichever behaviour we choose is pinned?
it('reads a stray ``` before the detect block', () => {
const rule = parseRule([...head, '# Description', 'Text', '```', '', '# When Triggered', 'Real text.', '', ...detect].join('\n'));
expect(rule?.descriptionTemplate).toBe('Real text.'); // or the default, if we keep the Markdown reading
});There was a problem hiding this comment.
I went with keeping the Markdown reading for a lone ```, since that's what the renderer shows, and took your CommonMark idea: a backtick opener whose info string contains a backtick isn't a fence, so a one-line ```js``` keeps the sections after it. The docblock now says a stray marker that a later closing line can close does open a fence. Two new tests pin both cases, for LF and CRLF. None of the built-in rules have a backtick in a fence info string, so they're unchanged.
…js``` The fence pattern ended in `(.*)$`, which never matches a line ending in `\r`, so parseRule found no fences in a CRLF rule while the Rule Editor form (which normalizes line endings) did. Allow an optional `\r`. A marker with no closer made fencedLines scan to the end of the text, so many unclosed markers cost O(n^2). Precompute the longest closing marker of each fence character from each line on, so a marker that can't close is skipped right away. Follow CommonMark and don't treat a backtick line whose info string has a backtick as a fence, so a one-line ```js``` keeps the sections after it. A lone ``` before the detect block still runs to the block's closing fence, as a Markdown renderer reads it; the docblock and a test say so.
|
Pushed cea8b74 for all three, replied inline on each. |
|
Thanks a lot thelastbackspace for the quick and thorough update, and for replying on each point. We re-tested
This looks good to us. A maintainer will take it from here. Thanks again for the careful work on this one! |
Description
Two fixes from #343.
The rule parser ended a section at any line starting with
#, including lines inside a fenced code block. So a Description with a fenced example like# When Triggeredgot cut off at the fence, and the fenced line was read as the When Triggered section.parseSectionand the Rule Editor form'ssectionBlocksnow both skip headings inside a closed fence (a small sharedfencedLineshelper insrc/core/markdown-fences.ts), so they still read sections the same way. A fence marker that never closes doesn't count, so a stray ``` can't hide the rest of the rule.Test Rule set its loading text with
textContenton the element preact renders into. Preact doesn't own that text node, so it stayed above the result, and for a rule without thresholds the second run showed only the loading text. I render it through preact instead.I updated the three tests that pinned the old behavior. The "heading inside the detect block" tests now open the detect block mid-line, which is the case where a heading inside it can still happen, so the read-only handling stays covered. None of the 45 built-in rules change.
Related Issues
Fixes #343
Checklist
npm run checkpasses (typecheck + lint + spellcheck + knip + tests). The 8 failing tests also fail on main.