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 literal table cell text and search words
Afloat45d0a98cf8ff
diff --git a/apps/node-services/AGENTS.md b/apps/node-services/AGENTS.mdindex 650d3ea4..5241d70c 100644--- a/apps/node-services/AGENTS.md+++ b/apps/node-services/AGENTS.md@@ -128,6 +128,13 @@ CSV and TSV normalization accepts large row counts within the existing sourceand Markdown byte limits. An output that exceeds its configured byte budgetfails with `DOCUMENT_MARKDOWN_TOO_LARGE`, independently of the number of rows.+## Imported table cells++CSV, TSV and XLSX values are table data. Both table converters use the shared+cell escaping function so backslashes and inline Markdown delimiters remain+visible text after document materialization. CR, LF and CRLF inside a+cell become spaces instead of introducing new Markdown rows.+## Image- The `Dockerfile` builds one image that runs every role: port 4319 for thediff --git a/apps/node-services/src/document-normalizer/document-normalizer-core.ts b/apps/node-services/src/document-normalizer/document-normalizer-core.tsindex 0bcebeee..fa770cd8 100644--- a/apps/node-services/src/document-normalizer/document-normalizer-core.ts+++ b/apps/node-services/src/document-normalizer/document-normalizer-core.ts@@ -11,6 +11,7 @@ import {stripGzipExtension,} from "./document-archive-extract.js";import {+ escapeMarkdownTableCell,extractDocText,extractOfficeMarkdown,extractSpreadsheetMarkdown,@@ -207,7 +208,7 @@ function delimitedToMarkdown(text: string, delimiter: string): string {const width = rows.reduce((max, row) => Math.max(max, row.length), 0);const padded = rows.map((row) =>Array.from({ length: width }, (_, index) =>- (row[index] ?? "").replaceAll("\n", " ").replaceAll("|", "\\|"),+ escapeMarkdownTableCell(row[index] ?? ""),),);const header = padded[0] ?? [];diff --git a/apps/node-services/src/document-normalizer/document-office-extract.ts b/apps/node-services/src/document-normalizer/document-office-extract.tsindex 660add31..b5509840 100644--- a/apps/node-services/src/document-normalizer/document-office-extract.ts+++ b/apps/node-services/src/document-normalizer/document-office-extract.ts@@ -64,6 +64,10 @@ export function decodeXmlEntities(value: string): string {.replace(/&/gu, "&");}+export function escapeMarkdownTableCell(value: string): string {+ return value.replace(/\r\n?|\n/gu, " ").replace(/[\\`*_[\]|~]/gu, "\\$&");+}+export async function extractOfficeMarkdown(source: Uint8Array,kind: SupportedFileType,@@ -126,9 +130,7 @@ export async function extractSpreadsheetMarkdown(const lines = rows.map((row) =>`| ${Array.from({ length: width }, (_, i) =>- String(row[i] ?? "")- .replace(/\r?\n/g, " ")- .replaceAll("|", "\\|"),+ escapeMarkdownTableCell(String(row[i] ?? "")),).join(" | ")} |`,);lines.splice(diff --git a/apps/node-services/tests/document-normalizer/document-table-literals.test.ts b/apps/node-services/tests/document-normalizer/document-table-literals.test.tsnew file mode 100644index 00000000..1fc32cc0--- /dev/null+++ b/apps/node-services/tests/document-normalizer/document-table-literals.test.ts@@ -0,0 +1,84 @@+// @vitest-environment jsdom+import {+ materializeRoomDocument,+ readRoomDocumentBlocks,+} from "@linger/document-model";+import { describe, expect, it } from "vitest";+import * as XLSX from "xlsx";++import { normalizeDocumentContent } from "../../src/document-normalizer/document-normalizer-core.js";++function source(format: string, value: string): Uint8Array {+ const rows = [+ ["Record", "Value"],+ ["item", value],+ ];+ if (format === "xlsx") {+ const workbook = XLSX.utils.book_new();+ XLSX.utils.book_append_sheet(+ workbook,+ XLSX.utils.aoa_to_sheet(rows),+ "Data",+ );+ return XLSX.write(workbook, { type: "buffer", bookType: "xlsx" });+ }+ const separator = format === "csv" ? "," : "\t";+ return new TextEncoder().encode(+ rows+ .map((row) =>+ row.map((cell) => `"${cell.replaceAll('"', '""')}"`).join(separator),+ )+ .join("\n"),+ );+}++describe("literal table data", () => {+ for (const format of ["csv", "tsv", "xlsx"]) {+ it.each([+ [+ "Markdown punctuation",+ "C:\\temp\\| **bold** `code` _under_ ~~strike~~ [label](target)",+ "C:\\temp\\| **bold** `code` _under_ ~~strike~~ [label](target)",+ ],+ [+ "carriage returns",+ "first\rsecond\r\nthird\nfourth",+ "first second third fourth",+ ],+ ])(+ `preserves %s from ${format} in an editable table cell`,+ async (_name, value, expected) => {+ const markdown = await normalizeDocumentContent({+ filename: `table.${format}`,+ mediaType: "application/octet-stream",+ source: source(format, value),+ });+ const state = await materializeRoomDocument({+ materializationId: "25c9e991-7cc8-47c0-9e80-b6d748cae919",+ schemaVersion: 1,+ sourceKind: "markdown",+ sourceBytes: markdown,+ });+ const table = readRoomDocumentBlocks(state.stateBytes).find(+ (block) => block.type === "table",+ );+ expect(table?.type).toBe("table");+ if (!table || table.type !== "table")+ throw new Error("Missing imported table");+ const cells = table.content.rows.map((row) =>+ row.cells.map((cell) => (Array.isArray(cell) ? cell : cell.content)),+ );+ expect(cells).toEqual([+ [+ [{ type: "text", text: "Record", styles: {} }],+ [{ type: "text", text: "Value", styles: {} }],+ ],+ [+ [{ type: "text", text: "item", styles: {} }],+ [{ type: "text", text: expected, styles: {} }],+ ],+ ]);+ },+ );+ }+});diff --git a/apps/teamhub/internal/document/README.md b/apps/teamhub/internal/document/README.mdindex 7386532a..a9501f36 100644--- a/apps/teamhub/internal/document/README.md+++ b/apps/teamhub/internal/document/README.md@@ -27,6 +27,9 @@ Markdown files and have no body.`document_texts` holds each active Document's current version normalized once: the Markdown, itsSHA-256 and the plain search words, with the version it came from (`native_body` sequence or `file_version`).+Search flattening restores escaped Markdown punctuation as literal text, so identifiers such as `room_id`,+email addresses and backslash-containing paths stay searchable. Code spans and code blocks keep their+literal backslashes; formatting removal does not turn escaped punctuation into new markup.`internal/documenttext` runs the one `document_text.sync` job; `enqueue_document_text_sync` queues it fromtriggers on `documents` (a new current Version, reactivation), on a new `document_bodies` row and in`record_document_history_point`. Global search and Memory (`memory_source.personal_documents`, throughdiff --git a/apps/teamhub/internal/document/search_text.go b/apps/teamhub/internal/document/search_text.goindex 0ec16e9c..1a089969 100644--- a/apps/teamhub/internal/document/search_text.go+++ b/apps/teamhub/internal/document/search_text.go@@ -2,18 +2,23 @@ package documentimport ("regexp"+ "strconv""strings"++ "github.com/yuin/goldmark/ast"+ gmtext "github.com/yuin/goldmark/text")var (- fenceLine = regexp.MustCompile("(?m)^[ \t]*(```|~~~)[^\n]*$")- image = regexp.MustCompile(`!\[([^\]]*)\]\([^)\n]*\)`)- link = regexp.MustCompile(`\[([^\]\n]+)\]\([^)\n]*\)`)- htmlTag = regexp.MustCompile(`</?[A-Za-z][^>\n]{0,200}>`)- tableSeparator = regexp.MustCompile(`(?m)^[ \t]*\|?(?:[ \t]*:?-{3,}:?[ \t]*\|?)+[ \t]*$`)- linePrefix = regexp.MustCompile(`(?m)^[ \t]*(?:#{1,6}[ \t]+|>[ \t]?|[-*+][ \t]+(?:\[[ xX]\][ \t]+)?|\d{1,3}[.)][ \t]+)`)- emphasis = regexp.MustCompile("\\*+|~~|__|`+")- whitespace = regexp.MustCompile(`\s+`)+ fenceLine = regexp.MustCompile("(?m)^[ \t]*(```|~~~)[^\n]*$")+ image = regexp.MustCompile(`!\[([^\]]*)\]\([^)\n]*\)`)+ link = regexp.MustCompile(`\[([^\]\n]+)\]\([^)\n]*\)`)+ htmlTag = regexp.MustCompile(`</?[A-Za-z][^>\n]{0,200}>`)+ tableSeparator = regexp.MustCompile(`(?m)^[ \t]*\|?(?:[ \t]*:?-{3,}:?[ \t]*\|?)+[ \t]*$`)+ linePrefix = regexp.MustCompile(`(?m)^[ \t]*(?:#{1,6}[ \t]+|>[ \t]?|[-*+][ \t]+(?:\[[ xX]\][ \t]+)?|\d{1,3}[.)][ \t]+)`)+ emphasis = regexp.MustCompile("\\*+|~~|__|`+")+ whitespace = regexp.MustCompile(`\s+`)+ escapedPunctuation = regexp.MustCompile(`\\[[:punct:]]`))// MarkdownToSearchText flattens Markdown into one line of plain words for@@ -23,6 +28,7 @@ var (func MarkdownToSearchText(markdown string) string {// PostgreSQL text rejects NUL; preserve the surrounding words as separate tokens.markdown = strings.ReplaceAll(markdown, "\x00", " ")+ markdown, escapes := protectSearchEscapes(markdown)text := fenceLine.ReplaceAllString(markdown, "")text = image.ReplaceAllString(text, " $1 ")text = link.ReplaceAllString(text, "$1")@@ -38,5 +44,54 @@ func MarkdownToSearchText(markdown string) string {}text = strings.ReplaceAll(text, "|", " ")text = emphasis.ReplaceAllString(text, "")+ if escapes != nil {+ text = escapes.Replace(text)+ }return strings.TrimSpace(whitespace.ReplaceAllString(text, " "))}++func protectSearchEscapes(content string) (string, *strings.Replacer) {+ matches := escapedPunctuation.FindAllStringIndex(content, -1)+ if len(matches) == 0 {+ return content, nil+ }+ var code [][2]int+ // Plain table cells need no parse when neither code delimiters nor code indentation can occur.+ if strings.ContainsAny(content, "`\t") || strings.Contains(content, "~~~") || strings.Contains(content, " ") {+ root := markdown.Parser().Parse(gmtext.NewReader([]byte(content)))+ _ = ast.Walk(root, func(node ast.Node, entering bool) (ast.WalkStatus, error) {+ if entering {+ code = append(code, codeRanges(node)...)+ }+ return ast.WalkContinue, nil+ })+ }+ var output strings.Builder+ var replacements []string+ markers := make(map[byte]string)+ offset, codeIndex := 0, 0+ for _, match := range matches {+ for codeIndex < len(code) && code[codeIndex][1] <= match[0] {+ codeIndex+++ }+ if codeIndex < len(code) && code[codeIndex][0] <= match[0] {+ continue+ }+ punctuation := content[match[0]+1]+ marker, exists := markers[punctuation]+ if !exists {+ // Input NULs are already gone, so these markers cannot collide with source text.+ marker = "\x00" + strconv.Itoa(len(markers)) + "\x00"+ markers[punctuation] = marker+ replacements = append(replacements, marker, string(punctuation))+ }+ output.WriteString(content[offset:match[0]])+ output.WriteString(marker)+ offset = match[1]+ }+ if len(replacements) == 0 {+ return content, nil+ }+ output.WriteString(content[offset:])+ return output.String(), strings.NewReplacer(replacements...)+}diff --git a/apps/teamhub/internal/document/search_text_test.go b/apps/teamhub/internal/document/search_text_test.goindex 835a5a8d..3bf7f36c 100644--- a/apps/teamhub/internal/document/search_text_test.go+++ b/apps/teamhub/internal/document/search_text_test.go@@ -29,6 +29,36 @@ func TestMarkdownToSearchText(t *testing.T) {markdown: "| Field | Meaning |\n| --- | :---: |\n| status | index state |\n",want: "Field Meaning status index state",},+ {+ name: "escaped identifiers",+ markdown: `room\_id first\[email protected]`,+ want: "room_id [email protected]",+ },+ {+ name: "escaped and literal backslashes",+ markdown: `C:\\temp C:\temp`,+ want: `C:\temp C:\temp`,+ },+ {+ name: "escaped punctuation stays literal",+ markdown: `a\*b \*\*bold\*\* \[label\](target) left\|right \_\_raw\_\_`,+ want: `a*b **bold** [label](target) left|right __raw__`,+ },+ {+ name: "escapes inside emphasis and link labels",+ markdown: `**room\_id** [first\[email protected]](mailto:[email protected])`,+ want: "room_id [email protected]",+ },+ {+ name: "code keeps its literal backslashes",+ markdown: "Use `C:\\\\temp room\\_id`.\n\n```text\nC:\\\\temp room\\_id\n```\n\n C:\\\\temp room\\_id\n",+ want: `Use C:\\temp room\_id. C:\\temp room\_id C:\\temp room\_id`,+ },+ {+ name: "NUL boundaries do not collide with escaped punctuation",+ markdown: "\x000\x00 room\\_id",+ want: "0 room_id",+ },{name: "whitespace collapses across lines",markdown: "Barge-in policy: when the user speaks\nstop playback within 200ms\n\n\nand drop unplayed frames.",diff --git a/apps/teamhub/internal/documenttext/worker_test.go b/apps/teamhub/internal/documenttext/worker_test.goindex 0070b91f..85b6f99e 100644--- a/apps/teamhub/internal/documenttext/worker_test.go+++ b/apps/teamhub/internal/documenttext/worker_test.go@@ -119,7 +119,7 @@ func TestWorkerSyncsNativeAndFileDocuments(t *testing.T) {request.Header.Get("X-Source-Representation-Format") != "pdf" {t.Errorf("source headers = %v", request.Header)}- _, _ = writer.Write([]byte("Invoice\x00total: **1,200 USD**\n\n| item | qty |\n| --- | --- |\n| widget | 3 |"))+ _, _ = writer.Write([]byte("Invoice\x00total: **1,200 USD**\n\n| item | qty |\n| --- | --- |\n| widget | 3 |\n| room\\_id | C:\\\\temp |"))})worker := NewWorker(queries, documents, objects, normalizer, nil)@@ -142,7 +142,7 @@ func TestWorkerSyncsNativeAndFileDocuments(t *testing.T) {t.Fatalf("native upsert = %+v", got)}if got := byDocument["doc_file"]; got.Status != StatusReady || got.SourceID != "ver_1" ||- got.SearchText != "Invoice total: 1,200 USD item qty widget 3" || !got.MarkdownSha256.Valid {+ got.SearchText != "Invoice total: 1,200 USD item qty widget 3 room_id C:\\temp" || !got.MarkdownSha256.Valid {t.Fatalf("file upsert = %+v", got)}if got := byDocument["doc_scan"]; got.Status != StatusNoText || got.SearchText != "" || got.Markdown != "" || got.MarkdownSha256.Valid {