Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): timeline-order repair (#7247)
garrytan267b35f363c5
diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex ffea007f4e..58e7086fc0 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1062,6 +1062,51 @@ It drops generated bullets that carry markup (yours are left alone), deletesmarkup-only rows and strips the rest, under the page lock. A second apply findsnothing, and a timeline-only rewrite queues no facts extraction.+<a id="timeline-order"></a>+### Timeline order++Bulk imports and hand edits appended timeline bullets at the end of a page,+copied one bullet twice, or started a second `## Timeline` section (#7247).+`add_timeline_entry` already inserts in date order; this explicit-only,+preview-bound kind fixes pages written before that. It never runs from+`--all`, doctor's remediation plan, the maintenance cycle or an upgrade.++**Say to your agent:** *"Preview which timelines are out of order, show me the+list and the pages it would leave alone, then apply after I agree."*++```bash+gbrain repair timeline-order --source <id> [--slug <slug>]... # preview: reorder / needs_human+gbrain repair timeline-order --source <id> --apply --expect <hash> --yes # rewrites exactly the previewed pages+```++It sorts `- **YYYY-MM-DD** | source — summary` bullets, each with its indented+lines and the materialized marker above it, in the direction the page already+uses (ascending unless most neighbouring bullets descend), keeping equal dates+in their order. Prose, sub-headings, comments and code blocks stay where they+are, so bullets are sorted only between them. A later exact copy of a bullet in+the same run is dropped; bullets with one date whose summaries differ only in+case and punctuation are counted as `near_duplicates` and kept. A later+timeline section joins the first one, under its heading, when it holds nothing+but bullets and the first holds one run of them.++The preview counts `pages_to_reorder`, `duplicates_to_merge`,+`sections_to_join`, `needs_human` and `near_duplicates`. A page is listed+`needs_human` and kept when a line could belong to a bullet (a line right under+it, odd indentation, an indented paragraph after a blank line), when dated+bullets in another format sit among them, when a fence or comment never closes,+when the sections cannot be joined without moving prose, or when the result+would not read back with the same text order and timeline rows. A page whose+database-only timeline rows the write would also put into the page+(`pending_materialization`) waits for `gbrain repair timeline` (or+`gbrain extract timeline --prune-orphans` for rows an edit removed).++Each page is one revision-bound `put_page`: a managed source publishes its file+through the Git effect and the database is projected from it. No timeline row+is added, removed or rewritten (a dropped copy shared its row with the one that+stays). An apply refuses `preview_changed` when a previewed page moved since the+preview; preview again. Undo a page on a managed source with `git revert` of its+commit, or `gbrain revert`.+### Timeline history scan coverageDoctor's `timeline_history` check classifies at most 2,000 pages or 10diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex cf2b6a43f9..b45aa3f209 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -498,6 +498,9 @@ src/core/repair/take-supersession.ts readPage call:serializePageToMarkdown SEGWsrc/core/repair/timeline-comments.ts timelineCommentsRepair call:serializePageToMarkdown SEGWsrc/core/repair/timeline-comments.ts timelineCommentsRepair field STREAMsrc/core/repair/timeline-comments.ts timelineCommentsRepair sql STREAM+src/core/repair/timeline-order.ts plannedChange call:serializePageToMarkdown SEGW+src/core/repair/timeline-order.ts plannedChange field SEGW+src/core/repair/timeline-order.ts scan sql SEGW SQL exclusion: body_storage='inline' only; segmented pages carrying timeline rows are counted (segmentedTimelinePages) and named in a warningsrc/core/repair/timeline.ts classifyTimelinePage field STREAMsrc/core/repair/timeline.ts recountTimelinePages sql STREAMsrc/core/repair/timeline.ts removedRowIds field STREAM@@ -549,6 +552,7 @@ src/core/timeline-extract.ts retractCoordinated sql STREAMsrc/core/timeline-extract.ts retractRemovedTimelineEntries field STREAMsrc/core/timeline-extract.ts retractRemovedTimelineEntries sql STREAMsrc/core/timeline-extract.ts retractStoredPage field STREAM+src/core/timeline-order.ts orderTimeline field SEGW pure text core; its only caller (repair/timeline-order.ts) passes inline pagessrc/core/timeline-write-through.ts writeTimelineEntryThrough field SEGW assertInlineBody before the file or row is touchedsrc/core/timeline-write-through.ts writeTimelineEntryThrough sql SEGW assertInlineBody before the file or row is touchedsrc/core/transcripts/recover.ts userlessCodexSessions sql STREAMdiff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.jsonindex 3637a8a315..7a88f23208 100644--- a/scripts/postgres-arm-weights.json+++ b/scripts/postgres-arm-weights.json@@ -367,6 +367,7 @@"test/repair-frontmatter.test.ts": 19462,"test/repair-receipt-compaction.test.ts": 11290,"test/repair-rename-identity-6729.test.ts": 12251,+ "test/repair-timeline-order.test.ts": 7000,"test/schema-missing-tables.test.ts": 7947,"test/scripts/test-stress-postgres.test.ts": 13530,"test/search-read-keyword-bound.test.ts": 5082,diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 3454a28716..42804dfc74 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -36,6 +36,8 @@ import { ItemRun } from '../core/item-failure.ts';export const CONTENT_LANE = 'content';const REPAIR_CONTENT_HELP = ` gbrain repair content [--source <id>] [--only <path>]... [--skip <path>]... [--no-llm] [--max-usd <n>] [--diff][--apply [--expect <hash>[,<hash>]]] [--json]`;+/** #7247: the usage line of the timeline-order kind, which also takes --slug (the hash covers the selection). */+const REPAIR_ORDER_HELP = ' gbrain repair timeline-order [--source <id>] [--slug <slug>]... [--apply --expect <preview-hash> --yes] [--json]';const REPAIR_CONTENT_SUMMARY = ` content The content-repair lane (#6377), not a kind: runs ${CONTENT_REPAIR_KINDS.join(', then ')} over the same--source/--only selection, so the holds managed sync records for a file's content (invalid_fence,frontmatter_slug_conflict) clear in one pass. The preview plans every kind before anything is written and@@ -79,6 +81,7 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <igbrain repair uncommitted-deletions --source <id> [--after <page-id>] [--include-ambiguous] [--apply --expect <preview-hash> --yes] [--json]gbrain repair url-clone-fences [--source <id>] [--apply --expect <preview-hash> --yes] [--json]gbrain repair fact-claim-dates --source <id> [--day YYYY-MM-DD] [--apply --expect <preview-hash> --yes] [--json]+${REPAIR_ORDER_HELP}gbrain repair rename-identity --source <id> [--slug <new-slug> [--from <old-slug>] [--close][--apply --expect <preview-hash> --yes]] [--json]${REPAIR_CONTENT_HELP}@@ -162,7 +165,7 @@ const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--ski/** Flags only some kinds accept, with the kinds that do. */const KIND_FLAGS: Record<string, readonly string[]> = {'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'legacy-twins', 'rename-identity', 'url-clone-fences'],- '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],+ '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins', 'timeline-order'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],'--held': ['file-drift'], '--side': ['file-drift'], '--state': ['file-drift'],'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],@@ -404,7 +407,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro...(olderThan ? ['--older-than', olderThan] : []), ...(includeFailures ? ['--include-failures'] : []), ...(force ? ['--force'] : []),...(afterPage !== undefined ? ['--after', String(afterPage)] : []), ...(day ? ['--day', day] : []),...(kind === 'rename-identity' ? [...slugs.flatMap(slug => ['--slug', slug]), ...(from ? ['--from', from] : []), ...(close ? ['--close'] : [])] : []),- ...(kind === 'origin-twins' ? slugs.flatMap(slug => ['--slug', slug]) : [])];+ ...(kind === 'origin-twins' || kind === 'timeline-order' ? slugs.flatMap(slug => ['--slug', slug]) : [])];const custom = repairSpec(kind as RepairKind).consentText;const text = custom ? { ...custom, why: `Preview ${expect}: ${custom.why}`, user_message: `${custom.user_message} (preview ${expect.slice(0, 12)}${keep ? `, keep ${keep}` : ''})` } : {what: `Rewrite the previewed ${kind} changes on disk and import them`,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex d1da3263eb..23998d1c6f 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1055,6 +1055,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.338.0', text: 'The keyword arm keeps one chunk per page in its candidate pool (Postgres and PGLite), so a page with hundreds of matching chunks no longer pushes every other matching page out of the results.' },{ since: '0.60.338.0', text: 'The title arm\'s any-word retry (after an all-words title match finds nothing) now matches page titles only, as remote callers already did, and drops repeated words (#7135): a date in a question no longer pulls every dated timeline into ranking, which cut a 3-5 s title arm to well under a second on a large brain. A local all-words title match is unchanged.' },{ since: 'TBD', text: 'New doctor check `fact_bulk_dates` warns when one calendar day holds a bulk-loaded share of a source\'s facts as their `valid_from` (200 or more active facts, at least a quarter of the source, across 20 or more entities): those dates record when the facts were loaded, not when they happened. It names `gbrain repair fact-claim-dates --source <id>`, an explicit preview-then-apply repair that moves each such fact whose claim states exactly one earlier ISO date to that date, rewriting the page\'s facts fence row so the database follows the file; facts without a date keep the load day, and nothing changes on upgrade.' },+ { since: 'TBD', text: 'New explicit repair `gbrain repair timeline-order --source <id> [--slug <slug>]` puts existing timelines back in date order: `- **YYYY-MM-DD** | source — summary` bullets that bulk imports or hand edits appended out of order move, with their indented lines, into the direction the page already uses; a later exact copy of a bullet is dropped; and a second `## Timeline` section (or bullets below the timeline sentinel next to a `## Timeline` heading) joins the first when only bullets move. Prose, sub-headings and comments stay where they are, near duplicates are only counted, and a page with a line it cannot place is listed `needs_human`. The preview writes nothing and prints a hash; `--apply --expect <hash> --yes` rewrites exactly the previewed pages through revision-bound `put_page` and refuses `preview_changed` when one moved. No timeline row is added or removed. Nothing runs on upgrade.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex c7d3cc8ef2..9c7933072d 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions' | 'fact-claim-dates';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions' | 'fact-claim-dates' | 'timeline-order';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 6752e7e348..6de0473fd4 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -49,7 +49,7 @@ import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';import { readFix } from '../ops/op-fix.ts';import { ItemRun, type ItemFailure } from '../item-failure.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions', 'fact-claim-dates'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions', 'fact-claim-dates'] 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.tsindex 822bf7fc85..f0d717c5cd 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -36,6 +36,7 @@ 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 { timelineOrderRepair } from './timeline-order.ts';import { visibilityRepair } from './visibility.ts';import { safeChunksRepair } from './safe-chunks.ts';import { contextualModeRepair } from './contextual-mode.ts';@@ -303,6 +304,21 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {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.',},+ 'timeline-order': {+ handler: timelineOrderRepair, embeds: 'effect', checks: [], explicit_only: true, preview_bound: true, consent: 'destructive',+ consentText: {+ what: 'Rewrite the previewed pages so each timeline is in date order, without exact duplicate bullets, in one section',+ why: 'The preview listed each page whose timeline bullets are out of date order, repeat a bullet exactly, or sit in more than one timeline section, with the page revision it read.',+ risk: 'Only timeline bullets move; a later exact copy of a bullet is dropped and a later timeline section\'s bullets join the first. No other text changes and no timeline row is added or removed. A page that changed since the preview refuses the apply (preview_changed). Managed sources commit the file through the Git effect; undo with git revert or gbrain revert.',+ user_message: 'Put the previewed timelines in date order? Exact duplicate bullets are dropped and split timeline sections are joined',+ },+ summary: 'Put existing timelines back in date order (#7247): bulk imports and hand edits appended - **YYYY-MM-DD** | bullets at the end, '+ + 'copied one twice, or started a second ## Timeline section. Bullets move with their indented lines in the direction the page already uses '+ + '(ascending unless mostly descending), stable for equal dates; prose, sub-headings and comments stay where they are. Exact duplicates in one '+ + 'run keep the first copy; near duplicates are only counted. Later timeline sections join the first one only when nothing but bullets moves. A '+ + 'page with a line the parser cannot place, or that would not read back with the same text and timeline rows, is listed needs_human. --slug '+ + '<slug> narrows. Preview-bound: --apply --expect <hash> --yes rewrites exactly the previewed pages through revision-bound put_page; runs only when named.',+ },fences: {handler: fencesRepair, embeds: 'effect', checks: ['fence_integrity'], preview_bound: true, spends: 'llm',summary: 'Repair malformed facts and takes fences (#6188) that sync held or that pages store: per file or page the free tiers first (the lossless 'diff --git a/src/core/repair/timeline-order.ts b/src/core/repair/timeline-order.tsnew file mode 100644index 0000000000..9b4f522007--- /dev/null+++ b/src/core/repair/timeline-order.ts@@ -0,0 +1,204 @@+/**+ * `gbrain repair timeline-order` (#7247): put existing timelines back in date+ * order. Bulk imports and hand edits appended entries at the end of a page's+ * timeline, copied the same bullet twice, or started a second timeline+ * section; `add_timeline_entry` already inserts in date order+ * (`spliceTimelineBlock`), so only pages written before that need this.+ *+ * The text change is `orderTimeline` (timeline-order.ts, pure). Each planned+ * page must also read back exactly: the serialized page parses into the same+ * halves, is a fixed point of the repair, and projects the same timeline rows+ * (same tuples and details), so the publication never deletes, inserts or+ * rewrites a `timeline_entries` row. A removed exact duplicate shared its row+ * with the copy that stays, as it would after a hand edit removing it. A page+ * whose database-only rows the write would materialize (`editing` writer) is+ * kept until those are handled, so the publication adds nothing unplanned.+ *+ * Explicit-only and preview-bound: the preview lists each page with its+ * revision under a hash and writes nothing but the approval checkpoint;+ * `--apply --expect <hash> --yes` publishes exactly that set, one revision-bound+ * `put_page` per page with a request id derived from the hash, so the+ * coordinated write path publishes the canonical file (managed sources) and+ * re-projects the database from it. An apply whose pages moved since the+ * preview refuses `preview_changed` before anything is written. It never runs+ * from `--all`, the remediation plan, the maintenance cycle or an upgrade.+ * Segmented pages are counted, not rewritten.+ */+import type { BrainEngine, PageSnapshot } from '../engine.ts';+import { OperationError } from '../ops/contract.ts';+import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';+import { digest } from '../persistence/digest.ts';+import { pendingTimelineRows, storedCanonicalTimeline } from '../persistence/canonical-projections.ts';+import { submitPageMutation } from '../persistence/page-mutations.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { orderTimeline, type TimelineOrderHold } from '../timeline-order.ts';+import { segmentedTimelineNote, segmentedTimelinePages } from './timeline.ts';+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';++const BATCH = 200;+const DOCS = 'docs/guides/repair.md#timeline-order';++interface Selection { source_ids: string[]; slugs: string[] }+interface PlannedPage { source_id: string; slug: string; id: number; revision: string; moved: number; duplicates: number; sections_joined: number }+interface OrderItem extends RepairItem { page: PlannedPage; hash: string; last: boolean }+type Hold = TimelineOrderHold | 'pending_materialization';+type Verdict = { content: string; moved: number; duplicates: number; sections_joined: number } | { hold: Hold; rows?: number } | null;++const HOLD_TEXT: Record<Hold, string> = {+ unclosed_fence: 'a code fence in the timeline never closes',+ unclosed_comment: 'an HTML comment in the timeline never closes',+ lazy_continuation: 'a plain line directly under a bullet could belong to it',+ ambiguous_indent: 'a line under a bullet is indented by less than two spaces',+ detached_continuation: 'an indented line after a blank line under a bullet could belong to it',+ mixed_bullet_format: 'dated bullets in another format sit between the - **YYYY-MM-DD** | bullets',+ join_not_lossless: 'the timeline sections cannot be joined without moving prose or sub-headings',+ not_conserved: 'the reordered page would not read back with the same text order and timeline rows',+ pending_materialization: 'database-only timeline row(s) would be written into the page by the same write',+};++function previewCommand(scope: RepairScope, slugs: string[]): string {+ return `gbrain repair timeline-order${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}${slugs.map(slug => ` --slug ${slug}`).join('')}`;+}++const sourcesOf = (engine: BrainEngine, scope: RepairScope) => engine.executeRaw<{ id: string; incarnation: string }>(+ 'SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);++const hashOf = async (engine: BrainEngine, scope: RepairScope, selection: Selection, pages: PlannedPage[]) =>+ previewHash({ kind: 'timeline-order-v1', brain_id: scope.brain_id, sources: await sourcesOf(engine, scope), selection, pages });++/** One request id per page of an approved set: a resumed apply replays it, and the plan knows which pages already published. */+function requestIdOf(hash: string, page: Pick<PlannedPage, 'source_id' | 'slug' | 'revision'>): string {+ const h = digest(['timeline-order-request-v1', hash, page.source_id, page.slug, page.revision]);+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;+}++const rowsKey = (rows: Map<string, { date: string; source?: string | null; summary: string; detail?: string | null }>) =>+ JSON.stringify([...rows].map(([key, row]) => [key, row.date, row.source ?? '', row.summary, row.detail ?? '']).sort());++/** The page's repaired file, or why it is kept; null when its timeline is already in order. */+async function plannedChange(engine: BrainEngine, snapshot: PageSnapshot): Promise<Verdict> {+ const { page, tags } = snapshot;+ const result = orderTimeline(page);+ if (result.status === 'unchanged') return null;+ if (result.status === 'needs_human') return { hold: result.reason };+ const content = serializePageToMarkdown({ ...page, compiled_truth: result.compiled_truth, timeline: result.timeline }, tags);+ const reread = parseMarkdown(content, `${page.slug}.md`);+ const same = reread.compiled_truth.trim() === result.compiled_truth.trim() && (reread.timeline ?? '').trim() === result.timeline.trim()+ && orderTimeline(reread).status === 'unchanged'+ && rowsKey(await storedCanonicalTimeline(engine, page, page.slug)) === rowsKey(await storedCanonicalTimeline(engine, { ...page, ...reread }, page.slug));+ if (!same) return { hold: 'not_conserved' };+ const pending = await pendingTimelineRows(engine, { id: Number(page.id), slug: page.slug, compiled_truth: page.compiled_truth, timeline: page.timeline ?? '' });+ if (pending.materializable) return { hold: 'pending_materialization', rows: pending.materializable };+ return { content, moved: result.moved, duplicates: result.duplicates, sections_joined: result.sections_joined };+}++function holdDetail(hold: Hold, rows: number | undefined, scope: RepairScope): string {+ const source = scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : '';+ if (hold === 'pending_materialization') return `${rows} ${HOLD_TEXT[hold]}; run gbrain repair timeline${source} (or gbrain extract timeline --prune-orphans for rows `+ + 'an edit removed), then preview again';+ return `${HOLD_TEXT[hold]}; fix the timeline by hand, then preview again`;+}++function changeDetail(page: PlannedPage): string {+ return [page.moved ? `moves ${page.moved} bullet(s) into date order` : '', page.duplicates ? `drops ${page.duplicates} exact duplicate bullet(s)` : '',+ page.sections_joined ? `joins ${page.sections_joined} later timeline section(s) into the first` : ''].filter(Boolean).join(', ');+}++/** Every inline page of the selection whose timeline the repair would change or keep for a person, in id order. Read-only. */+async function scan(engine: BrainEngine, scope: RepairScope, selection: Selection) {+ const planned: PlannedPage[] = [];+ const listing: RepairListing[] = [];+ const residuals: Record<string, number> = { pages_to_reorder: 0, duplicates_to_merge: 0, sections_to_join: 0, needs_human: 0, near_duplicates: 0 };+ for (let cursor = 0; ;) {+ const batch = 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 body_storage='inline' AND id>$2+ AND (timeline LIKE '%- **____-__-__**%' OR compiled_truth LIKE '%- **____-__-__**%')+ AND (cardinality($3::text[])=0 OR slug=ANY($3::text[]))+ ORDER BY id LIMIT ${BATCH}`, [scope.source_ids, cursor, selection.slugs]);+ for (const row of batch) {+ cursor = Number(row.id);+ const quick = orderTimeline(row);+ residuals.near_duplicates! += quick.near_duplicates;+ if (quick.status === 'unchanged') continue;+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });+ if (!snapshot) continue;+ const verdict = await plannedChange(engine, snapshot);+ if (!verdict) continue;+ const label = `${row.source_id}:${row.slug} (revision ${snapshot.revision})`;+ if ('hold' in verdict) {+ residuals.needs_human!++;+ if (verdict.hold === 'pending_materialization') residuals.pending_materialization = (residuals.pending_materialization ?? 0) + 1;+ listing.push({ item: label, class: 'needs_human', detail: holdDetail(verdict.hold, verdict.rows, scope) });+ continue;+ }+ const page = { source_id: row.source_id, slug: row.slug, id: Number(row.id), revision: snapshot.revision,+ moved: verdict.moved, duplicates: verdict.duplicates, sections_joined: verdict.sections_joined };+ planned.push(page);+ if (page.moved) residuals.pages_to_reorder!++;+ residuals.duplicates_to_merge! += page.duplicates;+ residuals.sections_to_join! += page.sections_joined;+ listing.push({ item: label, class: 'reorder', detail: changeDetail(page) });+ }+ if (batch.length < BATCH) return { planned, listing, residuals };+ }+}++function item(page: PlannedPage, hash: string, last: boolean): OrderItem {+ return { cursor: { phase: 0, id: page.id }, source_id: page.source_id, slug: page.slug, chars: 0, action: changeDetail(page), page, hash, last };+}++export const timelineOrderRepair: RepairHandler = {+ kind: 'timeline-order',+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ const selection: Selection = { source_ids: scope.source_ids, slugs: [...new Set(opts?.slugs ?? [])].sort() };+ const command = previewCommand(scope, selection.slugs);+ if (!opts?.apply) {+ const { planned, listing, residuals } = await scan(engine, scope, selection);+ const hash = await hashOf(engine, scope, selection, planned);+ if (planned.length) await saveApprovedSet<PlannedPage & { selection: Selection }>(engine, { command: 'timeline-order', hash }, planned.map(page => ({ ...page, selection })));+ const segmented = selection.slugs.length ? { pages: 0, rows: 0, sample: [] } : await segmentedTimelinePages(engine, scope.source_ids);+ if (segmented.pages) residuals.segmented_pages = segmented.pages;+ return { items: planned.map((page, index) => item(page, hash, index === planned.length - 1)), preview_hash: hash, residuals, listing,+ ...(segmented.pages ? { warnings: [`segmented_pages: ${segmentedTimelineNote(segmented)} gbrain repair timeline-order does not reorder them either.`] } : {}) };+ }+ if (!opts.expect) {+ throw new OperationError('invalid_params', 'gbrain repair timeline-order --apply reorders only the set a preview printed.',+ `Preview first: ${command} — show the user the listing, then run the apply command it prints: ${command} --apply --expect <preview-hash> --yes`, DOCS);+ }+ const expect = opts.expect;+ const approved = (await loadApprovedSet<PlannedPage & { selection: Selection }>(engine, { command: 'timeline-order', hash: expect, previewCommand: command,+ emptyHash: () => hashOf(engine, scope, selection, []) })).items;+ if (approved.some(page => digest(page.selection) !== digest(selection))) throw previewChangedError(expect, command);+ const pages = approved.map(({ selection: _selection, ...page }) => page);+ const published = new Set((await engine.executeRaw<{ request_id: string }>(+ "SELECT request_id::text AS request_id FROM persistence_requests WHERE request_id=ANY($1::uuid[]) AND state='committed'",+ [pages.map(page => requestIdOf(expect, page))])).map(row => row.request_id));+ // Every page not yet published under this hash still has the revision the user saw, or nothing is written.+ for (const page of pages) {+ if (published.has(requestIdOf(expect, page))) continue;+ const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });+ if (snapshot?.revision !== page.revision || Number(snapshot.page.id) !== page.id) throw previewChangedError(expect, command);+ }+ return { items: pages.map((page, index) => item(page, expect, index === pages.length - 1)).filter(entry => afterCursor(entry.cursor, after)),+ preview_hash: expect, residuals: {} };+ },+ async apply(ctx, entry): Promise<RepairItemOutcome> {+ const { page, hash, last } = entry as OrderItem;+ try {+ const requestId = requestIdOf(hash, page);+ const [done] = await ctx.engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);+ const detail = { moved: page.moved, duplicates: page.duplicates, sections_joined: page.sections_joined };+ if (done?.state === 'committed') return { applied: true, outcome: 'reordered', detail };+ const snapshot = await ctx.engine.readPageSnapshot(page.slug, { sourceId: page.source_id });+ if (!snapshot || snapshot.revision !== page.revision) return { applied: false, outcome: 'changed_since_preview', reason: 'the page changed since the preview' };+ const verdict = await plannedChange(ctx.engine, snapshot);+ if (!verdict || 'hold' in verdict) return { applied: false, outcome: 'changed_since_preview', reason: verdict ? verdict.hold : 'the timeline is already in order' };+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: page.slug, source_id: page.source_id, content: verdict.content,+ expected_revision: snapshot.revision, request_id: requestId } });+ return { applied: true, outcome: 'reordered', detail };+ } finally {+ if (last) await clearApprovedSet(ctx.engine, { command: 'timeline-order', hash });+ }+ },+};diff --git a/src/core/timeline-order.ts b/src/core/timeline-order.tsnew file mode 100644index 0000000000..583542ab31--- /dev/null+++ b/src/core/timeline-order.ts@@ -0,0 +1,272 @@+/**+ * #7247: put a page's timeline back in date order, without the database.+ *+ * Pure text in, text out: `orderTimeline` takes a page's two halves+ * (`compiled_truth` above the timeline sentinel, `timeline` below it) and+ * returns the repaired halves with what changed, or the reason it would not+ * touch the page. `gbrain repair timeline-order` (repair/timeline-order.ts)+ * publishes the result through a revision-bound `put_page`.+ *+ * A timeline section is the headingless lead of the timeline half, or an+ * exact `## Timeline` / `## History` H2 section on either side of the+ * sentinel, holding at least one Format-1 bullet (`- **YYYY-MM-DD** | source —+ * summary`); it ends at the next H1 or H2 outside code fences and comments.+ * Inside a section:+ *+ * - a Format-1 bullet moves with its indented continuation lines and with the+ * #5567 materialized marker directly above it (the marker belongs to it);+ * - every other line (prose, sub-headings, comments, fences, tables) is an+ * anchor that never moves, so bullets are sorted only within the runs of+ * bullets and blank lines between anchors; blank lines keep their slots;+ * - a line that cannot be classified safely (a lazy continuation, odd+ * indentation, a bullet paragraph after a blank line, a dated bullet in+ * another format, an unclosed fence or comment) keeps the whole page as+ * it is and reports it for a person.+ *+ * Sorting is stable and follows the page's own direction: descending only when+ * more neighbouring bullets of a run descend than ascend. Exact duplicates (the same+ * block, byte for byte after trimming trailing whitespace) within one run keep+ * the first copy. Bullets with the same date whose summaries differ only in+ * case and punctuation are counted, never merged. Several timeline sections are+ * joined into the first one (its position and heading) only when every later+ * section holds nothing but bullets and the first holds one run of them, and+ * only when the joined body reads back in the same order.+ */+import { FENCE_TOGGLE_RE, isTimelineHeadingAfterDash, splitBody } from './markdown.ts';+import { isMaterializedMarkerLine } from './timeline-marker.ts';+import { extractTimelineFromContent } from './timeline-extract.ts';++const BULLET_RE = /^-\s+\*\*(\d{4}-\d{2}-\d{2})\*\*\s*\|/;+const DATED_BULLET_RE = /^\s*[-*+]\s+\**\d{4}\b/;+const CONTINUATION_RE = /^\s{2,}\S/;+const SECTION_END_RE = /^ {0,3}#{1,2}\s+\S/;+const SAFE_FOLLOWER_RE = /^(#{1,6}\s|[-*+]\s|\d+[.)]\s|<!--)/;++export type TimelineOrderHold = 'unclosed_fence' | 'unclosed_comment' | 'lazy_continuation' | 'ambiguous_indent' | 'detached_continuation'+ | 'mixed_bullet_format' | 'join_not_lossless' | 'not_conserved';++export type TimelineOrderResult =+ | { status: 'unchanged'; near_duplicates: number }+ | { status: 'needs_human'; reason: TimelineOrderHold; near_duplicates: number }+ | { status: 'changed'; compiled_truth: string; timeline: string; direction: 'ascending' | 'descending';+ moved: number; duplicates: number; sections_joined: number; near_duplicates: number };++interface Bullet { date: string; lines: string[] }+interface Run { lead: number; bullets: Bullet[]; gaps: number[]; trail: number }+type Block = { kind: 'blank' } | { kind: 'anchor'; lines: string[] } | { kind: 'run'; run: Run };+interface Section { region: 0 | 1; start: number; end: number; heading: boolean; blocks: Block[] }++class Hold extends Error { constructor(readonly reason: TimelineOrderHold) { super(reason); } }++/** Whether a line opens an HTML comment it does not close. */+const opensComment = (line: string) => { const at = line.lastIndexOf('<!--'); return at >= 0 && line.indexOf('-->', at + 4) < 0; };++/** Indices of section-ending headings (H1/H2) outside fences and multi-line comments. */+function headingLines(lines: string[]): number[] {+ const found: number[] = [];+ let fence = false, comment = false;+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i]!;+ if (comment) { if (line.includes('-->')) comment = false; continue; }+ if (FENCE_TOGGLE_RE.test(line)) { fence = !fence; continue; }+ if (fence) continue;+ if (opensComment(line)) { comment = true; continue; }+ if (SECTION_END_RE.test(line)) found.push(i);+ }+ return found;+}++/** Line ranges of the timeline sections in one half: `[start, end)`, heading line included when there is one. */+function sectionRanges(lines: string[], region: 0 | 1): Array<{ start: number; end: number; heading: boolean }> {+ const headings = headingLines(lines);+ const ranges: Array<{ start: number; end: number; heading: boolean }> = [];+ const hasBullet = (start: number, end: number) => lines.slice(start, end).some(line => BULLET_RE.test(line));+ const leadEnd = headings[0] ?? lines.length;+ if (region === 1 && hasBullet(0, leadEnd)) ranges.push({ start: 0, end: leadEnd, heading: false });+ headings.forEach((at, n) => {+ const end = headings[n + 1] ?? lines.length;+ if (isTimelineHeadingAfterDash(lines[at]!.trim()) && hasBullet(at + 1, end)) ranges.push({ start: at, end, heading: true });+ });+ return ranges;+}++/** Last line (exclusive) of the indented continuation lines that start at `from`. */+function continuationEnd(lines: string[], from: number): number {+ let end = from;+ while (end < lines.length && CONTINUATION_RE.test(lines[end]!)) end++;+ return end;+}++/** End (exclusive) of a fenced block or multi-line comment that opens at `at`; throws Hold when it never closes. */+function closingEnd(lines: string[], at: number, closes: (line: string) => boolean, reason: TimelineOrderHold): number {+ let end = at + 1;+ while (end < lines.length && !closes(lines[end]!)) end++;+ if (end >= lines.length) throw new Hold(reason);+ return end + 1;+}++/** A section's content as blank lines, anchors and runs of bullets; throws Hold on a line it cannot place safely. */+function tokenize(lines: string[]): Block[] {+ const blocks: Block[] = [];+ let run: Run | null = null, blanks = 0, afterBullet = false;+ const closeRun = () => {+ if (run) { run.trail = blanks; blocks.push({ kind: 'run', run }); }+ else for (let n = 0; n < blanks; n++) blocks.push({ kind: 'blank' });+ run = null; blanks = 0;+ };+ const anchor = (taken: string[]) => { closeRun(); blocks.push({ kind: 'anchor', lines: taken }); afterBullet = false; };+ for (let i = 0; i < lines.length;) {+ const line = lines[i]!;+ if (!line.trim()) { blanks++; i++; continue; }+ if (/^\s/.test(line)) {+ if (afterBullet) throw new Hold(blanks ? 'detached_continuation' : 'ambiguous_indent');+ const end = continuationEnd(lines, i + 1);+ anchor(lines.slice(i, end)); i = end; continue;+ }+ if (afterBullet && !blanks && !BULLET_RE.test(line) && !isMaterializedMarkerLine(line) && !FENCE_TOGGLE_RE.test(line) && !SAFE_FOLLOWER_RE.test(line)) {+ throw new Hold('lazy_continuation');+ }+ const bulletAt = isMaterializedMarkerLine(line) && BULLET_RE.test(lines[i + 1] ?? '') ? i + 1 : i;+ const date = BULLET_RE.exec(lines[bulletAt]!)?.[1];+ if (date) {+ const end = continuationEnd(lines, bulletAt + 1);+ const bullet = { date, lines: lines.slice(i, end) };+ if (run) { run.gaps.push(blanks); run.bullets.push(bullet); }+ else run = { lead: blanks, bullets: [bullet], gaps: [], trail: 0 };+ blanks = 0; afterBullet = true; i = end; continue;+ }+ if (DATED_BULLET_RE.test(line)) throw new Hold('mixed_bullet_format');+ const closed = FENCE_TOGGLE_RE.test(line) ? closingEnd(lines, i, text => FENCE_TOGGLE_RE.test(text), 'unclosed_fence')+ : opensComment(line) ? closingEnd(lines, i, text => text.includes('-->'), 'unclosed_comment') : i + 1;+ const end = continuationEnd(lines, closed);+ anchor(lines.slice(i, end)); i = end;+ }+ closeRun();+ return blocks;+}++const runsOf = (section: Section) => section.blocks.flatMap(block => block.kind === 'run' ? [block.run] : []);+const blockKey = (bullet: Bullet) => bullet.lines.map(line => line.trimEnd()).join('\n');+const blankLines = (count: number) => Array.from({ length: count }, () => '');++function render(section: Section, lines: string[]): string[] {+ const out = section.heading ? [lines[section.start]!] : [];+ for (const block of section.blocks) {+ if (block.kind === 'blank') out.push('');+ else if (block.kind === 'anchor') out.push(...block.lines);+ else {+ const { lead, bullets, gaps, trail } = block.run;+ out.push(...blankLines(lead));+ bullets.forEach((bullet, index) => out.push(...blankLines(index ? gaps[index - 1]! : 0), ...bullet.lines));+ out.push(...blankLines(trail));+ }+ }+ return out;+}++/** Date plus summary of a Format-1 bullet for near-duplicate counting: lower case, no punctuation or symbols, single spaces. */+function nearKey(bullet: Bullet): string | null {+ const [entry] = extractTimelineFromContent(bullet.lines.find(text => BULLET_RE.test(text))!, '');+ if (!entry) return null;+ return `${bullet.date} ${entry.summary.toLowerCase().replace(/[\p{P}\p{S}]/gu, '').replace(/\s+/g, ' ').trim()}`;+}++/** Bullets that repeat an earlier bullet's date and near summary without being an exact copy in the same run. */+function countNearDuplicates(sections: Section[]): number {+ const seen = new Set<string>();+ let near = 0;+ for (const run of sections.flatMap(runsOf)) for (const bullet of run.bullets) {+ const key = nearKey(bullet);+ if (key === null) continue;+ if (seen.has(key)) near++;+ else seen.add(key);+ }+ return near;+}++/** Appends every later section's bullets to the first section's only run; returns how many sections were joined. */+function joinSections(sections: Section[]): number {+ if (sections.length < 2) return 0;+ const [first, ...later] = sections;+ const target = runsOf(first!);+ if (target.length !== 1 || later.some(section => section.blocks.some(block => block.kind === 'anchor'))) throw new Hold('join_not_lossless');+ const run = target[0]!;+ for (const moved of later.flatMap(runsOf)) {+ const gap = run.gaps[run.gaps.length - 1] ?? moved.gaps[0] ?? 0;+ moved.bullets.forEach((bullet, index) => { run.gaps.push(index ? moved.gaps[index - 1]! : gap); run.bullets.push(bullet); });+ }+ return later.length;+}++/** Drops later exact copies of a block within one run; the gap above a dropped copy goes with it. */+function dropDuplicates(run: Run): number {+ const seen = new Set<string>();+ let dropped = 0;+ for (let index = 0; index < run.bullets.length;) {+ const key = blockKey(run.bullets[index]!);+ if (!seen.has(key)) { seen.add(key); index++; continue; }+ run.bullets.splice(index, 1);+ run.gaps.splice(index - 1, 1);+ dropped++;+ }+ return dropped;+}++/** Stable sort by date in the page's direction; returns how many bullets changed position. */+function sortRun(run: Run, descending: boolean): number {+ const before = run.bullets.slice();+ run.bullets = before.map((bullet, index) => ({ bullet, index }))+ .sort((a, b) => (descending ? b.bullet.date.localeCompare(a.bullet.date) : a.bullet.date.localeCompare(b.bullet.date)) || a.index - b.index)+ .map(entry => entry.bullet);+ return run.bullets.filter((bullet, index) => bullet !== before[index]).length;+}++/** Non-blank lines of a body without timeline sentinels: what a reader sees, in order. */+const visibleLines = (text: string) => text.split('\n').map(line => line.trimEnd()).filter(line => line && line.trim() !== '<!-- timeline -->').join('\n');++function holdOf(error: unknown): TimelineOrderHold {+ if (error instanceof Hold) return error.reason;+ throw error;+}++export function orderTimeline(page: { compiled_truth: string; timeline?: string | null }): TimelineOrderResult {+ const halves = [page.compiled_truth ?? '', page.timeline ?? ''].map(text => text.split('\n'));+ let sections: Section[];+ try {+ sections = ([0, 1] as const).flatMap(region => sectionRanges(halves[region]!, region).map(range => ({ region, ...range,+ blocks: tokenize(halves[region]!.slice(range.start + (range.heading ? 1 : 0), range.end)) })));+ } catch (error) { return { status: 'needs_human', reason: holdOf(error), near_duplicates: 0 }; }+ let up = 0, down = 0;+ for (const { bullets } of sections.flatMap(runsOf)) for (let i = 1; i < bullets.length; i++) {+ if (bullets[i]!.date > bullets[i - 1]!.date) up++;+ else if (bullets[i]!.date < bullets[i - 1]!.date) down++;+ }+ const descending = down > up;+ let joined: number;+ try { joined = joinSections(sections); } catch (error) { return { status: 'needs_human', reason: holdOf(error), near_duplicates: countNearDuplicates(sections) }; }+ const kept = joined ? [sections[0]!] : sections;+ let duplicates = 0, moved = 0;+ for (const run of kept.flatMap(runsOf)) { duplicates += dropDuplicates(run); moved += sortRun(run, descending); }+ const near = countNearDuplicates(kept);+ if (!joined && !duplicates && !moved) return { status: 'unchanged', near_duplicates: near };++ const next = halves.map(lines => lines.slice());+ for (const section of [...sections].sort((a, b) => b.region - a.region || b.start - a.start)) {+ const lines = next[section.region]!;+ if (joined && section !== sections[0]) {+ let start = section.start;+ if (section.end >= lines.length) while (start > 0 && !lines[start - 1]!.trim()) start--;+ lines.splice(start, section.end - start);+ } else lines.splice(section.start, section.end - section.start, ...render(section, halves[section.region]!));+ }+ const [truth, timeline] = next.map((lines, region) => {+ if (halves[region]![halves[region]!.length - 1]?.trim()) while (lines.length && !lines[lines.length - 1]!.trim()) lines.pop();+ return lines.join('\n');+ }) as [string, string];+ const body = timeline.trim() ? `${truth}\n\n<!-- timeline -->\n\n${timeline}` : truth;+ // A parser reads the published body back into halves; a read that moves content past other sections is not lossless.+ const reread = splitBody(body);+ if (visibleLines(`${reread.compiled_truth}\n${reread.timeline}`) !== visibleLines(body)) return { status: 'needs_human', reason: 'not_conserved', near_duplicates: near };+ const halvesOut = timeline.trim() ? { compiled_truth: truth, timeline } : reread;+ return { status: 'changed', ...halvesOut, direction: descending ? 'descending' : 'ascending', moved, duplicates, sections_joined: joined, near_duplicates: near };+}diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.tsindex 01c7833b40..d908e9bb39 100644--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@ -195,7 +195,7 @@ for (const backend of testBackends()) {const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };const previews = { 'accepted-takes': 'gbrain repair accepted-takes', 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'atoms-restore': 'gbrain repair atoms-restore', 'extractor-facts': 'gbrain repair extractor-facts','conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'redacted-facts': 'gbrain repair redacted-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'facts-rehome': 'gbrain repair facts-rehome', 'consolidate-ties': 'gbrain repair consolidate-ties', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',- frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'content-receipt-root': 'gbrain repair content-receipt-root', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift',+ frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'timeline-order': 'gbrain repair timeline-order', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'content-receipt-root': 'gbrain repair content-receipt-root', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift','stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'origin-twins': 'gbrain repair origin-twins', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity','overwritten-edits': 'gbrain repair overwritten-edits', 'legacy-twins': 'gbrain repair legacy-twins', 'missing-tables': 'gbrain repair missing-tables', 'url-clone-fences': 'gbrain repair url-clone-fences', 'segmented-mirror': 'gbrain repair segmented-mirror','uncommitted-deletions': 'gbrain repair uncommitted-deletions', 'fact-claim-dates': 'gbrain repair fact-claim-dates' };diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 26b0ba27a9..c9cb319542 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -383,6 +383,7 @@ test/repair-frontmatter-keys-sweep-6454.test.tstest/repair-frontmatter.test.tstest/repair-receipt-compaction.test.tstest/repair-rename-identity-6729.test.ts+test/repair-timeline-order.test.tstest/schema-missing-tables.test.tstest/scripts/test-stress-postgres.test.tstest/search-read-keyword-bound.test.tsdiff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 166d6d1ee2..9282d40988 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[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions', 'fact-claim-dates'];+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions', 'fact-claim-dates'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));diff --git a/test/repair-timeline-order.test.ts b/test/repair-timeline-order.test.tsnew file mode 100644index 0000000000..ee26fc6af7--- /dev/null+++ b/test/repair-timeline-order.test.ts@@ -0,0 +1,137 @@+/**+ * #7247: `gbrain repair timeline-order` on real publication, PGLite and Postgres. A managed source (claimed worktree:+ * the canonical file is published and the database re-projected from it) and a database-only source share one run.+ * The preview writes nothing, a stale or moved preview refuses, the apply rewrites exactly the planned pages without+ * touching a timeline row, other pages stay byte-identical, and a second preview finds nothing.+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+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 { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { maintenanceAttribution } from '../src/core/persistence/attribution.ts';+import { parseMarkdown } from '../src/core/markdown.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { AUTO_REPAIR_REGISTRY, repairRunner } from '../src/core/repair/registry.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { durableGitRepo } from './helpers/git-publication.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const logger = { info() {}, warn() {}, error() {} };+const gitRoot = async ({ engine, root }: { engine: BrainEngine; root: string }) => {+ writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']);+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('source-a','source-a') ON CONFLICT DO NOTHING");+};+const doc = (title: string, body: string, timeline: string) => `---\ntype: person\ntitle: ${title}\n---\n\n${body}\n\n<!-- timeline -->\n\n${timeline}\n`;++const ALICE = ['## Timeline', '', '- **2020-01-01** | import — Joined acme-example', ' Detail kept with its bullet.', '- **2024-03-01** | meeting — Quarterly review',+ '- **2021-06-01** | import — Moved to the city', '- **2022-01-01** | import — Promoted', '- **2020-01-01** | import — Joined acme-example', ' Detail kept with its bullet.',+ '', '## Timeline', '', '- **2019-05-01** | import — Graduated', '- **2023-02-01** | manual — Spoke at a meetup'].join('\n');+const ALICE_AFTER = ['## Timeline', '', '- **2019-05-01** | import — Graduated', '- **2020-01-01** | import — Joined acme-example', ' Detail kept with its bullet.',+ '- **2021-06-01** | import — Moved to the city', '- **2022-01-01** | import — Promoted', '- **2023-02-01** | manual — Spoke at a meetup', '- **2024-03-01** | meeting — Quarterly review'].join('\n');+const ACME = '## Timeline\n\n- **2018-01-01** | import — Founded\n- **2020-01-01** | import — Raised a seed round';+const BOB = '## Timeline\n\n- **2024-01-01** | import — Joined\nwrapped words with no indent\n- **2020-01-01** | import — Graduated\n- **2019-01-01** | import — Born';+const CAROL = '## Timeline\n\n- **2021-01-01** | import — Second\n- **2022-01-01** | import — Third\n- **2020-01-01** | import — First';++async function put(ctx: OperationContext, sourceId: string, slug: string, content: string, expected_revision?: string) {+ await submitPageMutation({ ...ctx, sourceId }, { operation: 'put_page', params: { slug, source_id: sourceId, request_id: randomUUID(), content,+ ...(expected_revision ? { expected_revision } : {}) } });+}+const rows = (engine: BrainEngine) => engine.executeRaw<Record<string, unknown>>(`SELECT t.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 ORDER BY t.id`);+const revision = async (engine: BrainEngine, sourceId: string, slug: string) => (await engine.readPageSnapshot(slug, { sourceId }))!.revision;+const timelineOf = async (engine: BrainEngine, sourceId: string, slug: string) => (await engine.readPageSnapshot(slug, { sourceId }))!.page.timeline ?? '';++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ describe(`#7247 gbrain repair timeline-order (${backend})`, () => {+ test('preview writes nothing; a stale or moved preview refuses; the apply rewrites exactly the planned pages; a second preview is empty', () => managedBrain(async ({ engine, ctx, root }) => {+ await put(ctx, 'default', 'people/alice-example', doc('Alice Example', 'Alice Example is a synthetic person.', ALICE));+ await put(ctx, 'default', 'companies/acme-example', doc('Acme Example', 'A synthetic company.', ACME));+ await put(ctx, 'default', 'people/bob-example', doc('Bob Example', 'A synthetic person.', BOB));+ await put(ctx, 'source-a', 'people/carol-example', doc('Carol Example', 'A synthetic person on a database-only source.', CAROL));+ const file = (slug: string) => readFileSync(join(root, `${slug}.md`), 'utf8');+ const files = { alice: file('people/alice-example'), acme: file('companies/acme-example'), bob: file('people/bob-example') };+ const revisions = { acme: await revision(engine, 'default', 'companies/acme-example'), bob: await revision(engine, 'default', 'people/bob-example'),+ carol: await revision(engine, 'source-a', 'people/carol-example') };+ const rowsBefore = await rows(engine);+ expect(rowsBefore.filter(row => row.slug === 'people/alice-example')).toHaveLength(6);++ expect(AUTO_REPAIR_REGISTRY.map(spec => spec.kind)).not.toContain('timeline-order');+ const scope = await resolveRepairScope(engine);+ const preview = () => repairRunner(engine, { apply: false, logger }).then(runner => runner.run('timeline-order', scope, { explicit: true }));+ const apply = (expect_: string) => repairRunner(engine, { apply: true, logger }).then(runner => runner.run('timeline-order', scope, { explicit: true, expect: expect_ }));+ await expect(repairRunner(engine, { apply: true, logger }).then(runner => runner.run('timeline-order', scope, { explicit: true }))).rejects.toThrow(/preview/i);++ const first = await preview();+ expect(first.affected).toBe(2);+ expect(first.residuals).toEqual({ pages_to_reorder: 2, duplicates_to_merge: 1, sections_to_join: 1, needs_human: 1, near_duplicates: 0 });+ expect(first.listing!.map(entry => [entry.class, entry.item.split(' ')[0]])).toEqual([+ ['reorder', 'default:people/alice-example'], ['needs_human', 'default:people/bob-example'], ['reorder', 'source-a:people/carol-example']]);+ expect(first.listing!.find(entry => entry.class === 'needs_human')!.detail).toContain('a plain line directly under a bullet');+ // The preview writes nothing.+ expect({ alice: file('people/alice-example'), acme: file('companies/acme-example'), bob: file('people/bob-example') }).toEqual(files);+ expect(await rows(engine)).toEqual(rowsBefore);+ expect(await timelineOf(engine, 'source-a', 'people/carol-example')).toBe(CAROL);++ // An unknown hash refuses, and so does the printed hash once a previewed page moved.+ await expect(apply('f'.repeat(64))).rejects.toMatchObject({ code: 'preview_changed' });+ await put(ctx, 'source-a', 'people/carol-example', doc('Carol Example', 'Edited after the preview.', CAROL), revisions.carol);+ await expect(apply(first.preview_hash!)).rejects.toMatchObject({ code: 'preview_changed' });+ expect(file('people/alice-example')).toBe(files.alice);+ revisions.carol = await revision(engine, 'source-a', 'people/carol-example');++ const second = await preview();+ expect(second.preview_hash).not.toBe(first.preview_hash);+ const applied = await apply(second.preview_hash!);+ expect(applied.applied).toBe(2);+ expect(applied.outcomes).toEqual({ reordered: 2 });++ // The managed page's canonical file and database row are the reordered page; nothing else in them changed.+ // Body bytes are exact; the frontmatter is re-rendered from the stored page as every page write renders it (same keys and values).+ const body = (text: string) => text.slice(text.indexOf('\n---\n') + 5);+ expect(body(file('people/alice-example'))).toBe(body(files.alice).replace(ALICE, ALICE_AFTER));+ expect(parseMarkdown(file('people/alice-example'), 'people/alice-example.md').frontmatter).toEqual(parseMarkdown(files.alice, 'people/alice-example.md').frontmatter);+ expect((await timelineOf(engine, 'default', 'people/alice-example')).trim()).toBe(ALICE_AFTER);+ expect((await timelineOf(engine, 'source-a', 'people/carol-example')).trim())+ .toBe('## Timeline\n\n- **2020-01-01** | import — First\n- **2021-01-01** | import — Second\n- **2022-01-01** | import — Third');+ // Not one timeline row was deleted, inserted or rewritten; the dropped copy shared its row with the one that stays.+ expect(await rows(engine)).toEqual(rowsBefore);+ // Pages outside the plan are byte-identical.+ expect(file('companies/acme-example')).toBe(files.acme);+ expect(file('people/bob-example')).toBe(files.bob);+ expect(await revision(engine, 'default', 'companies/acme-example')).toBe(revisions.acme);+ expect(await revision(engine, 'default', 'people/bob-example')).toBe(revisions.bob);++ // Idempotent: nothing left to reorder, and the consumed hash approves nothing.+ const third = await preview();+ expect(third.affected).toBe(0);+ expect(third.residuals).toMatchObject({ pages_to_reorder: 0, duplicates_to_merge: 0, sections_to_join: 0, needs_human: 1 });+ await expect(apply(second.preview_hash!)).rejects.toMatchObject({ code: 'preview_changed' });+ }, { databaseUrl, setup: gitRoot }), 180_000);++ test('--slug narrows the preview and its hash; a page whose database-only rows the write would materialize is kept', () => managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'default', 'people/alice-example', doc('Alice Example', 'Alice Example is a synthetic person.', ALICE));+ await put(ctx, 'default', 'people/dana-example', doc('Dana Example', 'A synthetic person.', CAROL));+ const scope = await resolveRepairScope(engine, 'default');+ const runner = await repairRunner(engine, { apply: false, logger });+ const narrowed = await runner.run('timeline-order', scope, { explicit: true, sourceFlag: 'default', slugs: ['people/dana-example'] });+ expect(narrowed.listing!.map(entry => entry.item.split(' ')[0])).toEqual(['default:people/dana-example']);+ expect(narrowed.apply_command).toContain('--slug people/dana-example');+ const all = await runner.run('timeline-order', scope, { explicit: true, sourceFlag: 'default' });+ expect(all.affected).toBe(2);+ expect(all.preview_hash).not.toBe(narrowed.preview_hash);++ const [{ id }] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug='people/dana-example'");+ await engine.transaction(async tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(+ "INSERT INTO timeline_entries(page_id,date,source,summary,detail) VALUES($1,'2019-01-01','legacy','Database-only event','')", [id]), await maintenanceAttribution(tx)));+ const held = await runner.run('timeline-order', scope, { explicit: true, sourceFlag: 'default', slugs: ['people/dana-example'] });+ expect(held.affected).toBe(0);+ expect(held.residuals).toMatchObject({ needs_human: 1, pending_materialization: 1 });+ expect(held.listing![0]!.detail).toContain('gbrain repair timeline --source default');+ }, { databaseUrl, setup: gitRoot }), 180_000);+ });+}diff --git a/test/timeline-order.test.ts b/test/timeline-order.test.tsnew file mode 100644index 0000000000..e43d81186e--- /dev/null+++ b/test/timeline-order.test.ts@@ -0,0 +1,126 @@+/**+ * #7247: the pure timeline-order core. Page text in, repaired text plus counts out; no database.+ */+import { describe, expect, test } from 'bun:test';+import { orderTimeline, type TimelineOrderHold } from '../src/core/timeline-order.ts';+import { materializedMarker } from '../src/core/timeline-marker.ts';++const page = (timeline: string, compiled_truth = 'Alice Example is a synthetic person.') => ({ compiled_truth, timeline });+const changed = (result: ReturnType<typeof orderTimeline>) => {+ if (result.status !== 'changed') throw new Error(`expected changed, got ${JSON.stringify(result)}`);+ return result;+};+const lines = (text: string) => text.split('\n').filter(line => line.trim()).sort();++describe('orderTimeline: sorting', () => {+ test('sorts ascending bullets with their indented lines, stable for equal dates, every other byte kept', () => {+ const before = ['## Timeline', '', '- **2020-01-01** | import — Joined acme-example', ' Detail line one.', ' - nested note', '- **2024-03-01** | meeting — Quarterly review',+ '- **2021-01-01** | import — Moved', '- **2022-05-05** | import — First tie', '- **2022-05-05** | import — Second tie', '- **2023-01-01** | import — Appended'].join('\n');+ const result = changed(orderTimeline(page(before)));+ expect(result.timeline).toBe(['## Timeline', '', '- **2020-01-01** | import — Joined acme-example', ' Detail line one.', ' - nested note',+ '- **2021-01-01** | import — Moved', '- **2022-05-05** | import — First tie', '- **2022-05-05** | import — Second tie', '- **2023-01-01** | import — Appended',+ '- **2024-03-01** | meeting — Quarterly review'].join('\n'));+ expect(result.compiled_truth).toBe('Alice Example is a synthetic person.');+ expect(result).toMatchObject({ direction: 'ascending', duplicates: 0, sections_joined: 0 });+ expect(lines(result.timeline)).toEqual(lines(before));+ expect(orderTimeline(result).status).toBe('unchanged');+ });++ test('keeps a mostly descending page descending', () => {+ const result = changed(orderTimeline(page(['- **2024-03-01** | a — B', '- **2023-01-01** | a — A', '- **2022-01-01** | a — C', '- **2025-01-01** | a — D'].join('\n'))));+ expect(result.direction).toBe('descending');+ expect(result.timeline.split('\n').map(line => line.slice(4, 14))).toEqual(['2025-01-01', '2024-03-01', '2023-01-01', '2022-01-01']);+ });++ test('a page already in order, or with no Format-1 bullets, is unchanged', () => {+ expect(orderTimeline(page('## Timeline\n\n- **2020-01-01** | a — A\n- **2021-01-01** | a — B'))).toEqual({ status: 'unchanged', near_duplicates: 0 });+ expect(orderTimeline(page('## Timeline\n\n- 2024-01-01: Series A\n- 2020-01-01: Founded'))).toEqual({ status: 'unchanged', near_duplicates: 0 });+ expect(orderTimeline({ compiled_truth: 'Only prose.', timeline: '' })).toEqual({ status: 'unchanged', near_duplicates: 0 });+ });++ test('blank lines keep their slots and anchors split the runs that are sorted', () => {+ const before = ['## Timeline', '', '### 2024', '', '- **2024-01-01** | a — y', '', '- **2024-05-01** | a — x', '- **2024-03-01** | a — z', '- **2024-07-01** | a — u', '',+ 'A paragraph people wrote.', '', '- **2023-05-01** | a — w', '- **2023-01-01** | a — v', '- **2023-09-01** | a — t', '- **2023-10-01** | a — s'].join('\n');+ const result = changed(orderTimeline(page(before)));+ expect(result.timeline).toBe(['## Timeline', '', '### 2024', '', '- **2024-01-01** | a — y', '', '- **2024-03-01** | a — z', '- **2024-05-01** | a — x', '- **2024-07-01** | a — u', '',+ 'A paragraph people wrote.', '', '- **2023-01-01** | a — v', '- **2023-05-01** | a — w', '- **2023-09-01** | a — t', '- **2023-10-01** | a — s'].join('\n'));+ });++ test('a materialized marker moves with the bullet below it', () => {+ const marker = materializedMarker({ date: '2020-01-01', source: 'legacy', summary: 'Kickoff' });+ const result = changed(orderTimeline(page(['- **2024-05-01** | a — x', '- **2025-01-01** | a — z', marker, '- **2020-01-01** | legacy — Kickoff', ' detail'].join('\n'))));+ expect(result.timeline).toBe([marker, '- **2020-01-01** | legacy — Kickoff', ' detail', '- **2024-05-01** | a — x', '- **2025-01-01** | a — z'].join('\n'));+ });++ test('bullets quoted in a fenced code block are an anchor and never sorted', () => {+ const before = ['- **2020-01-01** | a — y', '- **2024-01-01** | a — x', '- **2019-01-01** | a — v', '', '```md', '- **2030-01-01** | example — z', '- **2010-01-01** | example — w', '```'].join('\n');+ expect(changed(orderTimeline(page(before))).timeline).toBe(['- **2019-01-01** | a — v', '- **2020-01-01** | a — y', '- **2024-01-01** | a — x', '', '```md',+ '- **2030-01-01** | example — z', '- **2010-01-01** | example — w', '```'].join('\n'));+ });++ test('sections other than the timeline are never touched', () => {+ const truth = 'Bio.\n\n## Notes\n\n- **2024-01-01** | a — not a timeline\n- **2020-01-01** | a — left alone';+ expect(orderTimeline({ compiled_truth: truth, timeline: '' }).status).toBe('unchanged');+ const result = changed(orderTimeline(page('## Timeline\n\n- **2020-01-01** | a — y\n- **2024-01-01** | a — x\n- **2019-01-01** | a — v\n\n## Facts\n\n- **2030-01-01** | a — kept', truth)));+ expect(result.compiled_truth).toBe(truth);+ expect(result.timeline).toBe('## Timeline\n\n- **2019-01-01** | a — v\n- **2020-01-01** | a — y\n- **2024-01-01** | a — x\n\n## Facts\n\n- **2030-01-01** | a — kept');+ });+});++describe('orderTimeline: duplicates', () => {+ test('drops later exact copies (trailing whitespace ignored) and keeps the first', () => {+ const result = changed(orderTimeline(page(['## Timeline', '', '- **2020-01-01** | import — A', '- **2021-01-01** | x — B', '', '- **2020-01-01** | import — A ',+ '- **2022-01-01** | x — C'].join('\n'))));+ expect(result.timeline).toBe(['## Timeline', '', '- **2020-01-01** | import — A', '- **2021-01-01** | x — B', '- **2022-01-01** | x — C'].join('\n'));+ expect(result).toMatchObject({ duplicates: 1, moved: 0, near_duplicates: 0 });+ });++ test('a copy with different indented lines, or a near duplicate, is kept and only counted', () => {+ const before = ['- **2020-01-01** | import — Joined acme-example.', ' first detail', '- **2020-01-01** | import — Joined acme-example.', ' other detail',+ '- **2020-01-01** | meeting — joined Acme-Example'].join('\n');+ expect(orderTimeline(page(before))).toEqual({ status: 'unchanged', near_duplicates: 2 });+ });+});++describe('orderTimeline: joining sections', () => {+ test('two ## Timeline sections below the sentinel join into the first', () => {+ const result = changed(orderTimeline(page('## Timeline\n\n- **2020-01-01** | a — A\n- **2022-01-01** | b — B\n\n## Timeline\n\n- **2021-01-01** | c — C\n- **2020-01-01** | a — A')));+ expect(result.timeline).toBe('## Timeline\n\n- **2020-01-01** | a — A\n- **2021-01-01** | c — C\n- **2022-01-01** | b — B');+ expect(result).toMatchObject({ sections_joined: 1, duplicates: 1 });+ });++ test('bullets right below the sentinel and a later ## Timeline heading join, keeping the headingless first section', () => {+ const result = changed(orderTimeline(page('- **2023-01-01** | a — A\n\n## Timeline\n\n- **2021-01-01** | b — B\n\n## Facts\n\nKept.')));+ expect(result.timeline).toBe('- **2021-01-01** | b — B\n- **2023-01-01** | a — A\n\n## Facts\n\nKept.');+ });++ test('a ## Timeline section above the sentinel takes the bullets below it when it is the last section of the body', () => {+ const result = changed(orderTimeline({ compiled_truth: 'Bio.\n\n## Timeline\n\n- **2020-01-01** | a — A', timeline: '## Timeline\n\n- **2019-01-01** | b — B' }));+ expect(result.compiled_truth.trim()).toBe('Bio.');+ expect(result.timeline).toBe('## Timeline\n\n- **2019-01-01** | b — B\n- **2020-01-01** | a — A');+ expect(orderTimeline(result).status).toBe('unchanged');+ });++ test('a join that would move other sections, or prose, is kept for a person', () => {+ expect(orderTimeline({ compiled_truth: 'Bio.\n\n## Timeline\n\n- **2020-01-01** | a — A\n\n## Notes\n\nProse.', timeline: '## Timeline\n\n- **2019-01-01** | b — B' }))+ .toEqual({ status: 'needs_human', reason: 'not_conserved', near_duplicates: 0 });+ expect(orderTimeline(page('## Timeline\n\n- **2020-01-01** | a — A\n\n## Timeline\n\nA note.\n\n- **2019-01-01** | b — B')))+ .toMatchObject({ status: 'needs_human', reason: 'join_not_lossless' });+ expect(orderTimeline(page('## Timeline\n\n- **2020-01-01** | a — A\n\n### Later\n\n- **2021-01-01** | a — C\n\n## History\n\n- **2019-01-01** | b — B')))+ .toMatchObject({ status: 'needs_human', reason: 'join_not_lossless' });+ });+});++describe('orderTimeline: lines it cannot place keep the page', () => {+ const cases: Array<[TimelineOrderHold, string]> = [+ ['lazy_continuation', '- **2024-01-01** | a — x\nwrapped text\n- **2020-01-01** | a — y'],+ ['ambiguous_indent', '- **2024-01-01** | a — x\n wrapped text\n- **2020-01-01** | a — y'],+ ['detached_continuation', '- **2024-01-01** | a — x\n\n second paragraph\n- **2020-01-01** | a — y'],+ ['mixed_bullet_format', '- **2024-01-01** | a — x\n- 2022-01-01: other format\n- **2020-01-01** | a — y'],+ ['unclosed_fence', '- **2024-01-01** | a — x\n- **2020-01-01** | a — y\n\n```\nnever closed'],+ ['unclosed_comment', '- **2024-01-01** | a — x\n- **2020-01-01** | a — y\n\n<!-- never\nclosed'],+ ];+ for (const [reason, timeline] of cases) {+ test(reason, () => { expect(orderTimeline(page(timeline))).toEqual({ status: 'needs_human', reason, near_duplicates: 0 }); });+ }+});