@openreachtech/hora-skills-ort-renchan 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.ja.md +135 -0
- package/README.md +135 -0
- package/dist/skills/hor-agent-loop/SKILL.md +123 -0
- package/dist/skills/hor-agent-loop/references/core.md +485 -0
- package/dist/skills/hor-agent-loop/references/graphql-integration.md +178 -0
- package/dist/skills/hor-agent-loop/references/renchan-job-integration.md +368 -0
- package/dist/skills/hor-agent-loop/references/testing.md +492 -0
- package/dist/skills/hor-ai-agent-structure/SKILL.md +403 -0
- package/dist/skills/hor-ai-agent-structure/references/loop-and-actions.md +100 -0
- package/dist/skills/hor-ai-prompt-document-store/SKILL.md +220 -0
- package/dist/skills/hor-ai-prompt-document-store/references/models-and-composition.md +156 -0
- package/dist/skills/hor-backend-testing/SKILL.md +118 -0
- package/dist/skills/hor-backend-testing/references/placement-and-ordering.md +89 -0
- package/dist/skills/hor-backend-testing/references/purity-and-mocks.md +82 -0
- package/dist/skills/hor-backend-testing/references/running-tests.md +186 -0
- package/dist/skills/hor-bank-id/SKILL.md +91 -0
- package/dist/skills/hor-build-e2e-test-environment/SKILL.md +609 -0
- package/dist/skills/hor-build-e2e-test-environment/references/compose-definition.md +368 -0
- package/dist/skills/hor-build-e2e-test-environment/references/edge-and-proxy.md +287 -0
- package/dist/skills/hor-build-e2e-test-environment/references/environment-and-ports.md +201 -0
- package/dist/skills/hor-build-e2e-test-environment/references/runner-and-lifecycle.md +330 -0
- package/dist/skills/hor-build-e2e-test-environment/references/seed-data.md +145 -0
- package/dist/skills/hor-build-e2e-test-environment/references/windows-runner.md +146 -0
- package/dist/skills/hor-constant-definition/SKILL.md +139 -0
- package/dist/skills/hor-cookie-authentication/SKILL.md +33 -0
- package/dist/skills/hor-cookie-authentication/references/auth-filter.md +55 -0
- package/dist/skills/hor-cookie-authentication/references/cookie-context.md +53 -0
- package/dist/skills/hor-cookie-authentication/references/dev-login-seeder.md +22 -0
- package/dist/skills/hor-cookie-authentication/references/environment.md +64 -0
- package/dist/skills/hor-cookie-authentication/references/error-codes.md +24 -0
- package/dist/skills/hor-cookie-authentication/references/migrations.md +18 -0
- package/dist/skills/hor-cookie-authentication/references/resolvers.md +97 -0
- package/dist/skills/hor-cookie-authentication/references/session-clerk.md +41 -0
- package/dist/skills/hor-cookie-authentication/references/token-models.md +125 -0
- package/dist/skills/hor-database-design/SKILL.md +54 -0
- package/dist/skills/hor-database-design/references/column-types.md +92 -0
- package/dist/skills/hor-database-design/references/datetimes.md +88 -0
- package/dist/skills/hor-database-design/references/master-tables.md +117 -0
- package/dist/skills/hor-database-design/references/normalization.md +40 -0
- package/dist/skills/hor-database-design/references/update-history.md +35 -0
- package/dist/skills/hor-execution-placement-pattern/SKILL.md +216 -0
- package/dist/skills/hor-external-api-client/SKILL.md +99 -0
- package/dist/skills/hor-external-api-client/references/architecture.md +127 -0
- package/dist/skills/hor-external-api-client/references/authorization.md +105 -0
- package/dist/skills/hor-external-api-client/references/capsule.md +130 -0
- package/dist/skills/hor-external-api-client/references/conventions.md +68 -0
- package/dist/skills/hor-external-api-client/references/launcher.md +138 -0
- package/dist/skills/hor-external-api-client/references/payload.md +176 -0
- package/dist/skills/hor-external-api-client/references/sdk-wrapper.md +291 -0
- package/dist/skills/hor-external-api-client/references/testing.md +130 -0
- package/dist/skills/hor-external-api-client/references/usage.md +152 -0
- package/dist/skills/hor-graphql-schema/SKILL.md +360 -0
- package/dist/skills/hor-graphql-server-engine/SKILL.md +356 -0
- package/dist/skills/hor-light-rag/SKILL.md +242 -0
- package/dist/skills/hor-light-rag/references/retrieval-internals.md +143 -0
- package/dist/skills/hor-multi-llm-provider/SKILL.md +288 -0
- package/dist/skills/hor-multi-llm-provider/references/provider-internals.md +153 -0
- package/dist/skills/hor-mutation-resolver/SKILL.md +360 -0
- package/dist/skills/hor-mutation-resolver/references/dependency-injection.md +148 -0
- package/dist/skills/hor-mutation-resolver/references/errors.md +120 -0
- package/dist/skills/hor-mutation-resolver/references/resolve-flow.md +275 -0
- package/dist/skills/hor-mutation-resolver/references/testing.md +125 -0
- package/dist/skills/hor-mutation-resolver/references/transaction.md +197 -0
- package/dist/skills/hor-post-worker/SKILL.md +320 -0
- package/dist/skills/hor-query-resolver/SKILL.md +246 -0
- package/dist/skills/hor-query-resolver/references/anatomy.md +384 -0
- package/dist/skills/hor-query-resolver/references/data-access.md +248 -0
- package/dist/skills/hor-query-resolver/references/errors-and-context.md +172 -0
- package/dist/skills/hor-query-resolver/references/testing.md +241 -0
- package/dist/skills/hor-renchan-job-bullmq/SKILL.md +178 -0
- package/dist/skills/hor-renchan-job-bullmq/references/daemon-and-scheduler.md +182 -0
- package/dist/skills/hor-renchan-job-bullmq/references/engine-and-infra.md +106 -0
- package/dist/skills/hor-renchan-job-bullmq/references/job-triple.md +189 -0
- package/dist/skills/hor-renchan-job-bullmq/references/queues.md +74 -0
- package/dist/skills/hor-renchan-job-bullmq/references/subscriptions.md +113 -0
- package/dist/skills/hor-resolver-share/SKILL.md +262 -0
- package/dist/skills/hor-resolver-validator/SKILL.md +194 -0
- package/dist/skills/hor-resolver-validator/references/inspector-api.md +115 -0
- package/dist/skills/hor-resolver-validator/references/validator-pattern.md +281 -0
- package/dist/skills/hor-restfulapi-architecture/SKILL.md +275 -0
- package/dist/skills/hor-restfulapi-architecture/references/engine-and-context.md +192 -0
- package/dist/skills/hor-restfulapi-architecture/references/renderers.md +204 -0
- package/dist/skills/hor-restfulapi-architecture/references/response-and-flusher.md +118 -0
- package/dist/skills/hor-restfulapi-architecture/references/validation.md +229 -0
- package/dist/skills/hor-security-audit/SKILL.md +110 -0
- package/dist/skills/hor-security-audit/references/application-surface.md +90 -0
- package/dist/skills/hor-security-audit/references/auth-and-transport.md +147 -0
- package/dist/skills/hor-security-audit/references/code-safety.md +74 -0
- package/dist/skills/hor-security-audit/references/dependencies.md +72 -0
- package/dist/skills/hor-security-audit/references/network-and-logging.md +56 -0
- package/dist/skills/hor-security-audit/references/secrets.md +95 -0
- package/dist/skills/hor-sequelize-migration/SKILL.md +336 -0
- package/dist/skills/hor-sequelize-migration/references/alter-table.md +147 -0
- package/dist/skills/hor-sequelize-migration/references/foreign-keys.md +107 -0
- package/dist/skills/hor-sequelize-migration/references/indexes.md +149 -0
- package/dist/skills/hor-sequelize-migration/references/notation.md +215 -0
- package/dist/skills/hor-sequelize-model/SKILL.md +69 -0
- package/dist/skills/hor-sequelize-model/references/associations.md +218 -0
- package/dist/skills/hor-sequelize-model/references/default-methods.md +244 -0
- package/dist/skills/hor-sequelize-model/references/mixins.md +247 -0
- package/dist/skills/hor-sequelize-model/references/notation.md +225 -0
- package/dist/skills/hor-sequelize-model/references/timestamps.md +74 -0
- package/dist/skills/hor-sequelize-seeder/SKILL.md +275 -0
- package/dist/skills/hor-sequelize-seeder/references/development-coverage.md +74 -0
- package/dist/skills/hor-sequelize-seeder/references/directory-structure.md +113 -0
- package/dist/skills/hor-sequelize-seeder/references/id-numbering.md +133 -0
- package/dist/skills/hor-sequelize-seeder/references/naming.md +59 -0
- package/dist/skills/hor-sequelize-seeder/references/notation.md +170 -0
- package/dist/skills/hor-sequelize-subquery/SKILL.md +369 -0
- package/dist/skills/hor-strategy-pattern/SKILL.md +371 -0
- package/dist/skills/hor-stub-api/SKILL.md +330 -0
- package/dist/skills/hor-subscription-resolver/SKILL.md +105 -0
- package/dist/skills/hor-subscription-resolver/references/authentication.md +99 -0
- package/dist/skills/hor-subscription-resolver/references/basic-notation.md +116 -0
- package/dist/skills/hor-subscription-resolver/references/design-philosophy.md +68 -0
- package/dist/skills/hor-type-interface/SKILL.md +200 -0
- package/docs/skills.ja.md +40 -0
- package/docs/skills.md +40 -0
- package/lib/equip/CommandLineArguments.js +178 -0
- package/lib/equip/HoraSkillsCli.js +590 -0
- package/lib/equip/SkillsInstaller.js +443 -0
- package/lib/equip/SkillsManifestFile.js +260 -0
- package/lib/equip/constants/CLI_COMMAND.js +8 -0
- package/lib/equip/hora-skills-ort-renchan.js +8 -0
- package/package.json +51 -0
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hor-graphql-server-engine
|
|
3
|
+
description: >
|
|
4
|
+
Implement and wire a GraphQL server engine — a per-endpoint *GraphqlServerEngine class under
|
|
5
|
+
server/graphql/ that declares one endpoint's URL, schema path, resolver directories, Share and
|
|
6
|
+
Context DI, auth filter, middleware, scalars and error codes, then is booted in server/index.js.
|
|
7
|
+
Use whenever the user asks to add a GraphQL endpoint (a new role such as user / admin / portal),
|
|
8
|
+
pair a stub engine with an actual one, change its auth policy or public-operation allowlist, or
|
|
9
|
+
enable Redis PubSub.
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
# GraphQL Server Engine
|
|
13
|
+
|
|
14
|
+
A skill for the **`*GraphqlServerEngine` classes under `server/graphql/`**. An engine is the one
|
|
15
|
+
object that **wires a single GraphQL endpoint**: its URL and port, which schema and resolver
|
|
16
|
+
directories to load, the Share / Context dependency-injection classes, the authentication filter,
|
|
17
|
+
the Express middleware, the custom scalars, and the error-code hash. `server/index.js` then boots
|
|
18
|
+
**one HTTP server per engine** through `GraphqlServerBuilder`.
|
|
19
|
+
|
|
20
|
+
The engine sits *above* the pieces other skills build: resolvers (`hor-resolver-validator`
|
|
21
|
+
validates their input), post-workers (`hor-post-worker` run after they resolve),
|
|
22
|
+
and jobs they enqueue (`hor-renchan-job-bullmq`). This skill is about the
|
|
23
|
+
**wiring layer** that mounts all of them onto an endpoint.
|
|
24
|
+
|
|
25
|
+
> The class names, endpoints, and ports below (`CustomerGraphqlServerEngine`, `/graphql-customer`, …)
|
|
26
|
+
> are **placeholders**; the pattern is the general Renchan convention. Adapt the anchors to whatever
|
|
27
|
+
> roles your project has.
|
|
28
|
+
|
|
29
|
+
## What an engine configures (the whole surface)
|
|
30
|
+
|
|
31
|
+
An engine file is the **entry-point configuration** for one API endpoint. Everything it declares is
|
|
32
|
+
one of these settings — nothing more:
|
|
33
|
+
|
|
34
|
+
| Setting | Member | Section |
|
|
35
|
+
| --- | --- | --- |
|
|
36
|
+
| Endpoint routing (URL, schema / resolver dirs, redis) | `static get config` | [§2](#2-static-get-config--the-endpoints-routing-declaration) |
|
|
37
|
+
| Middleware (cors / json / static / upload / urlencoded) | `collectMiddleware()` | [§6](#6-middleware-scalars-error-codes) |
|
|
38
|
+
| Share / Context DI classes | `static get Share` / `static get Context` | [§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver) |
|
|
39
|
+
| Custom scalars | `collectScalars()` | [§6](#6-middleware-scalars-error-codes) |
|
|
40
|
+
| Auth policy — the **no-auth (public) operations** + the filter | `schemasToSkipFiltering` + `generateFilterHandler()` | [§4](#4-authentication-schemastoskipfiltering--generatefilterhandler) |
|
|
41
|
+
| Shared error codes | `standardErrorCodeHash` | [§6](#6-middleware-scalars-error-codes) |
|
|
42
|
+
|
|
43
|
+
**App-common settings are not repeated per engine** — they are lifted into an **app base class**
|
|
44
|
+
(`BaseAppGraphqlServerEngine`) that every engine extends ([§1](#1-two-base-classes-put-app-common-settings-in-an-app-base-and-extend-it)).
|
|
45
|
+
|
|
46
|
+
## Grand principle: one endpoint = one engine, and the engine only *declares and wires*
|
|
47
|
+
|
|
48
|
+
Each GraphQL endpoint (a role such as `user` / `admin` / `portal`) gets **exactly one engine class**.
|
|
49
|
+
The engine **holds no business logic** — no DB queries, no response building, no request handling. It
|
|
50
|
+
is a thin **declaration + composition** object: routing config, DI wiring (`Share` / `Context`),
|
|
51
|
+
and cross-cutting policy (auth filter, error mapping, scalars, middleware). All real work lives in
|
|
52
|
+
the resolvers and the context; the engine just points at them.
|
|
53
|
+
|
|
54
|
+
- **Why a class per endpoint**: each role has its own schema, its own resolver set, its own auth
|
|
55
|
+
audience, and its own port. Keeping them in separate engine classes means a role's policy changes
|
|
56
|
+
in one file, and adding a role never edits an existing engine (Open-Closed).
|
|
57
|
+
- **Why no logic in the engine**: the engine is instantiated once at boot and shared across every
|
|
58
|
+
request. Anything stateful or per-request belongs in `Context` (per request) or `Share` (per
|
|
59
|
+
process); anything domain-specific belongs in a resolver. An engine that starts doing work becomes
|
|
60
|
+
a god object that every endpoint's behavior routes through.
|
|
61
|
+
- **Extend the app base, override only what differs.** The shared middleware and error codes live in
|
|
62
|
+
the app base ([§1](#1-two-base-classes-put-app-common-settings-in-an-app-base-and-extend-it)); a concrete engine should be
|
|
63
|
+
mostly `config` + `Share` + `Context` + auth policy.
|
|
64
|
+
|
|
65
|
+
**Comment language**: the `js` examples in this SKILL.md use English comments (matching the framework
|
|
66
|
+
files). In the **engine files you generate** (`*GraphqlServerEngine.js`), keep structural comments in
|
|
67
|
+
English and any domain notes in the surrounding language of the repo — same rule the other skills use.
|
|
68
|
+
|
|
69
|
+
## 1. Two base classes: put app-common settings in an app base and extend it
|
|
70
|
+
|
|
71
|
+
There are two layers of base class. The pattern is: **the framework base defines the contract; an
|
|
72
|
+
app base holds the settings shared across your endpoints; each concrete engine extends the app base
|
|
73
|
+
and overrides only what is endpoint-specific.**
|
|
74
|
+
|
|
75
|
+
| Base | Where | Role |
|
|
76
|
+
| --- | --- | --- |
|
|
77
|
+
| `BaseGraphqlServerEngine` | `@openreachtech/renchan` | The **framework contract**: factory (`create` / `createAsync`), `buildErrorHash`, and the abstract members every engine fills in (`config`, `Share`, `Context`, `collectMiddleware`, `generateFilterHandler`, …). |
|
|
78
|
+
| `BaseAppGraphqlServerEngine` | `server/graphql/BaseAppGraphqlServerEngine.js` | **This app's shared settings** — factor here anything common to every endpoint: the shared `collectMiddleware()` (cors / json / static / upload / urlencoded) and `standardErrorCodeHash`. |
|
|
79
|
+
|
|
80
|
+
- **When a setting is the same for every endpoint, lift it into the app base.** Middleware and the
|
|
81
|
+
error-code hash are the usual ones. Each concrete engine then extends `BaseAppGraphqlServerEngine`
|
|
82
|
+
and declares only the parts that differ per endpoint — `config`, `Share`, `Context`, and the auth
|
|
83
|
+
policy. This keeps one source of truth for the shared config (Open Reach Tech's DRY / "carve once"
|
|
84
|
+
stance) and makes a new endpoint a short file.
|
|
85
|
+
- **Only override a shared member to change it** for one endpoint — e.g. the user endpoint overrides
|
|
86
|
+
`collectMiddleware()` just to raise the body limit to `30mb` ([§6](#6-middleware-scalars-error-codes)).
|
|
87
|
+
- Prefer having the app base hold the shared middleware + error codes and every engine — **stub** and
|
|
88
|
+
**actual** — extend it. If some engines still extend the framework base directly and repeat those
|
|
89
|
+
members, migrate them to the app base when you next touch an engine so the shared settings live in
|
|
90
|
+
one place.
|
|
91
|
+
|
|
92
|
+
```js
|
|
93
|
+
// Good: a new engine extends the app base and declares only the endpoint-specific parts
|
|
94
|
+
import BaseAppGraphqlServerEngine from './BaseAppGraphqlServerEngine.js'
|
|
95
|
+
import PartnerGraphqlShare from './contexts/PartnerGraphqlShare.js'
|
|
96
|
+
import PartnerGraphqlContext from './contexts/PartnerGraphqlContext.js'
|
|
97
|
+
|
|
98
|
+
export default class PartnerGraphqlServerEngine extends BaseAppGraphqlServerEngine {
|
|
99
|
+
/** @override */ static get config () { /* ... §2 ... */ }
|
|
100
|
+
/** @override */ get schemasToSkipFiltering () { /* ... §4 ... */ }
|
|
101
|
+
/** @override */ generateFilterHandler () { /* ... §4 ... */ }
|
|
102
|
+
/** @override */ static get Share () { return PartnerGraphqlShare }
|
|
103
|
+
/** @override */ static get Context () { return PartnerGraphqlContext }
|
|
104
|
+
/** @override */ async collectScalars () { /* ... §6 ... */ }
|
|
105
|
+
// collectMiddleware() / standardErrorCodeHash inherited from the app base
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## 2. `static get config` — the endpoint's routing declaration
|
|
110
|
+
|
|
111
|
+
`config` is the one place the endpoint's URL and file locations are declared. The shape is fixed
|
|
112
|
+
(`GraphqlType.Config`):
|
|
113
|
+
|
|
114
|
+
| Key | Meaning |
|
|
115
|
+
| --- | --- |
|
|
116
|
+
| `graphqlEndpoint` | The URL path this engine serves (`'/graphql-admin'`). Unique per engine. |
|
|
117
|
+
| `staticPath` | Directory served as static files (`rootPath.to('public/')`). |
|
|
118
|
+
| `schemaPath` | The `.graphql` schema file **or** a directory of them (`server/graphql/schemas/user`). |
|
|
119
|
+
| `actualResolversPath` | Directory of the real resolvers (`.../resolvers/<role>/actual/`), or `null`. |
|
|
120
|
+
| `stubResolversPath` | Directory of stub resolvers (`.../resolvers/<role>/stub/`), or `null`. |
|
|
121
|
+
| `postWorkersPath` | Directory of post-workers, or `null` when unused ([§7](#7-post-resolve-hooks-defineonresolved--postworkerspath)). |
|
|
122
|
+
| `redisOptions?` | Redis connection for subscription PubSub; omit / `null` → in-process `LocalPubSub` ([§5](#5-stub-vs-actual-engines-and-subscriptions-redis-vs-local)). |
|
|
123
|
+
|
|
124
|
+
```js
|
|
125
|
+
// Good: config is a pure routing declaration; paths via rootPath.to(), redis resolved in env
|
|
126
|
+
import { rootPath, env } from '../../app/globals/_.js'
|
|
127
|
+
|
|
128
|
+
/** @override */
|
|
129
|
+
static get config () {
|
|
130
|
+
return {
|
|
131
|
+
graphqlEndpoint: '/graphql-customer',
|
|
132
|
+
staticPath: rootPath.to('public/'),
|
|
133
|
+
schemaPath: rootPath.to('server/graphql/schemas/customer'),
|
|
134
|
+
actualResolversPath: rootPath.to('server/graphql/resolvers/customer/actual/'),
|
|
135
|
+
stubResolversPath: rootPath.to('server/graphql/resolvers/customer/stub/'),
|
|
136
|
+
postWorkersPath: rootPath.to('server/graphql/post-workers/customer/'),
|
|
137
|
+
redisOptions: {
|
|
138
|
+
host: env.REDIS_HOST,
|
|
139
|
+
port: env.REDIS_PORT,
|
|
140
|
+
},
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
- **Always resolve paths with `rootPath.to(...)`** (`app/globals/root-path.js`),
|
|
146
|
+
never hand-built relative strings.
|
|
147
|
+
- **`graphqlEndpoint` must be unique** across all engines (each maps to its own path + port in
|
|
148
|
+
`server/index.js`, [§8](#8-wiring-into-serverindexjs)).
|
|
149
|
+
- **Keep `config` a pure declaration — never put logic in the getter.** Resolve the redis connection
|
|
150
|
+
in the **`env` layer**: `env.redisOptions` returns `{ host, port }` on staging / live and `null` in
|
|
151
|
+
dev (no Redis), so the getter just references it. Dev then falls back to `LocalPubSub`; staging /
|
|
152
|
+
live opt in via environment. Do **not** branch inside `config` (`env.REDIS_HOST ? { … } : null`) —
|
|
153
|
+
a getter must return a value, not compute one.
|
|
154
|
+
|
|
155
|
+
## 3. `Share` and `Context` — the DI the engine hands to every resolver
|
|
156
|
+
|
|
157
|
+
Two static getters name the DI classes this endpoint uses. The framework instantiates them and
|
|
158
|
+
threads them into every resolver call.
|
|
159
|
+
|
|
160
|
+
- **`static get Share`** → the per-**process** shared object (`Base…GraphqlShare`). Built once at boot
|
|
161
|
+
(`createAsync`), it holds process-wide clients (`env`, the subscription `broker`, external clients,
|
|
162
|
+
a `jobDispatcherProvider`, …). This is what `hor-post-worker` reaches through
|
|
163
|
+
`context.share` to dispatch jobs.
|
|
164
|
+
- **`static get Context`** → the per-**request** object (`Base…GraphqlContext`). Built for each request
|
|
165
|
+
from the access token; it exposes the authenticated principal (`context.admin` / `context.userId`)
|
|
166
|
+
and the **visa** the auth filter reads ([§4](#4-authentication-schemastoskipfiltering--generatefilterhandler)).
|
|
167
|
+
|
|
168
|
+
```js
|
|
169
|
+
// Good: the engine only names the classes; the classes hold the DI
|
|
170
|
+
/** @override */ static get Share () { return AdminGraphqlShare }
|
|
171
|
+
/** @override */ static get Context () { return AdminGraphqlContext }
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
- **Each endpoint pairs its own Share + Context** (`Admin*` with `Admin*`); do not share one role's
|
|
175
|
+
Context with another endpoint — the principal and permissions differ.
|
|
176
|
+
- The Share / Context implementations themselves (findUser, visa issuing, extra clients) are their own
|
|
177
|
+
concern; this skill only wires them onto the engine. (See the `contexts/` classes such as
|
|
178
|
+
`AdminGraphqlContext.js` /
|
|
179
|
+
`AdminGraphqlShare.js`.)
|
|
180
|
+
|
|
181
|
+
## 4. Authentication: `schemasToSkipFiltering` + `generateFilterHandler`
|
|
182
|
+
|
|
183
|
+
Every operation on the endpoint runs through the engine's **filter handler** before its resolver —
|
|
184
|
+
**except** operations named in `schemasToSkipFiltering`. This pair *is* the endpoint's auth policy.
|
|
185
|
+
|
|
186
|
+
- **`get schemasToSkipFiltering`** → an **allowlist of public operation names** (GraphQL field names)
|
|
187
|
+
that skip the filter entirely: `signIn`, `resetPassword`, sign-up, unauthenticated public reads.
|
|
188
|
+
Default is `[]` (everything is filtered).
|
|
189
|
+
- **`generateFilterHandler()`** → returns `async ({ variables, context, information, parent }) => {}`.
|
|
190
|
+
It reads the operation name from `information.fieldName` and gates it through the request
|
|
191
|
+
`context`'s **visa**, throwing the matching error from `this.errorHash` on failure.
|
|
192
|
+
|
|
193
|
+
```js
|
|
194
|
+
// Good: the standard four-step gate (per-operation allow → authn → authz → per-schema permission)
|
|
195
|
+
/** @override */
|
|
196
|
+
get schemasToSkipFiltering () {
|
|
197
|
+
return [
|
|
198
|
+
'signIn',
|
|
199
|
+
'resetPassword',
|
|
200
|
+
'generatePasswordResetUrl',
|
|
201
|
+
'generateAccessTokenByOAuthCode',
|
|
202
|
+
]
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** @override */
|
|
206
|
+
generateFilterHandler () {
|
|
207
|
+
return async ({ variables, context, information, parent }) => {
|
|
208
|
+
const schema = information.fieldName
|
|
209
|
+
|
|
210
|
+
// A per-operation visa grant (e.g. owner of the record) short-circuits the rest.
|
|
211
|
+
if (context.canResolve({ schema })) {
|
|
212
|
+
return
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (!context.hasAuthenticated()) {
|
|
216
|
+
throw this.errorHash.Unauthenticated.create()
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if (!context.hasAuthorized()) {
|
|
220
|
+
throw this.errorHash.Unauthorized.create()
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (!context.hasSchemaPermission({ schema })) {
|
|
224
|
+
throw this.errorHash.DeniedSchemaPermission.create({ value: { schema } })
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
- **The four checks are a fixed ladder**: `canResolve` (a visa grant issued for this operation) →
|
|
231
|
+
`hasAuthenticated` (a valid principal) → `hasAuthorized` (the principal is active/allowed) →
|
|
232
|
+
`hasSchemaPermission` (this principal may call this specific operation). Each reads `context.visa`;
|
|
233
|
+
keep the order and the early returns.
|
|
234
|
+
- **`schemasToSkipFiltering` is security-critical.** An entry here is **fully public**. Only put
|
|
235
|
+
genuinely unauthenticated operations in it; never place a sensitive mutation there to "make it
|
|
236
|
+
work". Conversely, a public operation missing from the list will 401. This is exactly check #3 of
|
|
237
|
+
`hor-security-audit` — every operation authenticated unless intentionally public.
|
|
238
|
+
- **Do not do real work in the filter.** It decides allow/deny from the visa only; it must not run
|
|
239
|
+
business queries or mutate state.
|
|
240
|
+
|
|
241
|
+
```js
|
|
242
|
+
// Avoid: an empty filter on a NON-stub engine — disables auth for the whole endpoint
|
|
243
|
+
/** @override */
|
|
244
|
+
generateFilterHandler () {
|
|
245
|
+
return async () => {} // every operation now unauthenticated. Only stub engines may do this (§5).
|
|
246
|
+
}
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
## 5. Stub vs actual engines (and subscriptions: Redis vs Local)
|
|
250
|
+
|
|
251
|
+
Each role is served by **two** engines on **two ports**:
|
|
252
|
+
|
|
253
|
+
| Kind | Extends | Resolvers | Auth filter | Purpose |
|
|
254
|
+
| --- | --- | --- | --- | --- |
|
|
255
|
+
| **actual** | (app base) | `actualResolversPath` → real resolvers | the real four-step gate | production behavior |
|
|
256
|
+
| **stub** | app base | `actualResolversPath` **points at the stub dir** | `generateFilterHandler` returns a **noop** | frontend/dev fixtures without auth |
|
|
257
|
+
|
|
258
|
+
- A stub engine is a thin copy with a different `graphqlEndpoint` (`…-stub`), its
|
|
259
|
+
`actualResolversPath` set to the **stub** resolver directory, and an **auth-disabled** filter
|
|
260
|
+
(`return async () => {}`, `schemasToSkipFiltering: []`). It exists so the frontend can develop
|
|
261
|
+
against canned data. **Auth-off is acceptable only because a stub serves fake data on a separate
|
|
262
|
+
port** — never ship a stub engine's config on a real endpoint.
|
|
263
|
+
- **Subscriptions PubSub**: when `config.redisOptions` is set, progress/subscription events go through
|
|
264
|
+
**Redis PubSub** (required when a separate process — e.g. the job daemon — publishes to
|
|
265
|
+
subscribers, see `hor-renchan-job-bullmq` §4). When it is `null`, the
|
|
266
|
+
engine uses an in-process `LocalPubSub` — fine for dev and single-process endpoints. Enable Redis on
|
|
267
|
+
the endpoints whose subscriptions are fed by another process.
|
|
268
|
+
|
|
269
|
+
## 6. Middleware, scalars, error codes
|
|
270
|
+
|
|
271
|
+
The remaining overrides are cross-cutting endpoint policy:
|
|
272
|
+
|
|
273
|
+
- **`collectMiddleware()`** → the Express middleware array (cors, `express.json({ limit })`,
|
|
274
|
+
`express.static`, the upload middleware, `express.urlencoded` capturing `rawBody`). Inherit it from
|
|
275
|
+
the app base; only override to change a limit (e.g. the user endpoint raises the body limit to
|
|
276
|
+
`30mb` for uploads).
|
|
277
|
+
- **`async collectScalars()`** → the custom GraphQL scalars this endpoint exposes
|
|
278
|
+
(`DateTimeScalar`, `BigNumberScalar`). Return only what the schema uses.
|
|
279
|
+
- **`static get standardErrorCodeHash`** → maps the framework error names (`Unauthenticated`,
|
|
280
|
+
`Unauthorized`, `DeniedSchemaPermission`, `Database`, `Unknown`, `ConcreteMemberNotFound`) to this
|
|
281
|
+
app's numeric codes. Inherit from the app base; the engine's `this.errorHash` (used in §4) is built
|
|
282
|
+
from it.
|
|
283
|
+
- **`passesThoughError()`** (default: true in pre-production) lets raw errors through outside
|
|
284
|
+
production and maps them to `errorHash` codes in production — do not disable error mapping in prod.
|
|
285
|
+
|
|
286
|
+
```js
|
|
287
|
+
// Good: only override middleware to change a limit; otherwise inherit from the app base
|
|
288
|
+
/** @override */
|
|
289
|
+
collectMiddleware () {
|
|
290
|
+
return [
|
|
291
|
+
cors({ origin: '*' }),
|
|
292
|
+
express.json({ limit: '30mb' }), // this endpoint accepts large uploads
|
|
293
|
+
express.static(this.config.staticPath),
|
|
294
|
+
graphqlUploadExpressWithResolvingContentType({ maxFileSize: 10000000, maxFiles: 10 }),
|
|
295
|
+
express.urlencoded({ extended: true, verify: (req, res, body) => { req['rawBody'] = body.toString() } }),
|
|
296
|
+
]
|
|
297
|
+
}
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
## 7. Post-resolve hooks: `defineOnResolved` + `postWorkersPath`
|
|
301
|
+
|
|
302
|
+
Two ways to run something *after* a resolver returns, both wired on the engine:
|
|
303
|
+
|
|
304
|
+
- **`config.postWorkersPath`** → a directory of per-operation post-workers, auto-loaded and matched by
|
|
305
|
+
operation name. This is how `hor-post-worker` fires. `null` → post-workers never
|
|
306
|
+
run. Set it to `server/graphql/post-workers/<role>/` to enable them for the endpoint.
|
|
307
|
+
- **`defineOnResolved()`** → an **engine-wide** (all operations) after-resolve hook; default noop. Use
|
|
308
|
+
it for a cross-cutting after-hook; use a `postWorkersPath` post-worker for a **specific** operation.
|
|
309
|
+
The same "dispatch only, no heavy logic" rule as post-worker applies.
|
|
310
|
+
|
|
311
|
+
## 8. Wiring into `server/index.js`
|
|
312
|
+
|
|
313
|
+
An engine does nothing until it is booted. `server/index.js` starts **one
|
|
314
|
+
HTTP server per engine** with `GraphqlServerBuilder`, each on its own port:
|
|
315
|
+
|
|
316
|
+
```js
|
|
317
|
+
// Good: register the new engine — import it, build, and listen on a free port
|
|
318
|
+
import PartnerGraphqlServerEngine from './graphql/PartnerGraphqlServerEngine.js'
|
|
319
|
+
|
|
320
|
+
GraphqlServerBuilder.createAsync({
|
|
321
|
+
Engine: PartnerGraphqlServerEngine,
|
|
322
|
+
})
|
|
323
|
+
.then(builder =>
|
|
324
|
+
builder.buildHttpServer()
|
|
325
|
+
.listen(6000)
|
|
326
|
+
)
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
An endpoint → port layout looks like this (roles, paths, and ports are illustrative — use your own):
|
|
330
|
+
|
|
331
|
+
| Engine | `graphqlEndpoint` | Port (example) |
|
|
332
|
+
| --- | --- | --- |
|
|
333
|
+
| `CustomerGraphqlServerEngine` | `/graphql-customer` | 4000 |
|
|
334
|
+
| `StubCustomerGraphqlServerEngine` | `/graphql-customer-stub` | 4001 |
|
|
335
|
+
| `AdminGraphqlServerEngine` | `/graphql-admin` | 4100 |
|
|
336
|
+
| `StubAdminGraphqlServerEngine` | `/graphql-admin-stub` | 4101 |
|
|
337
|
+
|
|
338
|
+
- `createAsync({ Engine })` calls the engine's `createAsync`, which builds the `Share`
|
|
339
|
+
(`Share.createAsync({ config })`) and constructs the engine; `buildHttpServer().listen(port)` mounts
|
|
340
|
+
it. **Adding an endpoint = new engine file + these ~6 lines**; forgetting the second step means the
|
|
341
|
+
engine is dead code.
|
|
342
|
+
- **Pick a unique port** not already used by another engine (including any non-GraphQL engine, such
|
|
343
|
+
as a REST server).
|
|
344
|
+
- Pair the actual engine with its stub engine here too (both get their own `createAsync` + `listen`).
|
|
345
|
+
|
|
346
|
+
## Finishing checklist
|
|
347
|
+
|
|
348
|
+
- [ ] One engine per endpoint, extending the **app base** ([§1](#1-two-base-classes-put-app-common-settings-in-an-app-base-and-extend-it)); no duplicated middleware / error hash unless the endpoint truly differs.
|
|
349
|
+
- [ ] The engine is **declaration + wiring only** — no DB queries, no response building, no per-request state in the engine.
|
|
350
|
+
- [ ] `config` has a **unique `graphqlEndpoint`**, `rootPath.to(...)` paths for schema / resolvers, and `redisOptions` from `env` (or `null`) ([§2](#2-static-get-config--the-endpoints-routing-declaration)).
|
|
351
|
+
- [ ] `static get Share` / `static get Context` name **this role's own** Share + Context ([§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver)).
|
|
352
|
+
- [ ] `schemasToSkipFiltering` lists **only genuinely public** operations; the filter runs the four-step visa gate; **no real work** in the filter ([§4](#4-authentication-schemastoskipfiltering--generatefilterhandler)).
|
|
353
|
+
- [ ] A **stub** engine (if added) points `actualResolversPath` at the stub dir and uses a **noop** filter — and never leaks that config onto a real endpoint ([§5](#5-stub-vs-actual-engines-and-subscriptions-redis-vs-local)).
|
|
354
|
+
- [ ] Redis PubSub enabled on endpoints whose subscriptions are published by **another process** ([§5](#5-stub-vs-actual-engines-and-subscriptions-redis-vs-local)).
|
|
355
|
+
- [ ] `postWorkersPath` set when the endpoint needs post-workers (`null` disables them) ([§7](#7-post-resolve-hooks-defineonresolved--postworkerspath)).
|
|
356
|
+
- [ ] Engine **registered in `server/index.js`** with a unique port ([§8](#8-wiring-into-serverindexjs)).
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hor-light-rag
|
|
3
|
+
description: >
|
|
4
|
+
Add lightweight retrieval-augmented generation (RAG) for AI-agent documents in a renchan backend
|
|
5
|
+
without a vector database — a vector-first / LLM-fallback pipeline that ranks stored Document
|
|
6
|
+
rows with an offline local embedder, plus a MySQL/MariaDB BOOLEAN-mode n-gram fulltext builder
|
|
7
|
+
for keyword search. Use whenever the user asks to add or tune document retrieval for an agent,
|
|
8
|
+
generate or store embeddings, or change how background knowledge is assembled into the prompt.
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# Light RAG (vector-first / LLM-fallback document retrieval, no vector DB)
|
|
12
|
+
|
|
13
|
+
This backend does RAG "lightly" — no external vector database, no heavy embedding service. Documents live as
|
|
14
|
+
`Document` rows; a **local, offline embedder** produces small vectors stored in `DocumentEmbedding`;
|
|
15
|
+
retrieval ranks them with **in-app cosine** and falls back to an **LLM-driven id selection** when vectors
|
|
16
|
+
find nothing. A separate n-gram fulltext builder exists for generic MySQL/MariaDB keyword search.
|
|
17
|
+
|
|
18
|
+
## Grand principle: size the retrieval to the corpus — local vectors first, LLM fallback, no vector DB
|
|
19
|
+
|
|
20
|
+
For an agent's own document set (tens–hundreds of docs), a vector database is overkill. Rank a small set of
|
|
21
|
+
**offline-precomputed local vectors** with cosine in the app; only when that yields nothing, ask the model
|
|
22
|
+
to pick document ids from a metadata catalog.
|
|
23
|
+
|
|
24
|
+
- **Why a local, dependency-free embedder**: `LocalTextEmbedder` hashes word tokens + CJK n-grams into a
|
|
25
|
+
fixed 256-dim L2-normalized vector — no network, no API cost, works offline, and (being normalized)
|
|
26
|
+
cosine is just a dot product. It matches surface forms well; true semantic paraphrase is its weakness, so
|
|
27
|
+
the interface can be swapped for a real embedding provider later without changing callers.
|
|
28
|
+
- **Why vector-first, LLM-fallback**: the vector path is cheap and deterministic; it wins whenever it
|
|
29
|
+
returns a non-empty selection. Any empty result (feature disabled, no embeddings yet, all below the score
|
|
30
|
+
floor, empty token budget) falls through to the LLM fetcher, which reads a metadata-only catalog and calls
|
|
31
|
+
one constrained tool to choose ids. You get cheap-and-fast normally, model-smart when needed.
|
|
32
|
+
- **Why BASE vs DYNAMIC documents**: a `DocumentAttachmentCategory` of `BASE_KNOWLEDGE` inlines the full
|
|
33
|
+
body into every prompt (small, always-relevant docs); `DYNAMIC_DOCUMENT` puts only catalog/skill metadata
|
|
34
|
+
in the prompt and fetches the body **on demand** when selected. This keeps the prompt small while still
|
|
35
|
+
covering a large dynamic corpus.
|
|
36
|
+
- **Why embeddings are offline**: generating a vector is a background job (`DocumentEmbeddingJob`), so the
|
|
37
|
+
online request only *reads* precomputed vectors — retrieval stays fast and never blocks on embedding.
|
|
38
|
+
|
|
39
|
+
## Two retrieval families (mostly independent)
|
|
40
|
+
|
|
41
|
+
| Family | What it retrieves | Where |
|
|
42
|
+
| --- | --- | --- |
|
|
43
|
+
| **Document RAG** (this skill's core) | agent documents (`Document` bodies) for background knowledge | `DynamicDocumentVectorSelector` + `DynamicDocumentsBackgroundKnowledgeFetcher`, meeting at `AiAgentBaseKnowledgeAssembler` |
|
|
44
|
+
| **N-gram fulltext** | generic keyword rows via `MATCH ... AGAINST` | `NgramSearchWordGenerator` + `FullTextSearchConditionGenerator` |
|
|
45
|
+
|
|
46
|
+
> Record search over CRM data (not documents) goes through Elasticsearch
|
|
47
|
+
> (`app/ReplicaFragments/OriginObjectReplicaFragmentClient.js`) and is a **separate subsystem** — see the
|
|
48
|
+
> `hor-ai-agent-structure` skill's execute step. Because *document* search is not on Elasticsearch and there is no
|
|
49
|
+
> tokenized-document table, the document-RAG path deliberately uses pure local cosine (no lexical/RRF
|
|
50
|
+
> channel).
|
|
51
|
+
|
|
52
|
+
## 1. Offline embedding — `LocalTextEmbedder` + `DocumentEmbeddingJob`
|
|
53
|
+
|
|
54
|
+
`LocalTextEmbedder` (in `app/tools/embedding/`) is self-contained (no imports):
|
|
55
|
+
|
|
56
|
+
- `DIMENSION = 256`, `MODEL_VERSION = 'local-hash-ngram-v1'` (persisted with each vector to guard drift).
|
|
57
|
+
- `#generateTokens(text)` — NFKC-lowercase, then three token sets: word tokens (`w:`), CJK ideograph
|
|
58
|
+
unigrams (`u:`), and 2/3-gram character grams (`g:`).
|
|
59
|
+
- `#generateEmbedding(text)` — bucket tokens by `FNV-1a hash % 256`, count collisions, L2-normalize →
|
|
60
|
+
`Float32Array`.
|
|
61
|
+
- `#calculateCosineSimilarity(a, b)` — dot product (vectors are pre-normalized).
|
|
62
|
+
- `.serializeVector()` / `.deserializeVector()` — JSON ↔ `Float32Array`.
|
|
63
|
+
|
|
64
|
+
`DocumentEmbeddingJob` (a renchan-job-bullmq job; see that skill) generates vectors ahead of time:
|
|
65
|
+
|
|
66
|
+
```js
|
|
67
|
+
async execute (payload) {
|
|
68
|
+
const document = await this.findDocument(payload)
|
|
69
|
+
const sourceText = this.generateEmbeddingSourceText({ document }) // name + description + content
|
|
70
|
+
const vector = this.embedder.generateEmbedding(sourceText)
|
|
71
|
+
|
|
72
|
+
return DocumentEmbedding.upsert(
|
|
73
|
+
{
|
|
74
|
+
DocumentId: document.id,
|
|
75
|
+
embedding: LocalTextEmbedder.serializeVector(vector),
|
|
76
|
+
embeddingModelVersion: LocalTextEmbedder.MODEL_VERSION,
|
|
77
|
+
embeddingDimension: LocalTextEmbedder.DIMENSION,
|
|
78
|
+
savedAt: this.generateCurrentDatetime(),
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
conflictFields: ['document_id'],
|
|
82
|
+
}
|
|
83
|
+
)
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
The online selector only *reads* `DocumentEmbedding`; it never embeds documents.
|
|
88
|
+
|
|
89
|
+
## 2. Vector path — `DynamicDocumentVectorSelector`
|
|
90
|
+
|
|
91
|
+
The primary retrieval. Constants: `TOP_K = 8`, `MINIMUM_VECTOR_SCORE = 0.01`,
|
|
92
|
+
`DEFAULT_MAX_TOTAL_TOKEN_COUNT = 50000` (overridable by env). The pass returns `''` at any empty step so the
|
|
93
|
+
assembler can fall back:
|
|
94
|
+
|
|
95
|
+
1. `#extractEligibleDocumentPrimaryKeys(...)` — the agent's DYNAMIC assignments whose document has a
|
|
96
|
+
COMPLETE skill-generation outcome; `''` if none.
|
|
97
|
+
2. `#loadDocumentEmbeddings(...)` — `DocumentEmbedding` rows for those ids; `''` if none.
|
|
98
|
+
3. `queryVector = this.embedder.generateEmbedding(taskInstructionText)`.
|
|
99
|
+
4. `#generateVectorScores(...)` — cosine of the query vs each stored vector.
|
|
100
|
+
5. rank desc → `.filter(score >= MINIMUM_VECTOR_SCORE)` → `.slice(0, TOP_K)`; `''` if empty.
|
|
101
|
+
6. `#loadDocumentTokenCounts(...)` — estimate tokens per doc (whitespace split of name+description+content).
|
|
102
|
+
7. `#limitDocumentPrimaryKeysToTokenBudget(...)` — greedy accumulate within the budget (always keep the
|
|
103
|
+
single top-ranked doc even if it alone exceeds it); `''` if empty.
|
|
104
|
+
8. `#fetchPrefetchedDynamicDocumentsPayload(...)` — `RetrieveDynamicDocumentsProcessor.process(...)` → the
|
|
105
|
+
documents-by-id XML.
|
|
106
|
+
|
|
107
|
+
The token-budget reduce:
|
|
108
|
+
|
|
109
|
+
```js
|
|
110
|
+
const selection = rankedScores.reduce(
|
|
111
|
+
(accumulated, score) => {
|
|
112
|
+
const documentTokenCount = tokenCountByDocumentId.get(score.documentId)
|
|
113
|
+
?? 0
|
|
114
|
+
const projectedTotalTokenCount = accumulated.totalTokenCount + documentTokenCount
|
|
115
|
+
const isFirstDocument = accumulated.documentIds.length === 0
|
|
116
|
+
const shouldKeepDocument = isFirstDocument
|
|
117
|
+
|| projectedTotalTokenCount <= maxTotalTokenCount
|
|
118
|
+
|
|
119
|
+
const accumulatedWithDocument = {
|
|
120
|
+
documentIds: [
|
|
121
|
+
...accumulated.documentIds,
|
|
122
|
+
score.documentId,
|
|
123
|
+
],
|
|
124
|
+
totalTokenCount: projectedTotalTokenCount,
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return shouldKeepDocument
|
|
128
|
+
? accumulatedWithDocument
|
|
129
|
+
: accumulated
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
documentIds: [],
|
|
133
|
+
totalTokenCount: 0,
|
|
134
|
+
}
|
|
135
|
+
)
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
## 3. LLM fallback — `DynamicDocumentsBackgroundKnowledgeFetcher`
|
|
139
|
+
|
|
140
|
+
When the vector path returns `''`, the assembler calls the LLM fetcher: it builds a **metadata-only
|
|
141
|
+
catalog** (`DynamicDocumentCatalogSectionBuilder`), sends **one constrained AI turn** forcing the
|
|
142
|
+
`retrieve_dynamic_documents` tool (`isAutoHandleFunctionCall: false`,
|
|
143
|
+
`shouldPrefetchDynamicDocumentsForBackground: false` to prevent recursion), extracts and normalizes the
|
|
144
|
+
returned `documentIds`, intersects them with the eligible set (order preserved), and fetches bodies through
|
|
145
|
+
the same `RetrieveDynamicDocumentsProcessor`. The processor loads `Document` rows by id and emits
|
|
146
|
+
`<retrieve_dynamic_documents_result>` XML (id list + `{ document_id, document_title, document_body }` per
|
|
147
|
+
doc, missing ids omitted). Both paths therefore produce the **same XML shape**.
|
|
148
|
+
|
|
149
|
+
## 4. The combination seam — `AiAgentBaseKnowledgeAssembler`
|
|
150
|
+
|
|
151
|
+
`.createAsync(...)` coordinates it. It **short-circuits with an empty dynamic section unless the caller
|
|
152
|
+
sets `shouldPrefetchDynamicDocumentsForBackground: true`** (set by the AI-generation jobs / the document
|
|
153
|
+
mutation). When prefetch is on, `#resolvePrefetchedDynamicDocumentsBackgroundSectionAsync(...)` is the
|
|
154
|
+
vector-first / LLM-fallback core:
|
|
155
|
+
|
|
156
|
+
```js
|
|
157
|
+
const vectorSection = this.isDynamicDocumentVectorSelectionEnabled()
|
|
158
|
+
? await dynamicDocumentVectorSelector.fetchPrefetchedDynamicDocumentsBackgroundSectionAsync({
|
|
159
|
+
aiAgentDocumentAssignments,
|
|
160
|
+
employeeId,
|
|
161
|
+
employeeRoleIds,
|
|
162
|
+
taskInstructionText,
|
|
163
|
+
})
|
|
164
|
+
: ''
|
|
165
|
+
|
|
166
|
+
if (vectorSection.trim().length > 0) {
|
|
167
|
+
return vectorSection
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return this.fetchPrefetchedDynamicDocumentsBackgroundSectionViaLlmAsync({
|
|
171
|
+
aiAgentDocumentAssignments,
|
|
172
|
+
employeeId,
|
|
173
|
+
employeeRoleIds,
|
|
174
|
+
taskInstructionText,
|
|
175
|
+
dynamicDocumentsBackgroundKnowledgeFetcher,
|
|
176
|
+
})
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
The assembler then builds the final background block: runtime datetime + **BASE-knowledge docs (full bodies
|
|
180
|
+
inlined)** + the **dynamic-documents section** (only when the prefetched section is non-empty, CDATA-wrapped;
|
|
181
|
+
the catalog is never duplicated into the final prompt). BASE vs DYNAMIC is decided by
|
|
182
|
+
`DocumentAttachmentCategoryId === DOCUMENT_ATTACHMENT_CATEGORY.BASE_KNOWLEDGE.ID`. This background block is
|
|
183
|
+
part 1 of the composed instruction — see the **`hor-ai-prompt-document-store` skill**.
|
|
184
|
+
|
|
185
|
+
## 5. N-gram fulltext (generic keyword search)
|
|
186
|
+
|
|
187
|
+
Independent of document RAG. `NgramTextTokenizer` (uses the `ngram` package) makes 2/3-gram tokens for
|
|
188
|
+
Japanese text (detected via a CJK regex) and passes non-Japanese text through unchanged.
|
|
189
|
+
`NgramSearchWordGenerator` builds a MySQL/MariaDB BOOLEAN-mode `AGAINST` string, and
|
|
190
|
+
`FullTextSearchConditionGenerator` wraps it into a clause:
|
|
191
|
+
|
|
192
|
+
```js
|
|
193
|
+
// NgramSearchWordGenerator#formatTokenGroups: AND requires each group, OR space-joins them
|
|
194
|
+
const formattedGroups = tokenGroups.map(tokens =>
|
|
195
|
+
`(${tokens.map(token => `+${token}`).join(' ')})`
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
return this.logicalOperator === 'or'
|
|
199
|
+
? formattedGroups.join(' ')
|
|
200
|
+
: formattedGroups.map(group => `+${group}`).join(' ')
|
|
201
|
+
|
|
202
|
+
// FullTextSearchConditionGenerator#generateCondition (null when the against text is empty):
|
|
203
|
+
`MATCH (${matchColumnNames}) AGAINST ('${againstText}' IN BOOLEAN MODE)`
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
AND → `+apple +banana`; OR → `apple banana`. Use this for generic fulltext filtering, not for agent
|
|
207
|
+
document RAG.
|
|
208
|
+
|
|
209
|
+
## Models
|
|
210
|
+
|
|
211
|
+
| Model (table) | Key columns | Role |
|
|
212
|
+
| --- | --- | --- |
|
|
213
|
+
| `Document` (`documents`) | `name`, `description`, `content` (the RAG body) | the document; `BackupMixinModel` → `DocumentBk` |
|
|
214
|
+
| `DocumentEmbedding` (`document_embeddings`) | `DocumentId`, `embedding` (JSON vector), `embeddingModelVersion`, `embeddingDimension`, `savedAt` | one vector per document (upsert on `document_id`) |
|
|
215
|
+
| `DocumentAttachmentCategory` | `name`, `displayName`, `displayOrder` | `BASE_KNOWLEDGE {ID:1}` (inline body) vs `DYNAMIC_DOCUMENT {ID:2}` (catalog + on-demand body) |
|
|
216
|
+
| `AiAgentDocumentAssignment` | `AiAgentId`, `DocumentId`, `DocumentAttachmentCategoryId` (default 1), `order` | binds a document to an agent; `order` drives assembly sort |
|
|
217
|
+
|
|
218
|
+
Eligibility for the DYNAMIC path also requires a COMPLETE `DocumentSkillGenerationOutcome`. See the
|
|
219
|
+
**`hor-ai-prompt-document-store` skill** for the full model set, migrations, and seeders, and the
|
|
220
|
+
**sequelize-model / sequelize-migration skills** for how to declare them.
|
|
221
|
+
|
|
222
|
+
## Env flags
|
|
223
|
+
|
|
224
|
+
| Env var | Read at | Default | Effect |
|
|
225
|
+
| --- | --- | --- | --- |
|
|
226
|
+
| `IS_DYNAMIC_DOCUMENT_VECTOR_SELECTION_ENABLED` | `AiAgentBaseKnowledgeAssembler` | enabled (only the literal `'false'` disables) | gate the vector-first path; disabled → straight to LLM fetcher |
|
|
227
|
+
| `DYNAMIC_DOCUMENT_VECTOR_SELECTION_MAX_TOKEN_COUNT` | `DynamicDocumentVectorSelector` | `50000` (used if unset / non-finite / ≤ 0) | cap total estimated tokens of selected dynamic bodies |
|
|
228
|
+
|
|
229
|
+
## Cross-cutting rules
|
|
230
|
+
|
|
231
|
+
- **Embed offline, retrieve online** — never embed a document in the request path.
|
|
232
|
+
- **Every empty step returns `''`** so the vector→LLM fallback composes cleanly; never throw to signal
|
|
233
|
+
"nothing found".
|
|
234
|
+
- **Keep the embedder interface swappable** — callers depend on `#generateEmbedding` /
|
|
235
|
+
`#calculateCosineSimilarity`, not on the hashing internals.
|
|
236
|
+
- Return `null` / `''` for missing values, not `undefined`; one class per file, `static create()` factory.
|
|
237
|
+
|
|
238
|
+
## Detail files
|
|
239
|
+
|
|
240
|
+
- [retrieval-internals.md](./references/retrieval-internals.md) — `LocalTextEmbedder` tokenization and
|
|
241
|
+
hashing in full, the vector selector step methods, the LLM fetcher's catalog + constrained tool turn, the
|
|
242
|
+
`RetrieveDynamicDocumentsProcessor` XML, and the n-gram tokenizer / fulltext builder details.
|