@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.
Files changed (126) hide show
  1. package/LICENSE +201 -0
  2. package/README.ja.md +135 -0
  3. package/README.md +135 -0
  4. package/dist/skills/hor-agent-loop/SKILL.md +123 -0
  5. package/dist/skills/hor-agent-loop/references/core.md +485 -0
  6. package/dist/skills/hor-agent-loop/references/graphql-integration.md +178 -0
  7. package/dist/skills/hor-agent-loop/references/renchan-job-integration.md +368 -0
  8. package/dist/skills/hor-agent-loop/references/testing.md +492 -0
  9. package/dist/skills/hor-ai-agent-structure/SKILL.md +403 -0
  10. package/dist/skills/hor-ai-agent-structure/references/loop-and-actions.md +100 -0
  11. package/dist/skills/hor-ai-prompt-document-store/SKILL.md +220 -0
  12. package/dist/skills/hor-ai-prompt-document-store/references/models-and-composition.md +156 -0
  13. package/dist/skills/hor-backend-testing/SKILL.md +118 -0
  14. package/dist/skills/hor-backend-testing/references/placement-and-ordering.md +89 -0
  15. package/dist/skills/hor-backend-testing/references/purity-and-mocks.md +82 -0
  16. package/dist/skills/hor-backend-testing/references/running-tests.md +186 -0
  17. package/dist/skills/hor-bank-id/SKILL.md +91 -0
  18. package/dist/skills/hor-build-e2e-test-environment/SKILL.md +609 -0
  19. package/dist/skills/hor-build-e2e-test-environment/references/compose-definition.md +368 -0
  20. package/dist/skills/hor-build-e2e-test-environment/references/edge-and-proxy.md +287 -0
  21. package/dist/skills/hor-build-e2e-test-environment/references/environment-and-ports.md +201 -0
  22. package/dist/skills/hor-build-e2e-test-environment/references/runner-and-lifecycle.md +330 -0
  23. package/dist/skills/hor-build-e2e-test-environment/references/seed-data.md +145 -0
  24. package/dist/skills/hor-build-e2e-test-environment/references/windows-runner.md +146 -0
  25. package/dist/skills/hor-constant-definition/SKILL.md +139 -0
  26. package/dist/skills/hor-cookie-authentication/SKILL.md +33 -0
  27. package/dist/skills/hor-cookie-authentication/references/auth-filter.md +55 -0
  28. package/dist/skills/hor-cookie-authentication/references/cookie-context.md +53 -0
  29. package/dist/skills/hor-cookie-authentication/references/dev-login-seeder.md +22 -0
  30. package/dist/skills/hor-cookie-authentication/references/environment.md +64 -0
  31. package/dist/skills/hor-cookie-authentication/references/error-codes.md +24 -0
  32. package/dist/skills/hor-cookie-authentication/references/migrations.md +18 -0
  33. package/dist/skills/hor-cookie-authentication/references/resolvers.md +97 -0
  34. package/dist/skills/hor-cookie-authentication/references/session-clerk.md +41 -0
  35. package/dist/skills/hor-cookie-authentication/references/token-models.md +125 -0
  36. package/dist/skills/hor-database-design/SKILL.md +54 -0
  37. package/dist/skills/hor-database-design/references/column-types.md +92 -0
  38. package/dist/skills/hor-database-design/references/datetimes.md +88 -0
  39. package/dist/skills/hor-database-design/references/master-tables.md +117 -0
  40. package/dist/skills/hor-database-design/references/normalization.md +40 -0
  41. package/dist/skills/hor-database-design/references/update-history.md +35 -0
  42. package/dist/skills/hor-execution-placement-pattern/SKILL.md +216 -0
  43. package/dist/skills/hor-external-api-client/SKILL.md +99 -0
  44. package/dist/skills/hor-external-api-client/references/architecture.md +127 -0
  45. package/dist/skills/hor-external-api-client/references/authorization.md +105 -0
  46. package/dist/skills/hor-external-api-client/references/capsule.md +130 -0
  47. package/dist/skills/hor-external-api-client/references/conventions.md +68 -0
  48. package/dist/skills/hor-external-api-client/references/launcher.md +138 -0
  49. package/dist/skills/hor-external-api-client/references/payload.md +176 -0
  50. package/dist/skills/hor-external-api-client/references/sdk-wrapper.md +291 -0
  51. package/dist/skills/hor-external-api-client/references/testing.md +130 -0
  52. package/dist/skills/hor-external-api-client/references/usage.md +152 -0
  53. package/dist/skills/hor-graphql-schema/SKILL.md +360 -0
  54. package/dist/skills/hor-graphql-server-engine/SKILL.md +356 -0
  55. package/dist/skills/hor-light-rag/SKILL.md +242 -0
  56. package/dist/skills/hor-light-rag/references/retrieval-internals.md +143 -0
  57. package/dist/skills/hor-multi-llm-provider/SKILL.md +288 -0
  58. package/dist/skills/hor-multi-llm-provider/references/provider-internals.md +153 -0
  59. package/dist/skills/hor-mutation-resolver/SKILL.md +360 -0
  60. package/dist/skills/hor-mutation-resolver/references/dependency-injection.md +148 -0
  61. package/dist/skills/hor-mutation-resolver/references/errors.md +120 -0
  62. package/dist/skills/hor-mutation-resolver/references/resolve-flow.md +275 -0
  63. package/dist/skills/hor-mutation-resolver/references/testing.md +125 -0
  64. package/dist/skills/hor-mutation-resolver/references/transaction.md +197 -0
  65. package/dist/skills/hor-post-worker/SKILL.md +320 -0
  66. package/dist/skills/hor-query-resolver/SKILL.md +246 -0
  67. package/dist/skills/hor-query-resolver/references/anatomy.md +384 -0
  68. package/dist/skills/hor-query-resolver/references/data-access.md +248 -0
  69. package/dist/skills/hor-query-resolver/references/errors-and-context.md +172 -0
  70. package/dist/skills/hor-query-resolver/references/testing.md +241 -0
  71. package/dist/skills/hor-renchan-job-bullmq/SKILL.md +178 -0
  72. package/dist/skills/hor-renchan-job-bullmq/references/daemon-and-scheduler.md +182 -0
  73. package/dist/skills/hor-renchan-job-bullmq/references/engine-and-infra.md +106 -0
  74. package/dist/skills/hor-renchan-job-bullmq/references/job-triple.md +189 -0
  75. package/dist/skills/hor-renchan-job-bullmq/references/queues.md +74 -0
  76. package/dist/skills/hor-renchan-job-bullmq/references/subscriptions.md +113 -0
  77. package/dist/skills/hor-resolver-share/SKILL.md +262 -0
  78. package/dist/skills/hor-resolver-validator/SKILL.md +194 -0
  79. package/dist/skills/hor-resolver-validator/references/inspector-api.md +115 -0
  80. package/dist/skills/hor-resolver-validator/references/validator-pattern.md +281 -0
  81. package/dist/skills/hor-restfulapi-architecture/SKILL.md +275 -0
  82. package/dist/skills/hor-restfulapi-architecture/references/engine-and-context.md +192 -0
  83. package/dist/skills/hor-restfulapi-architecture/references/renderers.md +204 -0
  84. package/dist/skills/hor-restfulapi-architecture/references/response-and-flusher.md +118 -0
  85. package/dist/skills/hor-restfulapi-architecture/references/validation.md +229 -0
  86. package/dist/skills/hor-security-audit/SKILL.md +110 -0
  87. package/dist/skills/hor-security-audit/references/application-surface.md +90 -0
  88. package/dist/skills/hor-security-audit/references/auth-and-transport.md +147 -0
  89. package/dist/skills/hor-security-audit/references/code-safety.md +74 -0
  90. package/dist/skills/hor-security-audit/references/dependencies.md +72 -0
  91. package/dist/skills/hor-security-audit/references/network-and-logging.md +56 -0
  92. package/dist/skills/hor-security-audit/references/secrets.md +95 -0
  93. package/dist/skills/hor-sequelize-migration/SKILL.md +336 -0
  94. package/dist/skills/hor-sequelize-migration/references/alter-table.md +147 -0
  95. package/dist/skills/hor-sequelize-migration/references/foreign-keys.md +107 -0
  96. package/dist/skills/hor-sequelize-migration/references/indexes.md +149 -0
  97. package/dist/skills/hor-sequelize-migration/references/notation.md +215 -0
  98. package/dist/skills/hor-sequelize-model/SKILL.md +69 -0
  99. package/dist/skills/hor-sequelize-model/references/associations.md +218 -0
  100. package/dist/skills/hor-sequelize-model/references/default-methods.md +244 -0
  101. package/dist/skills/hor-sequelize-model/references/mixins.md +247 -0
  102. package/dist/skills/hor-sequelize-model/references/notation.md +225 -0
  103. package/dist/skills/hor-sequelize-model/references/timestamps.md +74 -0
  104. package/dist/skills/hor-sequelize-seeder/SKILL.md +275 -0
  105. package/dist/skills/hor-sequelize-seeder/references/development-coverage.md +74 -0
  106. package/dist/skills/hor-sequelize-seeder/references/directory-structure.md +113 -0
  107. package/dist/skills/hor-sequelize-seeder/references/id-numbering.md +133 -0
  108. package/dist/skills/hor-sequelize-seeder/references/naming.md +59 -0
  109. package/dist/skills/hor-sequelize-seeder/references/notation.md +170 -0
  110. package/dist/skills/hor-sequelize-subquery/SKILL.md +369 -0
  111. package/dist/skills/hor-strategy-pattern/SKILL.md +371 -0
  112. package/dist/skills/hor-stub-api/SKILL.md +330 -0
  113. package/dist/skills/hor-subscription-resolver/SKILL.md +105 -0
  114. package/dist/skills/hor-subscription-resolver/references/authentication.md +99 -0
  115. package/dist/skills/hor-subscription-resolver/references/basic-notation.md +116 -0
  116. package/dist/skills/hor-subscription-resolver/references/design-philosophy.md +68 -0
  117. package/dist/skills/hor-type-interface/SKILL.md +200 -0
  118. package/docs/skills.ja.md +40 -0
  119. package/docs/skills.md +40 -0
  120. package/lib/equip/CommandLineArguments.js +178 -0
  121. package/lib/equip/HoraSkillsCli.js +590 -0
  122. package/lib/equip/SkillsInstaller.js +443 -0
  123. package/lib/equip/SkillsManifestFile.js +260 -0
  124. package/lib/equip/constants/CLI_COMMAND.js +8 -0
  125. package/lib/equip/hora-skills-ort-renchan.js +8 -0
  126. package/package.json +51 -0
@@ -0,0 +1,485 @@
1
+ # Core (`@openreachtech/mentsu-agent-loop-core` spec and use cases)
2
+
3
+ Rules for the iteration engine itself. Referenced from `SKILL.md`. Core has **zero dependencies
4
+ (deps:0)** and imports nothing about AI, DB, queues, or GraphQL. Business dependencies are all received
5
+ through **`context` (a DI seam)** (the grand principle in `SKILL.md`). Job execution and GraphQL
6
+ integration are [renchan-job-integration.md](./renchan-job-integration.md) /
7
+ [graphql-integration.md](./graphql-integration.md); testing is [testing.md](./testing.md).
8
+
9
+ All imports come from `@openreachtech/mentsu-agent-loop-core`.
10
+
11
+ ## Exported classes
12
+
13
+ | Category | Class | Role |
14
+ | --- | --- | --- |
15
+ | Action | `BaseAgentAction` | Base for an app "capability". Implement `get name` / `get description` / `run` |
16
+ | Action | `AgentActionRegistry` | Bundles actions by `name → action` (`getAction` / `describeActions`) |
17
+ | Loop | `BaseAgentLoop` | Skeleton of the iteration engine (tail-recursive `iterate`, QC hooks, automatic progress) |
18
+ | Loop | `AiDrivenAgentLoop` | **The AI decides the next move.** Implement `registry` / `decideNext` / `reduceActionResult` |
19
+ | Loop | `ProceduralAgentLoop` | **Code decides the procedure.** Implement `advanceState` (the procedure body) |
20
+ | Composition | `BaseCompositeAgent` | Parallel fan-out / fan-in (`planSubTasks` / `createSubAgent` / `mergeResults`, `concurrency`) |
21
+ | Composition | `BaseAgentPipeline` | Sequential composition (`get stageCtors`). Threads the payload via immutable merge |
22
+ | Composition | `BaseActionStage` | Wraps a single action as a Runnable (`ActionCtor` / `buildArgumentHash` / `buildOutput`) |
23
+ | Runner | `BaseAgentRunner` / `InlineAgentRunner` | Execution-mode abstraction and in-process implementation (`request({ input, onProgress })`) |
24
+ | VO | `AgentProgressEvent` | Standard shape of a progress event (`create({ phase, iteration, payload }).toHash()`) |
25
+ | VO | `AgentTopic` | Structurally matches the publish/subscribe channel name (`create({ channel, scope }).value`) |
26
+ | Error | `AgentLoopError` / `ConcreteMemberNotFoundError` / `ActionNotFoundError` | Error base and concretes |
27
+ | Testing | `LoopContractAssertion` / `ActionContractAssertion` in `.../lib/testing/index.js` | Contract test kit ([testing.md](./testing.md)) |
28
+
29
+ ## The Runnable contract (why composition works)
30
+
31
+ `BaseAgentLoop` / `BaseCompositeAgent` / `BaseAgentPipeline` / `BaseActionStage` / Runner all satisfy
32
+ the same contract. **Because of this one contract, loops, composites, and stages can be nested inside
33
+ one another.**
34
+
35
+ ```
36
+ static create({ context }) + async run({ input, onProgress })
37
+ ```
38
+
39
+ - **Why unify it**: you can freely put a loop as a pipeline stage, or another pipeline inside a
40
+ composite, because every Runnable has the same `create` / `run`. When you add a new Runnable,
41
+ always give it this shape.
42
+
43
+ ## The state model (do not mix the three concepts)
44
+
45
+ | Concept | Holds | Lifetime |
46
+ | --- | --- | --- |
47
+ | **state (iteration state)** | Per-step output, history, score | One run; **updated immutably** per iteration (`{ ...state, ... }`) |
48
+ | **context (shared dependencies)** | DI for AI / DB / external clients | Read-only and constant across the whole run |
49
+ | **compression (working context)** | The cumulative context passed to the AI | Grows per iteration → shrunk by `compressContext` |
50
+
51
+ - **Why separate them**: making state mutable, or mixing iteration state into context, breaks resume,
52
+ parallelism, and testing. **Keep state immutable-updated and context read-only.**
53
+
54
+ ## Action: `BaseAgentAction`
55
+
56
+ Define a "capability" as one class per file. Business dependencies are **always reached through
57
+ `argumentHash` and `context`**.
58
+
59
+ Members to override:
60
+
61
+ - `get name` (required): the registry key / the identifier the AI selects by.
62
+ - `get description` (required): the description used for selection (`describeActions()` formats it into
63
+ a prompt).
64
+ - `async run({ argumentHash, context, onProgress })` (required): the capability body. Side effects
65
+ through `context` only.
66
+ - `isValidArgumentHash({ argumentHash })` (optional): pre-run argument validation (default `true`).
67
+
68
+ ```js
69
+ import {
70
+ BaseAgentAction,
71
+ } from '@openreachtech/mentsu-agent-loop-core'
72
+
73
+ /**
74
+ * An action that searches for a topic.
75
+ *
76
+ * @extends {BaseAgentAction}
77
+ */
78
+ export default class SearchAction extends BaseAgentAction {
79
+ /** @override */
80
+ get name () {
81
+ return 'search'
82
+ }
83
+
84
+ /** @override */
85
+ get description () {
86
+ return 'Search by keyword. Arguments: { keyword: string }'
87
+ }
88
+
89
+ /** @override */
90
+ async run ({
91
+ argumentHash,
92
+ context,
93
+ onProgress = null,
94
+ }) {
95
+ // Progress can be emitted from inside an action too (onProgress is optional).
96
+ onProgress?.({
97
+ phase: 'searching',
98
+ keyword: argumentHash.keyword,
99
+ })
100
+
101
+ // Business dependencies come from context (no direct import).
102
+ return context.searchClient.search({
103
+ keyword: argumentHash.keyword,
104
+ })
105
+ }
106
+ }
107
+ ```
108
+
109
+ ```js
110
+ // Avoid: importing a dependency directly inside an action
111
+ // → it can't be swapped for a stub in in-process tests, breaking the one-way dependency. Use context.
112
+ import searchClient from '../../clients/searchClient.js' // ← NG
113
+ ```
114
+
115
+ Bundle actions with `AgentActionRegistry.create({ actions: [...] })`. Resolve with `getAction({ name })`
116
+ (throws `ActionNotFoundError` if unregistered); `describeActions()` yields a `- name: description` list.
117
+
118
+ ## Choosing a loop type (two types)
119
+
120
+ A loop always implements the four abstract hooks of `BaseAgentLoop`: `createInitialState({ input })` /
121
+ `advanceState({ state, iteration })` / `isComplete({ state, iteration })` / `buildResult({ state })`.
122
+ Tune the QC hooks via getters: `get maxIterations` (default 10, the safety bound) / `get
123
+ compressionInterval` (default null). `iterate` **always stops on `isComplete` or `maxIterations`** and
124
+ emits `onProgress` every iteration (not overridable).
125
+
126
+ | Aspect | `AiDrivenAgentLoop` (AI-driven) | `ProceduralAgentLoop` (procedural) |
127
+ | --- | --- | --- |
128
+ | Who decides the next move | **The AI** (`decideNext` asks each time) | **Code** (the fixed procedure in `advanceState`) |
129
+ | Control flow | Non-deterministic, exploratory | Deterministic, reproducible |
130
+ | What the app writes | `registry` / `decideNext` / `reduceActionResult` | `advanceState` (calls capabilities via `performAction`) |
131
+ | Fits | Exploratory tasks with no readable procedure | Tasks with a fixed procedure |
132
+
133
+ - **Why `maxIterations` is always enforced**: whether AI-driven or procedural, a bug in the stop
134
+ condition or an unstable external response can loop forever. `maxIterations` (default 10) is the
135
+ safety bound; even if `isComplete` never returns true, the loop still stops.
136
+ - ⚠️ Procedural does not mean "no AI". You may use the AI as a **tool inside a step**. The difference is
137
+ **whether the AI holds the control flow**.
138
+
139
+ ### AI-driven: `AiDrivenAgentLoop`
140
+
141
+ The base implements `advanceState` as "`decideNext` → `registry.getAction` → `action.run` →
142
+ `reduceActionResult`". The app writes the following.
143
+
144
+ ```js
145
+ import {
146
+ AiDrivenAgentLoop,
147
+ AgentActionRegistry,
148
+ } from '@openreachtech/mentsu-agent-loop-core'
149
+
150
+ import SearchAction from './actions/SearchAction.js'
151
+ import RefineAction from './actions/RefineAction.js'
152
+
153
+ /**
154
+ * @extends {AiDrivenAgentLoop}
155
+ */
156
+ export default class ResearchAgentLoop extends AiDrivenAgentLoop {
157
+ /** @override */
158
+ get maxIterations () {
159
+ return 6
160
+ }
161
+
162
+ /** @override */
163
+ get registry () {
164
+ return AgentActionRegistry.create({
165
+ actions: [
166
+ SearchAction.create(),
167
+ RefineAction.create(),
168
+ ],
169
+ })
170
+ }
171
+
172
+ /** @override */
173
+ createInitialState ({
174
+ input,
175
+ }) {
176
+ return {
177
+ keyword: input.keyword,
178
+ history: [],
179
+ score: 0,
180
+ }
181
+ }
182
+
183
+ /** @override */
184
+ async decideNext ({
185
+ state,
186
+ }) {
187
+ // Let the AI decide the next action (AI client via context).
188
+ return this.context.aiAgent.decideNextAction({
189
+ history: state.history,
190
+ describedActions: this.registry.describeActions(),
191
+ })
192
+ }
193
+
194
+ /** @override */
195
+ async reduceActionResult ({
196
+ state,
197
+ action,
198
+ result,
199
+ }) {
200
+ return {
201
+ ...state,
202
+ history: [
203
+ ...state.history,
204
+ {
205
+ action: action.name,
206
+ result,
207
+ },
208
+ ],
209
+ score: result.score ?? state.score,
210
+ }
211
+ }
212
+
213
+ /** @override */
214
+ isComplete ({
215
+ state,
216
+ }) {
217
+ return state.score >= 0.8
218
+ }
219
+
220
+ /** @override */
221
+ buildResult ({
222
+ state,
223
+ }) {
224
+ return {
225
+ items: state.history.at(-1)?.result?.items ?? [],
226
+ iterations: state.history.length,
227
+ }
228
+ }
229
+ }
230
+ ```
231
+
232
+ ### Procedural: `ProceduralAgentLoop`
233
+
234
+ Write the procedure in `advanceState`, and call a capability with `performAction({ name, argumentHash,
235
+ context })`.
236
+
237
+ ```js
238
+ /** @override */
239
+ async advanceState ({
240
+ state,
241
+ }) {
242
+ const found = await this.performAction({
243
+ name: 'search',
244
+ argumentHash: {
245
+ keyword: state.keyword,
246
+ },
247
+ context: this.context,
248
+ })
249
+
250
+ const refined = await this.performAction({
251
+ name: 'refine',
252
+ argumentHash: {
253
+ previousResults: found.items,
254
+ },
255
+ context: this.context,
256
+ })
257
+
258
+ return {
259
+ ...state,
260
+ keyword: refined.keyword,
261
+ items: found.items,
262
+ score: found.score,
263
+ }
264
+ }
265
+ ```
266
+
267
+ ## Composition (bundling multiple Runnables)
268
+
269
+ ### Sequential: `BaseAgentPipeline`
270
+
271
+ Chain stages of different natures (each stage is a Runnable) in series. The app declares only
272
+ `get stageCtors` (`[{ name, Ctor }]`); the base handles payload hand-off, progress tagging, and
273
+ sequential execution.
274
+
275
+ - Override `createInitialPayload({ input })` (default: the input as-is), `mapStageOutput({ stage, input,
276
+ output })` (default: the immutable merge `{ ...input, ...output }`), and `buildResult({ payload })`
277
+ (default: the payload as-is) only when needed.
278
+ - The base attaches `stage: <name>` to progress events (`buildStageEvent`).
279
+
280
+ ```js
281
+ import {
282
+ BaseAgentPipeline,
283
+ } from '@openreachtech/mentsu-agent-loop-core'
284
+
285
+ import KeywordStage from './KeywordStage.js'
286
+ import SearchStage from './SearchStage.js'
287
+ import RerankStage from './RerankStage.js'
288
+
289
+ /**
290
+ * @extends {BaseAgentPipeline}
291
+ */
292
+ export default class ResearchPipeline extends BaseAgentPipeline {
293
+ /** @override */
294
+ get stageCtors () {
295
+ return [
296
+ {
297
+ name: 'keyword',
298
+ Ctor: KeywordStage,
299
+ },
300
+ {
301
+ name: 'search',
302
+ Ctor: SearchStage,
303
+ },
304
+ {
305
+ name: 'rerank',
306
+ Ctor: RerankStage,
307
+ },
308
+ ]
309
+ }
310
+
311
+ /** @override */
312
+ buildResult ({
313
+ payload,
314
+ }) {
315
+ return {
316
+ ranked: payload.ranked,
317
+ }
318
+ }
319
+ }
320
+ ```
321
+
322
+ - **Do not override `run()`.** Sequential execution, payload merging, and progress tagging are the
323
+ base's assets. Why: reimplementing `run` forces you to re-guarantee progress tagging and immutable
324
+ merging yourself, and its behavior drifts from other pipelines. If you need resume/idempotency,
325
+ handle it in the stages / `context` (see idempotency in
326
+ [renchan-job-integration.md](./renchan-job-integration.md)).
327
+
328
+ ### A single action as a stage: `BaseActionStage`
329
+
330
+ A thin base that turns one `BaseAgentAction` into a pipeline stage (a Runnable). Declare just three
331
+ members.
332
+
333
+ ```js
334
+ import {
335
+ BaseActionStage,
336
+ } from '@openreachtech/mentsu-agent-loop-core'
337
+
338
+ import RerankAction from './actions/RerankAction.js'
339
+
340
+ /**
341
+ * @extends {BaseActionStage}
342
+ */
343
+ export default class RerankStage extends BaseActionStage {
344
+ /** @override */
345
+ static get ActionCtor () {
346
+ return RerankAction
347
+ }
348
+
349
+ /** @override */
350
+ buildArgumentHash ({
351
+ input,
352
+ }) {
353
+ return {
354
+ hits: input.hits, // ← the previous stage's output becomes the argument
355
+ }
356
+ }
357
+
358
+ /** @override */
359
+ buildOutput ({
360
+ result,
361
+ }) {
362
+ return {
363
+ ranked: result.items,
364
+ }
365
+ }
366
+ }
367
+ ```
368
+
369
+ ### Parallel: `BaseCompositeAgent`
370
+
371
+ Split the input into sub-tasks, run sub-agents (Runnables) in **parallel bounded by `concurrency`**,
372
+ and combine with `mergeResults`. Implement `planSubTasks` / `createSubAgent` / `mergeResults`, and cap
373
+ the degree of parallelism with `get concurrency` (default `Infinity`).
374
+
375
+ ```js
376
+ /** @override */
377
+ get concurrency () {
378
+ return 3
379
+ }
380
+
381
+ /** @override */
382
+ planSubTasks ({
383
+ input,
384
+ }) {
385
+ return input.keywords
386
+ .map(keyword => ({
387
+ keyword,
388
+ }))
389
+ }
390
+
391
+ /** @override */
392
+ createSubAgent ({
393
+ subTask,
394
+ }) {
395
+ return ResearchAgentLoop.create({
396
+ context: this.context,
397
+ })
398
+ }
399
+
400
+ /** @override */
401
+ mergeResults ({
402
+ results,
403
+ }) {
404
+ return {
405
+ items: results.flatMap(one => one.items),
406
+ }
407
+ }
408
+ ```
409
+
410
+ - **Why cap `concurrency`**: if sub-agents hit an AI / external API, unbounded parallelism causes rate
411
+ overruns and memory exhaustion. Do not leave it at the default `Infinity`; set a finite value
412
+ whenever external I/O is involved.
413
+
414
+ ## Runner (execution-mode abstraction)
415
+
416
+ Make the caller depend only on `runner.request({ input, onProgress })`, so the concrete (in-process vs
417
+ Redis job) can be swapped. The contract is `BaseAgentRunner#request`.
418
+
419
+ - `InlineAgentRunner.create({ AgentLoopCtor, context })` — in-process execution. `request` returns the
420
+ loop's **final result**. For CLI / tests / synchronous work / Lambda.
421
+ - The Redis version `JobAgentRunner` is provided by the renchan-job adapter
422
+ ([renchan-job-integration.md](./renchan-job-integration.md)). Its `request` returns `{ accepted, jobId }`
423
+ and progress goes over a Subscription.
424
+
425
+ ```js
426
+ import {
427
+ InlineAgentRunner,
428
+ } from '@openreachtech/mentsu-agent-loop-core'
429
+
430
+ const runner = InlineAgentRunner.create({
431
+ AgentLoopCtor: ResearchAgentLoop,
432
+ context: {
433
+ aiAgent,
434
+ searchClient,
435
+ },
436
+ })
437
+
438
+ const result = await runner.request({
439
+ input: {
440
+ keyword: 'example',
441
+ },
442
+ onProgress: event => console.log(event),
443
+ })
444
+ ```
445
+
446
+ - **Why put a Runner in front**: the same loop can be in-process in development and a Redis job in
447
+ production, switched by `env`, with no change to the caller. Keep the caller from touching a concrete
448
+ Loop or Dispatcher directly.
449
+
450
+ ## Progress VO and Topic
451
+
452
+ - `AgentProgressEvent.create({ phase, iteration, payload }).toHash()` — the standard progress shape
453
+ `{ phase, iteration, payload }`. `iteration` / `payload` default to `null`. A VO that produces a shape
454
+ that rides directly on `job.updateProgress` or JSON. The loop's default per-iteration event is
455
+ `{ phase: 'iteration', iteration }`.
456
+ - `AgentTopic.create({ channel, scope }).value` — composes the publish/subscribe channel name. If
457
+ `scope` is `null`, the value is `channel` itself; otherwise `channel:key=value&...` (**keys sorted
458
+ ascending** before joining).
459
+
460
+ ```js
461
+ import {
462
+ AgentTopic,
463
+ } from '@openreachtech/mentsu-agent-loop-core'
464
+
465
+ AgentTopic
466
+ .create({
467
+ channel: 'researchProgress',
468
+ scope: {
469
+ userId: 1001,
470
+ },
471
+ })
472
+ .value // → 'researchProgress:userId=1001'
473
+ ```
474
+
475
+ - **Why sort the scope keys**: even if the publish and subscribe sides build the scope object with a
476
+ different key order, sorting produces the same string. This is the key to "the publish and subscribe
477
+ channels match" ([graphql-integration.md](./graphql-integration.md) /
478
+ [renchan-job-integration.md](./renchan-job-integration.md)).
479
+ - To change the naming rule, extend `AgentTopic`, override `get value()`, and use the **same** extended
480
+ class on both the publish and subscribe sides. Swapping only one side makes the channels drift.
481
+
482
+ ## Unimplemented abstracts throw `ConcreteMemberNotFoundError`
483
+
484
+ Touching an abstract member (`get name` / `createInitialState`, etc.) without implementing it throws
485
+ `ConcreteMemberNotFoundError`. Use this in tests to "detect the unimplemented" ([testing.md](./testing.md)).
@@ -0,0 +1,178 @@
1
+ # GraphQL Integration (`@openreachtech/mentsu-agent-loop-graphql`)
2
+
3
+ Rules for the resolver bases that **launch** a core loop from renchan's GraphQL (a Mutation) and
4
+ **subscribe to its progress in realtime** (a Subscription). Referenced from `SKILL.md`. The core side is
5
+ [core.md](./core.md), the job-execution and publish side is
6
+ [renchan-job-integration.md](./renchan-job-integration.md), and testing is [testing.md](./testing.md).
7
+
8
+ The typical shape for an agent on the web is "launch with a Mutation → return `accepted` immediately →
9
+ stream progress over a Subscription". This package bases those two resolvers, so the app completes the
10
+ integration with a few member declarations. Because the publish side (the Worker) and the subscribe side
11
+ (the Subscription) share the **same `AgentTopic`**, the channel names match structurally.
12
+
13
+ | Class | Extends (renchan) | Role |
14
+ | --- | --- | --- |
15
+ | `BaseRequestAgentMutationResolver` | `BaseMutationResolver` | Turns GraphQL variables into a job body, enqueues, and returns `{ accepted, jobId }` immediately |
16
+ | `BaseAgentProgressSubscriptionResolver` | `BaseSubscriptionResolver` | Subscribes to what the Worker publishes, on the same `AgentTopic` channel |
17
+
18
+ ## Launch Mutation: `BaseRequestAgentMutationResolver`
19
+
20
+ Enqueue without waiting for the long loop, and respond immediately. The app implements only two members.
21
+
22
+ | Member | Kind | Description |
23
+ | --- | --- | --- |
24
+ | `buildJobBody({ variables })` | abstract | GraphQL variables → the job body (= the loop input) |
25
+ | `enqueue({ body, context })` | abstract | Enqueue the body via `context.share`; return the dispatch response (exposing `hasResponse()` / `idKey`) |
26
+ | `resolve({ variables, context })` | implemented | Calls `enqueue({ body: buildJobBody(...), context })` → returns `{ accepted, jobId }` |
27
+
28
+ ```js
29
+ import {
30
+ BaseRequestAgentMutationResolver,
31
+ } from '@openreachtech/mentsu-agent-loop-graphql'
32
+
33
+ import ResearchJobDispatcher from '../../../jobs/research/ResearchJobDispatcher.js'
34
+
35
+ /**
36
+ * @extends {BaseRequestAgentMutationResolver}
37
+ */
38
+ export default class RequestResearchMutationResolver extends BaseRequestAgentMutationResolver {
39
+ /** @override */
40
+ static get schema () {
41
+ return 'requestResearch' // ← the corresponding GraphQL mutation name (renchan binding)
42
+ }
43
+
44
+ /** @override */
45
+ buildJobBody ({
46
+ variables,
47
+ }) {
48
+ return {
49
+ jobId: variables.input.jobId,
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Source the dispatch seam from context.share (the house DI convention) and enqueue.
55
+ *
56
+ * @override
57
+ */
58
+ async enqueue ({
59
+ body,
60
+ context,
61
+ }) {
62
+ return context.share.jobDispatcherProvider.dispatchJob({
63
+ DispatcherCtor: ResearchJobDispatcher,
64
+ body,
65
+ })
66
+ }
67
+ }
68
+ ```
69
+
70
+ - **Why enqueue and return immediately**: the loop can be long-running. Running it synchronously inside
71
+ the API causes an HTTP timeout, and a mid-way disconnect cannot recover. Enqueuing lets the API respond
72
+ immediately while execution, retry, and progress ride on the Worker side.
73
+ - **Source the dispatcher from `context.share`, not a resolver field**: shared, connection-reusing
74
+ instances (the job-dispatcher provider) live on `share` and are torn down at process exit, so read
75
+ them through `context.share`. This keeps DI in one place and lets tests swap the provider via a fake
76
+ share. The provider reuses its connection, so the resolver never calls `createAsync` / `teardown`.
77
+ - **Why the seam takes `context`**: the `enqueue({ body, context })` hook receives the per-request
78
+ `context` so that the dispatcher can be sourced from `context.share`. A parameterless getter could
79
+ not — a renchan resolver instance holds only `errorHash`, and `context` is a per-call argument to
80
+ `resolve`. `resolve` (implemented by the base) calls `enqueue` with the built body, so the app never
81
+ reimplements `resolve`. The house provider is keyed by `DispatcherCtor`
82
+ (`dispatchJob({ DispatcherCtor, body })`), which the app passes inside `enqueue`.
83
+ - **Do not turn a light loop into a job**: a loop that finishes quickly and needs no progress
84
+ subscription can be run inside a normal resolver with `InlineAgentRunner` ([core.md](./core.md)),
85
+ returning the result synchronously, instead of using `BaseRequestAgentMutationResolver`. Why: the
86
+ enqueue → subscribe machinery is for long-running, asynchronous work; bringing it to light work adds
87
+ needless complexity.
88
+
89
+ ## Progress Subscription: `BaseAgentProgressSubscriptionResolver`
90
+
91
+ Subscribe to the channel the Worker publishes to. The app implements only `channel` and
92
+ `generateChannelQuery`.
93
+
94
+ | Member | Kind | Description |
95
+ | --- | --- | --- |
96
+ | `get channel()` | abstract | The subscribe channel name (**same as the Worker's `channel`**) |
97
+ | `generateChannelQuery({ variables })` | abstract | Scope extraction (GraphQL-specific; e.g. `{ userId }`) |
98
+ | `static get AgentTopicCtor()` | hook | Default `AgentTopic`. Override to change the naming rule (**use the same extended class as the Worker**) |
99
+ | `generateChannel({ query })` | implemented | Overrides renchan's channel hook to return `AgentTopic.create({ channel, scope: query }).value` |
100
+ | `buildTopic({ variables })` | implemented | `generateChannel({ query: generateChannelQuery({ variables }) })` |
101
+
102
+ ```js
103
+ import {
104
+ BaseAgentProgressSubscriptionResolver,
105
+ } from '@openreachtech/mentsu-agent-loop-graphql'
106
+
107
+ /**
108
+ * @extends {BaseAgentProgressSubscriptionResolver}
109
+ */
110
+ export default class OnResearchProgressSubscriptionResolver extends BaseAgentProgressSubscriptionResolver {
111
+ /** @override */
112
+ static get schema () {
113
+ return 'onResearchProgress' // ← the corresponding GraphQL subscription name
114
+ }
115
+
116
+ /** @override */
117
+ get channel () {
118
+ return 'researchProgress' // ← must be the same string as the Worker's channel
119
+ }
120
+
121
+ /** @override */
122
+ generateChannelQuery ({
123
+ variables,
124
+ }) {
125
+ return {
126
+ // The scope key set must match the key set the Worker's buildScope returns.
127
+ userId: variables.input.userId,
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Pass the Worker's raw event straight through.
133
+ *
134
+ * @override
135
+ */
136
+ resolve (payload) {
137
+ return payload
138
+ }
139
+ }
140
+ ```
141
+
142
+ - **Why override `resolve` to pass through**: renchan's Subscription base sometimes assumes it should
143
+ unwrap `payload[schema]`. The Worker publishes a raw `{ phase, ... }` event, so returning it **as-is**
144
+ with `resolve(payload) => payload` lets the frontend receive the Worker's event shape directly. Only
145
+ reshape here if you want to change the event shape.
146
+ - **Match `channel` and scope with the publish side**: `get channel()` must be the same string as the
147
+ Worker's `get channel()`, and the scope keys of `generateChannelQuery` must match the scope keys of
148
+ the Worker's `buildScope`. Why: a mismatch publishes to a channel nobody subscribes to and progress
149
+ never arrives, a silent failure (see "keep the progress channel identical" in
150
+ [renchan-job-integration.md](./renchan-job-integration.md)). Define the `channel` string in one place
151
+ and share it with the Worker.
152
+
153
+ ## How progress arrives (the full flow)
154
+
155
+ ```
156
+ RequestResearchMutationResolver.resolve
157
+ → buildJobBody → enqueue → context.share.jobDispatcherProvider.dispatchJob(...) → returns { accepted, jobId } immediately
158
+ → the Worker picks it up → loop.run({ input: body, onProgress }) inside executeJob
159
+ → onProgress → job.updateProgress(event) → onJobProgress
160
+ → publish to the channel AgentTopic.create({ channel: 'researchProgress', scope }).value
161
+ → OnResearchProgressSubscriptionResolver (subscribing to the same channel + scope) → delivered to the frontend
162
+ ```
163
+
164
+ The publish side (the Worker) and the subscribe side (this resolver) share the **core `AgentTopic`**
165
+ that `generateChannel` calls internally, so the channel names match structurally. To change the naming
166
+ rule, set the same `AgentTopic`-extended class as both sides' `AgentTopicCtor` (never change only one
167
+ side).
168
+
169
+ ## Registering the GraphQL schema
170
+
171
+ Register the Mutation (`requestResearch: RequestResearchOutput`) and the Subscription
172
+ (`onResearchProgress: ...`) in the app's GraphQL schema, matching the name each resolver's `schema`
173
+ getter returns. Authentication, authorization, and input validation put these two resolvers on the same
174
+ path as any other renchan resolver.
175
+
176
+ - **In a non-GraphQL setup** (REST / tRPC, etc.), this package is unnecessary. Publish `onProgress` to
177
+ the broker in the app and subscribe to the core `AgentTopic` channel directly (the publish/subscribe
178
+ matching principle is the same).