Skip to content

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 JSON numeric values in worker

Afloat8b4415370120
diff --git a/apps/node-services/AGENTS.md b/apps/node-services/AGENTS.md
index 070d93c7..650d3ea4 100644
--- a/apps/node-services/AGENTS.md
+++ b/apps/node-services/AGENTS.md
@@ -98,6 +98,16 @@ not make an empty message indexable.
- `scripts/generate-feature-catalog.ts` generates
`src/agent/agent-features/catalog.generated.ts`; `typecheck` verifies it.
+## JSON document conversion
+
+JSON imports validate and pretty-print the source while retaining each numeric
+literal. The converter uses Node's source-aware JSON reviver and raw JSON values
+so large identifiers, precise decimals and extreme exponents are not rounded or
+replaced with `null`. JSON conversion uses the normalizer's queued worker so
+per-value revival does not block the shared Node Services event loop, and it
+obeys the worker's cancellation, memory and timeout limits. UTF-8 validation
+is unchanged. Invalid JSON remains `DOCUMENT_SOURCE_INVALID`.
+
## Commands
- `pnpm --filter @linger/node-services check`: typecheck and lint
diff --git a/apps/node-services/src/document-normalizer/document-normalizer-core.ts b/apps/node-services/src/document-normalizer/document-normalizer-core.ts
index 9ef48876..d7234bb1 100644
--- a/apps/node-services/src/document-normalizer/document-normalizer-core.ts
+++ b/apps/node-services/src/document-normalizer/document-normalizer-core.ts
@@ -303,7 +303,18 @@ function parseDelimitedRows(text: string, delimiter: string): string[][] {
function jsonToMarkdown(text: string): string {
try {
- return fencedBlock("json", JSON.stringify(JSON.parse(text), null, 2));
+ // Node 26 provides raw JSON values; the project's ES2022 types omit them.
+ const json = JSON as typeof JSON & {
+ rawJSON(source: string): unknown;
+ };
+ const parsed: unknown = JSON.parse(
+ text,
+ (_key: string, value: unknown, context?: { source?: string }): unknown =>
+ typeof value === "number" && context?.source !== undefined
+ ? json.rawJSON(context.source)
+ : value,
+ );
+ return fencedBlock("json", JSON.stringify(parsed, null, 2));
} catch {
throw new DocumentNormalizationError("DOCUMENT_SOURCE_INVALID");
}
diff --git a/apps/node-services/src/document-normalizer/document-normalizer.ts b/apps/node-services/src/document-normalizer/document-normalizer.ts
index a1ccf545..4cd21855 100644
--- a/apps/node-services/src/document-normalizer/document-normalizer.ts
+++ b/apps/node-services/src/document-normalizer/document-normalizer.ts
@@ -160,9 +160,9 @@ interface WorkerDocumentNormalizerOptions {
}
/**
- * The process's one normalizer. Text formats convert in process; the rest
- * convert in an isolated worker, one at a time, so a PDF, Office or archive
- * parser that exhausts memory or hangs is stopped without the process. A request
+ * The process's one normalizer. Text formats other than JSON convert in process;
+ * the rest convert in an isolated worker, one at a time, so a parser
+ * that exhausts memory or hangs is stopped without the process. A request
* waits for the worker at most one timeout and fails as unavailable; the
* conversion itself then has its own timeout, which is terminal.
*/
diff --git a/apps/node-services/src/document-normalizer/document-source-kind.ts b/apps/node-services/src/document-normalizer/document-source-kind.ts
index 50ea2f2f..3a496e3c 100644
--- a/apps/node-services/src/document-normalizer/document-source-kind.ts
+++ b/apps/node-services/src/document-normalizer/document-source-kind.ts
@@ -30,7 +30,7 @@ export type DocumentSourceKind =
| "svg"
| "unsupported";
-const IN_PROCESS_DOCUMENT_SOURCE_KINDS = new Set<DocumentSourceKind>([
+const TEXT_DOCUMENT_SOURCE_KINDS = new Set<DocumentSourceKind>([
"markdown",
"plain",
"html",
@@ -271,7 +271,9 @@ export function isInProcessDocumentSource(
"filename" | "mediaType" | "representationFormat"
>,
): boolean {
- return IN_PROCESS_DOCUMENT_SOURCE_KINDS.has(resolveDocumentSourceKind(input));
+ 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);
}
export function codeFenceLanguage(filename: string | undefined): string {
@@ -342,7 +344,7 @@ function assertCompatibleCharset(
kind: DocumentSourceKind,
charset: string | null,
): void {
- if (!IN_PROCESS_DOCUMENT_SOURCE_KINDS.has(kind)) return;
+ if (!TEXT_DOCUMENT_SOURCE_KINDS.has(kind)) return;
if (
charset !== null &&
!["utf-8", "utf8"].includes(charset.toLocaleLowerCase("en-US"))
diff --git a/apps/node-services/tests/document-normalizer/document-json-numbers.test.ts b/apps/node-services/tests/document-normalizer/document-json-numbers.test.ts
new file mode 100644
index 00000000..f335817b
--- /dev/null
+++ b/apps/node-services/tests/document-normalizer/document-json-numbers.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vitest";
+
+import { normalizeDocumentContent } from "../../src/document-normalizer/document-normalizer-core.js";
+
+const encode = (value: string): Uint8Array => new TextEncoder().encode(value);
+const decode = (value: Uint8Array): string => new TextDecoder().decode(value);
+
+describe("JSON document numbers", () => {
+ it.each([
+ "9223372036854775807",
+ "-9223372036854775809",
+ "0.12345678901234567890123456789",
+ "1e400",
+ "1e-400",
+ "-0",
+ ])(
+ "retains the source number %s without a floating-point round trip",
+ async (number) => {
+ await expect(
+ normalizeDocumentContent({
+ filename: "value.json",
+ mediaType: "application/json",
+ source: encode(number),
+ }).then(decode),
+ ).resolves.toBe(`\`\`\`json\n${number}\n\`\`\`\n`);
+ },
+ );
+
+ it("preserves nested numeric values while keeping normal JSON formatting", async () => {
+ const source =
+ '{"id":9223372036854775807,"values":[0.1000000000000000001,{"small":1e-400}],"label":"9223372036854775807","active":true,"empty":null}';
+ const expected = [
+ "```json",
+ "{",
+ ' "id": 9223372036854775807,',
+ ' "values": [',
+ " 0.1000000000000000001,",
+ " {",
+ ' "small": 1e-400',
+ " }",
+ " ],",
+ ' "label": "9223372036854775807",',
+ ' "active": true,',
+ ' "empty": null',
+ "}",
+ "```",
+ "",
+ ].join("\n");
+ await expect(
+ normalizeDocumentContent({
+ filename: "values.json",
+ mediaType: "application/json",
+ source: encode(source),
+ }).then(decode),
+ ).resolves.toBe(expected);
+ });
+
+ it.each(["01", "Infinity", '{"value":1e}'])(
+ "still rejects invalid JSON numeric syntax: %s",
+ async (source) => {
+ await expect(
+ normalizeDocumentContent({
+ filename: "invalid.json",
+ mediaType: "application/json",
+ source: encode(source),
+ }),
+ ).rejects.toMatchObject({ code: "DOCUMENT_SOURCE_INVALID" });
+ },
+ );
+});
diff --git a/apps/node-services/tests/document-normalizer/document-json-worker.test.ts b/apps/node-services/tests/document-normalizer/document-json-worker.test.ts
new file mode 100644
index 00000000..520dedb2
--- /dev/null
+++ b/apps/node-services/tests/document-normalizer/document-json-worker.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from "vitest";
+
+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 request = (source: string) => ({
+ filename: "values.json",
+ mediaType: "application/json",
+ source: encode(source),
+});
+
+describe("JSON conversion worker", () => {
+ it("keeps the main event loop responsive while preserving numeric values", async () => {
+ const normalizer = new WorkerDocumentNormalizer();
+ await normalizer.normalizeDocument(request("0"));
+ const count = 20_000;
+ const number = "9223372036854775807";
+ const source = `[${Array.from({ length: count }, () => number).join(",")}]`;
+ let ticks = 0;
+ const timer = setInterval(() => {
+ ticks += 1;
+ }, 1);
+ let result: Uint8Array;
+ try {
+ result = await normalizer.normalizeDocument(request(source));
+ } finally {
+ clearInterval(timer);
+ }
+ expect(ticks).toBeGreaterThan(0);
+ expect(decode(result)).toBe(
+ `\`\`\`json\n[\n${Array.from({ length: count }, () => ` ${number}`).join(",\n")}\n]\n\`\`\`\n`,
+ );
+ });
+
+ it("rejects JSON conversion when the caller is already aborted", async () => {
+ const controller = new AbortController();
+ controller.abort();
+ await expect(
+ new WorkerDocumentNormalizer().normalizeDocument(
+ request("1"),
+ controller.signal,
+ ),
+ ).rejects.toMatchObject({ code: "DOCUMENT_NORMALIZATION_UNAVAILABLE" });
+ });
+
+ it("keeps invalid JSON errors across the real worker boundary", async () => {
+ await expect(
+ new WorkerDocumentNormalizer().normalizeDocument(request("01")),
+ ).rejects.toMatchObject({ code: "DOCUMENT_SOURCE_INVALID" });
+ });
+
+ it("keeps rejecting unsupported JSON charsets before conversion", async () => {
+ await expect(
+ new WorkerDocumentNormalizer().normalizeDocument({
+ ...request("1"),
+ mediaType: "application/json; charset=windows-1252",
+ }),
+ ).rejects.toMatchObject({ code: "DOCUMENT_SOURCE_UNSUPPORTED" });
+ });
+});