@odyssey365/cli 0.2.0 → 0.2.2

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.
package/dist/watch.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * 그 위에 프로그램(예: Claude Code 디스패처)이 붙는다 — `odyssey watch --tag "클로드 코드" | 디스패처`.
5
5
  *
6
6
  * ## 어떻게 듣나
7
- * MCP 서버는 무상태 함수라 밀어 줄 수 없다. 그래서 CLI 로그인(OAuth)을 서버에서 Firebase 커스텀 토큰 +
7
+ * MCP 서버는 무상태 함수라 밀어 줄 수 없다. 그래서 CLI 자격(OAuth · API 키)을 서버에서 Firebase 커스텀 토큰 +
8
8
  * App Check 토큰으로 바꿔(`/cli/firebase-session`) **Firestore 리스너를 직접** 붙인다. CLI 전용 신원으로 감시에 필요한 읽기만 허용한다.
9
9
  * - 할일: `user/{uid}/todo` 중 태그가 하나라도 맞는 것(`--tag`, 최대 30개) — 처음 스냅샷은 initial:true(밀린 일).
10
10
  * - 내 댓글: 컬렉션 그룹 `messages` 에서 senderUid == 나 · createdAt > 커서(기본 = 켠 시각).
@@ -15,25 +15,48 @@
15
15
  * 회수는 App Check 수명에 기대지 않는다 — rules 가 연결 원장을 확인해 회수 뒤 추가 데이터 접근을 거절한다.
16
16
  * 서버는 연결 전용 Firebase uid 의 갱신도 회수한다(사용자의 일반 앱 로그인과 분리).
17
17
  * 이력: document/90-process/work-log/261022 Odyssey CLI 자격 회수 CLI 전용 신원 companion 댓글 분류.md
18
+ * API 키는 폐기하면 새 교환만 바로 막는다 — 돌던 감시는 다음 재교환(위 1시간)에서 거절돼 끝나고, rules 도 폐기 뒤
19
+ * 1시간까지만 둔다.
20
+ * 이력: document/90-process/work-log/261028 Odyssey CLI API 키 감시 whoami 신원 앱 안내.md
18
21
  * Firebase 로그인 상태는 메모리에만 둔다(디스크에 refresh 토큰을 남기지 않는다).
19
22
  *
20
23
  * Firebase JS SDK 는 이 명령에서만 불러온다(동적 import) — 다른 명령은 의존성 없이 그대로 뜬다.
21
24
  *
22
25
  * 이력: document/90-process/work-log/261016 Odyssey CLI 스트림 odyssey watch 토큰 교환 Firestore 직접 감시.md
26
+ *
27
+ * ## 관심 스레드
28
+ * 에이전트가 댓글을 남긴 방은 서버가 `user/{uid}/followed_thread` 에 올린다(follow_thread 로 직접도). 감시는 그 목록을
29
+ * 듣고 방마다 메시지 리스너를 붙여, 그 방의 새 댓글을 **누가 썼든** followed:true 로 낸다(남이 쓴 것은 author other).
30
+ * 목록이 바뀌면 붙이고 떼며 {"type":"thread"} 를 낸다. 만료(expiresAt — 기간은 서버가 스레드마다 정한다, 기본 14일)는 여기서도 1분마다 다시 본다. 같은 댓글이
31
+ * 내 댓글 흐름과 관심 방 리스너 양쪽으로 오면 한 번만 낸다.
32
+ * 이력: document/90-process/work-log/261029 Odyssey CLI 관심 스레드 followed_thread watch 자동 등록.md
33
+ *
34
+ * ## 태그 항목의 스레드
35
+ * `--tag` 가 걸린 내 할일·메모·프로젝트·리포트(리포트는 `itemTags`)를 듣고, 그 항목들의 댓글방을 30개씩 묶어(`in`)
36
+ * 찾는다 — 보드는 보드 전체 방과 그 보드 카드 방(parentItemUid)까지. 찾은 방에 관심 스레드와 같은 리스너를 붙여 새
37
+ * 댓글을 누가 썼든 tagged:true 로 낸다. 태그가 곧 관심 표시라 등록·만료가 없고, 태그를 떼면 바로 빠진다
38
+ * ({"type":"thread","source":"tag"}). 한 방이 관심·태그 둘 다면 리스너는 하나다.
39
+ * 이력: document/90-process/work-log/261029 Odyssey CLI 감시 태그 항목 스레드 할일 메모 프로젝트 리포트 itemTags.md
23
40
  */
24
41
  import { UsageError } from './config.js';
25
42
  import { OdysseyClient, resolveTarget } from './session.js';
26
- import { commentEvent, isLiveComment, todoEvent } from './watch-events.js';
27
- export const WATCH_HELP = `odyssey watch [--tag 태그 ...] [--no-comments] [--include-agent] [--since ISO]
43
+ import { activeFollowedRooms, activeTaggedRooms, commentAuthor, commentEvent, InChunks, isLiveComment, isTaggedRoom, TAG_SOURCES, tagThreadEvent, threadEvent, todoEvent, } from './watch-events.js';
44
+ export const WATCH_HELP = `odyssey watch [--tag 태그 ...] [--no-tag-threads] [--no-comments] [--no-threads] [--include-agent] [--since ISO]
28
45
  내 계정의 변화를 실시간으로 받아 한 줄에 JSON 하나씩(NDJSON) stdout 으로 낸다. 끄려면 Ctrl+C.
29
- --tag <태그> 이 태그(하나라도)가 달린 할일의 추가·수정·삭제(반복 가능, 최대 30). 없으면 할일은 안 본다
30
- --no-comments 내 댓글은 보지 않는다
31
- --include-agent AI(MCP·컴패니언)가 단 댓글도 낸다(기본은 내가 쓴 것만)
46
+ --tag <태그> 이 태그(하나라도)가 달린 할일의 추가·수정·삭제와, 이 태그가 달린 내 할일·메모·프로젝트(그 보드의
47
+ 카드 포함)·리포트의 댓글 스레드(반복 가능, 최대 30). 없으면 둘 다 안 본다
48
+ --no-tag-threads 태그 항목의 댓글 스레드는 보지 않는다(할일 변화만)
49
+ --no-comments 내 댓글 흐름(모든 스레드의 내 댓글)을 보지 않는다
50
+ --no-threads 관심 스레드(에이전트가 댓글을 남긴 방 · odyssey threads follow)를 보지 않는다
51
+ --include-agent AI(MCP·컴패니언)가 단 댓글도 낸다(기본은 사람이 쓴 것만)
32
52
  --since <ISO> 이 시각 뒤의 댓글부터(기본: 지금). 밀린 댓글을 다시 받을 때
33
- 이벤트: {"type":"ready"} · {"type":"todo",...} · {"type":"comment",...} · {"type":"error",...}
34
- OAuth 로그인 프로필만 된다(API 키는 거절).`;
53
+ 이벤트: {"type":"ready"} · {"type":"todo",...} · {"type":"comment",...} · {"type":"thread",...} · {"type":"error",...}
54
+ comment 의 followed:true = 관심 스레드의 댓글 · tagged:true = 태그 항목 스레드의 댓글(둘 다 남이 쓴 것은 author "other")
55
+ replyTo = 답글이면 원 댓글과 그 작성자 · thread 의 source "tag" = 태그 항목의 방(태그를 떼면 reason "untagged" 로 빠진다)
56
+ 브라우저 로그인·API 키(--with-key) 프로필 모두 된다. 앱에서 키를 폐기하면 새 감시는 바로 막히고,
57
+ 돌던 감시는 길어야 1시간 안에 끝난다.`;
35
58
  export function parseWatchArgs(args, now = new Date()) {
36
- const o = { tags: [], comments: true, includeAgent: false, since: now };
59
+ const o = { tags: [], tagThreads: true, comments: true, threads: true, includeAgent: false, since: now };
37
60
  for (let i = 0; i < args.length; i++) {
38
61
  const a = args[i];
39
62
  const [flag, inline] = a.startsWith('--') && a.includes('=') ? [a.slice(0, a.indexOf('=')), a.slice(a.indexOf('=') + 1)] : [a, undefined];
@@ -47,9 +70,15 @@ export function parseWatchArgs(args, now = new Date()) {
47
70
  case '--tag':
48
71
  o.tags.push(value());
49
72
  break;
73
+ case '--no-tag-threads':
74
+ o.tagThreads = false;
75
+ break;
50
76
  case '--no-comments':
51
77
  o.comments = false;
52
78
  break;
79
+ case '--no-threads':
80
+ o.threads = false;
81
+ break;
53
82
  case '--include-agent':
54
83
  o.includeAgent = true;
55
84
  break;
@@ -67,8 +96,9 @@ export function parseWatchArgs(args, now = new Date()) {
67
96
  }
68
97
  if (o.tags.length > 30)
69
98
  throw new UsageError('--tag 는 30개까지입니다(Firestore array-contains-any 한도).');
70
- if (!o.tags.length && !o.comments)
71
- throw new UsageError('볼 것이 없습니다 — --tag 를 주거나 --no-comments 를 빼세요.');
99
+ if (!o.tags.length && !o.comments && !o.threads) {
100
+ throw new UsageError('볼 것이 없습니다 — --tag 를 주거나 --no-comments·--no-threads 를 빼세요.');
101
+ }
72
102
  return o;
73
103
  }
74
104
  function emit(event) {
@@ -111,54 +141,298 @@ export async function cmdWatch(g, args, version) {
111
141
  if (pending.size === 0)
112
142
  emit({ type: 'ready', uid, streams, since: opts.since.toISOString() });
113
143
  };
144
+ // 댓글 공용 — 방 메타·원 댓글 작성자 캐시, 한 번만 내기.
145
+ const rooms = new Map();
146
+ const roomOf = async (roomUid) => {
147
+ if (!roomUid)
148
+ return null;
149
+ if (rooms.has(roomUid))
150
+ return rooms.get(roomUid);
151
+ let room = null;
152
+ try {
153
+ const snap = await fs.getDoc(fs.doc(db, 'shared', 'communication', 'chat', roomUid));
154
+ room = snap.exists() ? snap.data() : null;
155
+ }
156
+ catch {
157
+ room = null; // 방을 못 읽어도(나간 공유 보드 등) 댓글은 낸다 — 항목 칸만 빈다.
158
+ }
159
+ rooms.set(roomUid, room);
160
+ return room;
161
+ };
162
+ const replyAuthors = new Map();
163
+ const replyAuthorOf = async (roomUid, replyId) => {
164
+ if (!roomUid || typeof replyId !== 'string' || !replyId)
165
+ return null;
166
+ const key = `${roomUid}/${replyId}`;
167
+ if (replyAuthors.has(key))
168
+ return replyAuthors.get(key);
169
+ let author = null;
170
+ try {
171
+ const snap = await fs.getDoc(fs.doc(db, 'shared', 'communication', 'chat', roomUid, 'messages', replyId));
172
+ author = snap.exists() ? commentAuthor(snap.data(), uid) : null;
173
+ }
174
+ catch {
175
+ author = null; // 못 읽는 방(다이렉트·권한 밖) — 답글 대상 작성자만 모른다.
176
+ }
177
+ replyAuthors.set(key, author);
178
+ return author;
179
+ };
180
+ const emitted = new Set();
181
+ const emitOnce = (key, event) => {
182
+ if (emitted.has(key))
183
+ return;
184
+ emitted.add(key);
185
+ // 오래 도는 감시의 기억을 묶어 둔다 — 같은 댓글이 두 흐름으로 오는 간격은 짧다.
186
+ if (emitted.size > 5000)
187
+ emitted.delete(emitted.values().next().value);
188
+ emit(event);
189
+ };
190
+ // 방 리스너 — 관심 스레드(followedRooms)든 태그 항목(taggedRooms)이든 방마다 하나만 붙인다.
191
+ const roomListeners = new Map();
192
+ const followedRooms = new Set();
193
+ const taggedRooms = new Set();
194
+ // 읽기를 거절당한 방 — 붙였다 떼기를 되풀이하지 않는다. 관심 문서가 다시 오면 지운다.
195
+ const forbidden = new Set();
196
+ // 마지막으로 본 관심 문서 — 목록에서 빠진 뒤의 unfollowed 이벤트도 항목을 말하게.
197
+ const lastFollowed = new Map();
198
+ // 감시 태그가 걸린 내 항목(`itemType/uid`) — 내 댓글 흐름도 이걸 보고 tagged 를 단다.
199
+ const taggedKeys = new Set();
200
+ // 관심 방 목록·태그 항목의 첫 스냅샷 전에는 내 댓글 흐름이 followed·tagged 를 모른다 — 밀린 댓글(--since)이
201
+ // 먼저 오면 false 로 나갈 수 있어 그 둘을 기다린다. 못 읽어도(구버전 서버 rules) 풀어 준다.
202
+ let releaseThreads = () => { };
203
+ const threadsReady = opts.threads ? new Promise((r) => { releaseThreads = r; }) : Promise.resolve();
204
+ const tagThreads = opts.tags.length > 0 && opts.tagThreads;
205
+ let releaseTagged = () => { };
206
+ const taggedReady = opts.tags.length ? new Promise((r) => { releaseTagged = r; }) : Promise.resolve();
207
+ const deliverComment = async (id, data, roomUid, room) => {
208
+ if (!isLiveComment(data))
209
+ return;
210
+ const ev = commentEvent(id, data, room, {
211
+ ownerUid: uid,
212
+ followed: !!roomUid && followedRooms.has(roomUid),
213
+ tagged: isTaggedRoom(room, taggedKeys, uid),
214
+ replyToAuthor: await replyAuthorOf(roomUid, data.replyToMessageUid),
215
+ });
216
+ if (ev.author === 'agent' && !opts.includeAgent)
217
+ return;
218
+ emitOnce(ev.commentUid, ev);
219
+ };
220
+ const listenRoom = (roomUid, room) => {
221
+ rooms.set(roomUid, room);
222
+ if (roomListeners.has(roomUid))
223
+ return;
224
+ const q = fs.query(fs.collection(db, 'shared', 'communication', 'chat', roomUid, 'messages'), fs.where('createdAt', '>', fs.Timestamp.fromDate(opts.since)), fs.orderBy('createdAt'));
225
+ const off = fs.onSnapshot(q, async (snap) => {
226
+ for (const ch of snap.docChanges()) {
227
+ if (ch.type !== 'added')
228
+ continue;
229
+ await deliverComment(ch.doc.id, ch.doc.data(), roomUid, room);
230
+ }
231
+ }, (e) => {
232
+ const code = e.code ?? null;
233
+ // 그 방을 못 읽게 됐다(공유 보드에서 빠짐 · 항목 삭제) — 감시 전체를 내리지 않고 그 방만 뗀다.
234
+ if (code === 'permission-denied') {
235
+ forbidden.add(roomUid);
236
+ roomListeners.delete(roomUid);
237
+ if (followedRooms.delete(roomUid)) {
238
+ emit(threadEvent('unfollowed', roomUid, lastFollowed.get(roomUid) ?? {}, false, 'forbidden'));
239
+ }
240
+ if (taggedRooms.delete(roomUid))
241
+ emit(tagThreadEvent('unfollowed', roomUid, room, false, 'forbidden'));
242
+ return;
243
+ }
244
+ emit({ type: 'error', stream: 'threads', roomUid, code, message: e.message });
245
+ });
246
+ roomListeners.set(roomUid, off);
247
+ };
248
+ /** 어느 이유로도 듣지 않게 된 방의 리스너를 뗀다. */
249
+ const dropRoom = (roomUid) => {
250
+ if (followedRooms.has(roomUid) || taggedRooms.has(roomUid))
251
+ return;
252
+ roomListeners.get(roomUid)?.();
253
+ roomListeners.delete(roomUid);
254
+ };
255
+ // ── 태그 항목 ── 할일은 변화도 이벤트로 낸다(밀린 일). 메모·프로젝트·리포트는 방을 찾는 데만 쓴다.
256
+ // 항목 uid 를 30개씩 묶어(`in`) 그 항목들의 방을 찾고, 찾은 방에 리스너를 붙인다. 태그를 떼면 그 방은 바로 빠진다.
257
+ const roomDocs = new Map();
258
+ const sourceUids = new Map();
259
+ const chunkers = new Map();
260
+ const chunkSubs = new Map();
261
+ // 첫 스냅샷을 아직 못 받은 방 찾기 쿼리 — 다 오기 전엔 ready 를 내지 않는다(그 사이 다시 묶이면 그 쿼리는 빠진다).
262
+ const firstPending = new Set();
263
+ let itemsPending = 0;
264
+ let tagInitial = true;
265
+ let tagDropped = false;
266
+ const settleTagged = () => {
267
+ if (!tagInitial || itemsPending > 0 || firstPending.size > 0)
268
+ return;
269
+ tagInitial = false;
270
+ releaseTagged();
271
+ if (tagThreads && !tagDropped) {
272
+ pending.delete('tagThreads');
273
+ ready();
274
+ }
275
+ };
276
+ const reconcileTagged = () => {
277
+ if (!tagThreads || tagDropped)
278
+ return;
279
+ const want = new Set(activeTaggedRooms(roomDocs, taggedKeys, uid).filter((r) => !forbidden.has(r)));
280
+ for (const r of [...taggedRooms]) {
281
+ if (want.has(r))
282
+ continue;
283
+ const d = roomDocs.get(r);
284
+ taggedRooms.delete(r);
285
+ dropRoom(r);
286
+ // 아직 태그 항목의 방인데 빠졌으면 상한에 밀린 것이다.
287
+ emit(tagThreadEvent('unfollowed', r, d ?? rooms.get(r) ?? {}, false, d && isTaggedRoom(d, taggedKeys, uid) ? 'limit' : 'untagged'));
288
+ }
289
+ for (const r of want) {
290
+ if (taggedRooms.has(r))
291
+ continue;
292
+ const d = roomDocs.get(r);
293
+ taggedRooms.add(r);
294
+ listenRoom(r, d);
295
+ emit(tagThreadEvent('followed', r, d, tagInitial));
296
+ }
297
+ // 태그가 빠진 항목의 방은 잊는다 — 다시 달면 그 칸의 쿼리가 다시 준다.
298
+ for (const [r, d] of [...roomDocs])
299
+ if (!isTaggedRoom(d, taggedKeys, uid))
300
+ roomDocs.delete(r);
301
+ };
302
+ const dropTagThreads = (why) => {
303
+ if (tagDropped)
304
+ return;
305
+ tagDropped = true;
306
+ process.stderr.write(`odyssey watch: ${why} — 태그 항목의 스레드 없이 감시합니다.\n`);
307
+ for (const off of chunkSubs.values())
308
+ off();
309
+ chunkSubs.clear();
310
+ firstPending.clear();
311
+ for (const r of [...taggedRooms]) {
312
+ taggedRooms.delete(r);
313
+ dropRoom(r);
314
+ }
315
+ roomDocs.clear();
316
+ const i = streams.indexOf('tagThreads');
317
+ if (i >= 0)
318
+ streams.splice(i, 1);
319
+ // 아직 ready 전이면 이 흐름 없이 낸다. 이미 냈다면 다시 내지 않는다(감시는 나머지로 계속 돈다).
320
+ if (pending.delete('tagThreads'))
321
+ ready();
322
+ settleTagged();
323
+ };
324
+ const syncChunks = (s) => {
325
+ if (!tagThreads || tagDropped)
326
+ return;
327
+ let chunker = chunkers.get(s.itemType);
328
+ if (!chunker)
329
+ chunkers.set(s.itemType, (chunker = new InChunks()));
330
+ for (const i of chunker.sync(sourceUids.get(s.itemType) ?? new Set())) {
331
+ s.rooms.forEach((rq, qi) => {
332
+ const key = `${s.itemType}:${qi}:${i}`;
333
+ chunkSubs.get(key)?.();
334
+ chunkSubs.delete(key);
335
+ firstPending.delete(key);
336
+ const ids = chunker.get(i);
337
+ if (!ids.length)
338
+ return;
339
+ // 방 목록은 내 항목(itemOwnerUid == 나)의 댓글방만 열린다(rules) — 남의 공유 보드 방은 여기서 안 나온다.
340
+ const q = fs.query(fs.collection(db, 'shared', 'communication', 'chat'), fs.where('itemOwnerUid', '==', uid), fs.where('itemType', '==', rq.itemType), fs.where(rq.keyField, 'in', [...ids]));
341
+ if (tagInitial)
342
+ firstPending.add(key);
343
+ const off = fs.onSnapshot(q, (snap) => {
344
+ for (const c of snap.docChanges()) {
345
+ if (c.type === 'removed')
346
+ roomDocs.delete(c.doc.id);
347
+ else
348
+ roomDocs.set(c.doc.id, c.doc.data());
349
+ }
350
+ reconcileTagged();
351
+ if (firstPending.delete(key))
352
+ settleTagged();
353
+ }, (e) => {
354
+ const code = e.code ?? null;
355
+ if (code === 'permission-denied') {
356
+ dropTagThreads('서버가 태그 항목의 스레드를 아직 지원하지 않아');
357
+ return;
358
+ }
359
+ if (firstPending.delete(key))
360
+ settleTagged();
361
+ emit({ type: 'error', stream: 'tagThreads', code, message: e.message });
362
+ });
363
+ chunkSubs.set(key, off);
364
+ });
365
+ }
366
+ };
114
367
  if (opts.tags.length) {
368
+ const sources = tagThreads ? TAG_SOURCES : TAG_SOURCES.filter((s) => s.itemType === 'todo');
115
369
  streams.push('todos');
116
370
  pending.add('todos');
117
- let first = true;
118
- const q = fs.query(fs.collection(db, 'user', uid, 'todo'), fs.where('tags', 'array-contains-any', opts.tags));
119
- unsubs.push(fs.onSnapshot(q, (snap) => {
120
- for (const ch of snap.docChanges())
121
- emit(todoEvent(ch.type, ch.doc.id, ch.doc.data(), first));
122
- if (first) {
371
+ if (tagThreads) {
372
+ streams.push('tagThreads');
373
+ pending.add('tagThreads');
374
+ }
375
+ itemsPending = sources.length;
376
+ for (const s of sources) {
377
+ const isTodo = s.itemType === 'todo';
378
+ const uids = new Set();
379
+ sourceUids.set(s.itemType, uids);
380
+ let first = true;
381
+ const settleFirst = () => {
382
+ if (!first)
383
+ return;
123
384
  first = false;
124
- pending.delete('todos');
125
- ready();
126
- }
127
- }, (e) => emit({ type: 'error', stream: 'todos', code: e.code ?? null, message: e.message })));
385
+ if (isTodo) {
386
+ pending.delete('todos');
387
+ ready();
388
+ }
389
+ itemsPending--;
390
+ settleTagged();
391
+ };
392
+ const q = fs.query(fs.collection(db, 'user', uid, s.collection), fs.where(s.tagField, 'array-contains-any', opts.tags));
393
+ unsubs.push(fs.onSnapshot(q, (snap) => {
394
+ for (const ch of snap.docChanges()) {
395
+ if (isTodo)
396
+ emit(todoEvent(ch.type, ch.doc.id, ch.doc.data(), first));
397
+ const key = `${s.itemType}/${ch.doc.id}`;
398
+ if (ch.type === 'removed') {
399
+ uids.delete(ch.doc.id);
400
+ taggedKeys.delete(key);
401
+ }
402
+ else {
403
+ uids.add(ch.doc.id);
404
+ taggedKeys.add(key);
405
+ }
406
+ }
407
+ syncChunks(s);
408
+ reconcileTagged();
409
+ settleFirst();
410
+ }, (e) => {
411
+ const code = e.code ?? null;
412
+ // 메모·프로젝트·리포트 읽기를 모르는 서버(rules 261029 전) — 할일 감시는 그대로 둔다. error 이벤트를 내면
413
+ // 받는 쪽(감시 예제)이 감시를 다시 띄우며 같은 거절을 되풀이한다.
414
+ if (!isTodo && code === 'permission-denied') {
415
+ settleFirst();
416
+ dropTagThreads('서버가 태그 항목의 스레드를 아직 지원하지 않아');
417
+ return;
418
+ }
419
+ emit({ type: 'error', stream: isTodo ? 'todos' : 'tagThreads', code, message: e.message });
420
+ }));
421
+ }
128
422
  }
129
423
  if (opts.comments) {
130
424
  streams.push('comments');
131
425
  pending.add('comments');
132
- const rooms = new Map();
133
- const roomOf = async (roomUid) => {
134
- if (!roomUid)
135
- return null;
136
- if (rooms.has(roomUid))
137
- return rooms.get(roomUid);
138
- let room = null;
139
- try {
140
- const snap = await fs.getDoc(fs.doc(db, 'shared', 'communication', 'chat', roomUid));
141
- room = snap.exists() ? snap.data() : null;
142
- }
143
- catch {
144
- room = null; // 방을 못 읽어도(나간 공유 보드 등) 댓글은 낸다 — 항목 칸만 빈다.
145
- }
146
- rooms.set(roomUid, room);
147
- return room;
148
- };
149
426
  let first = true;
150
427
  const q = fs.query(fs.collectionGroup(db, 'messages'), fs.where('senderUid', '==', uid), fs.where('createdAt', '>', fs.Timestamp.fromDate(opts.since)), fs.orderBy('createdAt'));
151
428
  unsubs.push(fs.onSnapshot(q, async (snap) => {
429
+ await Promise.all([threadsReady, taggedReady]);
152
430
  for (const ch of snap.docChanges()) {
153
431
  if (ch.type !== 'added')
154
432
  continue;
155
433
  const data = ch.doc.data();
156
- if (!isLiveComment(data))
157
- continue;
158
- const ev = commentEvent(ch.doc.id, data, await roomOf(data.chatRoomUid));
159
- if (ev.author === 'agent' && !opts.includeAgent)
160
- continue;
161
- emit(ev);
434
+ const roomUid = data.chatRoomUid;
435
+ await deliverComment(ch.doc.id, data, roomUid, await roomOf(roomUid));
162
436
  }
163
437
  if (first) {
164
438
  first = false;
@@ -167,6 +441,88 @@ export async function cmdWatch(g, args, version) {
167
441
  }
168
442
  }, (e) => emit({ type: 'error', stream: 'comments', code: e.code ?? null, message: e.message })));
169
443
  }
444
+ if (opts.threads) {
445
+ streams.push('threads');
446
+ pending.add('threads');
447
+ const followedDocs = new Map();
448
+ let initial = true;
449
+ const unfollow = (roomUid, reason) => {
450
+ if (!followedRooms.delete(roomUid))
451
+ return;
452
+ dropRoom(roomUid);
453
+ emit(threadEvent('unfollowed', roomUid, lastFollowed.get(roomUid) ?? {}, false, reason));
454
+ };
455
+ const follow = (roomUid) => {
456
+ const d = followedDocs.get(roomUid) ?? {};
457
+ followedRooms.add(roomUid);
458
+ listenRoom(roomUid, {
459
+ itemType: d.itemType, itemUid: d.itemUid, itemOwnerUid: d.itemOwnerUid, parentItemUid: d.parentItemUid,
460
+ });
461
+ emit(threadEvent('followed', roomUid, d, initial));
462
+ };
463
+ const reconcile = () => {
464
+ const now = Date.now();
465
+ const want = new Set(activeFollowedRooms(followedDocs, now).filter((r) => !forbidden.has(r)));
466
+ for (const roomUid of [...followedRooms]) {
467
+ if (want.has(roomUid))
468
+ continue;
469
+ const d = followedDocs.get(roomUid);
470
+ const expiresMs = Date.parse(threadEvent('followed', roomUid, d ?? lastFollowed.get(roomUid) ?? {}, false).expiresAt ?? '');
471
+ const expired = Number.isFinite(expiresMs) && expiresMs <= now;
472
+ unfollow(roomUid, expired ? 'expired' : d ? 'limit' : 'manual');
473
+ }
474
+ for (const roomUid of want)
475
+ if (!followedRooms.has(roomUid))
476
+ follow(roomUid);
477
+ };
478
+ unsubs.push(fs.onSnapshot(fs.collection(db, 'user', uid, 'followed_thread'), (snap) => {
479
+ for (const ch of snap.docChanges()) {
480
+ const data = ch.doc.data();
481
+ lastFollowed.set(ch.doc.id, data);
482
+ if (ch.type === 'removed')
483
+ followedDocs.delete(ch.doc.id);
484
+ else
485
+ followedDocs.set(ch.doc.id, data);
486
+ // 다시 올린 방은 거절 기억을 지운다(권한이 돌아왔을 수 있다).
487
+ if (ch.type === 'added')
488
+ forbidden.delete(ch.doc.id);
489
+ }
490
+ reconcile();
491
+ if (initial) {
492
+ initial = false;
493
+ releaseThreads();
494
+ pending.delete('threads');
495
+ ready();
496
+ }
497
+ }, (e) => {
498
+ const code = e.code ?? null;
499
+ releaseThreads();
500
+ if (code === 'permission-denied' && initial) {
501
+ // 관심 스레드를 모르는 서버(rules 261029 전) — 감시는 나머지로 계속한다. error 이벤트를 내면
502
+ // 받는 쪽(감시 예제)이 감시를 다시 띄우며 같은 거절을 되풀이한다.
503
+ process.stderr.write('odyssey watch: 서버가 관심 스레드를 아직 지원하지 않아 그것 없이 감시합니다.\n');
504
+ initial = false;
505
+ streams.splice(streams.indexOf('threads'), 1);
506
+ pending.delete('threads');
507
+ ready();
508
+ return;
509
+ }
510
+ emit({ type: 'error', stream: 'threads', code, message: e.message });
511
+ }));
512
+ // 만료는 문서가 바뀌지 않아도 온다 — 1분마다 다시 본다.
513
+ const timer = setInterval(reconcile, 60_000);
514
+ timer.unref();
515
+ unsubs.push(() => clearInterval(timer));
516
+ }
517
+ // 방 리스너·방 찾기 쿼리는 끝에 한 번에 뗀다(관심·태그가 같은 방을 나눠 든다).
518
+ unsubs.push(() => {
519
+ for (const off of chunkSubs.values())
520
+ off();
521
+ chunkSubs.clear();
522
+ for (const off of roomListeners.values())
523
+ off();
524
+ roomListeners.clear();
525
+ });
170
526
  return new Promise((resolve) => {
171
527
  const stop = () => {
172
528
  for (const u of unsubs)
@@ -1,6 +1,6 @@
1
1
  # Odyssey 감시 에이전트 예제
2
2
 
3
- > 0.2.0 보안 후보: 감시는 CLI 전용 Firebase 신원을 요구합니다. Functions·규칙의 동반 업데이트 전에는 감시가 시작되지 않습니다. 이 저장소 후보는 아직 배포하지 않았습니다.
3
+ > `@odyssey365/cli` **0.2.0+** · 감시는 CLI 로그인 프로필(브라우저 로그인 또는 API 키 `--with-key`)이 필요합니다.
4
4
 
5
5
  Odyssey에서 태그나 댓글로 맡긴 일을 Claude Code에 전달하는 실행 가능한 예제입니다.
6
6
  할일·항목마다 세션 하나를 만들고, 이후 댓글은 같은 세션으로 이어 받습니다.
@@ -8,12 +8,11 @@ Odyssey에서 태그나 댓글로 맡긴 일을 Claude Code에 전달하는 실
8
8
 
9
9
  ## 처음 시작하기
10
10
 
11
- Node.js 20 이상, OAuth 로그인한 Odyssey CLI, 로그인한 Claude Code가 필요합니다.
12
- 배포 전 후보를 받았다면 제공된 `.tgz`로 설치합니다. 공개된 0.1.0에는 이 예제가 없습니다.
11
+ Node.js 20 이상, 로그인한 Odyssey CLI(브라우저 로그인 또는 앱에서 만든 API 키), 로그인한 Claude Code가 필요합니다.
13
12
 
14
13
  ```sh
15
- npm install -g /path/to/odyssey365-cli-0.2.0.tgz
16
- odyssey --version
14
+ npm install -g @odyssey365/cli
15
+ odyssey --version # 0.2.0+
17
16
  odyssey login
18
17
  odyssey whoami
19
18
  ```
@@ -47,7 +46,7 @@ node dispatcher.mjs --check
47
46
  node dispatcher.mjs --dry-run
48
47
  ```
49
48
 
50
- `--check`는 모델을 부르지 않고 CLI OAuth 인증·Claude Code 설치·MCP 등록을 확인합니다.
49
+ `--check`는 모델을 부르지 않고 CLI 로그인 계정(uid)·Claude Code 설치·MCP 등록을 확인합니다.
51
50
  `--dry-run`은 실제 감시를 연결하지만 일꾼을 깨우거나 댓글을 쓰지 않습니다. 로그에서 `ready`와 배달 예정을 확인하고 Ctrl+C로 끕니다.
52
51
  시험할 할일 하나에 `클로드 코드` 태그를 붙이거나 메모에 `@클로드코드` 댓글을 써서 배달 예정이 나오는지 보세요.
53
52
 
@@ -88,7 +87,7 @@ node dispatcher.mjs
88
87
  - **로그:** 터미널과 `logs/dispatcher.log`. 로그에는 맡긴 내용이 들어갈 수 있으므로 공유 전에 확인하세요.
89
88
  - **단일 실행:** 같은 상태 파일의 실행 잠금으로 중복 실행을 막습니다. 복제한 여러 폴더로 같은 일을 동시에 감시하지 마세요.
90
89
  - **계정 변경:** 계정마다 별도 예제 폴더를 만드세요. 상태 파일에 이전 계정 uid가 있으면 다른 계정으로 이어 받지 않습니다.
91
- - **로그인 필요:** `odyssey login -p <프로필>` 뒤 다시 실행합니다. API 키 로그인은 watch에 사용할 수 없습니다.
90
+ - **로그인 필요:** `odyssey login -p <프로필>`(또는 `--with-key`) 뒤 다시 실행합니다. API 키 프로필은 `odyssey whoami`에 uid가 나와야 합니다(키 신원을 아는 서버 261028+).
92
91
  - **세션 직접 열기:** 멈춘 상태에서 state.json의 sessionId를 찾아 작업 폴더에서 `claude --resume <id>`. 일꾼이 실행 중일 때 같은 세션을 열지 마세요.
93
92
  - **초기화:** config.json과 state.json을 지우기보다 별도 폴더를 만들어 시작하세요. 상태를 잃으면 미완료 작업을 다시 맡길 수 있습니다.
94
93
 
@@ -115,10 +114,15 @@ npm test
115
114
 
116
115
  실제 Odyssey와 Claude 대신 가짜 프로세스를 사용합니다. 배달·세션 재개·중복 방지·커서·FIFO·예산·오류 복구를 확인합니다.
117
116
  구조를 바꾸고 싶으면 `odyssey agent-guide --watch-agent`의 프롬프트를 코딩 에이전트에 주되, 이 검사를 함께 유지하세요.
117
+ 이 예제의 결정마다 이유와 다른 에이전트로 바꾸는 법(리뷰어·공유 보드 비서·정리 리포트)은 `odyssey agent-guide --design`(CLI 0.2.2+)에 있습니다.
118
118
 
119
119
 
120
120
  ## 댓글과 자격 회수
121
121
 
122
122
  `claude`·`companion`·알 수 없는 작성자 표식은 모두 AI 댓글입니다. 멘션이 있거나 이미 열린 세션이어도 일꾼에게 지시로 배달하지 않습니다.
123
+ 일꾼이 답글을 단 스레드는 관심 스레드가 되어, 공유 보드의 다른 사람 댓글도 감시로 옵니다(`author: "other"`). 감시 태그가 달린 메모·프로젝트·리포트의
124
+ 스레드도 같은 길로 옵니다(`tagged: true` — CLI 0.2.2+). 예제는 다른 사람 댓글을 일꾼에게 배달하지 않습니다 —
125
+ 일꾼은 다음에 깨어날 때 스레드를 읽어 맥락으로만 봅니다. 내 「답글」이 일꾼 댓글을 향하는지는 감시가 `replyTo.author`로 알려 줍니다.
123
126
  서버가 OAuth 연결을 회수하면 해당 CLI 신원의 데이터 접근과 Firebase 갱신을 막습니다. 일반 앱 로그인과 다른 OAuth 연결은 유지됩니다.
127
+ API 키는 앱에서 폐기하면 새 감시만 바로 막고, 돌던 감시는 다음 토큰 재교환(길어야 1시간)에서 끝납니다.
124
128
  이미 받은 데이터·진행 중인 일꾼 작업은 회수로 되돌아가지 않습니다. 감시 오류 뒤에는 예제의 재시작 간격이 적용됩니다.
@@ -33,7 +33,7 @@ export const DEFAULT_CONFIG = Object.freeze({
33
33
  mentionAck: '👀 받았어요.',
34
34
  // 작업 폴더 — 일꾼(claude -p)의 cwd. 이 밖은 건드리지 않는다
35
35
  workDir: path.join(HERE, 'work'),
36
- // Odyssey 프로필 — `odyssey login` 으로 로그인된 OAuth 프로필(API 키 프로필은 감시 불가)
36
+ // Odyssey 프로필 — `odyssey login` 으로 로그인된 프로필(브라우저 로그인 또는 --with-key API 키)
37
37
  odysseyProfile: 'default',
38
38
  odysseyBin: 'odyssey',
39
39
  // 일꾼 — Claude Code 헤드리스
@@ -117,7 +117,7 @@ export function validateConfig(cfg) {
117
117
 
118
118
  export const PHASES = ['running', 'idle', 'done', 'blocked', 'cancelled'];
119
119
  const DELIVERED_KEEP = 1000; // 항목당 기억하는 배달 댓글 수(파일이 끝없이 커지지 않게)
120
- const AGENT_KEEP = 300; // 항목당 기억하는 에이전트 댓글 uid 수(일꾼 댓글에 단 「답글」 판정용)
120
+ const AGENT_KEEP = 300; // 항목당 기억하는 에이전트 댓글 uid 수 — 옛 감시(--include-agent)용. 이제 답글 대상은 감시가 replyTo 로 알려 준다
121
121
 
122
122
  /** 일꾼이 답글을 달 수 있는 항목 종류 — comment_on_item 의 itemType + 보드 전체(comment_on_project). */
123
123
  export const COMMENT_ITEM_TYPES = Object.freeze([
@@ -379,8 +379,10 @@ export function buildWorkerArgs(cfg, { sessionId, resume, systemPrompt, message
379
379
  }
380
380
 
381
381
  export function buildWatchArgs(cfg, since) {
382
- // --include-agent: 에이전트 댓글 uid 를 알아 두려고(내 댓글이 일꾼 댓글에 단 「답글」인지 가르는 근거). 배달은 하지 않는다.
383
- return ['-p', cfg.odysseyProfile, 'watch', '--tag', cfg.watchTag, '--include-agent', ...(since ? ['--since', since] : [])];
382
+ // 답글이 일꾼 댓글을 향하는지는 감시가 replyTo.author 로 알려 준다(관심 스레드 — CLI 261029+) — 에이전트 댓글을 받아
383
+ // uid 를 적어 둘 필요가 없어 --include-agent 를 뺐다.
384
+ // 이력: document/90-process/work-log/261029 Odyssey CLI 관심 스레드 followed_thread watch 자동 등록.md
385
+ return ['-p', cfg.odysseyProfile, 'watch', '--tag', cfg.watchTag, ...(since ? ['--since', since] : [])];
384
386
  }
385
387
 
386
388
  export function failureContent(reason, kind = 'worker') {
@@ -506,7 +508,9 @@ export async function checkSetup(cfg) {
506
508
  const who = await runProcess(cfg.odysseyBin, ['-p', cfg.odysseyProfile, 'whoami'], { timeoutMs: 30_000 });
507
509
  if (who.code !== 0 || who.timedOut) throw new Error(`CLI 로그인을 확인하세요: odyssey login -p ${cfg.odysseyProfile}`);
508
510
  const account = JSON.parse(who.stdout);
509
- if (account.auth !== 'oauth' || !account.uid || account.ok !== true) throw new Error('감시는 OAuth 로그인이 필요해요: odyssey login');
511
+ if (!['oauth', 'apiKey'].includes(account.auth) || account.ok !== true) throw new Error('감시는 로그인한 프로필이 필요해요: odyssey login');
512
+ // 키 신원을 모르는 구버전 서버면 uid 가 비어 있다 — 계정 대조를 못 하니 막는다.
513
+ if (!account.uid) throw new Error('CLI 계정을 확인하지 못했어요. odyssey whoami 로 uid 가 나오는지 확인하세요.');
510
514
  if (cfg.expectedUid && account.uid !== cfg.expectedUid) throw new Error('설정 expectedUid와 CLI 계정이 달라요. 프로필을 확인하세요.');
511
515
  const version = await runProcess(cfg.claudeBin, ['--version'], { cwd: cfg.workDir, timeoutMs: 15_000 });
512
516
  if (version.code !== 0 || version.timedOut) throw new Error('Claude Code 설치·claudeBin 경로를 확인하세요.');
@@ -688,6 +692,10 @@ export class Dispatcher {
688
692
  if (this.watchReady) this.#onComment(evt);
689
693
  else this.preReady.push(evt);
690
694
  break;
695
+ case 'thread':
696
+ // 관심 스레드·태그 항목의 방(source "tag" — CLI 261029+)이 붙고 떨어진 기록 — 깨우는 판단은 세션 있는 항목·멘션으로 그대로 한다.
697
+ this.log.info(`${evt.source === 'tag' ? '태그 항목 스레드' : '관심 스레드'} ${evt.change ?? '?'}${evt.reason ? `(${evt.reason})` : ''}: ${evt.itemType ?? '?'} ${evt.itemUid ?? evt.roomUid ?? '?'}`);
698
+ break;
691
699
  case 'error':
692
700
  this.watchErrored = true;
693
701
  this.log.warn(`watch 오류 [${evt.stream ?? '?'}] ${evt.code ?? ''} ${evt.message ?? ''}`.trim());
@@ -848,6 +856,12 @@ export class Dispatcher {
848
856
  const key = unaddressable ? null : itemKeyOf(ref);
849
857
  const item = key ? this.state.items[key] : undefined;
850
858
 
859
+ if (evt.author === 'other') {
860
+ // 관심 스레드에 다른 사람(공유 보드 멤버)이 쓴 댓글 — 일꾼에게는 내 댓글만 배달한다(남의 글로 내 작업 폴더의
861
+ // 에이전트를 움직이게 두지 않는다). 일꾼은 다음에 깨어날 때 스레드를 읽어 맥락으로 본다.
862
+ this.log.info(`${label} → 무시(다른 사람 댓글 — 일꾼에게는 내 댓글만 배달)`);
863
+ return;
864
+ }
851
865
  if (evt.author !== 'me') {
852
866
  // 절대 배달하지 않는다(일꾼 답글의 메아리). 그 항목 세션이 있으면 uid 만 적어 둔다 — 그 댓글에 단 내 「답글」을 알아보려고.
853
867
  const p = key ? this.pending.get(key) : undefined;
@@ -874,6 +888,7 @@ export class Dispatcher {
874
888
  createdAt: evt.createdAt ?? null,
875
889
  kind: evt.kind ?? null,
876
890
  ...(evt.replyToCommentUid ? { replyToCommentUid: evt.replyToCommentUid } : {}),
891
+ ...(evt.replyTo?.author ? { replyToAuthor: evt.replyTo.author } : {}),
877
892
  };
878
893
  const mention = hasMention(c.text, this.cfg.mentions);
879
894
 
@@ -916,7 +931,8 @@ export class Dispatcher {
916
931
  if (item && item.phase !== 'cancelled') {
917
932
  this.#enqueue(key, { comments: [c] });
918
933
  const note = this.running === key ? ' (지금 도는 중 — 끝나면 모아서 한 번에)' : '';
919
- const how = c.replyToCommentUid && item.agentComments.includes(c.replyToCommentUid) ? `일꾼 댓글(${c.replyToCommentUid})에 단 답글` : '세션 있는 스레드의 내 댓글';
934
+ const toAgent = c.replyToAuthor === 'agent' || (c.replyToCommentUid && item.agentComments.includes(c.replyToCommentUid));
935
+ const how = toAgent ? `일꾼 댓글(${c.replyToCommentUid})에 단 답글` : '세션 있는 스레드의 내 댓글';
920
936
  this.log.info(`${label} → ${how} — 세션 ${item.sessionId} 이어 받기 "새 댓글" 큐에 넣음${note}`);
921
937
  return;
922
938
  }