Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B 1b-i: keep markdown.ts under the size cap; key-files entry for the streamed parse and hash

garrytan7b254706d8f1
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index 4cb57f548d..a6dc3bcb31 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -33,7 +33,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/link-source-check-repair.ts` — schema-drift self-heal for the `links_link_source_check` CHECK constraint (third instance of the `timeline-dedup-repair.ts` / `pages-upsert-arbiter.ts` class). Migration v114 opened `link_source` from a closed allowlist to the kebab-case gate; the migrator trusts the version ledger, so a brain stamped >= 114 whose live constraint reverted to the pre-v114 allowlist (drifted restore, manual DDL) rejects every kebab provenance write (`atom-provenance`, `concept-provenance`) while the ledger reads current. `LINK_SOURCE_KEBAB_RE` is the ONE exported copy of the regex (a drift-guard test pins it to the literal in migrate.ts v114, `schema.sql`, `pglite-schema.ts`). `checkLinkSourceCheck(engine)` probes `pg_constraint` (`pg_get_constraintdef` + `convalidated`) and classifies the drift as `absent` / `wrong_def` / `not_validated` (read-only; powers the `links_link_source_check` doctor check in `doctor/checks/core-health.ts`, whose severity follows what writes do: only `wrong_def` rejects kebab writes → fail; `absent` / `not_validated` still accept them → warn). `repairLinkSourceCheck(engine)` first COUNTs rows that fail the gate and returns `reason: 'violations'` WITHOUT any DDL when there are any (the prior constraint survives; rows are never touched; a brain with a bad row never pays for a failing ALTER at every engine open), then restores v114's definition mirroring the migration's engine split: Postgres runs DROP + `ADD ... NOT VALID` in one `engine.transaction` (atomic, no scan) and `VALIDATE CONSTRAINT` as a separate `engine.runMigration` outside it (SHARE UPDATE EXCLUSIVE, never a plain ADD's ACCESS EXCLUSIVE + full-table scan), with a `not_validated` drift getting the VALIDATE only; PGLite keeps the one-shot DROP+ADD transaction. A DDL failure re-counts violators (a row written between probe and ALTER) and rethrows when there are none. `LINK_SOURCE_GATE_MIGRATION_VERSION` (114) is the ledger gate `runMigrations` applies before calling it. Pinned by `test/link-source-check-repair.test.ts` (PGLite, incl. a recording-engine assertion that violators trigger no DDL and that a sub-114 ledger never probes) and the DATABASE_URL-gated `test/e2e/link-source-check-repair-postgres.test.ts` (two-phase DDL sequence on real Postgres).
-- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relative `source_path` rows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller. After its pre-quote pass, a block the strict parse refuses goes to `recoverFrontmatter`; only `quote` recoveries are applied. Under `validate`, YAML_PARSE stays in `errors` (location-only message, `recoverable` plus a content-free `recovery` record), advisories go to `warnings` (`FRONTMATTER_RECOVERED`, `FRONTMATTER_COMMENT_VALUE`), and `recovery` carries interpretive, protected-key and identity-key findings. `HOLD_CODES` and `classifyImportHold(parsed, ctx)` define the ingestion hold set once; `isFrontmatterHoldMessage` recognizes its exact messages. Tests: `test/frontmatter-recovery.test.ts`.
+- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relative `source_path` rows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller. After its pre-quote pass, a block the strict parse refuses goes to `recoverFrontmatter`; only `quote` recoveries are applied. Under `validate`, YAML_PARSE stays in `errors` (location-only message, `recoverable` plus a content-free `recovery` record), advisories go to `warnings` (`FRONTMATTER_RECOVERED`, `FRONTMATTER_COMMENT_VALUE`), and `recovery` carries interpretive, protected-key and identity-key findings. `HOLD_CODES` and `classifyImportHold(parsed, ctx)` define the ingestion hold set once; `isFrontmatterHoldMessage` recognizes its exact messages. Tests: `test/frontmatter-recovery.test.ts` `parseMarkdown` is `parseMarkdownHead` (frontmatter readers, body text, findings) + `splitBody` + `parsedMarkdownFields`; with the exported line-level helpers (`timelineSentinelKind`, `bareTimelineSectionLine`, `h1TitleLineValue`, `embeddedTitleLineValue`, `quoteAmbiguousFrontmatterLine`, `validatorFrontmatterFence`) the streaming pass 1 in `src/core/page-body/body-scan.ts` reproduces its output over a bounded head and a line iterator (`test/large-pages/body-scan.test.ts`). `src/core/page-body/content-hash-stream.ts` streams `contentHash` (`utils.ts` `contentHashFrontmatterAndTags` shares the envelope tail) through the resumable SHA-256 in `page-body/sha256-resumable.ts`.
- `src/core/quarantine.ts` — the two frontmatter markers the content-quality gate writes, sibling of `src/core/embed-skip.ts` (same JSONB-object marker and `?` existence check on both engines; no migration). `quarantine` (key `QUARANTINE_KEY`) HIDES: set ONLY for high-confidence junk, writes zero chunks, excluded from search via `quarantineFilterFragment(pageAlias)` / `QUARANTINE_FILTER_FRAGMENT` (the `p`-aliased constant), the single source of truth `buildVisibilityClause` calls so the search filter and marker key can't drift. `content_flag` (key `CONTENT_FLAG_KEY`) WARNS, does NOT hide: set for fuzzy markup-heavy / oversize, page stays searchable, marker is READ INTO search/get_page output — deliberately NO SQL filter fragment. Three markers, three reasons: `embed_skip` = oversized-but-clean, `quarantine` = junk hidden, `content_flag` = odd-examine-still-here; a page can carry more than one (oversize → embed_skip + content_flag:oversized) and each clears independently. Exports `buildQuarantineMarker` / `isQuarantined` / `filterOutQuarantined`, `buildContentFlagMarker` / `getContentFlag` / `hasContentFlag`, plus the two key constants. Pinned by `test/quarantine.test.ts`. #6259: [quarantine cluster](quarantine.md). A quarantined page is skipped by every derived-data scan (stale listing via the engine-sql stale predicate, NER, meeting timeline projection, file walks via `quarantinedSlugs`, DB walks, the managed link derivation) and is not in the `links_extraction_lag` denominator. Pinned by `test/quarantine-extraction.test.ts`.
diff --git a/src/core/markdown.ts b/src/core/markdown.ts
index 076af48ca9..2037674a6f 100644
--- a/src/core/markdown.ts
+++ b/src/core/markdown.ts
@@ -222,11 +222,7 @@ function quoteAmbiguousFrontmatterScalars(content: string, quoted?: Array<{ key:
const QUOTE_FENCE_RE = /^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/;
-/**
- * How the pre-quote pass sees `lifted` (content after
- * stripLeadingBlanksBeforeFence): 'none' without a bare `---` opener line,
- * 'closed' when its fence closes inside `lifted`, else 'open'.
- */
+/** The pre-quote pass's fence in `lifted`: 'none' without a bare `---` opener line, 'closed' when it closes inside `lifted`. */
export function frontmatterQuoteFence(lifted: string): 'none' | 'closed' | 'open' {
if (!/^---\r?\n/.test(lifted)) return 'none';
return QUOTE_FENCE_RE.test(lifted) ? 'closed' : 'open';
@@ -335,13 +331,10 @@ export function parseMarkdown(
}
/**
- * What parseMarkdown reads before the body split: the raw frontmatter, the
- * body (after the closing fence, or the whole content when the block could
- * not be read) and the validation findings. `lifted` (leading blank lines
- * dropped before a fence) and `safeContent` (after the pre-quote pass) are the
- * strings the frontmatter readers saw; page-body/body-scan.ts checks that a
- * bounded file head yields the same reading as the whole file.
+ * What parseMarkdown reads before the body split. `lifted` and `safeContent` are the strings the frontmatter
+ * readers saw; page-body/body-scan.ts checks that a bounded file head reads the same as the whole file.
*/
+export type ParsedMarkdownFields = Omit<ParsedMarkdown, 'frontmatter' | 'compiled_truth' | 'timeline'>;
export interface ParsedMarkdownHead {
frontmatter: Record<string, unknown>;
body: string;
@@ -445,17 +438,8 @@ export function parseMarkdownHead(content: string, opts?: ParseOpts): ParsedMark
return { frontmatter, body, lifted, safeContent, errors, warnings, recovery };
}
-/**
- * Every ParsedMarkdown field derived from the head (all but frontmatter and
- * the body regions). `bodyTitle` (the body's first H1, then an embedded
- * leading fence block's `title:`) is consulted only without a frontmatter title.
- */
-export function parsedMarkdownFields(
- head: ParsedMarkdownHead,
- bodyTitle: () => string,
- filePath?: string,
- opts?: ParseOpts,
-): Omit<ParsedMarkdown, 'frontmatter' | 'compiled_truth' | 'timeline'> {
+/** ParsedMarkdown's head-derived fields; `bodyTitle` (first H1, then an embedded fence `title:`) only without a frontmatter title. */
+export function parsedMarkdownFields(head: ParsedMarkdownHead, bodyTitle: () => string, filePath?: string, opts?: ParseOpts): ParsedMarkdownFields {
const { frontmatter, errors, warnings, recovery } = head;
// #1948/#1939: frontmatter values can be non-strings (YAML coerces `title: 123`
// → number, a bare date → Date). The `as string` cast used to lie: a truthy
@@ -480,7 +464,7 @@ export function parsedMarkdownFields(
const tags = extractTags(frontmatter);
const slug = coerceFrontmatterString(frontmatter.slug) || inferSlug(filePath);
- const result: Omit<ParsedMarkdown, 'frontmatter' | 'compiled_truth' | 'timeline'> = {
+ const result: ParsedMarkdownFields = {
slug,
type,
typeExplicit: explicitType !== '',
@@ -611,11 +595,7 @@ export function nullBytesError(line: number): ParseValidationError {
return { code: 'NULL_BYTES', message: 'Content contains null bytes (likely binary corruption)', line };
}
-/**
- * The validator's view of the fence over `content.split('\n')`: the first
- * non-empty line (-1 when none), whether it opens a block, and the first later
- * line that trims to `---` (-1 when none, or when the first line does not open).
- */
+/** The validator's fence over `content.split('\n')`: first non-empty line, whether it opens, and the line closing it (-1: none). */
export function validatorFrontmatterFence(lines: readonly string[]): { firstNonEmpty: number; opens: boolean; closeLine: number } {
let firstNonEmpty = 0;
while (firstNonEmpty < lines.length && lines[firstNonEmpty]!.trim().length === 0) firstNonEmpty++;
@@ -943,11 +923,7 @@ function isTimelineSentinelLine(lines: string[], i: number, firstContent: number
return false;
}
-/**
- * The sentinel a trimmed body line can be: an explicit marker, or a bare `---`
- * ('dash'), which counts only when content precedes it and the next non-blank
- * line passes isTimelineHeadingAfterDash.
- */
+/** A trimmed sentinel line: a marker, or a `---` ('dash') that counts only after content and before isTimelineHeadingAfterDash. */
export function timelineSentinelKind(trimmed: string): 'marker' | 'dash' | null {
if (trimmed === '<!-- timeline -->' || trimmed === '<!--timeline-->') return 'marker';
if (trimmed === '--- timeline ---' || /^---\s+timeline\s+---$/i.test(trimmed)) return 'marker';
@@ -1011,11 +987,7 @@ export function isBareTimelineHeading(raw: string): boolean {
return /^##\s+(timeline|history)\b/i.test(raw.trim());
}
-/**
- * One line of a bare timeline section after its heading: the next H2 ends it,
- * blank lines, dated bullets and (after a bullet) wrapped continuations keep
- * it, anything else ('other') disqualifies the heading.
- */
+/** A line after a bare timeline heading: the next H2 ends the section, 'other' disqualifies the heading. */
export function bareTimelineSectionLine(raw: string, datedBullets: number): 'end' | 'blank' | 'bullet' | 'wrap' | 'other' {
const trimmed = raw.trim();
if (/^##\s+\S/.test(trimmed)) return 'end';