diff --git a/.agents/notes.md b/.agents/notes.md index e4c7f8e..f4114ce 100644 --- a/.agents/notes.md +++ b/.agents/notes.md @@ -43,3 +43,10 @@ [0] `pnpm run dev -- web` launches the CLI web stack (API + built static PWA) and does not provide Vite HMR. For frontend hot reload, run Vite (`pnpm run dev:web`) with API separately (now `pnpm run dev:stack` does both). [0] Current web UI architecture is intentionally mobile-first single-column across all viewport sizes; desktop split-pane branches were removed from `app-shell`, `inbox-filters`, and `inbox-list`. [0] In Fastify/Ajv query validation, `oneOf` with numeric query params can produce false validation failures (e.g. `querystring/limit must match exactly one schema in oneOf`) due to coercion behavior; use a single string schema pattern for query params and parse downstream. +[1] Drizzle SQLite table-rebuild migrations can generate invalid copy SQL when adding new columns (`INSERT ... SELECT` referencing columns that do not exist on the old table). After `drizzle-kit generate`, always verify the data-copy statement and map new columns to constants/nulls for backward-compatible migration. +[0] In TypeScript tests, shell script snippets inside template literals must escape `${...}` as `\${...}`; otherwise the TS parser treats them as JS interpolation and breaks compilation. +[0] With `exactOptionalPropertyTypes: true`, do not pass explicit `undefined` for optional object fields; build payload objects with conditional spreads so omitted fields stay omitted. +[0] Homebrew Python can enforce PEP 668 (`externally-managed-environment`) and block global `pip install`; document and prefer a small project-local virtualenv flow for optional Python helpers like auto-tags. +[0] In SQLite table-rebuild migrations (`__new_*` + rename), `CHECK` constraints must reference unqualified column names; qualifiers like `__new_table.column` can break after rename. +[0] Drizzle SQLite migrator runs migrations in a transaction; `PRAGMA foreign_keys=OFF` inside migration SQL may not disable FK checks. Table-copy migrations should filter/clean orphan rows explicitly (e.g., `INNER JOIN` parents) instead of relying on that pragma. +[0] CI `validate` workflow currently runs `format:check`, `lint`, `test`, and `apps/web` build. Before pushing, run all four locally to avoid fast-follow CI fix commits. diff --git a/.env.example b/.env.example index 9eaa528..50e0bf4 100644 --- a/.env.example +++ b/.env.example @@ -4,3 +4,10 @@ STASH_DB_PATH=~/.stash/stash.db # STASH_WEB_HOST=127.0.0.1 # STASH_API_PORT=4173 # STASH_PWA_PORT=5173 +# STASH_AUTO_TAGS_ENABLED=true +# STASH_AUTO_TAGS_MAX=3 +# STASH_AUTO_TAGS_MIN_SCORE=0.4 +# STASH_AUTO_TAGS_MODEL=sentence-transformers/all-MiniLM-L6-v2 +# STASH_AUTO_TAGS_BACKEND=python +# STASH_AUTO_TAGS_PYTHON=python3 +# STASH_AUTO_TAGS_HELPER=./scripts/auto-tags-embed.py diff --git a/AGENTS.md b/AGENTS.md index 1120852..6c4ae52 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,6 +19,9 @@ Current implementation status: - Implemented: thumbnail extraction (metadata-first with content-image fallback) persisted on `items.thumbnail_url`. - Implemented: automatic X/Twitter `status/` extraction via Playwright Chromium rendered DOM (public-only, single-status only, no generic fallback for X URLs). - Implemented: `extract` command to extract or re-extract content for existing items. +- Implemented: optional local auto-tagging on `save`/`extract` (`--auto-tags`) with deterministic rules + Python sentence-transformers backend fallback behavior. +- Implemented: auto-tag provenance tracking in `item_tags` (`is_manual`, `is_auto`, `auto_score`, `auto_source`, `auto_model`, `auto_updated_at`). +- Implemented: `stash tags doctor` diagnostics for local auto-tags runtime checks. - Not implemented yet: `archive`, `delete`, `open`, search command. ## Stack @@ -33,6 +36,7 @@ Current implementation status: - Package manager: `pnpm` - Content extraction: Mozilla Readability + linkedom - X/Twitter extraction: Playwright Chromium (headless browser) for public `status/` URLs +- Auto-tags embeddings backend: Python `sentence-transformers` helper (`scripts/auto-tags-embed.py`) - TTS provider (default): Coqui TTS (Python 3.11 + espeak-ng) - Default Coqui voice: `tts_models/en/vctk/vits|p241` - CLI discovery standardized across providers: PATH first, optional env overrides (`STASH_GTTS_CLI`, `STASH_COQUI_TTS_CLI`, `STASH_FFMPEG_CLI`, `STASH_SAY_CLI`, `STASH_AFCONVERT_CLI`, `STASH_ESPEAK_CLI`) @@ -156,6 +160,7 @@ stash save https://example.com --no-extract Save URL: ```bash stash save https://example.com --title "Example" --tag ai --tag typescript --json +stash save https://example.com --auto-tags --json ``` Save without content extraction: @@ -204,6 +209,8 @@ Extract or re-extract content: ```bash stash extract 1 --json stash extract 1 --force --json +stash extract 1 --auto-tags --json +stash tags doctor --json ``` ## UI/UX Workflow for Agents @@ -269,7 +276,8 @@ Typical error shape: - `tags` - Unique tag names. - `item_tags` - - Many-to-many link between items and tags. + - Many-to-many link between items and tags with provenance metadata: + - `is_manual`, `is_auto`, `auto_score`, `auto_source`, `auto_model`, `auto_updated_at`. - `notes` - Optional per-item note content. - `item_audio` @@ -321,6 +329,9 @@ Updates should include: - `.db/` is git-ignored local runtime data for repository-local development. - Local npm scripts load `.env` using `dotenv` via `scripts/with-env.mjs`. - CLI DB path precedence remains: `--db-path` > `STASH_DB_PATH` > `~/.stash/stash.db`. +- Auto-tags env controls: + - `STASH_AUTO_TAGS_ENABLED`, `STASH_AUTO_TAGS_MAX`, `STASH_AUTO_TAGS_MIN_SCORE` + - `STASH_AUTO_TAGS_MODEL`, `STASH_AUTO_TAGS_BACKEND`, `STASH_AUTO_TAGS_PYTHON`, `STASH_AUTO_TAGS_HELPER` - `stash web` now accepts `--host`, `--api-port`, `--pwa-port` (`--port` removed). - `stash web` runs split listeners (API + PWA) and fails fast on port conflicts or identical API/PWA ports. - Web dev (`apps/web` Vite) reads the same root `.env` port variables and uses strict port binding. @@ -335,6 +346,8 @@ Updates should include: - `has_extracted_content: boolean` - `tts_audio: null | { file_name, format, provider, voice, bytes, generated_at }` - `POST /api/items/:id/tts` is enqueue-first and returns job metadata (`job`, `poll_url`, `poll_interval_ms`). +- `POST /api/items` and `POST /api/items/:id/extract` accept optional `autoTags: boolean`. +- Web save UX requests auto-tags when the tags field is left empty. - `GET /api/tts-jobs/:id` and `GET /api/items/:id/tts-jobs` expose job status/history for polling/recovery. - `tts` auto-generated filenames use friendly slugs + timestamp + short random suffix and collision fallback (`_2`, `_3`, ...). - Vitest sets `STASH_TTS_MOCK_BASE64` in `test/vitest.setup.ts` for deterministic TTS tests; default `pnpm test` does not require local Coqui/espeak binaries. diff --git a/README.md b/README.md index 7c9872b..d3741d1 100644 --- a/README.md +++ b/README.md @@ -189,6 +189,7 @@ stash db doctor --json - Public X/Twitter `status/` extraction via Playwright Chromium (headless, public-only) - Extract or re-extract content for existing items - Organize with tags +- Optional local auto-tagging (`--auto-tags`) with provenance tracking - Mark items as read/unread - Generate TTS audio from extracted article content - Play previously generated TTS audio in the web UI @@ -200,15 +201,18 @@ stash db doctor --json ```bash stash save https://example.com --tag typescript --tag cli stash save https://example.com --no-extract # skip content extraction +stash save https://example.com --auto-tags --json stash list --status unread --tag typescript --tag-mode all stash list --json stash tags list --json +stash tags doctor --json stash tag add 1 productivity stash tag rm 1 productivity stash mark read 1 stash mark unread 1 stash extract 1 # extract content + thumbnail metadata for an existing item stash extract 1 --force # re-extract even if content exists +stash extract 1 --auto-tags --json stash tts 1 --json stash tts 1 --wait --json stash tts status 12 --json @@ -216,6 +220,21 @@ stash tts doctor --json stash jobs worker --once --json ``` +## Auto Tags + +- Auto-tags are opt-in by default: + - `stash save --auto-tags` + - `stash extract --auto-tags` +- Disable explicitly with `--no-auto-tags`. +- Existing URLs are supported: `stash save --auto-tags` re-runs auto-tagging and refreshes auto-only tags. +- Provenance is tracked in `item_tags` (`is_manual`, `is_auto`, score/source/model metadata). +- Manual tags are never removed by auto-tag refresh. +- Web save form behavior: when tag input is left empty, web save requests auto-tagging automatically. +- Runtime health check: + - `stash tags doctor --json` +- Python setup instructions: + - `docs/AUTO_TAGS_SETUP.md` + ## X / Twitter Extraction (Headless Browser) - `stash` automatically uses a Playwright Chromium-based extractor for public X/Twitter status URLs (`x.com/.../status/` and `twitter.com/.../status/`). diff --git a/apps/api/src/app/create-api-app.ts b/apps/api/src/app/create-api-app.ts index c0feff3..4e6aa88 100644 --- a/apps/api/src/app/create-api-app.ts +++ b/apps/api/src/app/create-api-app.ts @@ -1,9 +1,8 @@ import Fastify, { type FastifyInstance } from "fastify" - -import type { ApiRouteOptions } from "../features/options.js" import { extractRoutes } from "../features/extract/routes.js" import { inboxRoutes } from "../features/inbox/routes.js" import { itemRoutes } from "../features/item/routes.js" +import type { ApiRouteOptions } from "../features/options.js" import { saveRoutes } from "../features/save/routes.js" import { statusRoutes } from "../features/status/routes.js" import { tagsRoutes } from "../features/tags/routes.js" @@ -17,6 +16,20 @@ export function createApiApp(options: CreateApiAppOptions): FastifyInstance { logger: false, }) + // Fastify's default JSON parser rejects empty bodies (e.g. DELETE with Content-Type: application/json). + // Override it to treat empty bodies as undefined instead of an error. + server.addContentTypeParser("application/json", { parseAs: "string" }, (_req, body, done) => { + if (body === "") { + done(null, undefined) + return + } + try { + done(null, JSON.parse(body as string)) + } catch (err) { + done(err as Error, undefined) + } + }) + registerApiErrorHandlers(server) server.register( diff --git a/apps/api/src/features/extract/dto.ts b/apps/api/src/features/extract/dto.ts index 9497045..e49e33c 100644 --- a/apps/api/src/features/extract/dto.ts +++ b/apps/api/src/features/extract/dto.ts @@ -12,3 +12,12 @@ export function parseForce(body: unknown): boolean { const raw = body as Record return Boolean(raw.force) } + +export function parseAutoTags(body: unknown): boolean | undefined { + if (!body || typeof body !== "object") { + return undefined + } + + const raw = body as Record + return typeof raw.autoTags === "boolean" ? raw.autoTags : undefined +} diff --git a/apps/api/src/features/extract/routes.ts b/apps/api/src/features/extract/routes.ts index 960f1e6..9f5cfab 100644 --- a/apps/api/src/features/extract/routes.ts +++ b/apps/api/src/features/extract/routes.ts @@ -2,7 +2,7 @@ import type { FastifyPluginAsync } from "fastify" import { extractItem } from "../../../../../packages/core/src/features/extract/service.js" import type { ApiRouteOptions } from "../options.js" -import { parseForce, parseItemId } from "./dto.js" +import { parseAutoTags, parseForce, parseItemId } from "./dto.js" const extractParamsSchema = { type: "object", @@ -12,7 +12,13 @@ const extractParamsSchema = { required: ["id"], } as const -const extractBodySchema = {} as const +const extractBodySchema = { + type: "object", + properties: { + force: { type: "boolean" }, + autoTags: { type: "boolean" }, + }, +} as const export const extractRoutes: FastifyPluginAsync = async (fastify, options) => { fastify.post( @@ -24,13 +30,17 @@ export const extractRoutes: FastifyPluginAsync = async (fastify }, }, async (request) => { + const autoTags = parseAutoTags(request.body) const result = await extractItem( { dbPath: options.dbPath, migrationsDir: options.migrationsDir, }, parseItemId(request.params as Record), - parseForce(request.body), + { + force: parseForce(request.body), + ...(autoTags !== undefined ? { autoTags } : {}), + }, ) return { diff --git a/apps/api/src/features/save/dto.ts b/apps/api/src/features/save/dto.ts index 43a2a77..4bd7a0e 100644 --- a/apps/api/src/features/save/dto.ts +++ b/apps/api/src/features/save/dto.ts @@ -17,6 +17,7 @@ export function parseSaveBody(body: unknown): SaveItemInput { ? raw.tags.filter((value): value is string => typeof value === "string") : undefined const extract = typeof raw.extract === "boolean" ? raw.extract : undefined + const autoTags = typeof raw.autoTags === "boolean" ? raw.autoTags : undefined const input: SaveItemInput = { url } if (title !== undefined) { @@ -28,5 +29,8 @@ export function parseSaveBody(body: unknown): SaveItemInput { if (extract !== undefined) { input.extract = extract } + if (autoTags !== undefined) { + input.autoTags = autoTags + } return input } diff --git a/apps/api/src/features/save/routes.ts b/apps/api/src/features/save/routes.ts index 6fe608f..e98e11e 100644 --- a/apps/api/src/features/save/routes.ts +++ b/apps/api/src/features/save/routes.ts @@ -14,6 +14,7 @@ const saveBodySchema = { items: { type: "string" }, }, extract: { type: "boolean" }, + autoTags: { type: "boolean" }, }, required: ["url"], } as const diff --git a/apps/cli/src/cli.ts b/apps/cli/src/cli.ts index fba82f6..25440f8 100644 --- a/apps/cli/src/cli.ts +++ b/apps/cli/src/cli.ts @@ -10,6 +10,10 @@ import { openDb, type StashDb } from "../../../packages/core/src/db/client.js" import { getMigrationStatus, runMigrations } from "../../../packages/core/src/db/migrate.js" import * as schema from "../../../packages/core/src/db/schema.js" import { StashError } from "../../../packages/core/src/errors.js" +import { inspectAutoTagsHealth } from "../../../packages/core/src/features/auto-tags/doctor.js" +import { extractItem } from "../../../packages/core/src/features/extract/service.js" +import { saveItem } from "../../../packages/core/src/features/items/service.js" +import { addTag, listTags, removeTag } from "../../../packages/core/src/features/tags/service.js" import { inspectCoquiTtsHealth } from "../../../packages/core/src/features/tts/doctor.js" import { enqueueTtsJob, @@ -18,8 +22,6 @@ import { startTtsWorker, waitForTtsJob, } from "../../../packages/core/src/features/tts/jobs.js" -import { extractContent } from "../../../packages/core/src/lib/extract.js" -import { isContentExtractionError } from "../../../packages/core/src/lib/extract-x-browser.js" import { DEFAULT_AUDIO_DIR, DEFAULT_DB_PATH, @@ -49,7 +51,6 @@ type TagMode = "any" | "all" type ItemRow = typeof schema.items.$inferSelect & { status: ItemStatus } type Db = StashDb -type DbExecutor = Pick type StashItem = { id: number @@ -169,14 +170,6 @@ function parsePort(value: string): number { return port } -function parseUrl(value: string): URL { - try { - return new URL(value) - } catch { - throw new CliError(`Invalid URL: ${value}`, "VALIDATION_ERROR", 2) - } -} - function serializeItem(row: ItemRow, tags: string[]): StashItem { return { id: row.id, @@ -247,16 +240,6 @@ function withDb(dbPath: string, action: (db: Db) => T): T { } } -async function withDbAsync(dbPath: string, action: (db: Db) => Promise): Promise { - ensureDbDirectory(dbPath) - const { db, sqlite } = openDb(dbPath) - try { - return await action(db) - } finally { - sqlite.close() - } -} - function resolveMigrationsDir(value?: string): string { if (!value || value.trim().length === 0) { return DEFAULT_MIGRATIONS_DIR @@ -286,26 +269,6 @@ function withReadyDb(dbPath: string, action: (db: Db) => T): T { return withDb(dbPath, action) } -async function withReadyDbAsync(dbPath: string, action: (db: Db) => Promise): Promise { - ensureDbReady(dbPath) - return withDbAsync(dbPath, action) -} - -function getItemRowById(db: Db, id: number): ItemRow | undefined { - return db.select().from(schema.items).where(eq(schema.items.id, id)).get() as ItemRow | undefined -} - -function getItemTags(db: Db, itemId: number): string[] { - const rows = db - .select({ name: schema.tags.name }) - .from(schema.itemTags) - .innerJoin(schema.tags, eq(schema.tags.id, schema.itemTags.tagId)) - .where(eq(schema.itemTags.itemId, itemId)) - .orderBy(asc(schema.tags.name)) - .all() - return rows.map((row) => row.name) -} - function getTagsMap(db: Db, itemIds: number[]): Map { const map = new Map() if (itemIds.length === 0) { @@ -332,37 +295,6 @@ function getTagsMap(db: Db, itemIds: number[]): Map { return map } -function ensureTagId(db: DbExecutor, tag: string, createdAt: Date): number { - db.insert(schema.tags) - .values({ - name: tag, - createdAt, - }) - .onConflictDoNothing({ target: schema.tags.name }) - .run() - - const row = db - .select({ id: schema.tags.id }) - .from(schema.tags) - .where(eq(schema.tags.name, tag)) - .get() - if (!row) { - throw new CliError(`Could not resolve tag '${tag}'.`, "INTERNAL_ERROR", 1) - } - return row.id -} - -function ensureItemExists(db: Db, itemId: number): void { - const row = db - .select({ id: schema.items.id }) - .from(schema.items) - .where(eq(schema.items.id, itemId)) - .get() - if (!row) { - throw new CliError(`Item ${itemId} not found.`, "NOT_FOUND", 3) - } -} - function runDbAction(jsonMode: boolean, action: () => T | Promise): T | Promise { try { const result = action() @@ -391,16 +323,17 @@ program.addHelpText( "afterAll", ` Quick Reference: - stash save [--title ] [--tag ...] [--json] + stash save [--title ] [--tag ...] [--auto-tags|--no-auto-tags] [--json] stash list [--status unread|read|archived] [--tag ...] [--tag-mode any|all] [--limit ] [--offset ] [--json] stash tags list [--limit ] [--offset ] [--json] + stash tags doctor [--json] stash tag add [--json] stash tag rm [--json] stash mark read [--json] stash mark unread [--json] stash read [--json] stash unread [--json] - stash extract [--force] [--json] + stash extract [--force] [--auto-tags|--no-auto-tags] [--json] stash tts [--voice ] [--format mp3|wav] [--wait] [--json] stash tts status [--json] stash tts doctor [--json] @@ -516,145 +449,54 @@ program .option("--title ", "Optional title") .option("--tag ", "Tag to attach (repeatable)", collectValues, []) .option("--no-extract", "Skip content extraction") + .option("--auto-tags", "Apply auto-generated tags") + .option("--no-auto-tags", "Disable auto-generated tags") .option("--json", "Print machine-readable JSON output") .action( async ( url: string, - options: { title?: string; tag: string[]; extract?: boolean; json?: boolean }, + options: { + title?: string + tag: string[] + extract?: boolean + autoTags?: boolean + json?: boolean + }, ) => { const jsonMode = Boolean(options.json) + const context = { + dbPath: resolveDbPath(program.opts().dbPath as string), + migrationsDir: resolveMigrationsDir(), + } - return runDbAction(jsonMode, async () => - withReadyDbAsync(resolveDbPath(program.opts().dbPath as string), async (db) => { - const parsedUrl = parseUrl(url) - const normalizedTags = normalizeTags(options.tag ?? []) - const existing = db - .select() - .from(schema.items) - .where(eq(schema.items.url, parsedUrl.toString())) - .get() as ItemRow | undefined - const timestamp = new Date(nowMs()) - let created = false - let itemId: number | undefined - - db.transaction((tx) => { - if (existing) { - itemId = existing.id - if (!existing.title && options.title) { - tx.update(schema.items) - .set({ - title: options.title.trim(), - updatedAt: timestamp, - }) - .where(eq(schema.items.id, existing.id)) - .run() - } - } else { - const result = tx - .insert(schema.items) - .values({ - url: parsedUrl.toString(), - title: options.title?.trim() || null, - domain: parsedUrl.hostname, - status: "unread", - isStarred: false, - createdAt: timestamp, - updatedAt: timestamp, - readAt: null, - archivedAt: null, - }) - .run() - itemId = Number(result.lastInsertRowid) - created = true - } - - if (itemId === undefined) { - throw new CliError("Saved item id could not be determined.", "INTERNAL_ERROR", 1) - } + return runDbAction(jsonMode, async () => { + const saveInput = { + url, + tags: options.tag ?? [], + ...(options.title !== undefined ? { title: options.title } : {}), + ...(options.extract !== undefined ? { extract: options.extract } : {}), + ...(options.autoTags !== undefined ? { autoTags: options.autoTags } : {}), + } + const result = await saveItem(context, saveInput) - for (const tag of normalizedTags) { - const tagId = ensureTagId(tx, tag, timestamp) - tx.insert(schema.itemTags) - .values({ - itemId, - tagId, - createdAt: timestamp, - }) - .onConflictDoNothing() - .run() - } + if (jsonMode) { + printJson({ + ok: true, + ...result, }) + return + } - if (itemId === undefined) { - throw new CliError("Saved item id could not be determined.", "INTERNAL_ERROR", 1) - } - - const row = getItemRowById(db, itemId) - if (!row) { - throw new CliError("Saved item could not be reloaded.", "INTERNAL_ERROR", 1) - } - - // Extract content if not disabled - if (options.extract !== false && created) { - try { - const extracted = await extractContent(parsedUrl.toString()) - if (extracted?.textContent) { - // Save to notes table - db.insert(schema.notes) - .values({ - itemId, - content: extracted.textContent, - updatedAt: timestamp, - }) - .onConflictDoUpdate({ - target: schema.notes.itemId, - set: { - content: extracted.textContent, - updatedAt: timestamp, - }, - }) - .run() - - // Update title if we got a better one - if (extracted.title && !options.title) { - db.update(schema.items) - .set({ - title: extracted.title, - thumbnailUrl: extracted.thumbnailUrl ?? null, - updatedAt: timestamp, - }) - .where(eq(schema.items.id, itemId)) - .run() - } else { - db.update(schema.items) - .set({ - thumbnailUrl: extracted.thumbnailUrl ?? null, - updatedAt: timestamp, - }) - .where(eq(schema.items.id, itemId)) - .run() - } - } - } catch (error) { - console.error("Failed to extract content:", error) - // Continue without extraction on error - } - } - - const item = serializeItem(row, getItemTags(db, row.id)) - - if (jsonMode) { - printJson({ - ok: true, - created, - item, - }) - return - } - - process.stdout.write(`${created ? "saved" : "exists"} #${item.id} ${item.url}\n`) - }), - ) + process.stdout.write( + `${result.created ? "saved" : "exists"} #${result.item.id} ${result.item.url}\n`, + ) + if (result.auto_tags && result.auto_tags.length > 0) { + process.stdout.write(`auto-tags: ${result.auto_tags.join(", ")}\n`) + } + if (result.auto_tag_warning) { + process.stdout.write(`auto-tags warning: ${result.auto_tag_warning}\n`) + } + }) }, ) @@ -836,130 +678,40 @@ program .command("extract ") .description("Extract or re-extract content for an item") .option("--force", "Re-extract even if content already exists") + .option("--auto-tags", "Apply auto-generated tags") + .option("--no-auto-tags", "Disable auto-generated tags") .option("--json", "Print machine-readable JSON output") - .action(async (id: string, options: { force?: boolean; json?: boolean }) => { + .action(async (id: string, options: { force?: boolean; autoTags?: boolean; json?: boolean }) => { const jsonMode = Boolean(options.json) + const context = { + dbPath: resolveDbPath(program.opts().dbPath as string), + migrationsDir: resolveMigrationsDir(), + } + const itemId = parseItemId(id) - return runDbAction(jsonMode, async () => - withReadyDbAsync(resolveDbPath(program.opts().dbPath as string), async (db) => { - const itemId = parseItemId(id) - - // Get the item - const item = getItemRowById(db, itemId) - if (!item) { - throw new CliError(`Item ${itemId} not found.`, "NOT_FOUND", 3) - } - - // Check if content already exists - const existing = db.select().from(schema.notes).where(eq(schema.notes.itemId, itemId)).get() - - if (existing && !options.force) { - if (jsonMode) { - printJson({ - ok: false, - error: { - code: "CONTENT_EXISTS", - message: `Item ${itemId} already has extracted content. Use --force to re-extract.`, - }, - }) - return - } - throw new CliError( - `Item ${itemId} already has extracted content. Use --force to re-extract.`, - "CONTENT_EXISTS", - 4, - ) - } - - // Extract content - let extracted = null - let extractionError = null - try { - extracted = await extractContent(item.url) - } catch (error) { - if (isContentExtractionError(error)) { - const message = error.message - if (jsonMode) { - process.stderr.write(`${message}\n`) - } - extractionError = message - } else { - extractionError = error instanceof Error ? error.message : String(error) - } - } - - if (!extracted || !extracted.textContent) { - if (jsonMode) { - printJson({ - ok: false, - error: { - code: "EXTRACTION_FAILED", - message: extractionError || "Failed to extract content", - }, - }) - return - } - throw new CliError( - `Failed to extract content: ${extractionError || "No readable content found"}`, - "EXTRACTION_FAILED", - 1, - ) - } - - // Save to notes table - const timestamp = new Date() - db.insert(schema.notes) - .values({ - itemId, - content: extracted.textContent, - updatedAt: timestamp, - }) - .onConflictDoUpdate({ - target: schema.notes.itemId, - set: { - content: extracted.textContent, - updatedAt: timestamp, - }, - }) - .run() - - // Update title if we got a better one and item doesn't have one - if (extracted.title && !item.title) { - db.update(schema.items) - .set({ - title: extracted.title, - thumbnailUrl: extracted.thumbnailUrl ?? null, - updatedAt: timestamp, - }) - .where(eq(schema.items.id, itemId)) - .run() - } else { - db.update(schema.items) - .set({ - thumbnailUrl: extracted.thumbnailUrl ?? null, - updatedAt: timestamp, - }) - .where(eq(schema.items.id, itemId)) - .run() - } + return runDbAction(jsonMode, async () => { + const extractOptions = { + ...(options.force !== undefined ? { force: options.force } : {}), + ...(options.autoTags !== undefined ? { autoTags: options.autoTags } : {}), + } + const result = await extractItem(context, itemId, extractOptions) - if (jsonMode) { - printJson({ - ok: true, - item_id: itemId, - title_extracted: extracted.title || null, - title_updated: Boolean(extracted.title && !item.title), - content_length: extracted.textContent.length, - updated_at: timestamp.toISOString(), - }) - return - } + if (jsonMode) { + printJson({ + ok: true, + ...result, + }) + return + } - process.stdout.write( - `extracted #${itemId} ${item.url} (${extracted.textContent.length} chars)\n`, - ) - }), - ) + process.stdout.write(`extracted #${itemId} (${result.content_length} chars)\n`) + if (result.auto_tags && result.auto_tags.length > 0) { + process.stdout.write(`auto-tags: ${result.auto_tags.join(", ")}\n`) + } + if (result.auto_tag_warning) { + process.stdout.write(`auto-tags warning: ${result.auto_tag_warning}\n`) + } + }) }) program @@ -1081,6 +833,7 @@ tagsCommand.addHelpText( Examples: stash tags list stash tags list --limit 100 --offset 0 --json + stash tags doctor --json `, ) @@ -1092,47 +845,71 @@ tagsCommand .option("--json", "Print machine-readable JSON output") .action((options: { limit: number; offset: number; json?: boolean }) => { const jsonMode = Boolean(options.json) + const context = { + dbPath: resolveDbPath(program.opts().dbPath as string), + migrationsDir: resolveMigrationsDir(), + } - runDbAction(jsonMode, () => - withReadyDb(resolveDbPath(program.opts().dbPath as string), (db) => { - const rows = db - .select({ - name: schema.tags.name, - itemCount: sql`count(${schema.itemTags.itemId})`, - }) - .from(schema.tags) - .leftJoin(schema.itemTags, eq(schema.itemTags.tagId, schema.tags.id)) - .groupBy(schema.tags.id) - .orderBy(asc(schema.tags.name)) - .limit(options.limit) - .offset(options.offset) - .all() + runDbAction(jsonMode, () => { + const result = listTags(context, { + limit: options.limit, + offset: options.offset, + }) - const tags = rows.map((row) => ({ name: row.name, item_count: Number(row.itemCount) })) + if (jsonMode) { + printJson({ + ok: true, + ...result, + }) + return + } - if (jsonMode) { - printJson({ - ok: true, - tags, - paging: { - limit: options.limit, - offset: options.offset, - returned: tags.length, - }, - }) - return - } + if (result.tags.length === 0) { + process.stdout.write("No tags found.\n") + return + } - if (tags.length === 0) { - process.stdout.write("No tags found.\n") - return - } + for (const tag of result.tags) { + process.stdout.write(`${tag.name}\t${tag.item_count}\n`) + } + }) + }) + +tagsCommand + .command("doctor") + .description("Inspect auto-tags dependency health") + .option("--json", "Print machine-readable JSON output") + .action((options: { json?: boolean }) => { + const jsonMode = Boolean(options.json) - for (const tag of tags) { - process.stdout.write(`${tag.name}\t${tag.item_count}\n`) + runDbAction(jsonMode, () => { + const report = inspectAutoTagsHealth() + + if (jsonMode) { + printJson({ + ok: true, + ...report, + }) + } else { + process.stdout.write(`tags doctor: ${report.healthy ? "healthy" : "unhealthy"}\n`) + process.stdout.write(`backend: ${report.backend}\n`) + process.stdout.write(`model: ${report.model}\n`) + process.stdout.write(`helper: ${report.helper_path}\n`) + process.stdout.write(`python: ${report.python_path ?? "-"}\n`) + for (const check of report.checks) { + const requirement = check.required ? "required" : "optional" + const status = check.ok ? "ok" : "failed" + process.stdout.write(`${check.id} (${requirement}): ${status} [${check.path ?? "-"}]\n`) + if (check.message) { + process.stdout.write(` ${check.message}\n`) + } } - }), - ) + } + + if (!report.healthy) { + process.exitCode = 2 + } + }) }) const tagCommand = program.command("tag").description("Manage item tags") @@ -1152,40 +929,25 @@ tagCommand .option("--json", "Print machine-readable JSON output") .action((id: string, tag: string, options: { json?: boolean }) => { const jsonMode = Boolean(options.json) + const context = { + dbPath: resolveDbPath(program.opts().dbPath as string), + migrationsDir: resolveMigrationsDir(), + } - runDbAction(jsonMode, () => - withReadyDb(resolveDbPath(program.opts().dbPath as string), (db) => { - const itemId = parseItemId(id) - const normalizedTag = normalizeTag(tag) - ensureItemExists(db, itemId) - const timestamp = new Date(nowMs()) - const result = db.transaction((tx) => { - const tagId = ensureTagId(tx, normalizedTag, timestamp) - return tx - .insert(schema.itemTags) - .values({ - itemId, - tagId, - createdAt: timestamp, - }) - .onConflictDoNothing() - .run() + runDbAction(jsonMode, () => { + const result = addTag(context, parseItemId(id), tag) + if (jsonMode) { + printJson({ + ok: true, + ...result, }) - const added = Number(result.changes) > 0 - - if (jsonMode) { - printJson({ - ok: true, - item_id: itemId, - tag: normalizedTag, - added, - }) - return - } + return + } - process.stdout.write(`${added ? "added" : "exists"} tag '${normalizedTag}' on #${itemId}\n`) - }), - ) + process.stdout.write( + `${result.added ? "added" : "exists"} tag '${result.tag}' on #${result.item_id}\n`, + ) + }) }) tagCommand @@ -1194,42 +956,25 @@ tagCommand .option("--json", "Print machine-readable JSON output") .action((id: string, tag: string, options: { json?: boolean }) => { const jsonMode = Boolean(options.json) + const context = { + dbPath: resolveDbPath(program.opts().dbPath as string), + migrationsDir: resolveMigrationsDir(), + } - runDbAction(jsonMode, () => - withReadyDb(resolveDbPath(program.opts().dbPath as string), (db) => { - const itemId = parseItemId(id) - const normalizedTag = normalizeTag(tag) - ensureItemExists(db, itemId) - const row = db - .select({ id: schema.tags.id }) - .from(schema.tags) - .where(eq(schema.tags.name, normalizedTag)) - .get() - let removed = false - - if (row) { - const result = db - .delete(schema.itemTags) - .where(and(eq(schema.itemTags.itemId, itemId), eq(schema.itemTags.tagId, row.id))) - .run() - removed = Number(result.changes) > 0 - } - - if (jsonMode) { - printJson({ - ok: true, - item_id: itemId, - tag: normalizedTag, - removed, - }) - return - } + runDbAction(jsonMode, () => { + const result = removeTag(context, parseItemId(id), tag) + if (jsonMode) { + printJson({ + ok: true, + ...result, + }) + return + } - process.stdout.write( - `${removed ? "removed" : "missing"} tag '${normalizedTag}' on #${itemId}\n`, - ) - }), - ) + process.stdout.write( + `${result.removed ? "removed" : "missing"} tag '${result.tag}' on #${result.item_id}\n`, + ) + }) }) function markItemStatus( diff --git a/apps/cli/test/integration.test.ts b/apps/cli/test/integration.test.ts index 79dbcc8..a3614b0 100644 --- a/apps/cli/test/integration.test.ts +++ b/apps/cli/test/integration.test.ts @@ -45,6 +45,18 @@ type SaveResponse = { ok: boolean created: boolean item: StashItem + auto_tags?: string[] + auto_tag_scores?: Array<{ tag: string; score: number; source: "embedding" | "rule" }> + auto_tag_warning?: string +} + +type ExtractResponse = { + ok: boolean + item_id: number + content_length: number + auto_tags?: string[] + auto_tag_scores?: Array<{ tag: string; score: number; source: "embedding" | "rule" }> + auto_tag_warning?: string } type TagsListResponse = { @@ -125,6 +137,22 @@ type TtsDoctorResponse = { invocation_strategy: "text_file_then_fallback_text" } +type AutoTagsDoctorResponse = { + ok: boolean + backend: "python" | "rule" + healthy: boolean + model: string + helper_path: string + python_path: string | null + checks: Array<{ + id: "python" | "helper_script" | "sentence_transformers" | "helper_runtime" + required: boolean + ok: boolean + path: string | null + message: string | null + }> +} + type ErrorResponse = { ok: false error: { @@ -296,6 +324,49 @@ function getItemThumbnailUrl(dbPath: string, itemId: number): string | null { return JSON.parse(result.stdout.trim()) as string | null } +function getItemTagProvenance( + dbPath: string, + itemId: number, +): Array<{ tag: string; is_manual: number; is_auto: number }> { + const result = spawnSync( + process.execPath, + [ + "-e", + `import("better-sqlite3").then((mod) => { + const Database = mod.default + const db = new Database(process.env.DB_PATH) + const rows = db + .prepare("select t.name as tag, it.is_manual, it.is_auto from item_tags it inner join tags t on t.id = it.tag_id where it.item_id = ? order by t.name asc") + .all(Number(process.env.ITEM_ID)) + db.close() + process.stdout.write(JSON.stringify(rows)) +}).catch((error) => { + console.error(error?.message ?? String(error)) + process.exit(1) +})`, + ], + { + cwd: repoRoot, + encoding: "utf8", + env: { + ...process.env, + DB_PATH: dbPath, + ITEM_ID: String(itemId), + }, + }, + ) + + if (result.status !== 0) { + throw new Error(`Failed to read item tag provenance:\n${result.stdout}\n${result.stderr}`) + } + + return JSON.parse(result.stdout.trim()) as Array<{ + tag: string + is_manual: number + is_auto: number + }> +} + const sqliteProbe = probeSqliteBinding() const sqliteProbeOutput = `${sqliteProbe.stdout}\n${sqliteProbe.stderr}` const sqliteBindingsMissing = @@ -330,7 +401,7 @@ integrationSuite(integrationTitle, () => { const migrationStatus = runJson(["db", "doctor"], { dbPath }) expect(migrationStatus.ok).toBe(true) - expect(migrationStatus.applied_count).toBe(4) + expect(migrationStatus.applied_count).toBe(5) expect(migrationStatus.pending_count).toBe(0) } finally { cleanup() @@ -389,6 +460,111 @@ integrationSuite(integrationTitle, () => { }) }) + describe("auto-tags", () => { + const autoTagsEnv: NodeJS.ProcessEnv = { + STASH_AUTO_TAGS_BACKEND: "rule", + STASH_AUTO_TAGS_MIN_SCORE: "0.62", + STASH_AUTO_TAGS_MAX: "3", + } + + it("returns auto-tag fields from save --auto-tags and stores auto provenance", () => { + const { dbPath, cleanup } = createTempDb() + try { + const html = `

TypeScript backend API guide

${"TypeScript backend API architecture. ".repeat(10)}

` + const url = buildDataHtmlUrl(html) + + const saved = runJson(["save", url, "--auto-tags"], { + dbPath, + env: autoTagsEnv, + }) + + expect(saved.ok).toBe(true) + expect((saved.auto_tags ?? []).length).toBeGreaterThan(0) + expect((saved.auto_tag_scores ?? []).length).toBeGreaterThan(0) + + const rows = getItemTagProvenance(dbPath, saved.item.id) + const autoRows = rows.filter((row) => row.is_auto === 1) + expect(autoRows.length).toBeGreaterThan(0) + } finally { + cleanup() + } + }) + + it("re-runs auto-tags on existing URLs and replaces stale auto-only tags", () => { + const { dbPath, cleanup } = createTempDb() + try { + const url = "https://example.com/auto-tags-refresh" + const first = runJson( + ["save", url, "--title", "Refresh Item", "--no-extract"], + { + dbPath, + }, + ) + expect(first.created).toBe(true) + + upsertNoteContent( + dbPath, + first.item.id, + "TypeScript backend API architecture and implementation details.", + ) + runJson(["save", url, "--auto-tags", "--no-extract"], { + dbPath, + env: autoTagsEnv, + }) + + upsertNoteContent( + dbPath, + first.item.id, + "Security hardening and performance profiling in production systems.", + ) + + const second = runJson(["save", url, "--auto-tags", "--no-extract"], { + dbPath, + env: autoTagsEnv, + }) + expect(second.created).toBe(false) + expect(second.auto_tags ?? []).not.toContain("typescript") + expect( + (second.auto_tags ?? []).some((tag) => ["security", "performance"].includes(tag)), + ).toBe(true) + + const rows = getItemTagProvenance(dbPath, first.item.id) + const tags = rows.map((row) => row.tag) + expect(tags).toContain("security") + expect(tags).not.toContain("typescript") + } finally { + cleanup() + } + }) + + it("supports extract --auto-tags", () => { + const { dbPath, cleanup } = createTempDb() + try { + const html = `

Python security reference

${"Python security and backend API reference. ".repeat(10)}

` + const url = buildDataHtmlUrl(html) + const saved = runJson( + ["save", url, "--title", "No extract", "--no-extract"], + { + dbPath, + }, + ) + + const extracted = runJson( + ["extract", String(saved.item.id), "--auto-tags"], + { + dbPath, + env: autoTagsEnv, + }, + ) + + expect(extracted.ok).toBe(true) + expect((extracted.auto_tags ?? []).length).toBeGreaterThan(0) + } finally { + cleanup() + } + }) + }) + describe("save/list/tag lifecycle", () => { it("creates unread items with normalized tags", () => { const { dbPath, cleanup } = createTempDb() @@ -696,6 +872,89 @@ exit 0 }) }) + describe("tags doctor", () => { + it("returns auto-tags health details in JSON", () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "stash-auto-tags-doctor-cli-")) + const dbPath = path.join(tempDir, "stash.db") + try { + const helperPath = path.join(tempDir, "auto-tags-helper.py") + fs.writeFileSync(helperPath, "print('helper')\n", "utf8") + const pythonPath = path.join(tempDir, "fake-python.sh") + writeExecutable( + pythonPath, + `#!/bin/sh +if [ "$1" = "--version" ]; then + echo "Python 3.11.0" + exit 0 +fi +if [ "$1" = "-c" ]; then + exit 0 +fi +echo '{"ok":true,"scores":[{"tag":"health","score":0.9}]}' +exit 0 +`, + ) + + const report = runJson(["tags", "doctor"], { + dbPath, + env: { + STASH_AUTO_TAGS_BACKEND: "python", + STASH_AUTO_TAGS_PYTHON: pythonPath, + STASH_AUTO_TAGS_HELPER: helperPath, + }, + }) + + expect(report.ok).toBe(true) + expect(report.backend).toBe("python") + expect(report.healthy).toBe(true) + expect(report.checks.find((check) => check.id === "python")?.ok).toBe(true) + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }) + } + }) + + it("exits with code 2 when auto-tags dependencies are unhealthy", () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "stash-auto-tags-doctor-cli-")) + const dbPath = path.join(tempDir, "stash.db") + try { + const helperPath = path.join(tempDir, "auto-tags-helper.py") + fs.writeFileSync(helperPath, "print('helper')\n", "utf8") + const pythonPath = path.join(tempDir, "fake-python.sh") + writeExecutable( + pythonPath, + `#!/bin/sh +if [ "$1" = "--version" ]; then + echo "Python 3.11.0" + exit 0 +fi +if [ "$1" = "-c" ]; then + echo "ImportError: sentence_transformers missing" >&2 + exit 1 +fi +echo '{"ok":true,"scores":[{"tag":"health","score":0.9}]}' +exit 0 +`, + ) + + const report = runJson(["tags", "doctor"], { + dbPath, + expectedCode: 2, + env: { + STASH_AUTO_TAGS_BACKEND: "python", + STASH_AUTO_TAGS_PYTHON: pythonPath, + STASH_AUTO_TAGS_HELPER: helperPath, + }, + }) + + expect(report.ok).toBe(true) + expect(report.healthy).toBe(false) + expect(report.checks.find((check) => check.id === "sentence_transformers")?.ok).toBe(false) + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }) + } + }) + }) + describe("error contracts", () => { it("returns NOT_FOUND with exit code 3 for missing items", () => { const { dbPath, cleanup } = createTempDb() diff --git a/apps/web/src/features/save/api/save-item.ts b/apps/web/src/features/save/api/save-item.ts index 642d613..fc8f1d2 100644 --- a/apps/web/src/features/save/api/save-item.ts +++ b/apps/web/src/features/save/api/save-item.ts @@ -6,6 +6,7 @@ export type SavePayload = { title?: string tags?: string[] extract?: boolean + autoTags?: boolean } export type SaveResponse = { diff --git a/apps/web/src/features/save/ui/save-form.tsx b/apps/web/src/features/save/ui/save-form.tsx index 33cbe9f..40b9062 100644 --- a/apps/web/src/features/save/ui/save-form.tsx +++ b/apps/web/src/features/save/ui/save-form.tsx @@ -19,6 +19,7 @@ type SaveFormProps = { title?: string tags?: string[] extract?: boolean + autoTags?: boolean }) => Promise saving: boolean } @@ -45,6 +46,7 @@ export function SaveForm({ onSave, saving }: SaveFormProps): JSX.Element { title: title || undefined, tags: normalizedTags, extract, + autoTags: normalizedTags.length === 0, }).then(() => { setUrl("") setTitle("") @@ -98,8 +100,8 @@ export function SaveForm({ onSave, saving }: SaveFormProps): JSX.Element { label="Tags (comma separated)" value={tags} onChange={(event) => setTags(event.target.value)} - placeholder="ai, typescript, read-later" - helperText="Tags are normalized to lowercase." + placeholder="Optional manual tags (auto-tagging runs when empty)" + helperText="Tags are normalized to lowercase. Leave empty to auto-tag." slotProps={{ htmlInput: { name: "tags", diff --git a/config/seed-tags.json b/config/seed-tags.json new file mode 100644 index 0000000..a4a47e0 --- /dev/null +++ b/config/seed-tags.json @@ -0,0 +1,80 @@ +{ + "version": 1, + "description": "Seed tags for local auto-tag ranking (embeddings + rules)", + "tags": [ + { "tag": "ai", "descriptor": "artificial intelligence, machine learning, llm, neural networks" }, + { "tag": "ml", "descriptor": "machine learning, model training, inference, evaluation" }, + { "tag": "llm", "descriptor": "large language models, prompt engineering, agents, context windows" }, + { "tag": "typescript", "descriptor": "TypeScript, ts, typed JavaScript, type safety" }, + { "tag": "javascript", "descriptor": "JavaScript, js, web scripting, frontend runtime" }, + { "tag": "python", "descriptor": "Python programming, scripts, data tooling, backend" }, + { "tag": "rust", "descriptor": "Rust programming language, cargo, ownership, systems" }, + { "tag": "go", "descriptor": "Go programming language, golang, services, concurrency" }, + { "tag": "java", "descriptor": "Java language, JVM, enterprise backend" }, + { "tag": "kotlin", "descriptor": "Kotlin language, JVM, Android" }, + { "tag": "swift", "descriptor": "Swift language, iOS development, Apple platforms" }, + { "tag": "frontend", "descriptor": "frontend development, UI, browser apps" }, + { "tag": "backend", "descriptor": "backend services, APIs, server architecture" }, + { "tag": "fullstack", "descriptor": "full stack development, frontend and backend" }, + { "tag": "react", "descriptor": "React, hooks, components, SPA" }, + { "tag": "vue", "descriptor": "Vue framework, components, frontend" }, + { "tag": "svelte", "descriptor": "Svelte framework, frontend components" }, + { "tag": "node", "descriptor": "Node.js runtime, npm, server-side JavaScript" }, + { "tag": "api", "descriptor": "API design, endpoints, REST, integration" }, + { "tag": "graphql", "descriptor": "GraphQL schemas, resolvers, queries" }, + { "tag": "database", "descriptor": "database systems, SQL, data modeling" }, + { "tag": "postgres", "descriptor": "PostgreSQL, postgres, relational database" }, + { "tag": "sqlite", "descriptor": "SQLite embedded database" }, + { "tag": "redis", "descriptor": "Redis cache, key value store, queues" }, + { "tag": "testing", "descriptor": "software testing, unit tests, integration tests" }, + { "tag": "security", "descriptor": "security, vulnerabilities, authentication, authorization" }, + { "tag": "performance", "descriptor": "performance optimization, profiling, latency" }, + { "tag": "devops", "descriptor": "devops practices, deployment, automation" }, + { "tag": "docker", "descriptor": "Docker containers, images, containerization" }, + { "tag": "kubernetes", "descriptor": "Kubernetes, k8s, orchestration, clusters" }, + { "tag": "cloud", "descriptor": "cloud infrastructure, aws, gcp, azure" }, + { "tag": "ci-cd", "descriptor": "continuous integration, continuous delivery, pipelines" }, + { "tag": "mobile", "descriptor": "mobile apps, iOS, Android" }, + { "tag": "pwa", "descriptor": "progressive web app, offline web, service worker" }, + { "tag": "productivity", "descriptor": "personal productivity, workflows, tools" }, + { "tag": "career", "descriptor": "career growth, interviews, hiring" }, + { "tag": "leadership", "descriptor": "engineering leadership, management, team building" }, + { "tag": "design", "descriptor": "product design, UX, UI" }, + { "tag": "finance", "descriptor": "personal finance, investing, budgeting" }, + { "tag": "startup", "descriptor": "startups, entrepreneurship, product strategy" }, + { "tag": "open-source", "descriptor": "open source software, maintainers, community" }, + { "tag": "tutorial", "descriptor": "how-to tutorial, step by step guide" }, + { "tag": "reference", "descriptor": "reference documentation, cheatsheet, API docs" }, + { "tag": "opinion", "descriptor": "opinion, editorial, personal perspective" }, + { "tag": "news", "descriptor": "industry news, announcements, updates" }, + { "tag": "science", "descriptor": "scientific research, studies, scientific discovery, laboratories" }, + { "tag": "health", "descriptor": "health, wellness, public health, disease prevention" }, + { "tag": "medicine", "descriptor": "medicine, clinical care, doctors, treatment, medical research" }, + { "tag": "biology", "descriptor": "biology, life sciences, cells, organisms, ecosystems" }, + { "tag": "biotech", "descriptor": "biotechnology, bioengineering, synthetic biology, CRISPR, gene editing" }, + { "tag": "genetics", "descriptor": "genetics, DNA, genomics, heredity, sequencing" }, + { "tag": "neuroscience", "descriptor": "neuroscience, brain science, cognition, neural activity" }, + { "tag": "psychology", "descriptor": "psychology, behavior, cognition, mental health, therapy" }, + { "tag": "climate", "descriptor": "climate change, global warming, emissions, climate policy" }, + { "tag": "environment", "descriptor": "environment, conservation, biodiversity, ecosystems, pollution" }, + { "tag": "sustainability", "descriptor": "sustainability, sustainable development, circular economy, green technology" }, + { "tag": "energy", "descriptor": "energy systems, electricity, renewables, grid, power generation" }, + { "tag": "physics", "descriptor": "physics, theoretical physics, experiments, matter, forces" }, + { "tag": "chemistry", "descriptor": "chemistry, molecules, chemical reactions, materials science" }, + { "tag": "space", "descriptor": "space exploration, satellites, rockets, NASA, missions" }, + { "tag": "astronomy", "descriptor": "astronomy, planets, stars, galaxies, telescopes" }, + { "tag": "math", "descriptor": "mathematics, statistics, probability, equations, proofs" }, + { "tag": "economics", "descriptor": "economics, macroeconomics, microeconomics, markets, inflation" }, + { "tag": "business", "descriptor": "business strategy, companies, operations, management, industry" }, + { "tag": "policy", "descriptor": "public policy, regulation, legislation, governance" }, + { "tag": "politics", "descriptor": "politics, elections, political systems, government debates" }, + { "tag": "geopolitics", "descriptor": "geopolitics, international relations, diplomacy, global power dynamics" }, + { "tag": "education", "descriptor": "education, learning, schools, universities, teaching methods" }, + { "tag": "history", "descriptor": "history, historical analysis, past events, historical figures" }, + { "tag": "philosophy", "descriptor": "philosophy, ethics, epistemology, metaphysics, ideas" }, + { "tag": "culture", "descriptor": "culture, society, cultural trends, social norms" }, + { "tag": "media", "descriptor": "media, journalism, newsrooms, publishing, information ecosystem" }, + { "tag": "books", "descriptor": "books, literature, authors, reading, book reviews" }, + { "tag": "art", "descriptor": "art, visual arts, creative practice, artists, exhibitions" } + ] +} diff --git a/docs/AUTO_TAGS_PROPOSAL.md b/docs/AUTO_TAGS_PROPOSAL.md new file mode 100644 index 0000000..a5b27ac --- /dev/null +++ b/docs/AUTO_TAGS_PROPOSAL.md @@ -0,0 +1,217 @@ +# Auto Tags Proposal (Seed Tags + all-MiniLM-L6-v2) + +Status: Draft +Owner: Stash +Date: 2026-02-25 + +## Summary + +Add optional auto-tagging during `save` and `extract` using: + +1. A seeded tag catalog (`config/seed-tags.json`) +2. User-existing tags from DB +3. Local embeddings model (`sentence-transformers/all-MiniLM-L6-v2`) for ranking + +This gives smart-but-controlled tags without cloud dependency. + +--- + +## Goals + +- Auto-apply useful tags with high precision +- Avoid tag explosion/noise +- Work fully local-first +- Keep behavior deterministic and transparent + +## Non-goals (v1) + +- Open-ended free-form tag generation +- Cloud LLM dependency +- Full taxonomy management UI + +--- + +## UX / Product Behavior + +### Save / Extract behavior + +- Manual tags remain source of truth and are never removed. +- Auto tags are merged with manual tags and deduplicated. +- Apply at most `N` auto tags (default `3`). +- Only apply tags with score above threshold (default `0.62`). + +### CLI flags + +- `stash save ... --auto-tags` (v1 explicit opt-in) +- `stash extract --auto-tags` +- `--no-auto-tags` (explicit off) + +### JSON output (example) + +```json +{ + "ok": true, + "item": { "id": 123 }, + "auto_tags": ["typescript", "backend"], + "auto_tag_scores": [ + { "tag": "typescript", "score": 0.84, "source": "embedding" }, + { "tag": "backend", "score": 0.71, "source": "embedding" } + ] +} +``` + +--- + +## Architecture + +## 1) Candidate pool + +`candidate_tags = seed_tags + user_existing_tags` + +- Seed tags: from `config/seed-tags.json` +- User tags: distinct tags from DB +- Normalize + dedupe (`lowercase`, trim, hyphen policy) + +## 2) Embedding inputs + +### Article text input + +Use compact context: + +- title +- domain +- first 1500-2000 chars of extracted content (if available) + +Format: + +``` +Title: +Domain: <domain> +Content: <excerpt> +``` + +### Tag embedding input + +Use tag descriptor text (not tag key only). +Example: + +- tag: `typescript` +- descriptor: `TypeScript, ts, typed JavaScript, frontend/backend development` + +## 3) Scoring + +- Embed article text once +- Embed all tag descriptors (cached) +- cosine similarity per candidate +- sort desc, keep top `maxTags` above `minScore` + +## 4) Guardrails + +- stopwords blocklist (`news`, `article`, `general`, etc.) +- min tag length (>= 2) +- dedupe by canonical slug +- optional domain boosts (e.g. `github.com` -> `dev`, `code`) + +--- + +## Config + +Add env/config controls: + +- `STASH_AUTO_TAGS_ENABLED=false` +- `STASH_AUTO_TAGS_MAX=3` +- `STASH_AUTO_TAGS_MIN_SCORE=0.62` +- `STASH_AUTO_TAGS_MODEL=sentence-transformers/all-MiniLM-L6-v2` + +Optional runtime backend selector: + +- `STASH_AUTO_TAGS_BACKEND=python` (default for v1.5) + +--- + +## Model Runtime Options + +### Preferred (v1.5): Python helper + +Use `sentence-transformers` in a small Python helper script: + +- load `sentence-transformers/all-MiniLM-L6-v2` +- accept JSON payload (article + candidates) +- return ranked scores JSON + +Pros: reliable model support, straightforward implementation. + +### Future option: JS/ONNX + +Move to transformers.js/onnxruntime for single-runtime deployment if desired. + +--- + +## Implementation Plan + +### Phase 1 (Deterministic baseline) + +- Add `config/seed-tags.json` +- Add simple keyword/domain heuristic tagger +- Add CLI flags + JSON response fields +- Add tests for merge/dedupe/limits + +### Phase 2 (Embeddings ranking) + +- Add embedding service abstraction (`auto-tags` service) +- Add Python helper runtime + health check +- Rank candidate tags via embeddings +- Keep heuristics as fallback when model unavailable + +### Phase 3 (Polish) + +- Cache tag embeddings on disk +- Add `stash tags doctor` diagnostics +- Add optional score output in non-JSON mode + +--- + +## Data Contracts (suggested) + +### Internal result + +```ts +interface AutoTagResult { + applied: string[]; + candidates: Array<{ tag: string; score: number; source: 'embedding' | 'rule' }>; + skippedReason?: 'disabled' | 'no-content' | 'model-unavailable'; +} +``` + +--- + +## Testing + +- Unit: normalization, scoring threshold, dedupe +- Unit: merge behavior with manual tags +- Unit: deterministic fallback when model unavailable +- Integration: `save --auto-tags` applies expected tags on fixture pages + +--- + +## Rollout Recommendation + +- Start with `--auto-tags` opt-in +- Observe quality for 1-2 weeks +- If precision is good, allow default-on with `--no-auto-tags` override + +--- + +## Risks & Mitigation + +- **Noisy tags** -> strict threshold + max tags + stoplist +- **Model latency** -> short text window + embedding cache +- **Runtime fragility** -> deterministic fallback and clear errors + +--- + +## Success Criteria + +- Median 1-3 useful auto tags per article +- Low incorrect-tag rate (<15% subjective review) +- No regression in `save` latency beyond acceptable threshold diff --git a/docs/AUTO_TAGS_SETUP.md b/docs/AUTO_TAGS_SETUP.md new file mode 100644 index 0000000..1fa6bb1 --- /dev/null +++ b/docs/AUTO_TAGS_SETUP.md @@ -0,0 +1,68 @@ +# Auto Tags Setup (Local Python Backend) + +`stash` auto-tags uses a local Python helper with `sentence-transformers`. + +## 1) Install Python dependencies + +Recommended Python: `3.11+` + +### Recommended (works with Homebrew Python / PEP 668) + +Create a small local virtualenv just for auto-tags: + +```bash +python3 -m venv .venv-auto-tags +source .venv-auto-tags/bin/activate +python -m pip install --upgrade pip +python -m pip install sentence-transformers numpy torch +``` + +If `torch` installation differs for your platform, follow official PyTorch install instructions and then install `sentence-transformers`. + +### Optional (global install) + +If your Python allows global `pip` installs, this also works: + +```bash +python3 -m pip install --upgrade pip +python3 -m pip install sentence-transformers numpy torch +``` + +If you get `error: externally-managed-environment`, use the virtualenv flow above. + +## 2) Optional runtime overrides + +You can set these in `.env`: + +```bash +STASH_AUTO_TAGS_BACKEND=python +STASH_AUTO_TAGS_PYTHON=.venv-auto-tags/bin/python +STASH_AUTO_TAGS_HELPER=./scripts/auto-tags-embed.py +STASH_AUTO_TAGS_MODEL=sentence-transformers/all-MiniLM-L6-v2 +STASH_AUTO_TAGS_ENABLED=false +STASH_AUTO_TAGS_MAX=3 +STASH_AUTO_TAGS_MIN_SCORE=0.62 +``` + +Notes: +- `STASH_AUTO_TAGS_PYTHON` is optional, but recommended when using a venv. +- Use an absolute path if you run `stash` from different working directories. + +## 3) Verify setup + +```bash +stash tags doctor --json +``` + +Expected: +- `healthy: true` +- checks for `python`, `helper_script`, `sentence_transformers`, and `helper_runtime` are `ok: true` + +## 4) Usage + +```bash +stash save https://example.com --auto-tags --json +stash extract 1 --auto-tags --json +``` + +Auto-tagging remains opt-in by default unless you set `STASH_AUTO_TAGS_ENABLED=true`. diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index 65608a4..b149a4d 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -218,7 +218,7 @@ Web API item payloads (`GET /api/items`, `GET /api/items/:id`, `POST /api/items` Save a URL: ```bash -stash save <url> [--title <text>] [--tag <name> ...] [--no-extract] [--json] +stash save <url> [--title <text>] [--tag <name> ...] [--no-extract] [--auto-tags|--no-auto-tags] [--json] ``` Behavior: @@ -233,6 +233,8 @@ Behavior: - Thumbnail metadata is extracted and persisted to `items.thumbnail_url` (`og:image`/`twitter:image` first, article-image fallback) - Extracted title updates the item if no `--title` provided - Extracted text is stored in the `notes` table for future search/TTS features +- `--auto-tags` runs local auto-tagging and returns `auto_tags` / `auto_tag_scores` in JSON output +- `save --auto-tags` also runs for existing URLs and refreshes auto-only tags using current note content ## List @@ -256,6 +258,12 @@ List all tags: stash tags list [--limit <n>] [--offset <n>] [--json] ``` +Auto-tags runtime diagnostics: + +```bash +stash tags doctor [--json] +``` + Attach tag to item: ```bash @@ -298,7 +306,7 @@ stash unread <id> [--json] Extract or re-extract content for an item: ```bash -stash extract <id> [--force] [--json] +stash extract <id> [--force] [--auto-tags|--no-auto-tags] [--json] ``` Behavior: @@ -308,6 +316,7 @@ Behavior: - Persists extracted thumbnail metadata to `items.thumbnail_url` - Updates item title if extraction finds one and item has no title - Use `--force` to re-extract even if content already exists +- `--auto-tags` runs local auto-tagging after extraction and returns `auto_tags` / `auto_tag_scores` in JSON output - X extraction remains public-only and single-status only (no thread/conversation expansion) - `stash extract` surfaces actionable setup/rendering diagnostics for X browser extraction failures while preserving `EXTRACTION_FAILED` - Useful for: @@ -333,6 +342,33 @@ Linux (if Chromium system dependencies are missing): pnpm exec playwright install-deps chromium ``` +## Auto Tags + +Auto-tags are local-only and opt-in by default. + +Commands: + +```bash +stash save <url> --auto-tags --json +stash extract <id> --auto-tags --json +stash tags doctor --json +``` + +Environment: +- `STASH_AUTO_TAGS_ENABLED=false` +- `STASH_AUTO_TAGS_MAX=3` +- `STASH_AUTO_TAGS_MIN_SCORE=0.62` +- `STASH_AUTO_TAGS_MODEL=sentence-transformers/all-MiniLM-L6-v2` +- `STASH_AUTO_TAGS_BACKEND=python` (`rule` fallback mode is also supported) +- `STASH_AUTO_TAGS_PYTHON=python3` (optional override) +- `STASH_AUTO_TAGS_HELPER=./scripts/auto-tags-embed.py` (optional override) + +Notes: +- Existing URLs are supported (`save --auto-tags` re-runs auto-tagging on existing items). +- Auto-tag refresh replaces stale auto-only tags and preserves manual tags. +- Tag provenance is tracked in `item_tags` (`is_manual`, `is_auto`, plus auto metadata fields). +- Python setup instructions: `docs/AUTO_TAGS_SETUP.md` + ## TTS Export Queue audio generation jobs from extracted content stored in `notes`: @@ -435,6 +471,25 @@ Typical `tts doctor` JSON response: } ``` +Typical `tags doctor` JSON response: + +```json +{ + "ok": true, + "backend": "python", + "healthy": true, + "model": "sentence-transformers/all-MiniLM-L6-v2", + "helper_path": "/path/to/scripts/auto-tags-embed.py", + "python_path": "/usr/bin/python3", + "checks": [ + { "id": "python", "required": true, "ok": true, "path": "/usr/bin/python3", "message": null }, + { "id": "helper_script", "required": true, "ok": true, "path": "/path/to/scripts/auto-tags-embed.py", "message": null }, + { "id": "sentence_transformers", "required": true, "ok": true, "path": "/usr/bin/python3", "message": null }, + { "id": "helper_runtime", "required": true, "ok": true, "path": "/path/to/scripts/auto-tags-embed.py", "message": null } + ] +} +``` + ## JSON Output Contract Most commands support `--json`. @@ -489,6 +544,11 @@ Typical list response: } ``` +When `--auto-tags` is used on `save` or `extract`, successful JSON responses may also include: +- `auto_tags: string[]` +- `auto_tag_scores: Array<{ tag, score, source }>` +- `auto_tag_warning?: string` + ## Exit Codes - `0` success diff --git a/drizzle/0004_pale_mathemanic.sql b/drizzle/0004_pale_mathemanic.sql new file mode 100644 index 0000000..653db1b --- /dev/null +++ b/drizzle/0004_pale_mathemanic.sql @@ -0,0 +1,30 @@ +PRAGMA foreign_keys=OFF;--> statement-breakpoint +DROP TABLE IF EXISTS `__new_item_tags`;--> statement-breakpoint +CREATE TABLE `__new_item_tags` ( + `item_id` integer NOT NULL, + `tag_id` integer NOT NULL, + `created_at` integer NOT NULL, + `is_manual` integer DEFAULT true NOT NULL, + `is_auto` integer DEFAULT false NOT NULL, + `auto_score` real, + `auto_source` text, + `auto_model` text, + `auto_updated_at` integer, + PRIMARY KEY(`item_id`, `tag_id`), + FOREIGN KEY (`item_id`) REFERENCES `items`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON UPDATE no action ON DELETE cascade, + CONSTRAINT "item_tags_source_presence_check" CHECK("is_manual" = 1 OR "is_auto" = 1), + CONSTRAINT "item_tags_auto_source_check" CHECK("auto_source" is null or "auto_source" in ('embedding','rule')) +); +--> statement-breakpoint +INSERT INTO `__new_item_tags`("item_id", "tag_id", "created_at", "is_manual", "is_auto", "auto_score", "auto_source", "auto_model", "auto_updated_at") +SELECT it."item_id", it."tag_id", it."created_at", 1, 0, NULL, NULL, NULL, NULL +FROM `item_tags` it +INNER JOIN `items` i ON i."id" = it."item_id" +INNER JOIN `tags` t ON t."id" = it."tag_id";--> statement-breakpoint +DROP TABLE `item_tags`;--> statement-breakpoint +ALTER TABLE `__new_item_tags` RENAME TO `item_tags`;--> statement-breakpoint +PRAGMA foreign_keys=ON;--> statement-breakpoint +CREATE INDEX `idx_item_tags_tag_item` ON `item_tags` (`tag_id`,`item_id`);--> statement-breakpoint +CREATE INDEX `idx_item_tags_item_auto` ON `item_tags` (`item_id`,`is_auto`,`tag_id`);--> statement-breakpoint +CREATE INDEX `idx_item_tags_tag_manual` ON `item_tags` (`tag_id`,`is_manual`,`item_id`); diff --git a/drizzle/meta/0004_snapshot.json b/drizzle/meta/0004_snapshot.json new file mode 100644 index 0000000..0e08366 --- /dev/null +++ b/drizzle/meta/0004_snapshot.json @@ -0,0 +1,590 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "ea28beab-9dd5-4701-82cb-877ac0590e7e", + "prevId": "5cca971a-9d00-4f5e-9b3d-062eb5cc6009", + "tables": { + "item_audio": { + "name": "item_audio", + "columns": { + "item_id": { + "name": "item_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "voice": { + "name": "voice", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "format": { + "name": "format", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bytes": { + "name": "bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "generated_at": { + "name": "generated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "item_audio_item_id_items_id_fk": { + "name": "item_audio_item_id_items_id_fk", + "tableFrom": "item_audio", + "tableTo": "items", + "columnsFrom": [ + "item_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "item_audio_format_check": { + "name": "item_audio_format_check", + "value": "\"item_audio\".\"format\" in ('mp3','wav')" + } + } + }, + "item_tags": { + "name": "item_tags", + "columns": { + "item_id": { + "name": "item_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tag_id": { + "name": "tag_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "is_manual": { + "name": "is_manual", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "is_auto": { + "name": "is_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "auto_score": { + "name": "auto_score", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "auto_source": { + "name": "auto_source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "auto_model": { + "name": "auto_model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "auto_updated_at": { + "name": "auto_updated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_item_tags_tag_item": { + "name": "idx_item_tags_tag_item", + "columns": [ + "tag_id", + "item_id" + ], + "isUnique": false + }, + "idx_item_tags_item_auto": { + "name": "idx_item_tags_item_auto", + "columns": [ + "item_id", + "is_auto", + "tag_id" + ], + "isUnique": false + }, + "idx_item_tags_tag_manual": { + "name": "idx_item_tags_tag_manual", + "columns": [ + "tag_id", + "is_manual", + "item_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "item_tags_item_id_items_id_fk": { + "name": "item_tags_item_id_items_id_fk", + "tableFrom": "item_tags", + "tableTo": "items", + "columnsFrom": [ + "item_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "item_tags_tag_id_tags_id_fk": { + "name": "item_tags_tag_id_tags_id_fk", + "tableFrom": "item_tags", + "tableTo": "tags", + "columnsFrom": [ + "tag_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "item_tags_item_id_tag_id_pk": { + "columns": [ + "item_id", + "tag_id" + ], + "name": "item_tags_item_id_tag_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": { + "item_tags_source_presence_check": { + "name": "item_tags_source_presence_check", + "value": "\"item_tags\".\"is_manual\" = 1 OR \"item_tags\".\"is_auto\" = 1" + }, + "item_tags_auto_source_check": { + "name": "item_tags_auto_source_check", + "value": "\"item_tags\".\"auto_source\" is null or \"item_tags\".\"auto_source\" in ('embedding','rule')" + } + } + }, + "items": { + "name": "items", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "thumbnail_url": { + "name": "thumbnail_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unread'" + }, + "is_starred": { + "name": "is_starred", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "read_at": { + "name": "read_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "archived_at": { + "name": "archived_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "items_url_unique": { + "name": "items_url_unique", + "columns": [ + "url" + ], + "isUnique": true + }, + "idx_items_status_created": { + "name": "idx_items_status_created", + "columns": [ + "status", + "created_at", + "id" + ], + "isUnique": false + }, + "idx_items_created": { + "name": "idx_items_created", + "columns": [ + "created_at", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "items_status_check": { + "name": "items_status_check", + "value": "\"items\".\"status\" in ('unread','read','archived')" + } + } + }, + "notes": { + "name": "notes", + "columns": { + "item_id": { + "name": "item_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "notes_item_id_items_id_fk": { + "name": "notes_item_id_items_id_fk", + "tableFrom": "notes", + "tableTo": "items", + "columnsFrom": [ + "item_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tags": { + "name": "tags", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "tags_name_unique": { + "name": "tags_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tts_jobs": { + "name": "tts_jobs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "item_id": { + "name": "item_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "voice": { + "name": "voice", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "format": { + "name": "format", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "output_file_name": { + "name": "output_file_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "idx_tts_jobs_status_created": { + "name": "idx_tts_jobs_status_created", + "columns": [ + "status", + "created_at", + "id" + ], + "isUnique": false + }, + "idx_tts_jobs_item_created": { + "name": "idx_tts_jobs_item_created", + "columns": [ + "item_id", + "created_at", + "id" + ], + "isUnique": false + }, + "idx_tts_jobs_item_active": { + "name": "idx_tts_jobs_item_active", + "columns": [ + "item_id" + ], + "isUnique": true, + "where": "\"tts_jobs\".\"status\" in ('queued','running')" + } + }, + "foreignKeys": { + "tts_jobs_item_id_items_id_fk": { + "name": "tts_jobs_item_id_items_id_fk", + "tableFrom": "tts_jobs", + "tableTo": "items", + "columnsFrom": [ + "item_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "tts_jobs_status_check": { + "name": "tts_jobs_status_check", + "value": "\"tts_jobs\".\"status\" in ('queued','running','succeeded','failed')" + }, + "tts_jobs_format_check": { + "name": "tts_jobs_format_check", + "value": "\"tts_jobs\".\"format\" in ('mp3','wav')" + } + } + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index a210dfe..0d4f2e6 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -29,6 +29,13 @@ "when": 1771539382892, "tag": "0003_colossal_robin_chapel", "breakpoints": true + }, + { + "idx": 4, + "version": "6", + "when": 1772444307772, + "tag": "0004_pale_mathemanic", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/core/src/db/schema.ts b/packages/core/src/db/schema.ts index cfaf41c..48a281a 100644 --- a/packages/core/src/db/schema.ts +++ b/packages/core/src/db/schema.ts @@ -4,6 +4,7 @@ import { index, integer, primaryKey, + real, sqliteTable, text, uniqueIndex, @@ -53,10 +54,23 @@ export const itemTags = sqliteTable( .notNull() .references(() => tags.id, { onDelete: "cascade" }), createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull(), + isManual: integer("is_manual", { mode: "boolean" }).notNull().default(true), + isAuto: integer("is_auto", { mode: "boolean" }).notNull().default(false), + autoScore: real("auto_score"), + autoSource: text("auto_source"), + autoModel: text("auto_model"), + autoUpdatedAt: integer("auto_updated_at", { mode: "timestamp_ms" }), }, (table) => [ primaryKey({ columns: [table.itemId, table.tagId] }), index("idx_item_tags_tag_item").on(table.tagId, table.itemId), + index("idx_item_tags_item_auto").on(table.itemId, table.isAuto, table.tagId), + index("idx_item_tags_tag_manual").on(table.tagId, table.isManual, table.itemId), + check("item_tags_source_presence_check", sql`is_manual = 1 OR is_auto = 1`), + check( + "item_tags_auto_source_check", + sql`auto_source is null or auto_source in ('embedding','rule')`, + ), ], ) diff --git a/packages/core/src/features/auto-tags/config.ts b/packages/core/src/features/auto-tags/config.ts new file mode 100644 index 0000000..24b572a --- /dev/null +++ b/packages/core/src/features/auto-tags/config.ts @@ -0,0 +1,118 @@ +import fs from "node:fs" +import path from "node:path" +import { spawnSync } from "node:child_process" +import { fileURLToPath } from "node:url" + +import type { AutoTagBackend, AutoTagConfig } from "./types.js" + +const DEFAULT_MAX_TAGS = 3 +const DEFAULT_MIN_SCORE = 0.62 +const DEFAULT_MODEL = "sentence-transformers/all-MiniLM-L6-v2" + +function parseBooleanEnv(value: string | undefined, fallback: boolean): boolean { + if (value === undefined) { + return fallback + } + const normalized = value.trim().toLowerCase() + if (["1", "true", "yes", "on"].includes(normalized)) { + return true + } + if (["0", "false", "no", "off"].includes(normalized)) { + return false + } + return fallback +} + +function parsePositiveIntEnv(value: string | undefined, fallback: number): number { + if (value === undefined) { + return fallback + } + const parsed = Number.parseInt(value, 10) + return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback +} + +function parseScoreEnv(value: string | undefined, fallback: number): number { + if (value === undefined) { + return fallback + } + const parsed = Number.parseFloat(value) + if (!Number.isFinite(parsed)) { + return fallback + } + if (parsed < 0 || parsed > 1) { + return fallback + } + return parsed +} + +function resolveModuleCandidate(relativePath: string): string { + const moduleDir = path.dirname(fileURLToPath(import.meta.url)) + const srcCandidate = path.resolve(moduleDir, `../../../../../${relativePath}`) + const distCandidate = path.resolve(moduleDir, `../../../../../../${relativePath}`) + return fs.existsSync(srcCandidate) ? srcCandidate : distCandidate +} + +function resolveDefaultSeedTagsPath(): string { + const cwdCandidate = path.resolve(process.cwd(), "config/seed-tags.json") + if (fs.existsSync(cwdCandidate)) { + return cwdCandidate + } + return resolveModuleCandidate("config/seed-tags.json") +} + +function resolveDefaultHelperPath(): string { + const cwdCandidate = path.resolve(process.cwd(), "scripts/auto-tags-embed.py") + if (fs.existsSync(cwdCandidate)) { + return cwdCandidate + } + return resolveModuleCandidate("scripts/auto-tags-embed.py") +} + +function resolveDefaultPythonBin(): string | null { + const fromEnv = process.env.STASH_AUTO_TAGS_PYTHON?.trim() + if (fromEnv) { + return fromEnv + } + + const candidates = ["python3", "python"] + for (const candidate of candidates) { + const lookup = spawnSync("sh", ["-lc", `command -v ${candidate}`], { encoding: "utf-8" }) + const found = lookup.stdout?.trim() + if (found) { + return found + } + } + + return null +} + +function parseBackend(value: string | undefined): AutoTagBackend { + const normalized = value?.trim().toLowerCase() + if (normalized === "rule") { + return "rule" + } + return "python" +} + +export function resolveAutoTagConfig(): AutoTagConfig { + const helperPath = process.env.STASH_AUTO_TAGS_HELPER?.trim() || resolveDefaultHelperPath() + const seedTagsPath = resolveDefaultSeedTagsPath() + + return { + enabled: parseBooleanEnv(process.env.STASH_AUTO_TAGS_ENABLED, false), + maxTags: parsePositiveIntEnv(process.env.STASH_AUTO_TAGS_MAX, DEFAULT_MAX_TAGS), + minScore: parseScoreEnv(process.env.STASH_AUTO_TAGS_MIN_SCORE, DEFAULT_MIN_SCORE), + model: process.env.STASH_AUTO_TAGS_MODEL?.trim() || DEFAULT_MODEL, + backend: parseBackend(process.env.STASH_AUTO_TAGS_BACKEND), + pythonBin: resolveDefaultPythonBin(), + helperPath, + seedTagsPath, + } +} + +export function resolveAutoTagsRequested(explicit: boolean | undefined): boolean { + if (explicit !== undefined) { + return explicit + } + return resolveAutoTagConfig().enabled +} diff --git a/packages/core/src/features/auto-tags/doctor.ts b/packages/core/src/features/auto-tags/doctor.ts new file mode 100644 index 0000000..b700be7 --- /dev/null +++ b/packages/core/src/features/auto-tags/doctor.ts @@ -0,0 +1,205 @@ +import fs from "node:fs" +import { spawnSync } from "node:child_process" + +import { resolveAutoTagConfig } from "./config.js" +import type { AutoTagDependencyCheck, AutoTagsDoctorReport } from "./types.js" + +function truncateMessage(value: string): string { + const normalized = value.trim().replaceAll(/\s+/g, " ") + if (normalized.length <= 300) { + return normalized + } + return `${normalized.slice(0, 300)}...` +} + +function probeBinary( + pathToBinary: string, + args: string[], +): { + ok: boolean + output: string + message: string | null +} { + const result = spawnSync(pathToBinary, args, { encoding: "utf-8" }) + const output = `${result.stdout ?? ""}\n${result.stderr ?? ""}`.trim() + + if (result.error) { + return { + ok: false, + output, + message: truncateMessage(result.error.message), + } + } + + const ok = result.status === 0 + return { + ok, + output, + message: ok ? null : truncateMessage(output || `exit code ${String(result.status)}`), + } +} + +function buildPythonCheck(pathToBinary: string | null, required: boolean): AutoTagDependencyCheck { + if (!pathToBinary) { + return { + id: "python", + required, + ok: false, + path: null, + message: "Python not found in PATH and STASH_AUTO_TAGS_PYTHON is not set.", + } + } + + const probe = probeBinary(pathToBinary, ["--version"]) + return { + id: "python", + required, + ok: probe.ok, + path: pathToBinary, + message: probe.message, + } +} + +function buildHelperCheck(helperPath: string, required: boolean): AutoTagDependencyCheck { + if (!fs.existsSync(helperPath)) { + return { + id: "helper_script", + required, + ok: false, + path: helperPath, + message: "Auto-tags helper script not found.", + } + } + + return { + id: "helper_script", + required, + ok: true, + path: helperPath, + message: null, + } +} + +function buildImportCheck(pythonBin: string | null, required: boolean): AutoTagDependencyCheck { + if (!pythonBin) { + return { + id: "sentence_transformers", + required, + ok: false, + path: null, + message: "Python is unavailable.", + } + } + + const probe = probeBinary(pythonBin, [ + "-c", + "import sentence_transformers; import numpy; import torch; print('ok')", + ]) + + return { + id: "sentence_transformers", + required, + ok: probe.ok, + path: pythonBin, + message: probe.message, + } +} + +function buildHelperRuntimeCheck(options: { + pythonBin: string | null + helperPath: string + model: string + required: boolean +}): AutoTagDependencyCheck { + if (!options.pythonBin) { + return { + id: "helper_runtime", + required: options.required, + ok: false, + path: null, + message: "Python is unavailable.", + } + } + + if (!fs.existsSync(options.helperPath)) { + return { + id: "helper_runtime", + required: options.required, + ok: false, + path: options.helperPath, + message: "Auto-tags helper script not found.", + } + } + + const payload = JSON.stringify({ + model: options.model, + text: "health check", + candidates: [ + { + tag: "health", + descriptor: "health check", + }, + ], + }) + const probe = spawnSync(options.pythonBin, [options.helperPath], { + input: payload, + encoding: "utf-8", + }) + + if (probe.error) { + return { + id: "helper_runtime", + required: options.required, + ok: false, + path: options.helperPath, + message: truncateMessage(probe.error.message), + } + } + + if (probe.status !== 0) { + const output = `${probe.stdout ?? ""}\n${probe.stderr ?? ""}` + return { + id: "helper_runtime", + required: options.required, + ok: false, + path: options.helperPath, + message: truncateMessage(output || `exit code ${String(probe.status)}`), + } + } + + return { + id: "helper_runtime", + required: options.required, + ok: true, + path: options.helperPath, + message: null, + } +} + +export function inspectAutoTagsHealth(): AutoTagsDoctorReport { + const config = resolveAutoTagConfig() + const required = config.backend === "python" + + const checks: AutoTagDependencyCheck[] = [ + buildPythonCheck(config.pythonBin, required), + buildHelperCheck(config.helperPath, required), + buildImportCheck(config.pythonBin, required), + buildHelperRuntimeCheck({ + pythonBin: config.pythonBin, + helperPath: config.helperPath, + model: config.model, + required, + }), + ] + + const healthy = checks.every((check) => !check.required || check.ok) + + return { + backend: config.backend, + healthy, + model: config.model, + helper_path: config.helperPath, + python_path: config.pythonBin, + checks, + } +} diff --git a/packages/core/src/features/auto-tags/index.ts b/packages/core/src/features/auto-tags/index.ts new file mode 100644 index 0000000..4aff1f9 --- /dev/null +++ b/packages/core/src/features/auto-tags/index.ts @@ -0,0 +1,3 @@ +export * from "./config.js" +export * from "./doctor.js" +export * from "./service.js" diff --git a/packages/core/src/features/auto-tags/python.ts b/packages/core/src/features/auto-tags/python.ts new file mode 100644 index 0000000..4d28a55 --- /dev/null +++ b/packages/core/src/features/auto-tags/python.ts @@ -0,0 +1,106 @@ +import { spawn } from "node:child_process" + +import { StashError } from "../../errors.js" +import type { AutoTagCandidate } from "./types.js" + +type PythonScoreResponse = { + ok: true + scores: Array<{ tag: string; score: number }> +} + +type PythonErrorResponse = { + ok: false + error: { + code: string + message: string + } +} + +function parsePythonResponse(raw: string): PythonScoreResponse { + const parsed = JSON.parse(raw) as PythonScoreResponse | PythonErrorResponse + if (!parsed || typeof parsed !== "object") { + throw new Error("Invalid helper response.") + } + + if ("ok" in parsed && parsed.ok === false) { + throw new Error(`${parsed.error.code}: ${parsed.error.message}`) + } + + if (!("ok" in parsed) || parsed.ok !== true || !Array.isArray(parsed.scores)) { + throw new Error("Invalid helper score payload.") + } + + return parsed +} + +export async function scoreTagsWithPython(options: { + pythonBin: string + helperPath: string + model: string + text: string + candidates: AutoTagCandidate[] +}): Promise<Map<string, number>> { + const payload = JSON.stringify({ + model: options.model, + text: options.text, + candidates: options.candidates, + }) + + const result = await new Promise<{ code: number; stdout: string; stderr: string }>( + (resolve, reject) => { + const proc = spawn(options.pythonBin, [options.helperPath], { + stdio: ["pipe", "pipe", "pipe"], + }) + let stdout = "" + let stderr = "" + + proc.stdout.on("data", (chunk: Buffer) => { + stdout += chunk.toString() + }) + + proc.stderr.on("data", (chunk: Buffer) => { + stderr += chunk.toString() + }) + + proc.on("error", (error) => { + reject(error) + }) + + proc.stdin.write(payload) + proc.stdin.end() + + proc.on("close", (code) => { + resolve({ + code: code ?? -1, + stdout, + stderr, + }) + }) + }, + ) + + if (result.code !== 0) { + const message = result.stderr.trim() || `helper exited with ${result.code}` + throw new StashError( + `Auto-tags helper failed: ${message}`, + "AUTO_TAGS_BACKEND_UNAVAILABLE", + 1, + 500, + ) + } + + const parsed = parsePythonResponse(result.stdout.trim()) + const scores = new Map<string, number>() + for (const row of parsed.scores) { + if (typeof row.tag !== "string") { + continue + } + const score = Number(row.score) + if (!Number.isFinite(score)) { + continue + } + scores.set(row.tag, score) + } + + return scores +} diff --git a/packages/core/src/features/auto-tags/rules.ts b/packages/core/src/features/auto-tags/rules.ts new file mode 100644 index 0000000..e68293e --- /dev/null +++ b/packages/core/src/features/auto-tags/rules.ts @@ -0,0 +1,93 @@ +import type { AutoTagCandidate, AutoTagScore } from "./types.js" + +const STOPLIST = new Set(["news", "article", "general"]) +const DOMAIN_BOOSTS: Record<string, string[]> = { + "github.com": [ + "code", + "devops", + "open-source", + "typescript", + "javascript", + "python", + "rust", + "go", + ], + "docs.": ["reference", "api", "tutorial"], +} + +function tokenize(value: string): string[] { + return value + .toLowerCase() + .split(/[^a-z0-9-]+/g) + .map((part) => part.trim()) + .filter((part) => part.length > 0) +} + +function hasBoostForDomain(domain: string | null, tag: string): boolean { + if (!domain) { + return false + } + const normalizedDomain = domain.toLowerCase() + + for (const [domainKey, tags] of Object.entries(DOMAIN_BOOSTS)) { + if (domainKey.endsWith(".")) { + if (!normalizedDomain.startsWith(domainKey)) { + continue + } + } else if (normalizedDomain !== domainKey) { + continue + } + + if (tags.includes(tag)) { + return true + } + } + + return false +} + +export function shouldSkipTag(tag: string): boolean { + return tag.length < 2 || STOPLIST.has(tag) +} + +export function scoreTagsWithRules(options: { + text: string + domain: string | null + candidates: AutoTagCandidate[] +}): AutoTagScore[] { + const haystack = options.text.toLowerCase() + const results: AutoTagScore[] = [] + + for (const candidate of options.candidates) { + if (shouldSkipTag(candidate.tag)) { + continue + } + + let score = 0 + if (haystack.includes(candidate.tag)) { + score += 0.6 + } + + const descriptorTokens = tokenize(candidate.descriptor) + if (descriptorTokens.length > 0) { + const matched = descriptorTokens.filter( + (token) => token.length > 1 && haystack.includes(token), + ) + const ratio = matched.length / descriptorTokens.length + score += Math.min(0.35, ratio * 0.35) + } + + if (hasBoostForDomain(options.domain, candidate.tag)) { + score += 0.15 + } + + score = Math.min(1, score) + results.push({ + tag: candidate.tag, + score, + source: "rule", + }) + } + + return results +} diff --git a/packages/core/src/features/auto-tags/seed.ts b/packages/core/src/features/auto-tags/seed.ts new file mode 100644 index 0000000..49eed3c --- /dev/null +++ b/packages/core/src/features/auto-tags/seed.ts @@ -0,0 +1,28 @@ +import fs from "node:fs" + +import type { SeedTag, SeedTagsConfig } from "./types.js" + +export function loadSeedTags(seedTagsPath: string): SeedTag[] { + try { + const raw = fs.readFileSync(seedTagsPath, "utf-8") + const parsed = JSON.parse(raw) as SeedTagsConfig + if (!Array.isArray(parsed.tags)) { + return [] + } + + return parsed.tags + .filter( + (value): value is SeedTag => + value !== null && + typeof value === "object" && + typeof value.tag === "string" && + typeof value.descriptor === "string", + ) + .map((value) => ({ + tag: value.tag, + descriptor: value.descriptor, + })) + } catch { + return [] + } +} diff --git a/packages/core/src/features/auto-tags/service.ts b/packages/core/src/features/auto-tags/service.ts new file mode 100644 index 0000000..4696da0 --- /dev/null +++ b/packages/core/src/features/auto-tags/service.ts @@ -0,0 +1,308 @@ +import { and, eq } from "drizzle-orm" + +import * as schema from "../../db/schema.js" +import type { Db } from "../common/db.js" +import { ensureTagId, normalizeTag } from "../common/db.js" +import { resolveAutoTagConfig } from "./config.js" +import { scoreTagsWithPython } from "./python.js" +import { scoreTagsWithRules, shouldSkipTag } from "./rules.js" +import { loadSeedTags } from "./seed.js" +import type { + AutoTagApplyResult, + AutoTagCandidate, + AutoTagInput, + AutoTagScore, + AutoTagSource, +} from "./types.js" + +type AutoTagWriteDb = Pick<Db, "insert" | "update" | "delete" | "select"> + +function buildContentExcerpt(content: string | null): string { + const normalized = (content ?? "").replaceAll(/\s+/g, " ").trim() + if (normalized.length <= 2000) { + return normalized + } + return normalized.slice(0, 2000) +} + +function buildUrlTokens(url: string): string { + try { + const parsed = new URL(url) + const tokens = `${parsed.hostname} ${parsed.pathname}` + .toLowerCase() + .split(/[^a-z0-9-]+/g) + .filter((value) => value.length > 1) + return tokens.join(" ") + } catch { + return url + } +} + +function buildTextInput(input: AutoTagInput): string { + const excerpt = buildContentExcerpt(input.content) + const urlTokens = buildUrlTokens(input.url) + + return [ + `Title: ${input.title ?? ""}`, + `Domain: ${input.domain ?? ""}`, + `URL: ${urlTokens}`, + `Content: ${excerpt}`, + ].join("\n") +} + +function normalizeCandidateTag(value: string): string | null { + try { + const normalized = normalizeTag(value) + if (shouldSkipTag(normalized)) { + return null + } + return normalized + } catch { + return null + } +} + +function buildCandidates(db: Db, seedTagsPath: string): AutoTagCandidate[] { + const byTag = new Map<string, AutoTagCandidate>() + const seed = loadSeedTags(seedTagsPath) + + for (const row of seed) { + const tag = normalizeCandidateTag(row.tag) + if (!tag) { + continue + } + byTag.set(tag, { + tag, + descriptor: row.descriptor, + }) + } + + const userRows = db + .selectDistinct({ + name: schema.tags.name, + }) + .from(schema.itemTags) + .innerJoin(schema.tags, eq(schema.tags.id, schema.itemTags.tagId)) + .where(eq(schema.itemTags.isManual, true)) + .all() + + for (const row of userRows) { + const tag = normalizeCandidateTag(row.name) + if (!tag) { + continue + } + if (byTag.has(tag)) { + continue + } + byTag.set(tag, { + tag, + descriptor: tag, + }) + } + + return [...byTag.values()].sort((a, b) => a.tag.localeCompare(b.tag)) +} + +function pickTopScores(scores: AutoTagScore[], minScore: number, maxTags: number): AutoTagScore[] { + return scores + .filter((score) => score.score >= minScore) + .sort((a, b) => b.score - a.score || a.tag.localeCompare(b.tag)) + .slice(0, maxTags) +} + +function sanitizeScore(score: number): number { + if (!Number.isFinite(score)) { + return 0 + } + if (score <= 0) { + return 0 + } + if (score >= 1) { + return 1 + } + return score +} + +async function scoreCandidates( + input: AutoTagInput, + candidates: AutoTagCandidate[], +): Promise<{ + backend: "python" | "rule" + warning?: string + scores: AutoTagScore[] +}> { + const config = resolveAutoTagConfig() + const text = buildTextInput(input) + const ruleScores = scoreTagsWithRules({ + text, + domain: input.domain, + candidates, + }) + const ruleMap = new Map<string, number>(ruleScores.map((row) => [row.tag, row.score])) + + if (config.backend !== "python") { + return { + backend: "rule", + scores: ruleScores, + } + } + + if (!config.pythonBin) { + return { + backend: "rule", + warning: "Auto-tags python backend is unavailable; fell back to rule scoring.", + scores: ruleScores, + } + } + + try { + const embeddingMap = await scoreTagsWithPython({ + pythonBin: config.pythonBin, + helperPath: config.helperPath, + model: config.model, + text, + candidates, + }) + + const merged: AutoTagScore[] = [] + for (const candidate of candidates) { + const embedding = embeddingMap.get(candidate.tag) + const rule = ruleMap.get(candidate.tag) ?? 0 + if (embedding === undefined) { + merged.push({ + tag: candidate.tag, + score: sanitizeScore(rule), + source: "rule", + }) + continue + } + + merged.push({ + tag: candidate.tag, + score: sanitizeScore(embedding + rule * 0.15), + source: "embedding", + }) + } + + return { + backend: "python", + scores: merged, + } + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + return { + backend: "rule", + warning: `Auto-tags python backend failed; fell back to rule scoring (${message}).`, + scores: ruleScores, + } + } +} + +function upsertAutoTag( + db: AutoTagWriteDb, + itemId: number, + tag: string, + score: number, + source: AutoTagSource, + timestamp: Date, + model: string, +): void { + const tagId = ensureTagId(db, tag, timestamp) + db.insert(schema.itemTags) + .values({ + itemId, + tagId, + createdAt: timestamp, + isManual: false, + isAuto: true, + autoScore: score, + autoSource: source, + autoModel: model, + autoUpdatedAt: timestamp, + }) + .onConflictDoUpdate({ + target: [schema.itemTags.itemId, schema.itemTags.tagId], + set: { + isAuto: true, + autoScore: score, + autoSource: source, + autoModel: model, + autoUpdatedAt: timestamp, + }, + }) + .run() +} + +function pruneStaleAutoTags(db: AutoTagWriteDb, itemId: number, keep: Set<string>): void { + const rows = db + .select({ + tagId: schema.itemTags.tagId, + tag: schema.tags.name, + isManual: schema.itemTags.isManual, + isAuto: schema.itemTags.isAuto, + }) + .from(schema.itemTags) + .innerJoin(schema.tags, eq(schema.tags.id, schema.itemTags.tagId)) + .where(and(eq(schema.itemTags.itemId, itemId), eq(schema.itemTags.isAuto, true))) + .all() + + for (const row of rows) { + if (keep.has(row.tag)) { + continue + } + + if (row.isManual) { + db.update(schema.itemTags) + .set({ + isAuto: false, + autoScore: null, + autoSource: null, + autoModel: null, + autoUpdatedAt: null, + }) + .where(and(eq(schema.itemTags.itemId, itemId), eq(schema.itemTags.tagId, row.tagId))) + .run() + continue + } + + db.delete(schema.itemTags) + .where(and(eq(schema.itemTags.itemId, itemId), eq(schema.itemTags.tagId, row.tagId))) + .run() + } +} + +export async function applyAutoTags(db: Db, input: AutoTagInput): Promise<AutoTagApplyResult> { + const config = resolveAutoTagConfig() + const candidates = buildCandidates(db, config.seedTagsPath) + if (candidates.length === 0) { + return { + applied: [], + scores: [], + backend: "rule", + warning: "No candidate tags available for auto-tagging.", + } + } + + const ranked = await scoreCandidates(input, candidates) + const selected = pickTopScores(ranked.scores, config.minScore, config.maxTags) + const selectedSet = new Set(selected.map((row) => row.tag)) + const timestamp = new Date() + + db.transaction((tx) => { + for (const row of selected) { + upsertAutoTag(tx, input.itemId, row.tag, row.score, row.source, timestamp, config.model) + } + pruneStaleAutoTags(tx, input.itemId, selectedSet) + }) + + const result: AutoTagApplyResult = { + applied: selected.map((row) => row.tag), + scores: selected, + backend: ranked.backend, + } + if (ranked.warning) { + result.warning = ranked.warning + } + + return result +} diff --git a/packages/core/src/features/auto-tags/types.ts b/packages/core/src/features/auto-tags/types.ts new file mode 100644 index 0000000..fdcef55 --- /dev/null +++ b/packages/core/src/features/auto-tags/types.ts @@ -0,0 +1,74 @@ +export type AutoTagSource = "embedding" | "rule" + +export type AutoTagBackend = "python" | "rule" + +export type AutoTagScore = { + tag: string + score: number + source: AutoTagSource +} + +export type AutoTagApplyResult = { + applied: string[] + scores: AutoTagScore[] + backend: AutoTagBackend + warning?: string +} + +export type AutoTagConfig = { + enabled: boolean + maxTags: number + minScore: number + model: string + backend: AutoTagBackend + pythonBin: string | null + helperPath: string + seedTagsPath: string +} + +export type AutoTagDependencyCheckId = + | "python" + | "helper_script" + | "sentence_transformers" + | "helper_runtime" + +export type AutoTagDependencyCheck = { + id: AutoTagDependencyCheckId + required: boolean + ok: boolean + path: string | null + message: string | null +} + +export type AutoTagsDoctorReport = { + backend: AutoTagBackend + healthy: boolean + model: string + helper_path: string + python_path: string | null + checks: AutoTagDependencyCheck[] +} + +export type SeedTag = { + tag: string + descriptor: string +} + +export type SeedTagsConfig = { + version: number + description?: string + tags: SeedTag[] +} + +export type AutoTagCandidate = { + tag: string + descriptor: string +} + +export type AutoTagInput = { + itemId: number + url: string + title: string | null + domain: string | null + content: string | null +} diff --git a/packages/core/src/features/extract/service.ts b/packages/core/src/features/extract/service.ts index 0cadd6b..9a18309 100644 --- a/packages/core/src/features/extract/service.ts +++ b/packages/core/src/features/extract/service.ts @@ -4,13 +4,15 @@ import * as schema from "../../db/schema.js" import { StashError } from "../../errors.js" import { extractContent } from "../../lib/extract.js" import { isContentExtractionError } from "../../lib/extract-x-browser.js" -import type { ExtractItemResult, OperationContext } from "../../types.js" +import type { ExtractItemOptions, ExtractItemResult, OperationContext } from "../../types.js" +import { resolveAutoTagsRequested } from "../auto-tags/config.js" +import { applyAutoTags } from "../auto-tags/service.js" import { getItemRowById, withReadyDbAsync } from "../common/db.js" export async function extractItem( context: OperationContext, itemId: number, - force = false, + options: ExtractItemOptions = {}, ): Promise<ExtractItemResult> { return withReadyDbAsync(context.dbPath, context.migrationsDir, async (db) => { const item = getItemRowById(db, itemId) @@ -19,7 +21,7 @@ export async function extractItem( } const existing = db.select().from(schema.notes).where(eq(schema.notes.itemId, itemId)).get() - if (existing && !force) { + if (existing && !options.force) { throw new StashError( `Item ${itemId} already has extracted content. Use --force to re-extract.`, "CONTENT_EXISTS", @@ -79,12 +81,32 @@ export async function extractItem( .run() } - return { + const runAutoTags = resolveAutoTagsRequested(options.autoTags) + const autoTagResult = runAutoTags + ? await applyAutoTags(db, { + itemId, + url: item.url, + title: extracted.title ?? item.title ?? null, + domain: item.domain, + content: extracted.textContent, + }) + : null + + const result: ExtractItemResult = { item_id: itemId, title_extracted: extracted.title || null, title_updated: titleUpdated, content_length: extracted.textContent.length, updated_at: timestamp.toISOString(), } + if (autoTagResult) { + result.auto_tags = autoTagResult.applied + result.auto_tag_scores = autoTagResult.scores + if (autoTagResult.warning) { + result.auto_tag_warning = autoTagResult.warning + } + } + + return result }) } diff --git a/packages/core/src/features/items/service.ts b/packages/core/src/features/items/service.ts index 514213b..67ff8a7 100644 --- a/packages/core/src/features/items/service.ts +++ b/packages/core/src/features/items/service.ts @@ -9,6 +9,8 @@ import type { SaveItemInput, SaveItemResult, } from "../../types.js" +import { resolveAutoTagsRequested } from "../auto-tags/config.js" +import { applyAutoTags } from "../auto-tags/service.js" import { ensureTagId, getExtractedContentForItem, @@ -34,6 +36,7 @@ export async function saveItem( ): Promise<SaveItemResult> { const parsedUrl = parseUrl(input.url) const normalizedTags = normalizeTags(input.tags ?? []) + const runAutoTags = resolveAutoTagsRequested(input.autoTags) return withReadyDbAsync(context.dbPath, context.migrationsDir, async (db) => { const existing = db @@ -88,8 +91,19 @@ export async function saveItem( itemId, tagId, createdAt: timestamp, + isManual: true, + isAuto: false, + autoScore: null, + autoSource: null, + autoModel: null, + autoUpdatedAt: null, + }) + .onConflictDoUpdate({ + target: [schema.itemTags.itemId, schema.itemTags.tagId], + set: { + isManual: true, + }, }) - .onConflictDoNothing() .run() } }) @@ -98,7 +112,17 @@ export async function saveItem( throw new Error("Saved item id could not be determined.") } - if (input.extract !== false && created) { + const existingNote = db + .select({ + content: schema.notes.content, + }) + .from(schema.notes) + .where(eq(schema.notes.itemId, itemId)) + .get() + const hasNoteContent = (existingNote?.content ?? "").trim().length > 0 + const shouldExtract = input.extract !== false && (created || (runAutoTags && !hasNoteContent)) + + if (shouldExtract) { try { const extracted = await extractContent(parsedUrl.toString()) if (extracted?.textContent) { @@ -141,12 +165,34 @@ export async function saveItem( } } + let autoTagResult: Awaited<ReturnType<typeof applyAutoTags>> | null = null + if (runAutoTags) { + const refreshed = getItemRowById(db, itemId) + if (refreshed) { + const note = db + .select({ + content: schema.notes.content, + }) + .from(schema.notes) + .where(eq(schema.notes.itemId, itemId)) + .get() + + autoTagResult = await applyAutoTags(db, { + itemId, + url: refreshed.url, + title: refreshed.title, + domain: refreshed.domain, + content: note?.content ?? null, + }) + } + } + const row = getItemRowById(db, itemId) if (!row) { throw new Error("Saved item could not be reloaded.") } - return { + const result: SaveItemResult = { created, item: serializeItem( row, @@ -155,6 +201,15 @@ export async function saveItem( getItemAudioForItem(db, row.id), ), } + if (autoTagResult) { + result.auto_tags = autoTagResult.applied + result.auto_tag_scores = autoTagResult.scores + if (autoTagResult.warning) { + result.auto_tag_warning = autoTagResult.warning + } + } + + return result }) } diff --git a/packages/core/src/features/tags/service.ts b/packages/core/src/features/tags/service.ts index d6b9100..7b110e8 100644 --- a/packages/core/src/features/tags/service.ts +++ b/packages/core/src/features/tags/service.ts @@ -49,24 +49,42 @@ export function addTag( return withReadyDb(context.dbPath, context.migrationsDir, (db) => { ensureItemExists(db, itemId) const timestamp = new Date(nowMs()) + const existing = db + .select({ + isManual: schema.itemTags.isManual, + }) + .from(schema.itemTags) + .innerJoin(schema.tags, eq(schema.tags.id, schema.itemTags.tagId)) + .where(and(eq(schema.itemTags.itemId, itemId), eq(schema.tags.name, normalizedTag))) + .get() - const result = db.transaction((tx) => { + db.transaction((tx) => { const tagId = ensureTagId(tx, normalizedTag, timestamp) - return tx - .insert(schema.itemTags) + tx.insert(schema.itemTags) .values({ itemId, tagId, createdAt: timestamp, + isManual: true, + isAuto: false, + autoScore: null, + autoSource: null, + autoModel: null, + autoUpdatedAt: null, + }) + .onConflictDoUpdate({ + target: [schema.itemTags.itemId, schema.itemTags.tagId], + set: { + isManual: true, + }, }) - .onConflictDoNothing() .run() }) return { item_id: itemId, tag: normalizedTag, - added: Number(result.changes) > 0, + added: !existing || !existing.isManual, } }) } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 34df2ac..7e1b51b 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -2,6 +2,7 @@ export * as db from "./db/client.js" export * as migrate from "./db/migrate.js" export * as schema from "./db/schema.js" export * from "./errors.js" +export * from "./features/auto-tags/index.js" export * from "./features/extract/service.js" export * from "./features/items/service.js" export * from "./features/status/service.js" diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 0d6f0f5..ea43627 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -1,6 +1,13 @@ export type ItemStatus = "unread" | "read" | "archived" export type ListItemsStatusFilter = ItemStatus | "active" export type TagMode = "any" | "all" +export type AutoTagSource = "embedding" | "rule" + +export type AutoTagScore = { + tag: string + score: number + source: AutoTagSource +} export type ItemTtsAudio = { file_name: string @@ -52,11 +59,15 @@ export type SaveItemInput = { title?: string tags?: string[] extract?: boolean + autoTags?: boolean } export type SaveItemResult = { created: boolean item: StashItem + auto_tags?: string[] + auto_tag_scores?: AutoTagScore[] + auto_tag_warning?: string } export type TagsListInput = { @@ -75,6 +86,14 @@ export type ExtractItemResult = { title_updated: boolean content_length: number updated_at: string + auto_tags?: string[] + auto_tag_scores?: AutoTagScore[] + auto_tag_warning?: string +} + +export type ExtractItemOptions = { + force?: boolean + autoTags?: boolean } export type TtsResult = { diff --git a/packages/core/test/auto-tags-doctor.test.ts b/packages/core/test/auto-tags-doctor.test.ts new file mode 100644 index 0000000..c7f60a9 --- /dev/null +++ b/packages/core/test/auto-tags-doctor.test.ts @@ -0,0 +1,131 @@ +import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import path from "node:path" + +import { afterEach, describe, expect, it } from "vitest" + +import { inspectAutoTagsHealth } from "../src/features/auto-tags/doctor.js" + +const previousBackend = process.env.STASH_AUTO_TAGS_BACKEND +const previousPython = process.env.STASH_AUTO_TAGS_PYTHON +const previousHelper = process.env.STASH_AUTO_TAGS_HELPER +const previousImportFail = process.env.STASH_AUTO_TAGS_TEST_IMPORT_FAIL +const tempDirs: string[] = [] + +async function writeExecutable( + tempDir: string, + fileName: string, + content: string, +): Promise<string> { + const filePath = path.join(tempDir, fileName) + await writeFile(filePath, content, "utf-8") + await chmod(filePath, 0o755) + return filePath +} + +afterEach(async () => { + if (previousBackend === undefined) { + delete process.env.STASH_AUTO_TAGS_BACKEND + } else { + process.env.STASH_AUTO_TAGS_BACKEND = previousBackend + } + if (previousPython === undefined) { + delete process.env.STASH_AUTO_TAGS_PYTHON + } else { + process.env.STASH_AUTO_TAGS_PYTHON = previousPython + } + if (previousHelper === undefined) { + delete process.env.STASH_AUTO_TAGS_HELPER + } else { + process.env.STASH_AUTO_TAGS_HELPER = previousHelper + } + if (previousImportFail === undefined) { + delete process.env.STASH_AUTO_TAGS_TEST_IMPORT_FAIL + } else { + process.env.STASH_AUTO_TAGS_TEST_IMPORT_FAIL = previousImportFail + } + + for (const dir of tempDirs.splice(0, tempDirs.length)) { + await rm(dir, { recursive: true, force: true }) + } +}) + +describe("inspectAutoTagsHealth", () => { + it("reports healthy when python/helper/import checks pass", async () => { + const tempDir = await mkdtemp(path.join(tmpdir(), "stash-auto-tags-doctor-")) + tempDirs.push(tempDir) + + const helperPath = path.join(tempDir, "helper.py") + await writeFile(helperPath, "print('helper')\n", "utf-8") + + const pythonPath = await writeExecutable( + tempDir, + "fake-python.sh", + `#!/bin/sh +if [ "$1" = "--version" ]; then + echo "Python 3.11.0" + exit 0 +fi +if [ "$1" = "-c" ]; then + if [ "\${STASH_AUTO_TAGS_TEST_IMPORT_FAIL:-0}" = "1" ]; then + echo "ImportError" >&2 + exit 1 + fi + exit 0 +fi +echo '{"ok":true,"scores":[{"tag":"health","score":0.9}]}' +exit 0 +`, + ) + + process.env.STASH_AUTO_TAGS_BACKEND = "python" + process.env.STASH_AUTO_TAGS_PYTHON = pythonPath + process.env.STASH_AUTO_TAGS_HELPER = helperPath + + const report = inspectAutoTagsHealth() + + expect(report.backend).toBe("python") + expect(report.healthy).toBe(true) + expect(report.checks.find((check) => check.id === "python")?.ok).toBe(true) + expect(report.checks.find((check) => check.id === "sentence_transformers")?.ok).toBe(true) + expect(report.checks.find((check) => check.id === "helper_runtime")?.ok).toBe(true) + }) + + it("reports unhealthy when import check fails", async () => { + const tempDir = await mkdtemp(path.join(tmpdir(), "stash-auto-tags-doctor-")) + tempDirs.push(tempDir) + + const helperPath = path.join(tempDir, "helper.py") + await writeFile(helperPath, "print('helper')\n", "utf-8") + + const pythonPath = await writeExecutable( + tempDir, + "fake-python.sh", + `#!/bin/sh +if [ "$1" = "--version" ]; then + echo "Python 3.11.0" + exit 0 +fi +if [ "$1" = "-c" ]; then + if [ "\${STASH_AUTO_TAGS_TEST_IMPORT_FAIL:-0}" = "1" ]; then + echo "ImportError: sentence_transformers missing" >&2 + exit 1 + fi + exit 0 +fi +echo '{"ok":true,"scores":[{"tag":"health","score":0.9}]}' +exit 0 +`, + ) + + process.env.STASH_AUTO_TAGS_BACKEND = "python" + process.env.STASH_AUTO_TAGS_PYTHON = pythonPath + process.env.STASH_AUTO_TAGS_HELPER = helperPath + process.env.STASH_AUTO_TAGS_TEST_IMPORT_FAIL = "1" + + const report = inspectAutoTagsHealth() + + expect(report.healthy).toBe(false) + expect(report.checks.find((check) => check.id === "sentence_transformers")?.ok).toBe(false) + }) +}) diff --git a/packages/core/test/auto-tags.test.ts b/packages/core/test/auto-tags.test.ts new file mode 100644 index 0000000..8d067ed --- /dev/null +++ b/packages/core/test/auto-tags.test.ts @@ -0,0 +1,260 @@ +import fs from "node:fs" +import os from "node:os" +import path from "node:path" + +import { eq } from "drizzle-orm" +import { afterEach, describe, expect, it } from "vitest" + +import { openDb } from "../src/db/client.js" +import { runMigrations } from "../src/db/migrate.js" +import * as schema from "../src/db/schema.js" +import { applyAutoTags } from "../src/features/auto-tags/service.js" +import type { OperationContext } from "../src/types.js" + +type TempContext = { + context: OperationContext + tempDir: string +} + +function createTempContext(): TempContext { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "stash-core-auto-tags-")) + return { + context: { + dbPath: path.join(tempDir, "stash.db"), + migrationsDir: path.join(process.cwd(), "drizzle"), + }, + tempDir, + } +} + +function createItem(context: OperationContext, slug: string, note: string): number { + runMigrations(context.dbPath, context.migrationsDir) + const { db, sqlite } = openDb(context.dbPath) + try { + const timestamp = new Date() + const inserted = db + .insert(schema.items) + .values({ + url: `https://example.com/${slug}`, + title: slug, + domain: "example.com", + status: "unread", + isStarred: false, + createdAt: timestamp, + updatedAt: timestamp, + readAt: null, + archivedAt: null, + }) + .run() + const itemId = Number(inserted.lastInsertRowid) + db.insert(schema.notes) + .values({ + itemId, + content: note, + updatedAt: timestamp, + }) + .run() + return itemId + } finally { + sqlite.close() + } +} + +function createTag(context: OperationContext, tag: string): number { + const { db, sqlite } = openDb(context.dbPath) + try { + const timestamp = new Date() + db.insert(schema.tags) + .values({ + name: tag, + createdAt: timestamp, + }) + .onConflictDoNothing({ target: schema.tags.name }) + .run() + const row = db + .select({ id: schema.tags.id }) + .from(schema.tags) + .where(eq(schema.tags.name, tag)) + .get() + if (!row) { + throw new Error(`missing tag ${tag}`) + } + return row.id + } finally { + sqlite.close() + } +} + +function attachTag( + context: OperationContext, + options: { + itemId: number + tagId: number + isManual: boolean + isAuto: boolean + }, +): void { + const { db, sqlite } = openDb(context.dbPath) + try { + const timestamp = new Date() + db.insert(schema.itemTags) + .values({ + itemId: options.itemId, + tagId: options.tagId, + createdAt: timestamp, + isManual: options.isManual, + isAuto: options.isAuto, + autoScore: options.isAuto ? 0.91 : null, + autoSource: options.isAuto ? "rule" : null, + autoModel: options.isAuto ? "rule" : null, + autoUpdatedAt: options.isAuto ? timestamp : null, + }) + .onConflictDoUpdate({ + target: [schema.itemTags.itemId, schema.itemTags.tagId], + set: { + isManual: options.isManual, + isAuto: options.isAuto, + autoScore: options.isAuto ? 0.91 : null, + autoSource: options.isAuto ? "rule" : null, + autoModel: options.isAuto ? "rule" : null, + autoUpdatedAt: options.isAuto ? timestamp : null, + }, + }) + .run() + } finally { + sqlite.close() + } +} + +describe("auto-tags service", () => { + const tempDirs: string[] = [] + const previousBackend = process.env.STASH_AUTO_TAGS_BACKEND + const previousMinScore = process.env.STASH_AUTO_TAGS_MIN_SCORE + const previousMax = process.env.STASH_AUTO_TAGS_MAX + + afterEach(() => { + if (previousBackend === undefined) { + delete process.env.STASH_AUTO_TAGS_BACKEND + } else { + process.env.STASH_AUTO_TAGS_BACKEND = previousBackend + } + if (previousMinScore === undefined) { + delete process.env.STASH_AUTO_TAGS_MIN_SCORE + } else { + process.env.STASH_AUTO_TAGS_MIN_SCORE = previousMinScore + } + if (previousMax === undefined) { + delete process.env.STASH_AUTO_TAGS_MAX + } else { + process.env.STASH_AUTO_TAGS_MAX = previousMax + } + + while (tempDirs.length > 0) { + const dir = tempDirs.pop() + if (dir) { + fs.rmSync(dir, { recursive: true, force: true }) + } + } + }) + + it("uses manual DB tags as candidates and excludes auto-only DB tags", async () => { + process.env.STASH_AUTO_TAGS_BACKEND = "rule" + process.env.STASH_AUTO_TAGS_MIN_SCORE = "0.7" + process.env.STASH_AUTO_TAGS_MAX = "5" + + const { context, tempDir } = createTempContext() + tempDirs.push(tempDir) + + const seedItemId = createItem(context, "seed-item", "seed") + const manualTagId = createTag(context, "manualonly") + const autoOnlyTagId = createTag(context, "autoonly") + attachTag(context, { + itemId: seedItemId, + tagId: manualTagId, + isManual: true, + isAuto: false, + }) + attachTag(context, { + itemId: seedItemId, + tagId: autoOnlyTagId, + isManual: false, + isAuto: true, + }) + + const targetItemId = createItem(context, "target", "manualonly autoonly") + const { db, sqlite } = openDb(context.dbPath) + try { + const result = await applyAutoTags(db, { + itemId: targetItemId, + url: "https://example.com/target", + title: "target", + domain: "example.com", + content: "manualonly autoonly", + }) + + expect(result.backend).toBe("rule") + expect(result.applied).toContain("manualonly") + expect(result.applied).not.toContain("autoonly") + } finally { + sqlite.close() + } + }) + + it("replaces stale auto-only tags and preserves manual tags", async () => { + process.env.STASH_AUTO_TAGS_BACKEND = "rule" + process.env.STASH_AUTO_TAGS_MIN_SCORE = "0.62" + process.env.STASH_AUTO_TAGS_MAX = "3" + + const { context, tempDir } = createTempContext() + tempDirs.push(tempDir) + + const itemId = createItem(context, "replace", "TypeScript integration details") + const pythonTagId = createTag(context, "python") + const securityTagId = createTag(context, "security") + + attachTag(context, { + itemId, + tagId: pythonTagId, + isManual: false, + isAuto: true, + }) + attachTag(context, { + itemId, + tagId: securityTagId, + isManual: true, + isAuto: true, + }) + + const { db, sqlite } = openDb(context.dbPath) + try { + const result = await applyAutoTags(db, { + itemId, + url: "https://example.com/replace", + title: "replace", + domain: "example.com", + content: "TypeScript integration details", + }) + + expect(result.applied).toContain("typescript") + + const rows = db + .select({ + tag: schema.tags.name, + isManual: schema.itemTags.isManual, + isAuto: schema.itemTags.isAuto, + }) + .from(schema.itemTags) + .innerJoin(schema.tags, eq(schema.tags.id, schema.itemTags.tagId)) + .where(eq(schema.itemTags.itemId, itemId)) + .all() + + const byTag = new Map(rows.map((row) => [row.tag, row])) + expect(byTag.get("python")).toBeUndefined() + expect(byTag.get("security")?.isManual).toBe(true) + expect(byTag.get("security")?.isAuto).toBe(false) + expect(byTag.get("typescript")?.isAuto).toBe(true) + } finally { + sqlite.close() + } + }) +}) diff --git a/scripts/auto-tags-embed.py b/scripts/auto-tags-embed.py new file mode 100755 index 0000000..4621746 --- /dev/null +++ b/scripts/auto-tags-embed.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +import json +import sys +from typing import Any + + +def emit(payload: dict[str, Any]) -> None: + sys.stdout.write(json.dumps(payload)) + sys.stdout.flush() + + +def fail(code: str, message: str, exit_code: int = 1) -> int: + emit( + { + "ok": False, + "error": { + "code": code, + "message": message, + }, + } + ) + return exit_code + + +def parse_payload() -> tuple[str, list[dict[str, str]], str] | None: + try: + payload = json.load(sys.stdin) + except Exception as error: + fail("INVALID_INPUT", f"Failed to parse JSON input: {error}") + return None + + if not isinstance(payload, dict): + fail("INVALID_INPUT", "Input payload must be a JSON object.") + return None + + text = payload.get("text") + candidates = payload.get("candidates") + model = payload.get("model") or "sentence-transformers/all-MiniLM-L6-v2" + + if not isinstance(text, str) or len(text.strip()) == 0: + fail("INVALID_INPUT", "text is required and must be a non-empty string.") + return None + if not isinstance(model, str) or len(model.strip()) == 0: + fail("INVALID_INPUT", "model must be a non-empty string.") + return None + if not isinstance(candidates, list): + fail("INVALID_INPUT", "candidates must be an array.") + return None + + normalized_candidates: list[dict[str, str]] = [] + for row in candidates: + if not isinstance(row, dict): + continue + tag = row.get("tag") + descriptor = row.get("descriptor") + if not isinstance(tag, str) or not isinstance(descriptor, str): + continue + if len(tag.strip()) == 0 or len(descriptor.strip()) == 0: + continue + normalized_candidates.append({"tag": tag.strip(), "descriptor": descriptor.strip()}) + + return text, normalized_candidates, model + + +def run() -> int: + parsed = parse_payload() + if parsed is None: + return 1 + + text, candidates, model_name = parsed + if len(candidates) == 0: + emit({"ok": True, "scores": []}) + return 0 + + try: + from sentence_transformers import SentenceTransformer + except Exception as error: + return fail( + "DEPENDENCY_MISSING", + "sentence-transformers is not available. Install dependencies from docs/AUTO_TAGS_SETUP.md." + f" ({error})", + ) + + try: + import numpy as np + except Exception as error: + return fail("DEPENDENCY_MISSING", f"numpy is not available: {error}") + + try: + model = SentenceTransformer(model_name) + except Exception as error: + return fail("MODEL_LOAD_FAILED", f"Failed to load model '{model_name}': {error}") + + try: + inputs = [text] + [candidate["descriptor"] for candidate in candidates] + vectors = model.encode(inputs, normalize_embeddings=True) + base = vectors[0] + scores = [] + for idx, candidate in enumerate(candidates): + candidate_vec = vectors[idx + 1] + score = float(np.dot(base, candidate_vec)) + scores.append({"tag": candidate["tag"], "score": score}) + except Exception as error: + return fail("INFERENCE_FAILED", f"Failed while scoring tags: {error}") + + emit({"ok": True, "scores": scores}) + return 0 + + +if __name__ == "__main__": + raise SystemExit(run())