Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: add Elasticsearch full-text search provider (#18807)

YuTengjingd74e8971918c
diff --git a/.agents/skills/db-migrations/SKILL.md b/.agents/skills/db-migrations/SKILL.md
index a53f1e193f8..a4e18c955e6 100644
--- a/.agents/skills/db-migrations/SKILL.md
+++ b/.agents/skills/db-migrations/SKILL.md
@@ -29,6 +29,18 @@ Apply these before generating any migration — they change what the schema file
Classify every database change into one of these three rollout paths before generating or editing a migration.
+### Validate rollout assumptions on the actual Dev database
+
+Do not choose a rollout path from hypothetical claims such as “this migration might be slow” or “installing these triggers could block deployment.” Before deciding that a schema change needs a manual production step, deferred installation, or a dedicated backfill, test the relevant operation against the project's actual Dev database.
+
+- Classify the database target first using the project's approved database-access tooling; never read secret-bearing `.env` files directly.
+- Measure the real operation or the closest safe equivalent, such as creating an identically defined probe index under a temporary name or installing temporary triggers inside a transaction that is rolled back.
+- Record the tested SQL or operation, representative row count and table size, elapsed time, and cleanup verification.
+- Keep probes reversible and remove every temporary database object after the measurement.
+- Treat a single Dev result as evidence about the observed Dev scale, not proof of production behavior. State material differences in production scale, load, cache state, and lock contention explicitly, and label any resulting production claim as an inference.
+
+Rollout decisions must combine repository deployment facts with these measurements. Do not add operational tables, delayed activation paths, or manual release steps solely to guard against unmeasured performance concerns.
+
### 1. Regular Drizzle migration
Use the normal Drizzle workflow for schema changes that are safe to execute during deployment, such as creating a small table or adding a nullable column:
diff --git a/.agents/skills/deep-review/SKILL.md b/.agents/skills/deep-review/SKILL.md
index 2760c04ae81..6b8cc18e65b 100644
--- a/.agents/skills/deep-review/SKILL.md
+++ b/.agents/skills/deep-review/SKILL.md
@@ -1,11 +1,11 @@
---
name: deep-review
-description: 'Multi-dimensional code review. Use when the user asks to review, evaluate, or audit a PR, diff, branch, or pasted change — including informal review asks like "look at this change for problems" — via light mode: inline review against the dimension quick checklists. Not for explain-only questions about what a change does or why. Deep mode runs only on explicit invocation (/deep-review): independent dimension coverage, adversarial verification, and global duplicate consolidation before reporting.'
+description: 'Multi-dimensional code review. Use when the user asks to review, evaluate, or audit a PR, diff, branch, or pasted change — including informal review asks like "look at this change for problems" — via light mode: one independent reviewer against the dimension quick checklists. Not for explain-only questions about what a change does or why. Deep mode runs only on explicit invocation (/deep-review), and normally at most once per logical requirement.'
---
# Deep Review
-Multi-dimensional code review built on independent subagents. Review breadth comes from parallel
+Multi-dimensional code review built on independent reviewers. Review breadth comes from parallel
dimension coverage; precision comes from adversarial verification and global duplicate
consolidation before findings reach the report.
@@ -14,26 +14,37 @@ consolidation before findings reach the report.
Every design choice below serves one of these. When unsure how to execute a step, come back here.
1. **Anti-hallucination** — reviewers that only see diff fragments invent bugs. Candidate findings are therefore falsified one by one by an **independent verify subagent** that reads full context and returns a three-way verdict (`confirmed` / `false_positive` / `need_more_context`). Three-way verdicts beat confidence percentages: calibrated-sounding scores are unreliable as hard filters.
-2. **Anti self-approval** — an agent that just wrote the code is grading its own homework and will pass it. Review must run in **independent subagents** with a third-party reviewer stance. Never silently degrade deep mode to "the main agent reviews and then verifies its own findings".
+2. **Anti self-approval** — an agent that just wrote the code is grading its own homework and will pass it. Both modes use an **independent reviewer** with a third-party stance. Light: one reviewer that is not the main agent. Deep: independent subagents per the environment manual. Never silently degrade either mode to "the main agent reviews the diff itself".
3. **Rules over model** — review quality comes from fine-grained, executable dimension rules, not from a smarter model. Subagents run on balanced/fast model tiers; each dimension file tells them exactly how to check, what counts, and what does not.
4. **Calibrate to codebase and lifespan** — hold the diff to the standard the codebase already meets, not an idealized one. If a pattern is widespread in the existing code and this diff does not make it worse, it is not a finding. Declared-temporary code (time-boxed campaign, experiment, one-off script) is judged against its lifespan: hardcoding and low-extensibility shortcuts are the intended trade-off for shipping fast, and "delete the code at expiry" is a valid plan — do not demand configurability from code built to be deleted. (Security is exempt from all calibration — see the dimension file.)
5. **Speed is a feature** — one wave of parallel reviewers, verification pipelined per dimension (never a global barrier), irrelevant dimensions pruned up front.
## Two entry modes
-| Mode | Trigger | What runs |
-| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
-| **Light** (default) | Any ordinary review ask: "review this PR", an informal "look at this change for problems", a diff pasted for review — but not explain-only questions about a change | Main agent reviews inline against the **Quick checklist** section of each applicable dimension file. No subagents. |
-| **Deep** | Explicit only: `/deep-review`, "run deep review", "full multi-agent review" | Full orchestration: dimension review agents → pipelined verification → global consolidation → structured report → interactive fix flow. |
+| Mode | Trigger | What runs |
+| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **Light** (default) | Any ordinary review ask: "review this PR", an informal "look at this change for problems", a diff pasted for review — but not explain-only questions about a change | One independent reviewer against the **Quick checklist** of each applicable dimension. Prefer a different-vendor harness when the session can dispatch to one; otherwise one same-harness subagent. No verify pass. The main agent does not review. |
+| **Deep** | Explicit only: `/deep-review`, "run deep review", "full multi-agent review" | Full orchestration: dimension review agents → pipelined verification → global consolidation → structured report → interactive fix flow. |
Do not auto-escalate light to deep. Do not run deep mode for a casual "看看这个改动" — that is light mode.
+### Deep-mode budget
+
+Within one logical requirement (the same requirement, PR, or branch), run Deep mode at most once by
+default. Follow-up reviews after fixes, CI work, rebases, cleanup, context compaction, or a resumed
+session use Light mode, even when they review the whole diff again. These events do not reset the
+budget, and the review/verify/consolidate waves inside one Deep run all count as that single run.
+
+Run Deep again only when the user explicitly requests another Deep pass, or when a genuinely new
+logical requirement begins. A casual follow-up such as "review again", "复核一下", or "再看看" is a
+Light request, not implicit authorization for another Deep run.
+
## Dimensions
Rules live in one place: [`references/dimensions/`](references/dimensions/), one file per dimension.
-Both modes read the same files. Light mode reads the full `Quick checklist` section, including
-nested example subsections; deep-mode agents read the full dimension file plus only the rule
-sources and routed references applicable to the touched surface.
+Both modes use the same files. The light reviewer reads the full `Quick checklist` section,
+including nested example subsections; deep-mode agents read the full dimension file plus only the
+rule sources and routed references applicable to the touched surface.
| Dimension | id prefix | Covers | Verified? |
| --------------------------------------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
@@ -41,6 +52,7 @@ sources and routed references applicable to the touched surface.
| [code-style](references/dimensions/code-style.md) | `style` | naming, readability, dead code, comments, i18n hardcoding, UI-library and styling conventions | yes |
| [logic](references/dimensions/logic.md) | `logic` | logic correctness: edge cases, null, races, error handling, state machines, requirement deviation, test coverage | yes |
| [business-logic](references/dimensions/business-logic.md) | `design` | design judgment: framework misuse, best-practice violations, solution-weight mismatch, self-inflicted complexity | yes |
+| [new-feature](references/dimensions/new-feature.md) | `feature` | new-capability design: domain vocabulary and structure, durable data model and migration evidence, product analytics and operational observability | yes |
| [reuse-architecture](references/dimensions/reuse-architecture.md) | `reuse` | duplicate implementations, unused existing patterns, extensibility, architectural boundaries | yes |
| [performance](references/dimensions/performance.md) | `perf` | N+1, blocking calls, resource leaks, render-path waste, **DB migration locking and idempotency** | yes |
| [release-risk](references/dimensions/release-risk.md) | `risk` | ship/no-ship gate: irreversible persisted state (incl. schemaless shape drift), dev-cycle migration residue, in-flight work & config at deploy time, irreversible outbound effects, prompt/tool-description behavior shifts, shared-surface and high-frequency-UI blast radius, PR purity | yes + checks |
@@ -60,6 +72,7 @@ Before spawning, the main agent prunes dimensions that cannot apply to the diff.
| Dimension | Skip when |
| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| ai-coding-bad-habits, code-style, logic, business-logic, reuse-architecture | never (skip only for docs/lockfile-only diffs) |
+| new-feature | diff does not introduce a new product, operator, or platform capability |
| performance | no server/db/loop/render-path code touched (e.g. docs, copy, pure type changes) |
| release-risk | no DB schema/migration, no schemaless persisted payload, no queue/cron/config/outbound dependency, no prompt or tool-description text, no shared component or package public API, no high-frequency user surface, and the diff has one obvious purpose |
| security | lockfile/generated-only diff — docs and copy still run it (text is a leak vector: secrets, internal URLs, commercial details) |
@@ -71,7 +84,7 @@ Before spawning, the main agent prunes dimensions that cannot apply to the diff.
**"Docs-only" means human-facing prose only.** Files that are executable instructions for agents — `.agents/skills/**`, `AGENTS.md` / `CLAUDE.md`, prompt templates, orchestration manuals — count as code for pruning purposes: their "prose" carries control flow, contracts, and rules whose contradictions are exactly what logic / business-logic / reuse-architecture exist to catch. A diff touching them is never docs-only.
-Light mode applies the same table to decide which Quick checklists to read.
+Light mode applies the same table to decide which Quick checklists to pass to the reviewer.
## Extension packs
@@ -84,26 +97,29 @@ A wrapping repository (e.g. a private deployment that vendors this repo as a sub
## Light mode procedure
+If your user message is already an instantiated light-review prompt, you are the reviewer — follow
+that prompt and do not re-enter this procedure.
+
1. Determine review scope exactly as deep mode step 0 does (see the environment manual's scope rules — three-dot diff from a base that does not lag the fork point, submodule diffs included), but skip the background-hunting extras when context already tells you what changed.
-2. Apply the pruning table; read the `Quick checklist` section of each surviving dimension file, plus extension-pack counterparts.
-3. Review inline. Findings must cite a rule source or code evidence; respect the codebase-calibration principle.
- - On a follow-up round (verifying that earlier findings were fixed), review the newly changed code as a fresh diff under the same checklists — never just confirm the requested edits landed. Fix commits introduce new logic (guards, parsers, refactors) whose bugs a checkbox pass will miss.
-4. Label every finding on the same two axes deep mode uses, and let them drive the recommendation:
- - **Severity** — use only P0 (incident-level impact), P1 (must fix in this change), or P2
- (real but deferrable). Never invent additional levels. State whether each finding blocks
- release.
- - **Introduced or pre-existing** — if the problem lives in code this diff did not change, do not fix it here. Say who introduced it (`git blame` / `git log -L` on the location) and offer to file a Linear issue for that owner. The only exception is an old bug this diff makes reachable or harmful for the first time, at P0.
- - **Likelihood** — high / medium / low, judged on the real production path. State it next to the severity. A `low`-likelihood, non-blocking finding is a follow-up, not a fix-now item; on a repeat review of the same change, list it in one line and move on instead of re-arguing it.
-5. Output in your environment's normal review format (light mode does NOT use the deep report template). When `release-risk` produced pre-deploy confirmation items, list them as a short checklist separate from the findings — they are questions about production state, not defects. Mention that deep mode exists if findings suggest the diff deserves a full pass.
+2. Apply the pruning table; collect the surviving dimension files plus extension-pack counterparts. Do not read the checklists yourself.
+3. Instantiate [`references/light-review-prompt.md`](references/light-review-prompt.md) with the surviving `{dimensions}`, `{dimension_files}`, `{scope_summary}`, and `{changes}`. Dispatch exactly one independent reviewer, trying in this order:
+ 1. If this session can dispatch a self-contained task to a different vendor's coding-agent harness (not a same-harness subagent), use that. Prefer a preset whose job is independent code review when the dispatcher exposes one.
+ 2. Otherwise spawn one same-harness subagent. Disable context inheritance when the spawn API allows it.
+ 3. If the chosen path fails, try the next. If none work, stop and tell the user why. Do not review the diff yourself.
+4. Relay the reviewer's findings in your environment's normal review format (light mode does NOT use the deep report template). Do not drop, downgrade, or re-verify findings. When the reviewer listed pre-deploy confirmation items, keep them as a short checklist separate from defects. Mention that deep mode exists if findings suggest the diff deserves a full pass.
+ - On a follow-up round (verifying that earlier findings were fixed), dispatch again on the newly changed code as a fresh diff — never just confirm the requested edits landed. Fix commits introduce new logic (guards, parsers, refactors) whose bugs a checkbox pass will miss.
## Deep mode procedure
+Before entering this procedure, check the logical requirement's Deep-mode budget above. If Deep has
+already run and the user did not explicitly request another Deep pass, use the Light procedure.
+
Pick the manual for the current environment and follow it end to end:
- **Claude Code** → [`references/claude-code/main.md`](references/claude-code/main.md)
- **Codex** → [`references/codex/main.md`](references/codex/main.md)
-If the environment is not listed, tell the user deep mode does not support it yet and offer light mode instead. Do not improvise another environment's mechanics, and do not degrade to a single-agent pass (see principle 2).
+If the environment is not listed, tell the user deep mode does not support it yet and offer light mode instead. Do not improvise another environment's mechanics, and do not simulate deep in the main agent or as one packed reviewer (see principle 2).
## Keeping this skill sharp
diff --git a/.agents/skills/deep-review/references/dimensions/new-feature.md b/.agents/skills/deep-review/references/dimensions/new-feature.md
new file mode 100644
index 00000000000..abff8e3f03b
--- /dev/null
+++ b/.agents/skills/deep-review/references/dimensions/new-feature.md
@@ -0,0 +1,116 @@
+---
+id_prefix: feature
+verify: true
+skip_when: diff does not introduce a new product, operator, or platform capability
+---
+
+# New Feature Design
+
+Review a new capability as one coherent product and domain model before judging its individual
+files. This dimension covers design completeness that can look locally correct in every layer while
+the feature as a whole uses the wrong concepts, persists the wrong state, or cannot answer whether
+it works after release.
+
+Do not run this dimension for a pure bug fix, refactor, deletion, or documentation change. A new
+provider, backend, workflow, operator tool, or self-hosted capability counts as a feature even when
+it does not add a new UI.
+
+## Quick checklist
+
+### Domain model, naming, and structure
+
+- The capability should be statable in one sentence with clear domain nouns. Names across
+ interfaces, implementations, configuration, jobs, telemetry, database objects, and docs must use
+ the same vocabulary.
+- Distinguish the capability from its implementation/provider and from its operational lifecycle.
+ A provider-specific implementation must not use a broader platform name that implies behavior it
+ does not provide. Compare sibling implementations as one naming system, not one symbol at a time.
+- Check the nearest same-kind feature and the repository's domain skill before accepting new
+ folders, services, repositories, or configuration surfaces. When multiple repositories or layers
+ are possible, require an explicit product and engineering ownership decision; do not infer
+ placement solely from the current deployment, technical portability, or lack of secrecy.
+- Model capability availability separately from implementation/provider choice. Feature flags add
+ or remove a capability; do not turn them into a multi-value provider or operating-mode registry.
+ Temporary rollout flags need a removal condition, while a self-hosted product may deliberately
+ keep capability flags as durable customization.
+- Reserve dotted filename suffixes for established tool or runtime meanings such as `.test`,
+ `.server`, or `.desktop`; use the repository's folder or hyphen convention for ordinary grouping.
+
+### Database and lifecycle
+
+- Challenge every new table, column, index, trigger, and persisted status: what durable fact does it
+ own, who writes it, who consumes it, and when is it removed? Do not persist deployment or
+ installation state that is already derivable from the authoritative system.
+- Durable schema belongs in the normal migration path. Optional runtime installation is appropriate
+ only for objects whose existence genuinely depends on enabling the capability; instances that do
+ not enable the feature must not pay its ongoing write or operational cost.
+- For development-stage migrations, verify the schema, generated SQL, snapshot, and migration
+ history describe only the final model. Do not preserve compatibility with an unreleased draft.
+- When migration cost or locking changes the rollout plan, measure the actual operation or a
+ reversible equivalent on the project's actual Dev database. Record observed scale and duration,
+ and label production extrapolation as inference rather than fact.
+
+### Analytics and observability
+
+Scope boundary: whether each added event is well-shaped and well-placed belongs to `observability`;
+this section asks whether the feature as a whole can answer its outcome questions after release.
+
+- Name the questions the feature must answer after release. Cover user-perceived performance,
+ result/outcome quality, usage or continued intent, and the main failure mode where applicable;
+ avoid adding signals that have no decision attached.
+- Keep product analytics and backend telemetry separate: user events explain what people saw and
+ chose, while metrics/traces explain latency, errors, throughput, and resource cost. A backend span
+ alone cannot establish product quality or willingness to use the feature.
+- Instrument the real entry and completion points, including empty/abandoned outcomes when they
+ matter. Measurement failure must not change feature behavior.
+- Keep event properties and metric labels bounded and consent-aware. Never record raw user content,
+ search text, secrets, user IDs, document IDs, or other high-cardinality identifiers merely to make
+ debugging easier.
+- For a regression-prone main path, require one actionable alert tied to the user-visible failure
+ and a concrete threshold; do not demand alerts for every internal step.
+
+## Rule sources (deep mode: read before reviewing)
+
+- The requirement or issue that defines the new capability and its intended users
+- The nearest same-kind feature and its landing PR/commit
+- The directly matching domain skill under `.agents/skills/`
+- `.agents/skills/project-overview/SKILL.md` and repository `AGENTS.md` for ownership and structure
+- `.agents/skills/db-migrations/SKILL.md` and `.agents/skills/drizzle/SKILL.md` when schema changes
+- The observability and analytics paths used by the nearest same-kind feature
+
+## How to check
+
+1. Write a vocabulary map: capability, provider/variant, lifecycle operations, persisted entities,
+ and telemetry names. Search the diff and adjacent callers for competing terms.
+2. Draw the feature's complete path from entry point through runtime, persistence, background work,
+ recovery, configuration, and docs. Report missing or misplaced lifecycle pieces.
+3. For each database object, identify the durable fact and lifecycle it represents. Inspect the
+ generated migration and use approved Dev evidence before recommending manual rollout work.
+4. Turn every added event, metric, trace, and alert into a question it answers. Identify important
+ product questions with no signal and signals that have no plausible decision.
+
+## Violations
+
+- The feature's vocabulary or structure makes capability, provider, and lifecycle concepts
+ ambiguous across layers.
+- A database object has no necessary durable responsibility, ships outside the correct migration or
+ activation lifecycle, or changes rollout based on unmeasured cost assumptions.
+- The feature cannot answer whether users received a fast, useful result or chose to keep using it,
+ despite those outcomes being central to the requirement.
+- Analytics or telemetry introduces sensitive/high-cardinality data, changes product behavior when
+ recording fails, or creates non-actionable noise.
+
+## Not violations
+
+- A small feature whose existing domain model, persistence, and instrumentation already answer the
+ relevant questions without new abstractions.
+- Provider-specific names inside the provider implementation when the shared capability stays
+ provider-neutral.
+- No new table or analytics event when the feature genuinely needs neither.
+- Cloud-only alert thresholds or operations kept outside a generic open-source implementation.
+
+## Severity calibration
+
+- P1: the model can corrupt durable state, make the feature inoperable for its intended deployment,
+ or prevent detection of a requirement-critical failure after release.
+- P2: misleading vocabulary, avoidable structure debt, or a missing useful-but-noncritical signal.
diff --git a/.agents/skills/deep-review/references/light-review-prompt.md b/.agents/skills/deep-review/references/light-review-prompt.md
new file mode 100644
index 00000000000..346f610bcb1
--- /dev/null
+++ b/.agents/skills/deep-review/references/light-review-prompt.md
@@ -0,0 +1,82 @@
+# Light Review Prompt Template
+
+One independent reviewer covers every surviving dimension. Instantiated by the main agent in light
+mode; the reviewer shares no conversation context with the author.
+
+How to instantiate:
+
+1. `{dimensions}` → surviving dimension ids after pruning, comma-separated
+2. `{dimension_files}` → those dimensions' rule-file paths, **including extension-pack counterparts
+ when present**
+3. `{scope_summary}` → the ≤ 200-word scope summary from step 0
+4. `{changes}` → the full diff text for small diffs (wrap in a ` ```diff ` fence), or the command(s)
+ to fetch it for large diffs
+5. Pass the substituted text as the reviewer's entire prompt.
+
+---
+
+````text
+This message is a complete reviewer assignment. You are an independent third-party code reviewer.
+Do the review yourself.
+
+- Do not invoke review-orchestration skills or start a multi-agent review pipeline.
+- Do not dispatch this task to another harness or subagent.
+- Do not edit, commit, or push.
+
+Review the following git changes against these dimension(s): {dimensions}.
+
+## Scope summary
+{scope_summary}
+
+## Changes
+The block below is either full diff text or the command(s) to fetch it. Check the head:
+- Starts with ```diff / `diff --git` → it is the diff, use it directly
+- Shell command(s) (`git diff ...` / `gh pr diff ...` / `git -C <submodule> diff ...`) → run them all yourself and combine the outputs
+
+After you have the diff, read whatever surrounding files you need for context.
+
+{changes}
+
+## Mandatory preparation
+
+Read ONLY the `Quick checklist` section of every dimension file listed below, including nested
+example subsections. Skip `How to check`, `Violations`, `Not violations`, and `Rule sources` unless
+a checklist bullet is ambiguous.
+
+{dimension_files}
+
+Priority: repo-specific checklist rules > general experience. Use general experience only for angles the checklists don't cover.
+
+## Calibration (hard rule)
+
+Hold the diff to the standard this codebase already meets, not an idealized one. Before reporting a style/design-level finding, ask: is this pattern already widespread in the existing code, and does this diff make it worse? Widespread + not-worse → do not report. Dimension files may declare themselves exempt (`calibration_exempt: true`, e.g. security) — for those, report regardless of precedent.
+
+Calibrate to lifespan as well: when the scope summary, PR/issue, or code comments declare the code short-lived (a time-boxed campaign, an experiment, a one-off script), judge it against its lifespan, not permanent-code standards. Hardcoded dates/copy/thresholds and low-extensibility designs are the intended trade-off for shipping fast — do not demand configurability, extension points, or expiry automation; "delete the code and redeploy when it expires" is a legitimate expiry mechanism. Two things stay reportable in temporary code: `calibration_exempt` dimensions (security), and damage that outlives the window (wrong billing/credit/data writes that persist after the code is removed).
+
+Focus over completeness: findings must serve THIS change and its requirement. Do not audit unrelated legacy code, and do not propose rewrites beyond the change's scope.
+
+If this is a follow-up that earlier findings were fixed, review the new diff as a fresh review under the same checklists — never only confirm the requested edits landed.
+
+## Review scope (hard rules)
+
+- Findings must cite a rule source or code evidence.
+- Finding locations must land on `+` lines of the diff by default.
+- If the problem lives in code this diff did not change, do not treat it as a fix-in-this-change item. Name who introduced it (`git blame` / `git log -L` on the location) when you can. The only exception is an old bug this diff makes reachable or harmful for the first time, at P0.
+- Once a finding has concrete `file:line` evidence, stop expanding.
+
+## Labeling
+
+Every finding needs all of:
+
+- **Severity** — P0 (incident-level impact), P1 (must fix in this change), or P2 (real but deferrable). Never invent additional levels. State whether it blocks release.
+- **Introduced or pre-existing** — see the review-scope rule above.
+- **Likelihood** — high / medium / low, judged on the real production path. A `low`-likelihood, non-blocking finding is a follow-up, not a fix-now item; on a repeat review of the same change, list it in one line and move on.
+
+## Output
+
+Write an ordinary markdown review, not JSON and not a structured deep-review report.
+
+- Each finding: location, severity, likelihood, introduced or pre-existing, whether it blocks release, evidence.
+- If `release-risk` produced pre-deploy confirmation items (questions about production state the repo cannot answer), list them as a short checklist separate from defects.
+- If you find nothing, say so in one short paragraph. No silence, no pleasantries.
+````
diff --git a/.agents/skills/full-text-search/SKILL.md b/.agents/skills/full-text-search/SKILL.md
new file mode 100644
index 00000000000..69c87a56945
--- /dev/null
+++ b/.agents/skills/full-text-search/SKILL.md
@@ -0,0 +1,126 @@
+---
+name: full-text-search
+description: 'LobeHub product full-text search architecture and operations. Use for FtsSearchRepo, pg_search or Elasticsearch providers, search projections and mappings, reindexing, Outbox capture/sync, provider switching, search analytics, or search performance. Not for agent web-browsing tools.'
+---
+
+# Product Full-Text Search
+
+This skill covers search over LobeHub-owned product data such as agents, topics, messages, files,
+knowledge bases, documents, chat groups, and memories. It does not cover the agent's external web
+search providers under `apps/server/src/services/search/` or builtin web-browsing tools.
+
+## Architecture
+
+Product reads follow one stable path:
+
+```text
+router/service -> createFtsSearchRepo -> FtsSearchRepo -> selected backend -> existing result schema
+```
+
+- `apps/server/src/services/ftsSearch/` owns request-scoped provider selection, Elasticsearch
+ configuration, its HTTP client, and backend telemetry. Routers and domain services must call
+ `createFtsSearchRepo`; they must not construct providers themselves.
+- `packages/database/src/repositories/ftsSearch/` owns the provider-neutral contract and the concrete
+ PostgreSQL and Elasticsearch implementations. Keep public result shapes stable in `FtsSearchRepo`.
+- `packages/types/src/ftsSearch.ts` owns the shared searchable-entity list and search domain types.
+- `packages/database/src/repositories/ftsSearchDocument/` owns Elasticsearch document schemas,
+ mappings, queryable fields, and source-to-document projection.
+- `packages/database/src/schemas/ftsSearchSyncOutbox.ts` and
+ `packages/database/src/repositories/ftsSearchSyncOutbox/` own durable change capture, claims,
+ retries, dead letters, leases, revision fences, and capture-definition validation.
+- `packages/database/src/repositories/ftsSearchReindex/` and `scripts/elasticsearchReindex/` own the
+ resumable full backfill. `apps/server/src/services/ftsSearchSync/` and
+ `scripts/elasticsearchSync/` own continuous incremental draining.
+- `packages/env/src/ftsSearch.ts` owns generic Elasticsearch environment variables.
+
+## Provider and Permission Invariants
+
+- `FTS_SEARCH_PROVIDER` is a deployment-level provider selector with current values `pg_search` and
+ `elasticsearch`. It is not a feature flag or a user rollout. Add another enum value only when its
+ provider is implemented end to end.
+- Elasticsearch errors, missing configuration, and unsupported candidate behavior must remain
+ visible. Never silently retry through PostgreSQL or add an `ilike` fallback.
+- Deliberate routing of an entity that has not been migrated to Elasticsearch is not an error
+ fallback. Changing the migrated entity set is a product and migration decision.
+- Preserve `userId`, `workspaceId`, and caller-agent visibility throughout every provider. Candidate
+ retrieval must not broaden the caller's scope.
+- Where Elasticsearch only supplies candidate IDs, PostgreSQL hydration and parent checks remain
+ the authoritative permission boundary. Do not return raw Elasticsearch hits directly when the
+ existing result path requires database authorization or hydration.
+- Provider implementations return the existing hydrated response types and ordering contract. Do
+ not make routers understand provider-specific result shapes.
+
+## Changing a Searchable Entity
+
+Treat an entity addition or projection change as one cross-layer change. Inspect and update every
+applicable item:
+
+1. `FTS_SEARCH_DOCUMENT_ENTITIES` and shared request/result types.
+2. Search document schema, mapping, text fields, filters, fixtures, and mapping parity tests.
+3. `FtsSearchDocumentBuilder`, including soft deletion and fanout from related source rows.
+4. PostgreSQL and Elasticsearch backend behavior, permission hydration, pagination, and ranking.
+5. Capture functions/triggers or fanout queries in `captureInfrastructure.ts`.
+6. Reindex checkpoints, Outbox draining, metrics, and self-host documentation.
+
+Schema fields, mappings, builders, and fixed fixtures must agree exactly. A field that is not in the
+document schema must not appear in the mapping or query field list.
+
+## Capture, Reindex, and Sync
+
+- Regular database migrations own durable schema: the revision sequence, Outbox table and indexes,
+ and schema-managed source indexes such as the Memory fanout GIN index.
+- Capture functions and triggers are installed only when an operator explicitly enables the
+ Elasticsearch path. `installCaptureInfrastructure()` is transactional, definition-checked,
+ idempotent for an exact installation, and fail-closed for partial or altered definitions.
+- Do not install capture for every PostgreSQL-only instance. Do not move a normal schema index into
+ the runtime installer merely because it supports capture.
+- The Outbox coalesces by `(entity, document_id)`. A newer capture resets retry/dead-letter state and
+ allocates a new revision only after locking the conflicting row, preserving same-document commit
+ order.
+- Sequence allocation is non-transactional. Use the existing write fences and committed revision
+ boundary; never treat `last_value` alone as proof that all earlier Outbox rows are visible.
+- Claims use the precise lease timestamp as a fencing token. A stale worker must not acknowledge,
+ fail, or release work reclaimed by another worker.
+- Permanent failures and exhausted retries become durable dead letters. A drain that creates or
+ observes dead work must fail instead of continuing to publish a successful cutover signal.
+- Full backfill does not replace continuous sync and does not switch product traffic. Keep the
+ application on PostgreSQL until aliases are ready and the Outbox is empty and stable, then switch
+ explicitly.
+
+The supported operator entrypoints are:
+
+```bash
+bun run db:install-fts-search-capture
+bun run fts-search:reindex -- --status
+bun run fts-search:reindex -- --apply --yes
+bun run fts-search:sync -- --max-steps=8 --yes
+```
+
+Read `docs/self-hosting/advanced/elasticsearch-migration.mdx` or its Chinese counterpart before
+changing the operational sequence. When database rollout or index cost affects the design, also
+use the `db-migrations` skill and measure the relevant operation on the actual Dev database before
+adding manual or deferred release steps.
+
+## Observability and Product Analytics
+
+- Server provider metrics and traces live in `apps/server/src/services/ftsSearch/observability.ts`.
+ Keep labels bounded: entity, provider, operation, outcome, and coarse error type are acceptable;
+ raw queries, user IDs, document IDs, and index contents are not.
+- User-perceived search behavior lives with the open-source Command Menu in
+ `src/features/CommandMenu/analytics.ts`. Product analytics may cover end-to-end duration, rendered
+ result counts, empty results, result clicks, and abandonment without a Cloud business slot.
+- Measurement or analytics failures must never alter the selected provider's result or error.
+- Backend metrics explain provider cost and latency; frontend events explain what the user actually
+ experienced. Do not substitute one for the other.
+
+## Validation
+
+- Add or update focused tests beside every changed provider, mapping, builder, capture, sync, or
+ analytics module.
+- Preserve boundary tests proving callers use `FtsSearchRepo`, providers cannot leak raw result shapes,
+ and telemetry failures do not affect search behavior.
+- Test pagination after authorization drops candidates, delete/scope-change priority, concurrent
+ Outbox claims and stale settlements, retry/dead-letter behavior, reindex resume identity, and
+ capture-definition mismatch whenever those paths change.
+- Run `bun run check <changed-files...>` from the repository root. For migration or database-runtime
+ changes, follow the `db-migrations` and `testing` skills and verify against the actual Dev database.
diff --git a/.agents/skills/testing/references/db-model-test.md b/.agents/skills/testing/references/db-model-test.md
index aa56a5380ca..376119895db 100644
--- a/.agents/skills/testing/references/db-model-test.md
+++ b/.agents/skills/testing/references/db-model-test.md
@@ -28,7 +28,7 @@ cd packages/database && TEST_SERVER_DB=1 bunx vitest run --silent='passed-only'
```
Implication: client-db coverage **under-counts** any code that needs BM25 (e.g.
-`repositories/search/index.ts` reads near-0% locally but is fully covered in CI).
+`repositories/ftsSearch/index.ts` reads near-0% locally but is fully covered in CI).
Don't chase those lines locally — confirm via CI/Codecov.
## BM25 / full-text search → `describe.skipIf(!isServerDB)`
@@ -47,7 +47,7 @@ describe.skipIf(!isServerDB)('queryByKeyword', () => {
```
Convention already used in `session.test.ts`, `topic.query.test.ts`,
-`message.query.test.ts`, `home/index.test.ts`, `repositories/search/index.test.ts`.
+`message.query.test.ts`, `home/index.test.ts`, `repositories/ftsSearch/index.test.ts`.
## Setup boilerplate
diff --git a/.gitignore b/.gitignore
index f4accfb963b..262a5148ca9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -128,6 +128,7 @@ CLAUDE.local.md
docker-compose/dev/data/
# Migration scripts data
+.elasticsearch-reindex/
scripts/clerk-to-betterauth/test/*.csv
scripts/clerk-to-betterauth/test/*.json
scripts/clerk-to-betterauth/prod/*.csv
diff --git a/AGENTS.md b/AGENTS.md
index 7595bcbf865..49a88811a72 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -141,6 +141,6 @@ bun run check [changed-files...]
### Code Review
-Before reviewing a PR / diff / branch change, read the **deep-review** skill. Ordinary review requests use its light mode (inline review against the dimension quick checklists); the full multi-subagent deep mode runs only on explicit invocation.
+Before reviewing a PR / diff / branch change, read the **deep-review** skill. Ordinary review requests use its light mode (one independent reviewer against the dimension quick checklists); the full multi-subagent deep mode runs only on explicit invocation.
When designing or reviewing user-facing flows (empty/loading/error states, confirmations, async feedback, button hierarchy, lists at scale, pickers), follow LobeHub's design values in [`DESIGN.md`](./DESIGN.md) — Natural / Meaningful / Certainty / Growth (自然 / 意义感 / 确定性 / 成长).
diff --git a/Dockerfile b/Dockerfile
index de7464f4a6c..f68ed7e284a 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -94,6 +94,8 @@ RUN rm -rf src/app/desktop "src/app/(backend)/trpc/desktop"
# run build standalone for docker version
RUN npm run build:docker
+RUN pnpm exec esbuild scripts/elasticsearchReindex/index.ts --bundle --platform=node --format=cjs --outfile=/app/fts-search-elasticsearch-reindex.cjs --external:pg --external:drizzle-orm '--external:drizzle-orm/*'
+RUN pnpm exec esbuild scripts/elasticsearchSync/cli.ts --bundle --platform=node --format=cjs --outfile=/app/fts-search-elasticsearch-sync.cjs --external:pg --external:drizzle-orm '--external:drizzle-orm/*'
# Preserve SWC helpers referenced through pnpm virtual-store symlinks by Next.js.
RUN mkdir -p /runtime-deps && cp -a node_modules/.pnpm/@swc+helpers@* /runtime-deps/
@@ -115,6 +117,8 @@ COPY --from=builder /app/public/_spa-workbench /app/public/_spa-workbench
COPY --from=builder /app/packages/database/migrations /app/migrations
COPY --from=builder /app/scripts/migrateServerDB/docker.cjs /app/docker.cjs
COPY --from=builder /app/scripts/migrateServerDB/errorHint.js /app/errorHint.js
+COPY --from=builder /app/fts-search-elasticsearch-reindex.cjs /app/fts-search-elasticsearch-reindex.cjs
+COPY --from=builder /app/fts-search-elasticsearch-sync.cjs /app/fts-search-elasticsearch-sync.cjs
# copy dependencies
COPY --from=builder /deps/node_modules/.pnpm /app/node_modules/.pnpm
diff --git a/apps/server/src/routers/lambda/__tests__/chunk.test.ts b/apps/server/src/routers/lambda/__tests__/chunk.test.ts
index f2c02c42e8d..70e2276ec53 100644
--- a/apps/server/src/routers/lambda/__tests__/chunk.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/chunk.test.ts
@@ -7,7 +7,6 @@ import { DocumentModel } from '@/database/models/document';
import { EmbeddingModel } from '@/database/models/embedding';
import { FileModel } from '@/database/models/file';
import { MessageModel } from '@/database/models/message';
-import { SearchRepo } from '@/database/repositories/search';
import { ChunkService } from '@/server/services/chunk';
import { DocumentService } from '@/server/services/document';
@@ -19,7 +18,6 @@ vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn() }));
vi.mock('@/database/models/embedding', () => ({ EmbeddingModel: vi.fn() }));
vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));
vi.mock('@/database/models/message', () => ({ MessageModel: vi.fn() }));
-vi.mock('@/database/repositories/search', () => ({ SearchRepo: vi.fn() }));
vi.mock('@/server/services/chunk', () => ({ ChunkService: vi.fn() }));
vi.mock('@/server/services/document', () => ({ DocumentService: vi.fn() }));
vi.mock('@/database/server', () => ({ getServerDB: vi.fn() }));
@@ -45,7 +43,6 @@ describe('chunkRouter.getFileContents — ID branching', () => {
vi.mocked(ChunkModel).mockImplementation(() => ({}) as any);
vi.mocked(EmbeddingModel).mockImplementation(() => ({}) as any);
vi.mocked(MessageModel).mockImplementation(() => ({}) as any);
- vi.mocked(SearchRepo).mockImplementation(() => ({}) as any);
vi.mocked(ChunkService).mockImplementation(() => ({}) as any);
mockCtx = {
diff --git a/apps/server/src/routers/lambda/__tests__/search.test.ts b/apps/server/src/routers/lambda/__tests__/search.test.ts
index f1236a582a7..4e994687675 100644
--- a/apps/server/src/routers/lambda/__tests__/search.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/search.test.ts
@@ -2,8 +2,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { UserModel } from '@/database/models/user';
-import { SearchRepo } from '@/database/repositories/search';
import { DiscoverService } from '@/server/services/discover';
+import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import { searchRouter } from '../search';
@@ -11,9 +11,7 @@ vi.mock('@/database/core/db-adaptor', () => ({
getServerDB: vi.fn().mockResolvedValue({}),
}));
-vi.mock('@/database/repositories/search', () => ({
- SearchRepo: vi.fn(),
-}));
+vi.mock('@/server/services/ftsSearch', () => ({ createFtsSearchRepo: vi.fn() }));
vi.mock('@/database/models/user', () => ({
UserModel: Object.assign(vi.fn(), { findById: vi.fn() }),
@@ -42,7 +40,7 @@ describe('searchRouter', () => {
fullName: 'Test User',
} as any);
vi.mocked(UserModel).mockImplementation(() => ({ getUserSettings }) as any);
- vi.mocked(SearchRepo).mockImplementation(() => ({ search }) as unknown as SearchRepo);
+ vi.mocked(createFtsSearchRepo).mockResolvedValue({ search } as any);
vi.mocked(DiscoverService).mockImplementation(
() => ({ getAssistantList, getMcpList, getPluginList }) as unknown as DiscoverService,
);
@@ -82,6 +80,7 @@ describe('searchRouter', () => {
},
{ throwOnError: true },
);
+ expect(createFtsSearchRepo).not.toHaveBeenCalled();
});
it('does not load market identity for a local-only search', async () => {
@@ -95,6 +94,9 @@ describe('searchRouter', () => {
query: 'local message',
type: 'message',
});
+ expect(createFtsSearchRepo).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: 'test-user', workspaceId: undefined }),
+ );
expect(UserModel.findById).not.toHaveBeenCalled();
expect(getUserSettings).not.toHaveBeenCalled();
});
diff --git a/apps/server/src/routers/lambda/chunk.ts b/apps/server/src/routers/lambda/chunk.ts
index dfdaf749dc3..fa14026b5f8 100644
--- a/apps/server/src/routers/lambda/chunk.ts
+++ b/apps/server/src/routers/lambda/chunk.ts
@@ -11,7 +11,6 @@ import { DocumentModel } from '@/database/models/document';
import { EmbeddingModel } from '@/database/models/embedding';
import { FileModel } from '@/database/models/file';
import { MessageModel } from '@/database/models/message';
-import { SearchRepo } from '@/database/repositories/search';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { getServerDefaultFilesConfig } from '@/server/globalConfig';
@@ -37,7 +36,6 @@ const chunkProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
fileModel: new FileModel(ctx.serverDB, ctx.userId, wsId),
knowledgeBaseSearchService: new KnowledgeBaseSearchService(ctx.serverDB, ctx.userId, wsId),
messageModel: new MessageModel(ctx.serverDB, ctx.userId, wsId),
- searchRepo: new SearchRepo(ctx.serverDB, ctx.userId, wsId),
},
});
});
diff --git a/apps/server/src/routers/lambda/home.ts b/apps/server/src/routers/lambda/home.ts
index 7a8ba95a18a..4aebae65ec3 100644
--- a/apps/server/src/routers/lambda/home.ts
+++ b/apps/server/src/routers/lambda/home.ts
@@ -7,6 +7,7 @@ import { AgentMigrationRepo } from '@/database/repositories/agentMigration';
import { HomeRepository } from '@/database/repositories/home';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import { type HomeBriefData, HomeService } from '@/server/services/home';
import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
import { after } from '@/server/utils/scheduleAfterResponse';
@@ -25,6 +26,22 @@ const homeProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
});
});
+const homeSearchProcedure = homeProcedure.use(async (opts) => {
+ const { ctx } = opts;
+ const workspaceId = ctx.workspaceId ?? undefined;
+ const ftsSearchRepo = await createFtsSearchRepo({
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId,
+ });
+
+ return opts.next({
+ ctx: {
+ homeRepository: new HomeRepository(ctx.serverDB, ctx.userId, workspaceId, ftsSearchRepo),
+ },
+ });
+});
+
export const homeRouter = router({
getDailyBrief: homeProcedure.query(({ ctx }): Promise<HomeBriefData> =>
ctx.homeService.getDailyBrief(),
@@ -74,7 +91,7 @@ export const homeRouter = router({
return result;
}),
- searchAgents: homeProcedure
+ searchAgents: homeSearchProcedure
.input(z.object({ keyword: z.string() }))
.query(async ({ input, ctx }) => {
return ctx.homeRepository.searchAgents(input.keyword);
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index ee974554b64..90af21c4ae6 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -20,6 +20,7 @@ import { TopicDoctorRepo } from '@/database/repositories/topicDoctor';
import { publicProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { FileService } from '@/server/services/file';
+import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import { type MessageBatchOperation, MessageService } from '@/server/services/message';
import {
@@ -55,6 +56,22 @@ const messageProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)
});
});
+const messageSearchProcedure = messageProcedure.use(async (opts) => {
+ const { ctx } = opts;
+ const workspaceId = ctx.workspaceId ?? undefined;
+ const ftsSearchRepo = await createFtsSearchRepo({
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId,
+ });
+
+ return opts.next({
+ ctx: {
+ messageModel: new MessageModel(ctx.serverDB, ctx.userId, workspaceId, ftsSearchRepo),
+ },
+ });
+});
+
/**
* Shared input for the ownership-scoped message analytics queries
* (count / countByTopic / topicStats). Every field is an optional filter
@@ -523,7 +540,7 @@ export const messageRouter = router({
return ctx.messageModel.deleteMessagesBySession(null, input.topicId, input.groupId);
}),
- searchMessages: messageProcedure
+ searchMessages: messageSearchProcedure
.input(z.object({ keywords: z.string() }))
.query(async ({ input, ctx }) => {
return ctx.messageModel.queryByKeyword(input.keywords);
diff --git a/apps/server/src/routers/lambda/search.ts b/apps/server/src/routers/lambda/search.ts
index 7884abdeaf7..1f5ecb50156 100644
--- a/apps/server/src/routers/lambda/search.ts
+++ b/apps/server/src/routers/lambda/search.ts
@@ -2,10 +2,10 @@ import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
-import { SearchRepo } from '@/database/repositories/search';
import { router } from '@/libs/trpc/lambda';
import { resolveMarketUserContext, serverDatabase } from '@/libs/trpc/lambda/middleware';
import { DiscoverService } from '@/server/services/discover';
+import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import { getRestrictedKnowledgeBaseIds } from './_helpers/knowledgeBaseAccess';
@@ -41,7 +41,6 @@ const searchProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =
const { ctx } = opts;
const rawInput = (await opts.getRawInput()) as
{ includeMarketplace?: unknown; type?: unknown } | undefined;
- const wsId = ctx.workspaceId ?? undefined;
// Marketplace identity is only needed when the marketplace will be queried;
// DB-only searches skip the extra auth round-trip.
const marketContext = wantsMarketplace(rawInput)
@@ -54,7 +53,6 @@ const searchProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =
accessToken: marketContext.marketAccessToken ?? ctx.marketAccessToken,
userInfo: marketContext.marketUserInfo,
}),
- searchRepo: new SearchRepo(ctx.serverDB, ctx.userId, wsId),
},
});
});
@@ -130,10 +128,15 @@ export const searchRouter = router({
// this debounced search-as-you-type path.
const needsKbExclusion =
!type || ['file', 'folder', 'knowledgeBase', 'page'].includes(type);
- const excludeKnowledgeBaseIds = needsKbExclusion
- ? await getRestrictedKnowledgeBaseIds(ctx)
- : [];
- searchPromises.push(ctx.searchRepo.search({ ...input, excludeKnowledgeBaseIds }));
+ const [excludeKnowledgeBaseIds, ftsSearchRepo] = await Promise.all([
+ needsKbExclusion ? getRestrictedKnowledgeBaseIds(ctx) : [],
+ createFtsSearchRepo({
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ }),
+ ]);
+ searchPromises.push(ftsSearchRepo.search({ ...input, excludeKnowledgeBaseIds }));
}
// Marketplace searches: see `includeMarketplace` on the input schema —
@@ -256,7 +259,7 @@ export const searchRouter = router({
// Execute searches in parallel and merge results
const results = await Promise.all(searchPromises);
- // Results arrive pre-ordered per type (DB types from SearchRepo with
+ // Results arrive pre-ordered per type (DB types from FtsSearchRepo with
// topics/messages by recency, marketplace types from the discover service).
// The command palette groups results by type, so we keep each source's order
// instead of re-sorting the merged list by relevance.
diff --git a/apps/server/src/routers/lambda/session.ts b/apps/server/src/routers/lambda/session.ts
index 87ed388c1d2..bcf5c580353 100644
--- a/apps/server/src/routers/lambda/session.ts
+++ b/apps/server/src/routers/lambda/session.ts
@@ -12,6 +12,7 @@ import { insertAgentSchema, insertSessionSchema } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import { assertCanEditResource } from '@/server/services/resourcePermission';
import { AgentChatConfigSchema } from '@/types/agent';
import { LobeMetaDataSchema } from '@/types/meta';
@@ -65,6 +66,22 @@ const sessionProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)
});
});
+const sessionSearchProcedure = sessionProcedure.use(async (opts) => {
+ const { ctx } = opts;
+ const workspaceId = ctx.workspaceId ?? undefined;
+ const ftsSearchRepo = await createFtsSearchRepo({
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId,
+ });
+
+ return opts.next({
+ ctx: {
+ sessionModel: new SessionModel(ctx.serverDB, ctx.userId, workspaceId, ftsSearchRepo),
+ },
+ });
+});
+
/**
* @deprecated Session router is legacy. Use agent router for agent CRUD operations.
* Session-based agent creation (createSession, batchCreateSessions) should migrate
@@ -233,7 +250,7 @@ export const sessionRouter = router({
return result;
}),
- searchSessions: sessionProcedure
+ searchSessions: sessionSearchProcedure
.input(z.object({ keywords: z.string() }))
.query(async ({ input, ctx }) => {
return ctx.sessionModel.queryByKeyword(input.keywords);
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.ts
index 605daa61424..2ad9d818e0e 100644
--- a/apps/server/src/routers/lambda/topic.ts
+++ b/apps/server/src/routers/lambda/topic.ts
@@ -34,6 +34,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { FileService } from '@/server/services/file';
+import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import { after } from '@/server/utils/scheduleAfterResponse';
import { type BatchTaskResult } from '@/types/service';
@@ -81,6 +82,22 @@ const topicProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
});
});
+const topicSearchProcedure = topicProcedure.use(async (opts) => {
+ const { ctx } = opts;
+ const workspaceId = ctx.workspaceId ?? undefined;
+ const ftsSearchRepo = await createFtsSearchRepo({
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId,
+ });
+
+ return opts.next({
+ ctx: {
+ topicModel: new TopicModel(ctx.serverDB, ctx.userId, workspaceId, ftsSearchRepo),
+ },
+ });
+});
+
const topicBulkDeleteScopeSchema = z.enum(['own', 'workspace']).default('own');
interface TopicShareCtx {
@@ -911,7 +928,7 @@ export const topicRouter = router({
return result;
}),
- searchTopics: topicProcedure
+ searchTopics: topicSearchProcedure
.input(
z.object({
agentId: z.string().optional(),
diff --git a/apps/server/src/routers/lambda/userMemories.test.ts b/apps/server/src/routers/lambda/userMemories.test.ts
index dd29208a27a..788084a4513 100644
--- a/apps/server/src/routers/lambda/userMemories.test.ts
+++ b/apps/server/src/routers/lambda/userMemories.test.ts
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getServerDB } from '@/database/core/db-adaptor';
import type * as UserMemoryModule from '@/database/models/userMemory';
import { UserMemoryModel } from '@/database/models/userMemory';
+import { FtsSearchCandidateError } from '@/database/repositories/ftsSearch';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { userMemoriesRouter } from './userMemories';
@@ -240,6 +241,24 @@ describe('userMemories.queryMemories', () => {
order: 'desc',
});
});
+
+ it('propagates candidate-provider failures instead of returning a successful empty page', async () => {
+ const providerError = new Error('Elasticsearch unavailable');
+ const queryMemories = vi.fn().mockRejectedValue(new FtsSearchCandidateError(providerError));
+
+ vi.mocked(UserMemoryModel).mockImplementation(() => ({ queryMemories }) as any);
+ vi.mocked(getServerDB).mockResolvedValue(makeServerDBMock() as any);
+
+ const caller = userMemoriesRouter.createCaller(mockCtx as any);
+
+ await expect(caller.queryMemories({ q: 'atlas' })).rejects.toMatchObject({
+ cause: {
+ cause: providerError,
+ name: FtsSearchCandidateError.name,
+ },
+ code: 'INTERNAL_SERVER_ERROR',
+ });
+ });
});
describe('userMemories.getMemoryDetail', () => {
diff --git a/apps/server/src/routers/lambda/userMemories.ts b/apps/server/src/routers/lambda/userMemories.ts
index 6532985f1e2..7afb5ddc03d 100644
--- a/apps/server/src/routers/lambda/userMemories.ts
+++ b/apps/server/src/routers/lambda/userMemories.ts
@@ -32,6 +32,7 @@ import {
UserMemoryIdentityModel,
UserMemoryModel,
} from '@/database/models/userMemory';
+import { FtsSearchCandidateError } from '@/database/repositories/ftsSearch';
import { UserMemoryTopicRepository } from '@/database/repositories/userMemory';
import {
userMemories,
@@ -46,6 +47,7 @@ import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { getServerDefaultFilesConfig } from '@/server/globalConfig';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
+import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import type { UserMemoryEmbeddingRuntime } from '@/server/services/memory/userMemory/embedding';
import { embedUserMemoryTexts } from '@/server/services/memory/userMemory/embedding';
import { normalizeSearchMemoryParams } from '@/server/services/memory/userMemory/searchParams';
@@ -234,6 +236,11 @@ const normalizeEmbeddable = (value?: string | null): string | undefined => {
return trimmed.length > 0 ? trimmed : undefined;
};
+/** Candidate-provider outages must not be converted into successful empty memory responses. */
+const rethrowCandidateSearchError = (error: unknown) => {
+ if (error instanceof FtsSearchCandidateError) throw error;
+};
+
const memoryProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
const userSettingsRow = await ctx.serverDB.query.userSettings.findFirst({
@@ -256,6 +263,19 @@ const memoryProcedure = authedProcedure.use(serverDatabase).use(async (opts) =>
},
});
});
+const memorySearchProcedure = memoryProcedure.use(async (opts) => {
+ const { ctx } = opts;
+ const ftsSearchRepo = await createFtsSearchRepo({ db: ctx.serverDB, userId: ctx.userId });
+
+ return opts.next({
+ ctx: {
+ activityModel: new UserMemoryActivityModel(ctx.serverDB, ctx.userId, ftsSearchRepo),
+ experienceModel: new UserMemoryExperienceModel(ctx.serverDB, ctx.userId, ftsSearchRepo),
+ identityModel: new UserMemoryIdentityModel(ctx.serverDB, ctx.userId, ftsSearchRepo),
+ memoryModel: new UserMemoryModel(ctx.serverDB, ctx.userId, ftsSearchRepo),
+ },
+ });
+});
const memoryWriteProcedure = memoryProcedure.use(withScopedPermission('message:create'));
export const userMemoriesRouter = router({
@@ -270,7 +290,7 @@ export const userMemoriesRouter = router({
}
}),
- queryActivities: memoryProcedure
+ queryActivities: memorySearchProcedure
.input(
z
.object({
@@ -293,12 +313,13 @@ export const userMemoriesRouter = router({
try {
return await ctx.activityModel.queryList(params);
} catch (error) {
+ rethrowCandidateSearchError(error);
console.error('Failed to query activities:', error);
return { items: [], page: fallbackPage, pageSize: fallbackPageSize, total: 0 };
}
}),
- queryExperiences: memoryProcedure
+ queryExperiences: memorySearchProcedure
.input(
z
.object({
@@ -320,12 +341,13 @@ export const userMemoriesRouter = router({
try {
return await ctx.experienceModel.queryList(params);
} catch (error) {
+ rethrowCandidateSearchError(error);
console.error('Failed to query experiences:', error);
return { items: [], page: fallbackPage, pageSize: fallbackPageSize, total: 0 };
}
}),
- queryIdentities: memoryProcedure
+ queryIdentities: memorySearchProcedure
.input(
z
.object({
@@ -348,6 +370,7 @@ export const userMemoriesRouter = router({
try {
return await ctx.identityModel.queryList(params);
} catch (error) {
+ rethrowCandidateSearchError(error);
console.error('Failed to query identities:', error);
return { items: [], page: fallbackPage, pageSize: fallbackPageSize, total: 0 };
}
@@ -382,7 +405,7 @@ export const userMemoriesRouter = router({
}
}),
- queryMemories: memoryProcedure
+ queryMemories: memorySearchProcedure
.input(
z
.object({
@@ -420,6 +443,7 @@ export const userMemoriesRouter = router({
sort: params.sort,
});
} catch (error) {
+ rethrowCandidateSearchError(error);
console.error('Failed to query memories:', error);
return { items: [], page: fallbackPage, pageSize: fallbackPageSize, total: 0 };
}
@@ -922,7 +946,7 @@ export const userMemoriesRouter = router({
* Retrieve memories for a specific topic
* Uses concatenated user messages (first 7000 chars) as the search query
*/
- retrieveMemoryForTopic: memoryProcedure
+ retrieveMemoryForTopic: memorySearchProcedure
.input(z.object({ topicId: z.string() }))
.query(async ({ ctx, input }) => {
// Dev-only escape hatch: skip the embedding + memory search triggered by topic
@@ -956,15 +980,17 @@ export const userMemoriesRouter = router({
const result = await searchUserMemories(ctx, searchParams);
return result;
} catch (error) {
+ rethrowCandidateSearchError(error);
console.error('Failed to retrieve memory for topic:', error);
return EMPTY_SEARCH_RESULT;
}
}),
- searchMemory: memoryProcedure.input(searchMemorySchema).query(async ({ input, ctx }) => {
+ searchMemory: memorySearchProcedure.input(searchMemorySchema).query(async ({ input, ctx }) => {
try {
return await searchUserMemories(ctx, input);
} catch (error) {
+ rethrowCandidateSearchError(error);
console.error('Failed to retrieve memories:', error);
return EMPTY_SEARCH_RESULT;
}
@@ -1299,10 +1325,12 @@ export const userMemoriesRouter = router({
}
}),
- toolSearchMemory: memoryProcedure.input(searchMemorySchema).query(async ({ input, ctx }) => {
- const result = await searchUserMemories(ctx, input);
- return result;
- }),
+ toolSearchMemory: memorySearchProcedure
+ .input(searchMemorySchema)
+ .query(async ({ input, ctx }) => {
+ const result = await searchUserMemories(ctx, input);
+ return result;
+ }),
toolUpdateIdentityMemory: memoryWriteProcedure
.input(UpdateIdentityActionSchema)
diff --git a/apps/server/src/services/ftsSearch/elasticsearch.test.ts b/apps/server/src/services/ftsSearch/elasticsearch.test.ts
new file mode 100644
index 00000000000..8bf6a61ae02
--- /dev/null
+++ b/apps/server/src/services/ftsSearch/elasticsearch.test.ts
@@ -0,0 +1,564 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { ElasticsearchFtsSearchHttpClient } from './elasticsearch';
+
+const mocks = vi.hoisted(() => ({
+ recordSearchRequest: vi.fn(),
+}));
+
+vi.mock('./observability', () => ({
+ recordElasticsearchFtsSearchRequest: mocks.recordSearchRequest,
+}));
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+});
+
+describe('ElasticsearchFtsSearchHttpClient', () => {
+ it('rejects remote HTTP endpoints before exposing the API key', () => {
+ expect(
+ () =>
+ new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'http://search.example.com',
+ }),
+ ).toThrow('must use HTTPS unless it targets loopback');
+ });
+
+ it('allows loopback HTTP endpoints for local development', () => {
+ expect(
+ () =>
+ new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'http://localhost:9200',
+ }),
+ ).not.toThrow();
+ });
+
+ it('returns no write targets without making requests when no aliases are provided', async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.getFtsSearchSyncWriteTargets([])).resolves.toEqual({});
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('sends an authenticated search request and returns candidate hits', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ hits: {
+ hits: [{ _id: 'agent-1', _score: 8.5, sort: [8.5, 'agent-1'] }],
+ total: { value: 1 },
+ },
+ took: 12,
+ }),
+ { headers: { 'Content-Length': '120', 'Content-Type': 'application/json' }, status: 200 },
+ ),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ requestTimeoutMs: 5000,
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.search({
+ body: { query: { match_all: {} }, size: 1 },
+ entity: 'agents',
+ index: 'lobehub-dev-agents',
+ pagination: 'bounded',
+ }),
+ ).resolves.toEqual({
+ hits: {
+ hits: [{ _id: 'agent-1', _score: 8.5, sort: [8.5, 'agent-1'] }],
+ total: { value: 1 },
+ },
+ took: 12,
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ new URL('https://search.example.com/lobehub-dev-agents/_search'),
+ expect.objectContaining({
+ body: JSON.stringify({ query: { match_all: {} }, size: 1 }),
+ headers: {
+ 'Authorization': 'ApiKey test-api-key',
+ 'Content-Type': 'application/json',
+ },
+ method: 'POST',
+ }),
+ );
+ expect(mocks.recordSearchRequest).toHaveBeenCalledWith({
+ contentLength: 120,
+ decodedBytes: expect.any(Number),
+ durationMs: expect.any(Number),
+ entity: 'agents',
+ hits: 1,
+ pagination: 'bounded',
+ requestBytes: expect.any(Number),
+ result: 'success',
+ serverTookMs: 12,
+ });
+ });
+
+ it('surfaces HTTP failures without copying response payloads into the error', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValue(
+ new Response(JSON.stringify({ error: 'sensitive backend detail' }), { status: 503 }),
+ ),
+ );
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.search({
+ body: { query: { match_all: {} } },
+ entity: 'agents',
+ index: 'lobehub-dev-agents',
+ pagination: 'bounded',
+ }),
+ ).rejects.toMatchObject({
+ message: 'Elasticsearch search request failed (503)',
+ status: 503,
+ });
+ expect(mocks.recordSearchRequest).toHaveBeenCalledWith(
+ expect.objectContaining({ entity: 'agents', result: 'http_error' }),
+ );
+ });
+
+ it('rejects malformed successful responses', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ hits: { hits: [{ _id: 123 }] } }), {
+ headers: { 'Content-Type': 'application/json' },
+ status: 200,
+ }),
+ ),
+ );
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.search({
+ body: { query: { match_all: {} } },
+ entity: 'agents',
+ index: 'lobehub-dev-agents',
+ pagination: 'bounded',
+ }),
+ ).rejects.toThrow('Elasticsearch search response has an invalid shape');
+ expect(mocks.recordSearchRequest).toHaveBeenCalledWith(
+ expect.objectContaining({ entity: 'agents', result: 'parse_error' }),
+ );
+ });
+
+ it('classifies fetch timeouts separately from other transport failures', async () => {
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+ const input = {
+ body: { query: { match_all: {} } },
+ entity: 'agents' as const,
+ index: 'lobehub-dev-agents',
+ pagination: 'bounded' as const,
+ };
+
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockRejectedValueOnce(new DOMException('The operation timed out', 'TimeoutError')),
+ );
+ await expect(client.search(input)).rejects.toThrow('The operation timed out');
+ expect(mocks.recordSearchRequest).toHaveBeenLastCalledWith(
+ expect.objectContaining({ entity: 'agents', result: 'timeout' }),
+ );
+
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValueOnce(new TypeError('connection closed')));
+ await expect(client.search(input)).rejects.toThrow('connection closed');
+ expect(mocks.recordSearchRequest).toHaveBeenLastCalledWith(
+ expect.objectContaining({ entity: 'agents', result: 'other_error' }),
+ );
+ });
+
+ it('sends bulk payloads to the alias-only endpoint', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ errors: false, items: [{ index: { status: 201 } }] }), {
+ headers: { 'Content-Type': 'application/json' },
+ status: 200,
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ requestTimeoutMs: 5000,
+ url: 'https://search.example.com',
+ });
+ const body = '{"index":{}}\n{"id":"agent-1"}\n';
+
+ await expect(client.bulk(body)).resolves.toEqual({
+ errors: false,
+ items: [{ index: { status: 201 } }],
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ new URL('https://search.example.com/_bulk?require_alias=true'),
+ expect.objectContaining({
+ body,
+ headers: {
+ 'Authorization': 'ApiKey test-api-key',
+ 'Content-Type': 'application/x-ndjson',
+ },
+ method: 'POST',
+ }),
+ );
+ });
+
+ it('verifies writable aliases and their soft-delete mappings before synchronization', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v2': { aliases: { 'lobehub-agents': {} } },
+ 'lobehub-topics-v2': {
+ aliases: { 'lobehub-topics': { is_write_index: true } },
+ },
+ }),
+ )
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v2': {
+ mappings: {
+ fts_search_sync_deleted: {
+ full_name: 'fts_search_sync_deleted',
+ mapping: { fts_search_sync_deleted: { type: 'boolean' } },
+ },
+ },
+ },
+ 'lobehub-topics-v2': {
+ mappings: {
+ fts_search_sync_deleted: {
+ full_name: 'fts_search_sync_deleted',
+ mapping: { fts_search_sync_deleted: { type: 'boolean' } },
+ },
+ },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.assertFtsSearchSyncAliases(['lobehub-agents', 'lobehub-topics']),
+ ).resolves.toBeUndefined();
+ expect(fetchMock.mock.calls.map(([url]) => url.toString())).toEqual([
+ 'https://search.example.com/_alias/lobehub-agents,lobehub-topics',
+ 'https://search.example.com/lobehub-agents-v2,lobehub-topics-v2/_mapping/field/fts_search_sync_deleted',
+ ]);
+ });
+
+ it('returns writable physical indices in stable alias order', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v2': { aliases: { 'lobehub-agents': {} } },
+ 'lobehub-topics-v2': { aliases: { 'lobehub-topics': {} } },
+ }),
+ )
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v2': {
+ mappings: {
+ fts_search_sync_deleted: {
+ mapping: { fts_search_sync_deleted: { type: 'boolean' } },
+ },
+ },
+ },
+ 'lobehub-topics-v2': {
+ mappings: {
+ fts_search_sync_deleted: {
+ mapping: { fts_search_sync_deleted: { type: 'boolean' } },
+ },
+ },
+ },
+ }),
+ ),
+ );
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+
+ const writeTargets = await client.getFtsSearchSyncWriteTargets([
+ 'lobehub-topics',
+ 'lobehub-agents',
+ ]);
+
+ expect(writeTargets).toEqual({
+ 'lobehub-agents': 'lobehub-agents-v2',
+ 'lobehub-topics': 'lobehub-topics-v2',
+ });
+ expect(Object.keys(writeTargets)).toEqual(['lobehub-agents', 'lobehub-topics']);
+ });
+
+ it('returns stable runtime identities for indices from one reindex run', async () => {
+ const reindexRunId = '00000000-0000-4000-8000-000000000001';
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v2': { aliases: { 'lobehub-agents': {} } },
+ 'lobehub-topics-v2': { aliases: { 'lobehub-topics': {} } },
+ }),
+ )
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v2': {
+ mappings: {
+ _meta: { reindex_run_id: reindexRunId, schema_version: 2 },
+ dynamic: 'strict',
+ properties: {
+ id: { type: 'keyword' },
+ fts_search_sync_deleted: { type: 'boolean' },
+ },
+ },
+ settings: {
+ index: {
+ analysis: { analyzer: { lobehub_icu: { type: 'custom' } } },
+ uuid: 'agents-index-uuid',
+ },
+ },
+ },
+ 'lobehub-topics-v2': {
+ mappings: {
+ _meta: { reindex_run_id: reindexRunId, schema_version: 2 },
+ dynamic: 'strict',
+ properties: {
+ id: { type: 'keyword' },
+ fts_search_sync_deleted: { type: 'boolean' },
+ },
+ },
+ settings: {
+ index: {
+ analysis: { analyzer: { lobehub_icu: { type: 'custom' } } },
+ uuid: 'topics-index-uuid',
+ },
+ },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+
+ const identities = await client.getFtsSearchSyncIndexIdentities([
+ 'lobehub-topics',
+ 'lobehub-agents',
+ ]);
+
+ expect(identities).toEqual({
+ 'lobehub-agents': {
+ indexUuid: 'agents-index-uuid',
+ mappingSha256: expect.stringMatching(/^[\da-f]{64}$/),
+ physicalIndex: 'lobehub-agents-v2',
+ reindexRunId,
+ schemaVersion: 2,
+ settingsSha256: expect.stringMatching(/^[\da-f]{64}$/),
+ },
+ 'lobehub-topics': {
+ indexUuid: 'topics-index-uuid',
+ mappingSha256: expect.stringMatching(/^[\da-f]{64}$/),
+ physicalIndex: 'lobehub-topics-v2',
+ reindexRunId,
+ schemaVersion: 2,
+ settingsSha256: expect.stringMatching(/^[\da-f]{64}$/),
+ },
+ });
+ expect(Object.keys(identities)).toEqual(['lobehub-agents', 'lobehub-topics']);
+ expect(identities['lobehub-agents'].mappingSha256).toBe(
+ identities['lobehub-topics'].mappingSha256,
+ );
+ expect(identities['lobehub-agents'].settingsSha256).toBe(
+ identities['lobehub-topics'].settingsSha256,
+ );
+ expect(fetchMock.mock.calls.map(([url]) => url.toString())).toEqual([
+ 'https://search.example.com/_alias/lobehub-topics,lobehub-agents',
+ 'https://search.example.com/lobehub-agents-v2,lobehub-topics-v2?filter_path=*.mappings,*.settings.index.analysis,*.settings.index.uuid',
+ ]);
+ });
+
+ it('rejects a runtime identity response with missing reindex metadata', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json({ 'lobehub-agents-v2': { aliases: { 'lobehub-agents': {} } } }),
+ )
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v2': {
+ mappings: {
+ properties: { fts_search_sync_deleted: { type: 'boolean' } },
+ sensitive_payload: 'must-not-leak',
+ },
+ settings: { index: { analysis: {}, uuid: 'agents-index-uuid' } },
+ },
+ }),
+ ),
+ );
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+
+ const request = client.getFtsSearchSyncIndexIdentities(['lobehub-agents']);
+ await expect(request).rejects.toThrow(
+ 'Elasticsearch full-text search sync index identity response has an invalid shape',
+ );
+ await expect(request).rejects.not.toThrow(/test-api-key|must-not-leak/);
+ });
+
+ it('rejects aliases that point to indices from different reindex runs', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v2': { aliases: { 'lobehub-agents': {} } },
+ 'lobehub-topics-v2': { aliases: { 'lobehub-topics': {} } },
+ }),
+ )
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v2': {
+ mappings: {
+ _meta: {
+ reindex_run_id: '00000000-0000-4000-8000-000000000001',
+ schema_version: 2,
+ },
+ properties: { fts_search_sync_deleted: { type: 'boolean' } },
+ },
+ settings: { index: { analysis: {}, uuid: 'agents-index-uuid' } },
+ },
+ 'lobehub-topics-v2': {
+ mappings: {
+ _meta: {
+ reindex_run_id: '00000000-0000-4000-8000-000000000002',
+ schema_version: 2,
+ },
+ properties: { fts_search_sync_deleted: { type: 'boolean' } },
+ },
+ settings: { index: { analysis: {}, uuid: 'topics-index-uuid' } },
+ },
+ }),
+ ),
+ );
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.getFtsSearchSyncIndexIdentities(['lobehub-agents', 'lobehub-topics']),
+ ).rejects.toThrow(
+ 'Elasticsearch full-text search sync aliases do not share one reindex run identity',
+ );
+ });
+
+ it('selects the unique explicit write index for a multi-target alias', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v1': {
+ aliases: { 'lobehub-agents': { is_write_index: false } },
+ },
+ 'lobehub-agents-v2': {
+ aliases: { 'lobehub-agents': { is_write_index: true } },
+ },
+ }),
+ )
+ .mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v2': {
+ mappings: {
+ fts_search_sync_deleted: {
+ mapping: { fts_search_sync_deleted: { type: 'boolean' } },
+ },
+ },
+ },
+ }),
+ ),
+ );
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.getFtsSearchSyncWriteTargets(['lobehub-agents'])).resolves.toEqual({
+ 'lobehub-agents': 'lobehub-agents-v2',
+ });
+ });
+
+ it('rejects a multi-target alias without an explicit write index', async () => {
+ const fetchMock = vi.fn().mockResolvedValueOnce(
+ Response.json({
+ 'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } },
+ 'lobehub-agents-v2': { aliases: { 'lobehub-agents': {} } },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.getFtsSearchSyncWriteTargets(['lobehub-agents'])).rejects.toThrow(
+ 'Elasticsearch full-text search sync destination is not a writable alias: lobehub-agents',
+ );
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects an alias whose write index lacks the soft-delete mapping', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json({ 'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } } }),
+ )
+ .mockResolvedValueOnce(Response.json({ 'lobehub-agents-v1': { mappings: {} } })),
+ );
+ const client = new ElasticsearchFtsSearchHttpClient({
+ apiKey: 'test-api-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.getFtsSearchSyncWriteTargets(['lobehub-agents'])).rejects.toThrow(
+ 'Elasticsearch full-text search sync alias lacks a boolean fts_search_sync_deleted mapping: lobehub-agents',
+ );
+ });
+});
diff --git a/apps/server/src/services/ftsSearch/elasticsearch.ts b/apps/server/src/services/ftsSearch/elasticsearch.ts
new file mode 100644
index 00000000000..b5d8033d66e
--- /dev/null
+++ b/apps/server/src/services/ftsSearch/elasticsearch.ts
@@ -0,0 +1,468 @@
+import { Buffer } from 'node:buffer';
+import { createHash } from 'node:crypto';
+
+import { z } from 'zod';
+
+import type {
+ ElasticsearchFtsSearchClient,
+ ElasticsearchFtsSearchInput,
+ ElasticsearchFtsSearchResponse,
+} from '@/database/repositories/ftsSearch';
+import { parseElasticsearchUrl } from '@/database/repositories/ftsSearch/elasticsearch/url';
+
+import type { ElasticsearchFtsSearchRequestResult } from './observability';
+import { recordElasticsearchFtsSearchRequest } from './observability';
+
+const searchResponseSchema = z.object({
+ hits: z.object({
+ hits: z.array(
+ z.object({
+ _id: z.string(),
+ _score: z.number().nullable(),
+ sort: z.array(z.unknown()).optional(),
+ }),
+ ),
+ total: z.union([z.number(), z.object({ value: z.number() })]).optional(),
+ }),
+ took: z.number().nonnegative().optional(),
+});
+
+const bulkResponseSchema = z.object({
+ errors: z.boolean().optional(),
+ items: z.array(
+ z.object({
+ index: z.object({ error: z.unknown().optional(), status: z.number() }),
+ }),
+ ),
+});
+
+const aliasResponseSchema = z.record(
+ z.string(),
+ z.object({
+ aliases: z.record(
+ z.string(),
+ z.object({ is_write_index: z.boolean().optional() }).passthrough(),
+ ),
+ }),
+);
+
+const fieldMappingResponseSchema = z.record(
+ z.string(),
+ z.object({
+ mappings: z.record(
+ z.string(),
+ z.object({
+ mapping: z.record(z.string(), z.object({ type: z.string() }).passthrough()),
+ }),
+ ),
+ }),
+);
+
+const indexIdentityResponseSchema = z.record(
+ z.string(),
+ z.object({
+ mappings: z
+ .object({
+ _meta: z
+ .object({
+ reindex_run_id: z.string().uuid(),
+ schema_version: z.number().int().positive(),
+ })
+ .passthrough(),
+ properties: z
+ .object({
+ fts_search_sync_deleted: z.object({ type: z.literal('boolean') }).passthrough(),
+ })
+ .passthrough(),
+ })
+ .passthrough(),
+ settings: z.object({
+ index: z
+ .object({
+ analysis: z.record(z.string(), z.unknown()),
+ uuid: z.string().trim().min(1),
+ })
+ .passthrough(),
+ }),
+ }),
+);
+
+const stableStringify = (value: unknown): string => {
+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
+
+ return `{${Object.entries(value)
+ .sort(([leftKey], [rightKey]) => (leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0))
+ .map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`)
+ .join(',')}}`;
+};
+
+const sha256Json = (value: unknown) =>
+ createHash('sha256').update(stableStringify(value)).digest('hex');
+
+export interface ElasticsearchFtsSearchBulkResponse {
+ errors?: boolean;
+ items: Array<{ index: { error?: unknown; status: number } }>;
+}
+
+export interface ElasticsearchFtsSearchHttpClientOptions {
+ apiKey: string;
+ requestTimeoutMs?: number;
+ url: string;
+}
+
+export interface ElasticsearchFtsSearchSyncIndexIdentity {
+ indexUuid: string;
+ mappingSha256: string;
+ physicalIndex: string;
+ reindexRunId: string;
+ schemaVersion: number;
+ settingsSha256: string;
+}
+
+export class ElasticsearchFtsSearchRequestError extends Error {
+ readonly status?: number;
+
+ constructor(message: string, status?: number, cause?: unknown) {
+ super(message, { cause });
+ this.name = 'ElasticsearchFtsSearchRequestError';
+ this.status = status;
+ }
+}
+
+const classifyRequestError = (error: unknown): ElasticsearchFtsSearchRequestResult =>
+ error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')
+ ? 'timeout'
+ : 'other_error';
+
+const readContentLength = (response: Response): number | undefined => {
+ const header = response.headers.get('content-length');
+ if (!header) return;
+ const value = Number(header);
+ return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
+};
+
+/** HTTP transport that never logs credentials, request text, or Elasticsearch payloads. */
+export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchClient {
+ private readonly apiKey: string;
+ private readonly requestTimeoutMs: number;
+ private readonly url: URL;
+
+ constructor({ apiKey, requestTimeoutMs = 10_000, url }: ElasticsearchFtsSearchHttpClientOptions) {
+ this.apiKey = apiKey;
+ this.requestTimeoutMs = requestTimeoutMs;
+ this.url = parseElasticsearchUrl(url);
+ }
+
+ /** Fails closed unless every incremental destination is a writable alias with tombstone support. */
+ async assertFtsSearchSyncAliases(aliases: string[]): Promise<void> {
+ await this.getFtsSearchSyncWriteTargets(aliases);
+ }
+
+ private async getFtsSearchSyncWriteTargetMap(aliases: string[]) {
+ const aliasPath = aliases.map(encodeURIComponent).join(',');
+ const aliasResponse = await fetch(new URL(`/_alias/${aliasPath}`, this.url), {
+ headers: { Authorization: `ApiKey ${this.apiKey}` },
+ method: 'GET',
+ signal: AbortSignal.timeout(this.requestTimeoutMs),
+ });
+ if (!aliasResponse.ok) {
+ throw new ElasticsearchFtsSearchRequestError(
+ `Elasticsearch full-text search sync alias check failed (${aliasResponse.status})`,
+ aliasResponse.status,
+ );
+ }
+
+ let aliasJson: unknown;
+ try {
+ aliasJson = await aliasResponse.json();
+ } catch {
+ throw new ElasticsearchFtsSearchRequestError(
+ 'Elasticsearch full-text search sync alias response is not valid JSON',
+ aliasResponse.status,
+ );
+ }
+ const aliasPayload = aliasResponseSchema.safeParse(aliasJson);
+ if (!aliasPayload.success) {
+ throw new ElasticsearchFtsSearchRequestError(
+ 'Elasticsearch full-text search sync alias response has an invalid shape',
+ aliasResponse.status,
+ );
+ }
+
+ const writeTargets = new Map<string, string>();
+ for (const alias of aliases) {
+ const targets = Object.entries(aliasPayload.data).filter(([, value]) =>
+ Object.hasOwn(value.aliases, alias),
+ );
+ const explicitWriteTargets = targets.filter(
+ ([, value]) => value.aliases[alias].is_write_index === true,
+ );
+ const writeTarget =
+ explicitWriteTargets.length === 1
+ ? explicitWriteTargets[0]
+ : targets.length === 1 && targets[0][1].aliases[alias].is_write_index !== false
+ ? targets[0]
+ : undefined;
+ if (!writeTarget) {
+ throw new ElasticsearchFtsSearchRequestError(
+ `Elasticsearch full-text search sync destination is not a writable alias: ${alias}`,
+ );
+ }
+ writeTargets.set(alias, writeTarget[0]);
+ }
+
+ return writeTargets;
+ }
+
+ /** Returns each alias's unique writable physical index after validating tombstone support. */
+ async getFtsSearchSyncWriteTargets(aliases: string[]): Promise<Record<string, string>> {
+ if (aliases.length === 0) return {};
+
+ const writeTargets = await this.getFtsSearchSyncWriteTargetMap(aliases);
+
+ const physicalPath = [...new Set(writeTargets.values())].map(encodeURIComponent).join(',');
+ const mappingResponse = await fetch(
+ new URL(`/${physicalPath}/_mapping/field/fts_search_sync_deleted`, this.url),
+ {
+ headers: { Authorization: `ApiKey ${this.apiKey}` },
+ method: 'GET',
+ signal: AbortSignal.timeout(this.requestTimeoutMs),
+ },
+ );
+ if (!mappingResponse.ok) {
+ throw new ElasticsearchFtsSearchRequestError(
+ `Elasticsearch full-text search sync mapping check failed (${mappingResponse.status})`,
+ mappingResponse.status,
+ );
+ }
+
+ const mappingPayload = fieldMappingResponseSchema.safeParse(await mappingResponse.json());
+ if (!mappingPayload.success) {
+ throw new ElasticsearchFtsSearchRequestError(
+ 'Elasticsearch full-text search sync mapping response has an invalid shape',
+ mappingResponse.status,
+ mappingPayload.error,
+ );
+ }
+
+ for (const [alias, physicalIndex] of writeTargets) {
+ const mapping = mappingPayload.data[physicalIndex]?.mappings.fts_search_sync_deleted;
+ if (mapping?.mapping.fts_search_sync_deleted?.type !== 'boolean') {
+ throw new ElasticsearchFtsSearchRequestError(
+ `Elasticsearch full-text search sync alias lacks a boolean fts_search_sync_deleted mapping: ${alias}`,
+ );
+ }
+ }
+
+ return Object.fromEntries(
+ [...writeTargets].sort(([leftAlias], [rightAlias]) =>
+ leftAlias < rightAlias ? -1 : leftAlias > rightAlias ? 1 : 0,
+ ),
+ );
+ }
+
+ /** Returns stable runtime identities after validating aliases, soft deletes, and reindex metadata. */
+ async getFtsSearchSyncIndexIdentities(
+ aliases: string[],
+ ): Promise<Record<string, ElasticsearchFtsSearchSyncIndexIdentity>> {
+ if (aliases.length === 0) return {};
+
+ const writeTargets = await this.getFtsSearchSyncWriteTargetMap(aliases);
+ const physicalPath = [...new Set(writeTargets.values())]
+ .sort()
+ .map(encodeURIComponent)
+ .join(',');
+ const identityResponse = await fetch(
+ new URL(
+ `/${physicalPath}?filter_path=*.mappings,*.settings.index.analysis,*.settings.index.uuid`,
+ this.url,
+ ),
+ {
+ headers: { Authorization: `ApiKey ${this.apiKey}` },
+ method: 'GET',
+ signal: AbortSignal.timeout(this.requestTimeoutMs),
+ },
+ );
+ if (!identityResponse.ok) {
+ throw new ElasticsearchFtsSearchRequestError(
+ `Elasticsearch full-text search sync index identity check failed (${identityResponse.status})`,
+ identityResponse.status,
+ );
+ }
+
+ let payload: unknown;
+ try {
+ payload = await identityResponse.json();
+ } catch {
+ throw new ElasticsearchFtsSearchRequestError(
+ 'Elasticsearch full-text search sync index identity response is not valid JSON',
+ identityResponse.status,
+ );
+ }
+ const parsed = indexIdentityResponseSchema.safeParse(payload);
+ if (!parsed.success) {
+ throw new ElasticsearchFtsSearchRequestError(
+ 'Elasticsearch full-text search sync index identity response has an invalid shape',
+ identityResponse.status,
+ );
+ }
+
+ const identities = new Map<string, ElasticsearchFtsSearchSyncIndexIdentity>();
+ for (const [alias, physicalIndex] of writeTargets) {
+ const index = parsed.data[physicalIndex];
+ if (!index) {
+ throw new ElasticsearchFtsSearchRequestError(
+ `Elasticsearch full-text search sync index identity is missing for alias: ${alias}`,
+ );
+ }
+
+ identities.set(alias, {
+ indexUuid: index.settings.index.uuid,
+ mappingSha256: sha256Json(index.mappings),
+ physicalIndex,
+ reindexRunId: index.mappings._meta.reindex_run_id,
+ schemaVersion: index.mappings._meta.schema_version,
+ settingsSha256: sha256Json(index.settings.index.analysis),
+ });
+ }
+
+ const runIdentities = new Set(
+ [...identities.values()].map(({ reindexRunId, schemaVersion }) =>
+ JSON.stringify([reindexRunId, schemaVersion]),
+ ),
+ );
+ if (runIdentities.size !== 1) {
+ throw new ElasticsearchFtsSearchRequestError(
+ 'Elasticsearch full-text search sync aliases do not share one reindex run identity',
+ );
+ }
+
+ return Object.fromEntries(
+ [...identities].sort(([leftAlias], [rightAlias]) =>
+ leftAlias < rightAlias ? -1 : leftAlias > rightAlias ? 1 : 0,
+ ),
+ );
+ }
+
+ async bulk(body: string): Promise<ElasticsearchFtsSearchBulkResponse> {
+ const endpoint = new URL('/_bulk?require_alias=true', this.url);
+ const response = await fetch(endpoint, {
+ body,
+ headers: {
+ 'Authorization': `ApiKey ${this.apiKey}`,
+ 'Content-Type': 'application/x-ndjson',
+ },
+ method: 'POST',
+ signal: AbortSignal.timeout(this.requestTimeoutMs),
+ });
+
+ if (!response.ok) {
+ throw new ElasticsearchFtsSearchRequestError(
+ `Elasticsearch bulk request failed (${response.status})`,
+ response.status,
+ );
+ }
+
+ let payload: unknown;
+ try {
+ payload = await response.json();
+ } catch (error) {
+ throw new ElasticsearchFtsSearchRequestError(
+ 'Elasticsearch bulk response is not valid JSON',
+ response.status,
+ error,
+ );
+ }
+
+ const parsed = bulkResponseSchema.safeParse(payload);
+ if (!parsed.success) {
+ throw new ElasticsearchFtsSearchRequestError(
+ 'Elasticsearch bulk response has an invalid shape',
+ response.status,
+ parsed.error,
+ );
+ }
+
+ return parsed.data;
+ }
+
+ async search(input: ElasticsearchFtsSearchInput): Promise<ElasticsearchFtsSearchResponse> {
+ const endpoint = new URL(`/${encodeURIComponent(input.index)}/_search`, this.url);
+ const body = JSON.stringify(input.body);
+ const requestBytes = Buffer.byteLength(body);
+ const startedAt = Date.now();
+ let contentLength: number | undefined;
+ let decodedBytes: number | undefined;
+ let recorded = false;
+ const record = (
+ result: ElasticsearchFtsSearchRequestResult,
+ hits?: number,
+ serverTookMs?: number,
+ ) => {
+ recorded = true;
+ recordElasticsearchFtsSearchRequest({
+ contentLength,
+ decodedBytes,
+ durationMs: Date.now() - startedAt,
+ entity: input.entity,
+ hits,
+ pagination: input.pagination,
+ requestBytes,
+ result,
+ serverTookMs,
+ });
+ };
+
+ try {
+ const response = await fetch(endpoint, {
+ body,
+ headers: {
+ 'Authorization': `ApiKey ${this.apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ method: 'POST',
+ signal: AbortSignal.timeout(this.requestTimeoutMs),
+ });
+ contentLength = readContentLength(response);
+
+ if (!response.ok) {
+ record('http_error');
+ throw new ElasticsearchFtsSearchRequestError(
+ `Elasticsearch search request failed (${response.status})`,
+ response.status,
+ );
+ }
+
+ let payload: unknown;
+ try {
+ const responseText = await response.text();
+ decodedBytes = Buffer.byteLength(responseText);
+ payload = JSON.parse(responseText);
+ } catch (error) {
+ record(error instanceof SyntaxError ? 'parse_error' : classifyRequestError(error));
+ throw new ElasticsearchFtsSearchRequestError(
+ 'Elasticsearch search response is not valid JSON',
+ response.status,
+ error,
+ );
+ }
+
+ const parsed = searchResponseSchema.safeParse(payload);
+ if (!parsed.success) {
+ record('parse_error');
+ throw new ElasticsearchFtsSearchRequestError(
+ 'Elasticsearch search response has an invalid shape',
+ response.status,
+ parsed.error,
+ );
+ }
+
+ record('success', parsed.data.hits.hits.length, parsed.data.took);
+ return parsed.data;
+ } catch (error) {
+ if (!recorded) record(classifyRequestError(error));
+ throw error;
+ }
+ }
+}
diff --git a/apps/server/src/services/ftsSearch/index.test.ts b/apps/server/src/services/ftsSearch/index.test.ts
new file mode 100644
index 00000000000..f26bc6df247
--- /dev/null
+++ b/apps/server/src/services/ftsSearch/index.test.ts
@@ -0,0 +1,173 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { FtsSearchAgentResult, FtsSearchBackend } from '@/database/repositories/ftsSearch';
+
+import {
+ createFtsSearchRepo,
+ FTS_SEARCH_PROVIDERS,
+ FtsSearchBackendUnavailableError,
+ resolveFtsSearchProvider,
+} from './index';
+
+const db = {} as LobeChatDatabase;
+
+const agentResult: FtsSearchAgentResult = {
+ avatar: null,
+ backgroundColor: null,
+ createdAt: new Date('2026-08-26T00:00:00.000Z'),
+ description: 'Candidate result',
+ id: 'agent-1',
+ relevance: 1,
+ slug: null,
+ tags: [],
+ title: 'Candidate Agent',
+ type: 'agent',
+ updatedAt: new Date('2026-08-26T00:00:00.000Z'),
+};
+
+describe('full-text search provider selection', () => {
+ it('selects pg_search from deployment configuration', () => {
+ expect(
+ resolveFtsSearchProvider({
+ loadFtsSearchProvider: () => FTS_SEARCH_PROVIDERS.pgSearch,
+ }),
+ ).toBe(FTS_SEARCH_PROVIDERS.pgSearch);
+ });
+
+ it('selects Elasticsearch from deployment configuration', () => {
+ expect(
+ resolveFtsSearchProvider({
+ loadFtsSearchProvider: () => FTS_SEARCH_PROVIDERS.elasticsearch,
+ }),
+ ).toBe(FTS_SEARCH_PROVIDERS.elasticsearch);
+ });
+
+ it('routes the stable repository facade through the selected backend', async () => {
+ const search = vi.fn<FtsSearchBackend['search']>().mockResolvedValue({
+ candidates: [{ id: agentResult.id, score: 9.5 }],
+ items: [agentResult],
+ });
+ const createBackend = vi.fn(({ provider }): FtsSearchBackend => ({ key: provider, search }));
+ const repo = await createFtsSearchRepo(
+ { db, userId: 'allowed-user' },
+ {
+ createBackend,
+ loadFtsSearchProvider: () => FTS_SEARCH_PROVIDERS.elasticsearch,
+ },
+ );
+
+ await expect(repo.search({ query: 'candidate', type: 'agent' })).resolves.toEqual([
+ agentResult,
+ ]);
+ expect(createBackend).toHaveBeenCalledWith(
+ expect.objectContaining({ provider: FTS_SEARCH_PROVIDERS.elasticsearch }),
+ );
+ expect(repo.ftsSearchCandidateEnabled).toBe(true);
+ });
+
+ it('constructs the Elasticsearch backend from deployment-owned configuration', async () => {
+ const search = vi.fn().mockResolvedValue({ hits: { hits: [] } });
+ const createElasticsearchClient = vi.fn(() => ({ search }));
+ const config = {
+ apiKey: 'test-api-key',
+ indexNamespace: 'lobehub-dev',
+ url: 'https://search.example.com',
+ };
+ const repo = await createFtsSearchRepo(
+ { db, userId: 'allowed-user' },
+ {
+ createElasticsearchClient,
+ loadElasticsearchConfig: () => config,
+ loadFtsSearchProvider: () => FTS_SEARCH_PROVIDERS.elasticsearch,
+ },
+ );
+
+ await expect(repo.search({ query: 'candidate', type: 'agent' })).resolves.toEqual([]);
+ expect(createElasticsearchClient).toHaveBeenCalledWith(config);
+ expect(search).toHaveBeenCalledWith(expect.objectContaining({ index: 'lobehub-dev-agents' }));
+ });
+
+ it('routes unified memory search to Elasticsearch when configured', async () => {
+ const elasticsearchSearch = vi.fn().mockResolvedValue({ hits: { hits: [] } });
+ const pgSearch = vi.fn<FtsSearchBackend['search']>().mockResolvedValue({
+ candidates: [],
+ items: [],
+ });
+ const repo = await createFtsSearchRepo(
+ { db, userId: 'allowed-user' },
+ {
+ createElasticsearchClient: () => ({ search: elasticsearchSearch }),
+ createPgSearchBackend: () => ({ key: 'pg_search', search: pgSearch }),
+ loadElasticsearchConfig: () => ({
+ apiKey: 'test-api-key',
+ indexNamespace: 'lobehub-dev',
+ url: 'https://search.example.com',
+ }),
+ loadFtsSearchProvider: () => FTS_SEARCH_PROVIDERS.elasticsearch,
+ },
+ );
+
+ await expect(repo.search({ query: 'candidate' })).resolves.toEqual([]);
+ expect(elasticsearchSearch).toHaveBeenCalledTimes(9);
+ expect(pgSearch).not.toHaveBeenCalled();
+ });
+
+ it('does not fall back to pg_search when a migrated Elasticsearch request fails', async () => {
+ const providerError = new Error('Elasticsearch backend unavailable');
+ const pgSearch = vi.fn<FtsSearchBackend['search']>().mockResolvedValue({
+ candidates: [],
+ items: [],
+ });
+ const repo = await createFtsSearchRepo(
+ { db, userId: 'allowed-user' },
+ {
+ createElasticsearchClient: () => ({
+ search: vi.fn().mockRejectedValue(providerError),
+ }),
+ createPgSearchBackend: () => ({ key: 'pg_search', search: pgSearch }),
+ loadElasticsearchConfig: () => ({
+ apiKey: 'test-api-key',
+ indexNamespace: 'lobehub-dev',
+ url: 'https://search.example.com',
+ }),
+ loadFtsSearchProvider: () => FTS_SEARCH_PROVIDERS.elasticsearch,
+ },
+ );
+
+ await expect(repo.search({ query: 'failure', type: 'agent' })).rejects.toBe(providerError);
+ expect(pgSearch).not.toHaveBeenCalled();
+ });
+
+ it('fails explicitly when the selected provider is not configured', async () => {
+ await expect(
+ createFtsSearchRepo(
+ { db, userId: 'user-1' },
+ {
+ loadElasticsearchConfig: () => undefined,
+ loadFtsSearchProvider: () => FTS_SEARCH_PROVIDERS.elasticsearch,
+ },
+ ),
+ ).rejects.toEqual(new FtsSearchBackendUnavailableError(FTS_SEARCH_PROVIDERS.elasticsearch));
+ });
+
+ it('surfaces Elasticsearch failures without retrying pg_search', async () => {
+ const providerError = new Error('Elasticsearch backend unavailable');
+ const search = vi.fn<FtsSearchBackend['search']>().mockRejectedValue(providerError);
+ const createBackend = vi.fn(({ provider }): FtsSearchBackend => ({ key: provider, search }));
+ const repo = await createFtsSearchRepo(
+ { db, userId: 'user-1' },
+ {
+ createBackend,
+ loadFtsSearchProvider: () => FTS_SEARCH_PROVIDERS.elasticsearch,
+ },
+ );
+
+ await expect(repo.search({ query: 'failure', type: 'agent' })).rejects.toBe(providerError);
+ expect(createBackend).toHaveBeenCalledTimes(1);
+ expect(createBackend).toHaveBeenCalledWith(
+ expect.objectContaining({ provider: FTS_SEARCH_PROVIDERS.elasticsearch }),
+ );
+ });
+});
diff --git a/apps/server/src/services/ftsSearch/index.ts b/apps/server/src/services/ftsSearch/index.ts
new file mode 100644
index 00000000000..ac84995d9f4
--- /dev/null
+++ b/apps/server/src/services/ftsSearch/index.ts
@@ -0,0 +1,161 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+
+import {
+ ElasticsearchFtsSearchBackend,
+ type ElasticsearchFtsSearchClient,
+ type FtsSearchBackend,
+ type FtsSearchBackendScope,
+ FtsSearchRepo,
+ type FtsSearchRepoOptions,
+ isElasticsearchFtsSearchEntity,
+ PgSearchFtsSearchBackend,
+} from '@/database/repositories/ftsSearch';
+import { ftsSearchEnv } from '@/envs/ftsSearch';
+
+import { ElasticsearchFtsSearchHttpClient } from './elasticsearch';
+import {
+ createElasticsearchFtsSearchObserver,
+ withFtsSearchBackendObservability,
+} from './observability';
+
+export interface CreateFtsSearchRepoInput {
+ callerAgentVisibility?: 'private' | 'public' | null;
+ db: LobeChatDatabase;
+ options?: FtsSearchRepoOptions;
+ userId: string;
+ workspaceId?: string;
+}
+
+export const FTS_SEARCH_PROVIDERS = {
+ elasticsearch: 'elasticsearch',
+ pgSearch: 'pg_search',
+} as const;
+
+/** Deployment-selected implementation identity that resolves to an executable search backend. */
+export type FtsSearchProvider = (typeof FTS_SEARCH_PROVIDERS)[keyof typeof FTS_SEARCH_PROVIDERS];
+
+interface FtsSearchBackendFactoryContext {
+ db: CreateFtsSearchRepoInput['db'];
+ provider: FtsSearchProvider;
+ scope: FtsSearchBackendScope;
+}
+
+interface FtsSearchBackendFactoryDependencies {
+ createBackend?: (context: FtsSearchBackendFactoryContext) => FtsSearchBackend | undefined;
+ createElasticsearchClient?: (
+ config: ElasticsearchFtsSearchConfig,
+ ) => ElasticsearchFtsSearchClient;
+ createPgSearchBackend?: (context: FtsSearchBackendFactoryContext) => FtsSearchBackend;
+ loadElasticsearchConfig?: () => ElasticsearchFtsSearchConfig | undefined;
+ loadFtsSearchProvider?: () => FtsSearchProvider;
+}
+
+export interface ElasticsearchFtsSearchConfig {
+ apiKey: string;
+ indexNamespace: string;
+ url: string;
+}
+
+export class FtsSearchBackendUnavailableError extends Error {
+ readonly provider: FtsSearchProvider;
+
+ constructor(provider: FtsSearchProvider) {
+ super(`Full-text search backend provider is not configured: ${provider}`);
+ this.name = 'FtsSearchBackendUnavailableError';
+ this.provider = provider;
+ }
+}
+
+export const loadElasticsearchFtsSearchConfig = (): ElasticsearchFtsSearchConfig | undefined => {
+ const indexNamespace =
+ ftsSearchEnv.ES_INDEX_NAMESPACE ??
+ (process.env.NODE_ENV === 'development' ? 'lobehub-dev' : undefined);
+ if (!ftsSearchEnv.ES_API_KEY || !ftsSearchEnv.ES_URL || !indexNamespace) return;
+
+ return {
+ apiKey: ftsSearchEnv.ES_API_KEY,
+ indexNamespace,
+ url: ftsSearchEnv.ES_URL,
+ };
+};
+
+const createFtsSearchBackendForProvider = (
+ { db, provider, scope }: FtsSearchBackendFactoryContext,
+ dependencies: FtsSearchBackendFactoryDependencies,
+): FtsSearchBackend | undefined => {
+ const createPgSearchBackend =
+ dependencies.createPgSearchBackend ??
+ ((context: FtsSearchBackendFactoryContext) =>
+ new PgSearchFtsSearchBackend(context.db, context.scope));
+ const pgSearchBackend = createPgSearchBackend({ db, provider, scope });
+
+ if (provider === FTS_SEARCH_PROVIDERS.pgSearch) {
+ return pgSearchBackend;
+ }
+
+ const config = (dependencies.loadElasticsearchConfig ?? loadElasticsearchFtsSearchConfig)();
+ if (!config) return;
+
+ const client = (
+ dependencies.createElasticsearchClient ??
+ ((input) => new ElasticsearchFtsSearchHttpClient(input))
+ )(config);
+ const elasticsearchBackend = new ElasticsearchFtsSearchBackend(db, {
+ client,
+ indexNamespace: config.indexNamespace,
+ observer: createElasticsearchFtsSearchObserver(),
+ });
+
+ return {
+ key: `${elasticsearchBackend.key}+${pgSearchBackend.key}`,
+ /** Unmigrated entities stay on pg_search; Elasticsearch failures on migrated entities remain fatal. */
+ search: (request) =>
+ isElasticsearchFtsSearchEntity(request.entity)
+ ? elasticsearchBackend.search(request)
+ : pgSearchBackend.search(request),
+ };
+};
+
+export const resolveFtsSearchProvider = (
+ dependencies: FtsSearchBackendFactoryDependencies = {},
+): FtsSearchProvider => dependencies.loadFtsSearchProvider?.() ?? ftsSearchEnv.FTS_SEARCH_PROVIDER;
+
+/**
+ * Resolve the deployment-configured provider before constructing the stable repository facade.
+ * Missing Elasticsearch configuration and provider failures remain visible; this layer never
+ * falls back to pg_search.
+ */
+export const createFtsSearchRepo = async (
+ input: CreateFtsSearchRepoInput,
+ dependencies: FtsSearchBackendFactoryDependencies = {},
+) => {
+ const scope: FtsSearchBackendScope = {
+ callerAgentVisibility: input.callerAgentVisibility,
+ userId: input.userId,
+ workspaceId: input.workspaceId,
+ };
+ const provider = resolveFtsSearchProvider(dependencies);
+ const context = {
+ db: input.db,
+ provider,
+ scope,
+ };
+ const backend = dependencies.createBackend
+ ? dependencies.createBackend(context)
+ : createFtsSearchBackendForProvider(context, dependencies);
+
+ if (!backend) throw new FtsSearchBackendUnavailableError(provider);
+
+ const observedBackend = withFtsSearchBackendObservability(backend, (request) =>
+ provider === FTS_SEARCH_PROVIDERS.elasticsearch &&
+ !isElasticsearchFtsSearchEntity(request.entity)
+ ? FTS_SEARCH_PROVIDERS.pgSearch
+ : provider,
+ );
+
+ return new FtsSearchRepo(input.db, input.userId, input.workspaceId, input.callerAgentVisibility, {
+ ...input.options,
+ backend: observedBackend,
+ ftsSearchCandidateEnabled: provider === FTS_SEARCH_PROVIDERS.elasticsearch,
+ });
+};
diff --git a/apps/server/src/services/ftsSearch/observability.test.ts b/apps/server/src/services/ftsSearch/observability.test.ts
new file mode 100644
index 00000000000..647ef2aba79
--- /dev/null
+++ b/apps/server/src/services/ftsSearch/observability.test.ts
@@ -0,0 +1,217 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { FtsSearchBackend } from '@/database/repositories/ftsSearch';
+
+import {
+ buildFtsSearchBackendMetricAttributes,
+ recordElasticsearchFtsSearchRequest,
+ withFtsSearchBackendObservability,
+} from './observability';
+
+const mocks = vi.hoisted(() => {
+ const counters = new Map<string, { add: ReturnType<typeof vi.fn> }>();
+ const histograms = new Map<string, { record: ReturnType<typeof vi.fn> }>();
+ const span = {
+ end: vi.fn(),
+ setAttribute: vi.fn(),
+ setStatus: vi.fn(),
+ };
+ const startActiveSpan = vi.fn(
+ (_name: string, _options: unknown, callback: (span: unknown) => unknown) => callback(span),
+ );
+ return { counters, histograms, span, startActiveSpan };
+});
+
+vi.mock('@lobechat/observability-otel/api', () => ({
+ diag: { error: vi.fn() },
+ metrics: {
+ getMeter: () => ({
+ createCounter: (name: string) => {
+ const counter = { add: vi.fn() };
+ mocks.counters.set(name, counter);
+ return counter;
+ },
+ createHistogram: (name: string) => {
+ const histogram = { record: vi.fn() };
+ mocks.histograms.set(name, histogram);
+ return histogram;
+ },
+ }),
+ },
+ SpanStatusCode: { ERROR: 2, OK: 1 },
+ trace: {
+ getTracer: () => ({
+ startActiveSpan: mocks.startActiveSpan,
+ }),
+ },
+}));
+
+describe('full-text search backend observability', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('builds a bounded metric label set without request or scope identifiers', () => {
+ expect(
+ buildFtsSearchBackendMetricAttributes({
+ entity: 'messages',
+ operation: 'pg_hydration',
+ provider: 'elasticsearch',
+ result: 'success',
+ }),
+ ).toEqual({
+ entity: 'messages',
+ operation: 'pg_hydration',
+ provider: 'elasticsearch',
+ result: 'success',
+ });
+ });
+
+ it('observes the PostgreSQL product path and preserves its response', async () => {
+ const response = { candidates: [], items: [] };
+ const backend: FtsSearchBackend = {
+ key: 'pg_search',
+ search: vi.fn().mockResolvedValue(response),
+ };
+ const resolveProvider = vi.fn(() => 'pg_search' as const);
+ const observed = withFtsSearchBackendObservability(backend, resolveProvider);
+ const request = {
+ entity: 'agents',
+ filters: {},
+ pagination: { limit: 5 },
+ query: { text: 'private query' },
+ scope: { userId: 'private-user', workspaceId: 'private-workspace' },
+ } as const;
+
+ await expect(observed.search(request)).resolves.toBe(response);
+ expect(resolveProvider).toHaveBeenCalledWith(request);
+ const resultCount = mocks.histograms.get('fts_search_backend_result_count')?.record;
+ expect(resultCount).toHaveBeenCalledWith(5, {
+ entity: 'agents',
+ pagination: 'bounded',
+ provider: 'pg_search',
+ stage: 'requested',
+ });
+ expect(resultCount).toHaveBeenCalledWith(0, {
+ entity: 'agents',
+ pagination: 'bounded',
+ provider: 'pg_search',
+ stage: 'candidate',
+ });
+ expect(mocks.startActiveSpan).toHaveBeenCalledWith(
+ 'fts.search.backend.product_path',
+ {
+ attributes: {
+ 'fts.search.backend.entity': 'agents',
+ 'fts.search.backend.operation': 'product_path',
+ 'fts.search.backend.provider': 'pg_search',
+ },
+ },
+ expect.any(Function),
+ );
+ expect(mocks.span.setAttribute).toHaveBeenCalledWith('fts.search.backend.result', 'success');
+ });
+
+ it('does not record a requested result count for unbounded pagination', async () => {
+ const response = { candidates: [], items: [] };
+ const backend: FtsSearchBackend = {
+ key: 'pg_search',
+ search: vi.fn().mockResolvedValue(response),
+ };
+ const observed = withFtsSearchBackendObservability(backend, () => 'pg_search');
+
+ await expect(
+ observed.search({
+ entity: 'agents',
+ filters: {},
+ pagination: {},
+ query: { text: 'private query' },
+ scope: { userId: 'private-user' },
+ }),
+ ).resolves.toBe(response);
+
+ const resultCount = mocks.histograms.get('fts_search_backend_result_count')?.record;
+ expect(resultCount).toHaveBeenCalledTimes(2);
+ expect(resultCount).toHaveBeenCalledWith(0, {
+ entity: 'agents',
+ pagination: 'unbounded',
+ provider: 'pg_search',
+ stage: 'candidate',
+ });
+ expect(resultCount).toHaveBeenCalledWith(0, {
+ entity: 'agents',
+ pagination: 'unbounded',
+ provider: 'pg_search',
+ stage: 'product',
+ });
+ });
+
+ it('records actual Elasticsearch cost signals with only bounded dimensions', () => {
+ recordElasticsearchFtsSearchRequest({
+ contentLength: 1024,
+ decodedBytes: 2048,
+ durationMs: 40,
+ entity: 'messages',
+ hits: 20,
+ pagination: 'bounded',
+ requestBytes: 512,
+ result: 'success',
+ serverTookMs: 12,
+ });
+
+ const attributes = { entity: 'messages', pagination: 'bounded', result: 'success' };
+ expect(mocks.counters.get('fts_search_elasticsearch_requests_total')?.add).toHaveBeenCalledWith(
+ 1,
+ attributes,
+ );
+ expect(
+ mocks.histograms.get('fts_search_elasticsearch_server_took')?.record,
+ ).toHaveBeenCalledWith(12, attributes);
+ expect(
+ mocks.histograms.get('fts_search_elasticsearch_response_decoded_size')?.record,
+ ).toHaveBeenCalledWith(2048, attributes);
+ expect(Object.keys(attributes)).toEqual(['entity', 'pagination', 'result']);
+ });
+
+ it('preserves the selected provider error', async () => {
+ const providerError = new Error('provider unavailable');
+ const backend: FtsSearchBackend = {
+ key: 'elasticsearch',
+ search: vi.fn().mockRejectedValue(providerError),
+ };
+ const observed = withFtsSearchBackendObservability(backend, () => 'elasticsearch');
+
+ await expect(
+ observed.search({
+ entity: 'messages',
+ filters: {},
+ pagination: { limit: 5 },
+ query: { text: 'private query' },
+ scope: { userId: 'private-user' },
+ }),
+ ).rejects.toBe(providerError);
+ });
+
+ it('does not change the provider result when telemetry finalization fails', async () => {
+ const response = { candidates: [], items: [] };
+ const backend: FtsSearchBackend = {
+ key: 'pg_search',
+ search: vi.fn().mockResolvedValue(response),
+ };
+ const observed = withFtsSearchBackendObservability(backend, () => 'pg_search');
+ mocks.span.end.mockImplementationOnce(() => {
+ throw new Error('telemetry unavailable');
+ });
+
+ await expect(
+ observed.search({
+ entity: 'agents',
+ filters: {},
+ pagination: { limit: 5 },
+ query: { text: 'private query' },
+ scope: { userId: 'private-user' },
+ }),
+ ).resolves.toBe(response);
+ });
+});
diff --git a/apps/server/src/services/ftsSearch/observability.ts b/apps/server/src/services/ftsSearch/observability.ts
new file mode 100644
index 00000000000..74828e3b579
--- /dev/null
+++ b/apps/server/src/services/ftsSearch/observability.ts
@@ -0,0 +1,239 @@
+import type { Attributes, Span } from '@lobechat/observability-otel/api';
+import { diag, metrics, SpanStatusCode, trace } from '@lobechat/observability-otel/api';
+
+import type {
+ ElasticsearchFtsSearchEntity,
+ ElasticsearchFtsSearchObserver,
+ FtsSearchBackend,
+ FtsSearchBackendEntity,
+ FtsSearchBackendRequest,
+ FtsSearchBackendResponse,
+} from '@/database/repositories/ftsSearch';
+
+import type { FtsSearchProvider } from '.';
+
+export type FtsSearchBackendOperation = 'candidate_query' | 'pg_hydration' | 'product_path';
+export type FtsSearchBackendOperationResult = 'error' | 'success';
+export type ElasticsearchFtsSearchRequestResult =
+ 'http_error' | 'other_error' | 'parse_error' | 'success' | 'timeout';
+
+export interface FtsSearchBackendOperationAttributes {
+ entity: FtsSearchBackendEntity;
+ operation: FtsSearchBackendOperation;
+ provider: FtsSearchProvider;
+ result: FtsSearchBackendOperationResult;
+}
+
+type FtsSearchBackendOperationBaseAttributes = Omit<FtsSearchBackendOperationAttributes, 'result'>;
+
+const meter = metrics.getMeter('fts-search-backend');
+const tracer = trace.getTracer('fts.search.backend');
+
+const operationCounter = meter.createCounter('fts_search_backend_operations_total', {
+ description:
+ 'Full-text search backend operations grouped by provider, entity, operation, and result.',
+ unit: '{operation}',
+});
+
+const operationDuration = meter.createHistogram('fts_search_backend_operation_duration', {
+ description:
+ 'Full-text search backend operation duration by provider, entity, operation, and result.',
+ unit: 'ms',
+});
+
+const resultCount = meter.createHistogram('fts_search_backend_result_count', {
+ description: 'Requested, candidate, and hydrated product result counts for successful searches.',
+});
+
+const elasticsearchRequests = meter.createCounter('fts_search_elasticsearch_requests_total', {
+ description: 'Actual Elasticsearch search requests grouped by entity and result.',
+ unit: '{request}',
+});
+
+const elasticsearchRequestDuration = meter.createHistogram(
+ 'fts_search_elasticsearch_request_duration',
+ {
+ description: 'End-to-end Elasticsearch search request duration including response parsing.',
+ unit: 'ms',
+ },
+);
+
+const elasticsearchRequestBytes = meter.createHistogram('fts_search_elasticsearch_request_size', {
+ description: 'Serialized Elasticsearch search request body size.',
+ unit: 'By',
+});
+
+const elasticsearchServerTook = meter.createHistogram('fts_search_elasticsearch_server_took', {
+ description: 'Elasticsearch-reported server processing time for successful search requests.',
+ unit: 'ms',
+});
+
+const elasticsearchResponseContentLength = meter.createHistogram(
+ 'fts_search_elasticsearch_response_content_length',
+ {
+ description: 'Elasticsearch search response Content-Length when provided.',
+ unit: 'By',
+ },
+);
+
+const elasticsearchResponseDecodedBytes = meter.createHistogram(
+ 'fts_search_elasticsearch_response_decoded_size',
+ {
+ description: 'Decoded Elasticsearch search response body size.',
+ unit: 'By',
+ },
+);
+
+const elasticsearchResponseHits = meter.createHistogram('fts_search_elasticsearch_response_hits', {
+ description: 'Hits returned by each Elasticsearch search request.',
+});
+
+const recordSafely = (operation: string, record: () => void): void => {
+ try {
+ record();
+ } catch (error) {
+ /** Telemetry failures must never change the selected search provider's behavior. */
+ diag.error(`[fts-search-backend] failed to record ${operation}`, error);
+ }
+};
+
+/** Metric labels are deliberately limited to bounded rollout dimensions. */
+export const buildFtsSearchBackendMetricAttributes = (
+ attributes: FtsSearchBackendOperationAttributes,
+): Attributes => ({
+ entity: attributes.entity,
+ operation: attributes.operation,
+ provider: attributes.provider,
+ result: attributes.result,
+});
+
+const finishOperation = (
+ span: Span,
+ startedAt: number,
+ attributes: FtsSearchBackendOperationBaseAttributes,
+ result: FtsSearchBackendOperationResult,
+) => {
+ const metricAttributes = buildFtsSearchBackendMetricAttributes({ ...attributes, result });
+ recordSafely('operation metrics', () => {
+ operationCounter.add(1, metricAttributes);
+ operationDuration.record(Date.now() - startedAt, metricAttributes);
+ span.setAttribute('fts.search.backend.result', result);
+ span.setStatus({ code: result === 'success' ? SpanStatusCode.OK : SpanStatusCode.ERROR });
+ });
+ try {
+ span.end();
+ } catch (error) {
+ diag.error('[fts-search-backend] failed to end telemetry span', error);
+ }
+};
+
+export const recordElasticsearchFtsSearchRequest = (input: {
+ contentLength?: number;
+ decodedBytes?: number;
+ durationMs: number;
+ entity: ElasticsearchFtsSearchEntity;
+ hits?: number;
+ pagination: 'bounded' | 'unbounded';
+ requestBytes: number;
+ result: ElasticsearchFtsSearchRequestResult;
+ serverTookMs?: number;
+}): void => {
+ recordSafely('Elasticsearch search request', () => {
+ const attributes: Attributes = {
+ entity: input.entity,
+ pagination: input.pagination,
+ result: input.result,
+ };
+ elasticsearchRequests.add(1, attributes);
+ elasticsearchRequestDuration.record(input.durationMs, attributes);
+ elasticsearchRequestBytes.record(input.requestBytes, attributes);
+ if (input.contentLength !== undefined) {
+ elasticsearchResponseContentLength.record(input.contentLength, attributes);
+ }
+ if (input.decodedBytes !== undefined) {
+ elasticsearchResponseDecodedBytes.record(input.decodedBytes, attributes);
+ }
+ if (input.hits !== undefined) elasticsearchResponseHits.record(input.hits, attributes);
+ if (input.serverTookMs !== undefined) {
+ elasticsearchServerTook.record(input.serverTookMs, attributes);
+ }
+ });
+};
+
+const recordFtsSearchBackendResult = (
+ provider: FtsSearchProvider,
+ request: FtsSearchBackendRequest,
+ response: FtsSearchBackendResponse,
+): void => {
+ recordSafely('search result counts', () => {
+ const requestedLimit = request.pagination.limit;
+ const hasValidRequestedLimit =
+ typeof requestedLimit === 'number' && Number.isFinite(requestedLimit) && requestedLimit > 0;
+ const baseAttributes = {
+ entity: request.entity,
+ pagination: hasValidRequestedLimit ? 'bounded' : 'unbounded',
+ provider,
+ };
+ if (hasValidRequestedLimit) {
+ resultCount.record(requestedLimit, { ...baseAttributes, stage: 'requested' });
+ }
+ resultCount.record(response.candidates.length, {
+ ...baseAttributes,
+ stage: 'candidate',
+ });
+ resultCount.record(response.items.length, { ...baseAttributes, stage: 'product' });
+ });
+};
+
+export const observeFtsSearchBackendOperation = async <Result>(
+ attributes: FtsSearchBackendOperationBaseAttributes,
+ operation: () => Promise<Result>,
+): Promise<Result> =>
+ tracer.startActiveSpan(
+ `fts.search.backend.${attributes.operation}`,
+ {
+ attributes: {
+ 'fts.search.backend.entity': attributes.entity,
+ 'fts.search.backend.operation': attributes.operation,
+ 'fts.search.backend.provider': attributes.provider,
+ },
+ },
+ async (span) => {
+ const startedAt = Date.now();
+ try {
+ const result = await operation();
+ finishOperation(span, startedAt, attributes, 'success');
+ return result;
+ } catch (error) {
+ finishOperation(span, startedAt, attributes, 'error');
+ throw error;
+ }
+ },
+ );
+
+export const createElasticsearchFtsSearchObserver = (): ElasticsearchFtsSearchObserver => ({
+ observe: (entity, operation, callback) =>
+ observeFtsSearchBackendOperation({ entity, operation, provider: 'elasticsearch' }, callback),
+});
+
+export const withFtsSearchBackendObservability = (
+ backend: FtsSearchBackend,
+ resolveProvider: (request: FtsSearchBackendRequest) => FtsSearchProvider,
+): FtsSearchBackend => ({
+ key: backend.key,
+ search: (request) => {
+ const provider = resolveProvider(request);
+ return observeFtsSearchBackendOperation(
+ {
+ entity: request.entity,
+ operation: 'product_path',
+ provider,
+ },
+ async () => {
+ const response = await backend.search(request);
+ recordFtsSearchBackendResult(provider, request, response);
+ return response;
+ },
+ );
+ },
+});
diff --git a/apps/server/src/services/ftsSearchSync/index.ts b/apps/server/src/services/ftsSearchSync/index.ts
new file mode 100644
index 00000000000..5d66300ab4f
--- /dev/null
+++ b/apps/server/src/services/ftsSearchSync/index.ts
@@ -0,0 +1,18 @@
+export {
+ getFtsSearchSyncService,
+ isFtsSearchSyncEnabled,
+ verifyFtsSearchSyncReadiness,
+} from './runtime';
+export type { FtsSearchSyncBulkRequestSample, FtsSearchSyncDrainResult } from './service';
+export {
+ FTS_SEARCH_SYNC_BULK_MAX_BYTES,
+ FTS_SEARCH_SYNC_CLAIM_LIMIT,
+ FTS_SEARCH_SYNC_MAX_BULK_REQUESTS,
+ FTS_SEARCH_SYNC_PROJECTION_BATCH_SIZE,
+ FtsSearchSyncService,
+} from './service';
+export type {
+ FtsSearchSyncOutboxStats,
+ FtsSearchSyncWork,
+} from '@/database/repositories/ftsSearchSyncOutbox';
+export { ftsSearchSyncOutboxRepository } from '@/database/repositories/ftsSearchSyncOutbox/server';
diff --git a/apps/server/src/services/ftsSearchSync/runtime.test.ts b/apps/server/src/services/ftsSearchSync/runtime.test.ts
new file mode 100644
index 00000000000..1f80372707e
--- /dev/null
+++ b/apps/server/src/services/ftsSearchSync/runtime.test.ts
@@ -0,0 +1,130 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ assertFtsSearchSyncAliases: vi.fn(),
+ elasticsearchClient: vi.fn(),
+ loadElasticsearchFtsSearchConfig: vi.fn(),
+ searchDocumentBuilder: vi.fn(),
+ ftsSearchEnv: { FTS_SEARCH_SYNC_ENABLED: undefined as 'false' | 'true' | undefined },
+ assertCaptureInfrastructure: vi.fn(),
+}));
+
+vi.mock('@/envs/ftsSearch', () => ({ ftsSearchEnv: mocks.ftsSearchEnv }));
+
+vi.mock('@/database/repositories/ftsSearchDocument', () => ({
+ getFtsSearchIndexAlias: (namespace: string, entity: string) => `${namespace}-${entity}`,
+ FTS_SEARCH_DOCUMENT_ENTITIES: ['agents', 'messages'],
+ FtsSearchDocumentBuilder: mocks.searchDocumentBuilder,
+}));
+
+vi.mock('@/database/repositories/ftsSearchSyncOutbox/server', () => ({
+ ftsSearchSyncOutboxRepository: {
+ assertCaptureInfrastructure: mocks.assertCaptureInfrastructure,
+ claim: vi.fn(),
+ },
+}));
+
+vi.mock('@/database/server', () => ({ serverDB: { id: 'database' } }));
+
+vi.mock('../ftsSearch', () => ({
+ loadElasticsearchFtsSearchConfig: mocks.loadElasticsearchFtsSearchConfig,
+}));
+
+vi.mock('../ftsSearch/elasticsearch', () => ({
+ ElasticsearchFtsSearchHttpClient: mocks.elasticsearchClient,
+}));
+
+const config = {
+ apiKey: 'test-api-key',
+ indexNamespace: 'lobehub-test',
+ url: 'https://elasticsearch.example.com',
+};
+
+const loadRuntime = () => import('./runtime');
+
+describe('full-text search sync runtime', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.resetModules();
+ mocks.ftsSearchEnv.FTS_SEARCH_SYNC_ENABLED = undefined;
+ mocks.loadElasticsearchFtsSearchConfig.mockReturnValue(config);
+ mocks.elasticsearchClient.mockImplementation(() => ({
+ assertFtsSearchSyncAliases: mocks.assertFtsSearchSyncAliases,
+ bulk: vi.fn(),
+ }));
+ mocks.searchDocumentBuilder.mockImplementation(() => ({ buildByIds: vi.fn() }));
+ });
+
+ it('reports incremental sync as enabled only when the flag and configuration are present', async () => {
+ const { isFtsSearchSyncEnabled } = await loadRuntime();
+
+ expect(isFtsSearchSyncEnabled()).toBe(false);
+
+ mocks.ftsSearchEnv.FTS_SEARCH_SYNC_ENABLED = 'true';
+ expect(isFtsSearchSyncEnabled()).toBe(true);
+
+ mocks.loadElasticsearchFtsSearchConfig.mockReturnValue(undefined);
+ expect(isFtsSearchSyncEnabled()).toBe(false);
+ });
+
+ it('fails readiness checks when incremental sync is disabled', async () => {
+ const { verifyFtsSearchSyncReadiness } = await loadRuntime();
+
+ await expect(verifyFtsSearchSyncReadiness()).rejects.toThrow(
+ 'Elasticsearch full-text search sync is not enabled and configured',
+ );
+ expect(mocks.elasticsearchClient).not.toHaveBeenCalled();
+ });
+
+ it('verifies every search alias before reporting readiness', async () => {
+ mocks.ftsSearchEnv.FTS_SEARCH_SYNC_ENABLED = 'true';
+ const { verifyFtsSearchSyncReadiness } = await loadRuntime();
+
+ await expect(verifyFtsSearchSyncReadiness()).resolves.toEqual({ ready: true });
+
+ expect(mocks.elasticsearchClient).toHaveBeenCalledWith({
+ ...config,
+ requestTimeoutMs: 10_000,
+ });
+ expect(mocks.assertCaptureInfrastructure).toHaveBeenCalledOnce();
+ expect(mocks.assertFtsSearchSyncAliases).toHaveBeenCalledWith([
+ 'lobehub-test-agents',
+ 'lobehub-test-messages',
+ ]);
+ });
+
+ it('fails before checking aliases when PostgreSQL capture is not ready', async () => {
+ mocks.ftsSearchEnv.FTS_SEARCH_SYNC_ENABLED = 'true';
+ mocks.assertCaptureInfrastructure.mockRejectedValueOnce(new Error('capture is incomplete'));
+ const { verifyFtsSearchSyncReadiness } = await loadRuntime();
+
+ await expect(verifyFtsSearchSyncReadiness()).rejects.toThrow('capture is incomplete');
+ expect(mocks.elasticsearchClient).not.toHaveBeenCalled();
+ });
+
+ it('constructs and caches the configured service instance', async () => {
+ const { getFtsSearchSyncService } = await loadRuntime();
+
+ const first = getFtsSearchSyncService();
+ const second = getFtsSearchSyncService();
+
+ expect(second).toBe(first);
+ expect(mocks.searchDocumentBuilder).toHaveBeenCalledTimes(1);
+ expect(mocks.elasticsearchClient).toHaveBeenCalledTimes(1);
+ expect(mocks.elasticsearchClient).toHaveBeenCalledWith({
+ ...config,
+ requestTimeoutMs: 20_000,
+ });
+ });
+
+ it('refuses to construct a service without Elasticsearch configuration', async () => {
+ mocks.loadElasticsearchFtsSearchConfig.mockReturnValue(undefined);
+ const { getFtsSearchSyncService } = await loadRuntime();
+
+ expect(() => getFtsSearchSyncService()).toThrow(
+ 'Elasticsearch full-text search sync is not configured',
+ );
+ expect(mocks.searchDocumentBuilder).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/ftsSearchSync/runtime.ts b/apps/server/src/services/ftsSearchSync/runtime.ts
new file mode 100644
index 00000000000..d966f38793a
--- /dev/null
+++ b/apps/server/src/services/ftsSearchSync/runtime.ts
@@ -0,0 +1,49 @@
+import {
+ FTS_SEARCH_DOCUMENT_ENTITIES,
+ FtsSearchDocumentBuilder,
+ getFtsSearchIndexAlias,
+} from '@/database/repositories/ftsSearchDocument';
+import { ftsSearchSyncOutboxRepository } from '@/database/repositories/ftsSearchSyncOutbox/server';
+import { serverDB } from '@/database/server';
+import { ftsSearchEnv } from '@/envs/ftsSearch';
+
+import { loadElasticsearchFtsSearchConfig } from '../ftsSearch';
+import { ElasticsearchFtsSearchHttpClient } from '../ftsSearch/elasticsearch';
+import { FtsSearchSyncService } from './service';
+
+let cachedService: FtsSearchSyncService | undefined;
+
+export const isFtsSearchSyncEnabled = () =>
+ ftsSearchEnv.FTS_SEARCH_SYNC_ENABLED === 'true' &&
+ loadElasticsearchFtsSearchConfig() !== undefined;
+
+/** Fail closed unless every entity has a writable alias whose mapping supports soft tombstones. */
+export const verifyFtsSearchSyncReadiness = async () => {
+ const config = loadElasticsearchFtsSearchConfig();
+ if (ftsSearchEnv.FTS_SEARCH_SYNC_ENABLED !== 'true' || !config) {
+ throw new Error('Elasticsearch full-text search sync is not enabled and configured');
+ }
+
+ await ftsSearchSyncOutboxRepository.assertCaptureInfrastructure();
+ const client = new ElasticsearchFtsSearchHttpClient({ ...config, requestTimeoutMs: 10_000 });
+ await client.assertFtsSearchSyncAliases(
+ FTS_SEARCH_DOCUMENT_ENTITIES.map((entity) =>
+ getFtsSearchIndexAlias(config.indexNamespace, entity),
+ ),
+ );
+ return { ready: true as const };
+};
+
+export const getFtsSearchSyncService = (): FtsSearchSyncService => {
+ if (cachedService) return cachedService;
+ const config = loadElasticsearchFtsSearchConfig();
+ if (!config) throw new Error('Elasticsearch full-text search sync is not configured');
+
+ cachedService = new FtsSearchSyncService(
+ new FtsSearchDocumentBuilder(serverDB),
+ ftsSearchSyncOutboxRepository,
+ new ElasticsearchFtsSearchHttpClient({ ...config, requestTimeoutMs: 20_000 }),
+ config.indexNamespace,
+ );
+ return cachedService;
+};
diff --git a/apps/server/src/services/ftsSearchSync/service.test.ts b/apps/server/src/services/ftsSearchSync/service.test.ts
new file mode 100644
index 00000000000..0870e631846
--- /dev/null
+++ b/apps/server/src/services/ftsSearchSync/service.test.ts
@@ -0,0 +1,379 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type {
+ FtsSearchSyncFailure,
+ FtsSearchSyncWork,
+} from '@/database/repositories/ftsSearchSyncOutbox';
+
+import { ElasticsearchFtsSearchRequestError } from '../ftsSearch/elasticsearch';
+import { FtsSearchSyncService } from './service';
+
+const work = (documentId: string, revision: number = 1): FtsSearchSyncWork => ({
+ documentId,
+ entity: 'agents',
+ leaseToken: `${revision}`,
+ revision,
+});
+
+const createHarness = (
+ works: FtsSearchSyncWork[],
+ sources: Map<string, Record<string, unknown>>,
+) => {
+ const builder = {
+ buildByIds: vi.fn(async (_entity: string, ids: readonly string[]) =>
+ ids.flatMap((id) => {
+ const source = sources.get(id);
+ return source ? [{ entity: 'agents', id, source }] : [];
+ }),
+ ),
+ };
+ const outbox = {
+ acknowledgeMany: vi.fn(async (items: FtsSearchSyncWork[]) => items),
+ claim: vi.fn(async () => works),
+ hasActionableWork: vi.fn(async () => false),
+ hasDeadLetters: vi.fn(async () => false),
+ markFailures: vi.fn(
+ async (failures: FtsSearchSyncFailure[]) =>
+ failures.filter((failure) => failure.permanent).length,
+ ),
+ releaseMany: vi.fn(async (_items: FtsSearchSyncWork[]) => undefined),
+ };
+ const client = { bulk: vi.fn() };
+
+ return { builder, client, outbox };
+};
+
+describe('FtsSearchSyncService', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('checks durable dead-letter state without scanning or claiming work', async () => {
+ const harness = createHarness([], new Map());
+ harness.outbox.hasDeadLetters.mockResolvedValue(true);
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ );
+
+ await expect(service.hasDeadLetters()).resolves.toBe(true);
+ expect(harness.outbox.claim).not.toHaveBeenCalled();
+ });
+
+ it('settles each Elasticsearch bulk item independently', async () => {
+ const works = [work('a'), work('b'), work('c'), work('d')];
+ const harness = createHarness(
+ works,
+ new Map(works.map((item) => [item.documentId, { id: item.documentId, title: 'title' }])),
+ );
+ harness.client.bulk.mockResolvedValue({
+ errors: true,
+ items: [201, 409, 429, 400].map((status) => ({ index: { status } })),
+ });
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ { bulkMaxBytes: 10_000 },
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.outbox.acknowledgeMany).toHaveBeenCalledWith([works[0], works[1]]);
+ expect(harness.outbox.markFailures).toHaveBeenCalledWith([
+ expect.objectContaining({ documentId: 'c' }),
+ expect.objectContaining({ documentId: 'd' }),
+ ]);
+ expect(harness.outbox.markFailures.mock.calls[0][0]).toEqual([
+ expect.not.objectContaining({ permanent: true }),
+ expect.objectContaining({ permanent: true }),
+ ]);
+ expect(result).toMatchObject({
+ acknowledged: 2,
+ bulkBytes: expect.any(Number),
+ bulkItems: 4,
+ bulkRequestSamples: [
+ expect.objectContaining({ bytes: expect.any(Number), items: 4, result: 'mixed' }),
+ ],
+ claimed: 4,
+ dead: 1,
+ failed: 2,
+ });
+ expect(result.bulkBytes).toBeGreaterThan(0);
+ });
+
+ it('writes a soft tombstone when the PostgreSQL row no longer exists', async () => {
+ const harness = createHarness([work('deleted-agent', 7)], new Map());
+ harness.client.bulk.mockResolvedValue({
+ errors: false,
+ items: [{ index: { status: 201 } }],
+ });
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ );
+
+ await service.drainOnce();
+
+ expect(harness.client.bulk).toHaveBeenCalledWith(
+ expect.stringContaining('{"id":"deleted-agent","fts_search_sync_deleted":true}'),
+ );
+ expect(harness.client.bulk.mock.calls[0][0]).toContain('"version":7,"version_type":"external"');
+ });
+
+ it('dead-letters one operation that exceeds the configured byte limit', async () => {
+ const item = work('oversized');
+ const following = work('following');
+ const harness = createHarness(
+ [item, following],
+ new Map([
+ ['oversized', { content: 'x'.repeat(1000), id: 'oversized' }],
+ ['following', { id: 'following', title: 'later' }],
+ ]),
+ );
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ { bulkMaxBytes: 300 },
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.client.bulk).not.toHaveBeenCalled();
+ expect(harness.outbox.markFailures).toHaveBeenCalledWith([
+ expect.objectContaining({ documentId: 'oversized', permanent: true }),
+ ]);
+ expect(harness.outbox.releaseMany).toHaveBeenCalledWith([following]);
+ expect(result.dead).toBe(1);
+ expect(result.released).toBe(1);
+ });
+
+ it('stops after a split bulk creates a dead letter', async () => {
+ const works = [work('a'), work('b'), work('c')];
+ const harness = createHarness(
+ works,
+ new Map(works.map((item) => [item.documentId, { id: item.documentId, title: 'x' }])),
+ );
+ harness.client.bulk.mockResolvedValue({
+ errors: true,
+ items: [{ index: { status: 400 } }],
+ });
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ { bulkMaxBytes: 210 },
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.client.bulk).toHaveBeenCalledTimes(1);
+ expect(harness.outbox.releaseMany).toHaveBeenCalledWith([works[1], works[2]]);
+ expect(result).toMatchObject({ dead: 1, failed: 1, released: 2 });
+ });
+
+ it.each([401, 403, 408, 413, 429, 503])(
+ 'durably retries a top-level HTTP %s failure',
+ async (status) => {
+ const item = work(`http-${status}`);
+ const harness = createHarness(
+ [item],
+ new Map([[item.documentId, { id: item.documentId, title: 'title' }]]),
+ );
+ harness.client.bulk.mockRejectedValue(
+ new ElasticsearchFtsSearchRequestError('bulk failed', status),
+ );
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.outbox.markFailures).toHaveBeenCalledWith([
+ expect.objectContaining({ documentId: item.documentId }),
+ ]);
+ expect(harness.outbox.markFailures.mock.calls[0][0]).toEqual([
+ expect.not.objectContaining({ permanent: true }),
+ ]);
+ expect(result.bulkRequestSamples).toEqual([
+ expect.objectContaining({ items: 1, result: 'request_error' }),
+ ]);
+ },
+ );
+
+ it('preserves claimed priority order after grouping projection reads', async () => {
+ const works: FtsSearchSyncWork[] = [
+ { documentId: 'urgent-message', entity: 'messages', leaseToken: '2', revision: 2 },
+ { documentId: 'ordinary-agent', entity: 'agents', leaseToken: '1', revision: 1 },
+ ];
+ const harness = createHarness(
+ works,
+ new Map(works.map((item) => [item.documentId, { id: item.documentId, title: 'title' }])),
+ );
+ harness.client.bulk.mockResolvedValue({
+ errors: false,
+ items: works.map(() => ({ index: { status: 201 } })),
+ });
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ );
+
+ await service.drainOnce();
+
+ const body = harness.client.bulk.mock.calls[0][0] as string;
+ const documentIds = body
+ .trim()
+ .split('\n')
+ .filter((_, index) => index % 2 === 0)
+ .map((line) => JSON.parse(line).index._id);
+ expect(documentIds).toEqual(['urgent-message', 'ordinary-agent']);
+ });
+
+ it('releases unprocessed claims after exhausting the bulk-request budget', async () => {
+ const works = [work('a'), work('b'), work('c')];
+ const harness = createHarness(
+ works,
+ new Map(works.map((item) => [item.documentId, { id: item.documentId, title: 'x' }])),
+ );
+ harness.client.bulk.mockResolvedValue({
+ errors: false,
+ items: [{ index: { status: 201 } }],
+ });
+ let leasesReleased = false;
+ harness.outbox.releaseMany.mockImplementationOnce(async () => {
+ leasesReleased = true;
+ });
+ harness.outbox.hasActionableWork.mockImplementationOnce(async () => leasesReleased);
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ { bulkMaxBytes: 210, maxBulkRequests: 1 },
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.client.bulk).toHaveBeenCalledTimes(1);
+ expect(harness.outbox.releaseMany).toHaveBeenCalledWith([works[1], works[2]]);
+ expect(result).toMatchObject({ hasMore: true, released: 2 });
+ });
+
+ it('dead-letters an entity that the projection builder does not support', async () => {
+ const item = { ...work('unknown'), entity: 'removedEntity' } as unknown as FtsSearchSyncWork;
+ const supported = work('supported');
+ const harness = createHarness(
+ [item, supported],
+ new Map([['supported', { id: 'supported', title: 'later' }]]),
+ );
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ );
+
+ await expect(service.drainOnce()).resolves.toMatchObject({ dead: 1, failed: 1 });
+ expect(harness.builder.buildByIds).not.toHaveBeenCalled();
+ expect(harness.outbox.markFailures).toHaveBeenCalledWith([
+ expect.objectContaining({ documentId: 'unknown', permanent: true }),
+ ]);
+ expect(harness.outbox.releaseMany).toHaveBeenCalledWith([supported]);
+ });
+
+ it('stops when a projection failure exhausts its retry budget', async () => {
+ const works = [work('a'), work('b')];
+ const harness = createHarness(
+ works,
+ new Map(works.map((item) => [item.documentId, { id: item.documentId, title: 'x' }])),
+ );
+ harness.builder.buildByIds.mockRejectedValueOnce(new Error('projection unavailable'));
+ harness.outbox.markFailures.mockResolvedValueOnce(1);
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ { projectionBatchSize: 1 },
+ );
+
+ const result = await service.drainOnce();
+
+ expect(harness.builder.buildByIds).toHaveBeenCalledTimes(1);
+ expect(harness.client.bulk).not.toHaveBeenCalled();
+ expect(harness.outbox.releaseMany).toHaveBeenCalledWith([works[1]]);
+ expect(result).toMatchObject({ dead: 1, failed: 1, released: 1 });
+ });
+
+ it('releases every unsettled lease when acknowledgement fails without hiding the main error', async () => {
+ const works = [work('a'), work('b')];
+ const harness = createHarness(
+ works,
+ new Map(works.map((item) => [item.documentId, { id: item.documentId, title: 'x' }])),
+ );
+ const acknowledgementError = new Error('acknowledgement unavailable');
+ const releaseError = new Error('release unavailable');
+ harness.client.bulk.mockResolvedValue({
+ errors: false,
+ items: works.map(() => ({ index: { status: 201 } })),
+ });
+ harness.outbox.acknowledgeMany.mockRejectedValueOnce(acknowledgementError);
+ harness.outbox.releaseMany.mockRejectedValueOnce(releaseError);
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ );
+
+ await expect(service.drainOnce()).rejects.toBe(acknowledgementError);
+
+ expect(harness.outbox.releaseMany).toHaveBeenCalledWith(works);
+ expect(consoleError).toHaveBeenCalledWith(
+ 'Failed to release unsettled full-text search sync leases',
+ releaseError,
+ );
+ consoleError.mockRestore();
+ });
+
+ it('releases only failures still unsettled when failure settlement rejects', async () => {
+ const works = [work('acknowledged'), work('failed')];
+ const harness = createHarness(
+ works,
+ new Map(works.map((item) => [item.documentId, { id: item.documentId, title: 'x' }])),
+ );
+ const failureError = new Error('failure settlement unavailable');
+ harness.client.bulk.mockResolvedValue({
+ errors: true,
+ items: [{ index: { status: 201 } }, { index: { status: 429 } }],
+ });
+ harness.outbox.markFailures.mockRejectedValueOnce(failureError);
+ const service = new FtsSearchSyncService(
+ harness.builder as never,
+ harness.outbox as never,
+ harness.client,
+ 'lobehub-test',
+ );
+
+ await expect(service.drainOnce()).rejects.toBe(failureError);
+
+ expect(harness.outbox.acknowledgeMany).toHaveBeenCalledWith([works[0]]);
+ expect(harness.outbox.releaseMany).toHaveBeenCalledWith([works[1]]);
+ });
+});
diff --git a/apps/server/src/services/ftsSearchSync/service.ts b/apps/server/src/services/ftsSearchSync/service.ts
new file mode 100644
index 00000000000..e9e54a42297
--- /dev/null
+++ b/apps/server/src/services/ftsSearchSync/service.ts
@@ -0,0 +1,355 @@
+import { Buffer } from 'node:buffer';
+
+import type { FtsSearchDocumentBuilder } from '@/database/repositories/ftsSearchDocument';
+import {
+ FTS_SEARCH_DOCUMENT_ENTITIES,
+ getFtsSearchIndexAlias,
+} from '@/database/repositories/ftsSearchDocument';
+import type {
+ FtsSearchSyncFailure,
+ FtsSearchSyncOutboxRepository,
+ FtsSearchSyncWork,
+} from '@/database/repositories/ftsSearchSyncOutbox';
+
+import type { ElasticsearchFtsSearchBulkResponse } from '../ftsSearch/elasticsearch';
+
+export const FTS_SEARCH_SYNC_BULK_MAX_BYTES = 50 * 1024 * 1024;
+export const FTS_SEARCH_SYNC_CLAIM_LIMIT = 100;
+export const FTS_SEARCH_SYNC_MAX_BULK_REQUESTS = 2;
+export const FTS_SEARCH_SYNC_PROJECTION_BATCH_SIZE = FTS_SEARCH_SYNC_CLAIM_LIMIT;
+
+interface FtsSearchSyncElasticsearchClient {
+ bulk: (body: string) => Promise<ElasticsearchFtsSearchBulkResponse>;
+}
+
+interface FtsSearchSyncOperation {
+ body: string;
+ bytes: number;
+ work: FtsSearchSyncWork;
+}
+
+interface FtsSearchSyncServiceOptions {
+ bulkMaxBytes: number;
+ claimLimit: number;
+ maxBulkRequests: number;
+ projectionBatchSize: number;
+}
+
+export interface FtsSearchSyncDrainResult {
+ acknowledged: number;
+ bulkBytes: number;
+ bulkItems: number;
+ bulkRequests: number;
+ bulkRequestSamples: FtsSearchSyncBulkRequestSample[];
+ claimed: number;
+ dead: number;
+ failed: number;
+ hasMore: boolean;
+ released: number;
+}
+
+export interface FtsSearchSyncBulkRequestSample {
+ bytes: number;
+ durationMs: number;
+ items: number;
+ result: 'item_error' | 'mixed' | 'request_error' | 'response_error' | 'success';
+}
+
+const workKey = (work: FtsSearchSyncWork) => `${work.entity}:${work.documentId}:${work.revision}`;
+const sourceKey = (entity: FtsSearchSyncWork['entity'], documentId: string) =>
+ `${entity}:${documentId}`;
+
+const isPermanentElasticsearchStatus = (status: number | undefined) =>
+ status !== undefined && status >= 400 && status < 500 && status !== 408 && status !== 429;
+
+const chunks = <Item>(items: Item[], size: number): Item[][] => {
+ const result: Item[][] = [];
+ for (let offset = 0; offset < items.length; offset += size) {
+ result.push(items.slice(offset, offset + size));
+ }
+ return result;
+};
+
+const buildOperation = (
+ work: FtsSearchSyncWork,
+ indexNamespace: string,
+ source: Record<string, unknown>,
+): FtsSearchSyncOperation => {
+ const metadata = {
+ index: {
+ _id: work.documentId,
+ _index: getFtsSearchIndexAlias(indexNamespace, work.entity),
+ version: work.revision,
+ version_type: 'external',
+ },
+ };
+ const body = `${JSON.stringify(metadata)}\n${JSON.stringify(source)}\n`;
+ return { body, bytes: Buffer.byteLength(body), work };
+};
+
+/** Bounded PostgreSQL projection → byte-aware Elasticsearch bulk drain. */
+export class FtsSearchSyncService {
+ private readonly options: FtsSearchSyncServiceOptions;
+
+ constructor(
+ private readonly builder: Pick<FtsSearchDocumentBuilder, 'buildByIds'>,
+ private readonly outbox: Pick<
+ FtsSearchSyncOutboxRepository,
+ | 'acknowledgeMany'
+ | 'claim'
+ | 'hasActionableWork'
+ | 'hasDeadLetters'
+ | 'markFailures'
+ | 'releaseMany'
+ >,
+ private readonly client: FtsSearchSyncElasticsearchClient,
+ private readonly indexNamespace: string,
+ options: Partial<FtsSearchSyncServiceOptions> = {},
+ ) {
+ this.options = {
+ bulkMaxBytes: FTS_SEARCH_SYNC_BULK_MAX_BYTES,
+ claimLimit: FTS_SEARCH_SYNC_CLAIM_LIMIT,
+ maxBulkRequests: FTS_SEARCH_SYNC_MAX_BULK_REQUESTS,
+ projectionBatchSize: FTS_SEARCH_SYNC_PROJECTION_BATCH_SIZE,
+ ...options,
+ };
+ }
+
+ async hasDeadLetters(): Promise<boolean> {
+ return this.outbox.hasDeadLetters();
+ }
+
+ async drainOnce(): Promise<FtsSearchSyncDrainResult> {
+ const works = await this.outbox.claim(this.options.claimLimit);
+ if (works.length === 0) {
+ return {
+ acknowledged: 0,
+ bulkBytes: 0,
+ bulkItems: 0,
+ bulkRequestSamples: [],
+ bulkRequests: 0,
+ claimed: 0,
+ dead: 0,
+ failed: 0,
+ hasMore: await this.outbox.hasActionableWork(),
+ released: 0,
+ };
+ }
+
+ const unsettled = new Map(works.map((work) => [workKey(work), work]));
+ const result: FtsSearchSyncDrainResult = {
+ acknowledged: 0,
+ bulkBytes: 0,
+ bulkItems: 0,
+ bulkRequestSamples: [],
+ bulkRequests: 0,
+ claimed: works.length,
+ dead: 0,
+ failed: 0,
+ hasMore: false,
+ released: 0,
+ };
+ let bulk: FtsSearchSyncOperation[] = [];
+ let bulkBytes = 0;
+
+ const forget = (settledWorks: FtsSearchSyncWork[]) => {
+ for (const work of settledWorks) unsettled.delete(workKey(work));
+ };
+
+ const fail = async (failures: FtsSearchSyncFailure[]) => {
+ result.dead += await this.outbox.markFailures(failures);
+ result.failed += failures.length;
+ forget(failures);
+ };
+
+ const flush = async () => {
+ if (bulk.length === 0) return;
+ const operations = bulk;
+ const requestBody = operations.map((operation) => operation.body).join('');
+ const requestBytes = bulkBytes;
+ bulk = [];
+ bulkBytes = 0;
+ result.bulkBytes += requestBytes;
+ result.bulkItems += operations.length;
+ result.bulkRequests += 1;
+
+ let response: ElasticsearchFtsSearchBulkResponse;
+ const startedAt = Date.now();
+ try {
+ response = await this.client.bulk(requestBody);
+ } catch (error) {
+ result.bulkRequestSamples.push({
+ bytes: requestBytes,
+ durationMs: Date.now() - startedAt,
+ items: operations.length,
+ result: 'request_error',
+ });
+ /** Request-level failures can be deployment or proxy faults; retry every item durably. */
+ await fail(operations.map(({ work }) => ({ ...work, error })));
+ return;
+ }
+
+ if (response.items.length !== operations.length) {
+ result.bulkRequestSamples.push({
+ bytes: requestBytes,
+ durationMs: Date.now() - startedAt,
+ items: operations.length,
+ result: 'response_error',
+ });
+ await fail(
+ operations.map(({ work }) => ({
+ ...work,
+ error: new Error(
+ `Elasticsearch bulk returned ${response.items.length} items for ${operations.length} operations`,
+ ),
+ })),
+ );
+ return;
+ }
+
+ const acknowledged: FtsSearchSyncWork[] = [];
+ const failures: FtsSearchSyncFailure[] = [];
+ for (const [index, operation] of operations.entries()) {
+ const item = response.items[index].index;
+ if ((item.status >= 200 && item.status < 300) || item.status === 409) {
+ /**
+ * A version conflict is safe to settle because two database fences preserve source order:
+ * fresh reindexes reserve their base revision before capture activation, and same-document
+ * Outbox upserts allocate a revision only after locking the unique Outbox row. Settlement
+ * is also revision-and-lease fenced, so a concurrent refresh remains queued.
+ */
+ acknowledged.push(operation.work);
+ } else {
+ failures.push({
+ ...operation.work,
+ error: new Error(`Elasticsearch bulk item failed (${item.status})`),
+ permanent: isPermanentElasticsearchStatus(item.status),
+ });
+ }
+ }
+
+ result.bulkRequestSamples.push({
+ bytes: requestBytes,
+ durationMs: Date.now() - startedAt,
+ items: operations.length,
+ result:
+ failures.length === 0 ? 'success' : acknowledged.length === 0 ? 'item_error' : 'mixed',
+ });
+
+ const deleted = await this.outbox.acknowledgeMany(acknowledged);
+ result.acknowledged += deleted.length;
+ forget(acknowledged);
+ await fail(failures);
+ };
+
+ let hasPrimaryError = false;
+ let hasReleaseError = false;
+ let releaseError: unknown;
+ try {
+ const supportedEntities = new Set<string>(FTS_SEARCH_DOCUMENT_ENTITIES);
+ const unsupportedWorks = works.filter((work) => !supportedEntities.has(work.entity));
+ if (unsupportedWorks.length > 0) {
+ await fail(
+ unsupportedWorks.map((work) => ({
+ ...work,
+ error: new Error(`Unsupported full-text search sync entity: ${work.entity}`),
+ permanent: true,
+ })),
+ );
+ }
+ let stoppedForDeadLetter = result.dead > 0;
+
+ const projectedSources = new Map<string, Record<string, unknown>>();
+ projections: for (const entity of FTS_SEARCH_DOCUMENT_ENTITIES) {
+ if (stoppedForDeadLetter) break;
+ const entityWorks = works.filter((work) => work.entity === entity);
+ for (const projectionWorks of chunks(entityWorks, this.options.projectionBatchSize)) {
+ let documents: Awaited<ReturnType<FtsSearchDocumentBuilder['buildByIds']>>;
+ try {
+ documents = await this.builder.buildByIds(
+ entity,
+ projectionWorks.map((work) => work.documentId),
+ );
+ } catch (error) {
+ await fail(projectionWorks.map((work) => ({ ...work, error })));
+ if (result.dead > 0) {
+ stoppedForDeadLetter = true;
+ break projections;
+ }
+ continue;
+ }
+ for (const document of documents) {
+ projectedSources.set(
+ sourceKey(entity, document.id),
+ document.source as Record<string, unknown>,
+ );
+ }
+ }
+ }
+
+ let exhaustedBulkBudget = false;
+ operations: for (const work of works) {
+ if (stoppedForDeadLetter) break;
+ if (!unsettled.has(workKey(work))) continue;
+ /** Soft tombstones prevent delayed external-version writes from resurrecting deletions. */
+ const source =
+ projectedSources.get(sourceKey(work.entity, work.documentId)) ??
+ ({ id: work.documentId, fts_search_sync_deleted: true } as Record<string, unknown>);
+ const operation = buildOperation(work, this.indexNamespace, source);
+
+ if (operation.bytes > this.options.bulkMaxBytes) {
+ await fail([
+ {
+ ...work,
+ error: new Error(
+ `Full-text search document is ${operation.bytes} bytes and exceeds the ${this.options.bulkMaxBytes}-byte bulk limit`,
+ ),
+ permanent: true,
+ },
+ ]);
+ if (result.dead > 0) {
+ stoppedForDeadLetter = true;
+ break operations;
+ }
+ continue;
+ }
+
+ if (bulk.length > 0 && bulkBytes + operation.bytes > this.options.bulkMaxBytes) {
+ await flush();
+ if (result.dead > 0) {
+ stoppedForDeadLetter = true;
+ break operations;
+ }
+ if (result.bulkRequests >= this.options.maxBulkRequests) {
+ exhaustedBulkBudget = true;
+ break operations;
+ }
+ }
+
+ bulk.push(operation);
+ bulkBytes += operation.bytes;
+ }
+
+ if (!exhaustedBulkBudget && !stoppedForDeadLetter && bulk.length > 0) await flush();
+ } catch (error) {
+ hasPrimaryError = true;
+ throw error;
+ } finally {
+ const released = [...unsettled.values()];
+ try {
+ await this.outbox.releaseMany(released);
+ result.released = released.length;
+ } catch (error) {
+ console.error('Failed to release unsettled full-text search sync leases', error);
+ if (!hasPrimaryError) {
+ hasReleaseError = true;
+ releaseError = error;
+ }
+ }
+ }
+
+ if (hasReleaseError) throw releaseError;
+ result.hasMore = await this.outbox.hasActionableWork();
+ return result;
+ }
+}
diff --git a/apps/server/src/services/knowledgeBase/index.test.ts b/apps/server/src/services/knowledgeBase/index.test.ts
index 0f1c7411f00..0fe43e9355e 100644
--- a/apps/server/src/services/knowledgeBase/index.test.ts
+++ b/apps/server/src/services/knowledgeBase/index.test.ts
@@ -4,11 +4,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ChunkModel } from '@/database/models/chunk';
import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
-import { SearchRepo } from '@/database/repositories/search';
import { knowledgeBaseFiles } from '@/database/schemas';
import { buildWorkspaceWhere } from '@/database/utils/workspace';
import { getServerDefaultFilesConfig } from '@/server/globalConfig';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
+import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import { DocumentService } from '../document';
import { KnowledgeBaseSearchService } from './index';
@@ -16,7 +16,7 @@ import { KnowledgeBaseSearchService } from './index';
vi.mock('@/database/models/chunk', () => ({ ChunkModel: vi.fn() }));
vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn() }));
vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));
-vi.mock('@/database/repositories/search', () => ({ SearchRepo: vi.fn() }));
+vi.mock('@/server/services/ftsSearch', () => ({ createFtsSearchRepo: vi.fn() }));
vi.mock('../document', () => ({ DocumentService: vi.fn() }));
vi.mock('@/server/globalConfig', () => ({ getServerDefaultFilesConfig: vi.fn() }));
vi.mock('@/server/modules/ModelRuntime', () => ({ initModelRuntimeFromDB: vi.fn() }));
@@ -51,7 +51,7 @@ describe('KnowledgeBaseSearchService', () => {
vi.mocked(ChunkModel).mockImplementation(() => chunkModelMock);
vi.mocked(DocumentModel).mockImplementation(() => documentModelMock);
vi.mocked(FileModel).mockImplementation(() => fileModelMock);
- vi.mocked(SearchRepo).mockImplementation(() => searchRepoMock);
+ vi.mocked(createFtsSearchRepo).mockResolvedValue(searchRepoMock);
vi.mocked(DocumentService).mockImplementation(() => documentServiceMock);
service = new KnowledgeBaseSearchService(serverDB, userId);
@@ -189,6 +189,26 @@ describe('KnowledgeBaseSearchService', () => {
} as any);
});
+ it('forwards the caller agent visibility to the selected BM25 backend', async () => {
+ chunkModelMock.semanticSearchForChat.mockResolvedValue([]);
+ searchRepoMock.searchKnowledgeBaseDocuments.mockResolvedValue([]);
+ const scopedService = new KnowledgeBaseSearchService(
+ serverDB,
+ userId,
+ 'workspace-1',
+ 'public',
+ );
+
+ await scopedService.semanticSearchForChat({ knowledgeIds: ['kb_1'], query: 'hello' });
+
+ expect(createFtsSearchRepo).toHaveBeenCalledWith({
+ callerAgentVisibility: 'public',
+ db: serverDB,
+ userId,
+ workspaceId: 'workspace-1',
+ });
+ });
+
it('groups chunks by file and ranks them by average top-3 similarity', async () => {
chunkModelMock.semanticSearchForChat.mockResolvedValue([
{ id: 'c1', fileId: 'f1', fileName: 'a.pdf', similarity: 0.9, text: 'aaa' },
diff --git a/apps/server/src/services/knowledgeBase/index.ts b/apps/server/src/services/knowledgeBase/index.ts
index c2ba8e4ccad..7bb38add59d 100644
--- a/apps/server/src/services/knowledgeBase/index.ts
+++ b/apps/server/src/services/knowledgeBase/index.ts
@@ -12,12 +12,13 @@ import pMap from 'p-map';
import { ChunkModel } from '@/database/models/chunk';
import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
-import { type KnowledgeBaseDocumentHit, SearchRepo } from '@/database/repositories/search';
+import type { FtsSearchKnowledgeBaseDocumentHit } from '@/database/repositories/ftsSearch';
import { knowledgeBaseFiles } from '@/database/schemas';
import { buildWorkspaceWhere } from '@/database/utils/workspace';
import { getServerDefaultFilesConfig } from '@/server/globalConfig';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { DocumentService } from '@/server/services/document';
+import { createFtsSearchRepo } from '@/server/services/ftsSearch';
export interface FileContentResult {
content: string;
@@ -32,7 +33,7 @@ export interface FileContentResult {
export interface SemanticSearchForChatResult {
chunks: ChatSemanticSearchChunk[];
- documents: KnowledgeBaseDocumentHit[];
+ documents: FtsSearchKnowledgeBaseDocumentHit[];
errors?: { bm25?: string; vector?: string };
fileResults: FileSearchResult[];
/**
@@ -87,7 +88,6 @@ export class KnowledgeBaseSearchService {
private chunkModel: ChunkModel;
private documentModel: DocumentModel;
private fileModel: FileModel;
- private searchRepo: SearchRepo;
private documentServiceInstance?: DocumentService;
private callerAgentVisibility?: 'private' | 'public' | null;
@@ -111,7 +111,6 @@ export class KnowledgeBaseSearchService {
// enforcement point today.
this.documentModel = new DocumentModel(serverDB, userId, workspaceId, callerAgentVisibility);
this.fileModel = new FileModel(serverDB, userId, workspaceId);
- this.searchRepo = new SearchRepo(serverDB, userId, workspaceId);
}
private get documentService() {
@@ -174,16 +173,26 @@ export class KnowledgeBaseSearchService {
};
// Path 2: BM25 search over KB-scoped custom/document documents
- const bm25Path = async (): Promise<KnowledgeBaseDocumentHit[]> => {
+ const bm25Path = async (): Promise<FtsSearchKnowledgeBaseDocumentHit[]> => {
if (knowledgeIds.length === 0) return [];
- return this.searchRepo.searchKnowledgeBaseDocuments(input.query, knowledgeIds, topK);
+ /**
+ * BM25 results already contain snippets, so provider selection and the
+ * public-agent visibility gate must both be resolved before the search.
+ */
+ const ftsSearchRepo = await createFtsSearchRepo({
+ callerAgentVisibility: this.callerAgentVisibility,
+ db: this.serverDB,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+ return ftsSearchRepo.searchKnowledgeBaseDocuments(input.query, knowledgeIds, topK);
};
const [vectorResult, bm25Result] = await Promise.allSettled([vectorPath(), bm25Path()]);
const chunks: ChatSemanticSearchChunk[] =
vectorResult.status === 'fulfilled' ? vectorResult.value : [];
- const documents: KnowledgeBaseDocumentHit[] =
+ const documents: FtsSearchKnowledgeBaseDocumentHit[] =
bm25Result.status === 'fulfilled' ? bm25Result.value : [];
const errors: { bm25?: string; vector?: string } = {};
diff --git a/apps/server/src/services/memory/userMemory/extract.ts b/apps/server/src/services/memory/userMemory/extract.ts
index b95aa9710e0..78b1a6857d0 100644
--- a/apps/server/src/services/memory/userMemory/extract.ts
+++ b/apps/server/src/services/memory/userMemory/extract.ts
@@ -78,6 +78,7 @@ import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryEx
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import { S3 } from '@/server/modules/S3';
import { getUserScopedAiProviderRuntimeState } from '@/server/services/aiProviderAccess';
+import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import {
AsyncTaskError,
type AsyncTaskErrorBody,
@@ -1404,7 +1405,8 @@ export class MemoryExtractionExecutor {
tokenLimit?: number,
): Promise<UserMemoryHybridSearchAggregatedResult> {
const db = await this.db;
- const userMemoryModel = new UserMemoryModel(db, userId);
+ const ftsSearchRepo = await createFtsSearchRepo({ db, userId });
+ const userMemoryModel = new UserMemoryModel(db, userId, ftsSearchRepo);
// TODO: make topK configurable
const topK = 10;
const aggregatedContent = await this.trimTextToTokenLimit(
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/memory.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/memory.test.ts
index a32189ffedf..2e9285dcd96 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/memory.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/memory.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it, vi } from 'vitest';
import type { ToolExecutionContext } from '../../types';
const mocks = vi.hoisted(() => ({
+ createFtsSearchRepo: vi.fn(async () => ({ ftsSearchCandidateEnabled: false })),
embeddings: vi.fn(),
initModelRuntimeFromDB: vi.fn(),
initModelRuntimeWithUserPayload: vi.fn(),
@@ -40,6 +41,10 @@ vi.mock('@/server/services/agentSignal/store/adapters/redis/policyStateStore', (
redisPolicyStateStore: {},
}));
+vi.mock('@/server/services/ftsSearch', () => ({
+ createFtsSearchRepo: mocks.createFtsSearchRepo,
+}));
+
const { memoryRuntime } = await import('../memory');
const createContext = (): ToolExecutionContext => ({
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/memory.ts b/apps/server/src/services/toolExecution/serverRuntimes/memory.ts
index 551f24f1a4c..2110a7edb84 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/memory.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/memory.ts
@@ -51,6 +51,7 @@ import {
resolveToolOutcomeScope,
} from '@/server/services/agentSignal/procedure';
import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';
+import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import type { UserMemoryEmbeddingRuntime } from '@/server/services/memory/userMemory/embedding';
import { embedUserMemoryTexts } from '@/server/services/memory/userMemory/embedding';
import { normalizeSearchMemoryParams } from '@/server/services/memory/userMemory/searchParams';
@@ -877,7 +878,11 @@ export const memoryRuntime: ServerRuntimeRegistration = {
// fallback to medium
}
- const memoryModel = new UserMemoryModel(context.serverDB, context.userId);
+ const ftsSearchRepo = await createFtsSearchRepo({
+ db: context.serverDB,
+ userId: context.userId,
+ });
+ const memoryModel = new UserMemoryModel(context.serverDB, context.userId, ftsSearchRepo);
const service = new MemoryServerRuntimeService({
agentId: context.agentId,
diff --git a/docs/development/database-schema.dbml b/docs/development/database-schema.dbml
index cc7b1462f22..25427d5b54d 100644
--- a/docs/development/database-schema.dbml
+++ b/docs/development/database-schema.dbml
@@ -309,7 +309,7 @@ table agent_eval_runs {
updated_at "timestamp with time zone" [not null, default: `now()`]
indexes {
-
+
dataset_id [name: 'agent_eval_runs_dataset_id_idx']
experiment_id [name: 'agent_eval_runs_experiment_id_idx']
parent_run_id [name: 'agent_eval_runs_parent_run_id_idx']
@@ -450,11 +450,11 @@ table agent_intervention_resolutions {
resolution_request_id [name: 'agent_intervention_resolutions_request_unique', unique]
(user_id, workspace_id, batch_id) [name: 'agent_intervention_resolutions_owner_batch_idx']
(status, created_at) [name: 'agent_intervention_resolutions_status_created_idx']
-
-
-
-
-
+
+
+
+
+
}
}
@@ -504,11 +504,11 @@ table agent_interventions {
(user_id, workspace_id, batch_id, item_index) [name: 'agent_interventions_owner_batch_idx']
(user_id, activity_key) [name: 'agent_interventions_activity_key_idx']
(status, deadline) [name: 'agent_interventions_status_deadline_idx']
-
-
-
-
-
+
+
+
+
+
}
}
@@ -1261,7 +1261,7 @@ table expertise_bindings {
updated_at "timestamp with time zone" [not null, default: `now()`]
indexes {
-
+
(agent_id, domain_id) [name: 'expertise_bindings_agent_domain_unique', unique]
(project_id, domain_id) [name: 'expertise_bindings_project_domain_unique', unique]
(bound_workspace_id, domain_id) [name: 'expertise_bindings_workspace_domain_unique', unique]
@@ -1297,7 +1297,7 @@ table expertise_domain_snapshots {
captured_at "timestamp with time zone" [not null, default: `now()`]
indexes {
-
+
(domain_id, run_index) [name: 'expertise_domain_snapshots_domain_run_index_unique', unique]
(domain_id, captured_at) [name: 'expertise_domain_snapshots_domain_captured_idx']
domain_id [name: 'expertise_domain_snapshots_pending_fit_idx']
@@ -1358,8 +1358,8 @@ table expertise_hits {
created_at "timestamp with time zone" [not null, default: `now()`]
indexes {
-
-
+
+
(lesson_id, created_at) [name: 'expertise_hits_lesson_created_idx']
run_id [name: 'expertise_hits_run_idx']
(domain_id, outcome) [name: 'expertise_hits_domain_outcome_idx']
@@ -1735,9 +1735,9 @@ table goal_edges {
(source_node_id, target_node_id, kind) [name: 'goal_edges_source_target_kind_unique', unique]
goal_id [name: 'goal_edges_goal_id_idx']
target_node_id [name: 'goal_edges_target_node_id_idx']
-
-
-
+
+
+
}
}
@@ -1824,8 +1824,8 @@ table goal_nodes {
(goal_id, kind) [name: 'goal_nodes_goal_id_kind_idx']
(goal_id, id) [name: 'goal_nodes_goal_id_id_unique', unique]
task_id [name: 'goal_nodes_task_id_unique', unique]
-
-
+
+
}
}
@@ -2479,7 +2479,7 @@ table project_completion_reviews {
(project_id, created_at) [name: 'project_completion_reviews_project_id_created_at_idx']
reviewer_user_id [name: 'project_completion_reviews_reviewer_user_id_idx']
workspace_id [name: 'project_completion_reviews_workspace_id_idx']
-
+
}
}
@@ -2554,7 +2554,7 @@ table projects {
(workspace_id, visibility, user_id) [name: 'projects_workspace_visibility_idx']
(status, updated_at) [name: 'projects_status_updated_at_idx']
coordinator_agent_id [name: 'projects_coordinator_agent_id_unique', unique]
-
+
}
}
@@ -2575,7 +2575,7 @@ table push_live_activities {
(user_id, activity_key) [name: 'idx_push_live_activities_user_activity']
(user_id, operation_id) [name: 'idx_push_live_activities_user_operation']
last_seen_at [name: 'idx_push_live_activities_last_seen']
-
+
}
}
@@ -2596,7 +2596,7 @@ table push_tokens {
(user_id, device_id) [name: 'idx_push_tokens_user_device', unique]
user_id [name: 'idx_push_tokens_user']
last_seen_at [name: 'idx_push_tokens_last_seen']
-
+
}
}
@@ -2914,6 +2914,28 @@ table resource_transfer_requests {
}
}
+table fts_search_sync_outbox {
+ attempts integer [not null, default: 0]
+ available_at "timestamp with time zone" [not null, default: `now()`]
+ created_at "timestamp with time zone" [not null, default: `now()`]
+ dead_at "timestamp with time zone"
+ document_id text [not null]
+ entity text [not null]
+ id uuid [pk, not null, default: `gen_random_uuid()`]
+ last_error text
+ locked_until "timestamp with time zone"
+ priority smallint [not null, default: 10]
+ revision bigint [not null, default: `nextval('fts_search_sync_revision_seq')`]
+ updated_at "timestamp with time zone" [not null, default: `now()`]
+
+ indexes {
+ (entity, document_id) [name: 'fts_search_sync_outbox_entity_document_id_unique', unique]
+ (priority, available_at, revision) [name: 'fts_search_sync_outbox_claim_idx']
+ dead_at [name: 'fts_search_sync_outbox_dead_idx']
+ locked_until [name: 'fts_search_sync_outbox_lease_idx']
+ }
+}
+
table session_groups {
id text [pk, not null]
name text [not null]
@@ -3158,7 +3180,7 @@ table tasks {
updated_at "timestamp with time zone" [not null, default: `now()`]
indexes {
-
+
(identifier, created_by_user_id) [name: 'tasks_identifier_idx', unique]
created_by_user_id [name: 'tasks_created_by_user_id_idx']
created_by_agent_id [name: 'tasks_created_by_agent_id_idx']
@@ -3332,10 +3354,10 @@ table topic_comments {
indexes {
(topic_id, author_user_id, client_id) [name: 'topic_comments_topic_id_author_user_id_client_id_unique', unique]
-
-
-
-
+
+
+
+
(parent_comment_id, created_at, id) [name: 'topic_comments_parent_comment_id_created_at_id_idx']
(topic_id, created_at, id) [name: 'topic_comments_topic_id_created_at_id_idx']
(topic_id, message_id) [name: 'topic_comments_topic_id_message_id_idx']
@@ -3511,6 +3533,7 @@ table user_memories_contexts {
description_vector [name: 'user_memories_contexts_description_vector_index']
type [name: 'user_memories_contexts_type_index']
user_id [name: 'user_memories_contexts_user_id_index']
+ user_memory_ids [name: 'user_memories_contexts_user_memory_ids_gin_idx']
}
}
@@ -3821,7 +3844,7 @@ table verify_review_predictions {
workspace_id [name: 'verify_review_predictions_workspace_id_idx']
(provider, model) [name: 'verify_review_predictions_model_idx']
(check_result_id, provider, model, prompt_version) [name: 'verify_review_predictions_result_model_prompt_unique', unique]
-
+
}
}
@@ -3886,7 +3909,7 @@ table verify_runs {
workspace_id [name: 'verify_runs_workspace_id_idx']
acceptance_id [name: 'verify_runs_acceptance_id_idx']
(acceptance_id, round_index) [name: 'verify_runs_acceptance_round_unique', unique]
-
+
operation_id [name: 'verify_runs_operation_id_unique', unique]
source [name: 'verify_runs_source_idx']
user_decision [name: 'verify_runs_user_decision_idx']
@@ -4191,4 +4214,4 @@ ref: topic_documents.document_id > documents.id
ref: topic_documents.topic_id > topics.id
-ref: topics.session_id - sessions.id
\ No newline at end of file
+ref: topics.session_id - sessions.id
diff --git a/docs/self-hosting/advanced/elasticsearch-migration.mdx b/docs/self-hosting/advanced/elasticsearch-migration.mdx
new file mode 100644
index 00000000000..f0141315362
--- /dev/null
+++ b/docs/self-hosting/advanced/elasticsearch-migration.mdx
@@ -0,0 +1,276 @@
+---
+title: Migrate Search Data to Elasticsearch (3.x)
+description: Safely backfill LobeHub search data into an empty Elasticsearch project with durable resume support.
+tags:
+ - Elasticsearch
+ - Search
+ - Migration
+ - Self-hosting
+---
+
+# Migrate Search Data to Elasticsearch
+
+The 3.x migration tool copies LobeHub's 14 searchable entity types from PostgreSQL into a new Elasticsearch project. It atomically records the cursor, counters, and item-level failures in a local checkpoint file, so running the same command with the same state directory resumes the existing attempt.
+
+<Callout type="warning">
+ The reindex command does not switch product search requests to Elasticsearch. Keep the application on PostgreSQL search while you backfill and validate the new indexes. The regular database migration creates the PostgreSQL Outbox schema and the schema-managed Memory fanout GIN index; it does not install search-capture functions or triggers. Capture starts only after you explicitly run `bun run db:install-fts-search-capture` or start `bun run fts-search:reindex -- --apply`, even if the incremental consumer is still paused.
+</Callout>
+
+## Environment variables
+
+| Variable | Required | Purpose |
+| ------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
+| `DATABASE_URL` | Yes | PostgreSQL source database and incremental-change Outbox. Reindex checkpoints are not stored in the database. |
+| `ES_URL` | Apply | HTTPS endpoint of the new, empty Elasticsearch project that receives the 3.x search indexes. |
+| `ES_API_KEY` | Apply | Elasticsearch API key used to create indexes, write bulk documents, refresh/count indexes, and create aliases. Do not use a read-only key. |
+| `ES_INDEX_NAMESPACE` | Yes | Stable deployment-owned prefix, for example `lobehub`. It produces aliases such as `lobehub-messages`. Keep it unchanged across reruns. |
+| `FTS_SEARCH_SYNC_ENABLED` | Sync | Set to `true` only after the full backfill is ready and before running the incremental consumer. |
+| `ES_REINDEX_STATE_DIR` | Mutate | Local checkpoint directory. It must be explicit for mutations and must persist across every resume attempt. |
+| `FTS_SEARCH_PROVIDER` | Runtime | Full-text search provider: `pg_search` (default) or `elasticsearch`. Keep `pg_search` until backfill, catch-up, and validation finish. |
+
+`ES_URL` and `ES_API_KEY` are not needed for the read-only `--status` command.
+Operators that keep multiple Elasticsearch targets in one environment can select an explicit pair
+with `--elasticsearch-url-env=<KEY>` and `--elasticsearch-api-key-env=<KEY>`. Both flags are
+required together. `--expected-elasticsearch-host-prefix=<PREFIX>` can additionally refuse a
+mistargeted endpoint before any backfill mutation. The command prints and logs the selected
+hostname and variable names, never credential values.
+
+Remote Elasticsearch targets must use HTTPS. Plain HTTP is accepted only for loopback addresses
+such as `localhost` during local development, so an API key cannot be sent unencrypted to a remote
+host.
+
+## Before you start
+
+1. Create a new empty Elasticsearch project in the intended production region. LobeHub's search
+ analyzers require the official
+ [`analysis-icu`](https://www.elastic.co/docs/reference/elasticsearch/plugins/analysis-icu)
+ plugin. Elastic Cloud Serverless includes core analysis plugins; on Elastic Cloud Hosted, enable
+ the provided plugin for the deployment; on self-managed Elasticsearch, install it on every node
+ and restart every node before the first `--apply`.
+
+2. Back up PostgreSQL before enabling Elasticsearch capture.
+
+3. If an existing, write-heavy database is about to apply the migration, run the following
+ statement in the database SQL editor, outside a transaction. It builds the Memory fanout index
+ without blocking writes, so the regular migration can reuse it. A new or low-traffic
+ installation can skip this pre-step and let the migration create the index normally:
+
+ ```sql
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "user_memories_contexts_user_memory_ids_gin_idx"
+ ON "user_memories_contexts" USING gin ("user_memory_ids");
+ ```
+
+ `IF NOT EXISTS` does not verify an existing index definition. If an interrupted build left this
+ index invalid, or the installer reports that its table, column, GIN operator class, or predicate
+ is wrong, run `DROP INDEX CONCURRENTLY "user_memories_contexts_user_memory_ids_gin_idx"` outside
+ a transaction, recreate it with the statement above, and then continue.
+
+4. Apply the database migrations for the same LobeHub release:
+
+ ```bash
+ bun run db:migrate
+ ```
+
+ This creates the Outbox sequence, table, ordinary Outbox indexes, and the schema-managed Memory
+ fanout GIN index. It does not create the PostgreSQL change-capture functions or triggers. A
+ PostgreSQL-only deployment can stop here: it still maintains the schema-managed GIN index, but
+ does not pay the trigger or Outbox capture-write overhead.
+
+5. Install the optional PostgreSQL change capture before the first backfill:
+
+ ```bash
+ bun run db:install-fts-search-capture
+ ```
+
+ The installer first strictly validates the schema-managed GIN index (it does not create it), then
+ atomically installs and verifies the capture functions and 16 triggers in one transaction. It is
+ safe to rerun when the complete expected infrastructure already exists; partial, disabled, or
+ unexpected definitions fail closed instead of being silently repaired. Once it succeeds, source
+ changes are recorded in the Outbox immediately. The `bun run fts-search:reindex -- --apply` command
+ also runs this installer automatically; using the explicit command first is useful when you want
+ capture active while preparing the Elasticsearch target. If you do not intend to enable
+ Elasticsearch, do not run it.
+
+6. Keep the application's search backend on PostgreSQL and keep incremental Elasticsearch draining disabled.
+
+The first production mapping is version `v1`. The tool creates physical indexes such as `lobehub-messages-v1`. After all 14 indexes finish and their counts match the durable checkpoints, it creates stable aliases such as `lobehub-messages`. An alias is only a stable Elasticsearch name; creating it does not change which search backend serves users.
+
+If a stable alias already points to another physical index, the command fails instead of moving it.
+Online schema-version upgrades require a separately coordinated dual-write migration and are not
+supported by this initial migration tool.
+
+## Run from source
+
+Inspect the current state without writing to Elasticsearch:
+
+```bash
+bun run fts-search:reindex -- --status
+```
+
+Choose a durable local state directory and start a new backfill into an empty Elasticsearch target:
+
+```bash
+ES_REINDEX_STATE_DIR=.elasticsearch-reindex \
+ bun run fts-search:reindex -- --apply --fresh-run --yes
+```
+
+Only the first invocation uses `--fresh-run`. Resume the same run with the same state directory:
+
+```bash
+ES_REINDEX_STATE_DIR=.elasticsearch-reindex bun run fts-search:reindex -- --apply --yes
+```
+
+`--apply` verifies every physical Elasticsearch index and its ICU analysis settings before reading
+source rows. It also validates the schema-managed Memory fanout GIN index (it never creates this
+index) and idempotently installs the optional PostgreSQL capture infrastructure (unless it was
+installed already). The read-only `--status` command never installs or changes this infrastructure.
+Before reading source rows, `--apply`
+briefly fences writes to all trigger source tables so transactions holding older Outbox revisions
+finish before the snapshot.
+If the three-second lock timeout expires, let the long transaction finish and rerun the command.
+Keep the incremental consumer paused during the initial backfill if
+needed; PostgreSQL continues to append changes to the Outbox, and the consumer can drain them
+after the full snapshot is ready. The required `--yes` acknowledges the mutating operation; it is
+not an interactive prompt.
+
+The run ID is also stored in each physical index's mapping metadata. A different local checkpoint
+cannot silently continue writing the same physical indexes. Never run copies of one checkpoint
+concurrently from multiple machines.
+
+The checkpoint file contains only migration control state and sanitized failure metadata. It never
+stores database or Elasticsearch credentials. Keep the entire state directory until validation and
+incremental catch-up finish; moving to another machine requires copying that directory.
+
+For a bounded rehearsal that exercises every entity without completing the full database, run one
+batch per non-empty entity with bounded concurrency:
+
+```bash
+ES_REINDEX_STATE_DIR=.elasticsearch-reindex \
+ bun run fts-search:reindex -- --apply --yes \
+ --expected-elasticsearch-host-prefix=search-dev- \
+ --entity-concurrency=4 --bulk-concurrency=2 \
+ --batch-size=5000 --bulk-max-bytes=10485760 \
+ --max-batches-per-entity=1
+```
+
+This command creates all 14 entity indexes and writes source rows into each non-empty one. If at
+least one entity has more than the configured batch limit, the run remains in `backfilling` without
+creating aliases. A small deployment whose 14 entities all fit within the limit can complete and
+create aliases in this rehearsal, so always use an isolated empty Elasticsearch target. Re-run the
+same command to exercise resume behavior, or remove `--max-batches-per-entity` to intentionally
+continue until every entity completes.
+
+`--entity-concurrency` controls independent PostgreSQL entity scans. `--bulk-concurrency` controls
+parallel byte-bounded Elasticsearch requests inside each entity batch. Start conservatively and
+increase them only while PostgreSQL and Elasticsearch remain healthy. `--batch-size` limits rows
+per keyset page. `--bulk-max-bytes` limits each encoded `_bulk` request; an individual document
+larger than this limit is stored as an explicit failure.
+
+Transient request failures are retried with exponential backoff before the batch cursor advances.
+The defaults are four retries, a 500 ms base delay, and a 30-second request timeout. Override them
+with `--max-request-retries`, `--retry-base-delay-ms`, and `--request-timeout-ms` when required.
+
+Every apply or resume session appends sanitized operational events to
+`<state-dir>/runs/<run-id>/events.jsonl` and atomically replaces
+`<state-dir>/runs/<run-id>/summary.json`. The log records entity and bulk timings, byte and document
+counts, retries, cursors, failures, and final state. It never records database or Elasticsearch
+URLs, credentials, or document source text. Keep these private files with the checkpoint when
+moving or archiving a run.
+
+## Run from the Docker image
+
+The official image includes `/app/fts-search-elasticsearch-reindex.cjs`:
+
+```bash
+mkdir -m 700 -p .elasticsearch-reindex
+docker run --rm --user "$(id -u):$(id -g)" --env-file .env \
+ -e ES_REINDEX_STATE_DIR=/data/elasticsearch-reindex \
+ -v "$PWD/.elasticsearch-reindex:/data/elasticsearch-reindex" \
+ lobehub/lobehub:latest /app/fts-search-elasticsearch-reindex.cjs --status
+docker run --rm --user "$(id -u):$(id -g)" --env-file .env \
+ -e ES_REINDEX_STATE_DIR=/data/elasticsearch-reindex \
+ -v "$PWD/.elasticsearch-reindex:/data/elasticsearch-reindex" \
+ lobehub/lobehub:latest /app/fts-search-elasticsearch-reindex.cjs --apply --fresh-run --yes
+```
+
+The bind mount is required for resume after a `--rm` container exits. Running with the host user's
+ID lets the process write the bind-mounted directory without changing its ownership. If Docker
+Compose already supplies the same environment variables and database network, mount the same
+persistent state directory and run the image as a one-time service instead of starting a second
+application server.
+
+## Start incremental synchronization
+
+After the reindex status is `ready_for_incremental_sync`, set
+`FTS_SEARCH_SYNC_ENABLED=true` and run the bounded consumer:
+
+```bash
+bun run fts-search:sync -- --max-steps=8 --yes
+```
+
+One invocation processes at most eight drain steps and then exits. `hasMore: true` in the final JSON
+means the bound was reached safely; run it again. Schedule the same command with cron, a container
+job, or another process supervisor so it continues to run while Elasticsearch search is enabled.
+The consumer validates the PostgreSQL capture definitions and every Elasticsearch write alias before
+claiming work. Missing or stale capture infrastructure, an invalid alias, retryable write failure, or
+dead-letter work produces a non-zero exit code. It never installs triggers and never deletes failed
+work automatically.
+
+The official image includes `/app/fts-search-elasticsearch-sync.cjs` for the same bounded operation:
+
+```bash
+docker run --rm --env-file .env \
+ -e FTS_SEARCH_SYNC_ENABLED=true \
+ -e MIGRATION_DB=1 \
+ lobehub/lobehub:latest /app/fts-search-elasticsearch-sync.cjs --max-steps=8 --yes
+```
+
+Keep scheduling the consumer and run `bun run fts-search:reindex -- --status` until `pending`, `ready`,
+`retrying`, `inFlight`, `dead`, and `revisionLag` are all zero. Recheck that state immediately before
+switching queries. Then set `FTS_SEARCH_PROVIDER=elasticsearch` and redeploy the application. Keep
+`FTS_SEARCH_PROVIDER=pg_search` until catch-up is complete. Elasticsearch failures remain visible to
+callers; the search path does not silently fall back to PostgreSQL or `ilike`.
+
+## Resume and verify
+
+- After a process crash or temporary Elasticsearch failure, re-run the `--apply --yes` command with the same state directory but without `--fresh-run`. Completed entities are skipped and the next batch starts after the local cursor. This is safe while the optional capture infrastructure remains installed, because changes made during the pause are retained in the Outbox.
+- Request-level failures do not advance the cursor. If one concurrent bulk succeeds and another fails, the entire database batch is replayed safely on resume. Item-level failures are recorded in the local checkpoint and replayed before an entity can complete.
+- The tool refuses to create aliases while any entity or item-level failure is incomplete.
+- The final status is `ready_for_incremental_sync`. At this point the full snapshot, aliases, and the Outbox high-water boundary exist, but user queries must still remain on PostgreSQL.
+
+The high-water revision is an observation point for catch-up monitoring, not a committed database
+snapshot. An incremental consumer must process every queued row and must never discard rows only
+because their revision is at or below that value.
+
+Run `--status` and confirm all 14 entities show `completed`, every `failedCount` is `0`, and the
+Outbox `dead` count is `0` before starting the incremental consumer documented above. A paused
+incremental consumer may leave queued Outbox work; that is expected
+while backfill is running and does not mean source-change capture is paused. The status output
+lists unresolved document IDs, retryability, and attempt counts without persisting or printing
+Elasticsearch error reasons that may contain source text.
+
+After correcting a rejected source document or mapping, run `--apply --yes` again to retry it. If an
+operator deliberately accepts that one document with a non-retryable failure will be absent from
+the initial Elasticsearch snapshot, resolve the blocker explicitly and then resume:
+
+```bash
+ES_REINDEX_STATE_DIR=.elasticsearch-reindex \
+ bun run fts-search:reindex -- --skip-failure=agents:document-id --yes
+ES_REINDEX_STATE_DIR=.elasticsearch-reindex bun run fts-search:reindex -- --apply --yes
+```
+
+Only non-retryable failures can be skipped, and skipping does not count the document as indexed. Use
+it only after reviewing the source record and accepting that it will not be searchable until a
+later source change or incremental repair writes it.
+
+To pause incremental Elasticsearch writes during backfill, pause the deployment's incremental
+consumer using its normal worker setting. This does not stop the installed PostgreSQL capture
+triggers: source changes continue to accumulate in the Outbox and can be drained when the consumer
+is enabled. Do not disable or remove the triggers, or truncate the Outbox, while a reindex is in
+progress.
+
+<Callout type="info">
+ The full-reindex command does not run the recurring incremental consumer and does not claim that
+ the application is ready to switch search backends by itself. Keep `fts-search:sync` scheduled for as
+ long as Elasticsearch serves search traffic.
+</Callout>
diff --git a/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx b/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx
new file mode 100644
index 00000000000..6507fb657cd
--- /dev/null
+++ b/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx
@@ -0,0 +1,186 @@
+---
+title: 将搜索数据迁移到 Elasticsearch(3.x)
+description: 使用可断点续跑的工具,将 LobeHub 搜索数据安全回填到空的 Elasticsearch 项目。
+tags:
+ - Elasticsearch
+ - 搜索
+ - 迁移
+ - 私有部署
+---
+
+# 将搜索数据迁移到 Elasticsearch
+
+3.x 迁移工具会把 PostgreSQL 中 14 类可搜索数据复制到新的 Elasticsearch 项目。工具会把游标、计数和逐条失败记录原子写入本地 checkpoint 文件,因此中断后使用同一个状态目录重复执行命令即可续跑。
+
+<Callout type="warning">
+ 全量回填命令不会把产品搜索请求切到 Elasticsearch。回填和验收期间,应用必须继续使用 PostgreSQL 搜索。常规数据库迁移会创建 PostgreSQL 增量队列的基础结构和由数据库结构管理的 Memory 扇出 GIN 索引,但不会安装搜索变更采集函数和触发器。只有显式执行 `bun run db:install-fts-search-capture` 或启动 `bun run fts-search:reindex -- --apply` 后才会开始采集,即使增量消费器仍处于暂停状态也是如此。
+</Callout>
+
+## 环境变量
+
+| 变量 | 是否必需 | 用途 |
+| ------------------------- | ---- | --------------------------------------------------------------------- |
+| `DATABASE_URL` | 是 | PostgreSQL 源数据库和增量变更队列;回填 checkpoint 不写入数据库。 |
+| `ES_URL` | 执行时 | 新建空 Elasticsearch 项目的 HTTPS 地址,用于接收 3.x 搜索索引。 |
+| `ES_API_KEY` | 执行时 | 用于创建索引、批量写入、刷新 / 统计索引和创建别名的 Elasticsearch 密钥,不能使用只读密钥。 |
+| `ES_INDEX_NAMESPACE` | 是 | 当前部署长期不变的索引前缀,例如 `lobehub`;会生成 `lobehub-messages` 等别名,续跑时不能修改。 |
+| `FTS_SEARCH_SYNC_ENABLED` | 增量同步 | 只有全量回填就绪后才能设为 `true`,用于启用增量消费器。 |
+| `ES_REINDEX_STATE_DIR` | 执行时 | 本地 checkpoint 目录;修改状态时必须显式配置,且每次续跑都必须保留并使用同一个目录。 |
+| `FTS_SEARCH_PROVIDER` | 运行时 | 全文搜索提供方:`pg_search`(默认)或 `elasticsearch`;完成回填、追平和验收前必须保持 `pg_search`。 |
+
+只读的 `--status` 命令不需要 `ES_URL` 和 `ES_API_KEY`。
+如果同一个环境中保存了多套 Elasticsearch 目标,可以同时传入 `--elasticsearch-url-env=<变量名>` 和 `--elasticsearch-api-key-env=<变量名>` 显式选择其中一组。两个参数必须成对使用;还可以通过 `--expected-elasticsearch-host-prefix=<主机名前缀>` 在任何回填写入前拒绝错误目标。命令会打印并记录选中的主机名和变量名,但不会记录密钥值。
+
+远程 Elasticsearch 目标必须使用 HTTPS。只有本地开发时的 `localhost` 等回环地址可以使用明文 HTTP,避免把 API 密钥通过未加密连接发送到远程主机。
+
+## 开始前
+
+1. 在正式使用的区域创建一个新的空 Elasticsearch 项目。LobeHub 搜索分析器依赖官方
+ [`analysis-icu`](https://www.elastic.co/docs/reference/elasticsearch/plugins/analysis-icu)
+ 插件。Elastic Cloud Serverless 已包含核心分析插件;Elastic Cloud Hosted 需要为部署启用官方插件;自行管理的 Elasticsearch 必须在所有节点安装插件并重启所有节点。请在首次执行 `--apply` 前完成。
+
+2. 在启用 Elasticsearch 采集前备份 PostgreSQL。
+
+3. 如果是已有且写入量较大的数据库,请在执行数据库迁移前,在数据库 SQL 编辑器中、事务之外执行以下语句。它会在不阻塞写入的情况下创建 Memory 扇出索引,后续常规迁移可以直接复用。全新或低流量安装可以跳过这一步,交给迁移正常创建索引:
+
+ ```sql
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "user_memories_contexts_user_memory_ids_gin_idx"
+ ON "user_memories_contexts" USING gin ("user_memory_ids");
+ ```
+
+ `IF NOT EXISTS` 不会校验同名索引的定义。如果并发创建留下无效索引,或安装器提示索引的表、列、GIN 操作符类或条件不正确,请在事务之外执行 `DROP INDEX CONCURRENTLY "user_memories_contexts_user_memory_ids_gin_idx"`,用上面的语句重新创建,然后继续后续步骤。
+
+4. 执行同一 LobeHub 版本自带的数据库迁移:
+
+ ```bash
+ bun run db:migrate
+ ```
+
+ 这一步会创建增量队列的序列、表、普通索引,以及由数据库结构管理的 Memory 扇出 GIN 索引,但不会创建 PostgreSQL 变更采集函数和触发器。只使用 PostgreSQL 搜索的部署可以停在这里:它仍会维护这个 GIN 索引,但不会承担触发器和增量队列的采集写入开销。
+
+5. 在首次回填前安装可选的 PostgreSQL 变更采集:
+
+ ```bash
+ bun run db:install-fts-search-capture
+ ```
+
+ 安装器会先严格校验由数据库结构管理的 GIN 索引(不会创建这个索引),再在一个事务中原子安装并验证采集函数和 16 个触发器。完整的预期设施已经存在时可以安全重复执行;如果发现部分对象、被禁用的对象或定义异常,安装器会直接失败,不会静默修复。安装成功后,源数据变更会立即写入增量队列。`bun run fts-search:reindex -- --apply` 也会自动执行这一步;如果希望在准备 Elasticsearch 目标期间就开始采集,可以先显式执行安装命令。若不打算启用 Elasticsearch,不要执行这一步。
+
+6. 保持应用搜索后端为 PostgreSQL,并关闭 Elasticsearch 增量消费。
+
+首次正式映射版本是 `v1`。工具会创建 `lobehub-messages-v1` 这类实体索引;14 类索引全部完成且数量与断点记录一致后,再创建 `lobehub-messages` 这类稳定别名。别名只是 Elasticsearch 内部长期不变的名字,创建别名不会改变用户请求当前使用的搜索后端。
+
+如果稳定别名已经指向另一个物理索引,命令会直接失败,不会移动别名。在线升级索引版本需要另外设计受协调的双写迁移;这套首次迁移工具暂不支持该场景。
+
+## 在源码中运行
+
+只查看状态,不写 Elasticsearch:
+
+```bash
+bun run fts-search:reindex -- --status
+```
+
+选择可持久保留的本地状态目录,并向空的 Elasticsearch 目标开始一次新回填:
+
+```bash
+ES_REINDEX_STATE_DIR=.elasticsearch-reindex \
+ bun run fts-search:reindex -- --apply --fresh-run --yes
+```
+
+只有第一次执行需要 `--fresh-run`。后续使用同一个状态目录续跑:
+
+```bash
+ES_REINDEX_STATE_DIR=.elasticsearch-reindex bun run fts-search:reindex -- --apply --yes
+```
+
+`--apply` 会先创建或校验所有 Elasticsearch 物理索引及其 ICU 分析设置,校验由数据库结构管理的 Memory 扇出 GIN 索引(不会创建这个索引),并以幂等方式安装可选的 PostgreSQL 变更采集设施(如果之前已经安装则复用),然后读取源数据。只读的 `--status` 不会安装或修改这些设施。读取源数据前,`--apply` 会短暂阻挡所有触发器源表的写入,等待持有较旧 Outbox 版本的事务结束;如果三秒内拿不到锁,应先让长事务结束,再重新运行命令。首次回填期间可以暂停增量消费器;PostgreSQL 仍会把变更追加到增量队列,完整快照准备好后再由消费器追平。必须显式传入 `--yes`,用于确认这个会写入数据的操作;命令不会弹出交互确认。
+
+工具还会把 run ID 写入每个物理索引的 mapping 元数据,使用另一份本地 checkpoint 时无法静默继续写入同一组物理索引。禁止在多台机器上并发运行同一份 checkpoint。
+
+checkpoint 文件只包含迁移控制状态和脱敏后的失败信息,不保存数据库或 Elasticsearch 密钥。完成验收和增量追平前必须保留整个状态目录;换机器执行时需要一起复制该目录。
+
+如果只想验证 14 类数据都能走通真实回填路径,而不在测试环境跑完整库,可以让每个非空数据类型只执行一个批次,并开启受控并发:
+
+```bash
+ES_REINDEX_STATE_DIR=.elasticsearch-reindex \
+ bun run fts-search:reindex -- --apply --yes \
+ --expected-elasticsearch-host-prefix=search-dev- \
+ --entity-concurrency=4 --bulk-concurrency=2 \
+ --batch-size=5000 --bulk-max-bytes=10485760 \
+ --max-batches-per-entity=1
+```
+
+这条命令会创建 14 类索引,并向其中有源数据的索引写入真实数据。只要至少一类数据超过批次上限,任务就会保持在 `backfilling` 状态且不会创建别名;如果某个小型部署的 14 类数据都能在上限内读完,本次演练仍会正常完成并创建别名,因此必须使用隔离的空 Elasticsearch 目标。使用同一命令再次执行可以验证断点续跑;移除 `--max-batches-per-entity` 后会从当前断点继续,直到所有数据类型完成。
+
+`--entity-concurrency` 控制同时读取多少类 PostgreSQL 数据,`--bulk-concurrency` 控制每个数据类型的单批数据可同时发出多少个按字节拆分的 Elasticsearch 请求。应从较小数值开始,仅在 PostgreSQL 和 Elasticsearch 运行稳定时逐步增加。`--batch-size` 限制每次按主键翻页读取的 PostgreSQL 行数;`--bulk-max-bytes` 按编码后的字节数限制单次 `_bulk` 请求。单个文档超过限制时会被明确记为失败,不会静默跳过。
+
+临时请求失败会先按指数间隔自动重试,再决定是否推进本批游标。默认最多重试 4 次,基础间隔为 500 毫秒,单次请求超时为 30 秒;需要时可通过 `--max-request-retries`、`--retry-base-delay-ms` 和 `--request-timeout-ms` 调整。
+
+每次执行或续跑都会把脱敏后的详细运行事件追加到 `<状态目录>/runs/<run-id>/events.jsonl`,并原子更新 `<状态目录>/runs/<run-id>/summary.json`。日志包含各数据类型和批量请求的耗时、字节数、文档数、重试、游标、失败与最终状态,但不会记录数据库或 Elasticsearch 地址、密钥以及文档正文。迁移或归档任务时,应把这些私有日志和 checkpoint 一起保留。
+
+## 使用 Docker 镜像运行
+
+官方镜像内置 `/app/fts-search-elasticsearch-reindex.cjs`:
+
+```bash
+mkdir -m 700 -p .elasticsearch-reindex
+docker run --rm --user "$(id -u):$(id -g)" --env-file .env \
+ -e ES_REINDEX_STATE_DIR=/data/elasticsearch-reindex \
+ -v "$PWD/.elasticsearch-reindex:/data/elasticsearch-reindex" \
+ lobehub/lobehub:latest /app/fts-search-elasticsearch-reindex.cjs --status
+docker run --rm --user "$(id -u):$(id -g)" --env-file .env \
+ -e ES_REINDEX_STATE_DIR=/data/elasticsearch-reindex \
+ -v "$PWD/.elasticsearch-reindex:/data/elasticsearch-reindex" \
+ lobehub/lobehub:latest /app/fts-search-elasticsearch-reindex.cjs --apply --fresh-run --yes
+```
+
+使用 `--rm` 时必须挂载状态目录,否则容器退出后无法续跑。命令使用宿主机当前用户的 ID 运行,使进程可以写入挂载目录,同时不会修改目录所有者。如果 Docker Compose 已提供相同的环境变量和数据库网络,请挂载同一个持久化状态目录,并把镜像作为一次性服务运行,不要再启动一个应用服务实例。
+
+## 启动增量同步
+
+全量回填状态变为 `ready_for_incremental_sync` 后,设置
+`FTS_SEARCH_SYNC_ENABLED=true`,再运行有明确上限的增量消费器:
+
+```bash
+bun run fts-search:sync -- --max-steps=8 --yes
+```
+
+每次最多执行 8 轮消费后退出。最终 JSON 中出现 `hasMore: true` 只表示本次达到上限,可以安全再次执行。应使用 cron、容器任务或其他进程管理器持续调度同一条命令,Elasticsearch 承担搜索期间不能停止。消费器会在领取任务前校验 PostgreSQL 采集定义和全部 Elasticsearch 写入别名;采集设施缺失或过期、别名异常、可重试写入失败或死信都会返回非零退出码。消费器不会自动安装触发器,也不会自动删除失败任务。
+
+官方镜像内置 `/app/fts-search-elasticsearch-sync.cjs`,执行的是同一套有界消费逻辑:
+
+```bash
+docker run --rm --env-file .env \
+ -e FTS_SEARCH_SYNC_ENABLED=true \
+ -e MIGRATION_DB=1 \
+ lobehub/lobehub:latest /app/fts-search-elasticsearch-sync.cjs --max-steps=8 --yes
+```
+
+保持持续调度,并反复运行 `bun run fts-search:reindex -- --status`,直到 `pending`、`ready`、`retrying`、`inFlight`、`dead` 和 `revisionLag` 全部为 0。切换查询前必须再检查一次。确认追平后,把 `FTS_SEARCH_PROVIDER` 设为 `elasticsearch` 并重新部署。追平前必须保持 `FTS_SEARCH_PROVIDER=pg_search`。Elasticsearch 出错时会直接暴露给调用方,搜索路径不会静默回退到 PostgreSQL 或 `ilike`。
+
+## 续跑与验收
+
+- 进程崩溃或 Elasticsearch 临时失败后,使用同一个状态目录重新执行 `--apply --yes`,但不要再传 `--fresh-run`。已完成的数据类型会被跳过,未完成的数据类型从本地游标后继续。只要可选的采集设施仍在,暂停期间的变更就会保留在增量队列中,因此可以安全续跑。
+- 整个请求失败时不会推进游标;如果同一批中的部分并发请求成功、另一部分失败,续跑时会安全重放整个数据库批次。逐条写入失败会写入本地 checkpoint,并在该数据类型完成前重试。
+- 任何数据类型或逐条失败尚未完成时,工具都会拒绝创建别名。
+- 最终状态为 `ready_for_incremental_sync`。此时全量快照、别名和增量队列的追平边界已经就绪,但用户查询仍必须留在 PostgreSQL。
+
+这个修订号只用于观察增量追平进度,不是数据库已经提交的快照边界。增量消费器必须处理队列里的每一条记录,不能仅因修订号小于或等于该值就丢弃记录。
+
+启动上面说明的增量消费器前,运行 `--status`,确认 14 类数据全部为 `completed`、所有 `failedCount` 都是 `0`,且增量队列的 `dead` 为 `0`。增量消费器暂停时,队列中有待处理记录是预期现象;这不代表源数据变更采集已暂停。状态会列出未解决记录的文档标识、是否可重试和尝试次数,不会保存或输出可能包含原文的 Elasticsearch 错误原因。
+
+修正被拒绝的源数据或映射后,再执行 `--apply --yes` 即可重试。如果运维人员明确接受某一条不可重试的数据暂时不进入初始 Elasticsearch 快照,可以显式解除阻塞,然后继续回填:
+
+```bash
+ES_REINDEX_STATE_DIR=.elasticsearch-reindex \
+ bun run fts-search:reindex -- --skip-failure=agents:document-id --yes
+ES_REINDEX_STATE_DIR=.elasticsearch-reindex bun run fts-search:reindex -- --apply --yes
+```
+
+只有不可重试的失败可以跳过,且跳过不会把该文档计为写入成功。只有在检查源记录,并接受它需要等后续数据变更或增量修复后才能被搜索到时,才能使用这个命令。
+
+回填期间如需暂停写入 Elasticsearch,请使用部署环境提供的增量消费器开关。这只会暂停消费增量队列,不会停止已经安装的 PostgreSQL 采集触发器;源数据变更会继续进入增量队列,消费器重新开启后即可追平。回填进行期间不要禁用或删除触发器,也不要清空增量队列。
+
+<Callout type="info">
+ 全量回填命令不会代替持续运行的增量消费器,也不会自行宣称应用已经可以切换搜索后端。只要 Elasticsearch 仍在承担搜索,就必须持续调度 `fts-search:sync`。
+</Callout>
diff --git a/package.json b/package.json
index 550d8bf9b5c..609aa7976c8 100644
--- a/package.json
+++ b/package.json
@@ -59,6 +59,7 @@
"check": "bun run .agents/scripts/check/cli.ts",
"clean:node_modules": "bash -lc 'set -e; echo \"Removing all node_modules...\"; rm -rf node_modules; pnpm -r exec rm -rf node_modules; rm -rf apps/desktop/node_modules; echo \"All node_modules removed.\"'",
"db:generate": "drizzle-kit generate && npm run workflow:dbml",
+ "db:install-fts-search-capture": "cross-env MIGRATION_DB=1 tsx ./scripts/installFtsSearchSyncCapture/index.ts",
"db:migrate": "cross-env MIGRATION_DB=1 tsx ./scripts/migrateServerDB/index.ts",
"db:studio": "drizzle-kit studio",
"db:visualize": "dbdocs build docs/development/database-schema.dbml --project lobe-chat",
@@ -88,6 +89,8 @@
"e2e": "cd e2e && npm run test",
"e2e:install": "playwright install",
"e2e:ui": "playwright test --ui",
+ "fts-search:reindex": "bun run scripts/elasticsearchReindex/index.ts",
+ "fts-search:sync": "cross-env MIGRATION_DB=1 bun run scripts/elasticsearchSync/cli.ts",
"hotfix:branch": "tsx ./scripts/hotfixWorkflow/index.ts",
"i18n": "npm run workflow:i18n && lobe-i18n && prettier -c --write \"locales/**\"",
"i18n:unused": "tsx ./scripts/i18nWorkflow/analyzeUnusedKeys.ts",
@@ -536,6 +539,7 @@
"dpdm-fast": "^1.0.14",
"drizzle-dbml-generator": "^0.10.0",
"drizzle-kit": "^0.31.10",
+ "esbuild": "^0.28.2",
"eslint": "10.0.2",
"eslint-plugin-mdx": "^3.8.1",
"fake-indexeddb": "^6.2.5",
diff --git a/packages/builtin-tool-knowledge-base/src/types.ts b/packages/builtin-tool-knowledge-base/src/types.ts
index 933ed77e139..427c0fe359b 100644
--- a/packages/builtin-tool-knowledge-base/src/types.ts
+++ b/packages/builtin-tool-knowledge-base/src/types.ts
@@ -26,7 +26,7 @@ export interface SearchKnowledgeBaseArgs {
/**
* BM25 hit on a document inside a knowledge base. Covers both inline
* `custom/document` pages and file-backed documents (parsed PDFs and the like).
- * Mirrors database/repositories/search KnowledgeBaseDocumentHit; redeclared
+ * Mirrors database/repositories/ftsSearch FtsSearchKnowledgeBaseDocumentHit; redeclared
* here to keep this package decoupled from server-only types.
*/
export interface KnowledgeBaseDocumentResult {
diff --git a/packages/database/migrations/0153_fts_search_sync_outbox.sql b/packages/database/migrations/0153_fts_search_sync_outbox.sql
new file mode 100644
index 00000000000..69ff26080c7
--- /dev/null
+++ b/packages/database/migrations/0153_fts_search_sync_outbox.sql
@@ -0,0 +1,21 @@
+CREATE SEQUENCE IF NOT EXISTS "public"."fts_search_sync_revision_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1;--> statement-breakpoint
+CREATE TABLE IF NOT EXISTS "fts_search_sync_outbox" (
+ "attempts" integer DEFAULT 0 NOT NULL,
+ "available_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "dead_at" timestamp with time zone,
+ "document_id" text NOT NULL,
+ "entity" text NOT NULL,
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "last_error" text,
+ "locked_until" timestamp with time zone,
+ "priority" smallint DEFAULT 10 NOT NULL,
+ "revision" bigint DEFAULT nextval('fts_search_sync_revision_seq') NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS "fts_search_sync_outbox_entity_document_id_unique" ON "fts_search_sync_outbox" USING btree ("entity","document_id");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "fts_search_sync_outbox_claim_idx" ON "fts_search_sync_outbox" USING btree ("priority","available_at","revision") WHERE "fts_search_sync_outbox"."dead_at" IS NULL;--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "fts_search_sync_outbox_dead_idx" ON "fts_search_sync_outbox" USING btree ("dead_at") WHERE "fts_search_sync_outbox"."dead_at" IS NOT NULL;--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "fts_search_sync_outbox_lease_idx" ON "fts_search_sync_outbox" USING btree ("locked_until") WHERE "fts_search_sync_outbox"."dead_at" IS NULL AND "fts_search_sync_outbox"."locked_until" IS NOT NULL;--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "user_memories_contexts_user_memory_ids_gin_idx" ON "user_memories_contexts" USING gin ("user_memory_ids");
diff --git a/packages/database/migrations/meta/0153_snapshot.json b/packages/database/migrations/meta/0153_snapshot.json
new file mode 100644
index 00000000000..7bb9c49bb4b
--- /dev/null
+++ b/packages/database/migrations/meta/0153_snapshot.json
@@ -0,0 +1,34281 @@
+{
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ },
+ "dialect": "postgresql",
+ "enums": {},
+ "id": "ce060b2d-2042-4ce9-aa4d-5fff9bff81ba",
+ "policies": {},
+ "prevId": "4a79f706-85c1-49cd-91ed-ec6f26c1281c",
+ "roles": {},
+ "schemas": {},
+ "sequences": {
+ "public.fts_search_sync_revision_seq": {
+ "name": "fts_search_sync_revision_seq",
+ "schema": "public",
+ "increment": "1",
+ "startWith": "1",
+ "minValue": "1",
+ "maxValue": "9223372036854775807",
+ "cache": "1",
+ "cycle": false
+ }
+ },
+ "tables": {
+ "public.agents": {
+ "name": "agents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "varchar(100)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "varchar(1000)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "editor_data": {
+ "name": "editor_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "avatar": {
+ "name": "avatar",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "background_color": {
+ "name": "background_color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "market_identifier": {
+ "name": "market_identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "profile": {
+ "name": "profile",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "society_id": {
+ "name": "society_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "plugins": {
+ "name": "plugins",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agency_config": {
+ "name": "agency_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "chat_config": {
+ "name": "chat_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "few_shots": {
+ "name": "few_shots",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "params": {
+ "name": "params",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "system_role": {
+ "name": "system_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tts": {
+ "name": "tts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "virtual": {
+ "name": "virtual",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "pinned": {
+ "name": "pinned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "opening_message": {
+ "name": "opening_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "opening_questions": {
+ "name": "opening_questions",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'"
+ },
+ "session_group_id": {
+ "name": "session_group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "client_id_user_id_unique": {
+ "name": "client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_slug_user_id_unique": {
+ "name": "agents_slug_user_id_unique",
+ "columns": [
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agents\".\"workspace_id\" is null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_created_at_idx": {
+ "name": "agents_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_user_id_idx": {
+ "name": "agents_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_title_idx": {
+ "name": "agents_title_idx",
+ "columns": [
+ {
+ "expression": "title",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_description_idx": {
+ "name": "agents_description_idx",
+ "columns": [
+ {
+ "expression": "description",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_session_group_id_idx": {
+ "name": "agents_session_group_id_idx",
+ "columns": [
+ {
+ "expression": "session_group_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_workspace_id_idx": {
+ "name": "agents_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_workspace_visibility_idx": {
+ "name": "agents_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_slug_workspace_id_unique": {
+ "name": "agents_slug_workspace_id_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agents\".\"workspace_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agents_user_id_users_id_fk": {
+ "name": "agents_user_id_users_id_fk",
+ "tableFrom": "agents",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agents_workspace_id_workspaces_id_fk": {
+ "name": "agents_workspace_id_workspaces_id_fk",
+ "tableFrom": "agents",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agents_session_group_id_session_groups_id_fk": {
+ "name": "agents_session_group_id_session_groups_id_fk",
+ "tableFrom": "agents",
+ "tableTo": "session_groups",
+ "columnsFrom": ["session_group_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agents_files": {
+ "name": "agents_files",
+ "schema": "",
+ "columns": {
+ "file_id": {
+ "name": "file_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agents_files_agent_id_idx": {
+ "name": "agents_files_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_files_file_id_idx": {
+ "name": "agents_files_file_id_idx",
+ "columns": [
+ {
+ "expression": "file_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_files_user_id_idx": {
+ "name": "agents_files_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_files_workspace_id_idx": {
+ "name": "agents_files_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agents_files_file_id_files_id_fk": {
+ "name": "agents_files_file_id_files_id_fk",
+ "tableFrom": "agents_files",
+ "tableTo": "files",
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agents_files_agent_id_agents_id_fk": {
+ "name": "agents_files_agent_id_agents_id_fk",
+ "tableFrom": "agents_files",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agents_files_user_id_users_id_fk": {
+ "name": "agents_files_user_id_users_id_fk",
+ "tableFrom": "agents_files",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agents_files_workspace_id_workspaces_id_fk": {
+ "name": "agents_files_workspace_id_workspaces_id_fk",
+ "tableFrom": "agents_files",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "agents_files_file_id_agent_id_user_id_pk": {
+ "name": "agents_files_file_id_agent_id_user_id_pk",
+ "columns": ["file_id", "agent_id", "user_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agents_knowledge_bases": {
+ "name": "agents_knowledge_bases",
+ "schema": "",
+ "columns": {
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "knowledge_base_id": {
+ "name": "knowledge_base_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agents_knowledge_bases_agent_id_idx": {
+ "name": "agents_knowledge_bases_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_knowledge_bases_knowledge_base_id_idx": {
+ "name": "agents_knowledge_bases_knowledge_base_id_idx",
+ "columns": [
+ {
+ "expression": "knowledge_base_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_knowledge_bases_user_id_idx": {
+ "name": "agents_knowledge_bases_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_knowledge_bases_workspace_id_idx": {
+ "name": "agents_knowledge_bases_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agents_knowledge_bases_agent_id_agents_id_fk": {
+ "name": "agents_knowledge_bases_agent_id_agents_id_fk",
+ "tableFrom": "agents_knowledge_bases",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agents_knowledge_bases_knowledge_base_id_knowledge_bases_id_fk": {
+ "name": "agents_knowledge_bases_knowledge_base_id_knowledge_bases_id_fk",
+ "tableFrom": "agents_knowledge_bases",
+ "tableTo": "knowledge_bases",
+ "columnsFrom": ["knowledge_base_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agents_knowledge_bases_user_id_users_id_fk": {
+ "name": "agents_knowledge_bases_user_id_users_id_fk",
+ "tableFrom": "agents_knowledge_bases",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agents_knowledge_bases_workspace_id_workspaces_id_fk": {
+ "name": "agents_knowledge_bases_workspace_id_workspaces_id_fk",
+ "tableFrom": "agents_knowledge_bases",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "agents_knowledge_bases_agent_id_knowledge_base_id_pk": {
+ "name": "agents_knowledge_bases_agent_id_knowledge_base_id_pk",
+ "columns": ["agent_id", "knowledge_base_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_bot_providers": {
+ "name": "agent_bot_providers",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "platform": {
+ "name": "platform",
+ "type": "varchar(50)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "application_id": {
+ "name": "application_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credentials": {
+ "name": "credentials",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "settings": {
+ "name": "settings",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_bot_providers_platform_app_id_unique": {
+ "name": "agent_bot_providers_platform_app_id_unique",
+ "columns": [
+ {
+ "expression": "platform",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "application_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_bot_providers_platform_idx": {
+ "name": "agent_bot_providers_platform_idx",
+ "columns": [
+ {
+ "expression": "platform",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_bot_providers_agent_id_idx": {
+ "name": "agent_bot_providers_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_bot_providers_user_id_idx": {
+ "name": "agent_bot_providers_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_bot_providers_workspace_id_idx": {
+ "name": "agent_bot_providers_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_bot_providers_agent_id_agents_id_fk": {
+ "name": "agent_bot_providers_agent_id_agents_id_fk",
+ "tableFrom": "agent_bot_providers",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_bot_providers_user_id_users_id_fk": {
+ "name": "agent_bot_providers_user_id_users_id_fk",
+ "tableFrom": "agent_bot_providers",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_bot_providers_workspace_id_workspaces_id_fk": {
+ "name": "agent_bot_providers_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_bot_providers",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_cron_jobs": {
+ "name": "agent_cron_jobs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "cron_pattern": {
+ "name": "cron_pattern",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'UTC'"
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "edit_data": {
+ "name": "edit_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "max_executions": {
+ "name": "max_executions",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "remaining_executions": {
+ "name": "remaining_executions",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "execution_conditions": {
+ "name": "execution_conditions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_executed_at": {
+ "name": "last_executed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "total_executions": {
+ "name": "total_executions",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_cron_jobs_agent_id_idx": {
+ "name": "agent_cron_jobs_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_cron_jobs_group_id_idx": {
+ "name": "agent_cron_jobs_group_id_idx",
+ "columns": [
+ {
+ "expression": "group_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_cron_jobs_user_id_idx": {
+ "name": "agent_cron_jobs_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_cron_jobs_workspace_id_idx": {
+ "name": "agent_cron_jobs_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_cron_jobs_enabled_idx": {
+ "name": "agent_cron_jobs_enabled_idx",
+ "columns": [
+ {
+ "expression": "enabled",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_cron_jobs_remaining_executions_idx": {
+ "name": "agent_cron_jobs_remaining_executions_idx",
+ "columns": [
+ {
+ "expression": "remaining_executions",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_cron_jobs_last_executed_at_idx": {
+ "name": "agent_cron_jobs_last_executed_at_idx",
+ "columns": [
+ {
+ "expression": "last_executed_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_cron_jobs_agent_id_agents_id_fk": {
+ "name": "agent_cron_jobs_agent_id_agents_id_fk",
+ "tableFrom": "agent_cron_jobs",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_cron_jobs_group_id_chat_groups_id_fk": {
+ "name": "agent_cron_jobs_group_id_chat_groups_id_fk",
+ "tableFrom": "agent_cron_jobs",
+ "tableTo": "chat_groups",
+ "columnsFrom": ["group_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_cron_jobs_user_id_users_id_fk": {
+ "name": "agent_cron_jobs_user_id_users_id_fk",
+ "tableFrom": "agent_cron_jobs",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_cron_jobs_workspace_id_workspaces_id_fk": {
+ "name": "agent_cron_jobs_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_cron_jobs",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_documents": {
+ "name": "agent_documents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "template_id": {
+ "name": "template_id",
+ "type": "varchar(100)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_self": {
+ "name": "access_self",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 31
+ },
+ "access_shared": {
+ "name": "access_shared",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "access_public": {
+ "name": "access_public",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "policy_load": {
+ "name": "policy_load",
+ "type": "varchar(30)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'always'"
+ },
+ "policy": {
+ "name": "policy",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "policy_load_position": {
+ "name": "policy_load_position",
+ "type": "varchar(50)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'before-first-user'"
+ },
+ "policy_load_format": {
+ "name": "policy_load_format",
+ "type": "varchar(20)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'raw'"
+ },
+ "policy_load_rule": {
+ "name": "policy_load_rule",
+ "type": "varchar(50)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'always'"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deleted_by_user_id": {
+ "name": "deleted_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deleted_by_agent_id": {
+ "name": "deleted_by_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "delete_reason": {
+ "name": "delete_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_documents_workspace_id_idx": {
+ "name": "agent_documents_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_user_id_idx": {
+ "name": "agent_documents_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_agent_id_idx": {
+ "name": "agent_documents_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_access_self_idx": {
+ "name": "agent_documents_access_self_idx",
+ "columns": [
+ {
+ "expression": "access_self",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_access_shared_idx": {
+ "name": "agent_documents_access_shared_idx",
+ "columns": [
+ {
+ "expression": "access_shared",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_access_public_idx": {
+ "name": "agent_documents_access_public_idx",
+ "columns": [
+ {
+ "expression": "access_public",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_policy_load_idx": {
+ "name": "agent_documents_policy_load_idx",
+ "columns": [
+ {
+ "expression": "policy_load",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_template_id_idx": {
+ "name": "agent_documents_template_id_idx",
+ "columns": [
+ {
+ "expression": "template_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_policy_load_position_idx": {
+ "name": "agent_documents_policy_load_position_idx",
+ "columns": [
+ {
+ "expression": "policy_load_position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_policy_load_format_idx": {
+ "name": "agent_documents_policy_load_format_idx",
+ "columns": [
+ {
+ "expression": "policy_load_format",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_policy_load_rule_idx": {
+ "name": "agent_documents_policy_load_rule_idx",
+ "columns": [
+ {
+ "expression": "policy_load_rule",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_agent_load_position_idx": {
+ "name": "agent_documents_agent_load_position_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "policy_load_position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_deleted_at_idx": {
+ "name": "agent_documents_deleted_at_idx",
+ "columns": [
+ {
+ "expression": "deleted_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_agent_autoload_deleted_idx": {
+ "name": "agent_documents_agent_autoload_deleted_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "deleted_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "policy_load",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_document_id_idx": {
+ "name": "agent_documents_document_id_idx",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_documents_agent_document_user_unique": {
+ "name": "agent_documents_agent_document_user_unique",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_documents_user_id_users_id_fk": {
+ "name": "agent_documents_user_id_users_id_fk",
+ "tableFrom": "agent_documents",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_documents_workspace_id_workspaces_id_fk": {
+ "name": "agent_documents_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_documents",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_documents_agent_id_agents_id_fk": {
+ "name": "agent_documents_agent_id_agents_id_fk",
+ "tableFrom": "agent_documents",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_documents_document_id_documents_id_fk": {
+ "name": "agent_documents_document_id_documents_id_fk",
+ "tableFrom": "agent_documents",
+ "tableTo": "documents",
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_documents_deleted_by_user_id_users_id_fk": {
+ "name": "agent_documents_deleted_by_user_id_users_id_fk",
+ "tableFrom": "agent_documents",
+ "tableTo": "users",
+ "columnsFrom": ["deleted_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "agent_documents_deleted_by_agent_id_agents_id_fk": {
+ "name": "agent_documents_deleted_by_agent_id_agents_id_fk",
+ "tableFrom": "agent_documents",
+ "tableTo": "agents",
+ "columnsFrom": ["deleted_by_agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_eval_benchmarks": {
+ "name": "agent_eval_benchmarks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rubrics": {
+ "name": "rubrics",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reference_url": {
+ "name": "reference_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_system": {
+ "name": "is_system",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_eval_benchmarks_identifier_user_id_unique": {
+ "name": "agent_eval_benchmarks_identifier_user_id_unique",
+ "columns": [
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agent_eval_benchmarks\".\"workspace_id\" is null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_benchmarks_is_system_idx": {
+ "name": "agent_eval_benchmarks_is_system_idx",
+ "columns": [
+ {
+ "expression": "is_system",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_benchmarks_user_id_idx": {
+ "name": "agent_eval_benchmarks_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_benchmarks_workspace_id_idx": {
+ "name": "agent_eval_benchmarks_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_benchmarks_identifier_workspace_id_unique": {
+ "name": "agent_eval_benchmarks_identifier_workspace_id_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agent_eval_benchmarks\".\"workspace_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_eval_benchmarks_user_id_users_id_fk": {
+ "name": "agent_eval_benchmarks_user_id_users_id_fk",
+ "tableFrom": "agent_eval_benchmarks",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_benchmarks_workspace_id_workspaces_id_fk": {
+ "name": "agent_eval_benchmarks_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_eval_benchmarks",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_eval_datasets": {
+ "name": "agent_eval_datasets",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "benchmark_id": {
+ "name": "benchmark_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_experiment_id": {
+ "name": "source_experiment_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "eval_mode": {
+ "name": "eval_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "eval_config": {
+ "name": "eval_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_eval_datasets_identifier_user_id_unique": {
+ "name": "agent_eval_datasets_identifier_user_id_unique",
+ "columns": [
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agent_eval_datasets\".\"workspace_id\" is null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_datasets_benchmark_id_idx": {
+ "name": "agent_eval_datasets_benchmark_id_idx",
+ "columns": [
+ {
+ "expression": "benchmark_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_datasets_source_experiment_id_idx": {
+ "name": "agent_eval_datasets_source_experiment_id_idx",
+ "columns": [
+ {
+ "expression": "source_experiment_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_datasets_user_id_idx": {
+ "name": "agent_eval_datasets_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_datasets_workspace_id_idx": {
+ "name": "agent_eval_datasets_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_datasets_identifier_workspace_id_unique": {
+ "name": "agent_eval_datasets_identifier_workspace_id_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agent_eval_datasets\".\"workspace_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_eval_datasets_benchmark_id_agent_eval_benchmarks_id_fk": {
+ "name": "agent_eval_datasets_benchmark_id_agent_eval_benchmarks_id_fk",
+ "tableFrom": "agent_eval_datasets",
+ "tableTo": "agent_eval_benchmarks",
+ "columnsFrom": ["benchmark_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_datasets_source_experiment_id_agent_eval_experiments_id_fk": {
+ "name": "agent_eval_datasets_source_experiment_id_agent_eval_experiments_id_fk",
+ "tableFrom": "agent_eval_datasets",
+ "tableTo": "agent_eval_experiments",
+ "columnsFrom": ["source_experiment_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "agent_eval_datasets_user_id_users_id_fk": {
+ "name": "agent_eval_datasets_user_id_users_id_fk",
+ "tableFrom": "agent_eval_datasets",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_datasets_workspace_id_workspaces_id_fk": {
+ "name": "agent_eval_datasets_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_eval_datasets",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_eval_experiment_benchmarks": {
+ "name": "agent_eval_experiment_benchmarks",
+ "schema": "",
+ "columns": {
+ "experiment_id": {
+ "name": "experiment_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "benchmark_id": {
+ "name": "benchmark_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_eval_experiment_benchmarks_benchmark_id_idx": {
+ "name": "agent_eval_experiment_benchmarks_benchmark_id_idx",
+ "columns": [
+ {
+ "expression": "benchmark_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_experiment_benchmarks_user_id_idx": {
+ "name": "agent_eval_experiment_benchmarks_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_experiment_benchmarks_workspace_id_idx": {
+ "name": "agent_eval_experiment_benchmarks_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_eval_experiment_benchmarks_experiment_id_agent_eval_experiments_id_fk": {
+ "name": "agent_eval_experiment_benchmarks_experiment_id_agent_eval_experiments_id_fk",
+ "tableFrom": "agent_eval_experiment_benchmarks",
+ "tableTo": "agent_eval_experiments",
+ "columnsFrom": ["experiment_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_experiment_benchmarks_benchmark_id_agent_eval_benchmarks_id_fk": {
+ "name": "agent_eval_experiment_benchmarks_benchmark_id_agent_eval_benchmarks_id_fk",
+ "tableFrom": "agent_eval_experiment_benchmarks",
+ "tableTo": "agent_eval_benchmarks",
+ "columnsFrom": ["benchmark_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_experiment_benchmarks_user_id_users_id_fk": {
+ "name": "agent_eval_experiment_benchmarks_user_id_users_id_fk",
+ "tableFrom": "agent_eval_experiment_benchmarks",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_experiment_benchmarks_workspace_id_workspaces_id_fk": {
+ "name": "agent_eval_experiment_benchmarks_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_eval_experiment_benchmarks",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "agent_eval_experiment_benchmarks_experiment_id_benchmark_id_pk": {
+ "name": "agent_eval_experiment_benchmarks_experiment_id_benchmark_id_pk",
+ "columns": ["experiment_id", "benchmark_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_eval_experiments": {
+ "name": "agent_eval_experiments",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_eval_experiments_user_id_idx": {
+ "name": "agent_eval_experiments_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_experiments_workspace_id_idx": {
+ "name": "agent_eval_experiments_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_eval_experiments_user_id_users_id_fk": {
+ "name": "agent_eval_experiments_user_id_users_id_fk",
+ "tableFrom": "agent_eval_experiments",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_experiments_workspace_id_workspaces_id_fk": {
+ "name": "agent_eval_experiments_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_eval_experiments",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_eval_run_topics": {
+ "name": "agent_eval_run_topics",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "test_case_id": {
+ "name": "test_case_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "score": {
+ "name": "score",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "passed": {
+ "name": "passed",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "eval_result": {
+ "name": "eval_result",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_eval_run_topics_user_id_idx": {
+ "name": "agent_eval_run_topics_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_run_topics_run_id_idx": {
+ "name": "agent_eval_run_topics_run_id_idx",
+ "columns": [
+ {
+ "expression": "run_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_run_topics_test_case_id_idx": {
+ "name": "agent_eval_run_topics_test_case_id_idx",
+ "columns": [
+ {
+ "expression": "test_case_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_run_topics_workspace_id_idx": {
+ "name": "agent_eval_run_topics_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_eval_run_topics_user_id_users_id_fk": {
+ "name": "agent_eval_run_topics_user_id_users_id_fk",
+ "tableFrom": "agent_eval_run_topics",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_run_topics_workspace_id_workspaces_id_fk": {
+ "name": "agent_eval_run_topics_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_eval_run_topics",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_run_topics_run_id_agent_eval_runs_id_fk": {
+ "name": "agent_eval_run_topics_run_id_agent_eval_runs_id_fk",
+ "tableFrom": "agent_eval_run_topics",
+ "tableTo": "agent_eval_runs",
+ "columnsFrom": ["run_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_run_topics_topic_id_topics_id_fk": {
+ "name": "agent_eval_run_topics_topic_id_topics_id_fk",
+ "tableFrom": "agent_eval_run_topics",
+ "tableTo": "topics",
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_run_topics_test_case_id_agent_eval_test_cases_id_fk": {
+ "name": "agent_eval_run_topics_test_case_id_agent_eval_test_cases_id_fk",
+ "tableFrom": "agent_eval_run_topics",
+ "tableTo": "agent_eval_test_cases",
+ "columnsFrom": ["test_case_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "agent_eval_run_topics_run_id_topic_id_pk": {
+ "name": "agent_eval_run_topics_run_id_topic_id_pk",
+ "columns": ["run_id", "topic_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_eval_runs": {
+ "name": "agent_eval_runs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "dataset_id": {
+ "name": "dataset_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "experiment_id": {
+ "name": "experiment_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_run_id": {
+ "name": "parent_run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "target_agent_id": {
+ "name": "target_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'idle'"
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metrics": {
+ "name": "metrics",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_eval_runs_dataset_id_idx": {
+ "name": "agent_eval_runs_dataset_id_idx",
+ "columns": [
+ {
+ "expression": "dataset_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_runs_experiment_id_idx": {
+ "name": "agent_eval_runs_experiment_id_idx",
+ "columns": [
+ {
+ "expression": "experiment_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_runs_parent_run_id_idx": {
+ "name": "agent_eval_runs_parent_run_id_idx",
+ "columns": [
+ {
+ "expression": "parent_run_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_runs_user_id_idx": {
+ "name": "agent_eval_runs_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_runs_status_idx": {
+ "name": "agent_eval_runs_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_runs_target_agent_id_idx": {
+ "name": "agent_eval_runs_target_agent_id_idx",
+ "columns": [
+ {
+ "expression": "target_agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_runs_workspace_id_idx": {
+ "name": "agent_eval_runs_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_eval_runs_dataset_id_agent_eval_datasets_id_fk": {
+ "name": "agent_eval_runs_dataset_id_agent_eval_datasets_id_fk",
+ "tableFrom": "agent_eval_runs",
+ "tableTo": "agent_eval_datasets",
+ "columnsFrom": ["dataset_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_runs_experiment_id_agent_eval_experiments_id_fk": {
+ "name": "agent_eval_runs_experiment_id_agent_eval_experiments_id_fk",
+ "tableFrom": "agent_eval_runs",
+ "tableTo": "agent_eval_experiments",
+ "columnsFrom": ["experiment_id"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "agent_eval_runs_target_agent_id_agents_id_fk": {
+ "name": "agent_eval_runs_target_agent_id_agents_id_fk",
+ "tableFrom": "agent_eval_runs",
+ "tableTo": "agents",
+ "columnsFrom": ["target_agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_runs_user_id_users_id_fk": {
+ "name": "agent_eval_runs_user_id_users_id_fk",
+ "tableFrom": "agent_eval_runs",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_runs_workspace_id_workspaces_id_fk": {
+ "name": "agent_eval_runs_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_eval_runs",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_runs_parent_run_id_agent_eval_runs_id_fk": {
+ "name": "agent_eval_runs_parent_run_id_agent_eval_runs_id_fk",
+ "tableFrom": "agent_eval_runs",
+ "tableTo": "agent_eval_runs",
+ "columnsFrom": ["parent_run_id"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_eval_test_cases": {
+ "name": "agent_eval_test_cases",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dataset_id": {
+ "name": "dataset_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "eval_mode": {
+ "name": "eval_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "eval_config": {
+ "name": "eval_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_eval_test_cases_user_id_idx": {
+ "name": "agent_eval_test_cases_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_test_cases_dataset_id_idx": {
+ "name": "agent_eval_test_cases_dataset_id_idx",
+ "columns": [
+ {
+ "expression": "dataset_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_test_cases_sort_order_idx": {
+ "name": "agent_eval_test_cases_sort_order_idx",
+ "columns": [
+ {
+ "expression": "sort_order",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_eval_test_cases_workspace_id_idx": {
+ "name": "agent_eval_test_cases_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_eval_test_cases_user_id_users_id_fk": {
+ "name": "agent_eval_test_cases_user_id_users_id_fk",
+ "tableFrom": "agent_eval_test_cases",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_test_cases_workspace_id_workspaces_id_fk": {
+ "name": "agent_eval_test_cases_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_eval_test_cases",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_eval_test_cases_dataset_id_agent_eval_datasets_id_fk": {
+ "name": "agent_eval_test_cases_dataset_id_agent_eval_datasets_id_fk",
+ "tableFrom": "agent_eval_test_cases",
+ "tableTo": "agent_eval_datasets",
+ "columnsFrom": ["dataset_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_history_job_agents": {
+ "name": "agent_history_job_agents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "job_id": {
+ "name": "job_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "agent_history_job_agents_job_id_agent_id_unique": {
+ "name": "agent_history_job_agents_job_id_agent_id_unique",
+ "columns": [
+ {
+ "expression": "job_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_history_job_agents_agent_id_idx": {
+ "name": "agent_history_job_agents_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_history_job_agents_job_id_agent_history_jobs_id_fk": {
+ "name": "agent_history_job_agents_job_id_agent_history_jobs_id_fk",
+ "tableFrom": "agent_history_job_agents",
+ "tableTo": "agent_history_jobs",
+ "columnsFrom": ["job_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_history_job_agents_agent_id_agents_id_fk": {
+ "name": "agent_history_job_agents_agent_id_agents_id_fk",
+ "tableFrom": "agent_history_job_agents",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_history_job_groups": {
+ "name": "agent_history_job_groups",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "job_id": {
+ "name": "job_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "agent_history_job_groups_job_id_group_id_unique": {
+ "name": "agent_history_job_groups_job_id_group_id_unique",
+ "columns": [
+ {
+ "expression": "job_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "group_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_history_job_groups_group_id_idx": {
+ "name": "agent_history_job_groups_group_id_idx",
+ "columns": [
+ {
+ "expression": "group_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_history_job_groups_job_id_agent_history_jobs_id_fk": {
+ "name": "agent_history_job_groups_job_id_agent_history_jobs_id_fk",
+ "tableFrom": "agent_history_job_groups",
+ "tableTo": "agent_history_jobs",
+ "columnsFrom": ["job_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_history_job_groups_group_id_chat_groups_id_fk": {
+ "name": "agent_history_job_groups_group_id_chat_groups_id_fk",
+ "tableFrom": "agent_history_job_groups",
+ "tableTo": "chat_groups",
+ "columnsFrom": ["group_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_history_job_topics": {
+ "name": "agent_history_job_topics",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "job_id": {
+ "name": "job_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "priority": {
+ "name": "priority",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "activity_at": {
+ "name": "activity_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "agent_history_job_topics_job_id_topic_id_unique": {
+ "name": "agent_history_job_topics_job_id_topic_id_unique",
+ "columns": [
+ {
+ "expression": "job_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_history_job_topics_topic_id_idx": {
+ "name": "agent_history_job_topics_topic_id_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_history_job_topics_pick_idx": {
+ "name": "agent_history_job_topics_pick_idx",
+ "columns": [
+ {
+ "expression": "job_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "priority",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "activity_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_history_job_topics_job_id_agent_history_jobs_id_fk": {
+ "name": "agent_history_job_topics_job_id_agent_history_jobs_id_fk",
+ "tableFrom": "agent_history_job_topics",
+ "tableTo": "agent_history_jobs",
+ "columnsFrom": ["job_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_history_job_topics_topic_id_topics_id_fk": {
+ "name": "agent_history_job_topics_topic_id_topics_id_fk",
+ "tableFrom": "agent_history_job_topics",
+ "tableTo": "topics",
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_history_jobs": {
+ "name": "agent_history_jobs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'transfer'"
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_ids": {
+ "name": "agent_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "session_ids": {
+ "name": "session_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "group_ids": {
+ "name": "group_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "source_user_id": {
+ "name": "source_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_workspace_id": {
+ "name": "source_workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "target_user_id": {
+ "name": "target_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_workspace_id": {
+ "name": "target_workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "total_topics": {
+ "name": "total_topics",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "completed_topics": {
+ "name": "completed_topics",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_history_jobs_status_idx": {
+ "name": "agent_history_jobs_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_history_jobs_source_user_id_idx": {
+ "name": "agent_history_jobs_source_user_id_idx",
+ "columns": [
+ {
+ "expression": "source_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_history_jobs_target_user_id_idx": {
+ "name": "agent_history_jobs_target_user_id_idx",
+ "columns": [
+ {
+ "expression": "target_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_history_jobs_source_workspace_id_idx": {
+ "name": "agent_history_jobs_source_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "source_workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_history_jobs_target_workspace_id_idx": {
+ "name": "agent_history_jobs_target_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "target_workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_intervention_resolutions": {
+ "name": "agent_intervention_resolutions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "resolution_request_id": {
+ "name": "resolution_request_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "operation_id": {
+ "name": "operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "batch_id": {
+ "name": "batch_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "actor_id": {
+ "name": "actor_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "selected_intervention_ids": {
+ "name": "selected_intervention_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expected_versions": {
+ "name": "expected_versions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expected_request_revision_hashes": {
+ "name": "expected_request_revision_hashes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expected_item_count": {
+ "name": "expected_item_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "action": {
+ "name": "action",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "custom_execution_input_hash": {
+ "name": "custom_execution_input_hash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "custom_execution_state": {
+ "name": "custom_execution_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "custom_execution_attempt": {
+ "name": "custom_execution_attempt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "custom_execution_lease_token": {
+ "name": "custom_execution_lease_token",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "custom_execution_lease_expires_at": {
+ "name": "custom_execution_lease_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "custom_execution_result": {
+ "name": "custom_execution_result",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "remember_tool_key": {
+ "name": "remember_tool_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "remember_effect_status": {
+ "name": "remember_effect_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "original_arguments": {
+ "name": "original_arguments",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "edited_arguments": {
+ "name": "edited_arguments",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "original_request_revision_hash": {
+ "name": "original_request_revision_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "edited_request_revision_hash": {
+ "name": "edited_request_revision_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "argument_effect_status": {
+ "name": "argument_effect_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'resolving'"
+ },
+ "resolving_at": {
+ "name": "resolving_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "published_at": {
+ "name": "published_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "continuation_started_at": {
+ "name": "continuation_started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "producer_ack_at": {
+ "name": "producer_ack_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "terminal_at": {
+ "name": "terminal_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rolled_back_at": {
+ "name": "rolled_back_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_intervention_resolutions_request_unique": {
+ "name": "agent_intervention_resolutions_request_unique",
+ "columns": [
+ {
+ "expression": "resolution_request_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_intervention_resolutions_owner_batch_idx": {
+ "name": "agent_intervention_resolutions_owner_batch_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "batch_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_intervention_resolutions_status_created_idx": {
+ "name": "agent_intervention_resolutions_status_created_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_intervention_resolutions_operation_id_agent_operations_id_fk": {
+ "name": "agent_intervention_resolutions_operation_id_agent_operations_id_fk",
+ "tableFrom": "agent_intervention_resolutions",
+ "tableTo": "agent_operations",
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_intervention_resolutions_user_id_users_id_fk": {
+ "name": "agent_intervention_resolutions_user_id_users_id_fk",
+ "tableFrom": "agent_intervention_resolutions",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_intervention_resolutions_workspace_id_workspaces_id_fk": {
+ "name": "agent_intervention_resolutions_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_intervention_resolutions",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "agent_intervention_resolutions_expected_item_count_check": {
+ "name": "agent_intervention_resolutions_expected_item_count_check",
+ "value": "\"agent_intervention_resolutions\".\"expected_item_count\" > 0"
+ },
+ "agent_intervention_resolutions_custom_execution_input_hash_check": {
+ "name": "agent_intervention_resolutions_custom_execution_input_hash_check",
+ "value": "\"agent_intervention_resolutions\".\"custom_execution_input_hash\" IS NULL OR \"agent_intervention_resolutions\".\"custom_execution_input_hash\" ~ '^[a-f0-9]{64}$'"
+ },
+ "agent_intervention_resolutions_custom_execution_state_check": {
+ "name": "agent_intervention_resolutions_custom_execution_state_check",
+ "value": "(\n (\"agent_intervention_resolutions\".\"custom_execution_state\" IS NULL\n AND \"agent_intervention_resolutions\".\"custom_execution_input_hash\" IS NULL\n AND \"agent_intervention_resolutions\".\"custom_execution_attempt\" IS NULL\n AND \"agent_intervention_resolutions\".\"custom_execution_lease_token\" IS NULL\n AND \"agent_intervention_resolutions\".\"custom_execution_lease_expires_at\" IS NULL\n AND \"agent_intervention_resolutions\".\"custom_execution_result\" IS NULL)\n OR\n (\"agent_intervention_resolutions\".\"custom_execution_state\" = 'pending'\n AND \"agent_intervention_resolutions\".\"custom_execution_attempt\" = 0\n AND \"agent_intervention_resolutions\".\"custom_execution_lease_token\" IS NULL\n AND \"agent_intervention_resolutions\".\"custom_execution_lease_expires_at\" IS NULL\n AND \"agent_intervention_resolutions\".\"custom_execution_result\" IS NULL)\n OR\n (\"agent_intervention_resolutions\".\"custom_execution_state\" = 'executing'\n AND \"agent_intervention_resolutions\".\"custom_execution_input_hash\" IS NOT NULL\n AND \"agent_intervention_resolutions\".\"custom_execution_attempt\" > 0\n AND \"agent_intervention_resolutions\".\"custom_execution_lease_token\" IS NOT NULL\n AND \"agent_intervention_resolutions\".\"custom_execution_lease_expires_at\" IS NOT NULL\n AND \"agent_intervention_resolutions\".\"custom_execution_result\" IS NULL)\n OR\n (\"agent_intervention_resolutions\".\"custom_execution_state\" = 'completed'\n AND \"agent_intervention_resolutions\".\"custom_execution_input_hash\" IS NOT NULL\n AND \"agent_intervention_resolutions\".\"custom_execution_attempt\" > 0\n AND \"agent_intervention_resolutions\".\"custom_execution_lease_token\" IS NOT NULL\n AND \"agent_intervention_resolutions\".\"custom_execution_lease_expires_at\" IS NOT NULL\n AND \"agent_intervention_resolutions\".\"custom_execution_result\" IS NOT NULL)\n )"
+ },
+ "agent_intervention_resolutions_custom_execution_parent_status_check": {
+ "name": "agent_intervention_resolutions_custom_execution_parent_status_check",
+ "value": "\"agent_intervention_resolutions\".\"custom_execution_state\" NOT IN ('executing', 'completed') OR \"agent_intervention_resolutions\".\"status\" IN ('resolving', 'published', 'acknowledged', 'completed')"
+ },
+ "agent_intervention_resolutions_version_check": {
+ "name": "agent_intervention_resolutions_version_check",
+ "value": "\"agent_intervention_resolutions\".\"version\" > 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.agent_interventions": {
+ "name": "agent_interventions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "operation_id": {
+ "name": "operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tool_call_id": {
+ "name": "tool_call_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tool_message_id": {
+ "name": "tool_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "interaction_kind": {
+ "name": "interaction_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "surface": {
+ "name": "surface",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "system_action_eligibility": {
+ "name": "system_action_eligibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "approval_mode": {
+ "name": "approval_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "batch_id": {
+ "name": "batch_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "activity_key": {
+ "name": "activity_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "step_index": {
+ "name": "step_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "item_index": {
+ "name": "item_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "item_count": {
+ "name": "item_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sealed": {
+ "name": "sealed",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "canonical_tool_key": {
+ "name": "canonical_tool_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "request_revision_hash": {
+ "name": "request_revision_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "allowed_actions": {
+ "name": "allowed_actions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "risk": {
+ "name": "risk",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "review_token_hash": {
+ "name": "review_token_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "review_context": {
+ "name": "review_context",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sanitized_request": {
+ "name": "sanitized_request",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "deadline": {
+ "name": "deadline",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "resolution_id": {
+ "name": "resolution_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolving_at": {
+ "name": "resolving_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "published_at": {
+ "name": "published_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "producer_ack_at": {
+ "name": "producer_ack_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_interventions_operation_tool_call_unique": {
+ "name": "agent_interventions_operation_tool_call_unique",
+ "columns": [
+ {
+ "expression": "operation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "tool_call_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_interventions_review_token_hash_unique": {
+ "name": "agent_interventions_review_token_hash_unique",
+ "columns": [
+ {
+ "expression": "review_token_hash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_interventions_operation_batch_item_unique": {
+ "name": "agent_interventions_operation_batch_item_unique",
+ "columns": [
+ {
+ "expression": "operation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "batch_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "item_index",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_interventions_owner_activity_item_unique": {
+ "name": "agent_interventions_owner_activity_item_unique",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "activity_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "item_index",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_interventions_owner_status_deadline_idx": {
+ "name": "agent_interventions_owner_status_deadline_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "deadline",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_interventions_owner_batch_idx": {
+ "name": "agent_interventions_owner_batch_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "batch_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "item_index",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_interventions_activity_key_idx": {
+ "name": "agent_interventions_activity_key_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "activity_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_interventions_status_deadline_idx": {
+ "name": "agent_interventions_status_deadline_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "deadline",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_interventions_operation_id_agent_operations_id_fk": {
+ "name": "agent_interventions_operation_id_agent_operations_id_fk",
+ "tableFrom": "agent_interventions",
+ "tableTo": "agent_operations",
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_interventions_user_id_users_id_fk": {
+ "name": "agent_interventions_user_id_users_id_fk",
+ "tableFrom": "agent_interventions",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_interventions_workspace_id_workspaces_id_fk": {
+ "name": "agent_interventions_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_interventions",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_interventions_resolution_id_agent_intervention_resolutions_id_fk": {
+ "name": "agent_interventions_resolution_id_agent_intervention_resolutions_id_fk",
+ "tableFrom": "agent_interventions",
+ "tableTo": "agent_intervention_resolutions",
+ "columnsFrom": ["resolution_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "agent_interventions_review_token_hash_check": {
+ "name": "agent_interventions_review_token_hash_check",
+ "value": "\"agent_interventions\".\"review_token_hash\" ~ '^[a-f0-9]{64}$'"
+ },
+ "agent_interventions_request_revision_hash_check": {
+ "name": "agent_interventions_request_revision_hash_check",
+ "value": "\"agent_interventions\".\"request_revision_hash\" ~ '^[a-f0-9]{64}$'"
+ },
+ "agent_interventions_step_index_check": {
+ "name": "agent_interventions_step_index_check",
+ "value": "\"agent_interventions\".\"step_index\" >= 0"
+ },
+ "agent_interventions_item_bounds_check": {
+ "name": "agent_interventions_item_bounds_check",
+ "value": "\"agent_interventions\".\"item_count\" > 0 AND \"agent_interventions\".\"item_index\" >= 0 AND \"agent_interventions\".\"item_index\" < \"agent_interventions\".\"item_count\""
+ },
+ "agent_interventions_version_check": {
+ "name": "agent_interventions_version_check",
+ "value": "\"agent_interventions\".\"version\" > 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.agent_label_assignments": {
+ "name": "agent_label_assignments",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "label_id": {
+ "name": "label_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_label_assignments_label_id_agent_id_unique": {
+ "name": "agent_label_assignments_label_id_agent_id_unique",
+ "columns": [
+ {
+ "expression": "label_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_label_assignments_agent_id_idx": {
+ "name": "agent_label_assignments_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_label_assignments_workspace_id_idx": {
+ "name": "agent_label_assignments_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_label_assignments_label_id_agent_labels_id_fk": {
+ "name": "agent_label_assignments_label_id_agent_labels_id_fk",
+ "tableFrom": "agent_label_assignments",
+ "tableTo": "agent_labels",
+ "columnsFrom": ["label_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_label_assignments_agent_id_agents_id_fk": {
+ "name": "agent_label_assignments_agent_id_agents_id_fk",
+ "tableFrom": "agent_label_assignments",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_label_assignments_user_id_users_id_fk": {
+ "name": "agent_label_assignments_user_id_users_id_fk",
+ "tableFrom": "agent_label_assignments",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_label_assignments_workspace_id_workspaces_id_fk": {
+ "name": "agent_label_assignments_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_label_assignments",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_labels": {
+ "name": "agent_labels",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "archived": {
+ "name": "archived",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_labels_user_id_idx": {
+ "name": "agent_labels_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_labels_workspace_id_idx": {
+ "name": "agent_labels_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_labels_user_id_name_unique": {
+ "name": "agent_labels_user_id_name_unique",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agent_labels\".\"workspace_id\" IS NULL AND \"agent_labels\".\"archived\" = false",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_labels_workspace_id_name_unique": {
+ "name": "agent_labels_workspace_id_name_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agent_labels\".\"workspace_id\" IS NOT NULL AND \"agent_labels\".\"archived\" = false",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_labels_user_id_users_id_fk": {
+ "name": "agent_labels_user_id_users_id_fk",
+ "tableFrom": "agent_labels",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_labels_workspace_id_workspaces_id_fk": {
+ "name": "agent_labels_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_labels",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_operations": {
+ "name": "agent_operations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "chat_group_id": {
+ "name": "chat_group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_operation_id": {
+ "name": "parent_operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "completion_reason": {
+ "name": "completion_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "verify_status": {
+ "name": "verify_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "verify_plan": {
+ "name": "verify_plan",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "verify_plan_confirmed_at": {
+ "name": "verify_plan_confirmed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "step_count": {
+ "name": "step_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "max_steps": {
+ "name": "max_steps",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "force_finish": {
+ "name": "force_finish",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "interruption": {
+ "name": "interruption",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "total_cost": {
+ "name": "total_cost",
+ "type": "numeric(20, 6)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "currency": {
+ "name": "currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'USD'"
+ },
+ "total_input_tokens": {
+ "name": "total_input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "total_output_tokens": {
+ "name": "total_output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "total_tokens": {
+ "name": "total_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "llm_calls": {
+ "name": "llm_calls",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_calls": {
+ "name": "tool_calls",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "human_interventions": {
+ "name": "human_interventions",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "processing_time_ms": {
+ "name": "processing_time_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "human_waiting_time_ms": {
+ "name": "human_waiting_time_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cost": {
+ "name": "cost",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "usage": {
+ "name": "usage",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cost_limit": {
+ "name": "cost_limit",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model_runtime_config": {
+ "name": "model_runtime_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "app_context": {
+ "name": "app_context",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trace_s3_key": {
+ "name": "trace_s3_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_operations_user_id_idx": {
+ "name": "agent_operations_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_operations_workspace_id_idx": {
+ "name": "agent_operations_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_operations_agent_id_idx": {
+ "name": "agent_operations_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_operations_topic_id_idx": {
+ "name": "agent_operations_topic_id_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_operations_thread_id_idx": {
+ "name": "agent_operations_thread_id_idx",
+ "columns": [
+ {
+ "expression": "thread_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_operations_task_id_idx": {
+ "name": "agent_operations_task_id_idx",
+ "columns": [
+ {
+ "expression": "task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_operations_chat_group_id_idx": {
+ "name": "agent_operations_chat_group_id_idx",
+ "columns": [
+ {
+ "expression": "chat_group_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_operations_parent_operation_id_idx": {
+ "name": "agent_operations_parent_operation_id_idx",
+ "columns": [
+ {
+ "expression": "parent_operation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_operations_status_idx": {
+ "name": "agent_operations_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_operations_user_id_created_at_idx": {
+ "name": "agent_operations_user_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_operations_metadata_idx": {
+ "name": "agent_operations_metadata_idx",
+ "columns": [
+ {
+ "expression": "metadata",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_operations_workspace_id_workspaces_id_fk": {
+ "name": "agent_operations_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_operations",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_operations_agent_id_agents_id_fk": {
+ "name": "agent_operations_agent_id_agents_id_fk",
+ "tableFrom": "agent_operations",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "agent_operations_topic_id_topics_id_fk": {
+ "name": "agent_operations_topic_id_topics_id_fk",
+ "tableFrom": "agent_operations",
+ "tableTo": "topics",
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "agent_operations_thread_id_threads_id_fk": {
+ "name": "agent_operations_thread_id_threads_id_fk",
+ "tableFrom": "agent_operations",
+ "tableTo": "threads",
+ "columnsFrom": ["thread_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "agent_operations_task_id_tasks_id_fk": {
+ "name": "agent_operations_task_id_tasks_id_fk",
+ "tableFrom": "agent_operations",
+ "tableTo": "tasks",
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "agent_operations_chat_group_id_chat_groups_id_fk": {
+ "name": "agent_operations_chat_group_id_chat_groups_id_fk",
+ "tableFrom": "agent_operations",
+ "tableTo": "chat_groups",
+ "columnsFrom": ["chat_group_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_account_bindings": {
+ "name": "agent_account_bindings",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pool'"
+ },
+ "priority": {
+ "name": "priority",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "weight": {
+ "name": "weight",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_account_bindings_agent_account_unique": {
+ "name": "agent_account_bindings_agent_account_unique",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "account_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_account_bindings_agent_pinned_unique": {
+ "name": "agent_account_bindings_agent_pinned_unique",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agent_account_bindings\".\"role\" = 'pinned'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_account_bindings_agent_id_idx": {
+ "name": "agent_account_bindings_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_account_bindings_account_id_idx": {
+ "name": "agent_account_bindings_account_id_idx",
+ "columns": [
+ {
+ "expression": "account_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_account_bindings_user_id_idx": {
+ "name": "agent_account_bindings_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_account_bindings_workspace_id_idx": {
+ "name": "agent_account_bindings_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_account_bindings_agent_id_agents_id_fk": {
+ "name": "agent_account_bindings_agent_id_agents_id_fk",
+ "tableFrom": "agent_account_bindings",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_account_bindings_account_id_agent_provider_accounts_id_fk": {
+ "name": "agent_account_bindings_account_id_agent_provider_accounts_id_fk",
+ "tableFrom": "agent_account_bindings",
+ "tableTo": "agent_provider_accounts",
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_account_bindings_user_id_users_id_fk": {
+ "name": "agent_account_bindings_user_id_users_id_fk",
+ "tableFrom": "agent_account_bindings",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_account_bindings_workspace_id_workspaces_id_fk": {
+ "name": "agent_account_bindings_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_account_bindings",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_provider_accounts": {
+ "name": "agent_provider_accounts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "external_account_id": {
+ "name": "external_account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "display_name": {
+ "name": "display_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "plan_tier": {
+ "name": "plan_tier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rate_limit_tier": {
+ "name": "rate_limit_tier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "label": {
+ "name": "label",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "credential_mode": {
+ "name": "credential_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'referenced'"
+ },
+ "credentials": {
+ "name": "credentials",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "credential_ref": {
+ "name": "credential_ref",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "token_expires_at": {
+ "name": "token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "last_validated_at": {
+ "name": "last_validated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_provider_accounts_user_id_idx": {
+ "name": "agent_provider_accounts_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_provider_accounts_workspace_id_idx": {
+ "name": "agent_provider_accounts_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_provider_accounts_token_expires_at_idx": {
+ "name": "agent_provider_accounts_token_expires_at_idx",
+ "columns": [
+ {
+ "expression": "token_expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_provider_accounts_identity_unique": {
+ "name": "agent_provider_accounts_identity_unique",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "external_account_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agent_provider_accounts\".\"external_account_id\" IS NOT NULL and \"agent_provider_accounts\".\"workspace_id\" is null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_provider_accounts_identity_workspace_unique": {
+ "name": "agent_provider_accounts_identity_workspace_unique",
+ "columns": [
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "external_account_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agent_provider_accounts\".\"external_account_id\" IS NOT NULL and \"agent_provider_accounts\".\"workspace_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_provider_accounts_user_id_users_id_fk": {
+ "name": "agent_provider_accounts_user_id_users_id_fk",
+ "tableFrom": "agent_provider_accounts",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_provider_accounts_workspace_id_workspaces_id_fk": {
+ "name": "agent_provider_accounts_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_provider_accounts",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_quota_calibrations": {
+ "name": "agent_quota_calibrations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "limit_type": {
+ "name": "limit_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope_key": {
+ "name": "scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "capacity_usd": {
+ "name": "capacity_usd",
+ "type": "numeric(20, 6)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "capacity_tokens_equivalent": {
+ "name": "capacity_tokens_equivalent",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model_mix": {
+ "name": "model_mix",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sample_count": {
+ "name": "sample_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "confidence": {
+ "name": "confidence",
+ "type": "numeric(20, 6)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "window_seconds": {
+ "name": "window_seconds",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "calibrated_at": {
+ "name": "calibrated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_quota_calibrations_account_type_scope_idx": {
+ "name": "agent_quota_calibrations_account_type_scope_idx",
+ "columns": [
+ {
+ "expression": "account_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "limit_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "scope_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "calibrated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_quota_calibrations_workspace_id_idx": {
+ "name": "agent_quota_calibrations_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_quota_calibrations_account_id_agent_provider_accounts_id_fk": {
+ "name": "agent_quota_calibrations_account_id_agent_provider_accounts_id_fk",
+ "tableFrom": "agent_quota_calibrations",
+ "tableTo": "agent_provider_accounts",
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_quota_calibrations_user_id_users_id_fk": {
+ "name": "agent_quota_calibrations_user_id_users_id_fk",
+ "tableFrom": "agent_quota_calibrations",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_quota_calibrations_workspace_id_workspaces_id_fk": {
+ "name": "agent_quota_calibrations_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_quota_calibrations",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_quota_snapshots": {
+ "name": "agent_quota_snapshots",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "device_id": {
+ "name": "device_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "limit_type": {
+ "name": "limit_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope_key": {
+ "name": "scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "resets_at": {
+ "name": "resets_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "utilization": {
+ "name": "utilization",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "severity": {
+ "name": "severity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "captured_at": {
+ "name": "captured_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "raw": {
+ "name": "raw",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_quota_snapshots_account_type_scope_idx": {
+ "name": "agent_quota_snapshots_account_type_scope_idx",
+ "columns": [
+ {
+ "expression": "account_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "limit_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "scope_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "captured_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_quota_snapshots_account_captured_idx": {
+ "name": "agent_quota_snapshots_account_captured_idx",
+ "columns": [
+ {
+ "expression": "account_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "captured_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_quota_snapshots_resets_at_idx": {
+ "name": "agent_quota_snapshots_resets_at_idx",
+ "columns": [
+ {
+ "expression": "resets_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_quota_snapshots_workspace_id_idx": {
+ "name": "agent_quota_snapshots_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_quota_snapshots_account_id_agent_provider_accounts_id_fk": {
+ "name": "agent_quota_snapshots_account_id_agent_provider_accounts_id_fk",
+ "tableFrom": "agent_quota_snapshots",
+ "tableTo": "agent_provider_accounts",
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_quota_snapshots_user_id_users_id_fk": {
+ "name": "agent_quota_snapshots_user_id_users_id_fk",
+ "tableFrom": "agent_quota_snapshots",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_quota_snapshots_workspace_id_workspaces_id_fk": {
+ "name": "agent_quota_snapshots_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_quota_snapshots",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_quota_snapshots_device_id_devices_id_fk": {
+ "name": "agent_quota_snapshots_device_id_devices_id_fk",
+ "tableFrom": "agent_quota_snapshots",
+ "tableTo": "devices",
+ "columnsFrom": ["device_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_quota_usage_ledger": {
+ "name": "agent_quota_usage_ledger",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "occurred_at": {
+ "name": "occurred_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cache_read_tokens": {
+ "name": "cache_read_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cache_write_tokens": {
+ "name": "cache_write_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reasoning_tokens": {
+ "name": "reasoning_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "numeric(20, 6)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cost_source": {
+ "name": "cost_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "operation_id": {
+ "name": "operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "external_event_id": {
+ "name": "external_event_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_quota_usage_ledger_account_occurred_idx": {
+ "name": "agent_quota_usage_ledger_account_occurred_idx",
+ "columns": [
+ {
+ "expression": "account_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "occurred_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_quota_usage_ledger_account_model_occurred_idx": {
+ "name": "agent_quota_usage_ledger_account_model_occurred_idx",
+ "columns": [
+ {
+ "expression": "account_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "model",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "occurred_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_quota_usage_ledger_message_id_idx": {
+ "name": "agent_quota_usage_ledger_message_id_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_quota_usage_ledger_operation_id_idx": {
+ "name": "agent_quota_usage_ledger_operation_id_idx",
+ "columns": [
+ {
+ "expression": "operation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_quota_usage_ledger_workspace_id_idx": {
+ "name": "agent_quota_usage_ledger_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_quota_usage_ledger_external_event_unique": {
+ "name": "agent_quota_usage_ledger_external_event_unique",
+ "columns": [
+ {
+ "expression": "external_event_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agent_quota_usage_ledger\".\"external_event_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_quota_usage_ledger_account_id_agent_provider_accounts_id_fk": {
+ "name": "agent_quota_usage_ledger_account_id_agent_provider_accounts_id_fk",
+ "tableFrom": "agent_quota_usage_ledger",
+ "tableTo": "agent_provider_accounts",
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "agent_quota_usage_ledger_user_id_users_id_fk": {
+ "name": "agent_quota_usage_ledger_user_id_users_id_fk",
+ "tableFrom": "agent_quota_usage_ledger",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_quota_usage_ledger_workspace_id_workspaces_id_fk": {
+ "name": "agent_quota_usage_ledger_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_quota_usage_ledger",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_quota_usage_ledger_message_id_messages_id_fk": {
+ "name": "agent_quota_usage_ledger_message_id_messages_id_fk",
+ "tableFrom": "agent_quota_usage_ledger",
+ "tableTo": "messages",
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "agent_quota_usage_ledger_operation_id_agent_operations_id_fk": {
+ "name": "agent_quota_usage_ledger_operation_id_agent_operations_id_fk",
+ "tableFrom": "agent_quota_usage_ledger",
+ "tableTo": "agent_operations",
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "agent_quota_usage_ledger_topic_id_topics_id_fk": {
+ "name": "agent_quota_usage_ledger_topic_id_topics_id_fk",
+ "tableFrom": "agent_quota_usage_ledger",
+ "tableTo": "topics",
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "agent_quota_usage_ledger_agent_id_agents_id_fk": {
+ "name": "agent_quota_usage_ledger_agent_id_agents_id_fk",
+ "tableFrom": "agent_quota_usage_ledger",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_quota_windows": {
+ "name": "agent_quota_windows",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "limit_type": {
+ "name": "limit_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope_key": {
+ "name": "scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "resets_at": {
+ "name": "resets_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "window_start_at": {
+ "name": "window_start_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "window_seconds": {
+ "name": "window_seconds",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "peak_utilization": {
+ "name": "peak_utilization",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "last_utilization": {
+ "name": "last_utilization",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rate_limited_at": {
+ "name": "rate_limited_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "observed_cost_usd": {
+ "name": "observed_cost_usd",
+ "type": "numeric(20, 6)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "observed_tokens": {
+ "name": "observed_tokens",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "estimated_capacity_usd": {
+ "name": "estimated_capacity_usd",
+ "type": "numeric(20, 6)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contaminated": {
+ "name": "contaminated",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "first_seen_at": {
+ "name": "first_seen_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_quota_windows_natural_key_unique": {
+ "name": "agent_quota_windows_natural_key_unique",
+ "columns": [
+ {
+ "expression": "account_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "limit_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "scope_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resets_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_quota_windows_account_resets_idx": {
+ "name": "agent_quota_windows_account_resets_idx",
+ "columns": [
+ {
+ "expression": "account_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resets_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_quota_windows_user_id_idx": {
+ "name": "agent_quota_windows_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_quota_windows_workspace_id_idx": {
+ "name": "agent_quota_windows_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_quota_windows_account_id_agent_provider_accounts_id_fk": {
+ "name": "agent_quota_windows_account_id_agent_provider_accounts_id_fk",
+ "tableFrom": "agent_quota_windows",
+ "tableTo": "agent_provider_accounts",
+ "columnsFrom": ["account_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_quota_windows_user_id_users_id_fk": {
+ "name": "agent_quota_windows_user_id_users_id_fk",
+ "tableFrom": "agent_quota_windows",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_quota_windows_workspace_id_workspaces_id_fk": {
+ "name": "agent_quota_windows_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_quota_windows",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_shares": {
+ "name": "agent_shares",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'private'"
+ },
+ "share_config": {
+ "name": "share_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_view_count": {
+ "name": "user_view_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_shares_agent_id_unique": {
+ "name": "agent_shares_agent_id_unique",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_shares_visibility_idx": {
+ "name": "agent_shares_visibility_idx",
+ "columns": [
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_shares_agent_id_agents_id_fk": {
+ "name": "agent_shares_agent_id_agents_id_fk",
+ "tableFrom": "agent_shares",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_skills": {
+ "name": "agent_skills",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "manifest": {
+ "name": "manifest",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "editor_data": {
+ "name": "editor_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resources": {
+ "name": "resources",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "zip_file_hash": {
+ "name": "zip_file_hash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_skills_user_name_idx": {
+ "name": "agent_skills_user_name_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agent_skills\".\"workspace_id\" is null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_skills_identifier_idx": {
+ "name": "agent_skills_identifier_idx",
+ "columns": [
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_skills_user_id_idx": {
+ "name": "agent_skills_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_skills_source_idx": {
+ "name": "agent_skills_source_idx",
+ "columns": [
+ {
+ "expression": "source",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_skills_zip_hash_idx": {
+ "name": "agent_skills_zip_hash_idx",
+ "columns": [
+ {
+ "expression": "zip_file_hash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_skills_workspace_id_idx": {
+ "name": "agent_skills_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_skills_name_workspace_id_unique": {
+ "name": "agent_skills_name_workspace_id_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agent_skills\".\"workspace_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_skills_zip_file_hash_global_files_hash_id_fk": {
+ "name": "agent_skills_zip_file_hash_global_files_hash_id_fk",
+ "tableFrom": "agent_skills",
+ "tableTo": "global_files",
+ "columnsFrom": ["zip_file_hash"],
+ "columnsTo": ["hash_id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "agent_skills_user_id_users_id_fk": {
+ "name": "agent_skills_user_id_users_id_fk",
+ "tableFrom": "agent_skills",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_skills_workspace_id_workspaces_id_fk": {
+ "name": "agent_skills_workspace_id_workspaces_id_fk",
+ "tableFrom": "agent_skills",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_models": {
+ "name": "ai_models",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(150)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "_id": {
+ "name": "_id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "display_name": {
+ "name": "display_name",
+ "type": "varchar(200)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organization": {
+ "name": "organization",
+ "type": "varchar(100)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(20)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'chat'"
+ },
+ "sort": {
+ "name": "sort",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pricing": {
+ "name": "pricing",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parameters": {
+ "name": "parameters",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "abilities": {
+ "name": "abilities",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "context_window_tokens": {
+ "name": "context_window_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "varchar(20)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "released_at": {
+ "name": "released_at",
+ "type": "varchar(10)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "settings": {
+ "name": "settings",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "ai_models_id_provider_id_user_id_unique": {
+ "name": "ai_models_id_provider_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "provider_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"ai_models\".\"workspace_id\" is null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "ai_models_id_provider_id_user_id_workspace_id_unique": {
+ "name": "ai_models_id_provider_id_user_id_workspace_id_unique",
+ "columns": [
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "provider_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"ai_models\".\"workspace_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "ai_models_user_id_idx": {
+ "name": "ai_models_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "ai_models_workspace_id_idx": {
+ "name": "ai_models_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "ai_models_user_id_users_id_fk": {
+ "name": "ai_models_user_id_users_id_fk",
+ "tableFrom": "ai_models",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ai_models_workspace_id_workspaces_id_fk": {
+ "name": "ai_models_workspace_id_workspaces_id_fk",
+ "tableFrom": "ai_models",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_providers": {
+ "name": "ai_providers",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "_id": {
+ "name": "_id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sort": {
+ "name": "sort",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "fetch_on_client": {
+ "name": "fetch_on_client",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "check_model": {
+ "name": "check_model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "logo": {
+ "name": "logo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "key_vaults": {
+ "name": "key_vaults",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "varchar(20)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "settings": {
+ "name": "settings",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "ai_providers_id_user_id_unique": {
+ "name": "ai_providers_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"ai_providers\".\"workspace_id\" is null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "ai_providers_id_user_id_workspace_id_unique": {
+ "name": "ai_providers_id_user_id_workspace_id_unique",
+ "columns": [
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"ai_providers\".\"workspace_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "ai_providers_user_id_idx": {
+ "name": "ai_providers_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "ai_providers_workspace_id_idx": {
+ "name": "ai_providers_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "ai_providers_user_id_users_id_fk": {
+ "name": "ai_providers_user_id_users_id_fk",
+ "tableFrom": "ai_providers",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ai_providers_workspace_id_workspaces_id_fk": {
+ "name": "ai_providers_workspace_id_workspaces_id_fk",
+ "tableFrom": "ai_providers",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.api_keys": {
+ "name": "api_keys",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key_hash": {
+ "name": "key_hash",
+ "type": "varchar(128)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "api_keys_user_id_idx": {
+ "name": "api_keys_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "api_keys_workspace_id_idx": {
+ "name": "api_keys_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "api_keys_user_id_users_id_fk": {
+ "name": "api_keys_user_id_users_id_fk",
+ "tableFrom": "api_keys",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "api_keys_workspace_id_workspaces_id_fk": {
+ "name": "api_keys_workspace_id_workspaces_id_fk",
+ "tableFrom": "api_keys",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "api_keys_key_unique": {
+ "name": "api_keys_key_unique",
+ "nullsNotDistinct": false,
+ "columns": ["key"]
+ },
+ "api_keys_key_hash_unique": {
+ "name": "api_keys_key_hash_unique",
+ "nullsNotDistinct": false,
+ "columns": ["key_hash"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.async_tasks": {
+ "name": "async_tasks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "inference_id": {
+ "name": "inference_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "duration": {
+ "name": "duration",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_id": {
+ "name": "parent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "async_tasks_user_id_idx": {
+ "name": "async_tasks_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "async_tasks_parent_id_idx": {
+ "name": "async_tasks_parent_id_idx",
+ "columns": [
+ {
+ "expression": "parent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "async_tasks_type_status_idx": {
+ "name": "async_tasks_type_status_idx",
+ "columns": [
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "async_tasks_inference_id_idx": {
+ "name": "async_tasks_inference_id_idx",
+ "columns": [
+ {
+ "expression": "inference_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "async_tasks_metadata_idx": {
+ "name": "async_tasks_metadata_idx",
+ "columns": [
+ {
+ "expression": "metadata",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ },
+ "async_tasks_workspace_id_idx": {
+ "name": "async_tasks_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "async_tasks_user_id_users_id_fk": {
+ "name": "async_tasks_user_id_users_id_fk",
+ "tableFrom": "async_tasks",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "async_tasks_workspace_id_workspaces_id_fk": {
+ "name": "async_tasks_workspace_id_workspaces_id_fk",
+ "tableFrom": "async_tasks",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.accounts": {
+ "name": "accounts",
+ "schema": "",
+ "columns": {
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "account_userId_idx": {
+ "name": "account_userId_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "accounts_user_id_users_id_fk": {
+ "name": "accounts_user_id_users_id_fk",
+ "tableFrom": "accounts",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.passkey": {
+ "name": "passkey",
+ "schema": "",
+ "columns": {
+ "aaguid": {
+ "name": "aaguid",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "backedUp": {
+ "name": "backedUp",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "counter": {
+ "name": "counter",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "credentialID": {
+ "name": "credentialID",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "deviceType": {
+ "name": "deviceType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "publicKey": {
+ "name": "publicKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "transports": {
+ "name": "transports",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "passkey_credential_id_unique": {
+ "name": "passkey_credential_id_unique",
+ "columns": [
+ {
+ "expression": "credentialID",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "passkey_user_id_idx": {
+ "name": "passkey_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "passkey_userId_users_id_fk": {
+ "name": "passkey_userId_users_id_fk",
+ "tableFrom": "passkey",
+ "tableTo": "users",
+ "columnsFrom": ["userId"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.auth_sessions": {
+ "name": "auth_sessions",
+ "schema": "",
+ "columns": {
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "impersonated_by": {
+ "name": "impersonated_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "auth_session_userId_idx": {
+ "name": "auth_session_userId_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "auth_sessions_user_id_users_id_fk": {
+ "name": "auth_sessions_user_id_users_id_fk",
+ "tableFrom": "auth_sessions",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "auth_sessions_token_unique": {
+ "name": "auth_sessions_token_unique",
+ "nullsNotDistinct": false,
+ "columns": ["token"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.two_factor": {
+ "name": "two_factor",
+ "schema": "",
+ "columns": {
+ "backup_codes": {
+ "name": "backup_codes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "secret": {
+ "name": "secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "two_factor_secret_idx": {
+ "name": "two_factor_secret_idx",
+ "columns": [
+ {
+ "expression": "secret",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "two_factor_user_id_idx": {
+ "name": "two_factor_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "two_factor_user_id_users_id_fk": {
+ "name": "two_factor_user_id_users_id_fk",
+ "tableFrom": "two_factor",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verifications": {
+ "name": "verifications",
+ "schema": "",
+ "columns": {
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "verification_identifier_idx": {
+ "name": "verification_identifier_idx",
+ "columns": [
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.chat_groups": {
+ "name": "chat_groups",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "avatar": {
+ "name": "avatar",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "background_color": {
+ "name": "background_color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "market_identifier": {
+ "name": "market_identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "editor_data": {
+ "name": "editor_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pinned": {
+ "name": "pinned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "chat_groups_client_id_user_id_unique": {
+ "name": "chat_groups_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chat_groups_user_id_idx": {
+ "name": "chat_groups_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chat_groups_group_id_idx": {
+ "name": "chat_groups_group_id_idx",
+ "columns": [
+ {
+ "expression": "group_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chat_groups_workspace_id_idx": {
+ "name": "chat_groups_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chat_groups_workspace_visibility_idx": {
+ "name": "chat_groups_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chat_groups_user_id_users_id_fk": {
+ "name": "chat_groups_user_id_users_id_fk",
+ "tableFrom": "chat_groups",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_groups_workspace_id_workspaces_id_fk": {
+ "name": "chat_groups_workspace_id_workspaces_id_fk",
+ "tableFrom": "chat_groups",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_groups_group_id_session_groups_id_fk": {
+ "name": "chat_groups_group_id_session_groups_id_fk",
+ "tableFrom": "chat_groups",
+ "tableTo": "session_groups",
+ "columnsFrom": ["group_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.chat_groups_agents": {
+ "name": "chat_groups_agents",
+ "schema": "",
+ "columns": {
+ "chat_group_id": {
+ "name": "chat_group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'participant'"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "chat_groups_agents_user_id_idx": {
+ "name": "chat_groups_agents_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chat_groups_agents_workspace_id_idx": {
+ "name": "chat_groups_agents_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chat_groups_agents_chat_group_id_chat_groups_id_fk": {
+ "name": "chat_groups_agents_chat_group_id_chat_groups_id_fk",
+ "tableFrom": "chat_groups_agents",
+ "tableTo": "chat_groups",
+ "columnsFrom": ["chat_group_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_groups_agents_agent_id_agents_id_fk": {
+ "name": "chat_groups_agents_agent_id_agents_id_fk",
+ "tableFrom": "chat_groups_agents",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_groups_agents_user_id_users_id_fk": {
+ "name": "chat_groups_agents_user_id_users_id_fk",
+ "tableFrom": "chat_groups_agents",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_groups_agents_workspace_id_workspaces_id_fk": {
+ "name": "chat_groups_agents_workspace_id_workspaces_id_fk",
+ "tableFrom": "chat_groups_agents",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "chat_groups_agents_chat_group_id_agent_id_pk": {
+ "name": "chat_groups_agents_chat_group_id_agent_id_pk",
+ "columns": ["chat_group_id", "agent_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_connector_tools": {
+ "name": "user_connector_tools",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_connector_id": {
+ "name": "user_connector_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_name": {
+ "name": "tool_name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "display_name": {
+ "name": "display_name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "input_schema": {
+ "name": "input_schema",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "output_schema": {
+ "name": "output_schema",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "crud_type": {
+ "name": "crud_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "render_config": {
+ "name": "render_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "permission": {
+ "name": "permission",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "is_work_artifact": {
+ "name": "is_work_artifact",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "work_artifact_config": {
+ "name": "work_artifact_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "limit_config": {
+ "name": "limit_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_connector_tools_connector_tool_unique": {
+ "name": "user_connector_tools_connector_tool_unique",
+ "columns": [
+ {
+ "expression": "user_connector_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "tool_name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_connector_tools_user_id_idx": {
+ "name": "user_connector_tools_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_connector_tools_connector_id_idx": {
+ "name": "user_connector_tools_connector_id_idx",
+ "columns": [
+ {
+ "expression": "user_connector_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_connector_tools_workspace_id_idx": {
+ "name": "user_connector_tools_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_connector_tools_user_connector_id_user_connectors_id_fk": {
+ "name": "user_connector_tools_user_connector_id_user_connectors_id_fk",
+ "tableFrom": "user_connector_tools",
+ "tableTo": "user_connectors",
+ "columnsFrom": ["user_connector_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_connector_tools_user_id_users_id_fk": {
+ "name": "user_connector_tools_user_id_users_id_fk",
+ "tableFrom": "user_connector_tools",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_connector_tools_workspace_id_workspaces_id_fk": {
+ "name": "user_connector_tools_workspace_id_workspaces_id_fk",
+ "tableFrom": "user_connector_tools",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_connectors": {
+ "name": "user_connectors",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_type": {
+ "name": "source_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "mcp_server_url": {
+ "name": "mcp_server_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "mcp_connection_type": {
+ "name": "mcp_connection_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "mcp_stdio_config": {
+ "name": "mcp_stdio_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "is_enabled": {
+ "name": "is_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "oidc_config": {
+ "name": "oidc_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "credentials": {
+ "name": "credentials",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "token_expires_at": {
+ "name": "token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_connectors_personal_identifier_idx": {
+ "name": "user_connectors_personal_identifier_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"user_connectors\".\"workspace_id\" IS NULL AND \"user_connectors\".\"agent_id\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_connectors_workspace_identifier_idx": {
+ "name": "user_connectors_workspace_identifier_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"user_connectors\".\"workspace_id\" IS NOT NULL AND \"user_connectors\".\"agent_id\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_connectors_agent_identifier_idx": {
+ "name": "user_connectors_agent_identifier_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"user_connectors\".\"agent_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_connectors_user_id_idx": {
+ "name": "user_connectors_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_connectors_token_expires_at_idx": {
+ "name": "user_connectors_token_expires_at_idx",
+ "columns": [
+ {
+ "expression": "token_expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_connectors_workspace_id_idx": {
+ "name": "user_connectors_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_connectors_agent_id_idx": {
+ "name": "user_connectors_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_connectors_user_id_users_id_fk": {
+ "name": "user_connectors_user_id_users_id_fk",
+ "tableFrom": "user_connectors",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_connectors_workspace_id_workspaces_id_fk": {
+ "name": "user_connectors_workspace_id_workspaces_id_fk",
+ "tableFrom": "user_connectors",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_connectors_agent_id_agents_id_fk": {
+ "name": "user_connectors_agent_id_agents_id_fk",
+ "tableFrom": "user_connectors",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_installed_plugins": {
+ "name": "user_installed_plugins",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "manifest": {
+ "name": "manifest",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "settings": {
+ "name": "settings",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "custom_params": {
+ "name": "custom_params",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_installed_plugins_workspace_id_idx": {
+ "name": "user_installed_plugins_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_installed_plugins_user_id_users_id_fk": {
+ "name": "user_installed_plugins_user_id_users_id_fk",
+ "tableFrom": "user_installed_plugins",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_installed_plugins_workspace_id_workspaces_id_fk": {
+ "name": "user_installed_plugins_workspace_id_workspaces_id_fk",
+ "tableFrom": "user_installed_plugins",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "user_installed_plugins_user_id_identifier_pk": {
+ "name": "user_installed_plugins_user_id_identifier_pk",
+ "columns": ["user_id", "identifier"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.devices": {
+ "name": "devices",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'private'"
+ },
+ "shared_from_device_id": {
+ "name": "shared_from_device_id",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "device_id": {
+ "name": "device_id",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "identity_source": {
+ "name": "identity_source",
+ "type": "varchar(20)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "hostname": {
+ "name": "hostname",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "platform": {
+ "name": "platform",
+ "type": "varchar(20)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "friendly_name": {
+ "name": "friendly_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "default_cwd": {
+ "name": "default_cwd",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "recent_cwds": {
+ "name": "recent_cwds",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'"
+ },
+ "working_dirs": {
+ "name": "working_dirs",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "first_seen_at": {
+ "name": "first_seen_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "devices_user_id_device_id_unique": {
+ "name": "devices_user_id_device_id_unique",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "device_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"devices\".\"workspace_id\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "devices_workspace_id_device_id_unique": {
+ "name": "devices_workspace_id_device_id_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "device_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"devices\".\"workspace_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "devices_user_id_idx": {
+ "name": "devices_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "devices_workspace_id_idx": {
+ "name": "devices_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "devices_workspace_visibility_idx": {
+ "name": "devices_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "devices_user_id_users_id_fk": {
+ "name": "devices_user_id_users_id_fk",
+ "tableFrom": "devices",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "devices_workspace_id_workspaces_id_fk": {
+ "name": "devices_workspace_id_workspaces_id_fk",
+ "tableFrom": "devices",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.document_comment_mentions": {
+ "name": "document_comment_mentions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "comment_id": {
+ "name": "comment_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "mentioned_user_id": {
+ "name": "mentioned_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "document_comment_mentions_comment_id_mentioned_user_id_unique": {
+ "name": "document_comment_mentions_comment_id_mentioned_user_id_unique",
+ "columns": [
+ {
+ "expression": "comment_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "mentioned_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_comment_mentions_mentioned_user_id_created_at_idx": {
+ "name": "document_comment_mentions_mentioned_user_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "mentioned_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_comment_mentions_workspace_id_idx": {
+ "name": "document_comment_mentions_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "document_comment_mentions_comment_id_document_comments_id_fk": {
+ "name": "document_comment_mentions_comment_id_document_comments_id_fk",
+ "tableFrom": "document_comment_mentions",
+ "tableTo": "document_comments",
+ "columnsFrom": ["comment_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "document_comment_mentions_mentioned_user_id_users_id_fk": {
+ "name": "document_comment_mentions_mentioned_user_id_users_id_fk",
+ "tableFrom": "document_comment_mentions",
+ "tableTo": "users",
+ "columnsFrom": ["mentioned_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "document_comment_mentions_workspace_id_workspaces_id_fk": {
+ "name": "document_comment_mentions_workspace_id_workspaces_id_fk",
+ "tableFrom": "document_comment_mentions",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.document_comments": {
+ "name": "document_comments",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "parent_comment_id": {
+ "name": "parent_comment_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reply_to_comment_id": {
+ "name": "reply_to_comment_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "author_user_id": {
+ "name": "author_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "editor_data": {
+ "name": "editor_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "document_comments_document_id_author_user_id_client_id_unique": {
+ "name": "document_comments_document_id_author_user_id_client_id_unique",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "author_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_comments_parent_comment_id_created_at_id_idx": {
+ "name": "document_comments_parent_comment_id_created_at_id_idx",
+ "columns": [
+ {
+ "expression": "parent_comment_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_comments_reply_to_comment_id_idx": {
+ "name": "document_comments_reply_to_comment_id_idx",
+ "columns": [
+ {
+ "expression": "reply_to_comment_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_comments_document_id_created_at_id_idx": {
+ "name": "document_comments_document_id_created_at_id_idx",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_comments_author_user_id_idx": {
+ "name": "document_comments_author_user_id_idx",
+ "columns": [
+ {
+ "expression": "author_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_comments_workspace_id_idx": {
+ "name": "document_comments_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "document_comments_document_id_documents_id_fk": {
+ "name": "document_comments_document_id_documents_id_fk",
+ "tableFrom": "document_comments",
+ "tableTo": "documents",
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "document_comments_parent_comment_id_document_comments_id_fk": {
+ "name": "document_comments_parent_comment_id_document_comments_id_fk",
+ "tableFrom": "document_comments",
+ "tableTo": "document_comments",
+ "columnsFrom": ["parent_comment_id"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "document_comments_reply_to_comment_id_document_comments_id_fk": {
+ "name": "document_comments_reply_to_comment_id_document_comments_id_fk",
+ "tableFrom": "document_comments",
+ "tableTo": "document_comments",
+ "columnsFrom": ["reply_to_comment_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "document_comments_author_user_id_users_id_fk": {
+ "name": "document_comments_author_user_id_users_id_fk",
+ "tableFrom": "document_comments",
+ "tableTo": "users",
+ "columnsFrom": ["author_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "document_comments_workspace_id_workspaces_id_fk": {
+ "name": "document_comments_workspace_id_workspaces_id_fk",
+ "tableFrom": "document_comments",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.document_histories": {
+ "name": "document_histories",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "editor_data": {
+ "name": "editor_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "save_source": {
+ "name": "save_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "saved_at": {
+ "name": "saved_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "document_histories_document_id_idx": {
+ "name": "document_histories_document_id_idx",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_histories_user_id_idx": {
+ "name": "document_histories_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_histories_workspace_id_idx": {
+ "name": "document_histories_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_histories_saved_at_idx": {
+ "name": "document_histories_saved_at_idx",
+ "columns": [
+ {
+ "expression": "saved_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "document_histories_document_id_documents_id_fk": {
+ "name": "document_histories_document_id_documents_id_fk",
+ "tableFrom": "document_histories",
+ "tableTo": "documents",
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "document_histories_user_id_users_id_fk": {
+ "name": "document_histories_user_id_users_id_fk",
+ "tableFrom": "document_histories",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "document_histories_workspace_id_workspaces_id_fk": {
+ "name": "document_histories_workspace_id_workspaces_id_fk",
+ "tableFrom": "document_histories",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.document_shares": {
+ "name": "document_shares",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'private'"
+ },
+ "permission": {
+ "name": "permission",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'read'"
+ },
+ "page_view_count": {
+ "name": "page_view_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "document_shares_document_id_unique": {
+ "name": "document_shares_document_id_unique",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_shares_user_id_idx": {
+ "name": "document_shares_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_shares_workspace_id_idx": {
+ "name": "document_shares_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "document_shares_document_id_documents_id_fk": {
+ "name": "document_shares_document_id_documents_id_fk",
+ "tableFrom": "document_shares",
+ "tableTo": "documents",
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "document_shares_user_id_users_id_fk": {
+ "name": "document_shares_user_id_users_id_fk",
+ "tableFrom": "document_shares",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "document_shares_workspace_id_workspaces_id_fk": {
+ "name": "document_shares_workspace_id_workspaces_id_fk",
+ "tableFrom": "document_shares",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.expertise_bindings": {
+ "name": "expertise_bindings",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "domain_id": {
+ "name": "domain_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "bound_workspace_id": {
+ "name": "bound_workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "bound_user_id": {
+ "name": "bound_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contribution_mode": {
+ "name": "contribution_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'derive'"
+ },
+ "added_by_user_id": {
+ "name": "added_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "expertise_bindings_agent_domain_unique": {
+ "name": "expertise_bindings_agent_domain_unique",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"expertise_bindings\".\"agent_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_bindings_project_domain_unique": {
+ "name": "expertise_bindings_project_domain_unique",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"expertise_bindings\".\"project_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_bindings_workspace_domain_unique": {
+ "name": "expertise_bindings_workspace_domain_unique",
+ "columns": [
+ {
+ "expression": "bound_workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"expertise_bindings\".\"bound_workspace_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_bindings_user_domain_unique": {
+ "name": "expertise_bindings_user_domain_unique",
+ "columns": [
+ {
+ "expression": "bound_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"expertise_bindings\".\"bound_user_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_bindings_domain_idx": {
+ "name": "expertise_bindings_domain_idx",
+ "columns": [
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_bindings_workspace_id_idx": {
+ "name": "expertise_bindings_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "expertise_bindings_domain_id_expertise_domains_id_fk": {
+ "name": "expertise_bindings_domain_id_expertise_domains_id_fk",
+ "tableFrom": "expertise_bindings",
+ "tableTo": "expertise_domains",
+ "columnsFrom": ["domain_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_bindings_agent_id_agents_id_fk": {
+ "name": "expertise_bindings_agent_id_agents_id_fk",
+ "tableFrom": "expertise_bindings",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_bindings_project_id_projects_id_fk": {
+ "name": "expertise_bindings_project_id_projects_id_fk",
+ "tableFrom": "expertise_bindings",
+ "tableTo": "projects",
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_bindings_bound_workspace_id_workspaces_id_fk": {
+ "name": "expertise_bindings_bound_workspace_id_workspaces_id_fk",
+ "tableFrom": "expertise_bindings",
+ "tableTo": "workspaces",
+ "columnsFrom": ["bound_workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_bindings_bound_user_id_users_id_fk": {
+ "name": "expertise_bindings_bound_user_id_users_id_fk",
+ "tableFrom": "expertise_bindings",
+ "tableTo": "users",
+ "columnsFrom": ["bound_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_bindings_added_by_user_id_users_id_fk": {
+ "name": "expertise_bindings_added_by_user_id_users_id_fk",
+ "tableFrom": "expertise_bindings",
+ "tableTo": "users",
+ "columnsFrom": ["added_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "expertise_bindings_workspace_id_workspaces_id_fk": {
+ "name": "expertise_bindings_workspace_id_workspaces_id_fk",
+ "tableFrom": "expertise_bindings",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "expertise_bindings_exactly_one_carrier": {
+ "name": "expertise_bindings_exactly_one_carrier",
+ "value": "(\"expertise_bindings\".\"agent_id\" IS NOT NULL)::int + (\"expertise_bindings\".\"project_id\" IS NOT NULL)::int + (\"expertise_bindings\".\"bound_workspace_id\" IS NOT NULL)::int + (\"expertise_bindings\".\"bound_user_id\" IS NOT NULL)::int = 1"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.expertise_domain_snapshots": {
+ "name": "expertise_domain_snapshots",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "domain_id": {
+ "name": "domain_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "run_index": {
+ "name": "run_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "learned_total": {
+ "name": "learned_total",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "retired_total": {
+ "name": "retired_total",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "active_count": {
+ "name": "active_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "compiled_count": {
+ "name": "compiled_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "layer_counts": {
+ "name": "layer_counts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "p_inf": {
+ "name": "p_inf",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tau": {
+ "name": "tau",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "maturity": {
+ "name": "maturity",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "fit_sample_size": {
+ "name": "fit_sample_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "fit_r2": {
+ "name": "fit_r2",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "fit_confidence": {
+ "name": "fit_confidence",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "fit_computed_at": {
+ "name": "fit_computed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tau_pinned": {
+ "name": "tau_pinned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "observed_span": {
+ "name": "observed_span",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "plateau_kind": {
+ "name": "plateau_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "layer_coverage": {
+ "name": "layer_coverage",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "canon_coverage": {
+ "name": "canon_coverage",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "active_rate": {
+ "name": "active_rate",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "captured_at": {
+ "name": "captured_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "expertise_domain_snapshots_domain_run_index_unique": {
+ "name": "expertise_domain_snapshots_domain_run_index_unique",
+ "columns": [
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "run_index",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_domain_snapshots_domain_captured_idx": {
+ "name": "expertise_domain_snapshots_domain_captured_idx",
+ "columns": [
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "captured_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_domain_snapshots_pending_fit_idx": {
+ "name": "expertise_domain_snapshots_pending_fit_idx",
+ "columns": [
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"expertise_domain_snapshots\".\"fit_computed_at\" is null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "expertise_domain_snapshots_domain_id_expertise_domains_id_fk": {
+ "name": "expertise_domain_snapshots_domain_id_expertise_domains_id_fk",
+ "tableFrom": "expertise_domain_snapshots",
+ "tableTo": "expertise_domains",
+ "columnsFrom": ["domain_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_domain_snapshots_run_id_expertise_runs_id_fk": {
+ "name": "expertise_domain_snapshots_run_id_expertise_runs_id_fk",
+ "tableFrom": "expertise_domain_snapshots",
+ "tableTo": "expertise_runs",
+ "columnsFrom": ["run_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "expertise_domain_snapshots_run_domain_fk": {
+ "name": "expertise_domain_snapshots_run_domain_fk",
+ "tableFrom": "expertise_domain_snapshots",
+ "tableTo": "expertise_runs",
+ "columnsFrom": ["run_id", "domain_id"],
+ "columnsTo": ["id", "domain_id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.expertise_domains": {
+ "name": "expertise_domains",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'private'"
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'user'"
+ },
+ "parent_domain_id": {
+ "name": "parent_domain_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "domain_filter": {
+ "name": "domain_filter",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "out_of_scope": {
+ "name": "out_of_scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "layers": {
+ "name": "layers",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "layer_source": {
+ "name": "layer_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'invented'"
+ },
+ "canon_entries": {
+ "name": "canon_entries",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "canon_document_id": {
+ "name": "canon_document_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "flow": {
+ "name": "flow",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "evidence_spec": {
+ "name": "evidence_spec",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "lesson_base_document_id": {
+ "name": "lesson_base_document_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "anchor_candidates": {
+ "name": "anchor_candidates",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "anchor_chosen_at": {
+ "name": "anchor_chosen_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "anchor_chosen_by_user_id": {
+ "name": "anchor_chosen_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "seed_state": {
+ "name": "seed_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'seeding'"
+ },
+ "seed_run_id": {
+ "name": "seed_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "expertise_domains_slug_user_unique": {
+ "name": "expertise_domains_slug_user_unique",
+ "columns": [
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"expertise_domains\".\"workspace_id\" is null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_domains_slug_workspace_unique": {
+ "name": "expertise_domains_slug_workspace_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"expertise_domains\".\"workspace_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_domains_user_id_idx": {
+ "name": "expertise_domains_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_domains_workspace_visibility_idx": {
+ "name": "expertise_domains_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_domains_parent_idx": {
+ "name": "expertise_domains_parent_idx",
+ "columns": [
+ {
+ "expression": "parent_domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "expertise_domains_user_id_users_id_fk": {
+ "name": "expertise_domains_user_id_users_id_fk",
+ "tableFrom": "expertise_domains",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_domains_workspace_id_workspaces_id_fk": {
+ "name": "expertise_domains_workspace_id_workspaces_id_fk",
+ "tableFrom": "expertise_domains",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_domains_parent_domain_id_expertise_domains_id_fk": {
+ "name": "expertise_domains_parent_domain_id_expertise_domains_id_fk",
+ "tableFrom": "expertise_domains",
+ "tableTo": "expertise_domains",
+ "columnsFrom": ["parent_domain_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "expertise_domains_canon_document_id_documents_id_fk": {
+ "name": "expertise_domains_canon_document_id_documents_id_fk",
+ "tableFrom": "expertise_domains",
+ "tableTo": "documents",
+ "columnsFrom": ["canon_document_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "expertise_domains_lesson_base_document_id_documents_id_fk": {
+ "name": "expertise_domains_lesson_base_document_id_documents_id_fk",
+ "tableFrom": "expertise_domains",
+ "tableTo": "documents",
+ "columnsFrom": ["lesson_base_document_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "expertise_domains_anchor_chosen_by_user_id_users_id_fk": {
+ "name": "expertise_domains_anchor_chosen_by_user_id_users_id_fk",
+ "tableFrom": "expertise_domains",
+ "tableTo": "users",
+ "columnsFrom": ["anchor_chosen_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.expertise_hits": {
+ "name": "expertise_hits",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "lesson_id": {
+ "name": "lesson_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "domain_id": {
+ "name": "domain_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "outcome": {
+ "name": "outcome",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "where": {
+ "name": "where",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "example": {
+ "name": "example",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "severity": {
+ "name": "severity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "evidence_id": {
+ "name": "evidence_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "operation_id": {
+ "name": "operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_decision": {
+ "name": "user_decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_decision_at": {
+ "name": "user_decision_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "expertise_hits_lesson_created_idx": {
+ "name": "expertise_hits_lesson_created_idx",
+ "columns": [
+ {
+ "expression": "lesson_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_hits_run_idx": {
+ "name": "expertise_hits_run_idx",
+ "columns": [
+ {
+ "expression": "run_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_hits_domain_outcome_idx": {
+ "name": "expertise_hits_domain_outcome_idx",
+ "columns": [
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "outcome",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_hits_operation_idx": {
+ "name": "expertise_hits_operation_idx",
+ "columns": [
+ {
+ "expression": "operation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "expertise_hits_domain_id_expertise_domains_id_fk": {
+ "name": "expertise_hits_domain_id_expertise_domains_id_fk",
+ "tableFrom": "expertise_hits",
+ "tableTo": "expertise_domains",
+ "columnsFrom": ["domain_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_hits_evidence_id_verify_evidence_id_fk": {
+ "name": "expertise_hits_evidence_id_verify_evidence_id_fk",
+ "tableFrom": "expertise_hits",
+ "tableTo": "verify_evidence",
+ "columnsFrom": ["evidence_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "expertise_hits_operation_id_agent_operations_id_fk": {
+ "name": "expertise_hits_operation_id_agent_operations_id_fk",
+ "tableFrom": "expertise_hits",
+ "tableTo": "agent_operations",
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "expertise_hits_run_domain_fk": {
+ "name": "expertise_hits_run_domain_fk",
+ "tableFrom": "expertise_hits",
+ "tableTo": "expertise_runs",
+ "columnsFrom": ["run_id", "domain_id"],
+ "columnsTo": ["id", "domain_id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_hits_lesson_domain_fk": {
+ "name": "expertise_hits_lesson_domain_fk",
+ "tableFrom": "expertise_hits",
+ "tableTo": "expertise_lessons",
+ "columnsFrom": ["lesson_id", "domain_id"],
+ "columnsTo": ["id", "domain_id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.expertise_insights": {
+ "name": "expertise_insights",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "domain_id": {
+ "name": "domain_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "headline": {
+ "name": "headline",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "action_label": {
+ "name": "action_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "action_target": {
+ "name": "action_target",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "evidence": {
+ "name": "evidence",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "confidence": {
+ "name": "confidence",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "dismiss_reason": {
+ "name": "dismiss_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stale_after_run_index": {
+ "name": "stale_after_run_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "generated_by_operation_id": {
+ "name": "generated_by_operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "expertise_insights_domain_status_idx": {
+ "name": "expertise_insights_domain_status_idx",
+ "columns": [
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_insights_user_status_idx": {
+ "name": "expertise_insights_user_status_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_insights_workspace_idx": {
+ "name": "expertise_insights_workspace_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "expertise_insights_domain_id_expertise_domains_id_fk": {
+ "name": "expertise_insights_domain_id_expertise_domains_id_fk",
+ "tableFrom": "expertise_insights",
+ "tableTo": "expertise_domains",
+ "columnsFrom": ["domain_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_insights_user_id_users_id_fk": {
+ "name": "expertise_insights_user_id_users_id_fk",
+ "tableFrom": "expertise_insights",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_insights_workspace_id_workspaces_id_fk": {
+ "name": "expertise_insights_workspace_id_workspaces_id_fk",
+ "tableFrom": "expertise_insights",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_insights_generated_by_operation_id_agent_operations_id_fk": {
+ "name": "expertise_insights_generated_by_operation_id_agent_operations_id_fk",
+ "tableFrom": "expertise_insights",
+ "tableTo": "agent_operations",
+ "columnsFrom": ["generated_by_operation_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.expertise_lesson_revisions": {
+ "name": "expertise_lesson_revisions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "lesson_id": {
+ "name": "lesson_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sections": {
+ "name": "sections",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "feedback": {
+ "name": "feedback",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "changed_by": {
+ "name": "changed_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'user-feedback'"
+ },
+ "prev_title": {
+ "name": "prev_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "changed_by_user_id": {
+ "name": "changed_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_run_id": {
+ "name": "source_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "operation_id": {
+ "name": "operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "expertise_lesson_revisions_lesson_revision_unique": {
+ "name": "expertise_lesson_revisions_lesson_revision_unique",
+ "columns": [
+ {
+ "expression": "lesson_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "revision",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_lesson_revisions_lesson_idx": {
+ "name": "expertise_lesson_revisions_lesson_idx",
+ "columns": [
+ {
+ "expression": "lesson_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "expertise_lesson_revisions_lesson_id_expertise_lessons_id_fk": {
+ "name": "expertise_lesson_revisions_lesson_id_expertise_lessons_id_fk",
+ "tableFrom": "expertise_lesson_revisions",
+ "tableTo": "expertise_lessons",
+ "columnsFrom": ["lesson_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_lesson_revisions_changed_by_user_id_users_id_fk": {
+ "name": "expertise_lesson_revisions_changed_by_user_id_users_id_fk",
+ "tableFrom": "expertise_lesson_revisions",
+ "tableTo": "users",
+ "columnsFrom": ["changed_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "expertise_lesson_revisions_operation_id_agent_operations_id_fk": {
+ "name": "expertise_lesson_revisions_operation_id_agent_operations_id_fk",
+ "tableFrom": "expertise_lesson_revisions",
+ "tableTo": "agent_operations",
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.expertise_lessons": {
+ "name": "expertise_lessons",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "domain_id": {
+ "name": "domain_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "code": {
+ "name": "code",
+ "type": "varchar(20)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "polarity": {
+ "name": "polarity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sections": {
+ "name": "sections",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "layer": {
+ "name": "layer",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "canon_anchor": {
+ "name": "canon_anchor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "origin_run_id": {
+ "name": "origin_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "origin_hit_id": {
+ "name": "origin_hit_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "rejected_reason": {
+ "name": "rejected_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "salvaged_from_id": {
+ "name": "salvaged_from_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retired_at": {
+ "name": "retired_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "compilability": {
+ "name": "compilability",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'compilable'"
+ },
+ "compiled_criterion_id": {
+ "name": "compiled_criterion_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "hit_count": {
+ "name": "hit_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "hit_run_count": {
+ "name": "hit_run_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "false_positive_count": {
+ "name": "false_positive_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "last_hit_at": {
+ "name": "last_hit_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_hit_run_id": {
+ "name": "last_hit_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "generalized_from_ids": {
+ "name": "generalized_from_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "specificity": {
+ "name": "specificity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "example_count": {
+ "name": "example_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "current_revision": {
+ "name": "current_revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "expertise_lessons_domain_code_unique": {
+ "name": "expertise_lessons_domain_code_unique",
+ "columns": [
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "code",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_lessons_domain_status_hits_idx": {
+ "name": "expertise_lessons_domain_status_hits_idx",
+ "columns": [
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "hit_count",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_lessons_domain_layer_idx": {
+ "name": "expertise_lessons_domain_layer_idx",
+ "columns": [
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "layer",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_lessons_compiled_criterion_idx": {
+ "name": "expertise_lessons_compiled_criterion_idx",
+ "columns": [
+ {
+ "expression": "compiled_criterion_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "expertise_lessons_domain_id_expertise_domains_id_fk": {
+ "name": "expertise_lessons_domain_id_expertise_domains_id_fk",
+ "tableFrom": "expertise_lessons",
+ "tableTo": "expertise_domains",
+ "columnsFrom": ["domain_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_lessons_created_by_user_id_users_id_fk": {
+ "name": "expertise_lessons_created_by_user_id_users_id_fk",
+ "tableFrom": "expertise_lessons",
+ "tableTo": "users",
+ "columnsFrom": ["created_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "expertise_lessons_salvaged_from_id_expertise_lessons_id_fk": {
+ "name": "expertise_lessons_salvaged_from_id_expertise_lessons_id_fk",
+ "tableFrom": "expertise_lessons",
+ "tableTo": "expertise_lessons",
+ "columnsFrom": ["salvaged_from_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "expertise_lessons_compiled_criterion_id_verify_criteria_id_fk": {
+ "name": "expertise_lessons_compiled_criterion_id_verify_criteria_id_fk",
+ "tableFrom": "expertise_lessons",
+ "tableTo": "verify_criteria",
+ "columnsFrom": ["compiled_criterion_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "expertise_lessons_id_domain_unique": {
+ "name": "expertise_lessons_id_domain_unique",
+ "nullsNotDistinct": false,
+ "columns": ["id", "domain_id"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.expertise_runs": {
+ "name": "expertise_runs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "domain_id": {
+ "name": "domain_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "run_index": {
+ "name": "run_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "is_seed_run": {
+ "name": "is_seed_run",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "actor_type": {
+ "name": "actor_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "actor_id": {
+ "name": "actor_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "subject_type": {
+ "name": "subject_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "subject_id": {
+ "name": "subject_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "window_start": {
+ "name": "window_start",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "window_end": {
+ "name": "window_end",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reflection_key": {
+ "name": "reflection_key",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "had_human_in_loop": {
+ "name": "had_human_in_loop",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "instance_count": {
+ "name": "instance_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "refine_count": {
+ "name": "refine_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "new_count": {
+ "name": "new_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "expertise_runs_domain_run_index_unique": {
+ "name": "expertise_runs_domain_run_index_unique",
+ "columns": [
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "run_index",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_runs_domain_reflection_key_unique": {
+ "name": "expertise_runs_domain_reflection_key_unique",
+ "columns": [
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "reflection_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"expertise_runs\".\"reflection_key\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_runs_domain_started_idx": {
+ "name": "expertise_runs_domain_started_idx",
+ "columns": [
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "started_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_runs_actor_idx": {
+ "name": "expertise_runs_actor_idx",
+ "columns": [
+ {
+ "expression": "actor_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "actor_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "expertise_runs_subject_idx": {
+ "name": "expertise_runs_subject_idx",
+ "columns": [
+ {
+ "expression": "subject_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "subject_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "expertise_runs_domain_id_expertise_domains_id_fk": {
+ "name": "expertise_runs_domain_id_expertise_domains_id_fk",
+ "tableFrom": "expertise_runs",
+ "tableTo": "expertise_domains",
+ "columnsFrom": ["domain_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "expertise_runs_user_id_users_id_fk": {
+ "name": "expertise_runs_user_id_users_id_fk",
+ "tableFrom": "expertise_runs",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "expertise_runs_workspace_id_workspaces_id_fk": {
+ "name": "expertise_runs_workspace_id_workspaces_id_fk",
+ "tableFrom": "expertise_runs",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "expertise_runs_id_domain_unique": {
+ "name": "expertise_runs_id_domain_unique",
+ "nullsNotDistinct": false,
+ "columns": ["id", "domain_id"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.documents": {
+ "name": "documents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_type": {
+ "name": "file_type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "filename": {
+ "name": "filename",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "total_char_count": {
+ "name": "total_char_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "total_line_count": {
+ "name": "total_line_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pages": {
+ "name": "pages",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_type": {
+ "name": "source_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "file_id": {
+ "name": "file_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "knowledge_base_id": {
+ "name": "knowledge_base_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_id": {
+ "name": "parent_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "editor_data": {
+ "name": "editor_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "slug": {
+ "name": "slug",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "documents_source_idx": {
+ "name": "documents_source_idx",
+ "columns": [
+ {
+ "expression": "source",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "documents_file_type_idx": {
+ "name": "documents_file_type_idx",
+ "columns": [
+ {
+ "expression": "file_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "documents_source_type_idx": {
+ "name": "documents_source_type_idx",
+ "columns": [
+ {
+ "expression": "source_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "documents_user_id_idx": {
+ "name": "documents_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "documents_file_id_idx": {
+ "name": "documents_file_id_idx",
+ "columns": [
+ {
+ "expression": "file_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "documents_parent_id_idx": {
+ "name": "documents_parent_id_idx",
+ "columns": [
+ {
+ "expression": "parent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "documents_knowledge_base_id_idx": {
+ "name": "documents_knowledge_base_id_idx",
+ "columns": [
+ {
+ "expression": "knowledge_base_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "documents_client_id_user_id_unique": {
+ "name": "documents_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "documents_slug_user_id_unique": {
+ "name": "documents_slug_user_id_unique",
+ "columns": [
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"documents\".\"workspace_id\" IS NULL AND \"documents\".\"slug\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "documents_workspace_id_idx": {
+ "name": "documents_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "documents_workspace_visibility_idx": {
+ "name": "documents_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "documents_slug_workspace_id_unique": {
+ "name": "documents_slug_workspace_id_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"documents\".\"workspace_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "documents_file_id_files_id_fk": {
+ "name": "documents_file_id_files_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "files",
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "documents_knowledge_base_id_knowledge_bases_id_fk": {
+ "name": "documents_knowledge_base_id_knowledge_bases_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "knowledge_bases",
+ "columnsFrom": ["knowledge_base_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "documents_parent_id_documents_id_fk": {
+ "name": "documents_parent_id_documents_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "documents",
+ "columnsFrom": ["parent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "documents_user_id_users_id_fk": {
+ "name": "documents_user_id_users_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "documents_workspace_id_workspaces_id_fk": {
+ "name": "documents_workspace_id_workspaces_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.files": {
+ "name": "files",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "file_type": {
+ "name": "file_type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "file_hash": {
+ "name": "file_hash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "size": {
+ "name": "size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_id": {
+ "name": "parent_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "chunk_task_id": {
+ "name": "chunk_task_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "embedding_task_id": {
+ "name": "embedding_task_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "file_hash_idx": {
+ "name": "file_hash_idx",
+ "columns": [
+ {
+ "expression": "file_hash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_user_id_idx": {
+ "name": "files_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_parent_id_idx": {
+ "name": "files_parent_id_idx",
+ "columns": [
+ {
+ "expression": "parent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_chunk_task_id_idx": {
+ "name": "files_chunk_task_id_idx",
+ "columns": [
+ {
+ "expression": "chunk_task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_embedding_task_id_idx": {
+ "name": "files_embedding_task_id_idx",
+ "columns": [
+ {
+ "expression": "embedding_task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_client_id_user_id_unique": {
+ "name": "files_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_workspace_id_idx": {
+ "name": "files_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_workspace_visibility_idx": {
+ "name": "files_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "files_user_id_users_id_fk": {
+ "name": "files_user_id_users_id_fk",
+ "tableFrom": "files",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "files_file_hash_global_files_hash_id_fk": {
+ "name": "files_file_hash_global_files_hash_id_fk",
+ "tableFrom": "files",
+ "tableTo": "global_files",
+ "columnsFrom": ["file_hash"],
+ "columnsTo": ["hash_id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "files_parent_id_documents_id_fk": {
+ "name": "files_parent_id_documents_id_fk",
+ "tableFrom": "files",
+ "tableTo": "documents",
+ "columnsFrom": ["parent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "files_chunk_task_id_async_tasks_id_fk": {
+ "name": "files_chunk_task_id_async_tasks_id_fk",
+ "tableFrom": "files",
+ "tableTo": "async_tasks",
+ "columnsFrom": ["chunk_task_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "files_embedding_task_id_async_tasks_id_fk": {
+ "name": "files_embedding_task_id_async_tasks_id_fk",
+ "tableFrom": "files",
+ "tableTo": "async_tasks",
+ "columnsFrom": ["embedding_task_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "files_workspace_id_workspaces_id_fk": {
+ "name": "files_workspace_id_workspaces_id_fk",
+ "tableFrom": "files",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.global_files": {
+ "name": "global_files",
+ "schema": "",
+ "columns": {
+ "hash_id": {
+ "name": "hash_id",
+ "type": "varchar(64)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "file_type": {
+ "name": "file_type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "size": {
+ "name": "size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "creator": {
+ "name": "creator",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "global_files_creator_idx": {
+ "name": "global_files_creator_idx",
+ "columns": [
+ {
+ "expression": "creator",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "global_files_creator_users_id_fk": {
+ "name": "global_files_creator_users_id_fk",
+ "tableFrom": "global_files",
+ "tableTo": "users",
+ "columnsFrom": ["creator"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.knowledge_base_files": {
+ "name": "knowledge_base_files",
+ "schema": "",
+ "columns": {
+ "knowledge_base_id": {
+ "name": "knowledge_base_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "file_id": {
+ "name": "file_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "knowledge_base_files_kb_id_idx": {
+ "name": "knowledge_base_files_kb_id_idx",
+ "columns": [
+ {
+ "expression": "knowledge_base_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "knowledge_base_files_user_id_idx": {
+ "name": "knowledge_base_files_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "knowledge_base_files_file_id_idx": {
+ "name": "knowledge_base_files_file_id_idx",
+ "columns": [
+ {
+ "expression": "file_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "knowledge_base_files_workspace_id_idx": {
+ "name": "knowledge_base_files_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "knowledge_base_files_knowledge_base_id_knowledge_bases_id_fk": {
+ "name": "knowledge_base_files_knowledge_base_id_knowledge_bases_id_fk",
+ "tableFrom": "knowledge_base_files",
+ "tableTo": "knowledge_bases",
+ "columnsFrom": ["knowledge_base_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "knowledge_base_files_file_id_files_id_fk": {
+ "name": "knowledge_base_files_file_id_files_id_fk",
+ "tableFrom": "knowledge_base_files",
+ "tableTo": "files",
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "knowledge_base_files_user_id_users_id_fk": {
+ "name": "knowledge_base_files_user_id_users_id_fk",
+ "tableFrom": "knowledge_base_files",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "knowledge_base_files_workspace_id_workspaces_id_fk": {
+ "name": "knowledge_base_files_workspace_id_workspaces_id_fk",
+ "tableFrom": "knowledge_base_files",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "knowledge_base_files_knowledge_base_id_file_id_pk": {
+ "name": "knowledge_base_files_knowledge_base_id_file_id_pk",
+ "columns": ["knowledge_base_id", "file_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.knowledge_bases": {
+ "name": "knowledge_bases",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "avatar": {
+ "name": "avatar",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_public": {
+ "name": "is_public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "settings": {
+ "name": "settings",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "knowledge_bases_client_id_user_id_unique": {
+ "name": "knowledge_bases_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "knowledge_bases_user_id_idx": {
+ "name": "knowledge_bases_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "knowledge_bases_workspace_id_idx": {
+ "name": "knowledge_bases_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "knowledge_bases_workspace_visibility_idx": {
+ "name": "knowledge_bases_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "knowledge_bases_user_id_users_id_fk": {
+ "name": "knowledge_bases_user_id_users_id_fk",
+ "tableFrom": "knowledge_bases",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "knowledge_bases_workspace_id_workspaces_id_fk": {
+ "name": "knowledge_bases_workspace_id_workspaces_id_fk",
+ "tableFrom": "knowledge_bases",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.fts_search_sync_outbox": {
+ "name": "fts_search_sync_outbox",
+ "schema": "",
+ "columns": {
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "available_at": {
+ "name": "available_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "dead_at": {
+ "name": "dead_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "entity": {
+ "name": "entity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "locked_until": {
+ "name": "locked_until",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "priority": {
+ "name": "priority",
+ "type": "smallint",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 10
+ },
+ "revision": {
+ "name": "revision",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "nextval('fts_search_sync_revision_seq')"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "fts_search_sync_outbox_entity_document_id_unique": {
+ "name": "fts_search_sync_outbox_entity_document_id_unique",
+ "columns": [
+ {
+ "expression": "entity",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "fts_search_sync_outbox_claim_idx": {
+ "name": "fts_search_sync_outbox_claim_idx",
+ "columns": [
+ {
+ "expression": "priority",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "available_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "revision",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"fts_search_sync_outbox\".\"dead_at\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "fts_search_sync_outbox_dead_idx": {
+ "name": "fts_search_sync_outbox_dead_idx",
+ "columns": [
+ {
+ "expression": "dead_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"fts_search_sync_outbox\".\"dead_at\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "fts_search_sync_outbox_lease_idx": {
+ "name": "fts_search_sync_outbox_lease_idx",
+ "columns": [
+ {
+ "expression": "locked_until",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"fts_search_sync_outbox\".\"dead_at\" IS NULL AND \"fts_search_sync_outbox\".\"locked_until\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.generation_batches": {
+ "name": "generation_batches",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "generation_topic_id": {
+ "name": "generation_topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "width": {
+ "name": "width",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "height": {
+ "name": "height",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ratio": {
+ "name": "ratio",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "generation_batches_user_id_idx": {
+ "name": "generation_batches_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "generation_batches_topic_id_idx": {
+ "name": "generation_batches_topic_id_idx",
+ "columns": [
+ {
+ "expression": "generation_topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "generation_batches_workspace_id_idx": {
+ "name": "generation_batches_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "generation_batches_user_id_users_id_fk": {
+ "name": "generation_batches_user_id_users_id_fk",
+ "tableFrom": "generation_batches",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "generation_batches_workspace_id_workspaces_id_fk": {
+ "name": "generation_batches_workspace_id_workspaces_id_fk",
+ "tableFrom": "generation_batches",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "generation_batches_generation_topic_id_generation_topics_id_fk": {
+ "name": "generation_batches_generation_topic_id_generation_topics_id_fk",
+ "tableFrom": "generation_batches",
+ "tableTo": "generation_topics",
+ "columnsFrom": ["generation_topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.generation_topics": {
+ "name": "generation_topics",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cover_url": {
+ "name": "cover_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'image'"
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "generation_topics_user_id_idx": {
+ "name": "generation_topics_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "generation_topics_workspace_id_idx": {
+ "name": "generation_topics_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "generation_topics_workspace_visibility_idx": {
+ "name": "generation_topics_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "generation_topics_user_id_users_id_fk": {
+ "name": "generation_topics_user_id_users_id_fk",
+ "tableFrom": "generation_topics",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "generation_topics_workspace_id_workspaces_id_fk": {
+ "name": "generation_topics_workspace_id_workspaces_id_fk",
+ "tableFrom": "generation_topics",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.generations": {
+ "name": "generations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "generation_batch_id": {
+ "name": "generation_batch_id",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "async_task_id": {
+ "name": "async_task_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_id": {
+ "name": "file_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "seed": {
+ "name": "seed",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "asset": {
+ "name": "asset",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "generations_user_id_idx": {
+ "name": "generations_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "generations_batch_id_idx": {
+ "name": "generations_batch_id_idx",
+ "columns": [
+ {
+ "expression": "generation_batch_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "generations_file_id_idx": {
+ "name": "generations_file_id_idx",
+ "columns": [
+ {
+ "expression": "file_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "generations_workspace_id_idx": {
+ "name": "generations_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "generations_user_id_users_id_fk": {
+ "name": "generations_user_id_users_id_fk",
+ "tableFrom": "generations",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "generations_workspace_id_workspaces_id_fk": {
+ "name": "generations_workspace_id_workspaces_id_fk",
+ "tableFrom": "generations",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "generations_generation_batch_id_generation_batches_id_fk": {
+ "name": "generations_generation_batch_id_generation_batches_id_fk",
+ "tableFrom": "generations",
+ "tableTo": "generation_batches",
+ "columnsFrom": ["generation_batch_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "generations_async_task_id_async_tasks_id_fk": {
+ "name": "generations_async_task_id_async_tasks_id_fk",
+ "tableFrom": "generations",
+ "tableTo": "async_tasks",
+ "columnsFrom": ["async_task_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "generations_file_id_files_id_fk": {
+ "name": "generations_file_id_files_id_fk",
+ "tableFrom": "generations",
+ "tableTo": "files",
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goals": {
+ "name": "goals",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "requirement": {
+ "name": "requirement",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "max_rounds": {
+ "name": "max_rounds",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "max_total_cost": {
+ "name": "max_total_cost",
+ "type": "numeric(20, 6)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'planning'"
+ },
+ "subject_type": {
+ "name": "subject_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "subject_id": {
+ "name": "subject_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "goals_user_id_idx": {
+ "name": "goals_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goals_workspace_id_idx": {
+ "name": "goals_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goals_agent_id_idx": {
+ "name": "goals_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goals_project_id_idx": {
+ "name": "goals_project_id_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goals_status_idx": {
+ "name": "goals_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goals_subject_idx": {
+ "name": "goals_subject_idx",
+ "columns": [
+ {
+ "expression": "subject_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "subject_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "goals_user_id_users_id_fk": {
+ "name": "goals_user_id_users_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "goals_workspace_id_workspaces_id_fk": {
+ "name": "goals_workspace_id_workspaces_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "goals_agent_id_agents_id_fk": {
+ "name": "goals_agent_id_agents_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "goals_project_id_projects_id_fk": {
+ "name": "goals_project_id_projects_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "projects",
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goal_edges": {
+ "name": "goal_edges",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_node_id": {
+ "name": "source_node_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_node_id": {
+ "name": "target_node_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "goal_edges_source_target_kind_unique": {
+ "name": "goal_edges_source_target_kind_unique",
+ "columns": [
+ {
+ "expression": "source_node_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "target_node_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "kind",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goal_edges_goal_id_idx": {
+ "name": "goal_edges_goal_id_idx",
+ "columns": [
+ {
+ "expression": "goal_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goal_edges_target_node_id_idx": {
+ "name": "goal_edges_target_node_id_idx",
+ "columns": [
+ {
+ "expression": "target_node_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "goal_edges_goal_id_goals_id_fk": {
+ "name": "goal_edges_goal_id_goals_id_fk",
+ "tableFrom": "goal_edges",
+ "tableTo": "goals",
+ "columnsFrom": ["goal_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "goal_edges_goal_source_node_fk": {
+ "name": "goal_edges_goal_source_node_fk",
+ "tableFrom": "goal_edges",
+ "tableTo": "goal_nodes",
+ "columnsFrom": ["goal_id", "source_node_id"],
+ "columnsTo": ["goal_id", "id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "goal_edges_goal_target_node_fk": {
+ "name": "goal_edges_goal_target_node_fk",
+ "tableFrom": "goal_edges",
+ "tableTo": "goal_nodes",
+ "columnsFrom": ["goal_id", "target_node_id"],
+ "columnsTo": ["goal_id", "id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "goal_edges_distinct_nodes": {
+ "name": "goal_edges_distinct_nodes",
+ "value": "\"goal_edges\".\"source_node_id\" <> \"goal_edges\".\"target_node_id\""
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.goal_events": {
+ "name": "goal_events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "event_type": {
+ "name": "event_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "entity_type": {
+ "name": "entity_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "entity_id": {
+ "name": "entity_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "actor_type": {
+ "name": "actor_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "actor_id": {
+ "name": "actor_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "operation_id": {
+ "name": "operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "goal_events_goal_id_created_at_idx": {
+ "name": "goal_events_goal_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "goal_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goal_events_entity_idx": {
+ "name": "goal_events_entity_idx",
+ "columns": [
+ {
+ "expression": "entity_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "entity_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goal_events_task_id_idx": {
+ "name": "goal_events_task_id_idx",
+ "columns": [
+ {
+ "expression": "task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goal_events_operation_id_idx": {
+ "name": "goal_events_operation_id_idx",
+ "columns": [
+ {
+ "expression": "operation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "goal_events_goal_id_goals_id_fk": {
+ "name": "goal_events_goal_id_goals_id_fk",
+ "tableFrom": "goal_events",
+ "tableTo": "goals",
+ "columnsFrom": ["goal_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "goal_events_task_id_tasks_id_fk": {
+ "name": "goal_events_task_id_tasks_id_fk",
+ "tableFrom": "goal_events",
+ "tableTo": "tasks",
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goal_node_decisions": {
+ "name": "goal_node_decisions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "node_id": {
+ "name": "node_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "authority": {
+ "name": "authority",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "question": {
+ "name": "question",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "options": {
+ "name": "options",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "recommended_option_id": {
+ "name": "recommended_option_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requested_user_id": {
+ "name": "requested_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requested_project_role": {
+ "name": "requested_project_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolved_option_id": {
+ "name": "resolved_option_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolution": {
+ "name": "resolution",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolved_by_user_id": {
+ "name": "resolved_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolved_by_agent_id": {
+ "name": "resolved_by_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "canceled_at": {
+ "name": "canceled_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "goal_node_decisions_node_id_unique": {
+ "name": "goal_node_decisions_node_id_unique",
+ "columns": [
+ {
+ "expression": "node_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goal_node_decisions_status_idx": {
+ "name": "goal_node_decisions_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goal_node_decisions_requested_user_id_status_idx": {
+ "name": "goal_node_decisions_requested_user_id_status_idx",
+ "columns": [
+ {
+ "expression": "requested_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "goal_node_decisions_node_id_goal_nodes_id_fk": {
+ "name": "goal_node_decisions_node_id_goal_nodes_id_fk",
+ "tableFrom": "goal_node_decisions",
+ "tableTo": "goal_nodes",
+ "columnsFrom": ["node_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "goal_node_decisions_requested_user_id_users_id_fk": {
+ "name": "goal_node_decisions_requested_user_id_users_id_fk",
+ "tableFrom": "goal_node_decisions",
+ "tableTo": "users",
+ "columnsFrom": ["requested_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "goal_node_decisions_resolved_by_user_id_users_id_fk": {
+ "name": "goal_node_decisions_resolved_by_user_id_users_id_fk",
+ "tableFrom": "goal_node_decisions",
+ "tableTo": "users",
+ "columnsFrom": ["resolved_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "goal_node_decisions_resolved_by_agent_id_agents_id_fk": {
+ "name": "goal_node_decisions_resolved_by_agent_id_agents_id_fk",
+ "tableFrom": "goal_node_decisions",
+ "tableTo": "agents",
+ "columnsFrom": ["resolved_by_agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goal_node_work_versions": {
+ "name": "goal_node_work_versions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "node_id": {
+ "name": "node_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "work_version_id": {
+ "name": "work_version_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "relation": {
+ "name": "relation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "goal_node_work_versions_node_version_relation_unique": {
+ "name": "goal_node_work_versions_node_version_relation_unique",
+ "columns": [
+ {
+ "expression": "node_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "work_version_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "relation",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goal_node_work_versions_work_version_id_idx": {
+ "name": "goal_node_work_versions_work_version_id_idx",
+ "columns": [
+ {
+ "expression": "work_version_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "goal_node_work_versions_node_id_goal_nodes_id_fk": {
+ "name": "goal_node_work_versions_node_id_goal_nodes_id_fk",
+ "tableFrom": "goal_node_work_versions",
+ "tableTo": "goal_nodes",
+ "columnsFrom": ["node_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "goal_node_work_versions_work_version_id_work_versions_id_fk": {
+ "name": "goal_node_work_versions_work_version_id_work_versions_id_fk",
+ "tableFrom": "goal_node_work_versions",
+ "tableTo": "work_versions",
+ "columnsFrom": ["work_version_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goal_nodes": {
+ "name": "goal_nodes",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'proposed'"
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "priority": {
+ "name": "priority",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "confidence": {
+ "name": "confidence",
+ "type": "numeric(4, 3)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_agent_id": {
+ "name": "created_by_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "goal_nodes_goal_id_status_idx": {
+ "name": "goal_nodes_goal_id_status_idx",
+ "columns": [
+ {
+ "expression": "goal_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goal_nodes_goal_id_kind_idx": {
+ "name": "goal_nodes_goal_id_kind_idx",
+ "columns": [
+ {
+ "expression": "goal_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "kind",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goal_nodes_task_id_unique": {
+ "name": "goal_nodes_task_id_unique",
+ "columns": [
+ {
+ "expression": "task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"goal_nodes\".\"task_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "goal_nodes_goal_id_goals_id_fk": {
+ "name": "goal_nodes_goal_id_goals_id_fk",
+ "tableFrom": "goal_nodes",
+ "tableTo": "goals",
+ "columnsFrom": ["goal_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "goal_nodes_task_id_tasks_id_fk": {
+ "name": "goal_nodes_task_id_tasks_id_fk",
+ "tableFrom": "goal_nodes",
+ "tableTo": "tasks",
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "goal_nodes_created_by_user_id_users_id_fk": {
+ "name": "goal_nodes_created_by_user_id_users_id_fk",
+ "tableFrom": "goal_nodes",
+ "tableTo": "users",
+ "columnsFrom": ["created_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "goal_nodes_created_by_agent_id_agents_id_fk": {
+ "name": "goal_nodes_created_by_agent_id_agents_id_fk",
+ "tableFrom": "goal_nodes",
+ "tableTo": "agents",
+ "columnsFrom": ["created_by_agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "goal_nodes_goal_id_id_unique": {
+ "name": "goal_nodes_goal_id_id_unique",
+ "nullsNotDistinct": false,
+ "columns": ["goal_id", "id"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "goal_nodes_task_requires_work_kind": {
+ "name": "goal_nodes_task_requires_work_kind",
+ "value": "\"goal_nodes\".\"task_id\" IS NULL OR \"goal_nodes\".\"kind\" = 'work'"
+ },
+ "goal_nodes_confidence_range": {
+ "name": "goal_nodes_confidence_range",
+ "value": "\"goal_nodes\".\"confidence\" IS NULL OR (\"goal_nodes\".\"confidence\" >= 0 AND \"goal_nodes\".\"confidence\" <= 1)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.goal_traces": {
+ "name": "goal_traces",
+ "schema": "",
+ "columns": {
+ "goal_id": {
+ "name": "goal_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "trace_s3_key": {
+ "name": "trace_s3_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "final_status": {
+ "name": "final_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "advances_total": {
+ "name": "advances_total",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ticks_total": {
+ "name": "ticks_total",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "advances_by_trigger": {
+ "name": "advances_by_trigger",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "advances_by_outcome": {
+ "name": "advances_by_outcome",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ticks_by_branch": {
+ "name": "ticks_by_branch",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "total_cost": {
+ "name": "total_cost",
+ "type": "numeric(20, 6)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "work_operations": {
+ "name": "work_operations",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "nodes_total": {
+ "name": "nodes_total",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "work_resolved": {
+ "name": "work_resolved",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "work_retired": {
+ "name": "work_retired",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "findings_total": {
+ "name": "findings_total",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "gates_opened": {
+ "name": "gates_opened",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "gates_resolved": {
+ "name": "gates_resolved",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "human_waiting_ms": {
+ "name": "human_waiting_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "goal_traces_started_at_idx": {
+ "name": "goal_traces_started_at_idx",
+ "columns": [
+ {
+ "expression": "started_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "goal_traces_final_status_idx": {
+ "name": "goal_traces_final_status_idx",
+ "columns": [
+ {
+ "expression": "final_status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "goal_traces_goal_id_goals_id_fk": {
+ "name": "goal_traces_goal_id_goals_id_fk",
+ "tableFrom": "goal_traces",
+ "tableTo": "goals",
+ "columnsFrom": ["goal_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.llm_generation_tracing": {
+ "name": "llm_generation_tracing",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "scenario": {
+ "name": "scenario",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prompt_version": {
+ "name": "prompt_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prompt_hash": {
+ "name": "prompt_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "schema_name": {
+ "name": "schema_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_tracing_id": {
+ "name": "parent_tracing_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "success": {
+ "name": "success",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "error_code": {
+ "name": "error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error_detail": {
+ "name": "error_detail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "validation_failed": {
+ "name": "validation_failed",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "input_hash": {
+ "name": "input_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "input_hint": {
+ "name": "input_hint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "latency_ms": {
+ "name": "latency_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "numeric(12, 8)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "storage_key": {
+ "name": "storage_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "feedback_signal": {
+ "name": "feedback_signal",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "feedback_score": {
+ "name": "feedback_score",
+ "type": "numeric(3, 2)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "feedback_source": {
+ "name": "feedback_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "feedback_data": {
+ "name": "feedback_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "feedback_updated_at": {
+ "name": "feedback_updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trace_id": {
+ "name": "trace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "span_id": {
+ "name": "span_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "llm_generation_tracing_scenario_idx": {
+ "name": "llm_generation_tracing_scenario_idx",
+ "columns": [
+ {
+ "expression": "scenario",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_prompt_version_idx": {
+ "name": "llm_generation_tracing_prompt_version_idx",
+ "columns": [
+ {
+ "expression": "prompt_version",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_user_id_idx": {
+ "name": "llm_generation_tracing_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_agent_id_idx": {
+ "name": "llm_generation_tracing_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_topic_id_idx": {
+ "name": "llm_generation_tracing_topic_id_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_workspace_id_idx": {
+ "name": "llm_generation_tracing_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_provider_idx": {
+ "name": "llm_generation_tracing_provider_idx",
+ "columns": [
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_model_idx": {
+ "name": "llm_generation_tracing_model_idx",
+ "columns": [
+ {
+ "expression": "model",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_success_idx": {
+ "name": "llm_generation_tracing_success_idx",
+ "columns": [
+ {
+ "expression": "success",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_error_code_idx": {
+ "name": "llm_generation_tracing_error_code_idx",
+ "columns": [
+ {
+ "expression": "error_code",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_validation_failed_idx": {
+ "name": "llm_generation_tracing_validation_failed_idx",
+ "columns": [
+ {
+ "expression": "validation_failed",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_feedback_signal_idx": {
+ "name": "llm_generation_tracing_feedback_signal_idx",
+ "columns": [
+ {
+ "expression": "feedback_signal",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "llm_generation_tracing_created_at_idx": {
+ "name": "llm_generation_tracing_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "llm_generation_tracing_workspace_id_workspaces_id_fk": {
+ "name": "llm_generation_tracing_workspace_id_workspaces_id_fk",
+ "tableFrom": "llm_generation_tracing",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.message_chunks": {
+ "name": "message_chunks",
+ "schema": "",
+ "columns": {
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "chunk_id": {
+ "name": "chunk_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "message_chunks_user_id_idx": {
+ "name": "message_chunks_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_chunks_message_id_idx": {
+ "name": "message_chunks_message_id_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_chunks_workspace_id_idx": {
+ "name": "message_chunks_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "message_chunks_message_id_messages_id_fk": {
+ "name": "message_chunks_message_id_messages_id_fk",
+ "tableFrom": "message_chunks",
+ "tableTo": "messages",
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_chunks_chunk_id_chunks_id_fk": {
+ "name": "message_chunks_chunk_id_chunks_id_fk",
+ "tableFrom": "message_chunks",
+ "tableTo": "chunks",
+ "columnsFrom": ["chunk_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_chunks_user_id_users_id_fk": {
+ "name": "message_chunks_user_id_users_id_fk",
+ "tableFrom": "message_chunks",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_chunks_workspace_id_workspaces_id_fk": {
+ "name": "message_chunks_workspace_id_workspaces_id_fk",
+ "tableFrom": "message_chunks",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "message_chunks_chunk_id_message_id_pk": {
+ "name": "message_chunks_chunk_id_message_id_pk",
+ "columns": ["chunk_id", "message_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.message_groups": {
+ "name": "message_groups",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_group_id": {
+ "name": "parent_group_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_message_id": {
+ "name": "parent_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "editor_data": {
+ "name": "editor_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "message_groups_client_id_user_id_unique": {
+ "name": "message_groups_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_groups_user_id_idx": {
+ "name": "message_groups_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_groups_topic_id_idx": {
+ "name": "message_groups_topic_id_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_groups_type_idx": {
+ "name": "message_groups_type_idx",
+ "columns": [
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_groups_parent_group_id_idx": {
+ "name": "message_groups_parent_group_id_idx",
+ "columns": [
+ {
+ "expression": "parent_group_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_groups_parent_message_id_idx": {
+ "name": "message_groups_parent_message_id_idx",
+ "columns": [
+ {
+ "expression": "parent_message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_groups_workspace_id_idx": {
+ "name": "message_groups_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "message_groups_topic_id_topics_id_fk": {
+ "name": "message_groups_topic_id_topics_id_fk",
+ "tableFrom": "message_groups",
+ "tableTo": "topics",
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_groups_user_id_users_id_fk": {
+ "name": "message_groups_user_id_users_id_fk",
+ "tableFrom": "message_groups",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_groups_workspace_id_workspaces_id_fk": {
+ "name": "message_groups_workspace_id_workspaces_id_fk",
+ "tableFrom": "message_groups",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_groups_parent_group_id_message_groups_id_fk": {
+ "name": "message_groups_parent_group_id_message_groups_id_fk",
+ "tableFrom": "message_groups",
+ "tableTo": "message_groups",
+ "columnsFrom": ["parent_group_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_groups_parent_message_id_messages_id_fk": {
+ "name": "message_groups_parent_message_id_messages_id_fk",
+ "tableFrom": "message_groups",
+ "tableTo": "messages",
+ "columnsFrom": ["parent_message_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.message_plugins": {
+ "name": "message_plugins",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "tool_call_id": {
+ "name": "tool_call_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'default'"
+ },
+ "intervention": {
+ "name": "intervention",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "api_name": {
+ "name": "api_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "arguments": {
+ "name": "arguments",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "state": {
+ "name": "state",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "message_plugins_client_id_user_id_unique": {
+ "name": "message_plugins_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_plugins_user_id_idx": {
+ "name": "message_plugins_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_plugins_tool_call_id_idx": {
+ "name": "message_plugins_tool_call_id_idx",
+ "columns": [
+ {
+ "expression": "tool_call_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_plugins_workspace_id_idx": {
+ "name": "message_plugins_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "message_plugins_id_messages_id_fk": {
+ "name": "message_plugins_id_messages_id_fk",
+ "tableFrom": "message_plugins",
+ "tableTo": "messages",
+ "columnsFrom": ["id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_plugins_user_id_users_id_fk": {
+ "name": "message_plugins_user_id_users_id_fk",
+ "tableFrom": "message_plugins",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_plugins_workspace_id_workspaces_id_fk": {
+ "name": "message_plugins_workspace_id_workspaces_id_fk",
+ "tableFrom": "message_plugins",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.message_queries": {
+ "name": "message_queries",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "rewrite_query": {
+ "name": "rewrite_query",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_query": {
+ "name": "user_query",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "embeddings_id": {
+ "name": "embeddings_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "message_queries_client_id_user_id_unique": {
+ "name": "message_queries_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_queries_user_id_idx": {
+ "name": "message_queries_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_queries_message_id_idx": {
+ "name": "message_queries_message_id_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_queries_embeddings_id_idx": {
+ "name": "message_queries_embeddings_id_idx",
+ "columns": [
+ {
+ "expression": "embeddings_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_queries_workspace_id_idx": {
+ "name": "message_queries_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "message_queries_message_id_messages_id_fk": {
+ "name": "message_queries_message_id_messages_id_fk",
+ "tableFrom": "message_queries",
+ "tableTo": "messages",
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_queries_user_id_users_id_fk": {
+ "name": "message_queries_user_id_users_id_fk",
+ "tableFrom": "message_queries",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_queries_workspace_id_workspaces_id_fk": {
+ "name": "message_queries_workspace_id_workspaces_id_fk",
+ "tableFrom": "message_queries",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_queries_embeddings_id_embeddings_id_fk": {
+ "name": "message_queries_embeddings_id_embeddings_id_fk",
+ "tableFrom": "message_queries",
+ "tableTo": "embeddings",
+ "columnsFrom": ["embeddings_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.message_query_chunks": {
+ "name": "message_query_chunks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "query_id": {
+ "name": "query_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "chunk_id": {
+ "name": "chunk_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "similarity": {
+ "name": "similarity",
+ "type": "numeric(6, 5)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "message_query_chunks_user_id_idx": {
+ "name": "message_query_chunks_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_query_chunks_message_id_idx": {
+ "name": "message_query_chunks_message_id_idx",
+ "columns": [
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_query_chunks_query_id_idx": {
+ "name": "message_query_chunks_query_id_idx",
+ "columns": [
+ {
+ "expression": "query_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_query_chunks_workspace_id_idx": {
+ "name": "message_query_chunks_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "message_query_chunks_id_messages_id_fk": {
+ "name": "message_query_chunks_id_messages_id_fk",
+ "tableFrom": "message_query_chunks",
+ "tableTo": "messages",
+ "columnsFrom": ["id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_query_chunks_query_id_message_queries_id_fk": {
+ "name": "message_query_chunks_query_id_message_queries_id_fk",
+ "tableFrom": "message_query_chunks",
+ "tableTo": "message_queries",
+ "columnsFrom": ["query_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_query_chunks_chunk_id_chunks_id_fk": {
+ "name": "message_query_chunks_chunk_id_chunks_id_fk",
+ "tableFrom": "message_query_chunks",
+ "tableTo": "chunks",
+ "columnsFrom": ["chunk_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_query_chunks_user_id_users_id_fk": {
+ "name": "message_query_chunks_user_id_users_id_fk",
+ "tableFrom": "message_query_chunks",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_query_chunks_workspace_id_workspaces_id_fk": {
+ "name": "message_query_chunks_workspace_id_workspaces_id_fk",
+ "tableFrom": "message_query_chunks",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "message_query_chunks_chunk_id_id_query_id_pk": {
+ "name": "message_query_chunks_chunk_id_id_query_id_pk",
+ "columns": ["chunk_id", "id", "query_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.message_tts": {
+ "name": "message_tts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "content_md5": {
+ "name": "content_md5",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_id": {
+ "name": "file_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "voice": {
+ "name": "voice",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "message_tts_client_id_user_id_unique": {
+ "name": "message_tts_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_tts_user_id_idx": {
+ "name": "message_tts_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_tts_workspace_id_idx": {
+ "name": "message_tts_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "message_tts_id_messages_id_fk": {
+ "name": "message_tts_id_messages_id_fk",
+ "tableFrom": "message_tts",
+ "tableTo": "messages",
+ "columnsFrom": ["id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_tts_file_id_files_id_fk": {
+ "name": "message_tts_file_id_files_id_fk",
+ "tableFrom": "message_tts",
+ "tableTo": "files",
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_tts_user_id_users_id_fk": {
+ "name": "message_tts_user_id_users_id_fk",
+ "tableFrom": "message_tts",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_tts_workspace_id_workspaces_id_fk": {
+ "name": "message_tts_workspace_id_workspaces_id_fk",
+ "tableFrom": "message_tts",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.message_translates": {
+ "name": "message_translates",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "from": {
+ "name": "from",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "to": {
+ "name": "to",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "message_translates_client_id_user_id_unique": {
+ "name": "message_translates_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_translates_user_id_idx": {
+ "name": "message_translates_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_translates_workspace_id_idx": {
+ "name": "message_translates_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "message_translates_id_messages_id_fk": {
+ "name": "message_translates_id_messages_id_fk",
+ "tableFrom": "message_translates",
+ "tableTo": "messages",
+ "columnsFrom": ["id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_translates_user_id_users_id_fk": {
+ "name": "message_translates_user_id_users_id_fk",
+ "tableFrom": "message_translates",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "message_translates_workspace_id_workspaces_id_fk": {
+ "name": "message_translates_workspace_id_workspaces_id_fk",
+ "tableFrom": "message_translates",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.messages": {
+ "name": "messages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "editor_data": {
+ "name": "editor_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reasoning": {
+ "name": "reasoning",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "search": {
+ "name": "search",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "usage": {
+ "name": "usage",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "favorite": {
+ "name": "favorite",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "error": {
+ "name": "error",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tools": {
+ "name": "tools",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trace_id": {
+ "name": "trace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "observation_id": {
+ "name": "observation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_id": {
+ "name": "parent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "quota_id": {
+ "name": "quota_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "target_id": {
+ "name": "target_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "message_group_id": {
+ "name": "message_group_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "messages_created_at_idx": {
+ "name": "messages_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_client_id_user_unique": {
+ "name": "message_client_id_user_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_topic_id_idx": {
+ "name": "messages_topic_id_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_topic_id_updated_at_idx": {
+ "name": "messages_topic_id_updated_at_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_parent_id_idx": {
+ "name": "messages_parent_id_idx",
+ "columns": [
+ {
+ "expression": "parent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_quota_id_idx": {
+ "name": "messages_quota_id_idx",
+ "columns": [
+ {
+ "expression": "quota_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_user_id_idx": {
+ "name": "messages_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_session_id_idx": {
+ "name": "messages_session_id_idx",
+ "columns": [
+ {
+ "expression": "session_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_thread_id_idx": {
+ "name": "messages_thread_id_idx",
+ "columns": [
+ {
+ "expression": "thread_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_agent_id_idx": {
+ "name": "messages_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_group_id_idx": {
+ "name": "messages_group_id_idx",
+ "columns": [
+ {
+ "expression": "group_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_message_group_id_idx": {
+ "name": "messages_message_group_id_idx",
+ "columns": [
+ {
+ "expression": "message_group_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_usage_cost_idx": {
+ "name": "messages_usage_cost_idx",
+ "columns": [
+ {
+ "expression": "((\"usage\"->>'cost')::numeric)",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_usage_total_tokens_idx": {
+ "name": "messages_usage_total_tokens_idx",
+ "columns": [
+ {
+ "expression": "((\"usage\"->>'totalTokens')::numeric)",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_workspace_id_idx": {
+ "name": "messages_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "messages_user_id_users_id_fk": {
+ "name": "messages_user_id_users_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messages_session_id_sessions_id_fk": {
+ "name": "messages_session_id_sessions_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "sessions",
+ "columnsFrom": ["session_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messages_topic_id_topics_id_fk": {
+ "name": "messages_topic_id_topics_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "topics",
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messages_thread_id_threads_id_fk": {
+ "name": "messages_thread_id_threads_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "threads",
+ "columnsFrom": ["thread_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messages_parent_id_messages_id_fk": {
+ "name": "messages_parent_id_messages_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "messages",
+ "columnsFrom": ["parent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "messages_quota_id_messages_id_fk": {
+ "name": "messages_quota_id_messages_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "messages",
+ "columnsFrom": ["quota_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "messages_agent_id_agents_id_fk": {
+ "name": "messages_agent_id_agents_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messages_group_id_chat_groups_id_fk": {
+ "name": "messages_group_id_chat_groups_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "chat_groups",
+ "columnsFrom": ["group_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "messages_message_group_id_message_groups_id_fk": {
+ "name": "messages_message_group_id_message_groups_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "message_groups",
+ "columnsFrom": ["message_group_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messages_workspace_id_workspaces_id_fk": {
+ "name": "messages_workspace_id_workspaces_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.messages_files": {
+ "name": "messages_files",
+ "schema": "",
+ "columns": {
+ "file_id": {
+ "name": "file_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "messages_files_user_id_idx": {
+ "name": "messages_files_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_files_message_id_idx": {
+ "name": "messages_files_message_id_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_files_workspace_id_idx": {
+ "name": "messages_files_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "messages_files_file_id_files_id_fk": {
+ "name": "messages_files_file_id_files_id_fk",
+ "tableFrom": "messages_files",
+ "tableTo": "files",
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messages_files_message_id_messages_id_fk": {
+ "name": "messages_files_message_id_messages_id_fk",
+ "tableFrom": "messages_files",
+ "tableTo": "messages",
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messages_files_user_id_users_id_fk": {
+ "name": "messages_files_user_id_users_id_fk",
+ "tableFrom": "messages_files",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messages_files_workspace_id_workspaces_id_fk": {
+ "name": "messages_files_workspace_id_workspaces_id_fk",
+ "tableFrom": "messages_files",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "messages_files_file_id_message_id_pk": {
+ "name": "messages_files_file_id_message_id_pk",
+ "columns": ["file_id", "message_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.messenger_account_links": {
+ "name": "messenger_account_links",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "platform": {
+ "name": "platform",
+ "type": "varchar(50)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tenant_id": {
+ "name": "tenant_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "platform_user_id": {
+ "name": "platform_user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "platform_username": {
+ "name": "platform_username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "application_id": {
+ "name": "application_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "credentials": {
+ "name": "credentials",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "active_agent_id": {
+ "name": "active_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "messenger_account_links_platform_tenant_user_unique": {
+ "name": "messenger_account_links_platform_tenant_user_unique",
+ "columns": [
+ {
+ "expression": "platform",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "tenant_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "platform_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messenger_account_links_user_platform_tenant_unique": {
+ "name": "messenger_account_links_user_platform_tenant_unique",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "platform",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "tenant_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messenger_account_links_platform_tenant_application_unique": {
+ "name": "messenger_account_links_platform_tenant_application_unique",
+ "columns": [
+ {
+ "expression": "platform",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "tenant_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "application_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"messenger_account_links\".\"application_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messenger_account_links_active_agent_idx": {
+ "name": "messenger_account_links_active_agent_idx",
+ "columns": [
+ {
+ "expression": "active_agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messenger_account_links_workspace_id_idx": {
+ "name": "messenger_account_links_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "messenger_account_links_user_id_users_id_fk": {
+ "name": "messenger_account_links_user_id_users_id_fk",
+ "tableFrom": "messenger_account_links",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messenger_account_links_workspace_id_workspaces_id_fk": {
+ "name": "messenger_account_links_workspace_id_workspaces_id_fk",
+ "tableFrom": "messenger_account_links",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messenger_account_links_active_agent_id_agents_id_fk": {
+ "name": "messenger_account_links_active_agent_id_agents_id_fk",
+ "tableFrom": "messenger_account_links",
+ "tableTo": "agents",
+ "columnsFrom": ["active_agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.messenger_installations": {
+ "name": "messenger_installations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "platform": {
+ "name": "platform",
+ "type": "varchar(50)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tenant_id": {
+ "name": "tenant_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "application_id": {
+ "name": "application_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "credentials": {
+ "name": "credentials",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "token_expires_at": {
+ "name": "token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "installed_by_user_id": {
+ "name": "installed_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "installed_by_platform_user_id": {
+ "name": "installed_by_platform_user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "messenger_installations_platform_app_tenant_unique": {
+ "name": "messenger_installations_platform_app_tenant_unique",
+ "columns": [
+ {
+ "expression": "platform",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "application_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "tenant_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messenger_installations_platform_tenant_idx": {
+ "name": "messenger_installations_platform_tenant_idx",
+ "columns": [
+ {
+ "expression": "platform",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "tenant_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messenger_installations_token_expires_at_idx": {
+ "name": "messenger_installations_token_expires_at_idx",
+ "columns": [
+ {
+ "expression": "token_expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "messenger_installations_installed_by_user_id_users_id_fk": {
+ "name": "messenger_installations_installed_by_user_id_users_id_fk",
+ "tableFrom": "messenger_installations",
+ "tableTo": "users",
+ "columnsFrom": ["installed_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.nextauth_accounts": {
+ "name": "nextauth_accounts",
+ "schema": "",
+ "columns": {
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "providerAccountId": {
+ "name": "providerAccountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_state": {
+ "name": "session_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "token_type": {
+ "name": "token_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "nextauth_accounts_user_id_idx": {
+ "name": "nextauth_accounts_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "nextauth_accounts_user_id_users_id_fk": {
+ "name": "nextauth_accounts_user_id_users_id_fk",
+ "tableFrom": "nextauth_accounts",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "nextauth_accounts_provider_providerAccountId_pk": {
+ "name": "nextauth_accounts_provider_providerAccountId_pk",
+ "columns": ["provider", "providerAccountId"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.nextauth_authenticators": {
+ "name": "nextauth_authenticators",
+ "schema": "",
+ "columns": {
+ "counter": {
+ "name": "counter",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credentialBackedUp": {
+ "name": "credentialBackedUp",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credentialDeviceType": {
+ "name": "credentialDeviceType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credentialID": {
+ "name": "credentialID",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credentialPublicKey": {
+ "name": "credentialPublicKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "providerAccountId": {
+ "name": "providerAccountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "transports": {
+ "name": "transports",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "nextauth_authenticators_user_id_users_id_fk": {
+ "name": "nextauth_authenticators_user_id_users_id_fk",
+ "tableFrom": "nextauth_authenticators",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "nextauth_authenticators_user_id_credentialID_pk": {
+ "name": "nextauth_authenticators_user_id_credentialID_pk",
+ "columns": ["user_id", "credentialID"]
+ }
+ },
+ "uniqueConstraints": {
+ "nextauth_authenticators_credentialID_unique": {
+ "name": "nextauth_authenticators_credentialID_unique",
+ "nullsNotDistinct": false,
+ "columns": ["credentialID"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.nextauth_sessions": {
+ "name": "nextauth_sessions",
+ "schema": "",
+ "columns": {
+ "expires": {
+ "name": "expires",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sessionToken": {
+ "name": "sessionToken",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "nextauth_sessions_user_id_idx": {
+ "name": "nextauth_sessions_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "nextauth_sessions_user_id_users_id_fk": {
+ "name": "nextauth_sessions_user_id_users_id_fk",
+ "tableFrom": "nextauth_sessions",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.nextauth_verificationtokens": {
+ "name": "nextauth_verificationtokens",
+ "schema": "",
+ "columns": {
+ "expires": {
+ "name": "expires",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "nextauth_verificationtokens_identifier_token_pk": {
+ "name": "nextauth_verificationtokens_identifier_token_pk",
+ "columns": ["identifier", "token"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.notification_deliveries": {
+ "name": "notification_deliveries",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "notification_id": {
+ "name": "notification_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_message_id": {
+ "name": "provider_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "failed_reason": {
+ "name": "failed_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "idx_deliveries_notification": {
+ "name": "idx_deliveries_notification",
+ "columns": [
+ {
+ "expression": "notification_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_deliveries_channel": {
+ "name": "idx_deliveries_channel",
+ "columns": [
+ {
+ "expression": "channel",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_deliveries_status": {
+ "name": "idx_deliveries_status",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "notification_deliveries_notification_id_notifications_id_fk": {
+ "name": "notification_deliveries_notification_id_notifications_id_fk",
+ "tableFrom": "notification_deliveries",
+ "tableTo": "notifications",
+ "columnsFrom": ["notification_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.notifications": {
+ "name": "notifications",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "category": {
+ "name": "category",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "context": {
+ "name": "context",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "action_url": {
+ "name": "action_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_read": {
+ "name": "is_read",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "is_archived": {
+ "name": "is_archived",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "idx_notifications_user": {
+ "name": "idx_notifications_user",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_notifications_user_active": {
+ "name": "idx_notifications_user_active",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"notifications\".\"is_archived\" = false",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_notifications_user_unread": {
+ "name": "idx_notifications_user_unread",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"notifications\".\"is_read\" = false AND \"notifications\".\"is_archived\" = false",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_notifications_dedupe": {
+ "name": "idx_notifications_dedupe",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "dedupe_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_notifications_user_workspace": {
+ "name": "idx_notifications_user_workspace",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_notifications_workspace_id": {
+ "name": "idx_notifications_workspace_id",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_notifications_archived_cleanup": {
+ "name": "idx_notifications_archived_cleanup",
+ "columns": [
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"notifications\".\"is_archived\" = true",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "notifications_user_id_users_id_fk": {
+ "name": "notifications_user_id_users_id_fk",
+ "tableFrom": "notifications",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notifications_workspace_id_workspaces_id_fk": {
+ "name": "notifications_workspace_id_workspaces_id_fk",
+ "tableFrom": "notifications",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_handoffs": {
+ "name": "oauth_handoffs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "client": {
+ "name": "client",
+ "type": "varchar(50)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oidc_access_tokens": {
+ "name": "oidc_access_tokens",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consumed_at": {
+ "name": "consumed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "grant_id": {
+ "name": "grant_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "oidc_access_tokens_user_id_idx": {
+ "name": "oidc_access_tokens_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oidc_access_tokens_user_id_users_id_fk": {
+ "name": "oidc_access_tokens_user_id_users_id_fk",
+ "tableFrom": "oidc_access_tokens",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oidc_authorization_codes": {
+ "name": "oidc_authorization_codes",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consumed_at": {
+ "name": "consumed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "grant_id": {
+ "name": "grant_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "oidc_authorization_codes_user_id_idx": {
+ "name": "oidc_authorization_codes_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oidc_authorization_codes_user_id_users_id_fk": {
+ "name": "oidc_authorization_codes_user_id_users_id_fk",
+ "tableFrom": "oidc_authorization_codes",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oidc_clients": {
+ "name": "oidc_clients",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_secret": {
+ "name": "client_secret",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redirect_uris": {
+ "name": "redirect_uris",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "grants": {
+ "name": "grants",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "response_types": {
+ "name": "response_types",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token_endpoint_auth_method": {
+ "name": "token_endpoint_auth_method",
+ "type": "varchar(20)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "application_type": {
+ "name": "application_type",
+ "type": "varchar(20)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_uri": {
+ "name": "client_uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "logo_uri": {
+ "name": "logo_uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "policy_uri": {
+ "name": "policy_uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tos_uri": {
+ "name": "tos_uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_first_party": {
+ "name": "is_first_party",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "oidc_clients_user_id_idx": {
+ "name": "oidc_clients_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oidc_clients_workspace_id_idx": {
+ "name": "oidc_clients_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oidc_clients_user_id_users_id_fk": {
+ "name": "oidc_clients_user_id_users_id_fk",
+ "tableFrom": "oidc_clients",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oidc_clients_workspace_id_workspaces_id_fk": {
+ "name": "oidc_clients_workspace_id_workspaces_id_fk",
+ "tableFrom": "oidc_clients",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oidc_consents": {
+ "name": "oidc_consents",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oidc_consents_user_id_users_id_fk": {
+ "name": "oidc_consents_user_id_users_id_fk",
+ "tableFrom": "oidc_consents",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oidc_consents_client_id_oidc_clients_id_fk": {
+ "name": "oidc_consents_client_id_oidc_clients_id_fk",
+ "tableFrom": "oidc_consents",
+ "tableTo": "oidc_clients",
+ "columnsFrom": ["client_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "oidc_consents_user_id_client_id_pk": {
+ "name": "oidc_consents_user_id_client_id_pk",
+ "columns": ["user_id", "client_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oidc_device_codes": {
+ "name": "oidc_device_codes",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consumed_at": {
+ "name": "consumed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "grant_id": {
+ "name": "grant_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_code": {
+ "name": "user_code",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "oidc_device_codes_user_id_idx": {
+ "name": "oidc_device_codes_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oidc_device_codes_user_id_users_id_fk": {
+ "name": "oidc_device_codes_user_id_users_id_fk",
+ "tableFrom": "oidc_device_codes",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oidc_grants": {
+ "name": "oidc_grants",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consumed_at": {
+ "name": "consumed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "oidc_grants_user_id_idx": {
+ "name": "oidc_grants_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oidc_grants_user_id_users_id_fk": {
+ "name": "oidc_grants_user_id_users_id_fk",
+ "tableFrom": "oidc_grants",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oidc_interactions": {
+ "name": "oidc_interactions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oidc_refresh_tokens": {
+ "name": "oidc_refresh_tokens",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consumed_at": {
+ "name": "consumed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "grant_id": {
+ "name": "grant_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "oidc_refresh_tokens_user_id_idx": {
+ "name": "oidc_refresh_tokens_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oidc_refresh_tokens_user_id_users_id_fk": {
+ "name": "oidc_refresh_tokens_user_id_users_id_fk",
+ "tableFrom": "oidc_refresh_tokens",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oidc_sessions": {
+ "name": "oidc_sessions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "oidc_sessions_user_id_idx": {
+ "name": "oidc_sessions_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oidc_sessions_user_id_users_id_fk": {
+ "name": "oidc_sessions_user_id_users_id_fk",
+ "tableFrom": "oidc_sessions",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_agents": {
+ "name": "project_agents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "added_by_user_id": {
+ "name": "added_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "responsibility": {
+ "name": "responsibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_agents_project_id_agent_id_unique": {
+ "name": "project_agents_project_id_agent_id_unique",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_agents_project_id_sort_order_idx": {
+ "name": "project_agents_project_id_sort_order_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "sort_order",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_agents_agent_id_idx": {
+ "name": "project_agents_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_agents_workspace_id_idx": {
+ "name": "project_agents_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_agents_project_id_projects_id_fk": {
+ "name": "project_agents_project_id_projects_id_fk",
+ "tableFrom": "project_agents",
+ "tableTo": "projects",
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_agents_agent_id_agents_id_fk": {
+ "name": "project_agents_agent_id_agents_id_fk",
+ "tableFrom": "project_agents",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_agents_added_by_user_id_users_id_fk": {
+ "name": "project_agents_added_by_user_id_users_id_fk",
+ "tableFrom": "project_agents",
+ "tableTo": "users",
+ "columnsFrom": ["added_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_agents_workspace_id_workspaces_id_fk": {
+ "name": "project_agents_workspace_id_workspaces_id_fk",
+ "tableFrom": "project_agents",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_chat_groups": {
+ "name": "project_chat_groups",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "chat_group_id": {
+ "name": "chat_group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "added_by_user_id": {
+ "name": "added_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "responsibility": {
+ "name": "responsibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_chat_groups_project_id_chat_group_id_unique": {
+ "name": "project_chat_groups_project_id_chat_group_id_unique",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "chat_group_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_chat_groups_project_id_sort_order_idx": {
+ "name": "project_chat_groups_project_id_sort_order_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "sort_order",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_chat_groups_chat_group_id_idx": {
+ "name": "project_chat_groups_chat_group_id_idx",
+ "columns": [
+ {
+ "expression": "chat_group_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_chat_groups_workspace_id_idx": {
+ "name": "project_chat_groups_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_chat_groups_project_id_projects_id_fk": {
+ "name": "project_chat_groups_project_id_projects_id_fk",
+ "tableFrom": "project_chat_groups",
+ "tableTo": "projects",
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_chat_groups_chat_group_id_chat_groups_id_fk": {
+ "name": "project_chat_groups_chat_group_id_chat_groups_id_fk",
+ "tableFrom": "project_chat_groups",
+ "tableTo": "chat_groups",
+ "columnsFrom": ["chat_group_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_chat_groups_added_by_user_id_users_id_fk": {
+ "name": "project_chat_groups_added_by_user_id_users_id_fk",
+ "tableFrom": "project_chat_groups",
+ "tableTo": "users",
+ "columnsFrom": ["added_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_chat_groups_workspace_id_workspaces_id_fk": {
+ "name": "project_chat_groups_workspace_id_workspaces_id_fk",
+ "tableFrom": "project_chat_groups",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_completion_reviews": {
+ "name": "project_completion_reviews",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reviewer_user_id": {
+ "name": "reviewer_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "round": {
+ "name": "round",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "comment": {
+ "name": "comment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_completion_reviews_project_id_round_unique": {
+ "name": "project_completion_reviews_project_id_round_unique",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "round",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_completion_reviews_project_id_created_at_idx": {
+ "name": "project_completion_reviews_project_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_completion_reviews_reviewer_user_id_idx": {
+ "name": "project_completion_reviews_reviewer_user_id_idx",
+ "columns": [
+ {
+ "expression": "reviewer_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_completion_reviews_workspace_id_idx": {
+ "name": "project_completion_reviews_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_completion_reviews_project_id_projects_id_fk": {
+ "name": "project_completion_reviews_project_id_projects_id_fk",
+ "tableFrom": "project_completion_reviews",
+ "tableTo": "projects",
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_completion_reviews_reviewer_user_id_users_id_fk": {
+ "name": "project_completion_reviews_reviewer_user_id_users_id_fk",
+ "tableFrom": "project_completion_reviews",
+ "tableTo": "users",
+ "columnsFrom": ["reviewer_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_completion_reviews_workspace_id_workspaces_id_fk": {
+ "name": "project_completion_reviews_workspace_id_workspaces_id_fk",
+ "tableFrom": "project_completion_reviews",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "project_completion_reviews_round_positive": {
+ "name": "project_completion_reviews_round_positive",
+ "value": "\"project_completion_reviews\".\"round\" > 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.project_knowledge_bases": {
+ "name": "project_knowledge_bases",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "knowledge_base_id": {
+ "name": "knowledge_base_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "added_by_user_id": {
+ "name": "added_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_knowledge_bases_project_id_knowledge_base_id_unique": {
+ "name": "project_knowledge_bases_project_id_knowledge_base_id_unique",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "knowledge_base_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_knowledge_bases_project_id_sort_order_idx": {
+ "name": "project_knowledge_bases_project_id_sort_order_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "sort_order",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_knowledge_bases_knowledge_base_id_idx": {
+ "name": "project_knowledge_bases_knowledge_base_id_idx",
+ "columns": [
+ {
+ "expression": "knowledge_base_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_knowledge_bases_workspace_id_idx": {
+ "name": "project_knowledge_bases_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_knowledge_bases_project_id_projects_id_fk": {
+ "name": "project_knowledge_bases_project_id_projects_id_fk",
+ "tableFrom": "project_knowledge_bases",
+ "tableTo": "projects",
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_knowledge_bases_knowledge_base_id_knowledge_bases_id_fk": {
+ "name": "project_knowledge_bases_knowledge_base_id_knowledge_bases_id_fk",
+ "tableFrom": "project_knowledge_bases",
+ "tableTo": "knowledge_bases",
+ "columnsFrom": ["knowledge_base_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_knowledge_bases_added_by_user_id_users_id_fk": {
+ "name": "project_knowledge_bases_added_by_user_id_users_id_fk",
+ "tableFrom": "project_knowledge_bases",
+ "tableTo": "users",
+ "columnsFrom": ["added_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_knowledge_bases_workspace_id_workspaces_id_fk": {
+ "name": "project_knowledge_bases_workspace_id_workspaces_id_fk",
+ "tableFrom": "project_knowledge_bases",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_works": {
+ "name": "project_works",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "work_id": {
+ "name": "work_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "added_by_user_id": {
+ "name": "added_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_works_project_id_work_id_unique": {
+ "name": "project_works_project_id_work_id_unique",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "work_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_works_project_id_sort_order_idx": {
+ "name": "project_works_project_id_sort_order_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "sort_order",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_works_work_id_idx": {
+ "name": "project_works_work_id_idx",
+ "columns": [
+ {
+ "expression": "work_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_works_workspace_id_idx": {
+ "name": "project_works_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_works_project_id_projects_id_fk": {
+ "name": "project_works_project_id_projects_id_fk",
+ "tableFrom": "project_works",
+ "tableTo": "projects",
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_works_work_id_works_id_fk": {
+ "name": "project_works_work_id_works_id_fk",
+ "tableFrom": "project_works",
+ "tableTo": "works",
+ "columnsFrom": ["work_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_works_added_by_user_id_users_id_fk": {
+ "name": "project_works_added_by_user_id_users_id_fk",
+ "tableFrom": "project_works",
+ "tableTo": "users",
+ "columnsFrom": ["added_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_works_workspace_id_workspaces_id_fk": {
+ "name": "project_works_workspace_id_workspaces_id_fk",
+ "tableFrom": "project_works",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.projects": {
+ "name": "projects",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "varchar(100)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "varchar(6)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "avatar": {
+ "name": "avatar",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "coordinator_agent_id": {
+ "name": "coordinator_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'backlog'"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "completed_review_id": {
+ "name": "completed_review_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "projects_slug_user_id_unique": {
+ "name": "projects_slug_user_id_unique",
+ "columns": [
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"projects\".\"workspace_id\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "projects_slug_workspace_id_unique": {
+ "name": "projects_slug_workspace_id_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"projects\".\"workspace_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "projects_identifier_user_id_unique": {
+ "name": "projects_identifier_user_id_unique",
+ "columns": [
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"projects\".\"workspace_id\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "projects_identifier_workspace_id_unique": {
+ "name": "projects_identifier_workspace_id_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"projects\".\"workspace_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "projects_user_id_idx": {
+ "name": "projects_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "projects_workspace_id_idx": {
+ "name": "projects_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "projects_workspace_visibility_idx": {
+ "name": "projects_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "projects_status_updated_at_idx": {
+ "name": "projects_status_updated_at_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "projects_coordinator_agent_id_unique": {
+ "name": "projects_coordinator_agent_id_unique",
+ "columns": [
+ {
+ "expression": "coordinator_agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "projects_coordinator_agent_id_agents_id_fk": {
+ "name": "projects_coordinator_agent_id_agents_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "agents",
+ "columnsFrom": ["coordinator_agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "restrict",
+ "onUpdate": "no action"
+ },
+ "projects_user_id_users_id_fk": {
+ "name": "projects_user_id_users_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "projects_workspace_id_workspaces_id_fk": {
+ "name": "projects_workspace_id_workspaces_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "projects_completed_requires_human_review": {
+ "name": "projects_completed_requires_human_review",
+ "value": "\"projects\".\"status\" <> 'completed' OR (\"projects\".\"completed_review_id\" IS NOT NULL AND \"projects\".\"completed_at\" IS NOT NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.push_live_activities": {
+ "name": "push_live_activities",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "device_id": {
+ "name": "device_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "activity_key": {
+ "name": "activity_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "operation_id": {
+ "name": "operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "activity_id": {
+ "name": "activity_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "push_token": {
+ "name": "push_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "apns_environment": {
+ "name": "apns_environment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "idx_push_live_activities_user_device_activity": {
+ "name": "idx_push_live_activities_user_device_activity",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "device_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "activity_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_push_live_activities_user_activity": {
+ "name": "idx_push_live_activities_user_activity",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "activity_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_push_live_activities_user_operation": {
+ "name": "idx_push_live_activities_user_operation",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "operation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_push_live_activities_last_seen": {
+ "name": "idx_push_live_activities_last_seen",
+ "columns": [
+ {
+ "expression": "last_seen_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "push_live_activities_user_id_users_id_fk": {
+ "name": "push_live_activities_user_id_users_id_fk",
+ "tableFrom": "push_live_activities",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "push_live_activities_apns_environment_check": {
+ "name": "push_live_activities_apns_environment_check",
+ "value": "\"push_live_activities\".\"apns_environment\" IN ('sandbox', 'production')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.push_tokens": {
+ "name": "push_tokens",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expo_token": {
+ "name": "expo_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "device_id": {
+ "name": "device_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "platform": {
+ "name": "platform",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "apns_environment": {
+ "name": "apns_environment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "app_version": {
+ "name": "app_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "locale": {
+ "name": "locale",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "live_activity_push_to_start_token": {
+ "name": "live_activity_push_to_start_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "idx_push_tokens_user_device": {
+ "name": "idx_push_tokens_user_device",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "device_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_push_tokens_user": {
+ "name": "idx_push_tokens_user",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_push_tokens_last_seen": {
+ "name": "idx_push_tokens_last_seen",
+ "columns": [
+ {
+ "expression": "last_seen_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "push_tokens_user_id_users_id_fk": {
+ "name": "push_tokens_user_id_users_id_fk",
+ "tableFrom": "push_tokens",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "push_tokens_apns_environment_check": {
+ "name": "push_tokens_apns_environment_check",
+ "value": "\"push_tokens\".\"apns_environment\" IS NULL OR \"push_tokens\".\"apns_environment\" IN ('sandbox', 'production')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.chunks": {
+ "name": "chunks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "abstract": {
+ "name": "abstract",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "index": {
+ "name": "index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "chunks_client_id_user_id_unique": {
+ "name": "chunks_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chunks_user_id_idx": {
+ "name": "chunks_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chunks_workspace_id_idx": {
+ "name": "chunks_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chunks_user_id_users_id_fk": {
+ "name": "chunks_user_id_users_id_fk",
+ "tableFrom": "chunks",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chunks_workspace_id_workspaces_id_fk": {
+ "name": "chunks_workspace_id_workspaces_id_fk",
+ "tableFrom": "chunks",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.document_chunks": {
+ "name": "document_chunks",
+ "schema": "",
+ "columns": {
+ "document_id": {
+ "name": "document_id",
+ "type": "varchar(30)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "chunk_id": {
+ "name": "chunk_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "page_index": {
+ "name": "page_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "document_chunks_document_id_idx": {
+ "name": "document_chunks_document_id_idx",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_chunks_chunk_id_idx": {
+ "name": "document_chunks_chunk_id_idx",
+ "columns": [
+ {
+ "expression": "chunk_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_chunks_user_id_idx": {
+ "name": "document_chunks_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "document_chunks_workspace_id_idx": {
+ "name": "document_chunks_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "document_chunks_document_id_documents_id_fk": {
+ "name": "document_chunks_document_id_documents_id_fk",
+ "tableFrom": "document_chunks",
+ "tableTo": "documents",
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "document_chunks_chunk_id_chunks_id_fk": {
+ "name": "document_chunks_chunk_id_chunks_id_fk",
+ "tableFrom": "document_chunks",
+ "tableTo": "chunks",
+ "columnsFrom": ["chunk_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "document_chunks_user_id_users_id_fk": {
+ "name": "document_chunks_user_id_users_id_fk",
+ "tableFrom": "document_chunks",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "document_chunks_workspace_id_workspaces_id_fk": {
+ "name": "document_chunks_workspace_id_workspaces_id_fk",
+ "tableFrom": "document_chunks",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "document_chunks_document_id_chunk_id_pk": {
+ "name": "document_chunks_document_id_chunk_id_pk",
+ "columns": ["document_id", "chunk_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.embeddings": {
+ "name": "embeddings",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "chunk_id": {
+ "name": "chunk_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "embeddings": {
+ "name": "embeddings",
+ "type": "vector(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "embeddings_client_id_user_id_unique": {
+ "name": "embeddings_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "embeddings_chunk_id_idx": {
+ "name": "embeddings_chunk_id_idx",
+ "columns": [
+ {
+ "expression": "chunk_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "embeddings_user_id_idx": {
+ "name": "embeddings_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "embeddings_workspace_id_idx": {
+ "name": "embeddings_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "embeddings_chunk_id_chunks_id_fk": {
+ "name": "embeddings_chunk_id_chunks_id_fk",
+ "tableFrom": "embeddings",
+ "tableTo": "chunks",
+ "columnsFrom": ["chunk_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "embeddings_user_id_users_id_fk": {
+ "name": "embeddings_user_id_users_id_fk",
+ "tableFrom": "embeddings",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "embeddings_workspace_id_workspaces_id_fk": {
+ "name": "embeddings_workspace_id_workspaces_id_fk",
+ "tableFrom": "embeddings",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "embeddings_chunk_id_unique": {
+ "name": "embeddings_chunk_id_unique",
+ "nullsNotDistinct": false,
+ "columns": ["chunk_id"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.unstructured_chunks": {
+ "name": "unstructured_chunks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "index": {
+ "name": "index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "parent_id": {
+ "name": "parent_id",
+ "type": "varchar",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "composite_id": {
+ "name": "composite_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_id": {
+ "name": "file_id",
+ "type": "varchar",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "unstructured_chunks_client_id_user_id_unique": {
+ "name": "unstructured_chunks_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "unstructured_chunks_user_id_idx": {
+ "name": "unstructured_chunks_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "unstructured_chunks_composite_id_idx": {
+ "name": "unstructured_chunks_composite_id_idx",
+ "columns": [
+ {
+ "expression": "composite_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "unstructured_chunks_file_id_idx": {
+ "name": "unstructured_chunks_file_id_idx",
+ "columns": [
+ {
+ "expression": "file_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "unstructured_chunks_workspace_id_idx": {
+ "name": "unstructured_chunks_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "unstructured_chunks_composite_id_chunks_id_fk": {
+ "name": "unstructured_chunks_composite_id_chunks_id_fk",
+ "tableFrom": "unstructured_chunks",
+ "tableTo": "chunks",
+ "columnsFrom": ["composite_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "unstructured_chunks_user_id_users_id_fk": {
+ "name": "unstructured_chunks_user_id_users_id_fk",
+ "tableFrom": "unstructured_chunks",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "unstructured_chunks_workspace_id_workspaces_id_fk": {
+ "name": "unstructured_chunks_workspace_id_workspaces_id_fk",
+ "tableFrom": "unstructured_chunks",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "unstructured_chunks_file_id_files_id_fk": {
+ "name": "unstructured_chunks_file_id_files_id_fk",
+ "tableFrom": "unstructured_chunks",
+ "tableTo": "files",
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.rag_eval_dataset_records": {
+ "name": "rag_eval_dataset_records",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "dataset_id": {
+ "name": "dataset_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ideal": {
+ "name": "ideal",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "question": {
+ "name": "question",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reference_files": {
+ "name": "reference_files",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "rag_eval_dataset_records_user_id_idx": {
+ "name": "rag_eval_dataset_records_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "rag_eval_dataset_records_workspace_id_idx": {
+ "name": "rag_eval_dataset_records_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "rag_eval_dataset_records_dataset_id_rag_eval_datasets_id_fk": {
+ "name": "rag_eval_dataset_records_dataset_id_rag_eval_datasets_id_fk",
+ "tableFrom": "rag_eval_dataset_records",
+ "tableTo": "rag_eval_datasets",
+ "columnsFrom": ["dataset_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rag_eval_dataset_records_user_id_users_id_fk": {
+ "name": "rag_eval_dataset_records_user_id_users_id_fk",
+ "tableFrom": "rag_eval_dataset_records",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rag_eval_dataset_records_workspace_id_workspaces_id_fk": {
+ "name": "rag_eval_dataset_records_workspace_id_workspaces_id_fk",
+ "tableFrom": "rag_eval_dataset_records",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.rag_eval_datasets": {
+ "name": "rag_eval_datasets",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "knowledge_base_id": {
+ "name": "knowledge_base_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "rag_eval_datasets_user_id_idx": {
+ "name": "rag_eval_datasets_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "rag_eval_datasets_workspace_id_idx": {
+ "name": "rag_eval_datasets_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "rag_eval_datasets_knowledge_base_id_knowledge_bases_id_fk": {
+ "name": "rag_eval_datasets_knowledge_base_id_knowledge_bases_id_fk",
+ "tableFrom": "rag_eval_datasets",
+ "tableTo": "knowledge_bases",
+ "columnsFrom": ["knowledge_base_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rag_eval_datasets_user_id_users_id_fk": {
+ "name": "rag_eval_datasets_user_id_users_id_fk",
+ "tableFrom": "rag_eval_datasets",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rag_eval_datasets_workspace_id_workspaces_id_fk": {
+ "name": "rag_eval_datasets_workspace_id_workspaces_id_fk",
+ "tableFrom": "rag_eval_datasets",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.rag_eval_evaluations": {
+ "name": "rag_eval_evaluations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "eval_records_url": {
+ "name": "eval_records_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dataset_id": {
+ "name": "dataset_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "knowledge_base_id": {
+ "name": "knowledge_base_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "language_model": {
+ "name": "language_model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "embedding_model": {
+ "name": "embedding_model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "rag_eval_evaluations_user_id_idx": {
+ "name": "rag_eval_evaluations_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "rag_eval_evaluations_workspace_id_idx": {
+ "name": "rag_eval_evaluations_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "rag_eval_evaluations_dataset_id_rag_eval_datasets_id_fk": {
+ "name": "rag_eval_evaluations_dataset_id_rag_eval_datasets_id_fk",
+ "tableFrom": "rag_eval_evaluations",
+ "tableTo": "rag_eval_datasets",
+ "columnsFrom": ["dataset_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rag_eval_evaluations_knowledge_base_id_knowledge_bases_id_fk": {
+ "name": "rag_eval_evaluations_knowledge_base_id_knowledge_bases_id_fk",
+ "tableFrom": "rag_eval_evaluations",
+ "tableTo": "knowledge_bases",
+ "columnsFrom": ["knowledge_base_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rag_eval_evaluations_user_id_users_id_fk": {
+ "name": "rag_eval_evaluations_user_id_users_id_fk",
+ "tableFrom": "rag_eval_evaluations",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rag_eval_evaluations_workspace_id_workspaces_id_fk": {
+ "name": "rag_eval_evaluations_workspace_id_workspaces_id_fk",
+ "tableFrom": "rag_eval_evaluations",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.rag_eval_evaluation_records": {
+ "name": "rag_eval_evaluation_records",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "question": {
+ "name": "question",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "answer": {
+ "name": "answer",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "context": {
+ "name": "context",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ideal": {
+ "name": "ideal",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "language_model": {
+ "name": "language_model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "embedding_model": {
+ "name": "embedding_model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "question_embedding_id": {
+ "name": "question_embedding_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "duration": {
+ "name": "duration",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dataset_record_id": {
+ "name": "dataset_record_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "evaluation_id": {
+ "name": "evaluation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "rag_eval_evaluation_records_user_id_idx": {
+ "name": "rag_eval_evaluation_records_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "rag_eval_evaluation_records_workspace_id_idx": {
+ "name": "rag_eval_evaluation_records_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "rag_eval_evaluation_records_question_embedding_id_embeddings_id_fk": {
+ "name": "rag_eval_evaluation_records_question_embedding_id_embeddings_id_fk",
+ "tableFrom": "rag_eval_evaluation_records",
+ "tableTo": "embeddings",
+ "columnsFrom": ["question_embedding_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "rag_eval_evaluation_records_dataset_record_id_rag_eval_dataset_records_id_fk": {
+ "name": "rag_eval_evaluation_records_dataset_record_id_rag_eval_dataset_records_id_fk",
+ "tableFrom": "rag_eval_evaluation_records",
+ "tableTo": "rag_eval_dataset_records",
+ "columnsFrom": ["dataset_record_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rag_eval_evaluation_records_evaluation_id_rag_eval_evaluations_id_fk": {
+ "name": "rag_eval_evaluation_records_evaluation_id_rag_eval_evaluations_id_fk",
+ "tableFrom": "rag_eval_evaluation_records",
+ "tableTo": "rag_eval_evaluations",
+ "columnsFrom": ["evaluation_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rag_eval_evaluation_records_user_id_users_id_fk": {
+ "name": "rag_eval_evaluation_records_user_id_users_id_fk",
+ "tableFrom": "rag_eval_evaluation_records",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rag_eval_evaluation_records_workspace_id_workspaces_id_fk": {
+ "name": "rag_eval_evaluation_records_workspace_id_workspaces_id_fk",
+ "tableFrom": "rag_eval_evaluation_records",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.rbac_permissions": {
+ "name": "rbac_permissions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "code": {
+ "name": "code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "category": {
+ "name": "category",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "rbac_permissions_code_unique": {
+ "name": "rbac_permissions_code_unique",
+ "nullsNotDistinct": false,
+ "columns": ["code"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.rbac_role_permissions": {
+ "name": "rbac_role_permissions",
+ "schema": "",
+ "columns": {
+ "role_id": {
+ "name": "role_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "permission_id": {
+ "name": "permission_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "rbac_role_permissions_role_id_idx": {
+ "name": "rbac_role_permissions_role_id_idx",
+ "columns": [
+ {
+ "expression": "role_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "rbac_role_permissions_permission_id_idx": {
+ "name": "rbac_role_permissions_permission_id_idx",
+ "columns": [
+ {
+ "expression": "permission_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "rbac_role_permissions_role_id_rbac_roles_id_fk": {
+ "name": "rbac_role_permissions_role_id_rbac_roles_id_fk",
+ "tableFrom": "rbac_role_permissions",
+ "tableTo": "rbac_roles",
+ "columnsFrom": ["role_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rbac_role_permissions_permission_id_rbac_permissions_id_fk": {
+ "name": "rbac_role_permissions_permission_id_rbac_permissions_id_fk",
+ "tableFrom": "rbac_role_permissions",
+ "tableTo": "rbac_permissions",
+ "columnsFrom": ["permission_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "rbac_role_permissions_role_id_permission_id_pk": {
+ "name": "rbac_role_permissions_role_id_permission_id_pk",
+ "columns": ["role_id", "permission_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.rbac_roles": {
+ "name": "rbac_roles",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "display_name": {
+ "name": "display_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_system": {
+ "name": "is_system",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "rbac_roles_workspace_id_idx": {
+ "name": "rbac_roles_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "rbac_roles_name_workspace_unique": {
+ "name": "rbac_roles_name_workspace_unique",
+ "columns": [
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "COALESCE(\"workspace_id\", '')",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "rbac_roles_workspace_id_workspaces_id_fk": {
+ "name": "rbac_roles_workspace_id_workspaces_id_fk",
+ "tableFrom": "rbac_roles",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.rbac_user_roles": {
+ "name": "rbac_user_roles",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role_id": {
+ "name": "role_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "rbac_user_roles_user_role_scope_unique": {
+ "name": "rbac_user_roles_user_role_scope_unique",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "role_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "COALESCE(\"workspace_id\", '')",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "rbac_user_roles_user_id_idx": {
+ "name": "rbac_user_roles_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "rbac_user_roles_role_id_idx": {
+ "name": "rbac_user_roles_role_id_idx",
+ "columns": [
+ {
+ "expression": "role_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "rbac_user_roles_workspace_id_idx": {
+ "name": "rbac_user_roles_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "rbac_user_roles_user_id_users_id_fk": {
+ "name": "rbac_user_roles_user_id_users_id_fk",
+ "tableFrom": "rbac_user_roles",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rbac_user_roles_role_id_rbac_roles_id_fk": {
+ "name": "rbac_user_roles_role_id_rbac_roles_id_fk",
+ "tableFrom": "rbac_user_roles",
+ "tableTo": "rbac_roles",
+ "columnsFrom": ["role_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "rbac_user_roles_workspace_id_workspaces_id_fk": {
+ "name": "rbac_user_roles_workspace_id_workspaces_id_fk",
+ "tableFrom": "rbac_user_roles",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agents_to_sessions": {
+ "name": "agents_to_sessions",
+ "schema": "",
+ "columns": {
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "agents_to_sessions_session_id_idx": {
+ "name": "agents_to_sessions_session_id_idx",
+ "columns": [
+ {
+ "expression": "session_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_to_sessions_agent_id_idx": {
+ "name": "agents_to_sessions_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_to_sessions_user_id_idx": {
+ "name": "agents_to_sessions_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agents_to_sessions_workspace_id_idx": {
+ "name": "agents_to_sessions_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agents_to_sessions_agent_id_agents_id_fk": {
+ "name": "agents_to_sessions_agent_id_agents_id_fk",
+ "tableFrom": "agents_to_sessions",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agents_to_sessions_session_id_sessions_id_fk": {
+ "name": "agents_to_sessions_session_id_sessions_id_fk",
+ "tableFrom": "agents_to_sessions",
+ "tableTo": "sessions",
+ "columnsFrom": ["session_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agents_to_sessions_user_id_users_id_fk": {
+ "name": "agents_to_sessions_user_id_users_id_fk",
+ "tableFrom": "agents_to_sessions",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agents_to_sessions_workspace_id_workspaces_id_fk": {
+ "name": "agents_to_sessions_workspace_id_workspaces_id_fk",
+ "tableFrom": "agents_to_sessions",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "agents_to_sessions_agent_id_session_id_pk": {
+ "name": "agents_to_sessions_agent_id_session_id_pk",
+ "columns": ["agent_id", "session_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.file_chunks": {
+ "name": "file_chunks",
+ "schema": "",
+ "columns": {
+ "file_id": {
+ "name": "file_id",
+ "type": "varchar",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "chunk_id": {
+ "name": "chunk_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "file_chunks_user_id_idx": {
+ "name": "file_chunks_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "file_chunks_workspace_id_idx": {
+ "name": "file_chunks_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "file_chunks_file_id_idx": {
+ "name": "file_chunks_file_id_idx",
+ "columns": [
+ {
+ "expression": "file_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "file_chunks_chunk_id_idx": {
+ "name": "file_chunks_chunk_id_idx",
+ "columns": [
+ {
+ "expression": "chunk_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "file_chunks_file_id_files_id_fk": {
+ "name": "file_chunks_file_id_files_id_fk",
+ "tableFrom": "file_chunks",
+ "tableTo": "files",
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "file_chunks_chunk_id_chunks_id_fk": {
+ "name": "file_chunks_chunk_id_chunks_id_fk",
+ "tableFrom": "file_chunks",
+ "tableTo": "chunks",
+ "columnsFrom": ["chunk_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "file_chunks_user_id_users_id_fk": {
+ "name": "file_chunks_user_id_users_id_fk",
+ "tableFrom": "file_chunks",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "file_chunks_workspace_id_workspaces_id_fk": {
+ "name": "file_chunks_workspace_id_workspaces_id_fk",
+ "tableFrom": "file_chunks",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "file_chunks_file_id_chunk_id_pk": {
+ "name": "file_chunks_file_id_chunk_id_pk",
+ "columns": ["file_id", "chunk_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.files_to_sessions": {
+ "name": "files_to_sessions",
+ "schema": "",
+ "columns": {
+ "file_id": {
+ "name": "file_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "files_to_sessions_user_id_idx": {
+ "name": "files_to_sessions_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_to_sessions_workspace_id_idx": {
+ "name": "files_to_sessions_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_to_sessions_file_id_idx": {
+ "name": "files_to_sessions_file_id_idx",
+ "columns": [
+ {
+ "expression": "file_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_to_sessions_session_id_idx": {
+ "name": "files_to_sessions_session_id_idx",
+ "columns": [
+ {
+ "expression": "session_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "files_to_sessions_file_id_files_id_fk": {
+ "name": "files_to_sessions_file_id_files_id_fk",
+ "tableFrom": "files_to_sessions",
+ "tableTo": "files",
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "files_to_sessions_session_id_sessions_id_fk": {
+ "name": "files_to_sessions_session_id_sessions_id_fk",
+ "tableFrom": "files_to_sessions",
+ "tableTo": "sessions",
+ "columnsFrom": ["session_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "files_to_sessions_user_id_users_id_fk": {
+ "name": "files_to_sessions_user_id_users_id_fk",
+ "tableFrom": "files_to_sessions",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "files_to_sessions_workspace_id_workspaces_id_fk": {
+ "name": "files_to_sessions_workspace_id_workspaces_id_fk",
+ "tableFrom": "files_to_sessions",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "files_to_sessions_file_id_session_id_pk": {
+ "name": "files_to_sessions_file_id_session_id_pk",
+ "columns": ["file_id", "session_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.resource_permissions": {
+ "name": "resource_permissions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "resource_type": {
+ "name": "resource_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resource_id": {
+ "name": "resource_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_level": {
+ "name": "access_level",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "resource_permissions_workspace_resource_unique": {
+ "name": "resource_permissions_workspace_resource_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resource_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resource_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"resource_permissions\".\"user_id\" is null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "resource_permissions_workspace_resource_user_id_unique": {
+ "name": "resource_permissions_workspace_resource_user_id_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resource_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resource_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"resource_permissions\".\"user_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "resource_permissions_resource_idx": {
+ "name": "resource_permissions_resource_idx",
+ "columns": [
+ {
+ "expression": "resource_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resource_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "resource_permissions_workspace_idx": {
+ "name": "resource_permissions_workspace_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "resource_permissions_workspace_user_idx": {
+ "name": "resource_permissions_workspace_user_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "resource_permissions_workspace_id_workspaces_id_fk": {
+ "name": "resource_permissions_workspace_id_workspaces_id_fk",
+ "tableFrom": "resource_permissions",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "resource_permissions_user_id_users_id_fk": {
+ "name": "resource_permissions_user_id_users_id_fk",
+ "tableFrom": "resource_permissions",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "resource_permissions_created_by_users_id_fk": {
+ "name": "resource_permissions_created_by_users_id_fk",
+ "tableFrom": "resource_permissions",
+ "tableTo": "users",
+ "columnsFrom": ["created_by"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.resource_transfer_requests": {
+ "name": "resource_transfer_requests",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "resource_type": {
+ "name": "resource_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resource_id": {
+ "name": "resource_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "initiator_id": {
+ "name": "initiator_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "recipient_id": {
+ "name": "recipient_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "previous_owner_id": {
+ "name": "previous_owner_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "options": {
+ "name": "options",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "resource_transfer_requests_pending_resource_unique": {
+ "name": "resource_transfer_requests_pending_resource_unique",
+ "columns": [
+ {
+ "expression": "resource_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resource_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"resource_transfer_requests\".\"status\" = 'pending' AND \"resource_transfer_requests\".\"recipient_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "resource_transfer_requests_recipient_idx": {
+ "name": "resource_transfer_requests_recipient_idx",
+ "columns": [
+ {
+ "expression": "recipient_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "resource_transfer_requests_workspace_idx": {
+ "name": "resource_transfer_requests_workspace_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "resource_transfer_requests_workspace_id_workspaces_id_fk": {
+ "name": "resource_transfer_requests_workspace_id_workspaces_id_fk",
+ "tableFrom": "resource_transfer_requests",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "resource_transfer_requests_initiator_id_users_id_fk": {
+ "name": "resource_transfer_requests_initiator_id_users_id_fk",
+ "tableFrom": "resource_transfer_requests",
+ "tableTo": "users",
+ "columnsFrom": ["initiator_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "resource_transfer_requests_recipient_id_users_id_fk": {
+ "name": "resource_transfer_requests_recipient_id_users_id_fk",
+ "tableFrom": "resource_transfer_requests",
+ "tableTo": "users",
+ "columnsFrom": ["recipient_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "resource_transfer_requests_previous_owner_id_users_id_fk": {
+ "name": "resource_transfer_requests_previous_owner_id_users_id_fk",
+ "tableFrom": "resource_transfer_requests",
+ "tableTo": "users",
+ "columnsFrom": ["previous_owner_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session_groups": {
+ "name": "session_groups",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sort": {
+ "name": "sort",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "session_groups_client_id_user_id_unique": {
+ "name": "session_groups_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "session_groups_user_id_idx": {
+ "name": "session_groups_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "session_groups_workspace_id_idx": {
+ "name": "session_groups_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "session_groups_workspace_visibility_idx": {
+ "name": "session_groups_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "session_groups_user_id_users_id_fk": {
+ "name": "session_groups_user_id_users_id_fk",
+ "tableFrom": "session_groups",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "session_groups_workspace_id_workspaces_id_fk": {
+ "name": "session_groups_workspace_id_workspaces_id_fk",
+ "tableFrom": "session_groups",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sessions": {
+ "name": "sessions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "varchar(100)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "avatar": {
+ "name": "avatar",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "background_color": {
+ "name": "background_color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'agent'"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pinned": {
+ "name": "pinned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "slug_user_id_unique": {
+ "name": "slug_user_id_unique",
+ "columns": [
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"sessions\".\"workspace_id\" is null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sessions_client_id_user_id_unique": {
+ "name": "sessions_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sessions_user_id_idx": {
+ "name": "sessions_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sessions_id_user_id_idx": {
+ "name": "sessions_id_user_id_idx",
+ "columns": [
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sessions_user_id_updated_at_idx": {
+ "name": "sessions_user_id_updated_at_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sessions_group_id_idx": {
+ "name": "sessions_group_id_idx",
+ "columns": [
+ {
+ "expression": "group_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sessions_workspace_id_idx": {
+ "name": "sessions_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sessions_slug_workspace_id_unique": {
+ "name": "sessions_slug_workspace_id_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"sessions\".\"workspace_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "sessions_user_id_users_id_fk": {
+ "name": "sessions_user_id_users_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sessions_group_id_session_groups_id_fk": {
+ "name": "sessions_group_id_session_groups_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "session_groups",
+ "columnsFrom": ["group_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sessions_workspace_id_workspaces_id_fk": {
+ "name": "sessions_workspace_id_workspaces_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.system_bot_providers": {
+ "name": "system_bot_providers",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "platform": {
+ "name": "platform",
+ "type": "varchar(50)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "credentials": {
+ "name": "credentials",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "application_id": {
+ "name": "application_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "settings": {
+ "name": "settings",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "connection_mode": {
+ "name": "connection_mode",
+ "type": "varchar(20)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "system_bot_providers_platform_unique": {
+ "name": "system_bot_providers_platform_unique",
+ "columns": [
+ {
+ "expression": "platform",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.briefs": {
+ "name": "briefs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cron_job_id": {
+ "name": "cron_job_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "priority": {
+ "name": "priority",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'info'"
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "artifacts": {
+ "name": "artifacts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "actions": {
+ "name": "actions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolved_action": {
+ "name": "resolved_action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolved_comment": {
+ "name": "resolved_comment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "read_at": {
+ "name": "read_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "briefs_user_id_idx": {
+ "name": "briefs_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "briefs_task_id_idx": {
+ "name": "briefs_task_id_idx",
+ "columns": [
+ {
+ "expression": "task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "briefs_cron_job_id_idx": {
+ "name": "briefs_cron_job_id_idx",
+ "columns": [
+ {
+ "expression": "cron_job_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "briefs_agent_id_idx": {
+ "name": "briefs_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "briefs_type_idx": {
+ "name": "briefs_type_idx",
+ "columns": [
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "briefs_priority_idx": {
+ "name": "briefs_priority_idx",
+ "columns": [
+ {
+ "expression": "priority",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "briefs_unresolved_idx": {
+ "name": "briefs_unresolved_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resolved_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "briefs_trigger_idx": {
+ "name": "briefs_trigger_idx",
+ "columns": [
+ {
+ "expression": "trigger",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "briefs_workspace_id_idx": {
+ "name": "briefs_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "briefs_user_id_users_id_fk": {
+ "name": "briefs_user_id_users_id_fk",
+ "tableFrom": "briefs",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "briefs_workspace_id_workspaces_id_fk": {
+ "name": "briefs_workspace_id_workspaces_id_fk",
+ "tableFrom": "briefs",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "briefs_task_id_tasks_id_fk": {
+ "name": "briefs_task_id_tasks_id_fk",
+ "tableFrom": "briefs",
+ "tableTo": "tasks",
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "briefs_cron_job_id_agent_cron_jobs_id_fk": {
+ "name": "briefs_cron_job_id_agent_cron_jobs_id_fk",
+ "tableFrom": "briefs",
+ "tableTo": "agent_cron_jobs",
+ "columnsFrom": ["cron_job_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.task_comments": {
+ "name": "task_comments",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "author_user_id": {
+ "name": "author_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "author_agent_id": {
+ "name": "author_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "editor_data": {
+ "name": "editor_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "brief_id": {
+ "name": "brief_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "task_comments_task_id_idx": {
+ "name": "task_comments_task_id_idx",
+ "columns": [
+ {
+ "expression": "task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_comments_user_id_idx": {
+ "name": "task_comments_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_comments_author_user_id_idx": {
+ "name": "task_comments_author_user_id_idx",
+ "columns": [
+ {
+ "expression": "author_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_comments_agent_id_idx": {
+ "name": "task_comments_agent_id_idx",
+ "columns": [
+ {
+ "expression": "author_agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_comments_brief_id_idx": {
+ "name": "task_comments_brief_id_idx",
+ "columns": [
+ {
+ "expression": "brief_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_comments_topic_id_idx": {
+ "name": "task_comments_topic_id_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_comments_workspace_id_idx": {
+ "name": "task_comments_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_comments_workspace_visibility_idx": {
+ "name": "task_comments_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "task_comments_task_id_tasks_id_fk": {
+ "name": "task_comments_task_id_tasks_id_fk",
+ "tableFrom": "task_comments",
+ "tableTo": "tasks",
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_comments_user_id_users_id_fk": {
+ "name": "task_comments_user_id_users_id_fk",
+ "tableFrom": "task_comments",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_comments_workspace_id_workspaces_id_fk": {
+ "name": "task_comments_workspace_id_workspaces_id_fk",
+ "tableFrom": "task_comments",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_comments_author_user_id_users_id_fk": {
+ "name": "task_comments_author_user_id_users_id_fk",
+ "tableFrom": "task_comments",
+ "tableTo": "users",
+ "columnsFrom": ["author_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "task_comments_author_agent_id_agents_id_fk": {
+ "name": "task_comments_author_agent_id_agents_id_fk",
+ "tableFrom": "task_comments",
+ "tableTo": "agents",
+ "columnsFrom": ["author_agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "task_comments_brief_id_briefs_id_fk": {
+ "name": "task_comments_brief_id_briefs_id_fk",
+ "tableFrom": "task_comments",
+ "tableTo": "briefs",
+ "columnsFrom": ["brief_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "task_comments_topic_id_topics_id_fk": {
+ "name": "task_comments_topic_id_topics_id_fk",
+ "tableFrom": "task_comments",
+ "tableTo": "topics",
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.task_dependencies": {
+ "name": "task_dependencies",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "depends_on_id": {
+ "name": "depends_on_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'blocks'"
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "condition": {
+ "name": "condition",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "task_deps_unique_idx": {
+ "name": "task_deps_unique_idx",
+ "columns": [
+ {
+ "expression": "task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "depends_on_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_deps_task_id_idx": {
+ "name": "task_deps_task_id_idx",
+ "columns": [
+ {
+ "expression": "task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_deps_depends_on_id_idx": {
+ "name": "task_deps_depends_on_id_idx",
+ "columns": [
+ {
+ "expression": "depends_on_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_deps_user_id_idx": {
+ "name": "task_deps_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_dependencies_workspace_id_idx": {
+ "name": "task_dependencies_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_deps_workspace_visibility_idx": {
+ "name": "task_deps_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "task_dependencies_task_id_tasks_id_fk": {
+ "name": "task_dependencies_task_id_tasks_id_fk",
+ "tableFrom": "task_dependencies",
+ "tableTo": "tasks",
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_dependencies_depends_on_id_tasks_id_fk": {
+ "name": "task_dependencies_depends_on_id_tasks_id_fk",
+ "tableFrom": "task_dependencies",
+ "tableTo": "tasks",
+ "columnsFrom": ["depends_on_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_dependencies_user_id_users_id_fk": {
+ "name": "task_dependencies_user_id_users_id_fk",
+ "tableFrom": "task_dependencies",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_dependencies_workspace_id_workspaces_id_fk": {
+ "name": "task_dependencies_workspace_id_workspaces_id_fk",
+ "tableFrom": "task_dependencies",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.task_documents": {
+ "name": "task_documents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pinned_by": {
+ "name": "pinned_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'agent'"
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "task_docs_unique_idx": {
+ "name": "task_docs_unique_idx",
+ "columns": [
+ {
+ "expression": "task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_docs_task_id_idx": {
+ "name": "task_docs_task_id_idx",
+ "columns": [
+ {
+ "expression": "task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_docs_document_id_idx": {
+ "name": "task_docs_document_id_idx",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_docs_user_id_idx": {
+ "name": "task_docs_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_documents_workspace_id_idx": {
+ "name": "task_documents_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_docs_workspace_visibility_idx": {
+ "name": "task_docs_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "task_documents_task_id_tasks_id_fk": {
+ "name": "task_documents_task_id_tasks_id_fk",
+ "tableFrom": "task_documents",
+ "tableTo": "tasks",
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_documents_document_id_documents_id_fk": {
+ "name": "task_documents_document_id_documents_id_fk",
+ "tableFrom": "task_documents",
+ "tableTo": "documents",
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_documents_user_id_users_id_fk": {
+ "name": "task_documents_user_id_users_id_fk",
+ "tableFrom": "task_documents",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_documents_workspace_id_workspaces_id_fk": {
+ "name": "task_documents_workspace_id_workspaces_id_fk",
+ "tableFrom": "task_documents",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.task_topics": {
+ "name": "task_topics",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "operation_id": {
+ "name": "operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'running'"
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "handoff": {
+ "name": "handoff",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "review_passed": {
+ "name": "review_passed",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "review_score": {
+ "name": "review_score",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "review_scores": {
+ "name": "review_scores",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "review_iteration": {
+ "name": "review_iteration",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reviewed_at": {
+ "name": "reviewed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "task_topics_unique_idx": {
+ "name": "task_topics_unique_idx",
+ "columns": [
+ {
+ "expression": "task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_topics_task_id_idx": {
+ "name": "task_topics_task_id_idx",
+ "columns": [
+ {
+ "expression": "task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_topics_topic_id_idx": {
+ "name": "task_topics_topic_id_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_topics_user_id_idx": {
+ "name": "task_topics_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_topics_status_idx": {
+ "name": "task_topics_status_idx",
+ "columns": [
+ {
+ "expression": "task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_topics_workspace_id_idx": {
+ "name": "task_topics_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_topics_workspace_visibility_idx": {
+ "name": "task_topics_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "task_topics_task_id_tasks_id_fk": {
+ "name": "task_topics_task_id_tasks_id_fk",
+ "tableFrom": "task_topics",
+ "tableTo": "tasks",
+ "columnsFrom": ["task_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_topics_topic_id_topics_id_fk": {
+ "name": "task_topics_topic_id_topics_id_fk",
+ "tableFrom": "task_topics",
+ "tableTo": "topics",
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_topics_user_id_users_id_fk": {
+ "name": "task_topics_user_id_users_id_fk",
+ "tableFrom": "task_topics",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_topics_workspace_id_workspaces_id_fk": {
+ "name": "task_topics_workspace_id_workspaces_id_fk",
+ "tableFrom": "task_topics",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.tasks": {
+ "name": "tasks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_agent_id": {
+ "name": "created_by_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "assignee_user_id": {
+ "name": "assignee_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "assignee_agent_id": {
+ "name": "assignee_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_task_id": {
+ "name": "parent_task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "instruction": {
+ "name": "instruction",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "editor_data": {
+ "name": "editor_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'backlog'"
+ },
+ "priority": {
+ "name": "priority",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "automation_mode": {
+ "name": "automation_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "heartbeat_interval": {
+ "name": "heartbeat_interval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "heartbeat_timeout": {
+ "name": "heartbeat_timeout",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_heartbeat_at": {
+ "name": "last_heartbeat_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "schedule_pattern": {
+ "name": "schedule_pattern",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "schedule_timezone": {
+ "name": "schedule_timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'UTC'"
+ },
+ "total_topics": {
+ "name": "total_topics",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "max_topics": {
+ "name": "max_topics",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "current_topic_id": {
+ "name": "current_topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "context": {
+ "name": "context",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "tasks_identifier_idx": {
+ "name": "tasks_identifier_idx",
+ "columns": [
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_by_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"tasks\".\"workspace_id\" is null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "tasks_created_by_user_id_idx": {
+ "name": "tasks_created_by_user_id_idx",
+ "columns": [
+ {
+ "expression": "created_by_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "tasks_created_by_agent_id_idx": {
+ "name": "tasks_created_by_agent_id_idx",
+ "columns": [
+ {
+ "expression": "created_by_agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "tasks_assignee_user_id_idx": {
+ "name": "tasks_assignee_user_id_idx",
+ "columns": [
+ {
+ "expression": "assignee_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "tasks_assignee_agent_id_idx": {
+ "name": "tasks_assignee_agent_id_idx",
+ "columns": [
+ {
+ "expression": "assignee_agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "tasks_parent_task_id_idx": {
+ "name": "tasks_parent_task_id_idx",
+ "columns": [
+ {
+ "expression": "parent_task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "tasks_status_idx": {
+ "name": "tasks_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "tasks_priority_idx": {
+ "name": "tasks_priority_idx",
+ "columns": [
+ {
+ "expression": "priority",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "tasks_automation_mode_idx": {
+ "name": "tasks_automation_mode_idx",
+ "columns": [
+ {
+ "expression": "automation_mode",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "tasks_heartbeat_idx": {
+ "name": "tasks_heartbeat_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "last_heartbeat_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "tasks_workspace_id_idx": {
+ "name": "tasks_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "tasks_project_id_status_idx": {
+ "name": "tasks_project_id_status_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "tasks_workspace_visibility_idx": {
+ "name": "tasks_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_by_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "tasks_identifier_workspace_id_unique": {
+ "name": "tasks_identifier_workspace_id_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"tasks\".\"workspace_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "tasks_created_by_user_id_users_id_fk": {
+ "name": "tasks_created_by_user_id_users_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "users",
+ "columnsFrom": ["created_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tasks_workspace_id_workspaces_id_fk": {
+ "name": "tasks_workspace_id_workspaces_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tasks_project_id_projects_id_fk": {
+ "name": "tasks_project_id_projects_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "projects",
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "tasks_created_by_agent_id_agents_id_fk": {
+ "name": "tasks_created_by_agent_id_agents_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "agents",
+ "columnsFrom": ["created_by_agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "tasks_assignee_user_id_users_id_fk": {
+ "name": "tasks_assignee_user_id_users_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "users",
+ "columnsFrom": ["assignee_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "tasks_assignee_agent_id_agents_id_fk": {
+ "name": "tasks_assignee_agent_id_agents_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "agents",
+ "columnsFrom": ["assignee_agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "tasks_current_topic_id_topics_id_fk": {
+ "name": "tasks_current_topic_id_topics_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "topics",
+ "columnsFrom": ["current_topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "tasks_parent_task_id_tasks_id_fk": {
+ "name": "tasks_parent_task_id_tasks_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "tasks",
+ "columnsFrom": ["parent_task_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.threads": {
+ "name": "threads",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "editor_data": {
+ "name": "editor_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_message_id": {
+ "name": "source_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_thread_id": {
+ "name": "parent_thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "last_active_at": {
+ "name": "last_active_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "threads_client_id_user_id_unique": {
+ "name": "threads_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "threads_user_id_idx": {
+ "name": "threads_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "threads_topic_id_idx": {
+ "name": "threads_topic_id_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "threads_type_idx": {
+ "name": "threads_type_idx",
+ "columns": [
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "threads_agent_id_idx": {
+ "name": "threads_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "threads_group_id_idx": {
+ "name": "threads_group_id_idx",
+ "columns": [
+ {
+ "expression": "group_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "threads_parent_thread_id_idx": {
+ "name": "threads_parent_thread_id_idx",
+ "columns": [
+ {
+ "expression": "parent_thread_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "threads_workspace_id_idx": {
+ "name": "threads_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "threads_topic_id_topics_id_fk": {
+ "name": "threads_topic_id_topics_id_fk",
+ "tableFrom": "threads",
+ "tableTo": "topics",
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "threads_parent_thread_id_threads_id_fk": {
+ "name": "threads_parent_thread_id_threads_id_fk",
+ "tableFrom": "threads",
+ "tableTo": "threads",
+ "columnsFrom": ["parent_thread_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "threads_agent_id_agents_id_fk": {
+ "name": "threads_agent_id_agents_id_fk",
+ "tableFrom": "threads",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "threads_group_id_chat_groups_id_fk": {
+ "name": "threads_group_id_chat_groups_id_fk",
+ "tableFrom": "threads",
+ "tableTo": "chat_groups",
+ "columnsFrom": ["group_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "threads_user_id_users_id_fk": {
+ "name": "threads_user_id_users_id_fk",
+ "tableFrom": "threads",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "threads_workspace_id_workspaces_id_fk": {
+ "name": "threads_workspace_id_workspaces_id_fk",
+ "tableFrom": "threads",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.topic_documents": {
+ "name": "topic_documents",
+ "schema": "",
+ "columns": {
+ "document_id": {
+ "name": "document_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "topic_documents_user_id_idx": {
+ "name": "topic_documents_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_documents_topic_id_idx": {
+ "name": "topic_documents_topic_id_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_documents_document_id_idx": {
+ "name": "topic_documents_document_id_idx",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_documents_workspace_id_idx": {
+ "name": "topic_documents_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "topic_documents_document_id_documents_id_fk": {
+ "name": "topic_documents_document_id_documents_id_fk",
+ "tableFrom": "topic_documents",
+ "tableTo": "documents",
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "topic_documents_topic_id_topics_id_fk": {
+ "name": "topic_documents_topic_id_topics_id_fk",
+ "tableFrom": "topic_documents",
+ "tableTo": "topics",
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "topic_documents_user_id_users_id_fk": {
+ "name": "topic_documents_user_id_users_id_fk",
+ "tableFrom": "topic_documents",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "topic_documents_workspace_id_workspaces_id_fk": {
+ "name": "topic_documents_workspace_id_workspaces_id_fk",
+ "tableFrom": "topic_documents",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "topic_documents_document_id_topic_id_pk": {
+ "name": "topic_documents_document_id_topic_id_pk",
+ "columns": ["document_id", "topic_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.topic_shares": {
+ "name": "topic_shares",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'private'"
+ },
+ "page_view_count": {
+ "name": "page_view_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "topic_shares_topic_id_unique": {
+ "name": "topic_shares_topic_id_unique",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_shares_user_id_idx": {
+ "name": "topic_shares_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_shares_workspace_id_idx": {
+ "name": "topic_shares_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "topic_shares_topic_id_topics_id_fk": {
+ "name": "topic_shares_topic_id_topics_id_fk",
+ "tableFrom": "topic_shares",
+ "tableTo": "topics",
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "topic_shares_user_id_users_id_fk": {
+ "name": "topic_shares_user_id_users_id_fk",
+ "tableFrom": "topic_shares",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "topic_shares_workspace_id_workspaces_id_fk": {
+ "name": "topic_shares_workspace_id_workspaces_id_fk",
+ "tableFrom": "topic_shares",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.topics": {
+ "name": "topics",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "favorite": {
+ "name": "favorite",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "editor_data": {
+ "name": "editor_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "history_summary": {
+ "name": "history_summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "mode": {
+ "name": "mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "total_cost": {
+ "name": "total_cost",
+ "type": "numeric(20, 6)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "total_input_tokens": {
+ "name": "total_input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "total_output_tokens": {
+ "name": "total_output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "total_tokens": {
+ "name": "total_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cost": {
+ "name": "cost",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "usage": {
+ "name": "usage",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sender_id": {
+ "name": "sender_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "topics_client_id_user_id_unique": {
+ "name": "topics_client_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topics_created_at_idx": {
+ "name": "topics_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topics_user_id_idx": {
+ "name": "topics_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topics_id_user_id_idx": {
+ "name": "topics_id_user_id_idx",
+ "columns": [
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topics_session_id_idx": {
+ "name": "topics_session_id_idx",
+ "columns": [
+ {
+ "expression": "session_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topics_group_id_idx": {
+ "name": "topics_group_id_idx",
+ "columns": [
+ {
+ "expression": "group_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topics_agent_id_idx": {
+ "name": "topics_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topics_trigger_idx": {
+ "name": "topics_trigger_idx",
+ "columns": [
+ {
+ "expression": "trigger",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topics_status_idx": {
+ "name": "topics_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topics_model_idx": {
+ "name": "topics_model_idx",
+ "columns": [
+ {
+ "expression": "model",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topics_provider_idx": {
+ "name": "topics_provider_idx",
+ "columns": [
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topics_user_id_completed_at_idx": {
+ "name": "topics_user_id_completed_at_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "completed_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topics_sender_id_idx": {
+ "name": "topics_sender_id_idx",
+ "columns": [
+ {
+ "expression": "sender_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topics_workspace_id_idx": {
+ "name": "topics_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topics_extract_status_gin_idx": {
+ "name": "topics_extract_status_gin_idx",
+ "columns": [
+ {
+ "expression": "(metadata->'userMemoryExtractStatus') jsonb_path_ops",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "topics_session_id_sessions_id_fk": {
+ "name": "topics_session_id_sessions_id_fk",
+ "tableFrom": "topics",
+ "tableTo": "sessions",
+ "columnsFrom": ["session_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "topics_agent_id_agents_id_fk": {
+ "name": "topics_agent_id_agents_id_fk",
+ "tableFrom": "topics",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "topics_group_id_chat_groups_id_fk": {
+ "name": "topics_group_id_chat_groups_id_fk",
+ "tableFrom": "topics",
+ "tableTo": "chat_groups",
+ "columnsFrom": ["group_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "topics_user_id_users_id_fk": {
+ "name": "topics_user_id_users_id_fk",
+ "tableFrom": "topics",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "topics_workspace_id_workspaces_id_fk": {
+ "name": "topics_workspace_id_workspaces_id_fk",
+ "tableFrom": "topics",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.topic_comment_mentions": {
+ "name": "topic_comment_mentions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "comment_id": {
+ "name": "comment_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "mentioned_user_id": {
+ "name": "mentioned_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "topic_comment_mentions_comment_id_mentioned_user_id_unique": {
+ "name": "topic_comment_mentions_comment_id_mentioned_user_id_unique",
+ "columns": [
+ {
+ "expression": "comment_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "mentioned_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_comment_mentions_mentioned_user_id_created_at_idx": {
+ "name": "topic_comment_mentions_mentioned_user_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "mentioned_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_comment_mentions_workspace_id_idx": {
+ "name": "topic_comment_mentions_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "topic_comment_mentions_comment_id_topic_comments_id_fk": {
+ "name": "topic_comment_mentions_comment_id_topic_comments_id_fk",
+ "tableFrom": "topic_comment_mentions",
+ "tableTo": "topic_comments",
+ "columnsFrom": ["comment_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "topic_comment_mentions_mentioned_user_id_users_id_fk": {
+ "name": "topic_comment_mentions_mentioned_user_id_users_id_fk",
+ "tableFrom": "topic_comment_mentions",
+ "tableTo": "users",
+ "columnsFrom": ["mentioned_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "topic_comment_mentions_workspace_id_workspaces_id_fk": {
+ "name": "topic_comment_mentions_workspace_id_workspaces_id_fk",
+ "tableFrom": "topic_comment_mentions",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.topic_comments": {
+ "name": "topic_comments",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parent_comment_id": {
+ "name": "parent_comment_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "author_user_id": {
+ "name": "author_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "editor_data": {
+ "name": "editor_data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "anchor_preview": {
+ "name": "anchor_preview",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "moderated_at": {
+ "name": "moderated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "moderated_by_user_id": {
+ "name": "moderated_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "moderation_expires_at": {
+ "name": "moderation_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "topic_comments_topic_id_author_user_id_client_id_unique": {
+ "name": "topic_comments_topic_id_author_user_id_client_id_unique",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "author_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_comments_parent_comment_id_created_at_id_idx": {
+ "name": "topic_comments_parent_comment_id_created_at_id_idx",
+ "columns": [
+ {
+ "expression": "parent_comment_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_comments_topic_id_created_at_id_idx": {
+ "name": "topic_comments_topic_id_created_at_id_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_comments_topic_id_message_id_idx": {
+ "name": "topic_comments_topic_id_message_id_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_comments_message_id_idx": {
+ "name": "topic_comments_message_id_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_comments_author_user_id_idx": {
+ "name": "topic_comments_author_user_id_idx",
+ "columns": [
+ {
+ "expression": "author_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_comments_moderation_expires_at_idx": {
+ "name": "topic_comments_moderation_expires_at_idx",
+ "columns": [
+ {
+ "expression": "moderation_expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_comments_moderated_by_user_id_idx": {
+ "name": "topic_comments_moderated_by_user_id_idx",
+ "columns": [
+ {
+ "expression": "moderated_by_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "topic_comments_workspace_id_idx": {
+ "name": "topic_comments_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "topic_comments_topic_id_topics_id_fk": {
+ "name": "topic_comments_topic_id_topics_id_fk",
+ "tableFrom": "topic_comments",
+ "tableTo": "topics",
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "topic_comments_message_id_messages_id_fk": {
+ "name": "topic_comments_message_id_messages_id_fk",
+ "tableFrom": "topic_comments",
+ "tableTo": "messages",
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "topic_comments_parent_comment_id_topic_comments_id_fk": {
+ "name": "topic_comments_parent_comment_id_topic_comments_id_fk",
+ "tableFrom": "topic_comments",
+ "tableTo": "topic_comments",
+ "columnsFrom": ["parent_comment_id"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "topic_comments_author_user_id_users_id_fk": {
+ "name": "topic_comments_author_user_id_users_id_fk",
+ "tableFrom": "topic_comments",
+ "tableTo": "users",
+ "columnsFrom": ["author_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "topic_comments_workspace_id_workspaces_id_fk": {
+ "name": "topic_comments_workspace_id_workspaces_id_fk",
+ "tableFrom": "topic_comments",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "topic_comments_moderated_by_user_id_users_id_fk": {
+ "name": "topic_comments_moderated_by_user_id_users_id_fk",
+ "tableFrom": "topic_comments",
+ "tableTo": "users",
+ "columnsFrom": ["moderated_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "topic_comments_anchored_requires_preview": {
+ "name": "topic_comments_anchored_requires_preview",
+ "value": "\"topic_comments\".\"message_id\" IS NULL OR \"topic_comments\".\"anchor_preview\" IS NOT NULL"
+ },
+ "topic_comments_reply_has_no_anchor": {
+ "name": "topic_comments_reply_has_no_anchor",
+ "value": "\"topic_comments\".\"parent_comment_id\" IS NULL OR (\"topic_comments\".\"message_id\" IS NULL AND \"topic_comments\".\"anchor_preview\" IS NULL)"
+ },
+ "topic_comments_moderation_window_consistent": {
+ "name": "topic_comments_moderation_window_consistent",
+ "value": "(\"topic_comments\".\"moderated_at\" IS NULL) = (\"topic_comments\".\"moderation_expires_at\" IS NULL)"
+ },
+ "topic_comments_deleted_not_recoverable": {
+ "name": "topic_comments_deleted_not_recoverable",
+ "value": "\"topic_comments\".\"deleted_at\" IS NULL OR \"topic_comments\".\"moderated_at\" IS NULL"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.trash_items": {
+ "name": "trash_items",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "resource_type": {
+ "name": "resource_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resource_id": {
+ "name": "resource_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "meta": {
+ "name": "meta",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "root_id": {
+ "name": "root_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deleted_by_user_id": {
+ "name": "deleted_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "trash_items_resource_unique": {
+ "name": "trash_items_resource_unique",
+ "columns": [
+ {
+ "expression": "resource_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resource_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "trash_items_personal_listing_idx": {
+ "name": "trash_items_personal_listing_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "deleted_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"trash_items\".\"root_id\" IS NULL AND \"trash_items\".\"workspace_id\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "trash_items_workspace_listing_idx": {
+ "name": "trash_items_workspace_listing_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "deleted_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"trash_items\".\"root_id\" IS NULL AND \"trash_items\".\"workspace_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "trash_items_expires_at_idx": {
+ "name": "trash_items_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"trash_items\".\"root_id\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "trash_items_root_id_idx": {
+ "name": "trash_items_root_id_idx",
+ "columns": [
+ {
+ "expression": "root_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "trash_items_root_id_trash_items_id_fk": {
+ "name": "trash_items_root_id_trash_items_id_fk",
+ "tableFrom": "trash_items",
+ "tableTo": "trash_items",
+ "columnsFrom": ["root_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "trash_items_user_id_users_id_fk": {
+ "name": "trash_items_user_id_users_id_fk",
+ "tableFrom": "trash_items",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "trash_items_workspace_id_workspaces_id_fk": {
+ "name": "trash_items_workspace_id_workspaces_id_fk",
+ "tableFrom": "trash_items",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "trash_items_deleted_by_user_id_users_id_fk": {
+ "name": "trash_items_deleted_by_user_id_users_id_fk",
+ "tableFrom": "trash_items",
+ "tableTo": "users",
+ "columnsFrom": ["deleted_by_user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_settings": {
+ "name": "user_settings",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "tts": {
+ "name": "tts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "hotkey": {
+ "name": "hotkey",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "key_vaults": {
+ "name": "key_vaults",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "general": {
+ "name": "general",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "language_model": {
+ "name": "language_model",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "system_agent": {
+ "name": "system_agent",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "default_agent": {
+ "name": "default_agent",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "market": {
+ "name": "market",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "memory": {
+ "name": "memory",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool": {
+ "name": "tool",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "image": {
+ "name": "image",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "notification": {
+ "name": "notification",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_settings_id_users_id_fk": {
+ "name": "user_settings_id_users_id_fk",
+ "tableFrom": "user_settings",
+ "tableTo": "users",
+ "columnsFrom": ["id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.users": {
+ "name": "users",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "username": {
+ "name": "username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "normalized_email": {
+ "name": "normalized_email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "avatar": {
+ "name": "avatar",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "phone": {
+ "name": "phone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "first_name": {
+ "name": "first_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_name": {
+ "name": "last_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "full_name": {
+ "name": "full_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "interests": {
+ "name": "interests",
+ "type": "varchar(64)[]",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_onboarded": {
+ "name": "is_onboarded",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "agent_onboarding": {
+ "name": "agent_onboarding",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "onboarding": {
+ "name": "onboarding",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clerk_created_at": {
+ "name": "clerk_created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "email_verified_at": {
+ "name": "email_verified_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "preference": {
+ "name": "preference",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banned": {
+ "name": "banned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "ban_reason": {
+ "name": "ban_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ban_expires": {
+ "name": "ban_expires",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "two_factor_enabled": {
+ "name": "two_factor_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "phone_number_verified": {
+ "name": "phone_number_verified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_active_at": {
+ "name": "last_active_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "users_email_idx": {
+ "name": "users_email_idx",
+ "columns": [
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "users_username_idx": {
+ "name": "users_username_idx",
+ "columns": [
+ {
+ "expression": "username",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "users_created_at_idx": {
+ "name": "users_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "users_banned_true_created_at_idx": {
+ "name": "users_banned_true_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"users\".\"banned\" = true",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "users_username_unique": {
+ "name": "users_username_unique",
+ "nullsNotDistinct": false,
+ "columns": ["username"]
+ },
+ "users_email_unique": {
+ "name": "users_email_unique",
+ "nullsNotDistinct": false,
+ "columns": ["email"]
+ },
+ "users_normalized_email_unique": {
+ "name": "users_normalized_email_unique",
+ "nullsNotDistinct": false,
+ "columns": ["normalized_email"]
+ },
+ "users_phone_unique": {
+ "name": "users_phone_unique",
+ "nullsNotDistinct": false,
+ "columns": ["phone"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_memories": {
+ "name": "user_memories",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "memory_category": {
+ "name": "memory_category",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "memory_layer": {
+ "name": "memory_layer",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "memory_type": {
+ "name": "memory_type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "summary_vector_1024": {
+ "name": "summary_vector_1024",
+ "type": "vector(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "details": {
+ "name": "details",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "details_vector_1024": {
+ "name": "details_vector_1024",
+ "type": "vector(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_count": {
+ "name": "accessed_count",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "last_accessed_at": {
+ "name": "last_accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "captured_at": {
+ "name": "captured_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_memories_summary_vector_1024_index": {
+ "name": "user_memories_summary_vector_1024_index",
+ "columns": [
+ {
+ "expression": "summary_vector_1024",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "vector_cosine_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "hnsw",
+ "with": {}
+ },
+ "user_memories_details_vector_1024_index": {
+ "name": "user_memories_details_vector_1024_index",
+ "columns": [
+ {
+ "expression": "details_vector_1024",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "vector_cosine_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "hnsw",
+ "with": {}
+ },
+ "user_memories_user_id_index": {
+ "name": "user_memories_user_id_index",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_memories_user_id_users_id_fk": {
+ "name": "user_memories_user_id_users_id_fk",
+ "tableFrom": "user_memories",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_memories_activities": {
+ "name": "user_memories_activities",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_memory_id": {
+ "name": "user_memory_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "starts_at": {
+ "name": "starts_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ends_at": {
+ "name": "ends_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "associated_objects": {
+ "name": "associated_objects",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "associated_subjects": {
+ "name": "associated_subjects",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "associated_locations": {
+ "name": "associated_locations",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "narrative": {
+ "name": "narrative",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "narrative_vector": {
+ "name": "narrative_vector",
+ "type": "vector(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "feedback": {
+ "name": "feedback",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "feedback_vector": {
+ "name": "feedback_vector",
+ "type": "vector(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "captured_at": {
+ "name": "captured_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_memories_activities_narrative_vector_index": {
+ "name": "user_memories_activities_narrative_vector_index",
+ "columns": [
+ {
+ "expression": "narrative_vector",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "vector_cosine_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "hnsw",
+ "with": {}
+ },
+ "user_memories_activities_feedback_vector_index": {
+ "name": "user_memories_activities_feedback_vector_index",
+ "columns": [
+ {
+ "expression": "feedback_vector",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "vector_cosine_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "hnsw",
+ "with": {}
+ },
+ "user_memories_activities_type_index": {
+ "name": "user_memories_activities_type_index",
+ "columns": [
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_memories_activities_user_id_index": {
+ "name": "user_memories_activities_user_id_index",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_memories_activities_user_memory_id_index": {
+ "name": "user_memories_activities_user_memory_id_index",
+ "columns": [
+ {
+ "expression": "user_memory_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_memories_activities_status_index": {
+ "name": "user_memories_activities_status_index",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_memories_activities_user_id_users_id_fk": {
+ "name": "user_memories_activities_user_id_users_id_fk",
+ "tableFrom": "user_memories_activities",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_memories_activities_user_memory_id_user_memories_id_fk": {
+ "name": "user_memories_activities_user_memory_id_user_memories_id_fk",
+ "tableFrom": "user_memories_activities",
+ "tableTo": "user_memories",
+ "columnsFrom": ["user_memory_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_memories_contexts": {
+ "name": "user_memories_contexts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_memory_ids": {
+ "name": "user_memory_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "associated_objects": {
+ "name": "associated_objects",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "associated_subjects": {
+ "name": "associated_subjects",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description_vector": {
+ "name": "description_vector",
+ "type": "vector(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "current_status": {
+ "name": "current_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "score_impact": {
+ "name": "score_impact",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "score_urgency": {
+ "name": "score_urgency",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "captured_at": {
+ "name": "captured_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_memories_contexts_description_vector_index": {
+ "name": "user_memories_contexts_description_vector_index",
+ "columns": [
+ {
+ "expression": "description_vector",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "vector_cosine_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "hnsw",
+ "with": {}
+ },
+ "user_memories_contexts_type_index": {
+ "name": "user_memories_contexts_type_index",
+ "columns": [
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_memories_contexts_user_id_index": {
+ "name": "user_memories_contexts_user_id_index",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_memories_contexts_user_memory_ids_gin_idx": {
+ "name": "user_memories_contexts_user_memory_ids_gin_idx",
+ "columns": [
+ {
+ "expression": "user_memory_ids",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_memories_contexts_user_id_users_id_fk": {
+ "name": "user_memories_contexts_user_id_users_id_fk",
+ "tableFrom": "user_memories_contexts",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_memories_experiences": {
+ "name": "user_memories_experiences",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_memory_id": {
+ "name": "user_memory_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "situation": {
+ "name": "situation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "situation_vector": {
+ "name": "situation_vector",
+ "type": "vector(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reasoning": {
+ "name": "reasoning",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "possible_outcome": {
+ "name": "possible_outcome",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "action_vector": {
+ "name": "action_vector",
+ "type": "vector(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "key_learning": {
+ "name": "key_learning",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "key_learning_vector": {
+ "name": "key_learning_vector",
+ "type": "vector(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "score_confidence": {
+ "name": "score_confidence",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "captured_at": {
+ "name": "captured_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_memories_experiences_situation_vector_index": {
+ "name": "user_memories_experiences_situation_vector_index",
+ "columns": [
+ {
+ "expression": "situation_vector",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "vector_cosine_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "hnsw",
+ "with": {}
+ },
+ "user_memories_experiences_action_vector_index": {
+ "name": "user_memories_experiences_action_vector_index",
+ "columns": [
+ {
+ "expression": "action_vector",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "vector_cosine_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "hnsw",
+ "with": {}
+ },
+ "user_memories_experiences_key_learning_vector_index": {
+ "name": "user_memories_experiences_key_learning_vector_index",
+ "columns": [
+ {
+ "expression": "key_learning_vector",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "vector_cosine_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "hnsw",
+ "with": {}
+ },
+ "user_memories_experiences_type_index": {
+ "name": "user_memories_experiences_type_index",
+ "columns": [
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_memories_experiences_user_id_index": {
+ "name": "user_memories_experiences_user_id_index",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_memories_experiences_user_memory_id_index": {
+ "name": "user_memories_experiences_user_memory_id_index",
+ "columns": [
+ {
+ "expression": "user_memory_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_memories_experiences_user_id_users_id_fk": {
+ "name": "user_memories_experiences_user_id_users_id_fk",
+ "tableFrom": "user_memories_experiences",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_memories_experiences_user_memory_id_user_memories_id_fk": {
+ "name": "user_memories_experiences_user_memory_id_user_memories_id_fk",
+ "tableFrom": "user_memories_experiences",
+ "tableTo": "user_memories",
+ "columnsFrom": ["user_memory_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_memories_identities": {
+ "name": "user_memories_identities",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_memory_id": {
+ "name": "user_memory_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description_vector": {
+ "name": "description_vector",
+ "type": "vector(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "episodic_date": {
+ "name": "episodic_date",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "relationship": {
+ "name": "relationship",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "captured_at": {
+ "name": "captured_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_memories_identities_description_vector_index": {
+ "name": "user_memories_identities_description_vector_index",
+ "columns": [
+ {
+ "expression": "description_vector",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "vector_cosine_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "hnsw",
+ "with": {}
+ },
+ "user_memories_identities_type_index": {
+ "name": "user_memories_identities_type_index",
+ "columns": [
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_memories_identities_user_id_index": {
+ "name": "user_memories_identities_user_id_index",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_memories_identities_user_memory_id_index": {
+ "name": "user_memories_identities_user_memory_id_index",
+ "columns": [
+ {
+ "expression": "user_memory_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_memories_identities_user_id_users_id_fk": {
+ "name": "user_memories_identities_user_id_users_id_fk",
+ "tableFrom": "user_memories_identities",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_memories_identities_user_memory_id_user_memories_id_fk": {
+ "name": "user_memories_identities_user_memory_id_user_memories_id_fk",
+ "tableFrom": "user_memories_identities",
+ "tableTo": "user_memories",
+ "columnsFrom": ["user_memory_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_memories_preferences": {
+ "name": "user_memories_preferences",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_memory_id": {
+ "name": "user_memory_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "conclusion_directives": {
+ "name": "conclusion_directives",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "conclusion_directives_vector": {
+ "name": "conclusion_directives_vector",
+ "type": "vector(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "suggestions": {
+ "name": "suggestions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "score_priority": {
+ "name": "score_priority",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "captured_at": {
+ "name": "captured_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_memories_preferences_conclusion_directives_vector_index": {
+ "name": "user_memories_preferences_conclusion_directives_vector_index",
+ "columns": [
+ {
+ "expression": "conclusion_directives_vector",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last",
+ "opclass": "vector_cosine_ops"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "hnsw",
+ "with": {}
+ },
+ "user_memories_preferences_user_id_index": {
+ "name": "user_memories_preferences_user_id_index",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_memories_preferences_user_memory_id_index": {
+ "name": "user_memories_preferences_user_memory_id_index",
+ "columns": [
+ {
+ "expression": "user_memory_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_memories_preferences_user_id_users_id_fk": {
+ "name": "user_memories_preferences_user_id_users_id_fk",
+ "tableFrom": "user_memories_preferences",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_memories_preferences_user_memory_id_user_memories_id_fk": {
+ "name": "user_memories_preferences_user_memory_id_user_memories_id_fk",
+ "tableFrom": "user_memories_preferences",
+ "tableTo": "user_memories",
+ "columnsFrom": ["user_memory_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_memory_persona_document_histories": {
+ "name": "user_memory_persona_document_histories",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "persona_id": {
+ "name": "persona_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "profile": {
+ "name": "profile",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'default'"
+ },
+ "snapshot_persona": {
+ "name": "snapshot_persona",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "snapshot_tagline": {
+ "name": "snapshot_tagline",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reasoning": {
+ "name": "reasoning",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "diff_persona": {
+ "name": "diff_persona",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "diff_tagline": {
+ "name": "diff_tagline",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "edited_by": {
+ "name": "edited_by",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'agent'"
+ },
+ "memory_ids": {
+ "name": "memory_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_ids": {
+ "name": "source_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "previous_version": {
+ "name": "previous_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "next_version": {
+ "name": "next_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "captured_at": {
+ "name": "captured_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_persona_document_histories_persona_id_index": {
+ "name": "user_persona_document_histories_persona_id_index",
+ "columns": [
+ {
+ "expression": "persona_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_persona_document_histories_user_id_index": {
+ "name": "user_persona_document_histories_user_id_index",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_persona_document_histories_profile_index": {
+ "name": "user_persona_document_histories_profile_index",
+ "columns": [
+ {
+ "expression": "profile",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_memory_persona_document_histories_user_id_users_id_fk": {
+ "name": "user_memory_persona_document_histories_user_id_users_id_fk",
+ "tableFrom": "user_memory_persona_document_histories",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_memory_persona_document_histories_persona_id_user_memory_persona_documents_id_fk": {
+ "name": "user_memory_persona_document_histories_persona_id_user_memory_persona_documents_id_fk",
+ "tableFrom": "user_memory_persona_document_histories",
+ "tableTo": "user_memory_persona_documents",
+ "columnsFrom": ["persona_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_memory_persona_documents": {
+ "name": "user_memory_persona_documents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "profile": {
+ "name": "profile",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'default'"
+ },
+ "tagline": {
+ "name": "tagline",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "persona": {
+ "name": "persona",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "memory_ids": {
+ "name": "memory_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_ids": {
+ "name": "source_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "captured_at": {
+ "name": "captured_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_persona_documents_user_id_profile_unique": {
+ "name": "user_persona_documents_user_id_profile_unique",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "profile",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_persona_documents_user_id_index": {
+ "name": "user_persona_documents_user_id_index",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_memory_persona_documents_user_id_users_id_fk": {
+ "name": "user_memory_persona_documents_user_id_users_id_fk",
+ "tableFrom": "user_memory_persona_documents",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.acceptances": {
+ "name": "acceptances",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "subject_type": {
+ "name": "subject_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "subject_id": {
+ "name": "subject_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "requirement": {
+ "name": "requirement",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "visual_render": {
+ "name": "visual_render",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "acceptances_user_id_idx": {
+ "name": "acceptances_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "acceptances_workspace_id_idx": {
+ "name": "acceptances_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "acceptances_project_id_idx": {
+ "name": "acceptances_project_id_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "acceptances_subject_idx": {
+ "name": "acceptances_subject_idx",
+ "columns": [
+ {
+ "expression": "subject_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "subject_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "acceptances_status_idx": {
+ "name": "acceptances_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "acceptances_workspace_visibility_idx": {
+ "name": "acceptances_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "acceptances_personal_subject_unique": {
+ "name": "acceptances_personal_subject_unique",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "subject_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "subject_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"acceptances\".\"workspace_id\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "acceptances_workspace_subject_unique": {
+ "name": "acceptances_workspace_subject_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "subject_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "subject_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"acceptances\".\"workspace_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "acceptances_user_id_users_id_fk": {
+ "name": "acceptances_user_id_users_id_fk",
+ "tableFrom": "acceptances",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "acceptances_workspace_id_workspaces_id_fk": {
+ "name": "acceptances_workspace_id_workspaces_id_fk",
+ "tableFrom": "acceptances",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "acceptances_project_id_projects_id_fk": {
+ "name": "acceptances_project_id_projects_id_fk",
+ "tableFrom": "acceptances",
+ "tableTo": "projects",
+ "columnsFrom": ["project_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verify_check_results": {
+ "name": "verify_check_results",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "verify_run_id": {
+ "name": "verify_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "operation_id": {
+ "name": "operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "check_item_id": {
+ "name": "check_item_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "check_item_title": {
+ "name": "check_item_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "required": {
+ "name": "required",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "check_item_index": {
+ "name": "check_item_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "verifier_type": {
+ "name": "verifier_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "verifier_config_hash": {
+ "name": "verifier_config_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "verifier_operation_id": {
+ "name": "verifier_operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "verifier_tracing_id": {
+ "name": "verifier_tracing_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "verdict": {
+ "name": "verdict",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "confidence": {
+ "name": "confidence",
+ "type": "numeric(3, 2)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "toulmin": {
+ "name": "toulmin",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "suggestion": {
+ "name": "suggestion",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_decision": {
+ "name": "user_decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_decision_detail": {
+ "name": "user_decision_detail",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_false_positive": {
+ "name": "is_false_positive",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_false_negative": {
+ "name": "is_false_negative",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "repair_operation_id": {
+ "name": "repair_operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "verify_check_results_verify_run_id_idx": {
+ "name": "verify_check_results_verify_run_id_idx",
+ "columns": [
+ {
+ "expression": "verify_run_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_check_results_operation_id_idx": {
+ "name": "verify_check_results_operation_id_idx",
+ "columns": [
+ {
+ "expression": "operation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_check_results_user_id_idx": {
+ "name": "verify_check_results_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_check_results_verify_run_id_check_item_id_unique": {
+ "name": "verify_check_results_verify_run_id_check_item_id_unique",
+ "columns": [
+ {
+ "expression": "verify_run_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "check_item_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_check_results_verifier_type_idx": {
+ "name": "verify_check_results_verifier_type_idx",
+ "columns": [
+ {
+ "expression": "verifier_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_check_results_verifier_operation_id_idx": {
+ "name": "verify_check_results_verifier_operation_id_idx",
+ "columns": [
+ {
+ "expression": "verifier_operation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_check_results_verifier_tracing_id_idx": {
+ "name": "verify_check_results_verifier_tracing_id_idx",
+ "columns": [
+ {
+ "expression": "verifier_tracing_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_check_results_status_idx": {
+ "name": "verify_check_results_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_check_results_verdict_idx": {
+ "name": "verify_check_results_verdict_idx",
+ "columns": [
+ {
+ "expression": "verdict",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_check_results_repair_operation_id_idx": {
+ "name": "verify_check_results_repair_operation_id_idx",
+ "columns": [
+ {
+ "expression": "repair_operation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_check_results_workspace_id_idx": {
+ "name": "verify_check_results_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "verify_check_results_verify_run_id_verify_runs_id_fk": {
+ "name": "verify_check_results_verify_run_id_verify_runs_id_fk",
+ "tableFrom": "verify_check_results",
+ "tableTo": "verify_runs",
+ "columnsFrom": ["verify_run_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_check_results_operation_id_agent_operations_id_fk": {
+ "name": "verify_check_results_operation_id_agent_operations_id_fk",
+ "tableFrom": "verify_check_results",
+ "tableTo": "agent_operations",
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "verify_check_results_user_id_users_id_fk": {
+ "name": "verify_check_results_user_id_users_id_fk",
+ "tableFrom": "verify_check_results",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_check_results_workspace_id_workspaces_id_fk": {
+ "name": "verify_check_results_workspace_id_workspaces_id_fk",
+ "tableFrom": "verify_check_results",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_check_results_verifier_operation_id_agent_operations_id_fk": {
+ "name": "verify_check_results_verifier_operation_id_agent_operations_id_fk",
+ "tableFrom": "verify_check_results",
+ "tableTo": "agent_operations",
+ "columnsFrom": ["verifier_operation_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "verify_check_results_verifier_tracing_id_llm_generation_tracing_id_fk": {
+ "name": "verify_check_results_verifier_tracing_id_llm_generation_tracing_id_fk",
+ "tableFrom": "verify_check_results",
+ "tableTo": "llm_generation_tracing",
+ "columnsFrom": ["verifier_tracing_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "verify_check_results_repair_operation_id_agent_operations_id_fk": {
+ "name": "verify_check_results_repair_operation_id_agent_operations_id_fk",
+ "tableFrom": "verify_check_results",
+ "tableTo": "agent_operations",
+ "columnsFrom": ["repair_operation_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verify_criteria": {
+ "name": "verify_criteria",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "required": {
+ "name": "required",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "verifier_type": {
+ "name": "verifier_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "verifier_config": {
+ "name": "verifier_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "on_fail": {
+ "name": "on_fail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'manual'"
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "verify_criteria_user_id_idx": {
+ "name": "verify_criteria_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_criteria_verifier_type_idx": {
+ "name": "verify_criteria_verifier_type_idx",
+ "columns": [
+ {
+ "expression": "verifier_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_criteria_document_id_idx": {
+ "name": "verify_criteria_document_id_idx",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_criteria_workspace_id_idx": {
+ "name": "verify_criteria_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "verify_criteria_user_id_users_id_fk": {
+ "name": "verify_criteria_user_id_users_id_fk",
+ "tableFrom": "verify_criteria",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_criteria_document_id_documents_id_fk": {
+ "name": "verify_criteria_document_id_documents_id_fk",
+ "tableFrom": "verify_criteria",
+ "tableTo": "documents",
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "verify_criteria_workspace_id_workspaces_id_fk": {
+ "name": "verify_criteria_workspace_id_workspaces_id_fk",
+ "tableFrom": "verify_criteria",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verify_evidence": {
+ "name": "verify_evidence",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "check_result_id": {
+ "name": "check_result_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_id": {
+ "name": "file_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "captured_by": {
+ "name": "captured_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "captured_at": {
+ "name": "captured_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "verify_evidence_check_result_id_idx": {
+ "name": "verify_evidence_check_result_id_idx",
+ "columns": [
+ {
+ "expression": "check_result_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_evidence_document_id_idx": {
+ "name": "verify_evidence_document_id_idx",
+ "columns": [
+ {
+ "expression": "document_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_evidence_file_id_idx": {
+ "name": "verify_evidence_file_id_idx",
+ "columns": [
+ {
+ "expression": "file_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_evidence_user_id_idx": {
+ "name": "verify_evidence_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_evidence_workspace_id_idx": {
+ "name": "verify_evidence_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "verify_evidence_check_result_id_verify_check_results_id_fk": {
+ "name": "verify_evidence_check_result_id_verify_check_results_id_fk",
+ "tableFrom": "verify_evidence",
+ "tableTo": "verify_check_results",
+ "columnsFrom": ["check_result_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_evidence_document_id_documents_id_fk": {
+ "name": "verify_evidence_document_id_documents_id_fk",
+ "tableFrom": "verify_evidence",
+ "tableTo": "documents",
+ "columnsFrom": ["document_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "verify_evidence_file_id_files_id_fk": {
+ "name": "verify_evidence_file_id_files_id_fk",
+ "tableFrom": "verify_evidence",
+ "tableTo": "files",
+ "columnsFrom": ["file_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "verify_evidence_user_id_users_id_fk": {
+ "name": "verify_evidence_user_id_users_id_fk",
+ "tableFrom": "verify_evidence",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_evidence_workspace_id_workspaces_id_fk": {
+ "name": "verify_evidence_workspace_id_workspaces_id_fk",
+ "tableFrom": "verify_evidence",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verify_reports": {
+ "name": "verify_reports",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "verify_run_id": {
+ "name": "verify_run_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "operation_id": {
+ "name": "operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "verdict": {
+ "name": "verdict",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "overall_confidence": {
+ "name": "overall_confidence",
+ "type": "numeric(3, 2)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "total_checks": {
+ "name": "total_checks",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "passed_checks": {
+ "name": "passed_checks",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "failed_checks": {
+ "name": "failed_checks",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "uncertain_checks": {
+ "name": "uncertain_checks",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reviewed_by_user": {
+ "name": "reviewed_by_user",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "generated_by": {
+ "name": "generated_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'system'"
+ },
+ "generated_at": {
+ "name": "generated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "verify_reports_verify_run_id_unique": {
+ "name": "verify_reports_verify_run_id_unique",
+ "columns": [
+ {
+ "expression": "verify_run_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_reports_operation_id_idx": {
+ "name": "verify_reports_operation_id_idx",
+ "columns": [
+ {
+ "expression": "operation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_reports_user_id_idx": {
+ "name": "verify_reports_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_reports_workspace_id_idx": {
+ "name": "verify_reports_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "verify_reports_verify_run_id_verify_runs_id_fk": {
+ "name": "verify_reports_verify_run_id_verify_runs_id_fk",
+ "tableFrom": "verify_reports",
+ "tableTo": "verify_runs",
+ "columnsFrom": ["verify_run_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_reports_operation_id_agent_operations_id_fk": {
+ "name": "verify_reports_operation_id_agent_operations_id_fk",
+ "tableFrom": "verify_reports",
+ "tableTo": "agent_operations",
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "verify_reports_user_id_users_id_fk": {
+ "name": "verify_reports_user_id_users_id_fk",
+ "tableFrom": "verify_reports",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_reports_workspace_id_workspaces_id_fk": {
+ "name": "verify_reports_workspace_id_workspaces_id_fk",
+ "tableFrom": "verify_reports",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verify_review_predictions": {
+ "name": "verify_review_predictions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "check_result_id": {
+ "name": "check_result_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prompt_version": {
+ "name": "prompt_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status_reason": {
+ "name": "status_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "confidence": {
+ "name": "confidence",
+ "type": "numeric(3, 2)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "comment": {
+ "name": "comment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rationale": {
+ "name": "rationale",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "annotations": {
+ "name": "annotations",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "adjudication": {
+ "name": "adjudication",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "adjudication_edit": {
+ "name": "adjudication_edit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "adjudicated_at": {
+ "name": "adjudicated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "latency_ms": {
+ "name": "latency_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "prompt_tokens": {
+ "name": "prompt_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completion_tokens": {
+ "name": "completion_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "verify_review_predictions_check_result_id_idx": {
+ "name": "verify_review_predictions_check_result_id_idx",
+ "columns": [
+ {
+ "expression": "check_result_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_review_predictions_user_id_idx": {
+ "name": "verify_review_predictions_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_review_predictions_workspace_id_idx": {
+ "name": "verify_review_predictions_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_review_predictions_model_idx": {
+ "name": "verify_review_predictions_model_idx",
+ "columns": [
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "model",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_review_predictions_result_model_prompt_unique": {
+ "name": "verify_review_predictions_result_model_prompt_unique",
+ "columns": [
+ {
+ "expression": "check_result_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "model",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "prompt_version",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "verify_review_predictions_check_result_id_verify_check_results_id_fk": {
+ "name": "verify_review_predictions_check_result_id_verify_check_results_id_fk",
+ "tableFrom": "verify_review_predictions",
+ "tableTo": "verify_check_results",
+ "columnsFrom": ["check_result_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_review_predictions_user_id_users_id_fk": {
+ "name": "verify_review_predictions_user_id_users_id_fk",
+ "tableFrom": "verify_review_predictions",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_review_predictions_workspace_id_workspaces_id_fk": {
+ "name": "verify_review_predictions_workspace_id_workspaces_id_fk",
+ "tableFrom": "verify_review_predictions",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "verify_review_predictions_action_matches_status": {
+ "name": "verify_review_predictions_action_matches_status",
+ "value": "(\"verify_review_predictions\".\"status\" = 'judged') = (\"verify_review_predictions\".\"action\" IS NOT NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.verify_rubric_criteria": {
+ "name": "verify_rubric_criteria",
+ "schema": "",
+ "columns": {
+ "rubric_id": {
+ "name": "rubric_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "criterion_id": {
+ "name": "criterion_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "verify_rubric_criteria_criterion_id_idx": {
+ "name": "verify_rubric_criteria_criterion_id_idx",
+ "columns": [
+ {
+ "expression": "criterion_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_rubric_criteria_user_id_idx": {
+ "name": "verify_rubric_criteria_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_rubric_criteria_workspace_id_idx": {
+ "name": "verify_rubric_criteria_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "verify_rubric_criteria_rubric_id_verify_rubrics_id_fk": {
+ "name": "verify_rubric_criteria_rubric_id_verify_rubrics_id_fk",
+ "tableFrom": "verify_rubric_criteria",
+ "tableTo": "verify_rubrics",
+ "columnsFrom": ["rubric_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_rubric_criteria_criterion_id_verify_criteria_id_fk": {
+ "name": "verify_rubric_criteria_criterion_id_verify_criteria_id_fk",
+ "tableFrom": "verify_rubric_criteria",
+ "tableTo": "verify_criteria",
+ "columnsFrom": ["criterion_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_rubric_criteria_user_id_users_id_fk": {
+ "name": "verify_rubric_criteria_user_id_users_id_fk",
+ "tableFrom": "verify_rubric_criteria",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_rubric_criteria_workspace_id_workspaces_id_fk": {
+ "name": "verify_rubric_criteria_workspace_id_workspaces_id_fk",
+ "tableFrom": "verify_rubric_criteria",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "verify_rubric_criteria_rubric_id_criterion_id_pk": {
+ "name": "verify_rubric_criteria_rubric_id_criterion_id_pk",
+ "columns": ["rubric_id", "criterion_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verify_rubrics": {
+ "name": "verify_rubrics",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "verify_rubrics_user_id_idx": {
+ "name": "verify_rubrics_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_rubrics_workspace_id_idx": {
+ "name": "verify_rubrics_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "verify_rubrics_user_id_users_id_fk": {
+ "name": "verify_rubrics_user_id_users_id_fk",
+ "tableFrom": "verify_rubrics",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_rubrics_workspace_id_workspaces_id_fk": {
+ "name": "verify_rubrics_workspace_id_workspaces_id_fk",
+ "tableFrom": "verify_rubrics",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verify_runs": {
+ "name": "verify_runs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "acceptance_id": {
+ "name": "acceptance_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "round_index": {
+ "name": "round_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "operation_id": {
+ "name": "operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'agent'"
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'public'"
+ },
+ "scenario": {
+ "name": "scenario",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "goal": {
+ "name": "goal",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "context": {
+ "name": "context",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "plan": {
+ "name": "plan",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "plan_confirmed_at": {
+ "name": "plan_confirmed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_decision": {
+ "name": "user_decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "decision_detail": {
+ "name": "decision_detail",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessed_at": {
+ "name": "accessed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "verify_runs_user_id_idx": {
+ "name": "verify_runs_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_runs_workspace_id_idx": {
+ "name": "verify_runs_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_runs_acceptance_id_idx": {
+ "name": "verify_runs_acceptance_id_idx",
+ "columns": [
+ {
+ "expression": "acceptance_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_runs_acceptance_round_unique": {
+ "name": "verify_runs_acceptance_round_unique",
+ "columns": [
+ {
+ "expression": "acceptance_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "round_index",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_runs_operation_id_unique": {
+ "name": "verify_runs_operation_id_unique",
+ "columns": [
+ {
+ "expression": "operation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_runs_source_idx": {
+ "name": "verify_runs_source_idx",
+ "columns": [
+ {
+ "expression": "source",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verify_runs_user_decision_idx": {
+ "name": "verify_runs_user_decision_idx",
+ "columns": [
+ {
+ "expression": "user_decision",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "verify_runs_user_id_users_id_fk": {
+ "name": "verify_runs_user_id_users_id_fk",
+ "tableFrom": "verify_runs",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_runs_workspace_id_workspaces_id_fk": {
+ "name": "verify_runs_workspace_id_workspaces_id_fk",
+ "tableFrom": "verify_runs",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "verify_runs_acceptance_id_acceptances_id_fk": {
+ "name": "verify_runs_acceptance_id_acceptances_id_fk",
+ "tableFrom": "verify_runs",
+ "tableTo": "acceptances",
+ "columnsFrom": ["acceptance_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "verify_runs_operation_id_agent_operations_id_fk": {
+ "name": "verify_runs_operation_id_agent_operations_id_fk",
+ "tableFrom": "verify_runs",
+ "tableTo": "agent_operations",
+ "columnsFrom": ["operation_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "verify_runs_acceptance_requires_round": {
+ "name": "verify_runs_acceptance_requires_round",
+ "value": "\"verify_runs\".\"acceptance_id\" IS NULL OR \"verify_runs\".\"round_index\" IS NOT NULL"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.work_versions": {
+ "name": "work_versions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "work_id": {
+ "name": "work_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "change_type": {
+ "name": "change_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tool_name": {
+ "name": "tool_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tool_identifier": {
+ "name": "tool_identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "topic_id": {
+ "name": "topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "root_operation_id": {
+ "name": "root_operation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_call_id": {
+ "name": "tool_call_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cumulative_cost": {
+ "name": "cumulative_cost",
+ "type": "numeric(20, 6)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cumulative_usage": {
+ "name": "cumulative_usage",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "work_versions_work_id_version_unique": {
+ "name": "work_versions_work_id_version_unique",
+ "columns": [
+ {
+ "expression": "work_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "version",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "work_versions_work_id_tool_call_id_unique": {
+ "name": "work_versions_work_id_tool_call_id_unique",
+ "columns": [
+ {
+ "expression": "work_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "tool_call_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"work_versions\".\"tool_call_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "work_versions_thread_id_idx": {
+ "name": "work_versions_thread_id_idx",
+ "columns": [
+ {
+ "expression": "thread_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "work_versions_message_id_idx": {
+ "name": "work_versions_message_id_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "work_versions_agent_id_idx": {
+ "name": "work_versions_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "work_versions_root_operation_created_at_idx": {
+ "name": "work_versions_root_operation_created_at_idx",
+ "columns": [
+ {
+ "expression": "root_operation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "work_versions_topic_created_at_idx": {
+ "name": "work_versions_topic_created_at_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "work_versions_topic_thread_created_at_idx": {
+ "name": "work_versions_topic_thread_created_at_idx",
+ "columns": [
+ {
+ "expression": "topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "thread_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "work_versions_work_id_works_id_fk": {
+ "name": "work_versions_work_id_works_id_fk",
+ "tableFrom": "work_versions",
+ "tableTo": "works",
+ "columnsFrom": ["work_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "work_versions_topic_id_topics_id_fk": {
+ "name": "work_versions_topic_id_topics_id_fk",
+ "tableFrom": "work_versions",
+ "tableTo": "topics",
+ "columnsFrom": ["topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "work_versions_thread_id_threads_id_fk": {
+ "name": "work_versions_thread_id_threads_id_fk",
+ "tableFrom": "work_versions",
+ "tableTo": "threads",
+ "columnsFrom": ["thread_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "work_versions_message_id_messages_id_fk": {
+ "name": "work_versions_message_id_messages_id_fk",
+ "tableFrom": "work_versions",
+ "tableTo": "messages",
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "work_versions_agent_id_agents_id_fk": {
+ "name": "work_versions_agent_id_agents_id_fk",
+ "tableFrom": "work_versions",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.works": {
+ "name": "works",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "current_version_id": {
+ "name": "current_version_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resource_type": {
+ "name": "resource_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resource_id": {
+ "name": "resource_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_name": {
+ "name": "tool_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tool_identifier": {
+ "name": "tool_identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "origin_topic_id": {
+ "name": "origin_topic_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "origin_thread_id": {
+ "name": "origin_thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "origin_agent_id": {
+ "name": "origin_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "works_resource_user_unique": {
+ "name": "works_resource_user_unique",
+ "columns": [
+ {
+ "expression": "resource_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resource_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"works\".\"workspace_id\" is null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "works_resource_workspace_unique": {
+ "name": "works_resource_workspace_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resource_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resource_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"works\".\"workspace_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "works_user_id_idx": {
+ "name": "works_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "works_workspace_id_idx": {
+ "name": "works_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "works_workspace_visibility_idx": {
+ "name": "works_workspace_visibility_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "visibility",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "works_user_updated_at_id_idx": {
+ "name": "works_user_updated_at_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"works\".\"workspace_id\" is null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "works_workspace_updated_at_id_idx": {
+ "name": "works_workspace_updated_at_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"works\".\"workspace_id\" is not null",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "works_origin_topic_id_idx": {
+ "name": "works_origin_topic_id_idx",
+ "columns": [
+ {
+ "expression": "origin_topic_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "works_origin_thread_id_idx": {
+ "name": "works_origin_thread_id_idx",
+ "columns": [
+ {
+ "expression": "origin_thread_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "works_origin_agent_id_idx": {
+ "name": "works_origin_agent_id_idx",
+ "columns": [
+ {
+ "expression": "origin_agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "works_origin_topic_id_topics_id_fk": {
+ "name": "works_origin_topic_id_topics_id_fk",
+ "tableFrom": "works",
+ "tableTo": "topics",
+ "columnsFrom": ["origin_topic_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "works_origin_thread_id_threads_id_fk": {
+ "name": "works_origin_thread_id_threads_id_fk",
+ "tableFrom": "works",
+ "tableTo": "threads",
+ "columnsFrom": ["origin_thread_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "works_origin_agent_id_agents_id_fk": {
+ "name": "works_origin_agent_id_agents_id_fk",
+ "tableFrom": "works",
+ "tableTo": "agents",
+ "columnsFrom": ["origin_agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "works_user_id_users_id_fk": {
+ "name": "works_user_id_users_id_fk",
+ "tableFrom": "works",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "works_workspace_id_workspaces_id_fk": {
+ "name": "works_workspace_id_workspaces_id_fk",
+ "tableFrom": "works",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.workspace_audit_logs": {
+ "name": "workspace_audit_logs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resource_type": {
+ "name": "resource_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resource_id": {
+ "name": "resource_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "workspace_audit_logs_workspace_id_idx": {
+ "name": "workspace_audit_logs_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workspace_audit_logs_action_idx": {
+ "name": "workspace_audit_logs_action_idx",
+ "columns": [
+ {
+ "expression": "action",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workspace_audit_logs_created_at_idx": {
+ "name": "workspace_audit_logs_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "workspace_audit_logs_workspace_id_workspaces_id_fk": {
+ "name": "workspace_audit_logs_workspace_id_workspaces_id_fk",
+ "tableFrom": "workspace_audit_logs",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.workspace_invitations": {
+ "name": "workspace_invitations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "inviter_id": {
+ "name": "inviter_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'member'"
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "workspace_invitations_workspace_id_idx": {
+ "name": "workspace_invitations_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workspace_invitations_email_idx": {
+ "name": "workspace_invitations_email_idx",
+ "columns": [
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workspace_invitations_token_idx": {
+ "name": "workspace_invitations_token_idx",
+ "columns": [
+ {
+ "expression": "token",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "workspace_invitations_workspace_id_workspaces_id_fk": {
+ "name": "workspace_invitations_workspace_id_workspaces_id_fk",
+ "tableFrom": "workspace_invitations",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "workspace_invitations_inviter_id_users_id_fk": {
+ "name": "workspace_invitations_inviter_id_users_id_fk",
+ "tableFrom": "workspace_invitations",
+ "tableTo": "users",
+ "columnsFrom": ["inviter_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "workspace_invitations_token_unique": {
+ "name": "workspace_invitations_token_unique",
+ "nullsNotDistinct": false,
+ "columns": ["token"]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.workspace_members": {
+ "name": "workspace_members",
+ "schema": "",
+ "columns": {
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'member'"
+ },
+ "joined_at": {
+ "name": "joined_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "workspace_members_user_id_idx": {
+ "name": "workspace_members_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workspace_members_unique_active_owner_idx": {
+ "name": "workspace_members_unique_active_owner_idx",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"workspace_members\".\"role\" = 'owner' AND \"workspace_members\".\"deleted_at\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "workspace_members_workspace_id_workspaces_id_fk": {
+ "name": "workspace_members_workspace_id_workspaces_id_fk",
+ "tableFrom": "workspace_members",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "workspace_members_user_id_users_id_fk": {
+ "name": "workspace_members_user_id_users_id_fk",
+ "tableFrom": "workspace_members",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "workspace_members_workspace_id_user_id_pk": {
+ "name": "workspace_members_workspace_id_user_id_pk",
+ "columns": ["workspace_id", "user_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.workspace_user_settings": {
+ "name": "workspace_user_settings",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "preference": {
+ "name": "preference",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "workspace_user_settings_workspace_id_user_id_unique": {
+ "name": "workspace_user_settings_workspace_id_user_id_unique",
+ "columns": [
+ {
+ "expression": "workspace_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workspace_user_settings_user_id_idx": {
+ "name": "workspace_user_settings_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "workspace_user_settings_workspace_id_workspaces_id_fk": {
+ "name": "workspace_user_settings_workspace_id_workspaces_id_fk",
+ "tableFrom": "workspace_user_settings",
+ "tableTo": "workspaces",
+ "columnsFrom": ["workspace_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "workspace_user_settings_user_id_users_id_fk": {
+ "name": "workspace_user_settings_user_id_users_id_fk",
+ "tableFrom": "workspace_user_settings",
+ "tableTo": "users",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.workspaces": {
+ "name": "workspaces",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "varchar(100)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "varchar(1000)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "avatar": {
+ "name": "avatar",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "primary_owner_id": {
+ "name": "primary_owner_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "settings": {
+ "name": "settings",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "frozen": {
+ "name": "frozen",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "frozen_reason": {
+ "name": "frozen_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "frozen_at": {
+ "name": "frozen_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "workspaces_slug_idx": {
+ "name": "workspaces_slug_idx",
+ "columns": [
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workspaces_primary_owner_id_idx": {
+ "name": "workspaces_primary_owner_id_idx",
+ "columns": [
+ {
+ "expression": "primary_owner_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "workspaces_primary_owner_id_users_id_fk": {
+ "name": "workspaces_primary_owner_id_users_id_fk",
+ "tableFrom": "workspaces",
+ "tableTo": "users",
+ "columnsFrom": ["primary_owner_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "version": "7",
+ "views": {}
+}
diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json
index 67eda327a42..53fff648c42 100644
--- a/packages/database/migrations/meta/_journal.json
+++ b/packages/database/migrations/meta/_journal.json
@@ -1071,6 +1071,13 @@
"when": 1788016606062,
"tag": "0152_trash_goal_traces_eval_dataset",
"breakpoints": true
+ },
+ {
+ "idx": 153,
+ "version": "7",
+ "when": 1788108760793,
+ "tag": "0153_fts_search_sync_outbox",
+ "breakpoints": true
}
],
"version": "6"
diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.ts
index 3e2c90d2934..d30cc1269b1 100644
--- a/packages/database/src/models/__tests__/messages/message.query.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts
@@ -1756,6 +1756,84 @@ describe('MessageModel Query Tests', () => {
});
});
+ describe('queryByKeyword with external candidates', () => {
+ it('hydrates current-scope messages in the legacy recency order', async () => {
+ await serverDB.insert(messages).values([
+ {
+ content: 'Own older message',
+ createdAt: new Date('2026-08-20T00:00:00.000Z'),
+ id: 'candidate-message-old',
+ role: 'user',
+ userId,
+ },
+ {
+ content: 'Own recent message',
+ createdAt: new Date('2026-08-25T00:00:00.000Z'),
+ id: 'candidate-message-recent',
+ role: 'assistant',
+ userId,
+ },
+ {
+ content: 'Other user message',
+ id: 'candidate-message-other',
+ role: 'user',
+ userId: otherUserId,
+ },
+ ]);
+ const ftsSearchCandidates = vi.fn().mockResolvedValue({
+ candidates: [
+ { id: 'candidate-message-other', score: 12 },
+ { id: 'candidate-message-deleted', score: 10 },
+ { id: 'candidate-message-old', score: 8 },
+ { id: 'candidate-message-recent', score: 6 },
+ ],
+ total: 4,
+ });
+ const model = new MessageModel(serverDB, userId, undefined, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates,
+ });
+
+ const result = await model.queryByKeyword('candidate');
+
+ expect(result.map(({ id }) => id)).toEqual([
+ 'candidate-message-recent',
+ 'candidate-message-old',
+ ]);
+ expect(ftsSearchCandidates).toHaveBeenCalledWith({
+ entity: 'messages',
+ filters: {},
+ pagination: {},
+ query: { fields: ['content'], text: 'candidate' },
+ });
+ });
+
+ it('hydrates candidate sets larger than the PostgreSQL bind-parameter limit', async () => {
+ await serverDB.insert(messages).values({
+ content: 'Matching message',
+ id: 'candidate-message-match',
+ role: 'user',
+ userId,
+ });
+ const candidates = Array.from({ length: 65_536 }, (_, index) => ({
+ id: `candidate-stale-${index}`,
+ score: 1,
+ }));
+ candidates.push({ id: 'candidate-message-match', score: 2 });
+ const model = new MessageModel(serverDB, userId, undefined, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates: vi.fn().mockResolvedValue({
+ candidates,
+ total: candidates.length,
+ }),
+ });
+
+ const result = await model.queryByKeyword('candidate');
+
+ expect(result.map(({ id }) => id)).toEqual(['candidate-message-match']);
+ });
+ });
+
describe('query with files edge cases', () => {
it('should handle files with empty fileType', async () => {
await serverDB.transaction(async (trx) => {
diff --git a/packages/database/src/models/__tests__/session.test.ts b/packages/database/src/models/__tests__/session.test.ts
index f1ef42b6a68..4992702539a 100644
--- a/packages/database/src/models/__tests__/session.test.ts
+++ b/packages/database/src/models/__tests__/session.test.ts
@@ -366,6 +366,80 @@ describe('SessionModel', () => {
});
});
+ describe('queryByKeyword with external candidates', () => {
+ it('hydrates only current-scope sessions and surfaces candidate failures', async () => {
+ await serverDB.insert(users).values({ id: 'candidate-other-user' });
+ await serverDB.insert(sessions).values([
+ { id: 'candidate-session-own-a', userId },
+ { id: 'candidate-session-own-a-secondary', userId },
+ { id: 'candidate-session-own-b', userId },
+ { id: 'candidate-session-other', userId: 'candidate-other-user' },
+ ]);
+ await serverDB.insert(agents).values([
+ { id: 'candidate-agent-own-a', title: 'Own A', userId },
+ { id: 'candidate-agent-own-b', title: 'Own B', userId },
+ { id: 'candidate-agent-own-unlinked', title: 'Own Unlinked', userId },
+ { id: 'candidate-agent-other', title: 'Other', userId: 'candidate-other-user' },
+ ]);
+ await serverDB.insert(agentsToSessions).values([
+ { agentId: 'candidate-agent-own-a', sessionId: 'candidate-session-own-a', userId },
+ {
+ agentId: 'candidate-agent-own-a',
+ sessionId: 'candidate-session-own-a-secondary',
+ userId,
+ },
+ { agentId: 'candidate-agent-own-b', sessionId: 'candidate-session-own-b', userId },
+ {
+ agentId: 'candidate-agent-other',
+ sessionId: 'candidate-session-other',
+ userId: 'candidate-other-user',
+ },
+ ]);
+ const ftsSearchCandidates = vi.fn().mockResolvedValue({
+ candidates: [
+ { id: 'candidate-agent-other', score: 10 },
+ { id: 'candidate-agent-deleted', score: 9 },
+ { id: 'candidate-agent-own-b', score: 8 },
+ { id: 'candidate-agent-own-unlinked', score: 7 },
+ { id: 'candidate-agent-own-a', score: 6 },
+ ],
+ total: 5,
+ });
+ const model = new SessionModel(serverDB, userId, undefined, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates,
+ });
+
+ const result = await model.queryByKeyword('candidate');
+ expect(result).toHaveLength(2);
+ expect(['candidate-session-own-a', 'candidate-session-own-a-secondary']).toContain(
+ result[0]?.id,
+ );
+ expect(result[1]?.id).toBe('candidate-session-own-b');
+ await expect(
+ model.findSessionsByKeywords({ current: 0, keyword: 'candidate', pageSize: 1 }),
+ ).resolves.toMatchObject([
+ { id: expect.stringMatching(/^candidate-session-own-a(?:-secondary)?$/) },
+ ]);
+ await expect(
+ model.findSessionsByKeywords({ current: 1, keyword: 'candidate', pageSize: 1 }),
+ ).resolves.toMatchObject([{ id: 'candidate-session-own-b' }]);
+ await expect(
+ model.findSessionsByKeywords({ current: 2, keyword: 'candidate', pageSize: 1 }),
+ ).resolves.toEqual([]);
+ expect(ftsSearchCandidates).toHaveBeenCalledWith({
+ entity: 'agents',
+ filters: {},
+ pagination: {},
+ query: { fields: ['title', 'description'], text: 'candidate' },
+ });
+
+ const providerError = new Error('candidate unavailable');
+ ftsSearchCandidates.mockRejectedValueOnce(providerError);
+ await expect(model.queryByKeyword('failure')).rejects.toBe(providerError);
+ });
+ });
+
describe('create', () => {
it('should create a new session', async () => {
// Call the create method
diff --git a/packages/database/src/models/__tests__/topics/topic.query.test.ts b/packages/database/src/models/__tests__/topics/topic.query.test.ts
index 03b4b63c1d7..653df450292 100644
--- a/packages/database/src/models/__tests__/topics/topic.query.test.ts
+++ b/packages/database/src/models/__tests__/topics/topic.query.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import {
@@ -1822,6 +1822,86 @@ describe('TopicModel - Query', () => {
});
});
+ describe('queryByKeyword with external candidates', () => {
+ it('hydrates title and message legs through the requested topic scope', async () => {
+ await serverDB.insert(topics).values([
+ {
+ id: 'candidate-topic-title',
+ sessionId,
+ title: 'Title match',
+ updatedAt: new Date('2026-08-20T00:00:00.000Z'),
+ userId,
+ },
+ {
+ id: 'candidate-topic-message',
+ sessionId,
+ title: 'Message match',
+ updatedAt: new Date('2026-08-25T00:00:00.000Z'),
+ userId,
+ },
+ { id: 'candidate-topic-wrong-scope', title: 'Wrong scope', userId },
+ { id: 'candidate-topic-other', title: 'Other user', userId: userId2 },
+ ]);
+ await serverDB.insert(messages).values([
+ {
+ content: 'Own matching message',
+ id: 'candidate-topic-message-hit',
+ role: 'user',
+ topicId: 'candidate-topic-message',
+ userId,
+ },
+ {
+ content: 'Other matching message',
+ id: 'candidate-topic-message-other',
+ role: 'user',
+ topicId: 'candidate-topic-other',
+ userId: userId2,
+ },
+ ]);
+ const ftsSearchCandidates = vi.fn().mockImplementation(({ entity }) =>
+ Promise.resolve({
+ candidates:
+ entity === 'topics'
+ ? [
+ { id: 'candidate-topic-other', score: 12 },
+ { id: 'candidate-topic-wrong-scope', score: 10 },
+ { id: 'candidate-topic-deleted', score: 8 },
+ { id: 'candidate-topic-title', score: 6 },
+ ]
+ : [
+ { id: 'candidate-topic-message-other', score: 12 },
+ { id: 'candidate-message-deleted', score: 10 },
+ { id: 'candidate-topic-message-hit', score: 8 },
+ ],
+ total: 4,
+ }),
+ );
+ const model = new TopicModel(serverDB, userId, undefined, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates,
+ });
+
+ const result = await model.queryByKeyword('candidate', sessionId);
+
+ expect(result.map(({ id }) => id)).toEqual([
+ 'candidate-topic-message',
+ 'candidate-topic-title',
+ ]);
+ expect(ftsSearchCandidates).toHaveBeenCalledWith({
+ entity: 'topics',
+ filters: { topicScope: { containerId: sessionId } },
+ pagination: {},
+ query: { fields: ['title'], text: 'candidate' },
+ });
+ expect(ftsSearchCandidates).toHaveBeenCalledWith({
+ entity: 'messages',
+ filters: { topicScope: { containerId: sessionId } },
+ pagination: {},
+ query: { fields: ['content'], text: 'candidate' },
+ });
+ });
+ });
+
describe('queryRecent', () => {
it('should return recent topics with agentId', async () => {
await serverDB.transaction(async (tx) => {
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index b29acefebc0..d0078b9a64b 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -59,6 +59,7 @@ import { merge } from '@/utils/merge';
import { sanitizeNullBytes } from '@/utils/sanitizeNullBytes';
import { today } from '@/utils/time';
+import type { FtsSearchCandidateSource } from '../repositories/ftsSearch';
import {
agentsToSessions,
chunks,
@@ -82,6 +83,7 @@ import { sanitizeBm25Query } from '../utils/bm25';
import { notCopiedTranscript } from '../utils/copiedTranscript';
import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';
import { idGenerator } from '../utils/idGenerator';
+import { inJsonStringArray } from '../utils/inJsonStringArray';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
import { recomputeTopicUsage } from './topicUsage';
import { WorkModel } from './work';
@@ -449,12 +451,19 @@ const computeTopicMessageStats = (counts: number[]): TopicMessageStats => {
export class MessageModel {
private userId: string;
private db: LobeChatDatabase;
+ private ftsSearchCandidateSource?: FtsSearchCandidateSource;
private workspaceId?: string;
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ constructor(
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+ ftsSearchCandidateSource?: FtsSearchCandidateSource,
+ ) {
this.userId = userId;
this.db = db;
this.workspaceId = workspaceId;
+ this.ftsSearchCandidateSource = ftsSearchCandidateSource;
}
private ownership = () =>
@@ -2055,10 +2064,26 @@ export class MessageModel {
if (!keyword.trim()) return [];
const bm25Query = sanitizeBm25Query(keyword);
+ const candidateResult = this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled
+ ? await this.ftsSearchCandidateSource.ftsSearchCandidates({
+ entity: 'messages',
+ filters: {},
+ pagination: {},
+ query: { fields: ['content'], text: keyword },
+ })
+ : undefined;
+ const candidateIds = candidateResult?.candidates.map(({ id }) => id);
const result = await this.db
.select()
.from(messages)
- .where(and(this.ownership(), sql`${messages.content} @@@ ${bm25Query}`))
+ .where(
+ and(
+ this.ownership(),
+ candidateIds
+ ? inJsonStringArray(messages.id, candidateIds)
+ : sql`${messages.content} @@@ ${bm25Query}`,
+ ),
+ )
.orderBy(desc(messages.createdAt));
return result as DBMessageItem[];
diff --git a/packages/database/src/models/session.ts b/packages/database/src/models/session.ts
index 3f51efdbda3..ff50bc2d3af 100644
--- a/packages/database/src/models/session.ts
+++ b/packages/database/src/models/session.ts
@@ -10,23 +10,32 @@ import type { PartialDeep } from 'type-fest';
import { merge } from '@/utils/merge';
+import type { FtsSearchCandidateSource } from '../repositories/ftsSearch';
import type { AgentItem, NewAgent, NewSession, SessionItem } from '../schemas';
import { agents, agentsToSessions, sessionGroups, sessions } from '../schemas';
import type { LobeChatDatabase } from '../type';
import { sanitizeBm25Query } from '../utils/bm25';
import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';
import { idGenerator } from '../utils/idGenerator';
+import { inJsonStringArray } from '../utils/inJsonStringArray';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
export class SessionModel {
private userId: string;
private db: LobeChatDatabase;
+ private ftsSearchCandidateSource?: FtsSearchCandidateSource;
private workspaceId?: string;
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ constructor(
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+ ftsSearchCandidateSource?: FtsSearchCandidateSource,
+ ) {
this.userId = userId;
this.db = db;
this.workspaceId = workspaceId;
+ this.ftsSearchCandidateSource = ftsSearchCandidateSource;
}
private ownership = () =>
@@ -605,6 +614,44 @@ export class SessionModel {
const { keyword, pageSize = 9999, current = 0 } = params;
const offset = current * pageSize;
+ if (this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled) {
+ const { candidates } = await this.ftsSearchCandidateSource.ftsSearchCandidates({
+ entity: 'agents',
+ filters: {},
+ pagination: {},
+ query: { fields: ['title', 'description'], text: keyword },
+ });
+ const candidateIds = candidates.map(({ id }) => id);
+ if (candidateIds.length === 0) return [];
+
+ const matchingAgents = await this.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(and(this.agentsOwnership(), inJsonStringArray(agents.id, candidateIds)))
+ .orderBy(asc(agents.id))
+ .limit(pageSize)
+ .offset(offset);
+ const matchingAgentIds = matchingAgents.map(({ id }) => id);
+ if (matchingAgentIds.length === 0) return [];
+
+ const agentSessions = await this.db
+ .select({ agentId: agentsToSessions.agentId, session: sessions })
+ .from(agentsToSessions)
+ .leftJoin(sessions, eq(agentsToSessions.sessionId, sessions.id))
+ .where(inArray(agentsToSessions.agentId, matchingAgentIds));
+ const firstSessionByAgentId = new Map<string, SessionItem>();
+
+ for (const { agentId, session } of agentSessions) {
+ if (session && !firstSessionByAgentId.has(agentId)) {
+ firstSessionByAgentId.set(agentId, session as SessionItem);
+ }
+ }
+
+ return matchingAgents
+ .map(({ id }) => firstSessionByAgentId.get(id))
+ .filter((session): session is SessionItem => session !== undefined);
+ }
+
try {
const bm25Query = sanitizeBm25Query(keyword);
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index 946b4055b9f..c3e49f46391 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -32,6 +32,7 @@ import {
sql,
} from 'drizzle-orm';
+import type { FtsSearchCandidateSource } from '../repositories/ftsSearch';
import type { TopicItem } from '../schemas';
import {
agentOperations,
@@ -48,6 +49,7 @@ import { COPIED_TOPIC_USAGE_RESET } from '../utils/copiedTranscript';
import { markCopiedMessageMetadata } from '../utils/copyMessagesInDatabase';
import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';
import { idGenerator } from '../utils/idGenerator';
+import { inJsonStringArray } from '../utils/inJsonStringArray';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
import { recomputeTopicUsage } from './topicUsage';
@@ -289,12 +291,19 @@ const buildTopicOrderBy = (topicActivityAt: SQL, sortBy?: TopicQuerySortBy): SQL
export class TopicModel {
private userId: string;
private db: LobeChatDatabase;
+ private ftsSearchCandidateSource?: FtsSearchCandidateSource;
private workspaceId?: string;
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ constructor(
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+ ftsSearchCandidateSource?: FtsSearchCandidateSource,
+ ) {
this.userId = userId;
this.db = db;
this.workspaceId = workspaceId;
+ this.ftsSearchCandidateSource = ftsSearchCandidateSource;
}
private ownership = () =>
@@ -844,6 +853,24 @@ export class TopicModel {
const scopeCondition = this.matchKeywordScope(scopeOptions);
const bm25Query = sanitizeBm25Query(keyword);
+ const candidateResults = this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled
+ ? await Promise.all([
+ this.ftsSearchCandidateSource.ftsSearchCandidates({
+ entity: 'topics',
+ filters: { topicScope: scopeOptions },
+ pagination: {},
+ query: { fields: ['title'], text: keyword },
+ }),
+ this.ftsSearchCandidateSource.ftsSearchCandidates({
+ entity: 'messages',
+ filters: { topicScope: scopeOptions },
+ pagination: {},
+ query: { fields: ['content'], text: keyword },
+ }),
+ ])
+ : undefined;
+ const topicCandidateIds = candidateResults?.[0].candidates.map(({ id }) => id);
+ const messageCandidateIds = candidateResults?.[1].candidates.map(({ id }) => id);
// Run title and message content searches in parallel
const [topicsByTitle, topicIdsByMessages] = await Promise.all([
@@ -851,7 +878,15 @@ export class TopicModel {
this.db
.select()
.from(topics)
- .where(and(this.ownership(), scopeCondition, sql`${topics.title} @@@ ${bm25Query}`))
+ .where(
+ and(
+ this.ownership(),
+ scopeCondition,
+ topicCandidateIds
+ ? inJsonStringArray(topics.id, topicCandidateIds)
+ : sql`${topics.title} @@@ ${bm25Query}`,
+ ),
+ )
.orderBy(desc(topics.updatedAt)),
// Query topic IDs matching by message content (BM25)
this.db
@@ -861,7 +896,9 @@ export class TopicModel {
.where(
and(
this.messageOwnership(),
- sql`${messages.content} @@@ ${bm25Query}`,
+ messageCandidateIds
+ ? inJsonStringArray(messages.id, messageCandidateIds)
+ : sql`${messages.content} @@@ ${bm25Query}`,
this.ownership(),
scopeCondition,
),
diff --git a/packages/database/src/models/userMemory/__tests__/activity.test.ts b/packages/database/src/models/userMemory/__tests__/activity.test.ts
index a0bb8fd9cd2..2e54952991a 100644
--- a/packages/database/src/models/userMemory/__tests__/activity.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/activity.test.ts
@@ -1,5 +1,5 @@
// @vitest-environment node
-import { beforeEach, describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import type { NewUserMemoryActivity } from '../../../schemas';
@@ -236,6 +236,36 @@ describe('UserMemoryActivityModel', () => {
expect(result.pageSize).toBe(100);
});
+ it('hydrates external keyword candidates through current user and filter constraints', async () => {
+ const ftsSearchCandidates = vi.fn().mockResolvedValue({
+ candidates: [
+ { id: 'other-list-activity', score: 12 },
+ { id: 'deleted-list-activity', score: 10 },
+ { id: 'list-activity-2', score: 8 },
+ { id: 'list-activity-1', score: 6 },
+ ],
+ total: 4,
+ });
+ const model = new UserMemoryActivityModel(serverDB, userId, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates,
+ });
+
+ const result = await model.queryList({ q: 'candidate', status: ['completed'] });
+
+ expect(result.items.map(({ id }) => id)).toEqual(['list-activity-1']);
+ expect(result.total).toBe(1);
+ expect(ftsSearchCandidates).toHaveBeenCalledWith({
+ entity: 'memoryActivities',
+ filters: { memoryStatus: ['completed'] },
+ pagination: {},
+ query: {
+ fields: ['parent_title', 'narrative', 'notes', 'feedback'],
+ text: 'candidate',
+ },
+ });
+ });
+
// BM25 search requires pg_search extension (ParadeDB), not available in PGlite
const isServerDB = process.env.TEST_SERVER_DB === '1';
it.skipIf(!isServerDB)('should search by query in title', async () => {
diff --git a/packages/database/src/models/userMemory/__tests__/experience.test.ts b/packages/database/src/models/userMemory/__tests__/experience.test.ts
index 94647913bde..2a455836315 100644
--- a/packages/database/src/models/userMemory/__tests__/experience.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/experience.test.ts
@@ -1,5 +1,5 @@
// @vitest-environment node
-import { beforeEach, describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import type { NewUserMemoryExperience } from '../../../schemas';
@@ -433,6 +433,40 @@ describe('UserMemoryExperienceModel', () => {
expect(result.pageSize).toBe(100);
});
+ it('hydrates external candidates through current user and list filters', async () => {
+ const ftsSearchCandidates = vi.fn().mockResolvedValue({
+ candidates: [
+ { id: 'other-list-exp', score: 12 },
+ { id: 'deleted-list-exp', score: 10 },
+ { id: 'list-exp-2', score: 8 },
+ { id: 'list-exp-1', score: 6 },
+ ],
+ total: 4,
+ });
+ const model = new UserMemoryExperienceModel(serverDB, userId, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates,
+ });
+
+ const result = await model.queryList({ q: 'candidate', tags: ['tag1'], types: ['lesson'] });
+
+ expect(result.items.map(({ id }) => id)).toEqual(['list-exp-1']);
+ expect(result.total).toBe(1);
+ expect(ftsSearchCandidates).toHaveBeenCalledWith({
+ entity: 'memoryExperiences',
+ filters: {
+ memoryTagMatch: 'any',
+ memoryTags: ['tag1'],
+ memoryTypes: ['lesson'],
+ },
+ pagination: {},
+ query: {
+ fields: ['parent_title', 'situation', 'key_learning', 'action'],
+ text: 'candidate',
+ },
+ });
+ });
+
// BM25 search requires pg_search extension (ParadeDB), not available in PGlite
const isServerDB = process.env.TEST_SERVER_DB === '1';
it.skipIf(!isServerDB)('should search by query in title', async () => {
diff --git a/packages/database/src/models/userMemory/__tests__/identity.test.ts b/packages/database/src/models/userMemory/__tests__/identity.test.ts
index 0e5febdaf29..54ec7a84840 100644
--- a/packages/database/src/models/userMemory/__tests__/identity.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/identity.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { RelationshipEnum } from '@lobechat/types';
-import { beforeEach, describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import type { NewUserMemoryIdentity } from '../../../schemas';
@@ -451,6 +451,36 @@ describe('UserMemoryIdentityModel', () => {
expect(result.pageSize).toBe(100);
});
+ it('hydrates external candidates through the default self relationship filter', async () => {
+ const ftsSearchCandidates = vi.fn().mockResolvedValue({
+ candidates: [
+ { id: 'other-list-id', score: 12 },
+ { id: 'deleted-list-id', score: 10 },
+ { id: 'list-id-3', score: 8 },
+ { id: 'list-id-2', score: 6 },
+ ],
+ total: 4,
+ });
+ const model = new UserMemoryIdentityModel(serverDB, userId, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates,
+ });
+
+ const result = await model.queryList({ q: 'candidate' });
+
+ expect(result.items.map(({ id }) => id)).toEqual(['list-id-2']);
+ expect(result.total).toBe(1);
+ expect(ftsSearchCandidates).toHaveBeenCalledWith({
+ entity: 'memoryIdentities',
+ filters: { memoryRelationships: [RelationshipEnum.Self] },
+ pagination: {},
+ query: {
+ fields: ['parent_title', 'description', 'role'],
+ text: 'candidate',
+ },
+ });
+ });
+
// BM25 search requires pg_search extension (ParadeDB), not available in PGlite
const isServerDB = process.env.TEST_SERVER_DB === '1';
it.skipIf(!isServerDB)('should search by query in title', async () => {
diff --git a/packages/database/src/models/userMemory/__tests__/model.test.ts b/packages/database/src/models/userMemory/__tests__/model.test.ts
index 163bdefcbdd..24236dbbd4f 100644
--- a/packages/database/src/models/userMemory/__tests__/model.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/model.test.ts
@@ -215,6 +215,7 @@ async function createActivityPair(opts?: {
async function createContextPair(opts?: {
associatedObjectName?: string;
associatedSubjectName?: string;
+ currentStatus?: string;
description?: string;
tags?: string[];
title?: string;
@@ -245,6 +246,7 @@ async function createContextPair(opts?: {
associatedSubjects: opts?.associatedSubjectName
? [{ name: opts.associatedSubjectName, type: 'person' }]
: [],
+ currentStatus: opts?.currentStatus,
description: opts?.description ?? 'A context description',
tags: opts?.tags,
title: opts?.title ?? 'A context',
@@ -540,6 +542,63 @@ describe('UserMemoryModel', () => {
const result = await memoryModel.queryMemories({ layer: LayersEnum.Context });
expect(result.total).toBe(1);
});
+
+ it('applies exact context status filters without an external candidate provider', async () => {
+ const { context: active } = await createContextPair({ currentStatus: 'active' });
+ await createContextPair({ currentStatus: 'archived' });
+
+ const result = await memoryModel.queryMemories({
+ layer: LayersEnum.Context,
+ status: ['active'],
+ });
+
+ expect(result.items).toEqual([
+ expect.objectContaining({ context: expect.objectContaining({ id: active.id }) }),
+ ]);
+ expect(result.total).toBe(1);
+ });
+
+ it('hydrates external candidates through current user and context status filters', async () => {
+ const { context: matching } = await createContextPair({ currentStatus: 'active' });
+ const { context: wrongStatus } = await createContextPair({ currentStatus: 'archived' });
+ const { context: otherUser } = await createContextPair({
+ currentStatus: 'active',
+ user: otherUserId,
+ });
+ const ftsSearchCandidates = vi.fn().mockResolvedValue({
+ candidates: [
+ { id: otherUser.id, score: 12 },
+ { id: 'deleted-context', score: 10 },
+ { id: wrongStatus.id, score: 8 },
+ { id: matching.id, score: 6 },
+ ],
+ total: 4,
+ });
+ const model = new UserMemoryModel(serverDB, userId, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates,
+ });
+
+ const result = await model.queryMemories({
+ layer: LayersEnum.Context,
+ q: 'candidate',
+ status: ['active'],
+ });
+
+ expect(result.items).toEqual([
+ expect.objectContaining({ context: expect.objectContaining({ id: matching.id }) }),
+ ]);
+ expect(result.total).toBe(1);
+ expect(ftsSearchCandidates).toHaveBeenCalledWith({
+ entity: 'memoryContexts',
+ filters: { memoryStatus: ['active'] },
+ pagination: {},
+ query: {
+ fields: ['parent_text', 'title', 'description', 'current_status'],
+ text: 'candidate',
+ },
+ });
+ });
});
describe('activity layer', () => {
@@ -551,6 +610,40 @@ describe('UserMemoryModel', () => {
expect(result.items.length).toBe(1);
expect(result.total).toBe(1);
});
+
+ it('preserves parent memory fields and any-tag semantics for external candidates', async () => {
+ const ftsSearchCandidates = vi.fn().mockResolvedValue({ candidates: [], total: 0 });
+ const model = new UserMemoryModel(serverDB, userId, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates,
+ });
+
+ await model.queryMemories({
+ layer: LayersEnum.Activity,
+ q: 'candidate',
+ tags: ['typescript', 'search'],
+ });
+
+ expect(ftsSearchCandidates).toHaveBeenCalledWith({
+ entity: 'memoryActivities',
+ filters: {
+ memoryTagMatch: 'any',
+ memoryTags: ['typescript', 'search'],
+ },
+ pagination: {},
+ query: {
+ fields: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'narrative',
+ 'notes',
+ 'feedback',
+ ],
+ text: 'candidate',
+ },
+ });
+ });
});
describe('experience layer', () => {
@@ -619,6 +712,52 @@ describe('UserMemoryModel', () => {
});
describe('searchMemory', () => {
+ it('routes each hybrid lexical layer through external candidates', async () => {
+ const { activity } = await createActivityPair({ title: 'Candidate activity' });
+ const { context } = await createContextPair({ title: 'Candidate context' });
+ const { experience } = await createExperiencePair({});
+ const { identity } = await createIdentityPair({});
+ const { preference } = await createPreferencePair({});
+ const candidateIds = {
+ memoryActivities: activity.id,
+ memoryContexts: context.id,
+ memoryExperiences: experience.id,
+ memoryIdentities: identity.id,
+ memoryPreferences: preference.id,
+ };
+ const ftsSearchCandidates = vi
+ .fn()
+ .mockImplementation((request: { entity: keyof typeof candidateIds }) =>
+ Promise.resolve({
+ candidates: [{ id: candidateIds[request.entity], score: 8 }],
+ total: 1,
+ }),
+ );
+ const model = new UserMemoryModel(serverDB, userId, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates,
+ });
+
+ const result = await model.searchMemory({
+ layers: [
+ LayersEnum.Activity,
+ LayersEnum.Context,
+ LayersEnum.Experience,
+ LayersEnum.Identity,
+ LayersEnum.Preference,
+ ],
+ queries: ['candidate'],
+ topK: { activities: 1, contexts: 1, experiences: 1, identities: 1, preferences: 1 },
+ });
+
+ expect(result.activities.map(({ id }) => id)).toEqual([activity.id]);
+ expect(result.contexts.map(({ id }) => id)).toEqual([context.id]);
+ expect(result.experiences.map(({ id }) => id)).toEqual([experience.id]);
+ expect(result.identities.map(({ id }) => id)).toEqual([identity.id]);
+ expect(result.preferences.map(({ id }) => id)).toEqual([preference.id]);
+ expect(ftsSearchCandidates).toHaveBeenCalledTimes(5);
+ });
+
it('boosts short-term related memories with matching tags and category during hybrid ranking', async () => {
const seedTime = new Date('2024-01-10T10:00:00.000Z');
const boostedTime = new Date('2024-01-10T16:00:00.000Z');
diff --git a/packages/database/src/models/userMemory/__tests__/query.test.ts b/packages/database/src/models/userMemory/__tests__/query.test.ts
index 88a7de00ef2..b716bdf4f99 100644
--- a/packages/database/src/models/userMemory/__tests__/query.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/query.test.ts
@@ -73,6 +73,7 @@ const createActivityPair = async (opts: {
};
const createContextPair = async (opts: {
+ currentStatus?: string;
description?: string;
memoryTags?: string[];
tags?: string[];
@@ -96,6 +97,7 @@ const createContextPair = async (opts: {
.insert(userMemoriesContexts)
.values({
associatedObjects: [{ name: 'Linear', type: UserMemoryContextObjectType.Application }],
+ currentStatus: opts.currentStatus,
description: opts.description ?? 'A context description',
tags: opts.tags,
title: opts.title ?? 'Atlas context',
@@ -306,6 +308,46 @@ describe('user memory query layer', () => {
});
describe('searchMemory', () => {
+ it('uses external candidates only for the lexical leg and rechecks PostgreSQL rows', async () => {
+ const { activity } = await createActivityPair({ title: 'External lexical activity' });
+ const ftsSearchCandidates = vi.fn().mockResolvedValue({
+ candidates: [
+ { id: 'deleted-activity', score: 10 },
+ { id: activity.id, score: 8 },
+ ],
+ total: 2,
+ });
+ const model = new UserMemoryModel(serverDB, userId, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates,
+ });
+
+ const result = await model.searchMemory({
+ layers: [LayersEnum.Activity],
+ queries: ['external candidate'],
+ status: ['completed'],
+ topK: { activities: 5, contexts: 0, experiences: 0, identities: 0, preferences: 0 },
+ });
+
+ expect(result.activities.map(({ id }) => id)).toEqual([activity.id]);
+ expect(ftsSearchCandidates).toHaveBeenCalledWith({
+ entity: 'memoryActivities',
+ filters: { memoryStatus: ['completed'] },
+ pagination: { limit: 15 },
+ query: {
+ fields: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'narrative',
+ 'notes',
+ 'feedback',
+ ],
+ text: 'external candidate',
+ },
+ });
+ });
+
it('requires all requested tags to match during lexical filter-only search', async () => {
const { activity: exactMatch } = await createActivityPair({
memoryTags: ['atlas', 'urgent'],
@@ -327,6 +369,19 @@ describe('user memory query layer', () => {
expect(result.activities.map((item) => item.id)).toEqual([exactMatch.id]);
});
+ it('applies context status during lexical filter-only search', async () => {
+ const { context: active } = await createContextPair({ currentStatus: 'active' });
+ await createContextPair({ currentStatus: 'archived' });
+
+ const result = await memoryModel.searchMemory({
+ layers: [LayersEnum.Context],
+ status: ['active'],
+ topK: { activities: 0, contexts: 5, experiences: 0, identities: 0, preferences: 0 },
+ });
+
+ expect(result.contexts.map((item) => item.id)).toEqual([active.id]);
+ });
+
it('does not execute retrieval for layers with topK set to zero', async () => {
const queryModel = Reflect.get(memoryModel, 'queryModel') as {
searchHybridActivities: (...args: unknown[]) => Promise<unknown[]>;
diff --git a/packages/database/src/models/userMemory/activity.ts b/packages/database/src/models/userMemory/activity.ts
index 3c1350f68bb..6333209d45f 100644
--- a/packages/database/src/models/userMemory/activity.ts
+++ b/packages/database/src/models/userMemory/activity.ts
@@ -2,18 +2,26 @@ import type { ActivityListParams, ActivityListResult } from '@lobechat/types';
import type { SQL } from 'drizzle-orm';
import { and, asc, desc, eq, inArray, or, sql } from 'drizzle-orm';
+import type { FtsSearchCandidateSource } from '../../repositories/ftsSearch';
import type { NewUserMemoryActivity, UserMemoryActivity } from '../../schemas';
import { userMemories, userMemoriesActivities } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { normalizeBm25MatchQuery, SAFE_BM25_QUERY_OPTIONS } from '../../utils/bm25';
+import { inJsonStringArray } from '../../utils/inJsonStringArray';
export class UserMemoryActivityModel {
private userId: string;
private db: LobeChatDatabase;
+ private ftsSearchCandidateSource?: FtsSearchCandidateSource;
- constructor(db: LobeChatDatabase, userId: string) {
+ constructor(
+ db: LobeChatDatabase,
+ userId: string,
+ ftsSearchCandidateSource?: FtsSearchCandidateSource,
+ ) {
this.userId = userId;
this.db = db;
+ this.ftsSearchCandidateSource = ftsSearchCandidateSource;
}
private memoryWhere(table: { userId: any }) {
@@ -69,10 +77,28 @@ export class UserMemoryActivityModel {
const bm25MatchQuery = normalizedQuery
? normalizeBm25MatchQuery(normalizedQuery, SAFE_BM25_QUERY_OPTIONS)
: '';
+ const candidateResult =
+ normalizedQuery && this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled
+ ? await this.ftsSearchCandidateSource.ftsSearchCandidates({
+ entity: 'memoryActivities',
+ filters: {
+ ...(status?.length ? { memoryStatus: status } : {}),
+ ...(tags?.length ? { memoryTagMatch: 'any' as const, memoryTags: tags } : {}),
+ ...(types?.length ? { memoryTypes: types } : {}),
+ },
+ pagination: {},
+ query: {
+ fields: ['parent_title', 'narrative', 'notes', 'feedback'],
+ text: normalizedQuery,
+ },
+ })
+ : undefined;
+ const candidateIds = candidateResult?.candidates.map(({ id }) => id);
const conditions: Array<SQL | undefined> = [
this.memoryWhere(userMemoriesActivities),
- normalizedQuery
+ candidateIds ? inJsonStringArray(userMemoriesActivities.id, candidateIds) : undefined,
+ normalizedQuery && !candidateIds
? sql`(${userMemories.id} @@@ paradedb.boolean(should => ARRAY[paradedb.match('title', ${bm25MatchQuery}, conjunction_mode => true)]) OR ${userMemoriesActivities.id} @@@ paradedb.boolean(should => ARRAY[paradedb.match('narrative', ${bm25MatchQuery}, conjunction_mode => true), paradedb.match('notes', ${bm25MatchQuery}, conjunction_mode => true), paradedb.match('feedback', ${bm25MatchQuery}, conjunction_mode => true)]))`
: undefined,
types && types.length > 0 ? inArray(userMemoriesActivities.type, types) : undefined,
diff --git a/packages/database/src/models/userMemory/experience.ts b/packages/database/src/models/userMemory/experience.ts
index da4954f79d8..4653445c3fc 100644
--- a/packages/database/src/models/userMemory/experience.ts
+++ b/packages/database/src/models/userMemory/experience.ts
@@ -2,18 +2,26 @@ import type { ExperienceListParams, ExperienceListResult } from '@lobechat/types
import type { SQL } from 'drizzle-orm';
import { and, asc, desc, eq, inArray, or, sql } from 'drizzle-orm';
+import type { FtsSearchCandidateSource } from '../../repositories/ftsSearch';
import type { NewUserMemoryExperience, UserMemoryExperience } from '../../schemas';
import { userMemories, userMemoriesExperiences } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { normalizeBm25MatchQuery, SAFE_BM25_QUERY_OPTIONS } from '../../utils/bm25';
+import { inJsonStringArray } from '../../utils/inJsonStringArray';
export class UserMemoryExperienceModel {
private userId: string;
private db: LobeChatDatabase;
+ private ftsSearchCandidateSource?: FtsSearchCandidateSource;
- constructor(db: LobeChatDatabase, userId: string) {
+ constructor(
+ db: LobeChatDatabase,
+ userId: string,
+ ftsSearchCandidateSource?: FtsSearchCandidateSource,
+ ) {
this.userId = userId;
this.db = db;
+ this.ftsSearchCandidateSource = ftsSearchCandidateSource;
}
private memoryWhere(table: { userId: any }) {
@@ -74,12 +82,29 @@ export class UserMemoryExperienceModel {
const bm25MatchQuery = normalizedQuery
? normalizeBm25MatchQuery(normalizedQuery, SAFE_BM25_QUERY_OPTIONS)
: '';
+ const candidateResult =
+ normalizedQuery && this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled
+ ? await this.ftsSearchCandidateSource.ftsSearchCandidates({
+ entity: 'memoryExperiences',
+ filters: {
+ ...(tags?.length ? { memoryTagMatch: 'any' as const, memoryTags: tags } : {}),
+ ...(types?.length ? { memoryTypes: types } : {}),
+ },
+ pagination: {},
+ query: {
+ fields: ['parent_title', 'situation', 'key_learning', 'action'],
+ text: normalizedQuery,
+ },
+ })
+ : undefined;
+ const candidateIds = candidateResult?.candidates.map(({ id }) => id);
// Build WHERE conditions
const conditions: Array<SQL | undefined> = [
this.memoryWhere(userMemoriesExperiences),
+ candidateIds ? inJsonStringArray(userMemoriesExperiences.id, candidateIds) : undefined,
// Full-text search across title, situation, keyLearning, action
- normalizedQuery
+ normalizedQuery && !candidateIds
? sql`(${userMemories.id} @@@ paradedb.boolean(should => ARRAY[paradedb.match('title', ${bm25MatchQuery}, conjunction_mode => true)]) OR ${userMemoriesExperiences.id} @@@ paradedb.boolean(should => ARRAY[paradedb.match('situation', ${bm25MatchQuery}, conjunction_mode => true), paradedb.match('key_learning', ${bm25MatchQuery}, conjunction_mode => true), paradedb.match('action', ${bm25MatchQuery}, conjunction_mode => true)]))`
: undefined,
types && types.length > 0 ? inArray(userMemoriesExperiences.type, types) : undefined,
diff --git a/packages/database/src/models/userMemory/identity.ts b/packages/database/src/models/userMemory/identity.ts
index 4850bebc8eb..fb501cdce54 100644
--- a/packages/database/src/models/userMemory/identity.ts
+++ b/packages/database/src/models/userMemory/identity.ts
@@ -3,18 +3,26 @@ import { RelationshipEnum } from '@lobechat/types';
import type { SQL } from 'drizzle-orm';
import { and, asc, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm';
+import type { FtsSearchCandidateSource } from '../../repositories/ftsSearch';
import type { NewUserMemoryIdentity, UserMemoryIdentity } from '../../schemas';
import { userMemories, userMemoriesIdentities } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { normalizeBm25MatchQuery, SAFE_BM25_QUERY_OPTIONS } from '../../utils/bm25';
+import { inJsonStringArray } from '../../utils/inJsonStringArray';
export class UserMemoryIdentityModel {
private userId: string;
private db: LobeChatDatabase;
+ private ftsSearchCandidateSource?: FtsSearchCandidateSource;
- constructor(db: LobeChatDatabase, userId: string) {
+ constructor(
+ db: LobeChatDatabase,
+ userId: string,
+ ftsSearchCandidateSource?: FtsSearchCandidateSource,
+ ) {
this.userId = userId;
this.db = db;
+ this.ftsSearchCandidateSource = ftsSearchCandidateSource;
}
private memoryWhere(table: { userId: any }) {
@@ -75,19 +83,37 @@ export class UserMemoryIdentityModel {
const bm25MatchQuery = normalizedQuery
? normalizeBm25MatchQuery(normalizedQuery, SAFE_BM25_QUERY_OPTIONS)
: '';
+ const resolvedRelationships =
+ relationships && relationships.length > 0 ? relationships : [RelationshipEnum.Self];
+ const candidateResult =
+ normalizedQuery && this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled
+ ? await this.ftsSearchCandidateSource.ftsSearchCandidates({
+ entity: 'memoryIdentities',
+ filters: {
+ memoryRelationships: resolvedRelationships,
+ ...(tags?.length ? { memoryTagMatch: 'any' as const, memoryTags: tags } : {}),
+ ...(types?.length ? { memoryTypes: types } : {}),
+ },
+ pagination: {},
+ query: {
+ fields: ['parent_title', 'description', 'role'],
+ text: normalizedQuery,
+ },
+ })
+ : undefined;
+ const candidateIds = candidateResult?.candidates.map(({ id }) => id);
// Build WHERE conditions
const conditions: Array<SQL | undefined> = [
this.memoryWhere(userMemoriesIdentities),
+ candidateIds ? inJsonStringArray(userMemoriesIdentities.id, candidateIds) : undefined,
// Full-text search across title, description, role
- normalizedQuery
+ normalizedQuery && !candidateIds
? sql`(${userMemories.id} @@@ paradedb.boolean(should => ARRAY[paradedb.match('title', ${bm25MatchQuery}, conjunction_mode => true)]) OR ${userMemoriesIdentities.id} @@@ paradedb.boolean(should => ARRAY[paradedb.match('description', ${bm25MatchQuery}, conjunction_mode => true), paradedb.match('role', ${bm25MatchQuery}, conjunction_mode => true)]))`
: undefined,
types && types.length > 0 ? inArray(userMemoriesIdentities.type, types) : undefined,
// Default to 'self' relationship if not specified
- relationships && relationships.length > 0
- ? inArray(userMemoriesIdentities.relationship, relationships)
- : eq(userMemoriesIdentities.relationship, RelationshipEnum.Self),
+ inArray(userMemoriesIdentities.relationship, resolvedRelationships),
tags && tags.length > 0
? or(...tags.map((tag) => sql<boolean>`${tag} = ANY(${userMemoriesIdentities.tags})`))
: undefined,
diff --git a/packages/database/src/models/userMemory/model.ts b/packages/database/src/models/userMemory/model.ts
index d922a0f804b..038845bf4c5 100644
--- a/packages/database/src/models/userMemory/model.ts
+++ b/packages/database/src/models/userMemory/model.ts
@@ -28,6 +28,7 @@ import { and, asc, cosineDistance, desc, eq, inArray, isNotNull, ne, or, sql } f
import { merge } from '@/utils/merge';
+import type { FtsSearchCandidateSource } from '../../repositories/ftsSearch';
import type {
UserMemoryActivitiesWithoutVectors,
UserMemoryActivity,
@@ -48,6 +49,7 @@ import {
import type { LobeChatDatabase } from '../../type';
import { normalizeBm25MatchQuery, SAFE_BM25_QUERY_OPTIONS } from '../../utils/bm25';
import { selectNonVectorColumns } from '../../utils/columns';
+import { inJsonStringArray } from '../../utils/inJsonStringArray';
import { TopicModel } from '../topic';
import type { UserMemoryHybridSearchAggregatedResult } from './query';
import { UserMemoryQueryModel } from './query';
@@ -547,10 +549,14 @@ export class UserMemoryModel {
private topicModel: TopicModel;
private queryModel: UserMemoryQueryModel;
- constructor(db: LobeChatDatabase, userId: string) {
+ constructor(
+ db: LobeChatDatabase,
+ userId: string,
+ private readonly ftsSearchCandidateSource?: FtsSearchCandidateSource,
+ ) {
this.userId = userId;
this.db = db;
- this.queryModel = new UserMemoryQueryModel(db, userId);
+ this.queryModel = new UserMemoryQueryModel(db, userId, ftsSearchCandidateSource);
this.topicModel = new TopicModel(db, userId);
}
@@ -959,6 +965,81 @@ export class UserMemoryModel {
const bm25MatchQuery = normalizedQuery
? normalizeBm25MatchQuery(normalizedQuery, SAFE_BM25_QUERY_OPTIONS)
: '';
+ const candidateConfig = (() => {
+ switch (resolvedLayer) {
+ case LayersEnum.Activity: {
+ return {
+ entity: 'memoryActivities' as const,
+ fields: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'narrative',
+ 'notes',
+ 'feedback',
+ ],
+ };
+ }
+ case LayersEnum.Context: {
+ return {
+ entity: 'memoryContexts' as const,
+ fields: ['parent_text', 'title', 'description', 'current_status'],
+ };
+ }
+ case LayersEnum.Experience: {
+ return {
+ entity: 'memoryExperiences' as const,
+ fields: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'situation',
+ 'key_learning',
+ 'action',
+ ],
+ };
+ }
+ case LayersEnum.Identity: {
+ return {
+ entity: 'memoryIdentities' as const,
+ fields: ['parent_title', 'parent_summary', 'parent_details', 'description', 'role'],
+ };
+ }
+ case LayersEnum.Preference: {
+ return {
+ entity: 'memoryPreferences' as const,
+ fields: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'conclusion_directives',
+ 'suggestions',
+ ],
+ };
+ }
+ default: {
+ return undefined;
+ }
+ }
+ })();
+ const candidateResult =
+ normalizedQuery && candidateConfig && this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled
+ ? await this.ftsSearchCandidateSource.ftsSearchCandidates({
+ entity: candidateConfig.entity,
+ filters: {
+ ...(categories?.length ? { memoryCategories: categories } : {}),
+ ...((resolvedLayer === LayersEnum.Activity || resolvedLayer === LayersEnum.Context) &&
+ status?.length
+ ? { memoryStatus: status }
+ : {}),
+ ...(tags?.length ? { memoryTagMatch: 'any' as const, memoryTags: tags } : {}),
+ ...(types?.length ? { memoryTypes: types } : {}),
+ },
+ pagination: {},
+ query: { fields: candidateConfig.fields, text: normalizedQuery },
+ })
+ : undefined;
+ const candidateIds = candidateResult?.candidates.map(({ id }) => id);
// NOTICE:
// Why this workaround is needed.
// PGlite-based tests do not provide ParadeDB `pg_search`, so BM25 `@@@`
@@ -1043,27 +1124,36 @@ export class UserMemoryModel {
const contextFilters: Array<SQL | undefined> = [
whereClause,
- buildTextSearchCondition({
- bm25MatchQuery,
- groups: [
- {
- fallbackColumns: [userMemories.title, userMemories.summary, userMemories.details],
- fields: ['title', 'summary', 'details'],
- keyColumn: userMemories.id,
- },
- {
- fallbackColumns: [
- userMemoriesContexts.title,
- userMemoriesContexts.description,
- userMemoriesContexts.currentStatus,
+ candidateIds
+ ? inJsonStringArray(userMemoriesContexts.id, candidateIds)
+ : buildTextSearchCondition({
+ bm25MatchQuery,
+ groups: [
+ {
+ fallbackColumns: [
+ userMemories.title,
+ userMemories.summary,
+ userMemories.details,
+ ],
+ fields: ['title', 'summary', 'details'],
+ keyColumn: userMemories.id,
+ },
+ {
+ fallbackColumns: [
+ userMemoriesContexts.title,
+ userMemoriesContexts.description,
+ userMemoriesContexts.currentStatus,
+ ],
+ fields: ['title', 'description', 'current_status'],
+ keyColumn: userMemoriesContexts.id,
+ },
],
- fields: ['title', 'description', 'current_status'],
- keyColumn: userMemoriesContexts.id,
- },
- ],
- normalizedQuery,
- supportsBm25,
- }),
+ normalizedQuery,
+ supportsBm25,
+ }),
+ status && status.length > 0
+ ? inArray(userMemoriesContexts.currentStatus, status)
+ : undefined,
types && types.length > 0 ? inArray(userMemoriesContexts.type, types) : undefined,
tags && tags.length > 0
? or(
@@ -1150,27 +1240,33 @@ export class UserMemoryModel {
const activityFilters: Array<SQL | undefined> = [
whereClause,
- buildTextSearchCondition({
- bm25MatchQuery,
- groups: [
- {
- fallbackColumns: [userMemories.title, userMemories.summary, userMemories.details],
- fields: ['title', 'summary', 'details'],
- keyColumn: userMemories.id,
- },
- {
- fallbackColumns: [
- userMemoriesActivities.narrative,
- userMemoriesActivities.notes,
- userMemoriesActivities.feedback,
+ candidateIds
+ ? inJsonStringArray(userMemoriesActivities.id, candidateIds)
+ : buildTextSearchCondition({
+ bm25MatchQuery,
+ groups: [
+ {
+ fallbackColumns: [
+ userMemories.title,
+ userMemories.summary,
+ userMemories.details,
+ ],
+ fields: ['title', 'summary', 'details'],
+ keyColumn: userMemories.id,
+ },
+ {
+ fallbackColumns: [
+ userMemoriesActivities.narrative,
+ userMemoriesActivities.notes,
+ userMemoriesActivities.feedback,
+ ],
+ fields: ['narrative', 'notes', 'feedback'],
+ keyColumn: userMemoriesActivities.id,
+ },
],
- fields: ['narrative', 'notes', 'feedback'],
- keyColumn: userMemoriesActivities.id,
- },
- ],
- normalizedQuery,
- supportsBm25,
- }),
+ normalizedQuery,
+ supportsBm25,
+ }),
types && types.length > 0 ? inArray(userMemoriesActivities.type, types) : undefined,
status && status.length > 0 ? inArray(userMemoriesActivities.status, status) : undefined,
tags && tags.length > 0
@@ -1265,27 +1361,33 @@ export class UserMemoryModel {
const experienceFilters: Array<SQL | undefined> = [
whereClause,
- buildTextSearchCondition({
- bm25MatchQuery,
- groups: [
- {
- fallbackColumns: [userMemories.title, userMemories.summary, userMemories.details],
- fields: ['title', 'summary', 'details'],
- keyColumn: userMemories.id,
- },
- {
- fallbackColumns: [
- userMemoriesExperiences.situation,
- userMemoriesExperiences.keyLearning,
- userMemoriesExperiences.action,
+ candidateIds
+ ? inJsonStringArray(userMemoriesExperiences.id, candidateIds)
+ : buildTextSearchCondition({
+ bm25MatchQuery,
+ groups: [
+ {
+ fallbackColumns: [
+ userMemories.title,
+ userMemories.summary,
+ userMemories.details,
+ ],
+ fields: ['title', 'summary', 'details'],
+ keyColumn: userMemories.id,
+ },
+ {
+ fallbackColumns: [
+ userMemoriesExperiences.situation,
+ userMemoriesExperiences.keyLearning,
+ userMemoriesExperiences.action,
+ ],
+ fields: ['situation', 'key_learning', 'action'],
+ keyColumn: userMemoriesExperiences.id,
+ },
],
- fields: ['situation', 'key_learning', 'action'],
- keyColumn: userMemoriesExperiences.id,
- },
- ],
- normalizedQuery,
- supportsBm25,
- }),
+ normalizedQuery,
+ supportsBm25,
+ }),
types && types.length > 0 ? inArray(userMemoriesExperiences.type, types) : undefined,
tags && tags.length > 0
? or(...tags.map((tag) => sql<boolean>`${tag} = ANY(${userMemoriesExperiences.tags})`))
@@ -1360,23 +1462,32 @@ export class UserMemoryModel {
const identityFilters: Array<SQL | undefined> = [
whereClause,
- buildTextSearchCondition({
- bm25MatchQuery,
- groups: [
- {
- fallbackColumns: [userMemories.title, userMemories.summary, userMemories.details],
- fields: ['title', 'summary', 'details'],
- keyColumn: userMemories.id,
- },
- {
- fallbackColumns: [userMemoriesIdentities.description, userMemoriesIdentities.role],
- fields: ['description', 'role'],
- keyColumn: userMemoriesIdentities.id,
- },
- ],
- normalizedQuery,
- supportsBm25,
- }),
+ candidateIds
+ ? inJsonStringArray(userMemoriesIdentities.id, candidateIds)
+ : buildTextSearchCondition({
+ bm25MatchQuery,
+ groups: [
+ {
+ fallbackColumns: [
+ userMemories.title,
+ userMemories.summary,
+ userMemories.details,
+ ],
+ fields: ['title', 'summary', 'details'],
+ keyColumn: userMemories.id,
+ },
+ {
+ fallbackColumns: [
+ userMemoriesIdentities.description,
+ userMemoriesIdentities.role,
+ ],
+ fields: ['description', 'role'],
+ keyColumn: userMemoriesIdentities.id,
+ },
+ ],
+ normalizedQuery,
+ supportsBm25,
+ }),
types && types.length > 0 ? inArray(userMemoriesIdentities.type, types) : undefined,
tags && tags.length > 0
? or(...tags.map((tag) => sql<boolean>`${tag} = ANY(${userMemoriesIdentities.tags})`))
@@ -1458,26 +1569,32 @@ export class UserMemoryModel {
const preferenceFilters: Array<SQL | undefined> = [
whereClause,
- buildTextSearchCondition({
- bm25MatchQuery,
- groups: [
- {
- fallbackColumns: [userMemories.title, userMemories.summary, userMemories.details],
- fields: ['title', 'summary', 'details'],
- keyColumn: userMemories.id,
- },
- {
- fallbackColumns: [
- userMemoriesPreferences.conclusionDirectives,
- userMemoriesPreferences.suggestions,
+ candidateIds
+ ? inJsonStringArray(userMemoriesPreferences.id, candidateIds)
+ : buildTextSearchCondition({
+ bm25MatchQuery,
+ groups: [
+ {
+ fallbackColumns: [
+ userMemories.title,
+ userMemories.summary,
+ userMemories.details,
+ ],
+ fields: ['title', 'summary', 'details'],
+ keyColumn: userMemories.id,
+ },
+ {
+ fallbackColumns: [
+ userMemoriesPreferences.conclusionDirectives,
+ userMemoriesPreferences.suggestions,
+ ],
+ fields: ['conclusion_directives', 'suggestions'],
+ keyColumn: userMemoriesPreferences.id,
+ },
],
- fields: ['conclusion_directives', 'suggestions'],
- keyColumn: userMemoriesPreferences.id,
- },
- ],
- normalizedQuery,
- supportsBm25,
- }),
+ normalizedQuery,
+ supportsBm25,
+ }),
types && types.length > 0 ? inArray(userMemoriesPreferences.type, types) : undefined,
tags && tags.length > 0
? or(...tags.map((tag) => sql<boolean>`${tag} = ANY(${userMemoriesPreferences.tags})`))
diff --git a/packages/database/src/models/userMemory/query.ts b/packages/database/src/models/userMemory/query.ts
index 5aeb844fe07..7508049d0f0 100644
--- a/packages/database/src/models/userMemory/query.ts
+++ b/packages/database/src/models/userMemory/query.ts
@@ -20,6 +20,11 @@ import {
sql,
} from 'drizzle-orm';
+import type {
+ FtsSearchBackendEntity,
+ FtsSearchBackendFilters,
+ FtsSearchCandidateSource,
+} from '../../repositories/ftsSearch';
import type {
UserMemoryActivitiesWithoutVectors,
UserMemoryContextsWithoutVectors,
@@ -37,6 +42,7 @@ import {
} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { normalizeBm25MatchQuery, SAFE_BM25_QUERY_OPTIONS } from '../../utils/bm25';
+import { inJsonStringArray } from '../../utils/inJsonStringArray';
const DEFAULT_HYBRID_SEARCH_LIMIT = 5;
const HYBRID_SEARCH_OVERFETCH_MULTIPLIER = 3;
@@ -70,11 +76,7 @@ export const buildBm25MatchCondition = (
};
export type SearchLayerKey =
- | 'activities'
- | 'contexts'
- | 'experiences'
- | 'identities'
- | 'preferences';
+ 'activities' | 'contexts' | 'experiences' | 'identities' | 'preferences';
interface HybridLayerLimitRecord {
activities?: number;
@@ -662,12 +664,52 @@ export class UserMemoryQueryModel {
constructor(
private readonly db: LobeChatDatabase,
private readonly userId: string,
+ private readonly ftsSearchCandidateSource?: FtsSearchCandidateSource,
) {}
private memoryWhere(table: { userId: any }) {
return eq(table.userId, this.userId);
}
+ private buildCandidateFilters(
+ entity: FtsSearchBackendEntity,
+ params: SearchMemoryParams,
+ ): FtsSearchBackendFilters {
+ const memoryTags = this.toSearchTags(params);
+
+ return {
+ ...(params.categories?.length ? { memoryCategories: params.categories } : {}),
+ ...(entity === 'memoryIdentities' && params.relationships?.length
+ ? { memoryRelationships: params.relationships }
+ : {}),
+ ...((entity === 'memoryActivities' || entity === 'memoryContexts') && params.status?.length
+ ? { memoryStatus: params.status }
+ : {}),
+ ...(memoryTags.length ? { memoryTags } : {}),
+ ...(params.timeRange ? { memoryTimeRange: params.timeRange } : {}),
+ ...(params.types?.length ? { memoryTypes: params.types } : {}),
+ };
+ }
+
+ private async fetchFtsSearchCandidates(params: {
+ entity: FtsSearchBackendEntity;
+ fields: string[];
+ limit: number;
+ query: string;
+ searchParams: SearchMemoryParams;
+ }) {
+ if (!this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled) return undefined;
+
+ const { candidates } = await this.ftsSearchCandidateSource.ftsSearchCandidates({
+ entity: params.entity,
+ filters: this.buildCandidateFilters(params.entity, params.searchParams),
+ pagination: { limit: params.limit },
+ query: { fields: params.fields, text: params.query },
+ });
+
+ return candidates.map(({ id }) => id);
+ }
+
/**
* Hybrid memory retrieval pipeline for the five heterogeneous memory layers.
*
@@ -2089,6 +2131,22 @@ export class UserMemoryQueryModel {
params: SearchMemoryParams,
) {
const normalizedQuery = typeof query === 'string' ? query.trim() : '';
+ const candidateIds = normalizedQuery
+ ? await this.fetchFtsSearchCandidates({
+ entity: 'memoryActivities',
+ fields: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'narrative',
+ 'notes',
+ 'feedback',
+ ],
+ limit,
+ query: normalizedQuery,
+ searchParams: params,
+ })
+ : undefined;
const conditions = [
this.memoryWhere(userMemoriesActivities),
this.memoryWhere(userMemories),
@@ -2108,13 +2166,15 @@ export class UserMemoryQueryModel {
params.timeRange,
),
normalizedQuery
- ? buildBm25MatchCondition(normalizedQuery, [
- { fields: ['title', 'summary', 'details'], keyColumn: userMemories.id },
- {
- fields: ['narrative', 'notes', 'feedback'],
- keyColumn: userMemoriesActivities.id,
- },
- ])
+ ? candidateIds
+ ? inJsonStringArray(userMemoriesActivities.id, candidateIds)
+ : buildBm25MatchCondition(normalizedQuery, [
+ { fields: ['title', 'summary', 'details'], keyColumn: userMemories.id },
+ {
+ fields: ['narrative', 'notes', 'feedback'],
+ keyColumn: userMemoriesActivities.id,
+ },
+ ])
: undefined,
this.buildExactTagFilterCondition(userMemoriesActivities.tags, userMemories.tags, params),
].filter((condition): condition is SQL => Boolean(condition));
@@ -2157,12 +2217,24 @@ export class UserMemoryQueryModel {
params: SearchMemoryParams,
) {
const normalizedQuery = typeof query === 'string' ? query.trim() : '';
+ const candidateIds = normalizedQuery
+ ? await this.fetchFtsSearchCandidates({
+ entity: 'memoryContexts',
+ fields: ['parent_text', 'title', 'description', 'current_status'],
+ limit,
+ query: normalizedQuery,
+ searchParams: params,
+ })
+ : undefined;
const conditions = [
this.memoryWhere(userMemoriesContexts),
this.memoryWhere(userMemories),
params.categories?.length
? inArray(userMemories.memoryCategory, params.categories)
: undefined,
+ params.status?.length
+ ? inArray(userMemoriesContexts.currentStatus, params.status)
+ : undefined,
params.types?.length ? inArray(userMemoriesContexts.type, params.types) : undefined,
this.buildTimeRangeCondition(
{
@@ -2173,13 +2245,15 @@ export class UserMemoryQueryModel {
params.timeRange,
),
normalizedQuery
- ? buildBm25MatchCondition(normalizedQuery, [
- { fields: ['title', 'summary', 'details'], keyColumn: userMemories.id },
- {
- fields: ['title', 'description', 'current_status'],
- keyColumn: userMemoriesContexts.id,
- },
- ])
+ ? candidateIds
+ ? inJsonStringArray(userMemoriesContexts.id, candidateIds)
+ : buildBm25MatchCondition(normalizedQuery, [
+ { fields: ['title', 'summary', 'details'], keyColumn: userMemories.id },
+ {
+ fields: ['title', 'description', 'current_status'],
+ keyColumn: userMemoriesContexts.id,
+ },
+ ])
: undefined,
this.buildExactTagFilterCondition(userMemoriesContexts.tags, userMemories.tags, params),
].filter((condition): condition is SQL => Boolean(condition));
@@ -2261,6 +2335,24 @@ export class UserMemoryQueryModel {
params: SearchMemoryParams,
) {
const normalizedQuery = typeof query === 'string' ? query.trim() : '';
+ const candidateIds = normalizedQuery
+ ? await this.fetchFtsSearchCandidates({
+ entity: 'memoryExperiences',
+ fields: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'situation',
+ 'reasoning',
+ 'possible_outcome',
+ 'action',
+ 'key_learning',
+ ],
+ limit,
+ query: normalizedQuery,
+ searchParams: params,
+ })
+ : undefined;
const conditions = [
this.memoryWhere(userMemoriesExperiences),
this.memoryWhere(userMemories),
@@ -2277,13 +2369,15 @@ export class UserMemoryQueryModel {
params.timeRange,
),
normalizedQuery
- ? buildBm25MatchCondition(normalizedQuery, [
- { fields: ['title', 'summary', 'details'], keyColumn: userMemories.id },
- {
- fields: ['situation', 'key_learning', 'action', 'reasoning', 'possible_outcome'],
- keyColumn: userMemoriesExperiences.id,
- },
- ])
+ ? candidateIds
+ ? inJsonStringArray(userMemoriesExperiences.id, candidateIds)
+ : buildBm25MatchCondition(normalizedQuery, [
+ { fields: ['title', 'summary', 'details'], keyColumn: userMemories.id },
+ {
+ fields: ['situation', 'key_learning', 'action', 'reasoning', 'possible_outcome'],
+ keyColumn: userMemoriesExperiences.id,
+ },
+ ])
: undefined,
this.buildExactTagFilterCondition(userMemoriesExperiences.tags, userMemories.tags, params),
].filter((condition): condition is SQL => Boolean(condition));
@@ -2322,6 +2416,21 @@ export class UserMemoryQueryModel {
params: SearchMemoryParams,
) {
const normalizedQuery = typeof query === 'string' ? query.trim() : '';
+ const candidateIds = normalizedQuery
+ ? await this.fetchFtsSearchCandidates({
+ entity: 'memoryPreferences',
+ fields: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'conclusion_directives',
+ 'suggestions',
+ ],
+ limit,
+ query: normalizedQuery,
+ searchParams: params,
+ })
+ : undefined;
const conditions = [
this.memoryWhere(userMemoriesPreferences),
this.memoryWhere(userMemories),
@@ -2338,13 +2447,15 @@ export class UserMemoryQueryModel {
params.timeRange,
),
normalizedQuery
- ? buildBm25MatchCondition(normalizedQuery, [
- { fields: ['title', 'summary', 'details'], keyColumn: userMemories.id },
- {
- fields: ['conclusion_directives', 'suggestions'],
- keyColumn: userMemoriesPreferences.id,
- },
- ])
+ ? candidateIds
+ ? inJsonStringArray(userMemoriesPreferences.id, candidateIds)
+ : buildBm25MatchCondition(normalizedQuery, [
+ { fields: ['title', 'summary', 'details'], keyColumn: userMemories.id },
+ {
+ fields: ['conclusion_directives', 'suggestions'],
+ keyColumn: userMemoriesPreferences.id,
+ },
+ ])
: undefined,
this.buildExactTagFilterCondition(userMemoriesPreferences.tags, userMemories.tags, params),
].filter((condition): condition is SQL => Boolean(condition));
@@ -2380,6 +2491,15 @@ export class UserMemoryQueryModel {
params: SearchMemoryParams,
) {
const normalizedQuery = typeof query === 'string' ? query.trim() : '';
+ const candidateIds = normalizedQuery
+ ? await this.fetchFtsSearchCandidates({
+ entity: 'memoryIdentities',
+ fields: ['parent_title', 'parent_summary', 'parent_details', 'description', 'role'],
+ limit,
+ query: normalizedQuery,
+ searchParams: params,
+ })
+ : undefined;
const conditions = [
this.memoryWhere(userMemoriesIdentities),
this.memoryWhere(userMemories),
@@ -2400,10 +2520,12 @@ export class UserMemoryQueryModel {
params.timeRange,
),
normalizedQuery
- ? buildBm25MatchCondition(normalizedQuery, [
- { fields: ['title', 'summary', 'details'], keyColumn: userMemories.id },
- { fields: ['description', 'role'], keyColumn: userMemoriesIdentities.id },
- ])
+ ? candidateIds
+ ? inJsonStringArray(userMemoriesIdentities.id, candidateIds)
+ : buildBm25MatchCondition(normalizedQuery, [
+ { fields: ['title', 'summary', 'details'], keyColumn: userMemories.id },
+ { fields: ['description', 'role'], keyColumn: userMemoriesIdentities.id },
+ ])
: undefined,
this.buildExactTagFilterCondition(userMemoriesIdentities.tags, userMemories.tags, params),
].filter((condition): condition is SQL => Boolean(condition));
diff --git a/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.ts b/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.ts
new file mode 100644
index 00000000000..020536da870
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.ts
@@ -0,0 +1,1797 @@
+// @vitest-environment node
+import { FileSource } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ agents,
+ chatGroups,
+ DOCUMENT_FOLDER_TYPE,
+ documents,
+ files,
+ knowledgeBaseFiles,
+ knowledgeBases,
+ messages,
+ sessions,
+ topics,
+ userMemories,
+ users,
+ workspaces,
+} from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { ElasticsearchFtsSearchBackend, type ElasticsearchFtsSearchClient } from '../elasticsearch';
+import type {
+ FtsSearchBackendFilters,
+ FtsSearchBackendRequest,
+ FtsSearchBackendScope,
+} from '../types';
+
+const db: LobeChatDatabase = await getTestDB();
+
+const userId = 'es-search-user';
+const otherUserId = 'es-search-other-user';
+const workspaceId = 'es-search-workspace';
+const otherWorkspaceId = 'es-search-other-workspace';
+const indexNamespace = 'lobehub-dev';
+
+const request = (
+ entity: FtsSearchBackendRequest['entity'],
+ options: {
+ agentId?: string;
+ filters?: Partial<FtsSearchBackendFilters>;
+ limit?: number;
+ query?: string;
+ scope?: Partial<FtsSearchBackendScope>;
+ } = {},
+): FtsSearchBackendRequest => ({
+ entity,
+ filters: { agentId: options.agentId, ...options.filters },
+ pagination: { limit: options.limit ?? 5 },
+ query: { text: options.query ?? 'search phrase' },
+ scope: {
+ userId,
+ workspaceId,
+ ...options.scope,
+ },
+});
+
+const createClient = (
+ hits: Array<{ _id: string; _score: number | null }>,
+): ElasticsearchFtsSearchClient => ({
+ search: vi.fn().mockResolvedValue({ hits: { hits } }),
+});
+
+beforeEach(async () => {
+ await db.delete(users);
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await db.insert(workspaces).values([
+ {
+ id: workspaceId,
+ name: 'Search Workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ },
+ {
+ id: otherWorkspaceId,
+ name: 'Other Search Workspace',
+ primaryOwnerId: otherUserId,
+ slug: otherWorkspaceId,
+ },
+ ]);
+});
+
+afterEach(async () => {
+ await db.delete(users);
+});
+
+describe('ElasticsearchFtsSearchBackend', () => {
+ it('searches and reauthorizes unified user-memory candidates in PostgreSQL', async () => {
+ await db.insert(userMemories).values([
+ {
+ id: 'memory-own',
+ lastAccessedAt: new Date(),
+ memoryLayer: 'context',
+ title: 'Own memory',
+ userId,
+ },
+ {
+ id: 'memory-other',
+ lastAccessedAt: new Date(),
+ memoryLayer: 'context',
+ title: 'Other memory',
+ userId: otherUserId,
+ },
+ ]);
+ const client = createClient([
+ { _id: 'memory-other', _score: 12 },
+ { _id: 'memory-deleted', _score: 10 },
+ { _id: 'memory-own', _score: 8 },
+ ]);
+ const operations: string[] = [];
+ const observer = {
+ observe: async <Result>(
+ _entity: string,
+ operation: string,
+ callback: () => Promise<Result>,
+ ) => {
+ operations.push(operation);
+ return callback();
+ },
+ };
+ const backend = new ElasticsearchFtsSearchBackend(db, {
+ client,
+ indexNamespace,
+ observer,
+ });
+
+ const response = await backend.search(
+ request('userMemories', { scope: { workspaceId: undefined } }),
+ );
+
+ expect(response.items).toEqual([
+ expect.objectContaining({ id: 'memory-own', memoryLayer: 'context', type: 'memory' }),
+ ]);
+ expect(operations).toEqual(['candidate_query', 'pg_hydration']);
+ expect(client.search).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ filter: [{ term: { user_id: userId } }],
+ must: [
+ {
+ multi_match: {
+ fields: ['title^4', 'summary^2', 'details'],
+ operator: 'and',
+ query: 'search phrase',
+ type: 'best_fields',
+ },
+ },
+ ],
+ }),
+ },
+ }),
+ entity: 'userMemories',
+ index: 'lobehub-dev-user-memories',
+ pagination: 'bounded',
+ }),
+ );
+ });
+
+ it('builds exact memory-layer candidate filters without hydrating index documents', async () => {
+ const client = createClient([{ _id: 'context-1', _score: 7 }]);
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ const response = await backend.search({
+ entity: 'memoryContexts',
+ filters: {
+ memoryCategories: ['project'],
+ memoryStatus: ['active'],
+ memoryTags: ['typescript', 'search'],
+ memoryTimeRange: {
+ end: new Date('2026-08-27T00:00:00.000Z'),
+ start: new Date('2026-08-20T00:00:00.000Z'),
+ },
+ memoryTypes: ['workflow'],
+ },
+ mode: 'candidates',
+ pagination: { limit: 3 },
+ query: {
+ fields: ['parent_text', 'title', 'description', 'current_status'],
+ text: 'search-phrase',
+ },
+ scope: { userId },
+ });
+
+ expect(response).toEqual({
+ candidates: [{ id: 'context-1', score: 7 }],
+ items: [],
+ total: 1,
+ });
+ expect(client.search).toHaveBeenCalledWith({
+ body: {
+ _source: false,
+ query: {
+ bool: {
+ filter: [
+ { term: { user_id: userId } },
+ {
+ bool: {
+ minimum_should_match: 1,
+ should: [
+ { terms: { parent_memory_categories: ['project'] } },
+ {
+ bool: {
+ must_not: [{ exists: { field: 'parent_memory_categories' } }],
+ },
+ },
+ ],
+ },
+ },
+ { terms: { type: ['workflow'] } },
+ { terms: { 'current_status.raw': ['active'] } },
+ {
+ bool: {
+ minimum_should_match: 1,
+ should: [
+ { term: { tags: 'typescript' } },
+ { term: { parent_tags: 'typescript' } },
+ { bool: { must_not: [{ exists: { field: 'parent_tags' } }] } },
+ ],
+ },
+ },
+ {
+ bool: {
+ minimum_should_match: 1,
+ should: [
+ { term: { tags: 'search' } },
+ { term: { parent_tags: 'search' } },
+ { bool: { must_not: [{ exists: { field: 'parent_tags' } }] } },
+ ],
+ },
+ },
+ {
+ range: {
+ captured_at: {
+ gte: '2026-08-20T00:00:00.000Z',
+ lte: '2026-08-27T00:00:00.000Z',
+ },
+ },
+ },
+ ],
+ must: [
+ {
+ multi_match: {
+ fields: ['parent_text', 'title', 'description', 'current_status'],
+ operator: 'and',
+ query: 'search phrase',
+ type: 'best_fields',
+ },
+ },
+ ],
+ must_not: [{ term: { fts_search_sync_deleted: true } }],
+ },
+ },
+ size: 12,
+ sort: [{ _score: 'desc' }, { id: 'asc' }],
+ track_total_hits: true,
+ },
+ entity: 'memoryContexts',
+ index: 'lobehub-dev-memory-contexts',
+ pagination: 'bounded',
+ });
+ });
+
+ it('preserves the any-tag contract for legacy memory lists', async () => {
+ const client = createClient([]);
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ await backend.search({
+ entity: 'memoryActivities',
+ filters: {
+ memoryTagMatch: 'any',
+ memoryTags: ['typescript', 'search'],
+ },
+ mode: 'candidates',
+ pagination: { limit: 3 },
+ query: { text: 'candidate' },
+ scope: { userId },
+ });
+
+ expect(client.search).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ filter: [
+ { term: { user_id: userId } },
+ {
+ bool: {
+ minimum_should_match: 1,
+ should: [
+ {
+ bool: {
+ minimum_should_match: 1,
+ should: [
+ { term: { tags: 'typescript' } },
+ { term: { parent_tags: 'typescript' } },
+ { bool: { must_not: [{ exists: { field: 'parent_tags' } }] } },
+ ],
+ },
+ },
+ {
+ bool: {
+ minimum_should_match: 1,
+ should: [
+ { term: { tags: 'search' } },
+ { term: { parent_tags: 'search' } },
+ { bool: { must_not: [{ exists: { field: 'parent_tags' } }] } },
+ ],
+ },
+ },
+ ],
+ },
+ },
+ ],
+ }),
+ },
+ }),
+ }),
+ );
+ });
+
+ it('rejects message topic scope when PostgreSQL parent filtering is unavailable', async () => {
+ const client = createClient([]);
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ await expect(
+ backend.search({
+ entity: 'messages',
+ filters: { topicScope: { groupId: 'group-1' } },
+ pagination: { limit: 5 },
+ query: { text: 'scoped message' },
+ scope: { userId, workspaceId },
+ }),
+ ).rejects.toThrow('Elasticsearch message topic scope requires candidate-only search');
+ expect(client.search).not.toHaveBeenCalled();
+ });
+
+ it('applies topic scope only where the indexed document owns the scope fields', async () => {
+ const client = createClient([]);
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ await backend.search({
+ entity: 'topics',
+ filters: { topicScope: { agentId: 'agent-1' } },
+ mode: 'candidates',
+ pagination: {},
+ query: { fields: ['title'], text: 'legacy topic' },
+ scope: { userId, workspaceId },
+ });
+ await backend.search({
+ entity: 'topics',
+ filters: { topicScope: { groupId: 'group-1' } },
+ mode: 'candidates',
+ pagination: {},
+ query: { fields: ['title'], text: 'legacy topic' },
+ scope: { userId, workspaceId },
+ });
+ await backend.search({
+ entity: 'topics',
+ filters: { topicScope: { containerId: 'container-1' } },
+ mode: 'candidates',
+ pagination: {},
+ query: { fields: ['title'], text: 'legacy topic' },
+ scope: { userId, workspaceId },
+ });
+ await backend.search({
+ entity: 'messages',
+ filters: { topicScope: { groupId: 'group-1' } },
+ mode: 'candidates',
+ pagination: {},
+ query: { fields: ['content'], text: 'legacy message' },
+ scope: { userId, workspaceId },
+ });
+ await backend.search({
+ entity: 'messages',
+ filters: { topicScope: { agentId: 'agent-1' } },
+ mode: 'candidates',
+ pagination: {},
+ query: { fields: ['content'], text: 'legacy message' },
+ scope: { userId, workspaceId },
+ });
+ await backend.search({
+ entity: 'messages',
+ filters: { topicScope: { containerId: 'container-1' } },
+ mode: 'candidates',
+ pagination: {},
+ query: { fields: ['content'], text: 'legacy message' },
+ scope: { userId, workspaceId },
+ });
+
+ expect(client.search).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ filter: [{ term: { workspace_id: workspaceId } }, { term: { agent_id: 'agent-1' } }],
+ must: [
+ {
+ multi_match: {
+ fields: ['title'],
+ operator: 'and',
+ query: 'legacy topic',
+ type: 'best_fields',
+ },
+ },
+ ],
+ }),
+ },
+ }),
+ entity: 'topics',
+ index: 'lobehub-dev-topics',
+ pagination: 'unbounded',
+ }),
+ );
+ expect(client.search).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ filter: [{ term: { workspace_id: workspaceId } }, { term: { group_id: 'group-1' } }],
+ }),
+ },
+ }),
+ entity: 'topics',
+ }),
+ );
+ expect(client.search).toHaveBeenNthCalledWith(
+ 3,
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ filter: [
+ { term: { workspace_id: workspaceId } },
+ {
+ bool: {
+ minimum_should_match: 1,
+ should: [
+ { term: { session_id: 'container-1' } },
+ { term: { group_id: 'container-1' } },
+ ],
+ },
+ },
+ ],
+ }),
+ },
+ }),
+ entity: 'topics',
+ }),
+ );
+ expect(client.search).toHaveBeenNthCalledWith(
+ 4,
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ filter: [
+ { term: { workspace_id: workspaceId } },
+ {
+ bool: {
+ minimum_should_match: 1,
+ should: [
+ { term: { group_id: 'group-1' } },
+ { bool: { must_not: [{ exists: { field: 'group_id' } }] } },
+ ],
+ },
+ },
+ ],
+ must_not: [{ term: { fts_search_sync_deleted: true } }],
+ }),
+ },
+ }),
+ entity: 'messages',
+ index: 'lobehub-dev-messages',
+ pagination: 'unbounded',
+ }),
+ );
+ expect(client.search).toHaveBeenNthCalledWith(
+ 5,
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ filter: [
+ { term: { workspace_id: workspaceId } },
+ {
+ bool: {
+ minimum_should_match: 1,
+ should: [
+ { term: { agent_id: 'agent-1' } },
+ { bool: { must_not: [{ exists: { field: 'agent_id' } }] } },
+ ],
+ },
+ },
+ ],
+ }),
+ },
+ }),
+ entity: 'messages',
+ }),
+ );
+ expect(client.search).toHaveBeenNthCalledWith(
+ 6,
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ filter: [
+ { term: { workspace_id: workspaceId } },
+ {
+ bool: {
+ minimum_should_match: 1,
+ should: [
+ { term: { session_id: 'container-1' } },
+ { term: { group_id: 'container-1' } },
+ {
+ bool: {
+ must_not: [
+ { exists: { field: 'session_id' } },
+ { exists: { field: 'group_id' } },
+ ],
+ },
+ },
+ ],
+ },
+ },
+ ],
+ }),
+ },
+ }),
+ entity: 'messages',
+ }),
+ );
+ });
+
+ it('paginates unbounded legacy candidates with search_after', async () => {
+ const firstPage = Array.from({ length: 1000 }, (_, index) => ({
+ _id: `topic-${index.toString().padStart(4, '0')}`,
+ _score: 1000 - index,
+ sort: [1000 - index, `topic-${index.toString().padStart(4, '0')}`],
+ }));
+ const client: ElasticsearchFtsSearchClient = {
+ search: vi
+ .fn()
+ .mockResolvedValueOnce({ hits: { hits: firstPage, total: { value: 1001 } } })
+ .mockResolvedValueOnce({
+ hits: {
+ hits: [{ _id: 'topic-final', _score: 0, sort: [0, 'topic-final'] }],
+ total: { value: 1001 },
+ },
+ }),
+ };
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ const response = await backend.search({
+ entity: 'topics',
+ filters: {},
+ mode: 'candidates',
+ pagination: {},
+ query: { fields: ['title'], text: 'legacy topic' },
+ scope: { userId },
+ });
+
+ expect(response.candidates).toHaveLength(1001);
+ expect(response.total).toBe(1001);
+ expect(client.search).toHaveBeenCalledTimes(2);
+ expect(client.search).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({ entity: 'topics', pagination: 'unbounded' }),
+ );
+ expect(client.search).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ body: expect.not.objectContaining({
+ track_total_hits: true,
+ }),
+ }),
+ );
+ expect(client.search).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ body: expect.objectContaining({ search_after: firstPage.at(-1)?.sort }),
+ }),
+ );
+ });
+
+ it('queries weighted agent fields and rechecks workspace visibility during hydration', async () => {
+ await db.insert(agents).values([
+ {
+ id: 'agent-public',
+ title: 'Public workspace agent',
+ userId: otherUserId,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ id: 'agent-private-own',
+ title: 'Own private workspace agent',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ },
+ {
+ id: 'agent-legacy-public',
+ title: 'Legacy public workspace agent',
+ userId: otherUserId,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ id: 'agent-private-other',
+ title: 'Other private workspace agent',
+ userId: otherUserId,
+ visibility: 'private',
+ workspaceId,
+ },
+ ]);
+ const client = createClient([
+ { _id: 'agent-private-other', _score: 12 },
+ { _id: 'agent-legacy-public', _score: 11 },
+ { _id: 'agent-public', _score: 10 },
+ { _id: 'agent-private-own', _score: 8 },
+ { _id: 'agent-deleted', _score: 7 },
+ ]);
+ const backend = new ElasticsearchFtsSearchBackend(db, {
+ client,
+ indexNamespace,
+ });
+
+ const response = await backend.search(request('agents'));
+
+ expect(response.candidates).toEqual([
+ { id: 'agent-private-other', score: 12 },
+ { id: 'agent-legacy-public', score: 11 },
+ { id: 'agent-public', score: 10 },
+ { id: 'agent-private-own', score: 8 },
+ { id: 'agent-deleted', score: 7 },
+ ]);
+ expect(response.items).toEqual([
+ expect.objectContaining({ id: 'agent-legacy-public' }),
+ expect.objectContaining({ id: 'agent-public' }),
+ expect.objectContaining({ id: 'agent-private-own' }),
+ ]);
+ expect(client.search).toHaveBeenCalledWith({
+ body: {
+ _source: false,
+ query: {
+ bool: {
+ filter: [
+ { term: { workspace_id: workspaceId } },
+ {
+ bool: {
+ minimum_should_match: 1,
+ should: [
+ { bool: { must_not: [{ exists: { field: 'visibility' } }] } },
+ { term: { visibility: 'public' } },
+ { term: { user_id: userId } },
+ ],
+ },
+ },
+ ],
+ must: [
+ {
+ multi_match: {
+ fields: ['title^5', 'slug^4', 'tags^3', 'description^2', 'system_role'],
+ operator: 'and',
+ query: 'search phrase',
+ type: 'best_fields',
+ },
+ },
+ ],
+ must_not: [{ term: { fts_search_sync_deleted: true } }],
+ },
+ },
+ size: 20,
+ sort: [{ _score: 'desc' }, { id: 'asc' }],
+ },
+ entity: 'agents',
+ index: 'lobehub-dev-agents',
+ pagination: 'bounded',
+ });
+
+ const publicCaller = await backend.search(
+ request('agents', { scope: { callerAgentVisibility: 'public' } }),
+ );
+ expect(publicCaller.items).toEqual([
+ expect.objectContaining({ id: 'agent-legacy-public' }),
+ expect.objectContaining({ id: 'agent-public' }),
+ ]);
+ });
+
+ it('searches chat-group content while personal hydration blocks workspace and stale hits', async () => {
+ await db.insert(chatGroups).values([
+ {
+ content: 'Deep planning notes',
+ id: 'group-personal',
+ title: 'Personal group',
+ userId,
+ },
+ {
+ content: 'Deep workspace notes',
+ id: 'group-workspace',
+ title: 'Workspace group',
+ userId,
+ workspaceId,
+ },
+ ]);
+ const client = createClient([
+ { _id: 'group-workspace', _score: 9 },
+ { _id: 'group-personal', _score: 7 },
+ { _id: 'group-deleted', _score: 6 },
+ ]);
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ const response = await backend.search(
+ request('chatGroups', { scope: { workspaceId: undefined } }),
+ );
+
+ expect(response.items).toEqual([expect.objectContaining({ id: 'group-personal' })]);
+ expect(client.search).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ filter: [{ term: { user_id: userId } }],
+ must: [
+ {
+ multi_match: {
+ fields: ['title^4', 'description^2', 'content'],
+ operator: 'and',
+ query: 'search phrase',
+ type: 'best_fields',
+ },
+ },
+ ],
+ must_not: [
+ { exists: { field: 'workspace_id' } },
+ { term: { fts_search_sync_deleted: true } },
+ ],
+ }),
+ },
+ }),
+ entity: 'chatGroups',
+ index: 'lobehub-dev-chat-groups',
+ pagination: 'bounded',
+ }),
+ );
+ });
+
+ it('reranks topic candidates by recency and blocks invisible parent containers', async () => {
+ await db.insert(agents).values([
+ {
+ id: 'topic-agent-public',
+ title: 'Public topic agent',
+ userId: otherUserId,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ id: 'topic-agent-private',
+ title: 'Private topic agent',
+ userId: otherUserId,
+ visibility: 'private',
+ workspaceId,
+ },
+ ]);
+ await db.insert(chatGroups).values([
+ {
+ id: 'topic-group-public',
+ title: 'Public topic group',
+ userId: otherUserId,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ id: 'topic-group-private',
+ title: 'Private topic group',
+ userId: otherUserId,
+ visibility: 'private',
+ workspaceId,
+ },
+ ]);
+ await db.insert(sessions).values({
+ id: 'topic-session',
+ title: 'Topic session',
+ userId: otherUserId,
+ workspaceId,
+ });
+ await db.insert(topics).values([
+ {
+ agentId: 'topic-agent-public',
+ groupId: 'topic-group-public',
+ id: 'topic-old',
+ sessionId: 'topic-session',
+ title: 'Older relevant topic',
+ updatedAt: new Date('2026-08-20T00:00:00.000Z'),
+ userId,
+ workspaceId,
+ },
+ {
+ agentId: 'topic-agent-public',
+ groupId: 'topic-group-public',
+ id: 'topic-recent',
+ sessionId: 'topic-session',
+ title: 'Recent relevant topic',
+ updatedAt: new Date('2026-08-25T00:00:00.000Z'),
+ userId,
+ workspaceId,
+ },
+ {
+ agentId: 'topic-agent-private',
+ id: 'topic-private-agent',
+ title: 'Private parent agent topic',
+ userId,
+ workspaceId,
+ },
+ {
+ groupId: 'topic-group-private',
+ id: 'topic-private-group',
+ title: 'Private parent group topic',
+ userId,
+ workspaceId,
+ },
+ ]);
+ const client = createClient([
+ { _id: 'topic-old', _score: 12 },
+ { _id: 'topic-private-agent', _score: 11 },
+ { _id: 'topic-private-group', _score: 10 },
+ { _id: 'topic-recent', _score: 8 },
+ ]);
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ const response = await backend.search(request('topics', { limit: 2 }));
+
+ expect(response.items).toEqual([
+ expect.objectContaining({ id: 'topic-recent' }),
+ expect.objectContaining({ id: 'topic-old' }),
+ ]);
+ expect(response.items[0]).toMatchObject({
+ agentId: 'topic-agent-public',
+ groupId: 'topic-group-public',
+ sessionId: 'topic-session',
+ });
+
+ await backend.search(request('topics', { agentId: 'topic-agent-public', limit: 2 }));
+ expect(client.search).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ filter: expect.arrayContaining([{ term: { agent_id: 'topic-agent-public' } }]),
+ }),
+ },
+ }),
+ }),
+ );
+ });
+
+ it('continues topic candidates after parent authorization empties the first page', async () => {
+ await db.insert(agents).values([
+ {
+ id: 'paging-agent-private',
+ title: 'Private paging agent',
+ userId: otherUserId,
+ visibility: 'private',
+ workspaceId,
+ },
+ {
+ id: 'paging-agent-public',
+ title: 'Public paging agent',
+ userId: otherUserId,
+ visibility: 'public',
+ workspaceId,
+ },
+ ]);
+ const privateTopics = Array.from({ length: 7 }, (_, index) => ({
+ agentId: 'paging-agent-private',
+ id: `paging-private-${index}`,
+ title: `Private match ${index}`,
+ userId: otherUserId,
+ workspaceId,
+ }));
+ await db.insert(topics).values([
+ ...privateTopics,
+ {
+ agentId: 'paging-agent-public',
+ id: 'paging-visible-old',
+ title: 'Visible older match',
+ updatedAt: new Date('2026-08-20T00:00:00.000Z'),
+ userId,
+ workspaceId,
+ },
+ {
+ agentId: 'paging-agent-public',
+ id: 'paging-visible-recent',
+ title: 'Visible recent match',
+ updatedAt: new Date('2026-08-25T00:00:00.000Z'),
+ userId,
+ workspaceId,
+ },
+ ]);
+ const firstPage = [
+ ...privateTopics.map(({ id }, index) => ({
+ _id: id,
+ _score: 20 - index,
+ sort: [20 - index, id],
+ })),
+ { _id: 'paging-visible-old', _score: 10, sort: [10, 'paging-visible-old'] },
+ ];
+ const client: ElasticsearchFtsSearchClient = {
+ search: vi
+ .fn()
+ .mockResolvedValueOnce({ hits: { hits: firstPage } })
+ .mockResolvedValueOnce({
+ hits: {
+ hits: [{ _id: 'paging-visible-recent', _score: 9 }],
+ },
+ }),
+ };
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ const response = await backend.search(request('topics', { limit: 2 }));
+
+ expect(response.items).toEqual([
+ expect.objectContaining({ id: 'paging-visible-recent' }),
+ expect.objectContaining({ id: 'paging-visible-old' }),
+ ]);
+ expect(client.search).toHaveBeenCalledTimes(2);
+ expect(client.search).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ body: expect.objectContaining({ search_after: firstPage.at(-1)?.sort }),
+ pagination: 'bounded',
+ }),
+ );
+ });
+
+ it('continues message candidates after parent authorization empties the first page', async () => {
+ await db.insert(agents).values([
+ {
+ id: 'message-paging-agent-private',
+ title: 'Private message paging agent',
+ userId: otherUserId,
+ visibility: 'private',
+ workspaceId,
+ },
+ {
+ id: 'message-paging-agent-public',
+ title: 'Public message paging agent',
+ userId: otherUserId,
+ visibility: 'public',
+ workspaceId,
+ },
+ ]);
+ const privateMessages = Array.from({ length: 8 }, (_, index) => ({
+ agentId: 'message-paging-agent-private',
+ content: `Private message match ${index}`,
+ id: `message-paging-private-${index}`,
+ role: 'assistant' as const,
+ userId: otherUserId,
+ workspaceId,
+ }));
+ await db.insert(messages).values([
+ ...privateMessages,
+ {
+ agentId: 'message-paging-agent-public',
+ content: 'Visible older message',
+ createdAt: new Date('2026-08-20T00:00:00.000Z'),
+ id: 'message-paging-visible-old',
+ role: 'assistant',
+ userId,
+ workspaceId,
+ },
+ {
+ agentId: 'message-paging-agent-public',
+ content: 'Visible recent message',
+ createdAt: new Date('2026-08-25T00:00:00.000Z'),
+ id: 'message-paging-visible-recent',
+ role: 'assistant',
+ userId,
+ workspaceId,
+ },
+ ]);
+ const firstPage = privateMessages.map(({ id }, index) => ({
+ _id: id,
+ _score: 20 - index,
+ sort: [20 - index, id],
+ }));
+ const client: ElasticsearchFtsSearchClient = {
+ search: vi
+ .fn()
+ .mockResolvedValueOnce({ hits: { hits: firstPage } })
+ .mockResolvedValueOnce({
+ hits: {
+ hits: [
+ { _id: 'message-paging-visible-old', _score: 10 },
+ { _id: 'message-paging-visible-recent', _score: 9 },
+ ],
+ },
+ }),
+ };
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ const response = await backend.search(request('messages', { limit: 2 }));
+
+ expect(response.items).toEqual([
+ expect.objectContaining({ id: 'message-paging-visible-recent' }),
+ expect.objectContaining({ id: 'message-paging-visible-old' }),
+ ]);
+ expect(client.search).toHaveBeenCalledTimes(2);
+ expect(client.search).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ body: expect.objectContaining({ search_after: firstPage.at(-1)?.sort }),
+ pagination: 'bounded',
+ }),
+ );
+ });
+
+ it('returns partial conversation results instead of exceeding the candidate budget', async () => {
+ await db.insert(topics).values({
+ id: 'budget-visible-topic',
+ title: 'Visible within budget',
+ userId,
+ workspaceId,
+ });
+ let requestCount = 0;
+ const client: ElasticsearchFtsSearchClient = {
+ search: vi.fn().mockImplementation(({ body }) => {
+ requestCount += 1;
+ if (requestCount > 5) throw new Error('conversation paging exceeded its candidate budget');
+ const searchAfter = body.search_after as [number, string] | undefined;
+ const page = searchAfter?.[0] ?? 0;
+ return Promise.resolve({
+ hits: {
+ hits: Array.from({ length: 8 }, (_, index) => {
+ const id =
+ page === 0 && index === 0
+ ? 'budget-visible-topic'
+ : `hidden-candidate-${page}-${index}`;
+ return { _id: id, _score: 20 - page, sort: [page + 1, id] };
+ }),
+ },
+ });
+ }),
+ };
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ const response = await backend.search(request('topics', { limit: 2 }));
+
+ expect(response.items).toEqual([expect.objectContaining({ id: 'budget-visible-topic' })]);
+ expect(response.candidates).toHaveLength(40);
+ expect(client.search).toHaveBeenCalledTimes(5);
+ });
+
+ it('searches message summaries but excludes tool, foreign, deleted, and private-parent hits in PG', async () => {
+ await db.insert(agents).values([
+ {
+ id: 'message-agent-public',
+ title: 'Public message agent',
+ userId: otherUserId,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ id: 'message-agent-private',
+ title: 'Private message agent',
+ userId: otherUserId,
+ visibility: 'private',
+ workspaceId,
+ },
+ ]);
+ await db.insert(chatGroups).values({
+ id: 'message-group',
+ title: 'Message group',
+ userId: otherUserId,
+ workspaceId,
+ });
+ await db.insert(sessions).values({
+ id: 'message-session',
+ title: 'Message session',
+ userId: otherUserId,
+ workspaceId,
+ });
+ await db.insert(topics).values({
+ agentId: 'message-agent-public',
+ groupId: 'message-group',
+ id: 'message-topic',
+ sessionId: 'message-session',
+ title: 'Message topic',
+ userId,
+ workspaceId,
+ });
+ await db.insert(topics).values({
+ agentId: 'message-agent-private',
+ id: 'message-private-topic',
+ title: 'Private parent agent topic',
+ userId,
+ workspaceId,
+ });
+ await db.insert(messages).values([
+ {
+ agentId: 'message-agent-public',
+ content: 'Older hydrated message',
+ createdAt: new Date('2026-08-20T00:00:00.000Z'),
+ groupId: 'message-group',
+ id: 'message-old',
+ role: 'assistant',
+ sessionId: 'message-session',
+ summary: 'Search phrase only appears in this summary',
+ topicId: 'message-topic',
+ userId,
+ workspaceId,
+ },
+ {
+ agentId: 'message-agent-public',
+ content: 'Recent hydrated message',
+ createdAt: new Date('2026-08-25T00:00:00.000Z'),
+ groupId: 'message-group',
+ id: 'message-recent',
+ role: 'user',
+ sessionId: 'message-session',
+ topicId: 'message-topic',
+ userId,
+ workspaceId,
+ },
+ {
+ content: 'Tool payload',
+ id: 'message-tool',
+ role: 'tool',
+ userId,
+ workspaceId,
+ },
+ {
+ agentId: 'message-agent-private',
+ content: 'Private parent payload',
+ id: 'message-private-agent',
+ role: 'assistant',
+ userId,
+ workspaceId,
+ },
+ {
+ content: 'Private topic parent payload',
+ id: 'message-private-topic-parent',
+ role: 'assistant',
+ topicId: 'message-private-topic',
+ userId,
+ workspaceId,
+ },
+ {
+ content: 'Foreign workspace payload',
+ id: 'message-foreign-workspace',
+ role: 'user',
+ userId: otherUserId,
+ workspaceId: otherWorkspaceId,
+ },
+ ]);
+ const client = createClient([
+ { _id: 'message-old', _score: 12 },
+ { _id: 'message-tool', _score: 11 },
+ { _id: 'message-private-agent', _score: 10 },
+ { _id: 'message-private-topic-parent', _score: 9.5 },
+ { _id: 'message-foreign-workspace', _score: 9 },
+ { _id: 'message-deleted', _score: 8 },
+ { _id: 'message-recent', _score: 7 },
+ ]);
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ const response = await backend.search(request('messages', { limit: 2 }));
+
+ expect(response.items).toEqual([
+ expect.objectContaining({ id: 'message-recent' }),
+ expect.objectContaining({ id: 'message-old' }),
+ ]);
+ expect(response.items[0]).toMatchObject({
+ agentId: 'message-agent-public',
+ groupId: 'message-group',
+ topicId: 'message-topic',
+ });
+ expect(client.search).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ must: [
+ {
+ multi_match: {
+ fields: ['content^2', 'summary'],
+ operator: 'and',
+ query: 'search phrase',
+ type: 'best_fields',
+ },
+ },
+ ],
+ must_not: [{ term: { fts_search_sync_deleted: true } }, { term: { role: 'tool' } }],
+ }),
+ },
+ }),
+ entity: 'messages',
+ index: 'lobehub-dev-messages',
+ pagination: 'bounded',
+ }),
+ );
+ });
+
+ it('searches files by name and rechecks hidden sources and restricted KB memberships in PG', async () => {
+ const longFileDescription = `Hydrated file description ${'x'.repeat(220)}`;
+ await db.insert(knowledgeBases).values([
+ {
+ id: 'file-kb-open',
+ name: 'Open file KB',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ id: 'file-kb-restricted',
+ name: 'Restricted file KB',
+ userId: otherUserId,
+ visibility: 'public',
+ workspaceId,
+ },
+ ]);
+ await db.insert(files).values([
+ {
+ fileType: 'text/plain',
+ id: 'file-open',
+ name: 'Search phrase notes',
+ size: 10,
+ url: 'file://file-open',
+ userId,
+ workspaceId,
+ },
+ {
+ fileType: 'text/plain',
+ id: 'file-restricted',
+ name: 'Search phrase restricted',
+ size: 20,
+ url: 'file://file-restricted',
+ userId,
+ workspaceId,
+ },
+ {
+ fileType: 'text/plain',
+ id: 'file-hidden-source',
+ name: 'Search phrase acceptance',
+ size: 30,
+ source: FileSource.Acceptance,
+ url: 'file://file-hidden-source',
+ userId,
+ workspaceId,
+ },
+ {
+ fileType: 'custom/document',
+ id: 'file-page-shell',
+ name: 'Search phrase page shell',
+ size: 40,
+ url: 'file://file-page-shell',
+ userId,
+ workspaceId,
+ },
+ {
+ fileType: 'text/plain',
+ id: 'file-private-other',
+ name: 'Search phrase private',
+ size: 50,
+ url: 'file://file-private-other',
+ userId: otherUserId,
+ visibility: 'private',
+ workspaceId,
+ },
+ ]);
+ await db.insert(knowledgeBaseFiles).values([
+ { fileId: 'file-open', knowledgeBaseId: 'file-kb-open', userId, workspaceId },
+ {
+ fileId: 'file-restricted',
+ knowledgeBaseId: 'file-kb-restricted',
+ userId,
+ workspaceId,
+ },
+ ]);
+ await db.insert(documents).values({
+ content: longFileDescription,
+ fileId: 'file-open',
+ fileType: 'text/plain',
+ filename: 'search-phrase-notes.txt',
+ source: 'file://search-phrase-notes.txt',
+ sourceType: 'file',
+ title: 'Search phrase notes',
+ totalCharCount: longFileDescription.length,
+ totalLineCount: 1,
+ userId,
+ workspaceId,
+ });
+ const client = createClient([
+ { _id: 'file-restricted', _score: 12 },
+ { _id: 'file-hidden-source', _score: 11 },
+ { _id: 'file-page-shell', _score: 10 },
+ { _id: 'file-private-other', _score: 9 },
+ { _id: 'file-deleted', _score: 8 },
+ { _id: 'file-open', _score: 7 },
+ ]);
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ const response = await backend.search(
+ request('files', {
+ filters: { excludeKnowledgeBaseIds: ['file-kb-restricted'] },
+ }),
+ );
+
+ expect(response.items).toEqual([
+ expect.objectContaining({
+ description: `${longFileDescription.slice(0, 200)}...`,
+ id: 'file-open',
+ knowledgeBaseId: 'file-kb-open',
+ type: 'file',
+ }),
+ ]);
+ expect(client.search).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ must: [
+ {
+ multi_match: {
+ fields: ['name.raw^8', 'name^4', 'name.words^2'],
+ operator: 'and',
+ query: 'search phrase',
+ type: 'best_fields',
+ },
+ },
+ ],
+ must_not: expect.arrayContaining([
+ { term: { file_type: 'custom/document' } },
+ { terms: { source: [FileSource.Acceptance] } },
+ { terms: { knowledge_base_ids: ['file-kb-restricted'] } },
+ ]),
+ }),
+ },
+ }),
+ entity: 'files',
+ index: 'lobehub-dev-files',
+ pagination: 'bounded',
+ }),
+ );
+ });
+
+ it('keeps folder fields separate from page content and rechecks restricted document links', async () => {
+ await db.insert(knowledgeBases).values({
+ id: 'documents-kb-restricted',
+ name: 'Restricted documents KB',
+ userId: otherUserId,
+ visibility: 'public',
+ workspaceId,
+ });
+ await db.insert(documents).values([
+ {
+ description: 'Search phrase folder description',
+ fileType: DOCUMENT_FOLDER_TYPE,
+ filename: 'open-folder',
+ id: 'folder-open',
+ source: 'internal://folder/open',
+ sourceType: 'api',
+ title: 'Open search folder',
+ totalCharCount: 0,
+ totalLineCount: 0,
+ userId,
+ workspaceId,
+ },
+ {
+ description: 'Search phrase restricted folder',
+ fileType: DOCUMENT_FOLDER_TYPE,
+ filename: 'restricted-folder',
+ id: 'folder-restricted',
+ knowledgeBaseId: 'documents-kb-restricted',
+ source: 'internal://folder/restricted',
+ sourceType: 'api',
+ title: 'Restricted folder',
+ totalCharCount: 0,
+ totalLineCount: 0,
+ userId,
+ workspaceId,
+ },
+ {
+ content: 'Search phrase appears only in page content',
+ fileType: 'custom/document',
+ filename: 'content-page',
+ id: 'folder-page-candidate',
+ source: 'internal://document/content-page',
+ sourceType: 'api',
+ title: 'Unrelated page title',
+ totalCharCount: 42,
+ totalLineCount: 1,
+ userId,
+ workspaceId,
+ },
+ ]);
+ const client = createClient([
+ { _id: 'folder-restricted', _score: 10 },
+ { _id: 'folder-page-candidate', _score: 9 },
+ { _id: 'folder-open', _score: 8 },
+ ]);
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ const response = await backend.search(
+ request('documents', {
+ filters: {
+ documentKind: 'folder',
+ excludeKnowledgeBaseIds: ['documents-kb-restricted'],
+ },
+ }),
+ );
+
+ expect(response.items).toEqual([
+ expect.objectContaining({ id: 'folder-open', type: 'folder' }),
+ ]);
+ expect(client.search).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ filter: expect.arrayContaining([{ term: { file_type: DOCUMENT_FOLDER_TYPE } }]),
+ must: [
+ {
+ multi_match: {
+ fields: ['title^4', 'slug^3', 'description^2'],
+ operator: 'and',
+ query: 'search phrase',
+ type: 'best_fields',
+ },
+ },
+ ],
+ must_not: expect.arrayContaining([
+ { terms: { knowledge_base_ids: ['documents-kb-restricted'] } },
+ ]),
+ }),
+ },
+ }),
+ entity: 'documents',
+ index: 'lobehub-dev-documents',
+ pagination: 'bounded',
+ }),
+ );
+ });
+
+ it('rechecks direct and file-backed restricted memberships while hydrating pages', async () => {
+ await db.insert(knowledgeBases).values([
+ {
+ id: 'page-kb-open',
+ name: 'Open page KB',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ id: 'page-kb-restricted',
+ name: 'Restricted page KB',
+ userId: otherUserId,
+ visibility: 'public',
+ workspaceId,
+ },
+ ]);
+ await db.insert(files).values({
+ fileType: 'application/pdf',
+ id: 'page-restricted-file',
+ name: 'restricted.pdf',
+ size: 100,
+ url: 'file://page-restricted-file',
+ userId,
+ workspaceId,
+ });
+ await db.insert(knowledgeBaseFiles).values({
+ fileId: 'page-restricted-file',
+ knowledgeBaseId: 'page-kb-restricted',
+ userId,
+ workspaceId,
+ });
+ await db.insert(documents).values([
+ {
+ content: 'Search phrase open page',
+ fileType: 'custom/document',
+ filename: 'open-page',
+ id: 'page-open',
+ knowledgeBaseId: 'page-kb-open',
+ source: 'internal://document/open-page',
+ sourceType: 'api',
+ title: 'Open page',
+ totalCharCount: 23,
+ totalLineCount: 1,
+ userId,
+ workspaceId,
+ },
+ {
+ content: 'Search phrase direct restricted page',
+ fileType: 'custom/document',
+ filename: 'direct-restricted-page',
+ id: 'page-direct-restricted',
+ knowledgeBaseId: 'page-kb-restricted',
+ source: 'internal://document/direct-restricted',
+ sourceType: 'api',
+ title: 'Direct restricted page',
+ totalCharCount: 36,
+ totalLineCount: 1,
+ userId,
+ workspaceId,
+ },
+ {
+ content: 'Search phrase file restricted page',
+ fileId: 'page-restricted-file',
+ fileType: 'custom/document',
+ filename: 'file-restricted-page',
+ id: 'page-file-restricted',
+ source: 'file://page-restricted-file',
+ sourceType: 'file',
+ title: 'File restricted page',
+ totalCharCount: 34,
+ totalLineCount: 1,
+ userId,
+ workspaceId,
+ },
+ ]);
+ const client = createClient([
+ { _id: 'page-direct-restricted', _score: 12 },
+ { _id: 'page-file-restricted', _score: 11 },
+ { _id: 'page-open', _score: 10 },
+ ]);
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ const response = await backend.search(
+ request('documents', {
+ filters: {
+ documentKind: 'page',
+ excludeKnowledgeBaseIds: ['page-kb-restricted'],
+ },
+ }),
+ );
+
+ expect(response.items).toEqual([expect.objectContaining({ id: 'page-open', type: 'page' })]);
+ expect(client.search).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ filter: expect.arrayContaining([{ term: { file_type: 'custom/document' } }]),
+ must: [
+ {
+ multi_match: {
+ fields: ['title^4', 'slug^3', 'content'],
+ operator: 'and',
+ query: 'search phrase',
+ type: 'best_fields',
+ },
+ },
+ ],
+ must_not: expect.arrayContaining([
+ { terms: { knowledge_base_ids: ['page-kb-restricted'] } },
+ ]),
+ }),
+ },
+ }),
+ }),
+ );
+ });
+
+ it('hydrates inline and file-backed KB documents without truncating candidates by document size', async () => {
+ const largeContent = `search phrase ${'x'.repeat(1_000_000)}`;
+ await db.insert(knowledgeBases).values([
+ {
+ id: 'document-kb-target',
+ name: 'Target document KB',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ id: 'document-kb-other',
+ name: 'Other document KB',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ },
+ ]);
+ await db.insert(files).values({
+ fileType: 'application/pdf',
+ id: 'document-file-backed',
+ name: 'file-backed.pdf',
+ size: 1024,
+ url: 'file://document-file-backed',
+ userId,
+ workspaceId,
+ });
+ await db.insert(knowledgeBaseFiles).values({
+ fileId: 'document-file-backed',
+ knowledgeBaseId: 'document-kb-target',
+ userId,
+ workspaceId,
+ });
+ await db.insert(documents).values([
+ {
+ content: largeContent,
+ fileType: 'custom/document',
+ filename: 'inline-large',
+ id: 'document-inline-large',
+ knowledgeBaseId: 'document-kb-target',
+ source: 'internal://document/inline-large',
+ sourceType: 'api',
+ title: 'Large inline document',
+ totalCharCount: largeContent.length,
+ totalLineCount: 1,
+ userId,
+ visibility: 'private',
+ workspaceId,
+ },
+ {
+ content: 'Search phrase in parsed PDF',
+ fileId: 'document-file-backed',
+ fileType: 'application/pdf',
+ filename: 'file-backed.pdf',
+ id: 'document-file-backed-row',
+ source: 'file://document-file-backed',
+ sourceType: 'file',
+ title: 'File-backed document',
+ totalCharCount: 27,
+ totalLineCount: 1,
+ userId,
+ workspaceId,
+ },
+ {
+ content: 'Search phrase in another KB',
+ fileType: 'custom/document',
+ filename: 'other-kb',
+ id: 'document-other-kb',
+ knowledgeBaseId: 'document-kb-other',
+ source: 'internal://document/other-kb',
+ sourceType: 'api',
+ title: 'Other KB document',
+ totalCharCount: 27,
+ totalLineCount: 1,
+ userId,
+ workspaceId,
+ },
+ {
+ content: 'Search phrase folder',
+ fileType: DOCUMENT_FOLDER_TYPE,
+ filename: 'document-folder',
+ id: 'document-folder',
+ knowledgeBaseId: 'document-kb-target',
+ source: 'internal://folder/document-folder',
+ sourceType: 'api',
+ title: 'Document folder',
+ totalCharCount: 20,
+ totalLineCount: 1,
+ userId,
+ workspaceId,
+ },
+ ]);
+ const client = createClient([
+ { _id: 'document-other-kb', _score: 13 },
+ { _id: 'document-folder', _score: 12 },
+ { _id: 'document-inline-large', _score: 11 },
+ { _id: 'document-file-backed-row', _score: 10 },
+ { _id: 'document-deleted', _score: 9 },
+ ]);
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ const response = await backend.search(
+ request('documents', {
+ filters: {
+ documentKind: 'knowledgeBaseDocument',
+ knowledgeBaseIds: ['document-kb-target'],
+ },
+ }),
+ );
+
+ expect(response.items).toEqual([
+ expect.objectContaining({
+ documentId: 'document-inline-large',
+ knowledgeBaseId: 'document-kb-target',
+ }),
+ expect.objectContaining({
+ documentId: 'document-file-backed-row',
+ fileId: 'document-file-backed',
+ knowledgeBaseId: 'document-kb-target',
+ }),
+ ]);
+ expect(response.items[0]).toMatchObject({
+ snippet: `${largeContent.slice(0, 300)}...`,
+ });
+
+ const publicAgentResponse = await backend.search(
+ request('documents', {
+ filters: {
+ documentKind: 'knowledgeBaseDocument',
+ knowledgeBaseIds: ['document-kb-target'],
+ },
+ scope: { callerAgentVisibility: 'public' },
+ }),
+ );
+ expect(publicAgentResponse.items).toEqual([
+ expect.objectContaining({ documentId: 'document-file-backed-row' }),
+ ]);
+ expect(client.search).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ filter: expect.arrayContaining([
+ { terms: { knowledge_base_ids: ['document-kb-target'] } },
+ ]),
+ must_not: expect.arrayContaining([{ term: { file_type: DOCUMENT_FOLDER_TYPE } }]),
+ }),
+ },
+ }),
+ }),
+ );
+ });
+
+ it('searches knowledge bases and rechecks visibility and restricted IDs in PG', async () => {
+ await db.insert(knowledgeBases).values([
+ {
+ id: 'kb-public',
+ name: 'Public search phrase KB',
+ userId: otherUserId,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ id: 'kb-private-own',
+ name: 'Own private search phrase KB',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ },
+ {
+ id: 'kb-private-other',
+ name: 'Other private search phrase KB',
+ userId: otherUserId,
+ visibility: 'private',
+ workspaceId,
+ },
+ {
+ id: 'kb-restricted',
+ name: 'Restricted search phrase KB',
+ userId: otherUserId,
+ visibility: 'public',
+ workspaceId,
+ },
+ ]);
+ const client = createClient([
+ { _id: 'kb-private-other', _score: 12 },
+ { _id: 'kb-restricted', _score: 11 },
+ { _id: 'kb-public', _score: 10 },
+ { _id: 'kb-private-own', _score: 9 },
+ ]);
+ const backend = new ElasticsearchFtsSearchBackend(db, { client, indexNamespace });
+
+ const response = await backend.search(
+ request('knowledgeBases', {
+ filters: { excludeKnowledgeBaseIds: ['kb-restricted'] },
+ }),
+ );
+
+ expect(response.items).toEqual([
+ expect.objectContaining({ id: 'kb-public', type: 'knowledgeBase' }),
+ expect.objectContaining({ id: 'kb-private-own', type: 'knowledgeBase' }),
+ ]);
+ expect(client.search).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: expect.objectContaining({
+ query: {
+ bool: expect.objectContaining({
+ must_not: expect.arrayContaining([{ terms: { id: ['kb-restricted'] } }]),
+ }),
+ },
+ }),
+ entity: 'knowledgeBases',
+ index: 'lobehub-dev-knowledge-bases',
+ pagination: 'bounded',
+ }),
+ );
+ });
+
+ it('rejects memory-layer entities in hydrated product-result mode', async () => {
+ const backend = new ElasticsearchFtsSearchBackend(db, {
+ client: createClient([{ _id: 'context-1', _score: 1 }]),
+ indexNamespace,
+ });
+
+ await expect(backend.search(request('memoryContexts'))).rejects.toThrow(
+ 'Memory-layer entity only supports candidate search: memoryContexts',
+ );
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearch/boundary.test.ts b/packages/database/src/repositories/ftsSearch/boundary.test.ts
new file mode 100644
index 00000000000..ddc495678d3
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/boundary.test.ts
@@ -0,0 +1,221 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import type { LobeChatDatabase } from '../../type';
+import { FtsSearchRepo } from './index';
+import type {
+ FtsSearchBackend,
+ FtsSearchBackendMeasurement,
+ FtsSearchKnowledgeBaseDocumentHit,
+ FtsSearchMessageResult,
+} from './types';
+
+const db = {} as LobeChatDatabase;
+const now = new Date('2026-08-26T00:00:00.000Z');
+
+const messageResult: FtsSearchMessageResult = {
+ agentId: 'agent-1',
+ content: 'provider-neutral result',
+ createdAt: now,
+ description: 'Agent',
+ groupId: null,
+ id: 'message-1',
+ model: null,
+ relevance: 1,
+ role: 'user',
+ title: 'provider-neutral result',
+ topicId: 'topic-1',
+ type: 'message',
+ updatedAt: now,
+};
+
+describe('FtsSearchRepo backend boundary', () => {
+ it('forwards the supported request contract without exposing the legacy ignored offset', async () => {
+ const search = vi.fn<FtsSearchBackend['search']>().mockResolvedValue({
+ candidates: [{ id: messageResult.id, score: 7.25 }],
+ items: [messageResult],
+ });
+ const backend: FtsSearchBackend = { key: 'candidate', search };
+ const repo = new FtsSearchRepo(db, 'user-1', 'workspace-1', 'public', { backend });
+
+ await expect(
+ repo.search({
+ agentId: 'agent-1',
+ limitPerType: 7,
+ offset: 4,
+ query: ' search text ',
+ type: 'message',
+ }),
+ ).resolves.toEqual([messageResult]);
+
+ expect(search).toHaveBeenCalledWith({
+ entity: 'messages',
+ filters: { agentId: 'agent-1' },
+ pagination: { limit: 7 },
+ query: { text: 'search text' },
+ scope: {
+ callerAgentVisibility: 'public',
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ },
+ });
+ });
+
+ it('emits provider-native candidates through the shared measurement hook', async () => {
+ const measurements: FtsSearchBackendMeasurement[] = [];
+ const backend: FtsSearchBackend = {
+ key: 'candidate',
+ search: vi.fn().mockResolvedValue({
+ candidates: [
+ { id: messageResult.id, score: 9.75 },
+ { id: 'message-2', score: 8.5 },
+ ],
+ items: [messageResult],
+ }),
+ };
+ const repo = new FtsSearchRepo(db, 'user-1', undefined, undefined, {
+ backend,
+ onMeasurement: (measurement) => {
+ measurements.push(measurement);
+ },
+ });
+
+ await repo.search({ agentId: 'agent-1', query: 'message', type: 'message' });
+
+ expect(measurements).toHaveLength(1);
+ expect(measurements[0]).toMatchObject({
+ candidateCount: 2,
+ itemCount: 1,
+ provider: 'candidate',
+ request: {
+ entity: 'messages',
+ filterKeys: ['agentId'],
+ limit: 5,
+ queryLength: 7,
+ scope: 'personal',
+ },
+ status: 'success',
+ });
+ expect(measurements[0]).not.toHaveProperty('candidates');
+ expect(measurements[0]?.request).not.toHaveProperty('query');
+ expect(measurements[0]?.request).not.toHaveProperty('userId');
+ });
+
+ it('keeps measurement hook failures outside product behavior', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const backend: FtsSearchBackend = {
+ key: 'candidate',
+ search: vi.fn().mockResolvedValue({
+ candidates: [{ id: messageResult.id, score: 9.75 }],
+ items: [messageResult],
+ }),
+ };
+ const repo = new FtsSearchRepo(db, 'user-1', undefined, undefined, {
+ backend,
+ onMeasurement: () => {
+ throw new Error('measurement failed');
+ },
+ });
+
+ await expect(repo.search({ query: 'message', type: 'message' })).resolves.toEqual([
+ messageResult,
+ ]);
+ expect(consoleError).toHaveBeenCalledWith(
+ '[FtsSearchRepo] measurement hook failed',
+ expect.any(Error),
+ );
+ consoleError.mockRestore();
+ });
+
+ it('keeps asynchronous measurement rejections outside product behavior', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const measurementError = new Error('async measurement failed');
+ const backend: FtsSearchBackend = {
+ key: 'candidate',
+ search: vi.fn().mockResolvedValue({
+ candidates: [{ id: messageResult.id, score: 9.75 }],
+ items: [messageResult],
+ }),
+ };
+ const repo = new FtsSearchRepo(db, 'user-1', undefined, undefined, {
+ backend,
+ onMeasurement: async () => {
+ throw measurementError;
+ },
+ });
+
+ await expect(repo.search({ query: 'message', type: 'message' })).resolves.toEqual([
+ messageResult,
+ ]);
+ await vi.waitFor(() => {
+ expect(consoleError).toHaveBeenCalledWith(
+ '[FtsSearchRepo] measurement hook failed',
+ measurementError,
+ );
+ });
+ consoleError.mockRestore();
+ });
+
+ it('forwards KB scope and caller visibility through the same backend contract', async () => {
+ const document: FtsSearchKnowledgeBaseDocumentHit = {
+ documentId: 'document-1',
+ knowledgeBaseId: 'kb-1',
+ relevance: 1,
+ snippet: 'Matched content',
+ title: 'Matched document',
+ updatedAt: now,
+ };
+ const search = vi.fn<FtsSearchBackend['search']>().mockResolvedValue({
+ candidates: [{ id: document.documentId, score: 4.5 }],
+ items: [document],
+ });
+ const repo = new FtsSearchRepo(db, 'user-1', 'workspace-1', 'public', {
+ backend: { key: 'candidate', search },
+ });
+
+ await expect(repo.searchKnowledgeBaseDocuments(' knowledge ', ['kb-1'], 12)).resolves.toEqual(
+ [document],
+ );
+ expect(search).toHaveBeenCalledWith({
+ entity: 'documents',
+ filters: { documentKind: 'knowledgeBaseDocument', knowledgeBaseIds: ['kb-1'] },
+ pagination: { limit: 12 },
+ query: { text: 'knowledge' },
+ scope: {
+ callerAgentVisibility: 'public',
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ },
+ });
+ });
+
+ it('reports and rethrows the original provider error without fallback', async () => {
+ const providerError = new Error('provider failed');
+ const measurements: FtsSearchBackendMeasurement[] = [];
+ const search = vi.fn<FtsSearchBackend['search']>().mockRejectedValue(providerError);
+ const repo = new FtsSearchRepo(db, 'user-1', undefined, undefined, {
+ backend: { key: 'candidate', search },
+ onMeasurement: (measurement) => {
+ measurements.push(measurement);
+ },
+ });
+
+ await expect(
+ repo.search({ agentId: 'agent-1', query: 'message', type: 'message' }),
+ ).rejects.toBe(providerError);
+ expect(search).toHaveBeenCalledTimes(1);
+ expect(measurements).toHaveLength(1);
+ expect(measurements[0]).toMatchObject({
+ errorType: 'Error',
+ provider: 'candidate',
+ request: {
+ entity: 'messages',
+ filterKeys: ['agentId'],
+ limit: 5,
+ queryLength: 7,
+ scope: 'personal',
+ },
+ status: 'error',
+ });
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch.ts b/packages/database/src/repositories/ftsSearch/elasticsearch.ts
new file mode 100644
index 00000000000..42bfa16138e
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/elasticsearch.ts
@@ -0,0 +1,358 @@
+import type { LobeChatDatabase } from '../../type';
+import { searchElasticsearchCandidates } from './elasticsearch/candidates';
+import {
+ hydrateAgents,
+ hydrateChatGroups,
+ hydrateFiles,
+ hydrateFolders,
+ hydrateKnowledgeBaseDocuments,
+ hydrateKnowledgeBases,
+ hydrateMessages,
+ hydratePages,
+ hydrateTopics,
+ hydrateUserMemories,
+} from './elasticsearch/hydration';
+import type { ElasticsearchFtsSearchEntity } from './elasticsearch/query-fields';
+import {
+ isElasticsearchFtsSearchEntity,
+ isElasticsearchFtsSearchMemoryEntity,
+} from './elasticsearch/query-fields';
+import type {
+ ElasticsearchFtsSearchBackendOptions,
+ ElasticsearchFtsSearchCandidateTarget,
+ ElasticsearchFtsSearchClient,
+ ElasticsearchFtsSearchObserver,
+ ElasticsearchFtsSearchOperation,
+ ElasticsearchFtsSearchResult,
+ FtsSearchCandidateHit,
+} from './elasticsearch/types';
+import type {
+ FtsSearchBackend,
+ FtsSearchBackendRequest,
+ FtsSearchBackendResponse,
+ FtsSearchMessageResult,
+ FtsSearchTopicResult,
+} from './types';
+
+export type {
+ ElasticsearchFtsSearchConversationEntity,
+ ElasticsearchFtsSearchEntity,
+ ElasticsearchFtsSearchMemoryEntity,
+ ElasticsearchFtsSearchResourceEntity,
+} from './elasticsearch/query-fields';
+export {
+ ELASTICSEARCH_FTS_SEARCH_CONVERSATION_QUERY_FIELDS,
+ ELASTICSEARCH_FTS_SEARCH_MEMORY_QUERY_FIELDS,
+ ELASTICSEARCH_FTS_SEARCH_RESOURCE_QUERY_FIELDS,
+ isElasticsearchFtsSearchConversationEntity,
+ isElasticsearchFtsSearchEntity,
+ isElasticsearchFtsSearchMemoryEntity,
+ isElasticsearchFtsSearchResourceEntity,
+} from './elasticsearch/query-fields';
+export type {
+ ElasticsearchFtsSearchBackendOptions,
+ ElasticsearchFtsSearchClient,
+ ElasticsearchFtsSearchInput,
+ ElasticsearchFtsSearchObserver,
+ ElasticsearchFtsSearchOperation,
+ ElasticsearchFtsSearchResponse,
+} from './elasticsearch/types';
+
+/** Prevent parent authorization misses from turning one product search into an unbounded scan. */
+const MAX_PRODUCT_CANDIDATE_PAGES = 5;
+
+const normalizeQuery = (query: string) =>
+ query.trim().replaceAll('-', ' ').split(/\s+/).filter(Boolean).join(' ');
+
+/** Elasticsearch candidate provider. Product hits are always reloaded through current PostgreSQL scope. */
+export class ElasticsearchFtsSearchBackend implements FtsSearchBackend {
+ readonly key = 'elasticsearch';
+
+ private readonly client: ElasticsearchFtsSearchClient;
+ private readonly indexNamespace: string;
+ private readonly observer?: ElasticsearchFtsSearchObserver;
+
+ constructor(
+ private readonly db: LobeChatDatabase,
+ { client, indexNamespace, observer }: ElasticsearchFtsSearchBackendOptions,
+ ) {
+ const namespace = indexNamespace.trim();
+ if (!namespace) throw new Error('Elasticsearch search index namespace is required');
+
+ this.client = client;
+ this.indexNamespace = namespace;
+ this.observer = observer;
+ }
+
+ private observe<Result>(
+ entity: ElasticsearchFtsSearchEntity,
+ operation: ElasticsearchFtsSearchOperation,
+ callback: () => Promise<Result>,
+ ): Promise<Result> {
+ return this.observer?.observe(entity, operation, callback) ?? callback();
+ }
+
+ async search(
+ request: FtsSearchBackendRequest,
+ ): Promise<FtsSearchBackendResponse<ElasticsearchFtsSearchResult>> {
+ const entity = request.entity;
+ if (!isElasticsearchFtsSearchEntity(entity)) {
+ throw new Error(`Unsupported Elasticsearch search entity: ${request.entity}`);
+ }
+
+ const query = normalizeQuery(request.query.text);
+ if (!query) return { candidates: [], items: [], total: 0 };
+ let target: ElasticsearchFtsSearchCandidateTarget;
+ if (entity === 'documents') {
+ const documentKind = request.filters.documentKind;
+ if (!documentKind) {
+ throw new Error('Elasticsearch document search requires a supported document kind');
+ }
+ target = { documentKind, entity };
+ } else {
+ target = { entity };
+ }
+ if (
+ target.entity === 'documents' &&
+ target.documentKind === 'knowledgeBaseDocument' &&
+ !request.filters.knowledgeBaseIds?.length
+ ) {
+ return { candidates: [], items: [] };
+ }
+
+ if (
+ target.entity === 'messages' &&
+ request.mode !== 'candidates' &&
+ request.filters.topicScope
+ ) {
+ /** Only the candidate-only TopicModel flow rejoins parent topics before returning results. */
+ throw new Error(
+ 'Elasticsearch message topic scope requires candidate-only search and PostgreSQL parent filtering',
+ );
+ }
+
+ if (
+ request.mode !== 'candidates' &&
+ (target.entity === 'topics' || target.entity === 'messages')
+ ) {
+ return this.searchConversationProduct(request, target.entity, query);
+ }
+
+ const candidateResult = await this.observe(entity, 'candidate_query', () =>
+ searchElasticsearchCandidates(
+ { client: this.client, indexNamespace: this.indexNamespace },
+ request,
+ target,
+ query,
+ ),
+ );
+ const { hits } = candidateResult;
+ const candidates = hits.map(({ id, score }) => ({ id, score }));
+
+ if (request.mode === 'candidates') {
+ return { candidates, items: [], total: candidateResult.total };
+ }
+
+ const limit = request.pagination.limit;
+ if (!limit) throw new Error('Elasticsearch product search requires a positive limit');
+
+ if (entity === 'userMemories') {
+ return {
+ candidates,
+ items: await this.observe(entity, 'pg_hydration', () =>
+ hydrateUserMemories(this.db, hits, request.scope, limit),
+ ),
+ total: candidateResult.total,
+ };
+ }
+ if (isElasticsearchFtsSearchMemoryEntity(entity)) {
+ throw new Error(`Memory-layer entity only supports candidate search: ${entity}`);
+ }
+
+ if (request.entity === 'agents') {
+ return {
+ candidates,
+ items: await this.observe(entity, 'pg_hydration', () =>
+ hydrateAgents(this.db, hits, request.scope, limit),
+ ),
+ };
+ }
+ if (request.entity === 'chatGroups') {
+ return {
+ candidates,
+ items: await this.observe(entity, 'pg_hydration', () =>
+ hydrateChatGroups(this.db, hits, request.scope, limit),
+ ),
+ };
+ }
+ if (entity === 'files') {
+ return {
+ candidates,
+ items: await this.observe(entity, 'pg_hydration', () =>
+ hydrateFiles(
+ this.db,
+ hits,
+ request.scope,
+ limit,
+ request.filters.excludeKnowledgeBaseIds,
+ ),
+ ),
+ };
+ }
+ if (entity === 'knowledgeBases') {
+ return {
+ candidates,
+ items: await this.observe(entity, 'pg_hydration', () =>
+ hydrateKnowledgeBases(
+ this.db,
+ hits,
+ request.scope,
+ limit,
+ request.filters.excludeKnowledgeBaseIds,
+ ),
+ ),
+ };
+ }
+ if (target.entity !== 'documents') {
+ throw new Error(`Unsupported Elasticsearch search entity: ${target.entity}`);
+ }
+ if (target.documentKind === 'folder') {
+ return {
+ candidates,
+ items: await this.observe(entity, 'pg_hydration', () =>
+ hydrateFolders(
+ this.db,
+ hits,
+ request.scope,
+ limit,
+ request.filters.excludeKnowledgeBaseIds,
+ ),
+ ),
+ };
+ }
+ if (target.documentKind === 'page') {
+ return {
+ candidates,
+ items: await this.observe(entity, 'pg_hydration', () =>
+ hydratePages(
+ this.db,
+ hits,
+ request.scope,
+ limit,
+ request.filters.excludeKnowledgeBaseIds,
+ ),
+ ),
+ };
+ }
+ if (target.documentKind === 'knowledgeBaseDocument') {
+ return {
+ candidates,
+ items: await this.observe(entity, 'pg_hydration', () =>
+ hydrateKnowledgeBaseDocuments(
+ this.db,
+ hits,
+ request.scope,
+ limit,
+ request.filters.knowledgeBaseIds ?? [],
+ ),
+ ),
+ };
+ }
+
+ target.documentKind satisfies never;
+ throw new Error(`Unsupported Elasticsearch document kind: ${String(target.documentKind)}`);
+ }
+
+ /**
+ * Conversation parent permissions are intentionally authoritative in PostgreSQL and cannot be
+ * represented by the child search document. Continue after an authorization-heavy first page,
+ * but stop after a 20x candidate budget: partial results are safer than unbounded user latency.
+ */
+ private async searchConversationProduct(
+ request: FtsSearchBackendRequest,
+ entity: 'messages' | 'topics',
+ query: string,
+ ): Promise<FtsSearchBackendResponse<ElasticsearchFtsSearchResult>> {
+ const limit = request.pagination.limit;
+ if (!limit) throw new Error('Elasticsearch product search requires a positive limit');
+
+ const hits: FtsSearchCandidateHit[] = [];
+ const seen = new Set<string>();
+ const visibleItems = new Map<string, FtsSearchMessageResult | FtsSearchTopicResult>();
+ let pageCount = 0;
+ let searchAfter: unknown[] | undefined;
+
+ while (pageCount < MAX_PRODUCT_CANDIDATE_PAGES) {
+ const page = await this.observe(entity, 'candidate_query', () =>
+ searchElasticsearchCandidates(
+ { client: this.client, indexNamespace: this.indexNamespace },
+ request,
+ { entity },
+ query,
+ { searchAfter, singlePage: true },
+ ),
+ );
+ pageCount += 1;
+ const pageHits: FtsSearchCandidateHit[] = [];
+ for (const hit of page.hits) {
+ if (seen.has(hit.id)) continue;
+ seen.add(hit.id);
+ const candidate = { ...hit, rank: hits.length };
+ hits.push(candidate);
+ pageHits.push(candidate);
+ }
+
+ const pageItems =
+ entity === 'topics'
+ ? await this.observe(entity, 'pg_hydration', () =>
+ hydrateTopics(
+ this.db,
+ pageHits,
+ request.scope,
+ pageHits.length,
+ request.filters.agentId,
+ ),
+ )
+ : await this.observe(entity, 'pg_hydration', () =>
+ hydrateMessages(
+ this.db,
+ pageHits,
+ request.scope,
+ pageHits.length,
+ request.filters.agentId,
+ ),
+ );
+ for (const item of pageItems) visibleItems.set(item.id, item);
+ if (
+ visibleItems.size >= limit ||
+ page.exhausted ||
+ pageCount >= MAX_PRODUCT_CANDIDATE_PAGES
+ ) {
+ break;
+ }
+ if (!page.nextFtsSearchAfter) {
+ throw new Error('Elasticsearch bounded candidate search requires hit sort values');
+ }
+ searchAfter = page.nextFtsSearchAfter;
+ }
+
+ const hitById = new Map(hits.map((hit) => [hit.id, hit]));
+ const maxScore = Math.max(0, ...[...visibleItems].map(([id]) => hitById.get(id)?.score ?? 0));
+ const items = [...visibleItems.values()]
+ .map((item) => {
+ const score = hitById.get(item.id)?.score ?? 0;
+ return { ...item, relevance: maxScore > 0 ? 1 + 2 * (1 - score / maxScore) : 3 };
+ })
+ .sort((left, right) =>
+ entity === 'topics'
+ ? right.updatedAt.getTime() - left.updatedAt.getTime()
+ : right.createdAt.getTime() - left.createdAt.getTime(),
+ )
+ .slice(0, limit);
+
+ return {
+ candidates: hits.map(({ id, score }) => ({ id, score })),
+ items,
+ };
+ }
+}
diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/candidates.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/candidates.ts
new file mode 100644
index 00000000000..aeb591b6966
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/candidates.ts
@@ -0,0 +1,347 @@
+import { LIBRARY_HIDDEN_FILE_SOURCES } from '@lobechat/types';
+
+import { DOCUMENT_FOLDER_TYPE } from '../../../schemas';
+import { getFtsSearchIndexAlias } from '../../ftsSearchDocument';
+import type {
+ FtsSearchBackendFilters,
+ FtsSearchBackendRequest,
+ FtsSearchBackendScope,
+} from '../types';
+import {
+ ELASTICSEARCH_FTS_SEARCH_CONVERSATION_QUERY_FIELDS,
+ ELASTICSEARCH_FTS_SEARCH_DOCUMENT_QUERY_FIELDS,
+ ELASTICSEARCH_FTS_SEARCH_MEMORY_QUERY_FIELDS,
+ ELASTICSEARCH_FTS_SEARCH_RESOURCE_QUERY_FIELDS,
+ type ElasticsearchFtsSearchEntity,
+ isElasticsearchFtsSearchConversationEntity,
+ isElasticsearchFtsSearchMemoryEntity,
+} from './query-fields';
+import type {
+ ElasticsearchFtsSearchCandidateContext,
+ ElasticsearchFtsSearchCandidateOptions,
+ ElasticsearchFtsSearchCandidateResult,
+ ElasticsearchFtsSearchCandidateTarget,
+ FtsSearchCandidateHit,
+} from './types';
+
+/**
+ * Candidate over-fetch keeps authorized lower-ranked hits available when an index still contains
+ * a deleted or newly restricted document. PostgreSQL remains the final authorization source.
+ */
+const CANDIDATE_MULTIPLIER = 4;
+
+const UNBOUNDED_CANDIDATE_PAGE_SIZE = 1000;
+
+/**
+ * Rolling reindexes leave legacy documents without newly denormalized fields. Keep those documents
+ * eligible as candidates because PostgreSQL reapplies the exact filters during hydration.
+ */
+const exactOrLegacyMissingFilter = (
+ field: string,
+ exactClause: Record<string, unknown>,
+): Record<string, unknown> => ({
+ bool: {
+ minimum_should_match: 1,
+ should: [exactClause, { bool: { must_not: [{ exists: { field } }] } }],
+ },
+});
+
+const buildScopeClauses = (
+ entity: ElasticsearchFtsSearchEntity,
+ scope: FtsSearchBackendScope,
+): { filter: Array<Record<string, unknown>>; mustNot: Array<Record<string, unknown>> } => {
+ if (isElasticsearchFtsSearchMemoryEntity(entity)) {
+ return { filter: [{ term: { user_id: scope.userId } }], mustNot: [] };
+ }
+
+ if (!scope.workspaceId) {
+ return {
+ filter: [{ term: { user_id: scope.userId } }],
+ mustNot: [{ exists: { field: 'workspace_id' } }],
+ };
+ }
+
+ const filter: Array<Record<string, unknown>> = [{ term: { workspace_id: scope.workspaceId } }];
+ if (
+ entity === 'agents' ||
+ entity === 'chatGroups' ||
+ entity === 'documents' ||
+ entity === 'files' ||
+ entity === 'knowledgeBases'
+ ) {
+ filter.push(
+ scope.callerAgentVisibility === 'public'
+ ? {
+ bool: {
+ minimum_should_match: 1,
+ should: [
+ { bool: { must_not: [{ exists: { field: 'visibility' } }] } },
+ { term: { visibility: 'public' } },
+ ],
+ },
+ }
+ : {
+ bool: {
+ minimum_should_match: 1,
+ should: [
+ { bool: { must_not: [{ exists: { field: 'visibility' } }] } },
+ { term: { visibility: 'public' } },
+ { term: { user_id: scope.userId } },
+ ],
+ },
+ },
+ );
+ }
+
+ return { filter, mustNot: [] };
+};
+
+const appendMemoryFilters = (
+ entity: ElasticsearchFtsSearchEntity,
+ filters: FtsSearchBackendFilters,
+ clauses: Array<Record<string, unknown>>,
+) => {
+ if (!isElasticsearchFtsSearchMemoryEntity(entity)) return;
+
+ if (filters.memoryCategories?.length) {
+ const field = entity === 'userMemories' ? 'memory_category' : 'parent_memory_categories';
+ const exactClause = { terms: { [field]: filters.memoryCategories } };
+ clauses.push(
+ entity === 'userMemories' ? exactClause : exactOrLegacyMissingFilter(field, exactClause),
+ );
+ }
+ if (filters.memoryTypes?.length) {
+ clauses.push({ terms: { type: filters.memoryTypes } });
+ }
+ if (filters.memoryRelationships?.length) {
+ clauses.push({ terms: { relationship: filters.memoryRelationships } });
+ }
+ if (filters.memoryStatus?.length) {
+ const field = entity === 'memoryContexts' ? 'current_status.raw' : 'status';
+ /**
+ * Do not treat a missing exact-value subfield as a legacy document. Elasticsearch also omits
+ * keyword values above `ignore_above`, and accepting those would bypass the status filter.
+ */
+ clauses.push({ terms: { [field]: filters.memoryStatus } });
+ }
+ const tagClauses = (filters.memoryTags ?? []).map((tag) =>
+ entity === 'userMemories'
+ ? { term: { tags: tag } }
+ : {
+ bool: {
+ minimum_should_match: 1,
+ should: [
+ { term: { tags: tag } },
+ { term: { parent_tags: tag } },
+ { bool: { must_not: [{ exists: { field: 'parent_tags' } }] } },
+ ],
+ },
+ },
+ );
+ if (tagClauses.length > 0) {
+ if (filters.memoryTagMatch === 'any') {
+ clauses.push({ bool: { minimum_should_match: 1, should: tagClauses } });
+ } else {
+ clauses.push(...tagClauses);
+ }
+ }
+ if (filters.memoryTimeRange) {
+ const { end, field = 'capturedAt', start } = filters.memoryTimeRange;
+ const dateRange = {
+ ...(start ? { gte: start.toISOString() } : {}),
+ ...(end ? { lte: end.toISOString() } : {}),
+ };
+ if (Object.keys(dateRange).length > 0) {
+ const dateField = field.replaceAll(/[A-Z]/g, (character) => `_${character.toLowerCase()}`);
+ clauses.push({ range: { [dateField]: dateRange } });
+ }
+ }
+};
+
+/**
+ * Topics own their scope fields. Messages may carry the same fields for candidate pruning, but
+ * topic-bound messages are also valid with only topic_id, so missing fields must survive until
+ * PostgreSQL applies the authoritative parent-topic scope.
+ */
+const appendTopicScopeFilters = (
+ entity: ElasticsearchFtsSearchEntity,
+ filters: FtsSearchBackendFilters,
+ clauses: Array<Record<string, unknown>>,
+) => {
+ if (entity !== 'topics' && entity !== 'messages') return;
+
+ const scope = filters.topicScope;
+ if (!scope) return;
+ if (scope.groupId) {
+ const exactClause = { term: { group_id: scope.groupId } };
+ clauses.push(
+ entity === 'messages' ? exactOrLegacyMissingFilter('group_id', exactClause) : exactClause,
+ );
+ } else if (scope.agentId) {
+ const exactClause = { term: { agent_id: scope.agentId } };
+ clauses.push(
+ entity === 'messages' ? exactOrLegacyMissingFilter('agent_id', exactClause) : exactClause,
+ );
+ } else if (scope.containerId) {
+ const exactClauses = [
+ { term: { session_id: scope.containerId } },
+ { term: { group_id: scope.containerId } },
+ ];
+ clauses.push({
+ bool: {
+ minimum_should_match: 1,
+ should:
+ entity === 'messages'
+ ? [
+ ...exactClauses,
+ {
+ bool: {
+ must_not: [
+ { exists: { field: 'session_id' } },
+ { exists: { field: 'group_id' } },
+ ],
+ },
+ },
+ ]
+ : exactClauses,
+ },
+ });
+ }
+};
+
+export const searchElasticsearchCandidates = async (
+ { client, indexNamespace }: ElasticsearchFtsSearchCandidateContext,
+ request: FtsSearchBackendRequest,
+ target: ElasticsearchFtsSearchCandidateTarget,
+ query: string,
+ options: ElasticsearchFtsSearchCandidateOptions = {},
+): Promise<ElasticsearchFtsSearchCandidateResult> => {
+ const { entity } = target;
+ const { filter, mustNot } = buildScopeClauses(entity, request.scope);
+ mustNot.push({ term: { fts_search_sync_deleted: true } });
+ if (request.filters.agentId && (entity === 'topics' || entity === 'messages')) {
+ filter.push({ term: { agent_id: request.filters.agentId } });
+ }
+ if (entity === 'messages' && request.mode !== 'candidates') {
+ mustNot.push({ term: { role: 'tool' } });
+ }
+ if (request.filters.excludeVirtual && entity === 'agents') {
+ mustNot.push({ term: { virtual: true } });
+ }
+ if (entity === 'files') {
+ mustNot.push(
+ { term: { file_type: 'custom/document' } },
+ { terms: { source: LIBRARY_HIDDEN_FILE_SOURCES } },
+ );
+ if (request.filters.excludeKnowledgeBaseIds?.length) {
+ mustNot.push({ terms: { knowledge_base_ids: request.filters.excludeKnowledgeBaseIds } });
+ }
+ }
+ if (entity === 'knowledgeBases' && request.filters.excludeKnowledgeBaseIds?.length) {
+ mustNot.push({ terms: { id: request.filters.excludeKnowledgeBaseIds } });
+ }
+ if (target.entity === 'documents') {
+ const { documentKind } = target;
+ if (documentKind === 'folder') {
+ filter.push({ term: { file_type: DOCUMENT_FOLDER_TYPE } });
+ } else if (documentKind === 'page') {
+ filter.push({ term: { file_type: 'custom/document' } });
+ } else if (documentKind === 'knowledgeBaseDocument') {
+ filter.push({ terms: { knowledge_base_ids: request.filters.knowledgeBaseIds ?? [] } });
+ mustNot.push({ term: { file_type: DOCUMENT_FOLDER_TYPE } });
+ } else {
+ documentKind satisfies never;
+ throw new Error(`Unsupported Elasticsearch document kind: ${String(documentKind)}`);
+ }
+ if (
+ documentKind !== 'knowledgeBaseDocument' &&
+ request.filters.excludeKnowledgeBaseIds?.length
+ ) {
+ mustNot.push({ terms: { knowledge_base_ids: request.filters.excludeKnowledgeBaseIds } });
+ }
+ }
+
+ appendMemoryFilters(entity, request.filters, filter);
+ appendTopicScopeFilters(entity, request.filters, filter);
+
+ const fields =
+ request.query.fields ??
+ (target.entity === 'documents'
+ ? ELASTICSEARCH_FTS_SEARCH_DOCUMENT_QUERY_FIELDS[target.documentKind]
+ : isElasticsearchFtsSearchConversationEntity(target.entity)
+ ? ELASTICSEARCH_FTS_SEARCH_CONVERSATION_QUERY_FIELDS[target.entity]
+ : isElasticsearchFtsSearchMemoryEntity(target.entity)
+ ? ELASTICSEARCH_FTS_SEARCH_MEMORY_QUERY_FIELDS[target.entity]
+ : ELASTICSEARCH_FTS_SEARCH_RESOURCE_QUERY_FIELDS[target.entity]);
+ const requestedLimit = request.pagination.limit;
+ const size = requestedLimit
+ ? requestedLimit * CANDIDATE_MULTIPLIER
+ : UNBOUNDED_CANDIDATE_PAGE_SIZE;
+ const trackTotalHits = request.mode === 'candidates';
+ const seen = new Set<string>();
+ const hits: FtsSearchCandidateHit[] = [];
+ let exhausted = false;
+ let nextFtsSearchAfter: unknown[] | undefined;
+ let searchAfter = options.searchAfter;
+ let shouldContinue = true;
+ let total = 0;
+
+ /** Unbounded legacy APIs require exhaustive hydration; search_after avoids the result window. */
+ while (shouldContinue) {
+ const isFirstPage = searchAfter === undefined;
+ const response = await client.search({
+ body: {
+ _source: false,
+ query: {
+ bool: {
+ filter,
+ must: [
+ {
+ multi_match: {
+ fields,
+ operator: 'and',
+ query,
+ type: 'best_fields',
+ },
+ },
+ ],
+ must_not: mustNot,
+ },
+ },
+ ...(searchAfter ? { search_after: searchAfter } : {}),
+ size,
+ sort: [{ _score: 'desc' }, { id: 'asc' }],
+ ...(trackTotalHits && isFirstPage ? { track_total_hits: true } : {}),
+ },
+ entity,
+ index: getFtsSearchIndexAlias(indexNamespace, entity),
+ pagination: requestedLimit ? 'bounded' : 'unbounded',
+ });
+ if (isFirstPage) {
+ const responseTotal = response.hits.total;
+ total =
+ typeof responseTotal === 'number'
+ ? responseTotal
+ : (responseTotal?.value ?? hits.length + response.hits.hits.length);
+ }
+
+ for (const hit of response.hits.hits) {
+ if (!hit._id || seen.has(hit._id)) continue;
+ seen.add(hit._id);
+ hits.push({ id: hit._id, rank: hits.length, score: hit._score });
+ }
+
+ exhausted = response.hits.hits.length < size;
+ nextFtsSearchAfter = exhausted ? undefined : response.hits.hits.at(-1)?.sort;
+ if (options.singlePage || requestedLimit || exhausted) {
+ shouldContinue = false;
+ } else {
+ if (!nextFtsSearchAfter) {
+ throw new Error('Elasticsearch unbounded candidate search requires hit sort values');
+ }
+ searchAfter = nextFtsSearchAfter;
+ }
+ }
+
+ return { exhausted, hits, nextFtsSearchAfter, total: Math.max(total, hits.length) };
+};
diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts
new file mode 100644
index 00000000000..58465cbf17a
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts
@@ -0,0 +1,752 @@
+import { LIBRARY_HIDDEN_FILE_SOURCES } from '@lobechat/types';
+import {
+ and,
+ eq,
+ inArray,
+ isNotNull,
+ isNull,
+ ne,
+ notInArray,
+ or,
+ type SQL,
+ sql,
+} from 'drizzle-orm';
+import { alias } from 'drizzle-orm/pg-core';
+
+import {
+ agents,
+ chatGroups,
+ DOCUMENT_FOLDER_TYPE,
+ documents,
+ files,
+ knowledgeBaseFiles,
+ knowledgeBases,
+ messages,
+ sessions,
+ topics,
+ userMemories,
+} from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { normalizeInboxAgentMeta, normalizeInboxAgentTitle } from '../../../utils/inboxAgent';
+import { buildWorkspaceWhere } from '../../../utils/workspace';
+import type {
+ FtsSearchAgentResult,
+ FtsSearchBackendScope,
+ FtsSearchChatGroupResult,
+ FtsSearchFileResult,
+ FtsSearchFolderResult,
+ FtsSearchKnowledgeBaseDocumentHit,
+ FtsSearchKnowledgeBaseResult,
+ FtsSearchMemoryResult,
+ FtsSearchMessageResult,
+ FtsSearchPageResult,
+ FtsSearchTopicResult,
+} from '../types';
+import type { FtsSearchCandidateHit, FtsSearchHydratedScore } from './types';
+
+const DEFAULT_SNIPPET_MAX_LENGTH = 200;
+const FILE_DESCRIPTION_MAX_LENGTH = 200;
+const KNOWLEDGE_BASE_DOCUMENT_SNIPPET_MAX_LENGTH = 300;
+
+const truncate = (
+ content: string | null | undefined,
+ maxLength: number = DEFAULT_SNIPPET_MAX_LENGTH,
+) => {
+ if (!content) return null;
+ if (content.length <= maxLength) return content;
+ return `${content.slice(0, maxLength)}...`;
+};
+
+/** Select one extra character so truncation preserves exact ellipsis behavior without loading full content. */
+const documentContentPreview = (maxLength: number) =>
+ sql<string | null>`left(${documents.content}, ${maxLength + 1})`;
+
+const visibleParent = (
+ foreignKey: Parameters<typeof isNull>[0],
+ id: Parameters<typeof isNotNull>[0],
+) => or(isNull(foreignKey), isNotNull(id)) as SQL;
+
+const messageTopicAgents = alias(agents, 'search_message_topic_agents');
+const messageTopicChatGroups = alias(chatGroups, 'search_message_topic_chat_groups');
+const messageTopicSessions = alias(sessions, 'search_message_topic_sessions');
+
+const attachScores = <T extends { id: string }>(rows: T[], hits: FtsSearchCandidateHit[]) => {
+ const rowById = new Map(rows.map((row) => [row.id, row]));
+ const hydrated = hits.flatMap((hit) => {
+ const row = rowById.get(hit.id);
+ return row ? [{ ...row, rank: hit.rank, score: hit.score ?? 0 }] : [];
+ });
+ const maxScore = Math.max(0, ...hydrated.map(({ score }) => score));
+
+ return hydrated.map((row): T & FtsSearchCandidateHit & FtsSearchHydratedScore => ({
+ ...row,
+ relevance: maxScore > 0 ? 1 + 2 * (1 - row.score / maxScore) : 3,
+ }));
+};
+
+export const hydrateUserMemories = async (
+ db: LobeChatDatabase,
+ hits: FtsSearchCandidateHit[],
+ scope: FtsSearchBackendScope,
+ limit: number,
+): Promise<FtsSearchMemoryResult[]> => {
+ if (hits.length === 0) return [];
+
+ const rows = await db
+ .select({
+ createdAt: userMemories.createdAt,
+ id: userMemories.id,
+ memoryLayer: userMemories.memoryLayer,
+ summary: userMemories.summary,
+ title: userMemories.title,
+ updatedAt: userMemories.updatedAt,
+ })
+ .from(userMemories)
+ .where(
+ and(
+ inArray(
+ userMemories.id,
+ hits.map(({ id }) => id),
+ ),
+ eq(userMemories.userId, scope.userId),
+ ),
+ );
+
+ return attachScores(rows, hits)
+ .slice(0, limit)
+ .map((row) => ({
+ createdAt: row.createdAt,
+ description: truncate(row.summary),
+ id: row.id,
+ memoryLayer: row.memoryLayer,
+ relevance: row.relevance,
+ title: row.title || 'Untitled Memory',
+ type: 'memory' as const,
+ updatedAt: row.updatedAt,
+ }));
+};
+
+export const hydrateAgents = async (
+ db: LobeChatDatabase,
+ hits: FtsSearchCandidateHit[],
+ scope: FtsSearchBackendScope,
+ limit: number,
+): Promise<FtsSearchAgentResult[]> => {
+ if (hits.length === 0) return [];
+
+ const rows = await db
+ .select({
+ avatar: agents.avatar,
+ backgroundColor: agents.backgroundColor,
+ createdAt: agents.createdAt,
+ description: agents.description,
+ id: agents.id,
+ slug: agents.slug,
+ tags: agents.tags,
+ title: agents.title,
+ updatedAt: agents.updatedAt,
+ })
+ .from(agents)
+ .where(
+ and(
+ inArray(
+ agents.id,
+ hits.map(({ id }) => id),
+ ),
+ buildWorkspaceWhere(scope, agents),
+ ),
+ );
+
+ return attachScores(rows, hits)
+ .slice(0, limit)
+ .map((row) => {
+ const meta = normalizeInboxAgentMeta(
+ { avatar: row.avatar, title: row.title },
+ { slug: row.slug },
+ );
+
+ return {
+ avatar: meta.avatar,
+ backgroundColor: row.backgroundColor,
+ createdAt: row.createdAt,
+ description: row.description,
+ id: row.id,
+ relevance: row.relevance,
+ slug: row.slug,
+ tags: (row.tags as string[]) || [],
+ title: meta.title || '',
+ type: 'agent' as const,
+ updatedAt: row.updatedAt,
+ };
+ });
+};
+
+export const hydrateChatGroups = async (
+ db: LobeChatDatabase,
+ hits: FtsSearchCandidateHit[],
+ scope: FtsSearchBackendScope,
+ limit: number,
+): Promise<FtsSearchChatGroupResult[]> => {
+ if (hits.length === 0) return [];
+
+ const rows = await db
+ .select({
+ avatar: chatGroups.avatar,
+ backgroundColor: chatGroups.backgroundColor,
+ createdAt: chatGroups.createdAt,
+ description: chatGroups.description,
+ id: chatGroups.id,
+ title: chatGroups.title,
+ updatedAt: chatGroups.updatedAt,
+ })
+ .from(chatGroups)
+ .where(
+ and(
+ inArray(
+ chatGroups.id,
+ hits.map(({ id }) => id),
+ ),
+ buildWorkspaceWhere(scope, chatGroups),
+ ),
+ );
+
+ return attachScores(rows, hits)
+ .slice(0, limit)
+ .map((row) => ({
+ avatar: row.avatar,
+ backgroundColor: row.backgroundColor,
+ createdAt: row.createdAt,
+ description: row.description,
+ id: row.id,
+ relevance: row.relevance,
+ title: row.title || '',
+ type: 'chatGroup' as const,
+ updatedAt: row.updatedAt,
+ }));
+};
+
+export const hydrateTopics = async (
+ db: LobeChatDatabase,
+ hits: FtsSearchCandidateHit[],
+ scope: FtsSearchBackendScope,
+ limit: number,
+ agentId?: string,
+): Promise<FtsSearchTopicResult[]> => {
+ if (hits.length === 0) return [];
+
+ const rows = await db
+ .select({
+ agentAvatar: agents.avatar,
+ agentBackgroundColor: agents.backgroundColor,
+ agentId: topics.agentId,
+ agentMatchedId: agents.id,
+ agentSlug: agents.slug,
+ agentTitle: agents.title,
+ content: topics.content,
+ createdAt: topics.createdAt,
+ favorite: topics.favorite,
+ groupId: topics.groupId,
+ groupMatchedId: chatGroups.id,
+ id: topics.id,
+ sessionId: topics.sessionId,
+ sessionMatchedId: sessions.id,
+ title: topics.title,
+ updatedAt: topics.updatedAt,
+ })
+ .from(topics)
+ .leftJoin(agents, and(eq(topics.agentId, agents.id), buildWorkspaceWhere(scope, agents)))
+ .leftJoin(
+ chatGroups,
+ and(eq(topics.groupId, chatGroups.id), buildWorkspaceWhere(scope, chatGroups)),
+ )
+ .leftJoin(
+ sessions,
+ and(eq(topics.sessionId, sessions.id), buildWorkspaceWhere(scope, sessions)),
+ )
+ .where(
+ and(
+ inArray(
+ topics.id,
+ hits.map(({ id }) => id),
+ ),
+ buildWorkspaceWhere(scope, topics),
+ agentId ? eq(topics.agentId, agentId) : undefined,
+ visibleParent(topics.agentId, agents.id),
+ visibleParent(topics.groupId, chatGroups.id),
+ visibleParent(topics.sessionId, sessions.id),
+ ),
+ );
+
+ return attachScores(rows, hits)
+ .sort((left, right) => right.updatedAt.getTime() - left.updatedAt.getTime())
+ .slice(0, limit)
+ .map((row) => ({
+ agent: row.agentMatchedId
+ ? {
+ avatar: normalizeInboxAgentMeta(
+ { avatar: row.agentAvatar, title: row.agentTitle },
+ { slug: row.agentSlug },
+ ).avatar,
+ backgroundColor: row.agentBackgroundColor,
+ title: normalizeInboxAgentTitle(row.agentTitle, { slug: row.agentSlug }),
+ }
+ : null,
+ agentId: row.agentId,
+ createdAt: row.createdAt,
+ description: truncate(row.content),
+ favorite: row.favorite,
+ groupId: row.groupId,
+ id: row.id,
+ relevance: row.relevance,
+ sessionId: row.sessionId,
+ title: row.title || '',
+ type: 'topic' as const,
+ updatedAt: row.updatedAt,
+ }));
+};
+
+export const hydrateMessages = async (
+ db: LobeChatDatabase,
+ hits: FtsSearchCandidateHit[],
+ scope: FtsSearchBackendScope,
+ limit: number,
+ agentId?: string,
+): Promise<FtsSearchMessageResult[]> => {
+ if (hits.length === 0) return [];
+
+ const rows = await db
+ .select({
+ agentId: messages.agentId,
+ agentMatchedId: agents.id,
+ agentSlug: agents.slug,
+ agentTitle: agents.title,
+ content: messages.content,
+ createdAt: messages.createdAt,
+ groupId: messages.groupId,
+ groupMatchedId: chatGroups.id,
+ id: messages.id,
+ model: messages.model,
+ role: messages.role,
+ sessionId: messages.sessionId,
+ sessionMatchedId: sessions.id,
+ topicId: messages.topicId,
+ topicMatchedId: topics.id,
+ updatedAt: messages.updatedAt,
+ })
+ .from(messages)
+ .leftJoin(agents, and(eq(messages.agentId, agents.id), buildWorkspaceWhere(scope, agents)))
+ .leftJoin(
+ chatGroups,
+ and(eq(messages.groupId, chatGroups.id), buildWorkspaceWhere(scope, chatGroups)),
+ )
+ .leftJoin(
+ sessions,
+ and(eq(messages.sessionId, sessions.id), buildWorkspaceWhere(scope, sessions)),
+ )
+ .leftJoin(topics, and(eq(messages.topicId, topics.id), buildWorkspaceWhere(scope, topics)))
+ .leftJoin(
+ messageTopicAgents,
+ and(
+ eq(topics.agentId, messageTopicAgents.id),
+ buildWorkspaceWhere(scope, messageTopicAgents),
+ ),
+ )
+ .leftJoin(
+ messageTopicChatGroups,
+ and(
+ eq(topics.groupId, messageTopicChatGroups.id),
+ buildWorkspaceWhere(scope, messageTopicChatGroups),
+ ),
+ )
+ .leftJoin(
+ messageTopicSessions,
+ and(
+ eq(topics.sessionId, messageTopicSessions.id),
+ buildWorkspaceWhere(scope, messageTopicSessions),
+ ),
+ )
+ .where(
+ and(
+ inArray(
+ messages.id,
+ hits.map(({ id }) => id),
+ ),
+ buildWorkspaceWhere(scope, messages),
+ ne(messages.role, 'tool'),
+ agentId ? eq(messages.agentId, agentId) : undefined,
+ visibleParent(messages.agentId, agents.id),
+ visibleParent(messages.groupId, chatGroups.id),
+ visibleParent(messages.sessionId, sessions.id),
+ visibleParent(messages.topicId, topics.id),
+ /** A topic is itself a permission container; validate its parents even when the message omits direct foreign keys. */
+ visibleParent(topics.agentId, messageTopicAgents.id),
+ visibleParent(topics.groupId, messageTopicChatGroups.id),
+ visibleParent(topics.sessionId, messageTopicSessions.id),
+ ),
+ );
+
+ return attachScores(rows, hits)
+ .sort((left, right) => right.createdAt.getTime() - left.createdAt.getTime())
+ .slice(0, limit)
+ .map((row) => ({
+ agentId: row.agentId,
+ content: row.content || '',
+ createdAt: row.createdAt,
+ description:
+ normalizeInboxAgentTitle(row.agentTitle, { slug: row.agentSlug }) || 'General Chat',
+ groupId: row.groupId,
+ id: row.id,
+ model: row.model,
+ relevance: row.relevance,
+ role: row.role,
+ title: truncate(row.content) || '',
+ topicId: row.topicId,
+ type: 'message' as const,
+ updatedAt: row.updatedAt,
+ }));
+};
+
+/**
+ * Omitting scope is intentionally conservative for exclusion checks: any restricted membership
+ * hides the result. Authorization checks must pass scope so unrelated memberships cannot grant access.
+ */
+const getKnowledgeBaseIdsByFile = async (
+ db: LobeChatDatabase,
+ fileIds: string[],
+ scope?: FtsSearchBackendScope,
+): Promise<Map<string, string[]>> => {
+ if (fileIds.length === 0) return new Map();
+
+ const rows = await db
+ .select({
+ fileId: knowledgeBaseFiles.fileId,
+ knowledgeBaseId: knowledgeBaseFiles.knowledgeBaseId,
+ })
+ .from(knowledgeBaseFiles)
+ .where(
+ and(
+ inArray(knowledgeBaseFiles.fileId, fileIds),
+ scope ? buildWorkspaceWhere(scope, knowledgeBaseFiles) : undefined,
+ ),
+ );
+ const idsByFile = new Map<string, Set<string>>();
+ for (const { fileId, knowledgeBaseId } of rows) {
+ const ids = idsByFile.get(fileId) ?? new Set<string>();
+ ids.add(knowledgeBaseId);
+ idsByFile.set(fileId, ids);
+ }
+
+ return new Map(
+ [...idsByFile.entries()].map(([fileId, ids]) => [fileId, [...ids].sort()] as const),
+ );
+};
+
+export const hydrateFiles = async (
+ db: LobeChatDatabase,
+ hits: FtsSearchCandidateHit[],
+ scope: FtsSearchBackendScope,
+ limit: number,
+ excludeKnowledgeBaseIds: string[] = [],
+): Promise<FtsSearchFileResult[]> => {
+ if (hits.length === 0) return [];
+
+ const rows = await db
+ .select({
+ createdAt: files.createdAt,
+ fileType: files.fileType,
+ id: files.id,
+ name: files.name,
+ size: files.size,
+ updatedAt: files.updatedAt,
+ url: files.url,
+ })
+ .from(files)
+ .where(
+ and(
+ inArray(
+ files.id,
+ hits.map(({ id }) => id),
+ ),
+ buildWorkspaceWhere(scope, files),
+ ne(files.fileType, 'custom/document'),
+ or(isNull(files.source), notInArray(files.source, LIBRARY_HIDDEN_FILE_SOURCES)),
+ ),
+ );
+ const fileIds = rows.map(({ id }) => id);
+ const knowledgeBaseIdsByFile = await getKnowledgeBaseIdsByFile(db, fileIds);
+ const excluded = new Set(excludeKnowledgeBaseIds);
+ const authorizedRows = rows.filter(({ id }) =>
+ (knowledgeBaseIdsByFile.get(id) ?? []).every(
+ (knowledgeBaseId) => !excluded.has(knowledgeBaseId),
+ ),
+ );
+ const scoredRows = attachScores(authorizedRows, hits).slice(0, limit);
+ const selectedFileIds = scoredRows.map(({ id }) => id);
+ const documentRows =
+ selectedFileIds.length === 0
+ ? []
+ : await db
+ .select({
+ content: documentContentPreview(FILE_DESCRIPTION_MAX_LENGTH),
+ fileId: documents.fileId,
+ id: documents.id,
+ })
+ .from(documents)
+ .where(
+ and(inArray(documents.fileId, selectedFileIds), buildWorkspaceWhere(scope, documents)),
+ );
+ const contentByFile = new Map<string, string | null>();
+ for (const row of documentRows.toSorted((left, right) => left.id.localeCompare(right.id))) {
+ if (row.fileId && !contentByFile.has(row.fileId)) contentByFile.set(row.fileId, row.content);
+ }
+
+ return scoredRows.map((row) => ({
+ createdAt: row.createdAt,
+ description: truncate(contentByFile.get(row.id), FILE_DESCRIPTION_MAX_LENGTH),
+ fileType: row.fileType,
+ id: row.id,
+ knowledgeBaseId: knowledgeBaseIdsByFile.get(row.id)?.[0] ?? null,
+ name: row.name,
+ relevance: row.relevance,
+ size: row.size,
+ title: row.name,
+ type: 'file' as const,
+ updatedAt: row.updatedAt,
+ url: row.url,
+ }));
+};
+
+export const hydrateFolders = async (
+ db: LobeChatDatabase,
+ hits: FtsSearchCandidateHit[],
+ scope: FtsSearchBackendScope,
+ limit: number,
+ excludeKnowledgeBaseIds: string[] = [],
+): Promise<FtsSearchFolderResult[]> => {
+ if (hits.length === 0) return [];
+
+ const rows = await db
+ .select({
+ createdAt: documents.createdAt,
+ description: documents.description,
+ fileId: documents.fileId,
+ filename: documents.filename,
+ id: documents.id,
+ knowledgeBaseId: documents.knowledgeBaseId,
+ slug: documents.slug,
+ title: documents.title,
+ updatedAt: documents.updatedAt,
+ })
+ .from(documents)
+ .where(
+ and(
+ inArray(
+ documents.id,
+ hits.map(({ id }) => id),
+ ),
+ buildWorkspaceWhere(scope, documents),
+ eq(documents.fileType, DOCUMENT_FOLDER_TYPE),
+ ),
+ );
+ const knowledgeBaseIdsByFile = await getKnowledgeBaseIdsByFile(
+ db,
+ rows.flatMap(({ fileId }) => (fileId ? [fileId] : [])),
+ );
+ const excluded = new Set(excludeKnowledgeBaseIds);
+ const authorizedRows = rows.filter((row) => {
+ const knowledgeBaseIds = [
+ ...(row.knowledgeBaseId ? [row.knowledgeBaseId] : []),
+ ...(row.fileId ? (knowledgeBaseIdsByFile.get(row.fileId) ?? []) : []),
+ ];
+ return knowledgeBaseIds.every((knowledgeBaseId) => !excluded.has(knowledgeBaseId));
+ });
+
+ return attachScores(authorizedRows, hits)
+ .slice(0, limit)
+ .map((row) => ({
+ createdAt: row.createdAt,
+ description: row.description,
+ id: row.id,
+ knowledgeBaseId: row.knowledgeBaseId,
+ relevance: row.relevance,
+ slug: row.slug,
+ title: row.title || row.filename || 'Untitled',
+ type: 'folder' as const,
+ updatedAt: row.updatedAt,
+ }));
+};
+
+export const hydratePages = async (
+ db: LobeChatDatabase,
+ hits: FtsSearchCandidateHit[],
+ scope: FtsSearchBackendScope,
+ limit: number,
+ excludeKnowledgeBaseIds: string[] = [],
+): Promise<FtsSearchPageResult[]> => {
+ if (hits.length === 0) return [];
+
+ const rows = await db
+ .select({
+ createdAt: documents.createdAt,
+ fileId: documents.fileId,
+ filename: documents.filename,
+ id: documents.id,
+ knowledgeBaseId: documents.knowledgeBaseId,
+ title: documents.title,
+ updatedAt: documents.updatedAt,
+ })
+ .from(documents)
+ .where(
+ and(
+ inArray(
+ documents.id,
+ hits.map(({ id }) => id),
+ ),
+ buildWorkspaceWhere(scope, documents),
+ eq(documents.fileType, 'custom/document'),
+ ),
+ );
+ const knowledgeBaseIdsByFile = await getKnowledgeBaseIdsByFile(
+ db,
+ rows.flatMap(({ fileId }) => (fileId ? [fileId] : [])),
+ );
+ const excluded = new Set(excludeKnowledgeBaseIds);
+ const authorizedRows = rows.filter((row) => {
+ const knowledgeBaseIds = [
+ ...(row.knowledgeBaseId ? [row.knowledgeBaseId] : []),
+ ...(row.fileId ? (knowledgeBaseIdsByFile.get(row.fileId) ?? []) : []),
+ ];
+ return knowledgeBaseIds.every((knowledgeBaseId) => !excluded.has(knowledgeBaseId));
+ });
+
+ return attachScores(authorizedRows, hits)
+ .slice(0, limit)
+ .map((row) => ({
+ createdAt: row.createdAt,
+ description: null,
+ id: row.id,
+ relevance: row.relevance,
+ title: row.title || row.filename || 'Untitled',
+ type: 'page' as const,
+ updatedAt: row.updatedAt,
+ }));
+};
+
+export const hydrateKnowledgeBaseDocuments = async (
+ db: LobeChatDatabase,
+ hits: FtsSearchCandidateHit[],
+ scope: FtsSearchBackendScope,
+ limit: number,
+ knowledgeBaseIds: string[],
+): Promise<FtsSearchKnowledgeBaseDocumentHit[]> => {
+ if (hits.length === 0 || knowledgeBaseIds.length === 0) return [];
+
+ const rows = await db
+ .select({
+ fileId: documents.fileId,
+ filename: documents.filename,
+ id: documents.id,
+ knowledgeBaseId: documents.knowledgeBaseId,
+ title: documents.title,
+ updatedAt: documents.updatedAt,
+ })
+ .from(documents)
+ .where(
+ and(
+ inArray(
+ documents.id,
+ hits.map(({ id }) => id),
+ ),
+ buildWorkspaceWhere(scope, documents),
+ ne(documents.fileType, DOCUMENT_FOLDER_TYPE),
+ ),
+ );
+ const knowledgeBaseIdsByFile = await getKnowledgeBaseIdsByFile(
+ db,
+ rows.flatMap(({ fileId }) => (fileId ? [fileId] : [])),
+ scope,
+ );
+ const requested = new Set(knowledgeBaseIds);
+ const authorizedRows = rows.flatMap((row) => {
+ const matchingKnowledgeBaseId =
+ row.knowledgeBaseId && requested.has(row.knowledgeBaseId)
+ ? row.knowledgeBaseId
+ : row.fileId
+ ? knowledgeBaseIdsByFile
+ .get(row.fileId)
+ ?.find((knowledgeBaseId) => requested.has(knowledgeBaseId))
+ : undefined;
+ return matchingKnowledgeBaseId ? [{ ...row, matchingKnowledgeBaseId }] : [];
+ });
+ const scoredRows = attachScores(authorizedRows, hits).slice(0, limit);
+ const selectedDocumentIds = scoredRows.map(({ id }) => id);
+ const contentRows =
+ selectedDocumentIds.length === 0
+ ? []
+ : await db
+ .select({
+ content: documentContentPreview(KNOWLEDGE_BASE_DOCUMENT_SNIPPET_MAX_LENGTH),
+ id: documents.id,
+ })
+ .from(documents)
+ .where(
+ and(inArray(documents.id, selectedDocumentIds), buildWorkspaceWhere(scope, documents)),
+ );
+ const contentById = new Map(contentRows.map(({ content, id }) => [id, content] as const));
+
+ return scoredRows.map((row) => ({
+ documentId: row.id,
+ fileId: row.fileId ?? undefined,
+ knowledgeBaseId: row.matchingKnowledgeBaseId,
+ relevance: row.relevance,
+ snippet: truncate(contentById.get(row.id), KNOWLEDGE_BASE_DOCUMENT_SNIPPET_MAX_LENGTH) ?? '',
+ title: row.title || row.filename || 'Untitled',
+ updatedAt: row.updatedAt,
+ }));
+};
+
+export const hydrateKnowledgeBases = async (
+ db: LobeChatDatabase,
+ hits: FtsSearchCandidateHit[],
+ scope: FtsSearchBackendScope,
+ limit: number,
+ excludeKnowledgeBaseIds: string[] = [],
+): Promise<FtsSearchKnowledgeBaseResult[]> => {
+ if (hits.length === 0) return [];
+
+ const rows = await db
+ .select({
+ avatar: knowledgeBases.avatar,
+ createdAt: knowledgeBases.createdAt,
+ description: knowledgeBases.description,
+ id: knowledgeBases.id,
+ name: knowledgeBases.name,
+ updatedAt: knowledgeBases.updatedAt,
+ })
+ .from(knowledgeBases)
+ .where(
+ and(
+ inArray(
+ knowledgeBases.id,
+ hits.map(({ id }) => id),
+ ),
+ buildWorkspaceWhere(scope, knowledgeBases),
+ excludeKnowledgeBaseIds.length > 0
+ ? notInArray(knowledgeBases.id, excludeKnowledgeBaseIds)
+ : undefined,
+ ),
+ );
+
+ return attachScores(rows, hits)
+ .slice(0, limit)
+ .map((row) => ({
+ avatar: row.avatar,
+ createdAt: row.createdAt,
+ description: row.description,
+ id: row.id,
+ relevance: row.relevance,
+ title: row.name,
+ type: 'knowledgeBase' as const,
+ updatedAt: row.updatedAt,
+ }));
+};
diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/query-fields.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/query-fields.ts
new file mode 100644
index 00000000000..641067d0a31
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/query-fields.ts
@@ -0,0 +1,88 @@
+import type { FtsSearchMemoryDocumentEntity } from '../../ftsSearchDocument';
+import type { FtsSearchBackendEntity } from '../types';
+
+export const ELASTICSEARCH_FTS_SEARCH_CONVERSATION_QUERY_FIELDS = {
+ agents: ['title^5', 'slug^4', 'tags^3', 'description^2', 'system_role'],
+ chatGroups: ['title^4', 'description^2', 'content'],
+ messages: ['content^2', 'summary'],
+ topics: ['title', 'content', 'description'],
+} as const;
+
+export type ElasticsearchFtsSearchConversationEntity =
+ keyof typeof ELASTICSEARCH_FTS_SEARCH_CONVERSATION_QUERY_FIELDS;
+
+export const isElasticsearchFtsSearchConversationEntity = (
+ entity: FtsSearchBackendEntity,
+): entity is ElasticsearchFtsSearchConversationEntity =>
+ Object.hasOwn(ELASTICSEARCH_FTS_SEARCH_CONVERSATION_QUERY_FIELDS, entity);
+
+export const ELASTICSEARCH_FTS_SEARCH_RESOURCE_QUERY_FIELDS = {
+ files: ['name.raw^8', 'name^4', 'name.words^2'],
+ knowledgeBases: ['name^4', 'description'],
+} as const;
+
+export const ELASTICSEARCH_FTS_SEARCH_DOCUMENT_QUERY_FIELDS = {
+ folder: ['title^4', 'slug^3', 'description^2'],
+ knowledgeBaseDocument: ['title^4', 'slug^3', 'content'],
+ page: ['title^4', 'slug^3', 'content'],
+} as const;
+
+export type ElasticsearchFtsSearchResourceEntity =
+ keyof typeof ELASTICSEARCH_FTS_SEARCH_RESOURCE_QUERY_FIELDS | 'documents';
+
+export const isElasticsearchFtsSearchResourceEntity = (
+ entity: FtsSearchBackendEntity,
+): entity is ElasticsearchFtsSearchResourceEntity =>
+ entity === 'documents' || Object.hasOwn(ELASTICSEARCH_FTS_SEARCH_RESOURCE_QUERY_FIELDS, entity);
+
+export const ELASTICSEARCH_FTS_SEARCH_MEMORY_QUERY_FIELDS = {
+ memoryActivities: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'narrative',
+ 'notes',
+ 'feedback',
+ ],
+ memoryContexts: ['parent_text', 'title', 'description', 'current_status'],
+ memoryExperiences: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'situation',
+ 'reasoning',
+ 'possible_outcome',
+ 'action',
+ 'key_learning',
+ ],
+ memoryIdentities: ['parent_title', 'parent_summary', 'parent_details', 'description', 'role'],
+ memoryPreferences: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'conclusion_directives',
+ 'suggestions',
+ ],
+ personaDocuments: ['tagline', 'persona'],
+ userMemories: ['title^4', 'summary^2', 'details'],
+} as const satisfies Record<FtsSearchMemoryDocumentEntity, readonly string[]>;
+
+export type ElasticsearchFtsSearchMemoryEntity =
+ keyof typeof ELASTICSEARCH_FTS_SEARCH_MEMORY_QUERY_FIELDS;
+
+export const isElasticsearchFtsSearchMemoryEntity = (
+ entity: FtsSearchBackendEntity,
+): entity is ElasticsearchFtsSearchMemoryEntity =>
+ Object.hasOwn(ELASTICSEARCH_FTS_SEARCH_MEMORY_QUERY_FIELDS, entity);
+
+export type ElasticsearchFtsSearchEntity =
+ | ElasticsearchFtsSearchConversationEntity
+ | ElasticsearchFtsSearchMemoryEntity
+ | ElasticsearchFtsSearchResourceEntity;
+
+export const isElasticsearchFtsSearchEntity = (
+ entity: FtsSearchBackendEntity,
+): entity is ElasticsearchFtsSearchEntity =>
+ isElasticsearchFtsSearchConversationEntity(entity) ||
+ isElasticsearchFtsSearchMemoryEntity(entity) ||
+ isElasticsearchFtsSearchResourceEntity(entity);
diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/types.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/types.ts
new file mode 100644
index 00000000000..84b4d576f6d
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/types.ts
@@ -0,0 +1,101 @@
+import type {
+ FtsSearchAgentResult,
+ FtsSearchBackendCandidate,
+ FtsSearchBackendFilters,
+ FtsSearchChatGroupResult,
+ FtsSearchFileResult,
+ FtsSearchFolderResult,
+ FtsSearchKnowledgeBaseDocumentHit,
+ FtsSearchKnowledgeBaseResult,
+ FtsSearchMemoryResult,
+ FtsSearchMessageResult,
+ FtsSearchPageResult,
+ FtsSearchTopicResult,
+} from '../types';
+import type { ElasticsearchFtsSearchEntity } from './query-fields';
+
+export interface ElasticsearchFtsSearchInput {
+ body: Record<string, unknown>;
+ entity: ElasticsearchFtsSearchEntity;
+ index: string;
+ pagination: 'bounded' | 'unbounded';
+}
+
+export interface ElasticsearchFtsSearchResponse {
+ hits: {
+ hits: Array<{
+ _id: string;
+ _score: number | null;
+ sort?: unknown[];
+ }>;
+ total?: number | { value: number };
+ };
+ took?: number;
+}
+
+/** Minimal transport contract so deployments own credentials and HTTP/client policy. */
+export interface ElasticsearchFtsSearchClient {
+ search: (input: ElasticsearchFtsSearchInput) => Promise<ElasticsearchFtsSearchResponse>;
+}
+
+export type ElasticsearchFtsSearchOperation = 'candidate_query' | 'pg_hydration';
+
+/** Optional deployment-owned instrumentation that keeps the database package vendor-neutral. */
+export interface ElasticsearchFtsSearchObserver {
+ observe: <Result>(
+ entity: ElasticsearchFtsSearchEntity,
+ operation: ElasticsearchFtsSearchOperation,
+ callback: () => Promise<Result>,
+ ) => Promise<Result>;
+}
+
+export interface ElasticsearchFtsSearchBackendOptions {
+ client: ElasticsearchFtsSearchClient;
+ indexNamespace: string;
+ observer?: ElasticsearchFtsSearchObserver;
+}
+
+export interface FtsSearchCandidateHit extends FtsSearchBackendCandidate {
+ rank: number;
+}
+
+export interface ElasticsearchFtsSearchCandidateResult {
+ exhausted: boolean;
+ hits: FtsSearchCandidateHit[];
+ nextFtsSearchAfter?: unknown[];
+ total: number;
+}
+
+export interface ElasticsearchFtsSearchCandidateOptions {
+ searchAfter?: unknown[];
+ singlePage?: boolean;
+}
+
+export interface FtsSearchHydratedScore {
+ relevance: number;
+ score: number;
+}
+
+export type ElasticsearchFtsSearchResult =
+ | FtsSearchAgentResult
+ | FtsSearchChatGroupResult
+ | FtsSearchFileResult
+ | FtsSearchFolderResult
+ | FtsSearchKnowledgeBaseDocumentHit
+ | FtsSearchKnowledgeBaseResult
+ | FtsSearchMemoryResult
+ | FtsSearchMessageResult
+ | FtsSearchPageResult
+ | FtsSearchTopicResult;
+
+export type ElasticsearchFtsSearchDocumentKind = NonNullable<
+ FtsSearchBackendFilters['documentKind']
+>;
+export type ElasticsearchFtsSearchCandidateTarget =
+ | { documentKind: ElasticsearchFtsSearchDocumentKind; entity: 'documents' }
+ | { entity: Exclude<ElasticsearchFtsSearchEntity, 'documents'> };
+
+export interface ElasticsearchFtsSearchCandidateContext {
+ client: ElasticsearchFtsSearchClient;
+ indexNamespace: string;
+}
diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/url.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/url.ts
new file mode 100644
index 00000000000..f39223a96b6
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/url.ts
@@ -0,0 +1,25 @@
+/** Parses an Elasticsearch endpoint without allowing credentials to cross a plaintext network. */
+export const parseElasticsearchUrl = (value: string): URL => {
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ throw new Error('Elasticsearch URL must be a valid absolute URL');
+ }
+
+ if (url.username || url.password) {
+ throw new Error('Elasticsearch URL must not contain embedded credentials');
+ }
+
+ const isLoopback =
+ url.hostname === '127.0.0.1' ||
+ url.hostname === '[::1]' ||
+ url.hostname === 'localhost' ||
+ url.hostname.endsWith('.localhost');
+ /** Local development may use HTTP, but remote API keys must only cross an encrypted transport. */
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopback)) {
+ throw new Error('Elasticsearch URL must use HTTPS unless it targets loopback');
+ }
+
+ return url;
+};
diff --git a/packages/database/src/repositories/search/index.test.ts b/packages/database/src/repositories/ftsSearch/index.test.ts
similarity index 84%
rename from packages/database/src/repositories/search/index.test.ts
rename to packages/database/src/repositories/ftsSearch/index.test.ts
index 8783745c0cb..2d699979d1d 100644
--- a/packages/database/src/repositories/search/index.test.ts
+++ b/packages/database/src/repositories/ftsSearch/index.test.ts
@@ -2,7 +2,7 @@
import { eq } from 'drizzle-orm';
import { drizzle as nodeDrizzle } from 'drizzle-orm/node-postgres';
import { Pool as NodePool } from 'pg';
-import { afterAll, beforeEach, describe, expect, it } from 'vitest';
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
import * as schema from '../../schemas';
@@ -21,13 +21,13 @@ import type { NewTopic } from '../../schemas/topic';
import { topics } from '../../schemas/topic';
import { users } from '../../schemas/user';
import type { LobeChatDatabase } from '../../type';
-import type { SearchResult } from './index';
-import { SearchRepo } from './index';
+import type { FtsSearchResult } from './index';
+import { FtsSearchCandidateError, FtsSearchRepo } from './index';
const userId = 'search-test-user';
const otherUserId = 'other-search-user';
-let searchRepo: SearchRepo;
+let ftsSearchRepo: FtsSearchRepo;
const serverDB: LobeChatDatabase = await getTestDB();
@@ -39,7 +39,74 @@ beforeEach(async () => {
await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
// Initialize repo
- searchRepo = new SearchRepo(serverDB, userId);
+ ftsSearchRepo = new FtsSearchRepo(serverDB, userId);
+});
+
+describe('FtsSearchRepo candidate search', () => {
+ it('forwards candidate-only requests through the selected backend without product hydration', async () => {
+ const backendFtsSearch = vi.fn().mockResolvedValue({
+ candidates: [{ id: 'memory-context-1', score: 8 }],
+ items: [],
+ total: 1,
+ });
+ const repo = new FtsSearchRepo(serverDB, userId, undefined, undefined, {
+ backend: { key: 'candidate', search: backendFtsSearch },
+ ftsSearchCandidateEnabled: true,
+ });
+
+ await expect(
+ repo.ftsSearchCandidates({
+ entity: 'memoryContexts',
+ filters: {
+ memoryCategories: ['project'],
+ memoryTags: ['typescript'],
+ memoryTypes: ['workflow'],
+ },
+ pagination: { limit: 12 },
+ query: {
+ fields: ['parent_text', 'title', 'description', 'current_status'],
+ text: 'search phrase',
+ },
+ }),
+ ).resolves.toEqual({ candidates: [{ id: 'memory-context-1', score: 8 }], total: 1 });
+ expect(backendFtsSearch).toHaveBeenCalledWith({
+ entity: 'memoryContexts',
+ filters: {
+ memoryCategories: ['project'],
+ memoryTags: ['typescript'],
+ memoryTypes: ['workflow'],
+ },
+ mode: 'candidates',
+ pagination: { limit: 12 },
+ query: {
+ fields: ['parent_text', 'title', 'description', 'current_status'],
+ text: 'search phrase',
+ },
+ scope: { callerAgentVisibility: undefined, userId, workspaceId: undefined },
+ });
+ });
+
+ it('marks provider failures so API boundaries cannot mistake them for legacy fallbacks', async () => {
+ const providerError = new Error('Elasticsearch unavailable');
+ const repo = new FtsSearchRepo(serverDB, userId, undefined, undefined, {
+ backend: { key: 'candidate', search: vi.fn().mockRejectedValue(providerError) },
+ ftsSearchCandidateEnabled: true,
+ });
+
+ await expect(
+ repo.ftsSearchCandidates({
+ entity: 'memoryContexts',
+ filters: {},
+ pagination: { limit: 12 },
+ query: { text: 'search phrase' },
+ }),
+ ).rejects.toEqual(
+ expect.objectContaining({
+ cause: providerError,
+ name: FtsSearchCandidateError.name,
+ }),
+ );
+ });
});
// BM25 search requires pg_search extension (ParadeDB), not available in PGlite
@@ -73,15 +140,15 @@ const SCAN_ALIASES = [
'topic_hits',
];
-describe.skipIf(!isServerDB)('SearchRepo', () => {
+describe.skipIf(!isServerDB)('FtsSearchRepo', () => {
describe('search - empty query', () => {
it('should return empty array for empty query', async () => {
- const results = await searchRepo.search({ query: '' });
+ const results = await ftsSearchRepo.search({ query: '' });
expect(results).toEqual([]);
});
it('should return empty array for whitespace query', async () => {
- const results = await searchRepo.search({ query: ' ' });
+ const results = await ftsSearchRepo.search({ query: ' ' });
expect(results).toEqual([]);
});
});
@@ -143,7 +210,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should find agents by title', async () => {
- const results = await searchRepo.search({ query: 'React Helper' });
+ const results = await ftsSearchRepo.search({ query: 'React Helper' });
const agentResults = results.filter((r) => r.type === 'agent');
expect(agentResults).toHaveLength(1);
@@ -151,7 +218,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should find topics by title', async () => {
- const results = await searchRepo.search({ query: 'React Hooks' });
+ const results = await ftsSearchRepo.search({ query: 'React Hooks' });
const topicResults = results.filter((r) => r.type === 'topic');
expect(topicResults).toHaveLength(1);
@@ -161,7 +228,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
// Note: ICU tokenizer treats "react-component.jsx" as a single token,
// so we search by prefix "react" which matches via BM25
it('should find files by name', async () => {
- const results = await searchRepo.search({ query: 'react' });
+ const results = await ftsSearchRepo.search({ query: 'react' });
const fileResults = results.filter((r) => r.type === 'file');
expect(fileResults).toHaveLength(1);
@@ -169,7 +236,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should find results across all types', async () => {
- const results = await searchRepo.search({ query: 'react' });
+ const results = await ftsSearchRepo.search({ query: 'react' });
// Should find: 1 agent, 1 topic, 1 file
expect(results.length).toBeGreaterThanOrEqual(3);
@@ -181,7 +248,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should search in agent description', async () => {
- const results = await searchRepo.search({ query: 'coding assistant' });
+ const results = await ftsSearchRepo.search({ query: 'coding assistant' });
const agentResults = results.filter((r) => r.type === 'agent');
expect(agentResults.length).toBeGreaterThanOrEqual(1);
@@ -189,7 +256,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should search in topic content', async () => {
- const results = await searchRepo.search({ query: 'async programming' });
+ const results = await ftsSearchRepo.search({ query: 'async programming' });
const topicResults = results.filter((r) => r.type === 'topic');
expect(topicResults.length).toBeGreaterThanOrEqual(1);
@@ -197,7 +264,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should search in agent tags', async () => {
- const results = await searchRepo.search({ query: 'frontend' });
+ const results = await ftsSearchRepo.search({ query: 'frontend' });
const agentResults = results.filter((r) => r.type === 'agent');
expect(agentResults.length).toBeGreaterThanOrEqual(1);
@@ -228,7 +295,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should assign relevance values in valid range', async () => {
- const results = await searchRepo.search({ query: 'test' });
+ const results = await ftsSearchRepo.search({ query: 'test' });
const agentResults = results.filter((r) => r.type === 'agent');
expect(agentResults.length).toBe(3);
@@ -241,7 +308,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should rank results by BM25 relevance (lower = better)', async () => {
- const results = await searchRepo.search({ query: 'test' });
+ const results = await ftsSearchRepo.search({ query: 'test' });
const agentResults = results.filter((r) => r.type === 'agent');
expect(agentResults.length).toBe(3);
@@ -300,7 +367,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should only return current user results', async () => {
- const results = await searchRepo.search({ query: 'agent' });
+ const results = await ftsSearchRepo.search({ query: 'agent' });
expect(results.length).toBeGreaterThan(0);
@@ -311,21 +378,21 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should not return other user agents', async () => {
- const results = await searchRepo.search({ query: 'agent' });
+ const results = await ftsSearchRepo.search({ query: 'agent' });
const otherAgent = results.find((r) => r.title === 'Other Agent');
expect(otherAgent).toBeUndefined();
});
it('should not return other user topics', async () => {
- const results = await searchRepo.search({ query: 'topic' });
+ const results = await ftsSearchRepo.search({ query: 'topic' });
const otherTopic = results.find((r) => r.title === 'Other Topic');
expect(otherTopic).toBeUndefined();
});
it('should not return other user files', async () => {
- const results = await searchRepo.search({ query: 'file' });
+ const results = await ftsSearchRepo.search({ query: 'file' });
const otherFile = results.find((r) => r.title === 'other-file.txt');
expect(otherFile).toBeUndefined();
@@ -355,7 +422,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should filter by agent type', async () => {
- const results = await searchRepo.search({ query: 'test', type: 'agent' });
+ const results = await ftsSearchRepo.search({ query: 'test', type: 'agent' });
expect(results.length).toBeGreaterThan(0);
results.forEach((result) => {
@@ -364,7 +431,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should filter by topic type', async () => {
- const results = await searchRepo.search({ query: 'test', type: 'topic' });
+ const results = await ftsSearchRepo.search({ query: 'test', type: 'topic' });
expect(results.length).toBeGreaterThan(0);
results.forEach((result) => {
@@ -373,7 +440,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should filter by file type', async () => {
- const results = await searchRepo.search({ query: 'test', type: 'file' });
+ const results = await ftsSearchRepo.search({ query: 'test', type: 'file' });
expect(results.length).toBeGreaterThan(0);
results.forEach((result) => {
@@ -394,14 +461,14 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should respect default limit of 5 per type', async () => {
- const results = await searchRepo.search({ query: 'test' });
+ const results = await ftsSearchRepo.search({ query: 'test' });
const agentResults = results.filter((r) => r.type === 'agent');
expect(agentResults.length).toBeLessThanOrEqual(5);
});
it('should respect custom limit per type', async () => {
- const results = await searchRepo.search({ limitPerType: 3, query: 'test' });
+ const results = await ftsSearchRepo.search({ limitPerType: 3, query: 'test' });
const agentResults = results.filter((r) => r.type === 'agent');
expect(agentResults.length).toBeLessThanOrEqual(3);
@@ -419,9 +486,9 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should search case-insensitively', async () => {
- const upperResults = await searchRepo.search({ query: 'REACT' });
- const lowerResults = await searchRepo.search({ query: 'react' });
- const mixedResults = await searchRepo.search({ query: 'ReAcT' });
+ const upperResults = await ftsSearchRepo.search({ query: 'REACT' });
+ const lowerResults = await ftsSearchRepo.search({ query: 'react' });
+ const mixedResults = await ftsSearchRepo.search({ query: 'ReAcT' });
expect(upperResults.length).toBeGreaterThan(0);
expect(lowerResults.length).toBeGreaterThan(0);
@@ -462,7 +529,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should return correct agent result structure', async () => {
- const results = await searchRepo.search({ query: 'test', type: 'agent' });
+ const results = await ftsSearchRepo.search({ query: 'test', type: 'agent' });
expect(results.length).toBeGreaterThan(0);
const agent = results[0];
@@ -481,7 +548,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should return correct topic result structure', async () => {
- const results = await searchRepo.search({ query: 'test', type: 'topic' });
+ const results = await ftsSearchRepo.search({ query: 'test', type: 'topic' });
expect(results.length).toBeGreaterThan(0);
const topic = results[0];
@@ -499,7 +566,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should return correct file result structure', async () => {
- const results = await searchRepo.search({ query: 'test', type: 'file' });
+ const results = await ftsSearchRepo.search({ query: 'test', type: 'file' });
expect(results.length).toBeGreaterThan(0);
const file = results[0];
@@ -578,7 +645,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should only return topics of the current agent when agentId is provided', async () => {
- const results = await searchRepo.search({
+ const results = await ftsSearchRepo.search({
agentId: testAgentId,
query: 'testing',
});
@@ -594,7 +661,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should include topics from all agents when agentId is not provided', async () => {
- const results = await searchRepo.search({
+ const results = await ftsSearchRepo.search({
query: 'testing',
});
@@ -624,7 +691,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
userId,
});
- const results = await searchRepo.search({ query: 'decorated' });
+ const results = await ftsSearchRepo.search({ query: 'decorated' });
const topicResults = results.filter((r) => r.type === 'topic');
const decoratedTopic = topicResults.find(
(t) => t.type === 'topic' && t.agentId === decoratedAgent.id,
@@ -668,7 +735,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
userId,
});
- const results = await searchRepo.search({ query: 'cross-tenant' });
+ const results = await ftsSearchRepo.search({ query: 'cross-tenant' });
const topicResults = results.filter((r) => r.type === 'topic');
const probeTopic = topicResults.find(
(t) => t.type === 'topic' && t.title === 'Cross-tenant probe',
@@ -693,7 +760,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
})),
);
- const results = await searchRepo.search({
+ const results = await ftsSearchRepo.search({
agentId: testAgentId,
query: 'test',
});
@@ -723,7 +790,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
})),
);
- const results = await searchRepo.search({
+ const results = await ftsSearchRepo.search({
agentId: testAgentId,
query: 'test',
});
@@ -736,7 +803,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should use normal limits without agent context', async () => {
- const results = await searchRepo.search({
+ const results = await ftsSearchRepo.search({
query: 'testing',
});
@@ -747,7 +814,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should return topics with normal relevance range (1-3) when agentId is not provided', async () => {
- const results = await searchRepo.search({
+ const results = await ftsSearchRepo.search({
query: 'testing',
});
@@ -792,7 +859,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should find folders by title', async () => {
- const results = await searchRepo.search({ query: 'Project', type: 'folder' });
+ const results = await ftsSearchRepo.search({ query: 'Project', type: 'folder' });
expect(results.length).toBeGreaterThan(0);
results.forEach((result) => {
@@ -801,7 +868,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should find folders by description', async () => {
- const results = await searchRepo.search({ query: 'archive', type: 'folder' });
+ const results = await ftsSearchRepo.search({ query: 'archive', type: 'folder' });
expect(results.length).toBeGreaterThan(0);
const folder = results[0];
@@ -811,7 +878,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should return correct folder structure', async () => {
- const results = await searchRepo.search({ query: 'project', type: 'folder' });
+ const results = await ftsSearchRepo.search({ query: 'project', type: 'folder' });
expect(results.length).toBeGreaterThan(0);
const folder = results[0];
@@ -859,7 +926,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should find pages by title', async () => {
- const results = await searchRepo.search({ query: 'Notes', type: 'page' });
+ const results = await ftsSearchRepo.search({ query: 'Notes', type: 'page' });
expect(results.length).toBeGreaterThan(0);
results.forEach((result) => {
@@ -868,14 +935,14 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should find pages by filename', async () => {
- const results = await searchRepo.search({ query: 'readme', type: 'page' });
+ const results = await ftsSearchRepo.search({ query: 'readme', type: 'page' });
expect(results.length).toBeGreaterThan(0);
expect(results[0].type).toBe('page');
});
it('should return correct page structure', async () => {
- const results = await searchRepo.search({ query: 'notes', type: 'page' });
+ const results = await ftsSearchRepo.search({ query: 'notes', type: 'page' });
expect(results.length).toBeGreaterThan(0);
const page = results[0];
@@ -960,17 +1027,17 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should return [] for empty query', async () => {
- const results = await searchRepo.searchKnowledgeBaseDocuments('', [kbA]);
+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('', [kbA]);
expect(results).toEqual([]);
});
it('should return [] when no knowledgeBaseIds provided', async () => {
- const results = await searchRepo.searchKnowledgeBaseDocuments('machine learning', []);
+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', []);
expect(results).toEqual([]);
});
it('should match documents within KB scope by content', async () => {
- const results = await searchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
expect(results.length).toBeGreaterThan(0);
// Should hit ML overview, not cooking
expect(results.some((r) => r.title === 'Machine Learning Overview')).toBe(true);
@@ -978,28 +1045,76 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should respect KB scope (KB-A query does not return KB-B docs)', async () => {
- const results = await searchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
expect(results.every((r) => r.title !== 'Machine Learning in KB-B')).toBe(true);
});
it('should isolate across users', async () => {
// Searching with otherUserId's KB should not leak to current user
- const results = await searchRepo.searchKnowledgeBaseDocuments('machine learning', [
+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', [
'kb-other-1',
]);
// Current user (`userId`) does not own kb-other-1, so query against it returns []
expect(results).toEqual([]);
});
+ it('should hide caller-private workspace documents from a public agent', async () => {
+ const workspaceId = 'kb-search-workspace';
+ const privateKbId = 'kb-search-private';
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Search Workspace',
+ primaryOwnerId: userId,
+ slug: 'search-workspace',
+ });
+ await serverDB.insert(knowledgeBases).values({
+ id: privateKbId,
+ name: 'Private Knowledge Base',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ });
+ await serverDB.insert(documents).values({
+ content: 'Confidential launch details for the private workspace project.',
+ fileType: 'custom/document',
+ filename: 'private-launch.md',
+ knowledgeBaseId: privateKbId,
+ source: 'internal://document/private-launch',
+ sourceType: 'api',
+ title: 'Private Launch Plan',
+ totalCharCount: 62,
+ totalLineCount: 1,
+ userId,
+ visibility: 'private',
+ workspaceId,
+ });
+
+ const privateAgentResults = await new FtsSearchRepo(
+ serverDB,
+ userId,
+ workspaceId,
+ 'private',
+ ).searchKnowledgeBaseDocuments('confidential launch', [privateKbId]);
+ const publicAgentResults = await new FtsSearchRepo(
+ serverDB,
+ userId,
+ workspaceId,
+ 'public',
+ ).searchKnowledgeBaseDocuments('confidential launch', [privateKbId]);
+
+ expect(privateAgentResults).toHaveLength(1);
+ expect(publicAgentResults).toEqual([]);
+ });
+
it('should produce snippet ≤ 300 characters', async () => {
- const results = await searchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
results.forEach((r) => {
expect(r.snippet.length).toBeLessThanOrEqual(303); // 300 + '...' suffix
});
});
it('should produce relevance in [1, 3] range', async () => {
- const results = await searchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
results.forEach((r) => {
expect(r.relevance).toBeGreaterThanOrEqual(1);
expect(r.relevance).toBeLessThanOrEqual(3);
@@ -1085,7 +1200,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('returns a PDF-backed document hit via knowledge_base_files join', async () => {
- const results = await searchRepo.searchKnowledgeBaseDocuments('attention transformer', [
+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('attention transformer', [
kbA,
]);
const pdfHit = results.find((r) => r.documentId === pdfDocId);
@@ -1109,18 +1224,22 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
userId,
});
- const results = await searchRepo.searchKnowledgeBaseDocuments('attention', [kbA]);
+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('attention', [kbA]);
expect(results.some((r) => r.title === 'Inline Attention Notes')).toBe(true);
expect(results.some((r) => r.documentId === pdfDocId)).toBe(true);
});
it('excludes folder documents even when they match the query', async () => {
- const results = await searchRepo.searchKnowledgeBaseDocuments('transformer folder', [kbA]);
+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('transformer folder', [
+ kbA,
+ ]);
expect(results.every((r) => r.documentId !== folderDocId)).toBe(true);
});
it('does not surface another user PDF when querying their KB', async () => {
- const results = await searchRepo.searchKnowledgeBaseDocuments('attention', ['kb-other-1']);
+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('attention', [
+ 'kb-other-1',
+ ]);
expect(results).toEqual([]);
});
});
@@ -1179,7 +1298,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should expand pages to 6 in page context', async () => {
- const results = await searchRepo.search({
+ const results = await ftsSearchRepo.search({
contextType: 'page',
query: 'context test',
});
@@ -1189,7 +1308,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should limit other types to 3 in page context', async () => {
- const results = await searchRepo.search({
+ const results = await ftsSearchRepo.search({
contextType: 'page',
query: 'context test',
});
@@ -1206,7 +1325,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should expand files and folders to 6 in resource context', async () => {
- const results = await searchRepo.search({
+ const results = await ftsSearchRepo.search({
contextType: 'resource',
query: 'context-test',
});
@@ -1219,7 +1338,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should limit other types to 3 in resource context', async () => {
- const results = await searchRepo.search({
+ const results = await ftsSearchRepo.search({
contextType: 'resource',
query: 'context test',
});
@@ -1234,7 +1353,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should use agent context limits with contextType=agent', async () => {
- const results = await searchRepo.search({
+ const results = await ftsSearchRepo.search({
contextType: 'agent',
query: 'context test',
});
@@ -1275,7 +1394,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should find messages by content', async () => {
- const results = await searchRepo.search({ query: 'React hooks', type: 'message' });
+ const results = await ftsSearchRepo.search({ query: 'React hooks', type: 'message' });
expect(results.length).toBeGreaterThan(0);
results.forEach((result) => {
@@ -1284,7 +1403,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should filter out messages with role=tool', async () => {
- const results = await searchRepo.search({ query: 'tool', type: 'message' });
+ const results = await ftsSearchRepo.search({ query: 'tool', type: 'message' });
// Should not find any tool messages even though they contain "tool" in content
const toolMessages = results.filter((r) => r.type === 'message' && r.role === 'tool');
@@ -1292,7 +1411,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should return user and assistant messages but not tool messages', async () => {
- const results = await searchRepo.search({ query: 'hooks' });
+ const results = await ftsSearchRepo.search({ query: 'hooks' });
const messageResults = results.filter((r) => r.type === 'message');
@@ -1308,7 +1427,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should return correct message structure', async () => {
- const results = await searchRepo.search({ query: 'help', type: 'message' });
+ const results = await ftsSearchRepo.search({ query: 'help', type: 'message' });
expect(results.length).toBeGreaterThan(0);
const message = results[0];
@@ -1465,7 +1584,10 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
* which a differently-worded row could slip past. Case is normalised
* because the fixtures are not consistently cased.
*/
- const expectEveryHitScopedTo = (results: SearchResult[], scope: 'personal' | 'workspace') => {
+ const expectEveryHitScopedTo = (
+ results: FtsSearchResult[],
+ scope: 'personal' | 'workspace',
+ ) => {
expect(results.length).toBeGreaterThan(0);
const foreign = results.filter((r) => !r.title.toLowerCase().includes(scope));
@@ -1476,13 +1598,13 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
};
it('should never surface workspace-scoped rows in personal mode', async () => {
- const results = await new SearchRepo(serverDB, userId).search({ query: 'Kubernetes' });
+ const results = await new FtsSearchRepo(serverDB, userId).search({ query: 'Kubernetes' });
expectEveryHitScopedTo(results, 'personal');
});
it('should never surface personal rows in workspace mode', async () => {
- const results = await new SearchRepo(serverDB, userId, workspaceId).search({
+ const results = await new FtsSearchRepo(serverDB, userId, workspaceId).search({
query: 'Kubernetes',
});
@@ -1490,7 +1612,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('keeps agent-scoped search exact in workspace mode', async () => {
- const results = await new SearchRepo(serverDB, userId, workspaceId).search({
+ const results = await new FtsSearchRepo(serverDB, userId, workspaceId).search({
agentId: workspaceAgentId,
query: 'Kubernetes',
});
@@ -1503,7 +1625,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should keep joined agent metadata on topics and messages after the scan split', async () => {
- const results = await new SearchRepo(serverDB, userId).search({ query: 'Kubernetes' });
+ const results = await new FtsSearchRepo(serverDB, userId).search({ query: 'Kubernetes' });
const topic = results.find((r) => r.type === 'topic');
expect(topic).toBeDefined();
@@ -1535,7 +1657,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
.insert(knowledgeBaseFiles)
.values({ fileId: file.id, knowledgeBaseId: base.id, userId });
- const results = await new SearchRepo(serverDB, userId).search({
+ const results = await new FtsSearchRepo(serverDB, userId).search({
query: 'kubernetes',
type: 'file',
});
@@ -1579,7 +1701,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should only surface the requested agent rows in topics and messages', async () => {
- const results = await searchRepo.search({ agentId: agentAId, query: 'Terraform' });
+ const results = await ftsSearchRepo.search({ agentId: agentAId, query: 'Terraform' });
const scoped = results.filter((r) => r.type === 'topic' || r.type === 'message');
expect(scoped.length).toBeGreaterThan(0);
@@ -1592,11 +1714,11 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
it('should not leak rows between two agent-scoped searches', async () => {
const [forA, forB] = await Promise.all([
- searchRepo.search({ agentId: agentAId, query: 'Terraform' }),
- searchRepo.search({ agentId: agentBId, query: 'Terraform' }),
+ ftsSearchRepo.search({ agentId: agentAId, query: 'Terraform' }),
+ ftsSearchRepo.search({ agentId: agentBId, query: 'Terraform' }),
]);
- const idsOf = (results: SearchResult[]) =>
+ const idsOf = (results: FtsSearchResult[]) =>
results.filter((r) => r.type === 'topic' || r.type === 'message').map((r) => r.id);
expect(idsOf(forA)).toHaveLength(2);
@@ -1605,7 +1727,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should keep agent-less rows reachable without an agent filter', async () => {
- const results = await searchRepo.search({ query: 'Terraform' });
+ const results = await ftsSearchRepo.search({ query: 'Terraform' });
const scoped = results.filter((r) => r.type === 'topic' || r.type === 'message');
const agentIds = new Set(
@@ -1615,7 +1737,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('should keep joined agent metadata after the agent filter moved above the scan', async () => {
- const results = await searchRepo.search({ agentId: agentAId, query: 'Terraform' });
+ const results = await ftsSearchRepo.search({ agentId: agentAId, query: 'Terraform' });
const topic = results.find((r) => r.type === 'topic');
expect(topic).toBeDefined();
@@ -1664,7 +1786,11 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
schema,
});
- await new SearchRepo(db as unknown as LobeChatDatabase, userId, options?.workspaceId).search({
+ await new FtsSearchRepo(
+ db as unknown as LobeChatDatabase,
+ userId,
+ options?.workspaceId,
+ ).search({
agentId: options?.agentId,
query: 'kubernetes',
});
diff --git a/packages/database/src/repositories/ftsSearch/index.ts b/packages/database/src/repositories/ftsSearch/index.ts
new file mode 100644
index 00000000000..8acc0b32a44
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/index.ts
@@ -0,0 +1,334 @@
+import type { LobeChatDatabase } from '../../type';
+import { PgSearchFtsSearchBackend } from './pgSearch';
+import type {
+ FtsSearchBackendFilters,
+ FtsSearchBackendMeasurement,
+ FtsSearchBackendRequest,
+ FtsSearchBackendResponse,
+ FtsSearchBackendScope,
+ FtsSearchCandidateRequest,
+ FtsSearchCandidateResult,
+ FtsSearchDatabaseResult,
+ FtsSearchKnowledgeBaseDocumentHit,
+ FtsSearchOptions,
+ FtsSearchRepoOptions,
+ FtsSearchResult,
+ FtsSearchResultType,
+} from './types';
+
+export * from './elasticsearch';
+export { PgSearchFtsSearchBackend } from './pgSearch';
+export * from './types';
+
+interface FtsSearchLimits {
+ agent: number;
+ chatGroup: number;
+ file: number;
+ folder: number;
+ knowledgeBase: number;
+ memory: number;
+ message: number;
+ page: number;
+ pageContent: number;
+ topic: number;
+}
+
+/** Identifies candidate-provider failures that must stay visible to API callers. */
+export class FtsSearchCandidateError extends Error {
+ constructor(cause: unknown) {
+ super('Candidate search provider failed', { cause });
+ this.name = 'FtsSearchCandidateError';
+ }
+}
+
+/**
+ * Provider-neutral search facade. Backends own candidate retrieval and final
+ * PostgreSQL hydration, while this class preserves the public repository API.
+ */
+export class FtsSearchRepo {
+ readonly ftsSearchCandidateEnabled: boolean;
+
+ private backend: NonNullable<FtsSearchRepoOptions['backend']>;
+ private onMeasurement?: FtsSearchRepoOptions['onMeasurement'];
+ private scope: FtsSearchBackendScope;
+
+ constructor(
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+ callerAgentVisibility?: 'private' | 'public' | null,
+ options: FtsSearchRepoOptions = {},
+ ) {
+ this.scope = { callerAgentVisibility, userId, workspaceId };
+ this.backend = options.backend ?? new PgSearchFtsSearchBackend(db, this.scope);
+ this.ftsSearchCandidateEnabled = options.ftsSearchCandidateEnabled ?? false;
+ this.onMeasurement = options.onMeasurement;
+ }
+
+ private createRequest(
+ entity: FtsSearchBackendRequest['entity'],
+ query: string,
+ limit: number,
+ filters: FtsSearchBackendFilters = {},
+ ): FtsSearchBackendRequest {
+ return {
+ entity,
+ filters,
+ pagination: { limit },
+ query: { text: query },
+ scope: this.scope,
+ };
+ }
+
+ private createMeasurementRequest(
+ request: FtsSearchBackendRequest,
+ ): FtsSearchBackendMeasurement['request'] {
+ return {
+ entity: request.entity,
+ filterKeys: Object.entries(request.filters)
+ .filter(([, value]) => value !== undefined && (!Array.isArray(value) || value.length > 0))
+ .map(([key]) => key)
+ .sort() as (keyof FtsSearchBackendFilters)[],
+ limit: request.pagination.limit ?? 0,
+ queryLength: request.query.text.length,
+ scope: request.scope.workspaceId ? 'workspace' : 'personal',
+ };
+ }
+
+ private async execute(request: FtsSearchBackendRequest): Promise<FtsSearchBackendResponse> {
+ const startedAt = Date.now();
+
+ try {
+ const response = await this.backend.search(request);
+ this.recordMeasurement({
+ candidateCount: response.candidates.length,
+ durationMs: Date.now() - startedAt,
+ itemCount: response.items.length,
+ provider: this.backend.key,
+ request: this.createMeasurementRequest(request),
+ status: 'success',
+ });
+ return response;
+ } catch (error) {
+ this.recordMeasurement({
+ durationMs: Date.now() - startedAt,
+ errorType: error instanceof Error ? error.name : typeof error,
+ provider: this.backend.key,
+ request: this.createMeasurementRequest(request),
+ status: 'error',
+ });
+ throw error;
+ }
+ }
+
+ /** Measurement failures must never change the selected provider's result or error. */
+ private recordMeasurement(measurement: FtsSearchBackendMeasurement) {
+ try {
+ const hookResult = this.onMeasurement?.(measurement);
+ if (hookResult) {
+ void hookResult.catch((error) => {
+ console.error('[FtsSearchRepo] measurement hook failed', error);
+ });
+ }
+ } catch (error) {
+ console.error('[FtsSearchRepo] measurement hook failed', error);
+ }
+ }
+
+ /** Full-text search across the database-backed product result types. */
+ async search(options: FtsSearchOptions): Promise<FtsSearchResult[]> {
+ const { query, type, limitPerType = 5, agentId, contextType } = options;
+ if (!query || query.trim() === '') return [];
+
+ const trimmedQuery = query.trim();
+ const limits = this.calculateLimits(limitPerType, type, agentId, contextType);
+ const excludeKnowledgeBaseIds = options.excludeKnowledgeBaseIds ?? [];
+ const searches: Promise<FtsSearchBackendResponse>[] = [];
+
+ if ((!type || type === 'agent') && limits.agent > 0) {
+ searches.push(this.execute(this.createRequest('agents', trimmedQuery, limits.agent)));
+ }
+ if ((!type || type === 'chatGroup') && limits.chatGroup > 0) {
+ searches.push(this.execute(this.createRequest('chatGroups', trimmedQuery, limits.chatGroup)));
+ }
+ if ((!type || type === 'topic') && limits.topic > 0) {
+ searches.push(
+ this.execute(this.createRequest('topics', trimmedQuery, limits.topic, { agentId })),
+ );
+ }
+ if ((!type || type === 'message') && limits.message > 0) {
+ searches.push(
+ this.execute(this.createRequest('messages', trimmedQuery, limits.message, { agentId })),
+ );
+ }
+ if ((!type || type === 'file') && limits.file > 0) {
+ searches.push(
+ this.execute(
+ this.createRequest('files', trimmedQuery, limits.file, { excludeKnowledgeBaseIds }),
+ ),
+ );
+ }
+ if ((!type || type === 'folder') && limits.folder > 0) {
+ searches.push(
+ this.execute(
+ this.createRequest('documents', trimmedQuery, limits.folder, {
+ documentKind: 'folder',
+ excludeKnowledgeBaseIds,
+ }),
+ ),
+ );
+ }
+ if ((!type || type === 'page') && limits.page > 0) {
+ searches.push(
+ this.execute(
+ this.createRequest('documents', trimmedQuery, limits.page, {
+ documentKind: 'page',
+ excludeKnowledgeBaseIds,
+ }),
+ ),
+ );
+ }
+ if ((!type || type === 'memory') && limits.memory > 0) {
+ searches.push(this.execute(this.createRequest('userMemories', trimmedQuery, limits.memory)));
+ }
+ if ((!type || type === 'knowledgeBase') && limits.knowledgeBase > 0) {
+ searches.push(
+ this.execute(
+ this.createRequest('knowledgeBases', trimmedQuery, limits.knowledgeBase, {
+ excludeKnowledgeBaseIds,
+ }),
+ ),
+ );
+ }
+
+ const responses = await Promise.all(searches);
+
+ /** Each backend item already carries the existing hydrated response schema and display order. */
+ return responses.flatMap((response) => response.items as FtsSearchDatabaseResult[]);
+ }
+
+ /** Candidate-only retrieval for legacy and hybrid paths that own their PostgreSQL hydration. */
+ async ftsSearchCandidates(request: FtsSearchCandidateRequest): Promise<FtsSearchCandidateResult> {
+ if (!this.ftsSearchCandidateEnabled) {
+ throw new Error('Candidate-only search is not enabled for this repository');
+ }
+
+ const query = request.query.text.trim();
+ if (!query) return { candidates: [], total: 0 };
+
+ let response: FtsSearchBackendResponse;
+ try {
+ response = await this.execute({
+ ...request,
+ mode: 'candidates',
+ query: { ...request.query, text: query },
+ scope: this.scope,
+ });
+ } catch (error) {
+ throw new FtsSearchCandidateError(error);
+ }
+
+ return {
+ candidates: response.candidates,
+ total: response.total ?? response.candidates.length,
+ };
+ }
+
+ async searchKnowledgeBaseDocuments(
+ query: string,
+ knowledgeBaseIds: string[],
+ limit: number = 20,
+ ): Promise<FtsSearchKnowledgeBaseDocumentHit[]> {
+ if (!query || query.trim() === '') return [];
+ if (!knowledgeBaseIds || knowledgeBaseIds.length === 0) return [];
+
+ const response = await this.execute(
+ this.createRequest('documents', query.trim(), limit, {
+ documentKind: 'knowledgeBaseDocument',
+ knowledgeBaseIds,
+ }),
+ );
+
+ return response.items as FtsSearchKnowledgeBaseDocumentHit[];
+ }
+
+ private calculateLimits(
+ baseLimit: number,
+ type?: FtsSearchResultType,
+ agentId?: string,
+ contextType?: 'agent' | 'resource' | 'page',
+ ): FtsSearchLimits {
+ if (type) {
+ return {
+ agent: type === 'agent' ? baseLimit : 0,
+ chatGroup: type === 'chatGroup' ? baseLimit : 0,
+ file: type === 'file' ? baseLimit : 0,
+ folder: type === 'folder' ? baseLimit : 0,
+ knowledgeBase: type === 'knowledgeBase' ? baseLimit : 0,
+ memory: type === 'memory' ? baseLimit : 0,
+ message: type === 'message' ? baseLimit : 0,
+ page: type === 'page' ? baseLimit : 0,
+ pageContent: type === 'pageContent' ? baseLimit : 0,
+ topic: type === 'topic' ? baseLimit : 0,
+ };
+ }
+
+ if (contextType === 'page') {
+ return {
+ agent: 3,
+ chatGroup: 3,
+ file: 3,
+ folder: 3,
+ knowledgeBase: 3,
+ memory: 3,
+ message: 3,
+ page: 6,
+ pageContent: 0,
+ topic: 3,
+ };
+ }
+
+ if (contextType === 'resource') {
+ return {
+ agent: 3,
+ chatGroup: 3,
+ file: 6,
+ folder: 6,
+ knowledgeBase: 6,
+ memory: 3,
+ message: 3,
+ page: 3,
+ pageContent: 0,
+ topic: 3,
+ };
+ }
+
+ if (agentId || contextType === 'agent') {
+ return {
+ agent: 3,
+ chatGroup: 3,
+ file: 3,
+ folder: 3,
+ knowledgeBase: 3,
+ memory: 3,
+ message: 6,
+ page: 3,
+ pageContent: 0,
+ topic: 6,
+ };
+ }
+
+ return {
+ agent: 3,
+ chatGroup: 3,
+ file: 3,
+ folder: 3,
+ knowledgeBase: 3,
+ memory: 3,
+ message: 3,
+ page: 3,
+ pageContent: 0,
+ topic: 3,
+ };
+ }
+}
diff --git a/packages/database/src/repositories/ftsSearch/pgSearch.ts b/packages/database/src/repositories/ftsSearch/pgSearch.ts
new file mode 100644
index 00000000000..60ce13a643a
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/pgSearch.ts
@@ -0,0 +1,70 @@
+import type { LobeChatDatabase } from '../../type';
+import {
+ searchAgents,
+ searchChatGroups,
+ searchFiles,
+ searchKnowledgeBases,
+ searchMessages,
+ searchTopics,
+} from './pgSearch/command-menu';
+import { searchFolders, searchKnowledgeBaseDocuments, searchPages } from './pgSearch/documents';
+import { searchMemories } from './pgSearch/memories';
+import type { PgSearchFtsSearchContext } from './pgSearch/scope';
+import { createPgSearchFtsSearchContext } from './pgSearch/scope';
+import type {
+ FtsSearchBackend,
+ FtsSearchBackendRequest,
+ FtsSearchBackendResponse,
+ FtsSearchBackendScope,
+} from './types';
+
+/** pg_search adapter that preserves the existing query and hydration shape. */
+export class PgSearchFtsSearchBackend implements FtsSearchBackend {
+ readonly key = 'pg_search';
+
+ private readonly context: PgSearchFtsSearchContext;
+
+ constructor(db: LobeChatDatabase, scope: FtsSearchBackendScope) {
+ this.context = createPgSearchFtsSearchContext(db, scope);
+ }
+
+ async search(request: FtsSearchBackendRequest): Promise<FtsSearchBackendResponse> {
+ const query = request.query.text.trim();
+ if (!query) return { candidates: [], items: [] };
+
+ const { entity, filters, pagination } = request;
+ const limit = pagination.limit;
+ if (!limit) throw new Error('pg_search product search requires a positive limit');
+
+ if (entity === 'agents') return searchAgents(this.context, query, limit);
+ if (entity === 'chatGroups') return searchChatGroups(this.context, query, limit);
+ if (entity === 'topics') return searchTopics(this.context, query, limit, filters.agentId);
+ if (entity === 'messages') return searchMessages(this.context, query, limit, filters.agentId);
+ if (entity === 'files') {
+ return searchFiles(this.context, query, limit, filters.excludeKnowledgeBaseIds);
+ }
+ if (entity === 'knowledgeBases') {
+ return searchKnowledgeBases(this.context, query, limit, filters.excludeKnowledgeBaseIds);
+ }
+ if (entity === 'userMemories') return searchMemories(this.context, query, limit);
+
+ if (entity === 'documents') {
+ if (filters.documentKind === 'folder') {
+ return searchFolders(this.context, query, limit, filters.excludeKnowledgeBaseIds);
+ }
+ if (filters.documentKind === 'page') {
+ return searchPages(this.context, query, limit, filters.excludeKnowledgeBaseIds);
+ }
+ if (filters.documentKind === 'knowledgeBaseDocument') {
+ return searchKnowledgeBaseDocuments(
+ this.context,
+ query,
+ filters.knowledgeBaseIds ?? [],
+ limit,
+ );
+ }
+ }
+
+ throw new Error(`Unsupported pg_search entity: ${entity}`);
+ }
+}
diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/command-menu.ts b/packages/database/src/repositories/ftsSearch/pgSearch/command-menu.ts
new file mode 100644
index 00000000000..652b5d2aa04
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/pgSearch/command-menu.ts
@@ -0,0 +1,523 @@
+import { LIBRARY_HIDDEN_FILE_SOURCES } from '@lobechat/types';
+import { and, desc, eq, inArray, isNull, ne, notInArray, or, sql } from 'drizzle-orm';
+
+import {
+ agents,
+ chatGroups,
+ documents,
+ files,
+ knowledgeBaseFiles,
+ knowledgeBases,
+ messages,
+ topics,
+} from '../../../schemas';
+import { sanitizeBm25Query } from '../../../utils/bm25';
+import { normalizeInboxAgentMeta, normalizeInboxAgentTitle } from '../../../utils/inboxAgent';
+import { buildWorkspaceWhere } from '../../../utils/workspace';
+import type {
+ FtsSearchAgentResult,
+ FtsSearchBackendResponse,
+ FtsSearchChatGroupResult,
+ FtsSearchFileResult,
+ FtsSearchKnowledgeBaseResult,
+ FtsSearchMessageResult,
+ FtsSearchTopicResult,
+} from '../types';
+import { buildResponse, buildSelectedResponse, mapScoresToRelevance, truncate } from './results';
+import type { PgSearchFtsSearchContext } from './scope';
+import { AGENT_SCOPE_CANDIDATE_POOL } from './scope';
+
+/** Topics and messages are displayed by recency after a larger BM25 candidate pool is fetched. */
+const RECENCY_CANDIDATE_MULTIPLIER = 4;
+
+/** Search agents by title, description, slug, tags, and system role. */
+export async function searchAgents(
+ context: PgSearchFtsSearchContext,
+ query: string,
+ limit: number,
+): Promise<FtsSearchBackendResponse<FtsSearchAgentResult>> {
+ const bm25Query = sanitizeBm25Query(query);
+ const { db } = context;
+
+ const hits = db
+ .select({
+ avatar: agents.avatar,
+ backgroundColor: agents.backgroundColor,
+ createdAt: agents.createdAt,
+ description: agents.description,
+ id: agents.id,
+ name: agents.name,
+ score: sql<number>`paradedb.score(${agents.id})`.as('score'),
+ slug: agents.slug,
+ tags: agents.tags,
+ title: agents.title,
+ updatedAt: agents.updatedAt,
+ workspaceId: agents.workspaceId,
+ })
+ .from(agents)
+ .where(
+ and(
+ context.scanScopeWhere(agents),
+ sql`(${agents.title} @@@ ${bm25Query} OR ${agents.description} @@@ ${bm25Query} OR ${agents.slug} @@@ ${bm25Query} OR ${agents.tags} @@@ ${bm25Query} OR ${agents.systemRole} @@@ ${bm25Query})`,
+ ),
+ )
+ .orderBy(sql`paradedb.score(${agents.id}) DESC`)
+ .limit(context.scanCandidateLimit(limit))
+ .as('agent_hits');
+
+ const rows = await db
+ .select({
+ avatar: hits.avatar,
+ backgroundColor: hits.backgroundColor,
+ createdAt: hits.createdAt,
+ description: hits.description,
+ id: hits.id,
+ score: hits.score,
+ slug: hits.slug,
+ tags: hits.tags,
+ title: hits.title,
+ updatedAt: hits.updatedAt,
+ })
+ .from(hits)
+ .where(context.liftedScopeWhere(hits.workspaceId))
+ .orderBy(desc(hits.score))
+ .limit(limit);
+
+ return buildResponse(rows, (row) => {
+ const meta = normalizeInboxAgentMeta(
+ { avatar: row.avatar, title: row.title },
+ { slug: row.slug },
+ );
+
+ return {
+ avatar: meta.avatar,
+ backgroundColor: row.backgroundColor,
+ createdAt: row.createdAt,
+ description: row.description,
+ id: row.id,
+ relevance: row.relevance,
+ slug: row.slug,
+ tags: (row.tags as string[]) || [],
+ title: meta.title || '',
+ type: 'agent' as const,
+ updatedAt: row.updatedAt,
+ };
+ });
+}
+
+/** Search topics by title, content, and description. */
+export async function searchTopics(
+ context: PgSearchFtsSearchContext,
+ query: string,
+ limit: number,
+ agentId?: string,
+): Promise<FtsSearchBackendResponse<FtsSearchTopicResult>> {
+ const bm25Query = sanitizeBm25Query(query);
+ const candidateLimit = limit * RECENCY_CANDIDATE_MULTIPLIER;
+ const { db } = context;
+
+ const hits = db
+ .select({
+ agentId: topics.agentId,
+ content: topics.content,
+ createdAt: topics.createdAt,
+ favorite: topics.favorite,
+ groupId: topics.groupId,
+ id: topics.id,
+ score: sql<number>`paradedb.score(${topics.id})`.as('score'),
+ sessionId: topics.sessionId,
+ title: topics.title,
+ updatedAt: topics.updatedAt,
+ workspaceId: topics.workspaceId,
+ })
+ .from(topics)
+ .where(
+ and(
+ context.scanScopeWhere(topics),
+ agentId && !context.liftsAgentFilter ? eq(topics.agentId, agentId) : undefined,
+ sql`(${topics.title} @@@ ${bm25Query} OR ${topics.content} @@@ ${bm25Query} OR ${topics.description} @@@ ${bm25Query})`,
+ ),
+ )
+ .orderBy(sql`paradedb.score(${topics.id}) DESC`)
+ // `agent_id` is not a BM25 field, so when score ordering is valid its
+ // filter lives above the scan and the pool deepens to compensate.
+ .limit(
+ agentId && context.liftsAgentFilter
+ ? AGENT_SCOPE_CANDIDATE_POOL
+ : context.scanCandidateLimit(candidateLimit),
+ )
+ .as('topic_hits');
+
+ const rows = await db
+ .select({
+ // A matching agent row is a visibility sentinel. Foreign agent metadata
+ // must never leak into the topic result.
+ agentAvatar: agents.avatar,
+ agentBackgroundColor: agents.backgroundColor,
+ agentId: hits.agentId,
+ agentMatchedId: agents.id,
+ agentName: agents.name,
+ agentSlug: agents.slug,
+ agentTitle: agents.title,
+ content: hits.content,
+ createdAt: hits.createdAt,
+ favorite: hits.favorite,
+ groupId: hits.groupId,
+ id: hits.id,
+ score: hits.score,
+ sessionId: hits.sessionId,
+ title: hits.title,
+ updatedAt: hits.updatedAt,
+ })
+ .from(hits)
+ .leftJoin(agents, and(eq(hits.agentId, agents.id), buildWorkspaceWhere(context.scope, agents)))
+ .where(
+ and(
+ context.liftedScopeWhere(hits.workspaceId),
+ agentId ? eq(hits.agentId, agentId) : undefined,
+ ),
+ )
+ .orderBy(desc(hits.score))
+ .limit(candidateLimit);
+
+ const scoredRows = mapScoresToRelevance(rows);
+ const sortedRows = [...scoredRows]
+ .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())
+ .slice(0, limit);
+
+ return buildSelectedResponse(scoredRows, sortedRows, (row) => ({
+ agent: row.agentMatchedId
+ ? {
+ avatar: normalizeInboxAgentMeta(
+ { avatar: row.agentAvatar, title: row.agentTitle },
+ { slug: row.agentSlug },
+ ).avatar,
+ backgroundColor: row.agentBackgroundColor,
+ title: normalizeInboxAgentTitle(row.agentTitle, {
+ slug: row.agentSlug,
+ }),
+ }
+ : null,
+ agentId: row.agentId,
+ createdAt: row.createdAt,
+ description: truncate(row.content),
+ favorite: row.favorite,
+ groupId: row.groupId,
+ id: row.id,
+ relevance: row.relevance,
+ sessionId: row.sessionId,
+ title: row.title || '',
+ type: 'topic' as const,
+ updatedAt: row.updatedAt,
+ }));
+}
+
+/** Search messages by content. */
+export async function searchMessages(
+ context: PgSearchFtsSearchContext,
+ query: string,
+ limit: number,
+ agentId?: string,
+): Promise<FtsSearchBackendResponse<FtsSearchMessageResult>> {
+ const bm25Query = sanitizeBm25Query(query);
+ const candidateLimit = limit * RECENCY_CANDIDATE_MULTIPLIER;
+ const { db } = context;
+
+ const hits = db
+ .select({
+ agentId: messages.agentId,
+ content: messages.content,
+ createdAt: messages.createdAt,
+ groupId: messages.groupId,
+ id: messages.id,
+ model: messages.model,
+ role: messages.role,
+ score: sql<number>`paradedb.score(${messages.id})`.as('score'),
+ topicId: messages.topicId,
+ updatedAt: messages.updatedAt,
+ workspaceId: messages.workspaceId,
+ })
+ .from(messages)
+ .where(
+ and(
+ context.scanScopeWhere(messages),
+ ne(messages.role, 'tool'),
+ agentId && !context.liftsAgentFilter ? eq(messages.agentId, agentId) : undefined,
+ sql`${messages.content} @@@ ${bm25Query}`,
+ ),
+ )
+ .orderBy(sql`paradedb.score(${messages.id}) DESC`)
+ // `agent_id` is not a BM25 field, so when score ordering is valid its
+ // filter lives above the scan and the pool deepens to compensate.
+ .limit(
+ agentId && context.liftsAgentFilter
+ ? AGENT_SCOPE_CANDIDATE_POOL
+ : context.scanCandidateLimit(candidateLimit),
+ )
+ .as('message_hits');
+
+ const rows = await db
+ .select({
+ agentId: hits.agentId,
+ agentName: agents.name,
+ agentSlug: agents.slug,
+ agentTitle: agents.title,
+ content: hits.content,
+ createdAt: hits.createdAt,
+ groupId: hits.groupId,
+ id: hits.id,
+ model: hits.model,
+ role: hits.role,
+ score: hits.score,
+ topicId: hits.topicId,
+ updatedAt: hits.updatedAt,
+ })
+ .from(hits)
+ .leftJoin(agents, eq(hits.agentId, agents.id))
+ .where(
+ and(
+ context.liftedScopeWhere(hits.workspaceId),
+ agentId ? eq(hits.agentId, agentId) : undefined,
+ ),
+ )
+ .orderBy(desc(hits.score))
+ .limit(candidateLimit);
+
+ const scoredRows = mapScoresToRelevance(rows);
+ const sortedRows = [...scoredRows]
+ .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
+ .slice(0, limit);
+
+ return buildSelectedResponse(scoredRows, sortedRows, (row) => ({
+ agentId: row.agentId,
+ content: row.content || '',
+ createdAt: row.createdAt,
+ description:
+ normalizeInboxAgentTitle(row.agentTitle, {
+ slug: row.agentSlug,
+ }) || 'General Chat',
+ groupId: row.groupId,
+ id: row.id,
+ model: row.model,
+ relevance: row.relevance,
+ role: row.role,
+ title: truncate(row.content) || '',
+ topicId: row.topicId,
+ type: 'message' as const,
+ updatedAt: row.updatedAt,
+ }));
+}
+
+/** Search files by name. */
+export async function searchFiles(
+ context: PgSearchFtsSearchContext,
+ query: string,
+ limit: number,
+ excludeKbIds?: string[],
+): Promise<FtsSearchBackendResponse<FtsSearchFileResult>> {
+ const bm25Query = sanitizeBm25Query(query);
+ const { db } = context;
+
+ const hits = db
+ .select({
+ createdAt: files.createdAt,
+ fileType: files.fileType,
+ id: files.id,
+ name: files.name,
+ score: sql<number>`paradedb.score(${files.id})`.as('score'),
+ size: files.size,
+ updatedAt: files.updatedAt,
+ url: files.url,
+ workspaceId: files.workspaceId,
+ })
+ .from(files)
+ .where(
+ and(
+ context.scanScopeWhere(files),
+ ne(files.fileType, 'custom/document'),
+ // Hidden acceptance evidence must stay out of library search too.
+ or(isNull(files.source), notInArray(files.source, LIBRARY_HIDDEN_FILE_SOURCES)),
+ sql`${files.name} @@@ ${bm25Query}`,
+ ),
+ )
+ .orderBy(sql`paradedb.score(${files.id}) DESC`)
+ .limit(context.scanCandidateLimit(limit))
+ .as('file_hits');
+
+ const rows = await db
+ .select({
+ content: documents.content,
+ createdAt: hits.createdAt,
+ fileType: hits.fileType,
+ id: hits.id,
+ knowledgeBaseId: knowledgeBaseFiles.knowledgeBaseId,
+ name: hits.name,
+ score: hits.score,
+ size: hits.size,
+ updatedAt: hits.updatedAt,
+ url: hits.url,
+ })
+ .from(hits)
+ .leftJoin(documents, eq(hits.id, documents.fileId))
+ .leftJoin(knowledgeBaseFiles, eq(hits.id, knowledgeBaseFiles.fileId))
+ .where(
+ and(
+ context.liftedScopeWhere(hits.workspaceId),
+ // A file linked to any restricted KB is fully hidden. The subquery
+ // avoids leaking it through a different joined membership row.
+ excludeKbIds && excludeKbIds.length > 0
+ ? notInArray(
+ hits.id,
+ db
+ .select({ fileId: knowledgeBaseFiles.fileId })
+ .from(knowledgeBaseFiles)
+ .where(inArray(knowledgeBaseFiles.knowledgeBaseId, excludeKbIds)),
+ )
+ : undefined,
+ ),
+ )
+ .orderBy(desc(hits.score))
+ .limit(limit);
+
+ return buildResponse(rows, (row) => ({
+ createdAt: row.createdAt,
+ description: truncate(row.content),
+ fileType: row.fileType,
+ id: row.id,
+ knowledgeBaseId: row.knowledgeBaseId,
+ name: row.name,
+ relevance: row.relevance,
+ size: row.size,
+ title: row.name,
+ type: 'file' as const,
+ updatedAt: row.updatedAt,
+ url: row.url,
+ }));
+}
+
+/** Search chat groups by title and description. */
+export async function searchChatGroups(
+ context: PgSearchFtsSearchContext,
+ query: string,
+ limit: number,
+): Promise<FtsSearchBackendResponse<FtsSearchChatGroupResult>> {
+ const bm25Query = sanitizeBm25Query(query);
+ const { db } = context;
+
+ const hits = db
+ .select({
+ avatar: chatGroups.avatar,
+ backgroundColor: chatGroups.backgroundColor,
+ createdAt: chatGroups.createdAt,
+ description: chatGroups.description,
+ id: chatGroups.id,
+ score: sql<number>`paradedb.score(${chatGroups.id})`.as('score'),
+ title: chatGroups.title,
+ updatedAt: chatGroups.updatedAt,
+ workspaceId: chatGroups.workspaceId,
+ })
+ .from(chatGroups)
+ .where(
+ and(
+ context.scanScopeWhere(chatGroups),
+ sql`(${chatGroups.title} @@@ ${bm25Query} OR ${chatGroups.description} @@@ ${bm25Query})`,
+ ),
+ )
+ .orderBy(sql`paradedb.score(${chatGroups.id}) DESC`)
+ .limit(context.scanCandidateLimit(limit))
+ .as('chat_group_hits');
+
+ const rows = await db
+ .select({
+ avatar: hits.avatar,
+ backgroundColor: hits.backgroundColor,
+ createdAt: hits.createdAt,
+ description: hits.description,
+ id: hits.id,
+ score: hits.score,
+ title: hits.title,
+ updatedAt: hits.updatedAt,
+ })
+ .from(hits)
+ .where(context.liftedScopeWhere(hits.workspaceId))
+ .orderBy(desc(hits.score))
+ .limit(limit);
+
+ return buildResponse(rows, (row) => ({
+ avatar: row.avatar,
+ backgroundColor: row.backgroundColor,
+ createdAt: row.createdAt,
+ description: row.description,
+ id: row.id,
+ relevance: row.relevance,
+ title: row.title || '',
+ type: 'chatGroup' as const,
+ updatedAt: row.updatedAt,
+ }));
+}
+
+/** Search knowledge bases by name and description. */
+export async function searchKnowledgeBases(
+ context: PgSearchFtsSearchContext,
+ query: string,
+ limit: number,
+ excludeIds?: string[],
+): Promise<FtsSearchBackendResponse<FtsSearchKnowledgeBaseResult>> {
+ const bm25Query = sanitizeBm25Query(query);
+ const { db } = context;
+
+ const hits = db
+ .select({
+ avatar: knowledgeBases.avatar,
+ createdAt: knowledgeBases.createdAt,
+ description: knowledgeBases.description,
+ id: knowledgeBases.id,
+ name: knowledgeBases.name,
+ score: sql<number>`paradedb.score(${knowledgeBases.id})`.as('score'),
+ updatedAt: knowledgeBases.updatedAt,
+ workspaceId: knowledgeBases.workspaceId,
+ })
+ .from(knowledgeBases)
+ .where(
+ and(
+ context.scanScopeWhere(knowledgeBases),
+ sql`(${knowledgeBases.name} @@@ ${bm25Query} OR ${knowledgeBases.description} @@@ ${bm25Query})`,
+ ),
+ )
+ .orderBy(sql`paradedb.score(${knowledgeBases.id}) DESC`)
+ .limit(context.scanCandidateLimit(limit))
+ .as('knowledge_base_hits');
+
+ const rows = await db
+ .select({
+ avatar: hits.avatar,
+ createdAt: hits.createdAt,
+ description: hits.description,
+ id: hits.id,
+ name: hits.name,
+ score: hits.score,
+ updatedAt: hits.updatedAt,
+ })
+ .from(hits)
+ .where(
+ and(
+ context.liftedScopeWhere(hits.workspaceId),
+ // Keep excluded knowledge bases out of the inner BM25 scan so TopN
+ // ranking remains intact; restricted rows only consume pool slots.
+ excludeIds && excludeIds.length > 0 ? notInArray(hits.id, excludeIds) : undefined,
+ ),
+ )
+ .orderBy(desc(hits.score))
+ .limit(limit);
+
+ return buildResponse(rows, (row) => ({
+ avatar: row.avatar,
+ createdAt: row.createdAt,
+ description: row.description,
+ id: row.id,
+ relevance: row.relevance,
+ title: row.name,
+ type: 'knowledgeBase' as const,
+ updatedAt: row.updatedAt,
+ }));
+}
diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/documents.ts b/packages/database/src/repositories/ftsSearch/pgSearch/documents.ts
new file mode 100644
index 00000000000..58d0e1c05d9
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/pgSearch/documents.ts
@@ -0,0 +1,266 @@
+import { and, desc, eq, inArray, isNull, ne, notInArray, or, sql } from 'drizzle-orm';
+
+import { DOCUMENT_FOLDER_TYPE, documents, knowledgeBaseFiles } from '../../../schemas';
+import { sanitizeBm25Query } from '../../../utils/bm25';
+import { buildWorkspaceWhere } from '../../../utils/workspace';
+import type {
+ FtsSearchBackendResponse,
+ FtsSearchFolderResult,
+ FtsSearchKnowledgeBaseDocumentHit,
+ FtsSearchPageResult,
+} from '../types';
+import { buildResponse, truncate } from './results';
+import type { PgSearchFtsSearchContext } from './scope';
+
+/** Search folders (documents with `file_type=DOCUMENT_FOLDER_TYPE`). */
+export async function searchFolders(
+ context: PgSearchFtsSearchContext,
+ query: string,
+ limit: number,
+ excludeKbIds?: string[],
+): Promise<FtsSearchBackendResponse<FtsSearchFolderResult>> {
+ const bm25Query = sanitizeBm25Query(query);
+ const { db } = context;
+
+ const hits = db
+ .select({
+ createdAt: documents.createdAt,
+ description: documents.description,
+ filename: documents.filename,
+ id: documents.id,
+ knowledgeBaseId: documents.knowledgeBaseId,
+ score: sql<number>`paradedb.score(${documents.id})`.as('score'),
+ slug: documents.slug,
+ title: documents.title,
+ updatedAt: documents.updatedAt,
+ workspaceId: documents.workspaceId,
+ })
+ .from(documents)
+ .where(
+ and(
+ context.scanScopeWhere(documents),
+ eq(documents.fileType, DOCUMENT_FOLDER_TYPE),
+ sql`(${documents.title} @@@ ${bm25Query} OR ${documents.slug} @@@ ${bm25Query} OR ${documents.description} @@@ ${bm25Query})`,
+ ),
+ )
+ .orderBy(sql`paradedb.score(${documents.id}) DESC`)
+ .limit(context.scanCandidateLimit(limit))
+ .as('folder_hits');
+
+ const rows = await db
+ .select({
+ createdAt: hits.createdAt,
+ description: hits.description,
+ filename: hits.filename,
+ id: hits.id,
+ knowledgeBaseId: hits.knowledgeBaseId,
+ score: hits.score,
+ slug: hits.slug,
+ title: hits.title,
+ updatedAt: hits.updatedAt,
+ })
+ .from(hits)
+ .where(
+ and(
+ context.liftedScopeWhere(hits.workspaceId),
+ excludeKbIds && excludeKbIds.length > 0
+ ? or(isNull(hits.knowledgeBaseId), notInArray(hits.knowledgeBaseId, excludeKbIds))
+ : undefined,
+ ),
+ )
+ .orderBy(desc(hits.score))
+ .limit(limit);
+
+ return buildResponse(rows, (row) => {
+ const title = row.title || row.filename || 'Untitled';
+ return {
+ createdAt: row.createdAt,
+ description: row.description,
+ id: row.id,
+ knowledgeBaseId: row.knowledgeBaseId,
+ relevance: row.relevance,
+ slug: row.slug,
+ title,
+ type: 'folder' as const,
+ updatedAt: row.updatedAt,
+ };
+ });
+}
+
+/** Search pages (documents with `file_type='custom/document'`). */
+export async function searchPages(
+ context: PgSearchFtsSearchContext,
+ query: string,
+ limit: number,
+ excludeKbIds?: string[],
+): Promise<FtsSearchBackendResponse<FtsSearchPageResult>> {
+ const bm25Query = sanitizeBm25Query(query);
+ const { db } = context;
+
+ const hits = db
+ .select({
+ createdAt: documents.createdAt,
+ fileId: documents.fileId,
+ filename: documents.filename,
+ id: documents.id,
+ knowledgeBaseId: documents.knowledgeBaseId,
+ score: sql<number>`paradedb.score(${documents.id})`.as('score'),
+ title: documents.title,
+ updatedAt: documents.updatedAt,
+ workspaceId: documents.workspaceId,
+ })
+ .from(documents)
+ .where(
+ and(
+ context.scanScopeWhere(documents),
+ eq(documents.fileType, 'custom/document'),
+ sql`(${documents.title} @@@ ${bm25Query} OR ${documents.slug} @@@ ${bm25Query} OR ${documents.content} @@@ ${bm25Query})`,
+ ),
+ )
+ .orderBy(sql`paradedb.score(${documents.id}) DESC`)
+ .limit(context.scanCandidateLimit(limit))
+ .as('page_hits');
+
+ const rows = await db
+ .select({
+ createdAt: hits.createdAt,
+ filename: hits.filename,
+ id: hits.id,
+ score: hits.score,
+ title: hits.title,
+ updatedAt: hits.updatedAt,
+ })
+ .from(hits)
+ .where(
+ and(
+ context.liftedScopeWhere(hits.workspaceId),
+ excludeKbIds && excludeKbIds.length > 0
+ ? or(isNull(hits.knowledgeBaseId), notInArray(hits.knowledgeBaseId, excludeKbIds))
+ : undefined,
+ // Parsed-file pages store KB membership on file_id instead of the
+ // document row, so check the join table as well.
+ excludeKbIds && excludeKbIds.length > 0
+ ? or(
+ isNull(hits.fileId),
+ notInArray(
+ hits.fileId,
+ db
+ .select({ fileId: knowledgeBaseFiles.fileId })
+ .from(knowledgeBaseFiles)
+ .where(inArray(knowledgeBaseFiles.knowledgeBaseId, excludeKbIds)),
+ ),
+ )
+ : undefined,
+ ),
+ )
+ .orderBy(desc(hits.score))
+ .limit(limit);
+
+ return buildResponse(rows, (row) => {
+ const title = row.title || row.filename || 'Untitled';
+ return {
+ createdAt: row.createdAt,
+ description: null,
+ id: row.id,
+ relevance: row.relevance,
+ title,
+ type: 'page' as const,
+ updatedAt: row.updatedAt,
+ };
+ });
+}
+
+/**
+ * FTS search documents belonging to one or more knowledge bases.
+ *
+ * Inline pages and file-backed documents use separate scoring queries because
+ * ParadeDB rejects a disjunctive shape spanning BM25 and non-BM25 predicates.
+ */
+export async function searchKnowledgeBaseDocuments(
+ context: PgSearchFtsSearchContext,
+ query: string,
+ knowledgeBaseIds: string[],
+ limit: number = 20,
+): Promise<FtsSearchBackendResponse<FtsSearchKnowledgeBaseDocumentHit>> {
+ if (!query || query.trim() === '') return { candidates: [], items: [] };
+ if (!knowledgeBaseIds || knowledgeBaseIds.length === 0) {
+ return { candidates: [], items: [] };
+ }
+
+ const bm25Query = sanitizeBm25Query(query);
+ const { db } = context;
+ const matchClause = sql`(${documents.title} @@@ ${bm25Query} OR ${documents.slug} @@@ ${bm25Query} OR ${documents.content} @@@ ${bm25Query})`;
+ const folderClause = ne(documents.fileType, DOCUMENT_FOLDER_TYPE);
+ const userClause = buildWorkspaceWhere(context.scope, documents);
+
+ const inlineRowsPromise = db
+ .select({
+ content: documents.content,
+ fileId: documents.fileId,
+ filename: documents.filename,
+ id: documents.id,
+ knowledgeBaseId: documents.knowledgeBaseId,
+ score: sql<number>`paradedb.score(${documents.id})`,
+ title: documents.title,
+ updatedAt: documents.updatedAt,
+ })
+ .from(documents)
+ .where(
+ and(
+ userClause,
+ folderClause,
+ inArray(documents.knowledgeBaseId, knowledgeBaseIds),
+ matchClause,
+ ),
+ )
+ .orderBy(sql`paradedb.score(${documents.id}) DESC`)
+ .limit(limit);
+
+ const fileBackedRowsPromise = db
+ .select({
+ content: documents.content,
+ fileId: documents.fileId,
+ filename: documents.filename,
+ id: documents.id,
+ knowledgeBaseId: knowledgeBaseFiles.knowledgeBaseId,
+ score: sql<number>`paradedb.score(${documents.id})`,
+ title: documents.title,
+ updatedAt: documents.updatedAt,
+ })
+ .from(documents)
+ .innerJoin(
+ knowledgeBaseFiles,
+ and(
+ eq(knowledgeBaseFiles.fileId, documents.fileId),
+ buildWorkspaceWhere(context.scope, knowledgeBaseFiles),
+ inArray(knowledgeBaseFiles.knowledgeBaseId, knowledgeBaseIds),
+ ),
+ )
+ .where(and(userClause, folderClause, matchClause))
+ .orderBy(sql`paradedb.score(${documents.id}) DESC`)
+ .limit(limit);
+
+ const [inlineRows, fileBackedRows] = await Promise.all([
+ inlineRowsPromise,
+ fileBackedRowsPromise,
+ ]);
+
+ const byId = new Map<string, (typeof inlineRows)[number]>();
+ for (const row of [...inlineRows, ...fileBackedRows]) {
+ const previous = byId.get(row.id);
+ if (!previous || row.score > previous.score) byId.set(row.id, row);
+ }
+ const merged = Array.from(byId.values())
+ .sort((a, b) => b.score - a.score)
+ .slice(0, limit);
+
+ return buildResponse(merged, (row) => ({
+ documentId: row.id,
+ fileId: row.fileId ?? undefined,
+ knowledgeBaseId: row.knowledgeBaseId ?? '',
+ relevance: row.relevance,
+ snippet: truncate(row.content, 300) ?? '',
+ title: row.title || row.filename || 'Untitled',
+ updatedAt: row.updatedAt,
+ }));
+}
diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/memories.ts b/packages/database/src/repositories/ftsSearch/pgSearch/memories.ts
new file mode 100644
index 00000000000..93c8572ea9d
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/pgSearch/memories.ts
@@ -0,0 +1,50 @@
+import { and, eq, sql } from 'drizzle-orm';
+
+import { userMemories } from '../../../schemas';
+import { sanitizeBm25Query } from '../../../utils/bm25';
+import type { FtsSearchBackendResponse, FtsSearchMemoryResult } from '../types';
+import { buildResponse, truncate } from './results';
+import type { PgSearchFtsSearchContext } from './scope';
+
+/** Search user memories by title, summary, and details. */
+export async function searchMemories(
+ context: PgSearchFtsSearchContext,
+ query: string,
+ limit: number,
+): Promise<FtsSearchBackendResponse<FtsSearchMemoryResult>> {
+ const bm25Query = sanitizeBm25Query(query);
+ const { db } = context;
+
+ // Memories are user-scoped and have no workspace column, so the ownership
+ // predicate can remain in the single-table BM25 scan.
+ const rows = await db
+ .select({
+ createdAt: userMemories.createdAt,
+ id: userMemories.id,
+ memoryLayer: userMemories.memoryLayer,
+ score: sql<number>`paradedb.score(${userMemories.id})`,
+ summary: userMemories.summary,
+ title: userMemories.title,
+ updatedAt: userMemories.updatedAt,
+ })
+ .from(userMemories)
+ .where(
+ and(
+ eq(userMemories.userId, context.userId),
+ sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemories.summary} @@@ ${bm25Query} OR ${userMemories.details} @@@ ${bm25Query})`,
+ ),
+ )
+ .orderBy(sql`paradedb.score(${userMemories.id}) DESC`)
+ .limit(limit);
+
+ return buildResponse(rows, (row) => ({
+ createdAt: row.createdAt,
+ description: truncate(row.summary),
+ id: row.id,
+ memoryLayer: row.memoryLayer,
+ relevance: row.relevance,
+ title: row.title || 'Untitled Memory',
+ type: 'memory' as const,
+ updatedAt: row.updatedAt,
+ }));
+}
diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/results.ts b/packages/database/src/repositories/ftsSearch/pgSearch/results.ts
new file mode 100644
index 00000000000..3b4aab34210
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/pgSearch/results.ts
@@ -0,0 +1,51 @@
+import type { FtsSearchBackendItem, FtsSearchBackendResponse } from '../types';
+
+/** Map BM25 scores to the relevance scale used by existing search consumers. */
+export function mapScoresToRelevance<T extends { score: number }>(
+ rows: T[],
+): (T & { relevance: number })[] {
+ if (rows.length === 0) return [];
+
+ const maxScore = Math.max(...rows.map((row) => row.score));
+ return rows.map((row) => ({
+ ...row,
+ relevance: maxScore > 0 ? 1 + 2 * (1 - row.score / maxScore) : 3,
+ }));
+}
+
+export function buildResponse<
+ T extends { id: string; score: number },
+ TItem extends FtsSearchBackendItem,
+>(rows: T[], mapItem: (row: T & { relevance: number }) => TItem): FtsSearchBackendResponse<TItem> {
+ return buildScoredResponse(mapScoresToRelevance(rows), mapItem);
+}
+
+export function buildScoredResponse<
+ T extends { id: string; relevance: number; score: number },
+ TItem extends FtsSearchBackendItem,
+>(rows: T[], mapItem: (row: T) => TItem): FtsSearchBackendResponse<TItem> {
+ return {
+ candidates: rows.map((row) => ({ id: row.id, score: row.score })),
+ items: rows.map(mapItem),
+ };
+}
+
+export function buildSelectedResponse<
+ T extends { id: string; relevance: number; score: number },
+ TItem extends FtsSearchBackendItem,
+>(candidates: T[], rows: T[], mapItem: (row: T) => TItem): FtsSearchBackendResponse<TItem> {
+ return {
+ candidates: candidates.map((row) => ({ id: row.id, score: row.score })),
+ items: rows.map(mapItem),
+ };
+}
+
+/** Truncate optional search snippets while preserving the old empty-value behavior. */
+export function truncate(
+ content: string | null | undefined,
+ maxLength: number = 200,
+): string | null {
+ if (!content) return null;
+ if (content.length <= maxLength) return content;
+ return content.slice(0, maxLength) + '...';
+}
diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/scope.ts b/packages/database/src/repositories/ftsSearch/pgSearch/scope.ts
new file mode 100644
index 00000000000..ceee11fbb53
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/pgSearch/scope.ts
@@ -0,0 +1,93 @@
+import type { SQL, SQLWrapper } from 'drizzle-orm';
+import { eq, isNull } from 'drizzle-orm';
+import type { AnyPgColumn } from 'drizzle-orm/pg-core';
+
+import type { LobeChatDatabase } from '../../../type';
+import { buildWorkspaceWhere } from '../../../utils/workspace';
+import type { FtsSearchBackendScope } from '../types';
+
+/** Columns shared by the workspace-aware tables searched by pg_search. */
+export interface PgSearchFtsSearchWorkspaceScopedColumns {
+ userId: AnyPgColumn;
+ visibility?: AnyPgColumn;
+ workspaceId: AnyPgColumn;
+}
+
+/** Shared state and query-shaping helpers used by the pg_search provider modules. */
+export interface PgSearchFtsSearchContext {
+ db: LobeChatDatabase;
+ liftedScopeWhere: (workspaceIdColumn: SQLWrapper) => SQL | undefined;
+ liftsAgentFilter: boolean;
+ liftsWorkspaceFilter: boolean;
+ scanCandidateLimit: (limit: number) => number;
+ scanScopeWhere: (cols: PgSearchFtsSearchWorkspaceScopedColumns) => SQL;
+ scope: FtsSearchBackendScope;
+ userId: string;
+}
+
+/**
+ * Every query here is shaped as "inner single-table BM25 scan → outer enrichment",
+ * because ParadeDB only picks its TopN custom scan (`TopNScanExecState`, which
+ * visits a handful of heap rows) when the scan node itself carries the whole
+ * `ORDER BY paradedb.score() LIMIT n`. Joins and non-indexed ownership filters
+ * therefore stay outside the scan whenever the score ordering remains valid.
+ *
+ * The workspace filter is currently not a fast field in the BM25 indexes. In
+ * personal mode we keep the user filter in the scan and lift only the
+ * `workspace_id IS NULL` half above it, using a deeper candidate pool to keep
+ * personal rows from being displaced by workspace rows.
+ */
+const WORKSPACE_FILTER_CANDIDATE_MULTIPLIER = 5;
+
+/** See `WORKSPACE_FILTER_CANDIDATE_MULTIPLIER`; this floor protects small limits. */
+const WORKSPACE_FILTER_MIN_CANDIDATES = 500;
+
+/**
+ * Candidate pool used when the active-agent filter is lifted above the BM25
+ * scan. Agent IDs are not BM25 fields, so the pool must be deep enough for a
+ * small agent to survive the outer filter.
+ */
+const AGENT_SCOPE_CANDIDATE_POOL = 20_000;
+
+/**
+ * Flip to `true` once every BM25 index used by this repo carries `workspace_id`
+ * as a fast keyword field. At that point ownership can stay inline and
+ * personal-mode search becomes exact again.
+ */
+const WORKSPACE_ID_IN_BM25_INDEX = false;
+
+export function createPgSearchFtsSearchContext(
+ db: LobeChatDatabase,
+ scope: FtsSearchBackendScope,
+): PgSearchFtsSearchContext {
+ // The original backend copied scope fields in its constructor. Keep the same
+ // snapshot semantics instead of retaining a caller-owned mutable object.
+ const normalizedScope: FtsSearchBackendScope = {
+ callerAgentVisibility: scope.callerAgentVisibility,
+ userId: scope.userId,
+ workspaceId: scope.workspaceId,
+ };
+ const liftsWorkspaceFilter = !WORKSPACE_ID_IN_BM25_INDEX && !normalizedScope.workspaceId;
+ const liftsAgentFilter = WORKSPACE_ID_IN_BM25_INDEX || !normalizedScope.workspaceId;
+
+ return {
+ db,
+ liftedScopeWhere: (workspaceIdColumn) =>
+ liftsWorkspaceFilter ? (isNull(workspaceIdColumn) as SQL) : undefined,
+ liftsAgentFilter,
+ liftsWorkspaceFilter,
+ scanCandidateLimit: (limit) =>
+ liftsWorkspaceFilter
+ ? Math.max(limit * WORKSPACE_FILTER_CANDIDATE_MULTIPLIER, WORKSPACE_FILTER_MIN_CANDIDATES)
+ : limit,
+ scanScopeWhere: (cols) => {
+ if (!liftsWorkspaceFilter) return buildWorkspaceWhere(normalizedScope, cols);
+
+ return eq(cols.userId, normalizedScope.userId) as SQL;
+ },
+ scope: normalizedScope,
+ userId: normalizedScope.userId,
+ };
+}
+
+export { AGENT_SCOPE_CANDIDATE_POOL, WORKSPACE_FILTER_CANDIDATE_MULTIPLIER };
diff --git a/packages/database/src/repositories/ftsSearch/types.ts b/packages/database/src/repositories/ftsSearch/types.ts
new file mode 100644
index 00000000000..c7a0a95f5c9
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/types.ts
@@ -0,0 +1,312 @@
+export type FtsSearchResultType =
+ | 'page'
+ | 'pageContent'
+ | 'agent'
+ | 'topic'
+ | 'chatGroup'
+ | 'file'
+ | 'folder'
+ | 'memory'
+ | 'message'
+ | 'mcp'
+ | 'plugin'
+ | 'communityAgent'
+ | 'knowledgeBase';
+
+export interface FtsSearchBaseResult {
+ createdAt: Date;
+ description?: string | null;
+ id: string;
+ /** Normalized display relevance where lower is better. */
+ relevance: number;
+ title: string;
+ type: FtsSearchResultType;
+ updatedAt: Date;
+}
+
+export interface FtsSearchPageResult extends FtsSearchBaseResult {
+ id: string;
+ type: 'page';
+}
+
+export interface FtsSearchPageContentResult extends FtsSearchBaseResult {
+ id: string;
+ type: 'pageContent';
+}
+
+export interface FtsSearchAgentResult extends FtsSearchBaseResult {
+ avatar: string | null;
+ backgroundColor: string | null;
+ slug: string | null;
+ tags: string[];
+ type: 'agent';
+}
+
+export interface FtsSearchChatGroupResult extends FtsSearchBaseResult {
+ avatar: string | null;
+ backgroundColor: string | null;
+ type: 'chatGroup';
+}
+
+export interface FtsSearchTopicResult extends FtsSearchBaseResult {
+ agent: {
+ avatar: string | null;
+ backgroundColor: string | null;
+ title: string | null;
+ } | null;
+ agentId: string | null;
+ favorite: boolean | null;
+ groupId: string | null;
+ sessionId: string | null;
+ type: 'topic';
+}
+
+export interface FtsSearchFileResult extends FtsSearchBaseResult {
+ fileType: string;
+ knowledgeBaseId: string | null;
+ name: string;
+ size: number;
+ type: 'file';
+ url: string | null;
+}
+
+export interface FtsSearchFolderResult extends FtsSearchBaseResult {
+ knowledgeBaseId: string | null;
+ slug: string | null;
+ type: 'folder';
+}
+
+export interface FtsSearchMessageResult extends FtsSearchBaseResult {
+ agentId: string | null;
+ content: string;
+ groupId: string | null;
+ model: string | null;
+ role: string;
+ topicId: string | null;
+ type: 'message';
+}
+
+export interface FtsSearchMemoryResult extends FtsSearchBaseResult {
+ memoryLayer: string | null;
+ type: 'memory';
+}
+
+export interface FtsSearchMCPResult extends FtsSearchBaseResult {
+ author: string;
+ avatar?: string | null;
+ category?: string | null;
+ connectionType?: 'http' | 'stdio' | null;
+ identifier: string;
+ installCount?: number | null;
+ isFeatured?: boolean | null;
+ isValidated?: boolean | null;
+ tags?: string[] | null;
+ type: 'mcp';
+}
+
+export interface FtsSearchPluginResult extends FtsSearchBaseResult {
+ author: string;
+ avatar?: string | null;
+ category?: string | null;
+ identifier: string;
+ tags?: string[] | null;
+ type: 'plugin';
+}
+
+export interface FtsSearchKnowledgeBaseResult extends FtsSearchBaseResult {
+ avatar: string | null;
+ type: 'knowledgeBase';
+}
+
+/**
+ * Hydrated BM25 hit for KB-scoped documents. `fileId` identifies a parsed-file
+ * source; inline pages use `documentId` directly.
+ */
+export interface FtsSearchKnowledgeBaseDocumentHit {
+ documentId: string;
+ fileId?: string;
+ knowledgeBaseId: string;
+ relevance: number;
+ snippet: string;
+ title: string;
+ updatedAt: Date;
+}
+
+export interface FtsSearchAssistantResult extends FtsSearchBaseResult {
+ author: string;
+ avatar?: string | null;
+ homepage?: string | null;
+ identifier: string;
+ tags?: string[] | null;
+ type: 'communityAgent';
+}
+
+export type FtsSearchDatabaseResult =
+ | FtsSearchPageResult
+ | FtsSearchPageContentResult
+ | FtsSearchAgentResult
+ | FtsSearchChatGroupResult
+ | FtsSearchTopicResult
+ | FtsSearchFileResult
+ | FtsSearchFolderResult
+ | FtsSearchMessageResult
+ | FtsSearchMemoryResult
+ | FtsSearchKnowledgeBaseResult;
+
+export type FtsSearchResult =
+ FtsSearchDatabaseResult | FtsSearchMCPResult | FtsSearchPluginResult | FtsSearchAssistantResult;
+
+export interface FtsSearchOptions {
+ agentId?: string;
+ contextType?: 'agent' | 'resource' | 'page';
+ /** Caller-relative restricted KBs that must not be discoverable. */
+ excludeKnowledgeBaseIds?: string[];
+ limitPerType?: number;
+ offset?: number;
+ query: string;
+ type?: FtsSearchResultType;
+}
+
+/** Entities implemented by the current product search repository contract. */
+export type FtsSearchBackendEntity =
+ | 'agents'
+ | 'chatGroups'
+ | 'documents'
+ | 'files'
+ | 'knowledgeBases'
+ | 'memoryActivities'
+ | 'memoryContexts'
+ | 'memoryExperiences'
+ | 'memoryIdentities'
+ | 'memoryPreferences'
+ | 'messages'
+ | 'personaDocuments'
+ | 'topics'
+ | 'userMemories';
+
+export interface FtsSearchBackendScope {
+ /** Visibility of the agent initiating a KB search, when applicable. */
+ callerAgentVisibility?: 'private' | 'public' | null;
+ userId: string;
+ workspaceId?: string;
+}
+
+export interface FtsSearchBackendFilters {
+ agentId?: string;
+ documentKind?: 'folder' | 'knowledgeBaseDocument' | 'page';
+ excludeKnowledgeBaseIds?: string[];
+ excludeVirtual?: boolean;
+ knowledgeBaseIds?: string[];
+ memoryCategories?: string[];
+ memoryRelationships?: string[];
+ memoryStatus?: string[];
+ /** Hybrid search requires every tag; legacy list search preserves its any-tag contract. */
+ memoryTagMatch?: 'all' | 'any';
+ memoryTags?: string[];
+ memoryTimeRange?: {
+ end?: Date;
+ field?: 'capturedAt' | 'createdAt' | 'endsAt' | 'episodicDate' | 'startsAt' | 'updatedAt';
+ start?: Date;
+ };
+ memoryTypes?: string[];
+ topicScope?: {
+ agentId?: string | null;
+ containerId?: string | null;
+ groupId?: string | null;
+ };
+}
+
+export interface FtsSearchBackendPagination {
+ /** Omitted for legacy/list paths whose public contract is currently unbounded. */
+ limit?: number;
+}
+
+export interface FtsSearchBackendQuery {
+ /** Exact mapped fields for a candidate-only production path. */
+ fields?: string[];
+ text: string;
+}
+
+export interface FtsSearchBackendRequest {
+ entity: FtsSearchBackendEntity;
+ filters: FtsSearchBackendFilters;
+ mode?: 'candidates' | 'results';
+ pagination: FtsSearchBackendPagination;
+ query: FtsSearchBackendQuery;
+ scope: FtsSearchBackendScope;
+}
+
+/** Raw provider candidate before authorization hydration and product-specific post-ranking. */
+export interface FtsSearchBackendCandidate {
+ id: string;
+ /** Provider-native score where higher is better; legacy pg_search can emit null. */
+ score: number | null;
+}
+
+export type FtsSearchBackendItem = FtsSearchDatabaseResult | FtsSearchKnowledgeBaseDocumentHit;
+
+export interface FtsSearchBackendResponse<
+ TItem extends FtsSearchBackendItem = FtsSearchBackendItem,
+> {
+ /**
+ * Provider-native retrieval pool. It can be larger than and ordered differently from `items`
+ * when the product applies a secondary display ranking, such as topic/message recency.
+ */
+ candidates: FtsSearchBackendCandidate[];
+ /** Hydrated, authorization-checked product items in display order. */
+ items: TItem[];
+ /** Provider match count before PostgreSQL authorization hydration. */
+ total?: number;
+}
+
+/** Provider-neutral execution contract implemented by each full-text search adapter. */
+export interface FtsSearchBackend {
+ /** Stable backend identity used by repository-level measurements. */
+ key: string;
+ search: (request: FtsSearchBackendRequest) => Promise<FtsSearchBackendResponse>;
+}
+
+export interface FtsSearchBackendMeasurementRequest {
+ entity: FtsSearchBackendEntity;
+ filterKeys: (keyof FtsSearchBackendFilters)[];
+ limit: number;
+ queryLength: number;
+ scope: 'personal' | 'workspace';
+}
+
+interface FtsSearchBackendMeasurementBase {
+ durationMs: number;
+ provider: string;
+ /** Privacy-safe request shape that excludes identifiers and user-entered text. */
+ request: FtsSearchBackendMeasurementRequest;
+}
+
+export type FtsSearchBackendMeasurement =
+ | (FtsSearchBackendMeasurementBase & {
+ candidateCount: number;
+ itemCount: number;
+ status: 'success';
+ })
+ | (FtsSearchBackendMeasurementBase & {
+ errorType: string;
+ status: 'error';
+ });
+
+export interface FtsSearchRepoOptions {
+ backend?: FtsSearchBackend;
+ /** Enables candidate-only paths for models that otherwise keep their existing pg_search query. */
+ ftsSearchCandidateEnabled?: boolean;
+ onMeasurement?: (measurement: FtsSearchBackendMeasurement) => Promise<void> | void;
+}
+
+export type FtsSearchCandidateRequest = Omit<FtsSearchBackendRequest, 'mode' | 'scope'>;
+
+export interface FtsSearchCandidateResult {
+ candidates: FtsSearchBackendCandidate[];
+ total: number;
+}
+
+export interface FtsSearchCandidateSource {
+ ftsSearchCandidateEnabled: boolean;
+ ftsSearchCandidates: (request: FtsSearchCandidateRequest) => Promise<FtsSearchCandidateResult>;
+}
diff --git a/packages/database/src/repositories/ftsSearchDocument/__tests__/fixtures.ts b/packages/database/src/repositories/ftsSearchDocument/__tests__/fixtures.ts
new file mode 100644
index 00000000000..99dede53a61
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/__tests__/fixtures.ts
@@ -0,0 +1,225 @@
+import type { FtsSearchDocumentSourceMap } from '../schema';
+
+const createdAt = '2026-01-01T00:00:00.000Z';
+const updatedAt = '2026-01-02T00:00:00.000Z';
+const capturedAt = '2026-01-03T00:00:00.000Z';
+
+export const FTS_SEARCH_DOCUMENT_FIXTURES = {
+ agents: {
+ created_at: createdAt,
+ description: 'Agent description',
+ id: 'agent-1',
+ slug: 'agent-slug',
+ system_role: 'Agent system role',
+ tags: ['coding', 'search'],
+ title: 'Agent title',
+ updated_at: updatedAt,
+ user_id: 'search-document-user',
+ virtual: false,
+ visibility: 'public',
+ workspace_id: null,
+ },
+ chatGroups: {
+ content: 'Group content',
+ created_at: createdAt,
+ description: 'Group description',
+ group_id: null,
+ id: 'chat-group-1',
+ title: 'Group title',
+ updated_at: updatedAt,
+ user_id: 'search-document-user',
+ visibility: 'private',
+ workspace_id: null,
+ },
+ documents: {
+ content: 'Document content',
+ created_at: createdAt,
+ description: 'Document description',
+ file_id: 'file-1',
+ file_type: 'text/plain',
+ id: 'document-1',
+ knowledge_base_id: 'knowledge-base-inline',
+ knowledge_base_ids: ['knowledge-base-file', 'knowledge-base-inline'],
+ parent_id: null,
+ slug: 'document-slug',
+ source_type: 'file',
+ title: 'Document title',
+ total_char_count: 16,
+ updated_at: updatedAt,
+ user_id: 'search-document-user',
+ visibility: 'public',
+ workspace_id: null,
+ },
+ files: {
+ created_at: createdAt,
+ file_type: 'text/plain',
+ id: 'file-1',
+ knowledge_base_ids: ['knowledge-base-file'],
+ name: 'fixture.txt',
+ size: 128,
+ source: null,
+ updated_at: updatedAt,
+ user_id: 'search-document-user',
+ visibility: 'public',
+ workspace_id: null,
+ },
+ knowledgeBases: {
+ created_at: createdAt,
+ description: 'Knowledge base description',
+ id: 'knowledge-base-file',
+ is_public: true,
+ name: 'Knowledge base',
+ type: 'file',
+ updated_at: updatedAt,
+ user_id: 'search-document-user',
+ visibility: 'private',
+ workspace_id: null,
+ },
+ memoryActivities: {
+ captured_at: capturedAt,
+ created_at: createdAt,
+ ends_at: null,
+ feedback: 'Activity feedback',
+ id: 'memory-activity-1',
+ narrative: 'Activity narrative',
+ notes: 'Activity notes',
+ parent_details: 'Parent details',
+ parent_memory_categories: ['work'],
+ parent_summary: 'Parent summary',
+ parent_tags: ['parent'],
+ parent_title: 'Parent title',
+ starts_at: capturedAt,
+ status: 'pending',
+ tags: ['activity'],
+ type: 'task',
+ updated_at: updatedAt,
+ user_id: 'search-document-user',
+ user_memory_id: 'memory-1',
+ },
+ memoryContexts: {
+ captured_at: capturedAt,
+ created_at: createdAt,
+ current_status: 'Context status',
+ description: 'Context description',
+ id: 'memory-context-1',
+ parent_memory_categories: ['work'],
+ parent_tags: ['parent'],
+ parent_text: ['Parent title Parent summary Parent details'],
+ tags: ['context'],
+ title: 'Context title',
+ type: 'project',
+ updated_at: updatedAt,
+ user_id: 'search-document-user',
+ user_memory_ids: ['memory-1'],
+ },
+ memoryExperiences: {
+ action: 'Experience action',
+ captured_at: capturedAt,
+ created_at: createdAt,
+ id: 'memory-experience-1',
+ key_learning: 'Experience learning',
+ parent_details: 'Parent details',
+ parent_memory_categories: ['work'],
+ parent_summary: 'Parent summary',
+ parent_tags: ['parent'],
+ parent_title: 'Parent title',
+ possible_outcome: 'Experience outcome',
+ reasoning: 'Experience reasoning',
+ situation: 'Experience situation',
+ tags: ['experience'],
+ type: 'decision',
+ updated_at: updatedAt,
+ user_id: 'search-document-user',
+ user_memory_id: 'memory-1',
+ },
+ memoryIdentities: {
+ captured_at: capturedAt,
+ created_at: createdAt,
+ description: 'Identity description',
+ episodic_date: capturedAt,
+ id: 'memory-identity-1',
+ parent_details: 'Parent details',
+ parent_memory_categories: ['work'],
+ parent_summary: 'Parent summary',
+ parent_tags: ['parent'],
+ parent_title: 'Parent title',
+ relationship: 'colleague',
+ role: 'Engineer',
+ tags: ['identity'],
+ type: 'person',
+ updated_at: updatedAt,
+ user_id: 'search-document-user',
+ user_memory_id: 'memory-1',
+ },
+ memoryPreferences: {
+ captured_at: capturedAt,
+ conclusion_directives: 'Preference directives',
+ created_at: createdAt,
+ id: 'memory-preference-1',
+ parent_details: 'Parent details',
+ parent_memory_categories: ['work'],
+ parent_summary: 'Parent summary',
+ parent_tags: ['parent'],
+ parent_title: 'Parent title',
+ suggestions: 'Preference suggestions',
+ tags: ['preference'],
+ type: 'communication',
+ updated_at: updatedAt,
+ user_id: 'search-document-user',
+ user_memory_id: 'memory-1',
+ },
+ messages: {
+ agent_id: 'agent-1',
+ content: 'Message content',
+ created_at: createdAt,
+ group_id: 'chat-group-1',
+ id: 'message-1',
+ role: 'user',
+ session_id: null,
+ summary: 'Message summary',
+ thread_id: null,
+ topic_id: 'topic-1',
+ updated_at: updatedAt,
+ user_id: 'search-document-user',
+ workspace_id: null,
+ },
+ personaDocuments: {
+ captured_at: capturedAt,
+ created_at: createdAt,
+ id: 'persona-document-1',
+ persona: 'Persona body',
+ profile: 'default',
+ tagline: 'Persona tagline',
+ updated_at: updatedAt,
+ user_id: 'search-document-user',
+ version: 2,
+ },
+ topics: {
+ agent_id: 'agent-1',
+ content: 'Topic content',
+ created_at: createdAt,
+ description: 'Topic description',
+ group_id: 'chat-group-1',
+ id: 'topic-1',
+ session_id: null,
+ status: 'active',
+ title: 'Topic title',
+ updated_at: updatedAt,
+ user_id: 'search-document-user',
+ workspace_id: null,
+ },
+ userMemories: {
+ captured_at: capturedAt,
+ created_at: createdAt,
+ details: 'Parent details',
+ id: 'memory-1',
+ memory_category: 'work',
+ memory_layer: 'episodic',
+ status: 'active',
+ summary: 'Parent summary',
+ tags: ['parent'],
+ title: 'Parent title',
+ updated_at: updatedAt,
+ user_id: 'search-document-user',
+ },
+} as const satisfies FtsSearchDocumentSourceMap;
diff --git a/packages/database/src/repositories/ftsSearchDocument/builder.test.ts b/packages/database/src/repositories/ftsSearchDocument/builder.test.ts
new file mode 100644
index 00000000000..e5ca3311d83
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/builder.test.ts
@@ -0,0 +1,325 @@
+// @vitest-environment node
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agents,
+ chatGroups,
+ documents,
+ files,
+ knowledgeBaseFiles,
+ knowledgeBases,
+ messages,
+ topics,
+ userMemories,
+ userMemoriesActivities,
+ userMemoriesContexts,
+ userMemoriesExperiences,
+ userMemoriesIdentities,
+ userMemoriesPreferences,
+ userPersonaDocuments,
+ users,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { FTS_SEARCH_DOCUMENT_FIXTURES } from './__tests__/fixtures';
+import { FtsSearchDocumentBuilder } from './builder';
+import { FTS_SEARCH_DOCUMENT_ENTITIES } from './schema';
+
+const userId = 'search-document-user';
+const createdAt = new Date('2026-01-01T00:00:00.000Z');
+const updatedAt = new Date('2026-01-02T00:00:00.000Z');
+const capturedAt = new Date('2026-01-03T00:00:00.000Z');
+
+const db: LobeChatDatabase = await getTestDB();
+const builder = new FtsSearchDocumentBuilder(db);
+
+const seedFixtures = async () => {
+ await db.insert(users).values({ id: userId });
+
+ await db.insert(agents).values([
+ {
+ createdAt,
+ description: 'Agent description',
+ id: 'agent-1',
+ slug: 'agent-slug',
+ systemRole: 'Agent system role',
+ tags: ['coding', 'search'],
+ title: 'Agent title',
+ updatedAt,
+ userId,
+ virtual: false,
+ visibility: 'public',
+ },
+ {
+ createdAt,
+ id: 'agent-2',
+ title: 'Second agent',
+ updatedAt,
+ userId,
+ },
+ ]);
+
+ await db.insert(chatGroups).values({
+ content: 'Group content',
+ createdAt,
+ description: 'Group description',
+ id: 'chat-group-1',
+ title: 'Group title',
+ updatedAt,
+ userId,
+ visibility: 'private',
+ });
+
+ await db.insert(topics).values({
+ agentId: 'agent-1',
+ content: 'Topic content',
+ createdAt,
+ description: 'Topic description',
+ groupId: 'chat-group-1',
+ id: 'topic-1',
+ status: 'active',
+ title: 'Topic title',
+ updatedAt,
+ userId,
+ });
+
+ await db.insert(messages).values({
+ agentId: 'agent-1',
+ content: 'Message content',
+ createdAt,
+ groupId: 'chat-group-1',
+ id: 'message-1',
+ role: 'user',
+ summary: 'Message summary',
+ topicId: 'topic-1',
+ updatedAt,
+ userId,
+ });
+
+ await db.insert(knowledgeBases).values([
+ {
+ createdAt,
+ description: 'Knowledge base description',
+ id: 'knowledge-base-file',
+ isPublic: true,
+ name: 'Knowledge base',
+ type: 'file',
+ updatedAt,
+ userId,
+ visibility: 'private',
+ },
+ {
+ createdAt,
+ id: 'knowledge-base-inline',
+ name: 'Inline knowledge base',
+ updatedAt,
+ userId,
+ },
+ ]);
+
+ await db.insert(files).values({
+ createdAt,
+ fileType: 'text/plain',
+ id: 'file-1',
+ name: 'fixture.txt',
+ size: 128,
+ updatedAt,
+ url: 'https://example.com/fixture.txt',
+ userId,
+ visibility: 'public',
+ });
+
+ await db.insert(knowledgeBaseFiles).values({
+ fileId: 'file-1',
+ knowledgeBaseId: 'knowledge-base-file',
+ userId,
+ });
+
+ await db.insert(documents).values({
+ content: 'Document content',
+ createdAt,
+ description: 'Document description',
+ fileId: 'file-1',
+ fileType: 'text/plain',
+ id: 'document-1',
+ knowledgeBaseId: 'knowledge-base-inline',
+ slug: 'document-slug',
+ source: 'https://example.com/fixture.txt',
+ sourceType: 'file',
+ title: 'Document title',
+ totalCharCount: 16,
+ totalLineCount: 1,
+ updatedAt,
+ userId,
+ visibility: 'public',
+ });
+
+ await db.insert(userMemories).values({
+ capturedAt,
+ createdAt,
+ details: 'Parent details',
+ id: 'memory-1',
+ lastAccessedAt: capturedAt,
+ memoryCategory: 'work',
+ memoryLayer: 'episodic',
+ status: 'active',
+ summary: 'Parent summary',
+ tags: ['parent'],
+ title: 'Parent title',
+ updatedAt,
+ userId,
+ });
+
+ await db.insert(userMemoriesContexts).values({
+ capturedAt,
+ createdAt,
+ currentStatus: 'Context status',
+ description: 'Context description',
+ id: 'memory-context-1',
+ tags: ['context'],
+ title: 'Context title',
+ type: 'project',
+ updatedAt,
+ userId,
+ userMemoryIds: ['memory-1'],
+ });
+
+ await db.insert(userMemoriesPreferences).values({
+ capturedAt,
+ conclusionDirectives: 'Preference directives',
+ createdAt,
+ id: 'memory-preference-1',
+ suggestions: 'Preference suggestions',
+ tags: ['preference'],
+ type: 'communication',
+ updatedAt,
+ userId,
+ userMemoryId: 'memory-1',
+ });
+
+ await db.insert(userMemoriesActivities).values({
+ capturedAt,
+ createdAt,
+ feedback: 'Activity feedback',
+ id: 'memory-activity-1',
+ narrative: 'Activity narrative',
+ notes: 'Activity notes',
+ startsAt: capturedAt,
+ status: 'pending',
+ tags: ['activity'],
+ type: 'task',
+ updatedAt,
+ userId,
+ userMemoryId: 'memory-1',
+ });
+
+ await db.insert(userMemoriesIdentities).values({
+ capturedAt,
+ createdAt,
+ description: 'Identity description',
+ episodicDate: capturedAt,
+ id: 'memory-identity-1',
+ relationship: 'colleague',
+ role: 'Engineer',
+ tags: ['identity'],
+ type: 'person',
+ updatedAt,
+ userId,
+ userMemoryId: 'memory-1',
+ });
+
+ await db.insert(userMemoriesExperiences).values({
+ action: 'Experience action',
+ capturedAt,
+ createdAt,
+ id: 'memory-experience-1',
+ keyLearning: 'Experience learning',
+ possibleOutcome: 'Experience outcome',
+ reasoning: 'Experience reasoning',
+ situation: 'Experience situation',
+ tags: ['experience'],
+ type: 'decision',
+ updatedAt,
+ userId,
+ userMemoryId: 'memory-1',
+ });
+
+ await db.insert(userPersonaDocuments).values({
+ capturedAt,
+ createdAt,
+ id: 'persona-document-1',
+ persona: 'Persona body',
+ profile: 'default',
+ tagline: 'Persona tagline',
+ updatedAt,
+ userId,
+ version: 2,
+ });
+};
+
+beforeAll(async () => {
+ await db.delete(users);
+ await seedFixtures();
+});
+
+afterAll(async () => {
+ await db.delete(users);
+});
+
+describe('FtsSearchDocumentBuilder', () => {
+ it('builds all 14 canonical fixtures with stable IDs and deterministic payloads', async () => {
+ for (const entity of FTS_SEARCH_DOCUMENT_ENTITIES) {
+ const fixture = FTS_SEARCH_DOCUMENT_FIXTURES[entity];
+ const first = await builder.buildByIds(entity, [fixture.id]);
+ const second = await builder.buildByIds(entity, [fixture.id]);
+
+ expect(first).toEqual([{ entity, id: fixture.id, source: fixture }]);
+ expect(second).toEqual(first);
+ }
+ });
+
+ it('uses a stable ID cursor for deterministic batches', async () => {
+ const first = await builder.buildBatch('agents', { limit: 1 });
+ const second = await builder.buildBatch('agents', { afterId: first[0].id, limit: 1 });
+
+ expect(first.map(({ id }) => id)).toEqual(['agent-1']);
+ expect(second.map(({ id }) => id)).toEqual(['agent-2']);
+ });
+
+ it('normalizes duplicate IDs and omits missing source records', async () => {
+ const result = await builder.buildByIds('agents', ['missing', 'agent-1', 'agent-1']);
+
+ expect(result.map(({ id }) => id)).toEqual(['agent-1']);
+ });
+
+ it('rejects invalid batch limits before querying PostgreSQL', async () => {
+ await expect(builder.buildBatch('agents', { limit: 0 })).rejects.toThrow(
+ 'FTS search document batch limit must be a positive integer',
+ );
+ });
+
+ it('lists file and file-backed document keys affected by KB relation changes', async () => {
+ await expect(
+ builder.resolveAffectedKeys({
+ fileIds: ['file-1', 'file-1'],
+ relation: 'knowledgeBaseFiles',
+ }),
+ ).resolves.toEqual([
+ { entity: 'files', id: 'file-1' },
+ { entity: 'documents', id: 'document-1' },
+ ]);
+ });
+
+ it('lists every denormalized child affected by a memory change', async () => {
+ await expect(
+ builder.resolveAffectedKeys({ memoryIds: ['memory-1'], relation: 'userMemoryReferences' }),
+ ).resolves.toEqual([
+ { entity: 'userMemories', id: 'memory-1' },
+ { entity: 'memoryContexts', id: 'memory-context-1' },
+ { entity: 'memoryPreferences', id: 'memory-preference-1' },
+ { entity: 'memoryActivities', id: 'memory-activity-1' },
+ { entity: 'memoryIdentities', id: 'memory-identity-1' },
+ { entity: 'memoryExperiences', id: 'memory-experience-1' },
+ ]);
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearchDocument/builder.ts b/packages/database/src/repositories/ftsSearchDocument/builder.ts
new file mode 100644
index 00000000000..ece1a21bb3b
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/builder.ts
@@ -0,0 +1,1005 @@
+import { and, asc, eq, gt, inArray, or, sql } from 'drizzle-orm';
+
+import {
+ agents,
+ chatGroups,
+ documents,
+ files,
+ knowledgeBaseFiles,
+ knowledgeBases,
+ messages,
+ topics,
+ userMemories,
+ userMemoriesActivities,
+ userMemoriesContexts,
+ userMemoriesExperiences,
+ userMemoriesIdentities,
+ userMemoriesPreferences,
+ userPersonaDocuments,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import type {
+ FtsSearchBuiltDocument,
+ FtsSearchDocumentEntity,
+ FtsSearchDocumentKey,
+ FtsSearchDocumentSourceMap,
+} from './schema';
+import { FTS_SEARCH_DOCUMENT_ENTITIES, parseFtsSearchDocumentSource } from './schema';
+
+interface FtsSearchDocumentSelection {
+ afterId?: string;
+ ids?: string[];
+ limit: number;
+}
+
+export interface FtsSearchDocumentBatchOptions {
+ afterId?: string;
+ limit: number;
+}
+
+export type FtsSearchDocumentRelationChange =
+ | { fileIds: readonly string[]; relation: 'knowledgeBaseFiles' }
+ | { memoryIds: readonly string[]; relation: 'userMemoryReferences' };
+
+const entityOrder = new Map(FTS_SEARCH_DOCUMENT_ENTITIES.map((entity, index) => [entity, index]));
+
+const normalizeIds = (ids: readonly string[]) => [...new Set(ids)].filter(Boolean).sort();
+
+const normalizeStringArray = (value: unknown): string[] => {
+ if (Array.isArray(value)) {
+ return value.map((item) => {
+ if (typeof item === 'string') return item;
+ return JSON.stringify(item) ?? String(item);
+ });
+ }
+ if (typeof value === 'string') return [value];
+ if (value === null || value === undefined) return [];
+ return [JSON.stringify(value) ?? String(value)];
+};
+
+const toDateTime = (value: Date) => value.toISOString();
+const toNullableDateTime = (value: Date | null) => value?.toISOString() ?? null;
+
+const groupKnowledgeBaseIds = (
+ rows: { fileId: string; knowledgeBaseId: string }[],
+): Map<string, string[]> => {
+ const grouped = new Map<string, Set<string>>();
+ for (const row of rows) {
+ const ids = grouped.get(row.fileId) ?? new Set<string>();
+ ids.add(row.knowledgeBaseId);
+ grouped.set(row.fileId, ids);
+ }
+
+ return new Map([...grouped.entries()].map(([fileId, ids]) => [fileId, [...ids].sort()] as const));
+};
+
+const compareKeys = (left: FtsSearchDocumentKey, right: FtsSearchDocumentKey) => {
+ const entityDifference =
+ (entityOrder.get(left.entity) ?? Number.MAX_SAFE_INTEGER) -
+ (entityOrder.get(right.entity) ?? Number.MAX_SAFE_INTEGER);
+ return entityDifference || left.id.localeCompare(right.id);
+};
+
+const dedupeKeys = (keys: FtsSearchDocumentKey[]) =>
+ [...new Map(keys.map((key) => [`${key.entity}:${key.id}`, key])).values()].sort(compareKeys);
+
+/**
+ * Canonical PostgreSQL → search projection builder.
+ *
+ * This repository is intentionally actor-agnostic: backfill, incremental sync, and reconciliation
+ * need the complete source-of-truth projection. Product reads must continue to use FtsSearchRepo,
+ * whose provider hydration reapplies authorization.
+ */
+export class FtsSearchDocumentBuilder {
+ constructor(private db: LobeChatDatabase) {}
+
+ async buildBatch(
+ entity: FtsSearchDocumentEntity,
+ { afterId, limit }: FtsSearchDocumentBatchOptions,
+ ): Promise<FtsSearchBuiltDocument[]> {
+ if (!Number.isInteger(limit) || limit < 1) {
+ throw new Error('FTS search document batch limit must be a positive integer');
+ }
+
+ return this.build(entity, { afterId, limit });
+ }
+
+ async buildByIds(
+ entity: FtsSearchDocumentEntity,
+ sourceIds: readonly string[],
+ ): Promise<FtsSearchBuiltDocument[]> {
+ const ids = normalizeIds(sourceIds);
+ if (ids.length === 0) return [];
+
+ return this.build(entity, { ids, limit: ids.length });
+ }
+
+ /**
+ * Keep these relation fanout rules aligned with the FTS search-sync trigger functions in the
+ * database migration. This method remains the application-side source for backfills and repair.
+ */
+ async resolveAffectedKeys(
+ change: FtsSearchDocumentRelationChange,
+ ): Promise<FtsSearchDocumentKey[]> {
+ if (change.relation === 'knowledgeBaseFiles') {
+ const fileIds = normalizeIds(change.fileIds);
+ if (fileIds.length === 0) return [];
+
+ const linkedDocuments = await this.db
+ .select({ id: documents.id })
+ .from(documents)
+ .where(inArray(documents.fileId, fileIds));
+
+ return dedupeKeys([
+ ...fileIds.map((id): FtsSearchDocumentKey => ({ entity: 'files', id })),
+ ...linkedDocuments.map(({ id }): FtsSearchDocumentKey => ({ entity: 'documents', id })),
+ ]);
+ }
+
+ const memoryIds = normalizeIds(change.memoryIds);
+ if (memoryIds.length === 0) return [];
+
+ const contextPredicates = memoryIds.map(
+ (memoryId) =>
+ sql`${userMemoriesContexts.userMemoryIds} @> ${JSON.stringify([memoryId])}::jsonb`,
+ );
+ const [contexts, preferences, activities, identities, experiences] = await Promise.all([
+ this.db
+ .select({ id: userMemoriesContexts.id })
+ .from(userMemoriesContexts)
+ .where(or(...contextPredicates)),
+ this.db
+ .select({ id: userMemoriesPreferences.id })
+ .from(userMemoriesPreferences)
+ .where(inArray(userMemoriesPreferences.userMemoryId, memoryIds)),
+ this.db
+ .select({ id: userMemoriesActivities.id })
+ .from(userMemoriesActivities)
+ .where(inArray(userMemoriesActivities.userMemoryId, memoryIds)),
+ this.db
+ .select({ id: userMemoriesIdentities.id })
+ .from(userMemoriesIdentities)
+ .where(inArray(userMemoriesIdentities.userMemoryId, memoryIds)),
+ this.db
+ .select({ id: userMemoriesExperiences.id })
+ .from(userMemoriesExperiences)
+ .where(inArray(userMemoriesExperiences.userMemoryId, memoryIds)),
+ ]);
+
+ return dedupeKeys([
+ ...memoryIds.map((id): FtsSearchDocumentKey => ({ entity: 'userMemories', id })),
+ ...contexts.map(({ id }): FtsSearchDocumentKey => ({ entity: 'memoryContexts', id })),
+ ...preferences.map(({ id }): FtsSearchDocumentKey => ({ entity: 'memoryPreferences', id })),
+ ...activities.map(({ id }): FtsSearchDocumentKey => ({ entity: 'memoryActivities', id })),
+ ...identities.map(({ id }): FtsSearchDocumentKey => ({ entity: 'memoryIdentities', id })),
+ ...experiences.map(({ id }): FtsSearchDocumentKey => ({ entity: 'memoryExperiences', id })),
+ ]);
+ }
+
+ private createDocument<Entity extends FtsSearchDocumentEntity>(
+ entity: Entity,
+ input: unknown,
+ ): Extract<FtsSearchBuiltDocument, { entity: Entity }> {
+ const source = parseFtsSearchDocumentSource(entity, input);
+ return { entity, id: source.id, source } as Extract<FtsSearchBuiltDocument, { entity: Entity }>;
+ }
+
+ private async build(
+ entity: FtsSearchDocumentEntity,
+ selection: FtsSearchDocumentSelection,
+ ): Promise<FtsSearchBuiltDocument[]> {
+ switch (entity) {
+ case 'agents': {
+ return this.buildAgents(selection);
+ }
+ case 'topics': {
+ return this.buildTopics(selection);
+ }
+ case 'files': {
+ return this.buildFiles(selection);
+ }
+ case 'knowledgeBases': {
+ return this.buildKnowledgeBases(selection);
+ }
+ case 'userMemories': {
+ return this.buildUserMemories(selection);
+ }
+ case 'chatGroups': {
+ return this.buildChatGroups(selection);
+ }
+ case 'memoryContexts': {
+ return this.buildMemoryContexts(selection);
+ }
+ case 'memoryPreferences': {
+ return this.buildMemoryPreferences(selection);
+ }
+ case 'memoryActivities': {
+ return this.buildMemoryActivities(selection);
+ }
+ case 'memoryIdentities': {
+ return this.buildMemoryIdentities(selection);
+ }
+ case 'memoryExperiences': {
+ return this.buildMemoryExperiences(selection);
+ }
+ case 'personaDocuments': {
+ return this.buildPersonaDocuments(selection);
+ }
+ case 'documents': {
+ return this.buildDocuments(selection);
+ }
+ case 'messages': {
+ return this.buildMessages(selection);
+ }
+ }
+ }
+
+ private async buildAgents(selection: FtsSearchDocumentSelection) {
+ const rows = await this.db
+ .select({
+ createdAt: agents.createdAt,
+ description: agents.description,
+ id: agents.id,
+ slug: agents.slug,
+ systemRole: agents.systemRole,
+ tags: agents.tags,
+ title: agents.title,
+ updatedAt: agents.updatedAt,
+ userId: agents.userId,
+ virtual: agents.virtual,
+ visibility: agents.visibility,
+ workspaceId: agents.workspaceId,
+ })
+ .from(agents)
+ .where(
+ selection.ids
+ ? inArray(agents.id, selection.ids)
+ : selection.afterId
+ ? gt(agents.id, selection.afterId)
+ : undefined,
+ )
+ .orderBy(asc(agents.id))
+ .limit(selection.limit);
+
+ return rows.map((row) =>
+ this.createDocument('agents', {
+ created_at: toDateTime(row.createdAt),
+ description: row.description,
+ id: row.id,
+ slug: row.slug,
+ system_role: row.systemRole,
+ tags: normalizeStringArray(row.tags),
+ title: row.title,
+ updated_at: toDateTime(row.updatedAt),
+ user_id: row.userId,
+ virtual: row.virtual,
+ visibility: row.visibility,
+ workspace_id: row.workspaceId,
+ }),
+ );
+ }
+
+ private async buildTopics(selection: FtsSearchDocumentSelection) {
+ const rows = await this.db
+ .select({
+ agentId: topics.agentId,
+ content: topics.content,
+ createdAt: topics.createdAt,
+ description: topics.description,
+ groupId: topics.groupId,
+ id: topics.id,
+ sessionId: topics.sessionId,
+ status: topics.status,
+ title: topics.title,
+ updatedAt: topics.updatedAt,
+ userId: topics.userId,
+ workspaceId: topics.workspaceId,
+ })
+ .from(topics)
+ .where(
+ selection.ids
+ ? inArray(topics.id, selection.ids)
+ : selection.afterId
+ ? gt(topics.id, selection.afterId)
+ : undefined,
+ )
+ .orderBy(asc(topics.id))
+ .limit(selection.limit);
+
+ return rows.map((row) =>
+ this.createDocument('topics', {
+ agent_id: row.agentId,
+ content: row.content,
+ created_at: toDateTime(row.createdAt),
+ description: row.description,
+ group_id: row.groupId,
+ id: row.id,
+ session_id: row.sessionId,
+ status: row.status,
+ title: row.title,
+ updated_at: toDateTime(row.updatedAt),
+ user_id: row.userId,
+ workspace_id: row.workspaceId,
+ }),
+ );
+ }
+
+ private async buildFiles(selection: FtsSearchDocumentSelection) {
+ const rows = await this.db
+ .select({
+ createdAt: files.createdAt,
+ fileType: files.fileType,
+ id: files.id,
+ name: files.name,
+ size: files.size,
+ source: files.source,
+ updatedAt: files.updatedAt,
+ userId: files.userId,
+ visibility: files.visibility,
+ workspaceId: files.workspaceId,
+ })
+ .from(files)
+ .where(
+ selection.ids
+ ? inArray(files.id, selection.ids)
+ : selection.afterId
+ ? gt(files.id, selection.afterId)
+ : undefined,
+ )
+ .orderBy(asc(files.id))
+ .limit(selection.limit);
+
+ const fileIds = rows.map(({ id }) => id);
+ const relations =
+ fileIds.length === 0
+ ? []
+ : await this.db
+ .select({
+ fileId: knowledgeBaseFiles.fileId,
+ knowledgeBaseId: knowledgeBaseFiles.knowledgeBaseId,
+ })
+ .from(knowledgeBaseFiles)
+ .where(inArray(knowledgeBaseFiles.fileId, fileIds));
+ const knowledgeBaseIds = groupKnowledgeBaseIds(relations);
+
+ return rows.map((row) =>
+ this.createDocument('files', {
+ created_at: toDateTime(row.createdAt),
+ file_type: row.fileType,
+ id: row.id,
+ knowledge_base_ids: knowledgeBaseIds.get(row.id) ?? [],
+ name: row.name,
+ size: row.size,
+ source: row.source,
+ updated_at: toDateTime(row.updatedAt),
+ user_id: row.userId,
+ visibility: row.visibility,
+ workspace_id: row.workspaceId,
+ }),
+ );
+ }
+
+ private async buildKnowledgeBases(selection: FtsSearchDocumentSelection) {
+ const rows = await this.db
+ .select({
+ createdAt: knowledgeBases.createdAt,
+ description: knowledgeBases.description,
+ id: knowledgeBases.id,
+ isPublic: knowledgeBases.isPublic,
+ name: knowledgeBases.name,
+ type: knowledgeBases.type,
+ updatedAt: knowledgeBases.updatedAt,
+ userId: knowledgeBases.userId,
+ visibility: knowledgeBases.visibility,
+ workspaceId: knowledgeBases.workspaceId,
+ })
+ .from(knowledgeBases)
+ .where(
+ selection.ids
+ ? inArray(knowledgeBases.id, selection.ids)
+ : selection.afterId
+ ? gt(knowledgeBases.id, selection.afterId)
+ : undefined,
+ )
+ .orderBy(asc(knowledgeBases.id))
+ .limit(selection.limit);
+
+ return rows.map((row) =>
+ this.createDocument('knowledgeBases', {
+ created_at: toDateTime(row.createdAt),
+ description: row.description,
+ id: row.id,
+ is_public: row.isPublic,
+ name: row.name,
+ type: row.type,
+ updated_at: toDateTime(row.updatedAt),
+ user_id: row.userId,
+ visibility: row.visibility,
+ workspace_id: row.workspaceId,
+ }),
+ );
+ }
+
+ private async buildUserMemories(selection: FtsSearchDocumentSelection) {
+ const rows = await this.db
+ .select({
+ capturedAt: userMemories.capturedAt,
+ createdAt: userMemories.createdAt,
+ details: userMemories.details,
+ id: userMemories.id,
+ memoryCategory: userMemories.memoryCategory,
+ memoryLayer: userMemories.memoryLayer,
+ status: userMemories.status,
+ summary: userMemories.summary,
+ tags: userMemories.tags,
+ title: userMemories.title,
+ updatedAt: userMemories.updatedAt,
+ userId: userMemories.userId,
+ })
+ .from(userMemories)
+ .where(
+ selection.ids
+ ? inArray(userMemories.id, selection.ids)
+ : selection.afterId
+ ? gt(userMemories.id, selection.afterId)
+ : undefined,
+ )
+ .orderBy(asc(userMemories.id))
+ .limit(selection.limit);
+
+ return rows.map((row) =>
+ this.createDocument('userMemories', {
+ captured_at: toDateTime(row.capturedAt),
+ created_at: toDateTime(row.createdAt),
+ details: row.details,
+ id: row.id,
+ memory_category: row.memoryCategory,
+ memory_layer: row.memoryLayer,
+ status: row.status,
+ summary: row.summary,
+ tags: normalizeStringArray(row.tags),
+ title: row.title,
+ updated_at: toDateTime(row.updatedAt),
+ user_id: row.userId,
+ }),
+ );
+ }
+
+ private async buildChatGroups(selection: FtsSearchDocumentSelection) {
+ const rows = await this.db
+ .select({
+ content: chatGroups.content,
+ createdAt: chatGroups.createdAt,
+ description: chatGroups.description,
+ groupId: chatGroups.groupId,
+ id: chatGroups.id,
+ title: chatGroups.title,
+ updatedAt: chatGroups.updatedAt,
+ userId: chatGroups.userId,
+ visibility: chatGroups.visibility,
+ workspaceId: chatGroups.workspaceId,
+ })
+ .from(chatGroups)
+ .where(
+ selection.ids
+ ? inArray(chatGroups.id, selection.ids)
+ : selection.afterId
+ ? gt(chatGroups.id, selection.afterId)
+ : undefined,
+ )
+ .orderBy(asc(chatGroups.id))
+ .limit(selection.limit);
+
+ return rows.map((row) =>
+ this.createDocument('chatGroups', {
+ content: row.content,
+ created_at: toDateTime(row.createdAt),
+ description: row.description,
+ group_id: row.groupId,
+ id: row.id,
+ title: row.title,
+ updated_at: toDateTime(row.updatedAt),
+ user_id: row.userId,
+ visibility: row.visibility,
+ workspace_id: row.workspaceId,
+ }),
+ );
+ }
+
+ private async buildMemoryContexts(selection: FtsSearchDocumentSelection) {
+ const rows = await this.db
+ .select({
+ capturedAt: userMemoriesContexts.capturedAt,
+ createdAt: userMemoriesContexts.createdAt,
+ currentStatus: userMemoriesContexts.currentStatus,
+ description: userMemoriesContexts.description,
+ id: userMemoriesContexts.id,
+ tags: userMemoriesContexts.tags,
+ title: userMemoriesContexts.title,
+ type: userMemoriesContexts.type,
+ updatedAt: userMemoriesContexts.updatedAt,
+ userId: userMemoriesContexts.userId,
+ userMemoryIds: userMemoriesContexts.userMemoryIds,
+ })
+ .from(userMemoriesContexts)
+ .where(
+ selection.ids
+ ? inArray(userMemoriesContexts.id, selection.ids)
+ : selection.afterId
+ ? gt(userMemoriesContexts.id, selection.afterId)
+ : undefined,
+ )
+ .orderBy(asc(userMemoriesContexts.id))
+ .limit(selection.limit);
+
+ const parentIds = normalizeIds(rows.flatMap(({ userMemoryIds }) => userMemoryIds ?? []));
+ const parents =
+ parentIds.length === 0
+ ? []
+ : await this.db
+ .select({
+ details: userMemories.details,
+ id: userMemories.id,
+ memoryCategory: userMemories.memoryCategory,
+ summary: userMemories.summary,
+ tags: userMemories.tags,
+ title: userMemories.title,
+ userId: userMemories.userId,
+ })
+ .from(userMemories)
+ .where(inArray(userMemories.id, parentIds));
+ const parentById = new Map(parents.map((parent) => [parent.id, parent]));
+
+ return rows.map((row) => {
+ const userMemoryIds = normalizeIds(row.userMemoryIds ?? []);
+ const matchedParents = userMemoryIds.flatMap((id) => {
+ const parent = parentById.get(id);
+ return parent && parent.userId === row.userId ? [parent] : [];
+ });
+ const parentText = userMemoryIds.flatMap((id) => {
+ const parent = parentById.get(id);
+ if (!parent || parent.userId !== row.userId) return [];
+ return [
+ [parent.title, parent.summary, parent.details]
+ .filter((value) => value !== null)
+ .join(' '),
+ ];
+ });
+
+ return this.createDocument('memoryContexts', {
+ captured_at: toDateTime(row.capturedAt),
+ created_at: toDateTime(row.createdAt),
+ current_status: row.currentStatus,
+ description: row.description,
+ id: row.id,
+ parent_memory_categories: normalizeStringArray(
+ matchedParents.flatMap(({ memoryCategory }) => (memoryCategory ? [memoryCategory] : [])),
+ ),
+ parent_tags: normalizeStringArray(matchedParents.flatMap(({ tags }) => tags ?? [])),
+ parent_text: parentText,
+ tags: normalizeStringArray(row.tags),
+ title: row.title,
+ type: row.type,
+ updated_at: toDateTime(row.updatedAt),
+ user_id: row.userId,
+ user_memory_ids: userMemoryIds,
+ });
+ });
+ }
+
+ private async buildMemoryPreferences(selection: FtsSearchDocumentSelection) {
+ const rows = await this.db
+ .select({
+ capturedAt: userMemoriesPreferences.capturedAt,
+ conclusionDirectives: userMemoriesPreferences.conclusionDirectives,
+ createdAt: userMemoriesPreferences.createdAt,
+ id: userMemoriesPreferences.id,
+ parentMemoryCategory: userMemories.memoryCategory,
+ parentDetails: userMemories.details,
+ parentSummary: userMemories.summary,
+ parentTags: userMemories.tags,
+ parentTitle: userMemories.title,
+ suggestions: userMemoriesPreferences.suggestions,
+ tags: userMemoriesPreferences.tags,
+ type: userMemoriesPreferences.type,
+ updatedAt: userMemoriesPreferences.updatedAt,
+ userId: userMemoriesPreferences.userId,
+ userMemoryId: userMemoriesPreferences.userMemoryId,
+ })
+ .from(userMemoriesPreferences)
+ .leftJoin(
+ userMemories,
+ and(
+ eq(userMemories.id, userMemoriesPreferences.userMemoryId),
+ eq(userMemories.userId, userMemoriesPreferences.userId),
+ ),
+ )
+ .where(
+ selection.ids
+ ? inArray(userMemoriesPreferences.id, selection.ids)
+ : selection.afterId
+ ? gt(userMemoriesPreferences.id, selection.afterId)
+ : undefined,
+ )
+ .orderBy(asc(userMemoriesPreferences.id))
+ .limit(selection.limit);
+
+ return rows.map((row) =>
+ this.createDocument('memoryPreferences', {
+ captured_at: toDateTime(row.capturedAt),
+ conclusion_directives: row.conclusionDirectives,
+ created_at: toDateTime(row.createdAt),
+ id: row.id,
+ parent_details: row.parentDetails,
+ parent_memory_categories: normalizeStringArray(row.parentMemoryCategory),
+ parent_summary: row.parentSummary,
+ parent_tags: normalizeStringArray(row.parentTags),
+ parent_title: row.parentTitle,
+ suggestions: row.suggestions,
+ tags: normalizeStringArray(row.tags),
+ type: row.type,
+ updated_at: toDateTime(row.updatedAt),
+ user_id: row.userId,
+ user_memory_id: row.userMemoryId,
+ }),
+ );
+ }
+
+ private async buildMemoryActivities(selection: FtsSearchDocumentSelection) {
+ const rows = await this.db
+ .select({
+ capturedAt: userMemoriesActivities.capturedAt,
+ createdAt: userMemoriesActivities.createdAt,
+ endsAt: userMemoriesActivities.endsAt,
+ feedback: userMemoriesActivities.feedback,
+ id: userMemoriesActivities.id,
+ narrative: userMemoriesActivities.narrative,
+ notes: userMemoriesActivities.notes,
+ parentMemoryCategory: userMemories.memoryCategory,
+ parentDetails: userMemories.details,
+ parentSummary: userMemories.summary,
+ parentTags: userMemories.tags,
+ parentTitle: userMemories.title,
+ startsAt: userMemoriesActivities.startsAt,
+ status: userMemoriesActivities.status,
+ tags: userMemoriesActivities.tags,
+ type: userMemoriesActivities.type,
+ updatedAt: userMemoriesActivities.updatedAt,
+ userId: userMemoriesActivities.userId,
+ userMemoryId: userMemoriesActivities.userMemoryId,
+ })
+ .from(userMemoriesActivities)
+ .leftJoin(
+ userMemories,
+ and(
+ eq(userMemories.id, userMemoriesActivities.userMemoryId),
+ eq(userMemories.userId, userMemoriesActivities.userId),
+ ),
+ )
+ .where(
+ selection.ids
+ ? inArray(userMemoriesActivities.id, selection.ids)
+ : selection.afterId
+ ? gt(userMemoriesActivities.id, selection.afterId)
+ : undefined,
+ )
+ .orderBy(asc(userMemoriesActivities.id))
+ .limit(selection.limit);
+
+ return rows.map((row) =>
+ this.createDocument('memoryActivities', {
+ captured_at: toDateTime(row.capturedAt),
+ created_at: toDateTime(row.createdAt),
+ ends_at: toNullableDateTime(row.endsAt),
+ feedback: row.feedback,
+ id: row.id,
+ narrative: row.narrative,
+ notes: row.notes,
+ parent_details: row.parentDetails,
+ parent_memory_categories: normalizeStringArray(row.parentMemoryCategory),
+ parent_summary: row.parentSummary,
+ parent_tags: normalizeStringArray(row.parentTags),
+ parent_title: row.parentTitle,
+ starts_at: toNullableDateTime(row.startsAt),
+ status: row.status,
+ tags: normalizeStringArray(row.tags),
+ type: row.type,
+ updated_at: toDateTime(row.updatedAt),
+ user_id: row.userId,
+ user_memory_id: row.userMemoryId,
+ }),
+ );
+ }
+
+ private async buildMemoryIdentities(selection: FtsSearchDocumentSelection) {
+ const rows = await this.db
+ .select({
+ capturedAt: userMemoriesIdentities.capturedAt,
+ createdAt: userMemoriesIdentities.createdAt,
+ description: userMemoriesIdentities.description,
+ episodicDate: userMemoriesIdentities.episodicDate,
+ id: userMemoriesIdentities.id,
+ parentMemoryCategory: userMemories.memoryCategory,
+ parentDetails: userMemories.details,
+ parentSummary: userMemories.summary,
+ parentTags: userMemories.tags,
+ parentTitle: userMemories.title,
+ relationship: userMemoriesIdentities.relationship,
+ role: userMemoriesIdentities.role,
+ tags: userMemoriesIdentities.tags,
+ type: userMemoriesIdentities.type,
+ updatedAt: userMemoriesIdentities.updatedAt,
+ userId: userMemoriesIdentities.userId,
+ userMemoryId: userMemoriesIdentities.userMemoryId,
+ })
+ .from(userMemoriesIdentities)
+ .leftJoin(
+ userMemories,
+ and(
+ eq(userMemories.id, userMemoriesIdentities.userMemoryId),
+ eq(userMemories.userId, userMemoriesIdentities.userId),
+ ),
+ )
+ .where(
+ selection.ids
+ ? inArray(userMemoriesIdentities.id, selection.ids)
+ : selection.afterId
+ ? gt(userMemoriesIdentities.id, selection.afterId)
+ : undefined,
+ )
+ .orderBy(asc(userMemoriesIdentities.id))
+ .limit(selection.limit);
+
+ return rows.map((row) =>
+ this.createDocument('memoryIdentities', {
+ captured_at: toDateTime(row.capturedAt),
+ created_at: toDateTime(row.createdAt),
+ description: row.description,
+ episodic_date: toNullableDateTime(row.episodicDate),
+ id: row.id,
+ parent_details: row.parentDetails,
+ parent_memory_categories: normalizeStringArray(row.parentMemoryCategory),
+ parent_summary: row.parentSummary,
+ parent_tags: normalizeStringArray(row.parentTags),
+ parent_title: row.parentTitle,
+ relationship: row.relationship,
+ role: row.role,
+ tags: normalizeStringArray(row.tags),
+ type: row.type,
+ updated_at: toDateTime(row.updatedAt),
+ user_id: row.userId,
+ user_memory_id: row.userMemoryId,
+ }),
+ );
+ }
+
+ private async buildMemoryExperiences(selection: FtsSearchDocumentSelection) {
+ const rows = await this.db
+ .select({
+ action: userMemoriesExperiences.action,
+ capturedAt: userMemoriesExperiences.capturedAt,
+ createdAt: userMemoriesExperiences.createdAt,
+ id: userMemoriesExperiences.id,
+ keyLearning: userMemoriesExperiences.keyLearning,
+ parentMemoryCategory: userMemories.memoryCategory,
+ parentDetails: userMemories.details,
+ parentSummary: userMemories.summary,
+ parentTags: userMemories.tags,
+ parentTitle: userMemories.title,
+ possibleOutcome: userMemoriesExperiences.possibleOutcome,
+ reasoning: userMemoriesExperiences.reasoning,
+ situation: userMemoriesExperiences.situation,
+ tags: userMemoriesExperiences.tags,
+ type: userMemoriesExperiences.type,
+ updatedAt: userMemoriesExperiences.updatedAt,
+ userId: userMemoriesExperiences.userId,
+ userMemoryId: userMemoriesExperiences.userMemoryId,
+ })
+ .from(userMemoriesExperiences)
+ .leftJoin(
+ userMemories,
+ and(
+ eq(userMemories.id, userMemoriesExperiences.userMemoryId),
+ eq(userMemories.userId, userMemoriesExperiences.userId),
+ ),
+ )
+ .where(
+ selection.ids
+ ? inArray(userMemoriesExperiences.id, selection.ids)
+ : selection.afterId
+ ? gt(userMemoriesExperiences.id, selection.afterId)
+ : undefined,
+ )
+ .orderBy(asc(userMemoriesExperiences.id))
+ .limit(selection.limit);
+
+ return rows.map((row) =>
+ this.createDocument('memoryExperiences', {
+ action: row.action,
+ captured_at: toDateTime(row.capturedAt),
+ created_at: toDateTime(row.createdAt),
+ id: row.id,
+ key_learning: row.keyLearning,
+ parent_details: row.parentDetails,
+ parent_memory_categories: normalizeStringArray(row.parentMemoryCategory),
+ parent_summary: row.parentSummary,
+ parent_tags: normalizeStringArray(row.parentTags),
+ parent_title: row.parentTitle,
+ possible_outcome: row.possibleOutcome,
+ reasoning: row.reasoning,
+ situation: row.situation,
+ tags: normalizeStringArray(row.tags),
+ type: row.type,
+ updated_at: toDateTime(row.updatedAt),
+ user_id: row.userId,
+ user_memory_id: row.userMemoryId,
+ }),
+ );
+ }
+
+ private async buildPersonaDocuments(selection: FtsSearchDocumentSelection) {
+ const rows = await this.db
+ .select({
+ capturedAt: userPersonaDocuments.capturedAt,
+ createdAt: userPersonaDocuments.createdAt,
+ id: userPersonaDocuments.id,
+ persona: userPersonaDocuments.persona,
+ profile: userPersonaDocuments.profile,
+ tagline: userPersonaDocuments.tagline,
+ updatedAt: userPersonaDocuments.updatedAt,
+ userId: userPersonaDocuments.userId,
+ version: userPersonaDocuments.version,
+ })
+ .from(userPersonaDocuments)
+ .where(
+ selection.ids
+ ? inArray(userPersonaDocuments.id, selection.ids)
+ : selection.afterId
+ ? gt(userPersonaDocuments.id, selection.afterId)
+ : undefined,
+ )
+ .orderBy(asc(userPersonaDocuments.id))
+ .limit(selection.limit);
+
+ return rows.map((row) =>
+ this.createDocument('personaDocuments', {
+ captured_at: toDateTime(row.capturedAt),
+ created_at: toDateTime(row.createdAt),
+ id: row.id,
+ persona: row.persona,
+ profile: row.profile,
+ tagline: row.tagline,
+ updated_at: toDateTime(row.updatedAt),
+ user_id: row.userId,
+ version: row.version,
+ }),
+ );
+ }
+
+ private async buildDocuments(selection: FtsSearchDocumentSelection) {
+ const rows = await this.db
+ .select({
+ content: documents.content,
+ createdAt: documents.createdAt,
+ description: documents.description,
+ fileId: documents.fileId,
+ fileType: documents.fileType,
+ id: documents.id,
+ knowledgeBaseId: documents.knowledgeBaseId,
+ parentId: documents.parentId,
+ slug: documents.slug,
+ sourceType: documents.sourceType,
+ title: documents.title,
+ totalCharCount: documents.totalCharCount,
+ updatedAt: documents.updatedAt,
+ userId: documents.userId,
+ visibility: documents.visibility,
+ workspaceId: documents.workspaceId,
+ })
+ .from(documents)
+ .where(
+ selection.ids
+ ? inArray(documents.id, selection.ids)
+ : selection.afterId
+ ? gt(documents.id, selection.afterId)
+ : undefined,
+ )
+ .orderBy(asc(documents.id))
+ .limit(selection.limit);
+
+ const fileIds = normalizeIds(rows.flatMap(({ fileId }) => (fileId ? [fileId] : [])));
+ const relations =
+ fileIds.length === 0
+ ? []
+ : await this.db
+ .select({
+ fileId: knowledgeBaseFiles.fileId,
+ knowledgeBaseId: knowledgeBaseFiles.knowledgeBaseId,
+ })
+ .from(knowledgeBaseFiles)
+ .where(inArray(knowledgeBaseFiles.fileId, fileIds));
+ const knowledgeBaseIdsByFile = groupKnowledgeBaseIds(relations);
+
+ return rows.map((row) => {
+ const knowledgeBaseIds = new Set<string>();
+ if (row.knowledgeBaseId) knowledgeBaseIds.add(row.knowledgeBaseId);
+ if (row.fileId) {
+ for (const knowledgeBaseId of knowledgeBaseIdsByFile.get(row.fileId) ?? []) {
+ knowledgeBaseIds.add(knowledgeBaseId);
+ }
+ }
+
+ return this.createDocument('documents', {
+ content: row.content,
+ created_at: toDateTime(row.createdAt),
+ description: row.description,
+ file_id: row.fileId,
+ file_type: row.fileType,
+ id: row.id,
+ knowledge_base_id: row.knowledgeBaseId,
+ knowledge_base_ids: [...knowledgeBaseIds].sort(),
+ parent_id: row.parentId,
+ slug: row.slug,
+ source_type: row.sourceType,
+ title: row.title,
+ total_char_count: row.totalCharCount,
+ updated_at: toDateTime(row.updatedAt),
+ user_id: row.userId,
+ visibility: row.visibility,
+ workspace_id: row.workspaceId,
+ });
+ });
+ }
+
+ private async buildMessages(selection: FtsSearchDocumentSelection) {
+ const rows = await this.db
+ .select({
+ agentId: messages.agentId,
+ content: messages.content,
+ createdAt: messages.createdAt,
+ groupId: messages.groupId,
+ id: messages.id,
+ role: messages.role,
+ sessionId: messages.sessionId,
+ summary: messages.summary,
+ threadId: messages.threadId,
+ topicId: messages.topicId,
+ updatedAt: messages.updatedAt,
+ userId: messages.userId,
+ workspaceId: messages.workspaceId,
+ })
+ .from(messages)
+ .where(
+ selection.ids
+ ? inArray(messages.id, selection.ids)
+ : selection.afterId
+ ? gt(messages.id, selection.afterId)
+ : undefined,
+ )
+ .orderBy(asc(messages.id))
+ .limit(selection.limit);
+
+ return rows.map((row) =>
+ this.createDocument('messages', {
+ agent_id: row.agentId,
+ content: row.content,
+ created_at: toDateTime(row.createdAt),
+ group_id: row.groupId,
+ id: row.id,
+ role: row.role,
+ session_id: row.sessionId,
+ summary: row.summary,
+ thread_id: row.threadId,
+ topic_id: row.topicId,
+ updated_at: toDateTime(row.updatedAt),
+ user_id: row.userId,
+ workspace_id: row.workspaceId,
+ }),
+ );
+ }
+}
+
+export type FtsSearchDocumentFor<Entity extends FtsSearchDocumentEntity> = Extract<
+ FtsSearchBuiltDocument,
+ { entity: Entity; source: FtsSearchDocumentSourceMap[Entity] }
+>;
diff --git a/packages/database/src/repositories/ftsSearchDocument/index.ts b/packages/database/src/repositories/ftsSearchDocument/index.ts
new file mode 100644
index 00000000000..c175f306ff5
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/index.ts
@@ -0,0 +1,3 @@
+export * from './builder';
+export * from './mappings';
+export * from './schema';
diff --git a/packages/database/src/repositories/ftsSearchDocument/mappings.test.ts b/packages/database/src/repositories/ftsSearchDocument/mappings.test.ts
new file mode 100644
index 00000000000..f9b4ad493e2
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/mappings.test.ts
@@ -0,0 +1,128 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ FTS_SEARCH_INDEX_ANALYSIS,
+ FTS_SEARCH_INDEX_DEFINITIONS,
+ FTS_SEARCH_INDEX_SCHEMA_VERSION,
+ getFtsSearchIndexAlias,
+ getFtsSearchPhysicalIndexName,
+} from './mappings';
+import {
+ FTS_SEARCH_DOCUMENT_ENTITIES,
+ FTS_SEARCH_DOCUMENT_SCHEMAS,
+ FTS_SEARCH_MEMORY_DOCUMENT_ENTITIES,
+} from './schema';
+
+describe('search index mappings', () => {
+ it.each(FTS_SEARCH_DOCUMENT_ENTITIES)('matches every %s schema field exactly', (entity) => {
+ const schemaFields = Object.keys(FTS_SEARCH_DOCUMENT_SCHEMAS[entity].shape).sort();
+ const mappingFields = Object.keys(
+ FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings.properties,
+ ).sort();
+
+ expect(mappingFields).toEqual(schemaFields);
+ expect(FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings.dynamic).toBe('strict');
+ });
+
+ it.each(FTS_SEARCH_DOCUMENT_ENTITIES)('only queries text fields for %s', (entity) => {
+ const definition = FTS_SEARCH_INDEX_DEFINITIONS[entity];
+
+ for (const field of definition.queryFields) {
+ expect(Object.entries(definition.mappings.properties)).toContainEqual([
+ field,
+ expect.objectContaining({ type: 'text' }),
+ ]);
+ }
+ });
+
+ it('includes the conversation fields used by the formal Elasticsearch provider', () => {
+ expect(FTS_SEARCH_INDEX_DEFINITIONS.chatGroups.queryFields).toEqual([
+ 'title',
+ 'description',
+ 'content',
+ ]);
+ expect(FTS_SEARCH_INDEX_DEFINITIONS.messages.queryFields).toEqual(['content', 'summary']);
+ });
+
+ it('provides deployment-neutral versioned alias and physical names', () => {
+ expect(FTS_SEARCH_INDEX_SCHEMA_VERSION).toBe(1);
+ expect(getFtsSearchIndexAlias('lobehub-dev', 'knowledgeBases')).toBe(
+ 'lobehub-dev-knowledge-bases',
+ );
+ expect(getFtsSearchPhysicalIndexName('lobehub-dev', 'knowledgeBases')).toBe(
+ 'lobehub-dev-knowledge-bases-v1',
+ );
+ expect(getFtsSearchPhysicalIndexName('lobehub-dev', 'knowledgeBases', 4)).toBe(
+ 'lobehub-dev-knowledge-bases-v4',
+ );
+ });
+
+ it.each(FTS_SEARCH_DOCUMENT_ENTITIES)('maps the soft-delete marker for %s', (entity) => {
+ expect(
+ FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings.properties.fts_search_sync_deleted,
+ ).toEqual({
+ type: 'boolean',
+ });
+ });
+
+ it('keeps analyzer names generic for OSS deployments', () => {
+ expect(Object.keys(FTS_SEARCH_INDEX_ANALYSIS.analyzer)).toEqual([
+ 'lobehub_cjk_bigram_english',
+ 'lobehub_filename',
+ 'lobehub_icu',
+ 'lobehub_icu_english',
+ ]);
+ });
+
+ it('splits file names on common separators while preserving an exact field', () => {
+ expect(FTS_SEARCH_INDEX_ANALYSIS.tokenizer.lobehub_filename).toEqual({
+ tokenize_on_chars: ['whitespace', '-', '_', '/', '.'],
+ type: 'char_group',
+ });
+ expect(FTS_SEARCH_INDEX_DEFINITIONS.files.mappings.properties.name).toEqual({
+ analyzer: 'lobehub_filename',
+ fields: {
+ raw: { ignore_above: 256, type: 'keyword' },
+ words: { analyzer: 'lobehub_icu', type: 'text' },
+ },
+ type: 'text',
+ });
+ });
+
+ it('bounds exact-match multi-fields so long text cannot fail keyword indexing', () => {
+ const rawFields = Object.values(FTS_SEARCH_INDEX_DEFINITIONS).flatMap(({ mappings }) =>
+ Object.values(mappings.properties)
+ .map(({ fields }) => fields?.raw)
+ .filter(Boolean),
+ );
+
+ expect(rawFields.length).toBeGreaterThan(0);
+ for (const rawField of rawFields) {
+ expect(rawField).toEqual(expect.objectContaining({ ignore_above: 256, type: 'keyword' }));
+ }
+ });
+
+ it('normalizes memory text before generating CJK bigrams', () => {
+ expect(FTS_SEARCH_INDEX_ANALYSIS.analyzer.lobehub_cjk_bigram_english.filter).toEqual([
+ 'english_possessive_stemmer',
+ 'icu_folding',
+ 'cjk_bigram',
+ 'english_stop',
+ 'english_stemmer',
+ ]);
+
+ for (const entity of FTS_SEARCH_MEMORY_DOCUMENT_ENTITIES) {
+ const definition = FTS_SEARCH_INDEX_DEFINITIONS[entity];
+ for (const field of definition.queryFields) {
+ expect(Object.entries(definition.mappings.properties)).toContainEqual([
+ field,
+ expect.objectContaining({ analyzer: 'lobehub_cjk_bigram_english' }),
+ ]);
+ }
+ }
+
+ expect(FTS_SEARCH_INDEX_DEFINITIONS.documents.mappings.properties.content).toEqual(
+ expect.objectContaining({ analyzer: 'lobehub_icu_english' }),
+ );
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearchDocument/mappings.ts b/packages/database/src/repositories/ftsSearchDocument/mappings.ts
new file mode 100644
index 00000000000..9ce9b08fdc8
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/mappings.ts
@@ -0,0 +1,465 @@
+import type { FtsSearchDocumentEntity, FtsSearchDocumentSourceMap } from './schema';
+
+export type ElasticsearchFtsSearchFieldType = 'boolean' | 'date' | 'integer' | 'keyword' | 'text';
+
+export interface ElasticsearchFtsSearchMappingProperty {
+ analyzer?: string;
+ fields?: Record<string, ElasticsearchFtsSearchMappingProperty>;
+ ignore_above?: number;
+ type: ElasticsearchFtsSearchFieldType;
+}
+
+export interface FtsSearchIndexDefinition<Entity extends FtsSearchDocumentEntity> {
+ indexedOnlyFields?: readonly (keyof FtsSearchDocumentSourceMap[Entity] & string)[];
+ longTextFields?: readonly (keyof FtsSearchDocumentSourceMap[Entity] & string)[];
+ mappings: {
+ dynamic: 'strict';
+ properties: Record<
+ keyof FtsSearchDocumentSourceMap[Entity] & string,
+ ElasticsearchFtsSearchMappingProperty
+ >;
+ };
+ queryFields: readonly (keyof FtsSearchDocumentSourceMap[Entity] & string)[];
+}
+
+const mixedText = { analyzer: 'lobehub_icu_english', type: 'text' } as const;
+const memoryText = { analyzer: 'lobehub_cjk_bigram_english', type: 'text' } as const;
+const memoryTextWithRaw = {
+ analyzer: 'lobehub_cjk_bigram_english',
+ fields: { raw: { ignore_above: 256, type: 'keyword' } },
+ type: 'text',
+} as const;
+const fileNameText = {
+ analyzer: 'lobehub_filename',
+ fields: {
+ raw: { ignore_above: 256, type: 'keyword' },
+ words: { analyzer: 'lobehub_icu', type: 'text' },
+ },
+ type: 'text',
+} as const;
+const icuText = {
+ analyzer: 'lobehub_icu',
+ fields: { raw: { ignore_above: 256, type: 'keyword' } },
+ type: 'text',
+} as const;
+const keyword = { type: 'keyword' } as const;
+const date = { type: 'date' } as const;
+const integer = { type: 'integer' } as const;
+const boolean = { type: 'boolean' } as const;
+
+const ownershipProperties = {
+ user_id: keyword,
+ visibility: keyword,
+ workspace_id: keyword,
+};
+
+const timestampProperties = {
+ created_at: date,
+ updated_at: date,
+};
+
+const projectionMetadataProperties = {
+ fts_search_sync_deleted: boolean,
+};
+
+export const FTS_SEARCH_INDEX_ANALYSIS = {
+ analyzer: {
+ lobehub_cjk_bigram_english: {
+ /** Normalize width and case before generating CJK bigrams so decomposed characters stay intact. */
+ filter: [
+ 'english_possessive_stemmer',
+ 'icu_folding',
+ 'cjk_bigram',
+ 'english_stop',
+ 'english_stemmer',
+ ],
+ tokenizer: 'standard',
+ type: 'custom',
+ },
+ lobehub_filename: {
+ filter: ['icu_folding'],
+ tokenizer: 'lobehub_filename',
+ type: 'custom',
+ },
+ lobehub_icu: {
+ filter: ['icu_folding'],
+ tokenizer: 'icu_tokenizer',
+ type: 'custom',
+ },
+ lobehub_icu_english: {
+ filter: ['english_possessive_stemmer', 'icu_folding', 'english_stop', 'english_stemmer'],
+ tokenizer: 'icu_tokenizer',
+ type: 'custom',
+ },
+ },
+ filter: {
+ english_possessive_stemmer: {
+ language: 'possessive_english',
+ type: 'stemmer',
+ },
+ english_stemmer: {
+ language: 'english',
+ type: 'stemmer',
+ },
+ english_stop: {
+ stopwords: '_english_',
+ type: 'stop',
+ },
+ },
+ tokenizer: {
+ lobehub_filename: {
+ tokenize_on_chars: ['whitespace', '-', '_', '/', '.'],
+ type: 'char_group',
+ },
+ },
+} as const;
+
+export const FTS_SEARCH_INDEX_DEFINITIONS = {
+ agents: {
+ longTextFields: ['system_role'],
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...ownershipProperties,
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ description: mixedText,
+ id: keyword,
+ slug: icuText,
+ system_role: mixedText,
+ tags: icuText,
+ title: mixedText,
+ virtual: boolean,
+ },
+ },
+ queryFields: ['title', 'description', 'slug', 'tags', 'system_role'],
+ } satisfies FtsSearchIndexDefinition<'agents'>,
+ chatGroups: {
+ indexedOnlyFields: ['content'],
+ longTextFields: ['content'],
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...ownershipProperties,
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ content: mixedText,
+ description: mixedText,
+ group_id: keyword,
+ id: keyword,
+ title: mixedText,
+ },
+ },
+ queryFields: ['title', 'description', 'content'],
+ } satisfies FtsSearchIndexDefinition<'chatGroups'>,
+ documents: {
+ longTextFields: ['content'],
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...ownershipProperties,
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ content: mixedText,
+ description: mixedText,
+ file_id: keyword,
+ file_type: keyword,
+ id: keyword,
+ knowledge_base_id: keyword,
+ knowledge_base_ids: keyword,
+ parent_id: keyword,
+ slug: icuText,
+ source_type: keyword,
+ title: mixedText,
+ total_char_count: integer,
+ },
+ },
+ queryFields: ['title', 'slug', 'description', 'content'],
+ } satisfies FtsSearchIndexDefinition<'documents'>,
+ files: {
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...ownershipProperties,
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ file_type: keyword,
+ id: keyword,
+ knowledge_base_ids: keyword,
+ name: fileNameText,
+ size: integer,
+ source: keyword,
+ },
+ },
+ /** Provider-neutral source field; Elasticsearch-only multi-fields are selected by its backend. */
+ queryFields: ['name'],
+ } satisfies FtsSearchIndexDefinition<'files'>,
+ knowledgeBases: {
+ longTextFields: ['description'],
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...ownershipProperties,
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ description: mixedText,
+ id: keyword,
+ is_public: boolean,
+ name: icuText,
+ type: keyword,
+ },
+ },
+ queryFields: ['name', 'description'],
+ } satisfies FtsSearchIndexDefinition<'knowledgeBases'>,
+ memoryActivities: {
+ longTextFields: ['notes', 'narrative', 'feedback'],
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ captured_at: date,
+ ends_at: date,
+ feedback: memoryText,
+ id: keyword,
+ narrative: memoryText,
+ notes: memoryText,
+ parent_details: memoryText,
+ parent_memory_categories: keyword,
+ parent_summary: memoryText,
+ parent_tags: keyword,
+ parent_title: memoryText,
+ starts_at: date,
+ status: keyword,
+ tags: keyword,
+ type: keyword,
+ user_id: keyword,
+ user_memory_id: keyword,
+ },
+ },
+ queryFields: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'narrative',
+ 'notes',
+ 'feedback',
+ ],
+ } satisfies FtsSearchIndexDefinition<'memoryActivities'>,
+ memoryContexts: {
+ longTextFields: ['description', 'current_status'],
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ captured_at: date,
+ current_status: memoryTextWithRaw,
+ description: memoryText,
+ id: keyword,
+ parent_text: memoryText,
+ parent_memory_categories: keyword,
+ parent_tags: keyword,
+ tags: keyword,
+ title: memoryText,
+ type: keyword,
+ user_id: keyword,
+ user_memory_ids: keyword,
+ },
+ },
+ queryFields: ['parent_text', 'title', 'description', 'current_status'],
+ } satisfies FtsSearchIndexDefinition<'memoryContexts'>,
+ memoryExperiences: {
+ longTextFields: ['situation', 'reasoning', 'possible_outcome', 'action', 'key_learning'],
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ action: memoryText,
+ captured_at: date,
+ id: keyword,
+ key_learning: memoryText,
+ parent_details: memoryText,
+ parent_memory_categories: keyword,
+ parent_summary: memoryText,
+ parent_tags: keyword,
+ parent_title: memoryText,
+ possible_outcome: memoryText,
+ reasoning: memoryText,
+ situation: memoryText,
+ tags: keyword,
+ type: keyword,
+ user_id: keyword,
+ user_memory_id: keyword,
+ },
+ },
+ queryFields: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'situation',
+ 'reasoning',
+ 'possible_outcome',
+ 'action',
+ 'key_learning',
+ ],
+ } satisfies FtsSearchIndexDefinition<'memoryExperiences'>,
+ memoryIdentities: {
+ longTextFields: ['description', 'role'],
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ captured_at: date,
+ description: memoryText,
+ episodic_date: date,
+ id: keyword,
+ parent_details: memoryText,
+ parent_memory_categories: keyword,
+ parent_summary: memoryText,
+ parent_tags: keyword,
+ parent_title: memoryText,
+ relationship: keyword,
+ role: memoryText,
+ tags: keyword,
+ type: keyword,
+ user_id: keyword,
+ user_memory_id: keyword,
+ },
+ },
+ queryFields: ['parent_title', 'parent_summary', 'parent_details', 'description', 'role'],
+ } satisfies FtsSearchIndexDefinition<'memoryIdentities'>,
+ memoryPreferences: {
+ longTextFields: ['conclusion_directives', 'suggestions'],
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ captured_at: date,
+ conclusion_directives: memoryText,
+ id: keyword,
+ parent_details: memoryText,
+ parent_memory_categories: keyword,
+ parent_summary: memoryText,
+ parent_tags: keyword,
+ parent_title: memoryText,
+ suggestions: memoryText,
+ tags: keyword,
+ type: keyword,
+ user_id: keyword,
+ user_memory_id: keyword,
+ },
+ },
+ queryFields: [
+ 'parent_title',
+ 'parent_summary',
+ 'parent_details',
+ 'conclusion_directives',
+ 'suggestions',
+ ],
+ } satisfies FtsSearchIndexDefinition<'memoryPreferences'>,
+ messages: {
+ indexedOnlyFields: ['summary'],
+ longTextFields: ['content', 'summary'],
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ agent_id: keyword,
+ content: mixedText,
+ group_id: keyword,
+ id: keyword,
+ role: keyword,
+ session_id: keyword,
+ summary: mixedText,
+ thread_id: keyword,
+ topic_id: keyword,
+ user_id: keyword,
+ workspace_id: keyword,
+ },
+ },
+ queryFields: ['content', 'summary'],
+ } satisfies FtsSearchIndexDefinition<'messages'>,
+ personaDocuments: {
+ longTextFields: ['persona'],
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ captured_at: date,
+ id: keyword,
+ persona: memoryText,
+ profile: keyword,
+ tagline: memoryText,
+ user_id: keyword,
+ version: integer,
+ },
+ },
+ queryFields: ['tagline', 'persona'],
+ } satisfies FtsSearchIndexDefinition<'personaDocuments'>,
+ topics: {
+ longTextFields: ['content'],
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ agent_id: keyword,
+ content: mixedText,
+ description: mixedText,
+ group_id: keyword,
+ id: keyword,
+ session_id: keyword,
+ status: keyword,
+ title: mixedText,
+ user_id: keyword,
+ workspace_id: keyword,
+ },
+ },
+ queryFields: ['title', 'content', 'description'],
+ } satisfies FtsSearchIndexDefinition<'topics'>,
+ userMemories: {
+ longTextFields: ['details'],
+ mappings: {
+ dynamic: 'strict',
+ properties: {
+ ...projectionMetadataProperties,
+ ...timestampProperties,
+ captured_at: date,
+ details: memoryText,
+ id: keyword,
+ memory_category: keyword,
+ memory_layer: keyword,
+ status: keyword,
+ summary: memoryText,
+ tags: keyword,
+ title: memoryText,
+ user_id: keyword,
+ },
+ },
+ queryFields: ['title', 'summary', 'details'],
+ } satisfies FtsSearchIndexDefinition<'userMemories'>,
+} as const satisfies {
+ [Entity in FtsSearchDocumentEntity]: FtsSearchIndexDefinition<Entity>;
+};
+
+/** First production Elasticsearch mapping version. Development-only iterations were never shipped. */
+export const FTS_SEARCH_INDEX_SCHEMA_VERSION = 1;
+
+const toIndexSegment = (entity: FtsSearchDocumentEntity) =>
+ entity.replaceAll(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);
+
+/** Namespace is deployment-owned so OSS does not encode environment or tenant policy. */
+export const getFtsSearchIndexAlias = (namespace: string, entity: FtsSearchDocumentEntity) =>
+ `${namespace}-${toIndexSegment(entity)}`;
+
+export const getFtsSearchPhysicalIndexName = (
+ namespace: string,
+ entity: FtsSearchDocumentEntity,
+ version: number = FTS_SEARCH_INDEX_SCHEMA_VERSION,
+) => `${getFtsSearchIndexAlias(namespace, entity)}-v${version}`;
diff --git a/packages/database/src/repositories/ftsSearchDocument/schema.test.ts b/packages/database/src/repositories/ftsSearchDocument/schema.test.ts
new file mode 100644
index 00000000000..fb0dc9fe9cb
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/schema.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+
+import { FTS_SEARCH_DOCUMENT_FIXTURES } from './__tests__/fixtures';
+import { FTS_SEARCH_DOCUMENT_ENTITIES, parseFtsSearchDocumentSource } from './schema';
+
+describe('search document schemas', () => {
+ it.each(FTS_SEARCH_DOCUMENT_ENTITIES)('parses the fixed %s fixture', (entity) => {
+ expect(parseFtsSearchDocumentSource(entity, FTS_SEARCH_DOCUMENT_FIXTURES[entity])).toEqual(
+ FTS_SEARCH_DOCUMENT_FIXTURES[entity],
+ );
+ });
+
+ it('rejects fields not declared by the canonical document schema', () => {
+ expect(() =>
+ parseFtsSearchDocumentSource('agents', {
+ ...FTS_SEARCH_DOCUMENT_FIXTURES.agents,
+ undeclared_field: 'must not reach Elasticsearch',
+ }),
+ ).toThrow();
+ });
+
+ it('accepts the shared soft-delete projection marker', () => {
+ expect(
+ parseFtsSearchDocumentSource('agents', {
+ ...FTS_SEARCH_DOCUMENT_FIXTURES.agents,
+ fts_search_sync_deleted: true,
+ }),
+ ).toMatchObject({ fts_search_sync_deleted: true });
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearchDocument/schema.ts b/packages/database/src/repositories/ftsSearchDocument/schema.ts
new file mode 100644
index 00000000000..77e08950bb9
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchDocument/schema.ts
@@ -0,0 +1,299 @@
+import type { FtsSearchDocumentEntity } from '@lobechat/types';
+import { z } from 'zod';
+
+export type { FtsSearchDocumentEntity } from '@lobechat/types';
+export { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
+
+export const FTS_SEARCH_MEMORY_DOCUMENT_ENTITIES = [
+ 'memoryActivities',
+ 'memoryContexts',
+ 'memoryExperiences',
+ 'memoryIdentities',
+ 'memoryPreferences',
+ 'personaDocuments',
+ 'userMemories',
+] as const satisfies readonly FtsSearchDocumentEntity[];
+
+export type FtsSearchMemoryDocumentEntity = (typeof FTS_SEARCH_MEMORY_DOCUMENT_ENTITIES)[number];
+
+const dateTime = z.string().datetime();
+const nullableDateTime = dateTime.nullable();
+const nullableString = z.string().nullable();
+const stringArray = z.array(z.string());
+const visibility = z.enum(['private', 'public']);
+
+const timestampShape = {
+ created_at: dateTime,
+ updated_at: dateTime,
+};
+
+const projectionMetadataShape = {
+ fts_search_sync_deleted: z.boolean().optional(),
+};
+
+const ownershipShape = {
+ user_id: z.string(),
+ visibility,
+ workspace_id: nullableString,
+};
+
+export const FTS_SEARCH_DOCUMENT_SCHEMAS = {
+ agents: z
+ .object({
+ ...ownershipShape,
+ ...projectionMetadataShape,
+ ...timestampShape,
+ description: nullableString,
+ id: z.string(),
+ slug: nullableString,
+ system_role: nullableString,
+ tags: stringArray,
+ title: nullableString,
+ virtual: z.boolean().nullable(),
+ })
+ .strict(),
+ chatGroups: z
+ .object({
+ ...ownershipShape,
+ ...projectionMetadataShape,
+ ...timestampShape,
+ content: nullableString,
+ description: nullableString,
+ group_id: nullableString,
+ id: z.string(),
+ title: nullableString,
+ })
+ .strict(),
+ documents: z
+ .object({
+ ...ownershipShape,
+ ...projectionMetadataShape,
+ ...timestampShape,
+ content: nullableString,
+ description: nullableString,
+ file_id: nullableString,
+ file_type: z.string(),
+ id: z.string(),
+ knowledge_base_id: nullableString,
+ knowledge_base_ids: stringArray,
+ parent_id: nullableString,
+ slug: nullableString,
+ source_type: z.string(),
+ title: nullableString,
+ total_char_count: z.number().int(),
+ })
+ .strict(),
+ files: z
+ .object({
+ ...ownershipShape,
+ ...projectionMetadataShape,
+ ...timestampShape,
+ file_type: z.string(),
+ id: z.string(),
+ knowledge_base_ids: stringArray,
+ name: z.string(),
+ size: z.number().int(),
+ source: nullableString,
+ })
+ .strict(),
+ knowledgeBases: z
+ .object({
+ ...ownershipShape,
+ ...projectionMetadataShape,
+ ...timestampShape,
+ description: nullableString,
+ id: z.string(),
+ is_public: z.boolean().nullable(),
+ name: z.string(),
+ type: nullableString,
+ })
+ .strict(),
+ memoryActivities: z
+ .object({
+ ...projectionMetadataShape,
+ ...timestampShape,
+ captured_at: dateTime,
+ ends_at: nullableDateTime,
+ feedback: nullableString,
+ id: z.string(),
+ narrative: nullableString,
+ notes: nullableString,
+ parent_details: nullableString,
+ parent_memory_categories: stringArray,
+ parent_summary: nullableString,
+ parent_tags: stringArray,
+ parent_title: nullableString,
+ starts_at: nullableDateTime,
+ status: z.string(),
+ tags: stringArray,
+ type: z.string(),
+ user_id: nullableString,
+ user_memory_id: nullableString,
+ })
+ .strict(),
+ memoryContexts: z
+ .object({
+ ...projectionMetadataShape,
+ ...timestampShape,
+ captured_at: dateTime,
+ current_status: nullableString,
+ description: nullableString,
+ id: z.string(),
+ parent_memory_categories: stringArray,
+ parent_tags: stringArray,
+ parent_text: stringArray,
+ tags: stringArray,
+ title: nullableString,
+ type: nullableString,
+ user_id: nullableString,
+ user_memory_ids: stringArray,
+ })
+ .strict(),
+ memoryExperiences: z
+ .object({
+ ...projectionMetadataShape,
+ ...timestampShape,
+ action: nullableString,
+ captured_at: dateTime,
+ id: z.string(),
+ key_learning: nullableString,
+ parent_details: nullableString,
+ parent_memory_categories: stringArray,
+ parent_summary: nullableString,
+ parent_tags: stringArray,
+ parent_title: nullableString,
+ possible_outcome: nullableString,
+ reasoning: nullableString,
+ situation: nullableString,
+ tags: stringArray,
+ type: nullableString,
+ user_id: nullableString,
+ user_memory_id: nullableString,
+ })
+ .strict(),
+ memoryIdentities: z
+ .object({
+ ...projectionMetadataShape,
+ ...timestampShape,
+ captured_at: dateTime,
+ description: nullableString,
+ episodic_date: nullableDateTime,
+ id: z.string(),
+ parent_details: nullableString,
+ parent_memory_categories: stringArray,
+ parent_summary: nullableString,
+ parent_tags: stringArray,
+ parent_title: nullableString,
+ relationship: nullableString,
+ role: nullableString,
+ tags: stringArray,
+ type: nullableString,
+ user_id: nullableString,
+ user_memory_id: nullableString,
+ })
+ .strict(),
+ memoryPreferences: z
+ .object({
+ ...projectionMetadataShape,
+ ...timestampShape,
+ captured_at: dateTime,
+ conclusion_directives: nullableString,
+ id: z.string(),
+ parent_details: nullableString,
+ parent_memory_categories: stringArray,
+ parent_summary: nullableString,
+ parent_tags: stringArray,
+ parent_title: nullableString,
+ suggestions: nullableString,
+ tags: stringArray,
+ type: nullableString,
+ user_id: nullableString,
+ user_memory_id: nullableString,
+ })
+ .strict(),
+ messages: z
+ .object({
+ ...projectionMetadataShape,
+ ...timestampShape,
+ agent_id: nullableString,
+ content: nullableString,
+ group_id: nullableString,
+ id: z.string(),
+ role: z.string(),
+ session_id: nullableString,
+ summary: nullableString,
+ thread_id: nullableString,
+ topic_id: nullableString,
+ user_id: z.string(),
+ workspace_id: nullableString,
+ })
+ .strict(),
+ personaDocuments: z
+ .object({
+ ...projectionMetadataShape,
+ ...timestampShape,
+ captured_at: dateTime,
+ id: z.string(),
+ persona: nullableString,
+ profile: z.string(),
+ tagline: nullableString,
+ user_id: nullableString,
+ version: z.number().int(),
+ })
+ .strict(),
+ topics: z
+ .object({
+ ...projectionMetadataShape,
+ ...timestampShape,
+ agent_id: nullableString,
+ content: nullableString,
+ description: nullableString,
+ group_id: nullableString,
+ id: z.string(),
+ session_id: nullableString,
+ status: nullableString,
+ title: nullableString,
+ user_id: z.string(),
+ workspace_id: nullableString,
+ })
+ .strict(),
+ userMemories: z
+ .object({
+ ...projectionMetadataShape,
+ ...timestampShape,
+ captured_at: dateTime,
+ details: nullableString,
+ id: z.string(),
+ memory_category: nullableString,
+ memory_layer: nullableString,
+ status: nullableString,
+ summary: nullableString,
+ tags: stringArray,
+ title: nullableString,
+ user_id: nullableString,
+ })
+ .strict(),
+} as const satisfies Record<FtsSearchDocumentEntity, z.ZodType>;
+
+export type FtsSearchDocumentSourceMap = {
+ [Entity in FtsSearchDocumentEntity]: z.infer<(typeof FTS_SEARCH_DOCUMENT_SCHEMAS)[Entity]>;
+};
+
+export interface FtsSearchDocumentKey<
+ Entity extends FtsSearchDocumentEntity = FtsSearchDocumentEntity,
+> {
+ entity: Entity;
+ id: string;
+}
+
+export type FtsSearchBuiltDocument = {
+ [Entity in FtsSearchDocumentEntity]: FtsSearchDocumentKey<Entity> & {
+ source: FtsSearchDocumentSourceMap[Entity];
+ };
+}[FtsSearchDocumentEntity];
+
+export const parseFtsSearchDocumentSource = <Entity extends FtsSearchDocumentEntity>(
+ entity: Entity,
+ input: unknown,
+): FtsSearchDocumentSourceMap[Entity] =>
+ FTS_SEARCH_DOCUMENT_SCHEMAS[entity].parse(input) as FtsSearchDocumentSourceMap[Entity];
diff --git a/packages/database/src/repositories/ftsSearchReindex/__tests__/elasticsearch.test.ts b/packages/database/src/repositories/ftsSearchReindex/__tests__/elasticsearch.test.ts
new file mode 100644
index 00000000000..051e54006d9
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchReindex/__tests__/elasticsearch.test.ts
@@ -0,0 +1,236 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { FTS_SEARCH_INDEX_ANALYSIS, FTS_SEARCH_INDEX_DEFINITIONS } from '../../ftsSearchDocument';
+import { FtsSearchReindexHttpClient } from '../elasticsearch';
+import type { FtsSearchReindexIndexBody } from '../service';
+
+const response = (body: unknown, status = 200) =>
+ new Response(body === undefined ? undefined : JSON.stringify(body), {
+ headers: { 'Content-Type': 'application/json' },
+ status,
+ });
+
+const reindexMeta = { reindex_run_id: '00000000-0000-4000-8000-000000000001', schema_version: 1 };
+const agentsIndexBody: FtsSearchReindexIndexBody = {
+ mappings: { ...FTS_SEARCH_INDEX_DEFINITIONS.agents.mappings, _meta: reindexMeta },
+ settings: { analysis: FTS_SEARCH_INDEX_ANALYSIS },
+};
+const existingAgentsMapping = {
+ 'lobehub-messages-v1': {
+ mappings: {
+ _meta: reindexMeta,
+ ...FTS_SEARCH_INDEX_DEFINITIONS.agents.mappings,
+ },
+ },
+};
+afterEach(() => vi.unstubAllGlobals());
+
+describe('FtsSearchReindexHttpClient', () => {
+ it('rejects remote HTTP endpoints before exposing the API key', () => {
+ expect(
+ () =>
+ new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'http://search.example.com',
+ }),
+ ).toThrow('must use HTTPS unless it targets loopback');
+ });
+
+ it('allows loopback HTTP endpoints for local development', () => {
+ expect(
+ () =>
+ new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'http://localhost:9200',
+ }),
+ ).not.toThrow();
+ });
+
+ it('creates a missing index without exposing credentials in the URL', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response(undefined, 404))
+ .mockResolvedValueOnce(response({ acknowledged: true }));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await client.ensureIndex('lobehub-messages-v1', agentsIndexBody);
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(String(fetchMock.mock.calls[1][0])).toBe(
+ 'https://search.example.com/lobehub-messages-v1',
+ );
+ expect(String(fetchMock.mock.calls[1][0])).not.toContain('secret-key');
+ });
+
+ it('refuses to recreate a missing index that the checkpoint already completed', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(response(undefined, 404));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.ensureIndex('lobehub-messages-v1', agentsIndexBody, { createIfMissing: false }),
+ ).rejects.toThrow('Completed Elasticsearch index lobehub-messages-v1 is missing');
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+
+ it('validates ICU analysis settings on an existing index', async () => {
+ const incompatibleSettings = {
+ 'lobehub-messages-v1': {
+ settings: {
+ index: {
+ analysis: {
+ ...FTS_SEARCH_INDEX_ANALYSIS,
+ analyzer: {
+ ...FTS_SEARCH_INDEX_ANALYSIS.analyzer,
+ lobehub_icu: {
+ filter: ['icu_folding'],
+ tokenizer: 'standard',
+ type: 'custom',
+ },
+ },
+ },
+ },
+ },
+ },
+ };
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response(undefined))
+ .mockResolvedValueOnce(response(existingAgentsMapping))
+ .mockResolvedValueOnce(response(incompatibleSettings));
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.ensureIndex('lobehub-messages-v1', agentsIndexBody)).rejects.toThrow(
+ 'analysis settings are incompatible',
+ );
+ });
+
+ it('accepts an existing index with the expected mapping and analysis settings', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response(undefined))
+ .mockResolvedValueOnce(response(existingAgentsMapping))
+ .mockResolvedValueOnce(
+ response({
+ 'lobehub-messages-v1': {
+ settings: { index: { analysis: FTS_SEARCH_INDEX_ANALYSIS } },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.ensureIndex('lobehub-messages-v1', agentsIndexBody),
+ ).resolves.toBeUndefined();
+ });
+
+ it('refuses to resume into an existing index with an incompatible mapping', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response(undefined))
+ .mockResolvedValueOnce(
+ response({
+ 'lobehub-messages-v1': {
+ mappings: {
+ _meta: reindexMeta,
+ dynamic: 'strict',
+ properties: {
+ ...FTS_SEARCH_INDEX_DEFINITIONS.agents.mappings.properties,
+ id: { type: 'text' },
+ },
+ },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.ensureIndex('lobehub-messages-v1', agentsIndexBody)).rejects.toThrow(
+ 'mapping is incompatible for id',
+ );
+ });
+
+ it('refuses to resume an index created by a different local reindex run', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(response(undefined))
+ .mockResolvedValueOnce(
+ response({
+ 'lobehub-messages-v1': {
+ mappings: {
+ _meta: { ...reindexMeta, reindex_run_id: '00000000-0000-4000-8000-000000000002' },
+ dynamic: 'strict',
+ properties: {},
+ },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.ensureIndex('lobehub-messages-v1', agentsIndexBody)).rejects.toThrow(
+ 'reindex run identity is incompatible',
+ );
+ });
+
+ it('keeps an alias that already targets the expected writable index', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ response({
+ 'lobehub-messages-v1': {
+ aliases: { 'lobehub-messages': { is_write_index: true } },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(
+ client.ensureAlias('lobehub-messages', 'lobehub-messages-v1'),
+ ).resolves.toBeUndefined();
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+
+ it('refuses to advance an alias that targets an older schema version', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ response({
+ 'lobehub-messages-v1': {
+ aliases: { 'lobehub-messages': { is_write_index: true } },
+ },
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: 'secret-key',
+ url: 'https://search.example.com',
+ });
+
+ await expect(client.ensureAlias('lobehub-messages', 'lobehub-messages-v2')).rejects.toThrow(
+ 'Elasticsearch alias lobehub-messages already points to a different index',
+ );
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearchReindex/__tests__/index.test.ts b/packages/database/src/repositories/ftsSearchReindex/__tests__/index.test.ts
new file mode 100644
index 00000000000..b63c48dc681
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchReindex/__tests__/index.test.ts
@@ -0,0 +1,227 @@
+// @vitest-environment node
+import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { FtsSearchReindexFileRepository } from '..';
+
+let stateDirectory: string;
+let repository: FtsSearchReindexFileRepository;
+let captureFingerprint = 'capture-v1';
+let revision = 10;
+
+beforeEach(async () => {
+ stateDirectory = await mkdtemp(path.join(tmpdir(), 'search-reindex-test-'));
+ captureFingerprint = 'capture-v1';
+ revision = 10;
+ repository = new FtsSearchReindexFileRepository({
+ readCaptureFingerprint: vi.fn(async () => captureFingerprint),
+ readHighWaterRevision: vi.fn(async () => revision),
+ reserveRevisionWithWriteFence: vi.fn(async () => ++revision),
+ stateDirectory,
+ });
+});
+
+afterEach(async () => {
+ await rm(stateDirectory, { force: true, recursive: true });
+});
+
+describe('FtsSearchReindexFileRepository', () => {
+ it('creates one local v2 checkpoint and resumes it after constructing a new repository', async () => {
+ const first = await repository.createOrResume('test-search', 1);
+ const resumed = await new FtsSearchReindexFileRepository({
+ readCaptureFingerprint: vi.fn(async () => captureFingerprint),
+ readHighWaterRevision: vi.fn(async () => revision),
+ reserveRevisionWithWriteFence: vi.fn(async () => ++revision),
+ stateDirectory,
+ }).createOrResume('test-search', 1);
+
+ expect(first.run.baseRevision).toBe(11);
+ expect(first.progress).toHaveLength(14);
+ expect(first.progress.map(({ physicalIndex }) => physicalIndex)).toContain(
+ 'test-search-messages-v1',
+ );
+ expect(resumed.run.id).toBe(first.run.id);
+ expect(resumed.run.captureFingerprint).toBe(captureFingerprint);
+
+ const checkpointFiles = await readdir(stateDirectory);
+ expect(checkpointFiles).toHaveLength(1);
+ expect(checkpointFiles[0]).toMatch(/^reindex-test-search-[a-f\d]{12}-v1\.json$/);
+ const checkpoint = JSON.parse(
+ await readFile(path.join(stateDirectory, checkpointFiles[0]), 'utf8'),
+ );
+ expect(checkpoint).toMatchObject({
+ formatVersion: 2,
+ run: { captureFingerprint, namespace: 'test-search' },
+ });
+ });
+
+ it('refuses to resume a checkpoint when capture definitions changed', async () => {
+ const state = await repository.createOrResume('changed-capture-search', 1);
+ await repository.completeEntity(state.run.id, 'agents');
+ captureFingerprint = 'capture-v2';
+
+ const restarted = new FtsSearchReindexFileRepository({
+ readCaptureFingerprint: vi.fn(async () => captureFingerprint),
+ readHighWaterRevision: vi.fn(async () => revision),
+ reserveRevisionWithWriteFence: vi.fn(async () => ++revision),
+ stateDirectory,
+ });
+
+ await expect(restarted.createOrResume('changed-capture-search', 1)).rejects.toThrow(
+ 'capture definition fingerprint changed',
+ );
+ await expect(restarted.getTargetRun('changed-capture-search', 1)).resolves.toMatchObject({
+ progress: expect.arrayContaining([
+ expect.objectContaining({ entity: 'agents', status: 'completed' }),
+ ]),
+ run: { captureFingerprint: 'capture-v1' },
+ });
+ });
+
+ it('reports a corrupt checkpoint instead of silently starting over', async () => {
+ await repository.createOrResume('corrupt-search', 1);
+ const [checkpointFile] = await readdir(stateDirectory);
+ await writeFile(path.join(stateDirectory, checkpointFile), '{');
+
+ await expect(repository.createOrResume('corrupt-search', 1)).rejects.toThrow(
+ 'FTS reindex checkpoint is not valid JSON',
+ );
+ await expect(readdir(stateDirectory)).resolves.toEqual([checkpointFile]);
+ });
+
+ it('loads the exact target without parsing an unrelated corrupt checkpoint', async () => {
+ const state = await repository.createOrResume('healthy-search', 1);
+ await writeFile(path.join(stateDirectory, 'reindex-unrelated-deadbeef-v1.json'), '{');
+
+ const restarted = new FtsSearchReindexFileRepository({
+ readCaptureFingerprint: vi.fn(async () => captureFingerprint),
+ readHighWaterRevision: vi.fn(async () => revision),
+ reserveRevisionWithWriteFence: vi.fn(async () => ++revision),
+ stateDirectory,
+ });
+ await expect(restarted.getTargetRun('healthy-search', 1)).resolves.toMatchObject({
+ run: { id: state.run.id },
+ });
+ });
+
+ it('atomically checkpoints item failures and rejects a stale cursor', async () => {
+ const state = await repository.createOrResume('checkpoint-search', 1);
+
+ await expect(
+ repository.checkpointBatch({
+ cursor: 'agent-2',
+ entity: 'agents',
+ failures: [
+ { documentId: 'agent-2', error: new Error('mapping rejected'), retryable: false },
+ ],
+ indexedCount: 1,
+ previousCursor: null,
+ processedCount: 2,
+ runId: state.run.id,
+ }),
+ ).resolves.toBe(true);
+ await expect(
+ repository.checkpointBatch({
+ cursor: 'agent-2',
+ entity: 'agents',
+ failures: [{ documentId: 'agent-3', error: new Error('stale worker'), retryable: true }],
+ indexedCount: 1,
+ previousCursor: null,
+ processedCount: 2,
+ runId: state.run.id,
+ }),
+ ).resolves.toBe(false);
+
+ const checkpointed = await repository.getRun(state.run.id);
+ expect(checkpointed?.progress.find(({ entity }) => entity === 'agents')).toMatchObject({
+ cursor: 'agent-2',
+ failedCount: 1,
+ indexedCount: 1,
+ processedCount: 2,
+ });
+ await expect(repository.completeEntity(state.run.id, 'agents')).rejects.toThrow(
+ '1 reindex failures remain',
+ );
+
+ await expect(repository.resolveFailures(state.run.id, 'agents', ['agent-2'])).resolves.toBe(1);
+ await repository.completeEntity(state.run.id, 'agents');
+
+ const completed = await repository.getRun(state.run.id);
+ expect(completed?.progress.find(({ entity }) => entity === 'agents')).toMatchObject({
+ failedCount: 0,
+ indexedCount: 2,
+ status: 'completed',
+ });
+ await expect(repository.listUnresolvedFailures(state.run.id)).resolves.toEqual([]);
+ });
+
+ it('refuses to mark a run ready while entities are incomplete', async () => {
+ const state = await repository.createOrResume('not-ready-search', 1);
+
+ await expect(repository.markReadyForIncrementalSync(state.run.id)).rejects.toThrow(
+ 'Cannot create aliases',
+ );
+ });
+
+ it('lets an operator skip a failed document without counting it as indexed', async () => {
+ const state = await repository.createOrResume('skip-failure-search', 1);
+ await repository.checkpointBatch({
+ cursor: 'agent-1',
+ entity: 'agents',
+ failures: [{ documentId: 'agent-1', error: new Error('mapping rejected'), retryable: false }],
+ indexedCount: 0,
+ previousCursor: null,
+ processedCount: 1,
+ runId: state.run.id,
+ });
+
+ await expect(repository.skipFailure(state.run.id, 'agents', 'agent-1')).resolves.toBe(true);
+ await expect(repository.skipFailure(state.run.id, 'agents', 'agent-1')).resolves.toBe(false);
+
+ const skipped = await repository.getRun(state.run.id);
+ expect(skipped?.progress.find(({ entity }) => entity === 'agents')).toMatchObject({
+ failedCount: 0,
+ indexedCount: 0,
+ processedCount: 1,
+ });
+ await expect(repository.listUnresolvedFailures(state.run.id)).resolves.toEqual([]);
+ });
+
+ it('does not let an operator skip an uncertain retryable failure', async () => {
+ const state = await repository.createOrResume('retryable-failure-search', 1);
+ await repository.checkpointBatch({
+ cursor: 'agent-1',
+ entity: 'agents',
+ failures: [{ documentId: 'agent-1', error: new Error('gateway timeout'), retryable: true }],
+ indexedCount: 0,
+ previousCursor: null,
+ processedCount: 1,
+ runId: state.run.id,
+ });
+
+ await expect(repository.skipFailure(state.run.id, 'agents', 'agent-1')).resolves.toBe(false);
+ await expect(repository.listUnresolvedFailures(state.run.id, 'agents')).resolves.toHaveLength(
+ 1,
+ );
+ });
+
+ it('records the Outbox high-water boundary when all entities are ready', async () => {
+ const state = await repository.createOrResume('ready-search', 1);
+ for (const entity of FTS_SEARCH_DOCUMENT_ENTITIES) {
+ await repository.completeEntity(state.run.id, entity);
+ }
+
+ await repository.markReadyForIncrementalSync(state.run.id);
+
+ const ready = await repository.getRun(state.run.id);
+ expect(ready?.run).toMatchObject({
+ backfillHighWaterRevision: revision,
+ status: 'ready_for_incremental_sync',
+ });
+ expect(ready!.run.backfillHighWaterRevision).toBeGreaterThanOrEqual(state.run.baseRevision);
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearchReindex/__tests__/logger.test.ts b/packages/database/src/repositories/ftsSearchReindex/__tests__/logger.test.ts
new file mode 100644
index 00000000000..a0eb25eccb3
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchReindex/__tests__/logger.test.ts
@@ -0,0 +1,73 @@
+// @vitest-environment node
+import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { FtsSearchReindexFileLogger, summarizeFtsSearchReindexError } from '../logger';
+
+let stateDirectory: string;
+
+beforeEach(async () => {
+ stateDirectory = await mkdtemp(path.join(tmpdir(), 'search-reindex-logger-test-'));
+});
+
+afterEach(async () => {
+ await rm(stateDirectory, { force: true, recursive: true });
+});
+
+describe('FtsSearchReindexFileLogger', () => {
+ it('appends ordered JSONL events and atomically writes a private summary', async () => {
+ const logger = new FtsSearchReindexFileLogger({
+ runId: 'run-1',
+ sessionId: 'session-1',
+ stateDirectory,
+ });
+
+ await Promise.all([
+ logger.append({ entity: 'agents', processed: 100, type: 'batch_checkpointed' }),
+ logger.append({ entity: 'topics', processed: 50, type: 'batch_checkpointed' }),
+ ]);
+ await logger.writeSummary({ failed: 0, indexed: 150, status: 'backfilling' });
+
+ const runDirectory = path.join(stateDirectory, 'runs', 'run-1');
+ const events = (await readFile(path.join(runDirectory, 'events.jsonl'), 'utf8'))
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line));
+ expect(events).toMatchObject([
+ { entity: 'agents', processed: 100, runId: 'run-1', sessionId: 'session-1' },
+ { entity: 'topics', processed: 50, runId: 'run-1', sessionId: 'session-1' },
+ ]);
+ await expect(readFile(path.join(runDirectory, 'summary.json'), 'utf8')).resolves.toContain(
+ '"indexed": 150',
+ );
+ expect((await stat(runDirectory)).mode & 0o777).toBe(0o700);
+ expect((await stat(path.join(runDirectory, 'events.jsonl'))).mode & 0o777).toBe(0o600);
+ expect((await stat(path.join(runDirectory, 'summary.json'))).mode & 0o777).toBe(0o600);
+ });
+
+ it('refuses credential-shaped fields before writing an audit event', async () => {
+ const logger = new FtsSearchReindexFileLogger({
+ runId: 'run-1',
+ sessionId: 'session-1',
+ stateDirectory,
+ });
+
+ expect(() => logger.append({ apiKey: 'secret', type: 'unsafe_event' })).toThrow(
+ 'credential-shaped field',
+ );
+ });
+
+ it('redacts connection URLs and credential assignments from failure summaries', () => {
+ const summary = summarizeFtsSearchReindexError(
+ new Error('connect postgres://operator:[email protected]/app token=private-token'),
+ );
+
+ expect(summary).toContain('[redacted-url]');
+ expect(summary).toContain('token=[redacted]');
+ expect(summary).not.toContain('operator');
+ expect(summary).not.toContain('private');
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearchReindex/__tests__/service.test.ts b/packages/database/src/repositories/ftsSearchReindex/__tests__/service.test.ts
new file mode 100644
index 00000000000..3e98435c550
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchReindex/__tests__/service.test.ts
@@ -0,0 +1,563 @@
+import type { FtsSearchDocumentEntity } from '@lobechat/types';
+import { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { FtsSearchReindexRunState } from '..';
+import type {
+ FtsSearchReindexElasticsearchClient,
+ FtsSearchReindexProgressEvent,
+ FtsSearchReindexStateRepository,
+} from '../service';
+import { FtsSearchReindexService } from '../service';
+
+const createState = (): FtsSearchReindexRunState => ({
+ progress: FTS_SEARCH_DOCUMENT_ENTITIES.map((entity) => ({
+ completedAt: null,
+ cursor: null,
+ entity,
+ failedCount: 0,
+ indexedCount: 0,
+ physicalIndex: `test-${entity}-v1`,
+ processedCount: 0,
+ status: 'pending',
+ })),
+ run: {
+ aliasesCreatedAt: null,
+ backfillHighWaterRevision: null,
+ baseRevision: 10,
+ captureFingerprint: 'capture-v1',
+ createdAt: '2026-08-28T00:00:00.000Z',
+ id: 'run-1',
+ namespace: 'test',
+ schemaVersion: 1,
+ status: 'backfilling',
+ updatedAt: '2026-08-28T00:00:00.000Z',
+ },
+});
+
+const createDependencies = () => {
+ const state = createState();
+ const failures = new Map<FtsSearchDocumentEntity, { documentId: string }[]>();
+ const builder = {
+ buildBatch: vi.fn().mockResolvedValue([]),
+ buildByIds: vi.fn().mockResolvedValue([]),
+ };
+ const client: FtsSearchReindexElasticsearchClient = {
+ bulk: vi.fn().mockResolvedValue([]),
+ count: vi.fn().mockResolvedValue(0),
+ ensureAlias: vi.fn().mockResolvedValue(undefined),
+ ensureIndex: vi.fn().mockResolvedValue(undefined),
+ refresh: vi.fn().mockResolvedValue(undefined),
+ };
+ const repository: FtsSearchReindexStateRepository = {
+ checkpointBatch: vi.fn(
+ async (checkpoint: Parameters<FtsSearchReindexStateRepository['checkpointBatch']>[0]) => {
+ const progress = state.progress.find(({ entity }) => entity === checkpoint.entity)!;
+ if (progress.cursor !== checkpoint.previousCursor) return false;
+ progress.cursor = checkpoint.cursor;
+ progress.processedCount += checkpoint.processedCount;
+ progress.indexedCount += checkpoint.indexedCount;
+ failures.set(
+ checkpoint.entity,
+ checkpoint.failures.map(({ documentId }) => ({ documentId })),
+ );
+ progress.failedCount = failures.get(checkpoint.entity)?.length ?? 0;
+ return true;
+ },
+ ),
+ completeEntity: vi.fn(async (_runId, entity) => {
+ state.progress.find((item) => item.entity === entity)!.status = 'completed';
+ }),
+ createOrResume: vi.fn().mockResolvedValue(state),
+ getRun: vi.fn().mockImplementation(async () => state),
+ listUnresolvedFailures: vi
+ .fn()
+ .mockImplementation(async (_runId, entity) => failures.get(entity) ?? []),
+ markReadyForIncrementalSync: vi.fn(async () => {
+ state.run.status = 'ready_for_incremental_sync';
+ }),
+ resolveFailures: vi.fn().mockResolvedValue(0),
+ };
+ return { builder, client, repository, state };
+};
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('FtsSearchReindexService', () => {
+ it('uses defaults when optional batch limits are undefined', async () => {
+ const { builder, client, repository } = createDependencies();
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ batchSize: undefined,
+ bulkMaxBytes: undefined,
+ });
+
+ await expect(service.run('test', 1)).resolves.toMatchObject({
+ status: 'ready_for_incremental_sync',
+ });
+ });
+
+ it('creates aliases only after all 14 entities complete', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ const events: unknown[] = [];
+ const lifecycle: string[] = [];
+ const validateIncrementalSyncSource = vi.fn(async () => {
+ lifecycle.push('validate-incremental-sync-source');
+ });
+ vi.mocked(client.ensureAlias).mockImplementation(async () => {
+ lifecycle.push('create-alias');
+ });
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ onProgress: (event) => {
+ events.push(event);
+ },
+ validateIncrementalSyncSource,
+ });
+
+ await expect(service.run('test', 1)).resolves.toMatchObject({
+ status: 'ready_for_incremental_sync',
+ });
+
+ expect(client.ensureIndex).toHaveBeenCalledTimes(14);
+ expect(client.ensureIndex).toHaveBeenCalledWith(
+ 'test-agents-v1',
+ expect.objectContaining({
+ mappings: expect.objectContaining({
+ _meta: { reindex_run_id: 'run-1', schema_version: 1 },
+ }),
+ }),
+ { createIfMissing: true },
+ );
+ expect(client.ensureAlias).toHaveBeenCalledTimes(14);
+ expect(repository.markReadyForIncrementalSync).toHaveBeenCalledOnce();
+ expect(state.progress.every(({ status }) => status === 'completed')).toBe(true);
+ expect(events).toEqual(
+ expect.arrayContaining(
+ FTS_SEARCH_DOCUMENT_ENTITIES.map((entity) =>
+ expect.objectContaining({ drift: 0, entity, type: 'reconciliation' }),
+ ),
+ ),
+ );
+ expect(validateIncrementalSyncSource).toHaveBeenCalledOnce();
+ expect(lifecycle).toEqual([
+ 'validate-incremental-sync-source',
+ ...Array.from({ length: 14 }, () => 'create-alias'),
+ ]);
+ });
+
+ it('does not create aliases or mark a run ready when incremental source validation fails', async () => {
+ const { builder, client, repository } = createDependencies();
+ const validateIncrementalSyncSource = vi
+ .fn()
+ .mockRejectedValue(new Error('incremental sync source is not healthy'));
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ validateIncrementalSyncSource,
+ });
+
+ await expect(service.run('test', 1)).rejects.toThrow('incremental sync source is not healthy');
+
+ expect(validateIncrementalSyncSource).toHaveBeenCalledOnce();
+ expect(client.ensureAlias).not.toHaveBeenCalled();
+ expect(repository.markReadyForIncrementalSync).not.toHaveBeenCalled();
+ });
+
+ it('does not mark a run ready when an existing alias blocks cutover', async () => {
+ const { builder, client, repository } = createDependencies();
+ vi.mocked(client.ensureAlias).mockRejectedValue(
+ new Error('Elasticsearch alias test-agents already points to a different index'),
+ );
+ const service = new FtsSearchReindexService(builder, repository, client);
+
+ await expect(service.run('test', 1)).rejects.toThrow(
+ 'Elasticsearch alias test-agents already points to a different index',
+ );
+
+ expect(client.ensureAlias).toHaveBeenCalledOnce();
+ expect(repository.markReadyForIncrementalSync).not.toHaveBeenCalled();
+ });
+
+ it('reuses index preparation when the run already prepared it', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ const service = new FtsSearchReindexService(builder, repository, client);
+
+ await service.prepareIndices(state);
+ await service.run('test', 1);
+
+ expect(client.ensureIndex).toHaveBeenCalledTimes(14);
+ });
+
+ it('requires completed physical indexes to remain present', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ const agents = state.progress.find(({ entity }) => entity === 'agents')!;
+ agents.completedAt = '2026-08-28T00:01:00.000Z';
+ agents.status = 'completed';
+ const service = new FtsSearchReindexService(builder, repository, client);
+
+ await service.prepareIndices(state);
+
+ expect(client.ensureIndex).toHaveBeenCalledWith('test-agents-v1', expect.any(Object), {
+ createIfMissing: false,
+ });
+ });
+
+ it('attributes index preparation failures to their entity', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ vi.mocked(client.ensureIndex).mockImplementation(async (index) => {
+ if (index === 'test-agents-v1') throw new Error('analysis-icu is unavailable');
+ });
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entityConcurrency: 1,
+ });
+
+ await expect(service.prepareIndices(state)).rejects.toMatchObject({
+ entity: 'agents',
+ message: expect.stringContaining('analysis-icu is unavailable'),
+ });
+ });
+
+ it('backfills independent entities with bounded concurrency', async () => {
+ const { builder, client, repository } = createDependencies();
+ let active = 0;
+ let maxActive = 0;
+ vi.mocked(client.ensureIndex).mockImplementation(async () => {
+ active += 1;
+ maxActive = Math.max(maxActive, active);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ active -= 1;
+ });
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entityConcurrency: 4,
+ });
+
+ await service.run('test', 1);
+
+ expect(maxActive).toBe(4);
+ });
+
+ it('writes byte-bounded bulk requests concurrently', async () => {
+ const { builder, client, repository } = createDependencies();
+ builder.buildBatch.mockImplementation(async (entity) => {
+ if (entity !== 'agents' || builder.buildBatch.mock.calls.length > 1) return [];
+ return Array.from({ length: 4 }, (_, index) => ({
+ entity: 'agents' as const,
+ id: `agent-${index}`,
+ source: { content: 'x'.repeat(100), id: `agent-${index}` },
+ }));
+ });
+ let active = 0;
+ let maxActive = 0;
+ vi.mocked(client.bulk).mockImplementation(async (body) => {
+ active += 1;
+ maxActive = Math.max(maxActive, active);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ active -= 1;
+ return Array.from({ length: body.trim().split('\n').length / 2 }, () => ({ status: 201 }));
+ });
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index.includes('-agents-') ? 4 : 0,
+ );
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ bulkConcurrency: 2,
+ bulkMaxBytes: 250,
+ entityConcurrency: 1,
+ });
+
+ await service.run('test', 1);
+
+ expect(client.bulk).toHaveBeenCalledTimes(4);
+ expect(maxActive).toBe(2);
+ });
+
+ it('includes PostgreSQL batch scan time in the reported batch duration', async () => {
+ const { builder, client, repository } = createDependencies();
+ const events: FtsSearchReindexProgressEvent[] = [];
+ const scanDelayMs = 100;
+ let returnedAgents = false;
+ builder.buildBatch.mockImplementation(async (entity) => {
+ if (entity !== 'agents' || returnedAgents) return [];
+ returnedAgents = true;
+ await new Promise((resolve) => setTimeout(resolve, scanDelayMs));
+ return [{ entity: 'agents', id: 'agent-1', source: { id: 'agent-1' } }];
+ });
+ vi.mocked(client.bulk).mockResolvedValue([{ status: 201 }]);
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index.includes('-agents-') ? 1 : 0,
+ );
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ entityConcurrency: 1,
+ onProgress: (event) => {
+ events.push(event);
+ },
+ });
+
+ vi.useFakeTimers();
+ try {
+ const run = service.run('test', 1);
+ await vi.advanceTimersByTimeAsync(scanDelayMs);
+ await run;
+ } finally {
+ vi.useRealTimers();
+ }
+
+ const batch = events.find(
+ (event): event is Extract<FtsSearchReindexProgressEvent, { type: 'batch' }> =>
+ event.type === 'batch' && event.entity === 'agents',
+ );
+ expect(batch).toBeDefined();
+ expect(batch!.durationMs).toBeGreaterThanOrEqual(scanDelayMs);
+ });
+
+ it('starts byte-bounded requests before encoding the remainder of a large batch', async () => {
+ const { builder, client, repository } = createDependencies();
+ let firstRequestStarted = false;
+ let thirdDocumentEncodedAfterRequestStarted = false;
+ builder.buildBatch.mockImplementation(async (entity) => {
+ if (entity !== 'agents' || builder.buildBatch.mock.calls.length > 1) return [];
+ return Array.from({ length: 3 }, (_, index) => ({
+ entity: 'agents' as const,
+ id: `agent-${index}`,
+ source: {
+ get content() {
+ if (index === 2) {
+ thirdDocumentEncodedAfterRequestStarted = firstRequestStarted;
+ }
+ return 'x'.repeat(100);
+ },
+ id: `agent-${index}`,
+ },
+ }));
+ });
+ vi.mocked(client.bulk).mockImplementation(async () => {
+ firstRequestStarted = true;
+ return [{ status: 201 }];
+ });
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index.includes('-agents-') ? 3 : 0,
+ );
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ bulkConcurrency: 2,
+ bulkMaxBytes: 250,
+ });
+
+ await service.run('test', 1);
+
+ expect(thirdDocumentEncodedAfterRequestStarted).toBe(true);
+ });
+
+ it('retries a request-level timeout before checkpointing the batch', async () => {
+ const { builder, client, repository } = createDependencies();
+ const events: unknown[] = [];
+ builder.buildBatch
+ .mockResolvedValueOnce([{ entity: 'agents', id: 'agent-1', source: { id: 'agent-1' } }])
+ .mockResolvedValue([]);
+ vi.mocked(client.bulk)
+ .mockRejectedValueOnce(new DOMException('The operation timed out', 'TimeoutError'))
+ .mockResolvedValueOnce([{ status: 201 }]);
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index.includes('-agents-') ? 1 : 0,
+ );
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ maxRequestRetries: 1,
+ onProgress: (event) => {
+ events.push(event);
+ },
+ retryBaseDelayMs: 0,
+ });
+
+ await expect(service.run('test', 1)).resolves.toMatchObject({
+ status: 'ready_for_incremental_sync',
+ });
+ expect(client.bulk).toHaveBeenCalledTimes(2);
+ expect(events).toContainEqual(
+ expect.objectContaining({ attempt: 1, entity: 'agents', type: 'bulk_retry' }),
+ );
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ attempts: 2,
+ entity: 'agents',
+ result: 'success',
+ type: 'bulk_completed',
+ }),
+ );
+ });
+
+ it('pauses every non-empty entity after a bounded number of batches', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ const visited = new Set<FtsSearchDocumentEntity>();
+ builder.buildBatch.mockImplementation(async (entity) => {
+ if (visited.has(entity)) return [];
+ visited.add(entity);
+ return [{ entity, id: `${entity}-1`, source: { id: `${entity}-1` } }];
+ });
+ vi.mocked(client.bulk).mockResolvedValue([{ status: 201 }]);
+ vi.mocked(client.count).mockResolvedValue(1);
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ batchSize: 1,
+ entityConcurrency: 4,
+ maxBatchesPerEntity: 1,
+ });
+
+ await expect(service.run('test', 1)).resolves.toMatchObject({ status: 'backfilling' });
+
+ expect(client.ensureAlias).not.toHaveBeenCalled();
+ expect(state.progress.every(({ processedCount }) => processedCount === 1)).toBe(true);
+ expect(state.progress.every(({ status }) => status !== 'completed')).toBe(true);
+ });
+
+ it('does not advance the cursor or create aliases after a request-level bulk failure', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ const events: unknown[] = [];
+ builder.buildBatch
+ .mockResolvedValueOnce([{ entity: 'agents', id: 'agent-1', source: { id: 'agent-1' } }])
+ .mockResolvedValue([]);
+ vi.mocked(client.bulk).mockRejectedValueOnce(new Error('gateway unavailable'));
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ maxRequestRetries: 0,
+ onProgress: (event) => {
+ events.push(event);
+ },
+ });
+
+ await expect(service.run('test', 1)).rejects.toThrow('gateway unavailable');
+
+ expect(repository.checkpointBatch).not.toHaveBeenCalled();
+ expect(client.ensureAlias).not.toHaveBeenCalled();
+ expect(state.progress[0].cursor).toBeNull();
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ attempts: 1,
+ entity: 'agents',
+ result: 'request_error',
+ type: 'bulk_completed',
+ }),
+ );
+ });
+
+ it('replays a partially successful concurrent batch before advancing its cursor', async () => {
+ const { builder, client, repository, state } = createDependencies();
+ const documents = Array.from({ length: 2 }, (_, index) => ({
+ entity: 'agents' as const,
+ id: `agent-${index}`,
+ source: { content: 'x'.repeat(100), id: `agent-${index}` },
+ }));
+ builder.buildBatch.mockImplementation(async (entity, { afterId }) =>
+ entity === 'agents' && !afterId ? documents : [],
+ );
+ vi.mocked(client.bulk)
+ .mockResolvedValueOnce([{ status: 201 }])
+ .mockRejectedValueOnce(new Error('gateway unavailable'));
+ const service = new FtsSearchReindexService(builder, repository, client, {
+ bulkConcurrency: 2,
+ bulkMaxBytes: 250,
+ maxRequestRetries: 0,
+ });
+
+ await expect(service.run('test', 1)).rejects.toThrow('gateway unavailable');
+ expect(repository.checkpointBatch).not.toHaveBeenCalled();
+ expect(state.progress[0].cursor).toBeNull();
+
+ vi.mocked(client.bulk).mockResolvedValue([{ status: 409 }]);
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index.includes('-agents-') ? 2 : 0,
+ );
+ await expect(service.run('test', 1)).resolves.toMatchObject({
+ status: 'ready_for_incremental_sync',
+ });
+
+ expect(repository.checkpointBatch).toHaveBeenCalledWith(
+ expect.objectContaining({ cursor: 'agent-1', indexedCount: 2, processedCount: 2 }),
+ );
+ expect(client.bulk).toHaveBeenCalledTimes(4);
+ });
+
+ it('persists an oversized item and blocks alias creation', async () => {
+ const { builder, client, repository } = createDependencies();
+ builder.buildBatch
+ .mockResolvedValueOnce([
+ { entity: 'agents', id: 'agent-large', source: { id: 'agent-large', title: 'large' } },
+ ])
+ .mockResolvedValue([]);
+ const service = new FtsSearchReindexService(builder, repository, client, { bulkMaxBytes: 1 });
+
+ await expect(service.run('test', 1)).rejects.toThrow('unresolved agents failures');
+
+ expect(repository.checkpointBatch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cursor: 'agent-large',
+ failures: [expect.objectContaining({ documentId: 'agent-large', retryable: false })],
+ }),
+ );
+ expect(client.ensureAlias).not.toHaveBeenCalled();
+ });
+
+ it('treats an external version conflict as an already indexed document', async () => {
+ const { builder, client, repository } = createDependencies();
+ builder.buildBatch
+ .mockResolvedValueOnce([{ entity: 'agents', id: 'agent-1', source: { id: 'agent-1' } }])
+ .mockResolvedValue([]);
+ vi.mocked(client.bulk).mockResolvedValueOnce([{ status: 409 }]);
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index.includes('-agents-') ? 1 : 0,
+ );
+ const service = new FtsSearchReindexService(builder, repository, client);
+
+ await expect(service.run('test', 1)).resolves.toMatchObject({
+ status: 'ready_for_incremental_sync',
+ });
+ expect(repository.checkpointBatch).toHaveBeenCalledWith(
+ expect.objectContaining({ failures: [], indexedCount: 1 }),
+ );
+ });
+
+ it('emits signed reconciliation drift before blocking alias creation', async () => {
+ const { client, repository } = createDependencies();
+ const events: unknown[] = [];
+ vi.mocked(client.count).mockImplementation(async (index) =>
+ index.includes('-agents-') ? 1 : 0,
+ );
+ const service = new FtsSearchReindexService(
+ { buildBatch: vi.fn().mockResolvedValue([]), buildByIds: vi.fn().mockResolvedValue([]) },
+ repository,
+ client,
+ {
+ onProgress: (event) => {
+ events.push(event);
+ },
+ },
+ );
+
+ await expect(service.run('test', 1)).rejects.toThrow('Reindex count mismatch for agents');
+
+ expect(events).toContainEqual({
+ checkpointCount: 0,
+ drift: 1,
+ elasticsearchCount: 1,
+ entity: 'agents',
+ type: 'reconciliation',
+ });
+ expect(client.ensureAlias).not.toHaveBeenCalled();
+ });
+
+ it('persists only a safe Elasticsearch error type, never its source-text reason', async () => {
+ const { builder, client, repository } = createDependencies();
+ builder.buildBatch
+ .mockResolvedValueOnce([{ entity: 'agents', id: 'agent-1', source: { id: 'agent-1' } }])
+ .mockResolvedValue([]);
+ vi.mocked(client.bulk).mockResolvedValue([
+ {
+ error: { reason: 'private source text', type: 'mapper_parsing_exception' },
+ status: 400,
+ },
+ ]);
+ const service = new FtsSearchReindexService(builder, repository, client);
+
+ await expect(service.run('test', 1)).rejects.toThrow('unresolved agents failures');
+
+ const persistedErrors = vi
+ .mocked(repository.checkpointBatch)
+ .mock.calls.flatMap(([checkpoint]) => checkpoint.failures.map(({ error }) => String(error)));
+ expect(persistedErrors).toContain(
+ 'Error: Elasticsearch bulk item failed (400, type=mapper_parsing_exception)',
+ );
+ expect(persistedErrors.join('\n')).not.toContain('private source text');
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearchReindex/elasticsearch.ts b/packages/database/src/repositories/ftsSearchReindex/elasticsearch.ts
new file mode 100644
index 00000000000..b22d5adb751
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchReindex/elasticsearch.ts
@@ -0,0 +1,346 @@
+import { isDeepStrictEqual } from 'node:util';
+
+import { z } from 'zod';
+
+import { parseElasticsearchUrl } from '../ftsSearch/elasticsearch/url';
+import type {
+ FtsSearchReindexBulkItemResult,
+ FtsSearchReindexElasticsearchClient,
+ FtsSearchReindexIndexBody,
+ FtsSearchReindexIndexOptions,
+} from './service';
+
+const bulkResponseSchema = z.object({
+ items: z.array(
+ z.object({
+ index: z.object({ error: z.unknown().optional(), status: z.number() }),
+ }),
+ ),
+});
+
+const countResponseSchema = z.object({ count: z.number().int().nonnegative() });
+
+const aliasResponseSchema = z.record(
+ z.string(),
+ z.object({
+ aliases: z.record(
+ z.string(),
+ z.object({ is_write_index: z.boolean().optional() }).passthrough(),
+ ),
+ }),
+);
+
+interface ElasticsearchFtsSearchMappingPropertyResponse {
+ analyzer?: string;
+ fields?: Record<string, ElasticsearchFtsSearchMappingPropertyResponse>;
+ ignore_above?: number;
+ type?: string;
+}
+
+const mappingPropertyResponseSchema: z.ZodType<ElasticsearchFtsSearchMappingPropertyResponse> =
+ z.lazy(() =>
+ z.object({
+ analyzer: z.string().optional(),
+ fields: z.record(z.string(), mappingPropertyResponseSchema).optional(),
+ ignore_above: z.number().int().positive().optional(),
+ type: z.string().optional(),
+ }),
+ );
+
+const mappingResponseSchema = z.record(
+ z.string(),
+ z.object({
+ mappings: z.object({
+ _meta: z
+ .object({
+ reindex_run_id: z.string().optional(),
+ schema_version: z.number().int().positive().optional(),
+ })
+ .optional(),
+ dynamic: z.union([z.boolean(), z.string()]).optional(),
+ properties: z.record(z.string(), mappingPropertyResponseSchema),
+ }),
+ }),
+);
+
+const settingsResponseSchema = z.record(
+ z.string(),
+ z.object({
+ settings: z.object({
+ index: z.object({ analysis: z.record(z.string(), z.unknown()) }),
+ }),
+ }),
+);
+
+export interface FtsSearchReindexHttpClientOptions {
+ apiKey: string;
+ requestTimeoutMs?: number;
+ url: string;
+}
+
+export class FtsSearchReindexRequestError extends Error {
+ readonly status?: number;
+
+ constructor(message: string, status?: number, cause?: unknown) {
+ super(message, { cause });
+ this.name = 'FtsSearchReindexRequestError';
+ this.status = status;
+ }
+}
+
+/** Minimal credential-safe Elasticsearch transport for the self-host reindex command. */
+export class FtsSearchReindexHttpClient implements FtsSearchReindexElasticsearchClient {
+ private readonly apiKey: string;
+ private readonly requestTimeoutMs: number;
+ private readonly url: URL;
+
+ constructor({ apiKey, requestTimeoutMs = 30_000, url }: FtsSearchReindexHttpClientOptions) {
+ this.apiKey = apiKey;
+ this.requestTimeoutMs = requestTimeoutMs;
+ this.url = parseElasticsearchUrl(url);
+ }
+
+ private async request(path: string, init: RequestInit = {}) {
+ return fetch(new URL(path, this.url), {
+ ...init,
+ headers: {
+ Authorization: `ApiKey ${this.apiKey}`,
+ ...init.headers,
+ },
+ signal: AbortSignal.timeout(this.requestTimeoutMs),
+ });
+ }
+
+ private assertMappingProperty(
+ field: string,
+ actual: ElasticsearchFtsSearchMappingPropertyResponse | undefined,
+ expected: ElasticsearchFtsSearchMappingPropertyResponse,
+ ) {
+ if (
+ !actual ||
+ actual.type !== expected.type ||
+ actual.analyzer !== expected.analyzer ||
+ actual.ignore_above !== expected.ignore_above
+ ) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch index mapping is incompatible for ${field}`,
+ );
+ }
+ for (const [subfield, expectedSubfield] of Object.entries(expected.fields ?? {})) {
+ this.assertMappingProperty(
+ `${field}.${subfield}`,
+ actual.fields?.[subfield],
+ expectedSubfield,
+ );
+ }
+ }
+
+ private async assertIndexMapping(index: string, expected: FtsSearchReindexIndexBody) {
+ const response = await this.request(`/${encodeURIComponent(index)}/_mapping`, {
+ method: 'GET',
+ });
+ if (!response.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch mapping check failed for ${index} (${response.status})`,
+ response.status,
+ );
+ }
+ const parsed = mappingResponseSchema.safeParse(await response.json());
+ if (!parsed.success) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch mapping response has an invalid shape for ${index}`,
+ response.status,
+ parsed.error,
+ );
+ }
+ const actual = parsed.data[index]?.mappings;
+ if (
+ !actual ||
+ actual.dynamic !== expected.mappings.dynamic ||
+ actual._meta?.reindex_run_id !== expected.mappings._meta.reindex_run_id ||
+ actual._meta?.schema_version !== expected.mappings._meta.schema_version
+ ) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch index mapping or reindex run identity is incompatible for ${index}; restore the matching checkpoint or use a clean target`,
+ );
+ }
+ for (const [field, expectedProperty] of Object.entries(expected.mappings.properties)) {
+ this.assertMappingProperty(field, actual.properties[field], expectedProperty);
+ }
+ }
+
+ private async assertIndexAnalysis(index: string, expected: FtsSearchReindexIndexBody) {
+ const response = await this.request(
+ `/${encodeURIComponent(index)}/_settings?flat_settings=false&filter_path=*.settings.index.analysis`,
+ { method: 'GET' },
+ );
+ if (!response.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch analysis settings check failed for ${index} (${response.status})`,
+ response.status,
+ );
+ }
+ const parsed = settingsResponseSchema.safeParse(await response.json());
+ if (!parsed.success) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch analysis settings response has an invalid shape for ${index}`,
+ response.status,
+ parsed.error,
+ );
+ }
+ if (
+ !isDeepStrictEqual(parsed.data[index]?.settings.index.analysis, expected.settings.analysis)
+ ) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch analysis settings are incompatible for ${index}`,
+ );
+ }
+ }
+
+ async bulk(body: string): Promise<FtsSearchReindexBulkItemResult[]> {
+ const response = await this.request('/_bulk', {
+ body,
+ headers: { 'Content-Type': 'application/x-ndjson' },
+ method: 'POST',
+ });
+ if (!response.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch bulk request failed (${response.status})`,
+ response.status,
+ );
+ }
+
+ const parsed = bulkResponseSchema.safeParse(await response.json());
+ if (!parsed.success) {
+ throw new FtsSearchReindexRequestError(
+ 'Elasticsearch bulk response has an invalid shape',
+ response.status,
+ parsed.error,
+ );
+ }
+ return parsed.data.items.map(({ index }) => index);
+ }
+
+ async count(index: string): Promise<number> {
+ const response = await this.request(`/${encodeURIComponent(index)}/_count`, { method: 'GET' });
+ if (!response.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch count request failed for ${index} (${response.status})`,
+ response.status,
+ );
+ }
+
+ const parsed = countResponseSchema.safeParse(await response.json());
+ if (!parsed.success) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch count response has an invalid shape for ${index}`,
+ response.status,
+ parsed.error,
+ );
+ }
+ return parsed.data.count;
+ }
+
+ async ensureAlias(alias: string, physicalIndex: string): Promise<void> {
+ const response = await this.request(`/_alias/${encodeURIComponent(alias)}`, { method: 'GET' });
+ if (response.ok) {
+ const parsed = aliasResponseSchema.safeParse(await response.json());
+ if (!parsed.success) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch alias response has an invalid shape for ${alias}`,
+ response.status,
+ parsed.error,
+ );
+ }
+ const targets = Object.entries(parsed.data).filter(([, value]) =>
+ Object.hasOwn(value.aliases, alias),
+ );
+ if (
+ targets.length === 1 &&
+ targets[0][0] === physicalIndex &&
+ targets[0][1].aliases[alias].is_write_index !== false
+ ) {
+ return;
+ }
+
+ /**
+ * Incremental sync writes only through the stable alias. Moving that alias while a resumable
+ * backfill is running could acknowledge a change in the old index without replaying it into
+ * the new one. Online schema upgrades therefore require a separate durable dual-write
+ * protocol; this initial migration fails closed instead of pretending the cutover is safe.
+ */
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch alias ${alias} already points to a different index`,
+ );
+ }
+ if (response.status !== 404) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch alias check failed for ${alias} (${response.status})`,
+ response.status,
+ );
+ }
+
+ const createResponse = await this.request('/_aliases', {
+ body: JSON.stringify({
+ actions: [{ add: { alias, index: physicalIndex, is_write_index: true } }],
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ });
+ if (!createResponse.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch alias creation failed for ${alias} (${createResponse.status})`,
+ createResponse.status,
+ );
+ }
+ }
+
+ async ensureIndex(
+ index: string,
+ body: FtsSearchReindexIndexBody,
+ { createIfMissing = true }: FtsSearchReindexIndexOptions = {},
+ ): Promise<void> {
+ const existsResponse = await this.request(`/${encodeURIComponent(index)}`, { method: 'HEAD' });
+ if (existsResponse.ok) {
+ await this.assertIndexMapping(index, body);
+ await this.assertIndexAnalysis(index, body);
+ return;
+ }
+ if (existsResponse.status !== 404) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch index check failed for ${index} (${existsResponse.status})`,
+ existsResponse.status,
+ );
+ }
+ if (!createIfMissing) {
+ throw new FtsSearchReindexRequestError(
+ `Completed Elasticsearch index ${index} is missing; use a new checkpoint and an empty target for a full backfill`,
+ existsResponse.status,
+ );
+ }
+
+ const response = await this.request(`/${encodeURIComponent(index)}`, {
+ body: JSON.stringify(body),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'PUT',
+ });
+ if (!response.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch index creation failed for ${index} (${response.status})`,
+ response.status,
+ );
+ }
+ }
+
+ async refresh(index: string): Promise<void> {
+ const response = await this.request(`/${encodeURIComponent(index)}/_refresh`, {
+ method: 'POST',
+ });
+ if (!response.ok) {
+ throw new FtsSearchReindexRequestError(
+ `Elasticsearch refresh failed for ${index} (${response.status})`,
+ response.status,
+ );
+ }
+ }
+}
diff --git a/packages/database/src/repositories/ftsSearchReindex/index.ts b/packages/database/src/repositories/ftsSearchReindex/index.ts
new file mode 100644
index 00000000000..22e74e3fd7f
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchReindex/index.ts
@@ -0,0 +1,587 @@
+import { createHash, randomUUID } from 'node:crypto';
+import { mkdir, open, readFile, rename, stat, unlink } from 'node:fs/promises';
+import path from 'node:path';
+
+import type {
+ FtsSearchDocumentEntity,
+ FtsSearchReindexEntityStatus,
+ FtsSearchReindexRunStatus,
+} from '@lobechat/types';
+import { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
+import { isRecord } from '@lobechat/utils/object';
+import { z } from 'zod';
+
+import { getFtsSearchPhysicalIndexName } from '../ftsSearchDocument';
+
+export interface FtsSearchReindexBatchFailure {
+ documentId: string;
+ error: unknown;
+ retryable: boolean;
+}
+
+export interface FtsSearchReindexBatchCheckpoint {
+ cursor: string;
+ entity: FtsSearchDocumentEntity;
+ failures: FtsSearchReindexBatchFailure[];
+ indexedCount: number;
+ previousCursor: string | null;
+ processedCount: number;
+ runId: string;
+}
+
+export interface FtsSearchReindexEntityProgress {
+ completedAt: string | null;
+ cursor: string | null;
+ entity: FtsSearchDocumentEntity;
+ failedCount: number;
+ indexedCount: number;
+ physicalIndex: string;
+ processedCount: number;
+ status: FtsSearchReindexEntityStatus;
+}
+
+export interface FtsSearchReindexFailure {
+ attempts: number;
+ documentId: string;
+ entity: FtsSearchDocumentEntity;
+ error: string;
+ resolvedAt: string | null;
+ retryable: boolean;
+}
+
+export interface FtsSearchReindexRun {
+ aliasesCreatedAt: string | null;
+ /**
+ * Highest allocated Outbox revision observed after backfill. This is not a committed snapshot
+ * boundary, so incremental consumers must not discard rows at or below it.
+ */
+ backfillHighWaterRevision: number | null;
+ baseRevision: number;
+ /** Capture function and trigger definitions used while this reindex run was created. */
+ captureFingerprint: string;
+ createdAt: string;
+ id: string;
+ namespace: string;
+ schemaVersion: number;
+ status: FtsSearchReindexRunStatus;
+ updatedAt: string;
+}
+
+export interface FtsSearchReindexRunState {
+ progress: FtsSearchReindexEntityProgress[];
+ run: FtsSearchReindexRun;
+}
+
+export interface FtsSearchReindexFileRepositoryOptions {
+ readCaptureFingerprint: () => Promise<string>;
+ readHighWaterRevision: () => Promise<number>;
+ reserveRevisionWithWriteFence: () => Promise<number>;
+ stateDirectory: string;
+}
+
+const CHECKPOINT_FORMAT_VERSION = 2;
+const CHECKPOINT_FILE_PREFIX = 'reindex-';
+const LOCK_RETRY_INTERVAL_MS = 50;
+/** Local checkpoint operations are bounded file writes; an older lock is treated as crash residue. */
+const LOCK_STALE_AFTER_MS = 30_000;
+const LOCK_WAIT_TIMEOUT_MS = LOCK_STALE_AFTER_MS + 5_000;
+
+const entitySchema = z.enum(FTS_SEARCH_DOCUMENT_ENTITIES);
+const entityStatusSchema = z.enum(['pending', 'backfilling', 'completed']);
+const runStatusSchema = z.enum([
+ 'backfilling',
+ 'ready_for_incremental_sync',
+ 'completed',
+ 'failed',
+]);
+const progressSchema = z.object({
+ completedAt: z.string().datetime().nullable(),
+ cursor: z.string().nullable(),
+ entity: entitySchema,
+ failedCount: z.number().int().nonnegative(),
+ indexedCount: z.number().int().nonnegative(),
+ physicalIndex: z.string().min(1),
+ processedCount: z.number().int().nonnegative(),
+ status: entityStatusSchema,
+});
+const failureSchema = z.object({
+ attempts: z.number().int().positive(),
+ documentId: z.string().min(1),
+ entity: entitySchema,
+ error: z.string(),
+ resolvedAt: z.string().datetime().nullable(),
+ retryable: z.boolean(),
+});
+const runSchema = z.object({
+ aliasesCreatedAt: z.string().datetime().nullable(),
+ backfillHighWaterRevision: z.number().int().nonnegative().nullable(),
+ baseRevision: z.number().int().positive(),
+ captureFingerprint: z.string().min(1),
+ createdAt: z.string().datetime(),
+ id: z.string().uuid(),
+ namespace: z.string().min(1),
+ schemaVersion: z.number().int().positive(),
+ status: runStatusSchema,
+ updatedAt: z.string().datetime(),
+});
+const checkpointSchema = z
+ .object({
+ failures: z.array(failureSchema),
+ formatVersion: z.literal(CHECKPOINT_FORMAT_VERSION),
+ progress: z.array(progressSchema).length(FTS_SEARCH_DOCUMENT_ENTITIES.length),
+ run: runSchema,
+ })
+ .superRefine((checkpoint, context) => {
+ const entities = new Set(checkpoint.progress.map(({ entity }) => entity));
+ if (entities.size !== FTS_SEARCH_DOCUMENT_ENTITIES.length) {
+ context.addIssue({
+ code: 'custom',
+ message: 'FTS reindex checkpoint must contain each entity exactly once',
+ path: ['progress'],
+ });
+ }
+ for (const progress of checkpoint.progress) {
+ const expectedIndex = getFtsSearchPhysicalIndexName(
+ checkpoint.run.namespace,
+ progress.entity,
+ checkpoint.run.schemaVersion,
+ );
+ if (progress.physicalIndex !== expectedIndex) {
+ context.addIssue({
+ code: 'custom',
+ message: `Expected physical index ${expectedIndex}`,
+ path: ['progress', progress.entity, 'physicalIndex'],
+ });
+ }
+ }
+ });
+
+type FtsSearchReindexCheckpointFile = z.infer<typeof checkpointSchema>;
+
+const errorMessage = (error: unknown) =>
+ (error instanceof Error ? error.message : String(error)).slice(0, 4000);
+
+const now = () => new Date().toISOString();
+
+const checkpointFileName = (namespace: string, schemaVersion: number) => {
+ const safeNamespace = namespace.replaceAll(/[^\w-]/g, '_').slice(0, 80) || 'search';
+ const namespaceHash = createHash('sha256').update(namespace).digest('hex').slice(0, 12);
+ return `${CHECKPOINT_FILE_PREFIX}${safeNamespace}-${namespaceHash}-v${schemaVersion}.json`;
+};
+
+const stateOf = ({ progress, run }: FtsSearchReindexCheckpointFile): FtsSearchReindexRunState => ({
+ progress,
+ run,
+});
+
+const unresolvedFailureCount = (
+ checkpoint: FtsSearchReindexCheckpointFile,
+ entity: FtsSearchDocumentEntity,
+) =>
+ checkpoint.failures.filter((failure) => failure.entity === entity && !failure.resolvedAt).length;
+
+const isMissingFileError = (error: unknown) => isRecord(error) && error.code === 'ENOENT';
+const isExistingFileError = (error: unknown) => isRecord(error) && error.code === 'EEXIST';
+
+/** Local, atomically written checkpoint storage for the one-shot Elasticsearch reindex CLI. */
+export class FtsSearchReindexFileRepository {
+ private readonly runPaths = new Map<string, string>();
+ private readonly stateDirectory: string;
+
+ constructor(private readonly options: FtsSearchReindexFileRepositoryOptions) {
+ this.stateDirectory = path.resolve(options.stateDirectory);
+ }
+
+ private checkpointPath(namespace: string, schemaVersion: number) {
+ return path.join(this.stateDirectory, checkpointFileName(namespace, schemaVersion));
+ }
+
+ private async findCheckpointPath(runId: string): Promise<string | undefined> {
+ const checkpointPath = this.runPaths.get(runId);
+ if (!checkpointPath) return;
+ const checkpoint = await this.readCheckpoint(checkpointPath);
+ if (checkpoint.run.id !== runId) {
+ throw new Error(`FTS reindex checkpoint run ID changed unexpectedly: ${checkpointPath}`);
+ }
+ return checkpointPath;
+ }
+
+ private stateOf(
+ checkpointPath: string,
+ checkpoint: FtsSearchReindexCheckpointFile,
+ ): FtsSearchReindexRunState {
+ this.runPaths.set(checkpoint.run.id, checkpointPath);
+ return stateOf(checkpoint);
+ }
+
+ private async readCheckpointIfExists(
+ checkpointPath: string,
+ ): Promise<FtsSearchReindexCheckpointFile | undefined> {
+ let source: string;
+ try {
+ source = await readFile(checkpointPath, 'utf8');
+ } catch (error) {
+ if (isMissingFileError(error)) return;
+ throw error;
+ }
+
+ let json: unknown;
+ try {
+ json = JSON.parse(source);
+ } catch (error) {
+ throw new Error(`FTS reindex checkpoint is not valid JSON: ${checkpointPath}`, {
+ cause: error,
+ });
+ }
+ const parsed = checkpointSchema.safeParse(json);
+ if (!parsed.success) {
+ throw new Error(`FTS reindex checkpoint is invalid: ${checkpointPath}`, {
+ cause: parsed.error,
+ });
+ }
+ return parsed.data;
+ }
+
+ private async readCheckpoint(checkpointPath: string): Promise<FtsSearchReindexCheckpointFile> {
+ const checkpoint = await this.readCheckpointIfExists(checkpointPath);
+ if (!checkpoint) throw new Error(`FTS reindex checkpoint does not exist: ${checkpointPath}`);
+ return checkpoint;
+ }
+
+ private async readCaptureFingerprint(): Promise<string> {
+ const fingerprint = await this.options.readCaptureFingerprint();
+ if (typeof fingerprint !== 'string' || fingerprint.trim().length === 0) {
+ throw new Error('Failed to read a valid search reindex capture definition fingerprint');
+ }
+ return fingerprint;
+ }
+
+ private assertCaptureFingerprint(
+ checkpoint: FtsSearchReindexCheckpointFile,
+ captureFingerprint: string,
+ ): void {
+ if (checkpoint.run.captureFingerprint === captureFingerprint) return;
+ throw new Error(
+ `FTS reindex capture definition fingerprint changed; refusing to resume checkpoint ${checkpoint.run.id}`,
+ );
+ }
+
+ private async writeCheckpoint(
+ checkpointPath: string,
+ checkpoint: FtsSearchReindexCheckpointFile,
+ ): Promise<void> {
+ await mkdir(this.stateDirectory, { mode: 0o700, recursive: true });
+ const temporaryPath = `${checkpointPath}.${process.pid}.${randomUUID()}.tmp`;
+ let temporaryFile;
+ try {
+ /**
+ * Persist the complete temporary file, atomically replace the checkpoint, then persist the
+ * directory entry so a crash cannot expose a partially written or lost rename.
+ */
+ temporaryFile = await open(temporaryPath, 'wx', 0o600);
+ await temporaryFile.writeFile(`${JSON.stringify(checkpoint, null, 2)}\n`, 'utf8');
+ await temporaryFile.sync();
+ await temporaryFile.close();
+ temporaryFile = undefined;
+ await rename(temporaryPath, checkpointPath);
+ const directory = await open(this.stateDirectory, 'r');
+ try {
+ await directory.sync();
+ } finally {
+ await directory.close();
+ }
+ } catch (error) {
+ await temporaryFile?.close().catch(() => {});
+ await unlink(temporaryPath).catch(() => {});
+ throw error;
+ }
+ }
+
+ private async withCheckpointLock<Result>(
+ checkpointPath: string,
+ operation: () => Promise<Result>,
+ ): Promise<Result> {
+ await mkdir(this.stateDirectory, { mode: 0o700, recursive: true });
+ const lockPath = `${checkpointPath}.lock`;
+ const lockToken = randomUUID();
+ const deadline = Date.now() + LOCK_WAIT_TIMEOUT_MS;
+ let lockFile;
+
+ while (!lockFile) {
+ try {
+ lockFile = await open(lockPath, 'wx', 0o600);
+ await lockFile.writeFile(lockToken, 'utf8');
+ await lockFile.sync();
+ } catch (error) {
+ if (lockFile) {
+ await lockFile.close().catch(() => {});
+ await unlink(lockPath).catch(() => {});
+ throw error;
+ }
+ if (!isExistingFileError(error)) throw error;
+ const lockStat = await stat(lockPath).catch(() => undefined);
+ if (lockStat && Date.now() - lockStat.mtimeMs > LOCK_STALE_AFTER_MS) {
+ console.warn(
+ `Taking over stale search reindex checkpoint lock (${Math.round(Date.now() - lockStat.mtimeMs)} ms): ${lockPath}`,
+ );
+ await unlink(lockPath).catch(() => {});
+ continue;
+ }
+ if (Date.now() >= deadline) {
+ throw new Error(`Timed out waiting for search reindex checkpoint lock: ${lockPath}`, {
+ cause: error,
+ });
+ }
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_INTERVAL_MS));
+ }
+ }
+
+ try {
+ return await operation();
+ } finally {
+ await lockFile.close();
+ const currentToken = await readFile(lockPath, 'utf8').catch(() => undefined);
+ if (currentToken === lockToken) await unlink(lockPath).catch(() => {});
+ }
+ }
+
+ private async updateCheckpoint<Result>(
+ runId: string,
+ operation: (checkpoint: FtsSearchReindexCheckpointFile) => Result,
+ ): Promise<Result> {
+ const checkpointPath = await this.findCheckpointPath(runId);
+ if (!checkpointPath) throw new Error(`Missing reindex run ${runId}`);
+
+ return this.withCheckpointLock(checkpointPath, async () => {
+ const checkpoint = await this.readCheckpoint(checkpointPath);
+ const result = await operation(checkpoint);
+ checkpoint.run.updatedAt = now();
+ await this.writeCheckpoint(checkpointPath, checkpoint);
+ return result;
+ });
+ }
+
+ async checkpointBatch({
+ cursor,
+ entity,
+ failures,
+ indexedCount,
+ previousCursor,
+ processedCount,
+ runId,
+ }: FtsSearchReindexBatchCheckpoint): Promise<boolean> {
+ return this.updateCheckpoint(runId, (checkpoint) => {
+ const progress = checkpoint.progress.find((item) => item.entity === entity);
+ if (!progress) throw new Error(`Missing reindex progress for ${entity}`);
+ if (progress.cursor !== previousCursor) return false;
+
+ progress.cursor = cursor;
+ progress.indexedCount += indexedCount;
+ progress.processedCount += processedCount;
+ progress.status = 'backfilling';
+
+ for (const failure of failures) {
+ const existing = checkpoint.failures.find(
+ (item) => item.entity === entity && item.documentId === failure.documentId,
+ );
+ if (existing) {
+ existing.attempts += 1;
+ existing.error = errorMessage(failure.error);
+ existing.resolvedAt = null;
+ existing.retryable = failure.retryable;
+ } else {
+ checkpoint.failures.push({
+ attempts: 1,
+ documentId: failure.documentId,
+ entity,
+ error: errorMessage(failure.error),
+ resolvedAt: null,
+ retryable: failure.retryable,
+ });
+ }
+ }
+ progress.failedCount = unresolvedFailureCount(checkpoint, entity);
+ return true;
+ });
+ }
+
+ async completeEntity(runId: string, entity: FtsSearchDocumentEntity): Promise<void> {
+ await this.updateCheckpoint(runId, (checkpoint) => {
+ const progress = checkpoint.progress.find((item) => item.entity === entity);
+ if (!progress) throw new Error(`Missing reindex progress for ${entity}`);
+ const unresolved = unresolvedFailureCount(checkpoint, entity);
+ if (unresolved > 0) {
+ throw new Error(`Cannot complete ${entity}: ${unresolved} reindex failures remain`);
+ }
+ progress.completedAt = now();
+ progress.failedCount = 0;
+ progress.status = 'completed';
+ });
+ }
+
+ async createOrResume(
+ namespace: string,
+ schemaVersion: number,
+ ): Promise<FtsSearchReindexRunState> {
+ const checkpointPath = this.checkpointPath(namespace, schemaVersion);
+ const existing = await this.readCheckpointIfExists(checkpointPath);
+ if (existing) {
+ this.assertCaptureFingerprint(existing, await this.readCaptureFingerprint());
+ return this.stateOf(checkpointPath, existing);
+ }
+
+ /** Reserve outside the file lock so a slow database connection cannot stale the local lock. */
+ const baseRevision = await this.options.reserveRevisionWithWriteFence();
+ if (!Number.isSafeInteger(baseRevision) || baseRevision < 1) {
+ throw new Error('Failed to reserve a valid search reindex base revision');
+ }
+ return this.withCheckpointLock(checkpointPath, async () => {
+ const concurrentlyCreated = await this.readCheckpointIfExists(checkpointPath);
+ const captureFingerprint = await this.readCaptureFingerprint();
+ if (concurrentlyCreated) {
+ this.assertCaptureFingerprint(concurrentlyCreated, captureFingerprint);
+ return this.stateOf(checkpointPath, concurrentlyCreated);
+ }
+
+ const timestamp = now();
+ const checkpoint: FtsSearchReindexCheckpointFile = {
+ failures: [],
+ formatVersion: CHECKPOINT_FORMAT_VERSION,
+ progress: FTS_SEARCH_DOCUMENT_ENTITIES.map((entity) => ({
+ completedAt: null,
+ cursor: null,
+ entity,
+ failedCount: 0,
+ indexedCount: 0,
+ physicalIndex: getFtsSearchPhysicalIndexName(namespace, entity, schemaVersion),
+ processedCount: 0,
+ status: 'pending',
+ })),
+ run: {
+ aliasesCreatedAt: null,
+ backfillHighWaterRevision: null,
+ baseRevision,
+ captureFingerprint,
+ createdAt: timestamp,
+ id: randomUUID(),
+ namespace,
+ schemaVersion,
+ status: 'backfilling',
+ updatedAt: timestamp,
+ },
+ };
+ await this.writeCheckpoint(checkpointPath, checkpoint);
+ return this.stateOf(checkpointPath, checkpoint);
+ });
+ }
+
+ async getTargetRun(
+ namespace: string,
+ schemaVersion: number,
+ ): Promise<FtsSearchReindexRunState | undefined> {
+ const checkpointPath = this.checkpointPath(namespace, schemaVersion);
+ const checkpoint = await this.readCheckpointIfExists(checkpointPath);
+ return checkpoint ? this.stateOf(checkpointPath, checkpoint) : undefined;
+ }
+
+ async getRun(runId: string): Promise<FtsSearchReindexRunState | undefined> {
+ const checkpointPath = await this.findCheckpointPath(runId);
+ if (!checkpointPath) return;
+ return this.stateOf(checkpointPath, await this.readCheckpoint(checkpointPath));
+ }
+
+ async listUnresolvedFailures(runId: string, entity?: FtsSearchDocumentEntity) {
+ const checkpointPath = await this.findCheckpointPath(runId);
+ if (!checkpointPath) throw new Error(`Missing reindex run ${runId}`);
+ const checkpoint = await this.readCheckpoint(checkpointPath);
+ return checkpoint.failures.filter(
+ (failure) => !failure.resolvedAt && (!entity || failure.entity === entity),
+ );
+ }
+
+ async markReadyForIncrementalSync(runId: string): Promise<void> {
+ /** Read outside the file lock so a slow database connection cannot stale the local lock. */
+ const highWaterRevision = await this.options.readHighWaterRevision();
+ if (!Number.isSafeInteger(highWaterRevision) || highWaterRevision < 0) {
+ throw new Error('Failed to read a valid search reindex high-water revision');
+ }
+ await this.updateCheckpoint(runId, (checkpoint) => {
+ const incomplete = checkpoint.progress.find((progress) => progress.status !== 'completed');
+ const unresolved = checkpoint.failures.find((failure) => !failure.resolvedAt);
+ if (incomplete || unresolved) {
+ throw new Error(
+ 'Cannot create aliases before every reindex entity and failure is complete',
+ );
+ }
+ checkpoint.run.aliasesCreatedAt = now();
+ checkpoint.run.backfillHighWaterRevision = highWaterRevision;
+ checkpoint.run.status = 'ready_for_incremental_sync';
+ });
+ }
+
+ async resolveFailures(
+ runId: string,
+ entity: FtsSearchDocumentEntity,
+ documentIds: string[],
+ ): Promise<number> {
+ if (documentIds.length === 0) return 0;
+ return this.updateCheckpoint(runId, (checkpoint) => {
+ const documentIdSet = new Set(documentIds);
+ const resolved = checkpoint.failures.filter(
+ (failure) =>
+ failure.entity === entity && documentIdSet.has(failure.documentId) && !failure.resolvedAt,
+ );
+ const resolvedAt = now();
+ for (const failure of resolved) failure.resolvedAt = resolvedAt;
+
+ const progress = checkpoint.progress.find((item) => item.entity === entity);
+ if (!progress) throw new Error(`Missing reindex progress for ${entity}`);
+ progress.failedCount = unresolvedFailureCount(checkpoint, entity);
+ progress.indexedCount += resolved.length;
+ return resolved.length;
+ });
+ }
+
+ /** Resolves one failure by explicit operator decision without counting it as indexed. */
+ async skipFailure(
+ runId: string,
+ entity: FtsSearchDocumentEntity,
+ documentId: string,
+ ): Promise<boolean> {
+ return this.updateCheckpoint(runId, (checkpoint) => {
+ const failure = checkpoint.failures.find(
+ (item) =>
+ item.entity === entity &&
+ item.documentId === documentId &&
+ !item.resolvedAt &&
+ !item.retryable,
+ );
+ if (!failure) return false;
+ failure.error = `Skipped by operator: ${failure.error}`.slice(0, 4000);
+ failure.resolvedAt = now();
+
+ const progress = checkpoint.progress.find((item) => item.entity === entity);
+ if (!progress) throw new Error(`Missing reindex progress for ${entity}`);
+ progress.failedCount = unresolvedFailureCount(checkpoint, entity);
+ return true;
+ });
+ }
+}
+
+export type { FtsSearchReindexHttpClientOptions } from './elasticsearch';
+export { FtsSearchReindexHttpClient, FtsSearchReindexRequestError } from './elasticsearch';
+export type {
+ FtsSearchReindexAuditEvent,
+ FtsSearchReindexAuditValue,
+ FtsSearchReindexFileLoggerOptions,
+} from './logger';
+export { FtsSearchReindexFileLogger, summarizeFtsSearchReindexError } from './logger';
+export type {
+ FtsSearchReindexElasticsearchClient,
+ FtsSearchReindexIndexBody,
+ FtsSearchReindexProgressEvent,
+ FtsSearchReindexResult,
+ FtsSearchReindexServiceOptions,
+ FtsSearchReindexStateRepository,
+} from './service';
+export { FtsSearchReindexEntityError, FtsSearchReindexService } from './service';
diff --git a/packages/database/src/repositories/ftsSearchReindex/logger.ts b/packages/database/src/repositories/ftsSearchReindex/logger.ts
new file mode 100644
index 00000000000..a48ba200d7c
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchReindex/logger.ts
@@ -0,0 +1,130 @@
+import { randomUUID } from 'node:crypto';
+import { mkdir, open, rename, unlink } from 'node:fs/promises';
+import path from 'node:path';
+
+import { isRecord } from '@lobechat/utils/object';
+
+import type { FtsSearchReindexProgressEvent } from './service';
+
+type JsonPrimitive = boolean | null | number | string;
+export type FtsSearchReindexAuditValue =
+ JsonPrimitive | FtsSearchReindexAuditValue[] | { [key: string]: FtsSearchReindexAuditValue };
+
+export interface FtsSearchReindexAuditEvent {
+ [key: string]: FtsSearchReindexAuditValue;
+ type: string;
+}
+
+export interface FtsSearchReindexFileLoggerOptions {
+ runId: string;
+ sessionId: string;
+ stateDirectory: string;
+}
+
+const FORBIDDEN_FIELD_PATTERN =
+ /(?:api.?key|database.?url|dsn|elasticsearch.?url|password|secret|token|url)$/i;
+const URL_PATTERN = /\b[a-z][a-z\d+.-]*:\/\/[^\s)\]}"']+/gi;
+const CREDENTIAL_ASSIGNMENT_PATTERN =
+ /(api.?key|authorization|credential|password|secret|token)\s*[:=]\s*[^\s,;]+/gi;
+
+export const summarizeFtsSearchReindexError = (error: unknown) => {
+ const message = error instanceof Error ? error.message : String(error);
+ return message
+ .replaceAll(URL_PATTERN, '[redacted-url]')
+ .replaceAll(CREDENTIAL_ASSIGNMENT_PATTERN, '$1=[redacted]')
+ .slice(0, 1000);
+};
+
+const assertCredentialSafe = (value: unknown, fieldPath = 'event'): void => {
+ if (Array.isArray(value)) {
+ for (const [index, item] of value.entries()) {
+ assertCredentialSafe(item, `${fieldPath}[${index}]`);
+ }
+ return;
+ }
+ if (!isRecord(value)) return;
+ for (const [key, child] of Object.entries(value)) {
+ if (FORBIDDEN_FIELD_PATTERN.test(key)) {
+ throw new Error(`FTS reindex audit log refuses credential-shaped field ${fieldPath}.${key}`);
+ }
+ assertCredentialSafe(child, `${fieldPath}.${key}`);
+ }
+};
+
+/** Private append-only operational audit log stored beside the durable reindex checkpoint. */
+export class FtsSearchReindexFileLogger {
+ readonly eventsPath: string;
+ readonly runDirectory: string;
+ readonly summaryPath: string;
+ private writeQueue: Promise<void> = Promise.resolve();
+
+ constructor(private readonly options: FtsSearchReindexFileLoggerOptions) {
+ const safeRunId = options.runId.replaceAll(/[^\w-]/g, '_').slice(0, 128) || 'run';
+ this.runDirectory = path.join(path.resolve(options.stateDirectory), 'runs', safeRunId);
+ this.eventsPath = path.join(this.runDirectory, 'events.jsonl');
+ this.summaryPath = path.join(this.runDirectory, 'summary.json');
+ }
+
+ private enqueue(operation: () => Promise<void>) {
+ const result = this.writeQueue.then(operation);
+ /** A failed append is returned to its caller without poisoning every later audit write. */
+ this.writeQueue = result.catch(() => {});
+ return result;
+ }
+
+ private async ensureRunDirectory() {
+ await mkdir(this.runDirectory, { mode: 0o700, recursive: true });
+ }
+
+ append(event: FtsSearchReindexAuditEvent | FtsSearchReindexProgressEvent) {
+ assertCredentialSafe(event);
+ const record = {
+ ...event,
+ at: new Date().toISOString(),
+ runId: this.options.runId,
+ sessionId: this.options.sessionId,
+ };
+ return this.enqueue(async () => {
+ await this.ensureRunDirectory();
+ const file = await open(this.eventsPath, 'a', 0o600);
+ try {
+ await file.writeFile(`${JSON.stringify(record)}\n`, 'utf8');
+ await file.sync();
+ } finally {
+ await file.close();
+ }
+ });
+ }
+
+ writeSummary<Summary extends { [key: string]: FtsSearchReindexAuditValue }>(summary: Summary) {
+ assertCredentialSafe(summary, 'summary');
+ const record = {
+ ...summary,
+ runId: this.options.runId,
+ updatedAt: new Date().toISOString(),
+ };
+ return this.enqueue(async () => {
+ await this.ensureRunDirectory();
+ const temporaryPath = `${this.summaryPath}.${process.pid}.${randomUUID()}.tmp`;
+ let temporaryFile;
+ try {
+ temporaryFile = await open(temporaryPath, 'wx', 0o600);
+ await temporaryFile.writeFile(`${JSON.stringify(record, null, 2)}\n`, 'utf8');
+ await temporaryFile.sync();
+ await temporaryFile.close();
+ temporaryFile = undefined;
+ await rename(temporaryPath, this.summaryPath);
+ const directory = await open(this.runDirectory, 'r');
+ try {
+ await directory.sync();
+ } finally {
+ await directory.close();
+ }
+ } catch (error) {
+ await temporaryFile?.close().catch(() => {});
+ await unlink(temporaryPath).catch(() => {});
+ throw error;
+ }
+ });
+ }
+}
diff --git a/packages/database/src/repositories/ftsSearchReindex/service.ts b/packages/database/src/repositories/ftsSearchReindex/service.ts
new file mode 100644
index 00000000000..ba14ac36fd9
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchReindex/service.ts
@@ -0,0 +1,674 @@
+import type { FtsSearchDocumentEntity } from '@lobechat/types';
+import { FTS_SEARCH_DOCUMENT_ENTITIES } from '@lobechat/types';
+import { isRecord } from '@lobechat/utils/object';
+
+import type { FtsSearchDocumentBuilder } from '../ftsSearchDocument';
+import {
+ FTS_SEARCH_INDEX_ANALYSIS,
+ FTS_SEARCH_INDEX_DEFINITIONS,
+ getFtsSearchIndexAlias,
+} from '../ftsSearchDocument';
+import type {
+ FtsSearchReindexBatchFailure,
+ FtsSearchReindexFileRepository,
+ FtsSearchReindexRunState,
+} from '.';
+
+export interface FtsSearchReindexBulkItemResult {
+ error?: unknown;
+ status: number;
+}
+
+export interface FtsSearchReindexElasticsearchClient {
+ bulk: (body: string) => Promise<FtsSearchReindexBulkItemResult[]>;
+ count: (index: string) => Promise<number>;
+ ensureAlias: (alias: string, physicalIndex: string) => Promise<void>;
+ ensureIndex: (
+ index: string,
+ body: FtsSearchReindexIndexBody,
+ options?: FtsSearchReindexIndexOptions,
+ ) => Promise<void>;
+ refresh: (index: string) => Promise<void>;
+}
+
+export interface FtsSearchReindexIndexOptions {
+ createIfMissing?: boolean;
+}
+
+export interface FtsSearchReindexIndexBody {
+ mappings: (typeof FTS_SEARCH_INDEX_DEFINITIONS)[FtsSearchDocumentEntity]['mappings'] & {
+ _meta: { reindex_run_id: string; schema_version: number };
+ };
+ settings: { analysis: typeof FTS_SEARCH_INDEX_ANALYSIS };
+}
+
+export interface FtsSearchReindexServiceOptions {
+ batchSize: number;
+ bulkConcurrency: number;
+ bulkMaxBytes: number;
+ entityConcurrency: number;
+ maxBatchesPerEntity?: number;
+ maxRequestRetries: number;
+ onProgress: (event: FtsSearchReindexProgressEvent) => Promise<void> | void;
+ retryBaseDelayMs: number;
+ validateIncrementalSyncSource: () => Promise<void> | void;
+}
+
+export type FtsSearchReindexStateRepository = Pick<
+ FtsSearchReindexFileRepository,
+ | 'checkpointBatch'
+ | 'completeEntity'
+ | 'createOrResume'
+ | 'getRun'
+ | 'listUnresolvedFailures'
+ | 'markReadyForIncrementalSync'
+ | 'resolveFailures'
+>;
+
+export type FtsSearchReindexProgressEvent =
+ | {
+ bulkRequests: number;
+ bytes: number;
+ cursor: string;
+ durationMs: number;
+ entity: FtsSearchDocumentEntity;
+ failed: number;
+ indexed: number;
+ processed: number;
+ checkpoint: { failed: number; indexed: number; scanned: number };
+ type: 'batch';
+ }
+ | { count: number; entity: FtsSearchDocumentEntity; type: 'entity_completed' }
+ | {
+ actualCursor: string | null;
+ entity: FtsSearchDocumentEntity;
+ expectedCursor: string | null;
+ type: 'checkpoint_conflict';
+ }
+ | {
+ attempt: number;
+ delayMs: number;
+ entity: FtsSearchDocumentEntity;
+ errorType: string;
+ status?: number;
+ type: 'bulk_retry';
+ }
+ | {
+ attempts: number;
+ bytes: number;
+ durationMs: number;
+ entity: FtsSearchDocumentEntity;
+ operations: number;
+ result: 'request_error' | 'response_error' | 'success';
+ type: 'bulk_completed';
+ }
+ | { entity: FtsSearchDocumentEntity; type: 'entity_started' }
+ | {
+ checkpointCount: number;
+ drift: number;
+ elasticsearchCount: number;
+ entity: FtsSearchDocumentEntity;
+ type: 'reconciliation';
+ }
+ | { type: 'aliases_created' }
+ | { type: 'run_paused' };
+
+export interface FtsSearchReindexResult {
+ runId: string;
+ status: FtsSearchReindexRunState['run']['status'];
+}
+
+export class FtsSearchReindexEntityError extends Error {
+ constructor(
+ readonly entity: FtsSearchDocumentEntity,
+ cause: unknown,
+ ) {
+ const causeMessage = cause instanceof Error ? cause.message : String(cause);
+ super(`FTS reindex failed for ${entity}: ${causeMessage}`, { cause });
+ this.name = 'FtsSearchReindexEntityError';
+ }
+}
+
+interface BulkOperation {
+ body: string;
+ bytes: number;
+ documentId: string;
+}
+
+const DEFAULT_BATCH_SIZE = 500;
+const DEFAULT_BULK_CONCURRENCY = 1;
+const DEFAULT_BULK_MAX_BYTES = 50 * 1024 * 1024;
+const DEFAULT_ENTITY_CONCURRENCY = 1;
+const DEFAULT_MAX_REQUEST_RETRIES = 4;
+const DEFAULT_RETRY_BASE_DELAY_MS = 500;
+const textEncoder = new TextEncoder();
+
+const errorStatus = (error: unknown) =>
+ isRecord(error) && typeof error.status === 'number' ? error.status : undefined;
+
+const isRetryableRequestError = (error: unknown) => {
+ const status = errorStatus(error);
+ return status === undefined || status === 408 || status === 429 || status >= 500;
+};
+
+const errorType = (error: unknown) =>
+ error instanceof Error ? error.name.slice(0, 128) : 'UnknownError';
+
+const sleep = (durationMs: number) =>
+ durationMs > 0 ? new Promise((resolve) => setTimeout(resolve, durationMs)) : Promise.resolve();
+
+const mapWithConcurrency = async <Item, Result>(
+ items: readonly Item[],
+ concurrency: number,
+ operation: (item: Item, index: number) => Promise<Result>,
+): Promise<Result[]> => {
+ const results: ({ value: Result } | undefined)[] = Array.from({ length: items.length });
+ let nextIndex = 0;
+ let firstFailure: { error: unknown } | undefined;
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
+ while (!firstFailure) {
+ const index = nextIndex;
+ nextIndex += 1;
+ if (index >= items.length) return;
+ try {
+ results[index] = { value: await operation(items[index], index) };
+ } catch (error) {
+ firstFailure ??= { error };
+ }
+ }
+ });
+ await Promise.all(workers);
+ if (firstFailure) throw firstFailure.error;
+ return results.map((result, index) => {
+ if (!result) throw new Error(`Missing concurrent operation result at index ${index}`);
+ return result.value;
+ });
+};
+
+const isPermanentElasticsearchStatus = (status: number) =>
+ status >= 400 && status < 500 && status !== 408 && status !== 409 && status !== 429;
+
+const describeBulkError = (status: number, error: unknown) => {
+ const type =
+ isRecord(error) && typeof error.type === 'string' ? error.type.slice(0, 128) : 'unknown';
+ return new Error(`Elasticsearch bulk item failed (${status}, type=${type})`);
+};
+
+const buildBulkOperation = (
+ documentId: string,
+ index: string,
+ revision: number,
+ source: Record<string, unknown>,
+): BulkOperation => {
+ const metadata = {
+ index: {
+ _id: documentId,
+ _index: index,
+ version: revision,
+ version_type: 'external_gte',
+ },
+ };
+ const body = `${JSON.stringify(metadata)}\n${JSON.stringify(source)}\n`;
+ return { body, bytes: textEncoder.encode(body).byteLength, documentId };
+};
+
+/** Resumable full backfill that leaves product reads on PostgreSQL. */
+export class FtsSearchReindexService {
+ private readonly options: FtsSearchReindexServiceOptions;
+ private preparedRunId?: string;
+
+ constructor(
+ private readonly builder: Pick<FtsSearchDocumentBuilder, 'buildBatch' | 'buildByIds'>,
+ private readonly repository: FtsSearchReindexStateRepository,
+ private readonly client: FtsSearchReindexElasticsearchClient,
+ options: Partial<FtsSearchReindexServiceOptions> = {},
+ ) {
+ this.options = {
+ batchSize: options.batchSize ?? DEFAULT_BATCH_SIZE,
+ bulkConcurrency: options.bulkConcurrency ?? DEFAULT_BULK_CONCURRENCY,
+ bulkMaxBytes: options.bulkMaxBytes ?? DEFAULT_BULK_MAX_BYTES,
+ entityConcurrency: options.entityConcurrency ?? DEFAULT_ENTITY_CONCURRENCY,
+ maxBatchesPerEntity: options.maxBatchesPerEntity,
+ maxRequestRetries: options.maxRequestRetries ?? DEFAULT_MAX_REQUEST_RETRIES,
+ onProgress: options.onProgress ?? (() => {}),
+ retryBaseDelayMs: options.retryBaseDelayMs ?? DEFAULT_RETRY_BASE_DELAY_MS,
+ validateIncrementalSyncSource: options.validateIncrementalSyncSource ?? (() => {}),
+ };
+ if (!Number.isInteger(this.options.batchSize) || this.options.batchSize < 1) {
+ throw new Error('FTS reindex batch size must be a positive integer');
+ }
+ if (!Number.isInteger(this.options.bulkMaxBytes) || this.options.bulkMaxBytes < 1) {
+ throw new Error('FTS reindex bulk byte limit must be a positive integer');
+ }
+ if (!Number.isInteger(this.options.bulkConcurrency) || this.options.bulkConcurrency < 1) {
+ throw new Error('FTS reindex bulk concurrency must be a positive integer');
+ }
+ if (!Number.isInteger(this.options.entityConcurrency) || this.options.entityConcurrency < 1) {
+ throw new Error('FTS reindex entity concurrency must be a positive integer');
+ }
+ if (
+ this.options.maxBatchesPerEntity !== undefined &&
+ (!Number.isInteger(this.options.maxBatchesPerEntity) || this.options.maxBatchesPerEntity < 1)
+ ) {
+ throw new Error('FTS reindex maximum batches per entity must be a positive integer');
+ }
+ if (!Number.isInteger(this.options.maxRequestRetries) || this.options.maxRequestRetries < 0) {
+ throw new Error('FTS reindex request retries must be a non-negative integer');
+ }
+ if (!Number.isInteger(this.options.retryBaseDelayMs) || this.options.retryBaseDelayMs < 0) {
+ throw new Error('FTS reindex retry delay must be a non-negative integer');
+ }
+ }
+
+ private async emitProgress(event: FtsSearchReindexProgressEvent) {
+ await this.options.onProgress(event);
+ }
+
+ /**
+ * Create and validate every physical index before the backfill starts so required Elasticsearch
+ * analysis capabilities, including analysis-icu, fail fast.
+ */
+ async prepareIndices(state: FtsSearchReindexRunState): Promise<void> {
+ if (this.preparedRunId === state.run.id) return;
+
+ await mapWithConcurrency(
+ state.progress,
+ this.options.entityConcurrency,
+ async ({ entity, physicalIndex, status }) => {
+ try {
+ await this.client.ensureIndex(
+ physicalIndex,
+ {
+ mappings: {
+ ...FTS_SEARCH_INDEX_DEFINITIONS[entity].mappings,
+ _meta: {
+ reindex_run_id: state.run.id,
+ schema_version: state.run.schemaVersion,
+ },
+ },
+ settings: { analysis: FTS_SEARCH_INDEX_ANALYSIS },
+ },
+ { createIfMissing: status !== 'completed' },
+ );
+ } catch (error) {
+ throw new FtsSearchReindexEntityError(entity, error);
+ }
+ },
+ );
+ this.preparedRunId = state.run.id;
+ }
+
+ private async flushBulk(
+ entity: FtsSearchDocumentEntity,
+ operations: BulkOperation[],
+ ): Promise<{
+ failures: FtsSearchReindexBatchFailure[];
+ indexedDocumentIds: string[];
+ }> {
+ if (operations.length === 0) return { failures: [], indexedDocumentIds: [] };
+
+ const body = operations.map((operation) => operation.body).join('');
+ const bytes = operations.reduce((total, operation) => total + operation.bytes, 0);
+ const startedAt = Date.now();
+ let attempts = 0;
+ let results: FtsSearchReindexBulkItemResult[];
+ while (true) {
+ attempts += 1;
+ try {
+ results = await this.client.bulk(body);
+ break;
+ } catch (error) {
+ if (!isRetryableRequestError(error) || attempts > this.options.maxRequestRetries) {
+ await this.emitProgress({
+ attempts,
+ bytes,
+ durationMs: Date.now() - startedAt,
+ entity,
+ operations: operations.length,
+ result: 'request_error',
+ type: 'bulk_completed',
+ });
+ throw error;
+ }
+ const exponentialDelay = this.options.retryBaseDelayMs * 2 ** (attempts - 1);
+ const delayMs = Math.floor(Math.random() * exponentialDelay);
+ await this.emitProgress({
+ attempt: attempts,
+ delayMs,
+ entity,
+ errorType: errorType(error),
+ status: errorStatus(error),
+ type: 'bulk_retry',
+ });
+ await sleep(delayMs);
+ }
+ }
+ if (results.length !== operations.length) {
+ await this.emitProgress({
+ attempts,
+ bytes,
+ durationMs: Date.now() - startedAt,
+ entity,
+ operations: operations.length,
+ result: 'response_error',
+ type: 'bulk_completed',
+ });
+ throw new Error(
+ `Elasticsearch bulk returned ${results.length} items for ${operations.length} operations`,
+ );
+ }
+ await this.emitProgress({
+ attempts,
+ bytes,
+ durationMs: Date.now() - startedAt,
+ entity,
+ operations: operations.length,
+ result: 'success',
+ type: 'bulk_completed',
+ });
+
+ const failures: FtsSearchReindexBatchFailure[] = [];
+ const indexedDocumentIds: string[] = [];
+ for (const [index, operation] of operations.entries()) {
+ const result = results[index];
+ if ((result.status >= 200 && result.status < 300) || result.status === 409) {
+ indexedDocumentIds.push(operation.documentId);
+ } else {
+ failures.push({
+ documentId: operation.documentId,
+ error: describeBulkError(result.status, result.error),
+ retryable: !isPermanentElasticsearchStatus(result.status),
+ });
+ }
+ }
+
+ return { failures, indexedDocumentIds };
+ }
+
+ private async indexDocuments(
+ documents: { id: string; source: Record<string, unknown> }[],
+ entity: FtsSearchDocumentEntity,
+ physicalIndex: string,
+ revision: number,
+ ) {
+ const failures: FtsSearchReindexBatchFailure[] = [];
+ const indexedDocumentIds: string[] = [];
+ const inFlight = new Set<Promise<void>>();
+ let bulkRequests = 0;
+ let bytes = 0;
+ let firstFailure: { error: unknown } | undefined;
+ let bulk: BulkOperation[] = [];
+ let bulkBytes = 0;
+
+ const waitForAvailableSlot = async () => {
+ if (inFlight.size < this.options.bulkConcurrency) return;
+ await Promise.race(inFlight);
+ if (firstFailure) {
+ await Promise.all(inFlight);
+ throw firstFailure.error;
+ }
+ };
+
+ const flushQueuedBulk = async () => {
+ if (bulk.length === 0) return;
+ const operations = bulk;
+ bulkRequests += 1;
+ bytes += bulkBytes;
+ bulk = [];
+ bulkBytes = 0;
+ const task = this.flushBulk(entity, operations)
+ .then((result) => {
+ failures.push(...result.failures);
+ indexedDocumentIds.push(...result.indexedDocumentIds);
+ })
+ .catch((error) => {
+ firstFailure ??= { error };
+ });
+ inFlight.add(task);
+ void task.then(() => inFlight.delete(task));
+ await waitForAvailableSlot();
+ };
+
+ for (const document of documents) {
+ const operation = buildBulkOperation(document.id, physicalIndex, revision, document.source);
+ if (operation.bytes > this.options.bulkMaxBytes) {
+ failures.push({
+ documentId: document.id,
+ error: new Error(
+ `FTS search document is ${operation.bytes} bytes and exceeds the ${this.options.bulkMaxBytes}-byte bulk limit`,
+ ),
+ retryable: false,
+ });
+ continue;
+ }
+ if (bulk.length > 0 && bulkBytes + operation.bytes > this.options.bulkMaxBytes) {
+ await flushQueuedBulk();
+ }
+ bulk.push(operation);
+ bulkBytes += operation.bytes;
+ }
+ await flushQueuedBulk();
+ await Promise.all(inFlight);
+ if (firstFailure) throw firstFailure.error;
+
+ return {
+ bulkRequests,
+ bytes,
+ failures,
+ indexedDocumentIds,
+ };
+ }
+
+ private async retryFailures(state: FtsSearchReindexRunState, entity: FtsSearchDocumentEntity) {
+ const failures = await this.repository.listUnresolvedFailures(state.run.id, entity);
+ if (failures.length === 0) return;
+
+ const documents = await this.builder.buildByIds(
+ entity,
+ failures.map(({ documentId }) => documentId),
+ );
+ const sources = new Map(
+ documents.map((document) => [document.id, document.source as Record<string, unknown>]),
+ );
+ const progress = state.progress.find((item) => item.entity === entity);
+ if (!progress) throw new Error(`Missing reindex progress for ${entity}`);
+
+ const retryDocuments = failures.map(({ documentId }) => ({
+ id: documentId,
+ /** A source row deleted during backfill remains versioned until the outbox applies its deletion. */
+ source:
+ sources.get(documentId) ??
+ ({ id: documentId, fts_search_sync_deleted: true } as Record<string, unknown>),
+ }));
+ const result = await this.indexDocuments(
+ retryDocuments,
+ entity,
+ progress.physicalIndex,
+ state.run.baseRevision,
+ );
+ await this.repository.resolveFailures(state.run.id, entity, result.indexedDocumentIds);
+ if (result.failures.length > 0) {
+ const checkpointed = await this.repository.checkpointBatch({
+ cursor: progress.cursor ?? '',
+ entity,
+ failures: result.failures,
+ indexedCount: 0,
+ previousCursor: progress.cursor,
+ processedCount: 0,
+ runId: state.run.id,
+ });
+ if (!checkpointed) {
+ const refreshed = await this.repository.getRun(state.run.id);
+ await this.emitProgress({
+ actualCursor: refreshed?.progress.find((item) => item.entity === entity)?.cursor ?? null,
+ entity,
+ expectedCursor: progress.cursor,
+ type: 'checkpoint_conflict',
+ });
+ }
+ }
+ }
+
+ private async runEntity(state: FtsSearchReindexRunState, entity: FtsSearchDocumentEntity) {
+ let progress = state.progress.find((item) => item.entity === entity);
+ if (!progress) throw new Error(`Missing reindex progress for ${entity}`);
+ if (progress.status === 'completed') return true;
+
+ await this.emitProgress({ entity, type: 'entity_started' });
+
+ let processedBatches = 0;
+ let sourceExhausted = false;
+ while (true) {
+ const batchStartedAt = Date.now();
+ const documents = await this.builder.buildBatch(entity, {
+ afterId: progress.cursor ?? undefined,
+ limit: this.options.batchSize,
+ });
+ if (documents.length === 0) {
+ sourceExhausted = true;
+ break;
+ }
+
+ const result = await this.indexDocuments(
+ documents.map((document) => ({
+ id: document.id,
+ source: document.source as Record<string, unknown>,
+ })),
+ entity,
+ progress.physicalIndex,
+ state.run.baseRevision,
+ );
+ const checkpointed = await this.repository.checkpointBatch({
+ cursor: documents.at(-1)!.id,
+ entity,
+ failures: result.failures,
+ indexedCount: result.indexedDocumentIds.length,
+ previousCursor: progress.cursor,
+ processedCount: documents.length,
+ runId: state.run.id,
+ });
+ const refreshed = await this.repository.getRun(state.run.id);
+ const checkpointProgress = refreshed?.progress.find((item) => item.entity === entity);
+ if (checkpointed) {
+ if (!checkpointProgress)
+ throw new Error(`Missing refreshed reindex progress for ${entity}`);
+ await this.emitProgress({
+ bulkRequests: result.bulkRequests,
+ bytes: result.bytes,
+ checkpoint: {
+ failed: checkpointProgress.failedCount,
+ indexed: checkpointProgress.indexedCount,
+ scanned: checkpointProgress.processedCount,
+ },
+ cursor: documents.at(-1)!.id,
+ durationMs: Date.now() - batchStartedAt,
+ entity,
+ failed: result.failures.length,
+ indexed: result.indexedDocumentIds.length,
+ processed: documents.length,
+ type: 'batch',
+ });
+ } else {
+ await this.emitProgress({
+ actualCursor: checkpointProgress?.cursor ?? null,
+ entity,
+ expectedCursor: progress.cursor,
+ type: 'checkpoint_conflict',
+ });
+ }
+ progress = checkpointProgress;
+ if (!progress) throw new Error(`Missing refreshed reindex progress for ${entity}`);
+ processedBatches += 1;
+ if (documents.length < this.options.batchSize) {
+ /** buildBatch applies LIMIT without post-query filtering, so a short keyset page is final. */
+ sourceExhausted = true;
+ break;
+ }
+ if (
+ this.options.maxBatchesPerEntity !== undefined &&
+ processedBatches >= this.options.maxBatchesPerEntity
+ ) {
+ break;
+ }
+ }
+
+ if (!sourceExhausted) return false;
+
+ const refreshedState = await this.repository.getRun(state.run.id);
+ if (!refreshedState) throw new Error(`Missing reindex run ${state.run.id}`);
+ await this.retryFailures(refreshedState, entity);
+ const unresolved = await this.repository.listUnresolvedFailures(state.run.id, entity);
+ if (unresolved.length > 0) {
+ throw new Error(`Reindex paused with ${unresolved.length} unresolved ${entity} failures`);
+ }
+
+ const finalState = await this.repository.getRun(state.run.id);
+ const finalProgress = finalState?.progress.find((item) => item.entity === entity);
+ if (!finalProgress) throw new Error(`Missing final reindex progress for ${entity}`);
+ await this.client.refresh(finalProgress.physicalIndex);
+ const indexedCount = await this.client.count(finalProgress.physicalIndex);
+ await this.emitProgress({
+ checkpointCount: finalProgress.indexedCount,
+ drift: indexedCount - finalProgress.indexedCount,
+ elasticsearchCount: indexedCount,
+ entity,
+ type: 'reconciliation',
+ });
+ if (indexedCount !== finalProgress.indexedCount) {
+ throw new Error(
+ `Reindex count mismatch for ${entity}: checkpoint=${finalProgress.indexedCount}, Elasticsearch=${indexedCount}`,
+ );
+ }
+ await this.repository.completeEntity(state.run.id, entity);
+ await this.emitProgress({ count: indexedCount, entity, type: 'entity_completed' });
+ return true;
+ }
+
+ async run(namespace: string, schemaVersion: number): Promise<FtsSearchReindexResult> {
+ const initialState = await this.repository.createOrResume(namespace, schemaVersion);
+ if (initialState.run.status === 'ready_for_incremental_sync') {
+ return {
+ runId: initialState.run.id,
+ status: initialState.run.status,
+ };
+ }
+
+ await this.prepareIndices(initialState);
+
+ const completed = await mapWithConcurrency(
+ FTS_SEARCH_DOCUMENT_ENTITIES,
+ this.options.entityConcurrency,
+ async (entity) => {
+ const currentState = await this.repository.getRun(initialState.run.id);
+ if (!currentState) throw new Error(`Missing reindex run ${initialState.run.id}`);
+ try {
+ return await this.runEntity(currentState, entity);
+ } catch (error) {
+ throw new FtsSearchReindexEntityError(entity, error);
+ }
+ },
+ );
+
+ if (completed.some((value) => !value)) {
+ await this.emitProgress({ type: 'run_paused' });
+ return { runId: initialState.run.id, status: 'backfilling' };
+ }
+
+ const completedState = await this.repository.getRun(initialState.run.id);
+ if (!completedState) throw new Error(`Missing reindex run ${initialState.run.id}`);
+ await this.options.validateIncrementalSyncSource();
+ for (const progress of completedState.progress) {
+ await this.client.ensureAlias(
+ getFtsSearchIndexAlias(namespace, progress.entity),
+ progress.physicalIndex,
+ );
+ }
+ await this.repository.markReadyForIncrementalSync(initialState.run.id);
+ await this.emitProgress({ type: 'aliases_created' });
+
+ return {
+ runId: initialState.run.id,
+ status: 'ready_for_incremental_sync',
+ };
+ }
+}
diff --git a/packages/database/src/repositories/ftsSearchSyncOutbox/__tests__/index.test.ts b/packages/database/src/repositories/ftsSearchSyncOutbox/__tests__/index.test.ts
new file mode 100644
index 00000000000..3d033079453
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchSyncOutbox/__tests__/index.test.ts
@@ -0,0 +1,875 @@
+// @vitest-environment node
+import path from 'node:path';
+
+import type { SQL } from 'drizzle-orm';
+import { and, eq, inArray, sql } from 'drizzle-orm';
+import { readMigrationFiles } from 'drizzle-orm/migrator';
+import { PgDialect } from 'drizzle-orm/pg-core';
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agents, ftsSearchSyncOutbox, users } from '../../../schemas';
+import { FtsSearchDocumentBuilder } from '../../ftsSearchDocument';
+import { FtsSearchSyncOutboxRepository } from '..';
+import {
+ FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS,
+ FTS_SEARCH_SYNC_MEMORY_CONTEXTS_GIN_INDEX,
+} from '../captureInfrastructure';
+
+const USER_ID = 'fts-search-sync-integration-user';
+const CAPTURE_INSTALL_TEST_TIMEOUT = 30_000;
+const FTS_SEARCH_SYNC_TRIGGER_TARGETS = [
+ { name: 'fts_search_sync_agents', table: 'agents' },
+ { name: 'fts_search_sync_chat_groups', table: 'chat_groups' },
+ { name: 'fts_search_sync_documents', table: 'documents' },
+ { name: 'fts_search_sync_files', table: 'files' },
+ { name: 'fts_search_sync_knowledge_base_files', table: 'knowledge_base_files' },
+ { name: 'fts_search_sync_knowledge_bases', table: 'knowledge_bases' },
+ { name: 'fts_search_sync_memory_activities', table: 'user_memories_activities' },
+ { name: 'fts_search_sync_memory_contexts', table: 'user_memories_contexts' },
+ { name: 'fts_search_sync_memory_experiences', table: 'user_memories_experiences' },
+ { name: 'fts_search_sync_memory_identities', table: 'user_memories_identities' },
+ { name: 'fts_search_sync_memory_preferences', table: 'user_memories_preferences' },
+ { name: 'fts_search_sync_messages', table: 'messages' },
+ { name: 'fts_search_sync_persona_documents', table: 'user_memory_persona_documents' },
+ { name: 'fts_search_sync_topics', table: 'topics' },
+ { name: 'fts_search_sync_user_memories', table: 'user_memories' },
+ { name: 'fts_search_sync_user_memories_fanout', table: 'user_memories' },
+] as const;
+const FTS_SEARCH_SYNC_CAPTURE_FUNCTION_NAMES = [
+ 'capture_fts_search_sync_change',
+ 'capture_fts_search_sync_knowledge_base_files',
+ 'capture_fts_search_sync_memory_fanout',
+ 'enqueue_fts_search_sync_outbox',
+] as const;
+
+const db = await getTestDB();
+const builder = new FtsSearchDocumentBuilder(db);
+const repository = new FtsSearchSyncOutboxRepository(db);
+let restoreCaptureInfrastructure = false;
+
+const sortKeys = (keys: { documentId: string; entity: string }[]) =>
+ keys.toSorted((left, right) =>
+ `${left.entity}:${left.documentId}`.localeCompare(`${right.entity}:${right.documentId}`),
+ );
+
+const normalizeSql = (statement: SQL) =>
+ new PgDialect().sqlToQuery(statement).sql.replaceAll(/\s+/g, ' ').trim();
+
+const createRecordedRepository = (revisionRows: unknown[]) => {
+ const statements: string[] = [];
+ const execute = vi.fn(async (statement: SQL) => {
+ const normalized = normalizeSql(statement);
+ statements.push(normalized);
+ return normalized.includes('FROM fts_search_sync_revision_seq') ? { rows: revisionRows } : [];
+ });
+ const database = {
+ execute,
+ transaction: async (callback: (transaction: { execute: typeof execute }) => Promise<unknown>) =>
+ callback({ execute }),
+ } as unknown as ConstructorParameters<typeof FtsSearchSyncOutboxRepository>[0];
+
+ return { repository: new FtsSearchSyncOutboxRepository(database), statements };
+};
+
+const dropCaptureInfrastructure = async () => {
+ for (const { name, table } of FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS) {
+ await db.execute(sql.raw(`DROP TRIGGER IF EXISTS "${name}" ON "${table}"`));
+ }
+
+ for (const functionName of FTS_SEARCH_SYNC_CAPTURE_FUNCTION_NAMES) {
+ const signature =
+ functionName === 'enqueue_fts_search_sync_outbox' ? '(text, text[], smallint)' : '()';
+ await db.execute(sql.raw(`DROP FUNCTION IF EXISTS "${functionName}"${signature}`));
+ }
+};
+
+const hasCompleteCaptureInfrastructure = async () => {
+ const triggerTargets = sql.join(
+ FTS_SEARCH_SYNC_TRIGGER_TARGETS.map(
+ ({ name, table }) => sql`(${name}, ${`public.${table}`}::regclass)`,
+ ),
+ sql`, `,
+ );
+ const functionNames = sql.join(
+ FTS_SEARCH_SYNC_CAPTURE_FUNCTION_NAMES.map((name) => sql`${name}`),
+ sql`, `,
+ );
+ const result = await db.execute(sql`
+ SELECT
+ EXISTS (
+ SELECT 1
+ FROM pg_index
+ WHERE indexrelid = to_regclass(${`public.${FTS_SEARCH_SYNC_MEMORY_CONTEXTS_GIN_INDEX}`})
+ AND indisready
+ AND indisvalid
+ ) AS has_gin_index,
+ (
+ SELECT count(DISTINCT proname)::integer
+ FROM pg_proc
+ WHERE pronamespace = 'public'::regnamespace
+ AND proname IN (${functionNames})
+ ) AS function_count,
+ (
+ SELECT count(*)::integer
+ FROM pg_trigger
+ WHERE NOT tgisinternal
+ AND (tgname, tgrelid) IN (${triggerTargets})
+ ) AS trigger_count,
+ (
+ SELECT count(*)::integer
+ FROM pg_trigger
+ WHERE NOT tgisinternal
+ AND tgenabled IN ('O', 'A')
+ AND (tgname, tgrelid) IN (${triggerTargets})
+ ) AS enabled_trigger_count
+ `);
+ const [row] = Array.isArray(result) ? result : result.rows;
+
+ return (
+ row?.has_gin_index === true &&
+ Number(row.function_count) === FTS_SEARCH_SYNC_CAPTURE_FUNCTION_NAMES.length &&
+ Number(row.trigger_count) === FTS_SEARCH_SYNC_TRIGGER_TARGETS.length &&
+ Number(row.enabled_trigger_count) === FTS_SEARCH_SYNC_TRIGGER_TARGETS.length
+ );
+};
+
+beforeAll(async () => {
+ restoreCaptureInfrastructure = await hasCompleteCaptureInfrastructure();
+ await dropCaptureInfrastructure();
+}, CAPTURE_INSTALL_TEST_TIMEOUT);
+
+beforeEach(async () => {
+ await db.delete(users).where(eq(users.id, USER_ID));
+ await db.delete(ftsSearchSyncOutbox);
+ await db.insert(users).values({ id: USER_ID });
+});
+
+afterAll(async () => {
+ await db.delete(users).where(eq(users.id, USER_ID));
+ await db.delete(ftsSearchSyncOutbox);
+ await dropCaptureInfrastructure();
+ if (restoreCaptureInfrastructure) {
+ await repository.installCaptureInfrastructure();
+ }
+}, CAPTURE_INSTALL_TEST_TIMEOUT);
+
+describe.sequential('FtsSearchSyncOutboxRepository', () => {
+ it('keeps optional capture infrastructure out of the deployment migration', () => {
+ const migration = readMigrationFiles({
+ migrationsFolder: path.join(__dirname, '../../../../migrations'),
+ }).find((item) =>
+ item.sql.some(
+ (statement) =>
+ statement.includes('fts_search_sync_revision_seq') &&
+ statement.includes('fts_search_sync_outbox'),
+ ),
+ );
+
+ if (!migration) throw new Error('FTS search sync migration was not generated');
+ const migrationSql = migration.sql.join('\n');
+
+ expect(migrationSql).toContain('fts_search_sync_revision_seq');
+ expect(migrationSql).toContain('fts_search_sync_outbox');
+ expect(migrationSql).not.toContain('CREATE TRIGGER');
+ expect(migrationSql).not.toContain('capture_fts_search_sync_change');
+ expect(migrationSql).not.toContain("set_config('lock_timeout', '3s', true)");
+ expect(migrationSql).toContain(FTS_SEARCH_SYNC_MEMORY_CONTEXTS_GIN_INDEX);
+ expect(migrationSql).not.toContain('fts_search_sync_settings');
+ });
+
+ it('does not install capture infrastructure or enqueue ordinary writes by default', async () => {
+ const triggerResult = await db.execute(sql`
+ SELECT tgname
+ FROM pg_trigger
+ WHERE NOT tgisinternal AND tgname LIKE 'fts_search_sync_%'
+ ORDER BY tgname
+ `);
+ const triggerRows = Array.isArray(triggerResult) ? triggerResult : triggerResult.rows;
+ expect(triggerRows).toEqual([]);
+
+ const indexResult = await db.execute(sql`
+ SELECT to_regclass(${`public.${FTS_SEARCH_SYNC_MEMORY_CONTEXTS_GIN_INDEX}`})::text AS index_name
+ `);
+ const indexRows = Array.isArray(indexResult) ? indexResult : indexResult.rows;
+ expect(indexRows).toEqual([{ index_name: FTS_SEARCH_SYNC_MEMORY_CONTEXTS_GIN_INDEX }]);
+
+ const functionResult = await db.execute(sql`
+ SELECT proname
+ FROM pg_proc
+ WHERE pronamespace = 'public'::regnamespace
+ AND proname IN (${sql.join(
+ FTS_SEARCH_SYNC_CAPTURE_FUNCTION_NAMES.map((name) => sql`${name}`),
+ sql`, `,
+ )})
+ ORDER BY proname
+ `);
+ const functionRows = Array.isArray(functionResult) ? functionResult : functionResult.rows;
+ expect(functionRows).toEqual([]);
+
+ await db.insert(agents).values({ id: 'base-agent', title: 'one', userId: USER_ID });
+ await expect(db.select().from(ftsSearchSyncOutbox)).resolves.toEqual([]);
+ });
+
+ it('replays the outbox migration safely', async () => {
+ const migration = readMigrationFiles({
+ migrationsFolder: path.join(__dirname, '../../../../migrations'),
+ }).find((item) =>
+ item.sql.some(
+ (statement) =>
+ statement.includes('fts_search_sync_revision_seq') &&
+ statement.includes('fts_search_sync_outbox'),
+ ),
+ );
+
+ if (!migration) throw new Error('FTS search sync migration was not generated');
+ for (const statement of migration.sql) await db.execute(sql.raw(statement));
+
+ const outboxResult = await db.execute(
+ sql`SELECT to_regclass('public.fts_search_sync_outbox')::text AS table_name`,
+ );
+ const outboxRows = Array.isArray(outboxResult) ? outboxResult : outboxResult.rows;
+ expect(outboxRows).toEqual([{ table_name: 'fts_search_sync_outbox' }]);
+ });
+
+ it('indexes durable dead-letter checks', async () => {
+ const result = await db.execute(sql`
+ SELECT to_regclass('fts_search_sync_outbox_dead_idx')::text AS index_name
+ `);
+ const rows = Array.isArray(result) ? result : result.rows;
+
+ expect(rows).toEqual([{ index_name: 'fts_search_sync_outbox_dead_idx' }]);
+ });
+
+ it(
+ 'requires the schema-managed GIN index and installs all exact capture triggers',
+ async () => {
+ await repository.installCaptureInfrastructure();
+
+ const result = await db.execute(sql`
+ SELECT pg_trigger.tgname, pg_trigger.tgenabled, source_table.relname AS table_name
+ FROM pg_trigger
+ JOIN pg_class AS source_table ON source_table.oid = pg_trigger.tgrelid
+ JOIN pg_namespace AS source_namespace ON source_namespace.oid = source_table.relnamespace
+ WHERE NOT tgisinternal AND tgname LIKE 'fts_search_sync_%'
+ AND source_namespace.nspname = 'public'
+ ORDER BY tgname
+ `);
+ const rows = Array.isArray(result) ? result : result.rows;
+
+ expect(rows).toEqual(
+ FTS_SEARCH_SYNC_TRIGGER_TARGETS.map(({ name: tgname, table: table_name }) => ({
+ tgname,
+ tgenabled: 'O',
+ table_name,
+ })),
+ );
+
+ const indexResult = await db.execute(sql`
+ SELECT
+ access_method.amname AS access_method,
+ indexed_attribute.attname AS indexed_column,
+ indexed_attribute.atttypid = 'jsonb'::regtype AS is_jsonb,
+ search_index.indpred IS NULL AS is_not_partial,
+ search_index.indisready AS is_ready,
+ search_index.indisvalid AS is_valid
+ FROM pg_index AS search_index
+ JOIN pg_class AS index_relation ON index_relation.oid = search_index.indexrelid
+ JOIN pg_am AS access_method ON access_method.oid = index_relation.relam
+ JOIN pg_attribute AS indexed_attribute
+ ON indexed_attribute.attrelid = search_index.indrelid
+ AND indexed_attribute.attnum = ANY(search_index.indkey)
+ WHERE search_index.indexrelid =
+ 'user_memories_contexts_user_memory_ids_gin_idx'::regclass
+ `);
+ const indexRows = Array.isArray(indexResult) ? indexResult : indexResult.rows;
+ expect(indexRows).toEqual([
+ {
+ access_method: 'gin',
+ indexed_column: 'user_memory_ids',
+ is_jsonb: true,
+ is_not_partial: true,
+ is_ready: true,
+ is_valid: true,
+ },
+ ]);
+ },
+ CAPTURE_INSTALL_TEST_TIMEOUT,
+ );
+
+ it(
+ 'keeps capture installation idempotent',
+ async () => {
+ await expect(repository.installCaptureInfrastructure()).resolves.toBeUndefined();
+ const firstResult = await db.execute(sql`
+ SELECT oid::text, tgname
+ FROM pg_trigger
+ WHERE NOT tgisinternal AND tgname LIKE 'fts_search_sync_%'
+ ORDER BY tgname
+ `);
+ const firstRows = Array.isArray(firstResult) ? firstResult : firstResult.rows;
+
+ await expect(repository.installCaptureInfrastructure()).resolves.toBeUndefined();
+
+ const result = await db.execute(sql`
+ SELECT oid::text, tgname
+ FROM pg_trigger
+ WHERE NOT tgisinternal AND tgname LIKE 'fts_search_sync_%'
+ ORDER BY tgname
+ `);
+ const rows = Array.isArray(result) ? result : result.rows;
+ expect(rows).toEqual(firstRows);
+ expect(rows).toHaveLength(16);
+ await expect(repository.readCaptureFingerprint()).resolves.toMatch(/^[a-f\d]{64}$/);
+ },
+ CAPTURE_INSTALL_TEST_TIMEOUT,
+ );
+
+ it(
+ 'atomically upgrades the known predecessor trigger definition',
+ async () => {
+ await db.execute(sql`DROP TRIGGER fts_search_sync_agents ON public.agents`);
+ await db.execute(sql`
+ CREATE TRIGGER fts_search_sync_agents
+ AFTER INSERT OR DELETE OR UPDATE OF
+ description, slug, system_role, tags, title, user_id, virtual, visibility, workspace_id
+ ON public.agents
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'agents', 'user_id', 'visibility', 'workspace_id'
+ )
+ `);
+
+ try {
+ await expect(repository.assertCaptureInfrastructure()).rejects.toThrow(
+ 'trigger fts_search_sync_agents',
+ );
+ await expect(repository.installCaptureInfrastructure()).resolves.toBeUndefined();
+ await expect(repository.assertCaptureInfrastructure()).resolves.toBeUndefined();
+ } finally {
+ try {
+ await repository.assertCaptureInfrastructure();
+ } catch {
+ await dropCaptureInfrastructure();
+ await repository.installCaptureInfrastructure();
+ }
+ }
+ },
+ CAPTURE_INSTALL_TEST_TIMEOUT,
+ );
+
+ it(
+ 'rejects a managed trigger name installed on an unexpected public table',
+ async () => {
+ await db.execute(sql`
+ CREATE TRIGGER fts_search_sync_agents
+ AFTER INSERT ON users
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change('agents', 'id')
+ `);
+ try {
+ await expect(repository.assertCaptureInfrastructure()).rejects.toThrow('triggers 17/16');
+ await expect(repository.installCaptureInfrastructure()).rejects.toThrow(
+ 'Refusing to replace partial or unknown FTS search sync capture infrastructure',
+ );
+ } finally {
+ await db.execute(sql`DROP TRIGGER IF EXISTS fts_search_sync_agents ON users`);
+ }
+
+ await expect(repository.assertCaptureInfrastructure()).resolves.toBeUndefined();
+ },
+ CAPTURE_INSTALL_TEST_TIMEOUT,
+ );
+
+ it('reserves and fences revisions for a local full-reindex checkpoint', async () => {
+ const revision = await repository.reserveRevisionWithWriteFence();
+
+ expect(revision).toBeGreaterThan(0);
+ await expect(repository.readHighWaterRevision()).resolves.toBeGreaterThanOrEqual(revision);
+ });
+
+ it('reads a committed revision boundary without allocating a new revision', async () => {
+ const before = await repository.readHighWaterRevision();
+
+ await expect(repository.readCommittedRevisionBoundary()).resolves.toBe(before);
+ await expect(repository.readHighWaterRevision()).resolves.toBe(before);
+ });
+
+ it('locks capture sources before reading the committed revision boundary', async () => {
+ const { repository: recordedRepository, statements } = createRecordedRepository([
+ { revision: '42' },
+ ]);
+
+ await expect(recordedRepository.readCommittedRevisionBoundary()).resolves.toBe(42);
+ expect(statements).toHaveLength(3);
+ expect(statements[0]).toBe("SET LOCAL lock_timeout = '3s'");
+ expect(statements[1]).toMatch(/^LOCK TABLE .* IN SHARE MODE$/);
+ expect(statements[2]).toBe(
+ 'SELECT CASE WHEN is_called THEN last_value ELSE 0 END AS revision FROM fts_search_sync_revision_seq',
+ );
+ });
+
+ it('rejects an invalid committed revision boundary', async () => {
+ const { repository: recordedRepository } = createRecordedRepository([]);
+
+ await expect(recordedRepository.readCommittedRevisionBoundary()).rejects.toThrow(
+ 'Failed to read a valid FTS search sync revision while reading the committed revision boundary',
+ );
+ });
+
+ it(
+ 'validates capture infrastructure and rejects a disabled trigger',
+ async () => {
+ await expect(repository.assertCaptureInfrastructure()).resolves.toBeUndefined();
+
+ await db.execute(sql`ALTER TABLE agents DISABLE TRIGGER fts_search_sync_agents`);
+ try {
+ await expect(repository.assertCaptureInfrastructure()).rejects.toThrow(
+ 'trigger fts_search_sync_agents',
+ );
+ await expect(repository.installCaptureInfrastructure()).rejects.toThrow(
+ 'Refusing to replace partial or unknown FTS search sync capture infrastructure',
+ );
+ } finally {
+ await db.execute(sql`ALTER TABLE agents ENABLE TRIGGER fts_search_sync_agents`);
+ }
+
+ await expect(repository.assertCaptureInfrastructure()).resolves.toBeUndefined();
+ },
+ CAPTURE_INSTALL_TEST_TIMEOUT,
+ );
+
+ it(
+ 'refuses to continue from a partial trigger installation',
+ async () => {
+ await db.execute(sql`DROP TRIGGER fts_search_sync_agents ON agents`);
+ try {
+ await expect(repository.installCaptureInfrastructure()).rejects.toThrow(
+ 'Refusing to replace partial or unknown FTS search sync capture infrastructure',
+ );
+ const result = await db.execute(sql`
+ SELECT to_regclass('public.agents') IS NOT NULL AND EXISTS (
+ SELECT 1 FROM pg_trigger
+ WHERE tgname = 'fts_search_sync_agents' AND tgrelid = 'public.agents'::regclass
+ ) AS restored
+ `);
+ const rows = Array.isArray(result) ? result : result.rows;
+ expect(rows).toEqual([{ restored: false }]);
+ } finally {
+ await dropCaptureInfrastructure();
+ await repository.installCaptureInfrastructure();
+ }
+ },
+ CAPTURE_INSTALL_TEST_TIMEOUT,
+ );
+
+ it(
+ 'rejects a stale function body instead of treating its name as installed',
+ async () => {
+ await db.execute(
+ sql.raw(`
+ CREATE OR REPLACE FUNCTION capture_fts_search_sync_change() RETURNS trigger AS $$
+ BEGIN
+ RETURN COALESCE(NEW, OLD);
+ END;
+ $$ LANGUAGE plpgsql
+ `),
+ );
+ try {
+ await expect(repository.assertCaptureInfrastructure()).rejects.toThrow(
+ 'function capture_fts_search_sync_change',
+ );
+ await expect(repository.installCaptureInfrastructure()).rejects.toThrow(
+ 'Refusing to replace partial or unknown FTS search sync capture infrastructure',
+ );
+ } finally {
+ await dropCaptureInfrastructure();
+ await repository.installCaptureInfrastructure();
+ }
+ },
+ CAPTURE_INSTALL_TEST_TIMEOUT,
+ );
+
+ it('captures the first mutation immediately after opt-in installation', async () => {
+ await db.insert(agents).values({ id: 'immediate-agent', title: 'one', userId: USER_ID });
+
+ await expect(
+ db
+ .select({ documentId: ftsSearchSyncOutbox.documentId, entity: ftsSearchSyncOutbox.entity })
+ .from(ftsSearchSyncOutbox),
+ ).resolves.toEqual([{ documentId: 'immediate-agent', entity: 'agents' }]);
+ });
+
+ it('coalesces mutations and increases the revision, prioritizing revocations', async () => {
+ await db.insert(agents).values({ id: 'sync-agent', title: 'one', userId: USER_ID });
+ const [inserted] = await db
+ .select()
+ .from(ftsSearchSyncOutbox)
+ .where(
+ and(
+ eq(ftsSearchSyncOutbox.entity, 'agents'),
+ eq(ftsSearchSyncOutbox.documentId, 'sync-agent'),
+ ),
+ );
+
+ await db
+ .update(agents)
+ .set({ title: 'two', visibility: 'private' })
+ .where(eq(agents.id, 'sync-agent'));
+ const rows = await db
+ .select()
+ .from(ftsSearchSyncOutbox)
+ .where(
+ and(
+ eq(ftsSearchSyncOutbox.entity, 'agents'),
+ eq(ftsSearchSyncOutbox.documentId, 'sync-agent'),
+ ),
+ );
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].revision).toBeGreaterThan(inserted.revision);
+ expect(rows[0].priority).toBe(0);
+
+ await db.delete(agents).where(eq(agents.id, 'sync-agent'));
+ const [deleted] = await db
+ .select()
+ .from(ftsSearchSyncOutbox)
+ .where(eq(ftsSearchSyncOutbox.documentId, 'sync-agent'));
+ expect(deleted.revision).toBeGreaterThan(rows[0].revision);
+ expect(deleted.priority).toBe(0);
+ });
+
+ it('does not enqueue an update that changes only an unprojected field', async () => {
+ await db.insert(agents).values({ id: 'unprojected-agent', title: 'one', userId: USER_ID });
+ await db.delete(ftsSearchSyncOutbox);
+
+ await db.execute(sql`UPDATE agents SET pinned = true WHERE id = 'unprojected-agent'`);
+
+ const rows = await db.select().from(ftsSearchSyncOutbox);
+ expect(rows).toEqual([]);
+ });
+
+ it('enqueues an update that changes only the projected updated_at field', async () => {
+ await db.insert(agents).values({ id: 'updated-at-agent', title: 'one', userId: USER_ID });
+ await db.delete(ftsSearchSyncOutbox);
+
+ await db
+ .update(agents)
+ .set({ updatedAt: new Date('2026-08-30T00:00:00.000Z') })
+ .where(eq(agents.id, 'updated-at-agent'));
+
+ await expect(
+ db
+ .select({ documentId: ftsSearchSyncOutbox.documentId, entity: ftsSearchSyncOutbox.entity })
+ .from(ftsSearchSyncOutbox),
+ ).resolves.toEqual([{ documentId: 'updated-at-agent', entity: 'agents' }]);
+ });
+
+ it('rolls the outbox entry back with the source transaction', async () => {
+ await expect(
+ db.transaction(async (transaction) => {
+ await transaction
+ .insert(agents)
+ .values({ id: 'rolled-back-agent', title: 'temporary', userId: USER_ID });
+ throw new Error('rollback');
+ }),
+ ).rejects.toThrow('rollback');
+
+ const rows = await db
+ .select()
+ .from(ftsSearchSyncOutbox)
+ .where(eq(ftsSearchSyncOutbox.documentId, 'rolled-back-agent'));
+ expect(rows).toEqual([]);
+ });
+
+ it('uses revisions to reject stale acknowledgements after a newer mutation', async () => {
+ await db.insert(agents).values({ id: 'revision-agent', title: 'one', userId: USER_ID });
+ const [first] = await repository.claim();
+
+ await db.update(agents).set({ title: 'two' }).where(eq(agents.id, 'revision-agent'));
+
+ await expect(repository.acknowledgeMany([first])).resolves.toEqual([]);
+ const [second] = await repository.claim();
+ expect(second.revision).toBeGreaterThan(first.revision);
+ await expect(repository.acknowledgeMany([second])).resolves.toEqual([second]);
+ await expect(repository.stats()).resolves.toMatchObject({ pending: 0, ready: 0 });
+ });
+
+ it('keeps concurrent claims disjoint and marks permanent failures dead', async () => {
+ await db.insert(agents).values([
+ { id: 'claim-agent-a', title: 'a', userId: USER_ID },
+ { id: 'claim-agent-b', title: 'b', userId: USER_ID },
+ ]);
+
+ const [first] = await repository.claim(1);
+ const [second] = await repository.claim(1);
+ expect(second.documentId).not.toBe(first.documentId);
+
+ await expect(
+ repository.markFailures([{ ...first, error: new Error('invalid mapping'), permanent: true }]),
+ ).resolves.toBe(1);
+ await expect(repository.hasDeadLetters()).resolves.toBe(true);
+ const [dead] = await db
+ .select()
+ .from(ftsSearchSyncOutbox)
+ .where(eq(ftsSearchSyncOutbox.documentId, first.documentId));
+ expect(dead.deadAt).toBeInstanceOf(Date);
+ expect(dead.lastError).toBe('invalid mapping');
+
+ await repository.releaseMany([second]);
+ await expect(repository.stats()).resolves.toMatchObject({ dead: 1, inFlight: 0, ready: 1 });
+ });
+
+ it('prevents stale workers from settling a reclaimed lease', async () => {
+ await db.insert(agents).values({ id: 'reclaimed-agent', title: 'one', userId: USER_ID });
+ const [stale] = await repository.claim(1, 1);
+
+ /** Simulate the lease reaper making the same revision available to another worker. */
+ await db
+ .update(ftsSearchSyncOutbox)
+ .set({ availableAt: new Date(0), lockedUntil: null })
+ .where(eq(ftsSearchSyncOutbox.documentId, stale.documentId));
+ const [current] = await repository.claim(1, 300);
+ expect(current.leaseToken).not.toBe(stale.leaseToken);
+ const [claimedRow] = await db
+ .select()
+ .from(ftsSearchSyncOutbox)
+ .where(eq(ftsSearchSyncOutbox.documentId, current.documentId));
+
+ await repository.releaseMany([stale]);
+ await expect(
+ db
+ .select()
+ .from(ftsSearchSyncOutbox)
+ .where(eq(ftsSearchSyncOutbox.documentId, current.documentId)),
+ ).resolves.toMatchObject([{ lockedUntil: claimedRow.lockedUntil }]);
+
+ await repository.markFailures([
+ { ...stale, error: new Error('late failure'), permanent: true },
+ ]);
+ await expect(
+ db
+ .select()
+ .from(ftsSearchSyncOutbox)
+ .where(eq(ftsSearchSyncOutbox.documentId, current.documentId)),
+ ).resolves.toMatchObject([
+ {
+ attempts: claimedRow.attempts,
+ deadAt: claimedRow.deadAt,
+ lastError: claimedRow.lastError,
+ lockedUntil: claimedRow.lockedUntil,
+ },
+ ]);
+
+ await expect(repository.acknowledgeMany([stale])).resolves.toEqual([]);
+ await expect(repository.acknowledgeMany([current])).resolves.toEqual([current]);
+ });
+
+ it('returns revocations before ordinary edits', async () => {
+ await db.insert(agents).values([
+ { id: 'ordinary-agent', title: 'before', userId: USER_ID },
+ { id: 'revoked-agent', title: 'before', userId: USER_ID },
+ ]);
+ await db.delete(ftsSearchSyncOutbox);
+ await db.update(agents).set({ title: 'after' }).where(eq(agents.id, 'ordinary-agent'));
+ await db.update(agents).set({ visibility: 'private' }).where(eq(agents.id, 'revoked-agent'));
+
+ await expect(repository.claim(2)).resolves.toMatchObject([
+ { documentId: 'revoked-agent' },
+ { documentId: 'ordinary-agent' },
+ ]);
+ });
+
+ it('reports a retry as dead when it exhausts the attempt budget', async () => {
+ await db.insert(agents).values({ id: 'exhausted-agent', title: 'one', userId: USER_ID });
+ const [claimed] = await repository.claim(1);
+ await db
+ .update(ftsSearchSyncOutbox)
+ .set({ attempts: 35 })
+ .where(eq(ftsSearchSyncOutbox.documentId, claimed.documentId));
+
+ await expect(
+ repository.markFailures([{ ...claimed, error: new Error('still failing') }]),
+ ).resolves.toBe(1);
+ await expect(repository.stats()).resolves.toMatchObject({ dead: 1, ready: 0 });
+ });
+
+ it('reaps expired leases into delayed retry without reclaiming them immediately', async () => {
+ await db.insert(agents).values({ id: 'expired-agent', title: 'one', userId: USER_ID });
+ const [claimed] = await repository.claim(1);
+ await db
+ .update(ftsSearchSyncOutbox)
+ .set({ lockedUntil: new Date(0) })
+ .where(eq(ftsSearchSyncOutbox.documentId, claimed.documentId));
+
+ await expect(repository.stats()).resolves.toMatchObject({
+ expiredLeases: 1,
+ inFlight: 0,
+ ready: 0,
+ });
+ await expect(repository.claim(1)).resolves.toEqual([]);
+ const [retried] = await db
+ .select()
+ .from(ftsSearchSyncOutbox)
+ .where(eq(ftsSearchSyncOutbox.documentId, claimed.documentId));
+ expect(retried).toMatchObject({ attempts: 1, deadAt: null, lockedUntil: null });
+ expect(retried.availableAt.getTime()).toBeGreaterThan(Date.now());
+ });
+
+ it('bounds expired lease recovery to the requested claim limit', async () => {
+ const documentIds = ['expired-agent-a', 'expired-agent-b', 'expired-agent-c'];
+ await db.insert(agents).values(
+ documentIds.map((id) => ({
+ id,
+ title: id,
+ userId: USER_ID,
+ })),
+ );
+ const claimed = await repository.claim(documentIds.length);
+ expect(claimed).toHaveLength(documentIds.length);
+ await db
+ .update(ftsSearchSyncOutbox)
+ .set({ lockedUntil: new Date(0) })
+ .where(inArray(ftsSearchSyncOutbox.documentId, documentIds));
+
+ await expect(repository.claim(1)).resolves.toEqual([]);
+ const rows = await db
+ .select({
+ attempts: ftsSearchSyncOutbox.attempts,
+ lockedUntil: ftsSearchSyncOutbox.lockedUntil,
+ })
+ .from(ftsSearchSyncOutbox)
+ .where(inArray(ftsSearchSyncOutbox.documentId, documentIds));
+
+ expect(rows.filter(({ lockedUntil }) => lockedUntil === null)).toHaveLength(1);
+ expect(rows.map(({ attempts }) => attempts).toSorted()).toEqual([0, 0, 1]);
+ });
+
+ it(
+ 'fans knowledge-base relation changes out to files and linked documents',
+ async () => {
+ await db.execute(sql`
+ INSERT INTO knowledge_bases (id, name, user_id)
+ VALUES ('sync-kb', 'KB', ${USER_ID})
+ `);
+ await db.execute(sql`
+ INSERT INTO files (id, user_id, file_type, name, size, url)
+ VALUES ('sync-file', ${USER_ID}, 'text/plain', 'file.txt', 10, 'https://example.com/file')
+ `);
+ await db.execute(sql`
+ INSERT INTO documents (
+ id, file_type, total_char_count, total_line_count, source_type, source, file_id, user_id
+ ) VALUES (
+ 'sync-document', 'text/plain', 10, 1, 'file', 'file.txt', 'sync-file', ${USER_ID}
+ )
+ `);
+ await db.delete(ftsSearchSyncOutbox);
+
+ await db.execute(sql`
+ INSERT INTO knowledge_base_files (knowledge_base_id, file_id, user_id)
+ VALUES ('sync-kb', 'sync-file', ${USER_ID})
+ `);
+
+ const rows = await db
+ .select({ documentId: ftsSearchSyncOutbox.documentId, entity: ftsSearchSyncOutbox.entity })
+ .from(ftsSearchSyncOutbox);
+ const expectedKeys = await builder.resolveAffectedKeys({
+ fileIds: ['sync-file'],
+ relation: 'knowledgeBaseFiles',
+ });
+ expect(sortKeys(rows)).toEqual(
+ sortKeys(expectedKeys.map(({ entity, id }) => ({ documentId: id, entity }))),
+ );
+ expect(rows).toEqual(
+ expect.arrayContaining([
+ { documentId: 'sync-file', entity: 'files' },
+ { documentId: 'sync-document', entity: 'documents' },
+ ]),
+ );
+ expect(rows.every((row) => ['documents', 'files'].includes(row.entity))).toBe(true);
+
+ await db.delete(ftsSearchSyncOutbox);
+ await db.execute(sql`
+ INSERT INTO knowledge_bases (id, name, user_id)
+ VALUES ('sync-kb-next', 'Next KB', ${USER_ID})
+ `);
+ await db.execute(sql`
+ UPDATE knowledge_base_files
+ SET knowledge_base_id = 'sync-kb-next'
+ WHERE knowledge_base_id = 'sync-kb' AND file_id = 'sync-file'
+ `);
+ const updatedRows = await db
+ .select({ documentId: ftsSearchSyncOutbox.documentId, entity: ftsSearchSyncOutbox.entity })
+ .from(ftsSearchSyncOutbox);
+ expect(updatedRows).toEqual(
+ expect.arrayContaining([
+ { documentId: 'sync-file', entity: 'files' },
+ { documentId: 'sync-document', entity: 'documents' },
+ ]),
+ );
+
+ await db.delete(ftsSearchSyncOutbox);
+ await db.execute(sql`
+ DELETE FROM knowledge_base_files
+ WHERE knowledge_base_id = 'sync-kb-next' AND file_id = 'sync-file'
+ `);
+ const removedRows = await db
+ .select({ documentId: ftsSearchSyncOutbox.documentId, entity: ftsSearchSyncOutbox.entity })
+ .from(ftsSearchSyncOutbox);
+ expect(removedRows).toEqual(
+ expect.arrayContaining([
+ { documentId: 'sync-file', entity: 'files' },
+ { documentId: 'sync-document', entity: 'documents' },
+ ]),
+ );
+ },
+ CAPTURE_INSTALL_TEST_TIMEOUT,
+ );
+
+ it(
+ 'fans parent memory text changes out to derived memory projections',
+ async () => {
+ await db.execute(sql`
+ INSERT INTO user_memories (id, user_id, title, last_accessed_at)
+ VALUES ('sync-memory', ${USER_ID}, 'before', now())
+ `);
+ await db.execute(sql`
+ INSERT INTO user_memories_contexts (id, user_id, user_memory_ids)
+ VALUES ('sync-context', ${USER_ID}, '["sync-memory"]'::jsonb)
+ `);
+ await db.delete(ftsSearchSyncOutbox);
+
+ await db.execute(sql`
+ UPDATE user_memories SET title = 'after' WHERE id = 'sync-memory'
+ `);
+
+ const rows = await db
+ .select({ documentId: ftsSearchSyncOutbox.documentId, entity: ftsSearchSyncOutbox.entity })
+ .from(ftsSearchSyncOutbox);
+ const expectedKeys = await builder.resolveAffectedKeys({
+ memoryIds: ['sync-memory'],
+ relation: 'userMemoryReferences',
+ });
+ expect(sortKeys(rows)).toEqual(
+ sortKeys(expectedKeys.map(({ entity, id }) => ({ documentId: id, entity }))),
+ );
+ expect(rows).toEqual(
+ expect.arrayContaining([
+ { documentId: 'sync-memory', entity: 'userMemories' },
+ { documentId: 'sync-context', entity: 'memoryContexts' },
+ ]),
+ );
+
+ await db.delete(ftsSearchSyncOutbox);
+ await db.execute(sql`DELETE FROM user_memories WHERE id = 'sync-memory'`);
+ const deletedRows = await db
+ .select({ documentId: ftsSearchSyncOutbox.documentId, entity: ftsSearchSyncOutbox.entity })
+ .from(ftsSearchSyncOutbox);
+ expect(deletedRows).toEqual(
+ expect.arrayContaining([
+ { documentId: 'sync-memory', entity: 'userMemories' },
+ { documentId: 'sync-context', entity: 'memoryContexts' },
+ ]),
+ );
+ },
+ CAPTURE_INSTALL_TEST_TIMEOUT,
+ );
+});
diff --git a/packages/database/src/repositories/ftsSearchSyncOutbox/captureInfrastructure.ts b/packages/database/src/repositories/ftsSearchSyncOutbox/captureInfrastructure.ts
new file mode 100644
index 00000000000..062e3cc4267
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchSyncOutbox/captureInfrastructure.ts
@@ -0,0 +1,388 @@
+import { createHash } from 'node:crypto';
+
+import { sql } from 'drizzle-orm';
+
+interface CaptureFunctionDefinition {
+ body: string;
+ identityArguments: string;
+ name: string;
+ result: 'trigger' | 'void';
+ signature: string;
+}
+
+interface CaptureTriggerDefinition {
+ createSql: string;
+ name: string;
+ table: string;
+}
+
+export const FTS_SEARCH_SYNC_MEMORY_CONTEXTS_GIN_INDEX =
+ 'user_memories_contexts_user_memory_ids_gin_idx';
+
+const ENQUEUE_FTS_SEARCH_SYNC_OUTBOX_BODY = `
+ BEGIN
+ INSERT INTO fts_search_sync_outbox (entity, document_id, priority)
+ SELECT DISTINCT p_entity, document_id, p_priority
+ FROM unnest(p_document_ids) AS document_id
+ WHERE document_id IS NOT NULL AND document_id <> ''
+ ORDER BY document_id
+ ON CONFLICT (entity, document_id) DO UPDATE SET
+ attempts = 0,
+ available_at = now(),
+ dead_at = NULL,
+ last_error = NULL,
+ locked_until = NULL,
+ priority = LEAST(fts_search_sync_outbox.priority, EXCLUDED.priority),
+ -- Allocate after locking the conflicting row so concurrent upserts preserve commit order.
+ revision = nextval('fts_search_sync_revision_seq'),
+ updated_at = now();
+ END;
+`;
+
+const CAPTURE_FTS_SEARCH_SYNC_CHANGE_BODY = `
+ DECLARE
+ field_name text;
+ old_row jsonb;
+ new_row jsonb;
+ priority smallint := CASE WHEN TG_OP = 'DELETE' THEN 0 ELSE 10 END;
+ row_id text;
+ BEGIN
+ IF TG_OP = 'UPDATE' AND TG_NARGS > 1 THEN
+ old_row := to_jsonb(OLD);
+ new_row := to_jsonb(NEW);
+ FOREACH field_name IN ARRAY TG_ARGV[1:TG_NARGS - 1] LOOP
+ IF old_row->field_name IS DISTINCT FROM new_row->field_name THEN
+ priority := 0;
+ END IF;
+ END LOOP;
+ END IF;
+
+ IF TG_OP = 'DELETE' THEN
+ row_id := OLD.id::text;
+ ELSE
+ row_id := NEW.id::text;
+ END IF;
+
+ PERFORM enqueue_fts_search_sync_outbox(TG_ARGV[0], ARRAY[row_id], priority);
+ RETURN COALESCE(NEW, OLD);
+ END;
+`;
+
+const CAPTURE_FTS_SEARCH_SYNC_MEMORY_FANOUT_BODY = `
+ -- Keep this fanout aligned with FtsSearchDocumentBuilder.resolveAffectedKeys.
+ DECLARE
+ memory_id text := COALESCE(NEW.id, OLD.id)::text;
+ priority smallint := CASE WHEN TG_OP = 'DELETE' THEN 0 ELSE 10 END;
+ BEGIN
+ PERFORM enqueue_fts_search_sync_outbox(
+ 'memoryContexts',
+ ARRAY(SELECT id::text FROM user_memories_contexts WHERE user_memory_ids @> to_jsonb(ARRAY[memory_id]) ORDER BY id),
+ priority
+ );
+ PERFORM enqueue_fts_search_sync_outbox(
+ 'memoryPreferences',
+ ARRAY(SELECT id::text FROM user_memories_preferences WHERE user_memory_id = memory_id ORDER BY id),
+ priority
+ );
+ PERFORM enqueue_fts_search_sync_outbox(
+ 'memoryActivities',
+ ARRAY(SELECT id::text FROM user_memories_activities WHERE user_memory_id = memory_id ORDER BY id),
+ priority
+ );
+ PERFORM enqueue_fts_search_sync_outbox(
+ 'memoryIdentities',
+ ARRAY(SELECT id::text FROM user_memories_identities WHERE user_memory_id = memory_id ORDER BY id),
+ priority
+ );
+ PERFORM enqueue_fts_search_sync_outbox(
+ 'memoryExperiences',
+ ARRAY(SELECT id::text FROM user_memories_experiences WHERE user_memory_id = memory_id ORDER BY id),
+ priority
+ );
+
+ RETURN COALESCE(NEW, OLD);
+ END;
+`;
+
+const CAPTURE_FTS_SEARCH_SYNC_KNOWLEDGE_BASE_FILES_BODY = `
+ -- Keep this fanout aligned with FtsSearchDocumentBuilder.resolveAffectedKeys.
+ DECLARE
+ file_ids text[] := ARRAY[
+ CASE WHEN TG_OP <> 'INSERT' THEN OLD.file_id::text END,
+ CASE WHEN TG_OP <> 'DELETE' THEN NEW.file_id::text END
+ ];
+ BEGIN
+ PERFORM enqueue_fts_search_sync_outbox('files', file_ids, 0::smallint);
+ PERFORM enqueue_fts_search_sync_outbox(
+ 'documents',
+ ARRAY(SELECT id::text FROM documents WHERE file_id = ANY(file_ids) ORDER BY id),
+ 0::smallint
+ );
+ RETURN COALESCE(NEW, OLD);
+ END;
+`;
+
+const CAPTURE_FUNCTION_DEFINITIONS: CaptureFunctionDefinition[] = [
+ {
+ body: ENQUEUE_FTS_SEARCH_SYNC_OUTBOX_BODY,
+ identityArguments: 'p_entity text, p_document_ids text[], p_priority smallint',
+ name: 'enqueue_fts_search_sync_outbox',
+ result: 'void',
+ signature: `
+ p_entity text,
+ p_document_ids text[],
+ p_priority smallint DEFAULT 10
+ `,
+ },
+ {
+ body: CAPTURE_FTS_SEARCH_SYNC_CHANGE_BODY,
+ identityArguments: '',
+ name: 'capture_fts_search_sync_change',
+ result: 'trigger',
+ signature: '',
+ },
+ {
+ body: CAPTURE_FTS_SEARCH_SYNC_MEMORY_FANOUT_BODY,
+ identityArguments: '',
+ name: 'capture_fts_search_sync_memory_fanout',
+ result: 'trigger',
+ signature: '',
+ },
+ {
+ body: CAPTURE_FTS_SEARCH_SYNC_KNOWLEDGE_BASE_FILES_BODY,
+ identityArguments: '',
+ name: 'capture_fts_search_sync_knowledge_base_files',
+ result: 'trigger',
+ signature: '',
+ },
+];
+
+const createCaptureFunctionStatement = ({
+ body,
+ name,
+ result,
+ signature,
+}: CaptureFunctionDefinition) =>
+ sql.raw(`
+ CREATE OR REPLACE FUNCTION ${name}(${signature}) RETURNS ${result} AS $fts_search_sync_capture$
+${body}
+ $fts_search_sync_capture$ LANGUAGE plpgsql
+ `);
+
+export const FTS_SEARCH_SYNC_CAPTURE_FUNCTION_STATEMENTS = CAPTURE_FUNCTION_DEFINITIONS.map(
+ createCaptureFunctionStatement,
+);
+
+export const FTS_SEARCH_SYNC_CAPTURE_FUNCTION_TARGETS = CAPTURE_FUNCTION_DEFINITIONS.map(
+ ({ body, identityArguments, name, result }) => ({
+ body: body.trim(),
+ identityArguments,
+ name,
+ result,
+ }),
+);
+
+const CAPTURE_TRIGGER_DEFINITIONS: CaptureTriggerDefinition[] = [
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_agents
+ AFTER INSERT OR DELETE OR UPDATE OF description, slug, system_role, tags, title, updated_at, user_id, virtual, visibility, workspace_id ON public.agents
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'agents', 'user_id', 'visibility', 'workspace_id'
+ )`,
+ name: 'fts_search_sync_agents',
+ table: 'agents',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_topics
+ AFTER INSERT OR DELETE OR UPDATE OF agent_id, content, description, group_id, session_id, status, title, updated_at, user_id, workspace_id ON public.topics
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'topics', 'user_id', 'workspace_id'
+ )`,
+ name: 'fts_search_sync_topics',
+ table: 'topics',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_files
+ AFTER INSERT OR DELETE OR UPDATE OF file_type, name, size, source, updated_at, user_id, visibility, workspace_id ON public.files
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'files', 'user_id', 'visibility', 'workspace_id'
+ )`,
+ name: 'fts_search_sync_files',
+ table: 'files',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_knowledge_bases
+ AFTER INSERT OR DELETE OR UPDATE OF description, is_public, name, type, updated_at, user_id, visibility, workspace_id ON public.knowledge_bases
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'knowledgeBases', 'is_public', 'user_id', 'visibility', 'workspace_id'
+ )`,
+ name: 'fts_search_sync_knowledge_bases',
+ table: 'knowledge_bases',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_chat_groups
+ AFTER INSERT OR DELETE OR UPDATE OF content, description, group_id, title, updated_at, user_id, visibility, workspace_id ON public.chat_groups
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'chatGroups', 'user_id', 'visibility', 'workspace_id'
+ )`,
+ name: 'fts_search_sync_chat_groups',
+ table: 'chat_groups',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_documents
+ AFTER INSERT OR DELETE OR UPDATE OF content, description, file_id, file_type, knowledge_base_id, parent_id, slug, source_type, title, total_char_count, updated_at, user_id, visibility, workspace_id ON public.documents
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'documents', 'user_id', 'visibility', 'workspace_id'
+ )`,
+ name: 'fts_search_sync_documents',
+ table: 'documents',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_messages
+ AFTER INSERT OR DELETE OR UPDATE OF agent_id, content, group_id, role, session_id, summary, thread_id, topic_id, updated_at, user_id, workspace_id ON public.messages
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'messages', 'user_id', 'workspace_id'
+ )`,
+ name: 'fts_search_sync_messages',
+ table: 'messages',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_user_memories
+ AFTER INSERT OR DELETE OR UPDATE OF captured_at, details, memory_category, memory_layer, status, summary, tags, title, updated_at, user_id ON public.user_memories
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'userMemories', 'user_id'
+ )`,
+ name: 'fts_search_sync_user_memories',
+ table: 'user_memories',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_user_memories_fanout
+ AFTER INSERT OR DELETE OR UPDATE OF captured_at, details, memory_category, memory_layer, status, summary, tags, title, user_id ON public.user_memories
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_memory_fanout()`,
+ name: 'fts_search_sync_user_memories_fanout',
+ table: 'user_memories',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_memory_contexts
+ AFTER INSERT OR DELETE OR UPDATE OF captured_at, current_status, description, tags, title, type, updated_at, user_id, user_memory_ids ON public.user_memories_contexts
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'memoryContexts', 'user_id'
+ )`,
+ name: 'fts_search_sync_memory_contexts',
+ table: 'user_memories_contexts',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_memory_preferences
+ AFTER INSERT OR DELETE OR UPDATE OF captured_at, conclusion_directives, suggestions, tags, type, updated_at, user_id, user_memory_id ON public.user_memories_preferences
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'memoryPreferences', 'user_id'
+ )`,
+ name: 'fts_search_sync_memory_preferences',
+ table: 'user_memories_preferences',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_memory_activities
+ AFTER INSERT OR DELETE OR UPDATE OF captured_at, ends_at, feedback, narrative, notes, starts_at, status, tags, type, updated_at, user_id, user_memory_id ON public.user_memories_activities
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'memoryActivities', 'user_id'
+ )`,
+ name: 'fts_search_sync_memory_activities',
+ table: 'user_memories_activities',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_memory_identities
+ AFTER INSERT OR DELETE OR UPDATE OF captured_at, description, episodic_date, relationship, role, tags, type, updated_at, user_id, user_memory_id ON public.user_memories_identities
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'memoryIdentities', 'user_id'
+ )`,
+ name: 'fts_search_sync_memory_identities',
+ table: 'user_memories_identities',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_memory_experiences
+ AFTER INSERT OR DELETE OR UPDATE OF action, captured_at, key_learning, possible_outcome, reasoning, situation, tags, type, updated_at, user_id, user_memory_id ON public.user_memories_experiences
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'memoryExperiences', 'user_id'
+ )`,
+ name: 'fts_search_sync_memory_experiences',
+ table: 'user_memories_experiences',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_persona_documents
+ AFTER INSERT OR DELETE OR UPDATE OF captured_at, persona, profile, tagline, updated_at, user_id, version ON public.user_memory_persona_documents
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_change(
+ 'personaDocuments', 'user_id'
+ )`,
+ name: 'fts_search_sync_persona_documents',
+ table: 'user_memory_persona_documents',
+ },
+ {
+ createSql: `CREATE TRIGGER fts_search_sync_knowledge_base_files
+ AFTER INSERT OR DELETE OR UPDATE OF file_id, knowledge_base_id ON public.knowledge_base_files
+ FOR EACH ROW EXECUTE FUNCTION capture_fts_search_sync_knowledge_base_files()`,
+ name: 'fts_search_sync_knowledge_base_files',
+ table: 'knowledge_base_files',
+ },
+];
+
+export const normalizeFtsSearchSyncCaptureDefinition = (definition: string) => {
+ const compact = definition
+ .trim()
+ .replaceAll(/\s+/g, ' ')
+ .replaceAll(/\(\s+/g, '(')
+ .replaceAll(/\s+\)/g, ')');
+
+ /** PostgreSQL renders UPDATE OF columns in table-column order; their SQL order is immaterial. */
+ return compact.replace(/UPDATE OF ([\w, ]+) ON /, (_, columns: string) => {
+ const normalizedColumns = columns
+ .split(',')
+ .map((column) => column.trim())
+ .toSorted()
+ .join(', ');
+ return `UPDATE OF ${normalizedColumns} ON `;
+ });
+};
+
+/** Reconstructs the only earlier trigger revision installed before this feature ships. */
+const toPreviousCaptureTriggerDefinition = (definition: string) =>
+ definition.replace(/UPDATE OF ([\w, ]+) ON /, (_, columns: string) => {
+ const previousColumns = columns
+ .split(',')
+ .map((column) => column.trim())
+ .filter((column) => column !== 'updated_at')
+ .join(', ');
+ return `UPDATE OF ${previousColumns} ON `;
+ });
+
+const createCaptureTriggerStatement = ({ createSql }: CaptureTriggerDefinition) =>
+ sql.raw(`${createSql};`);
+
+export const FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS = CAPTURE_TRIGGER_DEFINITIONS.map(
+ ({ createSql, name, table }) => {
+ const definition = normalizeFtsSearchSyncCaptureDefinition(createSql);
+ const previousDefinition = normalizeFtsSearchSyncCaptureDefinition(
+ toPreviousCaptureTriggerDefinition(createSql),
+ );
+
+ return {
+ definition,
+ name,
+ previousDefinitions: previousDefinition === definition ? [] : [previousDefinition],
+ table,
+ };
+ },
+);
+
+export const FTS_SEARCH_SYNC_CAPTURE_TRIGGER_STATEMENTS = CAPTURE_TRIGGER_DEFINITIONS.map(
+ createCaptureTriggerStatement,
+);
+
+/** Changes whenever a function body, trigger definition, or trigger target changes. */
+export const FTS_SEARCH_SYNC_CAPTURE_FINGERPRINT = createHash('sha256')
+ .update(
+ JSON.stringify({
+ functions: FTS_SEARCH_SYNC_CAPTURE_FUNCTION_TARGETS,
+ triggers: FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS,
+ }),
+ )
+ .digest('hex');
diff --git a/packages/database/src/repositories/ftsSearchSyncOutbox/index.ts b/packages/database/src/repositories/ftsSearchSyncOutbox/index.ts
new file mode 100644
index 00000000000..9652c3e93a7
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchSyncOutbox/index.ts
@@ -0,0 +1,648 @@
+import { sql } from 'drizzle-orm';
+
+import type { LobeChatDatabase } from '../../type';
+import type { FtsSearchDocumentEntity } from '../ftsSearchDocument';
+import { FTS_SEARCH_DOCUMENT_ENTITIES } from '../ftsSearchDocument';
+import {
+ FTS_SEARCH_SYNC_CAPTURE_FINGERPRINT,
+ FTS_SEARCH_SYNC_CAPTURE_FUNCTION_STATEMENTS,
+ FTS_SEARCH_SYNC_CAPTURE_FUNCTION_TARGETS,
+ FTS_SEARCH_SYNC_CAPTURE_TRIGGER_STATEMENTS,
+ FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS,
+ normalizeFtsSearchSyncCaptureDefinition,
+} from './captureInfrastructure';
+
+export interface FtsSearchSyncWork {
+ documentId: string;
+ entity: FtsSearchDocumentEntity;
+ /** Opaque fencing token that binds settlement to the worker's exact lease. */
+ leaseToken: string;
+ revision: number;
+}
+
+export interface FtsSearchSyncFailure extends FtsSearchSyncWork {
+ error: unknown;
+ permanent?: boolean;
+}
+
+export interface FtsSearchSyncOutboxEntityStats {
+ dead: number;
+ expiredLeases: number;
+ inFlight: number;
+ oldestReadyAgeSeconds: number;
+ pending: number;
+ ready: number;
+ retrying: number;
+}
+
+export interface FtsSearchSyncOutboxStats extends FtsSearchSyncOutboxEntityStats {
+ entities: Record<FtsSearchDocumentEntity, FtsSearchSyncOutboxEntityStats>;
+ highWaterRevision: number;
+ oldestActiveRevision: number | null;
+ revisionLag: number;
+}
+
+/** Approximately one day of durable retries when the exponential delay is capped at one hour. */
+export const FTS_SEARCH_SYNC_MAX_ATTEMPTS = 36;
+
+const FTS_SEARCH_SYNC_CAPTURE_SOURCE_TABLE_IDENTIFIERS = sql.join(
+ [...new Set(FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS.map(({ table }) => table))].map(
+ (table) => sql`${sql.identifier('public')}.${sql.identifier(table)}`,
+ ),
+ sql`, `,
+);
+
+type FtsSearchSyncExecutor = Pick<LobeChatDatabase, 'execute'>;
+type FtsSearchSyncDatabase = Pick<LobeChatDatabase, 'execute' | 'transaction'>;
+
+interface FtsSearchSyncRow {
+ document_id: string;
+ entity: FtsSearchDocumentEntity;
+ lease_token: string;
+ revision: number | string;
+}
+
+const rowsOf = <Row>(result: unknown): Row[] => {
+ if (Array.isArray(result)) return result as Row[];
+ return ((result as { rows?: Row[] }).rows ?? []) as Row[];
+};
+
+interface CaptureInfrastructureState {
+ absent: boolean;
+ mismatches: string[];
+ upgradeable: boolean;
+}
+
+const assertCaptureGinIndex = async (db: FtsSearchSyncExecutor): Promise<void> => {
+ const indexResult = await db.execute(sql`
+ SELECT (
+ search_index.indisvalid
+ AND search_index.indisready
+ AND search_index.indislive
+ AND access_method.amname = 'gin'
+ AND table_namespace.nspname = 'public'
+ AND source_table.relname = 'user_memories_contexts'
+ AND search_index.indnkeyatts = 1
+ AND search_index.indnatts = 1
+ AND search_index.indexprs IS NULL
+ AND search_index.indpred IS NULL
+ AND indexed_attribute.attname = 'user_memory_ids'
+ AND indexed_attribute.atttypid = 'jsonb'::regtype
+ AND operator_class.opcintype = 'jsonb'::regtype
+ AND operator_class.opcname IN ('jsonb_ops', 'jsonb_path_ops')
+ ) AS is_valid
+ FROM pg_index search_index
+ INNER JOIN pg_class index_class ON index_class.oid = search_index.indexrelid
+ INNER JOIN pg_am access_method ON access_method.oid = index_class.relam
+ INNER JOIN pg_class source_table ON source_table.oid = search_index.indrelid
+ INNER JOIN pg_namespace table_namespace ON table_namespace.oid = source_table.relnamespace
+ INNER JOIN pg_attribute indexed_attribute
+ ON indexed_attribute.attrelid = source_table.oid
+ AND indexed_attribute.attnum = search_index.indkey[0]
+ INNER JOIN pg_opclass operator_class ON operator_class.oid = search_index.indclass[0]
+ WHERE search_index.indexrelid =
+ to_regclass('public.user_memories_contexts_user_memory_ids_gin_idx')
+ `);
+ const [index] = rowsOf<{ is_valid: boolean }>(indexResult);
+ if (!index?.is_valid) {
+ throw new Error(
+ 'FTS search sync requires a valid, non-partial GIN index on user_memories_contexts.user_memory_ids',
+ );
+ }
+};
+
+const readCaptureInfrastructureState = async (
+ db: FtsSearchSyncExecutor,
+): Promise<CaptureInfrastructureState> => {
+ const functionNames = sql.join(
+ FTS_SEARCH_SYNC_CAPTURE_FUNCTION_TARGETS.map(({ name }) => sql`${name}`),
+ sql`, `,
+ );
+ const functionResult = await db.execute(sql`
+ SELECT
+ pg_get_function_identity_arguments(search_function.oid) AS identity_arguments,
+ search_language.lanname AS language,
+ search_function.proname AS name,
+ search_function.prosrc AS function_body,
+ pg_get_function_result(search_function.oid) AS function_result
+ FROM pg_proc search_function
+ INNER JOIN pg_language search_language ON search_language.oid = search_function.prolang
+ WHERE search_function.pronamespace = 'public'::regnamespace
+ AND search_function.proname IN (${functionNames})
+ ORDER BY search_function.proname, identity_arguments
+ `);
+ const functions = rowsOf<{
+ function_body: string;
+ function_result: string;
+ identity_arguments: string;
+ language: string;
+ name: string;
+ }>(functionResult);
+
+ const triggerNames = sql.join(
+ [...new Set(FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS.map(({ name }) => name))].map(
+ (name) => sql`${name}`,
+ ),
+ sql`, `,
+ );
+ const triggerResult = await db.execute(sql`
+ SELECT
+ pg_get_triggerdef(search_trigger.oid, false) AS definition,
+ search_trigger.tgenabled AS enabled,
+ search_trigger.tgname AS name,
+ source_table.relname AS table_name
+ FROM pg_trigger search_trigger
+ INNER JOIN pg_class source_table ON source_table.oid = search_trigger.tgrelid
+ INNER JOIN pg_namespace source_namespace ON source_namespace.oid = source_table.relnamespace
+ WHERE NOT search_trigger.tgisinternal
+ AND source_namespace.nspname = 'public'
+ AND search_trigger.tgname IN (${triggerNames})
+ ORDER BY search_trigger.tgname, source_table.relname
+ `);
+ const triggers = rowsOf<{
+ definition: string;
+ enabled: string;
+ name: string;
+ table_name: string;
+ }>(triggerResult);
+
+ const mismatches: string[] = [];
+ let functionsMatch = functions.length === FTS_SEARCH_SYNC_CAPTURE_FUNCTION_TARGETS.length;
+ if (!functionsMatch) {
+ mismatches.push(
+ `functions ${functions.length}/${FTS_SEARCH_SYNC_CAPTURE_FUNCTION_TARGETS.length}`,
+ );
+ }
+ for (const expected of FTS_SEARCH_SYNC_CAPTURE_FUNCTION_TARGETS) {
+ const actual = functions.find(
+ ({ identity_arguments: identityArguments, name }) =>
+ name === expected.name && identityArguments === expected.identityArguments,
+ );
+ if (
+ !actual ||
+ actual.function_body.trim() !== expected.body ||
+ actual.function_result !== expected.result ||
+ actual.language !== 'plpgsql'
+ ) {
+ functionsMatch = false;
+ mismatches.push(`function ${expected.name}`);
+ }
+ }
+
+ let triggersMatchKnownVersion =
+ triggers.length === FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS.length;
+ if (!triggersMatchKnownVersion) {
+ mismatches.push(
+ `triggers ${triggers.length}/${FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS.length}`,
+ );
+ }
+ for (const expected of FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS) {
+ const actual = triggers.find(
+ ({ name, table_name: table }) => name === expected.name && table === expected.table,
+ );
+ const actualDefinition = actual
+ ? normalizeFtsSearchSyncCaptureDefinition(actual.definition)
+ : undefined;
+ const enabled = actual ? ['A', 'O'].includes(actual.enabled) : false;
+ const current = enabled && actualDefinition === expected.definition;
+ const previous =
+ enabled &&
+ actualDefinition !== undefined &&
+ expected.previousDefinitions.includes(actualDefinition);
+ if (!current) {
+ mismatches.push(`trigger ${expected.name}`);
+ }
+ if (!current && !previous) triggersMatchKnownVersion = false;
+ }
+
+ return {
+ absent: functions.length === 0 && triggers.length === 0,
+ mismatches,
+ upgradeable: functionsMatch && triggersMatchKnownVersion && mismatches.length > 0,
+ };
+};
+
+const assertCaptureDefinitions = async (db: FtsSearchSyncExecutor): Promise<void> => {
+ const state = await readCaptureInfrastructureState(db);
+ if (state.mismatches.length > 0) {
+ throw new Error(
+ `FTS search sync capture infrastructure does not match the expected definition: ${state.mismatches.join(', ')}`,
+ );
+ }
+};
+
+const toWork = (row: FtsSearchSyncRow): FtsSearchSyncWork => ({
+ documentId: row.document_id,
+ entity: row.entity,
+ leaseToken: row.lease_token,
+ revision: Number(row.revision),
+});
+
+const errorMessage = (error: unknown) =>
+ (error instanceof Error ? error.message : String(error)).slice(0, 2000);
+
+const revisionNumber = (value: number | string | undefined, operation: string, minimum = 0) => {
+ const revision = Number(value);
+ if (!Number.isSafeInteger(revision) || revision < minimum) {
+ throw new Error(`Failed to read a valid FTS search sync revision while ${operation}`);
+ }
+ return revision;
+};
+
+const lockCaptureSourceWrites = async (transaction: FtsSearchSyncExecutor): Promise<void> => {
+ await transaction.execute(sql`SET LOCAL lock_timeout = '3s'`);
+ await transaction.execute(
+ sql`LOCK TABLE ${FTS_SEARCH_SYNC_CAPTURE_SOURCE_TABLE_IDENTIFIERS} IN SHARE MODE`,
+ );
+};
+
+/** Durable claim and settlement operations for the PostgreSQL-triggered search outbox. */
+export class FtsSearchSyncOutboxRepository {
+ constructor(private readonly db: FtsSearchSyncDatabase) {}
+
+ /**
+ * Installs all capture functions and triggers as one definition-checked transaction.
+ * Repeated deployments only validate the existing definition and perform no DDL. A partial,
+ * disabled, or unknown definition fails closed instead of silently repairing a capture gap.
+ */
+ async installCaptureInfrastructure(): Promise<void> {
+ await this.db.transaction(async (transaction) => {
+ await transaction.execute(sql`SET LOCAL lock_timeout = '3s'`);
+ /** Serialize installers before inspecting state so two deployments cannot both create DDL. */
+ await transaction.execute(
+ sql`SELECT pg_advisory_xact_lock(hashtext('lobehub.fts_search_sync_capture'))`,
+ );
+ await assertCaptureGinIndex(transaction);
+
+ const state = await readCaptureInfrastructureState(transaction);
+ if (state.mismatches.length === 0) return;
+ if (state.upgradeable) {
+ /** The transaction keeps writers from observing a capture gap during the known upgrade. */
+ for (const { name, table } of FTS_SEARCH_SYNC_CAPTURE_TRIGGER_TARGETS) {
+ await transaction.execute(sql.raw(`DROP TRIGGER "${name}" ON public."${table}"`));
+ }
+ for (const statement of FTS_SEARCH_SYNC_CAPTURE_TRIGGER_STATEMENTS) {
+ await transaction.execute(statement);
+ }
+ await assertCaptureDefinitions(transaction);
+ return;
+ }
+ if (!state.absent) {
+ throw new Error(
+ `Refusing to replace partial or unknown FTS search sync capture infrastructure: ${state.mismatches.join(', ')}`,
+ );
+ }
+
+ for (const statement of FTS_SEARCH_SYNC_CAPTURE_FUNCTION_STATEMENTS) {
+ await transaction.execute(statement);
+ }
+ for (const statement of FTS_SEARCH_SYNC_CAPTURE_TRIGGER_STATEMENTS) {
+ await transaction.execute(statement);
+ }
+
+ await assertCaptureDefinitions(transaction);
+ });
+ }
+
+ /** Fails before a reindex or incremental drain if capture is missing, disabled, or stale. */
+ async assertCaptureInfrastructure(): Promise<void> {
+ await assertCaptureGinIndex(this.db);
+ await assertCaptureDefinitions(this.db);
+ }
+
+ /** Returns the code-derived fingerprint only after the live definitions match it exactly. */
+ async readCaptureFingerprint(): Promise<string> {
+ await this.assertCaptureInfrastructure();
+ return FTS_SEARCH_SYNC_CAPTURE_FINGERPRINT;
+ }
+
+ /** Observes the latest allocated revision without treating it as a committed snapshot boundary. */
+ async readHighWaterRevision(): Promise<number> {
+ const result = await this.db.execute(sql`
+ SELECT CASE WHEN is_called THEN last_value ELSE 0 END AS revision
+ FROM fts_search_sync_revision_seq
+ `);
+ return revisionNumber(
+ rowsOf<{ revision: number | string }>(result)[0]?.revision,
+ 'reading the high-water mark',
+ );
+ }
+
+ /**
+ * Returns a revision boundary only after every earlier capture-source writer has committed or
+ * rolled back. Sequence allocation is non-transactional, so reading it before taking the SHARE
+ * locks could include a revision whose Outbox row is still invisible and later commits after the
+ * validation snapshot. The locks close that race without allocating a revision or mutating rows.
+ */
+ async readCommittedRevisionBoundary(): Promise<number> {
+ return this.db.transaction(async (transaction) => {
+ await lockCaptureSourceWrites(transaction);
+ const result = await transaction.execute(sql`
+ SELECT CASE WHEN is_called THEN last_value ELSE 0 END AS revision
+ FROM fts_search_sync_revision_seq
+ `);
+ return revisionNumber(
+ rowsOf<{ revision: number | string }>(result)[0]?.revision,
+ 'reading the committed revision boundary',
+ );
+ });
+ }
+
+ /**
+ * Reserves the full-reindex version, then waits for writers that allocated an older revision.
+ * Without this fence, a long transaction could commit an older Outbox revision after the
+ * backfill has already written stale data at the newer base revision.
+ */
+ async reserveRevisionWithWriteFence(): Promise<number> {
+ return this.db.transaction(async (transaction) => {
+ const result = await transaction.execute(sql`
+ SELECT nextval('fts_search_sync_revision_seq')::bigint AS revision
+ `);
+ const revision = revisionNumber(
+ rowsOf<{ revision: number | string }>(result)[0]?.revision,
+ 'reserving a reindex version',
+ 1,
+ );
+ await lockCaptureSourceWrites(transaction);
+ return revision;
+ });
+ }
+
+ /** Re-establishes the write fence before resuming a checkpoint created by an older process. */
+ async fenceSourceWrites(): Promise<void> {
+ await this.db.transaction(async (transaction) => {
+ await lockCaptureSourceWrites(transaction);
+ });
+ }
+
+ async acknowledgeMany(works: FtsSearchSyncWork[]): Promise<FtsSearchSyncWork[]> {
+ if (works.length === 0) return [];
+
+ const values = sql.join(
+ works.map(
+ (work) =>
+ sql`(${work.entity}::text, ${work.documentId}::text, ${work.revision}::bigint, ${work.leaseToken}::numeric)`,
+ ),
+ sql`, `,
+ );
+ const result = await this.db.execute(sql`
+ WITH acknowledged(entity, document_id, revision, lease_token) AS (
+ VALUES ${values}
+ )
+ DELETE FROM fts_search_sync_outbox AS outbox
+ USING acknowledged
+ WHERE outbox.entity = acknowledged.entity
+ AND outbox.document_id = acknowledged.document_id
+ AND outbox.revision = acknowledged.revision
+ AND EXTRACT(EPOCH FROM outbox.locked_until) = acknowledged.lease_token
+ RETURNING outbox.entity, outbox.document_id, outbox.revision,
+ EXTRACT(EPOCH FROM outbox.locked_until)::text AS lease_token
+ `);
+
+ return rowsOf<FtsSearchSyncRow>(result).map(toWork);
+ }
+
+ /** Keeps PostgreSQL's microsecond precision in the token instead of truncating through JS Date. */
+ async claim(limit = 100, leaseSeconds = 300): Promise<FtsSearchSyncWork[]> {
+ const result = await this.db.execute(sql`
+ WITH expired_candidates AS MATERIALIZED (
+ SELECT entity, document_id
+ FROM fts_search_sync_outbox
+ WHERE locked_until <= now()
+ AND dead_at IS NULL
+ ORDER BY locked_until, revision
+ LIMIT ${limit}
+ FOR UPDATE SKIP LOCKED
+ ), expired AS MATERIALIZED (
+ UPDATE fts_search_sync_outbox AS outbox
+ SET attempts = outbox.attempts + 1,
+ available_at = now() + make_interval(
+ secs => GREATEST(30, LEAST(POWER(2, outbox.attempts)::double precision, 3600))
+ ),
+ dead_at = CASE
+ WHEN outbox.attempts + 1 >= ${FTS_SEARCH_SYNC_MAX_ATTEMPTS} THEN now()
+ ELSE outbox.dead_at
+ END,
+ last_error = 'FTS search sync lease expired before settlement',
+ locked_until = NULL,
+ updated_at = now()
+ FROM expired_candidates
+ WHERE outbox.entity = expired_candidates.entity
+ AND outbox.document_id = expired_candidates.document_id
+ RETURNING outbox.entity, outbox.document_id
+ ), candidates AS (
+ SELECT entity, document_id, revision
+ FROM fts_search_sync_outbox
+ WHERE available_at <= now()
+ AND locked_until IS NULL
+ AND dead_at IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM expired
+ WHERE expired.entity = fts_search_sync_outbox.entity
+ AND expired.document_id = fts_search_sync_outbox.document_id
+ )
+ ORDER BY priority, available_at, revision
+ LIMIT ${limit}
+ FOR UPDATE SKIP LOCKED
+ )
+ , claimed AS (
+ UPDATE fts_search_sync_outbox AS outbox
+ SET locked_until = now() + make_interval(secs => ${leaseSeconds}),
+ updated_at = now()
+ FROM candidates
+ WHERE outbox.entity = candidates.entity
+ AND outbox.document_id = candidates.document_id
+ AND outbox.revision = candidates.revision
+ RETURNING outbox.entity, outbox.document_id, outbox.revision,
+ EXTRACT(EPOCH FROM outbox.locked_until)::text AS lease_token,
+ outbox.priority, outbox.available_at
+ )
+ SELECT entity, document_id, revision, lease_token
+ FROM claimed
+ ORDER BY priority, available_at, revision
+ `);
+
+ return rowsOf<FtsSearchSyncRow>(result).map(toWork);
+ }
+
+ async hasActionableWork(): Promise<boolean> {
+ const result = await this.db.execute(sql`
+ SELECT EXISTS (
+ SELECT 1
+ FROM fts_search_sync_outbox
+ WHERE available_at <= now()
+ AND (locked_until IS NULL OR locked_until <= now())
+ AND dead_at IS NULL
+ LIMIT 1
+ ) AS actionable
+ `);
+
+ return Boolean(rowsOf<{ actionable: boolean }>(result)[0]?.actionable);
+ }
+
+ async hasDeadLetters(): Promise<boolean> {
+ const result = await this.db.execute(sql`
+ SELECT EXISTS (
+ SELECT 1
+ FROM fts_search_sync_outbox
+ WHERE dead_at IS NOT NULL
+ LIMIT 1
+ ) AS has_dead_letters
+ `);
+
+ return Boolean(rowsOf<{ has_dead_letters: boolean }>(result)[0]?.has_dead_letters);
+ }
+
+ async markFailures(failures: FtsSearchSyncFailure[]): Promise<number> {
+ if (failures.length === 0) return 0;
+
+ const values = sql.join(
+ failures.map(
+ (failure) =>
+ sql`(${failure.entity}::text, ${failure.documentId}::text, ${failure.revision}::bigint, ${failure.leaseToken}::numeric, ${errorMessage(failure.error)}::text, ${failure.permanent ?? false}::boolean)`,
+ ),
+ sql`, `,
+ );
+ const result = await this.db.execute(sql`
+ WITH failed(entity, document_id, revision, lease_token, last_error, permanent) AS (
+ VALUES ${values}
+ )
+ UPDATE fts_search_sync_outbox AS outbox
+ SET attempts = outbox.attempts + 1,
+ available_at = CASE
+ WHEN failed.permanent THEN outbox.available_at
+ ELSE now() + make_interval(
+ secs => GREATEST(30, LEAST(POWER(2, outbox.attempts)::double precision, 3600))
+ )
+ END,
+ dead_at = CASE
+ WHEN failed.permanent OR outbox.attempts + 1 >= ${FTS_SEARCH_SYNC_MAX_ATTEMPTS} THEN now()
+ ELSE outbox.dead_at
+ END,
+ last_error = failed.last_error,
+ locked_until = NULL,
+ updated_at = now()
+ FROM failed
+ WHERE outbox.entity = failed.entity
+ AND outbox.document_id = failed.document_id
+ AND outbox.revision = failed.revision
+ AND EXTRACT(EPOCH FROM outbox.locked_until) = failed.lease_token
+ RETURNING outbox.dead_at IS NOT NULL AS dead
+ `);
+
+ return rowsOf<{ dead: boolean }>(result).filter((row) => row.dead).length;
+ }
+
+ async releaseMany(works: FtsSearchSyncWork[]): Promise<void> {
+ if (works.length === 0) return;
+
+ const values = sql.join(
+ works.map(
+ (work) =>
+ sql`(${work.entity}::text, ${work.documentId}::text, ${work.revision}::bigint, ${work.leaseToken}::numeric)`,
+ ),
+ sql`, `,
+ );
+ await this.db.execute(sql`
+ WITH released(entity, document_id, revision, lease_token) AS (
+ VALUES ${values}
+ )
+ UPDATE fts_search_sync_outbox AS outbox
+ SET locked_until = NULL, updated_at = now()
+ FROM released
+ WHERE outbox.entity = released.entity
+ AND outbox.document_id = released.document_id
+ AND outbox.revision = released.revision
+ AND EXTRACT(EPOCH FROM outbox.locked_until) = released.lease_token
+ `);
+ }
+
+ async stats(): Promise<FtsSearchSyncOutboxStats> {
+ const result = await this.db.execute(sql`
+ SELECT
+ entity,
+ COUNT(*) FILTER (WHERE attempts = 0 AND dead_at IS NULL)::int AS pending,
+ COUNT(*) FILTER (WHERE attempts > 0 AND dead_at IS NULL)::int AS retrying,
+ COUNT(*) FILTER (WHERE dead_at IS NOT NULL)::int AS dead,
+ COUNT(*) FILTER (
+ WHERE locked_until <= now() AND dead_at IS NULL
+ )::int AS expired_leases,
+ COUNT(*) FILTER (WHERE locked_until > now() AND dead_at IS NULL)::int AS in_flight,
+ COUNT(*) FILTER (
+ WHERE available_at <= now()
+ AND locked_until IS NULL
+ AND dead_at IS NULL
+ )::int AS ready,
+ (
+ SELECT CASE WHEN is_called THEN last_value ELSE 0 END
+ FROM fts_search_sync_revision_seq
+ )::bigint AS high_water_revision,
+ MIN(revision) FILTER (WHERE dead_at IS NULL)::bigint AS oldest_active_revision,
+ COALESCE(
+ GREATEST(
+ 0,
+ EXTRACT(EPOCH FROM (
+ now() - MIN(available_at) FILTER (
+ WHERE dead_at IS NULL
+ AND locked_until IS NULL
+ AND available_at <= now()
+ )
+ ))
+ ),
+ 0
+ )::double precision AS oldest_ready_age_seconds
+ FROM fts_search_sync_outbox
+ GROUP BY GROUPING SETS ((entity), ())
+ `);
+ const rows = rowsOf<{
+ dead: number | string;
+ entity: FtsSearchDocumentEntity | null;
+ expired_leases: number | string;
+ high_water_revision: number | string;
+ in_flight: number | string;
+ oldest_active_revision: number | string | null;
+ oldest_ready_age_seconds: number | string;
+ pending: number | string;
+ ready: number | string;
+ retrying: number | string;
+ }>(result);
+ const total = rows.find((row) => row.entity === null);
+ const entities = Object.fromEntries(
+ FTS_SEARCH_DOCUMENT_ENTITIES.map((entity) => {
+ const row = rows.find((item) => item.entity === entity);
+ return [
+ entity,
+ {
+ dead: Number(row?.dead ?? 0),
+ expiredLeases: Number(row?.expired_leases ?? 0),
+ inFlight: Number(row?.in_flight ?? 0),
+ oldestReadyAgeSeconds: Number(row?.oldest_ready_age_seconds ?? 0),
+ pending: Number(row?.pending ?? 0),
+ ready: Number(row?.ready ?? 0),
+ retrying: Number(row?.retrying ?? 0),
+ },
+ ];
+ }),
+ ) as Record<FtsSearchDocumentEntity, FtsSearchSyncOutboxEntityStats>;
+ const highWaterRevision = Number(total?.high_water_revision ?? 0);
+ const oldestActiveRevision =
+ total?.oldest_active_revision === null || total?.oldest_active_revision === undefined
+ ? null
+ : Number(total.oldest_active_revision);
+
+ return {
+ dead: Number(total?.dead ?? 0),
+ entities,
+ expiredLeases: Number(total?.expired_leases ?? 0),
+ highWaterRevision,
+ inFlight: Number(total?.in_flight ?? 0),
+ oldestActiveRevision,
+ oldestReadyAgeSeconds: Number(total?.oldest_ready_age_seconds ?? 0),
+ pending: Number(total?.pending ?? 0),
+ ready: Number(total?.ready ?? 0),
+ retrying: Number(total?.retrying ?? 0),
+ revisionLag: oldestActiveRevision === null ? 0 : highWaterRevision - oldestActiveRevision,
+ };
+ }
+}
diff --git a/packages/database/src/repositories/ftsSearchSyncOutbox/server.ts b/packages/database/src/repositories/ftsSearchSyncOutbox/server.ts
new file mode 100644
index 00000000000..a69abe83cb8
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearchSyncOutbox/server.ts
@@ -0,0 +1,5 @@
+import { serverDB } from '../../core/db-adaptor';
+import { FtsSearchSyncOutboxRepository } from '.';
+
+/** Application singleton kept separate so standalone tooling can import the repository class. */
+export const ftsSearchSyncOutboxRepository = new FtsSearchSyncOutboxRepository(serverDB);
diff --git a/packages/database/src/repositories/home/__tests__/index.test.ts b/packages/database/src/repositories/home/__tests__/index.test.ts
index cd8c7b953a3..cfc328014df 100644
--- a/packages/database/src/repositories/home/__tests__/index.test.ts
+++ b/packages/database/src/repositories/home/__tests__/index.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import * as Schema from '../../../schemas';
@@ -659,6 +659,56 @@ describe('HomeRepository', () => {
});
});
+ describe('searchAgents with external candidates', () => {
+ it('hydrates only current-scope non-virtual agents and chat groups', async () => {
+ await clientDB.insert(Schema.agents).values([
+ { id: 'candidate-agent-own', title: 'Own agent', userId },
+ { id: 'candidate-agent-virtual', title: 'Virtual agent', userId, virtual: true },
+ { id: 'candidate-agent-other', title: 'Other agent', userId: otherUserId },
+ ]);
+ await clientDB.insert(Schema.chatGroups).values([
+ { id: 'candidate-group-own', title: 'Own group', userId },
+ { id: 'candidate-group-other', title: 'Other group', userId: otherUserId },
+ ]);
+ const ftsSearchCandidates = vi.fn().mockImplementation(({ entity }) =>
+ Promise.resolve({
+ candidates:
+ entity === 'agents'
+ ? [
+ { id: 'candidate-agent-other', score: 12 },
+ { id: 'candidate-agent-virtual', score: 10 },
+ { id: 'candidate-agent-deleted', score: 8 },
+ { id: 'candidate-agent-own', score: 6 },
+ ]
+ : [
+ { id: 'candidate-group-other', score: 12 },
+ { id: 'candidate-group-deleted', score: 10 },
+ { id: 'candidate-group-own', score: 8 },
+ ],
+ total: 4,
+ }),
+ );
+ const repo = new HomeRepository(clientDB, userId, undefined, {
+ ftsSearchCandidateEnabled: true,
+ ftsSearchCandidates,
+ });
+
+ const result = await repo.searchAgents('candidate');
+
+ expect(result.map(({ id }) => id).sort()).toEqual([
+ 'candidate-agent-own',
+ 'candidate-group-own',
+ ]);
+ expect(ftsSearchCandidates).toHaveBeenCalledTimes(2);
+ expect(ftsSearchCandidates).toHaveBeenCalledWith({
+ entity: 'agents',
+ filters: { excludeVirtual: true },
+ pagination: {},
+ query: { fields: ['title', 'description'], text: 'candidate' },
+ });
+ });
+ });
+
describe('getSidebarAgentList - heterogeneous type', () => {
it('should expose heterogeneousType from agencyConfig.heterogeneousProvider.type', async () => {
await clientDB.insert(Schema.agents).values({
diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.ts
index 102ff7f126a..2393b25e233 100644
--- a/packages/database/src/repositories/home/index.ts
+++ b/packages/database/src/repositories/home/index.ts
@@ -21,7 +21,9 @@ import {
import { type LobeChatDatabase } from '../../type';
import { sanitizeBm25Query } from '../../utils/bm25';
import { normalizeInboxAgentMeta } from '../../utils/inboxAgent';
+import { inJsonStringArray } from '../../utils/inJsonStringArray';
import { buildWorkspaceWhere } from '../../utils/workspace';
+import type { FtsSearchCandidateSource } from '../ftsSearch';
// Mirrors the main chat sidebar's system-topic exclusions, plus the legacy
// task_manager trigger. These topics are surfaced in their own product surfaces,
@@ -43,11 +45,18 @@ export class HomeRepository {
private userId: string;
private workspaceId?: string;
private db: LobeChatDatabase;
-
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ private ftsSearchCandidateSource?: FtsSearchCandidateSource;
+
+ constructor(
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+ ftsSearchCandidateSource?: FtsSearchCandidateSource,
+ ) {
this.userId = userId;
this.workspaceId = workspaceId;
this.db = db;
+ this.ftsSearchCandidateSource = ftsSearchCandidateSource;
}
private get scope() {
@@ -466,6 +475,24 @@ export class HomeRepository {
if (!keyword.trim()) return [];
const bm25Query = sanitizeBm25Query(keyword);
+ const candidateResults = this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled
+ ? await Promise.all([
+ this.ftsSearchCandidateSource.ftsSearchCandidates({
+ entity: 'agents',
+ filters: { excludeVirtual: true },
+ pagination: {},
+ query: { fields: ['title', 'description'], text: keyword },
+ }),
+ this.ftsSearchCandidateSource.ftsSearchCandidates({
+ entity: 'chatGroups',
+ filters: {},
+ pagination: {},
+ query: { fields: ['title', 'description'], text: keyword },
+ }),
+ ])
+ : undefined;
+ const agentCandidateIds = candidateResults?.[0].candidates.map(({ id }) => id);
+ const chatGroupCandidateIds = candidateResults?.[1].candidates.map(({ id }) => id);
// Run agent and chat group searches in parallel
const [agentResults, chatGroupResults] = await Promise.all([
@@ -493,7 +520,9 @@ export class HomeRepository {
and(
buildWorkspaceWhere(this.scope, agents),
not(eq(agents.virtual, true)),
- sql`(${agents.title} @@@ ${bm25Query} OR ${agents.description} @@@ ${bm25Query})`,
+ agentCandidateIds
+ ? inJsonStringArray(agents.id, agentCandidateIds)
+ : sql`(${agents.title} @@@ ${bm25Query} OR ${agents.description} @@@ ${bm25Query})`,
),
)
.orderBy(desc(agents.updatedAt)),
@@ -514,7 +543,9 @@ export class HomeRepository {
.where(
and(
buildWorkspaceWhere(this.scope, chatGroups),
- sql`(${chatGroups.title} @@@ ${bm25Query} OR ${chatGroups.description} @@@ ${bm25Query})`,
+ chatGroupCandidateIds
+ ? inJsonStringArray(chatGroups.id, chatGroupCandidateIds)
+ : sql`(${chatGroups.title} @@@ ${bm25Query} OR ${chatGroups.description} @@@ ${bm25Query})`,
),
)
.orderBy(desc(chatGroups.updatedAt)),
diff --git a/packages/database/src/repositories/search/index.ts b/packages/database/src/repositories/search/index.ts
deleted file mode 100644
index 83bc0f4d769..00000000000
--- a/packages/database/src/repositories/search/index.ts
+++ /dev/null
@@ -1,1364 +0,0 @@
-import { LIBRARY_HIDDEN_FILE_SOURCES } from '@lobechat/types';
-import {
- and,
- desc,
- eq,
- inArray,
- isNull,
- ne,
- notInArray,
- or,
- type SQL,
- sql,
- type SQLWrapper,
-} from 'drizzle-orm';
-import type { AnyPgColumn } from 'drizzle-orm/pg-core';
-
-import {
- agents,
- chatGroups,
- DOCUMENT_FOLDER_TYPE,
- documents,
- files,
- knowledgeBaseFiles,
- knowledgeBases,
- messages,
- topics,
- userMemories,
-} from '../../schemas';
-import type { LobeChatDatabase } from '../../type';
-import { sanitizeBm25Query } from '../../utils/bm25';
-import { normalizeInboxAgentMeta, normalizeInboxAgentTitle } from '../../utils/inboxAgent';
-import { buildWorkspaceWhere } from '../../utils/workspace';
-
-export type SearchResultType =
- | 'page'
- | 'pageContent'
- | 'agent'
- | 'topic'
- | 'chatGroup'
- | 'file'
- | 'folder'
- | 'memory'
- | 'message'
- | 'mcp'
- | 'plugin'
- | 'communityAgent'
- | 'knowledgeBase';
-
-export interface BaseSearchResult {
- // 1=exact, 2=prefix, 3=contains
- createdAt: Date;
- description?: string | null;
- id: string;
- relevance: number;
- title: string;
- type: SearchResultType;
- updatedAt: Date;
-}
-
-export interface PageSearchResult extends BaseSearchResult {
- id: string;
- type: 'page';
-}
-
-export interface PageContentSearchResult extends BaseSearchResult {
- id: string;
- type: 'pageContent';
-}
-
-export interface AgentSearchResult extends BaseSearchResult {
- avatar: string | null;
- backgroundColor: string | null;
- slug: string | null;
- tags: string[];
- type: 'agent';
-}
-
-export interface ChatGroupSearchResult extends BaseSearchResult {
- avatar: string | null;
- backgroundColor: string | null;
- type: 'chatGroup';
-}
-
-export interface TopicSearchResult extends BaseSearchResult {
- agent: {
- avatar: string | null;
- backgroundColor: string | null;
- title: string | null;
- } | null;
- agentId: string | null;
- favorite: boolean | null;
- groupId: string | null;
- sessionId: string | null;
- type: 'topic';
-}
-
-export interface FileSearchResult extends BaseSearchResult {
- fileType: string;
- knowledgeBaseId: string | null;
- name: string;
- size: number;
- type: 'file';
- url: string | null;
-}
-
-export interface FolderSearchResult extends BaseSearchResult {
- knowledgeBaseId: string | null;
- slug: string | null;
- type: 'folder';
-}
-
-export interface MessageSearchResult extends BaseSearchResult {
- agentId: string | null;
- content: string;
- groupId: string | null;
- model: string | null;
- role: string;
- topicId: string | null;
- type: 'message';
-}
-
-export interface MemorySearchResult extends BaseSearchResult {
- memoryLayer: string | null;
- type: 'memory';
-}
-
-export interface MCPSearchResult extends BaseSearchResult {
- author: string;
- avatar?: string | null;
- category?: string | null;
- connectionType?: 'http' | 'stdio' | null;
- identifier: string;
- installCount?: number | null;
- isFeatured?: boolean | null;
- isValidated?: boolean | null;
- tags?: string[] | null;
- type: 'mcp';
-}
-
-export interface PluginSearchResult extends BaseSearchResult {
- author: string;
- avatar?: string | null;
- category?: string | null;
- identifier: string;
- tags?: string[] | null;
- type: 'plugin';
-}
-
-export interface KnowledgeBaseSearchResult extends BaseSearchResult {
- avatar: string | null;
- type: 'knowledgeBase';
-}
-
-/**
- * BM25 hit for KB-scoped documents used by chunkRouter.semanticSearchForChat.
- * Covers both inline `custom/document` pages and file-backed documents
- * (e.g. parsed PDFs) joined through `knowledge_base_files`.
- *
- * `fileId` is present when the hit comes from a parsed-file document, letting
- * the agent fetch the original via readKnowledge with either docs_* or file_*.
- * `relevance` is normalized to [1, 3] (lower = better, matches BaseSearchResult semantics).
- */
-export interface KnowledgeBaseDocumentHit {
- documentId: string;
- fileId?: string;
- knowledgeBaseId: string;
- relevance: number;
- snippet: string;
- title: string;
- updatedAt: Date;
-}
-
-export interface AssistantSearchResult extends BaseSearchResult {
- author: string;
- avatar?: string | null;
- homepage?: string | null;
- identifier: string;
- tags?: string[] | null;
- type: 'communityAgent';
-}
-
-export type SearchResult =
- | PageSearchResult
- | PageContentSearchResult
- | AgentSearchResult
- | ChatGroupSearchResult
- | TopicSearchResult
- | FileSearchResult
- | FolderSearchResult
- | MessageSearchResult
- | MemorySearchResult
- | MCPSearchResult
- | PluginSearchResult
- | AssistantSearchResult
- | KnowledgeBaseSearchResult;
-
-export interface SearchOptions {
- agentId?: string;
- contextType?: 'agent' | 'resource' | 'page';
- /**
- * Knowledge-base ids to drop from KB results — restricted (member
- * No-access) KBs must not be discoverable through unified search either.
- * Caller-relative, so the router computes it per request.
- */
- excludeKnowledgeBaseIds?: string[];
- limitPerType?: number;
- offset?: number;
- query: string;
- type?: SearchResultType;
-}
-
-/**
- * Topics and messages are ordered by recency rather than BM25 score, so we fetch
- * a larger candidate pool first (most relevant matches), then keep the most recent
- * ones. This prevents newly created/updated items from being buried under older
- * high-scoring matches that would otherwise fill the small per-type limit.
- */
-const RECENCY_CANDIDATE_MULTIPLIER = 4;
-
-/**
- * Every query here is shaped as "inner single-table BM25 scan → outer enrichment",
- * because ParadeDB only picks its TopN custom scan (`TopNScanExecState`, which
- * visits a handful of heap rows) when the scan node itself carries the whole
- * `ORDER BY paradedb.score() LIMIT n`. Two things break that:
- *
- * 1. A qual over a column that is not in the BM25 index — `workspace_id` is the
- * one that matters here. The plan degrades to a plain index scan that scores
- * and sorts the *entire* match set — on an account with a long message
- * history that turns a sub-second query into a multi-minute one, fetching
- * tens of thousands of heap rows instead of 10.
- * 2. A JOIN sitting between the scan and the `ORDER BY … LIMIT` — that alone
- * downgrades messages/topics/files to `NormalScanExecState` even without any
- * workspace qual.
- *
- * So joins always live outside the scan, and the ownership predicate is split by
- * `liftsWorkspaceFilter` below.
- *
- * On top of the plan degradation, production pg_search (0.15.26) has a scoring
- * defect that makes any non-indexed qual inside the scan strictly worse than
- * slow: `paradedb.score()` returns NULL for *every* row of the statement
- * (fixed in v0.17.0, see neondatabase/neon#12853). `ORDER BY score DESC` over
- * an all-NULL column is an arbitrary order, and `mapScoresToRelevance` maps it
- * to a flat relevance of 3. So a non-indexed qual inside the scan does not
- * merely cost TopN — it silently breaks ranking. That is why no such qual is
- * ever allowed back inside, and why falling back to the inline-exact query is
- * not an option: the "exact" query is the broken one.
- *
- * `agent_id` is not a BM25 field either, so the agent-scoped variants of
- * `searchMessages` / `searchTopics` (the command menu passes the active agent)
- * lift it above the scan the same way, over-fetching through a dedicated
- * candidate pool (`AGENT_SCOPE_CANDIDATE_POOL`) — but only while the scan's
- * score ordering is real (see `liftsAgentFilter`): trading the exact inline
- * predicate for a score-ordered pool is unsound when the scores backing that
- * order are NULL. Indexing the column instead is tracked with the other
- * missing fast fields.
- *
- * Indexing the column is tracked with the other missing fast fields.
- */
-const WORKSPACE_FILTER_CANDIDATE_MULTIPLIER = 5;
-
-/**
- * Candidate pool for the inner scan when the agent filter is lifted above it.
- *
- * `agent_id` is far more selective than the ownership predicate — a single
- * agent can hold well under 1% of an account's matches — so the pool has to be
- * much deeper than the workspace one for small agents to survive the cut. The
- * agent-scoped caller needs ≥ 24 rows to fill its per-type limit (limit 6 ×
- * `RECENCY_CANDIDATE_MULTIPLIER`); measured on a 60k-match account, a pool of
- * 20k keeps ~50 rows for an agent holding 0.32% of matches, while the TopN
- * scan's cost stays nearly flat as the pool grows (6ms at 500 → 11ms at 20k).
- */
-const AGENT_SCOPE_CANDIDATE_POOL = 20_000;
-
-/**
- * Floor for the personal-mode candidate pool. Rows dropped by the lifted
- * `workspace_id IS NULL` check eat into the per-type limit, so an account with
- * many workspace rows could otherwise come up short — with a pool of 60 an
- * adversarial mix (5k high-scoring workspace rows vs 20 low-scoring personal
- * ones) returned 0 of 12 rows.
- *
- * A generous pool is what makes that a non-issue, and it is measurably free:
- * once the scan is TopN, the pool size barely registers (same dataset, full
- * payload: 60 rows → 0.53s, 1000 → 0.46s, 2000 → 0.46s). The tantivy scan
- * dominates; the extra heap fetches do not.
- */
-const WORKSPACE_FILTER_MIN_CANDIDATES = 500;
-
-/**
- * Flip to `true` once every BM25 index used by this repo carries `workspace_id`
- * as a fast keyword field. pg_search then pushes `workspace_id IS
- * NULL` down as `must_not: exists(workspace_id)` and `workspace_id = ?` as a
- * `term`, so the ownership predicate can stay inline and personal search becomes
- * exact again (no candidate over-fetch, no dropped rows) while workspace-mode
- * search gets TopN for free.
- */
-const WORKSPACE_ID_IN_BM25_INDEX = false;
-
-interface WorkspaceScopedColumns {
- userId: AnyPgColumn;
- visibility?: AnyPgColumn;
- workspaceId: AnyPgColumn;
-}
-
-/**
- * Search Repository - provides unified search across Agents, Topics, and Files
- */
-export class SearchRepo {
- private userId: string;
- private db: LobeChatDatabase;
- private workspaceId?: string;
-
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
- this.userId = userId;
- this.db = db;
- this.workspaceId = workspaceId;
- }
-
- private get scope() {
- return { userId: this.userId, workspaceId: this.workspaceId };
- }
-
- /**
- * Whether the `workspace_id IS NULL` half of the personal-mode ownership
- * predicate has to be evaluated above the BM25 scan.
- *
- * Only personal mode gets this treatment: it still keeps `user_id = ?` inside
- * the scan (a fast field, so ParadeDB pushes it down), which bounds the
- * candidate pool to the caller's own rows and makes over-fetching a sound
- * approximation. Workspace mode has no such pushdown-able owner column — its
- * rows are a tiny slice of a global TopN — so lifting the filter there would
- * silently return nothing. It keeps the exact inline predicate and stays on
- * the slow plan until `workspace_id` becomes a fast keyword field in the BM25 index.
- */
- private get liftsWorkspaceFilter() {
- return !WORKSPACE_ID_IN_BM25_INDEX && !this.workspaceId;
- }
-
- /**
- * Whether the agent filter can be lifted above the BM25 scan.
- *
- * Lifting swaps the exact inline predicate for a score-ordered candidate
- * pool, which is only sound while the scan's `ORDER BY paradedb.score()` is
- * real. Personal mode qualifies: its scan keeps only pushdown-able quals, so
- * scores are valid and the pool is genuinely the top-N matches. Workspace
- * mode does not (until `workspace_id` becomes a fast field in the BM25 index): its
- * inline `workspace_id` qual NULLs the whole score column on pg_search
- * 0.15.26, so a pool cut on that ordering would be an arbitrary slice that
- * silently drops agent rows. It keeps `agent_id` inline next to
- * `workspace_id` instead — exact, on the already-degraded plan.
- */
- private get liftsAgentFilter() {
- return WORKSPACE_ID_IN_BM25_INDEX || !this.workspaceId;
- }
-
- /** Ownership predicate that is safe to keep inside the BM25 scan. */
- private scanScopeWhere(cols: WorkspaceScopedColumns): SQL {
- if (!this.liftsWorkspaceFilter) return buildWorkspaceWhere(this.scope, cols);
-
- return eq(cols.userId, this.userId) as SQL;
- }
-
- /** Remainder of the ownership predicate, applied above the BM25 scan. */
- private liftedScopeWhere(workspaceIdColumn: SQLWrapper): SQL | undefined {
- return this.liftsWorkspaceFilter ? (isNull(workspaceIdColumn) as SQL) : undefined;
- }
-
- /**
- * Candidate pool for the inner scan. When the workspace filter is lifted, rows
- * dropped above the scan would otherwise shrink the result set, so over-fetch.
- * Personal search stays exact unless more than `WORKSPACE_FILTER_MIN_CANDIDATES`
- * of the account's workspace rows outscore its personal matches.
- */
- private scanCandidateLimit(limit: number) {
- if (!this.liftsWorkspaceFilter) return limit;
-
- return Math.max(limit * WORKSPACE_FILTER_CANDIDATE_MULTIPLIER, WORKSPACE_FILTER_MIN_CANDIDATES);
- }
-
- /**
- * Search across agents, topics, files, and pages
- */
- async search(options: SearchOptions): Promise<SearchResult[]> {
- const { query, type, limitPerType = 5, agentId, contextType } = options;
-
- // Early return for empty query
- if (!query || query.trim() === '') return [];
-
- const trimmedQuery = query.trim();
-
- // Context-aware limits: prioritize relevant types based on context
- const limits = this.calculateLimits(limitPerType, type, agentId, contextType);
-
- // Run searches in parallel for better performance
- const searchPromises: Promise<SearchResult[]>[] = [];
-
- const excludeKbIds = options.excludeKnowledgeBaseIds ?? [];
-
- if ((!type || type === 'agent') && limits.agent > 0) {
- searchPromises.push(this.searchAgents(trimmedQuery, limits.agent));
- }
- if ((!type || type === 'chatGroup') && limits.chatGroup > 0) {
- searchPromises.push(this.searchChatGroups(trimmedQuery, limits.chatGroup));
- }
- if ((!type || type === 'topic') && limits.topic > 0) {
- searchPromises.push(this.searchTopics(trimmedQuery, limits.topic, agentId));
- }
- if ((!type || type === 'message') && limits.message > 0) {
- searchPromises.push(this.searchMessages(trimmedQuery, limits.message, agentId));
- }
- if ((!type || type === 'file') && limits.file > 0) {
- searchPromises.push(this.searchFiles(trimmedQuery, limits.file, excludeKbIds));
- }
- if ((!type || type === 'folder') && limits.folder > 0) {
- searchPromises.push(this.searchFolders(trimmedQuery, limits.folder, excludeKbIds));
- }
- if ((!type || type === 'page') && limits.page > 0) {
- searchPromises.push(this.searchPages(trimmedQuery, limits.page, excludeKbIds));
- }
- if ((!type || type === 'memory') && limits.memory > 0) {
- searchPromises.push(this.searchMemories(trimmedQuery, limits.memory));
- }
- if ((!type || type === 'knowledgeBase') && limits.knowledgeBase > 0) {
- searchPromises.push(
- this.searchKnowledgeBases(
- trimmedQuery,
- limits.knowledgeBase,
- options.excludeKnowledgeBaseIds,
- ),
- );
- }
-
- const results = await Promise.all(searchPromises);
-
- // Each search method already returns its results in the intended display order
- // (topics/messages by recency, other types by BM25 score). The command palette
- // groups results by type, so we only need to preserve each type's internal order
- // here rather than re-sorting the merged list by relevance.
- return results.flat();
- }
-
- /**
- * Calculate result limits based on context
- */
- private calculateLimits(
- baseLimit: number,
- type?: SearchResultType,
- agentId?: string,
- contextType?: 'agent' | 'resource' | 'page',
- ): {
- agent: number;
- chatGroup: number;
- file: number;
- folder: number;
- knowledgeBase: number;
- memory: number;
- message: number;
- page: number;
- pageContent: number;
- topic: number;
- } {
- // If type filter is specified, use full limit for that type
- if (type) {
- return {
- agent: type === 'agent' ? baseLimit : 0,
- chatGroup: type === 'chatGroup' ? baseLimit : 0,
- file: type === 'file' ? baseLimit : 0,
- folder: type === 'folder' ? baseLimit : 0,
- knowledgeBase: type === 'knowledgeBase' ? baseLimit : 0,
- memory: type === 'memory' ? baseLimit : 0,
- message: type === 'message' ? baseLimit : 0,
- page: type === 'page' ? baseLimit : 0,
- pageContent: type === 'pageContent' ? baseLimit : 0,
- topic: type === 'topic' ? baseLimit : 0,
- };
- }
-
- // Page context: expand pages to 6, limit others to 3
- if (contextType === 'page') {
- return {
- agent: 3,
- chatGroup: 3,
- file: 3,
- folder: 3,
- knowledgeBase: 3,
- memory: 3,
- message: 3,
- page: 6,
- pageContent: 0,
- topic: 3,
- };
- }
-
- // Resource context: expand files and folders to 6, limit others to 3
- if (contextType === 'resource') {
- return {
- agent: 3,
- chatGroup: 3,
- file: 6,
- folder: 6,
- knowledgeBase: 6,
- memory: 3,
- message: 3,
- page: 3,
- pageContent: 0,
- topic: 3,
- };
- }
-
- // Agent context: expand topics and messages to 6, limit others to 3
- if (agentId || contextType === 'agent') {
- return {
- agent: 3,
- chatGroup: 3,
- file: 3,
- folder: 3,
- knowledgeBase: 3,
- memory: 3,
- message: 6,
- page: 3,
- pageContent: 0,
- topic: 6,
- };
- }
-
- // General context: limit all types to 3
- return {
- agent: 3,
- chatGroup: 3,
- file: 3,
- folder: 3,
- knowledgeBase: 3,
- memory: 3,
- message: 3,
- page: 3,
- pageContent: 0,
- topic: 3,
- };
- }
-
- /**
- * Map BM25 scores to relevance values compatible with the existing sort system.
- * BM25 score (higher=better) → relevance (1-3, lower=better)
- */
- private mapScoresToRelevance<T extends { score: number }>(
- rows: T[],
- ): (Omit<T, 'score'> & { relevance: number })[] {
- if (rows.length === 0) return [];
- const maxScore = Math.max(...rows.map((r) => r.score));
- return rows.map(({ score, ...rest }) => ({
- ...rest,
- relevance: maxScore > 0 ? 1 + 2 * (1 - score / maxScore) : 3,
- }));
- }
-
- /**
- * Truncate content with ellipsis
- */
- private truncate(content: string | null | undefined, maxLength: number = 200): string | null {
- if (!content) return null;
- if (content.length <= maxLength) return content;
- return content.slice(0, maxLength) + '...';
- }
-
- /**
- * Search agents by title, description, slug, tags (BM25)
- */
- private async searchAgents(query: string, limit: number): Promise<AgentSearchResult[]> {
- const bm25Query = sanitizeBm25Query(query);
-
- const hits = this.db
- .select({
- avatar: agents.avatar,
- backgroundColor: agents.backgroundColor,
- createdAt: agents.createdAt,
- description: agents.description,
- id: agents.id,
- name: agents.name,
- score: sql<number>`paradedb.score(${agents.id})`.as('score'),
- slug: agents.slug,
- tags: agents.tags,
- title: agents.title,
- updatedAt: agents.updatedAt,
- workspaceId: agents.workspaceId,
- })
- .from(agents)
- .where(
- and(
- this.scanScopeWhere(agents),
- sql`(${agents.title} @@@ ${bm25Query} OR ${agents.description} @@@ ${bm25Query} OR ${agents.slug} @@@ ${bm25Query} OR ${agents.tags} @@@ ${bm25Query} OR ${agents.systemRole} @@@ ${bm25Query})`,
- ),
- )
- .orderBy(sql`paradedb.score(${agents.id}) DESC`)
- .limit(this.scanCandidateLimit(limit))
- .as('agent_hits');
-
- const rows = await this.db
- .select({
- avatar: hits.avatar,
- backgroundColor: hits.backgroundColor,
- createdAt: hits.createdAt,
- description: hits.description,
- id: hits.id,
- score: hits.score,
- slug: hits.slug,
- tags: hits.tags,
- title: hits.title,
- updatedAt: hits.updatedAt,
- })
- .from(hits)
- .where(this.liftedScopeWhere(hits.workspaceId))
- .orderBy(desc(hits.score))
- .limit(limit);
-
- return this.mapScoresToRelevance(rows).map((row) => {
- const meta = normalizeInboxAgentMeta(
- { avatar: row.avatar, title: row.title },
- { slug: row.slug },
- );
-
- return {
- avatar: meta.avatar,
- backgroundColor: row.backgroundColor,
- createdAt: row.createdAt,
- description: row.description,
- id: row.id,
- relevance: row.relevance,
- slug: row.slug,
- tags: (row.tags as string[]) || [],
- title: meta.title || '',
- type: 'agent' as const,
- updatedAt: row.updatedAt,
- };
- });
- }
-
- /**
- * Search topics by title, content, description (BM25)
- */
- private async searchTopics(
- query: string,
- limit: number,
- agentId?: string,
- ): Promise<TopicSearchResult[]> {
- const bm25Query = sanitizeBm25Query(query);
-
- const candidateLimit = limit * RECENCY_CANDIDATE_MULTIPLIER;
-
- const hits = this.db
- .select({
- agentId: topics.agentId,
- content: topics.content,
- createdAt: topics.createdAt,
- favorite: topics.favorite,
- groupId: topics.groupId,
- id: topics.id,
- score: sql<number>`paradedb.score(${topics.id})`.as('score'),
- sessionId: topics.sessionId,
- title: topics.title,
- updatedAt: topics.updatedAt,
- workspaceId: topics.workspaceId,
- })
- .from(topics)
- .where(
- and(
- this.scanScopeWhere(topics),
- agentId && !this.liftsAgentFilter ? eq(topics.agentId, agentId) : undefined,
- sql`(${topics.title} @@@ ${bm25Query} OR ${topics.content} @@@ ${bm25Query} OR ${topics.description} @@@ ${bm25Query})`,
- ),
- )
- .orderBy(sql`paradedb.score(${topics.id}) DESC`)
- // `agent_id` is not a BM25 field, so where the scan's score order is real
- // its filter lives above the scan and the pool deepens to compensate. See
- // the scan-shape invariant and `liftsAgentFilter` above.
- .limit(
- agentId && this.liftsAgentFilter
- ? AGENT_SCOPE_CANDIDATE_POOL
- : this.scanCandidateLimit(candidateLimit),
- )
- .as('topic_hits');
-
- const rows = await this.db
- .select({
- // agents.id is selected as a sentinel: non-null only when the JOIN
- // matched an agent owned by this user. Topics carrying an agentId
- // that points to another user's agent (possible via migrated/crafted
- // data) yield null here, so the renderer falls back to the
- // agent-less subtitle and never surfaces foreign metadata.
- agentAvatar: agents.avatar,
- agentBackgroundColor: agents.backgroundColor,
- agentId: hits.agentId,
- agentMatchedId: agents.id,
- agentName: agents.name,
- agentSlug: agents.slug,
- agentTitle: agents.title,
- content: hits.content,
- createdAt: hits.createdAt,
- favorite: hits.favorite,
- groupId: hits.groupId,
- id: hits.id,
- score: hits.score,
- sessionId: hits.sessionId,
- title: hits.title,
- updatedAt: hits.updatedAt,
- })
- .from(hits)
- .leftJoin(agents, and(eq(hits.agentId, agents.id), buildWorkspaceWhere(this.scope, agents)))
- .where(
- and(
- this.liftedScopeWhere(hits.workspaceId),
- agentId ? eq(hits.agentId, agentId) : undefined,
- ),
- )
- .orderBy(desc(hits.score))
- .limit(candidateLimit);
-
- return this.mapScoresToRelevance(rows)
- .map((row) => ({
- agent: row.agentMatchedId
- ? {
- avatar: normalizeInboxAgentMeta(
- { avatar: row.agentAvatar, title: row.agentTitle },
- { slug: row.agentSlug },
- ).avatar,
- backgroundColor: row.agentBackgroundColor,
- title: normalizeInboxAgentTitle(row.agentTitle, {
- slug: row.agentSlug,
- }),
- }
- : null,
- agentId: row.agentId,
- createdAt: row.createdAt,
- description: this.truncate(row.content),
- favorite: row.favorite,
- groupId: row.groupId,
- id: row.id,
- relevance: row.relevance,
- sessionId: row.sessionId,
- title: row.title || '',
- type: 'topic' as const,
- updatedAt: row.updatedAt,
- }))
- .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())
- .slice(0, limit);
- }
-
- /**
- * Search messages by content (BM25)
- */
- private async searchMessages(
- query: string,
- limit: number,
- agentId?: string,
- ): Promise<MessageSearchResult[]> {
- const bm25Query = sanitizeBm25Query(query);
-
- const candidateLimit = limit * RECENCY_CANDIDATE_MULTIPLIER;
-
- const hits = this.db
- .select({
- agentId: messages.agentId,
- content: messages.content,
- createdAt: messages.createdAt,
- groupId: messages.groupId,
- id: messages.id,
- model: messages.model,
- role: messages.role,
- score: sql<number>`paradedb.score(${messages.id})`.as('score'),
- topicId: messages.topicId,
- updatedAt: messages.updatedAt,
- workspaceId: messages.workspaceId,
- })
- .from(messages)
- .where(
- and(
- this.scanScopeWhere(messages),
- ne(messages.role, 'tool'),
- agentId && !this.liftsAgentFilter ? eq(messages.agentId, agentId) : undefined,
- sql`${messages.content} @@@ ${bm25Query}`,
- ),
- )
- .orderBy(sql`paradedb.score(${messages.id}) DESC`)
- // `agent_id` is not a BM25 field, so where the scan's score order is real
- // its filter lives above the scan and the pool deepens to compensate. See
- // the scan-shape invariant and `liftsAgentFilter` above.
- .limit(
- agentId && this.liftsAgentFilter
- ? AGENT_SCOPE_CANDIDATE_POOL
- : this.scanCandidateLimit(candidateLimit),
- )
- .as('message_hits');
-
- const rows = await this.db
- .select({
- agentId: hits.agentId,
- agentName: agents.name,
- agentSlug: agents.slug,
- agentTitle: agents.title,
- content: hits.content,
- createdAt: hits.createdAt,
- groupId: hits.groupId,
- id: hits.id,
- model: hits.model,
- role: hits.role,
- score: hits.score,
- topicId: hits.topicId,
- updatedAt: hits.updatedAt,
- })
- .from(hits)
- .leftJoin(agents, eq(hits.agentId, agents.id))
- .where(
- and(
- this.liftedScopeWhere(hits.workspaceId),
- agentId ? eq(hits.agentId, agentId) : undefined,
- ),
- )
- .orderBy(desc(hits.score))
- .limit(candidateLimit);
-
- return this.mapScoresToRelevance(rows)
- .map((row) => ({
- agentId: row.agentId,
- content: row.content || '',
- createdAt: row.createdAt,
- description:
- normalizeInboxAgentTitle(row.agentTitle, {
- slug: row.agentSlug,
- }) || 'General Chat',
- groupId: row.groupId,
- id: row.id,
- model: row.model,
- relevance: row.relevance,
- role: row.role,
- title: this.truncate(row.content) || '',
- topicId: row.topicId,
- type: 'message' as const,
- updatedAt: row.updatedAt,
- }))
- .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
- .slice(0, limit);
- }
-
- /**
- * Search files by name (BM25)
- * Note: ICU tokenizer treats hyphenated/dotted names (e.g. "react-component.jsx") as single tokens,
- * so partial searches like "component" won't match. Full words or prefixes work fine.
- */
- private async searchFiles(
- query: string,
- limit: number,
- excludeKbIds?: string[],
- ): Promise<FileSearchResult[]> {
- const bm25Query = sanitizeBm25Query(query);
-
- const hits = this.db
- .select({
- createdAt: files.createdAt,
- fileType: files.fileType,
- id: files.id,
- name: files.name,
- score: sql<number>`paradedb.score(${files.id})`.as('score'),
- size: files.size,
- updatedAt: files.updatedAt,
- url: files.url,
- workspaceId: files.workspaceId,
- })
- .from(files)
- .where(
- and(
- this.scanScopeWhere(files),
- ne(files.fileType, 'custom/document'),
- // Acceptance evidence is hidden from the library, so it must stay out
- // of search too — otherwise a query for "execution" returns hundreds
- // of artifacts the user can't find anywhere else in the UI.
- or(isNull(files.source), notInArray(files.source, LIBRARY_HIDDEN_FILE_SOURCES)),
- sql`${files.name} @@@ ${bm25Query}`,
- ),
- )
- .orderBy(sql`paradedb.score(${files.id}) DESC`)
- .limit(this.scanCandidateLimit(limit))
- .as('file_hits');
-
- const rows = await this.db
- .select({
- content: documents.content,
- createdAt: hits.createdAt,
- fileType: hits.fileType,
- id: hits.id,
- knowledgeBaseId: knowledgeBaseFiles.knowledgeBaseId,
- name: hits.name,
- score: hits.score,
- size: hits.size,
- updatedAt: hits.updatedAt,
- url: hits.url,
- })
- .from(hits)
- .leftJoin(documents, eq(hits.id, documents.fileId))
- .leftJoin(knowledgeBaseFiles, eq(hits.id, knowledgeBaseFiles.fileId))
- .where(
- and(
- this.liftedScopeWhere(hits.workspaceId),
- // A file linked to ANY restricted KB is fully hidden (over-hiding
- // beats leaking through a shared membership) — subquery instead of
- // the joined column so multi-KB rows cannot slip through.
- excludeKbIds && excludeKbIds.length > 0
- ? notInArray(
- hits.id,
- this.db
- .select({ fileId: knowledgeBaseFiles.fileId })
- .from(knowledgeBaseFiles)
- .where(inArray(knowledgeBaseFiles.knowledgeBaseId, excludeKbIds)),
- )
- : undefined,
- ),
- )
- .orderBy(desc(hits.score))
- .limit(limit);
-
- return this.mapScoresToRelevance(rows).map((row) => ({
- createdAt: row.createdAt,
- description: this.truncate(row.content),
- fileType: row.fileType,
- id: row.id,
- knowledgeBaseId: row.knowledgeBaseId,
- name: row.name,
- relevance: row.relevance,
- size: row.size,
- title: row.name,
- type: 'file' as const,
- updatedAt: row.updatedAt,
- url: row.url,
- }));
- }
-
- /**
- * Search folders (documents with file_type=DOCUMENT_FOLDER_TYPE) (BM25)
- */
- private async searchFolders(
- query: string,
- limit: number,
- excludeKbIds?: string[],
- ): Promise<FolderSearchResult[]> {
- const bm25Query = sanitizeBm25Query(query);
-
- const hits = this.db
- .select({
- createdAt: documents.createdAt,
- description: documents.description,
- filename: documents.filename,
- id: documents.id,
- knowledgeBaseId: documents.knowledgeBaseId,
- score: sql<number>`paradedb.score(${documents.id})`.as('score'),
- slug: documents.slug,
- title: documents.title,
- updatedAt: documents.updatedAt,
- workspaceId: documents.workspaceId,
- })
- .from(documents)
- .where(
- and(
- this.scanScopeWhere(documents),
- eq(documents.fileType, DOCUMENT_FOLDER_TYPE),
- sql`(${documents.title} @@@ ${bm25Query} OR ${documents.slug} @@@ ${bm25Query} OR ${documents.description} @@@ ${bm25Query})`,
- ),
- )
- .orderBy(sql`paradedb.score(${documents.id}) DESC`)
- .limit(this.scanCandidateLimit(limit))
- .as('folder_hits');
-
- const rows = await this.db
- .select({
- createdAt: hits.createdAt,
- description: hits.description,
- filename: hits.filename,
- id: hits.id,
- knowledgeBaseId: hits.knowledgeBaseId,
- score: hits.score,
- slug: hits.slug,
- title: hits.title,
- updatedAt: hits.updatedAt,
- })
- .from(hits)
- .where(
- and(
- this.liftedScopeWhere(hits.workspaceId),
- excludeKbIds && excludeKbIds.length > 0
- ? or(isNull(hits.knowledgeBaseId), notInArray(hits.knowledgeBaseId, excludeKbIds))
- : undefined,
- ),
- )
- .orderBy(desc(hits.score))
- .limit(limit);
-
- return this.mapScoresToRelevance(rows).map((row) => {
- const title = row.title || row.filename || 'Untitled';
- return {
- createdAt: row.createdAt,
- description: row.description,
- id: row.id,
- knowledgeBaseId: row.knowledgeBaseId,
- relevance: row.relevance,
- slug: row.slug,
- title,
- type: 'folder' as const,
- updatedAt: row.updatedAt,
- };
- });
- }
-
- /**
- * Search pages (documents with file_type='custom/document') (BM25)
- */
- private async searchPages(
- query: string,
- limit: number,
- excludeKbIds?: string[],
- ): Promise<PageSearchResult[]> {
- const bm25Query = sanitizeBm25Query(query);
-
- const hits = this.db
- .select({
- createdAt: documents.createdAt,
- fileId: documents.fileId,
- filename: documents.filename,
- id: documents.id,
- knowledgeBaseId: documents.knowledgeBaseId,
- score: sql<number>`paradedb.score(${documents.id})`.as('score'),
- title: documents.title,
- updatedAt: documents.updatedAt,
- workspaceId: documents.workspaceId,
- })
- .from(documents)
- .where(
- and(
- this.scanScopeWhere(documents),
- eq(documents.fileType, 'custom/document'),
- sql`(${documents.title} @@@ ${bm25Query} OR ${documents.slug} @@@ ${bm25Query} OR ${documents.content} @@@ ${bm25Query})`,
- ),
- )
- .orderBy(sql`paradedb.score(${documents.id}) DESC`)
- .limit(this.scanCandidateLimit(limit))
- .as('page_hits');
-
- const rows = await this.db
- .select({
- createdAt: hits.createdAt,
- filename: hits.filename,
- id: hits.id,
- score: hits.score,
- title: hits.title,
- updatedAt: hits.updatedAt,
- })
- .from(hits)
- .where(
- and(
- this.liftedScopeWhere(hits.workspaceId),
- excludeKbIds && excludeKbIds.length > 0
- ? or(isNull(hits.knowledgeBaseId), notInArray(hits.knowledgeBaseId, excludeKbIds))
- : undefined,
- // Parsed-file pages leave `knowledgeBaseId` null — their KB
- // membership lives on `fileId` → `knowledge_base_files`.
- excludeKbIds && excludeKbIds.length > 0
- ? or(
- isNull(hits.fileId),
- notInArray(
- hits.fileId,
- this.db
- .select({ fileId: knowledgeBaseFiles.fileId })
- .from(knowledgeBaseFiles)
- .where(inArray(knowledgeBaseFiles.knowledgeBaseId, excludeKbIds)),
- ),
- )
- : undefined,
- ),
- )
- .orderBy(desc(hits.score))
- .limit(limit);
-
- return this.mapScoresToRelevance(rows).map((row) => {
- const title = row.title || row.filename || 'Untitled';
- return {
- createdAt: row.createdAt,
- description: null,
- id: row.id,
- relevance: row.relevance,
- title,
- type: 'page' as const,
- updatedAt: row.updatedAt,
- };
- });
- }
-
- /**
- * KB-scoped BM25 search over documents.
- *
- * Covers two routes to the KB scope, executed as two separate ParadeDB
- * scoring queries that we merge in JS:
- * - inline pages: `documents.knowledge_base_id` directly references the KB
- * - file-backed docs (e.g. parsed PDFs): joined through `knowledge_base_files`
- * via `documents.file_id`
- *
- * Two queries instead of an `OR`-ed WHERE clause because `paradedb.score()`
- * requires a tantivy index scan, and ParadeDB rejects disjunctive shapes
- * spanning bm25 and non-bm25 predicates ("Unsupported query shape").
- *
- * Folder rows (DOCUMENT_FOLDER_TYPE) are excluded — they carry no content.
- *
- * Unlike the command-palette searches above, this one is deliberately left on
- * the plain index-scan plan: `knowledge_base_id` is not in the BM25 index
- * either, so isolating the scan would not buy TopN. The KB filter does bound
- * the match set to one knowledge base (via its btree index), which keeps it
- * workable until `workspace_id` and `visibility` become fast fields in the BM25 index.
- */
- async searchKnowledgeBaseDocuments(
- query: string,
- knowledgeBaseIds: string[],
- limit: number = 20,
- ): Promise<KnowledgeBaseDocumentHit[]> {
- if (!query || query.trim() === '') return [];
- if (!knowledgeBaseIds || knowledgeBaseIds.length === 0) return [];
-
- const bm25Query = sanitizeBm25Query(query);
-
- const matchClause = sql`(${documents.title} @@@ ${bm25Query} OR ${documents.slug} @@@ ${bm25Query} OR ${documents.content} @@@ ${bm25Query})`;
- const folderClause = ne(documents.fileType, DOCUMENT_FOLDER_TYPE);
- const userClause = buildWorkspaceWhere(this.scope, documents);
-
- const inlineRowsPromise = this.db
- .select({
- content: documents.content,
- fileId: documents.fileId,
- filename: documents.filename,
- id: documents.id,
- knowledgeBaseId: documents.knowledgeBaseId,
- score: sql<number>`paradedb.score(${documents.id})`,
- title: documents.title,
- updatedAt: documents.updatedAt,
- })
- .from(documents)
- .where(
- and(
- userClause,
- folderClause,
- inArray(documents.knowledgeBaseId, knowledgeBaseIds),
- matchClause,
- ),
- )
- .orderBy(sql`paradedb.score(${documents.id}) DESC`)
- .limit(limit);
-
- const fileBackedRowsPromise = this.db
- .select({
- content: documents.content,
- fileId: documents.fileId,
- filename: documents.filename,
- id: documents.id,
- knowledgeBaseId: knowledgeBaseFiles.knowledgeBaseId,
- score: sql<number>`paradedb.score(${documents.id})`,
- title: documents.title,
- updatedAt: documents.updatedAt,
- })
- .from(documents)
- .innerJoin(
- knowledgeBaseFiles,
- and(
- eq(knowledgeBaseFiles.fileId, documents.fileId),
- buildWorkspaceWhere(this.scope, knowledgeBaseFiles),
- inArray(knowledgeBaseFiles.knowledgeBaseId, knowledgeBaseIds),
- ),
- )
- .where(and(userClause, folderClause, matchClause))
- .orderBy(sql`paradedb.score(${documents.id}) DESC`)
- .limit(limit);
-
- const [inlineRows, fileBackedRows] = await Promise.all([
- inlineRowsPromise,
- fileBackedRowsPromise,
- ]);
-
- const byId = new Map<string, (typeof inlineRows)[number]>();
- for (const row of [...inlineRows, ...fileBackedRows]) {
- const prev = byId.get(row.id);
- if (!prev || row.score > prev.score) byId.set(row.id, row);
- }
- const merged = Array.from(byId.values())
- .sort((a, b) => b.score - a.score)
- .slice(0, limit);
-
- return this.mapScoresToRelevance(merged).map((row) => ({
- documentId: row.id,
- fileId: row.fileId ?? undefined,
- knowledgeBaseId: row.knowledgeBaseId ?? '',
- relevance: row.relevance,
- snippet: this.truncate(row.content, 300) ?? '',
- title: row.title || row.filename || 'Untitled',
- updatedAt: row.updatedAt,
- }));
- }
-
- /**
- * Search memories by title, summary, details (BM25)
- *
- * Memories are user-scoped only (no workspace column) and this query joins
- * nothing, so `user_id` is pushed into the tantivy query as-is and the scan
- * already runs as TopN — no subquery isolation needed.
- */
- private async searchMemories(query: string, limit: number): Promise<MemorySearchResult[]> {
- const bm25Query = sanitizeBm25Query(query);
-
- const rows = await this.db
- .select({
- createdAt: userMemories.createdAt,
- id: userMemories.id,
- memoryLayer: userMemories.memoryLayer,
- score: sql<number>`paradedb.score(${userMemories.id})`,
- summary: userMemories.summary,
- title: userMemories.title,
- updatedAt: userMemories.updatedAt,
- })
- .from(userMemories)
- .where(
- and(
- eq(userMemories.userId, this.userId),
- sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemories.summary} @@@ ${bm25Query} OR ${userMemories.details} @@@ ${bm25Query})`,
- ),
- )
- .orderBy(sql`paradedb.score(${userMemories.id}) DESC`)
- .limit(limit);
-
- return this.mapScoresToRelevance(rows).map((row) => ({
- createdAt: row.createdAt,
- description: this.truncate(row.summary),
- id: row.id,
- memoryLayer: row.memoryLayer,
- relevance: row.relevance,
- title: row.title || 'Untitled Memory',
- type: 'memory' as const,
- updatedAt: row.updatedAt,
- }));
- }
-
- /**
- * Search chat groups by title and description (BM25)
- */
- private async searchChatGroups(query: string, limit: number): Promise<ChatGroupSearchResult[]> {
- const bm25Query = sanitizeBm25Query(query);
-
- const hits = this.db
- .select({
- avatar: chatGroups.avatar,
- backgroundColor: chatGroups.backgroundColor,
- createdAt: chatGroups.createdAt,
- description: chatGroups.description,
- id: chatGroups.id,
- score: sql<number>`paradedb.score(${chatGroups.id})`.as('score'),
- title: chatGroups.title,
- updatedAt: chatGroups.updatedAt,
- workspaceId: chatGroups.workspaceId,
- })
- .from(chatGroups)
- .where(
- and(
- this.scanScopeWhere(chatGroups),
- sql`(${chatGroups.title} @@@ ${bm25Query} OR ${chatGroups.description} @@@ ${bm25Query})`,
- ),
- )
- .orderBy(sql`paradedb.score(${chatGroups.id}) DESC`)
- .limit(this.scanCandidateLimit(limit))
- .as('chat_group_hits');
-
- const rows = await this.db
- .select({
- avatar: hits.avatar,
- backgroundColor: hits.backgroundColor,
- createdAt: hits.createdAt,
- description: hits.description,
- id: hits.id,
- score: hits.score,
- title: hits.title,
- updatedAt: hits.updatedAt,
- })
- .from(hits)
- .where(this.liftedScopeWhere(hits.workspaceId))
- .orderBy(desc(hits.score))
- .limit(limit);
-
- return this.mapScoresToRelevance(rows).map((row) => ({
- avatar: row.avatar,
- backgroundColor: row.backgroundColor,
- createdAt: row.createdAt,
- description: row.description,
- id: row.id,
- relevance: row.relevance,
- title: row.title || '',
- type: 'chatGroup' as const,
- updatedAt: row.updatedAt,
- }));
- }
-
- /**
- * Search knowledge bases by name and description (BM25)
- */
- private async searchKnowledgeBases(
- query: string,
- limit: number,
- excludeIds?: string[],
- ): Promise<KnowledgeBaseSearchResult[]> {
- const bm25Query = sanitizeBm25Query(query);
-
- const hits = this.db
- .select({
- avatar: knowledgeBases.avatar,
- createdAt: knowledgeBases.createdAt,
- description: knowledgeBases.description,
- id: knowledgeBases.id,
- name: knowledgeBases.name,
- score: sql<number>`paradedb.score(${knowledgeBases.id})`.as('score'),
- updatedAt: knowledgeBases.updatedAt,
- workspaceId: knowledgeBases.workspaceId,
- })
- .from(knowledgeBases)
- .where(
- and(
- this.scanScopeWhere(knowledgeBases),
- sql`(${knowledgeBases.name} @@@ ${bm25Query} OR ${knowledgeBases.description} @@@ ${bm25Query})`,
- ),
- )
- .orderBy(sql`paradedb.score(${knowledgeBases.id}) DESC`)
- .limit(this.scanCandidateLimit(limit))
- .as('knowledge_base_hits');
-
- const rows = await this.db
- .select({
- avatar: hits.avatar,
- createdAt: hits.createdAt,
- description: hits.description,
- id: hits.id,
- name: hits.name,
- score: hits.score,
- updatedAt: hits.updatedAt,
- })
- .from(hits)
- .where(
- and(
- this.liftedScopeWhere(hits.workspaceId),
- // Lifted above the BM25 scan (like the scope predicate) so the scan
- // keeps its TopN shape; restricted rows only consume candidate slots.
- excludeIds && excludeIds.length > 0 ? notInArray(hits.id, excludeIds) : undefined,
- ),
- )
- .orderBy(desc(hits.score))
- .limit(limit);
-
- return this.mapScoresToRelevance(rows).map((row) => ({
- avatar: row.avatar,
- createdAt: row.createdAt,
- description: row.description,
- id: row.id,
- relevance: row.relevance,
- title: row.name,
- type: 'knowledgeBase' as const,
- updatedAt: row.updatedAt,
- }));
- }
-}
diff --git a/packages/database/src/schemas/ftsSearchSyncOutbox.ts b/packages/database/src/schemas/ftsSearchSyncOutbox.ts
new file mode 100644
index 00000000000..3bc65e29d7f
--- /dev/null
+++ b/packages/database/src/schemas/ftsSearchSyncOutbox.ts
@@ -0,0 +1,68 @@
+import type { FtsSearchDocumentEntity } from '@lobechat/types';
+import { sql } from 'drizzle-orm';
+import {
+ bigint,
+ index,
+ integer,
+ pgSequence,
+ pgTable,
+ smallint,
+ text,
+ uniqueIndex,
+ uuid,
+} from 'drizzle-orm/pg-core';
+
+import { createdAt, timestamptz, updatedAt } from './_helpers';
+
+/** Monotonic version source shared by capture triggers, reindex fences, and Outbox work. */
+export const ftsSearchSyncRevisionSequence = pgSequence('fts_search_sync_revision_seq');
+
+/** Durable, coalescing queue for asynchronously refreshing search projections. */
+export const ftsSearchSyncOutbox = pgTable(
+ 'fts_search_sync_outbox',
+ {
+ /** Failed claims for the current revision; a newer captured change resets this to zero. */
+ attempts: integer('attempts').notNull().default(0),
+ /** Earliest time a worker may claim this row, including retry backoff delays. */
+ availableAt: timestamptz('available_at').notNull().defaultNow(),
+ /** Time this logical Outbox row was first created; coalesced changes preserve it. */
+ createdAt: createdAt(),
+ /** Terminal failure time; dead rows remain for inspection until a newer change revives them. */
+ deadAt: timestamptz('dead_at'),
+ /** Stable source document identifier within the selected search entity. */
+ documentId: text('document_id').notNull(),
+ /** FTS projection whose document must be refreshed or deleted. */
+ entity: text('entity').$type<FtsSearchDocumentEntity>().notNull(),
+ /** Internal surrogate identifier; work identity is the entity and document ID pair. */
+ id: uuid('id').primaryKey().defaultRandom(),
+ /** Latest truncated processing error or expired-lease reason, cleared by a newer change. */
+ lastError: text('last_error'),
+ /** Exclusive lease expiry whose exact timestamp also fences settlement by stale workers. */
+ lockedUntil: timestamptz('locked_until'),
+ /** Claim order where lower values run first; destructive or scope changes use priority zero. */
+ priority: smallint('priority').notNull().default(10),
+ /** Monotonic document version; sequence gaps are valid because allocation is non-transactional. */
+ revision: bigint('revision', { mode: 'number' })
+ .notNull()
+ .default(sql`nextval('fts_search_sync_revision_seq')`),
+ /** Last enqueue, claim, release, retry, or terminal-failure state transition. */
+ updatedAt: updatedAt(),
+ },
+ (table) => [
+ uniqueIndex('fts_search_sync_outbox_entity_document_id_unique').on(
+ table.entity,
+ table.documentId,
+ ),
+ index('fts_search_sync_outbox_claim_idx')
+ .on(table.priority, table.availableAt, table.revision)
+ .where(sql`${table.deadAt} IS NULL`),
+ index('fts_search_sync_outbox_dead_idx')
+ .on(table.deadAt)
+ .where(sql`${table.deadAt} IS NOT NULL`),
+ index('fts_search_sync_outbox_lease_idx')
+ .on(table.lockedUntil)
+ .where(sql`${table.deadAt} IS NULL AND ${table.lockedUntil} IS NOT NULL`),
+ ],
+);
+
+export type FtsSearchSyncOutboxItem = typeof ftsSearchSyncOutbox.$inferSelect;
diff --git a/packages/database/src/schemas/index.ts b/packages/database/src/schemas/index.ts
index 8f5e8441ac9..56d943a330b 100644
--- a/packages/database/src/schemas/index.ts
+++ b/packages/database/src/schemas/index.ts
@@ -22,6 +22,7 @@ export * from './documentHistory';
export * from './documentShare';
export * from './expertise';
export * from './file';
+export * from './ftsSearchSyncOutbox';
export * from './generation';
export * from './goal';
export * from './goalGraph';
diff --git a/packages/database/src/schemas/userMemories/index.ts b/packages/database/src/schemas/userMemories/index.ts
index 25d7e0d546b..11cb128fd9c 100644
--- a/packages/database/src/schemas/userMemories/index.ts
+++ b/packages/database/src/schemas/userMemories/index.ts
@@ -90,6 +90,7 @@ export const userMemoriesContexts = pgTable(
),
index('user_memories_contexts_type_index').on(table.type),
index('user_memories_contexts_user_id_index').on(table.userId),
+ index('user_memories_contexts_user_memory_ids_gin_idx').using('gin', table.userMemoryIds),
],
);
diff --git a/packages/database/src/utils/inJsonStringArray.ts b/packages/database/src/utils/inJsonStringArray.ts
new file mode 100644
index 00000000000..ba3f1c35919
--- /dev/null
+++ b/packages/database/src/utils/inJsonStringArray.ts
@@ -0,0 +1,16 @@
+import type { SQL, SQLWrapper } from 'drizzle-orm';
+import { sql } from 'drizzle-orm';
+
+/**
+ * Match a text column against an arbitrary-size ID set using one JSONB bind parameter.
+ * Candidate-only search can be unbounded, so expanding every ID through `inArray`
+ * would exceed PostgreSQL's bind-parameter limit for large histories.
+ */
+export const inJsonStringArray = (column: SQLWrapper, values: string[]): SQL<boolean> => {
+ if (values.length === 0) return sql<boolean>`false`;
+
+ return sql<boolean>`${column} IN (
+ SELECT value
+ FROM jsonb_array_elements_text(${JSON.stringify(values)}::jsonb) AS candidate_ids(value)
+ )`;
+};
diff --git a/packages/env/src/__tests__/ftsSearch.test.ts b/packages/env/src/__tests__/ftsSearch.test.ts
new file mode 100644
index 00000000000..49e8e952a2d
--- /dev/null
+++ b/packages/env/src/__tests__/ftsSearch.test.ts
@@ -0,0 +1,48 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { getFtsSearchConfig } from '../ftsSearch';
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe('getFtsSearchConfig', () => {
+ it('exposes optional Elasticsearch connection and index configuration', () => {
+ vi.stubEnv('ES_API_KEY', 'test-api-key');
+ vi.stubEnv('FTS_SEARCH_SYNC_ENABLED', 'true');
+ vi.stubEnv('ES_INDEX_NAMESPACE', 'lobehub-dev');
+ vi.stubEnv('ES_URL', 'https://search.example.com');
+ vi.stubEnv('FTS_SEARCH_PROVIDER', 'elasticsearch');
+
+ expect(getFtsSearchConfig()).toMatchObject({
+ ES_API_KEY: 'test-api-key',
+ FTS_SEARCH_SYNC_ENABLED: 'true',
+ ES_INDEX_NAMESPACE: 'lobehub-dev',
+ ES_URL: 'https://search.example.com',
+ FTS_SEARCH_PROVIDER: 'elasticsearch',
+ });
+ });
+
+ it('keeps Elasticsearch configuration optional', () => {
+ vi.stubEnv('ES_API_KEY', undefined);
+ vi.stubEnv('FTS_SEARCH_SYNC_ENABLED', undefined);
+ vi.stubEnv('ES_INDEX_NAMESPACE', undefined);
+ vi.stubEnv('ES_URL', undefined);
+ vi.stubEnv('FTS_SEARCH_PROVIDER', undefined);
+
+ expect(getFtsSearchConfig()).toMatchObject({
+ ES_API_KEY: undefined,
+ FTS_SEARCH_SYNC_ENABLED: undefined,
+ ES_INDEX_NAMESPACE: undefined,
+ ES_URL: undefined,
+ FTS_SEARCH_PROVIDER: 'pg_search',
+ });
+ });
+
+ it('rejects unsupported search backends', () => {
+ vi.stubEnv('FTS_SEARCH_PROVIDER', 'opensearch');
+
+ expect(() => getFtsSearchConfig()).toThrow();
+ });
+});
diff --git a/packages/env/src/ftsSearch.ts b/packages/env/src/ftsSearch.ts
new file mode 100644
index 00000000000..d3da59be2ed
--- /dev/null
+++ b/packages/env/src/ftsSearch.ts
@@ -0,0 +1,23 @@
+import { createEnv } from '@t3-oss/env-core';
+import { z } from 'zod';
+
+export const getFtsSearchConfig = () => {
+ return createEnv({
+ runtimeEnv: {
+ ES_API_KEY: process.env.ES_API_KEY,
+ FTS_SEARCH_SYNC_ENABLED: process.env.FTS_SEARCH_SYNC_ENABLED,
+ ES_INDEX_NAMESPACE: process.env.ES_INDEX_NAMESPACE,
+ ES_URL: process.env.ES_URL,
+ FTS_SEARCH_PROVIDER: process.env.FTS_SEARCH_PROVIDER,
+ },
+ server: {
+ ES_API_KEY: z.string().min(1).optional(),
+ FTS_SEARCH_SYNC_ENABLED: z.enum(['true', 'false']).optional(),
+ ES_INDEX_NAMESPACE: z.string().min(1).optional(),
+ ES_URL: z.string().url().optional(),
+ FTS_SEARCH_PROVIDER: z.enum(['elasticsearch', 'pg_search']).default('pg_search'),
+ },
+ });
+};
+
+export const ftsSearchEnv = getFtsSearchConfig();
diff --git a/packages/observability-otel/package.json b/packages/observability-otel/package.json
index 8f39d81025e..ff7df24598b 100644
--- a/packages/observability-otel/package.json
+++ b/packages/observability-otel/package.json
@@ -11,6 +11,7 @@
"./modules/agent-signal": "./src/modules/agent-signal/index.ts",
"./modules/memory-user-memory": "./src/modules/memory-user-memory/index.ts",
"./modules/onboarding-understanding": "./src/modules/onboarding-understanding/index.ts",
+ "./modules/fts-search-reindex": "./src/modules/fts-search-reindex/index.ts",
"./modules/upstash-workflow": "./src/modules/upstash-workflow/index.ts"
},
"dependencies": {
diff --git a/packages/observability-otel/src/modules/fts-search-reindex/index.test.ts b/packages/observability-otel/src/modules/fts-search-reindex/index.test.ts
new file mode 100644
index 00000000000..2c73a68673b
--- /dev/null
+++ b/packages/observability-otel/src/modules/fts-search-reindex/index.test.ts
@@ -0,0 +1,178 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ observeFtsSearchReindexRun,
+ recordFtsSearchReindexBatch,
+ recordFtsSearchReindexBulkRequest,
+ recordFtsSearchReindexBulkRetry,
+ recordFtsSearchReindexReconciliation,
+} from '.';
+
+const mocks = vi.hoisted(() => {
+ const counters = new Map<string, { add: ReturnType<typeof vi.fn> }>();
+ const gauges = new Map<string, { record: ReturnType<typeof vi.fn> }>();
+ const histograms = new Map<string, { record: ReturnType<typeof vi.fn> }>();
+ const getMeter = vi.fn(() => ({
+ createCounter: (name: string) => {
+ const counter = { add: vi.fn() };
+ counters.set(name, counter);
+ return counter;
+ },
+ createGauge: (name: string) => {
+ const gauge = { record: vi.fn() };
+ gauges.set(name, gauge);
+ return gauge;
+ },
+ createHistogram: (name: string) => {
+ const histogram = { record: vi.fn() };
+ histograms.set(name, histogram);
+ return histogram;
+ },
+ }));
+ const startActiveSpan = vi.fn();
+ return { counters, gauges, getMeter, histograms, startActiveSpan };
+});
+
+vi.mock('@opentelemetry/api', () => ({
+ diag: { error: vi.fn() },
+ metrics: {
+ getMeter: mocks.getMeter,
+ },
+ SpanStatusCode: { ERROR: 2, OK: 1 },
+ trace: {
+ getTracer: () => ({
+ startActiveSpan: mocks.startActiveSpan,
+ }),
+ },
+}));
+
+describe('full-text search reindex metrics', () => {
+ beforeEach(() => {
+ for (const counter of mocks.counters.values()) counter.add.mockClear();
+ for (const gauge of mocks.gauges.values()) gauge.record.mockClear();
+ for (const histogram of mocks.histograms.values()) histogram.record.mockClear();
+ mocks.startActiveSpan.mockReset();
+ });
+
+ it('records batch and durable checkpoint counts with bounded labels', () => {
+ recordFtsSearchReindexBatch({
+ checkpoint: { failed: 1, indexed: 8, scanned: 10 },
+ entity: 'messages',
+ failed: 1,
+ indexed: 8,
+ scanned: 10,
+ });
+
+ const documents = mocks.counters.get('fts_search_reindex_documents_total');
+ expect(documents?.add).toHaveBeenCalledWith(10, { entity: 'messages', result: 'scanned' });
+ expect(documents?.add).toHaveBeenCalledWith(8, { entity: 'messages', result: 'indexed' });
+ expect(documents?.add).toHaveBeenCalledWith(1, { entity: 'messages', result: 'failed' });
+ expect(
+ mocks.gauges.get('fts_search_reindex_checkpoint_documents')?.record,
+ ).toHaveBeenCalledWith(10, { entity: 'messages', result: 'scanned' });
+ });
+
+ it('records signed reconciliation drift without run or document identifiers', () => {
+ recordFtsSearchReindexReconciliation({
+ checkpointCount: 10,
+ elasticsearchCount: 12,
+ entity: 'messages',
+ });
+
+ expect(
+ mocks.gauges.get('fts_search_reindex_reconciliation_drift')?.record,
+ ).toHaveBeenCalledWith(2, { entity: 'messages' });
+ expect(
+ mocks.counters.get('fts_search_reindex_reconciliations_total')?.add,
+ ).toHaveBeenCalledWith(1, {
+ entity: 'messages',
+ result: 'drift',
+ });
+ });
+
+ it('records bulk retries without status or error labels', () => {
+ recordFtsSearchReindexBulkRetry('messages');
+
+ expect(mocks.counters.get('fts_search_reindex_bulk_retries_total')?.add).toHaveBeenCalledWith(
+ 1,
+ {
+ entity: 'messages',
+ },
+ );
+ });
+
+ it('records each completed bulk request for batch-size and concurrency tuning', () => {
+ recordFtsSearchReindexBulkRequest({
+ attempts: 2,
+ bytes: 4096,
+ durationMs: 750,
+ entity: 'messages',
+ operations: 100,
+ result: 'success',
+ });
+
+ const attributes = { entity: 'messages', result: 'success' };
+ expect(mocks.counters.get('fts_search_reindex_bulk_requests_total')?.add).toHaveBeenCalledWith(
+ 2,
+ attributes,
+ );
+ expect(mocks.counters.get('fts_search_reindex_bulk_bytes_total')?.add).toHaveBeenCalledWith(
+ 8192,
+ attributes,
+ );
+ expect(
+ mocks.histograms.get('fts_search_reindex_bulk_request_attempts')?.record,
+ ).toHaveBeenCalledWith(2, attributes);
+ expect(
+ mocks.histograms.get('fts_search_reindex_bulk_request_size')?.record,
+ ).toHaveBeenCalledWith(4096, attributes);
+ expect(
+ mocks.histograms.get('fts_search_reindex_bulk_request_duration')?.record,
+ ).toHaveBeenCalledWith(750, attributes);
+ expect(
+ mocks.histograms.get('fts_search_reindex_bulk_request_items')?.record,
+ ).toHaveBeenCalledWith(100, attributes);
+ });
+
+ it('does not expose metric recorder failures to the reindex operation', () => {
+ recordFtsSearchReindexBulkRetry('messages');
+ const add = mocks.counters.get('fts_search_reindex_bulk_retries_total')!.add;
+ add.mockClear();
+ add.mockImplementationOnce(() => {
+ throw new Error('telemetry unavailable');
+ });
+
+ expect(() => recordFtsSearchReindexBulkRetry('messages')).not.toThrow();
+ });
+
+ it('adds bounded failure type and stage attributes to failed run spans', async () => {
+ const span = {
+ end: vi.fn(),
+ setAttribute: vi.fn(),
+ setAttributes: vi.fn(),
+ setStatus: vi.fn(),
+ };
+ mocks.startActiveSpan.mockImplementation(async (_name, operation) => operation(span));
+ const requestError = new Error('request body contains document and query details');
+ requestError.name = 'FtsSearchReindexRequestError';
+ const entityError = new Error('entity contains a document identifier', { cause: requestError });
+ entityError.name = 'FtsSearchReindexEntityError';
+
+ await expect(
+ observeFtsSearchReindexRun(async () => {
+ throw entityError;
+ }),
+ ).rejects.toBe(entityError);
+
+ expect(mocks.startActiveSpan).toHaveBeenCalledWith(
+ 'fts.search.reindex.run',
+ expect.any(Function),
+ );
+ expect(span.setAttribute).toHaveBeenCalledWith('fts.search.reindex.result', 'error');
+ expect(span.setAttributes).toHaveBeenCalledWith({
+ 'fts.search.reindex.error.type': 'request_error',
+ 'fts.search.reindex.failure.stage': 'entity',
+ });
+ expect(span.setStatus).toHaveBeenCalledWith({ code: 2 });
+ });
+});
diff --git a/packages/observability-otel/src/modules/fts-search-reindex/index.ts b/packages/observability-otel/src/modules/fts-search-reindex/index.ts
new file mode 100644
index 00000000000..f465b32fa54
--- /dev/null
+++ b/packages/observability-otel/src/modules/fts-search-reindex/index.ts
@@ -0,0 +1,230 @@
+import { errorCauseFrom, errorNameFrom } from '@lobechat/utils';
+import type { Attributes, Span } from '@opentelemetry/api';
+import { diag, metrics, SpanStatusCode, trace } from '@opentelemetry/api';
+
+const tracer = trace.getTracer('fts-search-reindex');
+
+const createInstruments = () => {
+ const meter = metrics.getMeter('fts-search-reindex');
+ return {
+ bulkRequestAttempts: meter.createHistogram('fts_search_reindex_bulk_request_attempts', {
+ description: 'Attempts required by each completed Elasticsearch bulk request.',
+ }),
+ bulkRequestBytes: meter.createHistogram('fts_search_reindex_bulk_request_size', {
+ description: 'Encoded bytes in each completed Elasticsearch bulk request.',
+ unit: 'By',
+ }),
+ bulkRequestDuration: meter.createHistogram('fts_search_reindex_bulk_request_duration', {
+ description: 'Duration of each completed Elasticsearch bulk request including retries.',
+ unit: 'ms',
+ }),
+ bulkRequestItems: meter.createHistogram('fts_search_reindex_bulk_request_items', {
+ description: 'Documents in each completed Elasticsearch bulk request.',
+ }),
+ bulkBytes: meter.createCounter('fts_search_reindex_bulk_bytes_total', {
+ description:
+ 'Encoded bytes included in Elasticsearch bulk request attempts by full-text search reindex.',
+ unit: 'By',
+ }),
+ bulkRequests: meter.createCounter('fts_search_reindex_bulk_requests_total', {
+ description: 'Elasticsearch bulk request attempts issued by full-text search reindex.',
+ unit: '{request}',
+ }),
+ bulkRetries: meter.createCounter('fts_search_reindex_bulk_retries_total', {
+ description: 'Elasticsearch bulk request retries issued by full-text search reindex.',
+ unit: '{retry}',
+ }),
+ checkpointDocuments: meter.createGauge('fts_search_reindex_checkpoint_documents', {
+ description:
+ 'Durable full-text search reindex checkpoint counts grouped by entity and result.',
+ unit: '{document}',
+ }),
+ documentCounter: meter.createCounter('fts_search_reindex_documents_total', {
+ description: 'Full-text search reindex documents grouped by entity and result.',
+ unit: '{document}',
+ }),
+ reconciliationCounter: meter.createCounter('fts_search_reindex_reconciliations_total', {
+ description: 'Full-text search reindex count reconciliations grouped by entity and result.',
+ unit: '{reconciliation}',
+ }),
+ reconciliationDrift: meter.createGauge('fts_search_reindex_reconciliation_drift', {
+ description: 'Elasticsearch document count minus the durable reindex checkpoint count.',
+ unit: '{document}',
+ }),
+ runCounter: meter.createCounter('fts_search_reindex_runs_total', {
+ description: 'Full-text search reindex executions grouped by result.',
+ unit: '{run}',
+ }),
+ };
+};
+
+let instruments: ReturnType<typeof createInstruments> | undefined;
+
+/** The CLI imports this module before registering OTEL, so bind instruments only on first use. */
+const getInstruments = () => (instruments ??= createInstruments());
+
+export interface FtsSearchReindexCheckpointMetrics {
+ failed: number;
+ indexed: number;
+ scanned: number;
+}
+
+export interface FtsSearchReindexBatchMetrics {
+ checkpoint: FtsSearchReindexCheckpointMetrics;
+ entity: string;
+ failed: number;
+ indexed: number;
+ scanned: number;
+}
+
+export interface FtsSearchReindexReconciliationMetrics {
+ checkpointCount: number;
+ elasticsearchCount: number;
+ entity: string;
+}
+
+export interface FtsSearchReindexBulkRequestMetrics {
+ attempts: number;
+ bytes: number;
+ durationMs: number;
+ entity: string;
+ operations: number;
+ result: 'request_error' | 'response_error' | 'success';
+}
+
+type FtsSearchReindexRunFailureStage = 'entity' | 'request' | 'unknown';
+type FtsSearchReindexRunFailureType = 'entity_error' | 'request_error' | 'unknown_error';
+
+interface FtsSearchReindexRunFailure {
+ stage: FtsSearchReindexRunFailureStage;
+ type: FtsSearchReindexRunFailureType;
+}
+
+const documentAttributes = (entity: string, result: 'failed' | 'indexed' | 'scanned') => ({
+ entity,
+ result,
+});
+
+const recordSafely = (operation: string, record: () => void): void => {
+ try {
+ record();
+ } catch (error) {
+ /** A telemetry outage must never interrupt durable reindex progress. */
+ diag.error(`[fts-search-reindex] failed to record ${operation}`, error);
+ }
+};
+
+export const recordFtsSearchReindexBatch = (batch: FtsSearchReindexBatchMetrics): void => {
+ recordSafely('batch metrics', () => {
+ const { checkpointDocuments, documentCounter } = getInstruments();
+ documentCounter.add(batch.scanned, documentAttributes(batch.entity, 'scanned'));
+ documentCounter.add(batch.indexed, documentAttributes(batch.entity, 'indexed'));
+ documentCounter.add(batch.failed, documentAttributes(batch.entity, 'failed'));
+ checkpointDocuments.record(
+ batch.checkpoint.scanned,
+ documentAttributes(batch.entity, 'scanned'),
+ );
+ checkpointDocuments.record(
+ batch.checkpoint.indexed,
+ documentAttributes(batch.entity, 'indexed'),
+ );
+ checkpointDocuments.record(batch.checkpoint.failed, documentAttributes(batch.entity, 'failed'));
+ });
+};
+
+export const recordFtsSearchReindexReconciliation = (
+ reconciliation: FtsSearchReindexReconciliationMetrics,
+): void => {
+ recordSafely('reconciliation metrics', () => {
+ const { reconciliationCounter, reconciliationDrift } = getInstruments();
+ const drift = reconciliation.elasticsearchCount - reconciliation.checkpointCount;
+ reconciliationDrift.record(drift, { entity: reconciliation.entity });
+ reconciliationCounter.add(1, {
+ entity: reconciliation.entity,
+ result: drift === 0 ? 'match' : 'drift',
+ });
+ });
+};
+
+export const recordFtsSearchReindexBulkRetry = (entity: string): void => {
+ recordSafely('bulk retry metrics', () => getInstruments().bulkRetries.add(1, { entity }));
+};
+
+export const recordFtsSearchReindexBulkRequest = (
+ request: FtsSearchReindexBulkRequestMetrics,
+): void => {
+ recordSafely('bulk request metrics', () => {
+ const {
+ bulkBytes,
+ bulkRequestAttempts,
+ bulkRequestBytes,
+ bulkRequestDuration,
+ bulkRequestItems,
+ bulkRequests,
+ } = getInstruments();
+ const attributes = { entity: request.entity, result: request.result };
+ bulkRequests.add(request.attempts, attributes);
+ bulkBytes.add(request.bytes * request.attempts, attributes);
+ bulkRequestAttempts.record(request.attempts, attributes);
+ bulkRequestBytes.record(request.bytes, attributes);
+ bulkRequestDuration.record(request.durationMs, attributes);
+ bulkRequestItems.record(request.operations, attributes);
+ });
+};
+
+/** Maps known reindex errors to fixed labels so traces never expose error messages or identifiers. */
+const classifyFtsSearchReindexRunFailure = (error: unknown): FtsSearchReindexRunFailure => {
+ const errorName = errorNameFrom(error);
+ if (errorName === 'FtsSearchReindexRequestError') {
+ return { stage: 'request', type: 'request_error' };
+ }
+ if (errorName === 'FtsSearchReindexEntityError') {
+ return {
+ stage: 'entity',
+ type:
+ errorNameFrom(errorCauseFrom(error)) === 'FtsSearchReindexRequestError'
+ ? 'request_error'
+ : 'entity_error',
+ };
+ }
+ return { stage: 'unknown', type: 'unknown_error' };
+};
+
+const finishRun = (
+ span: Span,
+ result: 'error' | 'success',
+ failure?: FtsSearchReindexRunFailure,
+) => {
+ const attributes: Attributes = { result };
+ recordSafely('run result', () => {
+ getInstruments().runCounter.add(1, attributes);
+ span.setAttribute('fts.search.reindex.result', result);
+ if (failure) {
+ span.setAttributes({
+ 'fts.search.reindex.error.type': failure.type,
+ 'fts.search.reindex.failure.stage': failure.stage,
+ });
+ }
+ span.setStatus({ code: result === 'success' ? SpanStatusCode.OK : SpanStatusCode.ERROR });
+ });
+ try {
+ span.end();
+ } catch (error) {
+ diag.error('[fts-search-reindex] failed to end telemetry run', error);
+ }
+};
+
+/** Creates one root span for the reindex CLI execution. */
+export const observeFtsSearchReindexRun = async <Result>(
+ operation: () => Promise<Result>,
+): Promise<Result> =>
+ tracer.startActiveSpan('fts.search.reindex.run', async (span) => {
+ try {
+ const result = await operation();
+ finishRun(span, 'success');
+ return result;
+ } catch (error) {
+ finishRun(span, 'error', classifyFtsSearchReindexRunFailure(error));
+ throw error;
+ }
+ });
diff --git a/packages/observability-otel/src/modules/fts-search-reindex/initialization.test.ts b/packages/observability-otel/src/modules/fts-search-reindex/initialization.test.ts
new file mode 100644
index 00000000000..5bd9786be0d
--- /dev/null
+++ b/packages/observability-otel/src/modules/fts-search-reindex/initialization.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ getMeter: vi.fn() }));
+
+vi.mock('@opentelemetry/api', () => ({
+ diag: { error: vi.fn() },
+ metrics: { getMeter: mocks.getMeter },
+ SpanStatusCode: { ERROR: 2, OK: 1 },
+ trace: { getTracer: vi.fn(() => ({ startActiveSpan: vi.fn() })) },
+}));
+
+describe('full-text search reindex metric initialization', () => {
+ /** The dynamic import competes with package-wide transforms during the unified repository check. */
+ it('does not bind instruments while the CLI imports the module before registration', async () => {
+ expect(mocks.getMeter).not.toHaveBeenCalled();
+
+ await import('.');
+
+ expect(mocks.getMeter).not.toHaveBeenCalled();
+ }, 15_000);
+});
diff --git a/packages/observability-otel/src/modules/fts-search-reindex/registration.test.ts b/packages/observability-otel/src/modules/fts-search-reindex/registration.test.ts
new file mode 100644
index 00000000000..1813267e97c
--- /dev/null
+++ b/packages/observability-otel/src/modules/fts-search-reindex/registration.test.ts
@@ -0,0 +1,40 @@
+import { metrics } from '@opentelemetry/api';
+import {
+ AggregationTemporality,
+ InMemoryMetricExporter,
+ MeterProvider,
+ PeriodicExportingMetricReader,
+} from '@opentelemetry/sdk-metrics';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { recordFtsSearchReindexBulkRetry } from '.';
+
+/** Keep this file single-test because instrument memoization intentionally models one CLI process. */
+describe('full-text search reindex metric registration order', () => {
+ let provider: MeterProvider | undefined;
+
+ afterEach(async () => {
+ await provider?.shutdown();
+ metrics.disable();
+ });
+
+ it('binds instruments to a provider registered after the module import', async () => {
+ const exporter = new InMemoryMetricExporter(AggregationTemporality.CUMULATIVE);
+ const reader = new PeriodicExportingMetricReader({
+ exportIntervalMillis: 60_000,
+ exporter,
+ });
+ provider = new MeterProvider({ readers: [reader] });
+ metrics.setGlobalMeterProvider(provider);
+
+ recordFtsSearchReindexBulkRetry('messages');
+ await provider.forceFlush();
+
+ const metricNames = exporter
+ .getMetrics()
+ .flatMap(({ scopeMetrics }) => scopeMetrics)
+ .flatMap(({ metrics }) => metrics)
+ .map(({ descriptor }) => descriptor.name);
+ expect(metricNames).toContain('fts_search_reindex_bulk_retries_total');
+ });
+});
diff --git a/packages/observability-otel/src/node.test.ts b/packages/observability-otel/src/node.test.ts
new file mode 100644
index 00000000000..c878b618be2
--- /dev/null
+++ b/packages/observability-otel/src/node.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { attributesCommon, register, shutdownSafely } from './node';
+
+const mocks = vi.hoisted(() => ({
+ nodeSdkOptions: undefined as Record<string, unknown> | undefined,
+ start: vi.fn(),
+}));
+
+vi.mock('@opentelemetry/sdk-node', () => ({
+ NodeSDK: vi.fn(function NodeSDK(options: Record<string, unknown>) {
+ mocks.nodeSdkOptions = options;
+ return { start: mocks.start };
+ }),
+}));
+
+describe('Node observability resource attributes', () => {
+ it('uses one stable UUID for the service instance during the process lifetime', () => {
+ const first = attributesCommon()['service.instance.id'];
+ const second = attributesCommon()['service.instance.id'];
+
+ expect(first).toBe(second);
+ expect(first).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
+ });
+
+ it('can disable process resource detection for privacy-sensitive CLI execution', () => {
+ register({ autoDetectResources: false, autoInstrumentations: false });
+
+ expect(mocks.nodeSdkOptions).toMatchObject({
+ autoDetectResources: false,
+ instrumentations: [],
+ });
+ });
+
+ it('translates explicit histogram boundaries into SDK views', () => {
+ register({
+ autoInstrumentations: false,
+ histogramViews: [
+ {
+ boundaries: [1000, 3000, 5000],
+ instrumentName: 'fts_search_backend_operation_duration',
+ meterName: 'fts-search-backend',
+ },
+ ],
+ });
+
+ expect(mocks.nodeSdkOptions).toMatchObject({
+ views: [
+ {
+ aggregation: { options: { boundaries: [1000, 3000, 5000] } },
+ instrumentName: 'fts_search_backend_operation_duration',
+ meterName: 'fts-search-backend',
+ },
+ ],
+ });
+ });
+
+ it('does not expose telemetry shutdown failures to the caller', async () => {
+ const shutdown = vi.fn().mockRejectedValue(new Error('collector unavailable'));
+
+ await expect(shutdownSafely({ shutdown })).resolves.toBeUndefined();
+ expect(shutdown).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/observability-otel/src/node.ts b/packages/observability-otel/src/node.ts
index 9c46bd7f37d..39a85efe3eb 100644
--- a/packages/observability-otel/src/node.ts
+++ b/packages/observability-otel/src/node.ts
@@ -1,3 +1,4 @@
+import { randomUUID } from 'node:crypto';
import { env } from 'node:process';
import { diag, DiagConsoleLogger, DiagLogLevel } from '@opentelemetry/api';
@@ -8,10 +9,17 @@ import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
import { PgInstrumentation } from '@opentelemetry/instrumentation-pg';
import type { DetectedResourceAttributes } from '@opentelemetry/resources';
import { resourceFromAttributes } from '@opentelemetry/resources';
-import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';
+import { AggregationType, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';
import { NodeSDK } from '@opentelemetry/sdk-node';
import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions';
+/**
+ * One opaque ID per Node.js process matches the Vercel instance lifetime, including Fluid
+ * Compute reuse across concurrent invocations.
+ * @see https://opentelemetry.io/docs/specs/semconv/resource/service/
+ */
+const SERVICE_INSTANCE_ID = randomUUID();
+
export function attributesForVercel(): DetectedResourceAttributes {
return {
// Vercel.
@@ -51,6 +59,7 @@ export function attributesForEnv(): DetectedResourceAttributes {
export function attributesCommon(): DetectedResourceAttributes {
return {
[ATTR_SERVICE_NAME]: 'lobehub',
+ 'service.instance.id': SERVICE_INSTANCE_ID,
...attributesForEnv(),
};
}
@@ -92,12 +101,23 @@ function debugLogLevelFromString(level?: string | null): DiagLogLevel | undefine
}
export function register(options?: {
+ autoDetectResources?: boolean;
+ autoInstrumentations?: boolean;
debug?: true | DiagLogLevel;
+ environment?: string;
+ histogramViews?: {
+ boundaries: readonly number[];
+ instrumentName: string;
+ meterName?: string;
+ }[];
name?: string;
version?: string;
}) {
const attributes = attributesCommon();
+ if (typeof options?.environment !== 'undefined') {
+ attributes.env = options.environment;
+ }
if (typeof options?.name !== 'undefined') {
attributes[ATTR_SERVICE_NAME] = options.name;
}
@@ -122,11 +142,11 @@ export function register(options?: {
}
const sdk = new NodeSDK({
- instrumentations: [
- new PgInstrumentation(),
- new HttpInstrumentation(),
- getNodeAutoInstrumentations(),
- ],
+ autoDetectResources: options?.autoDetectResources,
+ instrumentations:
+ options?.autoInstrumentations === false
+ ? []
+ : [new PgInstrumentation(), new HttpInstrumentation(), getNodeAutoInstrumentations()],
metricReaders: [
new PeriodicExportingMetricReader({
exportIntervalMillis: metricsExporterInterval,
@@ -135,9 +155,27 @@ export function register(options?: {
],
resource: resourceFromAttributes(attributes),
traceExporter: new OTLPTraceExporter(),
+ views: options?.histogramViews?.map(({ boundaries, instrumentName, meterName }) => ({
+ aggregation: {
+ options: { boundaries: [...boundaries] },
+ type: AggregationType.EXPLICIT_BUCKET_HISTOGRAM,
+ },
+ instrumentName,
+ meterName,
+ })),
});
sdk.start();
+ return sdk;
}
+export const shutdownSafely = async (sdk: Pick<NodeSDK, 'shutdown'>): Promise<void> => {
+ try {
+ await sdk.shutdown();
+ } catch (error) {
+ /** Exporter shutdown failures must not change the caller's business result or exit status. */
+ diag.error('[observability-otel] failed to shut down telemetry', error);
+ }
+};
+
export { DiagLogLevel } from '@opentelemetry/api';
diff --git a/packages/types/src/ftsSearch.ts b/packages/types/src/ftsSearch.ts
new file mode 100644
index 00000000000..6e4af6e0c10
--- /dev/null
+++ b/packages/types/src/ftsSearch.ts
@@ -0,0 +1,23 @@
+export const FTS_SEARCH_DOCUMENT_ENTITIES = [
+ 'agents',
+ 'topics',
+ 'files',
+ 'knowledgeBases',
+ 'userMemories',
+ 'chatGroups',
+ 'memoryContexts',
+ 'memoryPreferences',
+ 'memoryActivities',
+ 'memoryIdentities',
+ 'memoryExperiences',
+ 'personaDocuments',
+ 'documents',
+ 'messages',
+] as const;
+
+export type FtsSearchDocumentEntity = (typeof FTS_SEARCH_DOCUMENT_ENTITIES)[number];
+
+export type FtsSearchReindexEntityStatus = 'pending' | 'backfilling' | 'completed';
+
+export type FtsSearchReindexRunStatus =
+ 'backfilling' | 'ready_for_incremental_sync' | 'completed' | 'failed';
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 5943789b645..80e22fb753f 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -25,6 +25,7 @@ export * from './export';
export * from './fetch';
export * from './files';
export * from './followUpAction';
+export * from './ftsSearch';
export * from './generation';
export * from './goal';
export * from './heteroSessionImport';
diff --git a/scripts/elasticsearchReindex/__tests__/options.test.ts b/scripts/elasticsearchReindex/__tests__/options.test.ts
new file mode 100644
index 00000000000..744b4b8dc2d
--- /dev/null
+++ b/scripts/elasticsearchReindex/__tests__/options.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ assertFtsSearchReindexElasticsearchHostname,
+ assertFtsSearchReindexTelemetryExportConfigured,
+ resolveFtsSearchReindexElasticsearchEnvironment,
+ resolveFtsSearchReindexTelemetryEnvironment,
+} from '../options';
+
+describe('resolveFtsSearchReindexElasticsearchEnvironment', () => {
+ it('uses the canonical pair by default', () => {
+ expect(resolveFtsSearchReindexElasticsearchEnvironment([])).toEqual({
+ apiKeyEnvironmentName: 'ES_API_KEY',
+ urlEnvironmentName: 'ES_URL',
+ });
+ });
+
+ it('selects an explicit endpoint and credential pair without reading their values', () => {
+ expect(
+ resolveFtsSearchReindexElasticsearchEnvironment([
+ '--elasticsearch-url-env=DEV_SEARCH_ES_URL',
+ '--elasticsearch-api-key-env=DEV_SEARCH_ES_API_KEY',
+ '--expected-elasticsearch-host-prefix=dev-search-',
+ ]),
+ ).toEqual({
+ apiKeyEnvironmentName: 'DEV_SEARCH_ES_API_KEY',
+ expectedHostPrefix: 'dev-search-',
+ urlEnvironmentName: 'DEV_SEARCH_ES_URL',
+ });
+ });
+
+ it('refuses a partial pair or a non-environment-variable name', () => {
+ expect(() =>
+ resolveFtsSearchReindexElasticsearchEnvironment([
+ '--elasticsearch-url-env=DEV_SEARCH_ES_URL',
+ ]),
+ ).toThrow('must be provided together');
+ expect(() =>
+ resolveFtsSearchReindexElasticsearchEnvironment([
+ '--elasticsearch-url-env=../../secret',
+ '--elasticsearch-api-key-env=ES_API_KEY',
+ ]),
+ ).toThrow('must name an uppercase environment variable');
+ });
+
+ it('refuses a hostname outside the explicitly required target prefix', () => {
+ expect(() =>
+ assertFtsSearchReindexElasticsearchHostname('production-search.example.com', 'dev-search-'),
+ ).toThrow('does not match required prefix');
+ expect(() =>
+ assertFtsSearchReindexElasticsearchHostname('dev-search-abc.example.com', 'dev-search-'),
+ ).not.toThrow();
+ });
+});
+
+describe('resolveFtsSearchReindexTelemetryEnvironment', () => {
+ it('requires an explicit, bounded environment label when provided', () => {
+ expect(resolveFtsSearchReindexTelemetryEnvironment([])).toBeUndefined();
+ expect(
+ resolveFtsSearchReindexTelemetryEnvironment(['--telemetry-environment=development']),
+ ).toBe('development');
+ expect(() =>
+ resolveFtsSearchReindexTelemetryEnvironment(['--telemetry-environment=Production']),
+ ).toThrow('must be one of development, preview, or production');
+ expect(() =>
+ resolveFtsSearchReindexTelemetryEnvironment(['--telemetry-environment=staging']),
+ ).toThrow('must be one of development, preview, or production');
+ });
+});
+
+describe('assertFtsSearchReindexTelemetryExportConfigured', () => {
+ it('accepts a shared OTLP endpoint', () => {
+ expect(() =>
+ assertFtsSearchReindexTelemetryExportConfigured({
+ OTEL_EXPORTER_OTLP_ENDPOINT: 'https://collector.example.com',
+ }),
+ ).not.toThrow();
+ });
+
+ it('accepts separate metrics and traces endpoints', () => {
+ expect(() =>
+ assertFtsSearchReindexTelemetryExportConfigured({
+ OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: 'https://collector.example.com/v1/metrics',
+ OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: 'https://collector.example.com/v1/traces',
+ }),
+ ).not.toThrow();
+ });
+
+ it('refuses telemetry without both export destinations', () => {
+ expect(() => assertFtsSearchReindexTelemetryExportConfigured({})).toThrow(
+ 'OTLP metrics and traces export endpoints are required',
+ );
+ expect(() =>
+ assertFtsSearchReindexTelemetryExportConfigured({
+ OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: 'https://collector.example.com/v1/metrics',
+ }),
+ ).toThrow('OTLP metrics and traces export endpoints are required');
+ expect(() =>
+ assertFtsSearchReindexTelemetryExportConfigured({
+ OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: 'https://collector.example.com/v1/traces',
+ }),
+ ).toThrow('OTLP metrics and traces export endpoints are required');
+ });
+});
diff --git a/scripts/elasticsearchReindex/__tests__/preparation.test.ts b/scripts/elasticsearchReindex/__tests__/preparation.test.ts
new file mode 100644
index 00000000000..134fd52e024
--- /dev/null
+++ b/scripts/elasticsearchReindex/__tests__/preparation.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { runFtsSearchReindexCommand } from '../preparation';
+
+describe('runFtsSearchReindexCommand', () => {
+ it('does not install capture infrastructure for the status command', async () => {
+ const installCaptureInfrastructure = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
+ const runWithLockRetry = vi.fn<(operation: () => Promise<void>) => Promise<void>>();
+ const readStatus = vi.fn<() => Promise<string>>().mockResolvedValue('status');
+
+ await expect(
+ runFtsSearchReindexCommand({
+ command: 'status',
+ installCaptureInfrastructure,
+ runWithLockRetry,
+ run: readStatus,
+ }),
+ ).resolves.toBe('status');
+
+ expect(readStatus).toHaveBeenCalledOnce();
+ expect(installCaptureInfrastructure).not.toHaveBeenCalled();
+ expect(runWithLockRetry).not.toHaveBeenCalled();
+ });
+
+ it('installs capture through lock retry before creating the reindex checkpoint', async () => {
+ const events: string[] = [];
+ const installCaptureInfrastructure = vi
+ .fn<() => Promise<void>>()
+ .mockImplementation(async () => {
+ events.push('install');
+ });
+ const runWithLockRetry = vi
+ .fn<(operation: () => Promise<void>) => Promise<void>>()
+ .mockImplementation(async (operation) => operation());
+ const createOrResume = vi.fn<() => Promise<string>>().mockImplementation(async () => {
+ events.push('create-or-resume');
+ return 'prepared';
+ });
+
+ await expect(
+ runFtsSearchReindexCommand({
+ command: 'apply',
+ installCaptureInfrastructure,
+ runWithLockRetry,
+ run: createOrResume,
+ }),
+ ).resolves.toBe('prepared');
+
+ expect(runWithLockRetry).toHaveBeenCalledOnce();
+ expect(runWithLockRetry).toHaveBeenCalledWith(installCaptureInfrastructure);
+ expect(events).toEqual(['install', 'create-or-resume']);
+ });
+
+ it('stops before the checkpoint when capture installation fails', async () => {
+ const error = new Error('capture install failed');
+ const installCaptureInfrastructure = vi.fn<() => Promise<void>>().mockRejectedValue(error);
+ const runWithLockRetry = vi
+ .fn<(operation: () => Promise<void>) => Promise<void>>()
+ .mockImplementation(async (operation) => operation());
+ const createOrResume = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
+
+ await expect(
+ runFtsSearchReindexCommand({
+ command: 'apply',
+ installCaptureInfrastructure,
+ runWithLockRetry,
+ run: createOrResume,
+ }),
+ ).rejects.toBe(error);
+
+ expect(installCaptureInfrastructure).toHaveBeenCalledOnce();
+ expect(createOrResume).not.toHaveBeenCalled();
+ });
+});
diff --git a/scripts/elasticsearchReindex/index.ts b/scripts/elasticsearchReindex/index.ts
new file mode 100644
index 00000000000..fcc085d3240
--- /dev/null
+++ b/scripts/elasticsearchReindex/index.ts
@@ -0,0 +1,452 @@
+import { randomUUID } from 'node:crypto';
+import path from 'node:path';
+
+import type { FtsSearchDocumentEntity } from '@lobechat/types';
+import { drizzle } from 'drizzle-orm/node-postgres';
+import pg from 'pg';
+
+import {
+ FTS_SEARCH_DOCUMENT_ENTITIES,
+ FTS_SEARCH_INDEX_SCHEMA_VERSION,
+ FtsSearchDocumentBuilder,
+} from '../../packages/database/src/repositories/ftsSearchDocument';
+import {
+ type FtsSearchReindexAuditValue,
+ FtsSearchReindexEntityError,
+ FtsSearchReindexFileLogger,
+ FtsSearchReindexFileRepository,
+ FtsSearchReindexHttpClient,
+ FtsSearchReindexService,
+ summarizeFtsSearchReindexError,
+} from '../../packages/database/src/repositories/ftsSearchReindex';
+import { FtsSearchSyncOutboxRepository } from '../../packages/database/src/repositories/ftsSearchSyncOutbox';
+import * as schema from '../../packages/database/src/schemas';
+import {
+ observeFtsSearchReindexRun,
+ recordFtsSearchReindexBatch,
+ recordFtsSearchReindexBulkRequest,
+ recordFtsSearchReindexBulkRetry,
+ recordFtsSearchReindexReconciliation,
+} from '../../packages/observability-otel/src/modules/fts-search-reindex';
+import { DiagLogLevel, register, shutdownSafely } from '../../packages/observability-otel/src/node';
+import { runWithLockRetry } from '../migrateServerDB/retry';
+import {
+ assertFtsSearchReindexElasticsearchHostname,
+ assertFtsSearchReindexTelemetryExportConfigured,
+ resolveFtsSearchReindexElasticsearchEnvironment,
+ resolveFtsSearchReindexTelemetryEnvironment,
+} from './options';
+import { runFtsSearchReindexCommand } from './preparation';
+
+const { Pool } = pg;
+
+const REINDEX_BYTE_BUCKETS = [
+ 0, 256, 1024, 4096, 16_384, 65_536, 262_144, 1_048_576, 4_194_304, 16_777_216, 52_428_800,
+];
+const REINDEX_COUNT_BUCKETS = [0, 1, 5, 10, 25, 50, 100, 250, 500, 1000];
+const REINDEX_DURATION_MS_BUCKETS = [
+ 0, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 3000, 5000, 10_000, 30_000, 60_000,
+];
+
+const readPositiveIntegerArgument = (name: string) => {
+ const argument = process.argv.find((item) => item.startsWith(`${name}=`));
+ if (!argument) return;
+ const value = Number.parseInt(argument.slice(name.length + 1), 10);
+ if (!Number.isInteger(value) || value < 1) throw new Error(`${name} must be a positive integer`);
+ return value;
+};
+
+const readNonNegativeIntegerArgument = (name: string) => {
+ const argument = process.argv.find((item) => item.startsWith(`${name}=`));
+ if (!argument) return;
+ const value = Number.parseInt(argument.slice(name.length + 1), 10);
+ if (!Number.isInteger(value) || value < 0) {
+ throw new Error(`${name} must be a non-negative integer`);
+ }
+ return value;
+};
+
+const args = new Set(process.argv.slice(2));
+const apply = args.has('--apply');
+const freshRun = args.has('--fresh-run');
+const skipFailureArgument = process.argv.find((item) => item.startsWith('--skip-failure='));
+const status = args.has('--status');
+const yes = args.has('--yes');
+const batchSize = readPositiveIntegerArgument('--batch-size');
+const bulkConcurrency = readPositiveIntegerArgument('--bulk-concurrency');
+const bulkMaxBytes = readPositiveIntegerArgument('--bulk-max-bytes');
+const entityConcurrency = readPositiveIntegerArgument('--entity-concurrency');
+const maxBatchesPerEntity = readPositiveIntegerArgument('--max-batches-per-entity');
+const maxRequestRetries = readNonNegativeIntegerArgument('--max-request-retries');
+const requestTimeoutMs = readPositiveIntegerArgument('--request-timeout-ms');
+const retryBaseDelayMs = readNonNegativeIntegerArgument('--retry-base-delay-ms');
+const telemetryEnvironment = resolveFtsSearchReindexTelemetryEnvironment(process.argv.slice(2));
+
+const knownArguments = new Set(['--apply', '--fresh-run', '--status', '--yes']);
+const unknownArgument = process.argv
+ .slice(2)
+ .find(
+ (item) =>
+ item.startsWith('--') &&
+ !knownArguments.has(item) &&
+ !item.startsWith('--batch-size=') &&
+ !item.startsWith('--bulk-concurrency=') &&
+ !item.startsWith('--bulk-max-bytes=') &&
+ !item.startsWith('--entity-concurrency=') &&
+ !item.startsWith('--elasticsearch-api-key-env=') &&
+ !item.startsWith('--elasticsearch-url-env=') &&
+ !item.startsWith('--expected-elasticsearch-host-prefix=') &&
+ !item.startsWith('--max-batches-per-entity=') &&
+ !item.startsWith('--max-request-retries=') &&
+ !item.startsWith('--request-timeout-ms=') &&
+ !item.startsWith('--retry-base-delay-ms=') &&
+ !item.startsWith('--skip-failure=') &&
+ !item.startsWith('--telemetry-environment='),
+ );
+if (unknownArgument) throw new Error(`Unknown argument: ${unknownArgument}`);
+
+const mutationModes = [apply, Boolean(skipFailureArgument)].filter(Boolean).length;
+if (mutationModes > 1 || (status && mutationModes > 0)) {
+ throw new Error('Choose exactly one of --status, --apply, or --skip-failure');
+}
+if (mutationModes > 0 && !yes) {
+ throw new Error('Mutating commands require --yes after reviewing their documented effects');
+}
+if (freshRun && !apply) throw new Error('--fresh-run can only be used with --apply');
+
+const readFailureReference = ():
+ { documentId: string; entity: FtsSearchDocumentEntity } | undefined => {
+ if (!skipFailureArgument) return;
+ const reference = skipFailureArgument.slice('--skip-failure='.length);
+ const separator = reference.indexOf(':');
+ if (separator < 1 || separator === reference.length - 1) {
+ throw new Error('--skip-failure must use <entity>:<document-id>');
+ }
+ const entityName = reference.slice(0, separator);
+ const entity = FTS_SEARCH_DOCUMENT_ENTITIES.find((item) => item === entityName);
+ if (!entity) throw new Error(`Unknown search entity: ${entityName}`);
+ return { documentId: reference.slice(separator + 1), entity };
+};
+
+const failureReference = readFailureReference();
+const { apiKeyEnvironmentName, expectedHostPrefix, urlEnvironmentName } =
+ resolveFtsSearchReindexElasticsearchEnvironment(process.argv.slice(2));
+
+const databaseUrl = process.env.DATABASE_URL;
+const elasticsearchApiKey = process.env[apiKeyEnvironmentName];
+const elasticsearchUrl = process.env[urlEnvironmentName];
+const namespace = process.env.ES_INDEX_NAMESPACE;
+const configuredStateDirectory = process.env.ES_REINDEX_STATE_DIR;
+const stateDirectory = path.resolve(configuredStateDirectory ?? '.elasticsearch-reindex');
+
+if (!databaseUrl) throw new Error('DATABASE_URL is required');
+if (!namespace) throw new Error('ES_INDEX_NAMESPACE is required');
+if (apply && !elasticsearchApiKey) {
+ throw new Error(`${apiKeyEnvironmentName} is required with --apply`);
+}
+if (apply && !elasticsearchUrl) {
+ throw new Error(`${urlEnvironmentName} is required with --apply`);
+}
+if ((apply || failureReference) && !configuredStateDirectory) {
+ throw new Error('ES_REINDEX_STATE_DIR is required for reindex mutations and resume attempts');
+}
+if (process.env.ENABLE_TELEMETRY && !telemetryEnvironment) {
+ throw new Error('--telemetry-environment is required when ENABLE_TELEMETRY is set');
+}
+if (process.env.ENABLE_TELEMETRY) {
+ assertFtsSearchReindexTelemetryExportConfigured(process.env);
+}
+
+const telemetrySdk = process.env.ENABLE_TELEMETRY
+ ? register({
+ autoDetectResources: false,
+ autoInstrumentations: false,
+ debug: DiagLogLevel.ERROR,
+ environment: telemetryEnvironment,
+ histogramViews: [
+ {
+ boundaries: [0, 1, 2, 3, 5, 10],
+ instrumentName: 'fts_search_reindex_bulk_request_attempts',
+ meterName: 'fts-search-reindex',
+ },
+ {
+ boundaries: REINDEX_BYTE_BUCKETS,
+ instrumentName: 'fts_search_reindex_bulk_request_size',
+ meterName: 'fts-search-reindex',
+ },
+ {
+ boundaries: REINDEX_DURATION_MS_BUCKETS,
+ instrumentName: 'fts_search_reindex_bulk_request_duration',
+ meterName: 'fts-search-reindex',
+ },
+ {
+ boundaries: REINDEX_COUNT_BUCKETS,
+ instrumentName: 'fts_search_reindex_bulk_request_items',
+ meterName: 'fts-search-reindex',
+ },
+ ],
+ name: 'lobehub-fts-search-reindex',
+ })
+ : undefined;
+const pool = new Pool({ connectionString: databaseUrl });
+const db = drizzle(pool, { schema });
+const outbox = new FtsSearchSyncOutboxRepository(db);
+const repository = new FtsSearchReindexFileRepository({
+ readCaptureFingerprint: () => outbox.readCaptureFingerprint(),
+ readHighWaterRevision: () => outbox.readHighWaterRevision(),
+ reserveRevisionWithWriteFence: () => outbox.reserveRevisionWithWriteFence(),
+ stateDirectory,
+});
+
+const logErrorSummary = (message: string, error: unknown) => {
+ console.error(message, summarizeFtsSearchReindexError(error));
+};
+
+const readStatus = async () => {
+ const state = await repository.getTargetRun(namespace, FTS_SEARCH_INDEX_SCHEMA_VERSION);
+ const unresolvedFailures = state ? await repository.listUnresolvedFailures(state.run.id) : [];
+ const outboxStats = await outbox.stats();
+ const entityStats: Record<string, FtsSearchReindexAuditValue> = Object.fromEntries(
+ Object.entries(outboxStats.entities).map(([entity, stats]) => [entity, { ...stats }]),
+ );
+ return {
+ namespace,
+ outbox: {
+ dead: outboxStats.dead,
+ entities: entityStats,
+ expiredLeases: outboxStats.expiredLeases,
+ highWaterRevision: outboxStats.highWaterRevision,
+ inFlight: outboxStats.inFlight,
+ oldestActiveRevision: outboxStats.oldestActiveRevision,
+ oldestReadyAgeSeconds: outboxStats.oldestReadyAgeSeconds,
+ pending: outboxStats.pending,
+ ready: outboxStats.ready,
+ revisionLag: outboxStats.revisionLag,
+ retrying: outboxStats.retrying,
+ },
+ run: state
+ ? {
+ baseRevision: state.run.baseRevision,
+ backfillHighWaterRevision: state.run.backfillHighWaterRevision,
+ entities: state.progress.map((progress) => ({
+ cursor: progress.cursor,
+ entity: progress.entity,
+ failedCount: progress.failedCount,
+ indexedCount: progress.indexedCount,
+ physicalIndex: progress.physicalIndex,
+ processedCount: progress.processedCount,
+ status: progress.status,
+ })),
+ id: state.run.id,
+ schemaVersion: state.run.schemaVersion,
+ status: state.run.status,
+ unresolvedFailures: unresolvedFailures.map(
+ ({ attempts, documentId, entity, error, retryable }) => ({
+ attempts,
+ documentId,
+ entity,
+ errorSummary: summarizeFtsSearchReindexError(error),
+ retryable,
+ }),
+ ),
+ }
+ : null,
+ stateDirectory,
+ };
+};
+
+const printStatus = async () => {
+ const currentStatus = await readStatus();
+ console.log(JSON.stringify(currentStatus, null, 2));
+ return currentStatus;
+};
+
+let auditLogger: FtsSearchReindexFileLogger | undefined;
+const executionStartedAt = Date.now();
+
+const run = async () => {
+ if (failureReference) {
+ await runFtsSearchReindexCommand({
+ command: 'skip-failure',
+ installCaptureInfrastructure: () => outbox.installCaptureInfrastructure(),
+ runWithLockRetry,
+ run: async () => {
+ const state = await repository.getTargetRun(namespace, FTS_SEARCH_INDEX_SCHEMA_VERSION);
+ if (!state) throw new Error(`No reindex run exists for namespace ${namespace}`);
+ const skipped = await repository.skipFailure(
+ state.run.id,
+ failureReference.entity,
+ failureReference.documentId,
+ );
+ if (!skipped) {
+ throw new Error('The requested unresolved, non-retryable reindex failure was not found');
+ }
+ await printStatus();
+ },
+ });
+ return;
+ }
+
+ if (!apply) {
+ await runFtsSearchReindexCommand({
+ command: 'status',
+ installCaptureInfrastructure: () => outbox.installCaptureInfrastructure(),
+ runWithLockRetry,
+ run: printStatus,
+ });
+ return;
+ }
+
+ const endpointHostname = new URL(elasticsearchUrl!).hostname;
+ assertFtsSearchReindexElasticsearchHostname(endpointHostname, expectedHostPrefix);
+ const existing = await repository.getTargetRun(namespace, FTS_SEARCH_INDEX_SCHEMA_VERSION);
+ if (!existing && !freshRun) {
+ throw new Error(
+ `No checkpoint exists in ${stateDirectory}; pass --fresh-run only for a new, empty Elasticsearch target`,
+ );
+ }
+ if (existing && freshRun) {
+ throw new Error(`Checkpoint ${existing.run.id} already exists; omit --fresh-run to resume it`);
+ }
+ const prepared = await runFtsSearchReindexCommand({
+ command: 'apply',
+ installCaptureInfrastructure: () => outbox.installCaptureInfrastructure(),
+ runWithLockRetry,
+ run: async () => {
+ console.log(
+ JSON.stringify({
+ endpointEnvName: urlEnvironmentName,
+ endpointHostname,
+ expectedHostPrefix: expectedHostPrefix ?? null,
+ type: 'reindex_target',
+ }),
+ );
+ return repository.createOrResume(namespace, FTS_SEARCH_INDEX_SCHEMA_VERSION);
+ },
+ });
+ if (existing && existing.run.status !== 'ready_for_incremental_sync') {
+ await outbox.fenceSourceWrites();
+ }
+ auditLogger = new FtsSearchReindexFileLogger({
+ runId: prepared.run.id,
+ sessionId: randomUUID(),
+ stateDirectory,
+ });
+ await auditLogger.append({
+ batchSize: batchSize ?? 500,
+ bulkConcurrency: bulkConcurrency ?? 1,
+ bulkMaxBytes: bulkMaxBytes ?? 50 * 1024 * 1024,
+ credentialEnvName: apiKeyEnvironmentName,
+ endpointHostname,
+ endpointEnvName: urlEnvironmentName,
+ expectedHostPrefix: expectedHostPrefix ?? null,
+ entityConcurrency: entityConcurrency ?? 1,
+ maxBatchesPerEntity: maxBatchesPerEntity ?? null,
+ maxRequestRetries: maxRequestRetries ?? 4,
+ mode: existing ? 'resume' : 'fresh',
+ requestTimeoutMs: requestTimeoutMs ?? 30_000,
+ retryBaseDelayMs: retryBaseDelayMs ?? 500,
+ schemaVersion: prepared.run.schemaVersion,
+ type: 'session_started',
+ });
+ console.log(
+ JSON.stringify({
+ eventsPath: auditLogger.eventsPath,
+ runId: prepared.run.id,
+ schemaVersion: prepared.run.schemaVersion,
+ stateDirectory,
+ summaryPath: auditLogger.summaryPath,
+ type: existing ? 'reindex_resumed' : 'reindex_started',
+ }),
+ );
+
+ const client = new FtsSearchReindexHttpClient({
+ apiKey: elasticsearchApiKey!,
+ requestTimeoutMs,
+ url: elasticsearchUrl!,
+ });
+ const service = new FtsSearchReindexService(
+ new FtsSearchDocumentBuilder(db),
+ repository,
+ client,
+ {
+ batchSize,
+ bulkConcurrency,
+ bulkMaxBytes,
+ entityConcurrency,
+ maxBatchesPerEntity,
+ maxRequestRetries,
+ onProgress: async (event) => {
+ if (event.type === 'batch') {
+ recordFtsSearchReindexBatch({
+ checkpoint: event.checkpoint,
+ entity: event.entity,
+ failed: event.failed,
+ indexed: event.indexed,
+ scanned: event.processed,
+ });
+ }
+ if (event.type === 'reconciliation') {
+ recordFtsSearchReindexReconciliation(event);
+ }
+ if (event.type === 'bulk_retry') {
+ recordFtsSearchReindexBulkRetry(event.entity);
+ }
+ if (event.type === 'bulk_completed') {
+ recordFtsSearchReindexBulkRequest(event);
+ }
+ console.log(JSON.stringify(event));
+ await auditLogger!.append(event);
+ },
+ retryBaseDelayMs,
+ validateIncrementalSyncSource: () => outbox.assertCaptureInfrastructure(),
+ },
+ );
+ const result = await service.run(namespace, FTS_SEARCH_INDEX_SCHEMA_VERSION);
+ console.log(JSON.stringify(result));
+ const currentStatus = await printStatus();
+ await auditLogger.append({
+ elapsedMs: Date.now() - executionStartedAt,
+ status: result.status,
+ type: 'session_completed',
+ });
+ await auditLogger.writeSummary({
+ elapsedMs: Date.now() - executionStartedAt,
+ runStatus: result.status,
+ status: currentStatus,
+ });
+};
+
+observeFtsSearchReindexRun(run)
+ .catch(async (error) => {
+ const rootError = error instanceof FtsSearchReindexEntityError ? error.cause : error;
+ logErrorSummary('❌ Elasticsearch reindex failed:', rootError);
+ if (auditLogger) {
+ const failure = {
+ elapsedMs: Date.now() - executionStartedAt,
+ entity: error instanceof FtsSearchReindexEntityError ? error.entity : null,
+ errorSummary: summarizeFtsSearchReindexError(rootError),
+ errorType: rootError instanceof Error ? rootError.name.slice(0, 128) : 'UnknownError',
+ type: 'session_failed' as const,
+ };
+ await auditLogger
+ .append(failure)
+ .catch((logError) => logErrorSummary('Failed to append reindex audit event:', logError));
+ const currentStatus = await readStatus().catch((statusError) => {
+ logErrorSummary('Failed to read reindex status after failure:', statusError);
+ return null;
+ });
+ await auditLogger
+ .writeSummary({ failure, status: currentStatus })
+ .catch((logError) => logErrorSummary('Failed to write reindex audit summary:', logError));
+ }
+ process.exitCode = 1;
+ })
+ .finally(async () => {
+ try {
+ await pool.end();
+ } finally {
+ /** Flush terminal run metrics and the root trace before the short-lived CLI exits. */
+ if (telemetrySdk) await shutdownSafely(telemetrySdk);
+ }
+ });
diff --git a/scripts/elasticsearchReindex/options.ts b/scripts/elasticsearchReindex/options.ts
new file mode 100644
index 00000000000..0136890c8aa
--- /dev/null
+++ b/scripts/elasticsearchReindex/options.ts
@@ -0,0 +1,87 @@
+export interface FtsSearchReindexElasticsearchEnvironment {
+ apiKeyEnvironmentName: string;
+ expectedHostPrefix?: string;
+ urlEnvironmentName: string;
+}
+
+export type FtsSearchReindexTelemetryEnvironment = 'development' | 'preview' | 'production';
+
+const readEnvironmentVariableNameArgument = (args: readonly string[], name: string) => {
+ const argument = args.find((item) => item.startsWith(`${name}=`));
+ if (!argument) return;
+ const value = argument.slice(name.length + 1);
+ if (!/^[A-Z][A-Z0-9_]*$/.test(value)) {
+ throw new Error(`${name} must name an uppercase environment variable`);
+ }
+ return value;
+};
+
+const readHostPrefixArgument = (args: readonly string[]) => {
+ const name = '--expected-elasticsearch-host-prefix';
+ const argument = args.find((item) => item.startsWith(`${name}=`));
+ if (!argument) return;
+ const value = argument.slice(name.length + 1).toLowerCase();
+ if (!/^[a-z\d][a-z\d.-]*$/.test(value)) {
+ throw new Error(`${name} must be a valid lowercase hostname prefix`);
+ }
+ return value;
+};
+
+export const resolveFtsSearchReindexElasticsearchEnvironment = (
+ args: readonly string[],
+): FtsSearchReindexElasticsearchEnvironment => {
+ const apiKeyEnvironmentName = readEnvironmentVariableNameArgument(
+ args,
+ '--elasticsearch-api-key-env',
+ );
+ const urlEnvironmentName = readEnvironmentVariableNameArgument(args, '--elasticsearch-url-env');
+ if (Boolean(apiKeyEnvironmentName) !== Boolean(urlEnvironmentName)) {
+ throw new Error(
+ '--elasticsearch-url-env and --elasticsearch-api-key-env must be provided together',
+ );
+ }
+ return {
+ apiKeyEnvironmentName: apiKeyEnvironmentName ?? 'ES_API_KEY',
+ expectedHostPrefix: readHostPrefixArgument(args),
+ urlEnvironmentName: urlEnvironmentName ?? 'ES_URL',
+ };
+};
+
+export const resolveFtsSearchReindexTelemetryEnvironment = (
+ args: readonly string[],
+): FtsSearchReindexTelemetryEnvironment | undefined => {
+ const name = '--telemetry-environment';
+ const argument = args.find((item) => item.startsWith(`${name}=`));
+ if (!argument) return;
+ const value = argument.slice(name.length + 1);
+ if (value !== 'development' && value !== 'preview' && value !== 'production') {
+ throw new Error(`${name} must be one of development, preview, or production`);
+ }
+ return value;
+};
+
+export const assertFtsSearchReindexTelemetryExportConfigured = (
+ environment: Readonly<Record<string, string | undefined>>,
+) => {
+ const sharedEndpoint = Boolean(environment.OTEL_EXPORTER_OTLP_ENDPOINT);
+ const hasMetricsEndpoint =
+ sharedEndpoint || Boolean(environment.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT);
+ const hasTracesEndpoint =
+ sharedEndpoint || Boolean(environment.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT);
+ if (!hasMetricsEndpoint || !hasTracesEndpoint) {
+ throw new Error(
+ 'OTLP metrics and traces export endpoints are required: set OTEL_EXPORTER_OTLP_ENDPOINT or both signal-specific endpoint variables',
+ );
+ }
+};
+
+export const assertFtsSearchReindexElasticsearchHostname = (
+ hostname: string,
+ expectedHostPrefix?: string,
+) => {
+ if (expectedHostPrefix && !hostname.toLowerCase().startsWith(expectedHostPrefix)) {
+ throw new Error(
+ `Elasticsearch hostname ${hostname} does not match required prefix ${expectedHostPrefix}`,
+ );
+ }
+};
diff --git a/scripts/elasticsearchReindex/preparation.ts b/scripts/elasticsearchReindex/preparation.ts
new file mode 100644
index 00000000000..cb08e4b6b28
--- /dev/null
+++ b/scripts/elasticsearchReindex/preparation.ts
@@ -0,0 +1,27 @@
+export type FtsSearchReindexCommand = 'apply' | 'skip-failure' | 'status';
+
+interface RunFtsSearchReindexCommandOptions<T> {
+ command: FtsSearchReindexCommand;
+ installCaptureInfrastructure: () => Promise<void>;
+ run: () => Promise<T>;
+ runWithLockRetry: (operation: () => Promise<void>) => Promise<void>;
+}
+
+/**
+ * Runs one reindex command while keeping capture installation ahead of every apply mutation.
+ *
+ * Status and failure-skipping commands intentionally execute without installing database
+ * triggers, so PG-only self-hosted instances do not pay the Elasticsearch capture overhead.
+ */
+export const runFtsSearchReindexCommand = async <T>({
+ command,
+ installCaptureInfrastructure,
+ run,
+ runWithLockRetry,
+}: RunFtsSearchReindexCommandOptions<T>): Promise<T> => {
+ if (command === 'apply') {
+ await runWithLockRetry(installCaptureInfrastructure);
+ }
+
+ return run();
+};
diff --git a/scripts/elasticsearchSync/cli.ts b/scripts/elasticsearchSync/cli.ts
new file mode 100644
index 00000000000..ea6c0f1c7de
--- /dev/null
+++ b/scripts/elasticsearchSync/cli.ts
@@ -0,0 +1,5 @@
+import { runElasticsearchFtsSearchSyncCli } from './index';
+
+void runElasticsearchFtsSearchSyncCli().then((exitCode) => {
+ process.exit(exitCode);
+});
diff --git a/scripts/elasticsearchSync/index.test.ts b/scripts/elasticsearchSync/index.test.ts
new file mode 100644
index 00000000000..fcb10c768f6
--- /dev/null
+++ b/scripts/elasticsearchSync/index.test.ts
@@ -0,0 +1,125 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { FtsSearchSyncDrainResult } from '../../apps/server/src/services/ftsSearchSync';
+import { runElasticsearchFtsSearchSync, runElasticsearchFtsSearchSyncCli } from './index';
+
+const drainResult = (
+ overrides: Partial<FtsSearchSyncDrainResult> = {},
+): FtsSearchSyncDrainResult => ({
+ acknowledged: 1,
+ bulkBytes: 100,
+ bulkItems: 1,
+ bulkRequests: 1,
+ bulkRequestSamples: [],
+ claimed: 1,
+ dead: 0,
+ failed: 0,
+ hasMore: false,
+ released: 0,
+ ...overrides,
+});
+
+const createRuntime = (results: FtsSearchSyncDrainResult[]) => {
+ const drainOnce = vi.fn();
+ for (const result of results) drainOnce.mockResolvedValueOnce(result);
+ const runtime = {
+ getFtsSearchSyncService: () => ({
+ drainOnce,
+ hasDeadLetters: vi.fn().mockResolvedValue(false),
+ }),
+ verifyFtsSearchSyncReadiness: vi.fn().mockResolvedValue(undefined),
+ };
+ return { drainOnce, runtime };
+};
+
+describe('runElasticsearchFtsSearchSync', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('drains until the queue is empty within the configured bound', async () => {
+ const { drainOnce, runtime } = createRuntime([
+ drainResult({ hasMore: true }),
+ drainResult({ acknowledged: 2, bulkItems: 2, claimed: 2 }),
+ ]);
+
+ await expect(
+ runElasticsearchFtsSearchSync({ loadRuntime: async () => runtime, maxSteps: 8 }),
+ ).resolves.toMatchObject({ acknowledged: 3, claimed: 3, hasMore: false, steps: 2 });
+ expect(runtime.verifyFtsSearchSyncReadiness).toHaveBeenCalledOnce();
+ expect(drainOnce).toHaveBeenCalledTimes(2);
+ });
+
+ it('stops at the configured bound and reports remaining work', async () => {
+ const { drainOnce, runtime } = createRuntime([drainResult({ hasMore: true })]);
+
+ await expect(
+ runElasticsearchFtsSearchSync({ loadRuntime: async () => runtime, maxSteps: 1 }),
+ ).resolves.toMatchObject({ hasMore: true, steps: 1 });
+ expect(drainOnce).toHaveBeenCalledOnce();
+ });
+
+ it('fails before draining when durable dead letters already exist', async () => {
+ const { runtime } = createRuntime([]);
+ const service = runtime.getFtsSearchSyncService();
+ service.hasDeadLetters = vi.fn().mockResolvedValue(true);
+ runtime.getFtsSearchSyncService = () => service;
+
+ await expect(
+ runElasticsearchFtsSearchSync({ loadRuntime: async () => runtime, maxSteps: 1 }),
+ ).rejects.toThrow('blocked by existing dead-letter work');
+ expect(service.drainOnce).not.toHaveBeenCalled();
+ });
+
+ it('fails when dead-letter work appears concurrently after draining', async () => {
+ const { runtime } = createRuntime([drainResult()]);
+ const service = runtime.getFtsSearchSyncService();
+ service.hasDeadLetters = vi.fn().mockResolvedValueOnce(false).mockResolvedValueOnce(true);
+ runtime.getFtsSearchSyncService = () => service;
+
+ await expect(
+ runElasticsearchFtsSearchSync({ loadRuntime: async () => runtime, maxSteps: 1 }),
+ ).rejects.toThrow('blocked by dead-letter work');
+ });
+
+ it.each([
+ [drainResult({ dead: 1, failed: 1 }), 'created dead-letter work'],
+ [drainResult({ failed: 1 }), 'left retryable failed work'],
+ ])('fails on unsettled drain results', async (result, message) => {
+ const { runtime } = createRuntime([result]);
+
+ await expect(
+ runElasticsearchFtsSearchSync({ loadRuntime: async () => runtime, maxSteps: 1 }),
+ ).rejects.toThrow(message);
+ });
+});
+
+describe('runElasticsearchFtsSearchSyncCli', () => {
+ it('requires explicit acknowledgement before loading the runtime', async () => {
+ const loadRuntime = vi.fn();
+ const logError = vi.fn();
+
+ await expect(
+ runElasticsearchFtsSearchSyncCli({ args: [], loadRuntime, logError }),
+ ).resolves.toBe(1);
+ expect(loadRuntime).not.toHaveBeenCalled();
+ expect(logError).toHaveBeenCalledWith(
+ 'Elasticsearch full-text search sync failed:',
+ 'Elasticsearch full-text search sync requires --yes after reviewing its documented effects',
+ );
+ });
+
+ it('returns zero and emits only bounded numeric summaries after a successful drain', async () => {
+ const { runtime } = createRuntime([drainResult()]);
+ const logSuccess = vi.fn();
+
+ await expect(
+ runElasticsearchFtsSearchSyncCli({
+ args: ['--yes'],
+ loadRuntime: async () => runtime,
+ logSuccess,
+ }),
+ ).resolves.toBe(0);
+ expect(logSuccess).toHaveBeenLastCalledWith(
+ expect.stringContaining('"type":"fts_search_sync_completed"'),
+ );
+ });
+});
diff --git a/scripts/elasticsearchSync/index.ts b/scripts/elasticsearchSync/index.ts
new file mode 100644
index 00000000000..0ee0b2acb15
--- /dev/null
+++ b/scripts/elasticsearchSync/index.ts
@@ -0,0 +1,123 @@
+import type { FtsSearchSyncDrainResult } from '../../apps/server/src/services/ftsSearchSync';
+import { summarizeFtsSearchReindexError } from '../../packages/database/src/repositories/ftsSearchReindex';
+import { parseElasticsearchFtsSearchSyncCliOptions } from './options';
+
+type FtsSearchSyncService = {
+ drainOnce: () => Promise<FtsSearchSyncDrainResult>;
+ hasDeadLetters: () => Promise<boolean>;
+};
+
+type FtsSearchSyncRuntime = {
+ getFtsSearchSyncService: () => FtsSearchSyncService;
+ verifyFtsSearchSyncReadiness: () => Promise<unknown>;
+};
+
+export interface ElasticsearchFtsSearchSyncRunSummary {
+ acknowledged: number;
+ bulkBytes: number;
+ bulkItems: number;
+ bulkRequests: number;
+ claimed: number;
+ failed: number;
+ hasMore: boolean;
+ released: number;
+ steps: number;
+}
+
+export interface RunElasticsearchFtsSearchSyncOptions {
+ loadRuntime?: () => Promise<FtsSearchSyncRuntime>;
+ logStep?: (summary: ElasticsearchFtsSearchSyncRunSummary) => void;
+ maxSteps: number;
+}
+
+const loadRuntime = () => import('../../apps/server/src/services/ftsSearchSync');
+
+/** Runs a bounded drain so any cron or process supervisor can schedule it without a daemon. */
+export const runElasticsearchFtsSearchSync = async ({
+ loadRuntime: load = loadRuntime,
+ logStep = () => undefined,
+ maxSteps,
+}: RunElasticsearchFtsSearchSyncOptions): Promise<ElasticsearchFtsSearchSyncRunSummary> => {
+ const runtime = await load();
+ await runtime.verifyFtsSearchSyncReadiness();
+ const service = runtime.getFtsSearchSyncService();
+ if (await service.hasDeadLetters()) {
+ throw new Error('Elasticsearch full-text search sync is blocked by existing dead-letter work');
+ }
+
+ const summary: ElasticsearchFtsSearchSyncRunSummary = {
+ acknowledged: 0,
+ bulkBytes: 0,
+ bulkItems: 0,
+ bulkRequests: 0,
+ claimed: 0,
+ failed: 0,
+ hasMore: false,
+ released: 0,
+ steps: 0,
+ };
+
+ for (let step = 0; step < maxSteps; step += 1) {
+ const drained = await service.drainOnce();
+ summary.acknowledged += drained.acknowledged;
+ summary.bulkBytes += drained.bulkBytes;
+ summary.bulkItems += drained.bulkItems;
+ summary.bulkRequests += drained.bulkRequests;
+ summary.claimed += drained.claimed;
+ summary.failed += drained.failed;
+ summary.hasMore = drained.hasMore;
+ summary.released += drained.released;
+ summary.steps += 1;
+ logStep({ ...summary });
+
+ if (drained.dead > 0) {
+ throw new Error('Elasticsearch full-text search sync created dead-letter work');
+ }
+ if (drained.failed > 0) {
+ throw new Error('Elasticsearch full-text search sync left retryable failed work');
+ }
+ if (drained.claimed === 0 || !drained.hasMore) break;
+ }
+
+ if (await service.hasDeadLetters()) {
+ throw new Error('Elasticsearch full-text search sync is blocked by dead-letter work');
+ }
+
+ return summary;
+};
+
+type Logger = (...arguments_: unknown[]) => void;
+
+export interface RunElasticsearchFtsSearchSyncCliOptions {
+ args?: readonly string[];
+ loadRuntime?: () => Promise<FtsSearchSyncRuntime>;
+ logError?: Logger;
+ logSuccess?: Logger;
+}
+
+export const runElasticsearchFtsSearchSyncCli = async ({
+ args = process.argv.slice(2),
+ loadRuntime: load,
+ logError = console.error,
+ logSuccess = console.log,
+}: RunElasticsearchFtsSearchSyncCliOptions = {}): Promise<number> => {
+ try {
+ const options = parseElasticsearchFtsSearchSyncCliOptions(args);
+ if (!options.yes) {
+ throw new Error(
+ 'Elasticsearch full-text search sync requires --yes after reviewing its documented effects',
+ );
+ }
+
+ const summary = await runElasticsearchFtsSearchSync({
+ loadRuntime: load,
+ logStep: (step) => logSuccess(JSON.stringify({ ...step, type: 'fts_search_sync_step' })),
+ maxSteps: options.maxSteps,
+ });
+ logSuccess(JSON.stringify({ ...summary, success: true, type: 'fts_search_sync_completed' }));
+ return 0;
+ } catch (error) {
+ logError('Elasticsearch full-text search sync failed:', summarizeFtsSearchReindexError(error));
+ return 1;
+ }
+};
diff --git a/scripts/elasticsearchSync/options.test.ts b/scripts/elasticsearchSync/options.test.ts
new file mode 100644
index 00000000000..1892ba665db
--- /dev/null
+++ b/scripts/elasticsearchSync/options.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseElasticsearchFtsSearchSyncCliOptions } from './options';
+
+describe('parseElasticsearchFtsSearchSyncCliOptions', () => {
+ it('defaults to one bounded drain step', () => {
+ expect(parseElasticsearchFtsSearchSyncCliOptions([])).toEqual({ maxSteps: 1, yes: false });
+ });
+
+ it('accepts explicit acknowledgement and a bounded step count', () => {
+ expect(parseElasticsearchFtsSearchSyncCliOptions(['--max-steps=8', '--yes'])).toEqual({
+ maxSteps: 8,
+ yes: true,
+ });
+ });
+
+ it.each(['--max-steps=0', '--max-steps=101', '--max-steps=1.5', '--max-steps=01'])(
+ 'rejects invalid bounded step count %s',
+ (argument) => {
+ expect(() => parseElasticsearchFtsSearchSyncCliOptions([argument])).toThrow(
+ '--max-steps must be an integer between 1 and 100',
+ );
+ },
+ );
+
+ it('rejects duplicate or unknown arguments', () => {
+ expect(() =>
+ parseElasticsearchFtsSearchSyncCliOptions(['--max-steps=1', '--max-steps=2']),
+ ).toThrow('--max-steps can only be provided once');
+ expect(() => parseElasticsearchFtsSearchSyncCliOptions(['--forever'])).toThrow(
+ 'Unknown argument: --forever',
+ );
+ expect(() => parseElasticsearchFtsSearchSyncCliOptions(['unexpected'])).toThrow(
+ 'Unknown argument: unexpected',
+ );
+ });
+});
diff --git a/scripts/elasticsearchSync/options.ts b/scripts/elasticsearchSync/options.ts
new file mode 100644
index 00000000000..95d90aa840e
--- /dev/null
+++ b/scripts/elasticsearchSync/options.ts
@@ -0,0 +1,33 @@
+export interface ElasticsearchFtsSearchSyncCliOptions {
+ maxSteps: number;
+ yes: boolean;
+}
+
+const MAX_ALLOWED_STEPS = 100;
+
+export const parseElasticsearchFtsSearchSyncCliOptions = (
+ args: readonly string[],
+): ElasticsearchFtsSearchSyncCliOptions => {
+ const knownFlags = new Set(['--yes']);
+ const unknownArgument = args.find(
+ (argument) => !knownFlags.has(argument) && !argument.startsWith('--max-steps='),
+ );
+ if (unknownArgument) throw new Error(`Unknown argument: ${unknownArgument}`);
+
+ const maxStepArguments = args.filter((argument) => argument.startsWith('--max-steps='));
+ if (maxStepArguments.length > 1) throw new Error('--max-steps can only be provided once');
+
+ const rawMaxSteps = maxStepArguments[0]?.slice('--max-steps='.length);
+ const maxSteps = rawMaxSteps === undefined ? 1 : Number.parseInt(rawMaxSteps, 10);
+ if (
+ !Number.isInteger(maxSteps) ||
+ rawMaxSteps === '' ||
+ (rawMaxSteps !== undefined && String(maxSteps) !== rawMaxSteps) ||
+ maxSteps < 1 ||
+ maxSteps > MAX_ALLOWED_STEPS
+ ) {
+ throw new Error(`--max-steps must be an integer between 1 and ${MAX_ALLOWED_STEPS}`);
+ }
+
+ return { maxSteps, yes: args.includes('--yes') };
+};
diff --git a/scripts/installFtsSearchSyncCapture/index.test.ts b/scripts/installFtsSearchSyncCapture/index.test.ts
new file mode 100644
index 00000000000..1647335443c
--- /dev/null
+++ b/scripts/installFtsSearchSyncCapture/index.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ type FtsSearchSyncCaptureRepository,
+ installFtsSearchSyncCapture,
+ runFtsSearchSyncCaptureCli,
+} from './index';
+
+const createRepository = (): FtsSearchSyncCaptureRepository => ({
+ installCaptureInfrastructure: vi.fn().mockResolvedValue(undefined),
+});
+
+describe('installFtsSearchSyncCapture', () => {
+ it('loads the repository only after DATABASE_URL is available and installs capture', async () => {
+ const repository = createRepository();
+ const loadRepository = vi.fn().mockResolvedValue(repository);
+ const runWithLockRetry = vi.fn(async (operation: () => Promise<void>) => operation());
+
+ await expect(
+ installFtsSearchSyncCapture({
+ env: { DATABASE_URL: 'postgres://test' },
+ loadRepository,
+ runWithLockRetry,
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(loadRepository).toHaveBeenCalledOnce();
+ expect(runWithLockRetry).toHaveBeenCalledOnce();
+ expect(repository.installCaptureInfrastructure).toHaveBeenCalledOnce();
+ });
+
+ it('fails before loading the repository when DATABASE_URL is missing', async () => {
+ const loadRepository = vi.fn();
+
+ await expect(installFtsSearchSyncCapture({ env: {}, loadRepository })).rejects.toThrow(
+ 'DATABASE_URL is required',
+ );
+
+ expect(loadRepository).not.toHaveBeenCalled();
+ });
+});
+
+describe('runFtsSearchSyncCaptureCli', () => {
+ it('returns success and logs only after capture installation succeeds', async () => {
+ const logError = vi.fn();
+ const logSuccess = vi.fn();
+ const repository = createRepository();
+
+ await expect(
+ runFtsSearchSyncCaptureCli({
+ env: { DATABASE_URL: 'postgres://test' },
+ loadRepository: vi.fn().mockResolvedValue(repository),
+ logError,
+ logSuccess,
+ runWithLockRetry: vi.fn(async (operation: () => Promise<void>) => operation()),
+ }),
+ ).resolves.toBe(0);
+
+ expect(logSuccess).toHaveBeenCalledWith(
+ '✅ full-text search sync capture infrastructure installed',
+ );
+ expect(logError).not.toHaveBeenCalled();
+ });
+
+ it('returns failure and does not report success when capture installation fails', async () => {
+ const error = new Error(
+ 'capture installation failed at https://operator:[email protected]/app?query=private token=private-token',
+ );
+ const logError = vi.fn();
+ const logSuccess = vi.fn();
+ const runWithLockRetry = vi.fn(async (operation: () => Promise<void>) => operation());
+ const repository: FtsSearchSyncCaptureRepository = {
+ installCaptureInfrastructure: vi.fn().mockRejectedValue(error),
+ };
+
+ await expect(
+ runFtsSearchSyncCaptureCli({
+ env: { DATABASE_URL: 'postgres://test' },
+ loadRepository: vi.fn().mockResolvedValue(repository),
+ logError,
+ logSuccess,
+ runWithLockRetry,
+ }),
+ ).resolves.toBe(1);
+
+ expect(logError).toHaveBeenCalledWith(
+ '❌ Full-text search sync capture installation failed:',
+ 'capture installation failed at [redacted-url] token=[redacted]',
+ );
+ expect(logSuccess).not.toHaveBeenCalled();
+ });
+});
diff --git a/scripts/installFtsSearchSyncCapture/index.ts b/scripts/installFtsSearchSyncCapture/index.ts
new file mode 100644
index 00000000000..76f3deb833d
--- /dev/null
+++ b/scripts/installFtsSearchSyncCapture/index.ts
@@ -0,0 +1,87 @@
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import * as dotenv from 'dotenv';
+import dotenvExpand from 'dotenv-expand';
+
+import { summarizeFtsSearchReindexError } from '../../packages/database/src/repositories/ftsSearchReindex';
+import { runWithLockRetry as defaultRunWithLockRetry } from '../migrateServerDB/retry';
+
+// Load environment variables in priority order:
+// 1. .env (lowest priority)
+// 2. .env.[env] (medium priority, overrides .env)
+// 3. .env.[env].local (highest priority, overrides previous)
+// Use dotenv-expand to support ${var} variable expansion
+const env = process.env.NODE_ENV || 'development';
+dotenvExpand.expand(dotenv.config()); // Load .env
+dotenvExpand.expand(dotenv.config({ override: true, path: `.env.${env}` })); // Load .env.[env] and override
+dotenvExpand.expand(dotenv.config({ override: true, path: `.env.${env}.local` })); // Load .env.[env].local and override
+
+export type FtsSearchSyncCaptureRepository = {
+ installCaptureInfrastructure: () => Promise<void>;
+};
+
+type LoadRepository = () => Promise<FtsSearchSyncCaptureRepository>;
+type RunWithLockRetry = (operation: () => Promise<void>) => Promise<void>;
+type Logger = (...arguments_: unknown[]) => void;
+
+export type InstallFtsSearchSyncCaptureOptions = {
+ env?: NodeJS.ProcessEnv;
+ loadRepository?: LoadRepository;
+ runWithLockRetry?: RunWithLockRetry;
+};
+
+export type FtsSearchSyncCaptureCliOptions = InstallFtsSearchSyncCaptureOptions & {
+ logError?: Logger;
+ logSuccess?: Logger;
+};
+
+const loadRepository: LoadRepository = async () => {
+ // Keep database initialization out of the module graph until the required environment is set.
+ const { ftsSearchSyncOutboxRepository } =
+ await import('../../packages/database/src/repositories/ftsSearchSyncOutbox/server');
+
+ return ftsSearchSyncOutboxRepository;
+};
+
+export const installFtsSearchSyncCapture = async ({
+ env: environment = process.env,
+ loadRepository: load = loadRepository,
+ runWithLockRetry = defaultRunWithLockRetry,
+}: InstallFtsSearchSyncCaptureOptions = {}) => {
+ if (!environment.DATABASE_URL) throw new Error('DATABASE_URL is required');
+
+ const repository = await load();
+
+ await runWithLockRetry(() => repository.installCaptureInfrastructure());
+};
+
+export const runFtsSearchSyncCaptureCli = async ({
+ logError = console.error,
+ logSuccess = console.log,
+ ...options
+}: FtsSearchSyncCaptureCliOptions = {}) => {
+ try {
+ await installFtsSearchSyncCapture(options);
+ logSuccess('✅ full-text search sync capture infrastructure installed');
+ return 0;
+ } catch (error) {
+ logError(
+ '❌ Full-text search sync capture installation failed:',
+ summarizeFtsSearchReindexError(error),
+ );
+ return 1;
+ }
+};
+
+const isDirectExecution = () => {
+ const entrypoint = process.argv[1];
+
+ return entrypoint !== undefined && path.resolve(entrypoint) === fileURLToPath(import.meta.url);
+};
+
+if (isDirectExecution()) {
+ void runFtsSearchSyncCaptureCli().then((exitCode) => {
+ process.exit(exitCode);
+ });
+}
diff --git a/scripts/migrateServerDB/index.ts b/scripts/migrateServerDB/index.ts
index 8efe36a6481..bf41db00c88 100644
--- a/scripts/migrateServerDB/index.ts
+++ b/scripts/migrateServerDB/index.ts
@@ -1,4 +1,4 @@
-import { join } from 'node:path';
+import path from 'node:path';
import * as dotenv from 'dotenv';
import dotenvExpand from 'dotenv-expand';
@@ -7,6 +7,7 @@ import { migrate as nodeMigrate } from 'drizzle-orm/node-postgres/migrator';
// @ts-ignore tsgo handle esm import cjs and compatibility issues
import { DB_FAIL_INIT_HINT, DUPLICATE_EMAIL_HINT, PGVECTOR_HINT } from './errorHint';
+import { runWithLockRetry } from './retry';
// Load environment variables in priority order:
// 1. .env (lowest priority)
@@ -18,17 +19,19 @@ dotenvExpand.expand(dotenv.config()); // Load .env
dotenvExpand.expand(dotenv.config({ override: true, path: `.env.${env}` })); // Load .env.[env] and override
dotenvExpand.expand(dotenv.config({ override: true, path: `.env.${env}.local` })); // Load .env.[env].local and override
-const migrationsFolder = join(__dirname, '../../packages/database/migrations');
+const migrationsFolder = path.join(__dirname, '../../packages/database/migrations');
const runMigrations = async () => {
const { serverDB } = await import('../../packages/database/src/server');
const time = Date.now();
- if (process.env.DATABASE_DRIVER === 'node') {
- await nodeMigrate(serverDB, { migrationsFolder });
- } else {
- await neonMigrate(serverDB, { migrationsFolder });
- }
+ await runWithLockRetry(async () => {
+ if (process.env.DATABASE_DRIVER === 'node') {
+ await nodeMigrate(serverDB, { migrationsFolder });
+ } else {
+ await neonMigrate(serverDB, { migrationsFolder });
+ }
+ });
console.log('✅ database migration pass. use: %s ms', Date.now() - time);
diff --git a/scripts/migrateServerDB/retry.test.ts b/scripts/migrateServerDB/retry.test.ts
new file mode 100644
index 00000000000..a125f8c4ea1
--- /dev/null
+++ b/scripts/migrateServerDB/retry.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { runWithLockRetry } from './retry';
+
+describe('runWithLockRetry', () => {
+ it('retries lock timeouts with increasing delays and succeeds', async () => {
+ const firstLockError = { cause: { code: '55P03' } };
+ const secondLockError = { code: '55P03' };
+ const migrate = vi
+ .fn<() => Promise<void>>()
+ .mockRejectedValueOnce(firstLockError)
+ .mockRejectedValueOnce(secondLockError)
+ .mockResolvedValueOnce(undefined);
+ const wait = vi.fn<(delayMs: number) => Promise<void>>().mockResolvedValue(undefined);
+
+ await expect(runWithLockRetry(migrate, wait)).resolves.toBeUndefined();
+
+ expect(migrate).toHaveBeenCalledTimes(3);
+ expect(wait).toHaveBeenCalledTimes(2);
+ expect(wait).toHaveBeenNthCalledWith(1, 1000);
+ expect(wait).toHaveBeenNthCalledWith(2, 3000);
+ });
+
+ it('does not retry non-lock errors and rethrows the same error', async () => {
+ const error = { code: '23505' };
+ const migrate = vi.fn<() => Promise<void>>().mockRejectedValue(error);
+ const wait = vi.fn<(delayMs: number) => Promise<void>>().mockResolvedValue(undefined);
+
+ await expect(runWithLockRetry(migrate, wait)).rejects.toBe(error);
+
+ expect(migrate).toHaveBeenCalledTimes(1);
+ expect(wait).not.toHaveBeenCalled();
+ });
+
+ it('rethrows the final lock error after the maximum number of attempts', async () => {
+ const error = { code: '55P03' };
+ const migrate = vi.fn<() => Promise<void>>().mockRejectedValue(error);
+ const wait = vi.fn<(delayMs: number) => Promise<void>>().mockResolvedValue(undefined);
+
+ await expect(runWithLockRetry(migrate, wait)).rejects.toBe(error);
+
+ expect(migrate).toHaveBeenCalledTimes(3);
+ expect(wait).toHaveBeenCalledTimes(2);
+ expect(wait).toHaveBeenNthCalledWith(1, 1000);
+ expect(wait).toHaveBeenNthCalledWith(2, 3000);
+ });
+});
diff --git a/scripts/migrateServerDB/retry.ts b/scripts/migrateServerDB/retry.ts
new file mode 100644
index 00000000000..91a062c67de
--- /dev/null
+++ b/scripts/migrateServerDB/retry.ts
@@ -0,0 +1,50 @@
+const LOCK_TIMEOUT_CODE = '55P03';
+const LOCK_RETRY_DELAYS_MS = [1000, 3000] as const;
+
+type Wait = (delayMs: number) => Promise<void>;
+
+const defaultWait: Wait = (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs));
+
+const isLockTimeoutError = (error: unknown): boolean => {
+ const seen = new Set<unknown>();
+ let current = error;
+
+ while (typeof current === 'object' && current !== null && !seen.has(current)) {
+ seen.add(current);
+ if ('code' in current && current.code === LOCK_TIMEOUT_CODE) return true;
+ current = 'cause' in current ? current.cause : undefined;
+ }
+
+ return false;
+};
+
+/**
+ * Retries a lock-sensitive database operation after PostgreSQL lock timeouts.
+ *
+ * Callers must ensure that each failed attempt either rolls back all partial changes before
+ * rejecting or is idempotent, because this helper invokes the operation again from its beginning.
+ * PostgreSQL releases transaction-scoped locks when an attempt rolls back, so retrying the whole
+ * operation is safer than waiting longer while earlier work remains locked.
+ */
+export const runWithLockRetry = async (
+ operation: () => Promise<void>,
+ wait: Wait = defaultWait,
+): Promise<void> => {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ await operation();
+ return;
+ } catch (error) {
+ const delayMs = LOCK_RETRY_DELAYS_MS[attempt];
+ if (!isLockTimeoutError(error) || delayMs === undefined) throw error;
+
+ console.warn(
+ 'Database operation lock timed out; retrying the operation in %d ms (%d/%d)',
+ delayMs,
+ attempt + 1,
+ LOCK_RETRY_DELAYS_MS.length,
+ );
+ await wait(delayMs);
+ }
+ }
+};
diff --git a/src/features/CommandMenu/SearchResults.tsx b/src/features/CommandMenu/SearchResults.tsx
index c1508e70377..52722eb4b56 100644
--- a/src/features/CommandMenu/SearchResults.tsx
+++ b/src/features/CommandMenu/SearchResults.tsx
@@ -22,11 +22,11 @@ import {
Sparkles,
Users,
} from 'lucide-react';
-import { memo, type ReactNode } from 'react';
+import { memo, type ReactNode, useLayoutEffect } from 'react';
import { useTranslation } from 'react-i18next';
import Avatar from '@/components/Avatar';
-import { type SearchResult } from '@/database/repositories/search';
+import type { FtsSearchResult } from '@/database/repositories/ftsSearch';
import { useCommandMenuContext } from '@/features/CommandMenu/CommandMenuContext';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useImageStore } from '@/store/image';
@@ -35,16 +35,21 @@ import { useVideoStore } from '@/store/video';
import { generationTopicSelectors as videoGenerationTopicSelectors } from '@/store/video/slices/generationTopic/selectors';
import { markdownToTxt } from '@/utils/markdownToTxt';
+import type { CommandMenuResultClick } from './analytics';
import { CommandItem } from './components';
import { styles } from './styles';
import { shouldShowMarketplaceFallback } from './utils/marketplaceFallback';
import { type ValidSearchType } from './utils/queryParser';
+import { createVisibleResultPositionMap } from './utils/visibleResultPosition';
interface SearchResultsProps {
isLoading: boolean;
onClose: () => void;
+ onResultClick: (input: CommandMenuResultClick) => void;
onSetTypeFilter: (typeFilter: ValidSearchType | undefined) => void;
- results: SearchResult[];
+ onTypeFilterChange: () => void;
+ onVisibleResultCountChange: (count: number) => void;
+ results: FtsSearchResult[];
searchQuery: string;
typeFilter: ValidSearchType | undefined;
}
@@ -60,7 +65,17 @@ interface LocalGenerationTopicResult {
* Search results from unified search index.
*/
const SearchResults = memo<SearchResultsProps>(
- ({ isLoading, onClose, onSetTypeFilter, results, searchQuery, typeFilter }) => {
+ ({
+ isLoading,
+ onClose,
+ onResultClick,
+ onSetTypeFilter,
+ onTypeFilterChange,
+ onVisibleResultCountChange,
+ results,
+ searchQuery,
+ typeFilter,
+ }) => {
const { t } = useTranslation('common');
const { t: tImage } = useTranslation('image');
const { t: tVideo } = useTranslation('video');
@@ -71,7 +86,8 @@ const SearchResults = memo<SearchResultsProps>(
const videoTopics = useVideoStore(videoGenerationTopicSelectors.generationTopics);
const activeVideoTopicId = useVideoStore((s) => s.activeGenerationTopicId);
- const handleNavigate = (result: SearchResult) => {
+ const handleNavigate = (result: FtsSearchResult, position: number) => {
+ onResultClick({ position, resultType: result.type });
switch (result.type) {
case 'agent': {
navigate(`/agent/${result.id}?agent=${result.id}`);
@@ -158,7 +174,7 @@ const SearchResults = memo<SearchResultsProps>(
onClose();
};
- const getIcon = (type: SearchResult['type']) => {
+ const getIcon = (type: FtsSearchResult['type']) => {
switch (type) {
case 'agent': {
return <Sparkles size={16} />;
@@ -199,7 +215,7 @@ const SearchResults = memo<SearchResultsProps>(
}
};
- const getTypeLabel = (type: SearchResult['type']) => {
+ const getTypeLabel = (type: FtsSearchResult['type']) => {
switch (type) {
case 'agent': {
return t('cmdk.search.agent');
@@ -240,14 +256,14 @@ const SearchResults = memo<SearchResultsProps>(
}
};
- const getItemValue = (result: SearchResult) => {
+ const getItemValue = (result: FtsSearchResult) => {
const meta = [result.title, result.description].filter(Boolean).join(' ');
// Prefix with "search-result" to ensure these items rank after built-in commands
// Include ID to ensure uniqueness when multiple items have the same title
return `search-result ${result.type} ${result.id} ${meta}`.trim();
};
- const getDescription = (result: SearchResult) => {
+ const getDescription = (result: FtsSearchResult) => {
if (!result.description) return null;
// Sanitize markdown content for message search results
if (result.type === 'message') {
@@ -256,7 +272,7 @@ const SearchResults = memo<SearchResultsProps>(
return result.description;
};
- const getSubtitle = (result: SearchResult): ReactNode => {
+ const getSubtitle = (result: FtsSearchResult): ReactNode => {
const description = getDescription(result);
// Topic results: prefix with agent identity (avatar + title) so users can
@@ -304,6 +320,7 @@ const SearchResults = memo<SearchResultsProps>(
};
const handleSearchMore = (type: ValidSearchType) => {
+ onTypeFilterChange();
onSetTypeFilter(type);
};
@@ -366,6 +383,29 @@ const SearchResults = memo<SearchResultsProps>(
const pluginResults = results.filter((r) => r.type === 'plugin');
const knowledgeBaseResults = results.filter((r) => r.type === 'knowledgeBase');
const assistantResults = results.filter((r) => r.type === 'communityAgent');
+ const localResultCount = localImageTopicResults.length + localVideoTopicResults.length;
+ const visibleResultPositions = createVisibleResultPositionMap<FtsSearchResult>(
+ [
+ messageResults,
+ agentResults,
+ chatGroupResults,
+ topicResults,
+ pageResults,
+ memoryResults,
+ fileResults,
+ folderResults,
+ knowledgeBaseResults,
+ mcpResults,
+ pluginResults,
+ assistantResults,
+ ],
+ localResultCount,
+ );
+ const visibleResultCount = localResultCount + visibleResultPositions.size;
+
+ useLayoutEffect(() => {
+ onVisibleResultCountChange(visibleResultCount);
+ }, [onVisibleResultCountChange, visibleResultCount]);
// Don't render anything if no results and not loading — except in the
// unfiltered view, which always carries the permanent marketplace entries
@@ -376,7 +416,7 @@ const SearchResults = memo<SearchResultsProps>(
}
// Render a single result item with type prefix (like "Message > content")
- const renderResultItem = (result: SearchResult) => {
+ const renderResultItem = (result: FtsSearchResult) => {
const typeLabel = getTypeLabel(result.type);
const subtitle = getSubtitle(result);
@@ -411,7 +451,7 @@ const SearchResults = memo<SearchResultsProps>(
title={titleWithPrefix}
value={getItemValue(result)}
variant="detailed"
- onSelect={() => handleNavigate(result)}
+ onSelect={() => handleNavigate(result, visibleResultPositions.get(result) ?? 1)}
/>
);
};
@@ -454,7 +494,7 @@ const SearchResults = memo<SearchResultsProps>(
<>
{localImageTopicResults.length > 0 && (
<Command.Group forceMount>
- {localImageTopicResults.map((result) => {
+ {localImageTopicResults.map((result, index) => {
const formattedDate = dayjs(result.updatedAt).format('MMM D, YYYY');
return (
<CommandItem
@@ -480,6 +520,7 @@ const SearchResults = memo<SearchResultsProps>(
</>
}
onSelect={() => {
+ onResultClick({ position: index + 1, resultType: 'imageTopic' });
navigate(`/image?topic=${result.id}`);
onClose();
}}
@@ -491,7 +532,7 @@ const SearchResults = memo<SearchResultsProps>(
{localVideoTopicResults.length > 0 && (
<Command.Group forceMount>
- {localVideoTopicResults.map((result) => {
+ {localVideoTopicResults.map((result, index) => {
const formattedDate = dayjs(result.updatedAt).format('MMM D, YYYY');
return (
<CommandItem
@@ -517,6 +558,10 @@ const SearchResults = memo<SearchResultsProps>(
</>
}
onSelect={() => {
+ onResultClick({
+ position: localImageTopicResults.length + index + 1,
+ resultType: 'videoTopic',
+ });
navigate(`/video?topic=${result.id}`);
onClose();
}}
diff --git a/src/features/CommandMenu/analytics.test.ts b/src/features/CommandMenu/analytics.test.ts
new file mode 100644
index 00000000000..2cd7aabbd59
--- /dev/null
+++ b/src/features/CommandMenu/analytics.test.ts
@@ -0,0 +1,338 @@
+// @vitest-environment happy-dom
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { trackProductUsageEvent } from '@/libs/analytics/productUsageEvent';
+
+import type { CommandMenuAnalyticsInput } from './analytics';
+import { GLOBAL_SEARCH_EVENTS, useCommandMenuAnalytics } from './analytics';
+
+vi.mock('@lobechat/utils', () => ({ uuid: () => 'search-session-1' }));
+vi.mock('@/const/version', () => ({ isDesktop: false }));
+vi.mock('@/libs/analytics/productUsageEvent', () => ({
+ trackProductUsageEvent: vi.fn(),
+}));
+
+const track = vi.mocked(trackProductUsageEvent);
+let currentTime = 0;
+let frameId = 0;
+let frameCallbacks = new Map<number, FrameRequestCallback>();
+
+const baseInput: CommandMenuAnalyticsInput = {
+ enabled: true,
+ hasError: false,
+ hasResponse: false,
+ isValidating: false,
+ menuContext: 'general',
+ resultCount: 0,
+ searchQuery: '',
+ typeFilter: undefined,
+};
+
+const eventsByName = (name: string) =>
+ track.mock.calls.map(([event]) => event).filter((event) => event.name === name);
+
+const flushAnimationFrame = () => {
+ act(() => {
+ const callbacks = [...frameCallbacks.values()];
+ frameCallbacks.clear();
+ callbacks.forEach((callback) => callback(currentTime));
+ });
+};
+
+describe('Command menu search analytics', () => {
+ beforeEach(() => {
+ currentTime = 0;
+ frameId = 0;
+ frameCallbacks = new Map();
+ track.mockReset();
+ vi.spyOn(performance, 'now').mockImplementation(() => currentTime);
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ const id = ++frameId;
+ frameCallbacks.set(id, callback);
+ return id;
+ });
+ vi.stubGlobal('cancelAnimationFrame', (id: number) => frameCallbacks.delete(id));
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it('tracks an opened search session with bounded surface properties', () => {
+ renderHook(() => useCommandMenuAnalytics(baseInput));
+
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.OPENED)).toEqual([
+ {
+ name: GLOBAL_SEARCH_EVENTS.OPENED,
+ properties: {
+ menu_context: 'general',
+ platform: 'web',
+ search_session_id: 'search-session-1',
+ spm: 'command_menu.search.opened',
+ surface: 'command_menu',
+ },
+ },
+ ]);
+ });
+
+ it('opens one search session when a disabled command mode first becomes enabled', () => {
+ const { rerender } = renderHook((input) => useCommandMenuAnalytics(input), {
+ initialProps: { ...baseInput, enabled: false },
+ });
+
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.OPENED)).toHaveLength(0);
+
+ rerender({ ...baseInput, enabled: true });
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.OPENED)).toHaveLength(1);
+
+ rerender({ ...baseInput, enabled: false });
+ rerender({ ...baseInput, enabled: true });
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.OPENED)).toHaveLength(1);
+ });
+
+ it('measures from the last input through the rendered response without exposing query text', () => {
+ const secretQuery = 'private-message-search-text';
+ const { rerender, result } = renderHook((input) => useCommandMenuAnalytics(input), {
+ initialProps: baseInput,
+ });
+
+ currentTime = 100;
+ act(() => result.current.trackInputChange(secretQuery));
+ currentTime = 700;
+ rerender({ ...baseInput, isValidating: true, searchQuery: secretQuery });
+
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.QUERY_SETTLED)[0].properties).toMatchObject({
+ query_length_bucket: '21-50',
+ sequence: 1,
+ type_filter: 'all',
+ });
+
+ currentTime = 3301;
+ rerender({
+ ...baseInput,
+ hasResponse: true,
+ resultCount: 4,
+ searchQuery: secretQuery,
+ });
+ flushAnimationFrame();
+
+ const rendered = eventsByName(GLOBAL_SEARCH_EVENTS.RESULTS_RENDERED);
+ expect(rendered).toHaveLength(1);
+ expect(rendered[0].properties).toMatchObject({
+ duration_bucket: '3s-5s',
+ duration_ms: 3201,
+ result_count_bucket: '1-5',
+ status: 'success',
+ visibility_state: 'foreground',
+ });
+
+ rerender({
+ ...baseInput,
+ hasResponse: true,
+ resultCount: 5,
+ searchQuery: secretQuery,
+ });
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.RESULTS_RENDERED)).toHaveLength(1);
+ expect(JSON.stringify(track.mock.calls)).not.toContain(secretQuery);
+ });
+
+ it('tracks refinement and result clicks with buckets but no result identifier', () => {
+ const { rerender, result, unmount } = renderHook((input) => useCommandMenuAnalytics(input), {
+ initialProps: baseInput,
+ });
+
+ act(() => result.current.trackInputChange('first query'));
+ rerender({ ...baseInput, hasResponse: true, resultCount: 8, searchQuery: 'first query' });
+ flushAnimationFrame();
+
+ currentTime = 2000;
+ act(() => result.current.trackInputChange('second query'));
+ rerender({ ...baseInput, isValidating: true, searchQuery: 'second query' });
+
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.REFINED)[0].properties).toMatchObject({
+ previous_result_count_bucket: '6-10',
+ previous_status: 'success',
+ refinement_type: 'query',
+ });
+
+ currentTime = 2800;
+ rerender({ ...baseInput, hasResponse: true, resultCount: 2, searchQuery: 'second query' });
+ flushAnimationFrame();
+ currentTime = 3200;
+ act(() => result.current.trackResultClick({ position: 2, resultType: 'message' }));
+
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.RESULT_CLICKED)[0].properties).toMatchObject({
+ input_to_click_ms: 1200,
+ position_bucket: '2-3',
+ position_scope: 'visible_results',
+ render_to_click_ms: 400,
+ result_type: 'message',
+ });
+
+ unmount();
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.ABANDONED)).toHaveLength(0);
+ expect(JSON.stringify(track.mock.calls)).not.toContain('result-id');
+ });
+
+ it('records pending abandonment but ignores non-search command modes', () => {
+ const { rerender, result, unmount } = renderHook((input) => useCommandMenuAnalytics(input), {
+ initialProps: baseInput,
+ });
+
+ act(() => result.current.trackInputChange('unfinished'));
+ rerender({ ...baseInput, isValidating: true, searchQuery: 'unfinished' });
+ unmount();
+
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.ABANDONED)[0].properties).toMatchObject({
+ last_status: 'pending',
+ query_count: 1,
+ });
+
+ track.mockClear();
+ const disabled = renderHook((input) => useCommandMenuAnalytics(input), {
+ initialProps: { ...baseInput, enabled: false },
+ });
+ act(() => disabled.result.current.trackInputChange('ask an agent'));
+ disabled.rerender({
+ ...baseInput,
+ enabled: false,
+ hasResponse: true,
+ resultCount: 1,
+ searchQuery: 'ask an agent',
+ });
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.OPENED)).toHaveLength(0);
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.QUERY_SETTLED)).toHaveLength(0);
+ });
+
+ it('keeps the latest pending query when a completed search is cleared before closing', () => {
+ const { rerender, result, unmount } = renderHook((input) => useCommandMenuAnalytics(input), {
+ initialProps: baseInput,
+ });
+
+ act(() => result.current.trackInputChange('completed query'));
+ rerender({ ...baseInput, hasResponse: true, resultCount: 8, searchQuery: 'completed query' });
+ flushAnimationFrame();
+
+ currentTime = 1000;
+ act(() => result.current.trackInputChange('pending query'));
+ rerender({ ...baseInput, isValidating: true, searchQuery: 'pending query' });
+
+ act(() => result.current.trackInputChange(''));
+ rerender(baseInput);
+ unmount();
+
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.ABANDONED)[0].properties).toMatchObject({
+ last_result_count_bucket: '0',
+ last_status: 'pending',
+ query_count: 2,
+ });
+ });
+
+ it('counts the same query again after the cleared query reaches the search state', () => {
+ const { rerender, result } = renderHook((input) => useCommandMenuAnalytics(input), {
+ initialProps: baseInput,
+ });
+
+ act(() => result.current.trackInputChange('same query'));
+ rerender({ ...baseInput, hasResponse: true, resultCount: 3, searchQuery: 'same query' });
+ flushAnimationFrame();
+
+ act(() => result.current.trackInputChange(''));
+ rerender(baseInput);
+
+ currentTime = 1000;
+ act(() => result.current.trackInputChange('same query'));
+ rerender({ ...baseInput, isValidating: true, searchQuery: 'same query' });
+
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.QUERY_SETTLED)).toHaveLength(2);
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.QUERY_SETTLED)[1].properties).toMatchObject({
+ is_refinement: true,
+ sequence: 2,
+ });
+ });
+
+ it('keeps observing an active request after a whitespace-only edit', () => {
+ const { rerender, result } = renderHook((input) => useCommandMenuAnalytics(input), {
+ initialProps: baseInput,
+ });
+
+ currentTime = 100;
+ act(() => result.current.trackInputChange('same query'));
+ currentTime = 700;
+ rerender({ ...baseInput, isValidating: true, searchQuery: 'same query' });
+
+ currentTime = 900;
+ act(() => result.current.trackInputChange('same query '));
+ currentTime = 3400;
+ rerender({ ...baseInput, hasResponse: true, resultCount: 3, searchQuery: 'same query' });
+ flushAnimationFrame();
+
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.RESULTS_RENDERED)).toHaveLength(1);
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.RESULTS_RENDERED)[0].properties).toMatchObject({
+ duration_ms: 3300,
+ status: 'success',
+ });
+ });
+
+ it('records errors and filter refinements with their actual duration boundary', () => {
+ const { rerender, result } = renderHook((input) => useCommandMenuAnalytics(input), {
+ initialProps: baseInput,
+ });
+
+ act(() => result.current.trackInputChange('first query'));
+ rerender({ ...baseInput, hasResponse: true, resultCount: 2, searchQuery: 'first query' });
+ flushAnimationFrame();
+
+ currentTime = 1000;
+ act(() => result.current.trackFilterChange());
+ rerender({
+ ...baseInput,
+ isValidating: true,
+ searchQuery: 'first query',
+ typeFilter: 'message',
+ });
+
+ currentTime = 1800;
+ rerender({
+ ...baseInput,
+ hasError: true,
+ searchQuery: 'first query',
+ typeFilter: 'message',
+ });
+ flushAnimationFrame();
+
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.REFINED)[0].properties).toMatchObject({
+ refinement_type: 'filter',
+ });
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.RESULTS_RENDERED)[1].properties).toMatchObject({
+ duration_ms: 800,
+ refinement_type: 'filter',
+ status: 'error',
+ });
+ });
+
+ it('starts timing while leaving a disabled command mode', () => {
+ const { rerender, result } = renderHook((input) => useCommandMenuAnalytics(input), {
+ initialProps: { ...baseInput, enabled: false },
+ });
+
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.OPENED)).toHaveLength(0);
+
+ currentTime = 100;
+ act(() => result.current.trackInputChange('normal search'));
+ currentTime = 700;
+ rerender({ ...baseInput, enabled: true, isValidating: true, searchQuery: 'normal search' });
+
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.OPENED)).toHaveLength(1);
+
+ currentTime = 1100;
+ rerender({ ...baseInput, enabled: true, hasResponse: true, searchQuery: 'normal search' });
+ flushAnimationFrame();
+
+ expect(eventsByName(GLOBAL_SEARCH_EVENTS.RESULTS_RENDERED)[0].properties).toMatchObject({
+ duration_ms: 1000,
+ });
+ });
+});
diff --git a/src/features/CommandMenu/analytics.ts b/src/features/CommandMenu/analytics.ts
new file mode 100644
index 00000000000..74c2907755e
--- /dev/null
+++ b/src/features/CommandMenu/analytics.ts
@@ -0,0 +1,410 @@
+import { uuid } from '@lobechat/utils';
+import { useCallback, useEffect, useRef } from 'react';
+
+import { isDesktop } from '@/const/version';
+import { useSingleton } from '@/hooks/useSingleton';
+import { trackProductUsageEvent } from '@/libs/analytics/productUsageEvent';
+
+export interface CommandMenuAnalyticsInput {
+ enabled: boolean;
+ hasError: boolean;
+ hasResponse: boolean;
+ isValidating: boolean;
+ menuContext: string;
+ resultCount: number;
+ searchQuery: string;
+ typeFilter?: string;
+}
+
+export interface CommandMenuResultClick {
+ position: number;
+ resultType: string;
+}
+
+export const GLOBAL_SEARCH_EVENTS = {
+ ABANDONED: 'search_abandoned',
+ OPENED: 'search_opened',
+ QUERY_SETTLED: 'search_query_settled',
+ REFINED: 'search_refined',
+ RESULTS_RENDERED: 'search_results_rendered',
+ RESULT_CLICKED: 'search_result_clicked',
+} as const;
+
+const GLOBAL_SEARCH_SPM = {
+ ABANDONED: 'command_menu.search.abandoned',
+ OPENED: 'command_menu.search.opened',
+ QUERY_SETTLED: 'command_menu.search.query_settled',
+ REFINED: 'command_menu.search.refined',
+ RESULTS_RENDERED: 'command_menu.search.results_rendered',
+ RESULT_CLICKED: 'command_menu.search.result_clicked',
+} as const;
+
+type SearchStatus = 'empty' | 'error' | 'pending' | 'success';
+type RefinementType = 'filter' | 'query';
+
+interface CompletedQuery {
+ durationMs: number;
+ renderedAt: number;
+ resultCount: number;
+ status: Exclude<SearchStatus, 'pending'>;
+}
+
+interface ActiveQuery {
+ clicked: boolean;
+ completed?: CompletedQuery;
+ inputRevision: number;
+ key: string;
+ refinementType: RefinementType;
+ sequence: number;
+ startedAt: number;
+ wasHidden: boolean;
+}
+
+interface LatestInput {
+ length: number;
+ refinementType: RefinementType;
+ revision: number;
+ startedAt: number;
+}
+
+interface SearchSession {
+ active?: ActiveQuery;
+ cleared: boolean;
+ clicked: boolean;
+ id: string;
+ lastCompleted?: CompletedQuery;
+ queryCount: number;
+}
+
+const bucketQueryLength = (length: number) => {
+ if (length <= 2) return '1-2';
+ if (length <= 5) return '3-5';
+ if (length <= 10) return '6-10';
+ if (length <= 20) return '11-20';
+ if (length <= 50) return '21-50';
+ return '51+';
+};
+
+const bucketResultCount = (count: number) => {
+ if (count === 0) return '0';
+ if (count <= 5) return '1-5';
+ if (count <= 10) return '6-10';
+ if (count <= 25) return '11-25';
+ if (count <= 50) return '26-50';
+ return '51+';
+};
+
+const bucketPosition = (position: number) => {
+ if (position <= 1) return '1';
+ if (position <= 3) return '2-3';
+ if (position <= 5) return '4-5';
+ if (position <= 10) return '6-10';
+ return '11+';
+};
+
+const bucketDuration = (durationMs: number) => {
+ if (durationMs <= 1000) return 'under_1s';
+ if (durationMs <= 3000) return '1s-3s';
+ if (durationMs <= 5000) return '3s-5s';
+ if (durationMs <= 10_000) return '5s-10s';
+ return 'over_10s';
+};
+
+const bucketClickDecision = (durationMs: number) => {
+ if (durationMs <= 2000) return 'under_2s';
+ if (durationMs <= 5000) return '2s-5s';
+ if (durationMs <= 15_000) return '5s-15s';
+ if (durationMs <= 60_000) return '15s-60s';
+ return 'over_60s';
+};
+
+const now = () => performance.now();
+
+/**
+ * Product analytics for one command-menu lifetime. Query text and result
+ * identifiers are used by the UI only and are never copied into event properties.
+ */
+export const useCommandMenuAnalytics = ({
+ enabled,
+ hasError,
+ hasResponse,
+ isValidating,
+ menuContext,
+ resultCount,
+ searchQuery,
+ typeFilter,
+}: CommandMenuAnalyticsInput) => {
+ const mountedAt = useSingleton(now);
+ const initialMenuContext = useRef(menuContext);
+ const latestInputRef = useRef<LatestInput>({
+ length: 0,
+ refinementType: 'query',
+ revision: 0,
+ startedAt: mountedAt,
+ });
+ const openedRef = useRef(false);
+ const sessionId = useSingleton(() => uuid());
+ const sessionRef = useRef<SearchSession>({
+ clicked: false,
+ cleared: false,
+ id: sessionId,
+ queryCount: 0,
+ });
+ const platform = isDesktop ? 'desktop' : 'web';
+ const queryKey = searchQuery ? `${searchQuery}\u0000${typeFilter ?? 'all'}` : '';
+
+ useEffect(() => {
+ if (!enabled || openedRef.current) return;
+ openedRef.current = true;
+ trackProductUsageEvent({
+ name: GLOBAL_SEARCH_EVENTS.OPENED,
+ properties: {
+ menu_context: initialMenuContext.current,
+ platform,
+ search_session_id: sessionRef.current.id,
+ spm: GLOBAL_SEARCH_SPM.OPENED,
+ surface: 'command_menu',
+ },
+ });
+ }, [enabled, platform]);
+
+ useEffect(() => {
+ const markBackgrounded = () => {
+ if (document.visibilityState === 'visible') return;
+ const active = sessionRef.current.active;
+ if (active) active.wasHidden = true;
+ };
+
+ document.addEventListener('visibilitychange', markBackgrounded);
+ return () => document.removeEventListener('visibilitychange', markBackgrounded);
+ }, []);
+
+ useEffect(() => {
+ if (!enabled) {
+ sessionRef.current.active = undefined;
+ return;
+ }
+
+ // Clearing the input does not start a new search, but abandonment still needs the last
+ // issued query rather than an earlier completed result. Once the debounced query is empty,
+ // typing the same query again is a distinct request and must get a new sequence.
+ if (!queryKey) {
+ sessionRef.current.cleared = true;
+ return;
+ }
+
+ const session = sessionRef.current;
+ if (session.active?.key === queryKey && !session.cleared) return;
+
+ const previous = session.active;
+ if (previous && !previous.clicked) {
+ trackProductUsageEvent({
+ name: GLOBAL_SEARCH_EVENTS.REFINED,
+ properties: {
+ platform,
+ previous_result_count_bucket: bucketResultCount(previous.completed?.resultCount ?? 0),
+ previous_status: previous.completed?.status ?? 'pending',
+ refinement_type: latestInputRef.current.refinementType,
+ search_session_id: session.id,
+ spm: GLOBAL_SEARCH_SPM.REFINED,
+ surface: 'command_menu',
+ },
+ });
+ }
+
+ session.queryCount += 1;
+ session.cleared = false;
+ session.active = {
+ clicked: false,
+ inputRevision: latestInputRef.current.revision,
+ key: queryKey,
+ refinementType: latestInputRef.current.refinementType,
+ sequence: session.queryCount,
+ startedAt: latestInputRef.current.startedAt,
+ wasHidden: document.visibilityState !== 'visible',
+ };
+
+ trackProductUsageEvent({
+ name: GLOBAL_SEARCH_EVENTS.QUERY_SETTLED,
+ properties: {
+ is_refinement: session.queryCount > 1,
+ menu_context: menuContext,
+ platform,
+ query_length_bucket: bucketQueryLength(latestInputRef.current.length || searchQuery.length),
+ refinement_type: latestInputRef.current.refinementType,
+ search_session_id: session.id,
+ sequence: session.queryCount,
+ spm: GLOBAL_SEARCH_SPM.QUERY_SETTLED,
+ surface: 'command_menu',
+ type_filter: typeFilter ?? 'all',
+ },
+ });
+ }, [enabled, menuContext, platform, queryKey, searchQuery.length, typeFilter]);
+
+ useEffect(() => {
+ const active = sessionRef.current.active;
+ if (
+ !enabled ||
+ !active ||
+ active.key !== queryKey ||
+ active.completed ||
+ active.inputRevision !== latestInputRef.current.revision ||
+ isValidating ||
+ (!hasResponse && !hasError)
+ ) {
+ return;
+ }
+
+ const frame = requestAnimationFrame(() => {
+ const current = sessionRef.current.active;
+ if (
+ current !== active ||
+ active.inputRevision !== latestInputRef.current.revision ||
+ active.completed
+ ) {
+ return;
+ }
+
+ const renderedAt = now();
+ const durationMs = Math.max(0, Math.round(renderedAt - active.startedAt));
+ const status = hasError ? 'error' : resultCount === 0 ? 'empty' : 'success';
+ const completed: CompletedQuery = { durationMs, renderedAt, resultCount, status };
+ active.completed = completed;
+ sessionRef.current.lastCompleted = completed;
+
+ trackProductUsageEvent({
+ name: GLOBAL_SEARCH_EVENTS.RESULTS_RENDERED,
+ properties: {
+ duration_bucket: bucketDuration(durationMs),
+ duration_ms: durationMs,
+ menu_context: menuContext,
+ platform,
+ refinement_type: active.refinementType,
+ result_count_bucket: bucketResultCount(resultCount),
+ search_session_id: sessionRef.current.id,
+ sequence: active.sequence,
+ spm: GLOBAL_SEARCH_SPM.RESULTS_RENDERED,
+ status,
+ surface: 'command_menu',
+ type_filter: typeFilter ?? 'all',
+ visibility_state: active.wasHidden ? 'backgrounded' : 'foreground',
+ },
+ });
+ });
+
+ return () => cancelAnimationFrame(frame);
+ }, [
+ enabled,
+ hasError,
+ hasResponse,
+ isValidating,
+ menuContext,
+ platform,
+ queryKey,
+ resultCount,
+ typeFilter,
+ ]);
+
+ useEffect(
+ () => () => {
+ const session = sessionRef.current;
+ if (session.clicked || session.queryCount === 0) return;
+
+ const last = session.active ? session.active.completed : session.lastCompleted;
+ trackProductUsageEvent({
+ name: GLOBAL_SEARCH_EVENTS.ABANDONED,
+ properties: {
+ last_result_count_bucket: bucketResultCount(last?.resultCount ?? 0),
+ last_status: last?.status ?? 'pending',
+ platform,
+ query_count: session.queryCount,
+ search_session_id: session.id,
+ spm: GLOBAL_SEARCH_SPM.ABANDONED,
+ surface: 'command_menu',
+ },
+ });
+ },
+ [platform],
+ );
+
+ const trackInputChange = useCallback(
+ (value: string) => {
+ const normalizedQuery = value.trim();
+ const active = sessionRef.current.active;
+ const nextKey = normalizedQuery ? `${normalizedQuery}\u0000${typeFilter ?? 'all'}` : '';
+
+ // Whitespace-only edits and quick edits reverted before the debounce fires do not issue a
+ // new request. Keep the active revision so the eventual response is still observable.
+ if (active?.key === nextKey && !sessionRef.current.cleared) {
+ latestInputRef.current = {
+ length: normalizedQuery.length,
+ refinementType: 'query',
+ revision: active.inputRevision,
+ startedAt: active.startedAt,
+ };
+ return;
+ }
+
+ latestInputRef.current = {
+ length: normalizedQuery.length,
+ refinementType: 'query',
+ revision: latestInputRef.current.revision + 1,
+ startedAt: now(),
+ };
+ },
+ [typeFilter],
+ );
+
+ const trackFilterChange = useCallback(() => {
+ latestInputRef.current = {
+ length: searchQuery.length,
+ refinementType: 'filter',
+ revision: latestInputRef.current.revision + 1,
+ startedAt: now(),
+ };
+ }, [searchQuery.length]);
+
+ const trackResultClick = useCallback(
+ ({ position, resultType }: CommandMenuResultClick) => {
+ if (!enabled) return;
+ const session = sessionRef.current;
+ const active = session.active;
+ if (!active) return;
+
+ active.clicked = true;
+ session.clicked = true;
+ const clickedAt = now();
+ const inputToClickMs = Math.max(0, Math.round(clickedAt - active.startedAt));
+ const renderToClickMs = active.completed
+ ? Math.max(0, Math.round(clickedAt - active.completed.renderedAt))
+ : undefined;
+
+ trackProductUsageEvent({
+ name: GLOBAL_SEARCH_EVENTS.RESULT_CLICKED,
+ properties: {
+ click_phase: active.completed ? 'after_latest_response' : 'before_latest_response',
+ input_to_click_bucket: bucketDuration(inputToClickMs),
+ input_to_click_ms: inputToClickMs,
+ menu_context: menuContext,
+ platform,
+ position_bucket: bucketPosition(position),
+ position_scope: 'visible_results',
+ ...(renderToClickMs === undefined
+ ? {}
+ : {
+ render_to_click_bucket: bucketClickDecision(renderToClickMs),
+ render_to_click_ms: renderToClickMs,
+ }),
+ result_type: resultType,
+ search_session_id: session.id,
+ spm: GLOBAL_SEARCH_SPM.RESULT_CLICKED,
+ surface: 'command_menu',
+ type_filter: typeFilter ?? 'all',
+ },
+ });
+ },
+ [enabled, menuContext, platform, typeFilter],
+ );
+
+ return { trackFilterChange, trackInputChange, trackResultClick };
+};
diff --git a/src/features/CommandMenu/components/CommandInput.tsx b/src/features/CommandMenu/components/CommandInput.tsx
index ddad4d30e82..9cd081c8102 100644
--- a/src/features/CommandMenu/components/CommandInput.tsx
+++ b/src/features/CommandMenu/components/CommandInput.tsx
@@ -15,7 +15,12 @@ import { styles } from '../styles';
import { useCommandMenu } from '../useCommandMenu';
import { type ValidSearchType } from '../utils/queryParser';
-const CommandInput = memo(() => {
+interface CommandInputProps {
+ onInputChange: (value: string) => void;
+ onTypeFilterChange: () => void;
+}
+
+const CommandInput = memo<CommandInputProps>(({ onInputChange, onTypeFilterChange }) => {
const { t } = useTranslation('common');
const { handleBack } = useCommandMenu();
@@ -84,7 +89,10 @@ const CommandInput = memo(() => {
<Tag
className={styles.backTag}
icon={<X size={12} />}
- onClick={() => setTypeFilter(undefined)}
+ onClick={() => {
+ onTypeFilterChange();
+ setTypeFilter(undefined);
+ }}
>
{getTypeLabel(typeFilter)}
</Tag>
@@ -117,7 +125,10 @@ const CommandInput = memo(() => {
maxLength={500}
placeholder={getPlaceholder()}
value={search}
- onValueChange={setSearch}
+ onValueChange={(value) => {
+ onInputChange(value);
+ setSearch(value);
+ }}
/>
{page !== 'ask-ai' && !hasSelectedAgent && search.trim() ? (
<>
diff --git a/src/features/CommandMenu/index.tsx b/src/features/CommandMenu/index.tsx
index e4cb33a392a..b8d50fa789f 100644
--- a/src/features/CommandMenu/index.tsx
+++ b/src/features/CommandMenu/index.tsx
@@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next';
import { useActiveLocation } from '@/hooks/useActiveLocation';
import { useGlobalStore } from '@/store/global';
+import { useCommandMenuAnalytics } from './analytics';
import AskAgentCommands from './AskAgentCommands';
import AskAIMenu from './AskAIMenu';
import { CommandMenuProvider, useCommandMenuContext } from './CommandMenuContext';
@@ -29,6 +30,11 @@ interface CommandMenuContentProps {
onClose: () => void;
}
+interface VisibleSearchResults {
+ count: number;
+ key: string;
+}
+
/**
* Inner component that uses the context
*/
@@ -38,14 +44,48 @@ const CommandMenuContent = memo<CommandMenuContentProps>(({ isClosing, onClose }
handleBack,
handleSendToSelectedAgent,
hasSearch,
+ hasSearchResponse,
isSearching,
+ isSearchValidating,
searchQuery,
+ searchError,
searchResults,
selectedAgent,
} = useCommandMenu();
- const { setPages, page, pages, search, setSearch, setTypeFilter, setSelectedAgent, typeFilter } =
- useCommandMenuContext();
+ const {
+ menuContext,
+ page,
+ pages,
+ search,
+ setPages,
+ setSearch,
+ setSelectedAgent,
+ setTypeFilter,
+ typeFilter,
+ } = useCommandMenuContext();
+ const analyticsResultKey = searchQuery ? `${searchQuery}\u0000${typeFilter ?? 'all'}` : '';
+ const [visibleSearchResults, setVisibleSearchResults] = useState<VisibleSearchResults>();
+ const handleVisibleResultCountChange = useCallback(
+ (count: number) => {
+ setVisibleSearchResults((current) => {
+ if (current?.key === analyticsResultKey && current.count === count) return current;
+ return { count, key: analyticsResultKey };
+ });
+ },
+ [analyticsResultKey],
+ );
+ const hasVisibleResultCount = visibleSearchResults?.key === analyticsResultKey;
+ const searchAnalytics = useCommandMenuAnalytics({
+ enabled: !page && !selectedAgent && !search.trimStart().startsWith('@'),
+ hasError: Boolean(searchError),
+ hasResponse: hasSearchResponse && hasVisibleResultCount,
+ isValidating: isSearchValidating,
+ menuContext,
+ resultCount: hasVisibleResultCount ? (visibleSearchResults?.count ?? 0) : 0,
+ searchQuery,
+ typeFilter,
+ });
// Ref for Command.List to control scroll position
const listRef = useRef<HTMLDivElement>(null);
@@ -129,7 +169,10 @@ const CommandMenuContent = memo<CommandMenuContentProps>(({ isClosing, onClose }
}
}}
>
- <CommandInput />
+ <CommandInput
+ onInputChange={searchAnalytics.trackInputChange}
+ onTypeFilterChange={searchAnalytics.trackFilterChange}
+ />
<Command.List ref={listRef}>
{/* Hide cmdk's Empty when we have search results or are loading them,
@@ -184,7 +227,10 @@ const CommandMenuContent = memo<CommandMenuContentProps>(({ isClosing, onClose }
searchQuery={searchQuery}
typeFilter={typeFilter}
onClose={onClose}
+ onResultClick={searchAnalytics.trackResultClick}
onSetTypeFilter={setTypeFilter}
+ onTypeFilterChange={searchAnalytics.trackFilterChange}
+ onVisibleResultCountChange={handleVisibleResultCountChange}
/>
)}
</Command.List>
diff --git a/src/features/CommandMenu/useCommandMenu.ts b/src/features/CommandMenu/useCommandMenu.ts
index 0d696e7e2e9..f51b8044e23 100644
--- a/src/features/CommandMenu/useCommandMenu.ts
+++ b/src/features/CommandMenu/useCommandMenu.ts
@@ -4,7 +4,7 @@ import { useCallback, useEffect } from 'react';
import useSWR from 'swr';
import { isDesktop } from '@/const/version';
-import { type SearchResult } from '@/database/repositories/search';
+import type { FtsSearchResult } from '@/database/repositories/ftsSearch';
import { useCreateMenuItems } from '@/features/HomeSidebar/hooks';
import { useCreateNewModal } from '@/features/LibraryModal';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
@@ -61,7 +61,12 @@ export const useCommandMenu = () => {
const hasSearch = debouncedSearch.trim().length > 0;
const searchQuery = debouncedSearch.trim();
- const { data: searchResults, isLoading: isSearching } = useSWR<SearchResult[]>(
+ const {
+ data: searchResults,
+ error: searchError,
+ isLoading: isSearching,
+ isValidating: isSearchValidating,
+ } = useSWR<FtsSearchResult[]>(
hasSearch ? ['search', searchQuery, agentId, typeFilter] : null,
async () => {
const locale = globalHelpers.getCurrentLanguage();
@@ -232,15 +237,18 @@ export const useCommandMenu = () => {
handleSendToSelectedAgent,
handleThemeChange,
hasSearch,
+ hasSearchResponse: searchResults !== undefined,
isSearching,
+ isSearchValidating,
mounted,
open,
page,
pages,
pathname,
search,
+ searchError,
searchQuery,
- searchResults: searchResults || ([] as SearchResult[]),
+ searchResults: searchResults || ([] as FtsSearchResult[]),
selectedAgent,
setSearch,
setSelectedAgent,
diff --git a/src/features/CommandMenu/utils/visibleResultPosition.test.ts b/src/features/CommandMenu/utils/visibleResultPosition.test.ts
new file mode 100644
index 00000000000..0de78d4d312
--- /dev/null
+++ b/src/features/CommandMenu/utils/visibleResultPosition.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest';
+
+import { createVisibleResultPositionMap } from './visibleResultPosition';
+
+describe('createVisibleResultPositionMap', () => {
+ it('uses final visible group order instead of the server array order', () => {
+ const firstServerResult = { id: 'agent-1' };
+ const secondServerResult = { id: 'message-1' };
+
+ const positions = createVisibleResultPositionMap(
+ [[secondServerResult], [firstServerResult]],
+ 2,
+ );
+
+ expect(positions.get(secondServerResult)).toBe(3);
+ expect(positions.get(firstServerResult)).toBe(4);
+ });
+});
diff --git a/src/features/CommandMenu/utils/visibleResultPosition.ts b/src/features/CommandMenu/utils/visibleResultPosition.ts
new file mode 100644
index 00000000000..57805636778
--- /dev/null
+++ b/src/features/CommandMenu/utils/visibleResultPosition.ts
@@ -0,0 +1,12 @@
+export const createVisibleResultPositionMap = <T>(groups: T[][], offset = 0) => {
+ const positions = new Map<T, number>();
+ let position = offset;
+
+ for (const group of groups) {
+ for (const result of group) {
+ positions.set(result, ++position);
+ }
+ }
+
+ return positions;
+};