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): convert OCR texts once and prune retired model packages
muterC972954f6032f
diff --git a/apps/node-services/AGENTS.md b/apps/node-services/AGENTS.mdindex 18066fcf..d2988ec6 100644--- a/apps/node-services/AGENTS.md+++ b/apps/node-services/AGENTS.md@@ -54,6 +54,8 @@and images, downloaded on first use where the offline runtime lists them in`models.json`. The `voice` role starts its download when the role starts,before any provider key exists, so the first worker start does not wait for it.+ At process start, downloaded packages `models.json` no longer lists are+ deleted, so a retired feature's model data leaves the machine.- Roles log through the `JsonLogger` the host passes to `start*Service`(`createJsonLogger` from `@linger/service-kit/node`); the `document` rolecreates its own inside its worker thread, and the `agent` role keeps its owndiff --git a/apps/node-services/src/main.ts b/apps/node-services/src/main.tsindex cef10d29..6500af21 100644--- a/apps/node-services/src/main.ts+++ b/apps/node-services/src/main.ts@@ -9,6 +9,7 @@ import { createJsonLogger, type JsonLogger } from "@linger/service-kit/node";import type { Flashback } from "./flashback.js";import type { ModelCall } from "./runtime-model-call.js";import { startHttpHost, type HttpHost } from "./http-host.js";+import { pruneModelPackages } from "./model-packages.js";import {NODE_SERVICES_DEFAULT_ADDRESS,readListenAddress,@@ -151,6 +152,14 @@ export async function main(? await startHttpHost(readHttpAddress(process.env)): undefined;const normalizer = new WorkerDocumentNormalizer();+ void pruneModelPackages().then(+ (removed) => {+ if (removed.length)+ logger.log("info", "model_packages.pruned", { packages: removed });+ },+ (error: unknown) =>+ logger.log("warn", "model_packages.prune_failed", { error }),+ );const seams: RoleHost["seams"] = {};const running: { name: RoleName; role: RunningRole }[] = [];const stopRoles = async (): Promise<void> => {diff --git a/apps/node-services/src/model-packages.ts b/apps/node-services/src/model-packages.tsindex 7fbd3bb7..55e44ba6 100644--- a/apps/node-services/src/model-packages.ts+++ b/apps/node-services/src/model-packages.ts@@ -138,6 +138,40 @@ export async function installModelPackages(}}+/**+ * Deletes downloaded packages the runtime no longer lists, so model data of+ * a retired feature does not stay on the machine. Downloads in progress+ * (`.partial-` folders) are left to their own installer.+ */+export async function pruneModelPackages(+ environment: NodeJS.ProcessEnv = process.env,+): Promise<string[]> {+ const root = modelPackagesRoot(environment);+ const listed = modelPackages();+ const removed: string[] = [];+ const entries = async (directory: string) =>+ readdir(directory, { withFileTypes: true }).catch(() => []);+ for (const entry of await entries(root)) {+ if (!entry.isDirectory()) continue;+ const names = entry.name.startsWith("@")+ ? (await entries(path.join(root, entry.name)))+ .filter((child) => child.isDirectory())+ .map((child) => `${entry.name}/${child.name}`)+ : [entry.name];+ for (const name of names) {+ if (name.includes(".partial-") || listed[name]) continue;+ await rm(path.join(root, name), { recursive: true, force: true });+ removed.push(name);+ }+ if (+ entry.name.startsWith("@") &&+ (await entries(path.join(root, entry.name))).length === 0+ )+ await rm(path.join(root, entry.name), { recursive: true, force: true });+ }+ return removed;+}+async function install(name: string,item: ModelPackage,diff --git a/apps/node-services/tests/model-packages.test.ts b/apps/node-services/tests/model-packages.test.tsindex f0f72abc..a07a21f3 100644--- a/apps/node-services/tests/model-packages.test.ts+++ b/apps/node-services/tests/model-packages.test.ts@@ -227,6 +227,38 @@ describe("model packages", () => {).toThrow("Unsafe path in model package: package/../escape");});+ it("removes downloaded packages the runtime no longer lists", async () => {+ const models = await load();+ const packagesRoot = models.modelPackagesRoot(environment);+ for (const name of [+ "@tesseract.js-data/eng",+ "@livekit/local-inference-linux-x64-gnu",+ "@livekit/local-inference-darwin-arm64.partial-1",+ "retired-model",+ ])+ await mkdir(path.join(packagesRoot, name), { recursive: true });+ expect((await models.pruneModelPackages(environment)).sort()).toEqual([+ "@tesseract.js-data/eng",+ "retired-model",+ ]);+ expect(existsSync(path.join(packagesRoot, "@tesseract.js-data"))).toBe(+ false,+ );+ expect(+ existsSync(+ path.join(packagesRoot, "@livekit/local-inference-linux-x64-gnu"),+ ),+ ).toBe(true);+ expect(+ existsSync(+ path.join(+ packagesRoot,+ "@livekit/local-inference-darwin-arm64.partial-1",+ ),+ ),+ ).toBe(true);+ });+it("installs nothing when the runtime lists no packages", async () => {await rm(path.join(runtime.packageRoot, "models.json"));const models = await load();diff --git a/apps/teamhub/migrations/00871_drop_scanned_document_texts.sql b/apps/teamhub/migrations/00871_drop_scanned_document_texts.sqlindex 69aa2f59..c83f17c8 100644--- a/apps/teamhub/migrations/00871_drop_scanned_document_texts.sql+++ b/apps/teamhub/migrations/00871_drop_scanned_document_texts.sql@@ -1,8 +1,27 @@-- +goose Up-- Document texts come only from text layers, never from OCR, so a ready PDF-- text always has one and the scanned flag goes away; a PDF without text is--- still rejected from the Wiki as scanned. Texts already stored are kept as--- they are.+-- still rejected from the Wiki as scanned. Texts OCR wrote are converted once+-- to what the normalizer gives now: a PDF read by OCR alone has no text and a+-- raster image is unsupported. Memory's hourly reconciliation then drops any+-- of them it indexed.+UPDATE document_texts+SET status = 'no_text', markdown = '', markdown_sha256 = NULL,+ search_text = '', longest_line_bytes = 0, updated_at = clock_timestamp()+WHERE status = 'ready' AND scanned;++UPDATE document_texts text+SET status = 'unsupported', markdown = '', markdown_sha256 = NULL,+ search_text = '', longest_line_bytes = 0, updated_at = clock_timestamp()+FROM document_versions version+WHERE text.source_kind = 'file_version' AND text.status = 'ready'+ AND version.id = text.source_id AND version.document_id = text.document_id+ AND lower(trim(split_part(version.media_type, ';', 1))) <> 'image/svg+xml'+ AND (lower(trim(split_part(version.media_type, ';', 1))) LIKE 'image/%'+ OR (lower(trim(split_part(version.media_type, ';', 1))) IN ('', 'application/octet-stream')+ AND lower(substring(version.filename FROM '\.([^.]+)$')) IN+ ('avif', 'bmp', 'gif', 'heic', 'heif', 'ico', 'jpeg', 'jpg', 'png', 'tif', 'tiff', 'webp')));+DROP VIEW public.wiki_current_sources;DROP VIEW public.wiki_document_verdicts;DROP FUNCTION public.source_rejection_reason(text, text, text, text, text, text, boolean, bigint, bigint);@@ -75,6 +94,8 @@ UNION ALLFROM public.wiki_session_sources;-- +goose Down+-- The converted texts stay converted; their Documents keep the texts the+-- current normalizer gives.DROP VIEW public.wiki_current_sources;DROP VIEW public.wiki_document_verdicts;DROP FUNCTION public.source_rejection_reason(text, text, text, text, text, text, bigint, bigint);diff --git a/apps/teamhub/tests/integration/drop_scanned_document_texts_migration_test.go b/apps/teamhub/tests/integration/drop_scanned_document_texts_migration_test.gonew file mode 100644index 00000000..16964eb8--- /dev/null+++ b/apps/teamhub/tests/integration/drop_scanned_document_texts_migration_test.go@@ -0,0 +1,81 @@+package integration_test++import (+ "context"+ "os"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/jackc/pgx/v5/stdlib"+ "github.com/pressly/goose/v3"+)++// Texts OCR wrote before the scanned flag was dropped are converted to what+// the normalizer gives now, so a scan stays out of the Wiki and an image has+// no searchable text; SVG and ordinary texts are untouched.+func TestDropScannedDocumentTextsConvertsOCRTexts(t *testing.T) {+ allowParallelIntegrationTest(t)+ ctx := context.Background()+ databaseURL := newIntegrationDatabaseWithoutSkills(t)+ config, err := pgx.ParseConfig(databaseURL)+ if err != nil {+ t.Fatal(err)+ }+ db := stdlib.OpenDB(*config)+ t.Cleanup(func() { _ = db.Close() })+ provider, err := goose.NewProvider(goose.DialectPostgres, db, os.DirFS("../../migrations"))+ if err != nil {+ t.Fatal(err)+ }+ if _, err := provider.DownTo(ctx, 870); err != nil {+ t.Fatal(err)+ }+ insertUnifiedDocumentIdentityFixture(t, ctx, db)+ pool, err := pgxpool.New(ctx, databaseURL)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(pool.Close)+ if _, err := pool.Exec(ctx, `+ INSERT INTO documents(id,tenant_id,title,format,owner_actor_id,owner_actor_kind,creator_actor_id,creator_actor_kind,status)+ SELECT id,'tenant_document_a',id,'markdown','actor_human_a','human','actor_human_a','human','active'+ FROM (VALUES('ocr_scan'),('ocr_photo'),('ocr_icon'),('ocr_notes')) document(id);+ INSERT INTO document_versions(id,tenant_id,document_id,version_number,filename,representation_format,media_type,+ size_bytes,sha256,content_object_id,source,created_by_actor_id)+ SELECT 'version_' || id,'tenant_document_a',id,1,filename,format,media,1,repeat('a',64),'object_' || id,+ 'ordinary_upload','actor_human_a'+ FROM (VALUES('ocr_scan','scan.pdf','pdf','application/pdf'),('ocr_photo','photo.png','png','image/png'),+ ('ocr_icon','icon.svg','svg','image/svg+xml'),('ocr_notes','notes.txt','plain_text','text/plain'))+ document(id,filename,format,media);+ UPDATE documents SET current_version_id='version_' || id WHERE id LIKE 'ocr\_%';+ INSERT INTO document_texts(document_id,tenant_id,source_kind,source_id,status,markdown,markdown_sha256,search_text,scanned)+ SELECT id,'tenant_document_a','file_version','version_' || id,'ready',body,repeat('b',64),body,scanned+ FROM (VALUES('ocr_scan','Recognized receipt',true),('ocr_photo','Recognized screenshot',false),+ ('ocr_icon','# icon.svg',false),('ocr_notes','Plain notes',false)) document(id,body,scanned)+ ON CONFLICT (document_id) DO UPDATE SET status=EXCLUDED.status,markdown=EXCLUDED.markdown,+ markdown_sha256=EXCLUDED.markdown_sha256,search_text=EXCLUDED.search_text,scanned=EXCLUDED.scanned;+ INSERT INTO personal_wikis(id,tenant_id,owner_actor_id)+ VALUES('wiki_ocr','tenant_document_a','actor_human_a');+ INSERT INTO document_context_bindings(id,tenant_id,document_id,binding_kind,wiki_id,status)+ SELECT 'binding_' || id,'tenant_document_a',id,'wiki_source','wiki_ocr','active'+ FROM (VALUES('ocr_scan'),('ocr_notes')) document(id);+ `); err != nil {+ t.Fatal(err)+ }+ if _, err := provider.Up(ctx); err != nil {+ t.Fatal(err)+ }++ assertMemorySourceRows(t, pool, `+ SELECT document_id,status,markdown FROM document_texts WHERE document_id LIKE 'ocr\_%' ORDER BY document_id`,+ [][]any{+ {"ocr_icon", "ready", "# icon.svg"},+ {"ocr_notes", "ready", "Plain notes"},+ {"ocr_photo", "unsupported", ""},+ {"ocr_scan", "no_text", ""},+ })+ assertMemorySourceRows(t, pool, `+ SELECT document_id,coalesce(reason,'') FROM wiki_document_verdicts WHERE document_id LIKE 'ocr\_%' ORDER BY document_id`,+ [][]any{{"ocr_notes", ""}, {"ocr_scan", "scanned"}})+}diff --git a/apps/teamhub/tests/integration/memory_source_views_test.go b/apps/teamhub/tests/integration/memory_source_views_test.goindex 80c4994f..413c7f99 100644--- a/apps/teamhub/tests/integration/memory_source_views_test.go+++ b/apps/teamhub/tests/integration/memory_source_views_test.go@@ -143,30 +143,30 @@ func TestMemorySourceViewsCarryMemoryAuthorization(t *testing.T) {assertMemorySourceRows(t, pool, `SELECT memory_source.human_can_read_document('actor_me_a','tenant_document_a','document_memory_page')`,[][]any{{false}})- // Files the Wiki cannot record stay out of Raw too: a spreadsheet with a- // ready text and a scanned PDF without one are not listed.+ // Files the Wiki cannot record stay out of Raw too, though their texts are+ // ready: a spreadsheet and a PDF with a line over the Wiki's budget.if _, err = pool.Exec(ctx, `INSERT INTO documents(id,tenant_id,title,format,owner_actor_id,owner_actor_kind,creator_actor_id,creator_actor_kind,status) VALUES('document_memory_sheet','tenant_document_a','Sheet','markdown','actor_human_a','human','actor_human_a','human','active'),- ('document_memory_scan','tenant_document_a','Scan','markdown','actor_human_a','human','actor_human_a','human','active');+ ('document_memory_wide','tenant_document_a','Wide','markdown','actor_human_a','human','actor_human_a','human','active');INSERT INTO document_versions(id,tenant_id,document_id,version_number,filename,representation_format,media_type,size_bytes,sha256,content_object_id,source,created_by_actor_id) VALUES('version_document_memory_sheet','tenant_document_a','document_memory_sheet',1,'sheet.csv','csv','text/csv',1,repeat('e',64),'object_document_memory_sheet','ordinary_upload','actor_human_a'),- ('version_document_memory_scan','tenant_document_a','document_memory_scan',1,'scan.pdf','pdf','application/pdf',- 1,repeat('f',64),'object_document_memory_scan','ordinary_upload','actor_human_a');+ ('version_document_memory_wide','tenant_document_a','document_memory_wide',1,'wide.pdf','pdf','application/pdf',+ 1,repeat('f',64),'object_document_memory_wide','ordinary_upload','actor_human_a');UPDATE documents SET current_version_id='version_' || id- WHERE id IN ('document_memory_sheet','document_memory_scan');- INSERT INTO document_texts(document_id,tenant_id,source_kind,source_id,status,markdown,markdown_sha256,search_text)- VALUES('document_memory_sheet','tenant_document_a','file_version','version_document_memory_sheet','ready','| a |',repeat('e',64),'a'),- ('document_memory_scan','tenant_document_a','file_version','version_document_memory_scan','no_text','',NULL,'');+ WHERE id IN ('document_memory_sheet','document_memory_wide');+ INSERT INTO document_texts(document_id,tenant_id,source_kind,source_id,status,markdown,markdown_sha256,search_text,longest_line_bytes)+ VALUES('document_memory_sheet','tenant_document_a','file_version','version_document_memory_sheet','ready','| a |',repeat('e',64),'a',5),+ ('document_memory_wide','tenant_document_a','file_version','version_document_memory_wide','ready',repeat('x',150000),repeat('f',64),'x',150000);INSERT INTO document_placements(id,tenant_id,scope_kind,owner_human_actor_id,parent_id,node_kind,name,document_id,sort_key) VALUES('placement_memory_sheet','tenant_document_a','personal','actor_human_a','placement_memory_folder','document',NULL,'document_memory_sheet','d'),- ('placement_memory_scan','tenant_document_a','personal','actor_human_a','placement_memory_folder','document',NULL,'document_memory_scan','e');+ ('placement_memory_wide','tenant_document_a','personal','actor_human_a','placement_memory_folder','document',NULL,'document_memory_wide','e');`); err != nil {t.Fatal(err)}