Compare commits

..
Author SHA1 Message Date
Garry TanandClaude Fable 5 303bbfb0b8 fix(extract): mirror plain-bullet Format 4 in parseTimelineEntries (db-source parity)
extractTimelineFromContent (fs-source) and parseTimelineEntries
(db-source extract + put_page auto_timeline) are documented as
kept-in-sync; adding Format 4 to only the fs parser left brain-authored
plain bullets invisible on the write path and `extract --source db`.
Same skip in the citation pass so a plain bullet carrying its own
[Source: ...] files exactly one entry on the db path too.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 11:22:44 -07:00
9efe229eee fix(extract): recognize plain-bullet timeline format as Format 4 (takeover of #1896)
Rebase of #1896 onto master: since it was opened, #2524 landed an
inline-citation arm as Format 3 at the same insertion point, so the
plain-bullet arm now lands as Format 4 and the citation loop's skip is
extended to plain-bullet lines — a plain bullet carrying its own
[Source: ...] citation (the shape quality.md mandates) files exactly
one entry instead of double-counting.

Co-authored-by: ElliotDrel <ElliotDrel@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:20:05 -07:00
9 changed files with 98 additions and 128 deletions
+18 -1
View File
@@ -509,8 +509,12 @@ export function extractTimelineFromContent(content: string, slug: string): Extra
// DB-level uniqueness cannot collapse.
const citationPattern = /\[Source:\s*([^\]]+?),\s*(\d{4}-\d{2}-\d{2})\s*\]/g;
const bulletLinePattern = /^-\s+\*\*\d{4}-\d{2}-\d{2}\*\*\s*\|/;
// Lines captured by Format 4 (plain bullet) are skipped for the same
// reason: quality.md mandates a trailing [Source: ...] on those bullets,
// and re-extracting the citation would double-count the event.
const plainBulletLinePattern = /^-\s+\d{4}-\d{2}-\d{2}\s*[—–-]/;
for (const line of content.split(/\r?\n/)) {
if (bulletLinePattern.test(line)) continue;
if (bulletLinePattern.test(line) || plainBulletLinePattern.test(line)) continue;
const lineMatches = [...line.matchAll(citationPattern)];
if (lineMatches.length === 0) continue;
// Strip every citation marker from the line to leave the annotated text.
@@ -526,6 +530,19 @@ export function extractTimelineFromContent(content: string, slug: string): Extra
}
}
// Format 4: Plain bullet — - YYYY-MM-DD — Summary
// This is the format gbrain's own enrich skill writes (no bold, no source
// pipe). Without it, every brain-authored timeline entry is invisible to
// extraction and timeline_coverage stays at 0%. Anchored at line start so a
// date inside a summary/link cannot start a spurious entry; a bold Format-1
// line (`- **…**`) cannot match here (a `*` follows the bullet, not a
// digit), and the citation loop above skips these lines, so a plain bullet
// carrying its own [Source: ...] files exactly one entry.
const plainBulletPattern = /^-\s+(\d{4}-\d{2}-\d{2})\s*[—–-]\s*(.+)$/gm;
while ((match = plainBulletPattern.exec(content)) !== null) {
entries.push({ slug, date: match[1], source: 'markdown', summary: match[2].trim() });
}
return entries;
}
+5 -5
View File
@@ -197,7 +197,7 @@ export interface SyncResult {
/** Pages re-embedded during this sync's auto-embed step. 0 if --no-embed or skipped. */
embedded: number;
pagesAffected: string[];
failedFiles?: number; // count of per-file import/sync failures (Bug 9)
failedFiles?: number; // count of parse failures (Bug 9)
/**
* v0.41.13.0 partial-sync fields (only set when status === 'partial').
*
@@ -3183,7 +3183,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
await clearOpCheckpoint(engine, ckpt.target);
};
// issue #1939 adversarial finding #1: a file that failed to import (open ledger
// issue #1939 adversarial finding #1: a file that failed to parse (open ledger
// row) and is then deleted/renamed-away never re-enters failedFiles and never
// imports, so its row would never clear and would age doctor to a permanent
// FAIL. Treat removed paths as resolved so the ledger self-heals.
@@ -3215,9 +3215,9 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
} else {
const fileFailCount = failedFiles.filter(f => isSkippablePath(f.path)).length;
serr(
`\nSync blocked: ${fileFailCount} file(s) failed to import:\n` +
`\nSync blocked: ${fileFailCount} file(s) failed to parse:\n` +
`${codeBreakdown}\n\n` +
`Fix the listed file errors and re-run, or use 'gbrain sync --skip-failed' to ` +
`Fix the frontmatter and re-run, or use 'gbrain sync --skip-failed' to ` +
`acknowledge and move on. A file that keeps failing auto-skips after ` +
`${resolveAutoSkipThreshold()} consecutive syncs.`,
);
@@ -5355,7 +5355,7 @@ function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = process.
case 'dry_run':
break; // already printed in performSync
case 'blocked_by_failures':
write(`Sync BLOCKED at ${result.toCommit.slice(0, 8)}: ${result.failedFiles ?? 0} file(s) failed to import.`);
write(`Sync BLOCKED at ${result.toCommit.slice(0, 8)}: ${result.failedFiles ?? 0} file(s) failed to parse.`);
write(` See ~/.gbrain/sync-failures.jsonl for details, or run 'gbrain doctor'.`);
write(` Fix the files then re-run 'gbrain sync', or 'gbrain sync --skip-failed' to move on.`);
break;
+8 -3
View File
@@ -1103,6 +1103,11 @@ export interface TimelineCandidate {
// Match: `- **YYYY-MM-DD** | summary` or `- **YYYY-MM-DD** -- summary`
// or `- **YYYY-MM-DD** - summary` or just `**YYYY-MM-DD** | summary`.
const TIMELINE_LINE_RE = /^\s*-?\s*\*\*(\d{4}-\d{2}-\d{2})\*\*\s*[|\-–—]+\s*(.+?)\s*$/;
// Plain bullet: `- YYYY-MM-DD — summary` (no bold, no source pipe). Kept in
// sync with extractTimelineFromContent's Format 4 (the fs-source path).
// Anchored flush-left so a date inside an indented continuation line cannot
// start a spurious entry.
const PLAIN_TIMELINE_LINE_RE = /^-\s+(\d{4}-\d{2}-\d{2})\s*[—–-]\s*(.+?)\s*$/;
/**
* Parse timeline entries from content. Looks at:
@@ -1119,7 +1124,7 @@ export function parseTimelineEntries(content: string): TimelineCandidate[] {
let i = 0;
while (i < lines.length) {
const m = TIMELINE_LINE_RE.exec(lines[i]);
const m = TIMELINE_LINE_RE.exec(lines[i]) ?? PLAIN_TIMELINE_LINE_RE.exec(lines[i]);
if (!m) {
i++;
continue;
@@ -1136,7 +1141,7 @@ export function parseTimelineEntries(content: string): TimelineCandidate[] {
let j = i + 1;
while (j < lines.length) {
const next = lines[j];
if (TIMELINE_LINE_RE.test(next)) break;
if (TIMELINE_LINE_RE.test(next) || PLAIN_TIMELINE_LINE_RE.test(next)) break;
if (/^#{1,6}\s/.test(next)) break;
if (next.trim().length === 0 && detailLines.length === 0) {
// skip leading blank line; if we hit a blank after detail content
@@ -1166,7 +1171,7 @@ export function parseTimelineEntries(content: string): TimelineCandidate[] {
// bullet pass are skipped (a bullet often carries its own citation).
const citationRe = /\[Source:\s*([^\]]+?),\s*(\d{4}-\d{2}-\d{2})\s*\]/g;
for (const line of lines) {
if (TIMELINE_LINE_RE.test(line)) continue;
if (TIMELINE_LINE_RE.test(line) || PLAIN_TIMELINE_LINE_RE.test(line)) continue;
const matches = [...line.matchAll(citationRe)];
if (matches.length === 0) continue;
const summary = line
-10
View File
@@ -1058,16 +1058,6 @@ export class PGLiteEngine implements BrainEngine {
RETURNING id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, effective_date, effective_date_source, import_filename, source_kind, source_uri, ingested_via, ingested_at`,
[sourceId, slug, page.type, pageKind, page.title, page.compiled_truth, page.timeline || '', JSON.stringify(frontmatter), hash, effectiveDate, effectiveDateSource, importFilename, chunkerVersion, sourcePath, sourceKind, sourceUri, ingestedVia, ingestedAt]
);
// #2189: an INSERT … ON CONFLICT DO UPDATE … RETURNING that yields 0 rows
// (e.g. a BEFORE trigger suppressing the write) previously crashed in
// rowToPage with an opaque "undefined is not an object (row.deleted_at)".
// Throw a diagnosable error naming the row instead. Mirrors postgres-engine.ts.
if (!rows[0]) {
throw new Error(
`putPage: INSERT … RETURNING produced no row for slug='${slug}' source_id='${sourceId}'. ` +
`A trigger or rule on the pages table may be suppressing the write.`
);
}
return rowToPage(rows[0] as Record<string, unknown>);
}
-10
View File
@@ -1119,16 +1119,6 @@ export class PostgresEngine implements BrainEngine {
ingested_at = COALESCE(EXCLUDED.ingested_at, pages.ingested_at)
RETURNING id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, effective_date, effective_date_source, import_filename, source_kind, source_uri, ingested_via, ingested_at
`;
// #2189: an INSERT … ON CONFLICT DO UPDATE … RETURNING that yields 0 rows
// (e.g. a BEFORE trigger suppressing the write) previously crashed in
// rowToPage with an opaque "undefined is not an object (row.deleted_at)".
// Throw a diagnosable error naming the row instead. Mirrors pglite-engine.ts.
if (!rows[0]) {
throw new Error(
`putPage: INSERT … RETURNING produced no row for slug='${slug}' source_id='${sourceId}'. ` +
`A trigger or rule on the pages table may be suppressing the write.`
);
}
return rowToPage(rows[0]);
}
+43
View File
@@ -185,6 +185,49 @@ describe('extractTimelineFromContent', () => {
expect(entries).toHaveLength(1);
expect(entries[0].summary).toBe('Landed the enterprise pilot with acme-example.');
});
// Format 4: the plain bullet `- YYYY-MM-DD — Summary` that gbrain's own
// enrich skill writes. Before this was supported, every brain-authored
// timeline entry was invisible and timeline_coverage was stuck at 0%.
it('extracts plain bullet format (- YYYY-MM-DD — Summary)', () => {
const content = `## Timeline\n- 2026-06-01 — Catch-up call with alice-example; intros offered.`;
const entries = extractTimelineFromContent(content, 'people/alice-example');
expect(entries).toHaveLength(1);
expect(entries[0].date).toBe('2026-06-01');
expect(entries[0].source).toBe('markdown');
expect(entries[0].summary).toBe('Catch-up call with alice-example; intros offered.');
});
it('files exactly one entry for a plain bullet that carries its own citation', () => {
// quality.md mandates this shape; it must not double-count via the
// citation arm (Format 3) AND the plain-bullet arm (Format 4).
const content = `- 2026-05-31 — Confirmed full name. [Source: User, 2026-05-31]`;
const entries = extractTimelineFromContent(content, 'people/charlie-example');
expect(entries).toHaveLength(1);
expect(entries[0].date).toBe('2026-05-31');
expect(entries[0].source).toBe('markdown');
expect(entries[0].summary).toContain('Confirmed full name.');
});
it('does not double-count bold (Format 1) lines as plain bullets', () => {
const content = `- **2025-03-18** | Meeting — Discussed partnership`;
const entries = extractTimelineFromContent(content, 'test');
expect(entries).toHaveLength(1);
expect(entries[0].source).toBe('Meeting');
});
it('does not start a spurious entry from a date inside a summary', () => {
const content = `- 2026-06-01 — See [meeting](meetings/2026-06-01).`;
const entries = extractTimelineFromContent(content, 'people/alice-example');
expect(entries).toHaveLength(1);
expect(entries[0].date).toBe('2026-06-01');
});
it('handles en dash and hyphen separators in plain bullets', () => {
const content = `- 2026-06-01 First\n- 2026-06-02 - Second`;
const entries = extractTimelineFromContent(content, 'test');
expect(entries).toHaveLength(2);
});
});
describe('walkMarkdownFiles', () => {
+24
View File
@@ -720,6 +720,30 @@ More prose here.
const entries = parseTimelineEntries(content);
expect(entries.length).toBe(2);
});
// Plain bullet (extract.ts Format 4 parity — the db-source path must see
// the same entries as the fs-source path).
test('parses plain bullet: - YYYY-MM-DD — summary', () => {
const entries = parseTimelineEntries('## Timeline\n- 2026-06-01 — Catch-up call with alice-example');
expect(entries.length).toBe(1);
expect(entries[0].date).toBe('2026-06-01');
expect(entries[0].summary).toBe('Catch-up call with alice-example');
});
test('files exactly one entry for a plain bullet carrying its own citation', () => {
const entries = parseTimelineEntries('- 2026-05-31 — Confirmed full name. [Source: User, 2026-05-31]');
expect(entries.length).toBe(1);
expect(entries[0].date).toBe('2026-05-31');
});
test('skips invalid dates in plain bullets', () => {
expect(parseTimelineEntries('- 2026-13-45 — Bad date').length).toBe(0);
});
test('does not double-count a bold bullet as a plain bullet', () => {
const entries = parseTimelineEntries('- **2026-01-15** | Met with Alice');
expect(entries.length).toBe(1);
});
});
// ─── isAutoLinkEnabled ─────────────────────────────────────────
-74
View File
@@ -1,74 +0,0 @@
// #2189 regression guard: putPage's INSERT … ON CONFLICT DO UPDATE … RETURNING
// can yield 0 rows when brain-local DB state (e.g. a BEFORE INSERT trigger)
// suppresses the write. Pre-fix, rowToPage(rows[0]) crashed with the opaque
// "undefined is not an object (evaluating 'row.deleted_at')" that failed
// ~all files of a code sync. Post-fix, putPage throws a descriptive error
// naming the slug + source_id so the failure is diagnosable per-file.
//
// Same guard lands in postgres-engine.ts (engine-parity invariant); this test
// exercises the PGLite side, where the issue was reported.
import { describe, expect, test, beforeAll, afterAll } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
let engine: PGLiteEngine;
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
// Simulate the reporter's state-dependent failure: a trigger that
// suppresses inserts for one slug, making RETURNING produce no row.
await engine.executeRaw(`
CREATE OR REPLACE FUNCTION suppress_pages_insert() RETURNS trigger AS $$
BEGIN
IF NEW.slug = 'suppressed-page' THEN RETURN NULL; END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
`);
await engine.executeRaw(`
CREATE TRIGGER suppress_pages_insert_trg
BEFORE INSERT ON pages
FOR EACH ROW EXECUTE FUNCTION suppress_pages_insert();
`);
});
afterAll(async () => {
await engine.executeRaw('DROP TRIGGER IF EXISTS suppress_pages_insert_trg ON pages');
await engine.executeRaw('DROP FUNCTION IF EXISTS suppress_pages_insert');
await engine.disconnect();
});
describe('putPage RETURNING guard (#2189)', () => {
test('0-row RETURNING throws a descriptive error, not row.deleted_at TypeError', async () => {
let err: Error | undefined;
try {
await engine.putPage('suppressed-page', {
type: 'code',
title: 'Suppressed',
compiled_truth: 'x',
timeline: '',
});
} catch (e) {
err = e as Error;
}
expect(err).toBeDefined();
expect(err!.message).toContain('putPage');
expect(err!.message).toContain("slug='suppressed-page'");
expect(err!.message).toContain("source_id='default'");
// The pre-fix crash signature must be gone.
expect(err!.message).not.toContain('deleted_at');
});
test('unsuppressed slugs still upsert normally with the trigger installed', async () => {
const page = await engine.putPage('normal-page', {
type: 'concept',
title: 'Normal',
compiled_truth: 'y',
timeline: '',
});
expect(page.slug).toBe('normal-page');
expect(page.source_id).toBe('default');
});
});
-25
View File
@@ -375,31 +375,6 @@ describe('performSync dry-run never writes', () => {
expect(messages.some(m => m.includes('git pull failed'))).toBe(false);
});
test('first PGLite code sync imports code files without runtime failures', async () => {
const { performSync } = await import('../src/commands/sync.ts');
mkdirSync(join(repoPath, 'src'), { recursive: true });
writeFileSync(
join(repoPath, 'src/example.ts'),
'export function add(left: number, right: number) { return left + right; }\n',
);
execSync('git add -A && git commit -m "add code file"', { cwd: repoPath, stdio: 'pipe' });
const result = await performSync(engine, {
repoPath,
noPull: true,
noEmbed: true,
noExtract: true,
strategy: 'code',
});
expect(result.status).toBe('first_sync');
expect(result.added).toBe(1);
expect(result.failedFiles ?? 0).toBe(0);
const page = await engine.getPage('src-example-ts');
expect(page?.type).toBe('code');
expect(page?.frontmatter).toMatchObject({ file: 'src/example.ts', language: 'typescript' });
});
test('incremental dry-run does NOT write to DB or advance the bookmark', async () => {
const { performSync } = await import('../src/commands/sync.ts');
// First do a real sync to seed the bookmark.