Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

line grammar: settings-bound link extraction (one snapshot per extraction, generation row, one watermark), agent-contract findings, get_page grammar_diagnostics, drain benchmark

garrytan0744648dd260
diff --git a/scripts/bench-link-extraction-drain.ts b/scripts/bench-link-extraction-drain.ts
new file mode 100644
index 0000000000..a2a349378c
--- /dev/null
+++ b/scripts/bench-link-extraction-drain.ts
@@ -0,0 +1,125 @@
+/**
+ * Link re-extraction drain benchmark: how long a brain takes to re-derive
+ * every page's links after the extraction watermark moves (a
+ * LINK_EXTRACTOR_VERSION_TS bump or a line-grammar setting change), and what
+ * put_page latency looks like with the grammar off and on.
+ *
+ * Seeds N synthetic pages (people with prose, typed relation lines and dated
+ * timelines; companies; notes with ordinary lists), runs one full extraction,
+ * then turns the grammar on (which moves the watermark the same way a version
+ * bump does) and times the complete drain with `extract --stale --catch-up`.
+ * A probe halfway through the drain reports the backlog and confirms reads
+ * still answer while it runs. Zero model calls.
+ *
+ * Usage: bun scripts/bench-link-extraction-drain.ts --pages 10000 [--json]
+ * DATABASE_URL=postgres://... bun scripts/bench-link-extraction-drain.ts --pages 100000 --json
+ * Postgres runs need an empty, disposable database (the script initializes the schema).
+ */
+import { performance } from 'node:perf_hooks';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { extractStaleFromDB } from '../src/commands/extract.ts';
+import { applyLineGrammarConfigChange } from '../src/core/line-grammar-config.ts';
+import { effectiveLinkExtractorWatermark } from '../src/core/link-extraction-watermark.ts';
+
+const arg = (name: string, fallback: string) => { const i = process.argv.indexOf(name); return i >= 0 ? process.argv[i + 1] : fallback; };
+const PAGES = Number(arg('--pages', '10000'));
+const WRITES = Number(arg('--writes', '200'));
+const json = process.argv.includes('--json');
+const ROLES = ['senior engineer', 'designer', 'product manager', 'head of sales', 'CTO'];
+
+function personBody(i: number, companies: number): string {
+ const c = (k: number) => `companies/company-${(i * 7 + k * 13) % companies}`;
+ return [
+ `Person ${i} works at [[${c(0)}]] as a ${ROLES[i % ROLES.length]} and advises [[${c(1)}]].`,
+ `Previously at [[${c(2)}]]; invested in [[${c(3)}]] early.`,
+ '',
+ `- works_at [[${c(0)}]] (since 20${10 + (i % 14)})`,
+ `- [preference] Prefers async updates #work`,
+ '- Ordinary list item about a project.',
+ `- Met [[people/person-${(i + 1) % Math.max(1, PAGES)}]] for coffee.`,
+ ].join('\n');
+}
+const personTimeline = (i: number, companies: number) => [
+ `- **2021-0${1 + (i % 9)}-01** | Joined [[companies/company-${(i * 7) % companies}]] as ${ROLES[i % ROLES.length]}`,
+ `- **2019-0${1 + (i % 9)}-15** | Left [[companies/company-${(i * 7 + 26) % companies}]]`,
+].join('\n');
+
+async function openEngine(): Promise<BrainEngine> {
+ if (process.env.DATABASE_URL) {
+ const { PostgresEngine } = await import('../src/core/postgres-engine.ts');
+ const engine = new PostgresEngine();
+ await engine.connect({ database_url: process.env.DATABASE_URL } as never);
+ await engine.initSchema();
+ return engine as unknown as BrainEngine;
+ }
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ return engine as unknown as BrainEngine;
+}
+
+const pct = (xs: number[], p: number) => { const s = [...xs].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.floor(p * s.length))]; };
+
+async function putLatency(engine: BrainEngine, label: string): Promise<{ p50: number; p95: number; p99: number }> {
+ const ctx: OperationContext = { engine, config: { engine: engine.kind } as never, logger: { info() {}, warn() {}, error() {} },
+ dryRun: false, remote: false, sourceId: 'default' };
+ const put = operationsByName['put_page'];
+ const ms: number[] = [];
+ for (let i = 0; i < WRITES; i++) {
+ const t = performance.now();
+ await put.handler(ctx, { slug: `notes/latency-${label}-${i}`, content: `---\ntype: person\ntitle: Latency ${label} ${i}\n---\n\nWritten in the ${label} arm.\n${personBody(i, Math.max(1, Math.floor(PAGES / 10)))}\n` });
+ ms.push(performance.now() - t);
+ }
+ return { p50: pct(ms, 0.5), p95: pct(ms, 0.95), p99: pct(ms, 0.99) };
+}
+
+async function main() {
+ const engine = await openEngine();
+ const companies = Math.max(1, Math.floor(PAGES / 10));
+ const people = Math.floor(PAGES * 0.6);
+ const notes = PAGES - companies - people;
+ const seedStart = performance.now();
+ for (let i = 0; i < companies; i++) await engine.putPage(`companies/company-${i}`, { type: 'company', title: `Company ${i}`, compiled_truth: `Company ${i} builds things.`, timeline: '', frontmatter: {} });
+ for (let i = 0; i < people; i++) await engine.putPage(`people/person-${i}`, { type: 'person', title: `Person ${i}`, compiled_truth: personBody(i, companies), timeline: personTimeline(i, companies), frontmatter: {} });
+ for (let i = 0; i < notes; i++) await engine.putPage(`notes/note-${i}`, { type: 'note', title: `Note ${i}`, compiled_truth: `- [Time] - [Event]\n- Agenda item ${i}\n- See [[people/person-${i % Math.max(1, people)}]]`, timeline: '', frontmatter: {} });
+ const seedMs = performance.now() - seedStart;
+
+ const opts = { dryRun: false, jsonMode: true, quiet: true, catchUp: true } as const;
+ let t = performance.now();
+ const first = await extractStaleFromDB(engine, opts);
+ const firstMs = performance.now() - t;
+ const latencyOff = await putLatency(engine, 'off');
+
+ const change = await applyLineGrammarConfigChange(engine, tx => tx.setConfig('line_grammar.enabled', 'true'));
+ const queued = await engine.countStalePagesForExtraction({ versionTs: await effectiveLinkExtractorWatermark(engine) });
+ t = performance.now();
+ const half = await extractStaleFromDB(engine, { ...opts, catchUp: false, timeBudgetMs: Math.max(1, firstMs / 2) });
+ const probeStart = performance.now();
+ const probe = await operationsByName['get_links'].handler({ engine, config: { engine: engine.kind } as never, logger: { info() {}, warn() {}, error() {} },
+ dryRun: false, remote: false, sourceId: 'default' }, { slug: 'people/person-1' }) as unknown[];
+ const probeMs = performance.now() - probeStart;
+ const midBacklog = await engine.countStalePagesForExtraction({ versionTs: await effectiveLinkExtractorWatermark(engine) });
+ const rest = await extractStaleFromDB(engine, opts);
+ const drainMs = performance.now() - t;
+ const latencyOn = await putLatency(engine, 'on');
+
+ const result = {
+ engine: engine.kind, pages: PAGES, seed_ms: Math.round(seedMs),
+ initial_extraction: { ms: Math.round(firstMs), pages: first.pagesProcessed, ms_per_page: +(firstMs / Math.max(1, first.pagesProcessed)).toFixed(2) },
+ toggle: { changed: change.changed, pages_queued: queued },
+ drain: { ms: Math.round(drainMs), pages: half.pagesProcessed + rest.pagesProcessed, ms_per_page: +(drainMs / Math.max(1, half.pagesProcessed + rest.pagesProcessed)).toFixed(2),
+ remaining: rest.staleRemaining, mid_drain_backlog: midBacklog, mid_drain_get_links_ms: +probeMs.toFixed(1), mid_drain_get_links_rows: Array.isArray(probe) ? probe.length : null },
+ put_page_ms: { grammar_off: latencyOff, grammar_on: latencyOn },
+ };
+ if (json) console.log(JSON.stringify(result, null, 2));
+ else {
+ console.log(`${result.engine}, ${PAGES} pages: initial extraction ${result.initial_extraction.ms} ms (${result.initial_extraction.ms_per_page} ms/page)`);
+ console.log(`toggle queued ${queued} pages; drain ${result.drain.ms} ms (${result.drain.ms_per_page} ms/page), ${result.drain.remaining} remaining; mid-drain backlog ${midBacklog}, get_links ${result.drain.mid_drain_get_links_ms} ms`);
+ console.log(`put_page p50/p95/p99 off ${latencyOff.p50.toFixed(1)}/${latencyOff.p95.toFixed(1)}/${latencyOff.p99.toFixed(1)} ms; on ${latencyOn.p50.toFixed(1)}/${latencyOn.p95.toFixed(1)}/${latencyOn.p99.toFixed(1)} ms`);
+ }
+ await engine.disconnect();
+}
+
+await main();
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 678e0c2583..65823d760b 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -371,7 +371,25 @@ export async function tryRunConfigEngineFree(args: string[]): Promise<boolean> {
* extraction, so they validate here too, and an explicit auto_chronicle set
* records the operator's answer to the default-on change.
*/
+/** Line-grammar keys commit with the extraction generation, so the graph follows the setting (core/line-grammar-config.ts). */
+async function changeLineGrammarConfig(engine: BrainEngine, mutate: (tx: BrainEngine) => Promise<void>): Promise<void> {
+ const { applyLineGrammarConfigChange, describeLineGrammarChange } = await import('../core/line-grammar-config.ts');
+ const change = await applyLineGrammarConfigChange(engine, mutate);
+ for (const line of (await describeLineGrammarChange(engine, change)).lines) console.error(`[config] ${line}`);
+}
+
async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value: string, force = false): Promise<void> {
+ const { isInternalConfigKey, isLineGrammarKey, invalidLineGrammarValue } = await import('../core/line-grammar-config.ts');
+ if (isInternalConfigKey(key)) {
+ console.error(`[config] ${key} is internal state gbrain maintains itself; it cannot be set. For the line grammar, set line_grammar.enabled instead.`);
+ process.exit(1);
+ }
+ if (isLineGrammarKey(key)) {
+ const err = invalidLineGrammarValue(key, value);
+ if (err) { console.error(`[config] ${err}`); process.exit(1); }
+ await changeLineGrammarConfig(engine, tx => tx.setConfig(key, value));
+ return;
+ }
if (key.startsWith('decide.')) {
const { validateDecideConfigValue } = await import('../core/ai/decide/config.ts');
const err = validateDecideConfigValue(key, value);
@@ -676,7 +694,8 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
console.error('Usage: gbrain config unset --pattern <prefix>');
process.exit(1);
}
- const keys = await engine.listConfigKeys(prefix);
+ const { isInternalConfigKey, isLineGrammarKey } = await import('../core/line-grammar-config.ts');
+ const keys = (await engine.listConfigKeys(prefix)).filter(k => !isInternalConfigKey(k));
// Dual-plane keys matching the prefix must ALSO leave the file mirror
// (codex re-review, this wave): a DB-only pattern delete would report
// success while the engine-free Stop hook keeps reading the mirror's
@@ -707,10 +726,14 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
return;
}
let deleted = 0;
- for (const k of keys) {
+ const grammarKeys = keys.filter(isLineGrammarKey);
+ for (const k of keys.filter(k => !isLineGrammarKey(k))) {
const n = await engine.unsetConfig(k);
if (n > 0) deleted += n;
}
+ if (grammarKeys.length) {
+ await changeLineGrammarConfig(engine, async tx => { for (const k of grammarKeys) deleted += await tx.unsetConfig(k); });
+ }
console.log(`Unset ${deleted} key(s) matching "${prefix}":`);
for (const k of keys) console.log(` - ${k}`);
for (const k of fileSwept) {
@@ -826,7 +849,14 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
}
return;
}
- const n = await engine.unsetConfig(key);
+ const { isInternalConfigKey, isLineGrammarKey } = await import('../core/line-grammar-config.ts');
+ if (isInternalConfigKey(key)) {
+ console.error(`[config] ${key} is internal state gbrain maintains itself; it cannot be unset.`);
+ process.exit(1);
+ }
+ let n = 0;
+ if (isLineGrammarKey(key)) await changeLineGrammarConfig(engine, async tx => { n = await tx.unsetConfig(key); });
+ else n = await engine.unsetConfig(key);
if (n > 0) {
console.log(`Unset ${key}${key === 'auto_chronicle' ? AUTO_CHRONICLE_UNSET_NOTE : ''}`);
if (key === 'facts.default_visibility') await restampVisibilityPosture(null);
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index 3408caf89c..bfd2a2d4d7 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -13,7 +13,7 @@ import { probeSourceGitState } from '../../../core/git-head.ts';
import { lagFromContentMs, loadSyncFreshnessSources, resolveStalenessCeilingSeconds } from '../../../core/source-health.ts';
import { resolveEnvNumber, resolveHoursEnv, warnOnceForEnv } from '../../../core/env-number.ts';
import { CHUNKER_VERSION } from '../../../core/chunkers/code.ts';
-import { LINK_EXTRACTOR_VERSION_TS } from '../../../core/link-extraction.ts';
+import { effectiveLinkExtractorWatermark } from '../../../core/link-extraction-watermark.ts';
import { previewMentionPass } from '../../../core/mentions/stale.ts';
import { isUndefinedColumnError } from '../../../core/utils.ts';
import {
@@ -120,13 +120,15 @@ export async function checkLinksExtractionLag(
// Vacuous-skip tiny brains unless explicitly source-scoped. Shared floor
// const so the sync nudge (D6/C4) skips on the exact same predicate.
if (total < EXTRACTION_LAG_MIN_PAGES && !sourceId) {
- return { name, status: 'ok', message: `Extraction lag not applicable (${total} pages — too few to assess)` };
+ // Too few pages to grade a percentage, but the exact backlog still tells an operator whether a re-extraction finished.
+ const pending = await engine.countStalePagesForExtraction({ versionTs: await effectiveLinkExtractorWatermark(engine) }).catch(() => null);
+ return { name, status: 'ok', message: `Extraction lag not applicable (${total} pages — too few to assess)${pending ? `; ${pending} page(s) pending link extraction (gbrain extract --stale finishes them)` : ''}` };
}
// #5761: a page left stale only by an unresolved attendee, and not edited
// since, is attendance-blocked: `extract --stale` cannot clear it, so it
// is reported apart from lag. Pre-v180 brains have no marker column.
- const versionTs = LINK_EXTRACTOR_VERSION_TS;
+ const versionTs = await effectiveLinkExtractorWatermark(engine);
let stale: number;
let attendanceBlocked = 0;
try {
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index bccb12223f..91ed374069 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -48,13 +48,15 @@ import type { PageType } from '../core/types.ts';
import { parseMarkdown } from '../core/markdown.ts';
import { resolveCandidateSources, resolveLinkFallbackDefault, loadLinkPageMetadata, capturedLinkEndpoints, fileLinkOwnership, replaceFileLinks, replacePageFileLinks, type LinkPageMetadata } from '../core/link-reconciliation.ts';
import { collectWantedLinks, isWantedPagesEnabled } from '../core/wanted-links.ts';
-import { lineGrammarOptions, statedRelationTypes } from '../core/line-grammar.ts';
+import { readLineGrammarSettings, statedRelationTypes } from '../core/line-grammar.ts';
+import { effectiveLinkExtractorWatermark, linkExtractorWatermarkFor } from '../core/link-extraction-watermark.ts';
+import { DerivedLinkSettingsChangedError } from '../core/derived-links.ts';
export { reconcileSourceLinks, type SourceLinkReconciliationResult } from '../core/link-reconciliation.ts';
export { extractMarkdownLinks } from '../core/link-extraction.ts';
import {
extractPageLinks, parseTimelineEntries, deriveTimelineAnchor, inferLinkType, makeResolver,
attendanceEvidenceRanges, hasAttendanceEvidence, resolvedLinkCandidate, orientCanonicalAttendance, extractMarkdownLinks,
- extractFrontmatterLinks, isGlobalBasenameEnabled, isCrossSourceLinksEnabled, LINK_EXTRACTOR_VERSION_TS,
+ extractFrontmatterLinks, isGlobalBasenameEnabled, isCrossSourceLinksEnabled,
WIKILINK_BASENAME_LINK_TYPE,
buildBasenameIndex, queryBasenameIndex, stripCodeBlocks, normalizeBasename,
parseInlineCitationTimelineEntries,
@@ -173,7 +175,7 @@ async function snapshotStampTimes(
refs: Array<{ slug: string; source_id: string }>,
): Promise<Map<string, string>> {
const out = new Map<string, string>();
- const versionTs = LINK_EXTRACTOR_VERSION_TS;
+ const versionTs = await effectiveLinkExtractorWatermark(engine);
const versionMs = Date.parse(versionTs);
for (let i = 0; i < refs.length; i += BATCH_SIZE) {
const batch = refs.slice(i, i + BATCH_SIZE);
@@ -1871,6 +1873,10 @@ async function extractLinksFromDB(
// links_extraction_lag doctor signal. Non-dry-run only.
const processedRefs: Array<{ slug: string; source_id: string }> = [];
+ // One line-grammar settings snapshot for the run; publication refuses a page if the settings move meanwhile.
+ const grammar = await readLineGrammarSettings(engine);
+ const lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };
+ let skippedSettingsChanged = 0;
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
progress.start('extract.links_db', walkRefs.length);
@@ -1897,7 +1903,7 @@ async function extractLinksFromDB(
// basename lookup; off by default for back-compat.
const extracted = await extractPageLinks(
slug, fullContent, page.frontmatter, page.type, resolver,
- { skipFrontmatter: !includeFrontmatter, globalBasename, pack, lineGrammar: await lineGrammarOptions(engine), targetType: (targetSlug, targetSourceId) => {
+ { skipFrontmatter: !includeFrontmatter, globalBasename, pack, lineGrammar, targetType: (targetSlug, targetSourceId) => {
const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, slug,
source_id, allSlugs, slugToSources, federatedSourceIds.has(source_id), { crossSource, defaultSourceId: linkDefaultSourceId });
return resolved.ok ? targetMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type : undefined;
@@ -1950,11 +1956,17 @@ async function extractLinksFromDB(
crossSourceAllowed: federatedSourceIds.has(source_id) || crossSource, resolve: c => resolveCandidateSources(c, slug, source_id,
allSlugs, slugToSources, federatedSourceIds.has(source_id), { crossSource, defaultSourceId: linkDefaultSourceId }) }) : [];
const written = await engine.replaceDerivedLinks({ slug, sourceId: source_id, expectedRevision: snapshot.revision,
- sourceIncarnation: snapshot.sourceIncarnation }, batch, { includeFrontmatter,
+ sourceIncarnation: snapshot.sourceIncarnation }, batch, { includeFrontmatter, lineGrammar: grammar,
wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] : ['body'], rows: wanted },
expectedEndpoints: capturedLinkEndpoints(batch, targetMetadata) });
created += written.created;
} catch (error) {
+ if (error instanceof DerivedLinkSettingsChangedError) {
+ // The line-grammar settings changed mid-run: this page stays stale and the next extraction derives it.
+ skippedSettingsChanged++;
+ progress.tick(1);
+ continue;
+ }
if (jsonMode) process.stderr.write(JSON.stringify({ event: 'batch_error', size: batch.length, code: 'graph_write_failed' }) + '\n');
throw error;
}
@@ -1980,6 +1992,7 @@ async function extractLinksFromDB(
const label = dryRun ? '(dry run) would create' : 'created';
console.log(`Links: ${label} ${created} from ${processed} pages (db source)`);
if (skippedAttendanceIncomplete) console.log(`Skipped ${skippedAttendanceIncomplete} page(s) with unresolved attendance; prior links and extraction watermarks were preserved.`);
+ if (skippedSettingsChanged) console.log(`Skipped ${skippedSettingsChanged} page(s) because the line-grammar settings changed during this run; they stay stale. Run \`gbrain extract --stale\` to finish them.`);
if (skippedMissingTarget > 0) {
console.log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);
}
@@ -2004,7 +2017,8 @@ async function extractLinksFromDB(
// #2589: the counters ride the return value so machine consumers (and the
// --json path, which has no summary event on this path) can see the drops —
// "counted, never silent" must hold beyond human-mode console lines.
- return { created, pages: processed, unresolved, skippedMissingTarget, skippedCrossSource, skippedAttendanceIncomplete };
+ return { created, pages: processed, unresolved, skippedMissingTarget, skippedCrossSource, skippedAttendanceIncomplete,
+ ...(skippedSettingsChanged ? { skippedSettingsChanged } : {}) };
}
/**
@@ -2047,7 +2061,10 @@ export async function extractStaleFromDB(
const includeFrontmatter = opts.includeFrontmatter ?? await resolveIncludeFrontmatter(engine);
const log = opts.quiet ? (..._args: unknown[]) => {} : console.log;
const timeBudgetMs = opts.timeBudgetMs ?? STALE_TIME_BUDGET_MS;
- const versionTs = LINK_EXTRACTOR_VERSION_TS;
+ // One line-grammar settings snapshot for the run: it fixes the watermark and how relation lines are read.
+ const grammar = await readLineGrammarSettings(engine);
+ const lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };
+ const versionTs = linkExtractorWatermarkFor(grammar.generation);
// Pre-flight count — cheap indexed COUNT. dry-run reports and returns.
const totalStale = await engine.countStalePagesForExtraction({ sourceId: sourceIdFilter, versionTs });
@@ -2129,6 +2146,7 @@ export async function extractStaleFromDB(
// design (source isolation) unless the #3908 flag is on, but distinct
// from a genuinely missing target.
let skippedCrossSource = 0;
+ let skippedChanged = 0;
const wantedEnabled = await isWantedPagesEnabled(engine);
for (;;) {
@@ -2157,7 +2175,7 @@ export async function extractStaleFromDB(
const resolver = resolvers.get(page.source_id)!;
const extracted = await extractPageLinks(
page.slug, fullContent, snapshot.page.frontmatter, snapshot.page.type, resolver,
- { skipFrontmatter: !includeFrontmatter, globalBasename, pack, lineGrammar: await lineGrammarOptions(engine), targetType: (targetSlug, targetSourceId) => {
+ { skipFrontmatter: !includeFrontmatter, globalBasename, pack, lineGrammar, targetType: (targetSlug, targetSourceId) => {
const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, page.slug,
page.source_id, allSlugs, slugToSources, federatedSourceIds.has(page.source_id), { crossSource, defaultSourceId: linkDefaultSourceId });
return resolved.ok ? targetMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type : undefined;
@@ -2186,10 +2204,17 @@ export async function extractStaleFromDB(
frontmatterUnresolved: includeFrontmatter ? extracted.unresolved : [], originSourceId: page.source_id,
crossSourceAllowed: federatedSourceIds.has(page.source_id) || crossSource, resolve: c => resolveCandidateSources(c, page.slug,
page.source_id, allSlugs, slugToSources, federatedSourceIds.has(page.source_id), { crossSource, defaultSourceId: linkDefaultSourceId }) }) : [];
- const linkOpts = { includeFrontmatter, expectedEndpoints: capturedLinkEndpoints(linkRows, targetMetadata),
+ const linkOpts = { includeFrontmatter, lineGrammar: grammar, expectedEndpoints: capturedLinkEndpoints(linkRows, targetMetadata),
wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] as const : ['body'] as const, rows: wanted } };
const stampIso = page.updated_at.getTime() >= Date.parse(versionTs) ? page.updated_at_iso : versionTs;
- const written = await engine.replaceDerivedLinks(origin, linkRows, linkOpts);
+ let written: { created: number; removed: number };
+ try {
+ written = await engine.replaceDerivedLinks(origin, linkRows, linkOpts);
+ } catch (error) {
+ // The line-grammar settings changed mid-run: the page stays stale (not stamped) and the next run derives it.
+ if (error instanceof DerivedLinkSettingsChangedError) { skippedChanged++; continue; }
+ throw error;
+ }
linksCreated += written.created;
await retractRemovedTimelineEntries(engine, page.slug, page.source_id, fullContent);
for (const entry of parseTimelineEntries(fullContent)) {
@@ -2246,6 +2271,7 @@ export async function extractStaleFromDB(
else log(`Extract --stale: ${linksCreated} link(s) + ${timelineCreated} timeline entr(ies) from ${pagesProcessed} page(s).`);
if (mentionLine) log(mentionLine);
if (skippedAttendanceIncomplete) log(`Skipped ${skippedAttendanceIncomplete} page(s) with unresolved attendance; prior links and extraction watermarks were preserved.`);
+ if (skippedChanged) log(`Skipped ${skippedChanged} page(s) because the line-grammar settings changed during this run; they stay stale. Re-run \`gbrain extract --stale\` to finish them.`);
if (skippedMissingTarget > 0) {
log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);
}
@@ -2260,11 +2286,12 @@ export async function extractStaleFromDB(
action: 'extract_stale_done', links_created: linksCreated, timeline_created: timelineCreated,
pages_processed: pagesProcessed, stale_remaining: staleRemaining, budget_hit: budgetHit,
skipped_missing_target: skippedMissingTarget, skipped_cross_source: skippedCrossSource,
- ...(skippedAttendanceIncomplete ? { skipped_attendance_incomplete: skippedAttendanceIncomplete } : {}), ...mentionJsonFields(mentions),
+ ...(skippedAttendanceIncomplete ? { skipped_attendance_incomplete: skippedAttendanceIncomplete } : {}),
+ ...(skippedChanged ? { skipped_changed: skippedChanged } : {}), ...mentionJsonFields(mentions),
}) + '\n');
}
return { linksCreated, timelineCreated, pagesProcessed, staleRemaining, skippedMissingTarget, skippedCrossSource,
- ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}), mentions };
+ ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skippedChanged } : {}), mentions };
}
/**
diff --git a/src/commands/lint.ts b/src/commands/lint.ts
index 8bd8066160..cfb5d78de5 100644
--- a/src/commands/lint.ts
+++ b/src/commands/lint.ts
@@ -147,9 +147,13 @@ export function lintContent(content: string, filePath: string, opts: LintContent
}
// Rule: line-grammar near-misses (a relation or fact line that will not be
- // read as written). Read-only; the fix is in each message.
+ // read as written). Read-only; the fix is in each message. Syntax-only: a
+ // file check reads no brain settings or schema pack, so it never implies an
+ // edge will be stored; `gbrain get <slug> --grammar-diagnostics` is the
+ // effective check against the brain.
for (const d of parseLineGrammar(content).diagnostics) {
- issues.push({ file: filePath, line: d.line, rule: 'line-grammar', message: `${d.message} (${d.reason})`, fixable: false });
+ issues.push({ file: filePath, line: d.line, rule: 'line-grammar',
+ message: `${d.message} (${d.reason}; syntax-only check: run \`gbrain get <slug> --grammar-diagnostics\` for what the brain reads)`, fixable: false });
}
// Rule: LLM preamble artifacts
diff --git a/src/commands/sync/report.ts b/src/commands/sync/report.ts
index 2be063560c..c3c52234a2 100644
--- a/src/commands/sync/report.ts
+++ b/src/commands/sync/report.ts
@@ -61,7 +61,7 @@ export async function maybeBackupCoverageRefresh(engine: BrainEngine): Promise<v
export async function maybeExtractionNudge(engine: BrainEngine, sourceId?: string): Promise<void> {
if (process.env.GBRAIN_SYNC_NO_EXTRACT_NUDGE) return;
try {
- const { LINK_EXTRACTOR_VERSION_TS } = await import('../../core/link-extraction.ts');
+ const { effectiveLinkExtractorWatermark } = await import('../../core/link-extraction-watermark.ts');
// D3/C4: resolve the warn threshold + vacuous-skip floor through the SAME
// helpers the doctor check uses (dynamic import keeps doctor.ts off sync's
// eager-load path) so "the nudge fires iff doctor would warn" can't drift.
@@ -76,7 +76,7 @@ export async function maybeExtractionNudge(engine: BrainEngine, sourceId?: strin
// Match doctor's predicate EXACTLY (C4): skip tiny brains only when NOT
// source-scoped (a small explicit source IS assessed, like orphan_ratio).
if (total < EXTRACTION_LAG_MIN_PAGES && !sourceId) return;
- const stale = await engine.countStalePagesForExtraction({ sourceId, versionTs: LINK_EXTRACTOR_VERSION_TS });
+ const stale = await engine.countStalePagesForExtraction({ sourceId, versionTs: await effectiveLinkExtractorWatermark(engine) });
const warnPct = _resolveEnvNumber('GBRAIN_EXTRACTION_LAG_WARN_PCT', EXTRACTION_LAG_WARN_PCT_DEFAULT, { unit: '%' });
if ((stale / total) * 100 > warnPct) {
serr(`[sync] ${stale} page(s) have un-extracted edges — run 'gbrain extract --stale'`);
diff --git a/src/core/cycle/edge-contradictions.ts b/src/core/cycle/edge-contradictions.ts
index c5414b8196..687f714a38 100644
--- a/src/core/cycle/edge-contradictions.ts
+++ b/src/core/cycle/edge-contradictions.ts
@@ -21,6 +21,8 @@
* different targets whose combined evidence hash has no proposal yet.
* Bounded by max_subjects and the cycle budget meter (max_usd).
*/
+import { LINK_EXTRACTION_GENERATION_KEY } from '../line-grammar.ts';
+import { linkExtractorWatermarkFor } from '../link-extraction-watermark.ts';
import { createHash } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import type { PhaseResult } from '../cycle.ts';
@@ -181,6 +183,10 @@ interface SubjectGroup { sourceId: string; fromId: number; slug: string; title:
async function findCandidateGroups(engine: BrainEngine, maxSubjects: number): Promise<SubjectGroup[]> {
const today = utcToday();
+ // After a line-grammar change, a subject whose links have not been re-derived yet is skipped: no closure is
+ // decided on a half-reconciled graph. Before any change (generation unset) every subject is eligible, as before.
+ const generation = await engine.getConfig(LINK_EXTRACTION_GENERATION_KEY);
+ const pendingCutoff = generation ? linkExtractorWatermarkFor(generation) : null;
const rows = await engine.executeRaw<CandidateRow>(
`WITH live AS (
SELECT lr.* FROM link_relationships lr
@@ -195,9 +201,10 @@ async function findCandidateGroups(engine: BrainEngine, maxSubjects: number): Pr
f.slug AS subject_slug, f.title AS subject_title, t.slug AS target_slug, t.title AS target_title
FROM live l JOIN multi m USING (source_id, from_page_id, link_type)
JOIN pages f ON f.id = l.from_page_id AND f.deleted_at IS NULL
+ AND ($3::timestamptz IS NULL OR f.links_extracted_at >= $3::timestamptz)
JOIN pages t ON t.id = l.to_page_id AND t.deleted_at IS NULL
ORDER BY l.from_page_id, l.link_type, l.last_start NULLS FIRST, t.slug`,
- [today, maxSubjects]);
+ [today, maxSubjects, pendingCutoff]);
const groups = new Map<string, SubjectGroup>();
for (const r of rows) {
const key = `${r.from_page_id}\0${r.link_type}`;
diff --git a/src/core/derived-links.ts b/src/core/derived-links.ts
index f5354cc481..d60edba567 100644
--- a/src/core/derived-links.ts
+++ b/src/core/derived-links.ts
@@ -5,7 +5,7 @@ import { sanitizeForJsonb } from './batch-rows.ts';
import { replaceWantedLinks, type WantedLinksReplacement } from './wanted-links-store.ts';
import { applyTemporalEvidence, relationshipKeysForOrigin } from './link-temporal-apply.ts';
import { primeRelationSemantics } from './link-semantics-pack.ts';
-import { effectiveRangesEnabled } from './line-grammar.ts';
+import { effectiveRangesEnabled, LINK_EXTRACTION_GENERATION_KEY, type LineGrammarSettings } from './line-grammar.ts';
export interface DerivedLinkOrigin {
slug: string;
@@ -21,6 +21,13 @@ export interface DerivedLinkReplacementOptions {
expectedEndpoints?: Array<{ slug: string; sourceId: string; revision: string }>;
/** The origin's unresolved authored references, replaced in the same transaction (wanted pages). */
wanted?: WantedLinksReplacement;
+ /**
+ * The line-grammar settings the links were prepared under. Publication uses
+ * them for validity ranges (never a second read) and refuses with
+ * DerivedLinkSettingsChangedError when the extraction generation moved since,
+ * so a page is never published from one setting and ranged from another.
+ */
+ lineGrammar?: LineGrammarSettings;
}
export class DerivedLinkRepairRequiredError extends Error {
@@ -35,6 +42,11 @@ export class DerivedLinkEndpointChangedError extends Error {
readonly code = 'revision_conflict';
}
+/** The line-grammar settings changed between preparation and publication; the page stays stale and re-extracts. */
+export class DerivedLinkSettingsChangedError extends DerivedLinkEndpointChangedError {
+ constructor() { super('Line-grammar settings changed after these links were prepared'); this.name = 'DerivedLinkSettingsChangedError'; }
+}
+
export async function applyAttendanceDelta(tx: Pick<BrainEngine, 'executeRaw' | 'addLinksBatch'>,
origin: { id: string; slug: string; source_id: string; type: string }, remove: string[], additions: LinkBatchInput[]) {
if (origin.type !== 'meeting' || remove.length > 512 || additions.length > 256
@@ -88,6 +100,11 @@ export async function replaceDerivedLinks(
await tx.lockPageKeys([{ sourceId: origin.sourceId, slug: origin.slug }, ...rows.flatMap(row => [
{ sourceId: row.from_source_id!, slug: row.from_slug }, { sourceId: row.to_source_id!, slug: row.to_slug },
])]);
+ if (opts.lineGrammar) {
+ // FOR SHARE: a concurrent setting change (which updates this row) waits for this publication, or this one sees it.
+ const [gen] = await tx.executeRaw<{ value: string }>('SELECT value FROM config WHERE key = $1 FOR SHARE', [LINK_EXTRACTION_GENERATION_KEY]);
+ if ((gen?.value ?? null) !== opts.lineGrammar.generation) throw new DerivedLinkSettingsChangedError();
+ }
const snapshot = await tx.readPageSnapshot(origin.slug, { sourceId: origin.sourceId });
assertPageRevision(snapshot, { expectedRevision: origin.expectedRevision });
if (!snapshot || snapshot.sourceIncarnation !== origin.sourceIncarnation || snapshot.page.deleted_at) {
@@ -99,7 +116,8 @@ export async function replaceDerivedLinks(
// of the same derived projection: captured before, replaced after.
const temporalKeysBefore = await relationshipKeysForOrigin(tx, Number(id));
const withTemporal = async (result: { created: number; removed: number }) => {
- await applyTemporalEvidence(tx, snapshot.page, rows, temporalKeysBefore, { inlineRanges: await effectiveRangesEnabled(tx) });
+ await applyTemporalEvidence(tx, snapshot.page, rows, temporalKeysBefore,
+ { inlineRanges: opts.lineGrammar ? opts.lineGrammar.effectiveRanges : await effectiveRangesEnabled(tx) });
return result;
};
if (opts.includeFrontmatter !== false && !opts.preserveExisting) {
diff --git a/src/core/engine-sql/health.ts b/src/core/engine-sql/health.ts
index 3ed7779108..88ab217db5 100644
--- a/src/core/engine-sql/health.ts
+++ b/src/core/engine-sql/health.ts
@@ -39,7 +39,7 @@
*/
import type { BrainHealth } from '../types.ts';
import { MIN_ENTITY_PAGES_FOR_COVERAGE } from '../types.ts';
-import { LINK_EXTRACTOR_VERSION_TS } from '../link-extraction.ts';
+import { effectiveLinkExtractorWatermark } from '../link-extraction-watermark.ts';
import { QUARANTINE_FILTER_FRAGMENT } from '../quarantine.ts';
import { loadOrphanPolicyOverrides, orphanExclusionSql } from '../orphan-policy.ts';
import { loadTimelineGradedPredicate } from '../timeline-grading.ts';
@@ -204,10 +204,11 @@ export async function getHealth(
LIMIT 5
`);
+ const watermark = await effectiveLinkExtractorWatermark(deps);
const stalePages = scope === null
- ? await deps.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })
+ ? await deps.countStalePagesForExtraction({ versionTs: watermark })
: (await Promise.all(scope.map(sourceId =>
- deps.countStalePagesForExtraction({ sourceId, versionTs: LINK_EXTRACTOR_VERSION_TS }),
+ deps.countStalePagesForExtraction({ sourceId, versionTs: watermark }),
))).reduce((a, b) => a + b, 0);
let linkablePageCount = 0;
diff --git a/src/core/line-grammar-config.ts b/src/core/line-grammar-config.ts
new file mode 100644
index 0000000000..748d3ba5c4
--- /dev/null
+++ b/src/core/line-grammar-config.ts
@@ -0,0 +1,69 @@
+/**
+ * Changing a line-grammar setting so the graph follows it. The setting and
+ * the extraction generation (`_internal.link_extraction_generation`) commit
+ * in one transaction, and the generation moves only when the effective
+ * extraction behavior changes (`lineGrammarFingerprint`), so `set`, `unset`
+ * and pattern unset converge the same way and repeated identical settings are
+ * no-ops. A moved generation makes every page's links stale; managed link
+ * extraction (dream cycle, managed sync, the serve owner) or
+ * `gbrain extract --stale` re-derives them.
+ */
+import type { BrainEngine } from './engine.ts';
+import {
+ LINE_GRAMMAR_KEYS, LINK_EXTRACTION_GENERATION_KEY, lineGrammarFingerprint, parseGrammarBoolean, readLineGrammarSettings,
+ type LineGrammarSettings,
+} from './line-grammar.ts';
+import { linkExtractorWatermarkFor } from './link-extraction-watermark.ts';
+
+export const isLineGrammarKey = (key: string): key is (typeof LINE_GRAMMAR_KEYS)[number] =>
+ (LINE_GRAMMAR_KEYS as readonly string[]).includes(key);
+
+/** Keys `gbrain config` never sets or unsets on a user's behalf. */
+export const isInternalConfigKey = (key: string) => key.startsWith('_internal.');
+
+/** A refusal message for a value that is not a grammar boolean, or null when the value is valid. */
+export function invalidLineGrammarValue(key: string, value: string): string | null {
+ return parseGrammarBoolean(value) === 'invalid'
+ ? `${key} takes true or false (also accepted: 1/0, yes/no, on/off); "${value}" was not saved. Run: gbrain config set ${key} true`
+ : null;
+}
+
+export interface LineGrammarChange {
+ before: LineGrammarSettings;
+ after: LineGrammarSettings;
+ changed: boolean;
+ generation: string | null;
+}
+
+/** Run `mutate` and move the extraction generation if the effective behavior changed, in one transaction. */
+export async function applyLineGrammarConfigChange(engine: BrainEngine, mutate: (tx: BrainEngine) => Promise<void>): Promise<LineGrammarChange> {
+ return engine.transaction(async tx => {
+ // Lock the generation row (when it exists) so a concurrent change serializes behind this one.
+ await tx.executeRaw('SELECT value FROM config WHERE key = $1 FOR UPDATE', [LINK_EXTRACTION_GENERATION_KEY]);
+ const before = await readLineGrammarSettings(tx);
+ await mutate(tx);
+ const after = await readLineGrammarSettings(tx);
+ if (lineGrammarFingerprint(before) === lineGrammarFingerprint(after)) return { before, after, changed: false, generation: before.generation };
+ // The database clock, at microsecond precision: page stamps come from the same clock.
+ const [row] = await tx.executeRaw<{ at: string }>(`SELECT to_char(clock_timestamp() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS at`);
+ await tx.setConfig(LINK_EXTRACTION_GENERATION_KEY, row.at);
+ return { before, after: { ...after, generation: row.at }, changed: true, generation: row.at };
+ });
+}
+
+/** What changed and what happens next, for the operator. */
+export async function describeLineGrammarChange(engine: BrainEngine, change: LineGrammarChange): Promise<{ lines: string[]; json: Record<string, unknown> }> {
+ const state = (s: LineGrammarSettings) => s.enabled ? `on (undeclared types ${s.allowUndeclaredTypes ? 'allowed' : 'refused'}, ranges ${s.effectiveRanges ? 'stored' : 'not stored'})` : 'off';
+ if (!change.changed) {
+ return { lines: [`Line grammar is ${state(change.after)}; extraction behavior did not change, so no pages need re-extraction.`],
+ json: { effective: change.after, changed: false, pages_queued: 0 } };
+ }
+ const queued = await engine.countStalePagesForExtraction({ versionTs: linkExtractorWatermarkFor(change.generation) }).catch(() => null);
+ const lines = [
+ `Line grammar is now ${state(change.after)} (was ${state(change.before)}).`,
+ `${queued ?? 'All'} page(s) are queued for link re-extraction (zero model calls). Managed extraction (dream cycle, managed sync, a running \`gbrain serve\`) finishes it in the background; run \`gbrain extract --stale\` to finish now.`,
+ 'Verify: `gbrain doctor --json` reports links_extraction_lag 0 when done. A gbrain process started before this change keeps the old setting until it restarts.',
+ ];
+ return { lines, json: { effective: change.after, previous: change.before, changed: true, pages_queued: queued,
+ next: { argv: ['gbrain', 'extract', '--stale'] }, verify: { argv: ['gbrain', 'doctor', '--json'] } } };
+}
diff --git a/src/core/line-grammar-report.ts b/src/core/line-grammar-report.ts
new file mode 100644
index 0000000000..684f722058
--- /dev/null
+++ b/src/core/line-grammar-report.ts
@@ -0,0 +1,108 @@
+/**
+ * What the line grammar reads from one page body, with every refused line
+ * explained in the agent operator contract's terms (`code`, `why`, a
+ * canonical form where one exists, and a read-only `verify`). Shared by the
+ * put_page advisory (first five findings) and `get_page grammar_diagnostics`
+ * (all findings), so a writer can always reach the full list.
+ *
+ * Effective mode: the brain's grammar settings and the source's active pack
+ * verbs. A failed settings or pack read is reported as `diagnostics_failed`,
+ * never as an ungated parse.
+ */
+import type { BrainEngine } from './engine.ts';
+import { parseLineGrammar, readLineGrammarSettings, type GrammarDiagnostic } from './line-grammar.ts';
+import { loadActivePackForEngine } from './schema-pack/engine-resolution.ts';
+import { readFix } from './ops/op-fix.ts';
+import type { Action } from './agent-output.ts';
+
+export interface LineGrammarFinding {
+ severity: 'warning';
+ validator: 'line-grammar';
+ code: GrammarDiagnostic['reason'];
+ reason: GrammarDiagnostic['reason'];
+ line: number;
+ text: string;
+ message: string;
+ why: string;
+ canonical?: string;
+ verify: Action;
+}
+
+export type LineGrammarReport =
+ | { state: 'diagnostics_failed'; message: string; fix: Action }
+ | {
+ state: 'ok';
+ enabled: boolean;
+ mode: 'effective';
+ pack: string | null;
+ relations: number;
+ facts: number;
+ findings: LineGrammarFinding[];
+ total: number;
+ details_truncated: boolean;
+ more?: Action;
+ };
+
+const WHY: Record<GrammarDiagnostic['reason'], string> = {
+ prose_tail: 'A relation line is one type, one link and at most one trailing (context); extra words make it a sentence.',
+ two_links: 'A relation line names exactly one link.',
+ stoplist_type: 'The word before the link is too generic to be a relation type.',
+ undeclared_type: 'Relation types are limited to the active schema pack\'s link verbs.',
+ unknown_qualifier: 'Only @effective[start,end) (alias @valid) is read.',
+ invalid_range: 'Validity ranges take ISO dates with the start before the end.',
+ template_slot: 'The line holds another bare [Slot], which marks an unfilled template, not a typed fact.',
+ separator_claim: 'The claim starts with a separator, which marks a template or table row.',
+ placeholder_claim: 'The claim is only a placeholder.',
+ usage_label: 'The bracketed word is a dictionary usage label, not a fact category.',
+ type_punctuation: 'A relation type is read only when written bare, without formatting or a colon.',
+};
+
+const verifyFor = (slug: string, sourceId: string): Action => readFix(
+ 'Re-reads this page\'s line-grammar findings after an edit, read-only.',
+ { argv: ['gbrain', 'get', '--source', sourceId, '--grammar-diagnostics', '--', slug],
+ mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId, grammar_diagnostics: true } } });
+
+/** The bare form of a decorated relation line (`- **works_at** [[x]]` -> `- works_at [[x]]`). */
+function canonicalLine(d: GrammarDiagnostic): string | undefined {
+ if (d.reason !== 'type_punctuation') return undefined;
+ const m = /^(\s*(?:[-*+]|\d{1,9}[.)])\s+)(?:\*\*|__|`)?([A-Za-z][A-Za-z0-9_-]*?)(?:\*\*|__|`)?:?(\s+.*)$/.exec(d.text);
+ return m ? `${m[1]}${m[2]}${m[3]}` : undefined;
+}
+
+export async function lineGrammarReport(engine: BrainEngine, opts: {
+ slug: string; sourceId: string; body: string; limit?: number;
+}): Promise<LineGrammarReport> {
+ let settings: Awaited<ReturnType<typeof readLineGrammarSettings>>;
+ let declaredTypes: Set<string> | null = null;
+ let pack: string | null = null;
+ try {
+ settings = await readLineGrammarSettings(engine);
+ if (!settings.allowUndeclaredTypes) {
+ const resolved = await loadActivePackForEngine(engine, { remote: false, sourceId: opts.sourceId });
+ pack = resolved?.manifest?.name ?? null;
+ const verbs = resolved?.manifest?.link_types.map((lt: { name: string }) => lt.name) ?? [];
+ declaredTypes = verbs.length ? new Set(verbs) : null;
+ }
+ } catch (e) {
+ return {
+ state: 'diagnostics_failed',
+ message: `Line-grammar diagnostics could not read the brain's grammar settings or schema pack (${(e as Error).message}); nothing about this page's typed lines is known.`,
+ fix: readFix('Checks the brain\'s configuration and schema pack health, read-only.', { argv: ['gbrain', 'doctor', '--json'] }),
+ };
+ }
+ const parsed = parseLineGrammar(opts.body, { declaredTypes, explainGuards: opts.limit === undefined });
+ const all = parsed.diagnostics.map((d): LineGrammarFinding => {
+ const canonical = canonicalLine(d);
+ return { severity: 'warning', validator: 'line-grammar', code: d.reason, reason: d.reason, line: d.line, text: d.text,
+ message: d.message, why: WHY[d.reason], ...(canonical ? { canonical } : {}), verify: verifyFor(opts.slug, opts.sourceId) };
+ });
+ const findings = opts.limit === undefined ? all : all.slice(0, opts.limit);
+ const truncated = findings.length < all.length;
+ return {
+ state: 'ok', enabled: settings.enabled, mode: 'effective', pack,
+ relations: parsed.relations.length, facts: parsed.facts.length, findings, total: all.length, details_truncated: truncated,
+ ...(truncated ? { more: readFix('Lists every line-grammar finding for this page, read-only.', {
+ argv: ['gbrain', 'get', '--source', opts.sourceId, '--grammar-diagnostics', '--', opts.slug],
+ mcp: { tool: 'get_page', arguments: { slug: opts.slug, source_id: opts.sourceId, grammar_diagnostics: true } } }) } : {}),
+ };
+}
diff --git a/src/core/line-grammar.ts b/src/core/line-grammar.ts
index 0a77b32b2a..2cb655069b 100644
--- a/src/core/line-grammar.ts
+++ b/src/core/line-grammar.ts
@@ -382,21 +382,72 @@ function parseRelationContent(content: string, original: string, declared: Reado
return { type, context, effective };
}
+const TRUTHY = new Set(['true', '1', 'yes', 'on']);
const FALSY = new Set(['false', '0', 'no', 'off']);
-const isTrue = (value: string | null) => value != null && ['true', '1', 'yes', 'on'].includes(value.trim().toLowerCase());
+/** A grammar boolean as written: true, false, null when unset, or 'invalid' for anything else. */
+export function parseGrammarBoolean(value: string | null | undefined): boolean | null | 'invalid' {
+ if (value == null) return null;
+ const v = value.trim().toLowerCase();
+ return TRUTHY.has(v) ? true : FALSY.has(v) ? false : 'invalid';
+}
+
+/** Defaults of the line-grammar settings (held-out verdicts H3 and H7). */
+export const LINE_GRAMMAR_DEFAULTS = { enabled: false, allowUndeclaredTypes: false, effectiveRanges: true } as const;
+export const LINE_GRAMMAR_KEYS = ['line_grammar.enabled', 'line_grammar.allow_undeclared_types', 'line_grammar.effective_ranges'] as const;
+/**
+ * Internal config row: when the effective line-grammar behavior last changed.
+ * Link extraction treats pages extracted before it as stale (see
+ * core/link-extraction-watermark.ts). Not a user setting; `config unset`
+ * refuses `_internal.*` keys.
+ */
+export const LINK_EXTRACTION_GENERATION_KEY = '_internal.link_extraction_generation';
+
+export interface LineGrammarSettings {
+ enabled: boolean;
+ allowUndeclaredTypes: boolean;
+ /** Ranges are stored only while the grammar is on. */
+ effectiveRanges: boolean;
+ /** ISO time of the last effective change, or null when never changed. */
+ generation: string | null;
+}
+
+const resolveBoolean = (value: string | null, fallback: boolean) => { const v = parseGrammarBoolean(value); return typeof v === 'boolean' ? v : fallback; };
+
+/** Settings from raw config values (unset or unreadable spellings take the default). */
+export function lineGrammarSettingsFrom(raw: { enabled: string | null; allow: string | null; ranges: string | null; generation: string | null }): LineGrammarSettings {
+ const enabled = resolveBoolean(raw.enabled, LINE_GRAMMAR_DEFAULTS.enabled);
+ return { enabled, allowUndeclaredTypes: resolveBoolean(raw.allow, LINE_GRAMMAR_DEFAULTS.allowUndeclaredTypes),
+ effectiveRanges: enabled && resolveBoolean(raw.ranges, LINE_GRAMMAR_DEFAULTS.effectiveRanges), generation: raw.generation };
+}
+
+/**
+ * The line-grammar settings link extraction runs under, read once. Strict: a
+ * failed config read throws, so the caller leaves the page stale instead of
+ * extracting under defaults it did not mean.
+ */
+export async function readLineGrammarSettings(engine: { getConfig(key: string): Promise<string | null> }): Promise<LineGrammarSettings> {
+ const [enabled, allow, ranges, generation] = await Promise.all([...LINE_GRAMMAR_KEYS, LINK_EXTRACTION_GENERATION_KEY].map(key => engine.getConfig(key)));
+ return lineGrammarSettingsFrom({ enabled, allow, ranges, generation });
+}
+
+/** What extraction actually does under these settings; two settings with the same fingerprint extract identically. */
+export function lineGrammarFingerprint(s: Pick<LineGrammarSettings, 'enabled' | 'allowUndeclaredTypes' | 'effectiveRanges'>): string {
+ return s.enabled ? `on|undeclared:${s.allowUndeclaredTypes}|ranges:${s.effectiveRanges}` : 'off';
+}
-/** `line_grammar.enabled` (default off, held-out verdict H3) and `line_grammar.allow_undeclared_types` (default off). */
+/** `line_grammar.enabled` and `line_grammar.allow_undeclared_types`, best-effort (read failures take the defaults); for advisories and lint. */
export async function lineGrammarOptions(engine: { getConfig(key: string): Promise<string | null> }): Promise<{ enabled: boolean; allowUndeclaredTypes: boolean }> {
const read = (key: string) => engine.getConfig(key).catch(() => null);
const [enabled, allow] = await Promise.all([read('line_grammar.enabled'), read('line_grammar.allow_undeclared_types')]);
- return { enabled: isTrue(enabled), allowUndeclaredTypes: isTrue(allow) };
+ const s = lineGrammarSettingsFrom({ enabled, allow, ranges: null, generation: null });
+ return { enabled: s.enabled, allowUndeclaredTypes: s.allowUndeclaredTypes };
}
/** `line_grammar.effective_ranges` (default on; applies only while `line_grammar.enabled` is on): store relation-line ranges on edges (core/link-effective.ts). */
export async function effectiveRangesEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {
const read = (key: string) => engine.getConfig(key).catch(() => null);
const [ranges, enabled] = await Promise.all([read('line_grammar.effective_ranges'), read('line_grammar.enabled')]);
- return (ranges == null || !FALSY.has(ranges.trim().toLowerCase())) && isTrue(enabled);
+ return lineGrammarSettingsFrom({ enabled, allow: null, ranges, generation: null }).effectiveRanges;
}
/**
diff --git a/src/core/link-extraction-watermark.ts b/src/core/link-extraction-watermark.ts
new file mode 100644
index 0000000000..3c1e9267ba
--- /dev/null
+++ b/src/core/link-extraction-watermark.ts
@@ -0,0 +1,35 @@
+/**
+ * The link-extraction freshness watermark every stale-page selector, counter
+ * and publisher uses: the later of the code's `LINK_EXTRACTOR_VERSION_TS` and
+ * the time the effective line-grammar behavior last changed
+ * (`_internal.link_extraction_generation`, written by `gbrain config` in the
+ * same transaction as the setting). A page extracted before the watermark is
+ * stale, so turning the grammar on or off re-extracts every page once and the
+ * graph converges to what the current settings derive.
+ *
+ * Strict on purpose: a failed read throws rather than silently using the code
+ * watermark, so a page is never stamped fresh against the wrong watermark.
+ */
+import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';
+import { LINK_EXTRACTION_GENERATION_KEY } from './line-grammar.ts';
+
+/** The later of two ISO-8601 instants, returned as written (a microsecond stamp keeps its precision). */
+export function laterInstant(a: string, b: string | null | undefined): string {
+ if (!b) return a;
+ const tb = Date.parse(b);
+ const ta = Date.parse(a);
+ if (!Number.isFinite(tb)) return a;
+ if (tb !== ta) return tb > ta ? b : a;
+ // Same millisecond: compare the sub-millisecond digits as written.
+ const micros = (s: string) => Number((/\.(\d+)Z?$/.exec(s)?.[1] ?? '0').padEnd(6, '0').slice(0, 6));
+ return micros(b) > micros(a) ? b : a;
+}
+
+/** The watermark for a known generation value (null: the grammar settings never changed). */
+export function linkExtractorWatermarkFor(generation: string | null | undefined): string {
+ return laterInstant(LINK_EXTRACTOR_VERSION_TS, generation);
+}
+
+export async function effectiveLinkExtractorWatermark(engine: { getConfig(key: string): Promise<string | null> }): Promise<string> {
+ return linkExtractorWatermarkFor(await engine.getConfig(LINK_EXTRACTION_GENERATION_KEY));
+}
diff --git a/src/core/link-reconciliation.ts b/src/core/link-reconciliation.ts
index 73d86e7a61..df4f70665a 100644
--- a/src/core/link-reconciliation.ts
+++ b/src/core/link-reconciliation.ts
@@ -6,7 +6,8 @@ import { parseMarkdown } from './markdown.ts';
import { isValidSourceId } from './source-id.ts';
import { buildSourceLocalReferenceIndex } from './source-local-reference-index.ts';
import { collectWantedLinks, isWantedPagesEnabled } from './wanted-links.ts';
-import { lineGrammarOptions } from './line-grammar.ts';
+import { readLineGrammarSettings } from './line-grammar.ts';
+import { DerivedLinkSettingsChangedError } from './derived-links.ts';
export interface LinkPageMetadata {
slug: string;
@@ -75,7 +76,8 @@ export async function reconcileSourceLinks(
const index = new Map(pages.map(page => [page.slug, page]));
const resolver = makeIndexedLinkResolver(pages, sourceId);
const wantedEnabled = await isWantedPagesEnabled(engine);
- const lineGrammar = await lineGrammarOptions(engine);
+ const grammar = await readLineGrammarSettings(engine);
+ const lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };
const remaining = pages.filter(page => !opts.afterSlug || page.slug > opts.afterSlug)
.sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);
for (const metadata of remaining.slice(0, limit)) {
@@ -118,10 +120,17 @@ export async function reconcileSourceLinks(
originSourceId: sourceId, crossSourceAllowed: false, resolve: candidate =>
candidate.targetSourceId && candidate.targetSourceId !== sourceId ? { ok: false, reason: 'cross_source' }
: !index.has(candidate.targetSlug) ? { ok: false, reason: 'missing_target' } : { ok: true } }) : [];
- const written = await engine.replaceDerivedLinks({ slug: page.slug, sourceId,
- expectedRevision: snapshot.revision, sourceIncarnation }, rows, { wanted: { producers: ['body', 'frontmatter'], rows: wanted }, expectedEndpoints:
- [...new Set(rows.flatMap(row => [row.from_slug, row.to_slug]))].map(slug => ({ slug, sourceId,
- revision: index.get(slug)!.knowledge_revision })) });
+ let written: { created: number; removed: number };
+ try {
+ written = await engine.replaceDerivedLinks({ slug: page.slug, sourceId,
+ expectedRevision: snapshot.revision, sourceIncarnation }, rows, { lineGrammar: grammar, wanted: { producers: ['body', 'frontmatter'], rows: wanted }, expectedEndpoints:
+ [...new Set(rows.flatMap(row => [row.from_slug, row.to_slug]))].map(slug => ({ slug, sourceId,
+ revision: index.get(slug)!.knowledge_revision })) });
+ } catch (error) {
+ if (!(error instanceof DerivedLinkSettingsChangedError)) throw error;
+ result.failures.push({ originSlug, code: 'revision_conflict' });
+ return result;
+ }
result.pagesProcessed++;
result.linksCreated += written.created;
result.linksRemoved += written.removed;
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index 10f9918e56..e18518270d 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -88,6 +88,7 @@ const get_page: Operation = {
content_only: { type: 'boolean', description: 'Round-trip fields only.' },
include_deleted: { type: 'boolean', description: 'Include soft-deleted pages.' },
include_timeline_entries: { type: 'boolean', description: 'Also return timeline rows.' },
+ grammar_diagnostics: { type: 'boolean', description: 'Also return every line-grammar finding for the page.', fullSurfaceOnly: true },
source_id: { type: 'string', description: "One source, or '__all__'." },
},
handler: async (ctx, p) => {
@@ -203,11 +204,16 @@ const get_page: Operation = {
// it would double every reader's payload for the round-trip minority.
const timelineEntries = includeTimelineEntries
? await ctx.engine.getTimeline(page.slug, await readPolicyOpts(ctx, { sourceId: page.source_id })) : undefined;
- return projectGetPage(visibleBody, {
+ // Read-only, over the same visibility-filtered body the reader gets (core/line-grammar-report.ts).
+ const lineGrammar = (p.grammar_diagnostics as boolean) === true
+ ? await (await import('../line-grammar-report.ts')).lineGrammarReport(ctx.engine, { slug: page.slug, sourceId: page.source_id, body: visibleBody.compiled_truth })
+ : undefined;
+ const projected = projectGetPage(visibleBody, {
revision: snapshot!.revision, tags, includeContent, contentOnly: (p.content_only as boolean) === true, resolved_slug, content_flag,
...(timelineEntries ? { timeline_entries: timelineEntries } : {}),
...(held ? { file_held: fileHeldField(held, isUntrustedReader) } : {}),
});
+ return lineGrammar ? { ...projected, line_grammar: lineGrammar } : projected;
},
scope: 'read', mutating: false,
cliHints: { name: 'get', positional: ['slug'] },
diff --git a/src/core/persistence/links-maintenance.ts b/src/core/persistence/links-maintenance.ts
index bbd83b7d06..dbebdbd848 100644
--- a/src/core/persistence/links-maintenance.ts
+++ b/src/core/persistence/links-maintenance.ts
@@ -1,5 +1,5 @@
import type { BrainEngine } from '../engine.ts';
-import { LINK_EXTRACTOR_VERSION_TS } from '../link-extraction.ts';
+import { effectiveLinkExtractorWatermark, laterInstant, linkExtractorWatermarkFor } from '../link-extraction-watermark.ts';
import { prepareAutomaticLinks } from './links-preparation.ts';
import { withCoordinatedWrite } from './context.ts';
import { maintenanceAttribution } from './attribution.ts';
@@ -14,7 +14,7 @@ export interface ManagedLinkExtraction { pages: number; created: number; removed
/** `gbrain extract --stale` on a managed brain, locally or inside the PGLite owner. */
export async function runManagedStaleExtraction(engine: BrainEngine, opts: { sourceId?: string; dryRun?: boolean }): Promise<ManagedLinkExtraction> {
if (!opts.dryRun) return extractManagedStaleLinks(engine, { sourceId: opts.sourceId });
- const remaining = await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs: LINK_EXTRACTOR_VERSION_TS });
+ const remaining = await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs: await effectiveLinkExtractorWatermark(engine) });
const m = await previewMentionPass(engine, opts.sourceId);
return { pages: 0, created: 0, removed: 0, timeline: 0, skipped: 0, remaining, mention_due: m.due, mention_last_pass_at: m.last_pass_at };
}
@@ -66,11 +66,11 @@ export async function extractManagedStaleLinks(engine: BrainEngine,
const withMentions = opts.mentions !== false;
const deadline = withMentions ? await linkPhaseDeadline(engine, opts.sourceId, startMs, opts.timeBudgetMs)
: opts.timeBudgetMs === undefined ? Infinity : startMs + opts.timeBudgetMs;
- const versionTs = LINK_EXTRACTOR_VERSION_TS;
+ const versionTs = await effectiveLinkExtractorWatermark(engine);
const maxPages = opts.maxPages ?? Infinity;
const done = new Set<string>();
const attribution = await maintenanceAttribution(engine);
- const derive = async (slug: string, sourceId: string, stamp?: string) => {
+ const derive = async (slug: string, sourceId: string) => {
opts.signal?.throwIfAborted();
done.add(`${sourceId}\0${slug}`);
const snapshot = await engine.readPageSnapshot(slug, { sourceId });
@@ -89,7 +89,12 @@ export async function extractManagedStaleLinks(engine: BrainEngine,
const timeline = (await unrecordedCanonicalTimeline(tx, current.page.id, current.page, slug)).map(entry => ({ slug, date: entry.date,
source: entry.source, summary: entry.summary, detail: entry.detail || '', source_id: sourceId }));
const added = timeline.length ? await tx.addTimelineEntriesBatch(timeline, { auditSite: 'extract.stale' }) : 0;
- const at = stamp ?? new Date().toISOString();
+ // Never stamp now(): a page prepared under settings older than the watermark must stay stale. The stamp is
+ // the later of the page's updated_at and the watermark of the settings it was prepared under.
+ const [{ updated_at_iso: updatedIso }] = await tx.executeRaw<{ updated_at_iso: string }>(
+ `SELECT to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso FROM pages WHERE id = $1`, [current.page.id]);
+ const preparedWatermark = linkExtractorWatermarkFor(prepared.settings?.generation);
+ const at = laterInstant(preparedWatermark, updatedIso);
await tx.markPagesExtractedBatch([{ slug, source_id: sourceId, extractedAt: at }], at);
return { ...written, timeline: added };
}, attribution));
@@ -111,7 +116,7 @@ export async function extractManagedStaleLinks(engine: BrainEngine,
if (!budget()) break;
afterPageId = row.id;
if (done.has(`${row.source_id}\0${row.slug}`)) continue;
- await derive(row.slug, row.source_id, row.updated_at.getTime() >= Date.parse(versionTs) ? row.updated_at_iso : versionTs);
+ await derive(row.slug, row.source_id);
}
}
result.remaining = await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs });
diff --git a/src/core/persistence/links-preparation.ts b/src/core/persistence/links-preparation.ts
index a0ed1b4d53..e749349dcd 100644
--- a/src/core/persistence/links-preparation.ts
+++ b/src/core/persistence/links-preparation.ts
@@ -7,7 +7,7 @@ import { DerivedLinkEndpointChangedError } from '../derived-links.ts';
import { capturedLinkEndpoints, indexLinkSources, loadLinkSourcePolicy, resolveCandidateSources } from '../link-reconciliation.ts';
import { collectWantedLinks, isWantedPagesEnabled } from '../wanted-links.ts';
import { readFix } from '../ops/op-fix.ts';
-import { lineGrammarOptions } from '../line-grammar.ts';
+import { readLineGrammarSettings, type LineGrammarSettings } from '../line-grammar.ts';
async function liveSlugAliases(engine: BrainEngine, sourceId: string, targets: string[]): Promise<Map<string, string>> {
if (!targets.length) return new Map();
@@ -26,9 +26,13 @@ async function liveSlugAliases(engine: BrainEngine, sourceId: string, targets: s
export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,
page: Pick<ParsedPage, 'type' | 'compiled_truth' | 'timeline' | 'frontmatter'>, sourceId: string) {
const resolver = makeResolver(engine, { mode: 'live', sourceId });
- const opts = { globalBasename: await isGlobalBasenameEnabled(engine), lineGrammar: await lineGrammarOptions(engine),
+ // One settings snapshot for the whole extraction; publication validates it (derived-links.ts). An unreadable
+ // setting leaves the page's links unpublished (stale) rather than extracted under defaults.
+ const settings: LineGrammarSettings | null = await readLineGrammarSettings(engine).catch(() => null);
+ const opts = { globalBasename: await isGlobalBasenameEnabled(engine),
+ lineGrammar: { enabled: settings?.enabled ?? false, allowUndeclaredTypes: settings?.allowUndeclaredTypes ?? false },
pack: (await loadActivePackForLocalEngine(engine, { sourceId }))?.manifest ?? null };
- if (!opts.pack) return { pageKeys: [{ sourceId, slug }], attendanceComplete: true,
+ if (!opts.pack || !settings) return { pageKeys: [{ sourceId, slug }], attendanceComplete: true, settings,
apply: async () => ({ created: 0, removed: 0, errors: 1, unresolved_count: 1 }) };
const content = `${page.compiled_truth}\n${page.timeline}`;
const referenced = new Set([slug]);
@@ -64,7 +68,7 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,
if (!candidate.canonicalAttendance && (resolved.fromSourceId !== sourceId || resolved.toSourceId !== sourceId)) return [];
return [resolvedLinkCandidate(candidate, slug, sourceId, resolved)];
});
- return { attendanceComplete, pageKeys: [{ sourceId, slug }, ...rows.flatMap(row => [
+ return { attendanceComplete, settings, pageKeys: [{ sourceId, slug }, ...rows.flatMap(row => [
{ sourceId: row.from_source_id!, slug: row.from_slug }, { sourceId: row.to_source_id!, slug: row.to_slug },
])], apply: async (tx: BrainEngine) => {
if (!attendanceComplete) return { created: 0, removed: 0, errors: 1, unresolved_count: Math.max(1, unresolved.length) };
@@ -72,7 +76,7 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,
if (!snapshot) throw new Error('Automatic link origin disappeared');
try {
const result = await tx.replaceDerivedLinks({ slug, sourceId, expectedRevision: snapshot.revision,
- sourceIncarnation: snapshot.sourceIncarnation }, rows, { preserveExisting: true, wanted: { ...wanted, producers: [...wanted.producers] },
+ sourceIncarnation: snapshot.sourceIncarnation }, rows, { preserveExisting: true, lineGrammar: settings, wanted: { ...wanted, producers: [...wanted.producers] },
expectedEndpoints: capturedLinkEndpoints(rows, new Map([...metadata,
[`${sourceId}\0${slug}`, { slug, source_id: sourceId, type: page.type, knowledge_revision: snapshot.revision }]]))
.filter(endpoint => endpoint.slug !== slug || endpoint.sourceId !== sourceId) });
diff --git a/src/core/persistence/page-advisories.ts b/src/core/persistence/page-advisories.ts
index 2beb941f8a..3ab5bd80df 100644
--- a/src/core/persistence/page-advisories.ts
+++ b/src/core/persistence/page-advisories.ts
@@ -4,9 +4,9 @@ import { sanitizeRemoteBody } from '../remote-body.ts';
import { writerLintForPutPage } from '../output/post-write.ts';
import type { WriteRequest } from './model.ts';
import { prepareFactsBackstop } from './effect-facts.ts';
-import { lineGrammarOptions, parseLineGrammar } from '../line-grammar.ts';
+import { parseLineGrammar } from '../line-grammar.ts';
+import { lineGrammarReport } from '../line-grammar-report.ts';
import { isAutoLinkEnabled } from '../link-extraction.ts';
-import { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';
import { findSimilarPages } from '../similar-pages.ts';
import { isQuarantined } from '../quarantine.ts';
import { readFix } from '../ops/op-fix.ts';
@@ -37,32 +37,32 @@ async function similarPagesAdvisory(engine: BrainEngine, row: WriteRequest, page
/**
* What the line grammar read from this page body: typed relation lines and
- * fact lines, with every near-miss explained. Absent when the page has none.
- * Relations are stored with the page's links (or by the next sweep for a
- * remote writer); fact lines stay page text and are not added to `facts`.
+ * fact lines, with every near-miss explained (core/line-grammar-report.ts).
+ * Absent when the page has none or the grammar is off. Relations are stored
+ * with the page's links (or by the next sweep for a remote writer); fact
+ * lines stay page text and are not added to `facts`.
*/
async function lineGrammarAdvisory(engine: BrainEngine, row: WriteRequest, page: ParsedPage): Promise<Record<string, unknown> | undefined> {
- // Declared-type gating only turns relations into findings, so a body with nothing to read needs no config or pack reads.
- const ungated = parseLineGrammar(page.compiled_truth);
+ // Settings and pack reads are skipped for a body with nothing the grammar could read or explain.
+ const ungated = parseLineGrammar(page.compiled_truth, { explainGuards: true });
if (!ungated.relations.length && !ungated.facts.length && !ungated.diagnostics.length) return undefined;
- const options = await lineGrammarOptions(engine);
- if (!options.enabled) return undefined;
- const pack = options.allowUndeclaredTypes ? null : (await loadActivePackForLocalEngine(engine, { sourceId: row.source_id }))?.manifest ?? null;
- const declaredTypes = pack?.link_types.length ? new Set(pack.link_types.map(lt => lt.name)) : null;
- const parsed = parseLineGrammar(page.compiled_truth, { declaredTypes });
- if (!parsed.relations.length && !parsed.facts.length && !parsed.diagnostics.length) return undefined;
+ const report = await lineGrammarReport(engine, { slug: row.slug, sourceId: row.source_id, body: page.compiled_truth, limit: LINE_GRAMMAR_FINDINGS_MAX });
+ if (report.state === 'diagnostics_failed') return report;
+ if (!report.enabled) return undefined;
+ if (!report.relations && !report.facts && !report.total) return undefined;
const relationsState = !(await isAutoLinkEnabled(engine)) ? 'auto_link_disabled'
: row.authority.remote && !row.authority.autoLinkTrusted ? 'pending_sweep' : 'stored';
return {
- relations: parsed.relations.length,
+ relations: report.relations,
relations_state: relationsState,
- facts: parsed.facts.length,
- ...(parsed.facts.length ? { facts_state: 'page_text_only',
+ facts: report.facts,
+ ...(report.facts ? { facts_state: 'page_text_only',
facts_message: 'Fact lines are searchable page text; they are not added to recall facts. Use remember (or the page ## Facts table) for a fact recall must return.' } : {}),
- findings: parsed.diagnostics.slice(0, LINE_GRAMMAR_FINDINGS_MAX).map(d => ({ severity: 'warning', validator: 'line-grammar',
- line: d.line, reason: d.reason, text: d.text, message: d.message })),
- total: parsed.diagnostics.length,
- details_truncated: parsed.diagnostics.length > LINE_GRAMMAR_FINDINGS_MAX,
+ findings: report.findings.map(f => ({ ...f, message: `Page saved; line ${f.line} was not read as written. ${f.message}` })),
+ total: report.total,
+ details_truncated: report.details_truncated,
+ ...(report.more ? { more: report.more } : {}),
+ pack: report.pack,
};
}
@@ -85,7 +85,9 @@ export async function preparePageAdvisories(engine: BrainEngine, row: WriteReque
top_findings: lint.top_findings.map(finding => ({ ...finding, message: LINT_MESSAGES[finding.validator] ?? `${finding.validator} validation finding.` })) } : lint;
const facts = ['put_page', 'capture', 'edit_page'].includes(row.operation)
? await prepareFactsBackstop(engine, row, page).catch(() => ({ skipped: 'backstop_error' })) : undefined;
- const grammar = await lineGrammarAdvisory(engine, row, visible).catch(() => undefined);
+ const grammar = await lineGrammarAdvisory(engine, row, visible).catch((e: unknown): Record<string, unknown> => ({ state: 'diagnostics_failed',
+ message: `Line-grammar diagnostics failed (${e instanceof Error ? e.message : String(e)}); the page was saved, but nothing is known about its typed lines.`,
+ fix: readFix('Checks the brain configuration and schema pack, read-only.', { argv: ['gbrain', 'doctor', '--json'] }) }));
const similar = await similarPagesAdvisory(engine, row, page).catch(() => undefined);
return { ...remoteLinkHint(row), ...(sanitized ? { writer_lint: sanitized } : {}), ...(facts ? { facts_backstop: facts } : {}),
...(grammar ? { line_grammar: grammar } : {}), ...(similar ? { similar_pages: similar } : {}) };
diff --git a/src/core/remediation/context.ts b/src/core/remediation/context.ts
index ec94702a90..475926ce71 100644
--- a/src/core/remediation/context.ts
+++ b/src/core/remediation/context.ts
@@ -22,12 +22,13 @@ export type { RecommendationContext };
*/
export async function staleExtractionBlocked(engine: BrainEngine, sourceId?: string): Promise<string | undefined> {
const { loadActivePackForLocalEngine } = await import('../schema-pack/best-effort.ts');
- const { LINK_EXTRACTOR_VERSION_TS } = await import('../link-extraction.ts');
+ const { effectiveLinkExtractorWatermark } = await import('../link-extraction-watermark.ts');
+ const watermark = await effectiveLinkExtractorWatermark(engine);
const sourceIds = sourceId ? [sourceId]
: (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE NOT archived ORDER BY id')).map(row => row.id);
for (const id of sourceIds) {
if (await loadActivePackForLocalEngine(engine, { sourceId: id })) continue;
- if (!sourceId && !await engine.countStalePagesForExtraction({ sourceId: id, versionTs: LINK_EXTRACTOR_VERSION_TS })) continue;
+ if (!sourceId && !await engine.countStalePagesForExtraction({ sourceId: id, versionTs: watermark })) continue;
return `active schema pack is unavailable for source ${id}; extract --stale cannot run until \`gbrain doctor\` schema-pack checks pass`;
}
return undefined;
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index a70d5c6448..4081d1ee59 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -1,6 +1,6 @@
import { lookupRefsForSlugs } from './link-reconciliation.ts';
import { collectWantedLinks, isWantedPagesEnabled, type WantedLinkInput } from './wanted-links.ts';
-import { lineGrammarOptions } from './line-grammar.ts';
+import { readLineGrammarSettings } from './line-grammar.ts';
/**
* Serve-resident maintenance sweep [CX-P0.1, CX-P0.3, CX2-4].
*
@@ -420,7 +420,9 @@ async function runLinksTimelinePass(
const incomplete = new Set<string>();
const wantedBySlug = new Map<string, WantedLinkInput[]>();
const wantedEnabled = await isWantedPagesEnabled(engine);
- const lineGrammar = await lineGrammarOptions(engine);
+ // One settings snapshot per sweep; publication refuses a page if the settings move meanwhile (it stays unstamped).
+ const grammar = await readLineGrammarSettings(engine);
+ const lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };
if (pageCandidates.length > 0) {
const needed = new Set<string>();
for (const { slug, candidates } of pageCandidates) {
@@ -533,7 +535,7 @@ async function runLinksTimelinePass(
const snapshot = snapshots.get(ref.slug)!;
const result = await engine.replaceDerivedLinks({ slug: ref.slug, sourceId,
expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation }, desired,
- { includeFrontmatter: false, preserveExisting: true,
+ { includeFrontmatter: false, preserveExisting: true, lineGrammar: grammar,
wanted: { producers: ['body'], rows: wantedBySlug.get(ref.slug) ?? [] }, expectedEndpoints: [...new Set(desired.flatMap(row =>
[`${row.from_source_id}\0${row.from_slug}`, `${row.to_source_id}\0${row.to_slug}`]))].map(key => {
const endpoint = endpointMetadata.get(key)!;
diff --git a/test/line-grammar-report.test.ts b/test/line-grammar-report.test.ts
new file mode 100644
index 0000000000..7b5e2261c3
--- /dev/null
+++ b/test/line-grammar-report.test.ts
@@ -0,0 +1,79 @@
+/**
+ * Line-grammar findings in the agent operator contract's terms: the put_page
+ * advisory (first five findings, a continuation route to the rest) and
+ * `get_page grammar_diagnostics` (every finding, guard refusals included)
+ * share core/line-grammar-report.ts. A failed settings read is reported, never
+ * an ungated parse. Managed PGLite brain.
+ */
+import { expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { operations } from '../src/core/operations.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { lineGrammarReport } from '../src/core/line-grammar-report.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+
+const put = (ctx: OperationContext, slug: string, body: string, type = 'person') =>
+ submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(),
+ content: `---\ntype: ${type}\ntitle: ${slug}\n---\n\n${body}\n` } }) as Promise<Record<string, any>>;
+const getPage = (ctx: OperationContext, params: Record<string, unknown>) =>
+ operations.find(op => op.name === 'get_page')!.handler(ctx, params) as Promise<Record<string, any>>;
+
+const BODY = [
+ 'Alice builds things.',
+ '',
+ '- works_at [[companies/acme-example]]',
+ '- **works_at** [[companies/acme-example]]',
+ '- [preference] Prefers oat milk',
+ '- [Time] - [Event]',
+ '- board_member [[companies/acme-example]]',
+ '- works_at [[companies/acme-example]] since 2024',
+ '- [noun] a thing',
+ '- [Item] TBD',
+].join('\n');
+
+test('advisory findings carry code, why, canonical form and a read-only verify; the rest are one call away', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ await engine.setConfig('line_grammar.enabled', 'true');
+ await put(ctx, 'companies/acme-example', 'Acme.', 'company');
+ const written = await put(ctx, 'people/alice-example', BODY);
+ const grammar = (written.outcome ?? written).line_grammar;
+ expect(grammar).toMatchObject({ relations: 1, facts: 1, total: 6, details_truncated: true, relations_state: 'stored' });
+ expect(grammar.findings).toHaveLength(5);
+ const decorated = grammar.findings.find((f: any) => f.code === 'type_punctuation');
+ expect(decorated).toMatchObject({ reason: 'type_punctuation', canonical: '- works_at [[companies/acme-example]]' });
+ expect(decorated.message).toStartWith('Page saved; line');
+ expect(decorated.why).toContain('bare');
+ expect(decorated.verify).toMatchObject({ actor: 'agent', consent: [], mcp: { tool: 'get_page', arguments: { slug: 'people/alice-example', grammar_diagnostics: true } } });
+ expect(grammar.more.mcp).toMatchObject({ tool: 'get_page', arguments: { grammar_diagnostics: true } });
+ const undeclared = grammar.findings.find((f: any) => f.code === 'undeclared_type');
+ expect(undeclared.message).not.toContain('Did you mean');
+
+ const read = await getPage(ctx, { slug: 'people/alice-example', grammar_diagnostics: true });
+ expect(read.line_grammar).toMatchObject({ state: 'ok', enabled: true, mode: 'effective', total: 6, details_truncated: false });
+ expect(read.line_grammar.findings.map((f: any) => f.code).sort()).toEqual(
+ ['placeholder_claim', 'prose_tail', 'template_slot', 'type_punctuation', 'undeclared_type', 'usage_label']);
+ expect(read.line_grammar.findings.every((f: any) => !f.message.startsWith('Page saved'))).toBe(true);
+
+ const plain = await getPage(ctx, { slug: 'people/alice-example' });
+ expect(plain.line_grammar).toBeUndefined();
+ });
+}, 120_000);
+
+test('with the grammar off, put_page reports nothing and get_page says the grammar is off', async () => {
+ await managedBrain(async ({ ctx }) => {
+ await put(ctx, 'companies/acme-example', 'Acme.', 'company');
+ const written = await put(ctx, 'people/alice-example', BODY);
+ expect((written.outcome ?? written).line_grammar).toBeUndefined();
+ const read = await getPage(ctx, { slug: 'people/alice-example', grammar_diagnostics: true });
+ expect(read.line_grammar).toMatchObject({ state: 'ok', enabled: false, relations: 1 });
+ });
+}, 120_000);
+
+test('a failed settings read is reported as diagnostics_failed, never as an ungated parse', async () => {
+ const broken = { getConfig: async () => { throw new Error('connection reset'); } } as unknown as BrainEngine;
+ const report = await lineGrammarReport(broken, { slug: 'people/x', sourceId: 'default', body: BODY });
+ expect(report).toMatchObject({ state: 'diagnostics_failed', fix: { argv: ['gbrain', 'doctor', '--json'] } });
+ expect((report as { message: string }).message).toContain('connection reset');
+});
diff --git a/test/line-grammar-toggle.test.ts b/test/line-grammar-toggle.test.ts
new file mode 100644
index 0000000000..f8d9e50e18
--- /dev/null
+++ b/test/line-grammar-toggle.test.ts
@@ -0,0 +1,111 @@
+/**
+ * Turning the line grammar on or off converges the graph: the setting and the
+ * extraction generation commit together (core/line-grammar-config.ts), every
+ * page extracted before the change reads as stale through the one watermark
+ * (core/link-extraction-watermark.ts), managed extraction re-derives it, and
+ * a page prepared under the old settings is never published as fresh.
+ * Managed PGLite brain.
+ */
+import { expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { extractManagedStaleLinks } from '../src/core/persistence/links-maintenance.ts';
+import { prepareAutomaticLinks } from '../src/core/persistence/links-preparation.ts';
+import { applyLineGrammarConfigChange, describeLineGrammarChange, invalidLineGrammarValue, isInternalConfigKey } from '../src/core/line-grammar-config.ts';
+import { effectiveLinkExtractorWatermark, laterInstant } from '../src/core/link-extraction-watermark.ts';
+import { LINK_EXTRACTOR_VERSION_TS } from '../src/core/link-extraction.ts';
+import { LINK_EXTRACTION_GENERATION_KEY } from '../src/core/line-grammar.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+
+const put = (ctx: OperationContext, slug: string, body: string, type = 'person') =>
+ submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(),
+ content: `---\ntype: ${type}\ntitle: ${slug}\n---\n\n${body}\n` } }) as Promise<Record<string, any>>;
+
+const aliceTypes = async (engine: BrainEngine) => (await engine.executeRaw<{ link_type: string }>(`SELECT DISTINCT l.link_type FROM links l
+ JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
+ WHERE f.slug='people/alice-example' AND t.slug='companies/acme-example' ORDER BY 1`)).map(r => r.link_type);
+
+const stale = async (engine: BrainEngine) => engine.countStalePagesForExtraction({ versionTs: await effectiveLinkExtractorWatermark(engine) });
+
+async function seed(engine: BrainEngine, ctx: OperationContext) {
+ await put(ctx, 'companies/acme-example', 'Acme.', 'company');
+ await put(ctx, 'people/alice-example', 'Alice builds things.\n\n- works_at [[companies/acme-example]]');
+ await extractManagedStaleLinks(engine, { mentions: false });
+}
+
+test('enable then disable: each effective change re-extracts and the stated type follows the setting', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ await seed(engine, ctx);
+ expect(await aliceTypes(engine)).not.toContain('works_at');
+ expect(await stale(engine)).toBe(0);
+
+ const on = await applyLineGrammarConfigChange(engine, tx => tx.setConfig('line_grammar.enabled', 'true'));
+ expect(on.changed).toBe(true);
+ expect(await engine.getConfig(LINK_EXTRACTION_GENERATION_KEY)).toBe(on.generation);
+ expect(await stale(engine)).toBeGreaterThanOrEqual(2);
+ const described = await describeLineGrammarChange(engine, on);
+ expect(described.lines.join('\n')).toContain('gbrain extract --stale');
+ expect(described.json).toMatchObject({ changed: true, effective: { enabled: true } });
+ await extractManagedStaleLinks(engine, { mentions: false });
+ expect(await stale(engine)).toBe(0);
+ expect(await aliceTypes(engine)).toContain('works_at');
+
+ const off = await applyLineGrammarConfigChange(engine, tx => tx.setConfig('line_grammar.enabled', 'false'));
+ expect(off.changed).toBe(true);
+ expect(Date.parse(off.generation!)).toBeGreaterThanOrEqual(Date.parse(on.generation!));
+ expect(await stale(engine)).toBeGreaterThanOrEqual(2);
+ await extractManagedStaleLinks(engine, { mentions: false });
+ expect(await stale(engine)).toBe(0);
+ expect(await aliceTypes(engine)).not.toContain('works_at');
+ });
+}, 180_000);
+
+test('no-op changes keep the generation: repeated settings, spellings, unset to the same default, subordinate keys while off', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ await seed(engine, ctx);
+ for (const mutate of [
+ (tx: BrainEngine) => tx.setConfig('line_grammar.enabled', 'false'),
+ (tx: BrainEngine) => tx.setConfig('line_grammar.enabled', 'off'),
+ async (tx: BrainEngine) => { await tx.unsetConfig('line_grammar.enabled'); },
+ (tx: BrainEngine) => tx.setConfig('line_grammar.effective_ranges', 'false'),
+ (tx: BrainEngine) => tx.setConfig('line_grammar.allow_undeclared_types', 'true'),
+ ]) {
+ const change = await applyLineGrammarConfigChange(engine, mutate);
+ expect(change.changed).toBe(false);
+ }
+ expect(await engine.getConfig(LINK_EXTRACTION_GENERATION_KEY)).toBeNull();
+ expect(await stale(engine)).toBe(0);
+ });
+}, 120_000);
+
+test('a page prepared before a change is not published or stamped fresh after it', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ await seed(engine, ctx);
+ const snapshot = await engine.readPageSnapshot('people/alice-example', { sourceId: 'default' });
+ const prepared = await prepareAutomaticLinks(engine, 'people/alice-example', snapshot!.page, 'default');
+ expect(prepared.settings?.enabled).toBe(false);
+ await applyLineGrammarConfigChange(engine, tx => tx.setConfig('line_grammar.enabled', 'true'));
+ const written = await engine.transaction(tx => prepared.apply(tx));
+ expect(written.errors).toBe(1);
+ expect(await stale(engine)).toBeGreaterThanOrEqual(2);
+ await extractManagedStaleLinks(engine, { mentions: false });
+ expect(await aliceTypes(engine)).toContain('works_at');
+ });
+}, 120_000);
+
+test('validation and internal keys', () => {
+ expect(invalidLineGrammarValue('line_grammar.enabled', 'tru')).toContain('true or false');
+ for (const v of ['true', 'false', 'on', 'off', '1', '0', 'yes', 'no', ' TRUE ']) expect(invalidLineGrammarValue('line_grammar.enabled', v)).toBeNull();
+ expect(isInternalConfigKey(LINK_EXTRACTION_GENERATION_KEY)).toBe(true);
+ expect(isInternalConfigKey('line_grammar.enabled')).toBe(false);
+});
+
+test('watermark arithmetic keeps microseconds and never moves before the code watermark', () => {
+ expect(laterInstant(LINK_EXTRACTOR_VERSION_TS, null)).toBe(LINK_EXTRACTOR_VERSION_TS);
+ expect(laterInstant(LINK_EXTRACTOR_VERSION_TS, '2001-01-01T00:00:00Z')).toBe(LINK_EXTRACTOR_VERSION_TS);
+ expect(laterInstant('2030-01-01T00:00:00.000100Z', '2030-01-01T00:00:00.000200Z')).toBe('2030-01-01T00:00:00.000200Z');
+ expect(laterInstant('2030-01-01T00:00:00.000300Z', '2030-01-01T00:00:00.000200Z')).toBe('2030-01-01T00:00:00.000300Z');
+ expect(laterInstant('2030-01-01T00:00:00Z', 'not a date')).toBe('2030-01-01T00:00:00Z');
+});