# Repository Instructions ## Parallel task execution For substantial changes, use subagents as a standard practice when the work can be divided into concrete, independent tasks that provide real parallel progress. 1. Delegate bounded mechanical work to faster, lower-reasoning agents (focused code discovery, repetitive call-site updates, documentation, isolated test coverage). 2. Keep architecture, security-sensitive behavior, database migrations, shared data-model decisions, and complex debugging with a suitably capable agent. 3. Assign explicit file or subsystem ownership before parallel edits. Avoid having multiple agents edit the same files unless their work is deliberately sequenced. 4. Do not delegate tightly coupled work merely to increase agent count. Keep it with the primary agent when coordination would cost more than it saves. 5. The primary agent remains responsible for integrating results, reviewing diffs, resolving cross-cutting concerns, and running the final required validation. 6. Subagents must follow every repository rule that applies to their assigned work, including design-system maintenance, audit logging, and database preservation. ## Documentation prose Use the `stop-slop` skill whenever an agent creates or changes project documentation. Apply its review to the complete affected document, including sections that the change did not introduce. Preserve technical meaning, commands, paths, formulas, links, policy strength, and product terminology. Remove filler, vague claims, formulaic contrasts, manufactured emphasis, false agency, and repetition. Prefer active voice and specific subjects. Do not weaken terms such as `must`, `never`, or `always` when they express a real requirement. ## Dependency source research Use `npx opensrc` before inspecting an npm dependency's implementation. It resolves the package version from this workspace's lockfile, shallow-clones the matching source revision, and caches it outside the repository at `~/.opensrc/`. - Do not guess at dependency behavior or implementation details. Identify the needed function, type, option, or control flow in the cached source and use that evidence when designing a change. - Search the smallest relevant source area first. Use the package entry point, exports, types, and targeted code search to locate the behavior instead of reading unrelated files. - Fetch source before a dependency investigation: `npx opensrc fetch --cwd . `. - Print the cached source path for use with repository search and file tools: `npx opensrc path --cwd . `. - Fetch several declared packages in one command: `npx opensrc fetch --cwd . `. - After adding or upgrading a direct dependency, fetch its source at the locked version. Do not commit `~/.opensrc/` or copy dependency source into this repository. - Use `npx opensrc list` to inspect the cache. Use `npx opensrc remove ` or `npx opensrc clean` only when cache removal is intended. ## Available skills The `.agents/skills/` directory contains repo-specific skill files. Key skills: - `stop-slop`: apply to documentation prose changes - `frontend-design` / `impeccable`: UI design, refinement, and polish - `import-talent-screenshot` / `import-weapon-screenshot`: extract Division Resurgence game data from screenshots and enter through ISAC - `webapp-testing`: Playwright-based local web app testing Use `skill` tool to load one when the task matches. ## Verify commands Run in order after source changes: ``` npm run check # svelte-kit sync + svelte-check (typecheck) npm run build # secretless Vite production build ``` `npm run check` runs `svelte-kit sync` (generates `.svelte-kit/tsconfig.json`) then `svelte-check --tsconfig ./tsconfig.json`. `npm test` runs all vitest tests; there is no separate vitest config (vitest inherits from `vite.config.ts`). Test files (`*.test.ts`) live adjacent to the code they test, mostly in `src/lib/`. Most server-unit tests mock `$lib/server/database` via `vi.mock(...)`; pure logic tests do not need that mock. Integration tests that need database state use the embedded Turso engine. ## Framework and toolchain quirks - **SvelteKit 2 / Svelte 5** with forced runes mode (configured in `vite.config.ts` via plugin `compilerOptions.runes`). There is no `svelte.config.js`; SvelteKit config lives in `vite.config.ts`. - **Node adapter** (`@sveltejs/adapter-node`). Production entry point is `node build`. The container runs migrations on startup, then serves. - **Embedded Turso** (`@tursodatabase/database`): local SQLite, no Turso Cloud, no libSQL HTTP, no replicas. The Infisical `dev` environment sets the database path to `./data/shd-build-development.db`. - **Passkey auth** (`@simplewebauthn`) is preferred. `APP_ORIGIN` must match the public origin. `PASSKEY_RP_ID` must be that hostname or a registrable parent domain; hosted environments use `shd.build`. - **Infisical secrets** live in project `2ee94b27-e599-4194-9797-3372d42e53f6` at `https://secrets.jb.codes`. Application values use `/app`; `SCHEDULER_TOKEN` uses `/shared/scheduler`. Local commands use the authenticated Infisical CLI and the `dev` environment. Deployed app and scheduler containers use separate Universal Auth bootstrap credentials mounted through Compose secrets. The root entrypoint exchanges those credentials for one-shot JSON exports, deletes the export files, and starts the workload as the dedicated `shd-runtime` UID 10001 without Infisical credentials or tokens. The self-hosted Free plan cannot scope Viewer identities by environment or path. - **Argon2id** password hashing with server-side sessions and CSRF protection. - **ISAC namespace**: `/isac` is the admin console; `/admin` redirects there via 308. ## Long-running development processes Use the installed `pi-background-tasks` extension's `bg_run` tool for development servers, watchers, and other persistent commands. Do not use foreground shell sessions, `nohup`, `&`, or process-tree/PID discovery when a tracked task exists. - Use `isAgent: false` and a concise, descriptive task name. - Retain the returned task ID and output path. Inspect a task with `bg_status` and read its output with `bg_logs`. - Stop a task with `bg_kill `. To restart it, start a new `bg_run` task and retain its new task ID and output path; do not search for and kill processes. - Do not leave duplicate tracked tasks for the same development service. ## Development server lifecycle After changing source code, styles, configuration, dependencies, or routes, restart the development server before handing work back. 1. Start `npm run dev` from the repository root with `bg_run`, using `isAgent: false` and a descriptive task name. Retain its task ID and output path. 2. Before starting a replacement, stop the existing tracked development-server task with `bg_kill ` so only one server runs. 3. Confirm the task logs show the server started, then confirm it accepts an HTTP request before completing the task. 4. Leave the verified tracked task running so the project owner can review the changes. Database maintenance may require the server to remain stopped while the embedded database is locked. Stop its tracked task first, then restart and verify it after maintenance completes. ## SHD design-system maintenance Treat `docs/DESIGN_SYSTEM.md` and the shared tokens in `src/app.css` as maintained parts of the product. When a change makes a significant visual or interaction-design decision, update the design system in the same change. For significant design changes: reuse or extend CSS custom properties from `src/app.css`; update `docs/DESIGN_SYSTEM.md`; refactor repeated UI into a reusable component; verify hover, pressed, focus-visible, pending, disabled, error, success, and reduced-motion behavior. Run `npm run check && npm run build` before completing. Design principles: tactical but restrained, data-first, square and engineered, orange reserved for action/emphasis, explicit textual state indicators. Minor alignment fixes, isolated bug fixes, and corrections that do not introduce a reusable design decision do not require a documentation update. ## Reusable interface patterns Favor shared components from `src/lib/components`. Before adding page-local markup, check if a shared component covers the need. When introducing a reusable pattern, migrate the clearest existing duplicate in the same change. For small, finite option sets, prefer the shared segmented-choice pattern over a dropdown. Use radio semantics for exactly one choice and checkbox semantics for additive independent choices. Reserve dropdowns for long, dynamic, or search-oriented option sets. ## ISAC editor lifecycle All ISAC data-management editors must follow the same successful-save behavior: 1. Saving an edit to an existing record closes the editor and returns the user to the registry. 2. Saving a newly added record keeps the editor open with a fresh blank record. 3. Validation errors keep the editor open and preserve the entered values. 4. Server actions must return the add/edit mode and a unique result token; client-side reactive handling must consume each token only once to avoid repeated state updates. 5. When a successful add keeps an icon-enabled editor open, increment the shared upload reset token so the file input, preview, filename, drag/paste state, validation message, and removal state are fresh for the next record. Apply this convention whenever an ISAC editor is added or materially changed. ## ISAC audit logging Every successful server-side ISAC mutation must create an append-only audit event. Follow these rules: 1. Use the shared audit utilities in `src/lib/server/audit.ts`; do not write directly to `audit_log`. 2. Record the authenticated operator ID, stable category, specific action (namespaced past tense, e.g. `weapon.updated`), target entity ID, timestamp, and useful before/after snapshots. Categories include `game_data`, `user_access`, `user_moderation`, `identity`, `role_management`. 3. Capture changes to the primary row and its relationships. Include meaningful previous and resulting sets for linked records. 4. Create audit records only after validation succeeds. Rejected or failed requests must not appear as successful mutation events. 5. Never include password hashes, session tokens, magic-link tokens, OAuth state, passkey public-key bytes, SMTP credentials, or environment secrets in audit snapshots. 6. Audit visibility is controlled by `audit.view`. The read-only `Auditor` role grants `isac.access` and `audit.view` without granting mutation permissions. 7. Audit reversion is a compensating action, never a history rewrite. Require `audit.revert`, confirmation, current-state comparison, relationship validation, and a new `audit.reverted` event. 8. Tests for an ISAC mutation must confirm its audit event contains the correct actor, category, action, target, and change evidence. ## Prototype compatibility Treat application data and client payloads as prototype formats until the project owner declares a production-stable format. 1. Prefer one current validated schema over compatibility readers, repair branches, dual writes, or fallback parsing for obsolete formats. 2. Remove incompatible local drafts, saved builds, calibration snapshots, and other derived records through a backed-up migration when the current model cannot represent them safely. 3. Preserve authored game data whenever the new model can retain it without guessing. 4. Follow the database-preservation rules before removing or reshaping persistent data. 5. Add compatibility support only when the project owner requires it for a production-stable format. ## Talent mechanic conventions Before importing a Talent or changing its mechanic program, read `docs/TALENT_MECHANIC_RULES.md`. Treat the confirmed lifecycle, trigger, cooldown, and targeting rules in that document as authoritative game behavior. Do not mark a mechanic `requires_assumptions` for behavior that the document resolves. When the project owner clarifies another Talent mechanic, record the answer in `docs/TALENT_MECHANIC_RULES.md`. ## Database preservation Treat embedded database files as persistent user data, not disposable build artifacts. Before destructive work on the database, stop the dev server, then create a verified timestamped JSON backup with `npm run db:backup`. Keep backups out of Git (they can contain user records). Prefer additive, repeatable schema migrations over database recreation. Report the backup path when completing database-destructive work. Use `npm run db:restore -- ` only with an empty, migrated target database. The command refuses to merge into a populated database. ## Development database maintenance 1. Stop this project's tracked development-server task with `bg_kill `. 2. Run and verify `npm run db:backup`. Retain and report the backup path. 3. Apply the migration or maintenance operation. Verify schema state, record counts, and critical entities. 4. If an operation fails, preserve logs and the verified backup rather than improvising against the database. 5. Restart the dev server, then confirm a basic health or page check. Production and staging backups and deployment are defined in `docs/DEPLOYMENT.md`.