Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(documents): preserve structure when importing HTML
Afloata0683e50481b
diff --git a/apps/node-services/src/document-normalizer/README.md b/apps/node-services/src/document-normalizer/README.mdindex 3fde80c1..b54866e3 100644--- a/apps/node-services/src/document-normalizer/README.md+++ b/apps/node-services/src/document-normalizer/README.md@@ -11,3 +11,13 @@ of the character encoding. Parameters use MIME quoted-string parsing, socharset must be `utf-8` or `utf8`, case-insensitively; other declared encodingsare unsupported. Regardless of metadata, text bytes must pass strict UTF-8decoding before format-specific conversion.++HTML uses the existing Office converter to preserve inline text, links, lists,+tables and code blocks as Markdown. HTML runs in the shared bounded normalization+worker, with remote assets, image extraction and OCR disabled. Plain text and+Markdown retain their in-process path. HTML headings omit generated anchor labels+so CommonMark readers do not display them as literal text.++The response announces this behavior as normalizer version 3. A version header+change does not enqueue existing Document Versions for normalization; their+stored Markdown remains until a text sync runs again.diff --git a/apps/node-services/src/document-normalizer/document-normalizer-core.ts b/apps/node-services/src/document-normalizer/document-normalizer-core.tsindex d7234bb1..0bcebeee 100644--- a/apps/node-services/src/document-normalizer/document-normalizer-core.ts+++ b/apps/node-services/src/document-normalizer/document-normalizer-core.ts@@ -11,7 +11,6 @@ import {stripGzipExtension,} from "./document-archive-extract.js";import {- decodeXmlEntities,extractDocText,extractOfficeMarkdown,extractSpreadsheetMarkdown,@@ -89,7 +88,8 @@ export async function normalizeDocumentContent();break;case "html":- markdown = htmlToMarkdown(decodeUtf8Text(input.source));+ decodeUtf8Text(input.source);+ markdown = await extractOfficeMarkdown(input.source, "html");break;case "csv":markdown = delimitedToMarkdown(decodeUtf8Text(input.source), ",");@@ -199,39 +199,6 @@ function decodeUtf8Text(source: Uint8Array): string {return decoded;}-function htmlToMarkdown(html: string): string {- let value = html- .replace(/<script\b[\s\S]*?<\/script>/giu, "")- .replace(/<style\b[\s\S]*?<\/style>/giu, "")- .replace(/<noscript\b[\s\S]*?<\/noscript>/giu, "")- .replace(/<!--[\s\S]*?-->/gu, "")- .replace(/<br\s*\/?>/giu, "\n");- value = value.replace(- /<h([1-6])\b[^>]*>([\s\S]*?)<\/h\1>/giu,- (_match, level: string, inner: string) =>- `\n${"#".repeat(Number(level))} ${stripHtml(inner)}\n`,- );- value = value.replace(- /<li\b[^>]*>([\s\S]*?)<\/li>/giu,- (_match, inner: string) => `\n- ${stripHtml(inner)}`,- );- value = value.replace(- /<p\b[^>]*>([\s\S]*?)<\/p>/giu,- (_match, inner: string) => `\n\n${stripHtml(inner)}\n`,- );- return decodeXmlEntities(stripHtml(value))- .replace(/[ \t]+\n/gu, "\n")- .replace(/\n{3,}/gu, "\n\n")- .trim();-}--function stripHtml(value: string): string {- return value- .replace(/<[^>]+>/gu, " ")- .replace(/[ \t]{2,}/gu, " ")- .trim();-}-function delimitedToMarkdown(text: string, delimiter: string): string {const rows = parseDelimitedRows(text, delimiter);if (rows.length === 0) {diff --git a/apps/node-services/src/document-normalizer/document-normalizer.ts b/apps/node-services/src/document-normalizer/document-normalizer.tsindex 4cd21855..c03f7822 100644--- a/apps/node-services/src/document-normalizer/document-normalizer.ts+++ b/apps/node-services/src/document-normalizer/document-normalizer.ts@@ -3,7 +3,7 @@ import { Worker } from "node:worker_threads";import { serviceModule } from "../paths.js";export const DOCUMENT_NORMALIZER_NAME = "llm-wiki-document-markdown";-export const DOCUMENT_NORMALIZER_VERSION = "2";+export const DOCUMENT_NORMALIZER_VERSION = "3";export const MAX_DOCUMENT_PAGES = 100;export const MAX_DOCUMENT_SOURCE_BYTES = 50 * 1024 * 1024;export const MAX_DOCUMENT_MARKDOWN_BYTES = 32 * 1024 * 1024;diff --git a/apps/node-services/src/document-normalizer/document-office-extract.ts b/apps/node-services/src/document-normalizer/document-office-extract.tsindex 81777cf2..660add31 100644--- a/apps/node-services/src/document-normalizer/document-office-extract.ts+++ b/apps/node-services/src/document-normalizer/document-office-extract.ts@@ -90,6 +90,7 @@ export async function extractOfficeMarkdown(ast.metadata = {};return (await ast.to("md", {+ generateIds: kind !== "html",includeImages: "none",mdConfig: { dialect: "github", fallbackToHtml: false },})diff --git a/apps/node-services/src/document-normalizer/document-source-kind.ts b/apps/node-services/src/document-normalizer/document-source-kind.tsindex 3a496e3c..95fa44ef 100644--- a/apps/node-services/src/document-normalizer/document-source-kind.ts+++ b/apps/node-services/src/document-normalizer/document-source-kind.ts@@ -272,8 +272,10 @@ export function isInProcessDocumentSource(>,): boolean {const kind = resolveDocumentSourceKind(input);- // Source-aware JSON revival visits every value and can block shared roles.- return kind !== "json" && TEXT_DOCUMENT_SOURCE_KINDS.has(kind);+ // Structured parsing can block shared roles even when the source is text.+ return (+ kind !== "json" && kind !== "html" && TEXT_DOCUMENT_SOURCE_KINDS.has(kind)+ );}export function codeFenceLanguage(filename: string | undefined): string {diff --git a/apps/node-services/tests/document-normalizer/document-html.test.ts b/apps/node-services/tests/document-normalizer/document-html.test.tsnew file mode 100644index 00000000..9a47dfd2--- /dev/null+++ b/apps/node-services/tests/document-normalizer/document-html.test.ts@@ -0,0 +1,118 @@+import { describe, expect, it, vi } from "vitest";++import { normalizeDocumentContent } from "../../src/document-normalizer/document-normalizer-core.js";+import { WorkerDocumentNormalizer } from "../../src/document-normalizer/document-normalizer.js";++const encode = (value: string): Uint8Array => new TextEncoder().encode(value);+const decode = (value: Uint8Array): string => new TextDecoder().decode(value);+const html = (value: string) => ({+ filename: "notes.html",+ mediaType: "text/html",+ source: encode(value),+});+const convert = (value: string) =>+ normalizeDocumentContent(html(value)).then(decode);++describe("HTML document structure", () => {+ it("keeps identifiers and addresses together across inline elements", async () => {+ await expect(+ convert(+ "<p>Email: agent@example<span>.com</span>; key: order_<span>42</span>.</p>",+ ),+ ).resolves.toBe("Email: [email protected]; key: order_42.\n");+ });++ it("retains link targets and nested ordered and unordered lists", async () => {+ await expect(+ convert(+ '<p>See <a href="https://example.test/spec?q=a&b=2">the spec</a>.</p><ol><li>First<ul><li>Nested</li></ul></li><li>Second</li></ol>',+ ),+ ).resolves.toBe(+ "See [the spec](https://example.test/spec?q=a&b=2).\n\n1. First\n - Nested\n2. Second\n",+ );+ });++ it("retains table rows and their column relationships", async () => {+ await expect(+ convert(+ "<table><tr><th>Item</th><th>USD</th></tr><tr><td>Widget</td><td>37.50</td></tr></table>",+ ),+ ).resolves.toBe("| Item | USD |\n| --- | --- |\n| Widget | 37.50 |\n");+ });++ it.each(["", "\uFEFF"])(+ "keeps UTF-8 text and a possible BOM despite stale HTML charset metadata",+ async (prefix) => {+ await expect(+ convert(+ `${prefix}<meta charset="windows-1252"><p>Caf\u00e9 \u20ac</p>`,+ ),+ ).resolves.toBe("Caf\u00e9 \u20ac\n");+ },+ );++ it("preserves indentation and blank lines in a code block", async () => {+ await expect(+ convert(+ "<pre><code> const total = 12;\n\n return total;\n</code></pre>",+ ),+ ).resolves.toBe("```\n const total = 12;\n\n return total;\n\n```\n");+ });++ it("uses the bounded worker executor for HTML while plain text stays in process", async () => {+ const execute = vi.fn(async () => encode("worker result\n"));+ const normalizer = new WorkerDocumentNormalizer({ execute });+ await expect(+ normalizer.normalizeDocument(html("<p>Hello</p>")).then(decode),+ ).resolves.toBe("worker result\n");+ expect(execute).toHaveBeenCalledOnce();+ await expect(+ normalizer+ .normalizeDocument({+ filename: "notes.txt",+ mediaType: "text/plain",+ source: encode("Hello"),+ })+ .then(decode),+ ).resolves.toBe("Hello\n");+ expect(execute).toHaveBeenCalledOnce();+ });++ it("omits scripts, styles, comments and remote images", async () => {+ await expect(+ convert(+ '<script>throw new Error("script")</script><style>.x{color:red}</style><noscript>Hidden fallback</noscript><!-- comment --><p>Hello & goodbye</p><img src="https://example.invalid/pixel.png">',+ ),+ ).resolves.toBe("Hello & goodbye\n");+ });++ it.each([new Uint8Array([0xff]), encode("<p>bad\u0000text</p>")])(+ "keeps the existing text-decoding validation",+ async (source) => {+ await expect(+ normalizeDocumentContent({ ...html(""), source }),+ ).rejects.toMatchObject({ code: "DOCUMENT_SOURCE_INVALID" });+ },+ );++ it("rejects an unsupported declared charset before worker dispatch", async () => {+ const execute = vi.fn(async () => encode("worker result\n"));+ const normalizer = new WorkerDocumentNormalizer({ execute });+ await expect(+ normalizer.normalizeDocument({+ ...html("<p>ASCII-only body</p>"),+ mediaType: "text/html; charset=iso-8859-1",+ }),+ ).rejects.toMatchObject({ code: "DOCUMENT_SOURCE_UNSUPPORTED" });+ expect(execute).not.toHaveBeenCalled();+ });++ it("keeps empty HTML terminal and enforces the Markdown byte limit", async () => {+ await expect(convert("<p> </p>")).rejects.toMatchObject({+ code: "DOCUMENT_SOURCE_EMPTY",+ });+ await expect(+ normalizeDocumentContent(html("<p>Long text</p>"), 5),+ ).rejects.toMatchObject({ code: "DOCUMENT_MARKDOWN_TOO_LARGE" });+ });+});diff --git a/apps/node-services/tests/document-normalizer/document-normalizer.test.ts b/apps/node-services/tests/document-normalizer/document-normalizer.test.tsindex 49f584fc..e86c23c7 100644--- a/apps/node-services/tests/document-normalizer/document-normalizer.test.ts+++ b/apps/node-services/tests/document-normalizer/document-normalizer.test.ts@@ -97,7 +97,7 @@ describe("document normalization", () => {mediaType: "text/html; charset=utf-8",source: encode("<h1>Title</h1><p>Hello <b>world</b></p>"),}).then(decode),- ).resolves.toBe("# Title\n\nHello world\n");+ ).resolves.toBe("# Title\n\nHello **world**\n");await expect(normalizeDocumentContent({diff --git a/apps/node-services/tests/llm-wiki/document-normalization-server.llm-wiki.test.ts b/apps/node-services/tests/llm-wiki/document-normalization-server.llm-wiki.test.tsindex fb8669ef..34f31ed4 100644--- a/apps/node-services/tests/llm-wiki/document-normalization-server.llm-wiki.test.ts+++ b/apps/node-services/tests/llm-wiki/document-normalization-server.llm-wiki.test.ts@@ -19,6 +19,20 @@ afterEach(async () => {});describe("document normalization HTTP API", () => {+ it("imports HTML table relationships and links through the real worker", async () => {+ const httpUrl = await startServer(new WorkerDocumentNormalizer());+ const response = await fetch(`${httpUrl}/v0/document-normalizations`, {+ body: '<p>agent@example<span>.com</span></p><table><tr><th>Item</th><th>USD</th></tr><tr><td><a href="https://example.test/item">Widget</a></td><td>37.50</td></tr></table>',+ headers: serviceHeaders("text/html"),+ method: "POST",+ });+ expect(response.status).toBe(200);+ expect(response.headers.get("x-normalizer-version")).toBe("3");+ await expect(response.text()).resolves.toBe(+ "[email protected]\n\n| Item | USD |\n| --- | --- |\n| [Widget](https://example.test/item) | 37.50 |\n",+ );+ });+it("streams raw source bytes to the normalizer and returns versioned Markdown", async () => {const requests: Array<{ mediaType: string; source: Uint8Array }> = [];const normalizer: DocumentNormalizer = {diff --git a/contracts/generated/typescript/src/generated/node-services-internal/types.ts b/contracts/generated/typescript/src/generated/node-services-internal/types.tsindex bdb0105f..e5c615d3 100644--- a/contracts/generated/typescript/src/generated/node-services-internal/types.ts+++ b/contracts/generated/typescript/src/generated/node-services-internal/types.ts@@ -3141,7 +3141,7 @@ export interface operations {/** @description Stable normalizer implementation identity. */"X-Normalizer-Name": "llm-wiki-document-markdown";/** @description Behavior version; it changes whenever normalized output semantics change. */- "X-Normalizer-Version": "2";+ "X-Normalizer-Version": "3";[name: string]: unknown;};content: {diff --git a/contracts/openapi/node-services-internal/openapi.yaml b/contracts/openapi/node-services-internal/openapi.yamlindex 816b775f..d48f37da 100644--- a/contracts/openapi/node-services-internal/openapi.yaml+++ b/contracts/openapi/node-services-internal/openapi.yaml@@ -1095,7 +1095,7 @@ paths:change.schema:type: string- const: "2"+ const: "3"content:text/markdown:schema: