@things-factory/ai-client-base 10.1.3 → 10.1.7

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 (44) hide show
  1. package/dist-server/service/assistant/abort-notice.d.ts +7 -0
  2. package/dist-server/service/assistant/abort-notice.js +29 -0
  3. package/dist-server/service/assistant/abort-notice.js.map +1 -0
  4. package/dist-server/service/assistant/assistant-chat.d.ts +41 -0
  5. package/dist-server/service/assistant/assistant-chat.js +63 -0
  6. package/dist-server/service/assistant/assistant-chat.js.map +1 -0
  7. package/dist-server/service/assistant/index.d.ts +5 -0
  8. package/dist-server/service/assistant/index.js +14 -0
  9. package/dist-server/service/assistant/index.js.map +1 -0
  10. package/dist-server/service/assistant/registry-assistant.d.ts +46 -0
  11. package/dist-server/service/assistant/registry-assistant.js +71 -0
  12. package/dist-server/service/assistant/registry-assistant.js.map +1 -0
  13. package/dist-server/service/assistant/registry-gate.d.ts +31 -0
  14. package/dist-server/service/assistant/registry-gate.js +61 -0
  15. package/dist-server/service/assistant/registry-gate.js.map +1 -0
  16. package/dist-server/service/assistant/summarize.d.ts +7 -0
  17. package/dist-server/service/assistant/summarize.js +67 -0
  18. package/dist-server/service/assistant/summarize.js.map +1 -0
  19. package/dist-server/service/index.d.ts +1 -0
  20. package/dist-server/service/index.js +1 -0
  21. package/dist-server/service/index.js.map +1 -1
  22. package/dist-server/service/tool-registry/registry.js +19 -0
  23. package/dist-server/service/tool-registry/registry.js.map +1 -1
  24. package/dist-server/service/tool-registry/types.d.ts +11 -1
  25. package/dist-server/service/tool-registry/types.js.map +1 -1
  26. package/dist-server/service/utils/grounding.d.ts +25 -2
  27. package/dist-server/service/utils/grounding.js +44 -8
  28. package/dist-server/service/utils/grounding.js.map +1 -1
  29. package/dist-server/tsconfig.tsbuildinfo +1 -1
  30. package/package.json +2 -2
  31. package/server/service/assistant/abort-notice.ts +44 -0
  32. package/server/service/assistant/assistant-chat.test.ts +218 -0
  33. package/server/service/assistant/assistant-chat.ts +99 -0
  34. package/server/service/assistant/index.ts +10 -0
  35. package/server/service/assistant/registry-assistant.test.ts +182 -0
  36. package/server/service/assistant/registry-assistant.ts +137 -0
  37. package/server/service/assistant/registry-gate.ts +76 -0
  38. package/server/service/assistant/summarize.ts +61 -0
  39. package/server/service/index.ts +1 -0
  40. package/server/service/tool-registry/registry.test.ts +59 -4
  41. package/server/service/tool-registry/registry.ts +22 -0
  42. package/server/service/tool-registry/types.ts +11 -1
  43. package/server/service/utils/grounding.test.ts +49 -0
  44. package/server/service/utils/grounding.ts +74 -8
@@ -0,0 +1,76 @@
1
+ /*
2
+ * Which tools this conversation may call — the registry half.
3
+ *
4
+ * ── Why a gate at all ───────────────────────────────────────────────────────────
5
+ * One product grows several conversation surfaces (a board authoring dock, an operations dock, a
6
+ * header assistant). Board edits can be reverted; an operations command reaches a real factory.
7
+ * If both sets hang in one conversation, the boundary is a label on the screen.
8
+ *
9
+ * **Hiding the definitions is not enough.** A model can guess a name, and an older conversation
10
+ * can be replayed with tool calls still in it. So the same gate has to decide *both* what is
11
+ * offered and what may be dispatched. A name that fails the gate is reported back to the model as
12
+ * unregistered — never a silent no-op, which the model would read as success.
13
+ *
14
+ * ── Why the registry half is here and the rest is not (2026-09-10) ──────────────
15
+ * This came out of `board-ai`, where the gate answered from two sources at once: the tool registry
16
+ * *and* board's own core tool-name sets. The first is neutral — any host asking "what kind of tool
17
+ * is this name, and may this conversation see it" wants the same answer. The second is board's.
18
+ *
19
+ * So the registry half lives here and a host **extends** it with whatever it owns
20
+ * (`extendToolGate`). Splitting it this way is what lets a product with no board of its own get
21
+ * the same dispatch discipline, instead of each product writing its own gate and diverging — which
22
+ * is what happened with the grounding guard: the twin's header route had it and the dock route did
23
+ * not, so the same question was verified on one side and not the other.
24
+ */
25
+ import { findToolSpec, getToolKind, type ToolCategoryFilter, type ToolSpec } from '../tool-registry/index.js'
26
+
27
+ /** 이름 하나에 대한 판정. 정의 조립과 dispatch 가 **같은 것**을 쓴다. */
28
+ export interface ToolGate {
29
+ /** 이 대화에 허용된 카테고리 목록. 없음 = 전부. */
30
+ filter: ToolCategoryFilter
31
+ isRead(name: string): boolean
32
+ isWrite(name: string): boolean
33
+ isAction(name: string): boolean
34
+ spec(name: string): ToolSpec | undefined
35
+ }
36
+
37
+ /** 호스트가 자기 도구를 더할 때 주는 것. 준 것만 더해지고, 안 준 축은 레지스트리 판정 그대로다. */
38
+ export interface ToolGateExtension {
39
+ isRead?(name: string): boolean
40
+ isWrite?(name: string): boolean
41
+ isAction?(name: string): boolean
42
+ spec?(name: string): ToolSpec | undefined
43
+ }
44
+
45
+ /**
46
+ * 레지스트리만 보고 답하는 게이트.
47
+ *
48
+ * `external` 은 읽기로 본다 — 등록한 쪽이 「밖에서 값을 가져온다」고 말한 것이고, 그것은 쓰지 않는다.
49
+ */
50
+ export function registryToolGate(filter?: ToolCategoryFilter): ToolGate {
51
+ const kind = (name: string) => getToolKind(name, filter)
52
+ return {
53
+ filter,
54
+ isRead: name => kind(name) === 'read' || kind(name) === 'external',
55
+ isWrite: name => kind(name) === 'write',
56
+ isAction: name => kind(name) === 'action',
57
+ spec: name => findToolSpec(name, filter)
58
+ }
59
+ }
60
+
61
+ /**
62
+ * 호스트의 판정을 **더한다.** 겹치면 어느 쪽이든 참이면 참이다 — 게이트는 「이 이름을 다룰 수 있나」를
63
+ * 묻고, 두 출처 중 하나가 안다고 하면 다룰 수 있다.
64
+ *
65
+ * 한쪽으로 덮지 않는 이유: 덮으면 호스트가 자기 이름집합에 없는 등록 도구를 **조용히 잠근다.** 그러면
66
+ * 대화면이 카테고리를 허용했는데 호출이 미등록으로 회신되고, 원인이 두 자리에 나뉘어 있어 못 찾는다.
67
+ */
68
+ export function extendToolGate(base: ToolGate, extension: ToolGateExtension): ToolGate {
69
+ return {
70
+ filter: base.filter,
71
+ isRead: name => base.isRead(name) || !!extension.isRead?.(name),
72
+ isWrite: name => base.isWrite(name) || !!extension.isWrite?.(name),
73
+ isAction: name => base.isAction(name) || !!extension.isAction?.(name),
74
+ spec: name => base.spec(name) ?? extension.spec?.(name)
75
+ }
76
+ }
@@ -0,0 +1,61 @@
1
+ /*
2
+ * Tool results, cut down to what a screen can hold.
3
+ *
4
+ * ── Why this is here and not in a product (2026-09-10) ───────────────────────────
5
+ * This came out of `board-ai`, and measuring the other consumer is what settled it: `twin-ai`
6
+ * passes `summarizeToolResult: v => v` — the identity function. So one product compressed its
7
+ * tool results before persisting them and the other did not, for no stated reason. That is the
8
+ * shape of a layer living in the wrong package: the second product does not decide differently,
9
+ * it just never gets the decision.
10
+ *
11
+ * ── ⚠ This is for the screen, never for a judgement ─────────────────────────────
12
+ * The output is depth- and length-limited, so it is **not evidence of what the model received**.
13
+ * A check that reads these summaries can pass while the model was handed `{}` — an un-awaited
14
+ * async builder did exactly that, and the screen still showed a successful call.
15
+ *
16
+ * What the model actually received is `AgenticLoopResult.groundedTexts`. Grounding already uses
17
+ * it, and anything that judges correctness must use it too.
18
+ */
19
+
20
+ /** 문자열은 이 길이에서 자른다. 자른 사실과 잘린 양을 남긴다 — 조용히 짧아지지 않는다. */
21
+ const MAX_STRING = 200
22
+ /** 배열은 이 개수까지 보이고 나머지는 수로 말한다. */
23
+ const MAX_ITEMS = 5
24
+ /** 배열 안의 배열은 이 깊이에서 모양만 남긴다. */
25
+ const MAX_ARRAY_DEPTH = 2
26
+ /** 객체는 이 깊이에서 키 이름만 남긴다. */
27
+ const MAX_OBJECT_DEPTH = 3
28
+ /** 깊이 한계에서 남길 키 개수. */
29
+ const MAX_KEYS = 6
30
+
31
+ /**
32
+ * 도구 결과를 화면·영속에 쓸 크기로 줄인다.
33
+ *
34
+ * 줄인 자리마다 **줄였다는 표시**를 남긴다(`…[+N chars]` · `…[+N items]` · `[Array(N)]`).
35
+ * 표시가 없으면 읽는 사람이 그것을 원본으로 믿는다.
36
+ */
37
+ export function summarizeToolResult(value: any, depth = 0): any {
38
+ if (value === null || value === undefined) return value
39
+ if (typeof value === 'string') {
40
+ return value.length > MAX_STRING ? `${value.slice(0, MAX_STRING)}…[+${value.length - MAX_STRING} chars]` : value
41
+ }
42
+ if (typeof value === 'number' || typeof value === 'boolean') return value
43
+ if (Array.isArray(value)) {
44
+ if (depth >= MAX_ARRAY_DEPTH) return `[Array(${value.length})]`
45
+ const out = value.slice(0, MAX_ITEMS).map(v => summarizeToolResult(v, depth + 1))
46
+ if (value.length > MAX_ITEMS) out.push(`…[+${value.length - MAX_ITEMS} items]`)
47
+ return out
48
+ }
49
+ if (typeof value === 'object') {
50
+ if (depth >= MAX_OBJECT_DEPTH) {
51
+ const keys = Object.keys(value).slice(0, MAX_KEYS).join(',')
52
+ return `{${keys}${Object.keys(value).length > MAX_KEYS ? ',…' : ''}}`
53
+ }
54
+ const out: any = {}
55
+ for (const key of Object.keys(value)) {
56
+ out[key] = summarizeToolResult(value[key], depth + 1)
57
+ }
58
+ return out
59
+ }
60
+ return undefined
61
+ }
@@ -4,3 +4,4 @@ export * from './providers/index.js'
4
4
  export * from './utils/index.js'
5
5
  export * from './tool-registry/index.js'
6
6
  export * from './agentic-loop/index.js'
7
+ export * from './assistant/index.js'
@@ -26,6 +26,8 @@ afterEach(() => {
26
26
  function makeCategory(name: string, specs: Partial<ToolSpec>[]): ToolCategory {
27
27
  return {
28
28
  name,
29
+ /* 지침은 필수다(2026-09-09). 픽스처가 그 강제를 우회하지 않도록 여기서도 채운다. */
30
+ guidance: `- fixture guidance for ${name}`,
29
31
  specs: specs.map(s => ({
30
32
  kind: 'read' as const,
31
33
  name: 'unnamed',
@@ -141,6 +143,7 @@ describe('registry — spec 보존', () => {
141
143
  const builder = jest.fn(() => ({ ok: true }))
142
144
  registerToolCategory({
143
145
  name: 'cat1',
146
+ guidance: '- fixture guidance for cat1',
144
147
  specs: [
145
148
  {
146
149
  kind: 'read',
@@ -165,6 +168,7 @@ describe('registry — spec 보존', () => {
165
168
  test('description / themeNote / schema 보존', () => {
166
169
  registerToolCategory({
167
170
  name: 'cat1',
171
+ guidance: '- fixture guidance for cat1',
168
172
  specs: [
169
173
  {
170
174
  kind: 'write',
@@ -196,10 +200,61 @@ describe('getCategoryGuidance — 도구와 함께 가는 사용 규율', () =>
196
200
  expect(getCategoryGuidance(undefined)).toEqual(['RULE-A'])
197
201
  })
198
202
 
199
- it('규율이 없는 카테고리는 건너뛴다 — 빈 줄을 프롬프트에 넣지 않는다', () => {
200
- registerToolCategory({ name: 'a', specs: [] })
201
- registerToolCategory({ name: 'b', guidance: ' ', specs: [] })
203
+ /*
204
+ * This test used to register two categories with no guidance and assert they were skipped, so
205
+ * that no blank line reached the prompt. Registration now refuses them (see the enforcement
206
+ * block below), which means the skip branch inside `getCategoryGuidance` can no longer be
207
+ * reached through the registry — it is left in place only so a mutated entry cannot emit a
208
+ * blank line.
209
+ *
210
+ * What is still worth asserting is the outcome that test was protecting: whatever a caller
211
+ * asks for, the collected guidance never contains an empty string.
212
+ */
213
+ it('collected guidance never contains a blank entry', () => {
214
+ registerToolCategory({ name: 'a', guidance: 'RULE-A', specs: [] })
202
215
  registerToolCategory({ name: 'c', guidance: 'RULE-C', specs: [] })
203
- expect(getCategoryGuidance(undefined)).toEqual(['RULE-C'])
216
+
217
+ for (const collected of [getCategoryGuidance(undefined), getCategoryGuidance(['a']), getCategoryGuidance(['a', 'c'])]) {
218
+ expect(collected.length).toBeGreaterThan(0)
219
+ for (const line of collected) expect(line.trim()).not.toBe('')
220
+ }
221
+ })
222
+ })
223
+
224
+ // ── 지침 강제 ────────────────────────────────────────────────────────
225
+
226
+ describe('registry — 지침 없는 카테고리는 등록되지 않는다', () => {
227
+ /*
228
+ * 왜 이 검사가 있나: 도구 목록만 받은 모델이 「언제 반드시 불러야 하는지」를 못 맞힌 사고가 있었다 —
229
+ * 조치 요청에 `proposeAction` 을 부르지 않고 「제안해 두었습니다」라고 답해 사용자에게 없는 버튼을
230
+ * 누르라고 안내했다. 규율을 적을 자리는 그 뒤에 생겼지만 **선택이었고**, 그래서 그 사고를 아는
231
+ * 사람만 채웠다.
232
+ *
233
+ * 여기서 재는 것은 「빠지면 거절하는가」다. 거절하지 않으면 이 규율은 다음 새 카테고리까지만 간다.
234
+ */
235
+ test('지침이 없으면 던진다', () => {
236
+ const withoutGuidance = { name: 'no-guidance', specs: [] } as unknown as ToolCategory
237
+ expect(() => registerToolCategory(withoutGuidance)).toThrow(/no guidance/)
238
+ expect(getToolCategories()).toEqual([])
239
+ })
240
+
241
+ test('빈 문자열·공백도 거절한다 — 「없음」을 「적었다」로 위장하지 못한다', () => {
242
+ for (const blank of ['', ' ', '\n\t']) {
243
+ const category = { name: 'blank', specs: [], guidance: blank } as ToolCategory
244
+ expect(() => registerToolCategory(category)).toThrow(/no guidance/)
245
+ }
246
+ expect(getToolCategories()).toEqual([])
247
+ })
248
+
249
+ test('거절 문장이 무엇을 하라고 말한다 — 이름만 대면 사람이 다시 찾는다', () => {
250
+ const withoutGuidance = { name: 'no-guidance', specs: [] } as unknown as ToolCategory
251
+ expect(() => registerToolCategory(withoutGuidance)).toThrow(/when the model must call/)
252
+ expect(() => registerToolCategory(withoutGuidance)).toThrow(/no-guidance/)
253
+ })
254
+
255
+ test('지침이 있으면 그대로 등록된다', () => {
256
+ registerToolCategory(makeCategory('ok', [{ name: 'tool1' }]))
257
+ expect(getToolCategories()).toHaveLength(1)
258
+ expect(getToolCategories()[0].guidance).toContain('fixture guidance')
204
259
  })
205
260
  })
@@ -33,6 +33,28 @@ const categories: Map<string, ToolCategory> = new Map()
33
33
  * 카테고리 등록. tool name 충돌 시 throw, 이름 중복 등록 시 덮어쓰기 + warn.
34
34
  */
35
35
  export function registerToolCategory(category: ToolCategory): void {
36
+ /*
37
+ * 지침 없는 카테고리는 **등록하지 않는다.**
38
+ *
39
+ * 도구 목록만 보낸 모델이 「불러야 할 때 부른다」를 맞히지 못한 사고가 있었다 — 조치 요청에
40
+ * `proposeAction` 을 부르지 않고 「제안해 두었습니다」라고 답해, 사용자에게 없는 버튼을 누르라고
41
+ * 안내했다. 화면에는 아무 일도 없었고 오류도 나지 않았다(§`ToolCategory.guidance`).
42
+ *
43
+ * 그 뒤로 규율을 적는 자리를 만들었지만 **선택이었다.** 선택인 규율은 그 사고를 아는 사람만
44
+ * 채운다. 여기서 거절하는 이유가 그것이다 — 빠진 것을 부팅에서 만든 사람이 보고, 모델이 헛말을
45
+ * 한 뒤에 사용자가 보지 않는다.
46
+ *
47
+ * 빈 문자열·공백도 거절한다. 통과시키면 이 검사가 형식이 되고, 형식이 된 검사는 없는 것과 같다.
48
+ */
49
+ if (!String(category.guidance ?? '').trim()) {
50
+ throw new Error(
51
+ `[ai-client-base/tool-registry] category '${category.name}' has no guidance. ` +
52
+ 'Tool descriptions say what a tool does; guidance says when the model must call one. ' +
53
+ 'Without it a model answers as though it called a tool it did not, and nothing errors. ' +
54
+ 'Write the rules for these tools in `guidance` — the side that registers them owns them.'
55
+ )
56
+ }
57
+
36
58
  if (categories.has(category.name)) {
37
59
  console.warn(
38
60
  `[board-ai/tool-registry] category '${category.name}' already registered — overwriting. ` +
@@ -155,6 +155,16 @@ export interface ToolCategory {
155
155
  *
156
156
  * 규율은 도구를 등록한 쪽이 소유한다. 호스트(board-ai)는 도메인을 모르는 채 **노출된 카테고리의
157
157
  * 규율만 모아 붙인다** — 도메인 지식이 호스트 프롬프트로 새지 않는다.
158
+ *
159
+ * ── 왜 필수인가 (2026-09-09) ──────────────────────────────────────────────
160
+ * 선택 필드였다. 그래서 위에 적힌 사고를 아는 사람만 채웠고, 세 제품이 각자 도구를 붙이기
161
+ * 시작한 지금 **채운 넷과 안 채운 하나**가 있었다.
162
+ *
163
+ * 안 채운 쪽은 조용하다 — 등록은 성공하고 부팅도 성공하고, 모델이 도구를 덜 부르거나 지어낸
164
+ * 뒤에 사람이 화면을 보고 안다. **두 개를 기억해야 성립하는 규칙은 다음 새 카테고리까지만
165
+ * 간다.** 그래서 기억이 아니라 등록이 거절한다(§`registerToolCategory`).
166
+ *
167
+ * 빈 문자열도 거절한다. 「없음」을 「적었다」로 위장하는 값이 통과하면 이 강제가 형식이 된다.
158
168
  */
159
- guidance?: string
169
+ guidance: string
160
170
  }
@@ -68,3 +68,52 @@ describe('groundingWarnings — 대화면 진입점', () => {
68
68
  expect(groundingWarnings('지게차들이 바쁘게 움직이고 있습니다.', corpus)).toEqual([])
69
69
  })
70
70
  })
71
+
72
+ /*
73
+ * ── 대문자 식별자 (2026-09-10) ──────────────────────────────────────────────
74
+ *
75
+ * `ID_TOKEN` 이 `[a-z]…` 이던 동안, 대문자 식별자를 쓰는 제품에는 이 가드가 **아예 닿지
76
+ * 않았다.** plant 의 실제 오더 이름이 `WO-ECU-SET-2609B` 이고, 그것에서 추출되는 토큰이 0 개였다.
77
+ *
78
+ * 그 상태의 무서운 점은 조용하다는 것이 아니라 **깨끗해 보인다**는 것이다 — 경고 0 건이 「지어낸
79
+ * 식별자가 없다」로 읽혔다. 없는 것과 안 보는 것이 같은 그림이었다.
80
+ *
81
+ * 이 블록은 그 구멍을 다시 열면 실패한다. 패턴을 소문자로 되돌리고 돌려 확인했다.
82
+ */
83
+ describe('식별자는 대문자도 본다 — 소문자만 보면 두 제품이 통째로 빠진다', () => {
84
+ it('근거에 없는 대문자 오더 번호를 경고한다', () => {
85
+ const warnings = groundingWarnings('WO-ECU-SET-2609B 가 밀렸습니다', '주문 목록: WO-ECU-SET-2601A')
86
+ expect(warnings.join(' ')).toContain('WO-ECU-SET-2609B')
87
+ })
88
+
89
+ it('근거에 있으면 경고하지 않는다', () => {
90
+ expect(groundingWarnings('WO-ECU-SET-2609B 가 밀렸습니다', '{"orders":["WO-ECU-SET-2609B"]}')).toEqual([])
91
+ })
92
+
93
+ it('표기만 다른 것은 다른 대상이 아니다 — 대소문자를 무시하고 대조한다', () => {
94
+ /* 모델이 오더 번호를 소문자로 적는 것은 형식이지 창작이 아니다. 그것을 경고로 만들면
95
+ * 경고가 소음이 되고, 소음이 되면 사람이 경고 자체를 안 본다. */
96
+ expect(groundingWarnings('wo-ecu-set-2609b 가 밀렸습니다', '{"orders":["WO-ECU-SET-2609B"]}')).toEqual([])
97
+ expect(groundingWarnings('WO-ECU-SET-2609B 가 밀렸습니다', '{"orders":["wo-ecu-set-2609b"]}')).toEqual([])
98
+ })
99
+
100
+ it('트윈의 태그도 잡힌다', () => {
101
+ expect(groundingWarnings('TAG-FUNC-AGING 을 적용했습니다', '가용 태그: TAG-FUNC-WELD').join(' ')).toContain(
102
+ 'TAG-FUNC-AGING'
103
+ )
104
+ })
105
+
106
+ it('★ 대문자 영어 합성어는 경고가 아니다 — 넓힌 대가로 소음을 사지 않는다', () => {
107
+ /*
108
+ * 넓히면서 걱정한 것이 이것이다. `filterEntityLike` 가 뒤에서 거른다 — 숫자도 없고 근거에
109
+ * 같은 계열도 없다. 이 줄이 깨지면 넓힌 것이 손해다.
110
+ */
111
+ for (const reply of ['This is Read-Only for now', 'Hand-Off complete', 'a Follow-Up is needed']) {
112
+ expect(groundingWarnings(reply, '보드 상태: 컴포넌트 3개')).toEqual([])
113
+ }
114
+ })
115
+
116
+ it('근거에 같은 계열이 있으면 대문자 합성어도 잡는다 — 같은 계열의 없는 대상', () => {
117
+ expect(groundingWarnings('DOCK-North 로 보냈습니다', '{"docks":["DOCK-South"]}').join(' ')).toContain('DOCK-North')
118
+ })
119
+ })
@@ -18,21 +18,43 @@
18
18
  * 한국어·하이픈 없는 일반어는 애초에 매칭하지 않는다.
19
19
  */
20
20
 
21
- /** id 관례 — 소문자로 시작, 하이픈으로 이어진 소문자·숫자 토큰. `fk-1` `weld-station` `a-dc` 등. */
22
- const ID_TOKEN = /[a-z][a-z0-9]*(?:-[a-z0-9]+)+/g
21
+ /**
22
+ * id 관례 — 영문자로 시작, 하이픈으로 이어진 영숫자 토큰. `fk-1` · `weld-station` · `WO-ECU-2609B`.
23
+ *
24
+ * ── 소문자만 보다가 두 제품을 통째로 놓치고 있었다 (2026-09-10) ──────────────
25
+ * 이 패턴이 `[a-z]…` 였다. 그래서 **대문자 식별자를 쓰는 제품에는 이 가드가 아예 닿지 않았다.**
26
+ * 실측:
27
+ *
28
+ * 'WO-ECU-SET-2609B' → [] plant 의 실제 오더 이름(seed/sets/svm-gunsan.ts)
29
+ * 'TAG-FUNC-AGING' → [] 트윈의 태그
30
+ * 'dock-3' → ['dock-3']
31
+ *
32
+ * 즉 「지어낸 오더 번호를 잡는다」는 보장이 plant 에서는 성립하지 않았고, 경고가 0 건인 것이
33
+ * 「깨끗하다」로 읽혔다. 없는 것과 안 보는 것이 같은 그림이었다.
34
+ *
35
+ * 넓혀도 소음이 늘지 않는 이유는 `filterEntityLike` 가 뒤에 있기 때문이다 — `Read-Only` 는 숫자도
36
+ * 없고 근거에 `Read-` 계열도 없어 그대로 걸러진다.
37
+ */
38
+ const ID_TOKEN = /[A-Za-z][A-Za-z0-9]*(?:-[A-Za-z0-9]+)+/g
23
39
 
24
- /** 문자열에서 id 후보 토큰을 뽑는다(중복 제거). */
40
+ /** 문자열에서 id 후보 토큰을 뽑는다(중복 제거). **쓰인 그대로** 담는다 — 사람에게 보일 값이다. */
25
41
  export function extractIdTokens(s: string): Set<string> {
26
42
  const out = new Set<string>()
27
43
  for (const m of (s ?? '').matchAll(ID_TOKEN)) out.add(m[0])
28
44
  return out
29
45
  }
30
46
 
31
- /** 답이 언급한 id − 근거 코퍼스의 id = 미확인(환각 후보). 순서는 답에 나온 순서. */
47
+ /**
48
+ * 답이 언급한 id − 근거 코퍼스의 id = 미확인(환각 후보). 순서는 답에 나온 순서.
49
+ *
50
+ * **대조는 대소문자를 무시한다.** 모델이 `WO-2609B` 를 `wo-2609b` 로 적는 것은 표기이지 다른
51
+ * 대상이 아니다. 엄격히 보면 그 한 글자 차이로 정상 답이 경고를 받고, 그런 경고가 몇 번 나오면
52
+ * 사람이 경고 자체를 안 본다. 대소문자만 다른 두 식별자를 쓰는 체계라면 그것이 먼저 고칠 문제다.
53
+ */
32
54
  export function checkGrounding(reply: string, groundedCorpus: string): string[] {
33
- const grounded = extractIdTokens(groundedCorpus)
55
+ const grounded = new Set([...extractIdTokens(groundedCorpus)].map(id => id.toLowerCase()))
34
56
  const mentioned = extractIdTokens(reply)
35
- return [...mentioned].filter(id => !grounded.has(id))
57
+ return [...mentioned].filter(id => !grounded.has(id.toLowerCase()))
36
58
  }
37
59
 
38
60
  /**
@@ -51,9 +73,11 @@ export function checkGrounding(reply: string, groundedCorpus: string): string[]
51
73
  * 잡으려면 일반 영어 합성어를 함께 잡게 되므로, 이 가드는 **정확도를 택하고 재현율을 버린다**.
52
74
  */
53
75
  export function filterEntityLike(tokens: string[], groundedCorpus: string): string[] {
76
+ /* 계열 대조도 대소문자를 무시한다 — `checkGrounding` 과 같은 규칙이어야 한다. 한쪽만 엄격하면
77
+ * 근거에 `WO-1` 이 있는데 답의 `wo-7` 이 계열 밖으로 새어 경고를 놓친다. */
54
78
  const families = new Set<string>()
55
- for (const id of extractIdTokens(groundedCorpus)) families.add(id.split('-')[0])
56
- return tokens.filter(t => /[0-9]/.test(t) || families.has(t.split('-')[0]))
79
+ for (const id of extractIdTokens(groundedCorpus)) families.add(id.split('-')[0].toLowerCase())
80
+ return tokens.filter(t => /[0-9]/.test(t) || families.has(t.split('-')[0].toLowerCase()))
57
81
  }
58
82
 
59
83
  /**
@@ -63,3 +87,45 @@ export function filterEntityLike(tokens: string[], groundedCorpus: string): stri
63
87
  export function groundingWarnings(reply: string, groundedCorpus: string): string[] {
64
88
  return filterEntityLike(checkGrounding(reply, groundedCorpus), groundedCorpus)
65
89
  }
90
+
91
+ /*
92
+ * ── 근거집합의 정의 (2026-09-10 에 board-ai 에서 옮겨 왔다) ────────────────────
93
+ *
94
+ * 이 모양이 `board-ai` 에 있었고, 그래서 접지 검사를 하려면 보드 편집기를 지나야 했다. 판정 규칙은
95
+ * 여기 있었는데 **무엇을 근거로 볼 것인가**가 저기 있었으니, 보드가 없는 제품은 규칙만 있고 쓸 길이
96
+ * 없었다. 자리는 있고 길이 없는 쪽이다.
97
+ *
98
+ * 옮기면서 칸 하나를 고쳤다: `boardContext` → `hostContext`. 근거는 보드일 수도 있고 공장 현황일
99
+ * 수도 있고 저작 중인 자산일 수도 있다 — 그것을 아는 것은 호스트뿐이다.
100
+ *
101
+ * **하나라도 빼면 정상 답이 경고를 받는다.** 모델이 시스템 프롬프트에서 읽은 타입 이름을 말하는 것은
102
+ * 근거 있는 발언이다. 그래서 이 목록은 「모델이 이 턴에 본 것 전부」이고, 줄이는 것이 아니라 채우는
103
+ * 것이 맞다.
104
+ */
105
+ export interface GroundingSources {
106
+ /** 시스템 프롬프트 — 생성 가능한 타입 목록·규칙 등. 여기 있는 이름을 말하는 것은 정상이다. */
107
+ systemPrompt?: string
108
+ /** 호스트가 대화 앞에 붙인 문맥 — 보드 요약·현장 상태·저작 중인 자산. */
109
+ hostContext?: string
110
+ /** 사용자·어시스턴트 이력 텍스트. 사용자가 말한 식별자를 되받는 것은 정상이다. */
111
+ messages?: string[]
112
+ /**
113
+ * `tool_result` 로 회신된 **원문**(시간순).
114
+ *
115
+ * ⚠ `toolUsages[].result` 를 넣지 말 것 — 그것은 화면 표시용으로 깊이·길이가 잘린 값이다. 잘려
116
+ * 나간 식별자를 「근거 없음」으로 오판한다. 넣을 값은 `AgenticLoopResult.groundedTexts` 다.
117
+ */
118
+ toolResults?: string[]
119
+ }
120
+
121
+ /** 근거집합을 한 덩어리로. 식별자 토큰만 대조하므로 구분자는 개행으로 충분하다. */
122
+ export function buildGroundedCorpus(sources: GroundingSources): string {
123
+ return [
124
+ sources.systemPrompt ?? '',
125
+ sources.hostContext ?? '',
126
+ ...(sources.messages ?? []),
127
+ ...(sources.toolResults ?? [])
128
+ ]
129
+ .filter(Boolean)
130
+ .join('\n')
131
+ }