Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(line-grammar): linear-time qualifier, citation and link parsing on the page-write path (#6186)
garrytana3208943b9dd
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 407178b73e..6e2940700f 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -110,7 +110,7 @@ rejection of serve-only flags before a brain opens.- `src/core/trajectory-format.ts` — shared `formatTrajectoryBlock(points, entitySlug, opts)` consumed by both `gbrain think` (production) and the LongMemEval harness (benchmark). Groups by `(metric ?? event_type)`, per-metric cap 20, total cap 100, knowledge_update intent annotates value-change rows with `(superseded prior)`. Emits a `<trajectory entity="...">` XML envelope — `INJECTION_PATTERNS` in `src/core/think/sanitize.ts` escapes `</trajectory>`, `<trajectory ...>` open tags, and attribute injection so adversarial fact text can't break out. Pinned by `test/trajectory-format.test.ts`.-- `src/core/line-grammar.ts` + `src/core/machine-sections.ts` — the line grammar: `parseLineGrammar` reads list items in a page body as typed relation lines (`- works_at [[companies/x]] (context)`: one type token or quoted phrase, exactly one link, optional `(context)`, optional `@effective[start,end)`, an optional trailing `[Source: ...]` citation) and fact lines (`- [category] claim #tag (context)`). Guards: a category is one letter-led token (timecodes, dates, citations, footnotes, task boxes and bracket phrases never match), `x`/`todo`/`done`/`wip` are refused, and code, blockquotes, HTML comments, frontmatter and the machine-written sections from `rolePriorSuppressedRanges` (now in `machine-sections.ts`, shared with type inference) are skipped. Prose after the link, two links, stoplisted generic words and verbs the active pack does not declare fall back to inference with a diagnostic. `statedRelationTypes` feeds `extractPageLinks` (and the filesystem scan in `commands/extract.ts`): the stated type wins for the link on its line, except an `attended` line on a meeting page, which stays with canonical attendance. `parseEffectiveQualifier` normalizes ISO ranges to half-open `[from, until)` dates and refuses everything else unpeeled. `lineGrammarOptions` resolves `line_grammar.enabled` (default off: held-out verdict H3 failed its precision bar) and `line_grammar.allow_undeclared_types`. Fact lines are reported (put_page `line_grammar`, `gbrain lint` rule `line-grammar`, `schema detect --fields`), not projected into `facts`. Pinned by `test/line-grammar.test.ts` (incl. a timeout-bounded adversarial input), `test/link-extraction-line-grammar.test.ts`, `test/put-page-line-grammar.test.ts`.+- `src/core/line-grammar.ts` + `src/core/machine-sections.ts` — the line grammar: `parseLineGrammar` reads list items in a page body as typed relation lines (`- works_at [[companies/x]] (context)`: one type token or quoted phrase, exactly one link, optional `(context)`, optional `@effective[start,end)`, an optional trailing `[Source: ...]` citation) and fact lines (`- [category] claim #tag (context)`). Guards: a category is one letter-led token (timecodes, dates, citations, footnotes, task boxes and bracket phrases never match), `x`/`todo`/`done`/`wip` are refused, and code, blockquotes, HTML comments, frontmatter and the machine-written sections from `rolePriorSuppressedRanges` (now in `machine-sections.ts`, shared with type inference) are skipped. Prose after the link, two links, stoplisted generic words and verbs the active pack does not declare fall back to inference with a diagnostic. `statedRelationTypes` feeds `extractPageLinks` (and the filesystem scan in `commands/extract.ts`): the stated type wins for the link on its line, except an `attended` line on a meeting page, which stays with canonical attendance. `parseEffectiveQualifier` normalizes ISO ranges to half-open `[from, until)` dates and refuses everything else unpeeled (a range with more than one comma is refused with an exactly-one-comma message). Parsing stays linear on adversarial lines: the qualifier's date groups exclude commas, the trailing-citation pattern has no overlapping whitespace quantifiers, and links come from `findLinks`, a scan with precomputed stop positions that returns exactly the old link regex's matches. `lineGrammarOptions` resolves `line_grammar.enabled` (default off: held-out verdict H3 failed its precision bar) and `line_grammar.allow_undeclared_types`. Fact lines are reported (put_page `line_grammar`, `gbrain lint` rule `line-grammar`, `schema detect --fields`), not projected into `facts`. Pinned by `test/line-grammar.test.ts` (incl. a timeout-bounded adversarial input, a 200k-character linear-time ratio check and a `findLinks` equivalence property test), `test/link-extraction-line-grammar.test.ts`, `test/put-page-line-grammar.test.ts`.- `src/core/wanted-links.ts` + `src/core/wanted-links-store.ts` — wanted pages. `collectWantedLinks` turns an origin's link candidates (each body markdown link / wikilink carries an `authoredRef` from `extractPageLinks`) and unresolved frontmatter names into `wanted_links` rows: a reference is wanted only when every alternative resolution failed with `missing_target`/`cross_source` (an unqualified target existing only in another source is wanted in the origin source; a qualified target in a source the origin may not link to is not). Bare prose paths never become rows. `replaceWantedLinks` runs inside `replaceDerivedLinks` (`opts.wanted`, per producer `body`/`frontmatter`), so every extraction path (managed put_page and stale sweep via `links-preparation.ts`, unmanaged `extract`, the serve sweep, source reconciliation) replaces rows atomically with links; it locks slug targets and stamps a row `-infinity` when its exact target already exists. `WANTED_ORIGIN_IS_STALE` in `engine-sql/pages.ts` joins the stale-for-extraction predicate: a live target (exact slug, or basename for `ref_kind='name'`) updated after `checked_at` makes the origin stale, so the next sweep creates the edge; restore and rename bump `updated_at`. `listWantedPages` backs the `wanted_pages` op (`gbrain wanted`): source-scoped, private origins excluded before aggregation for remote callers, soft-deleted origins never count, bare-name targets list `existing_matches`. `wanted_pages.enabled` (default on). Migration v214. Pinned by `test/wanted-links.test.ts` + `test/e2e/wanted-links-postgres.test.ts`.diff --git a/src/core/line-grammar.ts b/src/core/line-grammar.tsindex c5f30e6808..a757445b1f 100644--- a/src/core/line-grammar.ts+++ b/src/core/line-grammar.ts@@ -84,14 +84,57 @@ const TYPE_TOKEN_RE = /^[A-Za-z][A-Za-z0-9_-]{0,39}$/;const CATEGORY_STOPLIST = new Set(['x', 'todo', 'done', 'wip']);const TYPE_STOPLIST = new Set(['see', 'also', 'cf', 'via', 'and', 'or', 'with', 'from', 're', 'by', 'to', 'per', 'and/or']);const LIST_ITEM_RE = /^([ \t]*)(?:[-*+]|\d{1,9}[.)])[ \t]+(.*)$/;-const QUALIFIER_RE = /^@([A-Za-z][A-Za-z0-9_]*)([[(])([^\][()]*),([^\][()]*)([\])])(?=\s|$)/;+// Neither date group may contain a comma: with n commas and no closer, a group+// that could also eat commas made the engine retry every comma as the+// separator (quadratic on the page-write path, #6186).+const QUALIFIER_RE = /^@([A-Za-z][A-Za-z0-9_]*)([[(])([^\][(),]*),([^\][(),]*)([\])])(?=\s|$)/;+const QUALIFIER_BODY_RE = /^[^\][()]*/;const QUALIFIER_LIKE_RE = /^@([A-Za-z][A-Za-z0-9_]*)[[(:]/;-const LINK_RE = /\[\[[^\]\n]+\]\]|\[[^\][\n]+\]\([^)\n]+\)/g;const LINE_TEXT_MAX = 160;// A trailing `[Source: ...]` citation (plain or wrapping a markdown link) is// part of the brain's quality convention, not of the grammar: it is set aside// before a line is read.-const TRAILING_CITATION_RE = /\s*\[Source:\s*(?:[^\][]|\[[^\]]*\]\([^)]*\))*\]\s*$/i;+const TRAILING_CITATION_RE = /\[Source:(?:[^\][]|\[[^\]]*\]\([^)]*\))*\]\s*$/i;++/** Index of the first char at or after each position that is in `stops`, or `text.length`. */+function nextStop(text: string, stops: string): Int32Array {+ const next = new Int32Array(text.length + 1).fill(text.length);+ for (let i = text.length - 1; i >= 0; i--) next[i] = stops.includes(text[i]) ? i : next[i + 1];+ return next;+}++/**+ * `[[wikilinks]]` and `[markdown](links)` in order, without overlaps: the+ * matches of /\[\[[^\]\n]+\]\]|\[[^\][\n]+\]\([^)\n]+\)/g. A scan with+ * precomputed stop positions, so a long run of unclosed brackets costs linear+ * time where the regex rescanned the run from every bracket (#6186).+ */+export function findLinks(text: string): Array<{ index: number; text: string }> {+ const out: Array<{ index: number; text: string }> = [];+ if (!text.includes('[')) return out;+ const closeOrNl = nextStop(text, ']\n');+ const bracketOrNl = nextStop(text, '[]\n');+ const parenOrNl = nextStop(text, ')\n');+ for (let i = 0; i < text.length; i++) {+ if (text[i] !== '[') continue;+ let end = -1;+ if (text[i + 1] === '[') {+ const j = closeOrNl[i + 2];+ if (j > i + 2 && text[j] === ']' && text[j + 1] === ']') end = j + 2;+ }+ if (end < 0) {+ const k = bracketOrNl[i + 1];+ if (k > i + 1 && text[k] === ']' && text[k + 1] === '(') {+ const m = parenOrNl[k + 2];+ if (m > k + 2 && text[m] === ')') end = m + 1;+ }+ }+ if (end < 0) continue;+ out.push({ index: i, text: text.slice(i, end) });+ i = end - 1;+ }+ return out;+}/** Normalize a written relation type: `worksAt`, `works-at`, `"works at"` -> `works_at`. */export function normalizeRelationType(raw: string): string {@@ -132,8 +175,11 @@ export function parseEffectiveQualifier(text: string): QualifierParse {const like = QUALIFIER_LIKE_RE.exec(text);if (!like) return { kind: 'none' };const known = like[1] === 'effective' || like[1] === 'valid';+ const extraComma = known && (QUALIFIER_BODY_RE.exec(text.slice(like[0].length))?.[0].split(',').length ?? 0) > 2;return { kind: 'refused', reason: known ? 'invalid_range' : 'unknown_qualifier',- message: known+ message: extraComma+ ? 'A validity range has exactly one comma separating start and end: @effective[2024-01-01,2025-06-01).'+ : known? 'A validity range takes ISO dates: @effective[2024-01-01,2025-06-01) — [ ] inclusive, ( ) exclusive, an empty side is open.': `Only @effective[start,end) (alias @valid) is read; @${like[1]} stays plain text.` };}@@ -271,7 +317,7 @@ function levenshtein(a: string, b: string): number {function parseRelationContent(content: string, declared: ReadonlySet<string> | null,note: (reason: GrammarReason, message: string) => void): Omit<GrammarRelation, 'line' | 'start' | 'end'> | null {- const links = [...content.matchAll(LINK_RE)];+ const links = findLinks(content);if (!links.length) return null;const first = links[0];let prefix = content.slice(0, first.index).trim();@@ -294,7 +340,7 @@ function parseRelationContent(content: string, declared: ReadonlySet<string> | nif (explicit) note('two_links', 'A relation line names exactly one link; write one line per target.');return null;}- let suffix = content.slice(first.index! + first[0].length).trim();+ let suffix = content.slice(first.index + first.text.length).trim();if (!qualifierText && suffix.startsWith('@')) {const q = parseEffectiveQualifier(suffix);if (q.kind === 'ok') { qualifierText = q.range.raw; suffix = suffix.slice(q.length).trim(); }diff --git a/test/line-grammar.test.ts b/test/line-grammar.test.tsindex 46648efe5d..fcd5ba070d 100644--- a/test/line-grammar.test.ts+++ b/test/line-grammar.test.ts@@ -5,7 +5,7 @@*/import { describe, expect, test } from 'bun:test';import { spawnSync } from 'node:child_process';-import { normalizeRelationType, parseEffectiveQualifier, parseLineGrammar } from '../src/core/line-grammar.ts';+import { findLinks, normalizeRelationType, parseEffectiveQualifier, parseLineGrammar } from '../src/core/line-grammar.ts';const facts = (text: string) => parseLineGrammar(text).facts;const relations = (text: string, declared?: string[]) =>@@ -187,3 +187,40 @@ test('adversarial input stays linear (bounded child process)', () => {expect(run.status, run.stderr).toBe(0);expect(Number(run.stdout.trim())).toBeLessThan(5_000);}, 30_000);++test('long comma, bracket and space runs are parsed in linear time (#6186)', () => {+ const script = `+ const { parseLineGrammar } = await import(${JSON.stringify(new URL('../src/core/line-grammar.ts', import.meta.url).pathname)});+ const lines = (n) => ['- [idea] @effective[' + ','.repeat(n), '- t ' + '[['.repeat(n / 2), '- t ' + '[x]('.repeat(n / 4),+ '- [idea] a' + ' '.repeat(n) + 'b', '- [idea] a [Source:' + ' '.repeat(n) + 'b'].join('\\n');+ const time = (n) => { const text = lines(n); const t = performance.now(); parseLineGrammar(text); return performance.now() - t; };+ time(1000);+ const small = Math.min(time(100_000), time(100_000)); const large = Math.min(time(200_000), time(200_000));+ console.log(JSON.stringify({ small, large }));`;+ const run = spawnSync(process.execPath, ['-e', script], { timeout: 5_000, encoding: 'utf-8' });+ expect(run.error?.message ?? '', 'the 200k-character lines did not finish within 5 s').toBe('');+ expect(run.status, run.stderr).toBe(0);+ const { small, large } = JSON.parse(run.stdout.trim()) as { small: number; large: number };+ expect(large / Math.max(small, 1)).toBeLessThan(3);+}, 30_000);++test('a qualifier with more than one comma is refused as a range (#6186)', () => {+ const r = parseEffectiveQualifier('@effective[2020,2021,2022) rest');+ expect(r).toMatchObject({ kind: 'refused', reason: 'invalid_range' });+ expect(r.kind === 'refused' && r.message).toContain('exactly one comma');+ expect(parseEffectiveQualifier('@effective[2020,2022) rest')).toMatchObject({ kind: 'ok', range: { from: '2020-01-01', until: '2022-01-01' } });+ expect(parseEffectiveQualifier('@effective[,) rest')).toMatchObject({ kind: 'ok', range: { from: null, until: null } });+});+++test('findLinks returns exactly the matches of the link pattern it replaced', () => {+ const pattern = /\[\[[^\]\n]+\]\]|\[[^\][\n]+\]\([^)\n]+\)/g;+ const alphabet = ['[', ']', '(', ')', '\n', 'a', ' ', '[[', ']]', '](' ];+ let seed = 6186;+ const rand = (n: number) => { seed = (seed * 1103515245 + 12345) % 2147483648; return seed % n; };+ const samples = ['[[people/alice-example]]', '[a](b) [[c]]', '[[a]b]]', '[[]]', '[](x)', '[a]()', '[[a\nb]]', '[x](y\n)', '[[a]] [b](c)'];+ for (let n = 0; n < 4000; n++) samples.push(Array.from({ length: 1 + rand(14) }, () => alphabet[rand(alphabet.length)]).join(''));+ for (const text of samples) {+ expect(findLinks(text)).toEqual([...text.matchAll(pattern)].map(m => ({ index: m.index!, text: m[0] })));+ }+});