Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(timeline): keep HTML comments out of citation entries and page write-back; add repair timeline-comments (#6184)

garrytan80a06b1c095c
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index c779e68954..1a806fc87f 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -9,6 +9,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).
- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.
- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id; owner-produced writes are `producer_owned` residuals with the producer command. The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`). #5994: `laneContext` sets `ctx.replayAuthority` to the stored authority, so admission (`submissionAuthority` → `replayedAuthority` in `persistence/authority.ts`, and `requestPrincipalForContext`) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (`delegatedJobId`, or the id in a single legacy `wiki/agents/<id>/*` prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by `enforceSubagentSlugFence` (`ops/context.ts`) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored `timeline_section` (#5969).
+- `src/core/repair/timeline-comments.ts` — `gbrain repair timeline-comments` (#6184), explicit-only. The plan lists pages with timeline rows whose source, summary or detail carries `<!--`/`-->` or whose body has a materialized bullet carrying markup (`dropCommentBullets`), with residuals `comment_only_rows`, `comment_bearing_rows`, `pages_with_comment_bullets`. Apply: one revision-bound `put_page` per page dropping those generated bullets (user-written bullets are left), then one transaction under the page lock (`withCoordinatedWrite` with maintenance attribution on managed brains) that deletes comment-only rows and rewrites the rest to their stripped tuple, or deletes them when the page already has it. Idempotent. `timeline.ts` warns `timeline_comment_markup` naming this kind while such rows exist.
- `src/core/repair/orphan-children.ts` — `gbrain repair orphan-children` (#5216, #4738), explicit-only, brain-wide, projection publication. `PAGE_CHILD_FK_TARGETS` + `orphanPredicate` (a correlated, table-qualified `NOT EXISTS`, so Postgres plans an anti-join instead of a per-row subplan once page ids outgrow work_mem; `test/e2e/repair-orphan-children-plan-postgres.test.ts`) are the single target list (doctor `child_table_orphans` in `doctor/checks/core-health.ts` imports them and names this repair instead of printing SQL). One item per (table, column); apply deletes orphans or clears the two ON DELETE SET NULL references in one rechecking statement. `probeTornPages` reads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as the `torn_pages` residual plus a warning naming id/source/slug; they are never changed. The `storage_corrupt` reason in `pg-access-classify.ts` points XX000 storage errors here (`repair-orphan-children-5216.test.ts`, `pg-access-storage-corrupt-5216.test.ts`).
- `src/core/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). Scope: Git-visible `.md`/`.mdx` per source (managed owner root or legacy `local_path`) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. `frontmatterCandidates` builds a safe rewrite (NUL strip, nested-quote swap, `repairRecoverableFrontmatter` quoting; parsed values must be unchanged) and an interpretive one (`autoFixFrontmatter` missing close / slug line, fold, dup, unclosed, `#` rescue); both must strict-parse with no hold. `prepareRepairPublication` binds each proposal to the page fields its import would store; a refusal or canonical overlay is `needs_review`. The hash covers sources, `include_ambiguous`, `--only`/`--skip`, and per file before/after sha256, page id/revision, result digest and `rename_from`; the approved set stores no frontmatter text. Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through `managed_file_repair` (managed) or backup, write, `importFromFile`, hold clear and a printed commit step (legacy). Tests: `test/repair-frontmatter.test.ts`.
- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 5321aac16b..06f6b44960 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2334,6 +2334,16 @@ Reasons: `content_directory`.
|---|---|---|---|---|---|---|
| The skill target must remain within its selected root. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### timeline_comment_markup
+
+<a id="timeline_comment_markup"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A stored timeline row carries HTML comment markup, so gbrain keeps it database-side and never writes it back into the page; clean it with gbrain repair timeline-comments. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/repair.md#timeline-comments](../../docs/guides/repair.md#timeline-comments)
+
### timeline_rows_would_be_removed
<a id="timeline_rows_would_be_removed"></a>
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 60134ea70d..c570bb8871 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -376,6 +376,39 @@ doctor's `revision_backfill` check names those pages, and
`gbrain apply-migrations --force-schema` resumes the backfill for the rest and
prints its progress.
+<a id="timeline-comments"></a>
+### Timeline comments
+
+Before this release the inline-citation timeline parser read an HTML comment
+next to a `[Source: ..., YYYY-MM-DD]` citation as part of the entry, so a
+section marker such as `<!-- AUTO:slack END -->` became a timeline row, and
+writing that row back into the page added a second copy of the END marker.
+The parser now treats a comment-only line as a boundary and strips comments
+from summaries, and a row whose source, summary or detail still carries
+`<!--` or `-->` is never written back into the page (code
+`timeline_comment_markup`: it stays database-side and `gbrain repair timeline`
+warns about it). `gbrain repair timeline-comments` cleans what is already
+stored. It is explicit-only.
+
+**Say to your agent:** *"Preview the timeline comment cleanup, tell me how many
+rows and pages it touches, then apply after I agree."*
+
+```bash
+gbrain repair timeline-comments --source <id> # preview: comment_only_rows, comment_bearing_rows, pages_with_comment_bullets
+gbrain repair timeline-comments --source <id> --apply # clean them
+gbrain repair timeline-comments --source <id> # verify: nothing left
+```
+
+Per page it publishes one revision-bound `put_page` that drops the
+materialized bullets (marker, bullet and detail) whose line carries comment
+markup; bullets you wrote yourself are left alone. Then, under the page lock in
+a coordinated transaction, a row that is only markup is deleted, and a row with
+markup around real text is rewritten to the stripped text, or deleted when the
+page already has that stripped entry. A rewritten row is written back as a
+clean marked bullet by the page's next write. A second apply finds nothing. A
+page that is only rewritten in its timeline section queues no facts
+extraction (the body is unchanged).
+
### Timeline history scan coverage
Doctor's `timeline_history` check classifies at most 2,000 pages or 10
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index fcf78661e6..a73931bf75 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -261,6 +261,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.0.0-wave11', text: '`gbrain sources reconcile` now identifies a private fact row by its row number and claim, so a page whose world row shares a private row\'s claim publishes instead of being refused; it now also refuses a world row that copies a stored private row\'s context (24 or more characters) verbatim, naming only the row number.' },
{ since: '0.0.0-wave11', text: 'A remote put_page or put_pages entry whose content has no Timeline section is now refused with `timeline_rows_would_be_removed` when it would delete the page\'s dated entries; keep the section (get_page include_content:true) or pass `drop_timeline: true`. A local `gbrain put` without an expected revision keeps those rows; an explicitly empty `## Timeline` still deletes them, and every write that deletes rows reports `timeline_rows_removed` (count and dates).' },
{ since: '0.0.0-wave11', text: '`gbrain repair failed-writes` now replays subagent and restricted-namespace writes (they were all refused "via subagent requires ctx.subagentId"), under the original writer\'s stored authority re-checked against its live grant; replayed writes are attributed to that original writer.' },
+ { since: '0.0.0-wave11', text: 'Inline `[Source: ..., date]` citations no longer file an adjacent HTML comment (such as `<!-- AUTO:slack END -->`) as a timeline entry, and a timeline row carrying comment markup is never written back into a page (it would duplicate a section END marker); `gbrain repair timeline-comments --source <id>` previews and cleans rows and bullets stored before this release.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.ts
index abddd82ee4..e6cd3b30ae 100644
--- a/src/core/error-catalogue.ts
+++ b/src/core/error-catalogue.ts
@@ -49,6 +49,7 @@ export const ERROR_CATALOGUE = {
source_checkout_missing: { code: 'recovery_required', docs: 'docs/guides/write-refusals.md#source_checkout_missing' },
managed_pull_skipped: { code: 'managed_pull_skipped', docs: 'docs/guides/write-refusals.md#managed_pull_skipped' },
no_pricing: { code: 'no_pricing', docs: 'docs/guides/write-refusals.md#no_pricing' },
+ timeline_comment_markup: { code: 'timeline_comment_markup', docs: 'docs/guides/repair.md#timeline-comments' },
timeline_rows_would_be_removed: { code: 'timeline_rows_would_be_removed', docs: 'docs/guides/write-refusals.md#timeline_rows_would_be_removed' },
reconcile_private_facts: { code: 'permission_denied', docs: 'docs/guides/write-refusals.md#reconcile-private-facts' },
// F0 `gbrain sources refresh` (worktree-wide coordinated ff-only refresh).
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 0ca035a597..65017ee0ca 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -316,6 +316,7 @@ export const CODES = {
sync_parser_regression: { class: 'server', summary: "Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug.", why: "The upgrade invariant says a newer reader never refuses bytes an older one imported, so the run stops without advancing rather than hide a regression.", suggestion: 'Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull --retry-failed.' },
take_row_collision: { class: 'caller', summary: "A takes fence row number is already used by a different take that is not in this page's canonical fence." },
target_escape: { class: 'caller', summary: "The skill target must remain within its selected root." },
+ timeline_comment_markup: { class: 'caller', summary: "A stored timeline row carries HTML comment markup, so gbrain keeps it database-side and never writes it back into the page; clean it with gbrain repair timeline-comments.", docs: 'docs/guides/repair.md#timeline-comments' },
timeline_rows_would_be_removed: { class: 'caller', summary: "A remote put_page or put_pages entry has no Timeline section and would delete the page's dated entries; resend it with the section or with drop_timeline: true.", docs: 'docs/guides/write-refusals.md#timeline_rows_would_be_removed' },
timeout: { class: 'retryable', summary: "The operation did not finish within its time bound.", exit: 124 },
topology_change_required: { class: 'host_only', summary: "Adding this source would replace or overlap another owner root." },
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 910df6f1ae..fbc7bc689b 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -209,6 +209,7 @@ export async function timelineRowsToRemove(engine: BrainEngine, body: CanonicalB
}
const collapse = (text: string) => sanitizeForJsonb(text).replace(/\s+/g, ' ').trim();
+export const TIMELINE_COMMENT_MARKUP = /<!--|-->/;
/**
* Render one row as a marked bullet, or null when render-then-extract would
@@ -221,6 +222,9 @@ export function renderMaterializedBullet(row: { date: string; source: string; su
const detail = collapse(row.detail ?? '');
// Pre-#4277 backlink receipts are graph noise the extractors deliberately skip.
if (/^Referenced in\s+\[/i.test(tuple.summary)) return null;
+ // #6184: a row carrying HTML comment markup (a junk row the citation parser filed from a section END marker)
+ // would write a second copy of that marker into the page; it stays database-side until `gbrain repair timeline-comments`.
+ if (TIMELINE_COMMENT_MARKUP.test(`${row.source}\n${row.summary}\n${row.detail ?? ''}`)) return null;
const block = [materializedMarker(tuple), `- **${tuple.date}** | ${tuple.source} — ${tuple.summary}`, ...(detail ? [` ${detail}`] : [])].join('\n');
const extracted = [...canonicalTimeline({ compiled_truth: block, timeline: '' }, slug).values()];
if (extracted.length !== 1) return null;
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 3fc6c02bc5..225e558972 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -24,7 +24,7 @@ import { initializeLocalPersistence, requestPrincipalForContext } from '../persi
import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricing.ts';
import { shellQuote } from '../agent-output.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes', 'frontmatter'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 1d533e4dca..1a4d267c1d 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -24,6 +24,7 @@ import { loadConfig } from '../config.ts';
import { currentCliWriteWait } from '../persistence/write-wait.ts';
import { REPAIR_KINDS, runRepair, type RepairHandler, type RepairKind, type RepairResult, type RepairScope } from './core.ts';
import { timelineRepair } from './timeline.ts';
+import { timelineCommentsRepair } from './timeline-comments.ts';
import { visibilityRepair } from './visibility.ts';
import { safeChunksRepair } from './safe-chunks.ts';
import { contextualModeRepair } from './contextual-mode.ts';
@@ -177,6 +178,11 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'select files. Preview-bound: --apply --expect <hash> --yes writes exactly the previewed bytes, imports them and clears the hold (managed '
+ 'sources commit through the Git effect; legacy sources back up first and print the commit step). Files no rule fixes are listed with the exact manual fix.',
},
+ 'timeline-comments': {
+ handler: timelineCommentsRepair, embeds: 'effect', checks: [], explicit_only: true,
+ summary: 'Clean timeline rows filed from adjacent HTML comments (#6184): drop the materialized bullets that copied a section END marker into the page, '
+ + 'delete rows that are only comment markup, and strip the markup from the rest. Each page whose bullets change is re-embedded by its publication.',
+ },
'planner-stats': {
handler: plannerStatsRepair, embeds: 'none', checks: ['planner_stats_stale'],
summary: 'ANALYZE the hot tables (pages, links, facts, takes, content_chunks, timeline_entries) whose planner statistics are stale (F4b), '
diff --git a/src/core/repair/timeline-comments.ts b/src/core/repair/timeline-comments.ts
new file mode 100644
index 0000000000..e92cb9465f
--- /dev/null
+++ b/src/core/repair/timeline-comments.ts
@@ -0,0 +1,115 @@
+/**
+ * `gbrain repair timeline-comments` (#6184): clean timeline rows the
+ * inline-citation parser filed from adjacent HTML comments (a section's
+ * `<!-- AUTO:... END -->` marker, a materialized-row marker) and the
+ * materialized bullets that wrote those comments back into the page.
+ *
+ * Per page, one revision-bound `put_page` drops every materialized bullet whose
+ * line carries comment markup (gbrain wrote it; the user's own bullets are
+ * left alone), then one coordinated transaction under the page lock fixes the
+ * rows still carrying markup: a row whose summary is only markup is deleted, a
+ * row with markup around real text is rewritten to the stripped text (or
+ * deleted when that stripped tuple already exists on the page). Rewritten
+ * rows are database-only afterwards and are rendered back as clean marked
+ * bullets by the next writer. Preview first; a second apply finds nothing.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { serializePageToMarkdown } from '../markdown.ts';
+import { TIMELINE_COMMENT_MARKUP } from '../persistence/canonical-projections.ts';
+import { withCoordinatedWrite } from '../persistence/context.ts';
+import { maintenanceAttribution } from '../persistence/attribution.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { submitPageMutation } from '../persistence/page-mutations.ts';
+import { materializedMarkerHash } from '../timeline-marker.ts';
+import { stripHtmlComments } from '../timeline-citations.ts';
+import { repairRequestId, type RepairHandler, type RepairItem, type RepairScope, type RepairCursor } from './core.ts';
+
+interface MarkupRow { id: number; page_id: number; source_id: string; slug: string; date: string; source: string; summary: string; detail: string }
+
+const MARKUP_SQL = `(t.summary LIKE '%<!--%' OR t.summary LIKE '%-->%' OR t.source LIKE '%<!--%' OR t.source LIKE '%-->%'
+ OR t.detail LIKE '%<!--%' OR t.detail LIKE '%-->%')`;
+const clean = (text: string) => stripHtmlComments(text).replace(/\s+/g, ' ').trim();
+
+/** The body without materialized bullets (marker, bullet, indented detail) whose bullet line carries comment markup. */
+export function dropCommentBullets(body: string): string {
+ const lines = body.split('\n');
+ const kept: string[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ if (materializedMarkerHash(lines[i]!) && i + 1 < lines.length && /^\s*[-*+]\s/.test(lines[i + 1]!) && TIMELINE_COMMENT_MARKUP.test(lines[i + 1]!)) {
+ i++;
+ while (i + 1 < lines.length && /^[ \t]+\S/.test(lines[i + 1]!) && !/^[ \t]*[-*+] /.test(lines[i + 1]!)) i++;
+ continue;
+ }
+ kept.push(lines[i]!);
+ }
+ return kept.join('\n');
+}
+
+async function markupRows(engine: BrainEngine, where: string, params: unknown[]): Promise<MarkupRow[]> {
+ return engine.executeRaw<MarkupRow>(`SELECT t.id, t.page_id, p.source_id, p.slug, t.date::text AS date, t.source, t.summary, t.detail
+ FROM timeline_entries t JOIN pages p ON p.id=t.page_id
+ WHERE t.event_page_id IS NULL AND p.deleted_at IS NULL AND ${MARKUP_SQL} AND ${where} ORDER BY t.page_id, t.id`, params);
+}
+
+/** Rows of one page still carrying markup, fixed under the page lock: deleted, or rewritten to their stripped tuple. */
+async function cleanRows(engine: BrainEngine, page: { id: number; slug: string; source_id: string }): Promise<number> {
+ const run = async (tx: BrainEngine) => {
+ await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);
+ let fixed = 0;
+ for (const row of await markupRows(tx, 't.page_id=$1', [page.id])) {
+ const next = { source: clean(row.source), summary: clean(row.summary), detail: clean(row.detail ?? '') };
+ const [twin] = next.summary ? await tx.executeRaw<{ id: number }>(`SELECT id FROM timeline_entries
+ WHERE page_id=$1 AND event_page_id IS NULL AND date=$2::date AND source=$3 AND summary=$4 AND id<>$5 LIMIT 1`,
+ [page.id, row.date, next.source, next.summary, row.id]) : [];
+ if (!next.summary || twin) await tx.executeRaw('DELETE FROM timeline_entries WHERE id=$1', [row.id]);
+ else await tx.executeRaw('UPDATE timeline_entries SET source=$2, summary=$3, detail=$4 WHERE id=$1', [row.id, next.source, next.summary, next.detail]);
+ fixed++;
+ }
+ return fixed;
+ };
+ if (!await managedPersistenceEnabled(engine)) return engine.transaction(run);
+ const attribution = await maintenanceAttribution(engine);
+ return engine.transaction(tx => withCoordinatedWrite(tx, [page.source_id], () => run(tx), attribution));
+}
+
+export const timelineCommentsRepair: RepairHandler = {
+ kind: 'timeline-comments',
+ async plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null) {
+ const rows = await markupRows(engine, 'p.source_id=ANY($1::text[]) AND p.id>$2', [scope.source_ids, after?.id ?? 0]);
+ const pages = await engine.executeRaw<{ id: number; source_id: string; slug: string; compiled_truth: string; timeline: string | null }>(
+ `SELECT id, source_id, slug, compiled_truth, timeline FROM pages WHERE source_id=ANY($1::text[]) AND deleted_at IS NULL AND id>$2
+ AND (compiled_truth LIKE '%gbrain:materialized%' OR timeline LIKE '%gbrain:materialized%') ORDER BY id`, [scope.source_ids, after?.id ?? 0]);
+ const bullets = new Map(pages.map(p => [p.id, p] as const));
+ const byPage = new Map<number, { id: number; source_id: string; slug: string; rows: MarkupRow[]; bullets: boolean; chars: number }>();
+ for (const page of pages) {
+ const body = `${page.compiled_truth}\n${page.timeline ?? ''}`;
+ if (dropCommentBullets(body) !== body) byPage.set(page.id, { id: page.id, source_id: page.source_id, slug: page.slug, rows: [], bullets: true, chars: body.length });
+ }
+ for (const row of rows) {
+ const entry = byPage.get(row.page_id) ?? { id: row.page_id, source_id: row.source_id, slug: row.slug, rows: [], bullets: false,
+ chars: (bullets.get(row.page_id)?.compiled_truth.length ?? 0) + (bullets.get(row.page_id)?.timeline?.length ?? 0) };
+ entry.rows.push(row);
+ byPage.set(row.page_id, entry);
+ }
+ const items: RepairItem[] = [...byPage.values()].sort((a, b) => a.id - b.id).map(p => ({ cursor: { phase: 0, id: p.id }, source_id: p.source_id, slug: p.slug,
+ chars: p.chars, action: [p.bullets ? 'drop comment bullets' : '', p.rows.length ? `clean ${p.rows.length} row(s)` : ''].filter(Boolean).join(', ') }));
+ return { items, residuals: {
+ comment_only_rows: rows.filter(r => !clean(r.summary)).length,
+ comment_bearing_rows: rows.filter(r => !!clean(r.summary)).length,
+ pages_with_comment_bullets: [...byPage.values()].filter(p => p.bullets).length,
+ } };
+ },
+ async apply(ctx, item) {
+ const snapshot = await ctx.engine.readPageSnapshot(item.slug, { sourceId: item.source_id });
+ if (!snapshot) return false;
+ const next = { compiled_truth: dropCommentBullets(snapshot.page.compiled_truth), timeline: dropCommentBullets(snapshot.page.timeline ?? '') };
+ const rewrite = next.compiled_truth !== snapshot.page.compiled_truth || next.timeline !== (snapshot.page.timeline ?? '');
+ if (rewrite) {
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: item.slug, source_id: item.source_id,
+ content: serializePageToMarkdown({ ...snapshot.page, ...next }, snapshot.tags), expected_revision: snapshot.revision,
+ request_id: await repairRequestId(ctx, 'timeline-comments', item, snapshot.revision) } });
+ }
+ const fixed = await cleanRows(ctx.engine, { id: snapshot.page.id, slug: item.slug, source_id: item.source_id });
+ return rewrite || fixed > 0;
+ },
+};
diff --git a/src/core/repair/timeline.ts b/src/core/repair/timeline.ts
index e54ea9e7ce..64cee71d9f 100644
--- a/src/core/repair/timeline.ts
+++ b/src/core/repair/timeline.ts
@@ -72,7 +72,13 @@ export const timelineRepair: RepairHandler = {
const { pages } = await scanTimelineHistory(engine, scope.source_ids, after?.id ?? 0);
const items: RepairItem[] = pages.filter(p => p.materializable > 0).map(p => ({ cursor: { phase: 0, id: p.id }, source_id: p.source_id,
slug: p.slug, chars: p.compiled_truth.length + (p.timeline ?? '').length, action: `materialize ${p.materializable} row(s)` }));
- return { items, residuals: {
+ const [{ n: markup }] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM timeline_entries t JOIN pages p ON p.id=t.page_id
+ WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND t.event_page_id IS NULL
+ AND (t.summary LIKE '%<!--%' OR t.summary LIKE '%-->%' OR t.source LIKE '%<!--%' OR t.source LIKE '%-->%')`, [scope.source_ids]);
+ // #6184: such rows are never rendered back (they would duplicate a section END marker); name the cleanup.
+ const warnings = markup ? [`timeline_comment_markup: ${markup} timeline row(s) carry HTML comment markup and stay database-side; `
+ + `preview the cleanup with gbrain repair timeline-comments${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}.`] : [];
+ return { ...(warnings.length ? { warnings } : {}), items, residuals: {
materializable_rows: pages.reduce((n, p) => n + p.materializable, 0),
kept_unrenderable_rows: pages.reduce((n, p) => n + p.unrenderable, 0),
} };
diff --git a/src/core/timeline-citations.ts b/src/core/timeline-citations.ts
index e4434b3218..0b9cb37978 100644
--- a/src/core/timeline-citations.ts
+++ b/src/core/timeline-citations.ts
@@ -12,6 +12,13 @@ interface CitationParagraph {
text: string;
}
+/** #6184: HTML comments (section markers, materialized-row markers) are markup, never summary text. */
+const HTML_COMMENT_RE = /<!--[\s\S]*?-->/g;
+const COMMENT_ONLY_LINE_RE = /^\s*(?:<!--[\s\S]*?-->\s*)+$/;
+export function stripHtmlComments(text: string): string {
+ return text.replace(HTML_COMMENT_RE, ' ').replace(/<!--|-->/g, ' ');
+}
+
function startsMarkdownBlock(line: string): boolean {
return /^#{1,6}\s/.test(line) || /^\s*(?:[-*+]|\d+\.)\s+/.test(line);
}
@@ -31,7 +38,7 @@ function citationParagraphs(
};
for (const line of stripCodeBlocks(content).split(/\r?\n/)) {
- if (line.trim().length === 0) {
+ if (line.trim().length === 0 || COMMENT_ONLY_LINE_RE.test(line)) {
flush();
continue;
}
@@ -59,7 +66,7 @@ export function parseInlineCitationTimelineEntries(
for (const paragraph of citationParagraphs(content, opts)) {
const matches = [...paragraph.text.matchAll(CITATION_TIMELINE_RE)];
if (matches.length === 0) continue;
- const summary = paragraph.text
+ const summary = stripHtmlComments(paragraph.text)
.replace(/\[Source:[^\]]*\](?:\((?:[^()]|\([^()]*\))*\))?/g, '')
.replace(/^[-*>#\s]+/, '')
.replace(/\s+/g, ' ')
diff --git a/test/e2e/repair-timeline-comments.test.ts b/test/e2e/repair-timeline-comments.test.ts
new file mode 100644
index 0000000000..dccd19354d
--- /dev/null
+++ b/test/e2e/repair-timeline-comments.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../repair-timeline-comments.test.ts'));
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index 3dbaec1fac..0a8618142e 100644
--- a/test/repair-explicit-only.test.ts
+++ b/test/repair-explicit-only.test.ts
@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { withEnv } from './helpers/with-env.ts';
-const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes', 'frontmatter'];
+const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments'];
let engine: PGLiteEngine;
const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));
diff --git a/test/repair-timeline-comments.test.ts b/test/repair-timeline-comments.test.ts
new file mode 100644
index 0000000000..94e5265e1d
--- /dev/null
+++ b/test/repair-timeline-comments.test.ts
@@ -0,0 +1,107 @@
+/**
+ * `gbrain repair timeline-comments` (#6184): junk timeline rows filed from HTML
+ * comments, and the materialized bullets that copied a section END marker into
+ * the page, are cleaned through coordinated writes; preview first, a second
+ * apply is a no-op, valid bullets are untouched. Runs on PGLite and, through
+ * test/e2e, Postgres.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { materializedMarker } from '../src/core/timeline-marker.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-timeline-comments-'));
+let closePostgres: (() => Promise<void>) | undefined;
+const logger = { info() {}, warn() {}, error() {} };
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }
+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }
+ await closePostgres?.(); rmSync(dataDir, { recursive: true, force: true });
+});
+
+const slug = 'people/alice-example';
+const END = '<!-- AUTO:slack END -->';
+const junkOnly = { date: '2026-10-04', source: 'Slack import', summary: END };
+const junkSuffix = { date: '2026-10-05', source: 'Slack import', summary: `Talked with alice-example about the launch. ${END}` };
+/** What the pre-fix write-back rendered for a junk row: a marked bullet carrying a second copy of the END marker. */
+const junkBullet = (row: typeof junkOnly) => `${materializedMarker(row)}\n- **${row.date}** | ${row.source} — ${row.summary}`;
+const body = [
+ '---\ntype: person\ntitle: Alice Example\n---',
+ '<!-- AUTO:slack BEGIN -->',
+ '- Talked with alice-example about the launch. [Source: Slack import, 2026-10-05]',
+ END,
+ '',
+ '## Timeline',
+ '',
+ '- **2026-09-01** | markdown — Joined acme-example',
+ junkBullet(junkOnly),
+ junkBullet(junkSuffix),
+ '',
+].join('\n');
+
+test('preview counts junk rows and bullets; apply cleans them; a second apply is a no-op', async () => {
+ for (const engine of engines) {
+ const dir = mkdtempSync(join(dataDir, 'case-'));
+ const root = join(dir, 'brain'); mkdirSync(root);
+ const sourceId = `comments-${randomUUID().slice(0, 8)}`;
+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true }, dryRun: false, logger } as never;
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: body, request_id: randomUUID() } });
+ // The rows the pre-fix citation parser filed, as an upgraded brain has them.
+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {
+ for (const row of [junkOnly, junkSuffix]) await tx.executeRaw(`INSERT INTO timeline_entries(page_id,date,source,summary,detail)
+ SELECT id,$3::date,$4,$5,'' FROM pages WHERE source_id=$1 AND slug=$2 ON CONFLICT DO NOTHING`, [sourceId, slug, row.date, row.source, row.summary]);
+ }, TEST_WRITE_ATTRIBUTION));
+ const rows = async () => (await engine.executeRaw<{ d: string }>(`SELECT t.date::text || ' ' || t.source || ' — ' || t.summary AS d FROM timeline_entries t
+ JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 AND p.slug=$2 AND t.event_page_id IS NULL ORDER BY 1`, [sourceId, slug])).map(r => r.d);
+ const stored = async () => { const s = (await engine.readPageSnapshot(slug, { sourceId }))!; return `${s.page.compiled_truth}\n${s.page.timeline ?? ''}`; };
+ expect((await rows()).some(r => r.includes('<!--'))).toBe(true);
+
+ const scope = await resolveRepairScope(engine, sourceId);
+ const timelinePreview = async () => (await repairRunner(engine, { apply: false, logger })).run('timeline', scope, { sourceFlag: sourceId });
+ expect((await timelinePreview()).warnings?.join('\n')).toContain(`timeline_comment_markup: 2 timeline row(s)`);
+ expect((await timelinePreview()).warnings?.join('\n')).toContain(`gbrain repair timeline-comments --source ${sourceId}`);
+ const preview = await (await repairRunner(engine, { apply: false, logger })).run('timeline-comments', scope, { explicit: true, sourceFlag: sourceId });
+ expect(preview).toMatchObject({ mode: 'dry_run', affected: 1, residuals: { comment_only_rows: 1, comment_bearing_rows: 1, pages_with_comment_bullets: 1 } });
+ expect(await stored()).toContain(junkBullet(junkOnly));
+
+ const applied = await (await repairRunner(engine, { apply: true, logger })).run('timeline-comments', scope, { explicit: true, sourceFlag: sourceId });
+ expect(applied).toMatchObject({ applied: 1, complete: true });
+ expect(await rows()).toEqual(['2026-09-01 markdown — Joined acme-example', '2026-10-05 Slack import — Talked with alice-example about the launch.']);
+ const after = await stored();
+ expect(after.split(END).length - 1).toBe(1);
+ expect(after).toContain('- **2026-09-01** | markdown — Joined acme-example');
+ expect(after).not.toContain('Slack import — <!--');
+
+ const again = await (await repairRunner(engine, { apply: true, logger })).run('timeline-comments', scope, { explicit: true, sourceFlag: sourceId });
+ expect(again).toMatchObject({ affected: 0, applied: 0, complete: true });
+ expect((await timelinePreview()).warnings ?? []).toEqual([]);
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ }
+ }
+}, 120_000);
diff --git a/test/timeline-citations.test.ts b/test/timeline-citations.test.ts
new file mode 100644
index 0000000000..8bc84a4019
--- /dev/null
+++ b/test/timeline-citations.test.ts
@@ -0,0 +1,36 @@
+/** #6184: an HTML comment next to an inline citation is markup, never a timeline summary. */
+import { describe, expect, test } from 'bun:test';
+import { parseInlineCitationTimelineEntries } from '../src/core/timeline-citations.ts';
+import { renderMaterializedBullet } from '../src/core/persistence/canonical-projections.ts';
+
+describe('#6184 inline-citation timeline parsing', () => {
+ test('a comment-only line after a citation is a paragraph boundary, not the summary', () => {
+ expect(parseInlineCitationTimelineEntries('[Source: Slack import, 2026-10-04]\n<!-- AUTO:slack END -->')).toEqual([]);
+ });
+
+ test('an inline comment after the citation is stripped from the summary', () => {
+ expect(parseInlineCitationTimelineEntries('- Talked with alice-example about the launch. [Source: Slack import, 2026-10-04] <!-- AUTO:slack END -->'))
+ .toEqual([{ date: '2026-10-04', source: 'Slack import', summary: 'Talked with alice-example about the launch.' }]);
+ });
+
+ test('a materialized marker line after a cited sentence is not part of it', () => {
+ expect(parseInlineCitationTimelineEntries('Met alice-example. [Source: Slack import, 2026-10-04]\n<!-- gbrain:materialized v1 aa7e494fedca -->'))
+ .toEqual([{ date: '2026-10-04', source: 'Slack import', summary: 'Met alice-example.' }]);
+ });
+
+ test('a comment before the cited text and a dangling marker never reach the summary', () => {
+ expect(parseInlineCitationTimelineEntries('<!-- AUTO:slack BEGIN --> Shipped the beta. [Source: Slack import, 2026-10-05]'))
+ .toEqual([{ date: '2026-10-05', source: 'Slack import', summary: 'Shipped the beta.' }]);
+ expect(parseInlineCitationTimelineEntries('Shipped the beta. [Source: Slack import, 2026-10-05] -->').map(e => e.summary)).toEqual(['Shipped the beta.']);
+ });
+});
+
+describe('#6184 write-back guard', () => {
+ test('a row whose summary, source or detail carries comment markup is never rendered into the page', () => {
+ expect(renderMaterializedBullet({ date: '2026-10-04', source: 'Slack import', summary: '<!-- AUTO:slack END -->' }, 'notes/x')).toBeNull();
+ expect(renderMaterializedBullet({ date: '2026-10-04', source: 'Slack import', summary: 'Talked with alice-example. <!-- AUTO:slack END -->' }, 'notes/x')).toBeNull();
+ expect(renderMaterializedBullet({ date: '2026-10-04', source: '<!-- x -->', summary: 'ok' }, 'notes/x')).toBeNull();
+ expect(renderMaterializedBullet({ date: '2026-10-04', source: 'Slack import', summary: 'ok', detail: 'trailing -->' }, 'notes/x')).toBeNull();
+ expect(renderMaterializedBullet({ date: '2026-10-04', source: 'Slack import', summary: 'Talked with alice-example.' }, 'notes/x')).not.toBeNull();
+ });
+});