@things-factory/board-ai 10.0.2 → 10.0.3

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 (60) hide show
  1. package/client/components/board-ai-chat.ts +458 -19
  2. package/client/components/chat-echo-dedup.test.ts +59 -3
  3. package/client/components/chat-echo-dedup.ts +29 -0
  4. package/dist-client/client/components/board-ai-chat.d.ts +63 -0
  5. package/dist-client/client/components/board-ai-chat.js +438 -16
  6. package/dist-client/client/components/board-ai-chat.js.map +1 -1
  7. package/dist-client/client/components/chat-echo-dedup.js +28 -0
  8. package/dist-client/client/components/chat-echo-dedup.js.map +1 -1
  9. package/dist-client/client/components/chat-echo-dedup.test.js +53 -3
  10. package/dist-client/client/components/chat-echo-dedup.test.js.map +1 -1
  11. package/dist-client/server/service/agentic-loop.d.ts +15 -0
  12. package/dist-client/server/service/agentic-loop.js +70 -9
  13. package/dist-client/server/service/agentic-loop.js.map +1 -1
  14. package/dist-client/server/service/assistant.js +18 -3
  15. package/dist-client/server/service/assistant.js.map +1 -1
  16. package/dist-client/server/service/types.d.ts +23 -0
  17. package/dist-client/server/service/types.js.map +1 -1
  18. package/dist-client/tsconfig.tsbuildinfo +1 -1
  19. package/dist-server/service/agentic-loop.d.ts +15 -0
  20. package/dist-server/service/agentic-loop.js +71 -9
  21. package/dist-server/service/agentic-loop.js.map +1 -1
  22. package/dist-server/service/assistant.js +17 -2
  23. package/dist-server/service/assistant.js.map +1 -1
  24. package/dist-server/service/board-ai-resolver.d.ts +13 -0
  25. package/dist-server/service/board-ai-resolver.js +99 -1
  26. package/dist-server/service/board-ai-resolver.js.map +1 -1
  27. package/dist-server/service/chat-message/fold-history.d.ts +30 -0
  28. package/dist-server/service/chat-message/fold-history.js +29 -0
  29. package/dist-server/service/chat-message/fold-history.js.map +1 -0
  30. package/dist-server/service/chat-message/history-summary.d.ts +43 -0
  31. package/dist-server/service/chat-message/history-summary.js +77 -0
  32. package/dist-server/service/chat-message/history-summary.js.map +1 -0
  33. package/dist-server/service/chat-message/llm-history.d.ts +19 -0
  34. package/dist-server/service/chat-message/llm-history.js +31 -1
  35. package/dist-server/service/chat-message/llm-history.js.map +1 -1
  36. package/dist-server/service/chat-session/chat-session.d.ts +8 -0
  37. package/dist-server/service/chat-session/chat-session.js +5 -0
  38. package/dist-server/service/chat-session/chat-session.js.map +1 -1
  39. package/dist-server/service/types.d.ts +23 -0
  40. package/dist-server/service/types.js.map +1 -1
  41. package/dist-server/tsconfig.tsbuildinfo +1 -1
  42. package/package.json +6 -6
  43. package/server/service/agentic-loop.test.ts +91 -0
  44. package/server/service/agentic-loop.ts +80 -9
  45. package/server/service/assistant.ts +21 -3
  46. package/server/service/board-ai-resolver.ts +108 -1
  47. package/server/service/chat-message/fold-history.test.ts +98 -0
  48. package/server/service/chat-message/fold-history.ts +60 -0
  49. package/server/service/chat-message/history-summary.test.ts +127 -0
  50. package/server/service/chat-message/history-summary.ts +100 -0
  51. package/server/service/chat-message/llm-history.test.ts +65 -0
  52. package/server/service/chat-message/llm-history.ts +48 -1
  53. package/server/service/chat-session/chat-session.ts +11 -0
  54. package/server/service/dock-contract.test.ts +305 -0
  55. package/server/service/types.ts +23 -0
  56. package/translations/en.json +14 -1
  57. package/translations/ja.json +14 -1
  58. package/translations/ko.json +13 -0
  59. package/translations/ms.json +14 -1
  60. package/translations/zh.json +14 -1
@@ -0,0 +1,60 @@
1
+ /*
2
+ * 요약 접기 오케스트레이션 — **판정과 조립은 여기, DB 는 호출부**.
3
+ *
4
+ * 왜 분리하는가: 요약을 만드는 결정(무엇을·언제·무엇에 이어)은 규칙이고, 규칙은 테스트로 고정할 수
5
+ * 있어야 한다. 리졸버 안에 두면 DB 없이 검증할 수 없어 "배선했지만 한 번도 안 돌아본" 코드가 된다.
6
+ * 요약 생성기(LLM)와 이력·저장은 호출부가 주입한다.
7
+ */
8
+ import type { HistoryRow } from './llm-history.js'
9
+ import {
10
+ splitByCap,
11
+ pendingForSummary,
12
+ shouldResummarize,
13
+ summaryUserContent,
14
+ summaryPatch,
15
+ type StoredSummary
16
+ } from './history-summary.js'
17
+
18
+ export interface FoldHistoryInput {
19
+ /** 시간 오름차순 이력 전체. */
20
+ rows: HistoryRow[]
21
+ /** 세션에 저장된 요약 상태. */
22
+ stored?: StoredSummary
23
+ /** 프롬프트 상한(이 밖으로 밀려난 것이 요약 대상). */
24
+ maxTurns: number
25
+ /** 새로 밀려난 것이 이 수 이상일 때만 요약을 만든다(매 턴 호출 방지). */
26
+ threshold: number
27
+ /** 요약 생성 — 실패하면 throw 하거나 빈 문자열을 돌려주면 된다(둘 다 "접지 않음" 으로 처리). */
28
+ summarize: (content: string) => Promise<string | undefined | null>
29
+ }
30
+
31
+ export interface FoldHistoryResult {
32
+ /** 세션에 저장할 값. null 이면 이번엔 접지 않는다(대상 없음·임계치 미만·생성 실패). */
33
+ patch: { lastSummary: string; summaryUpToMessageId?: string } | null
34
+ /** 접지 않은 이유 — 관측·테스트용(조용한 무동작을 남기지 않는다). */
35
+ skipped?: 'nothing-dropped' | 'below-threshold' | 'empty-summary' | 'failed'
36
+ }
37
+
38
+ /**
39
+ * 접을지 판정하고, 접어야 하면 요약을 만들어 저장 값을 돌려준다.
40
+ *
41
+ * 실패를 삼키되 **왜 안 접었는지**는 남긴다 — 조용한 무동작은 나중에 "요약이 왜 안 생기지" 를
42
+ * 추적 불가능하게 만든다.
43
+ */
44
+ export async function foldHistorySummary(input: FoldHistoryInput): Promise<FoldHistoryResult> {
45
+ const { dropped } = splitByCap(input.rows, input.maxTurns)
46
+ if (dropped.length === 0) return { patch: null, skipped: 'nothing-dropped' }
47
+
48
+ const pending = pendingForSummary(dropped, input.stored)
49
+ if (!shouldResummarize(pending, input.threshold)) return { patch: null, skipped: 'below-threshold' }
50
+
51
+ let text: string | undefined | null
52
+ try {
53
+ text = await input.summarize(summaryUserContent(input.stored?.text, pending))
54
+ } catch {
55
+ return { patch: null, skipped: 'failed' }
56
+ }
57
+ if (!text || !text.trim()) return { patch: null, skipped: 'empty-summary' }
58
+
59
+ return { patch: summaryPatch(text, pending) }
60
+ }
@@ -0,0 +1,127 @@
1
+ /*
2
+ * 이력 요약 접기 규칙 검증.
3
+ *
4
+ * 무엇을 지키는가:
5
+ * ① **누적** — 이전 요약 뒤부터만 새로 접는다(전체 재요약=비용, 중복 접기=왜곡).
6
+ * ② **아껴 만든다** — 새로 밀려난 것이 임계치를 넘을 때만. 상한 넘긴 뒤 매 턴 부르면 호출이 두 배.
7
+ * ③ **덮은 범위를 함께 저장** — 본문과 upToMessageId 는 항상 같이 간다(따로 저장하면 어긋난다).
8
+ * ④ **모르면 다시 요약** — 기록된 id 를 이력에서 못 찾으면 전부 미반영으로 본다(맥락 상실 방지).
9
+ * ⑤ **지시는 사실 위주** — 결정·미결·식별자 보존을 요구하고 창작을 금지한다.
10
+ */
11
+ import {
12
+ splitByCap,
13
+ pendingForSummary,
14
+ shouldResummarize,
15
+ summarySourceText,
16
+ summaryUserContent,
17
+ summaryInstruction,
18
+ summaryPatch
19
+ } from './history-summary'
20
+
21
+ const rows = (n: number, from = 0) =>
22
+ Array.from({ length: n }, (_, i) => ({
23
+ id: `m${from + i}`,
24
+ role: (from + i) % 2 ? 'assistant' : 'user',
25
+ content: `말 ${from + i}`
26
+ }))
27
+
28
+ describe('splitByCap', () => {
29
+ it('상한 이하면 아무것도 밀려나지 않는다', () => {
30
+ const r = splitByCap(rows(5), 10)
31
+ expect(r.dropped).toEqual([])
32
+ expect(r.kept).toHaveLength(5)
33
+ })
34
+
35
+ it('상한을 넘으면 앞부분이 밀려나고 최근이 남는다', () => {
36
+ const r = splitByCap(rows(12), 4)
37
+ expect(r.dropped).toHaveLength(8)
38
+ expect(r.kept.map(x => x.id)).toEqual(['m8', 'm9', 'm10', 'm11'])
39
+ })
40
+ })
41
+
42
+ describe('pendingForSummary — 누적', () => {
43
+ const dropped = rows(8)
44
+
45
+ it('요약이 없으면 밀려난 전부가 대상', () => {
46
+ expect(pendingForSummary(dropped, undefined)).toHaveLength(8)
47
+ })
48
+
49
+ it('요약이 덮은 지점 뒤부터만 대상 — 이미 접은 것을 또 접지 않는다', () => {
50
+ const p = pendingForSummary(dropped, { text: '앞부분 요약', upToMessageId: 'm4' })
51
+ expect(p.map(x => x.id)).toEqual(['m5', 'm6', 'm7'])
52
+ })
53
+
54
+ it('기록된 id 를 못 찾으면 전부 다시 — 빠뜨리는 쪽보다 안전하다', () => {
55
+ const p = pendingForSummary(dropped, { text: '요약', upToMessageId: 'deleted' })
56
+ expect(p).toHaveLength(8)
57
+ })
58
+
59
+ it('본문 없는 기록은 요약이 없는 것으로 본다', () => {
60
+ expect(pendingForSummary(dropped, { text: '', upToMessageId: 'm4' })).toHaveLength(8)
61
+ })
62
+ })
63
+
64
+ describe('shouldResummarize — 아껴 만들기', () => {
65
+ it('임계치를 넘으면 만든다', () => {
66
+ expect(shouldResummarize(rows(10), 10)).toBe(true)
67
+ })
68
+ it('임계치 미만이면 만들지 않는다 — 매 턴 호출 방지', () => {
69
+ expect(shouldResummarize(rows(9), 10)).toBe(false)
70
+ })
71
+ it('밀려난 것이 없으면 만들지 않는다', () => {
72
+ expect(shouldResummarize([], 10)).toBe(false)
73
+ })
74
+ })
75
+
76
+ describe('요약 입력', () => {
77
+ it('발신자 표기를 유지한다 — 협의에서 누가 말했는지가 핵심 정보', () => {
78
+ const text = summarySourceText([
79
+ { id: 'a', role: 'user', content: '도크 포화 확인 필요', senderName: '김철수' },
80
+ { id: 'b', role: 'assistant', content: 'dock-1 점유 92%' },
81
+ { id: 'c', role: 'system', content: '실행됨: o7 보류' }
82
+ ])
83
+ expect(text).toContain('김철수: 도크 포화 확인 필요')
84
+ expect(text).toContain('AI: dock-1 점유 92%')
85
+ expect(text).toContain('SYSTEM: 실행됨: o7 보류')
86
+ })
87
+
88
+ it('이전 요약을 앞에 얹어 누적 입력을 만든다', () => {
89
+ const content = summaryUserContent('앞에서 정한 것: 지게차 1대 추가', rows(2))
90
+ expect(content).toContain('SUMMARY SO FAR')
91
+ expect(content).toContain('지게차 1대 추가')
92
+ expect(content).toContain('NEW MESSAGES TO FOLD IN')
93
+ })
94
+
95
+ it('이전 요약이 없으면 새 대화만 넣는다', () => {
96
+ expect(summaryUserContent(null, rows(2))).not.toContain('SUMMARY SO FAR')
97
+ })
98
+ })
99
+
100
+ describe('요약 지시', () => {
101
+ const instruction = summaryInstruction()
102
+
103
+ it('결정·미결을 남기라고 요구한다 — 그게 나중까지 필요한 것이다', () => {
104
+ expect(instruction).toMatch(/decided/i)
105
+ expect(instruction).toMatch(/still open/i)
106
+ })
107
+
108
+ it('식별자를 그대로 보존하라고 요구한다 — 이름이 바뀌면 이후 접지가 깨진다', () => {
109
+ expect(instruction).toMatch(/identifiers/i)
110
+ expect(instruction).toMatch(/EXACTLY/)
111
+ })
112
+
113
+ it('없는 사실을 더하지 말라고 못박는다', () => {
114
+ expect(instruction).toMatch(/Never add facts/i)
115
+ })
116
+ })
117
+
118
+ describe('summaryPatch — 본문과 범위는 함께', () => {
119
+ it('마지막으로 접은 메시지 id 를 함께 저장한다', () => {
120
+ const patch = summaryPatch('요약 본문', rows(3))
121
+ expect(patch).toEqual({ lastSummary: '요약 본문', summaryUpToMessageId: 'm2' })
122
+ })
123
+
124
+ it('본문은 상한(4000)으로 자른다 — 요약이 프롬프트를 다시 부풀리지 않게', () => {
125
+ expect(summaryPatch('가'.repeat(5000), rows(1)).lastSummary).toHaveLength(4000)
126
+ })
127
+ })
@@ -0,0 +1,100 @@
1
+ /*
2
+ * 이력 요약 접기 — 긴 협의의 앞부분을 **요약으로 대체**한다.
3
+ *
4
+ * ── 왜 필요한가 ─────────────────────────────────────────────────────────────
5
+ * 모델은 기억이 없어 매 턴 이력을 다시 받는다. 그래서 상한(maxTurns)을 두었지만, 상한만으로는
6
+ * 넘친 앞부분이 **그냥 사라진다** — 며칠 이어지는 협의에서 앞에서 합의한 내용이 없던 일이 된다.
7
+ * 요약을 대신 실어 보내면 토큰은 상한 안에 머물면서 맥락은 남는다.
8
+ *
9
+ * ── 규율 ────────────────────────────────────────────────────────────────────
10
+ * ① **어디까지 요약했는지 기록한다**(upToMessageId). 그것이 없으면 매 턴 전체를 다시 요약하거나
11
+ * (비용) 이미 요약한 것을 또 이어 붙인다(중복).
12
+ * ② **누적 요약**이다: 이전 요약 + 새로 밀려난 메시지 → 새 요약. 원본 전체를 다시 읽지 않는다.
13
+ * ③ **아껴 만든다**: 새로 밀려난 것이 임계치를 넘을 때만 다시 만든다. 상한을 넘긴 뒤 매 턴
14
+ * 요약을 만들면 대화마다 LLM 호출이 두 번씩 붙는다.
15
+ * ④ **요약은 요약이라고 밝힌다**: 프롬프트에 "요약(원문 아님)" 으로 표기해 모델이 그것을 인용
16
+ * 가능한 원문처럼 다루지 않게 한다. 요약에 없는 사실은 사용자에게 다시 확인해야 한다.
17
+ *
18
+ * 이 파일은 순수 로직이다 — LLM 호출·DB 는 리졸버가 한다(테스트 가능성 유지).
19
+ */
20
+ import type { HistoryRow } from './llm-history.js'
21
+
22
+ /** 세션에 저장된 요약 상태. */
23
+ export interface StoredSummary {
24
+ /** 요약 본문(사람이 읽어도 되는 몇 문장). 없으면 아직 요약이 없다. */
25
+ text?: string | null
26
+ /** 이 메시지까지 요약에 반영됐다. 이후 메시지는 아직 요약 밖. */
27
+ upToMessageId?: string | null
28
+ }
29
+
30
+ /** 상한 기준으로 이력을 둘로 나눈다 — 밀려나는 앞부분과 원문으로 남길 최근 부분. */
31
+ export function splitByCap(rows: HistoryRow[], maxTurns: number): { dropped: HistoryRow[]; kept: HistoryRow[] } {
32
+ if (!maxTurns || maxTurns <= 0 || rows.length <= maxTurns) return { dropped: [], kept: rows }
33
+ return { dropped: rows.slice(0, rows.length - maxTurns), kept: rows.slice(-maxTurns) }
34
+ }
35
+
36
+ /**
37
+ * 아직 요약에 반영되지 않은, 밀려난 메시지들.
38
+ *
39
+ * 저장된 요약이 어디까지 덮는지(upToMessageId)를 기준으로 그 **뒤부터** 센다. 기록된 id 가 이력에
40
+ * 없으면(삭제·편집) 덮은 범위를 알 수 없으므로 **전부 미반영으로 본다** — 빠뜨리는 쪽보다 다시
41
+ * 요약하는 쪽이 안전하다(맥락 상실은 답을 망친다).
42
+ */
43
+ export function pendingForSummary(dropped: HistoryRow[], stored: StoredSummary | undefined): HistoryRow[] {
44
+ const upTo = stored?.upToMessageId
45
+ if (!upTo || !stored?.text) return dropped
46
+ const idx = dropped.findIndex(r => r.id === upTo)
47
+ return idx < 0 ? dropped : dropped.slice(idx + 1)
48
+ }
49
+
50
+ /**
51
+ * 요약을 다시 만들 때인가 — 새로 밀려난 것이 임계치 이상일 때만.
52
+ * (상한을 넘긴 뒤 매 턴 만들면 대화마다 LLM 호출이 두 번씩 붙는다.)
53
+ */
54
+ export function shouldResummarize(pending: HistoryRow[], threshold = 10): boolean {
55
+ return pending.length >= Math.max(1, threshold)
56
+ }
57
+
58
+ /** 요약 대상 텍스트 — 발신자 표기를 유지해 누가 무엇을 말했는지 남긴다(협의의 핵심 정보). */
59
+ export function summarySourceText(pending: HistoryRow[]): string {
60
+ return pending
61
+ .map(r => {
62
+ const who = r.role === 'assistant' ? 'AI' : r.role === 'system' ? 'SYSTEM' : r.senderName || 'USER'
63
+ return `${who}: ${(r.content ?? '').trim()}`
64
+ })
65
+ .filter(line => line.length > 6)
66
+ .join('\n')
67
+ }
68
+
69
+ /**
70
+ * 요약 생성 지시 — **사실만, 짧게, 지어내지 말 것.**
71
+ *
72
+ * 협의에서 나중까지 필요한 것은 "무엇을 확인했고, 무엇을 정했고, 무엇이 남았는지" 다. 잡담·인사는
73
+ * 버려도 되지만 **결정과 미결**은 남아야 한다. 식별자는 원문 그대로 유지하라고 지시한다 — 요약이
74
+ * 이름을 바꾸면 이후 대화의 접지가 깨진다.
75
+ */
76
+ export function summaryInstruction(locale?: string): string {
77
+ return [
78
+ 'Summarize the earlier part of a shared operations deliberation so it can be carried into later turns.',
79
+ 'Keep ONLY what stays relevant: what was checked and found, what was decided, what is still open, and any action that was executed.',
80
+ 'Drop greetings, small talk, and repetition.',
81
+ 'Preserve identifiers (node / order / instance ids) EXACTLY as written — renaming them breaks grounding in later turns.',
82
+ 'Never add facts that are not in the text. If something is unclear, leave it out.',
83
+ 'At most 8 short bullet points. No preamble, no closing remark.',
84
+ locale ? `Write the summary in the language of locale "${locale}".` : ''
85
+ ]
86
+ .filter(Boolean)
87
+ .join(' ')
88
+ }
89
+
90
+ /** 이전 요약과 새로 밀려난 대화를 합쳐 넘길 본문 — 누적 요약의 입력. */
91
+ export function summaryUserContent(previous: string | null | undefined, pending: HistoryRow[]): string {
92
+ const head = previous?.trim() ? `SUMMARY SO FAR:\n${previous.trim()}\n\n` : ''
93
+ return `${head}NEW MESSAGES TO FOLD IN:\n${summarySourceText(pending)}`
94
+ }
95
+
96
+ /** 요약 저장 값 — 본문과 "어디까지 덮었는지". 둘은 항상 함께 저장한다(따로 저장하면 어긋난다). */
97
+ export function summaryPatch(text: string, pending: HistoryRow[]): { lastSummary: string; summaryUpToMessageId?: string } {
98
+ const last = [...pending].reverse().find(r => r.id)?.id
99
+ return { lastSummary: text.trim().slice(0, 4000), summaryUpToMessageId: last }
100
+ }
@@ -127,3 +127,68 @@ describe('기타', () => {
127
127
  expect(out.map(m => m.content)).toEqual(['A', 'B', 'C'])
128
128
  })
129
129
  })
130
+
131
+ describe('이력 상한 — 협의가 길어질 때', () => {
132
+ const rows = (n: number) =>
133
+ Array.from({ length: n }, (_, i) => ({ id: `m${i}`, role: i % 2 ? 'assistant' : 'user', content: `말 ${i}` }))
134
+
135
+ it('상한 미지정이면 전부 보낸다 — 기존 동작 유지', () => {
136
+ expect(buildLlmHistory(rows(10))).toHaveLength(10)
137
+ })
138
+
139
+ it('상한을 넘으면 최근 것만 남긴다 — 오래된 말보다 최근 상황이 답을 좌우한다', () => {
140
+ const out = buildLlmHistory(rows(10), { maxTurns: 4 })
141
+ /* 생략 알림 1줄 + 최근 4줄 */
142
+ expect(out).toHaveLength(5)
143
+ expect(out[out.length - 1].content).toContain('말 9')
144
+ })
145
+
146
+ it('생략은 **반드시 알린다** — 조용히 버리면 모델이 남은 첫 줄을 대화의 시작으로 오해한다', () => {
147
+ const out = buildLlmHistory(rows(10), { maxTurns: 4 })
148
+ expect(out[0].content).toContain('6개')
149
+ expect(out[0].content).toContain('생략')
150
+ })
151
+
152
+ it('상한에 걸리지 않으면 알림을 붙이지 않는다 — 없는 생략을 말하지 않는다', () => {
153
+ const out = buildLlmHistory(rows(3), { maxTurns: 10 })
154
+ expect(out).toHaveLength(3)
155
+ expect(out[0].content).toBe('말 0')
156
+ })
157
+
158
+ it('접은 구간 제거가 먼저, 상한이 나중 — 두 규칙이 겹쳐도 최근 것이 남는다', () => {
159
+ const out = buildLlmHistory(rows(10), { truncateAfterMessageId: 'm5', maxTurns: 3 })
160
+ expect(out).toHaveLength(4) // 알림 + 3
161
+ expect(out[out.length - 1].content).toContain('말 5')
162
+ })
163
+ })
164
+
165
+ describe('이력 요약 접기 — 프롬프트 조립', () => {
166
+ const rows = (n: number) =>
167
+ Array.from({ length: n }, (_, i) => ({ id: `m${i}`, role: i % 2 ? 'assistant' : 'user', content: `말 ${i}` }))
168
+
169
+ it('요약이 있으면 "생략" 대신 요약을 싣는다 — 앞에서 정한 것이 없던 일이 되지 않게', () => {
170
+ const out = buildLlmHistory(rows(10), {
171
+ maxTurns: 4,
172
+ summary: { text: '앞에서 정한 것: 지게차 1대 추가', upToMessageId: 'm5' }
173
+ })
174
+ expect(out[0].content).toContain('지게차 1대 추가')
175
+ expect(out[0].content).not.toContain('생략되었습니다.')
176
+ })
177
+
178
+ it('요약임을 밝힌다 — 모델이 원문처럼 인용하지 않게', () => {
179
+ const out = buildLlmHistory(rows(10), { maxTurns: 4, summary: { text: '요약본', upToMessageId: 'm5' } })
180
+ expect(out[0].content).toContain('원문 아님')
181
+ })
182
+
183
+ it('요약이 밀려난 구간을 다 덮지 못하면 남은 개수를 밝힌다 — 최신이 아님을 숨기지 않는다', () => {
184
+ /* 밀려난 것은 m0..m5(6개), 요약은 m3 까지 → m4·m5 두 개가 미반영. */
185
+ const out = buildLlmHistory(rows(10), { maxTurns: 4, summary: { text: '요약본', upToMessageId: 'm3' } })
186
+ expect(out[0].content).toContain('2개')
187
+ })
188
+
189
+ it('상한에 걸리지 않으면 요약을 싣지 않는다 — 필요 없는 문맥을 넣지 않는다', () => {
190
+ const out = buildLlmHistory(rows(3), { maxTurns: 10, summary: { text: '요약본', upToMessageId: 'm0' } })
191
+ expect(out).toHaveLength(3)
192
+ expect(out[0].content).toBe('말 0')
193
+ })
194
+ })
@@ -35,6 +35,7 @@
35
35
  * "내 발언만 접기"는 별도 개선으로 다룬다.
36
36
  */
37
37
  import type { LLMMessage } from '../types.js'
38
+ import { pendingForSummary, type StoredSummary } from './history-summary.js'
38
39
 
39
40
  /** 이력 한 줄 — 저장된 ChatMessage 에서 필요한 것만(엔티티·typeorm 비의존). */
40
41
  export interface HistoryRow {
@@ -55,12 +56,32 @@ export interface BuildLlmHistoryOptions {
55
56
  keepMessageIds?: string[]
56
57
  /** 발신자 표기 강제 — 미지정이면 사람 발신자가 둘 이상일 때만 표기. 테스트·특수 호출용. */
57
58
  labelSenders?: boolean
59
+ /**
60
+ * 모델에 넘길 **최근 메시지 수 상한**. 초과분(오래된 앞부분)은 버리고 생략 표시를 남긴다.
61
+ *
62
+ * 왜 필요한가: 협의는 며칠에 걸친다. 상한이 없으면 매 턴 전체 이력을 보내 프롬프트가 무한히
63
+ * 자라고(비용·지연·문맥 한계) 오래된 말이 최근 상황을 덮는다. 미지정이면 전부 보낸다(기존 동작).
64
+ *
65
+ * **생략은 반드시 알린다** — 조용히 버리면 모델은 남은 첫 줄을 대화의 시작으로 오해한다.
66
+ * 이건 상한일 뿐 요약이 아니다. 버린 내용을 요약해 실어 보내는 것은 다음 단계다(ChatSession.lastSummary).
67
+ */
68
+ maxTurns?: number
69
+ /**
70
+ * 상한으로 밀려난 앞부분을 대신할 **요약**(세션에 저장된 것).
71
+ *
72
+ * 있으면 "N개 생략" 대신 요약을 첫 줄로 싣는다 — 며칠 이어지는 협의에서 앞에서 합의한 것이
73
+ * 없던 일이 되지 않게. 요약이 밀려난 구간을 **전부 덮지 못하면** 덮지 못한 개수도 함께 밝힌다
74
+ * (요약이 최신이 아닐 수 있다는 사실을 숨기지 않는다).
75
+ */
76
+ summary?: StoredSummary
58
77
  }
59
78
 
60
79
  /** 사람이 아닌 기록(캔버스 직접 편집 등)의 표기. */
61
80
  const SYSTEM_LABEL = '시스템'
62
81
  /** 이름을 모르는 참여자의 표기 — 빈 대괄호를 남기지 않는다. */
63
82
  const UNKNOWN_LABEL = '참여자'
83
+ /** 상한으로 잘라낸 앞부분을 알리는 표기 — 모델이 남은 첫 줄을 대화의 시작으로 오해하지 않게. */
84
+ const OMITTED_LABEL = '시스템'
64
85
 
65
86
  /**
66
87
  * 저장된 이력 → LLM 대화.
@@ -70,12 +91,38 @@ const UNKNOWN_LABEL = '참여자'
70
91
  */
71
92
  export function buildLlmHistory(rows: HistoryRow[], options: BuildLlmHistoryOptions = {}): LLMMessage[] {
72
93
  const keep = new Set(options.keepMessageIds ?? [])
73
- const kept = truncate(rows, options.truncateAfterMessageId, keep)
94
+ const truncated = truncate(rows, options.truncateAfterMessageId, keep)
95
+ /* 상한 — 최근 것부터 남긴다. 오래된 말보다 최근 상황이 답을 좌우한다. */
96
+ const limit = options.maxTurns && options.maxTurns > 0 ? options.maxTurns : 0
97
+ const omitted = limit && truncated.length > limit ? truncated.length - limit : 0
98
+ const kept = omitted ? truncated.slice(-limit) : truncated
74
99
 
75
100
  const label =
76
101
  options.labelSenders ?? new Set(kept.filter(r => isHuman(r)).map(r => r.senderId ?? '')).size > 1
77
102
 
78
103
  const out: LLMMessage[] = []
104
+ if (omitted) {
105
+ const dropped = truncated.slice(0, truncated.length - kept.length)
106
+ const summaryText = (options.summary?.text ?? '').trim()
107
+ if (summaryText) {
108
+ /* 요약이 있으면 그것을 싣는다. **요약임을 밝힌다** — 모델이 원문처럼 인용하지 않게.
109
+ * 요약이 밀려난 구간을 다 덮지 못하면 남은 개수도 함께 알린다(최신이 아님을 숨기지 않는다). */
110
+ const uncovered = pendingForSummary(dropped, options.summary).length
111
+ const tail = uncovered
112
+ ? ` 그 뒤 ${uncovered}개 메시지는 요약에 아직 반영되지 않았습니다.`
113
+ : ''
114
+ out.push({
115
+ role: 'user',
116
+ content: `[${OMITTED_LABEL}] 이 대화의 앞부분 ${dropped.length}개 메시지는 길이 제한으로 아래 요약으로 대체되었습니다(원문 아님 — 요약에 없는 사실은 사용자에게 확인하세요).${tail}\n${summaryText}`
117
+ })
118
+ } else {
119
+ /* 요약이 아직 없으면 생략 사실만 알린다 — 개수만 밝히고 내용은 지어내지 않는다. */
120
+ out.push({
121
+ role: 'user',
122
+ content: `[${OMITTED_LABEL}] 이 대화의 앞부분 ${omitted}개 메시지는 길이 제한으로 생략되었습니다. 필요하면 사용자에게 다시 확인하세요.`
123
+ })
124
+ }
125
+ }
79
126
  for (const row of kept) {
80
127
  const content = (row.content ?? '').trim()
81
128
  if (!content) continue // 빈 본문(pending 자리 등)은 모델에 넘길 것이 없다
@@ -146,6 +146,17 @@ export class ChatSession {
146
146
  @Field({ nullable: true, description: 'Compressed summary of older messages (for token saving).' })
147
147
  lastSummary?: string
148
148
 
149
+ /**
150
+ * `lastSummary` 가 **어디까지 덮는지** — 이 메시지까지 요약에 반영됐다.
151
+ *
152
+ * 이게 없으면 누적 요약을 할 수 없다: 매 턴 전체를 다시 요약하거나(비용) 이미 요약한 구간을
153
+ * 또 이어 붙인다(중복). 이력에서 이 id 를 못 찾으면(삭제·편집) 덮은 범위를 알 수 없으므로
154
+ * 전부 미반영으로 보고 다시 요약한다 — 빠뜨리는 쪽보다 안전하다.
155
+ */
156
+ @Column({ nullable: true })
157
+ @Field({ nullable: true, description: 'Id of the last message folded into lastSummary — enables incremental summarization instead of re-reading the whole history.' })
158
+ summaryUpToMessageId?: string
159
+
149
160
  /** 사용 모델 식별 — 'anthropic:claude-sonnet-4-6' 등 */
150
161
  @Column({ nullable: true })
151
162
  @Field({ nullable: true })