@odyssey365/cli 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,763 @@
1
+ // 디스패처 단위·통합 테스트 — node --test test/
2
+ // 일꾼(claude)·댓글(odyssey)은 가짜로 바꿔 끼운다. 실제 Odyssey·Claude 는 부르지 않는다.
3
+ import test, { after } from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import { spawn } from 'node:child_process';
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { tmpdir } from 'node:os';
10
+
11
+ import {
12
+ DEFAULT_CONFIG,
13
+ Dispatcher,
14
+ ackContent,
15
+ buildCommentArgs,
16
+ buildFailureCommentArgs,
17
+ buildWatchArgs,
18
+ hasMention,
19
+ itemKeyOf,
20
+ normalizeState,
21
+ emptyState,
22
+ interpretWorkerOutput,
23
+ interruptedMessage,
24
+ loadState,
25
+ runProcess,
26
+ saveStateAtomic,
27
+ watchStderrLine,
28
+ } from '../dispatcher.mjs';
29
+
30
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
31
+ const TMP_ROOT = fs.mkdtempSync(path.join(tmpdir(), 'odyssey-dispatcher-tests-'));
32
+ after(() => fs.rmSync(TMP_ROOT, { recursive: true, force: true }));
33
+
34
+ const mkTmp = () => fs.mkdtempSync(path.join(TMP_ROOT, 't-'));
35
+
36
+ // ── 이벤트 만들기 ──
37
+ const ready = (uid = 'ME') => ({ type: 'ready', uid, streams: ['todos', 'comments'], since: null });
38
+ const todo = (change, uid, { title = `할일 ${uid}`, status = 'notStarted', initial = false } = {}) => ({
39
+ type: 'todo', change, initial, uid, title, status, tags: ['클로드 코드'], updatedAt: '2026-10-18T03:00:00.000Z',
40
+ });
41
+ const comment = (
42
+ commentUid,
43
+ itemUid,
44
+ { author = 'me', text = '본문', createdAt = '2026-10-18T03:10:00.000Z', itemType = 'todo', parentItemUid = null, replyToCommentUid = null } = {},
45
+ ) => ({
46
+ type: 'comment', author, commentUid, itemType, itemUid, itemOwnerUid: 'ME', parentItemUid, replyToCommentUid, roomUid: 'room', text, kind: 'text', createdAt,
47
+ });
48
+
49
+ function deferred() {
50
+ let resolve;
51
+ const promise = new Promise((r) => (resolve = r));
52
+ return { promise, resolve };
53
+ }
54
+
55
+ /** 가짜 일꾼·가짜 댓글로 디스패처를 만든다. */
56
+ function harness({ state, cfg: cfgOver = {}, clock } = {}) {
57
+ const dir = mkTmp();
58
+ const statePath = path.join(dir, 'state.json');
59
+ if (state) saveStateAtomic(statePath, state);
60
+ const cfg = { ...DEFAULT_CONFIG, workDir: dir, statePath, logPath: path.join(dir, 'd.log'), ...cfgOver };
61
+ const h = { dir, statePath, cfg, calls: [], comments: [], logs: [], results: [], gate: null, clock: clock ?? new Date('2026-10-18T03:00:00.000Z') };
62
+ let n = 0;
63
+ h.make = (st) =>
64
+ new Dispatcher({
65
+ config: cfg,
66
+ state: st,
67
+ statePath,
68
+ deps: {
69
+ log: { info: (m) => h.logs.push(m), warn: (m) => h.logs.push(m), error: (m) => h.logs.push(m) },
70
+ randomUUID: () => `sess-${++n}`,
71
+ now: () => h.clock,
72
+ runWorker: async (job) => {
73
+ // 일꾼이 뜨는 순간 디스크의 상태를 찍어 둔다(세션 id 를 먼저 적었는지 확인용)
74
+ const onDisk = JSON.parse(fs.readFileSync(statePath, 'utf8'));
75
+ h.calls.push({ ...job, onDisk });
76
+ if (h.gate) await h.gate.promise;
77
+ const r = h.results.shift() ?? { ok: true, reason: null, costUsd: 0.2, subtype: 'success', denials: [] };
78
+ return typeof r === 'function' ? r(job) : r;
79
+ },
80
+ postComment: async (c) => {
81
+ h.comments.push(c);
82
+ },
83
+ },
84
+ });
85
+ h.d = h.make(state ?? loadState(statePath));
86
+ h.send = async (...evts) => {
87
+ for (const e of evts) h.d.handleEvent(e);
88
+ await h.d.whenIdle();
89
+ };
90
+ return h;
91
+ }
92
+
93
+ // ───────────────────────── 2절 배달 표 ─────────────────────────
94
+
95
+ test('todo added · notStarted · 상태에 없음 → 새 세션 "새 일" (인자·일꾼 규칙까지)', async () => {
96
+ const h = harness();
97
+ await h.send(ready(), todo('added', 'T1', { title: 'README 한 줄' }));
98
+ assert.equal(h.calls.length, 1);
99
+ const c = h.calls[0];
100
+ assert.equal(c.resume, false);
101
+ assert.equal(c.message, '새 일: Odyssey 할일 T1 「README 한 줄」. 할일과 댓글 스레드를 읽고 시작해.');
102
+ assert.deepEqual(c.args.slice(0, 5), ['-p', '--output-format', 'json', '--session-id', 'sess-1']);
103
+ const at = (flag) => c.args[c.args.indexOf(flag) + 1];
104
+ assert.equal(at('--permission-mode'), 'acceptEdits');
105
+ assert.equal(at('--allowedTools'), 'mcp__odyssey');
106
+ const di = c.args.indexOf('--disallowedTools');
107
+ assert.deepEqual(c.args.slice(di + 1, di + 4), ['Bash(git push:*)', 'Bash(firebase deploy:*)', 'Bash(npm publish:*)']);
108
+ assert.equal(c.args[di + 4], '--max-budget-usd');
109
+ assert.equal(c.args[di + 5], '1');
110
+ assert.equal(c.args.at(-1), c.message, '배달 메시지는 마지막 위치 인자');
111
+ assert.equal(at('--append-system-prompt'), c.systemPrompt);
112
+ assert.match(c.systemPrompt, /「README 한 줄」\(T1\)/);
113
+ assert.match(c.systemPrompt, /내 uid\(ME\)/);
114
+ assert.match(c.systemPrompt, /mcp__odyssey__\*/);
115
+ assert.match(c.systemPrompt, /authorName "Claude", authorEmoji "✨"/);
116
+ assert.match(c.systemPrompt, /하지 않는 것: git push, firebase deploy, npm publish\./);
117
+ const st = loadState(h.statePath);
118
+ assert.equal(st.items.T1.phase, 'idle');
119
+ assert.equal(st.items.T1.costUsd, 0.2);
120
+ assert.equal(st.spend.usd, 0.2);
121
+ assert.deepEqual(st.tagged, ['T1']);
122
+ });
123
+
124
+ test('todo added(initial) · 세션 있음 · phase running → 같은 세션 이어 받기 "끊긴 일"', async () => {
125
+ const state = emptyState();
126
+ state.tagged = ['T1'];
127
+ state.items.T1 = { sessionId: 'old-sess', title: '끊긴 할일', phase: 'running', delivered: [], costUsd: 0.3, startedAt: 'x', updatedAt: 'x' };
128
+ const h = harness({ state });
129
+ await h.send(todo('added', 'T1', { status: 'inProgress', initial: true }), ready());
130
+ assert.equal(h.calls.length, 1);
131
+ assert.equal(h.calls[0].resume, true);
132
+ assert.deepEqual(h.calls[0].args.slice(3, 5), ['--resume', 'old-sess']);
133
+ assert.equal(h.calls[0].message, interruptedMessage('T1'));
134
+ assert.equal(loadState(h.statePath).items.T1.phase, 'idle');
135
+ });
136
+
137
+ test('todo added(initial) · phase running 인데 이미 done → 배달 안 함 · phase done', async () => {
138
+ const state = emptyState();
139
+ state.items.T1 = { sessionId: 's', title: 't', phase: 'running', delivered: [], costUsd: 0, startedAt: '', updatedAt: '' };
140
+ const h = harness({ state });
141
+ await h.send(todo('added', 'T1', { status: 'done', initial: true }), ready());
142
+ assert.equal(h.calls.length, 0);
143
+ assert.equal(loadState(h.statePath).items.T1.phase, 'done');
144
+ });
145
+
146
+ test('todo added(initial) · inProgress · 상태에 없음 → 배달 안 함(로그만)', async () => {
147
+ const h = harness();
148
+ await h.send(todo('added', 'T1', { status: 'inProgress', initial: true }), ready());
149
+ assert.equal(h.calls.length, 0);
150
+ assert.ok(h.logs.some((l) => l.includes('다른 곳에서 진행 중')));
151
+ });
152
+
153
+ test('todo added · 이미 시작한 할일(재시작 후) → 다시 배달하지 않음', async () => {
154
+ const h = harness();
155
+ await h.send(ready(), todo('added', 'T1'));
156
+ assert.equal(h.calls.length, 1);
157
+ // 재시작: 디스크 상태로 새 디스패처
158
+ h.d = h.make(loadState(h.statePath));
159
+ await h.send(todo('added', 'T1', { status: 'notStarted', initial: true }), ready());
160
+ assert.equal(h.calls.length, 1);
161
+ });
162
+
163
+ test('todo modified → 배달하지 않음(메아리), done 이면 phase done 으로만', async () => {
164
+ const h = harness();
165
+ await h.send(ready(), todo('added', 'T1'));
166
+ await h.send(todo('modified', 'T1', { status: 'inProgress' }));
167
+ assert.equal(h.calls.length, 1);
168
+ assert.equal(loadState(h.statePath).items.T1.phase, 'idle');
169
+ await h.send(todo('modified', 'T1', { status: 'done' }));
170
+ assert.equal(h.calls.length, 1);
171
+ assert.equal(loadState(h.statePath).items.T1.phase, 'done');
172
+ });
173
+
174
+ test('todo removed → 대기 큐 비움 · phase cancelled · 이후 댓글 무시', async () => {
175
+ const h = harness();
176
+ h.gate = deferred();
177
+ h.d.handleEvent(ready());
178
+ h.d.handleEvent(todo('added', 'T1')); // 도는 중(게이트에 걸림)
179
+ h.d.handleEvent(todo('added', 'T2')); // 큐에서 대기
180
+ await new Promise((r) => setImmediate(r));
181
+ h.d.handleEvent(todo('removed', 'T2')); // 대기 중에 태그 뗌 → 큐에서 빠짐
182
+ h.d.handleEvent(todo('removed', 'T1')); // 도는 중에 태그 뗌 → 끝나도 cancelled 유지
183
+ h.gate.resolve();
184
+ await h.d.whenIdle();
185
+ assert.deepEqual(h.calls.map((c) => c.todoUid), ['T1']);
186
+ const st = loadState(h.statePath);
187
+ assert.equal(st.items.T1.phase, 'cancelled');
188
+ assert.equal(st.items.T2, undefined);
189
+ assert.deepEqual(st.tagged, []);
190
+ await h.send(comment('C1', 'T1'));
191
+ assert.equal(h.calls.length, 1, '감시 해제된 할일의 댓글은 깨우지 않는다');
192
+ });
193
+
194
+ test('comment(me) · 세션 있음 → 그 세션 이어 받기 "새 댓글"', async () => {
195
+ const h = harness();
196
+ await h.send(ready(), todo('added', 'T1'));
197
+ await h.send(comment('C1', 'T1', { text: '이것도 해 줘', createdAt: '2026-10-18T03:10:00.000Z' }));
198
+ assert.equal(h.calls.length, 2);
199
+ const c = h.calls[1];
200
+ assert.equal(c.resume, true);
201
+ assert.deepEqual(c.args.slice(3, 5), ['--resume', 'sess-1']);
202
+ assert.equal(c.message, '할일 T1 에 내 새 댓글(C1 · 2026-10-18T03:10:00.000Z): 이것도 해 줘');
203
+ const st = loadState(h.statePath);
204
+ assert.deepEqual(st.items.T1.delivered, ['C1']);
205
+ assert.equal(st.cursor, '2026-10-18T03:10:00.000Z');
206
+ });
207
+
208
+ test('comment(me) · 감시 태그 할일인데 세션 없음 → 새 세션 "새 일" + 이 댓글', async () => {
209
+ const h = harness();
210
+ await h.send(todo('added', 'T1', { title: '진행 중이던 일', status: 'inProgress', initial: true }), ready());
211
+ assert.equal(h.calls.length, 0);
212
+ await h.send(comment('C1', 'T1', { text: '이거 맡아 줘' }));
213
+ assert.equal(h.calls.length, 1);
214
+ assert.equal(h.calls[0].resume, false);
215
+ assert.equal(
216
+ h.calls[0].message,
217
+ '새 일: Odyssey 할일 T1 「진행 중이던 일」. 할일과 댓글 스레드를 읽고 시작해.\n' +
218
+ '할일 T1 에 내 새 댓글(C1 · 2026-10-18T03:10:00.000Z): 이거 맡아 줘',
219
+ );
220
+ });
221
+
222
+ test('comment(me) · 그 밖의 항목(메모·감시 밖 할일) → 무시', async () => {
223
+ const h = harness();
224
+ await h.send(ready(), comment('C1', 'M1', { itemType: 'memo' }), comment('C2', 'T9'));
225
+ assert.equal(h.calls.length, 0);
226
+ });
227
+
228
+ test('comment(agent) → 절대 반응하지 않음', async () => {
229
+ const h = harness();
230
+ await h.send(ready(), todo('added', 'T1'));
231
+ await h.send(comment('C1', 'T1', { author: 'agent', text: '끝냈어요' }));
232
+ assert.equal(h.calls.length, 1);
233
+ });
234
+
235
+ test('ready 전에 온 댓글은 태그 집합이 다 찬 뒤(ready)에 판단한다', async () => {
236
+ const state = emptyState();
237
+ state.tagged = ['T1'];
238
+ state.items.T1 = { sessionId: 's1', title: 't', phase: 'idle', delivered: [], costUsd: 0, startedAt: '', updatedAt: '' };
239
+ const h = harness({ state });
240
+ // --since 로 밀린 댓글이 첫 스냅샷에 섞여 온다
241
+ await h.send(comment('C1', 'T1'), todo('added', 'T1', { status: 'inProgress', initial: true }));
242
+ assert.equal(h.calls.length, 0);
243
+ await h.send(ready());
244
+ assert.equal(h.calls.length, 1);
245
+ assert.equal(h.calls[0].resume, true);
246
+ });
247
+
248
+ test('첫 스냅샷에 없는 감시 할일 = 꺼져 있는 동안 태그 뗌 → cancelled', async () => {
249
+ const state = emptyState();
250
+ state.tagged = ['T1'];
251
+ state.items.T1 = { sessionId: 's1', title: 't', phase: 'idle', delivered: [], costUsd: 0, startedAt: '', updatedAt: '' };
252
+ const h = harness({ state });
253
+ await h.send(ready());
254
+ const st = loadState(h.statePath);
255
+ assert.equal(st.items.T1.phase, 'cancelled');
256
+ assert.deepEqual(st.tagged, []);
257
+ });
258
+
259
+ test('todos 스트림이 없는 ready 면 감시 해제 판단을 미룬다', async () => {
260
+ const state = emptyState();
261
+ state.tagged = ['T1'];
262
+ const h = harness({ state });
263
+ await h.send({ type: 'ready', uid: 'ME', streams: ['comments'], since: null });
264
+ assert.deepEqual(loadState(h.statePath).tagged, ['T1']);
265
+ });
266
+
267
+ test('커서가 비어 있으면 ready.since(감시 시작 시각)로 채운다 — 이미 있으면 그대로', async () => {
268
+ const h = harness();
269
+ await h.send({ type: 'ready', uid: 'ME', streams: ['todos', 'comments'], since: '2026-10-18T02:59:00.000Z' });
270
+ assert.equal(loadState(h.statePath).cursor, '2026-10-18T02:59:00.000Z');
271
+ await h.send({ type: 'ready', uid: 'ME', streams: ['todos', 'comments'], since: '2026-10-18T05:00:00.000Z' });
272
+ assert.equal(loadState(h.statePath).cursor, '2026-10-18T02:59:00.000Z');
273
+ });
274
+
275
+ // ───────────────────────── 중복 · 모아 보내기 · 세션 id ─────────────────────────
276
+
277
+ test('같은 댓글은 두 번 배달하지 않는다 — 재시작해도', async () => {
278
+ const h = harness();
279
+ await h.send(ready(), todo('added', 'T1'));
280
+ await h.send(comment('C1', 'T1'), comment('C1', 'T1'));
281
+ assert.equal(h.calls.length, 2);
282
+ h.d = h.make(loadState(h.statePath)); // 재시작 — --since 커서로 같은 댓글이 다시 온다
283
+ await h.send(todo('added', 'T1', { status: 'inProgress', initial: true }), comment('C1', 'T1'), ready());
284
+ assert.equal(h.calls.length, 2);
285
+ });
286
+
287
+ test('도는 중에 온 그 할일의 댓글은 모았다가 끝나면 한 번에(시각 순) 이어 받기', async () => {
288
+ const h = harness();
289
+ h.gate = deferred();
290
+ h.d.handleEvent(ready());
291
+ h.d.handleEvent(todo('added', 'T1'));
292
+ await new Promise((r) => setImmediate(r));
293
+ assert.equal(h.calls.length, 1);
294
+ h.d.handleEvent(comment('C2', 'T1', { text: '둘째', createdAt: '2026-10-18T03:12:00.000Z' }));
295
+ h.d.handleEvent(comment('C1', 'T1', { text: '첫째', createdAt: '2026-10-18T03:11:00.000Z' }));
296
+ h.gate.resolve();
297
+ await h.d.whenIdle();
298
+ assert.equal(h.calls.length, 2);
299
+ assert.equal(h.calls[1].resume, true);
300
+ assert.equal(
301
+ h.calls[1].message,
302
+ '할일 T1 에 내 새 댓글(C1 · 2026-10-18T03:11:00.000Z): 첫째\n할일 T1 에 내 새 댓글(C2 · 2026-10-18T03:12:00.000Z): 둘째',
303
+ );
304
+ assert.deepEqual(loadState(h.statePath).items.T1.delivered, ['C1', 'C2']);
305
+ });
306
+
307
+ test('작업 폴더당 한 번에 하나 — 다른 할일은 FIFO 로 기다린다', async () => {
308
+ const h = harness();
309
+ h.gate = deferred();
310
+ h.d.handleEvent(ready());
311
+ h.d.handleEvent(todo('added', 'T1'));
312
+ h.d.handleEvent(todo('added', 'T2'));
313
+ await new Promise((r) => setImmediate(r));
314
+ assert.deepEqual(h.calls.map((c) => c.todoUid), ['T1']);
315
+ h.gate.resolve();
316
+ await h.d.whenIdle();
317
+ assert.deepEqual(h.calls.map((c) => c.todoUid), ['T1', 'T2']);
318
+ });
319
+
320
+ test('세션 id 를 먼저 적는다 — 일꾼이 뜰 때 디스크에 이미 sessionId · running', async () => {
321
+ const h = harness();
322
+ await h.send(ready(), todo('added', 'T1'));
323
+ const c = h.calls[0];
324
+ assert.equal(c.onDisk.items.T1.sessionId, c.sessionId);
325
+ assert.equal(c.onDisk.items.T1.phase, 'running');
326
+ });
327
+
328
+ test('큐에 남은 댓글보다 커서가 앞서 가지 않는다(재시작해도 다시 받게)', async () => {
329
+ const h = harness();
330
+ await h.send(ready(), todo('added', 'TB')); // TB 는 세션이 있다(idle)
331
+ h.gate = deferred();
332
+ h.d.handleEvent(todo('added', 'T0')); // 도는 중
333
+ await new Promise((r) => setImmediate(r));
334
+ h.d.handleEvent(todo('added', 'TA')); // 큐: [TA]
335
+ h.d.handleEvent(comment('CB', 'TB', { createdAt: '2026-10-18T03:21:00.000Z' })); // 큐: [TA, TB]
336
+ h.d.handleEvent(comment('CA', 'TA', { createdAt: '2026-10-18T03:22:00.000Z' })); // TA 에 합류(TB 보다 앞)
337
+ h.gate.resolve();
338
+ await h.d.whenIdle();
339
+ assert.deepEqual(h.calls.map((c) => c.todoUid), ['TB', 'T0', 'TA', 'TB']);
340
+ // TA(03:22)를 배달하는 순간 TB 의 CB(03:21)는 아직 대기 — 커서는 그 앞에 머문다
341
+ assert.equal(h.calls[2].onDisk.cursor, '2026-10-18T03:20:59.999Z');
342
+ assert.equal(loadState(h.statePath).cursor, '2026-10-18T03:22:00.000Z');
343
+ });
344
+
345
+ // ───────────────────────── 6절 실패 알림 · 8절 예산 ─────────────────────────
346
+
347
+ test('일꾼 실패 → phase blocked + 실패 알림 한 번, 내 댓글이 오면 다시 깨운다', async () => {
348
+ const h = harness();
349
+ h.results.push({ ok: false, reason: '일꾼이 오류로 끝났어요(error_during_execution)', costUsd: 0.1, denials: [] });
350
+ await h.send(ready(), todo('added', 'T1'));
351
+ let st = loadState(h.statePath);
352
+ assert.equal(st.items.T1.phase, 'blocked');
353
+ assert.deepEqual(h.comments, [
354
+ {
355
+ ref: { itemType: 'todo', itemUid: 'T1' },
356
+ todoUid: 'T1',
357
+ content: '일꾼이 멈췄어요: 일꾼이 오류로 끝났어요(error_during_execution). 댓글을 달면 다시 깨웁니다.',
358
+ notifyMe: true,
359
+ kind: 'worker',
360
+ },
361
+ ]);
362
+ await h.send(comment('C1', 'T1', { text: '다시 해 봐' }));
363
+ assert.equal(h.calls.length, 2);
364
+ assert.equal(h.calls[1].resume, true);
365
+ st = loadState(h.statePath);
366
+ assert.equal(st.items.T1.phase, 'idle');
367
+ assert.equal(h.comments.length, 1);
368
+ });
369
+
370
+ test('실패 알림 인자 — notify false · notifyMe true · 작성자', () => {
371
+ const args = buildFailureCommentArgs(DEFAULT_CONFIG, 'T1', '일꾼이 멈췄어요: x. 댓글을 달면 다시 깨웁니다.');
372
+ assert.deepEqual(args.slice(0, 4), ['-p', 'default', 'comment_on_item', '--json']);
373
+ assert.deepEqual(JSON.parse(args[4]), {
374
+ itemType: 'todo',
375
+ itemUid: 'T1',
376
+ content: '일꾼이 멈췄어요: x. 댓글을 달면 다시 깨웁니다.',
377
+ authorName: 'Claude',
378
+ authorEmoji: '✨',
379
+ notify: false,
380
+ notifyMe: true,
381
+ });
382
+ });
383
+
384
+ test('watch 인자 — 프로필 · 태그 · 에이전트 댓글 포함(답글 판정용) · 커서', () => {
385
+ assert.deepEqual(buildWatchArgs(DEFAULT_CONFIG, null), ['-p', 'default', 'watch', '--tag', '클로드 코드', '--include-agent']);
386
+ assert.deepEqual(buildWatchArgs(DEFAULT_CONFIG, '2026-10-18T03:00:00.000Z'), [
387
+ '-p', 'default', 'watch', '--tag', '클로드 코드', '--include-agent', '--since', '2026-10-18T03:00:00.000Z',
388
+ ]);
389
+ });
390
+
391
+ test('watch stderr — 1시간마다 오는 UNAUTHENTICATED 는 토큰 교대(정상), 10분 안에 되풀이되면 경고', () => {
392
+ // 실제 dispatcher.log 의 줄(261019 03:53) — 60~62분 간격으로 찍히고, 그 뒤 댓글이 그대로 배달됐다
393
+ const L = "[2026-10-19T03:53:03.029Z] @firebase/firestore: Firestore (12.19.0): GrpcConnection RPC 'Listen' stream 0x88626ac1 error. Code: 16 Message: 16 UNAUTHENTICATED: Missing or invalid authentication.";
394
+ const t0 = Date.parse('2026-10-19T03:53:03.030Z');
395
+ const first = watchStderrLine(L, t0, null);
396
+ assert.equal(first.level, 'info');
397
+ assert.match(first.msg, /^watch 토큰 교대 — .*\(정상\)\n\[2026-10-19T03:53:03\.029Z\]/);
398
+ assert.equal(first.authAt, t0);
399
+ const hourLater = watchStderrLine(L, t0 + 61 * 60_000, first.authAt);
400
+ assert.equal(hourLater.level, 'info', '한 시간 뒤 한 번 더는 다음 교대');
401
+ const soon = watchStderrLine(L, t0 + 3 * 60_000, first.authAt);
402
+ assert.equal(soon.level, 'warn');
403
+ assert.match(soon.msg, /^watch 인증 오류 반복 — 3분 만에 또 끊김/);
404
+ // 그 밖의 stderr 는 종전 그대로, 교대 시각도 그대로 둔다
405
+ const other = watchStderrLine("GrpcConnection RPC 'Listen' stream 0x1 error. Code: 13 Message: 13 INTERNAL: Received RST_STREAM", t0 + 60_000, t0);
406
+ assert.deepEqual(other, { level: 'info', msg: "[watch stderr] GrpcConnection RPC 'Listen' stream 0x1 error. Code: 13 Message: 13 INTERNAL: Received RST_STREAM", authAt: t0 });
407
+ });
408
+
409
+ test('일꾼 결과 해석 — 성공 · is_error · 예산 초과 · 파싱 실패 · 타임아웃 · 실행 실패', () => {
410
+ const cfg = DEFAULT_CONFIG;
411
+ const ok = interpretWorkerOutput(
412
+ { code: 0, stdout: JSON.stringify({ type: 'result', subtype: 'success', is_error: false, session_id: 's', total_cost_usd: 0.21, result: '답글 달았어', permission_denials: [{ tool_name: 'Bash' }] }) },
413
+ cfg,
414
+ );
415
+ assert.equal(ok.ok, true);
416
+ assert.equal(ok.costUsd, 0.21);
417
+ assert.equal(ok.denials.length, 1);
418
+ const err = interpretWorkerOutput({ code: 1, stdout: JSON.stringify({ subtype: 'success', is_error: true, total_cost_usd: 0.1, result: 'API Error' }) }, cfg);
419
+ assert.equal(err.ok, false);
420
+ assert.equal(err.costUsd, 0.1);
421
+ assert.match(err.reason, /오류로 끝났어요/);
422
+ const budget = interpretWorkerOutput({ code: 1, stdout: JSON.stringify({ subtype: 'error_max_budget_usd', is_error: true, total_cost_usd: 1.02 }) }, cfg);
423
+ assert.equal(budget.ok, false);
424
+ assert.equal(budget.reason, '한 턴 예산($1)을 넘었어요');
425
+ const bad = interpretWorkerOutput({ code: 1, stdout: 'not json' }, cfg);
426
+ assert.equal(bad.reason, '결과를 읽지 못했어요(종료 코드 1)');
427
+ assert.equal(interpretWorkerOutput({ timedOut: true, stdout: '' }, cfg).reason, '30분 안에 끝나지 않아 끊었어요');
428
+ assert.match(interpretWorkerOutput({ spawnError: Object.assign(new Error('x'), { code: 'ENOENT' }) }, cfg).reason, /ENOENT/);
429
+ });
430
+
431
+ test('타임아웃이면 프로세스를 끊는다(runProcess)', async () => {
432
+ const dir = mkTmp();
433
+ const script = path.join(dir, 'sleep.mjs');
434
+ fs.writeFileSync(script, 'setTimeout(() => {}, 60_000);\n');
435
+ const t0 = Date.now();
436
+ const r = await runProcess(process.execPath, [script], { timeoutMs: 200, killGraceMs: 500 });
437
+ assert.equal(r.timedOut, true);
438
+ assert.ok(Date.now() - t0 < 5000);
439
+ });
440
+
441
+ test('하루 예산을 넘으면 큐를 멈추고 알림 한 번, 날짜가 바뀌면 다시 돈다', async () => {
442
+ const h = harness({ cfg: { dailyBudgetUsd: 0.5 } });
443
+ h.results.push({ ok: true, costUsd: 0.3 }, { ok: true, costUsd: 0.3 });
444
+ await h.send(ready(), todo('added', 'T1'), todo('added', 'T2'), todo('added', 'T3'), todo('added', 'T4'));
445
+ assert.deepEqual(h.calls.map((c) => c.todoUid), ['T1', 'T2']);
446
+ assert.equal(h.comments.length, 1);
447
+ assert.equal(h.comments[0].todoUid, 'T3');
448
+ assert.match(h.comments[0].content, /^일꾼이 멈췄어요: 오늘 예산\(\$0\.5\)을 다 써서\(누적 \$0\.60\) 큐를 멈췄어요\. 자정이 지나면 이어서 깨웁니다\.$/);
449
+ await h.send(comment('C9', 'T1')); // 예산이 풀리기 전에는 아무도 안 깨운다 · 알림도 더 없다
450
+ assert.equal(h.calls.length, 2);
451
+ assert.equal(h.comments.length, 1);
452
+ h.clock = new Date('2026-10-19T03:00:00.000Z');
453
+ await h.d.kick();
454
+ await h.d.whenIdle();
455
+ assert.deepEqual(h.calls.map((c) => c.todoUid), ['T1', 'T2', 'T3', 'T4', 'T1']);
456
+ });
457
+
458
+ // ───────────────────────── 통합: 진짜 프로세스 + 가짜 odyssey/claude ─────────────────────────
459
+
460
+ test('통합 — main() 이 watch 를 듣고 claude 를 새로 만들고/이어 받고, 실패면 comment_on_item 을 부른다', async () => {
461
+ const dir = mkTmp();
462
+ const rec = path.join(dir, 'rec');
463
+ const work = path.join(dir, 'work');
464
+ fs.mkdirSync(rec);
465
+ fs.mkdirSync(work);
466
+ const shebang = `#!${process.execPath}\n`;
467
+ const fakeOdyssey = path.join(dir, 'fake-odyssey.mjs');
468
+ fs.writeFileSync(
469
+ fakeOdyssey,
470
+ shebang +
471
+ `import fs from 'node:fs';
472
+ const rec = process.env.FAKE_REC_DIR;
473
+ const args = process.argv.slice(2);
474
+ fs.appendFileSync(rec + '/odyssey-calls.jsonl', JSON.stringify(args) + '\\n');
475
+ if (args.includes('watch')) {
476
+ const evts = JSON.parse(fs.readFileSync(rec + '/watch-events.json', 'utf8'));
477
+ let i = 0;
478
+ const next = () => { if (i < evts.length) { process.stdout.write(JSON.stringify(evts[i++]) + '\\n'); setTimeout(next, 300); } };
479
+ next();
480
+ setInterval(() => {}, 1000);
481
+ } else {
482
+ process.stdout.write('{"ok":true}\\n');
483
+ }
484
+ `,
485
+ );
486
+ const fakeClaude = path.join(dir, 'fake-claude.mjs');
487
+ fs.writeFileSync(
488
+ fakeClaude,
489
+ shebang +
490
+ `import fs from 'node:fs';
491
+ const rec = process.env.FAKE_REC_DIR;
492
+ const args = process.argv.slice(2);
493
+ const file = rec + '/claude-calls.jsonl';
494
+ fs.appendFileSync(file, JSON.stringify({ args, cwd: process.cwd() }) + '\\n');
495
+ const n = fs.readFileSync(file, 'utf8').trim().split('\\n').length;
496
+ const sid = args[args.indexOf('--session-id') + 1] || args[args.indexOf('--resume') + 1];
497
+ process.stderr.write('fake claude stderr line\\n');
498
+ process.stdout.write(JSON.stringify(n === 1
499
+ ? { type: 'result', subtype: 'success', is_error: false, session_id: sid, total_cost_usd: 0.21, result: '답글 달았어', permission_denials: [] }
500
+ : { type: 'result', subtype: 'error_during_execution', is_error: true, session_id: sid, total_cost_usd: 0.05, permission_denials: [] }));
501
+ `,
502
+ );
503
+ fs.chmodSync(fakeOdyssey, 0o755);
504
+ fs.chmodSync(fakeClaude, 0o755);
505
+ fs.writeFileSync(
506
+ path.join(rec, 'watch-events.json'),
507
+ JSON.stringify([
508
+ todo('added', 'T1', { title: '통합 시험', initial: true }),
509
+ ready('ME'),
510
+ comment('C2', 'T1', { author: 'agent', text: '메아리' }),
511
+ comment('C1', 'T1', { text: '하나 더', createdAt: '2026-10-18T03:30:00.000Z' }),
512
+ ]),
513
+ );
514
+ const cfgFile = path.join(dir, 'config.json');
515
+ fs.writeFileSync(
516
+ cfgFile,
517
+ JSON.stringify({ workDir: work, odysseyBin: fakeOdyssey, claudeBin: fakeClaude, statePath: path.join(dir, 'state.json'), logPath: path.join(dir, 'logs', 'd.log') }),
518
+ );
519
+
520
+ const child = spawn(process.execPath, [path.join(HERE, '..', 'dispatcher.mjs'), '--config', cfgFile], {
521
+ env: { ...process.env, FAKE_REC_DIR: rec },
522
+ stdio: ['ignore', 'pipe', 'pipe'],
523
+ });
524
+ let out = '';
525
+ child.stdout.on('data', (d) => (out += d));
526
+ child.stderr.on('data', (d) => (out += d));
527
+ const exited = new Promise((r) => child.on('close', (code) => r(code)));
528
+
529
+ const readLines = (f) => (fs.existsSync(f) ? fs.readFileSync(f, 'utf8').trim().split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []);
530
+ const deadline = Date.now() + 15_000;
531
+ while (Date.now() < deadline) {
532
+ if (readLines(path.join(rec, 'odyssey-calls.jsonl')).some((a) => a.includes('comment_on_item'))) break;
533
+ await new Promise((r) => setTimeout(r, 100));
534
+ }
535
+ child.kill('SIGTERM');
536
+ const code = await exited;
537
+ assert.equal(code, 0, out);
538
+
539
+ const claudeCalls = readLines(path.join(rec, 'claude-calls.jsonl'));
540
+ assert.equal(claudeCalls.length, 2, out);
541
+ const sid = claudeCalls[0].args[claudeCalls[0].args.indexOf('--session-id') + 1];
542
+ assert.match(sid, /^[0-9a-f-]{36}$/);
543
+ assert.equal(claudeCalls[1].args[claudeCalls[1].args.indexOf('--resume') + 1], sid);
544
+ assert.equal(claudeCalls[1].args.at(-1), '할일 T1 에 내 새 댓글(C1 · 2026-10-18T03:30:00.000Z): 하나 더');
545
+ assert.equal(fs.realpathSync(claudeCalls[0].cwd), fs.realpathSync(work));
546
+
547
+ const odysseyCalls = readLines(path.join(rec, 'odyssey-calls.jsonl'));
548
+ assert.deepEqual(odysseyCalls[0], ['-p', 'default', 'watch', '--tag', '클로드 코드', '--include-agent']);
549
+ const cmt = odysseyCalls.find((a) => a.includes('comment_on_item'));
550
+ const params = JSON.parse(cmt[cmt.indexOf('--json') + 1]);
551
+ assert.equal(params.itemUid, 'T1');
552
+ assert.equal(params.notify, false);
553
+ assert.equal(params.notifyMe, true);
554
+ assert.match(params.content, /^일꾼이 멈췄어요: 일꾼이 오류로 끝났어요\(error_during_execution\)\. 댓글을 달면 다시 깨웁니다\.$/);
555
+
556
+ const st = loadState(path.join(dir, 'state.json'));
557
+ assert.equal(st.items.T1.sessionId, sid);
558
+ assert.equal(st.items.T1.phase, 'blocked');
559
+ assert.deepEqual(st.items.T1.delivered, ['C1']);
560
+ assert.equal(st.cursor, '2026-10-18T03:30:00.000Z');
561
+ assert.equal(st.items.T1.costUsd, 0.26);
562
+ assert.ok(!fs.existsSync(path.join(dir, 'state.json.lock')), '끄면 잠금을 푼다');
563
+ assert.match(out, /comment\(agent\) C2 .*무시/);
564
+ });
565
+
566
+
567
+ // ───────────────────────── 멘션 입구 ─────────────────────────
568
+
569
+ const MENTION_TEXT = '@클로드코드 이 메모 세 줄로 줄여 줘';
570
+
571
+ test('멘션 판정 — 공백·대소문자 무시, 없는 말은 아님', () => {
572
+ const m = ['@클로드코드', '@ClaudeCode'];
573
+ assert.ok(hasMention('@클로드코드 해 줘', m));
574
+ assert.ok(hasMention('이거 @클로드 코드 님', m));
575
+ assert.ok(hasMention('@claudecode please', m));
576
+ assert.ok(!hasMention('클로드코드 가 뭐야', m), '@ 없이는 아님');
577
+ assert.ok(!hasMention('@클로드 이거', m));
578
+ assert.ok(!hasMention('', m));
579
+ });
580
+
581
+ test('항목 키 — 할일은 uid 그대로, 카드는 보드까지, 그 밖은 종류:uid', () => {
582
+ assert.equal(itemKeyOf('T1'), 'T1');
583
+ assert.equal(itemKeyOf({ itemType: 'todo', itemUid: 'T1' }), 'T1');
584
+ assert.equal(itemKeyOf({ itemType: 'memo', itemUid: 'M1' }), 'memo:M1');
585
+ assert.equal(itemKeyOf({ itemType: 'projectComponent', itemUid: 'C1', projectId: 'B1' }), 'projectComponent:B1/C1');
586
+ assert.notEqual(
587
+ itemKeyOf({ itemType: 'projectComponent', itemUid: 'C1', projectId: 'B1' }),
588
+ itemKeyOf({ itemType: 'projectComponent', itemUid: 'C1', projectId: 'B2' }),
589
+ '복제 보드의 같은 카드 id 는 다른 세션',
590
+ );
591
+ });
592
+
593
+ test('메모 댓글 멘션 → 새 세션 "멘션" + 그 댓글 · 7-2 일꾼 규칙 · 받았다 표시', async () => {
594
+ const h = harness();
595
+ await h.send(ready(), comment('C1', 'M1', { itemType: 'memo', text: MENTION_TEXT }));
596
+ assert.equal(h.calls.length, 1);
597
+ const c = h.calls[0];
598
+ assert.equal(c.resume, false);
599
+ assert.equal(
600
+ c.message,
601
+ `새 일: Odyssey 메모 M1 의 댓글에서 나를 불렀다. 그 댓글이 지시다 — 스레드와 항목을 읽고 시작해.\n메모 M1 에 내 새 댓글(C1 · 2026-10-18T03:10:00.000Z): ${MENTION_TEXT}`,
602
+ );
603
+ assert.match(c.systemPrompt, /메모 M1 의 댓글 스레드에서 「@클로드코드」으로 불려 온 일꾼/);
604
+ assert.match(c.systemPrompt, /list_item_comments\(itemType "memo", itemUid "M1"\)/);
605
+ assert.match(c.systemPrompt, /get_memo/);
606
+ assert.match(c.systemPrompt, /comment_on_item\(itemType "memo", itemUid "M1", authorName "Claude", authorEmoji "✨", notify false\)/);
607
+ assert.match(c.systemPrompt, /notifyMe true/);
608
+ assert.match(c.systemPrompt, /작업 기록용 Odyssey 할일을 새로 만들지 않는다 — 이 스레드가 기록이다\(내가 댓글로 할일을 만들어 달라고 하면 그건 일이니 만든다\)/);
609
+ assert.doesNotMatch(c.systemPrompt, /update_todo/, '할일이 아니면 상태 규칙은 없다');
610
+ assert.deepEqual(h.comments, [{ ref: { itemType: 'memo', itemUid: 'M1' }, content: '👀 받았어요.', notifyMe: false, kind: 'ack' }]);
611
+ const st = loadState(h.statePath);
612
+ assert.deepEqual(
613
+ { ...st.items['memo:M1'], sessionId: undefined, startedAt: undefined, updatedAt: undefined },
614
+ {
615
+ sessionId: undefined, title: '', itemType: 'memo', itemUid: 'M1', origin: 'mention', phase: 'idle',
616
+ delivered: ['C1'], agentComments: [], costUsd: 0.2, startedAt: undefined, updatedAt: undefined,
617
+ },
618
+ );
619
+ });
620
+
621
+ test('멘션으로 연 항목 — 그 뒤 스레드의 내 댓글은 멘션·답글 없이도 같은 세션(누구에게 한 말인지는 일꾼이 가른다)', async () => {
622
+ const h = harness();
623
+ await h.send(ready(), comment('C1', 'M1', { itemType: 'memo', text: MENTION_TEXT }));
624
+ // 일꾼이 단 답글(에이전트 댓글)이 감시로 돌아온다 → 배달 없이 uid 만 적어 둔다
625
+ await h.send(comment('A1', 'M1', { itemType: 'memo', author: 'agent', text: '종일 이벤트는 09시 기준이에요' }));
626
+ assert.deepEqual(loadState(h.statePath).items['memo:M1'].agentComments, ['A1']);
627
+ assert.equal(h.calls.length, 1, '에이전트 댓글은 깨우지 않는다');
628
+ // 일꾼 답 밑에 멘션 없이 이어 쓴 새 댓글 → 같은 세션 이어 받기(261019 실사례 — 종전엔 무시돼 답이 없었다)
629
+ await h.send(comment('C2', 'M1', { itemType: 'memo', text: '이거 할일로 만들고 메모도 고쳐 줘', createdAt: '2026-10-18T03:20:00.000Z' }));
630
+ assert.equal(h.calls.length, 2);
631
+ assert.equal(h.calls[1].resume, true);
632
+ assert.equal(h.calls[1].sessionId, h.calls[0].sessionId);
633
+ assert.equal(h.calls[1].message, '메모 M1 에 내 새 댓글(C2 · 2026-10-18T03:20:00.000Z): 이거 할일로 만들고 메모도 고쳐 줘');
634
+ assert.match(h.logs.join('\n'), /C2 .*세션 있는 스레드의 내 댓글 — 세션 sess-1 이어 받기/);
635
+ // 일꾼 질문에 단 「답글」 → 같은 세션(답글 대상이 메시지에 실린다)
636
+ await h.send(comment('C4', 'M1', { itemType: 'memo', text: '1번', replyToCommentUid: 'A1', createdAt: '2026-10-18T03:22:00.000Z' }));
637
+ assert.equal(h.calls.length, 3);
638
+ assert.equal(h.calls[2].sessionId, h.calls[0].sessionId);
639
+ assert.equal(h.calls[2].message, '메모 M1 에 내 새 댓글(C4 · 2026-10-18T03:22:00.000Z · 답글 ← A1): 1번');
640
+ assert.match(h.logs.join('\n'), /C4 .*일꾼 댓글\(A1\)에 단 답글/);
641
+ // 다시 멘션 → 같은 세션(받았다 표시 한 번 더)
642
+ await h.send(comment('C5', 'M1', { itemType: 'memo', text: '@클로드 코드 하나 더', createdAt: '2026-10-18T03:30:00.000Z' }));
643
+ assert.equal(h.calls.length, 4);
644
+ assert.equal(h.calls[3].resume, true);
645
+ assert.equal(h.comments.filter((c) => c.kind === 'ack').length, 2, '멘션 없는 댓글엔 받았다 표시를 달지 않는다');
646
+ // 일꾼 규칙 — 멘션 없이도 깨어나니, 너에게 한 말이 아니면 답글 없이 끝낸다
647
+ assert.match(h.calls[0].systemPrompt, /멘션이 없어도 너를 깨운다\. 깨운 댓글이 너에게 한 말이 아니면.*답글 없이 턴을 끝낸다/);
648
+ assert.doesNotMatch(h.calls[0].systemPrompt, /멘션 없는 새 댓글로는 깨어나지 않는다/);
649
+ });
650
+
651
+ test('멘션 세션이 도는 중에 멘션 없이 이어 쓴 댓글 → 모았다가 끝나면 한 번에', async () => {
652
+ const h = harness();
653
+ h.gate = deferred();
654
+ h.d.handleEvent(ready());
655
+ h.d.handleEvent(comment('C1', 'M1', { itemType: 'memo', text: MENTION_TEXT }));
656
+ await new Promise((r) => setImmediate(r));
657
+ h.d.handleEvent(comment('C2', 'M1', { itemType: 'memo', text: '아 그리고 이것도', createdAt: '2026-10-18T03:11:00.000Z' }));
658
+ h.gate.resolve();
659
+ h.gate = null;
660
+ await h.d.whenIdle();
661
+ assert.equal(h.calls.length, 2);
662
+ assert.equal(h.calls[1].resume, true);
663
+ assert.equal(h.calls[1].message, '메모 M1 에 내 새 댓글(C2 · 2026-10-18T03:11:00.000Z): 아 그리고 이것도');
664
+ });
665
+
666
+ test('보드 카드 멘션 — 키와 답글 자리에 보드(projectId)까지 · 보드를 모르는 카드는 무시', async () => {
667
+ const h = harness();
668
+ await h.send(
669
+ ready(),
670
+ comment('C0', 'K1', { itemType: 'projectComponent', text: MENTION_TEXT }),
671
+ comment('C1', 'K1', { itemType: 'projectComponent', parentItemUid: 'B1', text: MENTION_TEXT }),
672
+ );
673
+ assert.equal(h.calls.length, 1, '부모 보드 없는 카드 멘션은 답글 자리가 없어 무시');
674
+ assert.match(h.logs.join('\n'), /C0 .*무시\(멘션이지만 어느 보드의 카드인지 모름/);
675
+ const c = h.calls[0];
676
+ assert.match(c.message, /^새 일: Odyssey 보드 B1 의 카드 K1 의 댓글에서 나를 불렀다/);
677
+ assert.match(c.systemPrompt, /comment_on_item\(itemType "projectComponent", itemUid "K1", projectId "B1",/);
678
+ assert.match(c.systemPrompt, /get_project_components/);
679
+ assert.ok(loadState(h.statePath).items['projectComponent:B1/K1']);
680
+ assert.deepEqual(h.comments[0].ref, { itemType: 'projectComponent', itemUid: 'K1', projectId: 'B1' });
681
+ });
682
+
683
+ test('보드 전체 멘션 — comment_on_project · 나만 알림이 없어 notify false 로만', async () => {
684
+ const h = harness();
685
+ await h.send(ready(), comment('C1', 'B1', { itemType: 'project', text: MENTION_TEXT }));
686
+ assert.match(h.calls[0].systemPrompt, /comment_on_project\(projectId "B1", authorName "Claude", authorEmoji "✨", notify false\)/);
687
+ assert.match(h.calls[0].systemPrompt, /보드 전체 댓글엔 나만 알림이 없다/);
688
+ const ack = buildCommentArgs(DEFAULT_CONFIG, { itemType: 'project', itemUid: 'B1' }, '👀 받았어요.', { notifyMe: true });
689
+ assert.deepEqual(ack.slice(0, 4), ['-p', 'default', 'comment_on_project', '--json']);
690
+ assert.deepEqual(JSON.parse(ack[4]), { projectId: 'B1', content: '👀 받았어요.', authorName: 'Claude', authorEmoji: '✨', notify: false });
691
+ });
692
+
693
+ test('받지 않는 종류(스냅샷 등)의 멘션 · 멘션 없는 남의 항목 댓글 → 무시', async () => {
694
+ const h = harness();
695
+ await h.send(ready(), comment('C1', 'S1', { itemType: 'snapshot', text: MENTION_TEXT }), comment('C2', 'M9', { itemType: 'memo', text: '그냥 메모' }));
696
+ assert.equal(h.calls.length, 0);
697
+ assert.equal(h.comments.length, 0, '받았다 표시도 없다');
698
+ });
699
+
700
+ test('태그 할일에 멘션 → 태그 세션 그대로(받았다 표시 없음) · 태그를 뗀 할일도 멘션이면 다시 연다', async () => {
701
+ const h = harness();
702
+ await h.send(ready(), todo('added', 'T1'));
703
+ await h.send(comment('C1', 'T1', { text: '@클로드코드 이것도' }));
704
+ assert.equal(h.calls.length, 2);
705
+ assert.equal(h.calls[1].resume, true);
706
+ assert.match(h.calls[1].systemPrompt, /맡은 일꾼이다/, '7-1 규칙 그대로');
707
+ assert.equal(h.comments.length, 0);
708
+ await h.send(todo('removed', 'T1'));
709
+ await h.send(comment('C2', 'T1', { text: '고마워', createdAt: '2026-10-18T03:20:00.000Z' }));
710
+ assert.equal(h.calls.length, 2, '감시 해제된 할일의 멘션 없는 댓글은 무시');
711
+ await h.send(comment('C3', 'T1', { text: '@클로드코드 다시 봐 줘', createdAt: '2026-10-18T03:30:00.000Z' }));
712
+ assert.equal(h.calls.length, 3);
713
+ assert.equal(h.calls[2].sessionId, h.calls[0].sessionId);
714
+ });
715
+
716
+ test('받았다 표시 — 앞에 도는 일이 있으면 기다린다는 말 · 설정이 비면 끔', async () => {
717
+ assert.equal(ackContent(DEFAULT_CONFIG, false), '👀 받았어요.');
718
+ assert.equal(ackContent(DEFAULT_CONFIG, true), '👀 받았어요 — 앞의 일을 마치면 이어서 볼게요.');
719
+ const h = harness();
720
+ h.gate = deferred();
721
+ h.d.handleEvent(ready());
722
+ h.d.handleEvent(todo('added', 'T1'));
723
+ h.d.handleEvent(comment('C1', 'M1', { itemType: 'memo', text: MENTION_TEXT }));
724
+ await new Promise((r) => setImmediate(r)); // 받았다 표시는 배달을 막지 않게 비동기로 단다
725
+ assert.equal(h.comments.at(-1).content, '👀 받았어요 — 앞의 일을 마치면 이어서 볼게요.');
726
+ h.gate.resolve();
727
+ await h.d.whenIdle();
728
+ const off = harness({ cfg: { mentionAck: '' } });
729
+ await off.send(ready(), comment('C1', 'M1', { itemType: 'memo', text: MENTION_TEXT }));
730
+ assert.equal(off.calls.length, 1);
731
+ assert.equal(off.comments.length, 0);
732
+ });
733
+
734
+ test('멘션 세션의 실패 알림은 그 항목 스레드에(나만 알림)', async () => {
735
+ const h = harness();
736
+ h.results.push({ ok: false, reason: '일꾼이 오류로 끝났어요(x)', costUsd: 0, denials: [] });
737
+ await h.send(ready(), comment('C1', 'M1', { itemType: 'memo', text: MENTION_TEXT }));
738
+ const fail = h.comments.find((c) => c.kind === 'worker');
739
+ assert.deepEqual(fail.ref, { itemType: 'memo', itemUid: 'M1' });
740
+ assert.equal(fail.notifyMe, true);
741
+ const args = buildFailureCommentArgs(DEFAULT_CONFIG, fail.ref, fail.content);
742
+ assert.deepEqual(JSON.parse(args[4]), {
743
+ itemType: 'memo', itemUid: 'M1', content: fail.content, authorName: 'Claude', authorEmoji: '✨', notify: false, notifyMe: true,
744
+ });
745
+ });
746
+
747
+ test('옛 상태 파일(키=할일 uid · itemType 없음)은 할일 · 태그로 읽는다', () => {
748
+ const st = normalizeState({ items: { T1: { sessionId: 's', title: 'x', phase: 'done', delivered: ['C1'] } } });
749
+ assert.equal(st.items.T1.itemType, 'todo');
750
+ assert.equal(st.items.T1.itemUid, 'T1');
751
+ assert.equal(st.items.T1.origin, 'tag');
752
+ assert.deepEqual(st.items.T1.agentComments, []);
753
+ });
754
+
755
+ test('일꾼 허락·추가 규칙 — 설정이 인자와 규칙 끝에 붙는다', async () => {
756
+ const h = harness({ cfg: { allowedTools: ['Bash(git status:*)', 'Bash(flutter analyze:*)'], extraRules: ['코드를 고치면 내 경로만 커밋한다.'] } });
757
+ await h.send(ready(), todo('added', 'T1'));
758
+ const a = h.calls[0].args;
759
+ const i = a.indexOf('--allowedTools');
760
+ assert.deepEqual(a.slice(i + 1, i + 4), ['mcp__odyssey', 'Bash(git status:*)', 'Bash(flutter analyze:*)']);
761
+ assert.equal(a[i + 4], '--disallowedTools');
762
+ assert.match(h.calls[0].systemPrompt, /\n추가 규칙\(이 작업 폴더\):\n- 코드를 고치면 내 경로만 커밋한다\.$/);
763
+ });