diff --git a/docs/CLI.md b/docs/CLI.md index 598d8eb..e664cb6 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1,239 +1,168 @@ # CLI Reference -The `knowledge-studio` CLI provides terminal-based automation for managing your knowledge base. It uses the same repository layer as the browser app but runs in Node.js via `better-sqlite3`. +Command-line interface for Knowledge Studio. Run with `pnpm run cli -- `. -## Global Options - -| Flag | Description | Default | -|------|-------------|---------| -| `--db-path ` | Custom path to SQLite database file | `~/.local/share/do-knowledge-studio/data.db` | -| `--version` | Show version number | — | -| `--help` | Show help for any command | — | - -Run any command with `pnpm run cli -- [args] [options]`. - ---- - -## Commands - -### `init` - -Initialize the workspace. Creates the `./export` directory if it doesn't exist. - -```bash -pnpm run cli -- init -``` - ---- - -### `sync ` - -Sync data from a directory of Markdown files or a URL into the database. - -**Arguments:** -- `` — Directory path or HTTP(S) URL - -**From a directory:** Reads all `.md` files. The first H1 heading becomes the entity name. Entities are created as type `concept`. - -```bash -pnpm run cli -- sync ./path/to/markdown/files -``` - -**From a URL:** Fetches content via Jina AI reader (cross-origin) or direct fetch (same-origin). Creates an entity with the page title and content. - -```bash -pnpm run cli -- sync https://example.com/article -``` - ---- - -### `export` - -Export the knowledge base to various formats. - -**Options:** - -| Flag | Description | Default | -|------|-------------|---------| -| `-f, --format ` | Export format: `md`, `json`, or `site` | `md` | -| `-o, --output ` | Output directory | `./export` | - -```bash -# Markdown — one file per entity -pnpm run cli -- export --format md --output ./export/markdown - -# JSON — single knowledge.json file -pnpm run cli -- export --format json --output ./export/json - -# Static site — portable HTML file -pnpm run cli -- export --format site --output ./export/site -``` - ---- - -### `search ` - -Full-text search across entities using FTS5. - -```bash -pnpm run cli -- search "artificial intelligence" -``` - ---- +## Entity Commands ### `entity-create ` Create a new entity. -**Options:** - -| Flag | Description | Default | -|------|-------------|---------| -| `-t, --type ` | Entity type | `concept` | -| `-d, --description ` | Entity description | — | -| `-u, --source-url ` | Source URL for auto-hydration | — | - ```bash -pnpm run cli -- entity-create "TRIZ" --type concept --description "Theory of Inventive Problem Solving" - -# Auto-hydrate description from URL -pnpm run cli -- entity-create "TRIZ" --source-url https://en.wikipedia.org/wiki/TRIZ +pnpm run cli -- entity-create "TRIZ" -t concept -d "Theory of Inventive Problem Solving" ``` ---- +| Option | Description | Default | +|--------|-------------|---------| +| `-t, --type ` | Entity type | `concept` | +| `-d, --description ` | Entity description | | +| `-u, --source-url ` | Source URL for auto-hydration | | ### `entity-list` -List all entities in the database. +List all entities. ```bash pnpm run cli -- entity-list ``` -Output: `[type] name` per line. - ---- - ### `entity-get ` -Get detailed information about an entity by name. +Get entity details by name. ```bash pnpm run cli -- entity-get "TRIZ" ``` ---- - ### `entity-update ` Update an entity's type or description. -**Options:** - -| Flag | Description | -|------|-------------| -| `-t, --type ` | New entity type | -| `-d, --description ` | New description | - ```bash -pnpm run cli -- entity-update "TRIZ" --type methodology --description "Updated description" +pnpm run cli -- entity-update "TRIZ" -d "Updated description" ``` ---- +| Option | Description | +|--------|-------------| +| `-t, --type ` | New entity type | +| `-d, --description ` | New description | ### `entity-delete ` -Delete an entity and all its cascading data (claims, notes, links). +Delete an entity and cascade (claims, links, notes). ```bash -pnpm run cli -- entity-delete "Old Entity" +pnpm run cli -- entity-delete "TRIZ" ``` ---- +## Claim Commands ### `claim-create ` -Create a claim (assertion) about an entity. +Create a claim for an entity. -**Options:** +```bash +pnpm run cli -- claim-create "TRIZ" "TRIZ has 40 inventive principles" -c 0.95 +``` + +| Option | Description | Default | +|--------|-------------|---------| +| `-c, --confidence ` | Confidence score (0–1) | `1.0` | -| Flag | Description | Default | -|------|-------------|---------| -| `-c, --confidence ` | Confidence score (0.0–1.0) | `1.0` | +## Note Commands + +### `note-create ` + +Create a note for an entity. ```bash -pnpm run cli -- claim-create "TRIZ" "TRIZ was developed by Genrich Altshuller" --confidence 0.95 +pnpm run cli -- note-create "TRIZ" "Key insight: separation principles" ``` ---- +### `note-list ` -### `link-create ` +List notes for an entity. -Create a relationship link between two entities. +```bash +pnpm run cli -- note-list "TRIZ" +``` + +## Link Commands -**Options:** +### `link-create ` -| Flag | Description | Default | -|------|-------------|---------| -| `-r, --relation ` | Relation type | `related` | +Create a directed link between two entities. ```bash -pnpm run cli -- link-create "TRIZ" "Genrich Altshuller" --relation "created_by" +pnpm run cli -- link-create "TRIZ" "Innovation" -r "inspires" ``` ---- +| Option | Description | Default | +|--------|-------------|---------| +| `-r, --relation ` | Relation type | `related` | ### `link-list` -List all links in the database. +List all links with resolved entity names. ```bash pnpm run cli -- link-list ``` -Output: `[id] source --[relation]--> target` per line. - ---- - ### `link-delete ` -Delete a link by its ID. +Delete a link by ID. ```bash -pnpm run cli -- link-delete +pnpm run cli -- link-delete "abc-123" ``` ---- +## Search Commands -### `note-create ` +### `search ` -Create a note attached to an entity. +Full-text search entities using FTS5. ```bash -pnpm run cli -- note-create "TRIZ" "Key insight: contradictions drive innovation" +pnpm run cli -- search "inventive principles" ``` ---- +### `snapshot-list` -### `note-list ` +List all graph snapshots. + +```bash +pnpm run cli -- snapshot-list +``` + +## Export Commands + +### `export` -List all notes for an entity. +Export knowledge base data. ```bash -pnpm run cli -- note-list "TRIZ" +pnpm run cli -- export -f md -o ./export +pnpm run cli -- export -f json -o ./export +pnpm run cli -- export -f site -o ./export +pnpm run cli -- export -f pdf -o ./export ``` ---- +| Option | Description | Default | +|--------|-------------|---------| +| `-f, --format ` | Export format: `md`, `json`, `site`, `pdf` | `md` | +| `-o, --output ` | Output directory | `./export` | -### `snapshot-list` +### `import ` -List all saved graph snapshots. +Import from JSON or Markdown file. ```bash -pnpm run cli -- snapshot-list +pnpm run cli -- import knowledge.json +pnpm run cli -- import notes.md ``` ---- +## Database Commands ### `db:migrate` @@ -243,68 +172,26 @@ Run pending database migrations. pnpm run cli -- db:migrate ``` ---- - ### `db:rollback` -Roll back the last applied migration. +Rollback the last applied migration. ```bash pnpm run cli -- db:rollback ``` ---- - ### `db:status` -Show the status of all migrations (applied or pending). +Show migration status for all migrations. ```bash pnpm run cli -- db:status ``` ---- - -### `db:backup [path]` - -Create a backup of the SQLite database using `VACUUM INTO`. - -```bash -pnpm run cli -- db:backup # Default: .studio-cli-backup-.db -pnpm run cli -- db:backup ./backups/my.db # Custom path -``` - ---- - ### `db:reset` -**Destructive.** Drop all tables and re-run the schema from scratch. +Reset database (drop all tables and re-run schema). **Destructive operation.** ```bash pnpm run cli -- db:reset ``` - ---- - -## Sharing Data Between CLI and Browser - -To see CLI-created data in the browser app: - -1. Open the app in Chrome or Edge -2. Go to **AI Harness** → click the **Settings** (gear) icon -3. Click **Connect Local Database** -4. Select the database directory (usually `~/.local/share/do-knowledge-studio/`) -5. Reload the page when prompted - -The browser synchronizes its OPFS storage with the `data.db` file in that directory. - ---- - -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| `Database not initialized` | Ensure `--db-path` points to a valid SQLite file, or run `init` first | -| `Entity not found` | Use `entity-list` to verify the entity name (case-sensitive) | -| `Sync found 0 files` | Ensure the directory contains `.md` files with H1 headings | -| `Backup failed` | Check write permissions for the output directory | diff --git a/docs/DATABASE.md b/docs/DATABASE.md index b84302d..233cdc9 100644 --- a/docs/DATABASE.md +++ b/docs/DATABASE.md @@ -1,237 +1,148 @@ # Database Schema -`do-knowledge-studio` uses **SQLite** as its primary storage layer: -- **Browser**: SQLite WASM with OPFS (Origin Private File System) via a Web Worker pool -- **CLI**: `better-sqlite3` for Node.js access - -The same schema and migrations run in both environments. - ---- - -## Entity-Relationship Diagram - -``` -┌─────────────────────┐ ┌─────────────────────┐ -│ entities │ │ claims │ -├─────────────────────┤ ├─────────────────────┤ -│ id UUID PK │◄──┐ │ id UUID PK │ -│ name TEXT UQ │ │ │ entity_id UUID FK │──┐ -│ type TEXT │ │ │ statement TEXT │ │ -│ description TEXT │ │ │ evidence TEXT │ │ -│ source_url TEXT │ │ │ confidence REAL │ │ -│ metadata TEXT │ │ │ source TEXT │ │ -│ created_at DATETIME│ │ │ verification_status │ │ -│ updated_at DATETIME│ │ │ created_at DATETIME │ │ -└────────┬────────────┘ │ │ updated_at DATETIME │ │ - │ │ └─────────────────────┘ │ - │ │ │ - │ │ ┌─────────────────────┐ │ - │ │ │ notes │ │ - │ │ ├─────────────────────┤ │ - │ │ │ id UUID PK │ │ - │ ├───│ entity_id UUID FK │ │ - │ │ │ content TEXT │ │ - │ │ │ format TEXT │ │ - │ │ │ created_at DATETIME │ │ - │ │ │ updated_at DATETIME │ │ - │ │ └─────────────────────┘ │ - │ │ │ - │ │ ┌─────────────────────┐ │ - │ │ │ links │ │ - │ │ ├─────────────────────┤ │ - │ │ │ id UUID PK │ │ - ├────────────────┼───│ source_id UUID FK │ │ - │ ├───│ target_id UUID FK │ │ - │ │ │ relation TEXT │ │ - │ │ │ metadata TEXT │ │ - │ │ │ created_at DATETIME │ │ - │ │ │ updated_at DATETIME │ │ - │ │ └─────────────────────┘ │ - │ │ │ - │ │ ┌─────────────────────┐ │ - │ │ │ graph_snapshots │ │ - │ │ ├─────────────────────┤ │ - │ │ │ id UUID PK │ │ - │ │ │ name TEXT │ │ - │ │ │ nodes_json TEXT │ │ - │ │ │ edges_json TEXT │ │ - │ │ │ description TEXT │ │ - │ │ │ created_at DATETIME │ │ - │ │ └─────────────────────┘ │ - │ │ │ - │ │ ┌─────────────────────┐ │ - │ │ │ web_cache │ │ - │ │ ├─────────────────────┤ │ - │ │ │ url TEXT PK │ │ - │ │ │ content TEXT │ │ - │ │ │ format TEXT │ │ - │ │ │ title TEXT │ │ - │ │ │ resolved_at DATETIME│ │ - │ │ │ metadata TEXT │ │ - │ │ └─────────────────────┘ │ - │ │ │ - │ │ ┌─────────────────────┐ │ - │ │ │ schema_version │ │ - │ │ ├─────────────────────┤ │ - │ │ │ version INT PK │ │ - │ │ │ name TEXT │ │ - │ │ │ checksum TEXT │ │ - │ │ │ applied_at TEXT │ │ - │ │ └─────────────────────┘ │ - │ │ │ - └────────────────┘────────────────────────────┘ -``` - ---- +SQLite WASM + OPFS database with FTS5 full-text search. ## Tables ### `entities` -Central subjects of the knowledge base: people, concepts, projects, methodologies, etc. +Core knowledge entities (concepts, notes, people, projects). -| Column | Type | Constraints | Description | -|--------|------|-------------|-------------| -| `id` | UUID | PRIMARY KEY | Auto-generated UUID v4 | -| `name` | TEXT | NOT NULL, UNIQUE | Entity name (displayed everywhere) | -| `type` | TEXT | NOT NULL | Entity type (e.g. `concept`, `person`, `project`) | -| `description` | TEXT | — | Free-text description | -| `source_url` | TEXT | — | URL for auto-hydration via resolver | -| `metadata` | TEXT | — | JSON object for extensible metadata | -| `created_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | Creation timestamp | -| `updated_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | Last update timestamp | +| Column | Type | Constraints | +|--------|------|-------------| +| `id` | UUID | PRIMARY KEY | +| `name` | TEXT | NOT NULL, UNIQUE | +| `type` | TEXT | NOT NULL (`note`, `concept`, `person`, `project`) | +| `description` | TEXT | | +| `metadata` | TEXT | JSON string | +| `source_url` | TEXT | | +| `created_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | +| `updated_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | ### `claims` -Assertions made about entities, with confidence scoring and verification status. +Verifiable statements attached to entities. -| Column | Type | Constraints | Description | -|--------|------|-------------|-------------| -| `id` | UUID | PRIMARY KEY | Auto-generated UUID v4 | -| `entity_id` | UUID | NOT NULL, FK → entities(id) ON DELETE CASCADE | Parent entity | -| `statement` | TEXT | NOT NULL | The claim text | -| `evidence` | TEXT | — | Supporting evidence | -| `confidence` | REAL | DEFAULT 1.0, CHECK (0–1) | Confidence score | -| `source` | TEXT | — | Source reference | -| `verification_status` | TEXT | DEFAULT 'unverified', CHECK (unverified/verified/disputed) | Verification state | -| `created_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | Creation timestamp | -| `updated_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | Last update timestamp | +| Column | Type | Constraints | +|--------|------|-------------| +| `id` | UUID | PRIMARY KEY | +| `entity_id` | UUID | NOT NULL, FK → entities(id) CASCADE | +| `statement` | TEXT | NOT NULL | +| `evidence` | TEXT | | +| `confidence` | REAL | DEFAULT 1.0, CHECK (0–1) | +| `source` | TEXT | | +| `verification_status` | TEXT | DEFAULT 'unverified', CHECK ('unverified', 'verified', 'disputed') | +| `created_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | +| `updated_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | ### `notes` -Free-form text attached to entities. Supports markdown format. +Free-form notes attached to entities. -| Column | Type | Constraints | Description | -|--------|------|-------------|-------------| -| `id` | UUID | PRIMARY KEY | Auto-generated UUID v4 | -| `entity_id` | UUID | FK → entities(id) ON DELETE SET NULL | Parent entity (nullable) | -| `content` | TEXT | NOT NULL | Note content | -| `format` | TEXT | DEFAULT 'markdown' | Content format | -| `created_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | Creation timestamp | -| `updated_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | Last update timestamp | +| Column | Type | Constraints | +|--------|------|-------------| +| `id` | UUID | PRIMARY KEY | +| `entity_id` | UUID | FK → entities(id) SET NULL | +| `content` | TEXT | NOT NULL | +| `format` | TEXT | DEFAULT 'markdown' | +| `created_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | +| `updated_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | ### `links` Directed relationships between entities. -| Column | Type | Constraints | Description | -|--------|------|-------------|-------------| -| `id` | UUID | PRIMARY KEY | Auto-generated UUID v4 | -| `source_id` | UUID | NOT NULL, FK → entities(id) ON DELETE CASCADE | Source entity | -| `target_id` | UUID | NOT NULL, FK → entities(id) ON DELETE CASCADE | Target entity | -| `relation` | TEXT | NOT NULL | Relationship type (e.g. `related`, `created_by`) | -| `metadata` | TEXT | — | JSON object for extensible metadata | -| `created_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | Creation timestamp | -| `updated_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | Last update timestamp | +| Column | Type | Constraints | +|--------|------|-------------| +| `id` | UUID | PRIMARY KEY | +| `source_id` | UUID | NOT NULL, FK → entities(id) CASCADE | +| `target_id` | UUID | NOT NULL, FK → entities(id) CASCADE | +| `relation` | TEXT | NOT NULL | +| `metadata` | TEXT | JSON string | +| `created_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | +| `updated_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | ### `graph_snapshots` -Saved states of the knowledge graph visualization. +Saved graph states for comparison. -| Column | Type | Constraints | Description | -|--------|------|-------------|-------------| -| `id` | UUID | PRIMARY KEY | Auto-generated UUID v4 | -| `name` | TEXT | NOT NULL | Snapshot name | -| `nodes_json` | TEXT | NOT NULL | Serialized graph nodes | -| `edges_json` | TEXT | NOT NULL | Serialized graph edges | -| `description` | TEXT | — | Optional description | -| `created_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | Creation timestamp | +| Column | Type | Constraints | +|--------|------|-------------| +| `id` | UUID | PRIMARY KEY | +| `name` | TEXT | NOT NULL | +| `nodes_json` | TEXT | NOT NULL (JSON array) | +| `edges_json` | TEXT | NOT NULL (JSON array) | +| `description` | TEXT | | +| `created_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | ### `web_cache` -Offline-ready cache for resolved external URLs. +Cached web content for entity hydration. -| Column | Type | Constraints | Description | -|--------|------|-------------|-------------| -| `url` | TEXT | PRIMARY KEY | The resolved URL | -| `content` | TEXT | NOT NULL | Cached content | -| `format` | TEXT | DEFAULT 'markdown' | Content format | -| `title` | TEXT | — | Page title | -| `resolved_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | When the URL was resolved | -| `metadata` | TEXT | — | JSON: `{ content_length, word_count, provider, quality_score }` | +| Column | Type | Constraints | +|--------|------|-------------| +| `url` | TEXT | PRIMARY KEY | +| `content` | TEXT | NOT NULL | +| `format` | TEXT | DEFAULT 'markdown' | +| `title` | TEXT | | +| `resolved_at` | DATETIME | DEFAULT CURRENT_TIMESTAMP | +| `metadata` | TEXT | JSON string | ### `schema_version` -Tracks applied database migrations. - -| Column | Type | Constraints | Description | -|--------|------|-------------|-------------| -| `version` | INTEGER | PRIMARY KEY | Migration version number | -| `name` | TEXT | NOT NULL | Migration name | -| `checksum` | TEXT | NOT NULL | Content hash for tamper detection | -| `applied_at` | TEXT | NOT NULL | When the migration was applied | - ---- +Migration tracking. -## Search Tables +| Column | Type | Constraints | +|--------|------|-------------| +| `version` | INTEGER | PRIMARY KEY | +| `name` | TEXT | NOT NULL | +| `checksum` | TEXT | NOT NULL | +| `applied_at` | TEXT | DEFAULT datetime('now') | -### `entity_search_idx` (FTS5) +## Virtual Tables (FTS5) -Full-text search index for entities. Uses porter stemming and unicode61 tokenizer in contentless mode (no positional info for ~2x faster queries). +### `entity_search_idx` -**Indexed columns:** `name`, `description` +Full-text search index for entity names and descriptions. -### `claim_search_idx` (FTS5) - -Full-text search index for claims. - -**Indexed columns:** `statement` - ---- +```sql +CREATE VIRTUAL TABLE entity_search_idx USING fts5( + name, description, + tokenize='porter unicode61', + detail=none, content='' +); +``` -## Search Architecture +### `claim_search_idx` -The app uses a **dual search system**: +Full-text search index for claim statements. -1. **FTS5 (SQLite)** — Exact keyword matching with porter stemming. Used as the first search stage. -2. **Orama (in-memory)** — Fuzzy and semantic search. Hydrated from SQLite on app startup. +```sql +CREATE VIRTUAL TABLE claim_search_idx USING fts5( + statement, + tokenize='porter unicode61', + detail=none, content='' +); +``` -Search is progressive: exact → semantic → related entities. +## Indexes ---- +| Index | Table | Columns | +|-------|-------|---------| +| `idx_claims_entity_id` | claims | entity_id | +| `idx_claims_verification_status` | claims | verification_status | +| `idx_links_source_id` | links | source_id | +| `idx_links_target_id` | links | target_id | +| `idx_notes_entity_id` | notes | entity_id | +| `idx_graph_snapshots_created_at` | graph_snapshots | created_at | +| `idx_web_cache_resolved_at` | web_cache | resolved_at | ## Migrations -Migrations live in `public/db/migrations/` and are numbered sequentially: +Located in `public/db/migrations/`. Run with `pnpm run cli -- db:migrate`. -| Version | File | Description | +| Version | Name | Description | |---------|------|-------------| -| 1 | `001_initial.sql` | Creates all base tables and FTS5 indexes | -| 2 | `002_constraints.sql` | Adds foreign key constraints and indexes | -| 3 | `003_entity_source_url.sql` | Adds `source_url` column to entities | - -Migrations run automatically on database initialization. Use `pnpm run cli -- db:status` to check status, `pnpm run cli -- db:migrate` to run pending migrations, and `pnpm run cli -- db:rollback` to revert the last migration. - ---- - -## Indices - -| Table | Column | Purpose | -|-------|--------|---------| -| `claims` | `entity_id` | Fast lookup of claims by entity | -| `claims` | `verification_status` | Filter by verification state | -| `links` | `source_id` | Fast lookup of outgoing links | -| `links` | `target_id` | Fast lookup of incoming links (backlinks) | -| `notes` | `entity_id` | Fast lookup of notes by entity | -| `graph_snapshots` | `created_at` | Chronological snapshot ordering | -| `web_cache` | `resolved_at` | Cache expiration queries | +| 1 | initial | Core tables and FTS5 indexes | +| 2 | constraints | UNIQUE(name), CHECK constraints, additional indexes | +| 3 | entity_source_url | Add source_url column to entities | diff --git a/docs/REPOSITORY.md b/docs/REPOSITORY.md new file mode 100644 index 0000000..11197f1 --- /dev/null +++ b/docs/REPOSITORY.md @@ -0,0 +1,343 @@ +# Repository API + +The `IRepository` interface (`src/db/repository/types.ts`) provides the data access layer for Knowledge Studio. + +## Import + +```typescript +import { repository } from '../../db/repository'; +import type { IRepository } from '../../db/repository'; +``` + +## Core Methods + +### `exec(options)` + +Execute raw SQL. + +```typescript +await repository.exec({ sql: 'SELECT 1' }); +``` + +### `execRows(options)` + +Execute SQL and return parsed rows. + +```typescript +const rows = await repository.execRows({ + sql: 'SELECT * FROM entities WHERE type = ?', + bind: ['concept'], + returnValue: 'resultRows', + rowMode: 'object', +}); +``` + +### `transaction(statements)` + +Execute multiple statements in a transaction. + +```typescript +await repository.transaction([ + { sql: 'INSERT INTO entities ...' }, + { sql: 'INSERT INTO claims ...' }, +]); +``` + +## Entity Methods + +### `createEntity(entity)` + +```typescript +const entity = await repository.createEntity({ + name: 'TRIZ', + type: 'concept', + description: 'Theory of Inventive Problem Solving', +}); +// Returns: Entity & { rowid: number } +``` + +### `getAllEntities(options?)` + +```typescript +const entities = await repository.getAllEntities({ limit: 100, offset: 0 }); +``` + +### `getEntities(options?)` + +```typescript +const entities = await repository.getEntities({ + search: 'TRIZ', + type: 'concept', + sortBy: 'name', + sortOrder: 'ASC', + limit: 50, +}); +``` + +### `getEntitiesCount(options?)` + +```typescript +const count = await repository.getEntitiesCount({ type: 'concept' }); +``` + +### `getEntityById(id)` + +```typescript +const entity = await repository.getEntityById('uuid-here'); +// Returns: (Entity & { rowid: number }) | null +``` + +### `getEntityByName(name)` + +```typescript +const entity = await repository.getEntityByName('TRIZ'); +// Returns: Entity | null +``` + +### `updateEntity(id, entity)` + +```typescript +const updated = await repository.updateEntity('uuid-here', { + description: 'Updated description', +}); +``` + +### `deleteEntity(id)` + +```typescript +await repository.deleteEntity('uuid-here'); +// Cascades to claims, links, notes +``` + +### `searchEntities(query)` + +```typescript +const results = await repository.searchEntities('inventive principles'); +``` + +### `searchRelated(query, options?)` + +```typescript +const related = await repository.searchRelated('innovation', { + excludeIds: new Set(['uuid1', 'uuid2']), +}); +``` + +## Claim Methods + +### `createClaim(claim)` + +```typescript +const claim = await repository.createClaim({ + entity_id: 'uuid-here', + statement: 'TRIZ has 40 inventive principles', + confidence: 0.95, + verification_status: 'verified', +}); +``` + +### `getClaimsByEntityId(entity_id)` + +```typescript +const claims = await repository.getClaimsByEntityId('uuid-here'); +``` + +### `getAllClaims()` + +```typescript +const claims = await repository.getAllClaims(); +``` + +### `getAllClaimsGroupedByEntity()` + +```typescript +const grouped = await repository.getAllClaimsGroupedByEntity(); +// Returns: Record +``` + +### `getAllEntitiesWithClaims()` + +```typescript +const map = await repository.getAllEntitiesWithClaims(); +// Returns: Map +``` + +### `updateClaim(id, claim)` + +```typescript +const updated = await repository.updateClaim('uuid-here', { + confidence: 0.9, + verification_status: 'disputed', +}); +``` + +### `updateClaimVerification(claimId, status)` + +```typescript +const updated = await repository.updateClaimVerification('uuid-here', 'verified'); +``` + +### `getClaimsByVerificationStatus(status)` + +```typescript +const unverified = await repository.getClaimsByVerificationStatus('unverified'); +``` + +### `deleteClaim(id)` + +```typescript +await repository.deleteClaim('uuid-here'); +``` + +## Note Methods + +### `createNote(note)` + +```typescript +const note = await repository.createNote({ + entity_id: 'uuid-here', + content: 'Key insight about TRIZ', +}); +``` + +### `getAllNotes()` + +```typescript +const notes = await repository.getAllNotes(); +``` + +### `getNotesByEntityId(entity_id)` + +```typescript +const notes = await repository.getNotesByEntityId('uuid-here'); +``` + +### `getAllNotesGroupedByEntity()` + +```typescript +const grouped = await repository.getAllNotesGroupedByEntity(); +// Returns: Record +``` + +### `updateNote(id, note)` + +```typescript +const updated = await repository.updateNote('uuid-here', { + content: 'Updated note content', +}); +``` + +### `deleteNote(id)` + +```typescript +await repository.deleteNote('uuid-here'); +``` + +## Link Methods + +### `createLink(link)` + +```typescript +const link = await repository.createLink({ + source_id: 'uuid1', + target_id: 'uuid2', + relation: 'inspires', +}); +``` + +### `getAllLinks(options?)` + +```typescript +const links = await repository.getAllLinks({ limit: 100, offset: 0 }); +``` + +### `getBacklinks(entityId)` + +```typescript +const backlinks = await repository.getBacklinks('uuid-here'); +// Returns entities that link TO this entity +``` + +### `getBacklinkCount(entityId)` + +```typescript +const count = await repository.getBacklinkCount('uuid-here'); +``` + +### `deleteLink(id)` + +```typescript +await repository.deleteLink('uuid-here'); +``` + +## Web Cache Methods + +### `upsertWebCache(url, content, title?, format?)` + +```typescript +await repository.upsertWebCache( + 'https://example.com', + 'Page content...', + 'Page Title', + 'markdown' +); +``` + +### `getWebCache(url)` + +```typescript +const cached = await repository.getWebCache('https://example.com'); +// Returns: { url, content, format, title, resolved_at } | null +``` + +## Graph Snapshot Methods + +### `createSnapshot(name, nodes, edges, description?)` + +```typescript +const snapshot = await repository.createSnapshot( + 'Graph v1', + [{ id: 'n1', label: 'TRIZ' }, { id: 'n2', label: 'Innovation' }], + [{ id: 'e1', source: 'n1', target: 'n2', label: 'inspires' }], + 'Initial graph state' +); +``` + +### `getSnapshot(id)` + +```typescript +const snapshot = await repository.getSnapshot('uuid-here'); +``` + +### `listSnapshots()` + +```typescript +const snapshots = await repository.listSnapshots(); +``` + +### `diffSnapshots(id1, id2)` + +```typescript +const diff = await repository.diffSnapshots('uuid1', 'uuid2'); +// Returns: { added_nodes, removed_nodes, added_edges, removed_edges } +``` + +## Types + +```typescript +interface RankedResult { + id: string; + title: string; + type: string; + content: string; + score: number; + stage: string; +} + +interface GraphSnapshotDiff { + added_nodes: string[]; + removed_nodes: string[]; + added_edges: string[]; + removed_edges: string[]; +} +```