Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(lint): placeholder-date and code masking honor CommonMark inline spans (#6133)
garrytan920caaff0b9c
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 407178b73e..59cdb65a3e 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -78,7 +78,7 @@ rejection of serve-only flags before a brain opens.- `src/core/context/delta-cursor.ts` — pure helpers for delta's per-arm cursor: the opaque base64url `cursor` (`{v:1, p:[since, slug], f:[created_at, id]}`, validated like `since`), microsecond ISO normalization and the one-microsecond clamp, `nextPagesPos`/`nextFactsPos` (delivered prefix, `now() - 2 s` horizon `DELTA_COMMIT_LAG_MS`, the facts cursor computed from raw rows so a duplicate cluster split by a budget cut loses nothing), `resolveDeltaStart` and `legacyDeltaCursor`. `test/delta-cursor-integrity.test.ts`.- `src/core/ops/facts.ts` — shared fact/memory operations, including `recall` and the `delta` cursor. Recall keeps source/visibility and fact filters before per-arm candidate limits. Its default/explicit `facts_first` packing preserves the frozen memory-verb contract, including the positive sub-one budget quirk. Optional `query_first` packs the ranked page prefix first only with a nonblank query and positive finite budget; floor-zero and exhausted remainders explicitly return empty arms rather than call the unbounded zero-budget packer. Neither arm skips oversized prefix items or truncates. No-query and inactive-budget paths keep legacy behavior. Only policy-supplied calls add `budget_packing` effective-policy/reason and candidate/kept/dropped/estimated-used accounting. Counter sums match the frozen fields. Do not change the global packer or fact relevance to implement this policy. Delta rejects calendar-invalid ISO dates and years outside 0001-9999 (on the parsed UTC value) before normalization across fractional-second forms, while preserving valid six-digit microsecond cursors. Delta's per-arm cursor (contributor audit wave P0): the start position resolves `cursor` > `since` (whole tuple, slug only when supplied) > the session row; each arm advances through its delivered prefix only (`src/core/context/delta-cursor.ts`), an arm that failed or never finished holds, the conservative legacy `next_cursor.since`/`slug` never passes the oldest undelivered fact, and a legacy caller at an unpageable same-timestamp boundary is refused with `delta_cursor_upgrade_required`. Incomplete wakes emit `delta_incomplete` (`fix.next: wait`, `report` on the third consecutive wake, counted atomically in `session_context_state.degraded_wakes` with an in-process fallback when the store is down); a failed state read refuses with `unavailable`/`session_state` instead of re-initializing at now. `test/recall-budget-policy.test.ts` pins recall behavior; `test/ambient-recall.test.ts` pins delta cursor validation; `test/delta-cursor-integrity.test.ts` (both engines) pins every no-advance path, the facts drain, legacy safety and the commit-visibility bound.-- `src/core/markdown-code.ts` — `stripCodeBlocks` masks fenced and inline code while preserving every CR/LF and UTF-16 code-unit offset. Citation paragraphs and later link references retain their original boundaries, including after an unclosed fence. `parseTimelineEntries` in `src/core/link-extraction.ts` groups the optional dash with its trailing whitespace so leading whitespace does not trigger overlapping repetition. Existing date and delimiter rules remain unchanged. Standalone backtick and tilde fences require valid closing markers; historical inline triple-backtick spans remain masked. Pinned through real FS/DB link and timeline consumers by `test/timeline-parser-regression.test.ts`; its adversarial whitespace workload runs in a timeout-bounded child process.+- `src/core/markdown-code.ts` — `stripCodeBlocks` masks fenced and inline code while preserving every CR/LF and UTF-16 code-unit offset. Citation paragraphs and later link references retain their original boundaries, including after an unclosed fence. `parseTimelineEntries` in `src/core/link-extraction.ts` groups the optional dash with its trailing whitespace so leading whitespace does not trigger overlapping repetition. Existing date and delimiter rules remain unchanged. Standalone backtick and tilde fences require valid closing markers; historical inline triple-backtick spans remain masked. Pinned through real FS/DB link and timeline consumers by `test/timeline-parser-regression.test.ts`; its adversarial whitespace workload runs in a timeout-bounded child process. #6133: inline spans pair backtick runs of equal length (CommonMark), found read-only by `fence-scan.ts` `scanMarkdownCode`/`inlineCodeEndAt` over a view where a bare CR is a space (so a span may still cross one), so a double-backtick span and a span holding a single backtick are masked whole and a backslash-escaped backtick opens nothing; the lint `placeholder-date` rule (`src/commands/lint.ts`) runs over the masked text, so placeholders in inline code no longer fire (`test/lint-3958.test.ts`, `test/timeline-parser-regression.test.ts`).- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax cases) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K). `checkResolvable(skillsDir, opts?)` takes an optional `skillsDirSource` (the detection tier from `autoDetectSkillsDir`, threaded by both callers: doctor.ts and the check-resolvable command; an explicit `--skills-dir` passes `null`). An `unreachable` issue downgrades from `error` to `warning` only when ALL hold: the directory was found via the ungated `cwd_walk_up` tier, no resolver file contributes rows (no `RESOLVER.md`; a generic `AGENTS.md` with zero table rows counts as absent), unreachable skills outnumber reachable ones, and no `manifest.json` exists on disk. This keeps a foreign tool's `skills/` dir walked up to from cwd from being scored as a broken gbrain skillpack, while a real skillpack (RESOLVER.md present, higher-confidence tier, dense trigger coverage, or any manifest.json, even a corrupted one) stays strict. A foreign dir with zero `triggers:` and no resolver file still hard-fails via the `missing_file` branch (separate follow-up).diff --git a/src/commands/lint.ts b/src/commands/lint.tsindex dbc2631655..af80ca1c6a 100644--- a/src/commands/lint.ts+++ b/src/commands/lint.ts@@ -35,6 +35,7 @@ import { loadActivePack } from '../core/schema-pack/load-active.ts';import { loadActivePackForLocalEngine } from '../core/schema-pack/best-effort.ts';import { safeCliToken, sanitizeTypeForDisplay, storedTypeMissesPack, type TypeUsagePack } from '../core/schema-pack/type-usage.ts';import { parseLineGrammar } from '../core/line-grammar.ts';+import { stripCodeBlocks } from '../core/markdown-code.ts';import { pathToSlug } from '../core/sync.ts';import { isManagedBrain } from '../core/cycle/phase-table.ts';import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../core/persistence/prepared-maintenance.ts';@@ -204,17 +205,13 @@ export function lintContent(content: string, filePath: string, opts: LintContent});}- // Rule: Placeholder dates. #3958: skip lines inside fenced code blocks —- // a page DOCUMENTING date formats (```\ncreated: YYYY-MM-DD\n```) is not a- // page with an unfilled placeholder. Both ``` and ~~~ fences toggle.- let inFence = false;+ // Rule: Placeholder dates. #3958/#6133: code is not a placeholder — a page+ // DOCUMENTING date formats (```\ncreated: YYYY-MM-DD\n``` or `YYYY-MM-DD`)+ // is not a page with an unfilled one. stripCodeBlocks masks fenced blocks+ // and inline spans in place, so line numbers stay exact.+ const prose = stripCodeBlocks(content).split('\n');for (let i = 0; i < lines.length; i++) {- if (/^\s{0,3}(```|~~~)/.test(lines[i])) {- inFence = !inFence;- continue;- }- if (inFence) continue;- if (lines[i].match(/\bYYYY-MM-DD\b/) || lines[i].match(/\bXX-XX\b/) || lines[i].match(/\b\d{4}-XX-XX\b/)) {+ if (prose[i].match(/\bYYYY-MM-DD\b/) || prose[i].match(/\bXX-XX\b/) || prose[i].match(/\b\d{4}-XX-XX\b/)) {issues.push({file: filePath, line: i + 1, rule: 'placeholder-date',message: `Placeholder date found: ${lines[i].trim().slice(0, 60)}`,diff --git a/src/core/markdown-code.ts b/src/core/markdown-code.tsindex 0561af62ad..96e18734f9 100644--- a/src/core/markdown-code.ts+++ b/src/core/markdown-code.ts@@ -1,10 +1,16 @@+import { inlineCodeEndAt, scanMarkdownCode, type MarkdownCodeMap } from './fence-scan.ts';+/*** Strip fenced code blocks (```...```) and inline code (`...`) from markdown,* replacing non-newline characters with spaces. Preserves CR/LF characters* and UTF-16 code-unit offsets for callers that care about positions.+ * Inline spans follow CommonMark (#6133): a run of n backticks closes at the+ * next run of exactly n on the same line (fence-scan.ts finds the spans), so+ * ``a `b` c`` is one span; a bare CR does not end the line here.*/export function stripCodeBlocks(content: string, opts: { onHtmlComment?: (start: number, end: number) => void } = {}): string {let fence: string | undefined;+ let inline: MarkdownCodeMap | undefined;let out = '';let i = 0;while (i < content.length) {@@ -37,14 +43,15 @@ export function stripCodeBlocks(content: string, opts: { onHtmlComment?: (start:continue;}if (content[i] === '`') {- const end = content.indexOf('`', i + 1);- if (end === -1 || content.slice(i + 1, end).includes('\n')) {+ inline ??= scanMarkdownCode(content.replace(/\r(?!\n)/g, ' '));+ const end = inlineCodeEndAt(inline, i);+ if (end === -1) {out += content[i];i++;continue;}- out += content.slice(i, end + 1).replace(/[^\r\n]/g, ' ');- i = end + 1;+ out += content.slice(i, end).replace(/[^\r\n]/g, ' ');+ i = end;continue;}out += content[i];diff --git a/test/lint-3958.test.ts b/test/lint-3958.test.tsindex d8c9f50e35..c1394becbb 100644--- a/test/lint-3958.test.ts+++ b/test/lint-3958.test.ts@@ -26,6 +26,21 @@ import {const SANITY_OFF = { disabled: true } as const;+// #6133: inline code spans (CommonMark backtick runs, double-backtick spans included) are code too.+describe('#6133 placeholder-date skips inline code spans', () => {+ test('inline, table-cell and double-backtick spans give no hits; prose and frontmatter still fire', () => {+ const content = [+ '---', 'title: Formats', 'type: note', 'created: YYYY-MM-DD', '---', '',+ 'Use `YYYY-MM-DD` for dates.',+ '| field | format |', '|---|---|', '| created | `2026-XX-XX` |',+ 'A span with a tick inside: `` `XX-XX` stays code ``.',+ 'This event is still 2026-XX-XX in prose.',+ ].join('\n');+ const hits = lintContent(content, 'test.md', { contentSanity: SANITY_OFF }).filter(i => i.rule === 'placeholder-date');+ expect(hits.map(h => h.line)).toEqual([4, 12]);+ });+});+describe('#3958 placeholder-date skips fenced code blocks', () => {test('YYYY-MM-DD inside a ``` fence is not a placeholder', () => {const content =diff --git a/test/timeline-parser-regression.test.ts b/test/timeline-parser-regression.test.tsindex 7f7ce3e179..630e994101 100644--- a/test/timeline-parser-regression.test.ts+++ b/test/timeline-parser-regression.test.ts@@ -228,3 +228,11 @@ describe('inline citation link targets (#5483)', () => {)).toEqual([{ date: '2024-02-27', source: 'memo', summary: 'Reviewed (carefully).' }]);});});++// #6133: inline spans pair backtick runs of equal length (CommonMark), so a double-backtick span is code.+test('inline masking pairs backtick runs of equal length', () => {+ expect(stripCodeBlocks('a ``2026-XX-XX`` b')).toBe(`a ${' '.repeat(14)} b`);+ expect(stripCodeBlocks('a `` x ` y `` b')).toBe(`a ${' '.repeat(11)} b`);+ expect(stripCodeBlocks('a ``unclosed` run')).toBe('a ``unclosed` run');+ expect(stripCodeBlocks('see \\`not code` here')).toBe('see \\`not code` here');+});