@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,220 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hor-ai-prompt-document-store
|
|
3
|
+
description: >
|
|
4
|
+
Store and compose AI-agent prompts and documents from the database rather than hard-coding them
|
|
5
|
+
in a renchan backend — agent config, default and role instructions, documents, and tool schemas
|
|
6
|
+
all held as data, assembled into the runtime prompt at request time and versioned through backup
|
|
7
|
+
tables. Use whenever the user asks to add or change how agent instructions, roles, documents or
|
|
8
|
+
tools are stored, seeded, read or written, or to model the AiAgent / Document / AiTool tables.
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# AI Prompt & Document Store (DB-backed prompts, documents, and tools)
|
|
12
|
+
|
|
13
|
+
Every editable part of an AI agent — its instruction, its role, its attached documents, and its available
|
|
14
|
+
tool schemas — lives in the database, not in code. At request time a **composer** turns those rows into the
|
|
15
|
+
final prompt; edits are ordinary data changes, versioned by backup tables.
|
|
16
|
+
|
|
17
|
+
## Grand principle: prompts, documents, and tool schemas are versioned data; the prompt is composed at runtime
|
|
18
|
+
|
|
19
|
+
Nothing agent-facing is a string constant in code. The agent's `instruction` and `role` are DB columns; its
|
|
20
|
+
documents are `Document` rows linked by an assignment; its tools are JSON stored in `AiTool.payload`. A
|
|
21
|
+
`DocumentInstructionComposer` assembles the runtime prompt from these rows; every editable text has a `*Bk`
|
|
22
|
+
backup copy so history is preserved.
|
|
23
|
+
|
|
24
|
+
- **Why store prompts in the DB**: instruction/role wording changes constantly and per-agent — making it
|
|
25
|
+
data means editing it is a mutation (with history), not a deploy. Seeders provide the baseline text from
|
|
26
|
+
`constants/aiConstants.cjs`; runtime edits go through resolvers.
|
|
27
|
+
- **Why compose at runtime from parts**: a prompt is not one blob. It is **background knowledge** (RAG docs +
|
|
28
|
+
runtime datetime) + **task-specific instruction** (docs + instruction for this call) + **agent preset**
|
|
29
|
+
(the agent's own instruction). Composing these separately lets each source change independently and lets
|
|
30
|
+
RAG (see the `hor-light-rag` skill) inject only what a task needs.
|
|
31
|
+
- **Why tool schemas as `AiTool.payload` JSON**: the actions in the `hor-ai-agent-structure` skill hold only a
|
|
32
|
+
tool **id** and `JSON.parse(payload)` at runtime — so tool wording/parameters are data. Provider tools
|
|
33
|
+
(Claude web search, Gemini googleSearch) and function-declaration tools live side by side as rows.
|
|
34
|
+
- **Why `*Bk` / `*StatusPhase` history**: `.save()` on a `BackupMixinModel` copies the pre-change row into
|
|
35
|
+
its backup table, so the live row always holds the current value while every prior version is retained —
|
|
36
|
+
you get an audit trail for free (never overwrite without it).
|
|
37
|
+
|
|
38
|
+
## The store at a glance
|
|
39
|
+
|
|
40
|
+
| Concern | Where |
|
|
41
|
+
| --- | --- |
|
|
42
|
+
| Agent identity | `AiAgent` (`name`, `description`) |
|
|
43
|
+
| Agent **instruction** (preset) | `AiAgentDefaultInstruction.instruction` (TEXT) → `AiAgentDefaultInstructionBk` |
|
|
44
|
+
| Agent **role** (system prompt) | `AiAgentRoleInstruction.role` (TEXT) → `AiAgentRoleInstructionBk` |
|
|
45
|
+
| Agent model | `AiAgentDefaultModel → AiModel` (see `hor-multi-llm-provider` skill) |
|
|
46
|
+
| Agent documents | `AiAgentDocumentAssignment` → `Document` + `DocumentAttachmentCategory` |
|
|
47
|
+
| Documents | `Document.content` (+ `DocumentEmbedding` / `DocumentSkill`; see `hor-light-rag` skill) → `DocumentBk` |
|
|
48
|
+
| Agent tools | `AiAgentAvailableAiTool` → `AiTool.payload` (JSON schema) |
|
|
49
|
+
| Status / history | `AiAgentLatestStatus`+`AiAgentStatusPhase`, `DocumentLatestStatus`+`DocumentStatusPhase` |
|
|
50
|
+
|
|
51
|
+
## 1. Composing the runtime prompt — `DocumentInstructionComposer`
|
|
52
|
+
|
|
53
|
+
`.createAsync(...)` wires a `TaskSpecificInstructionGenerator` and an `AiAgentBaseKnowledgeAssembler` (the
|
|
54
|
+
light-rag seam), plus the agent's `defaultInstruction`. `#generateComposedInstruction()` joins **three
|
|
55
|
+
parts** with `\n\n`, in this order:
|
|
56
|
+
|
|
57
|
+
```js
|
|
58
|
+
generateComposedInstruction () {
|
|
59
|
+
const taskSpecificInstruction = this.taskSpecificInstructionGenerator.generateInstruction()
|
|
60
|
+
const backgroundKnowledge = this.aiAgentBaseKnowledgeAssembler.generateBackgroundKnowledge()
|
|
61
|
+
const defaultInstruction = this.generateDefaultInstruction()
|
|
62
|
+
|
|
63
|
+
return [
|
|
64
|
+
backgroundKnowledge, // 1. runtime datetime + BASE docs (inlined) + dynamic doc bodies (RAG)
|
|
65
|
+
taskSpecificInstruction, // 2. this call's documents + instruction
|
|
66
|
+
defaultInstruction, // 3. the agent preset
|
|
67
|
+
]
|
|
68
|
+
.join('\n\n')
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The parts are XML-wrapped so the model can tell them apart:
|
|
73
|
+
|
|
74
|
+
- **Part 3 — agent preset**: `<instruction><agent_preset>${defaultInstruction}</agent_preset></instruction>`.
|
|
75
|
+
- **Part 2 — task-specific** (`TaskSpecificInstructionGenerator#generateInstruction`): a `<documents>` block
|
|
76
|
+
(`<document index=N><source>…</source><content>…</content></document>`) followed by
|
|
77
|
+
`<instruction>${instruction}</instruction>`. Its documents are loaded from the DB by id
|
|
78
|
+
(`Document.findAll`) plus any one-time documents, sorted by `order`.
|
|
79
|
+
- **Part 1 — background knowledge** (`AiAgentBaseKnowledgeAssembler`): runtime datetime + BASE-knowledge
|
|
80
|
+
document bodies inlined + the dynamic-documents section (RAG) when prefetch selected any. This is the
|
|
81
|
+
`hor-light-rag` skill's output.
|
|
82
|
+
|
|
83
|
+
## 2. Exporting an agent as a document — `#generateAiAgentDocument()`
|
|
84
|
+
|
|
85
|
+
The same composer also renders a **Markdown** document (used by the export mutation), created with the three
|
|
86
|
+
generator deps `null` — only the formatting methods are used:
|
|
87
|
+
|
|
88
|
+
```
|
|
89
|
+
# AI Agent: <name>
|
|
90
|
+
|
|
91
|
+
<description>
|
|
92
|
+
|
|
93
|
+
## Default Instructions
|
|
94
|
+
|
|
95
|
+
<AiAgentDefaultInstruction.instruction>
|
|
96
|
+
|
|
97
|
+
## Attached Documents
|
|
98
|
+
|
|
99
|
+
### Document 1: <name>
|
|
100
|
+
|
|
101
|
+
*<description>*
|
|
102
|
+
|
|
103
|
+
<content>
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
`#formatAttachedDocuments()` sorts `AiAgentDocumentAssignments` by `order`, or emits "*No documents
|
|
107
|
+
attached*".
|
|
108
|
+
|
|
109
|
+
## 3. The models — prompts vs documents
|
|
110
|
+
|
|
111
|
+
All extend `BaseAppRenchanModel`, attributes via `ModelAttributeFactory` (`factory.ID_BIGINT` for
|
|
112
|
+
entities/junctions, `factory.ID_INTEGER` for small status lookups). See the **`hor-sequelize-model` skill** for
|
|
113
|
+
the declaration conventions.
|
|
114
|
+
|
|
115
|
+
**Prompt / agent:**
|
|
116
|
+
|
|
117
|
+
| Model | Key columns | Notable |
|
|
118
|
+
| --- | --- | --- |
|
|
119
|
+
| `AiAgent` | `name`, `description`, `registeredAt`, `savedAt` | hasOne `AiAgentDefaultInstruction`/`AiAgentRoleInstruction`/`AiAgentDefaultModel`/`AiAgentLatestStatus`; hasMany `AiAgentDocumentAssignment`/`AiAgentAvailableAiTool` |
|
|
120
|
+
| `AiAgentDefaultInstruction` | `AiAgentId`, `instruction` (TEXT), `savedAt` | `BackupMixinModel` → `AiAgentDefaultInstructionBk` |
|
|
121
|
+
| `AiAgentRoleInstruction` | `AiAgentId`, `role` (TEXT), `savedAt` | `BackupMixinModel` → `AiAgentRoleInstructionBk` (the system prompt) |
|
|
122
|
+
| `AiAgentDefaultModel` | `AiAgentId`, `AiModelId`, `savedAt` | model selection (`hor-multi-llm-provider` skill) |
|
|
123
|
+
| `AiAgentDocumentAssignment` | `AiAgentId`, `DocumentId`, `DocumentAttachmentCategoryId` (default 1), `order` | binds documents; BASE vs DYNAMIC + `order` |
|
|
124
|
+
| `AiAgentAvailableAiTool` | `AiAgentId`, `AiToolId`, `isEnabled`, `isDefault` | which tools the agent may use |
|
|
125
|
+
| `AiAgentDocumentInstructionRecord` | `DocumentId`, `AiAgentId`, `instruction` (TEXT) | per-document instruction override |
|
|
126
|
+
|
|
127
|
+
**Document:**
|
|
128
|
+
|
|
129
|
+
| Model | Key columns | Notable |
|
|
130
|
+
| --- | --- | --- |
|
|
131
|
+
| `Document` | `name`, `description`, `content` (TEXT, the body), `generatedAt` | `BackupMixinModel` → `DocumentBk`; hasOne `DocumentEmbedding`/`DocumentSkill` (`hor-light-rag` skill) |
|
|
132
|
+
| `DocumentAttachmentCategory` | `name`, `displayName`, `displayOrder` | `BASE_KNOWLEDGE {ID:1}` (body inlined) vs `DYNAMIC_DOCUMENT {ID:2}` (catalog only) |
|
|
133
|
+
| `DocumentSkill` | `DocumentId`, `skillName`, `skillCoverageDescription`, `contextHint` | `BackupMixinModel` → `DocumentSkillBk`; drives dynamic catalog |
|
|
134
|
+
|
|
135
|
+
**Tool:**
|
|
136
|
+
|
|
137
|
+
| Model | Key columns | Notable |
|
|
138
|
+
| --- | --- | --- |
|
|
139
|
+
| `AiTool` | `name`, `description`, `payload` (TEXT, **stringified JSON schema**), `isVisible`, `displayOrder` | no associations; loaded by PK + `JSON.parse(payload)` at runtime |
|
|
140
|
+
|
|
141
|
+
### The `*Bk` / `*StatusPhase` history pattern
|
|
142
|
+
|
|
143
|
+
`AiAgentRoleInstruction` declares `static get Mixins () { return [BackupMixinModel] }` and
|
|
144
|
+
`static get BackupModel () { return this._.AiAgentRoleInstructionBk }`. The `*Bk` model is a plain
|
|
145
|
+
`BaseAppRenchanModel` with **identical columns** and no mixin — the write-once history sink. On `.save()`
|
|
146
|
+
the mixin copies the pre-change row into `*Bk`. Same for `AiAgentDefaultInstruction`, `Document`,
|
|
147
|
+
`DocumentSkill`. A variant: `AiAgentLatestStatus` / `DocumentLatestStatus` use `BackupMixinModel` but point
|
|
148
|
+
`BackupModel` at the `*StatusPhase` table — every status change appends a phase row while the LatestStatus
|
|
149
|
+
row is mutated in place. **This is why writes use `.save()`, never `.update()`** (see the sequelize-model
|
|
150
|
+
skill).
|
|
151
|
+
|
|
152
|
+
## 4. `AiTool.payload` — tool schemas as data
|
|
153
|
+
|
|
154
|
+
Tool schemas are `JSON.stringify`-ed into `AiTool.payload` by seeders and `JSON.parse`-d at runtime:
|
|
155
|
+
|
|
156
|
+
- **Provider tools** (`sequelize/seeders/master/…-ai_tools_related.cjs`): e.g. Claude
|
|
157
|
+
`JSON.stringify({ type: 'web_search_20250305', name: 'web_search' })`, OpenAI
|
|
158
|
+
`{ type: 'web_search_preview' }`, Gemini `{ googleSearch: {} }`.
|
|
159
|
+
- **Function-calling tools** (from `constants/aiRecordSearchToolsConstants.cjs`): full
|
|
160
|
+
function-declaration objects (`{ name, description, parameters: { type, properties, required } }`)
|
|
161
|
+
stringified into `payload`, seeded with `is_visible: false` (internal forced tools — see the
|
|
162
|
+
`hor-ai-agent-structure` skill).
|
|
163
|
+
|
|
164
|
+
Runtime read (in an action): `const aiTool = await AiTool.findByPk(aiToolId); JSON.parse(aiTool.payload)`.
|
|
165
|
+
Agent↔tool binding is `AiAgentAvailableAiTool`; model↔tool availability is `AiModelToolAssignment`.
|
|
166
|
+
|
|
167
|
+
## 5. Seeders — master / dev-master / development
|
|
168
|
+
|
|
169
|
+
Three tiers under `sequelize/seeders/` (see the **sequelize-seeder skill**):
|
|
170
|
+
|
|
171
|
+
- **`master/`** — production baseline: the built-in system-worker agents and the AI-tools rows.
|
|
172
|
+
- **`dev-master/`** — the same data duplicated for the dev DB (identical filenames).
|
|
173
|
+
- **`development/`** — sample/demo rows with high fixed ids (`documents-id1000`, `ai_agents-id50000`).
|
|
174
|
+
|
|
175
|
+
Pattern: `TimestampSeedsSupplier.supplyAll(rows)` + `queryInterface.bulkInsert`; `down` = `bulkDelete` by
|
|
176
|
+
id. **Prompt text comes from `constants/aiConstants.cjs` → `DEFAULT_AI_AGENT.*`** — each entry has
|
|
177
|
+
`ID`, `NAME`, `DESCRIPTION`, `DEFAULT_INSTRUCTION` (→ `ai_agent_default_instructions.instruction`),
|
|
178
|
+
`ROLE_INSTRUCTION` (→ `ai_agent_role_instructions.role`). A single agent seeder wires ~10 tables (agent,
|
|
179
|
+
default/role instruction, latest status + status phase, default model, avatar, role category, emotional
|
|
180
|
+
level). See the **`hor-constant-definition` skill** for the `.cjs` constants rule.
|
|
181
|
+
|
|
182
|
+
## 6. Reading and writing (resolvers)
|
|
183
|
+
|
|
184
|
+
Schema `server/graphql/schemas/user/019-aiAgent.graphql` — queries `aiAgent` / `aiAgents` / `aiModels`;
|
|
185
|
+
mutations `addAiAgent` / `updateAiAgent` / `updateAiAgentStatus` / `exportAiAgentInstructionDocument` /
|
|
186
|
+
`generateDocumentByAiAgent`.
|
|
187
|
+
|
|
188
|
+
- **Read** (`AiAgentQueryResolver`): `AiAgent.findOne` with a deep `include` (LatestStatus, DefaultModel,
|
|
189
|
+
AvailableAiTool→AiTool `where isVisible`, DocumentAssignment→Document + DocumentAttachmentCategory
|
|
190
|
+
ordered by `order`, `AiAgentDefaultInstruction`, `AiAgentRoleInstruction`, …); `#formatResponse()` exposes
|
|
191
|
+
`instruction` (from `AiAgentDefaultInstruction.instruction`) and `role` (from `AiAgentRoleInstruction.role`).
|
|
192
|
+
The list resolver omits the instruction bodies. See the **`hor-query-resolver` skill**.
|
|
193
|
+
- **Write** (`AddAiAgentMutationResolver` / `UpdateAiAgentMutationResolver`): one transaction; build a nested
|
|
194
|
+
`AiAgent.build({ AiAgentDefaultInstruction: { instruction }, AiAgentRoleInstruction: { role },
|
|
195
|
+
AiAgentDocumentAssignments: [...], AiAgentDefaultModel, AiAgentLatestStatus })` with cascading `include`,
|
|
196
|
+
then bulk-create `AiAgentAvailableAiTool`. Update uses `.set(...)` + `await
|
|
197
|
+
builtAiAgent.AiAgentDefaultInstruction.save()` / `.AiAgentRoleInstruction.save()` (**these `.save()` calls
|
|
198
|
+
trigger the `*Bk` backup**), then destroy+recreate the assignment/tool rows. Verify requested tools belong
|
|
199
|
+
to the model (`AiModelToolAssignment`). See the **`hor-mutation-resolver` skill**.
|
|
200
|
+
- **Export** (`ExportAiAgentInstructionDocumentMutationResolver`): loads the agent, in a transaction calls
|
|
201
|
+
`DocumentInstructionComposer.create({ ...: null }).generateAiAgentDocument({ aiAgent })`, persists a
|
|
202
|
+
`Document` (status DRAFT), and **after commit** dispatches `DocumentEmbeddingDispatcher` +
|
|
203
|
+
`DocumentSkillSnapshotDispatcher` jobs so the exported document is indexed for later dynamic retrieval
|
|
204
|
+
(`hor-light-rag` skill; jobs via the `hor-renchan-job-bullmq` skill).
|
|
205
|
+
|
|
206
|
+
## Cross-cutting rules
|
|
207
|
+
|
|
208
|
+
- **No agent-facing text as a code constant** — instruction/role/document/tool text is DB data; baseline
|
|
209
|
+
comes from seeders.
|
|
210
|
+
- **Write editable text with `.save()` on the backup-mixin model**, never `.update()`, so history is
|
|
211
|
+
captured; wrap multi-table writes in one transaction.
|
|
212
|
+
- **Compose the prompt at runtime from the three parts** — do not concatenate a prompt by hand in a resolver.
|
|
213
|
+
- Return `null` for missing values, not `undefined`; one class per file; migrations use snake_case `field:`
|
|
214
|
+
names (see the `hor-sequelize-migration` skill).
|
|
215
|
+
|
|
216
|
+
## Detail files
|
|
217
|
+
|
|
218
|
+
- [models-and-composition.md](./references/models-and-composition.md) — every prompt/document/tool model
|
|
219
|
+
with columns and associations, the `*Bk` / `*StatusPhase` mechanics, the full composed-instruction and
|
|
220
|
+
exported-document skeletons, and the seeder wiring from `DEFAULT_AI_AGENT`.
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
# Models and composition (full)
|
|
2
|
+
|
|
3
|
+
Referenced from `SKILL.md`. The exact model shapes, the backup/history mechanics, the composed-prompt and
|
|
4
|
+
exported-document skeletons, and the seeder wiring.
|
|
5
|
+
|
|
6
|
+
## Composed runtime prompt — the three XML parts
|
|
7
|
+
|
|
8
|
+
`DocumentInstructionComposer#generateComposedInstruction()` joins with `\n\n`, in order: background
|
|
9
|
+
knowledge → task-specific → agent preset.
|
|
10
|
+
|
|
11
|
+
- **Agent preset** (`#generateDefaultInstruction()`):
|
|
12
|
+
`<instruction><agent_preset>${this.defaultInstruction}</agent_preset></instruction>`.
|
|
13
|
+
- **Task-specific** (`TaskSpecificInstructionGenerator#generateInstruction()`):
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
attached documents for this task:
|
|
17
|
+
<documents>
|
|
18
|
+
<document index=0>
|
|
19
|
+
<source>${name}</source>
|
|
20
|
+
<content>${content}</content>
|
|
21
|
+
</document>
|
|
22
|
+
</documents>
|
|
23
|
+
Instruction for this task:
|
|
24
|
+
<instruction>
|
|
25
|
+
${this.instruction}
|
|
26
|
+
</instruction>
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Documents are loaded by id (`Document.findAll({ where: { id } })`) plus one-time docs (named
|
|
30
|
+
`Additional Reference N`), sorted by `order`.
|
|
31
|
+
- **Background knowledge** (`AiAgentBaseKnowledgeAssembler#assembleCombinedBackgroundSection()`, joined with
|
|
32
|
+
`\n\n`, empties filtered):
|
|
33
|
+
- runtime datetime:
|
|
34
|
+
`<runtime_context>\n<current_datetime_iso>${iso}</current_datetime_iso>\n</runtime_context>`
|
|
35
|
+
- BASE-knowledge docs (bodies inlined) preceded by the legacy delimiter line
|
|
36
|
+
`----Please remember the content of the document below as prior knowledge, and then respond to the
|
|
37
|
+
instructions-----`, then a `<documents>…<document index=N><source>…</source><content>…</content>
|
|
38
|
+
</document>…</documents>` block.
|
|
39
|
+
- dynamic docs (only when prefetch selected any):
|
|
40
|
+
`<dynamic_documents_retrieved_for_background>\n<![CDATA[${payload}]]>\n
|
|
41
|
+
</dynamic_documents_retrieved_for_background>` — the payload is the `hor-light-rag` skill's
|
|
42
|
+
`<retrieve_dynamic_documents_result>` XML.
|
|
43
|
+
|
|
44
|
+
BASE vs DYNAMIC is decided by `DocumentAttachmentCategoryId ===
|
|
45
|
+
DOCUMENT_ATTACHMENT_CATEGORY.BASE_KNOWLEDGE.ID`.
|
|
46
|
+
|
|
47
|
+
## Exported Markdown document
|
|
48
|
+
|
|
49
|
+
`#generateAiAgentDocument({ aiAgent })` (composer built with all three deps `null`):
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
# AI Agent: <name>
|
|
53
|
+
|
|
54
|
+
<description>
|
|
55
|
+
|
|
56
|
+
## Default Instructions
|
|
57
|
+
|
|
58
|
+
<AiAgentDefaultInstruction.instruction>
|
|
59
|
+
|
|
60
|
+
## Attached Documents
|
|
61
|
+
|
|
62
|
+
### Document 1: <name>
|
|
63
|
+
|
|
64
|
+
*<description>*
|
|
65
|
+
|
|
66
|
+
<content>
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`#formatAttachedDocuments()` sorts `AiAgentDocumentAssignments` by `order`, else "*No documents attached*".
|
|
70
|
+
|
|
71
|
+
## Prompt / agent models (columns + associations)
|
|
72
|
+
|
|
73
|
+
- `AiAgent` — `name` STRING(191), `description` TEXT, `registeredAt`/`savedAt`/`lastModifiedAt`,
|
|
74
|
+
`CreatedByUserId`/`LastModifiedByUserId`. hasOne: `AiAgentLatestStatus`, `AiAgentDefaultInstruction`,
|
|
75
|
+
`AiAgentRoleInstruction`, `AiAgentAvatarUrl`, `AiAgentRoleCategory`, `AiAgentEmotionalLevel`,
|
|
76
|
+
`AiAgentDefaultModel`. hasMany: `AiAgentStatusPhase`, `AiAgentAvailableAiTool`, `AiAgentTagAssignment`,
|
|
77
|
+
`AiAgentDocumentAssignment`, `AiAgentDocumentInstructionRecord`. belongsToMany `AiAgentTag`, and `Document`
|
|
78
|
+
as `GeneratedDocuments` via `AiAgentDocumentGeneration`.
|
|
79
|
+
- `AiAgentDefaultInstruction` — `AiAgentId`, `instruction` TEXT, `savedAt`; belongsTo `AiAgent`;
|
|
80
|
+
`BackupMixinModel` → `AiAgentDefaultInstructionBk`.
|
|
81
|
+
- `AiAgentRoleInstruction` — `AiAgentId`, `role` TEXT, `savedAt`; belongsTo `AiAgent`; `BackupMixinModel` →
|
|
82
|
+
`AiAgentRoleInstructionBk`. (`role` is the provider system prompt — see the `hor-multi-llm-provider` skill's
|
|
83
|
+
payload generators.)
|
|
84
|
+
- `AiAgentDefaultModel` — `AiAgentId`, `AiModelId`, `savedAt`; belongsTo `AiAgent`, `AiModel`.
|
|
85
|
+
- `AiAgentAvailableAiTool` — `AiAgentId`, `AiToolId`, `isEnabled` BOOL, `isDefault` BOOL, `savedAt`;
|
|
86
|
+
belongsTo `AiAgent`, `AiTool`.
|
|
87
|
+
- `AiAgentDocumentAssignment` — `AiAgentId`, `DocumentId`, `DocumentAttachmentCategoryId` (default 1),
|
|
88
|
+
`order` INT, `savedAt`; belongsTo `AiAgent`, `Document`, `DocumentAttachmentCategory`.
|
|
89
|
+
- `AiAgentDocumentInstructionRecord` — `DocumentId`, `AiAgentId`, `instruction` TEXT, `savedAt`.
|
|
90
|
+
- `AiAgentStatus` — `ID_INTEGER`, `name`, `description` STRING(191); hasMany `AiAgentLatestStatus`,
|
|
91
|
+
`AiAgentStatusPhase`.
|
|
92
|
+
- `AiAgentLatestStatus` — `AiAgentId`, `AiAgentStatusId` INT, `savedAt`; belongsTo `AiAgent`,
|
|
93
|
+
`AiAgentStatus`; subquery `?AiAgentStatusId.AiAgentId`; `BackupMixinModel` → `AiAgentStatusPhase`.
|
|
94
|
+
- `AiAgentStatusPhase` — `AiAgentId`, `AiAgentStatusId` INT, `savedAt` (the status history sink).
|
|
95
|
+
|
|
96
|
+
## Document models (columns + associations)
|
|
97
|
+
|
|
98
|
+
- `Document` — `name` STRING(191), `description` TEXT, `content` TEXT (the body), `generatedAt`,
|
|
99
|
+
`savedAt`/`lastModifiedAt`, `CreatedByUserId`/`LastModifiedByUserId`. hasOne `DocumentLatestStatus`,
|
|
100
|
+
`DocumentSkill`, `DocumentSkillGenerationOutcome`, `DocumentEmbedding`; hasMany `DocumentStatusPhase`,
|
|
101
|
+
`AiAgentDocumentAssignment`, `AiAgentDocumentInstructionRecord`, `AiAgentDocumentGeneration`,
|
|
102
|
+
`AiChatRoomMessageDocumentLinkage`; `BackupMixinModel` → `DocumentBk`.
|
|
103
|
+
- `DocumentEmbedding` — `DocumentId`, `embedding` TEXT, `embeddingModelVersion` STRING(191),
|
|
104
|
+
`embeddingDimension` INT, `savedAt` (`hor-light-rag` skill).
|
|
105
|
+
- `DocumentSkill` — `DocumentId`, `skillName` STRING(191), `skillCoverageDescription` TEXT, `contextHint`
|
|
106
|
+
TEXT, `generatedAt`; `BackupMixinModel` → `DocumentSkillBk`.
|
|
107
|
+
- `DocumentAttachmentCategory` — `name`, `description`, `displayName` STRING(191), `displayOrder` INT;
|
|
108
|
+
hasMany `AiAgentDocumentAssignment`.
|
|
109
|
+
- `DocumentStatus` — `ID_INTEGER`, `name`, `description`; hasMany `DocumentLatestStatus`,
|
|
110
|
+
`DocumentStatusPhase`.
|
|
111
|
+
- `DocumentLatestStatus` — `DocumentId`, `DocumentStatusId` INT, `savedAt`; `BackupMixinModel` →
|
|
112
|
+
`DocumentStatusPhase`.
|
|
113
|
+
- `DocumentStatusPhase` — `DocumentId`, `DocumentStatusId` INT, `savedAt`.
|
|
114
|
+
|
|
115
|
+
## Tool model
|
|
116
|
+
|
|
117
|
+
- `AiTool` — `name` STRING(191), `description` STRING(191), `payload` TEXT (NOT NULL, stringified JSON
|
|
118
|
+
schema), `displayOrder` INT (default 0), `isVisible` BOOL (default true), `savedAt`; `associate()` is
|
|
119
|
+
noop. Migration `…-create_table-ai_tools.cjs` → table `ai_tools`, column `payload` TEXT NOT NULL.
|
|
120
|
+
- `AiModelToolAssignment` (join) — `AiModelId`, `AiToolId`, `savedAt` (model↔tool availability).
|
|
121
|
+
|
|
122
|
+
## The `*Bk` / `*StatusPhase` mechanics
|
|
123
|
+
|
|
124
|
+
- A backed-up model declares `static get Mixins () { return [BackupMixinModel] }` and
|
|
125
|
+
`static get BackupModel () { return this._.<Name>Bk }`. The `*Bk` model has identical columns, no mixin,
|
|
126
|
+
no `BackupModel` — the write-once sink. `.save()` copies the pre-change row into `*Bk`.
|
|
127
|
+
- Status variant: `AiAgentLatestStatus` / `DocumentLatestStatus` set `BackupModel` to the `*StatusPhase`
|
|
128
|
+
table — each change appends a phase row while the latest row is updated in place. Subqueries like
|
|
129
|
+
`?AiAgentStatusId.AiAgentId` filter agents by current status.
|
|
130
|
+
- Consequence: **always `.save()` on these models, never `.update()`** — `.update()` can bypass the mixin and
|
|
131
|
+
lose history / miss columns.
|
|
132
|
+
|
|
133
|
+
## Seeder wiring from `DEFAULT_AI_AGENT`
|
|
134
|
+
|
|
135
|
+
`constants/aiConstants.cjs` → `DEFAULT_AI_AGENT` is keyed by well-known agent; each entry:
|
|
136
|
+
`{ ID, NAME, DESCRIPTION, DEFAULT_INSTRUCTION, ROLE_INSTRUCTION }`. A master agent seeder (e.g.
|
|
137
|
+
`…-ai_agent_for_document_skill_snapshot.cjs`) `require`s it and seeds across ~10 tables in one file:
|
|
138
|
+
|
|
139
|
+
- `ai_agents` (`name`/`description` from the entry)
|
|
140
|
+
- `ai_agent_default_instructions` — `instruction: DEFAULT_AI_AGENT.<KEY>.DEFAULT_INSTRUCTION`
|
|
141
|
+
- `ai_agent_role_instructions` — `role: DEFAULT_AI_AGENT.<KEY>.ROLE_INSTRUCTION`
|
|
142
|
+
- `ai_agent_latest_statuses` + `ai_agent_status_phases` (from `AI_AGENT_STATUS`)
|
|
143
|
+
- `ai_agent_default_models` (an `AI_MODEL.*.ID`)
|
|
144
|
+
- plus `ai_agent_avatar_urls`, `ai_agent_role_categories`, `ai_agent_emotional_levels`,
|
|
145
|
+
`ai_agent_tag_assignments`
|
|
146
|
+
|
|
147
|
+
Tool seeders: `…-ai_tools_related.cjs` seeds `ai_tools` + `ai_model_tool_assignments` (Claude→Anthropic
|
|
148
|
+
models, OpenAI→OpenAI, Gemini→Google, from `AI_MODEL` provider ids); `…-ai_tools-record-search.cjs` seeds
|
|
149
|
+
`ai_tools` only, payloads from `aiRecordSearchToolsConstants.cjs`, `is_visible: false`. Document seeder
|
|
150
|
+
(`development/…-documents-id1000.cjs`) seeds `documents` (markdown `content`) then derives
|
|
151
|
+
`document_latest_statuses` + `document_status_phases` (`DOCUMENT_STATUS.ACTIVE.ID`).
|
|
152
|
+
|
|
153
|
+
Relevant limits/categories in `aiConstants.cjs`: `AI_AGENT` (`MAX_INSTRUCTION_LENGTH: 10000`,
|
|
154
|
+
`MAX_ROLE_LENGTH: 200`, `MAX_NAME_LENGTH: 50`, `MAX_DESCRIPTION_LENGTH: 500`),
|
|
155
|
+
`DOCUMENT_ATTACHMENT_CATEGORY` (`BASE_KNOWLEDGE {ID:1}` / `DYNAMIC_DOCUMENT {ID:2}`), `DOCUMENT_STATUS`,
|
|
156
|
+
`AI_AGENT_STATUS`.
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hor-backend-testing
|
|
3
|
+
description: >
|
|
4
|
+
Organize and run the backend repository's tests: where a test file goes (tests/__tests__ for
|
|
5
|
+
tests that do not write to the database, tests/_orders for tests that do), how run order among
|
|
6
|
+
DB-writing tests is guaranteed, how to run the whole suite or a single test, and the purity
|
|
7
|
+
rules for tests and their doubles. Use whenever the user asks where to place a test, how to
|
|
8
|
+
guarantee test order, how to run tests, or how to keep tests pure. Manual E2E verification is
|
|
9
|
+
out of scope.
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
# Backend Testing
|
|
13
|
+
|
|
14
|
+
A skill for **implementing tests in a backend repository**: **where** each test file belongs, **how**
|
|
15
|
+
DB-writing tests are ordered so they do not corrupt each other, **how** to run them, and the
|
|
16
|
+
**purity** rules that keep a failing test meaningful. It governs test *organization and discipline* —
|
|
17
|
+
the *writing style* of an individual test (describe/test structure, case data, naming) follows the
|
|
18
|
+
project's own Jest conventions and is out of scope here.
|
|
19
|
+
|
|
20
|
+
> This skill states a **general, project-independent rule**, not one repo's current tree. The
|
|
21
|
+
> directory names (`tests/__tests__`, `tests/_orders`, `tests/mocks`, `tests/tools`) are the
|
|
22
|
+
> **recommended layout** — map them onto your project. Sample code follows the project's lint style
|
|
23
|
+
> (no semicolons, 2-space indent, trailing commas).
|
|
24
|
+
|
|
25
|
+
## Core principle: a test fails only when the code under test is wrong
|
|
26
|
+
|
|
27
|
+
A test must fail **only** because the code it exercises is wrong — not because another test ran
|
|
28
|
+
first, and not because the test itself contains untested logic. Two rules enforce that, and
|
|
29
|
+
everything below follows from them:
|
|
30
|
+
|
|
31
|
+
1. **Isolate database state.** A test that **writes to the DB** mutates shared seed data that other
|
|
32
|
+
tests read, so it is placed **apart** from tests that don't, and **ordered** among its peers.
|
|
33
|
+
2. **Keep tests pure.** A test may only exercise code that is **itself already tested** — no logic is
|
|
34
|
+
invented inside a test, and every mock/tool it leans on has its own test cases.
|
|
35
|
+
|
|
36
|
+
## 1. Placement & execution order
|
|
37
|
+
|
|
38
|
+
Split every test by one question: **does it write to the database?**
|
|
39
|
+
|
|
40
|
+
| Location | Contents | Ordering |
|
|
41
|
+
| --- | --- | --- |
|
|
42
|
+
| `tests/__tests__/` | tests that **do not** write to the DB (pure units, read-only) | order-independent — run in any order |
|
|
43
|
+
| `tests/_orders/<Category>/` | tests that **do** write to the DB | order-**guaranteed within a category** via a `_.test.js` barrel |
|
|
44
|
+
|
|
45
|
+
- **Why the split.** A DB-writing test changes the shared `development` / `dev-master` seed fixtures,
|
|
46
|
+
so a later test can observe a mutated database. Read-only tests can't interfere, so they need no
|
|
47
|
+
ordering; DB-writing tests must be ordered.
|
|
48
|
+
- **The order barrel.** Each category folder holds `_.test.js` that **imports its test files in the
|
|
49
|
+
order they must run** — that import order *is* the execution order within the category.
|
|
50
|
+
- **Cross-category order is NOT guaranteed.** `_orders` fixes order *within* a category only. If two
|
|
51
|
+
categories can interfere, isolate them into **separate CI jobs** — add/update a
|
|
52
|
+
`.github/workflows/*.yml` per category so each runs against its own fresh database.
|
|
53
|
+
- **Verification against real middleware belongs in neither location.** Exercising the product
|
|
54
|
+
against a real broker, search cluster and change-data-capture pipeline needs those services brought
|
|
55
|
+
up in Docker and is done **by hand, outside `tests/` entirely** — see the E2E environment
|
|
56
|
+
convention. No such file is added here, and `npm run test` stays runnable with nothing but Node
|
|
57
|
+
installed.
|
|
58
|
+
|
|
59
|
+
Details, the barrel example, and the per-category workflow snippet are in
|
|
60
|
+
[placement-and-ordering.md](./references/placement-and-ordering.md).
|
|
61
|
+
|
|
62
|
+
## 2. Running tests
|
|
63
|
+
|
|
64
|
+
- **Whole suite**: `npm run test` — rebuilds the DB (teardown → migrate → seed) and runs everything on
|
|
65
|
+
**SQLite** (the local default). Authoritative, slowest.
|
|
66
|
+
- **A single test (fast, no rebuild)**: iterate by invoking Jest directly against one file —
|
|
67
|
+
`NODE_OPTIONS="--experimental-vm-modules" NODE_ENV=development npx jest <path>` (add `--runInBand`
|
|
68
|
+
for DB-writing/order-sensitive tests). It runs against the DB **as it currently is**, so prepare the
|
|
69
|
+
DB once and reset it piecemeal (migrations-only / one-seeder-set) instead of a full rebuild.
|
|
70
|
+
- **Live (real-dialect) run**: running against MariaDB instead of SQLite **requires a MariaDB
|
|
71
|
+
running locally**, selected with `NODE_ENV=live`. How that database is stood up is not part of this
|
|
72
|
+
convention.
|
|
73
|
+
- **Parallelism × per-worker heap must fit in real memory.** Jest runs one worker per core by
|
|
74
|
+
default, and `--max-old-space-size` is **not a reservation — it is how far the GC may be
|
|
75
|
+
deferred**, so a value the machine cannot actually give lets every worker grow until it crashes
|
|
76
|
+
the machine (one worker alone can do it). Derive the cap from a **measured peak**, check that
|
|
77
|
+
workers × cap fits in the memory actually free, and re-check as the project grows: per-worker
|
|
78
|
+
usage rises with every model and seeder added, so a pair that fit at the start can later crash the
|
|
79
|
+
machine.
|
|
80
|
+
|
|
81
|
+
The exact commands, the suite runner's steps, the fast single-test loop with the piecemeal DB
|
|
82
|
+
reset, and how to size the worker/heap budget are in
|
|
83
|
+
[running-tests.md](./references/running-tests.md).
|
|
84
|
+
|
|
85
|
+
## 3. Test purity & test doubles
|
|
86
|
+
|
|
87
|
+
- **No new logic in a test.** Never define a function or class inside a test to compute an expected
|
|
88
|
+
value or stand in for production behavior — an untested helper can be wrong, making the test lie.
|
|
89
|
+
Assert against literal expectations.
|
|
90
|
+
- **Everything a test uses must already be tested.** Every function, class, mock, and tool the test
|
|
91
|
+
leans on has its own test cases.
|
|
92
|
+
- **Doubles live under `tests/`, and are themselves tested.** Mocks go in `tests/mocks/`, shared test
|
|
93
|
+
tools/factories in `tests/tools/`, and **each mock class has its own test file**. Prefer explicit
|
|
94
|
+
fakes (obviously-fake names/values).
|
|
95
|
+
|
|
96
|
+
The rule with good/avoid examples, and the mocks/tools layout, are in
|
|
97
|
+
[purity-and-mocks.md](./references/purity-and-mocks.md).
|
|
98
|
+
|
|
99
|
+
## Finishing checklist
|
|
100
|
+
|
|
101
|
+
- [ ] The test is in `tests/__tests__/` if it does no DB write, or `tests/_orders/<Category>/` if it does ([§1](#1-placement--execution-order)).
|
|
102
|
+
- [ ] A DB-writing test is imported (in the right position) by its category's `_.test.js` barrel.
|
|
103
|
+
- [ ] If the new test's category can interfere with another, a per-category CI workflow isolates them.
|
|
104
|
+
- [ ] The test defines **no** new logic; every function/class/mock it uses is already tested ([§3](#3-test-purity--test-doubles)).
|
|
105
|
+
- [ ] Any new mock/tool lives under `tests/mocks/` or `tests/tools/` and has its **own** test file.
|
|
106
|
+
- [ ] Verified with a single-test run ([§2](#2-running-tests)).
|
|
107
|
+
|
|
108
|
+
## Detail files
|
|
109
|
+
|
|
110
|
+
- [placement-and-ordering.md](./references/placement-and-ordering.md) — `__tests__` vs `_orders`, why
|
|
111
|
+
DB-writing tests need ordering, the `_.test.js` order barrel, cross-category isolation via
|
|
112
|
+
per-category CI workflows (§1)
|
|
113
|
+
- [running-tests.md](./references/running-tests.md) — the whole-suite runner and what it does, running
|
|
114
|
+
a single test with the dev/master seed sets, resetting the database piecemeal, sizing the
|
|
115
|
+
parallelism × heap budget against real memory, and what a live (real-dialect) run requires (§2)
|
|
116
|
+
- [purity-and-mocks.md](./references/purity-and-mocks.md) — no-new-logic and only-tested-code rules
|
|
117
|
+
with good/avoid examples, and the `tests/mocks` / `tests/tools` layout where doubles are themselves
|
|
118
|
+
tested (§3)
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# Placement & execution order
|
|
2
|
+
|
|
3
|
+
Where a test file goes, and how DB-writing tests are ordered so they do not corrupt each other.
|
|
4
|
+
Referenced from §1 of [SKILL.md](../SKILL.md). Directory and category names are the recommended
|
|
5
|
+
layout with illustrative fakes.
|
|
6
|
+
|
|
7
|
+
## The two locations
|
|
8
|
+
|
|
9
|
+
Every test file lives in exactly one of two places, chosen by **whether it writes to the database**.
|
|
10
|
+
|
|
11
|
+
| Location | Put here | Ordering |
|
|
12
|
+
| --- | --- | --- |
|
|
13
|
+
| `tests/__tests__/` | tests that **do not** write to the DB — pure units, read-only queries, formatters, validators | none needed; run in any order |
|
|
14
|
+
| `tests/_orders/<Category>/` | tests that **do** write to the DB — anything that inserts/updates/deletes rows | guaranteed **within a category** by a `_.test.js` barrel |
|
|
15
|
+
|
|
16
|
+
- Mirror the source tree inside `tests/__tests__/` so a unit's test sits at the matching path.
|
|
17
|
+
- Under `tests/_orders/`, group by a **category** (a cohesive area of write behavior); each category is
|
|
18
|
+
its own folder.
|
|
19
|
+
- **Classify by what the method _does_, not by whether the test mocks the write away.** A method that
|
|
20
|
+
writes to the DB directly or transitively (calls `create` / `update` / `destroy` /
|
|
21
|
+
`beginTransaction`, or orchestrates sub-methods that do) belongs in `_orders` **even if the test
|
|
22
|
+
stubs the persist call** — mocking the write does not move it to `__tests__`.
|
|
23
|
+
- **Placement is per-method, so one class usually splits across both trees.** A DB-writing class
|
|
24
|
+
keeps its writing methods in `_orders` and its non-writing methods (`find~`, getters, builders,
|
|
25
|
+
validators, `format~`) in the sibling `__tests__` file. Do not dump a read-only method into
|
|
26
|
+
`_orders` just to keep it beside the class's other tests — keeping tests together is not a reason
|
|
27
|
+
to place it there.
|
|
28
|
+
|
|
29
|
+
## Why DB-writing tests need ordering
|
|
30
|
+
|
|
31
|
+
A DB-writing test mutates the **shared seed fixtures** (`development` / `dev-master`) that the running
|
|
32
|
+
database was seeded with. Because the database is shared across the tests in a run, a test that runs
|
|
33
|
+
**after** a mutation observes the changed state.
|
|
34
|
+
|
|
35
|
+
- Read-only tests can't change what others see, so they never need ordering (hence
|
|
36
|
+
`tests/__tests__/`); DB-writing tests can, so their run order must be **deterministic**, not left
|
|
37
|
+
to file-discovery order.
|
|
38
|
+
|
|
39
|
+
## The `_.test.js` order barrel
|
|
40
|
+
|
|
41
|
+
Each category folder contains a `_.test.js` that **imports the category's test files in the exact
|
|
42
|
+
order they must run**. Jest discovers `_.test.js`, and its import order becomes the execution order.
|
|
43
|
+
|
|
44
|
+
```js
|
|
45
|
+
// tests/_orders/<Category>/_.test.js
|
|
46
|
+
// Imports define the run order for this category; add each new test in its correct position.
|
|
47
|
+
import './CreateRecord.js'
|
|
48
|
+
import './UpdateRecord.js'
|
|
49
|
+
import './DeleteRecord.js'
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- The individual test files in the folder are **imported by the barrel**, not discovered independently
|
|
53
|
+
— name them so they are not matched as standalone tests by the runner, and let `_.test.js` be the
|
|
54
|
+
single entry point for the category.
|
|
55
|
+
- When you add a DB-writing test, add one `import` line to the category's barrel at the position where
|
|
56
|
+
it must run (e.g. after the test that creates the row it depends on).
|
|
57
|
+
|
|
58
|
+
## Cross-category isolation via CI
|
|
59
|
+
|
|
60
|
+
`tests/_orders` guarantees order **within** a category, but **not across** categories — two categories
|
|
61
|
+
run independently and may both mutate overlapping seed data. When two categories can interfere, run
|
|
62
|
+
them in **separate CI jobs** so each starts from its own fresh database.
|
|
63
|
+
|
|
64
|
+
- Add or update a **per-category** workflow under `.github/workflows/` that runs only that category's
|
|
65
|
+
path. Two interfering categories then never share a database within a single job.
|
|
66
|
+
|
|
67
|
+
```yaml
|
|
68
|
+
# .github/workflows/test-<category>.yml — one interfering category, isolated in its own job/DB
|
|
69
|
+
name: test <Category>
|
|
70
|
+
|
|
71
|
+
on:
|
|
72
|
+
pull_request:
|
|
73
|
+
branches:
|
|
74
|
+
- '**'
|
|
75
|
+
|
|
76
|
+
jobs:
|
|
77
|
+
test:
|
|
78
|
+
runs-on: ubuntu-latest
|
|
79
|
+
env:
|
|
80
|
+
NODE_ENV: development
|
|
81
|
+
steps:
|
|
82
|
+
- uses: actions/checkout@v4
|
|
83
|
+
- uses: actions/setup-node@v4
|
|
84
|
+
- run: npm ci
|
|
85
|
+
- run: npm run test -- --seeded tests/_orders/<Category>/
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
- The default catch-all workflow can run the rest of `tests/_orders/`; peel a category **out** into its
|
|
89
|
+
own workflow only when it demonstrably interferes with another.
|