Skip to content

fix: ignore headings inside code fences in rule sections, and clear Test Rule's loading text - #373

Merged
Sanjay Singh (san360) merged 2 commits into
microsoft:mainfrom
thelastbackspace:fix/343-rule-sections-code-fences
Nov 25, 2026
Merged

Sanjay Singh (san360) merged 2 commits into
microsoft:mainfrom
thelastbackspace:fix/343-rule-sections-code-fences

Conversation

@thelastbackspace

Copy link
Copy Markdown
Contributor

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 Triggered got cut off at the fence, and the fenced line was read as the When Triggered section. parseSection and the Rule Editor form's sectionBlocks now both skip headings inside a closed fence (a small shared fencedLines helper in src/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 textContent on 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 check passes (typecheck + lint + spellcheck + knip + tests). The 8 failing tests also fail on main.
  • Changes are covered by tests
  • Documentation updated (not needed)

… 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

@san360 Sanjay Singh (san360) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 main with a personal rule whose Description contains a fenced # When Triggered example. 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 main and 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 main plus 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 current main. 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

  1. CRLF rules still get the old behaviour from the rule parser. FENCE_MARKER ends in (.*)$, and . doesn't match \r. parseRule keeps 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 main they at least agreed. An optional \r before the end of the pattern fixes it (suggestion inline). A CRLF variant of your first test would cover it: rule-parser.test.ts already runs the readFrontmatter tests for both line endings with describe.each.

  2. fencedLines gets slow when markers don't close. For each marker without a closer, the inner loop scans to the end of the text, and parseRule calls fencedLines once per section, so four times. A rule with many lines like ```x and no bare closing fence after them slows down quickly. We measured parseRule at about 0.5 s for a 10 KB rule, 10 s for 50 KB and over 3 minutes for 200 KB; main takes 1–2 ms for each. In the webview, readRuleFields took 2.6 s for 50 KB. parseRule runs 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.

  3. 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. On main, 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).

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!

Comment thread src/core/markdown-fences.ts Outdated
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/

const FENCE_MARKER = /^ {0,3}(`{3,}|~{3,})(.*)$/;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
const FENCE_MARKER = /^ {0,3}(`{3,}|~{3,})(.*)$/;
const FENCE_MARKER = /^ {0,3}(`{3,}|~{3,})(.*?)\r?$/;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +14 to +30
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;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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;
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/core/rule-parser.test.ts Outdated
});

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'));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
});

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@thelastbackspace

Copy link
Copy Markdown
Contributor Author

Pushed cea8b74 for all three, replied inline on each. npm run check passes. The only vitest failures locally are 8 tests in github-app-analytics.test.ts and parser-xcode.test.ts that need the sqlite3 CLI, which I don't have here.

@san360

Copy link
Copy Markdown
Contributor

Thanks a lot thelastbackspace for the quick and thorough update, and for replying on each point. We re-tested cea8b74 merged onto current main:

  • CRLF: the rule parser now reads fences in CRLF rules. A personal rule saved with CRLF endings shows the same Description, When Triggered text and Test Rule result as the LF copy, in the Rules list, the rule detail and the Rule Editor. The new CRLF test variants fail on the previous commit and pass now.
  • Speed: fencedLines is linear now. parseRule reads a rule of 200,000 unclosed ```x lines in about 250 ms, and the 20,000-line test fails on the previous commit and passes well inside its 2 s limit. We also checked the new fencedLines against a straightforward implementation of the rules in its docblock on 300,000 random fence-heavy bodies, with LF and CRLF, and the output matched every time.
  • Stray fences: keeping the Markdown reading for a lone ``` and following CommonMark for ```js``` works for us, and the docblock and tests now say so clearly. Editing that kind of rule in the Rule Editor form and saving keeps the detect block and every line of text.
  • All 45 built-in rules still read exactly as they do on main, with LF and CRLF endings. npm run check (including spellcheck), the build and the bundle-size check pass, and the PR's CI run is green.

This looks good to us. A maintainer will take it from here. Thanks again for the careful work on this one!

@san360
Sanjay Singh (san360) merged commit 76e28ca into microsoft:main Nov 25, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Rule sections end at headings inside code fences, and Test Rule can show only "Running rule…" instead of its result

2 participants