@things-factory/ai-assistant 10.1.271 → 10.1.273

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 (96) hide show
  1. package/client/components/assistant-chat.ts +18 -6
  2. package/client/components/assistant-dock.ts +15 -1
  3. package/client/components/proposal-request.test.ts +12 -1
  4. package/client/utils/addressed-draft.test.ts +31 -0
  5. package/client/utils/assistant-ask.ts +7 -0
  6. package/client/utils/assistant-request-context.ts +10 -0
  7. package/dist-client/components/assistant-chat.d.ts +6 -0
  8. package/dist-client/components/assistant-chat.js +23 -6
  9. package/dist-client/components/assistant-chat.js.map +1 -1
  10. package/dist-client/components/assistant-dock.js +15 -0
  11. package/dist-client/components/assistant-dock.js.map +1 -1
  12. package/dist-client/components/proposal-request.test.js +11 -1
  13. package/dist-client/components/proposal-request.test.js.map +1 -1
  14. package/dist-client/tsconfig.tsbuildinfo +1 -1
  15. package/dist-client/utils/addressed-draft.test.d.ts +1 -0
  16. package/dist-client/utils/addressed-draft.test.js +27 -0
  17. package/dist-client/utils/addressed-draft.test.js.map +1 -0
  18. package/dist-client/utils/assistant-ask.d.ts +10 -0
  19. package/dist-client/utils/assistant-ask.js.map +1 -1
  20. package/dist-client/utils/assistant-request-context.d.ts +12 -0
  21. package/dist-client/utils/assistant-request-context.js +11 -0
  22. package/dist-client/utils/assistant-request-context.js.map +1 -1
  23. package/dist-server/service/assistant-chat-resolver.js +5 -2
  24. package/dist-server/service/assistant-chat-resolver.js.map +1 -1
  25. package/dist-server/service/assistant-mode/index.d.ts +1 -0
  26. package/dist-server/service/assistant-mode/index.js +4 -1
  27. package/dist-server/service/assistant-mode/index.js.map +1 -1
  28. package/dist-server/service/assistant-mode/mode-categories.d.ts +4 -3
  29. package/dist-server/service/assistant-mode/mode-categories.js +15 -5
  30. package/dist-server/service/assistant-mode/mode-categories.js.map +1 -1
  31. package/dist-server/service/assistant-mode/turn-lines.d.ts +12 -0
  32. package/dist-server/service/assistant-mode/turn-lines.js +38 -0
  33. package/dist-server/service/assistant-mode/turn-lines.js.map +1 -0
  34. package/dist-server/service/chat-message/index.d.ts +1 -0
  35. package/dist-server/service/chat-message/index.js +3 -1
  36. package/dist-server/service/chat-message/index.js.map +1 -1
  37. package/dist-server/service/chat-message/message-doors.d.ts +14 -5
  38. package/dist-server/service/chat-message/message-doors.js +19 -6
  39. package/dist-server/service/chat-message/message-doors.js.map +1 -1
  40. package/dist-server/service/chat-message/room-turn.d.ts +31 -0
  41. package/dist-server/service/chat-message/room-turn.js +30 -0
  42. package/dist-server/service/chat-message/room-turn.js.map +1 -0
  43. package/dist-server/service/chat-session-participant/mention-invite.d.ts +2 -0
  44. package/dist-server/service/chat-session-participant/mention-invite.js +5 -0
  45. package/dist-server/service/chat-session-participant/mention-invite.js.map +1 -1
  46. package/dist-server/service/chat-session-resolver.d.ts +5 -0
  47. package/dist-server/service/chat-session-resolver.js +55 -2
  48. package/dist-server/service/chat-session-resolver.js.map +1 -1
  49. package/dist-server/service/data-entry/entry-apply.d.ts +2 -0
  50. package/dist-server/service/data-entry/entry-apply.js +1 -1
  51. package/dist-server/service/data-entry/entry-apply.js.map +1 -1
  52. package/dist-server/service/data-entry/entry-resolver.js +2 -1
  53. package/dist-server/service/data-entry/entry-resolver.js.map +1 -1
  54. package/dist-server/service/data-entry/entry-target.d.ts +7 -2
  55. package/dist-server/service/data-entry/entry-target.js.map +1 -1
  56. package/dist-server/service/data-read/read-target.d.ts +6 -0
  57. package/dist-server/service/data-read/read-target.js.map +1 -1
  58. package/dist-server/service/people/index.d.ts +2 -0
  59. package/dist-server/service/people/index.js +9 -1
  60. package/dist-server/service/people/index.js.map +1 -1
  61. package/dist-server/service/people/person-subject.d.ts +34 -0
  62. package/dist-server/service/people/person-subject.js +89 -0
  63. package/dist-server/service/people/person-subject.js.map +1 -0
  64. package/dist-server/service/unattended-run/run-unattended.js +1 -1
  65. package/dist-server/service/unattended-run/run-unattended.js.map +1 -1
  66. package/dist-server/tsconfig.tsbuildinfo +1 -1
  67. package/package.json +9 -9
  68. package/server/service/assistant-chat-resolver.ts +5 -2
  69. package/server/service/assistant-mode/index.ts +1 -0
  70. package/server/service/assistant-mode/mode-categories.ts +16 -5
  71. package/server/service/assistant-mode/mode-front.test.ts +35 -0
  72. package/server/service/assistant-mode/open-subject-door.test.ts +7 -2
  73. package/server/service/assistant-mode/turn-lines.ts +43 -0
  74. package/server/service/chat-message/index.ts +1 -0
  75. package/server/service/chat-message/message-doors.test.ts +40 -3
  76. package/server/service/chat-message/message-doors.ts +26 -6
  77. package/server/service/chat-message/room-turn.ts +42 -0
  78. package/server/service/chat-session-participant/mention-invite.ts +5 -0
  79. package/server/service/chat-session-resolver.ts +49 -2
  80. package/server/service/data-entry/entry-apply.ts +3 -1
  81. package/server/service/data-entry/entry-resolver.ts +2 -1
  82. package/server/service/data-entry/entry-target.ts +5 -2
  83. package/server/service/data-read/read-target.ts +6 -0
  84. package/server/service/people/index.ts +2 -0
  85. package/server/service/people/person-subject.test.ts +163 -0
  86. package/server/service/people/person-subject.ts +88 -0
  87. package/server/service/unattended-run/run-unattended.test.ts +2 -1
  88. package/server/service/unattended-run/run-unattended.ts +1 -1
  89. package/test/assistant-request-context.test.ts +1 -1
  90. package/test/open-doors.test.ts +3 -1
  91. package/translations/en.json +2 -0
  92. package/translations/es.json +2 -0
  93. package/translations/ja.json +2 -0
  94. package/translations/ko.json +2 -0
  95. package/translations/ms.json +2 -0
  96. package/translations/zh.json +2 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@things-factory/ai-assistant",
3
- "version": "10.1.271",
3
+ "version": "10.1.273",
4
4
  "main": "dist-server/index.js",
5
5
  "things-factory": true,
6
6
  "author": "heartyoh",
@@ -36,14 +36,14 @@
36
36
  "@operato/shell": "^10.29.69",
37
37
  "@operato/styles": "^10.0.0",
38
38
  "@operato/utils": "^10.29.76",
39
- "@things-factory/ai-client-base": "^10.1.271",
40
- "@things-factory/apptool-base": "^10.1.270",
41
- "@things-factory/attachment-base": "^10.1.271",
42
- "@things-factory/auth-base": "^10.1.271",
39
+ "@things-factory/ai-client-base": "^10.1.273",
40
+ "@things-factory/apptool-base": "^10.1.273",
41
+ "@things-factory/attachment-base": "^10.1.273",
42
+ "@things-factory/auth-base": "^10.1.273",
43
43
  "@things-factory/env": "^10.1.149",
44
- "@things-factory/help": "^10.1.270",
45
- "@things-factory/setting-base": "^10.1.271",
46
- "@things-factory/shell": "^10.1.270",
44
+ "@things-factory/help": "^10.1.273",
45
+ "@things-factory/setting-base": "^10.1.273",
46
+ "@things-factory/shell": "^10.1.273",
47
47
  "dompurify": "^3.0.0",
48
48
  "exceljs": "4.2.0",
49
49
  "graphql-scalars": "^1.22.0",
@@ -59,5 +59,5 @@
59
59
  "copyfiles": "^2.4.1",
60
60
  "rimraf": "^5.0.0"
61
61
  },
62
- "gitHead": "843bc2608d8c89348ced871777535966758927db"
62
+ "gitHead": "0ead3ad069edf9f1ef5076caec85916bdb26728f"
63
63
  }
@@ -29,6 +29,7 @@ import '@things-factory/auth-base'
29
29
  import { getRepository, rethrowSpoken } from '@things-factory/shell'
30
30
  import { aiClientFor, findToolSpec, openSubjectLine, OPEN_TOOLS, registryAssistantChat, type AgentClient } from '@things-factory/ai-client-base'
31
31
 
32
+ import { turnLinesOf } from './assistant-mode/turn-lines.js'
32
33
  import { ChatSession } from './chat-session/chat-session.js'
33
34
  import { assertStationSession } from './chat-session/station-session-guard.js'
34
35
  import { ChatMessage } from './chat-message/chat-message.js'
@@ -321,7 +322,9 @@ export class AssistantChatResolver {
321
322
  state: context.state
322
323
  })
323
324
  : undefined
324
- const systemPrompt = turnSystemPrompt(settings.systemPrompt, { subjectLine, page: input.page })
325
+ /* What the person has in front of them besides the subject - the screen's unread notices (ADR-0199 amendment 1). */
326
+ const screenLines = await turnLinesOf({ page: input.page, state: context.state })
327
+ const systemPrompt = turnSystemPrompt(settings.systemPrompt, { subjectLine: [subjectLine, ...screenLines].filter(Boolean).join('\n\n') || undefined, page: input.page })
325
328
 
326
329
  const lastUserMessage = input.messages[input.messages.length - 1]
327
330
  let userMessageId: string | undefined
@@ -557,7 +560,7 @@ export class AssistantChatResolver {
557
560
  const { reply, suggestion } = splitNextRequest(result.reply)
558
561
 
559
562
  const answerDoors = doorsForAnswer(
560
- (result.loop.toolUsages ?? []).map((usage: any) => usage?.name).filter(Boolean),
563
+ result.loop.toolUsages ?? [],
561
564
  name => (findToolSpec(name, settings.toolCategories) as any)?.doors
562
565
  )
563
566
 
@@ -19,3 +19,4 @@ export { recordSubjectDescriber, registerRecordSubject, type RecordSubject } fro
19
19
  export { ABSENCE_RULE, FINISH_RULE, NEXT_REQUEST_RULE, SELECTION_RULE, SPEAKER_RULE, conversationPrompt, isPersonRequest, splitNextRequest } from './screen-rules.js'
20
20
  export type { AssistantModeSpec, AssistantModeSlash, AssistantModeWarning, UnattendedLimits } from './types.js'
21
21
  export type { AssistantModeRef, ModeSettings, AssistantModeView, AssistantModeSlashView, Translate } from './resolve.js'
22
+ export { registerTurnLine, turnLinesOf, type TurnLine, type TurnLineInput } from './turn-lines.js'
@@ -110,20 +110,31 @@ export function selectionAxesOf(rows: { role?: string; content?: string | null }
110
110
  type FrontMode = { toolCategories?: string[]; attachments?: { kinds?: string[] }; entryTargets?: string[]; readTargets?: string[] }
111
111
 
112
112
  /**
113
- * The records the open screen is about, among those the mode reads and enters (ADR-0061 decision 9). Nothing new is
114
- * declared: a read target's screen route is the page that lists it, and a key's last part is the axis of its record
115
- * (`office.contract` is the record of the axis `contract`) - reading and entering one record share its key.
113
+ * The records the open screen is about, among those the mode reads and enters (ADR-0061 decision 9). A key's page is
114
+ * the screen that lists its records (ReadTarget.screen.route), the screen a card's records are seen on
115
+ * (EntryTarget.screen) and the pages a read of one record names (DetailRead.frontPages); a key's last part is the axis
116
+ * of its record (`office.contract` is the record of the axis `contract`) - reading and entering one record share its key.
116
117
  */
117
118
  export function screenTargetKeys(mode: FrontMode, screen: TurnScreen, routeOf: (key: string) => string | undefined = key => readTargetOf(key)?.screen?.route): string[] {
118
119
  const keys = [...new Set([...(mode.readTargets ?? []), ...(mode.entryTargets ?? [])])]
119
120
  return keys.filter(
120
121
  key =>
121
- (!!screen.page && routeOf(key) === screen.page) ||
122
+ (!!screen.page && pagesOfKey(mode, key, routeOf).includes(screen.page)) ||
122
123
  (!!screen.subjectAxis && axesOfKey(mode, key).includes(screen.subjectAxis)) ||
123
124
  (!!screen.selectionAxes?.length && axesOfKey(mode, key).some(axis => screen.selectionAxes!.includes(axis)))
124
125
  )
125
126
  }
126
127
 
128
+ /**
129
+ * The pages a key is in front on. A card's own screen counts as its page: on 내 주간업무보고 the report line card was
130
+ * not in front, the model opened it with `openTools`, and the answer that followed was hidden (2026-11-12).
131
+ */
132
+ function pagesOfKey(mode: FrontMode, key: string, routeOf: (key: string) => string | undefined): string[] {
133
+ const card = (mode.entryTargets ?? []).includes(key) ? entryTargetOf(key)?.screen : undefined
134
+ const answer = (mode.readTargets ?? []).includes(key) ? detailReadOf(key)?.frontPages ?? [] : []
135
+ return [routeOf(key), card, ...answer].filter((page): page is string => !!page)
136
+ }
137
+
127
138
  /** The records a key is about: its last part, and the axes a card joins or a whole answer covers (EntryTarget.axes · DetailRead.axes). */
128
139
  function axesOfKey(mode: FrontMode, key: string): string[] {
129
140
  const card = (mode.entryTargets ?? []).includes(key) ? entryTargetOf(key)?.axes ?? [] : []
@@ -161,7 +172,7 @@ export function modeFrontCategories(mode: FrontMode, screen: TurnScreen = {}): s
161
172
  /** Each screen the mode could be asked from - a page that lists one of its records, a record's axis - for the boot report. */
162
173
  export function modeScreens(mode: FrontMode, routeOf: (key: string) => string | undefined = key => readTargetOf(key)?.screen?.route): TurnScreen[] {
163
174
  const keys = [...new Set([...(mode.readTargets ?? []), ...(mode.entryTargets ?? [])])]
164
- const pages = [...new Set([...keys.map(routeOf), ...conversationCategoriesOf().flatMap(one => one.frontPages ?? [])].filter(Boolean) as string[])]
175
+ const pages = [...new Set([...keys.flatMap(key => pagesOfKey(mode, key, routeOf)), ...conversationCategoriesOf().flatMap(one => one.frontPages ?? [])])]
165
176
  const axes = [...new Set(keys.flatMap(key => axesOfKey(mode, key)))]
166
177
  return [{}, ...pages.map(page => ({ page })), ...axes.map(subjectAxis => ({ subjectAxis }))]
167
178
  }
@@ -144,3 +144,38 @@ describe('a whole answer about any record is in front on their screens', () => {
144
144
  expect(modeFrontCategories(mode, { subjectAxis: 'cash-transaction' })).not.toContain('data-read:office.checks')
145
145
  })
146
146
  })
147
+
148
+ /* 2026-11-12: asked 「AI로 초안 작성」 on 내 주간업무보고, neither the week's read nor the report line card was in front. */
149
+ describe('a page puts in front the cards seen on it and the reads that name it', () => {
150
+ const line = {
151
+ key: 'office.weekly-report-line',
152
+ labelKey: 'label.line',
153
+ description: 'a line of the weekly report.',
154
+ mutation: 'mutation ($line: Line!) { saveLine(line: $line) { id } }',
155
+ variables: (row: any) => ({ line: row.values }),
156
+ appliedOf: (data: any) => ({ id: data?.saveLine?.id }),
157
+ fields: [{ name: 'content', type: 'string' as const, required: true }],
158
+ screen: 'my-weekly-report'
159
+ }
160
+ const week = { key: 'office.my-weekly-report', description: 'the week.', query: 'query ($weekStart: String!) { myWeeklyReport(weekStart: $weekStart) { id } }', args: [{ name: 'weekStart', type: 'date', required: true }], frontPages: ['my-weekly-report'] }
161
+ const writing = { ...mode, readTargets: [...mode.readTargets, week.key], entryTargets: [...mode.entryTargets, line.key] }
162
+ beforeEach(() => {
163
+ clearEntryTargets()
164
+ declareEntryTarget(line as any)
165
+ declareDetailRead(week as any)
166
+ })
167
+
168
+ it('★ on 내 주간업무보고 the week\'s read and the line card are in front', () => {
169
+ expect(screenTargetKeys(writing, { page: 'my-weekly-report' })).toEqual(['office.my-weekly-report', 'office.weekly-report-line'])
170
+ expect(modeFrontCategories(writing, { page: 'my-weekly-report' })).toEqual(expect.arrayContaining(['data-read:office.my-weekly-report', 'data-entry:office.weekly-report-line']))
171
+ })
172
+
173
+ it('★ not on another page, nor for a mode that does not read or enter them', () => {
174
+ expect(screenTargetKeys(writing, { page: 'cash-transaction-list' })).toEqual(['office.cash-transaction'])
175
+ expect(screenTargetKeys(mode, { page: 'my-weekly-report' })).toEqual([])
176
+ })
177
+
178
+ it('the boot report walks those pages, so they are counted against the budget', () => {
179
+ expect(modeScreens(writing)).toContainEqual({ page: 'my-weekly-report' })
180
+ })
181
+ })
@@ -12,8 +12,13 @@ describe('the door', () => {
12
12
  expect(block).toMatch(/anchorType: \(session as any\)\.anchorType/)
13
13
  expect(block).toMatch(/anchorId: \(session as any\)\.anchorId/)
14
14
  expect(block).not.toMatch(/hostContext/)
15
- /* The page adds its category's rule, never a line of the screen's. */
16
- expect(door).toMatch(/const systemPrompt = turnSystemPrompt\(settings\.systemPrompt, \{ subjectLine, page: input\.page \}\)/)
15
+ /*
16
+ * The page adds its category's rule, never a line of the screen's. A module's line (the screen's unread notices,
17
+ * ADR-0199 amendment 1) is read on the server from the asker's own records - the page only narrows them; nothing
18
+ * the screen sent goes in.
19
+ */
20
+ expect(door).toMatch(/const screenLines = await turnLinesOf\(\{ page: input\.page, state: context\.state \}\)/)
21
+ expect(door).toMatch(/const systemPrompt = turnSystemPrompt\(settings\.systemPrompt, \{ subjectLine: \[subjectLine, \.\.\.screenLines\]\.filter\(Boolean\)\.join\('\\n\\n'\) \|\| undefined, page: input\.page \}\)/)
17
22
  })
18
23
 
19
24
  it('★ the model and the grounding check both read the prompt with the line', () => {
@@ -0,0 +1,43 @@
1
+ /*
2
+ * Lines a module adds to one turn's system prompt, after the open subject's - what the person has in front of them that
3
+ * the conversation does not hold. notification says the unread notices of the screen the dock is on, so the assistant
4
+ * knows what the person was told there (ADR-0199 amendment 1).
5
+ *
6
+ * A line is the module's to build from the asker's own records, read as them; a value a person typed goes in as data.
7
+ * One that fails is left out - a turn is never refused for a line.
8
+ */
9
+ import { logger } from '@things-factory/env'
10
+
11
+ export interface TurnLineInput {
12
+ /** The application's route of the open page, as the dock sends it - it only narrows what is the asker's own. */
13
+ page?: string
14
+ /** The request state - domain and user. */
15
+ state: any
16
+ }
17
+
18
+ export type TurnLine = (input: TurnLineInput) => string | undefined | Promise<string | undefined>
19
+
20
+ const lines = new Map<string, TurnLine>()
21
+
22
+ /** A module adds its line, by name - a second registration of the name replaces the first. */
23
+ export function registerTurnLine(name: string, line: TurnLine): void {
24
+ lines.set(name, line)
25
+ }
26
+
27
+ export async function turnLinesOf(input: TurnLineInput): Promise<string[]> {
28
+ const said: string[] = []
29
+ for (const [name, line] of lines) {
30
+ try {
31
+ const one = await line(input)
32
+ if (one) said.push(one)
33
+ } catch (error: any) {
34
+ logger.error(`[ai-assistant/turn-lines] ${name} failed: ${error?.message ?? error}`)
35
+ }
36
+ }
37
+ return said
38
+ }
39
+
40
+ /** Test only. */
41
+ export function clearTurnLines(): void {
42
+ lines.clear()
43
+ }
@@ -10,3 +10,4 @@ export {
10
10
  export type { ChatMessagePayload } from './chat-message-subscription.js'
11
11
 
12
12
  export const entities = [ChatMessage]
13
+ export { onRoomTurn, type RoomTurn } from './room-turn.js'
@@ -13,7 +13,7 @@ describe('message doors', () => {
13
13
  const doorsOf = (name: string) =>
14
14
  ({ getPlantOverview: ['Query.jobOrders', 'Query.productionReports'], findJobOrders: ['Query.jobOrders'] } as any)[name]
15
15
 
16
- expect(doorsForAnswer(['getPlantOverview', 'findJobOrders'], doorsOf)).toEqual([
16
+ expect(doorsForAnswer([{ name: 'getPlantOverview' }, { name: 'findJobOrders', outcome: 'ok' }], doorsOf)).toEqual([
17
17
  'Query.jobOrders',
18
18
  'Query.productionReports'
19
19
  ])
@@ -21,17 +21,54 @@ describe('message doors', () => {
21
21
 
22
22
  it('사람의 말과 문 없는 도구는 빈 목록이다 — 누구나 읽는다', () => {
23
23
  expect(doorsForAnswer([], () => undefined)).toEqual([])
24
- expect(doorsForAnswer(['getOpenScene'], () => [])).toEqual([])
24
+ expect(doorsForAnswer([{ name: 'getOpenScene' }], () => [])).toEqual([])
25
25
  })
26
26
 
27
27
  it('★ 등록기가 모르는 도구는 아무도 못 지나는 자리로 적힌다', async () => {
28
- const doors = doorsForAnswer(['whoIsThis'], () => undefined)
28
+ const doors = doorsForAnswer([{ name: 'whoIsThis', outcome: 'ok' }], () => undefined)
29
29
  expect(doors).toEqual(['unresolved:whoIsThis'])
30
30
 
31
31
  /* 통과 검사에 무엇을 넣어도 열리지 않는다. */
32
32
  expect(await passesRow(doors, doorGate(async () => true))).toBe(false)
33
33
  })
34
34
 
35
+ it('★ 도구 꺼내기는 값을 읽지 않는다 — 꺼내기를 쓴 답도 읽는 사람의 문으로만 가린다', async () => {
36
+ const doorsOf = (name: string) => ({ readOfficeMyWeeklyReport: ['Query.myWeeklyReport'] } as any)[name]
37
+ const doors = doorsForAnswer([{ name: 'openTools', outcome: 'ok' }, { name: 'readOfficeMyWeeklyReport', outcome: 'ok' }], doorsOf)
38
+
39
+ expect(doors).toEqual(['Query.myWeeklyReport'])
40
+ expect(await passesRow(doors, doorGate(async door => door === 'Query.myWeeklyReport'))).toBe(true)
41
+ })
42
+
43
+ it('★ 거절·오류로 끝난 호출의 문은 적지 않는다 — 거절당한 본인에게 자기 답이 가려진다', () => {
44
+ const doorsOf = (name: string) =>
45
+ ({ queryOrganizationEmployee: ['Query.employees'], readOfficeMyWeeklyReport: ['Query.myWeeklyReport'] } as any)[name]
46
+
47
+ expect(
48
+ doorsForAnswer(
49
+ [
50
+ { name: 'queryOrganizationEmployee', outcome: 'rejected' },
51
+ { name: 'noSuchTool', outcome: 'error' },
52
+ { name: 'readOfficeMyWeeklyReport', outcome: 'ok' }
53
+ ],
54
+ doorsOf
55
+ )
56
+ ).toEqual(['Query.myWeeklyReport'])
57
+ })
58
+
59
+ it('값을 읽은 호출은 거절된 같은 도구가 있어도 문이 남는다', () => {
60
+ const doorsOf = () => ['Query.employees']
61
+ expect(
62
+ doorsForAnswer(
63
+ [
64
+ { name: 'queryOrganizationEmployee', outcome: 'rejected' },
65
+ { name: 'queryOrganizationEmployee', outcome: 'ok' }
66
+ ],
67
+ doorsOf
68
+ )
69
+ ).toEqual(['Query.employees'])
70
+ })
71
+
35
72
  it('★ 같은 문은 한 요청에 한 번만 묻는다', async () => {
36
73
  const asked: string[] = []
37
74
  const gate = doorGate(async door => {
@@ -23,20 +23,40 @@
23
23
  * 이 파일은 저장소·엔티티를 모르는 순수 판정이다.
24
24
  */
25
25
 
26
+ import { OPEN_TOOLS } from '@things-factory/ai-client-base'
27
+
26
28
  /** 문 이름으로 보이지 않는 값 — 등록되지 않은 도구가 답에 끼었을 때. */
27
29
  const UNRESOLVED = 'unresolved:'
28
30
 
31
+ /** 답에 실린 도구 한 번 — 이름과 어떻게 끝났는가(agentic loop 의 ToolUsage). */
32
+ export interface AnswerToolUse {
33
+ name: string
34
+ outcome?: string
35
+ }
36
+
29
37
  /**
30
- * 이 답이 지난 문들 — 부른 도구들의 문을 합친다(중복 없이, 정렬).
38
+ * 값을 읽지 않은 호출 — 거절·오류로 끝난 호출은 결과에 데이터가 없다(무엇이 빠졌는지·왜 못 했는지만).
39
+ * 그 문을 답에 적으면 그 문을 못 지나는 사람, 곧 **거절당한 본인**에게 자기 답이 가려진다(2026-11-12
40
+ * 운영: 직원 목록 조회가 거절된 답이 묻는 사람에게 가려짐).
41
+ */
42
+ const READ_NOTHING = new Set(['rejected', 'error'])
43
+
44
+ /**
45
+ * 이 답이 지난 문들 — 값을 읽은 도구들의 문을 합친다(중복 없이, 정렬).
46
+ *
47
+ * 도구 꺼내기(`openTools`, ADR-0061 결정 9)는 도구 이름을 열 뿐 값을 읽지 않는다. 등록기에 없으므로
48
+ * 아래 규칙대로 두면 아무도 못 지나는 자리가 되어, 꺼내기를 쓴 답은 묻는 사람 본인까지 누구도 못
49
+ * 읽었다(2026-11-12 운영: 가려진 답 22건 중 19건).
31
50
  *
32
- * 등록기에 없는 도구가 답에 끼면 그 도구가 무엇을 읽었는지 알 길이 없다. 그때 `[]`(누구나 읽는 답)로
33
- * 적으면 모르는 값이 공개된다. 아무도 못 지나는 이름을 적어 **가려지는 쪽**으로 넘어뜨리고, 이름에
34
- * 원인을 실어 둔다.
51
+ * 등록기에 없는 도구가 값을 읽고 답에 끼면 그 도구가 무엇을 읽었는지 알 길이 없다. 그때 `[]`(누구나
52
+ * 읽는 답)로 적으면 모르는 값이 공개된다. 아무도 못 지나는 이름을 적어 **가려지는 쪽**으로 넘어뜨리고,
53
+ * 이름에 원인을 실어 둔다.
35
54
  */
36
- export function doorsForAnswer(toolNames: readonly string[], doorsOf: (name: string) => string[] | undefined): string[] {
55
+ export function doorsForAnswer(usages: readonly AnswerToolUse[], doorsOf: (name: string) => string[] | undefined): string[] {
37
56
  const doors = new Set<string>()
38
57
 
39
- for (const name of toolNames) {
58
+ for (const { name, outcome } of usages) {
59
+ if (!name || name === OPEN_TOOLS || (outcome && READ_NOTHING.has(outcome))) continue
40
60
  const declared = doorsOf(name)
41
61
  if (declared === undefined) doors.add(`${UNRESOLVED}${name}`)
42
62
  else for (const door of declared) doors.add(door)
@@ -0,0 +1,42 @@
1
+ /*
2
+ * A person spoke to the people of a conversation - told to the modules that wait for it. worklist closes a question it
3
+ * handed to that person once they answer in the conversation it came from (ADR-0200 decision 3).
4
+ *
5
+ * Only the door that stores words to the room tells (`sendRoomMessage`): what the person asks the assistant - polish
6
+ * my draft - is not their answer.
7
+ */
8
+ import { logger } from '@things-factory/env'
9
+
10
+ export interface RoomTurn {
11
+ domain: { id: string }
12
+ /** Who spoke. */
13
+ user: { id: string; name?: string; email?: string }
14
+ session: { id: string; anchorType?: string | null; anchorId?: string | null }
15
+ /** The message as stored. */
16
+ message: { id: string; content: string }
17
+ /** The request's transaction - a listener writes in it, so the turn and what it closed stand or fall together. */
18
+ tx?: any
19
+ /** The request's translator. */
20
+ t?: (key: string, options?: any) => string
21
+ }
22
+
23
+ type Listener = (turn: RoomTurn) => void | Promise<void>
24
+
25
+ const listeners = new Set<Listener>()
26
+
27
+ /** A module waits for people's words in conversations. Answers the way to stop. */
28
+ export function onRoomTurn(listener: Listener): () => void {
29
+ listeners.add(listener)
30
+ return () => listeners.delete(listener)
31
+ }
32
+
33
+ /** Every listener hears the turn; one that fails is logged and does not stop the person's words. */
34
+ export async function tellRoomTurn(turn: RoomTurn): Promise<void> {
35
+ for (const listener of listeners) {
36
+ try {
37
+ await listener(turn)
38
+ } catch (error: any) {
39
+ logger.error(`[ai-assistant/room-turn] a listener failed for session ${turn.session.id}: ${error?.message ?? error}`)
40
+ }
41
+ }
42
+ }
@@ -27,6 +27,11 @@
27
27
  */
28
28
  import { isOpenRoom, maySeat } from '../chat-session/session-visibility.js'
29
29
 
30
+ /** The text as a person reads it - `@Admin{userId:UUID}` is `@Admin`. Kept where a turn's words are stored as an answer. */
31
+ export function withoutMentionIds(text: string): string {
32
+ return text.replace(/\{userId:[^}\s]+\}/g, '')
33
+ }
34
+
30
35
  /** 본문에서 `@user{userId:UUID}` 마커의 userId 를 뽑는다 — 첫 등장 순, 중복 제거. */
31
36
  export function extractMentionUserIds(text: string | null | undefined): string[] {
32
37
  if (!text) return []
@@ -21,6 +21,8 @@ import { roomMessageBody } from './chat-message/room-message.js'
21
21
  import { readerGate } from './chat-message/reader-gate.js'
22
22
  import { requestTranslator } from './request-translator.js'
23
23
  import { initialVisibility, isOpenRoom, mayReadSession, maySeat, SESSION_VISIBILITIES } from './chat-session/session-visibility.js'
24
+ import { PERSON_ROOM_REFUSALS, personOfAnchor, personRoomRefusal, personSeatOf } from './people/person-subject.js'
25
+ import { tellRoomTurn } from './chat-message/room-turn.js'
24
26
  import { seatParticipants, seatTurn } from './chat-session-participant/mention-invite.js'
25
27
  import { CHAT_TYPING_TOPIC, typingNotice } from './chat-message/chat-typing.js'
26
28
  import { sendInviteNotification } from './chat-session-participant/invite-notification.js'
@@ -223,6 +225,29 @@ function attachmentRefusalMessage(refusal: AttachmentRefusal, context: any): str
223
225
  }
224
226
  }
225
227
 
228
+
229
+ /**
230
+ * A conversation about someone seats them as it is made - they read whatever is asked of their records (ADR-0200).
231
+ * Their seat is a member's, given by the one who started it, as an invite gives it.
232
+ */
233
+ async function seatPersonOf(session: any, starter: any, tx: any): Promise<void> {
234
+ const seat = personSeatOf(session.anchorType, session.anchorId, starter)
235
+ if (!seat) return
236
+ await getRepository(ChatSessionParticipant, tx).save({
237
+ domain: session.domain,
238
+ session: { id: session.id } as any,
239
+ user: { id: seat.userId } as any,
240
+ role: 'member',
241
+ creator: starter,
242
+ updater: starter
243
+ } as any)
244
+ }
245
+
246
+ /** A conversation about someone stays a group they sit in - said in the asker's words when a change would undo that. */
247
+ function refusePersonRoom(session: any, change: { visibility?: string; removing?: string }, context: ResolverContext): void {
248
+ const refusal = session && personRoomRefusal({ ...session, creatorId: session.creatorId }, change)
249
+ if (refusal) throw new Error(requestTranslator(context)(`ai-assistant.text.${refusal}`, { defaultValue: PERSON_ROOM_REFUSALS[refusal] }))
250
+ }
226
251
  @Resolver()
227
252
  export class ChatSessionResolver {
228
253
  @Query(() => ChatSession, { nullable: true, description: 'Get AI chat session by id.' })
@@ -628,6 +653,7 @@ export class ChatSessionResolver {
628
653
  if (mine?.role !== 'owner') return false
629
654
 
630
655
  if ((session as any).visibility === visibility) return true
656
+ refusePersonRoom(session, { visibility }, context)
631
657
 
632
658
  /*
633
659
  * Private is the owner's alone (ADR-0073 decision 3). The members leave with the change - a private room
@@ -724,6 +750,7 @@ export class ChatSessionResolver {
724
750
  }
725
751
  const theirs = seats.find(seat => (seat as any).userId === userId && seat.role === 'member')
726
752
  if (!theirs) return false
753
+ refusePersonRoom(await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any }), { removing: userId }, context)
727
754
  return await this._leave(sessionId, theirs, context)
728
755
  }
729
756
 
@@ -745,6 +772,7 @@ export class ChatSessionResolver {
745
772
  throw new Error(requestTranslator(context)('ai-assistant.text.owner-cannot-leave', { defaultValue: 'you started this conversation, so you cannot leave it. delete it, or make it private.' }))
746
773
  }
747
774
  if (mine?.role !== 'member') return false
775
+ refusePersonRoom(await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any }), { removing: user.id }, context)
748
776
  return await this._leave(sessionId, mine, context)
749
777
  }
750
778
 
@@ -900,6 +928,22 @@ export class ChatSessionResolver {
900
928
  return maySeat((session as any).visibility, seat?.role)
901
929
  }
902
930
 
931
+ /**
932
+ * The person this conversation is about, who always reads it (ADR-0200) - the screen offers no way to send them out,
933
+ * and keeps no copy of the rule. The doors refuse again.
934
+ */
935
+ @Query(() => String, {
936
+ nullable: true,
937
+ description: 'The user this conversation is about, who cannot be sent out of it - none for any other conversation. A hint for the screen; the doors decide again.'
938
+ })
939
+ @Directive('@privilege(category: "ai-assistant", privilege: "query", domainOwnerGranted: true)')
940
+ async keptInAISession(@Arg('sessionId') sessionId: string, @Ctx() context: ResolverContext): Promise<string | null> {
941
+ const { domain } = context.state
942
+ const session: any = await getRepository(ChatSession).findOneBy({ id: sessionId, domain: { id: domain.id } as any })
943
+ const personId = session && personOfAnchor(session.anchorType, session.anchorId)
944
+ return personId && personRoomRefusal(session, { removing: personId }) ? personId : null
945
+ }
946
+
903
947
  @Mutation(() => Boolean, {
904
948
  description: 'Presence heartbeat — bump current user\'s lastSeenAt in the session (online indicator).'
905
949
  })
@@ -977,7 +1021,7 @@ export class ChatSessionResolver {
977
1021
  domain,
978
1022
  ...anchorColumns(anchorType, anchorId),
979
1023
  /* 새 대화는 비공개로 태어난다 — 공개는 owner 가 고른다(ADR-0073 결정 2, 2026-09-30 고침). */
980
- visibility: initialVisibility({ anchorType }),
1024
+ visibility: personSeatOf(anchorType, anchorId, user)?.visibility ?? initialVisibility({ anchorType }),
981
1025
  creator: user,
982
1026
  updater: user
983
1027
  } as any)
@@ -990,6 +1034,7 @@ export class ChatSessionResolver {
990
1034
  creator: user,
991
1035
  updater: user
992
1036
  } as any)
1037
+ await seatPersonOf(session, user, tx)
993
1038
  return session
994
1039
  }
995
1040
 
@@ -1014,7 +1059,7 @@ export class ChatSessionResolver {
1014
1059
  const session = await repo.save({
1015
1060
  domain,
1016
1061
  ...anchorColumns(anchorType, anchorId),
1017
- visibility: initialVisibility({ anchorType }),
1062
+ visibility: personSeatOf(anchorType, anchorId, user)?.visibility ?? initialVisibility({ anchorType }),
1018
1063
  creator: user,
1019
1064
  updater: user,
1020
1065
  name: finalName
@@ -1028,6 +1073,7 @@ export class ChatSessionResolver {
1028
1073
  creator: user,
1029
1074
  updater: user
1030
1075
  } as any)
1076
+ await seatPersonOf(session, user, tx)
1031
1077
  return session
1032
1078
  }
1033
1079
 
@@ -1233,6 +1279,7 @@ export class ChatSessionResolver {
1233
1279
  visibility: (session as any).visibility
1234
1280
  })
1235
1281
  await notifyInvited(context, invite.invited, user, (session as any).name)
1282
+ await tellRoomTurn({ domain, user, session: session as any, message: saved as any, tx, t: requestTranslator(context) })
1236
1283
 
1237
1284
  /* 사람의 말이다 — 목록의 최근 활동과 다른 참여자의 안 읽음이 이것으로 움직인다. */
1238
1285
  try {
@@ -61,6 +61,8 @@ export interface EntryApplyDeps {
61
61
  report?(message: string, error: unknown): void
62
62
  /** The fingerprint of what the AI 작업 패널 showed, when the person reviewed it there - entered only if the proposal is still that one. */
63
63
  reviewedHash?: string
64
+ /** The conversation the card is in - a row about the conversation itself takes it (a question handed on, ADR-0200). */
65
+ sessionId?: string
64
66
  }
65
67
 
66
68
  const nothing = (verdict: EntryApplyOutcome['verdict'], errorCode: string): EntryApplyOutcome => ({ verdict, errorCode, applied: 0, missed: 0, rows: [] })
@@ -155,7 +157,7 @@ export async function applyEntryProposal(key: string, deps: EntryApplyDeps, targ
155
157
  continue
156
158
  }
157
159
  try {
158
- const answer = await deps.execute(target.mutation, target.variables!(row))
160
+ const answer = await deps.execute(target.mutation, target.variables!(row, { sessionId: deps.sessionId }))
159
161
  if (answer.errors?.length) {
160
162
  results.push({ index: row.index, ok: false, error: answer.errors.map(one => one.message).join('; ') || 'refused' })
161
163
  continue
@@ -67,7 +67,8 @@ export class EntryProposalResolver {
67
67
  */
68
68
  execute: runAsCaller(context),
69
69
  report: (message, error) => logger.error(message, error),
70
- reviewedHash: reviewedHash || undefined
70
+ reviewedHash: reviewedHash || undefined,
71
+ sessionId: session.id
71
72
  })
72
73
  }
73
74
  }
@@ -159,8 +159,11 @@ export interface EntryTarget {
159
159
  * to a person typing it in.
160
160
  */
161
161
  mutation: string
162
- /** The mutation's variables for one row. Absent when the target enters rows by group (below). */
163
- variables?(row: EntryRow): Record<string, unknown>
162
+ /**
163
+ * The mutation's variables for one row. Absent when the target enters rows by group (below). `card.sessionId` is the
164
+ * conversation the card was pressed in - for a record about the conversation itself, never a value the model wrote.
165
+ */
166
+ variables?(row: EntryRow, card?: { sessionId?: string }): Record<string, unknown>
164
167
  /** What the conversation says of an entered row - its id and a short name. */
165
168
  appliedOf?(data: any, row: EntryRow): EntryApplied | undefined
166
169
  /**
@@ -207,6 +207,12 @@ export interface DetailRead {
207
207
  * for any ledger record; asked on a deposit's 360 why it was in the check, the model never opened it (2026-10-24).
208
208
  */
209
209
  axes?: string[]
210
+ /**
211
+ * The application routes whose conversations put it in front (ConversationCategory.frontPages) - a read of one record
212
+ * has no list screen to name its page. Asked 「AI로 초안 작성」 on 내 주간업무보고, the week's read was not in front, and the
213
+ * model looked for it in the help first (2026-11-12).
214
+ */
215
+ frontPages?: string[]
210
216
  /**
211
217
  * The lists the answer holds, each a table of typed columns - what a dashboard card may draw from a one-answer read
212
218
  * (ADR-0160 decision 2). The card keeps only `key`; where the rows are and what their columns are is read here.
@@ -5,9 +5,11 @@
5
5
  import { registerReadTarget } from '../data-read/read-tools.js'
6
6
  import { peopleReadTarget } from './people-read.js'
7
7
  import './invite-tools.js'
8
+ import './person-subject.js'
8
9
 
9
10
  registerReadTarget(peopleReadTarget())
10
11
 
11
12
  export * from './people-keys.js'
12
13
  export { peopleReadTarget, PEOPLE_SELECTION } from './people-read.js'
14
+ export { PERSON_AXIS, PERSON_QUESTION_KEY, PERSON_GUIDANCE, personOfAnchor, personSeatOf, personRoomRefusal } from './person-subject.js'
13
15
  export { proposeInvite, findPeopleNamed, inviteCategory, MAX_INVITE_CANDIDATES, type InviteCandidate } from './invite-tools.js'