Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .agents/notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,4 @@
[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.
[0] `stash db doctor` does not create parent directories for a missing DB path; if `STASH_DB_PATH` points to a non-existent directory, command can fail with `unable to open database file`.
[0] Prefer explicit named types over `ReturnType<typeof ...>` in production code/tests for readability and easier review comments.
10 changes: 10 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,15 @@ node apps/cli/dist/cli.js --help
node apps/cli/dist/cli.js list --help
```

## Pre-PR Handoff Gate

Before opening a PR/MR, run local quality gates and keep them green.

- Code changes: must run `pnpm run check` and fix all failures before PR/MR creation.
- Docs-only changes: must run `pnpm run format:check` before PR/MR creation.
- PR flow: use existing `gh` tooling (`gh pr create`), then watch checks with `gh pr checks --watch`.
- If CI fails, fix locally, re-run the local gate, push, and re-check until all required checks are green.

## Documentation Maintenance Rule

⚠️ **When adding new features or modifying existing CLI behavior, update ALL THREE documentation files in the same change:**
Expand Down Expand Up @@ -370,5 +379,6 @@ Updates should include:
- Prefer Drizzle ORM for database access in application/runtime code.
- Use raw SQL string queries only when Drizzle does not support the required functionality clearly or safely (for example, specialized migration-runner behavior).
- Prefer explicit return types on functions and methods (especially exported/public APIs and non-trivial helpers).
- Prefer explicit named types over inferred meta-types like `ReturnType<typeof ...>` in app/core code and tests.
- Dependency injection pattern: prefer `createXService`/`createCoreServices` factory objects over classes, and inject least-privilege service slices into API route plugins and command handlers.
- In this sandbox, local listener startup (for example Vite/dev servers on `127.0.0.1`) may fail with `listen EPERM`; validate listener-bound flows in a less restricted environment when needed.
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,17 @@ pnpm run setup
## Code Quality

```bash
pnpm run check
pnpm run lint
pnpm run format:check
pnpm run check
```

For code changes, use `pnpm run check` as the local pre-PR gate.
For docs-only changes, run `pnpm run format:check`.

## CI

GitHub Actions runs on pull requests and pushes to `main` with strict checks:
GitHub Actions runs on pull requests and pushes to `main` with strict staged checks:

```bash
pnpm run format:check && pnpm run lint && pnpm run test && pnpm --dir apps/web build
Expand Down
13 changes: 6 additions & 7 deletions apps/api/src/app/create-api-app.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
import Fastify, { type FastifyInstance } from "fastify"
import { createCoreServices } from "@stash/core"
import type { CoreServices } from "@stash/core"
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"
import { ttsRoutes } from "../features/tts/routes.js"
import { registerApiErrorHandlers } from "./error-handler.js"

export type CreateApiAppOptions = ApiRouteOptions
export type CreateApiAppOptions = {
services: CoreServices
audioDir: string
}

export function createApiApp(options: CreateApiAppOptions): FastifyInstance {
const server = Fastify({
logger: false,
})
const services = createCoreServices({
dbPath: options.dbPath,
migrationsDir: options.migrationsDir,
})
const { services } = options

// 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.
Expand Down
56 changes: 41 additions & 15 deletions apps/api/src/app/server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import http from "node:http"

import { resolveAudioDir, startTtsWorker } from "@stash/core"
import type { FastifyInstance } from "fastify"
import { createCoreRuntime, resolveAudioDir, type TtsWorkerHandle } from "@stash/core"
import { createApiApp } from "./create-api-app.js"
import { serveStatic } from "./static.js"

Expand Down Expand Up @@ -102,7 +103,7 @@ async function listenServer(
}

async function listenApiServer(
server: ReturnType<typeof createApiApp>,
server: FastifyInstance,
host: string,
port: number,
): Promise<number> {
Expand Down Expand Up @@ -202,32 +203,58 @@ function sendJson(res: http.ServerResponse, statusCode: number, value: unknown):
res.end(body)
}

async function shutdownApiResources(
server: FastifyInstance,
ttsWorker: TtsWorkerHandle,
closeRuntime: () => void,
): Promise<void> {
const results = await Promise.allSettled([ttsWorker.stop(), server.close()])
closeRuntime()

const errors = results
.filter((result): result is PromiseRejectedResult => result.status === "rejected")
.map((result) => result.reason)

if (errors.length === 1) {
throw errors[0]
}
if (errors.length > 1) {
throw new AggregateError(errors, "Failed to shutdown API server resources.")
}
}

export async function startApiServer(options: StartApiServerOptions): Promise<StartedApiServer> {
const audioDir = resolveAudioDir(options.audioDir)
const workerOptions = { audioDir } as { audioDir: string; pollMs?: number }
if (options.ttsWorkerPollMs !== undefined) {
workerOptions.pollMs = options.ttsWorkerPollMs
}

const ttsWorker = startTtsWorker(
{
dbPath: options.dbPath,
migrationsDir: options.migrationsDir,
},
workerOptions,
)
const server = createApiApp({
const runtime = createCoreRuntime({
dbPath: options.dbPath,
migrationsDir: options.migrationsDir,
audioDir,
})
let server: FastifyInstance
try {
server = createApiApp({
services: runtime.services,
audioDir,
})
} catch (error) {
runtime.close()
throw error
}
const ttsWorker = runtime.services.ttsJobs.startTtsWorker(workerOptions)

let resolvedPort = options.port
try {
resolvedPort = await listenApiServer(server, options.host, options.port)
} catch (error) {
await server.close()
await ttsWorker.stop()
try {
await shutdownApiResources(server, ttsWorker, runtime.close)
} catch {
// Preserve the original listen failure while still attempting full cleanup.
}
throw error
Comment on lines 252 to 258

Copilot AI Mar 7, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the failure path for listenApiServer, the cleanup sequence (await server.close(); await ttsWorker.stop(); runtime.close()) can short-circuit if server.close() throws, leaving the worker/runtime running and the SQLite connection open. Consider using nested try/finally (or Promise.allSettled) so ttsWorker.stop() and runtime.close() are always attempted regardless of which close step fails.

Copilot uses AI. Check for mistakes.
}

Expand All @@ -237,8 +264,7 @@ export async function startApiServer(options: StartApiServerOptions): Promise<St
port: resolvedPort,
audioDir,
close: async () => {
await ttsWorker.stop()
await server.close()
await shutdownApiResources(server, ttsWorker, runtime.close)
},
Comment on lines 266 to 268

Copilot AI Mar 7, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The returned close function awaits ttsWorker.stop() and server.close() before calling runtime.close(), but if either awaited call throws, runtime.close() won't run and the SQLite connection may remain open. Consider wrapping shutdown steps in try/finally to guarantee runtime.close() (and ideally attempt both worker+server shutdown even if one fails).

Copilot uses AI. Check for mistakes.
}
}
Expand Down
5 changes: 0 additions & 5 deletions apps/api/src/features/options.ts

This file was deleted.

7 changes: 6 additions & 1 deletion apps/api/test/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import path from "node:path"
import { fileURLToPath } from "node:url"

import { describe, expect, it } from "vitest"
import { createCoreRuntime } from "@stash/core"

import { createApiApp } from "../src/app/create-api-app.js"

Expand Down Expand Up @@ -169,9 +170,12 @@ const integrationTitle = sqliteBindingsMissing
integrationSuite(integrationTitle, () => {
it("keeps endpoint response contracts stable across save/list/item/status/extract/tags/tts flows", async () => {
const { dbPath, audioDir, cleanup } = createTempPaths()
const app = createApiApp({
const runtime = createCoreRuntime({
dbPath,
migrationsDir,
})
const app = createApiApp({
services: runtime.services,
audioDir,
})

Expand Down Expand Up @@ -322,6 +326,7 @@ integrationSuite(integrationTitle, () => {
expect(itemJobsBody.jobs[0]?.id).toBe(enqueueTtsBody.job.id)
} finally {
await app.close()
runtime.close()
cleanup()
}
})
Expand Down
Loading