triflux 3.2.0-dev.9 → 3.3.0-dev.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,11 +3,42 @@
3
3
  //
4
4
  // Claude Code 네이티브 Agent Teams (CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1)
5
5
  // 환경에서 teammate를 Codex/Gemini CLI 래퍼로 구성하는 유틸리티.
6
- // SKILL.md가 인라인 프롬프트를 사용하므로, 이 모듈은 CLI(tfx team --native)에서
6
+ // SKILL.md가 인라인 프롬프트를 사용하므로, 이 모듈은 CLI(tfx multi --native)에서
7
7
  // 팀 설정을 프로그래밍적으로 생성할 때 사용한다.
8
8
 
9
9
  const ROUTE_SCRIPT = "~/.claude/scripts/tfx-route.sh";
10
10
 
11
+ function inferWorkerIndex(agentName = "") {
12
+ const match = /(\d+)(?!.*\d)/.exec(agentName);
13
+ if (!match) return null;
14
+ const index = Number(match[1]);
15
+ return Number.isInteger(index) && index > 0 ? index : null;
16
+ }
17
+
18
+ function buildRouteEnvPrefix(agentName, workerIndex, searchTool) {
19
+ const effectiveWorkerIndex = Number.isInteger(workerIndex) && workerIndex > 0
20
+ ? workerIndex
21
+ : inferWorkerIndex(agentName);
22
+
23
+ let envPrefix = "";
24
+ if (effectiveWorkerIndex) envPrefix += ` TFX_WORKER_INDEX="${effectiveWorkerIndex}"`;
25
+ if (searchTool) envPrefix += ` TFX_SEARCH_TOOL="${searchTool}"`;
26
+ return envPrefix;
27
+ }
28
+
29
+ /**
30
+ * role/mcp_profile별 tfx-route.sh 기본 timeout (초)
31
+ * analyze/review 프로필이나 설계·분석 역할은 더 긴 timeout을 부여한다.
32
+ * @param {string} role — 워커 역할
33
+ * @param {string} mcpProfile — MCP 프로필
34
+ * @returns {number} timeout(초)
35
+ */
36
+ function getRouteTimeout(role, mcpProfile) {
37
+ if (mcpProfile === "analyze" || mcpProfile === "review") return 3600;
38
+ if (role === "architect" || role === "analyst") return 3600;
39
+ return 1080; // 기본 18분
40
+ }
41
+
11
42
  /**
12
43
  * v2.2 슬림 래퍼 프롬프트 생성
13
44
  * Agent spawn으로 네비게이션에 등록하되, 실제 작업은 tfx-route.sh가 수행.
@@ -22,35 +53,142 @@ const ROUTE_SCRIPT = "~/.claude/scripts/tfx-route.sh";
22
53
  * @param {string} [opts.agentName] — 워커 표시 이름
23
54
  * @param {string} [opts.leadName] — 리드 수신자 이름
24
55
  * @param {string} [opts.mcp_profile] — MCP 프로필
56
+ * @param {number} [opts.workerIndex] — 검색 힌트 회전에 사용할 워커 인덱스(1-based)
57
+ * @param {string} [opts.searchTool] — 전용 검색 도구 힌트(brave-search|tavily|exa)
58
+ * @param {number} [opts.bashTimeout] — Bash timeout(ms). 미지정 시 role/profile 기반 자동 산출.
25
59
  * @returns {string} 슬림 래퍼 프롬프트
26
60
  */
27
61
  export function buildSlimWrapperPrompt(cli, opts = {}) {
28
62
  const {
29
63
  subtask,
30
64
  role = "executor",
31
- teamName = "tfx-team",
65
+ teamName = "tfx-multi",
32
66
  taskId = "",
33
67
  agentName = "",
34
68
  leadName = "team-lead",
35
69
  mcp_profile = "auto",
70
+ workerIndex,
71
+ searchTool = "",
72
+ pipelinePhase = "",
73
+ bashTimeout,
36
74
  } = opts;
37
75
 
76
+ // role/profile 기반 timeout 산출 (기본 timeout + 60초 여유, ms 변환)
77
+ const bashTimeoutMs = bashTimeout ?? (getRouteTimeout(role, mcp_profile) + 60) * 1000;
78
+
38
79
  // 셸 이스케이프
39
80
  const escaped = subtask.replace(/'/g, "'\\''");
81
+ const pipelineHint = pipelinePhase
82
+ ? `\n파이프라인 단계: ${pipelinePhase}`
83
+ : '';
84
+ const routeEnvPrefix = buildRouteEnvPrefix(agentName, workerIndex, searchTool);
85
+
86
+ const taskIdRef = taskId ? `taskId: "${taskId}"` : "";
87
+
88
+ return `인터럽트 프로토콜:
89
+ 1. TaskUpdate(${taskIdRef ? `${taskIdRef}, ` : ""}status: in_progress) — task claim
90
+ 2. SendMessage(to: ${leadName}, "작업 시작: ${agentName}") — 시작 보고 (턴 경계 생성)
91
+ 3. Bash(command, timeout: ${bashTimeoutMs}) — 아래 명령 1회 실행
92
+ 4. 결과 보고 후 반드시 종료${pipelineHint}
93
+
94
+ [HARD CONSTRAINT] 너는 Bash, TaskUpdate, TaskGet, TaskList, SendMessage만 사용할 수 있다.
95
+ Read, Edit, Write, Grep, Glob, Agent, WebSearch, WebFetch 등 다른 모든 도구 사용을 금지한다.
96
+ 코드를 직접 읽거나 수정하면 안 된다. 반드시 아래 Bash 명령(tfx-route.sh)을 통해 Codex/Gemini에 위임하라.
97
+ 이 규칙을 위반하면 작업 실패로 간주한다.
40
98
 
41
- return `Bash 1회 실행 후 반드시 종료하라. 어떤 경우에도 hang하지 마라.
42
99
  gemini/codex를 직접 호출하지 마라. 반드시 tfx-route.sh를 거쳐야 한다.
43
100
  프롬프트를 파일로 저장하지 마라. tfx-route.sh가 인자로 받는다.
44
101
 
45
- TFX_TEAM_NAME="${teamName}" TFX_TEAM_TASK_ID="${taskId}" TFX_TEAM_AGENT_NAME="${agentName}" TFX_TEAM_LEAD_NAME="${leadName}" bash ${ROUTE_SCRIPT} "${role}" '${escaped}' ${mcp_profile}
102
+ Bash(command: 'TFX_TEAM_NAME="${teamName}" TFX_TEAM_TASK_ID="${taskId}" TFX_TEAM_AGENT_NAME="${agentName}" TFX_TEAM_LEAD_NAME="${leadName}"${routeEnvPrefix} bash ${ROUTE_SCRIPT} "${role}" '"'"'${escaped}'"'"' ${mcp_profile}', timeout: ${bashTimeoutMs})
46
103
 
47
- 성공 → TaskUpdate(status: completed, metadata: {result: "success"}) + SendMessage(to: ${leadName}).
48
- 실패 → TaskUpdate(status: completed, metadata: {result: "failed", error: "에러 요약"}) + SendMessage(to: ${leadName}).
104
+ 성공 → TaskUpdate(${taskIdRef ? `${taskIdRef}, ` : ""}status: completed, metadata: {result: "success"}) + SendMessage(to: ${leadName}).
105
+ 실패 → TaskUpdate(${taskIdRef ? `${taskIdRef}, ` : ""}status: completed, metadata: {result: "failed", error: "에러 요약"}) + SendMessage(to: ${leadName}).
49
106
 
50
107
  중요: TaskUpdate의 status는 "completed"만 사용. "failed"는 API 미지원.
51
108
  실패 여부는 metadata.result로 구분. Bash 실패 시에도 반드시 TaskUpdate + SendMessage 후 종료.`;
52
109
  }
53
110
 
111
+ /**
112
+ * v3 하이브리드 래퍼 프롬프트 생성
113
+ * psmux pane 기반 비동기 실행 + polling 패턴.
114
+ * Agent가 idle 상태를 유지하여 인터럽트 수신이 가능하다.
115
+ *
116
+ * @param {'codex'|'gemini'} cli — CLI 타입
117
+ * @param {object} opts
118
+ * @param {string} opts.subtask — 서브태스크 설명
119
+ * @param {string} [opts.role] — 역할
120
+ * @param {string} [opts.teamName] — 팀 이름
121
+ * @param {string} [opts.taskId] — Hub task ID
122
+ * @param {string} [opts.agentName] — 워커 표시 이름
123
+ * @param {string} [opts.leadName] — 리드 수신자 이름
124
+ * @param {string} [opts.mcp_profile] — MCP 프로필
125
+ * @param {number} [opts.workerIndex] — 검색 힌트 회전에 사용할 워커 인덱스(1-based)
126
+ * @param {string} [opts.searchTool] — 전용 검색 도구 힌트(brave-search|tavily|exa)
127
+ * @param {string} [opts.sessionName] — psmux 세션 이름
128
+ * @param {string} [opts.pipelinePhase] — 파이프라인 단계
129
+ * @param {string} [opts.psmuxPath] — psmux.mjs 경로
130
+ * @returns {string} 하이브리드 래퍼 프롬프트
131
+ */
132
+ export function buildHybridWrapperPrompt(cli, opts = {}) {
133
+ const {
134
+ subtask,
135
+ role = "executor",
136
+ teamName = "tfx-multi",
137
+ taskId = "",
138
+ agentName = "",
139
+ leadName = "team-lead",
140
+ mcp_profile = "auto",
141
+ workerIndex,
142
+ searchTool = "",
143
+ sessionName = teamName,
144
+ pipelinePhase = "",
145
+ psmuxPath = "hub/team/psmux.mjs",
146
+ } = opts;
147
+
148
+ const escaped = subtask.replace(/'/g, "'\\''");
149
+ const pipelineHint = pipelinePhase ? `\n파이프라인 단계: ${pipelinePhase}` : "";
150
+ const taskIdRef = taskId ? `taskId: "${taskId}"` : "";
151
+ const taskIdArg = taskIdRef ? `${taskIdRef}, ` : "";
152
+ const routeEnvPrefix = buildRouteEnvPrefix(agentName, workerIndex, searchTool);
153
+
154
+ const routeCmd = `TFX_TEAM_NAME="${teamName}" TFX_TEAM_TASK_ID="${taskId}" TFX_TEAM_AGENT_NAME="${agentName}" TFX_TEAM_LEAD_NAME="${leadName}"${routeEnvPrefix} bash ${ROUTE_SCRIPT} "${role}" '${escaped}' ${mcp_profile}`;
155
+
156
+ return `하이브리드 psmux 워커 프로토콜:
157
+
158
+ 1. TaskUpdate(${taskIdArg}status: in_progress) + SendMessage(to: ${leadName}, "작업 시작: ${agentName}")
159
+
160
+ 2. pane 생성 (비동기 실행):
161
+ Bash: node ${psmuxPath} spawn --session "${sessionName}" --name "${agentName}" --cmd "${routeCmd}"
162
+
163
+ 3. 폴링 루프 (10초 간격, idle 유지 → 인터럽트 수신 가능):
164
+ Bash: node ${psmuxPath} status --session "${sessionName}" --name "${agentName}"
165
+ - status: "running" → 10초 대기 후 재확인
166
+ - status: "exited" → 5단계로
167
+
168
+ 4. 인터럽트 수신 시:
169
+ Bash: node ${psmuxPath} kill --session "${sessionName}" --name "${agentName}"
170
+ → SendMessage(to: ${leadName}, "인터럽트 수신, 방향 전환")
171
+ → 새 지시에 따라 2단계부터 재실행
172
+
173
+ 5. 완료 시:
174
+ Bash: node ${psmuxPath} output --session "${sessionName}" --name "${agentName}" --lines 100
175
+ → 결과를 TaskUpdate + SendMessage로 보고
176
+ ${pipelineHint}
177
+ [HARD CONSTRAINT] 너는 Bash, TaskUpdate, TaskGet, TaskList, SendMessage만 사용할 수 있다.
178
+ Read, Edit, Write, Grep, Glob, Agent, WebSearch, WebFetch 등 다른 모든 도구 사용을 금지한다.
179
+ 코드를 직접 읽거나 수정하면 안 된다. 반드시 아래 Bash 명령(tfx-route.sh)을 통해 Codex/Gemini에 위임하라.
180
+ 이 규칙을 위반하면 작업 실패로 간주한다.
181
+
182
+ gemini/codex를 직접 호출하지 마라. psmux spawn이 tfx-route.sh를 통해 실행한다.
183
+ 프롬프트를 파일로 저장하지 마라. psmux spawn --cmd 인자로 전달된다.
184
+
185
+ 성공 → TaskUpdate(${taskIdArg}status: completed, metadata: {result: "success"}) + SendMessage(to: ${leadName}).
186
+ 실패 → TaskUpdate(${taskIdArg}status: completed, metadata: {result: "failed", error: "에러 요약"}) + SendMessage(to: ${leadName}).
187
+
188
+ 중요: TaskUpdate의 status는 "completed"만 사용. "failed"는 API 미지원.
189
+ 실패 여부는 metadata.result로 구분. pane 실패 시에도 반드시 TaskUpdate + SendMessage 후 종료.`;
190
+ }
191
+
54
192
  /**
55
193
  * 팀 이름 생성 (타임스탬프 기반)
56
194
  * @returns {string}
@@ -4,8 +4,6 @@
4
4
  import {
5
5
  existsSync,
6
6
  mkdirSync,
7
- readdirSync,
8
- readFileSync,
9
7
  renameSync,
10
8
  statSync,
11
9
  unlinkSync,
@@ -13,6 +11,7 @@ import {
13
11
  openSync,
14
12
  closeSync,
15
13
  } from 'node:fs';
14
+ import { readdir, stat, readFile } from 'node:fs/promises';
16
15
  import { basename, dirname, join } from 'node:path';
17
16
  import { homedir } from 'node:os';
18
17
  import { randomUUID } from 'node:crypto';
@@ -25,6 +24,7 @@ const TASKS_ROOT = join(CLAUDE_HOME, 'tasks');
25
24
  // ── 인메모리 캐시 (디렉토리 mtime 기반 무효화) ──
26
25
  const _dirCache = new Map(); // tasksDir → { mtimeMs, files: string[] }
27
26
  const _taskIdIndex = new Map(); // taskId → filePath
27
+ const _taskContentCache = new Map(); // filePath → { mtimeMs, data }
28
28
 
29
29
  function _invalidateCache(tasksDir) {
30
30
  _dirCache.delete(tasksDir);
@@ -40,9 +40,9 @@ function validateTeamName(teamName) {
40
40
  }
41
41
  }
42
42
 
43
- function readJsonSafe(path) {
43
+ async function readJsonSafe(path) {
44
44
  try {
45
- return JSON.parse(readFileSync(path, 'utf8'));
45
+ return JSON.parse(await readFile(path, 'utf8'));
46
46
  } catch {
47
47
  return null;
48
48
  }
@@ -66,12 +66,11 @@ function atomicWriteJson(path, value) {
66
66
  }
67
67
  }
68
68
 
69
- function sleepMs(ms) {
70
- // busy-wait를 피하고 Atomics.wait로 동기 대기 (CPU 점유 최소화)
71
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
69
+ async function sleepMs(ms) {
70
+ return new Promise((r) => setTimeout(r, ms));
72
71
  }
73
72
 
74
- function withFileLock(lockPath, fn, retries = 20, delayMs = 25) {
73
+ async function withFileLock(lockPath, fn, retries = 20, delayMs = 25) {
75
74
  let fd = null;
76
75
  for (let i = 0; i < retries; i += 1) {
77
76
  try {
@@ -79,12 +78,12 @@ function withFileLock(lockPath, fn, retries = 20, delayMs = 25) {
79
78
  break;
80
79
  } catch (e) {
81
80
  if (e?.code !== 'EEXIST' || i === retries - 1) throw e;
82
- sleepMs(delayMs);
81
+ await sleepMs(delayMs);
83
82
  }
84
83
  }
85
84
 
86
85
  try {
87
- return fn();
86
+ return await fn();
88
87
  } finally {
89
88
  try { if (fd != null) closeSync(fd); } catch {}
90
89
  try { unlinkSync(lockPath); } catch {}
@@ -99,13 +98,13 @@ function getLeadSessionId(config) {
99
98
  || null;
100
99
  }
101
100
 
102
- export function resolveTeamPaths(teamName) {
101
+ export async function resolveTeamPaths(teamName) {
103
102
  validateTeamName(teamName);
104
103
 
105
104
  const teamDir = join(TEAMS_ROOT, teamName);
106
105
  const configPath = join(teamDir, 'config.json');
107
106
  const inboxesDir = join(teamDir, 'inboxes');
108
- const config = readJsonSafe(configPath);
107
+ const config = await readJsonSafe(configPath);
109
108
  const leadSessionId = getLeadSessionId(config);
110
109
 
111
110
  const byTeam = join(TASKS_ROOT, teamName);
@@ -131,19 +130,20 @@ export function resolveTeamPaths(teamName) {
131
130
  };
132
131
  }
133
132
 
134
- function collectTaskFiles(tasksDir) {
133
+ async function collectTaskFiles(tasksDir) {
135
134
  if (!existsSync(tasksDir)) return [];
136
135
 
137
136
  // 디렉토리 mtime 기반 캐시 — O(N) I/O를 반복 호출 시 O(1)로 축소
138
137
  let dirMtime;
139
- try { dirMtime = statSync(tasksDir).mtimeMs; } catch { return []; }
138
+ try { dirMtime = (await stat(tasksDir)).mtimeMs; } catch { return []; }
140
139
 
141
140
  const cached = _dirCache.get(tasksDir);
142
141
  if (cached && cached.mtimeMs === dirMtime) {
143
142
  return cached.files;
144
143
  }
145
144
 
146
- const files = readdirSync(tasksDir)
145
+ const entries = await readdir(tasksDir);
146
+ const files = entries
147
147
  .filter((name) => name.endsWith('.json'))
148
148
  .filter((name) => !name.endsWith('.lock'))
149
149
  .filter((name) => name !== '.highwatermark')
@@ -153,7 +153,7 @@ function collectTaskFiles(tasksDir) {
153
153
  return files;
154
154
  }
155
155
 
156
- function locateTaskFile(tasksDir, taskId) {
156
+ async function locateTaskFile(tasksDir, taskId) {
157
157
  const direct = join(tasksDir, `${taskId}.json`);
158
158
  if (existsSync(direct)) return direct;
159
159
 
@@ -162,13 +162,13 @@ function locateTaskFile(tasksDir, taskId) {
162
162
  if (indexed && existsSync(indexed)) return indexed;
163
163
 
164
164
  // 캐시된 collectTaskFiles로 풀 스캔
165
- const files = collectTaskFiles(tasksDir);
165
+ const files = await collectTaskFiles(tasksDir);
166
166
  for (const file of files) {
167
167
  if (basename(file, '.json') === taskId) {
168
168
  _taskIdIndex.set(taskId, file);
169
169
  return file;
170
170
  }
171
- const json = readJsonSafe(file);
171
+ const json = await readJsonSafe(file);
172
172
  if (json && String(json.id || '') === taskId) {
173
173
  _taskIdIndex.set(taskId, file);
174
174
  return file;
@@ -181,7 +181,7 @@ function isObject(v) {
181
181
  return !!v && typeof v === 'object' && !Array.isArray(v);
182
182
  }
183
183
 
184
- export function teamInfo(args = {}) {
184
+ export async function teamInfo(args = {}) {
185
185
  const { team_name, include_members = true, include_paths = true } = args;
186
186
  try {
187
187
  validateTeamName(team_name);
@@ -189,7 +189,7 @@ export function teamInfo(args = {}) {
189
189
  return err('INVALID_TEAM_NAME', 'team_name 형식이 올바르지 않습니다');
190
190
  }
191
191
 
192
- const paths = resolveTeamPaths(team_name);
192
+ const paths = await resolveTeamPaths(team_name);
193
193
  if (!existsSync(paths.team_dir)) {
194
194
  return err('TEAM_NOT_FOUND', `팀 디렉토리가 없습니다: ${paths.team_dir}`);
195
195
  }
@@ -224,7 +224,7 @@ export function teamInfo(args = {}) {
224
224
  };
225
225
  }
226
226
 
227
- export function teamTaskList(args = {}) {
227
+ export async function teamTaskList(args = {}) {
228
228
  const {
229
229
  team_name,
230
230
  owner,
@@ -239,7 +239,7 @@ export function teamTaskList(args = {}) {
239
239
  return err('INVALID_TEAM_NAME', 'team_name 형식이 올바르지 않습니다');
240
240
  }
241
241
 
242
- const paths = resolveTeamPaths(team_name);
242
+ const paths = await resolveTeamPaths(team_name);
243
243
  if (paths.tasks_dir_resolution === 'not_found') {
244
244
  return err('TASKS_DIR_NOT_FOUND', `task 디렉토리를 찾지 못했습니다: ${team_name}`);
245
245
  }
@@ -249,8 +249,22 @@ export function teamTaskList(args = {}) {
249
249
  let parseWarnings = 0;
250
250
 
251
251
  const tasks = [];
252
- for (const file of collectTaskFiles(paths.tasks_dir)) {
253
- const json = readJsonSafe(file);
252
+ for (const file of await collectTaskFiles(paths.tasks_dir)) {
253
+ // mtime 기반 task 콘텐츠 캐시 — 변경 없으면 파일 읽기 생략
254
+ let fileMtime = Date.now();
255
+ try { fileMtime = (await stat(file)).mtimeMs; } catch {}
256
+
257
+ const contentCached = _taskContentCache.get(file);
258
+ let json;
259
+ if (contentCached && contentCached.mtimeMs === fileMtime) {
260
+ json = contentCached.data;
261
+ } else {
262
+ json = await readJsonSafe(file);
263
+ if (json && isObject(json)) {
264
+ _taskContentCache.set(file, { mtimeMs: fileMtime, data: json });
265
+ }
266
+ }
267
+
254
268
  if (!json || !isObject(json)) {
255
269
  parseWarnings += 1;
256
270
  continue;
@@ -260,13 +274,10 @@ export function teamTaskList(args = {}) {
260
274
  if (owner && String(json.owner || '') !== String(owner)) continue;
261
275
  if (statusSet.size > 0 && !statusSet.has(String(json.status || ''))) continue;
262
276
 
263
- let mtime = Date.now();
264
- try { mtime = statSync(file).mtimeMs; } catch {}
265
-
266
277
  tasks.push({
267
278
  ...json,
268
279
  task_file: file,
269
- mtime_ms: mtime,
280
+ mtime_ms: fileMtime,
270
281
  });
271
282
  }
272
283
 
@@ -288,7 +299,7 @@ export function teamTaskList(args = {}) {
288
299
  // status 화이트리스트 (Claude Code API 호환)
289
300
  const VALID_STATUSES = new Set(['pending', 'in_progress', 'completed', 'deleted']);
290
301
 
291
- export function teamTaskUpdate(args = {}) {
302
+ export async function teamTaskUpdate(args = {}) {
292
303
  // "failed" → "completed" + metadata.result 자동 매핑
293
304
  if (String(args.status || '') === 'failed') {
294
305
  args = {
@@ -326,12 +337,12 @@ export function teamTaskUpdate(args = {}) {
326
337
  return err('INVALID_TASK_ID', 'task_id가 필요합니다');
327
338
  }
328
339
 
329
- const paths = resolveTeamPaths(team_name);
340
+ const paths = await resolveTeamPaths(team_name);
330
341
  if (paths.tasks_dir_resolution === 'not_found') {
331
342
  return err('TASKS_DIR_NOT_FOUND', `task 디렉토리를 찾지 못했습니다: ${team_name}`);
332
343
  }
333
344
 
334
- const taskFile = locateTaskFile(paths.tasks_dir, String(task_id));
345
+ const taskFile = await locateTaskFile(paths.tasks_dir, String(task_id));
335
346
  if (!taskFile) {
336
347
  return err('TASK_NOT_FOUND', `task를 찾지 못했습니다: ${task_id}`);
337
348
  }
@@ -339,14 +350,14 @@ export function teamTaskUpdate(args = {}) {
339
350
  const lockFile = `${taskFile}.lock`;
340
351
 
341
352
  try {
342
- return withFileLock(lockFile, () => {
343
- const before = readJsonSafe(taskFile);
353
+ return await withFileLock(lockFile, async () => {
354
+ const before = await readJsonSafe(taskFile);
344
355
  if (!before || !isObject(before)) {
345
356
  return err('INVALID_TASK_FILE', `task 파일 파싱 실패: ${taskFile}`);
346
357
  }
347
358
 
348
359
  let beforeMtime = Date.now();
349
- try { beforeMtime = statSync(taskFile).mtimeMs; } catch {}
360
+ try { beforeMtime = (await stat(taskFile)).mtimeMs; } catch {}
350
361
 
351
362
  if (if_match_mtime_ms != null && Number(if_match_mtime_ms) !== Number(beforeMtime)) {
352
363
  return err('MTIME_CONFLICT', 'if_match_mtime_ms가 일치하지 않습니다', {
@@ -427,6 +438,8 @@ export function teamTaskUpdate(args = {}) {
427
438
  if (updated) {
428
439
  atomicWriteJson(taskFile, after);
429
440
  _invalidateCache(dirname(taskFile));
441
+ // 콘텐츠 캐시 무효화
442
+ _taskContentCache.delete(taskFile);
430
443
  }
431
444
 
432
445
  let afterMtime = beforeMtime;
@@ -453,7 +466,7 @@ function sanitizeRecipientName(v) {
453
466
  return String(v || 'team-lead').replace(/[\\/:*?"<>|]/g, '_');
454
467
  }
455
468
 
456
- export function teamSendMessage(args = {}) {
469
+ export async function teamSendMessage(args = {}) {
457
470
  const {
458
471
  team_name,
459
472
  from,
@@ -472,7 +485,7 @@ export function teamSendMessage(args = {}) {
472
485
  if (!String(from || '').trim()) return err('INVALID_FROM', 'from이 필요합니다');
473
486
  if (!String(text || '').trim()) return err('INVALID_TEXT', 'text가 필요합니다');
474
487
 
475
- const paths = resolveTeamPaths(team_name);
488
+ const paths = await resolveTeamPaths(team_name);
476
489
  if (!existsSync(paths.team_dir)) {
477
490
  return err('TEAM_NOT_FOUND', `팀 디렉토리가 없습니다: ${paths.team_dir}`);
478
491
  }
@@ -483,8 +496,8 @@ export function teamSendMessage(args = {}) {
483
496
  let message;
484
497
 
485
498
  try {
486
- const unreadCount = withFileLock(lockFile, () => {
487
- const queue = readJsonSafe(inboxFile);
499
+ const unreadCount = await withFileLock(lockFile, async () => {
500
+ const queue = await readJsonSafe(inboxFile);
488
501
  const list = Array.isArray(queue) ? queue : [];
489
502
 
490
503
  message = {
@@ -58,6 +58,8 @@ export function buildLeadPrompt(taskDescription, config) {
58
58
 
59
59
  const workerIds = workers.map((w) => w.agentId).join(", ");
60
60
 
61
+ const bridgePath = "node hub/bridge.mjs";
62
+
61
63
  return `리드 에이전트: ${agentId}
62
64
 
63
65
  목표: ${taskDescription}
@@ -68,14 +70,13 @@ ${roster}
68
70
 
69
71
  규칙:
70
72
  - 가능한 짧고 핵심만 지시/요약(토큰 절약)
71
- - 워커 제어 메시지 표준:
72
- publish(from="${agentId}", to="<worker-agent-id>", topic="lead.control", payload={command:"interrupt|stop|pause|resume", reason:"..."})
73
+ - 워커 제어:
74
+ ${bridgePath} result --agent ${agentId} --topic lead.control
73
75
  - 워커 결과 수집:
74
- poll_messages(agent_id="${agentId}", wait_ms=1000, max_messages=20)
76
+ ${bridgePath} context --agent ${agentId} --max 20
75
77
  - 최종 결과는 topic="task.result"를 모아 통합
76
78
 
77
- 권장 워커 ID: ${workerIds || "(없음)"}
78
- Hub: ${hubUrl}
79
+ 워커 ID: ${workerIds || "(없음)"}
79
80
  지금 즉시 워커를 배정하고 병렬 진행을 관리하라.`;
80
81
  }
81
82
 
@@ -93,26 +94,20 @@ export function buildPrompt(subtask, config) {
93
94
 
94
95
  const hubBase = hubUrl.replace("/mcp", "");
95
96
 
97
+ const bridgePath = "node hub/bridge.mjs";
98
+
96
99
  return `워커: ${agentId} (${cli})
97
100
  작업: ${subtask}
98
101
 
99
102
  필수 규칙:
100
103
  1) 간결하게 작업(불필요한 장문 설명 금지)
101
- 2) 시작 즉시 register 실행:
102
- register(agent_id="${agentId}", cli="${cli}", capabilities=["code"], topics=["lead.control","task.result"], heartbeat_ttl_ms=600000)
104
+ 2) 시작 즉시 등록:
105
+ ${bridgePath} register --agent ${agentId} --cli ${cli} --topics lead.control,task.result
103
106
  3) 주기적으로 수신함 확인:
104
- poll_messages(agent_id="${agentId}", wait_ms=1000, max_messages=10)
105
- 4) lead.control 수신 시 즉시 반응
106
- - interrupt: 즉시 중단, 진행상태 요약 publish
107
- - stop: 작업 종료, 최종 요약 publish 후 대기
108
- - pause: 작업 일시정지
109
- - resume: 작업 재개
107
+ ${bridgePath} context --agent ${agentId} --max 10
108
+ 4) lead.control 수신 시 즉시 반응 (interrupt/stop/pause/resume)
110
109
  5) 완료 시 결과 발행:
111
- publish(from="${agentId}", to="topic:task.result", topic="task.result", payload={summary:"..."})
112
-
113
- MCP가 없으면 REST 폴백:
114
- - POST ${hubBase}/bridge/register
115
- - POST ${hubBase}/bridge/result
110
+ ${bridgePath} result --agent ${agentId} --topic task.result --file <출력파일>
116
111
 
117
112
  지금 작업을 시작하라.`;
118
113
  }
@@ -149,7 +144,7 @@ export async function orchestrate(sessionName, assignments, opts = {}) {
149
144
  teammateMode,
150
145
  workers: workers.map((w) => ({ agentId: w.agentId, cli: w.cli, subtask: w.subtask })),
151
146
  });
152
- injectPrompt(lead.target, leadPrompt);
147
+ injectPrompt(lead.target, leadPrompt, { useFileRef: true });
153
148
  await new Promise((r) => setTimeout(r, 100));
154
149
  }
155
150
 
@@ -160,7 +155,7 @@ export async function orchestrate(sessionName, assignments, opts = {}) {
160
155
  hubUrl,
161
156
  sessionName,
162
157
  });
163
- injectPrompt(worker.target, prompt);
158
+ injectPrompt(worker.target, prompt, { useFileRef: true });
164
159
  await new Promise((r) => setTimeout(r, 100));
165
160
  }
166
161
  }