@things-factory/ai-assistant 10.1.271 → 10.1.272

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 (79) 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 +4 -1
  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/turn-lines.d.ts +12 -0
  29. package/dist-server/service/assistant-mode/turn-lines.js +38 -0
  30. package/dist-server/service/assistant-mode/turn-lines.js.map +1 -0
  31. package/dist-server/service/chat-message/index.d.ts +1 -0
  32. package/dist-server/service/chat-message/index.js +3 -1
  33. package/dist-server/service/chat-message/index.js.map +1 -1
  34. package/dist-server/service/chat-message/room-turn.d.ts +31 -0
  35. package/dist-server/service/chat-message/room-turn.js +30 -0
  36. package/dist-server/service/chat-message/room-turn.js.map +1 -0
  37. package/dist-server/service/chat-session-participant/mention-invite.d.ts +2 -0
  38. package/dist-server/service/chat-session-participant/mention-invite.js +5 -0
  39. package/dist-server/service/chat-session-participant/mention-invite.js.map +1 -1
  40. package/dist-server/service/chat-session-resolver.d.ts +5 -0
  41. package/dist-server/service/chat-session-resolver.js +55 -2
  42. package/dist-server/service/chat-session-resolver.js.map +1 -1
  43. package/dist-server/service/data-entry/entry-apply.d.ts +2 -0
  44. package/dist-server/service/data-entry/entry-apply.js +1 -1
  45. package/dist-server/service/data-entry/entry-apply.js.map +1 -1
  46. package/dist-server/service/data-entry/entry-resolver.js +2 -1
  47. package/dist-server/service/data-entry/entry-resolver.js.map +1 -1
  48. package/dist-server/service/data-entry/entry-target.d.ts +7 -2
  49. package/dist-server/service/data-entry/entry-target.js.map +1 -1
  50. package/dist-server/service/people/index.d.ts +2 -0
  51. package/dist-server/service/people/index.js +9 -1
  52. package/dist-server/service/people/index.js.map +1 -1
  53. package/dist-server/service/people/person-subject.d.ts +34 -0
  54. package/dist-server/service/people/person-subject.js +89 -0
  55. package/dist-server/service/people/person-subject.js.map +1 -0
  56. package/dist-server/tsconfig.tsbuildinfo +1 -1
  57. package/package.json +3 -3
  58. package/server/service/assistant-chat-resolver.ts +4 -1
  59. package/server/service/assistant-mode/index.ts +1 -0
  60. package/server/service/assistant-mode/open-subject-door.test.ts +7 -2
  61. package/server/service/assistant-mode/turn-lines.ts +43 -0
  62. package/server/service/chat-message/index.ts +1 -0
  63. package/server/service/chat-message/room-turn.ts +42 -0
  64. package/server/service/chat-session-participant/mention-invite.ts +5 -0
  65. package/server/service/chat-session-resolver.ts +49 -2
  66. package/server/service/data-entry/entry-apply.ts +3 -1
  67. package/server/service/data-entry/entry-resolver.ts +2 -1
  68. package/server/service/data-entry/entry-target.ts +5 -2
  69. package/server/service/people/index.ts +2 -0
  70. package/server/service/people/person-subject.test.ts +163 -0
  71. package/server/service/people/person-subject.ts +88 -0
  72. package/test/assistant-request-context.test.ts +1 -1
  73. package/test/open-doors.test.ts +3 -1
  74. package/translations/en.json +2 -0
  75. package/translations/es.json +2 -0
  76. package/translations/ja.json +2 -0
  77. package/translations/ko.json +2 -0
  78. package/translations/ms.json +2 -0
  79. 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.272",
4
4
  "main": "dist-server/index.js",
5
5
  "things-factory": true,
6
6
  "author": "heartyoh",
@@ -36,7 +36,7 @@
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",
39
+ "@things-factory/ai-client-base": "^10.1.272",
40
40
  "@things-factory/apptool-base": "^10.1.270",
41
41
  "@things-factory/attachment-base": "^10.1.271",
42
42
  "@things-factory/auth-base": "^10.1.271",
@@ -59,5 +59,5 @@
59
59
  "copyfiles": "^2.4.1",
60
60
  "rimraf": "^5.0.0"
61
61
  },
62
- "gitHead": "843bc2608d8c89348ced871777535966758927db"
62
+ "gitHead": "f87fefe0687eedf52a25cda1c54d59efabaf3dc2"
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
@@ -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'
@@ -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'
@@ -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
  /**
@@ -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'
@@ -0,0 +1,163 @@
1
+ /*
2
+ * A conversation about a person (ADR-0200) - through the doors themselves, on sqlite.
3
+ *
4
+ * Opened on someone's 360 it is a group they sit in, so nothing is asked of their records out of their sight; it stays
5
+ * a group with them in it. The model is told whose records answer and how such a conversation is held. Asking about
6
+ * oneself is an ordinary conversation.
7
+ */
8
+ import type { DataSource } from 'typeorm'
9
+
10
+ const { DataSource: TypeOrmDataSource } = require('typeorm')
11
+ const shell = require('@things-factory/shell')
12
+ const authBase = require('@things-factory/auth-base')
13
+
14
+ function loadCompiled(modulePath: string): any {
15
+ const { existsSync } = require('fs')
16
+ const { join } = require('path')
17
+ const resolved = join(__dirname, '..', '..', '..', 'dist-server', 'service', `${modulePath}.js`)
18
+ if (!existsSync(resolved)) throw new Error(`ai-assistant has no build output: ${resolved}\nBuild first:\n yarn workspace @things-factory/ai-assistant build:server`)
19
+ return require(resolved)
20
+ }
21
+ const { ChatSession } = loadCompiled('chat-session/chat-session')
22
+ const { ChatMessage } = loadCompiled('chat-message/chat-message')
23
+ const { ChatSessionParticipant } = loadCompiled('chat-session-participant/chat-session-participant')
24
+ const { ChatSessionResolver } = loadCompiled('chat-session-resolver')
25
+ const { onRoomTurn } = loadCompiled('chat-message/room-turn')
26
+ const { personOfAnchor, personSeatOf, personRoomRefusal, personSubjectDescriber, PERSON_GUIDANCE } = loadCompiled('people/person-subject')
27
+ const { openSubjectLine } = require('@things-factory/ai-client-base')
28
+
29
+ let db: DataSource
30
+ let domain: any
31
+ let manager: any
32
+ let employee: any
33
+ let colleague: any
34
+
35
+ const doors = new ChatSessionResolver()
36
+ const as = (user: any) => ({ state: { domain, user, tx: db.manager, sendNotice: () => undefined } }) as any
37
+
38
+ beforeAll(async () => {
39
+ db = new TypeOrmDataSource({
40
+ type: 'sqlite',
41
+ database: ':memory:',
42
+ synchronize: true,
43
+ dropSchema: true,
44
+ namingStrategy: new shell.NamingStrategy(),
45
+ entities: [...shell.entities, ...authBase.entities, ChatSession, ChatMessage, ChatSessionParticipant],
46
+ logging: false
47
+ })
48
+ await db.initialize()
49
+ shell.addDataSource('default', db)
50
+ domain = await db.getRepository(shell.Domain).save({ name: 'acme', subdomain: 'acme' })
51
+ const person = (name: string) => db.getRepository(authBase.User).save({ name, username: name, email: `${name}@example.com`, status: 'activated', domains: [domain] })
52
+ manager = await person('manager')
53
+ employee = await person('employee')
54
+ colleague = await person('colleague')
55
+ })
56
+
57
+ afterAll(async () => {
58
+ shell.removeDataSource('default')
59
+ await db?.destroy()
60
+ })
61
+
62
+ const seats = async (session: any) =>
63
+ (await db.getRepository(ChatSessionParticipant).find({ where: { session: { id: session.id } } as any })).map((row: any) => [row.userId, row.role]).sort()
64
+
65
+ const about = (user: any) => `person:${user.id}`
66
+
67
+ describe('who a conversation is about', () => {
68
+ it('a person anchor names them; anything else names nobody', () => {
69
+ expect(personOfAnchor('subject', 'person:u-1')).toBe('u-1')
70
+ expect(personOfAnchor('subject', 'contract:c-1')).toBeUndefined()
71
+ expect(personOfAnchor('domain', 'person:u-1')).toBeUndefined()
72
+ expect(personOfAnchor('subject', 'person:')).toBeUndefined()
73
+ })
74
+
75
+ it('★ asking about someone seats them in a group; asking about oneself seats nobody', () => {
76
+ expect(personSeatOf('subject', 'person:u-1', { id: 'u-2' })).toEqual({ userId: 'u-1', visibility: 'group' })
77
+ expect(personSeatOf('subject', 'person:u-1', { id: 'u-1' })).toBeUndefined()
78
+ })
79
+
80
+ it('★ it stays a group with them in it; a conversation about oneself is free', () => {
81
+ const room = { anchorType: 'subject', anchorId: 'person:u-1', creatorId: 'u-2' }
82
+ expect(personRoomRefusal(room, { visibility: 'private' })).toBe('person-room-group-only')
83
+ expect(personRoomRefusal(room, { visibility: 'open' })).toBe('person-room-group-only')
84
+ expect(personRoomRefusal(room, { visibility: 'group' })).toBeUndefined()
85
+ expect(personRoomRefusal(room, { removing: 'u-1' })).toBe('person-room-keeps-person')
86
+ expect(personRoomRefusal(room, { removing: 'u-3' })).toBeUndefined()
87
+ expect(personRoomRefusal({ ...room, creatorId: 'u-1' }, { visibility: 'private' })).toBeUndefined()
88
+ })
89
+ })
90
+
91
+ describe('the doors', () => {
92
+ it('★ a conversation opened on someone is a group with them seated as a member', async () => {
93
+ const session = await doors.createAISession('subject', about(employee), undefined, as(manager))
94
+ expect(session.visibility).toBe('group')
95
+ expect(await seats(session)).toEqual([[employee.id, 'member'], [manager.id, 'owner']].sort())
96
+ })
97
+
98
+ it('the conversation found again for that subject is the same group', async () => {
99
+ const session = await doors.startAISession('subject', about(colleague), as(manager))
100
+ expect(session.visibility).toBe('group')
101
+ expect(await seats(session)).toEqual([[colleague.id, 'member'], [manager.id, 'owner']].sort())
102
+ })
103
+
104
+ it('★ a conversation about oneself is private and seats nobody else', async () => {
105
+ const session = await doors.createAISession('subject', about(employee), undefined, as(employee))
106
+ expect(session.visibility).toBe('private')
107
+ expect(await seats(session)).toEqual([[employee.id, 'owner']])
108
+ })
109
+
110
+ it('★ it cannot be made private or open', async () => {
111
+ const session = await doors.createAISession('subject', about(employee), undefined, as(manager))
112
+ await expect(doors.setSessionVisibility(session.id, 'private', as(manager))).rejects.toThrow(/stays a group/)
113
+ await expect(doors.setSessionVisibility(session.id, 'open', as(manager))).rejects.toThrow(/stays a group/)
114
+ expect(await seats(session)).toContainEqual([employee.id, 'member'])
115
+ })
116
+
117
+ it('★ the person is neither sent out nor leaves; someone else brought in can be', async () => {
118
+ const session = await doors.createAISession('subject', about(employee), undefined, as(manager))
119
+ await doors.inviteToAISession(session.id, [colleague.id], as(manager))
120
+ await expect(doors.removeFromAISession(session.id, employee.id, as(manager))).rejects.toThrow(/always reads it/)
121
+ await expect(doors.leaveAISession(session.id, as(employee))).rejects.toThrow(/always reads it/)
122
+ expect(await doors.removeFromAISession(session.id, colleague.id, as(manager))).toBe(true)
123
+ expect(await seats(session)).toContainEqual([employee.id, 'member'])
124
+ })
125
+
126
+ it('★ the screen is told who stays, so it offers no button to send them out', async () => {
127
+ const session = await doors.createAISession('subject', about(employee), undefined, as(manager))
128
+ expect(await doors.keptInAISession(session.id, as(manager))).toBe(employee.id)
129
+ const own = await doors.createAISession('subject', about(manager), undefined, as(manager))
130
+ expect(await doors.keptInAISession(own.id, as(manager))).toBeNull()
131
+ const general = await doors.createAISession('domain', domain.id, undefined, as(manager))
132
+ expect(await doors.keptInAISession(general.id, as(manager))).toBeNull()
133
+ })
134
+
135
+ it('★ what the person says to the room is told to the modules that wait for it, with who spoke', async () => {
136
+ const heard: any[] = []
137
+ const stop = onRoomTurn((turn: any) => {
138
+ heard.push([turn.user.id, turn.session.anchorId, turn.message.content])
139
+ })
140
+ const session = await doors.createAISession('subject', about(employee), undefined, as(manager))
141
+ await doors.sayToRoom(session.id, '목요일 입고면 금요일 납품 가능합니다.', undefined, as(employee))
142
+ stop()
143
+ await doors.sayToRoom(session.id, 'after stop', undefined, as(employee))
144
+ expect(heard).toEqual([[employee.id, about(employee), '목요일 입고면 금요일 납품 가능합니다.']])
145
+ })
146
+ })
147
+
148
+ describe('what the model is told', () => {
149
+ it('★ the person by name, with how a conversation about someone is held', async () => {
150
+ const line = await openSubjectLine({ anchorType: 'subject', anchorId: about(employee), domain, state: as(manager).state })
151
+ expect(line).toContain('"employee"')
152
+ expect(line).toContain(PERSON_GUIDANCE)
153
+ expect(PERSON_GUIDANCE).toMatch(/never speak as them/)
154
+ expect(PERSON_GUIDANCE).toMatch(/Never guess their character/)
155
+ expect(PERSON_GUIDANCE).toMatch(/proposeWorklistPersonQuestionEntries/)
156
+ })
157
+
158
+ it('someone who does not work here is not named', async () => {
159
+ const describer = personSubjectDescriber(async () => false)
160
+ expect(await describer.describe({ anchorId: about(employee), domain })).toBeUndefined()
161
+ expect(await describer.describe({ anchorId: 'person:missing', domain })).toBeUndefined()
162
+ })
163
+ })
@@ -0,0 +1,88 @@
1
+ /*
2
+ * A conversation about a person (ADR-0200). The person 360 anchors its conversation to `subject` · `person:<user id>`
3
+ * (the 360 kind is the axis, as every 360's - record-subject.ts). Three things follow from that anchor, and each is
4
+ * asked here so no door keeps a rule of its own:
5
+ *
6
+ * · the model is told the person's name and how such a conversation is held - their records answer, with where and
7
+ * when each was written; their character, intent, mood and ability are never guessed; nobody speaks as them; what
8
+ * binds them goes to them as a to-do (`guidance`).
9
+ * · the person sits in it. A conversation about someone is a group the person always reads - nothing is asked of
10
+ * their records out of their sight (`personSeatOf`, the doors that open a conversation).
11
+ * · it stays a group with them in it - neither open to the whole domain nor private, and they are not sent out
12
+ * (`personRoomRefusal`).
13
+ *
14
+ * Asking about oneself is an ordinary conversation: nobody else is seated and the rules about speaking for someone do
15
+ * not apply.
16
+ */
17
+ import { User } from '@things-factory/auth-base'
18
+ import { entersDomainAsAssignee } from '@things-factory/auth-base/dist-server/utils/get-domain-users.js'
19
+ import { registerAssistantSubject, type AssistantSubjectDescriber } from '@things-factory/ai-client-base'
20
+ import { getRepository } from '@things-factory/shell'
21
+
22
+ import { entryToolName } from '../data-entry/entry-target.js'
23
+
24
+ /** The 360 kind of a person - auth-ui's `person`. */
25
+ export const PERSON_AXIS = 'person'
26
+
27
+ /** The confirmation card that hands a question to the person as a to-do - worklist declares it (ADR-0200 decision 3). */
28
+ export const PERSON_QUESTION_KEY = 'worklist.person-question'
29
+
30
+ /** The person a conversation is about, by its anchor - `undefined` when it is about no one. */
31
+ export function personOfAnchor(anchorType: string | null | undefined, anchorId: string | null | undefined): string | undefined {
32
+ if (anchorType !== 'subject' || typeof anchorId !== 'string' || !anchorId.startsWith(`${PERSON_AXIS}:`)) return undefined
33
+ return anchorId.slice(PERSON_AXIS.length + 1) || undefined
34
+ }
35
+
36
+ /**
37
+ * Who sits in a new conversation besides the one starting it - the person it is about, unless that is themself.
38
+ * The conversation is then a group (`visibility`): a private one seats nobody, an open one the whole domain reads.
39
+ */
40
+ export function personSeatOf(anchorType: string | null | undefined, anchorId: string | null | undefined, starter: { id?: string } | null | undefined): { userId: string; visibility: 'group' } | undefined {
41
+ const userId = personOfAnchor(anchorType, anchorId)
42
+ return userId && userId !== starter?.id ? { userId, visibility: 'group' } : undefined
43
+ }
44
+
45
+ /** Why this change is refused in a conversation about someone - or nothing when it is not about anyone else. */
46
+ export function personRoomRefusal(
47
+ session: { anchorType?: string | null; anchorId?: string | null; creatorId?: string | null },
48
+ change: { visibility?: string; removing?: string }
49
+ ): 'person-room-group-only' | 'person-room-keeps-person' | undefined {
50
+ const userId = personOfAnchor(session.anchorType, session.anchorId)
51
+ if (!userId || userId === session.creatorId) return undefined
52
+ if (change.visibility && change.visibility !== 'group') return 'person-room-group-only'
53
+ if (change.removing && change.removing === userId) return 'person-room-keeps-person'
54
+ return undefined
55
+ }
56
+
57
+ /** The words of a refusal above. */
58
+ export const PERSON_ROOM_REFUSALS: Record<string, string> = {
59
+ 'person-room-group-only': 'a conversation about someone stays a group they read - it cannot be opened to everyone or made private.',
60
+ 'person-room-keeps-person': 'the person this conversation is about always reads it - they cannot be sent out. they can hide it from their own list.'
61
+ }
62
+
63
+ /**
64
+ * How a conversation about someone is held - said to the model after the person's name, every turn.
65
+ */
66
+ export const PERSON_GUIDANCE = [
67
+ 'This conversation is about that person, and they read it. Rules:',
68
+ "- Answer from the records the read tools return about them. Say which record each fact comes from and when it was last changed; when a record is missing or old, say so.",
69
+ '- Never guess their character, intent, mood or ability, never judge their performance, and never speak as them - say "their weekly report says", never "I".',
70
+ `- What would bind them - whether something can be done, a deadline, an agreement, a refusal, their opinion - is theirs to say. Say it needs their confirmation and offer the confirmation card (${entryToolName(PERSON_QUESTION_KEY)}): the question, what the records already answered, what they must decide, and a draft answer drawn only from their records.`
71
+ ].join('\n')
72
+
73
+ export function personSubjectDescriber(entersDomain = entersDomainAsAssignee): AssistantSubjectDescriber {
74
+ return {
75
+ anchorType: 'subject',
76
+ axis: PERSON_AXIS,
77
+ async describe({ anchorId, domain }) {
78
+ const userId = personOfAnchor('subject', anchorId)
79
+ if (!userId) return undefined
80
+ const user = await getRepository(User).findOne({ where: { id: userId } })
81
+ if (!user || !(await entersDomain(domain as any, user))) return undefined
82
+ const name = user.name || user.email || ''
83
+ return name ? { noun: 'person', name, guidance: PERSON_GUIDANCE } : undefined
84
+ }
85
+ }
86
+ }
87
+
88
+ registerAssistantSubject(personSubjectDescriber())
@@ -67,6 +67,6 @@ test('the component places the draft and never sends it', () => {
67
67
  const updated = chat.slice(start, chat.indexOf('// 자동 스크롤', start))
68
68
  assert.ok(updated.includes('assistantDraftDecision('), 'the draft decision is made in updated()')
69
69
  const draftPart = updated.slice(updated.indexOf('assistantDraftDecision('))
70
- assert.match(draftPart, /this\.input = this\.draft!/)
70
+ assert.match(draftPart, /this\.input = addressed\.input/)
71
71
  assert.doesNotMatch(draftPart, /this\.send\(\)/)
72
72
  })
@@ -152,11 +152,13 @@ describe('what the walk itself has to be true for', () => {
152
152
  * group conversation and its typing line, ADR-0073 decision 3).
153
153
  * 2026-10-25: 46 — archivedSessionCount · cleanupSessionCount · aiSessionKeeping · deletedAISessions · restoreAISession
154
154
  * (archive, suggestions to clear and bringing a deleted one back, shared dock §2-7), declared.
155
+ * 2026-11-12: 47 — keptInAISession (the person a conversation is about, whom the screen offers no way to send out,
156
+ * ADR-0200), declared.
155
157
  */
156
158
  const all = fieldsOf('Query').length + fieldsOf('Mutation').length + fieldsOf('Subscription').length
157
159
  const open = openFields('Query').length + openFields('Mutation').length + openFields('Subscription').length
158
160
 
159
- expect(all).toBe(46)
161
+ expect(all).toBe(47)
160
162
  expect(open).toBe(3)
161
163
  })
162
164
  })
@@ -505,6 +505,8 @@
505
505
  "ai-assistant.text.invite-private-refused": "a private conversation is yours alone. make it a group to bring people in.",
506
506
  "ai-assistant.text.invite-owner-only": "only the person who started this group conversation can bring people in.",
507
507
  "ai-assistant.text.remove-owner-only": "only the person who started this conversation can send someone out.",
508
+ "ai-assistant.text.person-room-group-only": "a conversation about someone stays a group they read - it cannot be opened to everyone or made private.",
509
+ "ai-assistant.text.person-room-keeps-person": "the person this conversation is about always reads it - they cannot be sent out. they can hide it from their own list.",
508
510
  "ai-assistant.text.owner-cannot-leave": "you started this conversation, so you cannot leave it. delete it, or make it private.",
509
511
  "ai-assistant.text.session-not-found": "this conversation is not here any more. reload the list.",
510
512
  "ai-assistant.text.restore-creator-only": "only the person who started this conversation can bring it back.",