Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
line grammar: template-slot, separator, placeholder and usage-label guards; decorated-type diagnostics; typo-only suggestions
garrytanda33788b24ff
diff --git a/src/core/line-grammar.ts b/src/core/line-grammar.tsindex c5f30e6808..0a77b32b2a 100644--- a/src/core/line-grammar.ts+++ b/src/core/line-grammar.ts@@ -18,7 +18,12 @@* `[^1]`, `[ ]` and ids like `[D4]` never match), all-caps markers like* `[TODO]`, `[x]`/`[X]` task markers and a small stoplist are refused, and lines inside code, blockquotes, HTML* comments, the Facts/Takes fences and machine-written sections (Timeline,- * See also, Related, Sources, ...) are never read.+ * See also, Related, Sources, ...) are never read. Template and dictionary+ * lines are refused too: a fact line whose text holds another bare `[Slot]`+ * (`- [Time] - [Event]`), whose claim starts with a separator or is only a+ * placeholder (`TBD`, `...`), or whose category is a lexicographic usage+ * label (`[noun]`, `[informal]`). Every guard reads one line only, so a+ * line's parse never depends on its neighbors.** `@effective[start,end)` (alias `@valid`) is an inline validity range with* ISO dates (`YYYY`, `YYYY-MM`, `YYYY-MM-DD`, UTC); `[`/`]` are inclusive and@@ -33,7 +38,11 @@ import { inSuppressedRange, rolePriorSuppressedRanges } from './machine-sectionsexport type GrammarReason =| 'prose_tail' | 'two_links' | 'stoplist_type' | 'undeclared_type'- | 'unknown_qualifier' | 'invalid_range';+ | 'unknown_qualifier' | 'invalid_range'+ | 'template_slot' | 'separator_claim' | 'placeholder_claim' | 'usage_label' | 'type_punctuation';++/** Guard refusals: reported only when the page also holds a grammar line, or when asked (`explainGuards`). */+const GUARD_REASONS: ReadonlySet<GrammarReason> = new Set(['template_slot', 'separator_claim', 'placeholder_claim', 'usage_label']);export interface EffectiveRange {/** Inclusive start date `YYYY-MM-DD`, or null when open. */@@ -82,6 +91,18 @@ const FACT_KINDS = new Set(['event', 'preference', 'commitment', 'belief', 'factconst CATEGORY_RE = /^[A-Za-z][A-Za-z_-]{0,31}$/;const TYPE_TOKEN_RE = /^[A-Za-z][A-Za-z0-9_-]{0,39}$/;const CATEGORY_STOPLIST = new Set(['x', 'todo', 'done', 'wip']);+/** Lexicographic labels (parts of speech, register and region) mark dictionary entries, not fact categories. */+export const USAGE_LABELS: ReadonlySet<string> = new Set([+ 'noun', 'verb', 'adj', 'adjective', 'adv', 'adverb', 'pron', 'pronoun', 'prep', 'preposition', 'conj', 'interj',+ 'informal', 'formal', 'slang', 'colloquial', 'archaic', 'obsolete', 'dated', 'literary', 'figurative', 'vulgar',+ 'offensive', 'dialect', 'regional', 'plural', 'singular', 'transitive', 'intransitive', 'abbr',+]);+// A bare `[Slot]` of category shape: not a link label `[x](url)` or `[x][ref]`, not part of `[[x]]`, `![x]` or `\[x]`.+const BARE_SLOT_RE = /(?<![[\\!\]])\[[A-Za-z][A-Za-z_-]{0,31}\](?![[(\]])/;+// A claim that starts with a separator (`- [Time] - [Event]`, `[Day] | ...`); `-40 degrees` is still a claim.+const SEPARATOR_CLAIM_RE = /^(?:[–—|=>]|[-/](?=\s|$))/;+const PLACEHOLDER_CLAIM_RE = /^(?:\.{3,}|…|tbd|tba|tbc|x{3,}|_{3,}|<[^<>]*>|\?{2,})$/i;+const DECORATED_TYPE_RE = /^(\*\*|__|`)?([A-Za-z][A-Za-z0-9_-]{0,39}?)(\*\*|__|`)?(:)?$/;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|$)/;@@ -191,8 +212,9 @@ function lineText(line: string): string {* active schema pack's link verbs), gates relation types: an undeclared type* falls back to inference and is reported with the nearest declared verb.*/-export function parseLineGrammar(text: string, opts: { declaredTypes?: ReadonlySet<string> | null } = {}): LineGrammarResult {+export function parseLineGrammar(text: string, opts: { declaredTypes?: ReadonlySet<string> | null; explainGuards?: boolean } = {}): LineGrammarResult {const result: LineGrammarResult = { facts: [], relations: [], diagnostics: [] };+ const guarded: GrammarDiagnostic[] = [];if (!text.includes('- ') && !text.includes('* ') && !text.includes('+ ') && !/\d[.)] /.test(text)) return result;const masked = stripCodeBlocks(text, { onHtmlComment: () => {} });const excluded = excludedRanges(text);@@ -211,27 +233,48 @@ export function parseLineGrammar(text: string, opts: { declaredTypes?: ReadonlyS// the original line; structure is read from the masked text (links inside// code are not links), the fact text from the original.const visibleContent = item[2].replace(TRAILING_CITATION_RE, '').trim();- const content = line.slice(line.length - item[2].length).replace(TRAILING_CITATION_RE, '').trim();+ // Read from the original item: masking can widen the marker's whitespace when the item opens with inline code.+ const content = (LIST_ITEM_RE.exec(line)?.[2] ?? line.slice(line.length - item[2].length)).replace(TRAILING_CITATION_RE, '').trim();if (!visibleContent || visibleContent.startsWith('\\')) continue;- const note = (reason: GrammarReason, message: string) => result.diagnostics.push({ line: lineNo, reason, text: lineText(line), message });- if (visibleContent.startsWith('[')) {- const fact = parseFactContent(content, note);+ const note = (reason: GrammarReason, message: string) => (GUARD_REASONS.has(reason) ? guarded : result.diagnostics).push({ line: lineNo, reason, text: lineText(line), message });+ if (visibleContent.startsWith('[') && content.startsWith('[')) {+ const fact = parseFactContent(content, visibleContent, note);if (fact) result.facts.push({ line: lineNo, ...fact });continue;}- const relation = parseRelationContent(visibleContent, opts.declaredTypes ?? null, note);+ const relation = parseRelationContent(visibleContent, content, opts.declaredTypes ?? null, note);if (relation) result.relations.push({ line: lineNo, start, end: start + line.length, ...relation });}+ if (guarded.length && (opts.explainGuards || result.facts.length || result.relations.length)) {+ result.diagnostics.push(...guarded);+ result.diagnostics.sort((a, b) => a.line - b.line);+ }return result;}-function parseFactContent(content: string, note: (reason: GrammarReason, message: string) => void): Omit<GrammarFact, 'line'> | null {+const FACT_FORM = 'To state a typed fact, write `- [category] claim` with a real category, for example `- [preference] Prefers tea`.';++function parseFactContent(content: string, visibleContent: string, note: (reason: GrammarReason, message: string) => void): Omit<GrammarFact, 'line'> | null {const m = /^\[([^\][]*)\][ \t]+(\S.*)$/.exec(content);if (!m) return null;const category = m[1].trim();if (!CATEGORY_RE.test(category)) return null;// An all-caps token is a marker or acronym (`[TODO]`, `[WIP]`, `[NB]`), not a category.if (CATEGORY_STOPLIST.has(category.toLowerCase()) || (category.length > 1 && category === category.toUpperCase()) || /^[A-Z]{2,}[-_]/.test(category)) return null;+ if (USAGE_LABELS.has(category.toLowerCase())) {+ note('usage_label', `[${category}] is a dictionary usage label, so this line stays page text and is not read as a typed fact. ${FACT_FORM}`);+ return null;+ }+ // Structure comes from the masked text (code is not a slot), so read the remainder there.+ const visibleRest = /^\[[^\][]*\][ \t]+(\S.*)$/.exec(visibleContent)?.[1] ?? '';+ if (BARE_SLOT_RE.test(visibleRest)) {+ note('template_slot', `This line looks like an unfilled template ([${category}] followed by another [Slot]), so it stays page text and is not read as a typed fact. Leave templates as they are; ${FACT_FORM}`);+ return null;+ }+ if (SEPARATOR_CLAIM_RE.test(m[2])) {+ note('separator_claim', `The text after [${category}] starts with a separator, which marks a template or table row, so this line stays page text. ${FACT_FORM}`);+ return null;+ }let rest = m[2].trim();let effective: EffectiveRange | null = null;const q = parseEffectiveQualifier(rest);@@ -243,17 +286,22 @@ function parseFactContent(content: string, note: (reason: GrammarReason, messageconst tags = [...rest.matchAll(/(?:^|\s)#([A-Za-z][\w/-]*)/g)].map(t => t[1]);const claim = rest.replace(/(?:^|\s)#[A-Za-z][\w/-]*/g, '').replace(/\s+/g, ' ').trim();if (!claim) return null;+ if (PLACEHOLDER_CLAIM_RE.test(claim)) {+ note('placeholder_claim', `The claim after [${category}] is only a placeholder, so this line stays page text. Leave it until there is a real claim; ${FACT_FORM}`);+ return null;+ }const lower = category.toLowerCase();return { category, kind: (FACT_KINDS.has(lower) ? lower : 'fact') as GrammarFact['kind'], claim, tags, context, effective };}+/** The declared verb a typo most likely meant: within two edits and a third of the word, else none. */function nearest(type: string, declared: ReadonlySet<string>): string | null {let best: string | null = null; let bestScore = Infinity;for (const candidate of declared) {const d = levenshtein(type, candidate);if (d < bestScore) { bestScore = d; best = candidate; }}- return best;+ return bestScore <= 2 && bestScore <= Math.floor(type.length / 3) ? best : null;}function levenshtein(a: string, b: string): number {@@ -269,12 +317,22 @@ function levenshtein(a: string, b: string): number {return row[b.length];}-function parseRelationContent(content: string, declared: ReadonlySet<string> | null,+function parseRelationContent(content: string, original: string, declared: ReadonlySet<string> | null,note: (reason: GrammarReason, message: string) => void): Omit<GrammarRelation, 'line' | 'start' | 'end'> | null {const links = [...content.matchAll(LINK_RE)];if (!links.length) return null;const first = links[0];let prefix = content.slice(0, first.index).trim();+ // Masking blanks inline code, so a backticked type is read from the original line at the same offsets.+ const linkAt = original.indexOf(first[0]);+ const decorated = linkAt > 0 ? DECORATED_TYPE_RE.exec(original.slice(0, linkAt).trim()) : null;+ if (decorated && (decorated[1] || decorated[3] || decorated[4]) && (decorated[1] ?? '') === (decorated[3] ?? '')) {+ const type = normalizeRelationType(decorated[2]);+ if (type.includes('_') || declared?.has(type)) {+ note('type_punctuation', `"${type}" is wrapped in formatting or followed by a colon, so it is not read as a relation type and the link keeps its inferred type. Write it bare: \`- ${type} [[target]]\`.`);+ }+ return null;+ }let effective: EffectiveRange | null = null;// A qualifier may sit between the type and the link.const qualifierAt = prefix.search(/\s@[A-Za-z]/);@@ -316,7 +374,9 @@ function parseRelationContent(content: string, declared: ReadonlySet<string> | n}if (declared && declared.size && !declared.has(type)) {const near = nearest(type, declared);- note('undeclared_type', `"${type}" is not a link verb of the active schema pack, so the link keeps its inferred type.${near ? ` Did you mean ${near}?` : ''}`);+ note('undeclared_type', near+ ? `"${type}" is not a link verb of the active schema pack, so the link keeps its inferred type. Did you mean ${near}?`+ : `"${type}" is not a link verb of the active schema pack, so the link keeps its inferred type. The pack has no verb for this relationship: declare one in the pack's link_types, or use add_link with a declared type.`);return null;}return { type, context, effective };diff --git a/test/line-grammar-guards.test.ts b/test/line-grammar-guards.test.tsnew file mode 100644index 0000000000..371c75f037--- /dev/null+++ b/test/line-grammar-guards.test.ts@@ -0,0 +1,118 @@+/**+ * Line grammar guards for template and dictionary text (src/core/line-grammar.ts):+ * bare template slots, separator claims, placeholder claims and lexicographic+ * usage labels never parse as fact lines; decorated relation types explain+ * themselves; undeclared-type suggestions stay within a typo's distance. Every+ * guard reads one line, so a neighbor never changes a line's parse.+ */+import { describe, expect, test } from 'bun:test';+import { parseLineGrammar, USAGE_LABELS } from '../src/core/line-grammar.ts';++const BASE_VERBS = new Set(['works_at', 'advises', 'founded', 'invested_in', 'mentions', 'attended']);+const parse = (text: string, explainGuards = false) => parseLineGrammar(text, { declaredTypes: BASE_VERBS, explainGuards });+const facts = (text: string) => parse(text).facts;+const reasons = (text: string, explainGuards = false) => parse(text, explainGuards).diagnostics.map(d => d.reason);++describe('template and dictionary lines are not fact lines', () => {+ test('bare slots, separators, placeholders and usage labels', () => {+ for (const line of [+ '- [Time] - [Event]',+ '- [Time] [Event]',+ '- [Name]: [Role] at [Company]',+ '- [Date] — Kickoff',+ '- [Day] | Morning | Afternoon',+ '- [Step] = describe the step',+ '- [Owner] / [Due]',+ '- [Topic] > [Subtopic]',+ '- [Item] ...',+ '- [Note] TBD',+ '- [Value] <fill in>',+ '- [Answer] ___',+ '- [noun] a word for a thing',+ '- [informal] gonna, going to',+ '- [Slang] cheesy grin',+ '- [plural] mice',+ '- [transitive] to carry something',+ ]) expect(facts(line)).toEqual([]);+ });++ test('real fact lines keep parsing: links, wikilinks, escapes, code, negative numbers, slashes', () => {+ const kept = [+ '- [preference] Prefers oat milk #coffee (since the almond allergy)',+ '- [fact] value [label](https://example.invalid)',+ '- [fact] see [the guide][ref] for details',+ '- [event] Led the [[projects/pricing]] rework',+ '- [fact] -40 degrees is the lower operating limit',+ '- [fact] 3/4 of the team works remotely',+ '- [idea] Escape \\[Slot\\] literally',+ '- [technique] Use `[Event]` as the placeholder token in templates',+ '- [belief] Small teams win - most of the time',+ '- [commitment] Ship weekly (weekdays only)',+ ];+ for (const line of kept) expect(facts(line)).toHaveLength(1);+ });++ test('the usage-label list is lowercase and disjoint from the six named kinds', () => {+ for (const kind of ['event', 'preference', 'commitment', 'belief', 'fact', 'idea']) expect(USAGE_LABELS.has(kind)).toBe(false);+ for (const label of USAGE_LABELS) expect(label).toBe(label.toLowerCase());+ });+});++describe('guard diagnostics', () => {+ test('a template page stays quiet unless diagnostics are requested', () => {+ const template = '# Day plan\n\n- [Time] - [Event]\n- [Time] - [Event]\n';+ expect(reasons(template)).toEqual([]);+ expect(reasons(template, true)).toEqual(['template_slot', 'template_slot']);+ });++ test('on a page that uses the grammar, a refused line explains itself', () => {+ const page = '- [preference] Prefers tea\n- [noun] a thing\n- works_at [[companies/acme-example]]\n- [Idea] TBD\n';+ expect(reasons(page)).toEqual(['usage_label', 'placeholder_claim']);+ const message = parse(page).diagnostics[0].message;+ expect(message).toContain('stays page text');+ expect(message).toContain('- [preference] Prefers tea');+ });++ test('a placeholder message never asks the writer to fill the slot', () => {+ for (const d of parse('- [preference] Prefers tea\n- [Time] - [Event]\n- [Item] TBD').diagnostics) {+ expect(d.message).not.toMatch(/fill (it|the slot|in)/i);+ }+ });++ test('neighbor edits never change a line\'s parse', () => {+ const line = '- [preference] Prefers tea';+ for (const neighbor of ['- [Time] - [Event]', '- [Time] - [Event]\n- [Time] - [Event]', '- [noun] word', '']) {+ expect(parse(`${neighbor}\n${line}`).facts.map(f => f.claim)).toEqual(['Prefers tea']);+ expect(parse(`${line}\n${neighbor}`).facts.map(f => f.claim)).toEqual(['Prefers tea']);+ }+ });+});++describe('decorated relation types', () => {+ test('colon, bold and backticked types are reported, not read', () => {+ for (const line of ['- works_at: [[companies/acme]]', '- **works_at** [[companies/acme]]', '- `works_at` [[companies/acme]]', '- __advises__ [[companies/acme]]']) {+ const r = parse(line);+ expect(r.relations).toEqual([]);+ expect(r.diagnostics.map(d => d.reason)).toEqual(['type_punctuation']);+ expect(r.diagnostics[0].message).toMatch(/Write it bare: `- (works_at|advises) \[\[target\]\]`/);+ }+ });++ test('bold labels that are not types stay silent', () => {+ for (const line of ['- **Source:** [[companies/acme]]', '- **Note** [[companies/acme]]', '- Related: [[companies/acme]]']) {+ expect(parse(line).diagnostics).toEqual([]);+ }+ });+});++describe('undeclared-type suggestions', () => {+ test('a typo gets the declared verb it meant', () => {+ expect(parse('- wroks_at [[companies/acme]]').diagnostics[0].message).toContain('Did you mean works_at?');+ });++ test('an unrelated relationship never gets a substitute verb', () => {+ const message = parse('- board_member [[companies/acme]]').diagnostics[0].message;+ expect(message).not.toContain('Did you mean');+ expect(message).toContain('declare one in the pack');+ });+});