@triflux/remote 10.50.1 → 10.51.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.
Files changed (120) hide show
  1. package/cto/brief.mjs +0 -12
  2. package/cto/collect.mjs +16 -247
  3. package/cto/current.schema.json +4 -20
  4. package/cto/events.mjs +13 -294
  5. package/cto/hygiene.mjs +26 -346
  6. package/cto/lake-root.mjs +114 -16
  7. package/cto/status.mjs +33 -128
  8. package/hub/index.mjs +0 -8
  9. package/hub/store-adapter.mjs +1 -1
  10. package/hub/team/agent-map.json +0 -1
  11. package/hub/team/ansi.mjs +1 -35
  12. package/hub/team/backend.mjs +9 -145
  13. package/hub/team/cli/commands/attach.mjs +1 -17
  14. package/hub/team/cli/commands/control.mjs +12 -38
  15. package/hub/team/cli/commands/debug.mjs +1 -37
  16. package/hub/team/cli/commands/focus.mjs +5 -31
  17. package/hub/team/cli/commands/interrupt.mjs +6 -25
  18. package/hub/team/cli/commands/kill.mjs +1 -30
  19. package/hub/team/cli/commands/list.mjs +0 -16
  20. package/hub/team/cli/commands/send.mjs +6 -26
  21. package/hub/team/cli/commands/start/index.mjs +41 -133
  22. package/hub/team/cli/commands/start/parse-args.mjs +15 -40
  23. package/hub/team/cli/commands/start/start-headless.mjs +138 -105
  24. package/hub/team/cli/commands/start/start-mux.mjs +0 -3
  25. package/hub/team/cli/commands/status.mjs +2 -57
  26. package/hub/team/cli/commands/stop.mjs +14 -19
  27. package/hub/team/cli/help.mjs +4 -5
  28. package/hub/team/cli/manifest.mjs +5 -1
  29. package/hub/team/cli/render.mjs +0 -12
  30. package/hub/team/cli/services/hub-client.mjs +2 -88
  31. package/hub/team/cli/services/runtime-mode.mjs +27 -98
  32. package/hub/team/handoff.mjs +3 -34
  33. package/hub/team/headless.mjs +14 -755
  34. package/hub/team/orchestrator.mjs +4 -30
  35. package/hub/team/pane.mjs +6 -28
  36. package/hub/team/psmux.mjs +16 -403
  37. package/hub/team/remote-session.mjs +1 -2
  38. package/hub/team/session.mjs +8 -119
  39. package/hub/team/swarm-intent.mjs +0 -198
  40. package/hub/team/terminal-opener.mjs +11 -35
  41. package/hub/team/tui-core.mjs +1 -1
  42. package/hub/team/tui-viewer.mjs +2 -2
  43. package/hub/team/tui.mjs +8 -269
  44. package/hub/team/wt-manager.mjs +2 -2
  45. package/hub/workers/factory.mjs +4 -37
  46. package/hub/workers/lib/jsonrpc-ws-uds.mjs +0 -2
  47. package/package.json +1 -1
  48. package/scripts/lib/agent-route-policy.mjs +162 -14
  49. package/scripts/lib/claudemd-scanner.mjs +2 -199
  50. package/scripts/lib/cli-claude.mjs +0 -2
  51. package/scripts/lib/context.mjs +3 -19
  52. package/scripts/lib/env-probe.mjs +5 -64
  53. package/scripts/lib/gemini-profiles.mjs +2 -69
  54. package/scripts/lib/legacy-mcp-cleanup.mjs +14 -3
  55. package/scripts/lib/machine-profile.mjs +3 -17
  56. package/scripts/lib/mcp-filter.mjs +109 -53
  57. package/scripts/lib/mcp-health.mjs +2 -2
  58. package/scripts/lib/mcp-server-catalog.mjs +2 -2
  59. package/scripts/lib/psmux-info.mjs +25 -104
  60. package/scripts/lib/skill-template.mjs +0 -271
  61. package/cto/hygiene-actions.mjs +0 -355
  62. package/cto/hygiene-notify.mjs +0 -170
  63. package/hub/team/build-worker-prompt.mjs +0 -92
  64. package/hub/team/check-mcp-hub.mjs +0 -49
  65. package/hub/team/claude-native-bridge.mjs +0 -987
  66. package/hub/team/cli/commands/start/start-in-process.mjs +0 -50
  67. package/hub/team/cli/commands/start/start-wt.mjs +0 -86
  68. package/hub/team/cli/services/native-control.mjs +0 -145
  69. package/hub/team/codex-review.mjs +0 -520
  70. package/hub/team/conductor-mesh-bridge.mjs +0 -122
  71. package/hub/team/conductor.mjs +0 -1529
  72. package/hub/team/consensus-meta.mjs +0 -176
  73. package/hub/team/cto-pull.mjs +0 -31
  74. package/hub/team/daemon-pty-tmux-bridge.mjs +0 -146
  75. package/hub/team/dashboard.mjs +0 -322
  76. package/hub/team/event-log.mjs +0 -84
  77. package/hub/team/execution-mode.mjs +0 -324
  78. package/hub/team/extract-completion-payload.mjs +0 -110
  79. package/hub/team/headless-bridge-session.mjs +0 -17
  80. package/hub/team/health-probe.mjs +0 -435
  81. package/hub/team/interactive-native-launcher.mjs +0 -119
  82. package/hub/team/interactive-native-worker.mjs +0 -80
  83. package/hub/team/interactive-tui-transport.mjs +0 -479
  84. package/hub/team/launcher-template.mjs +0 -144
  85. package/hub/team/mcp-selector.mjs +0 -145
  86. package/hub/team/native-supervisor.mjs +0 -460
  87. package/hub/team/native.mjs +0 -727
  88. package/hub/team/recovery-store.mjs +0 -149
  89. package/hub/team/remote-probe.mjs +0 -292
  90. package/hub/team/remote-watcher.mjs +0 -506
  91. package/hub/team/runtime-strategy.mjs +0 -200
  92. package/hub/team/schemas/worker-completion.json +0 -39
  93. package/hub/team/sentinel-capture.mjs +0 -127
  94. package/hub/team/swarm-cli.mjs +0 -390
  95. package/hub/team/swarm-hypervisor.mjs +0 -2206
  96. package/hub/team/swarm-locks.mjs +0 -335
  97. package/hub/team/swarm-planner.mjs +0 -371
  98. package/hub/team/swarm-preflight.mjs +0 -366
  99. package/hub/team/swarm-reconciler.mjs +0 -242
  100. package/hub/team/tui-remote-adapter.mjs +0 -377
  101. package/hub/team/worker-completion-validator.mjs +0 -79
  102. package/hub/team/worktree-lifecycle.mjs +0 -639
  103. package/hub/team/wt-templates.json +0 -43
  104. package/hub/workers/antigravity-route-worker.mjs +0 -179
  105. package/hub/workers/gemini-worker.mjs +0 -217
  106. package/scripts/lib/agent-json.mjs +0 -27
  107. package/scripts/lib/async.mjs +0 -174
  108. package/scripts/lib/cli-agy.mjs +0 -85
  109. package/scripts/lib/cli-codex.mjs +0 -62
  110. package/scripts/lib/cli-gemini.mjs +0 -37
  111. package/scripts/lib/dynamic-route-cli.mjs +0 -107
  112. package/scripts/lib/env.mjs +0 -14
  113. package/scripts/lib/hub.mjs +0 -48
  114. package/scripts/lib/pid.mjs +0 -63
  115. package/scripts/lib/quota.mjs +0 -47
  116. package/scripts/lib/skill-state.mjs +0 -220
  117. package/scripts/lib/team.mjs +0 -75
  118. package/scripts/lib/timeout.mjs +0 -66
  119. package/scripts/lib/tmp.mjs +0 -26
  120. package/scripts/lib/toml.mjs +0 -132
@@ -1,355 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import {
3
- copyFileSync,
4
- cpSync,
5
- existsSync,
6
- lstatSync,
7
- mkdirSync,
8
- renameSync,
9
- rmSync,
10
- statSync,
11
- unlinkSync,
12
- } from "node:fs";
13
- import {
14
- basename,
15
- dirname,
16
- isAbsolute,
17
- join,
18
- relative,
19
- resolve,
20
- } from "node:path";
21
-
22
- const ARCHIVABLE_ACTIONS = new Set([
23
- "archive_or_resume_session",
24
- "prune_superseded_checkpoint",
25
- ]);
26
-
27
- function shortHash(value) {
28
- const str = String(value ?? "");
29
- let h = 5381;
30
- for (let i = 0; i < str.length; i += 1) {
31
- h = (h * 33) ^ str.charCodeAt(i);
32
- }
33
- return (h >>> 0).toString(36);
34
- }
35
-
36
- function stewardRootHash(rootDir) {
37
- return createHash("sha256")
38
- .update(String(rootDir || ""))
39
- .digest("hex")
40
- .slice(0, 12);
41
- }
42
-
43
- function hygieneKeyForRow(row) {
44
- return `${row.kind}:${row.id}`;
45
- }
46
-
47
- function yyyymmdd(value) {
48
- const date = value ? new Date(value) : new Date();
49
- if (Number.isNaN(date.getTime())) return yyyymmdd(new Date().toISOString());
50
- return date.toISOString().slice(0, 10).replace(/-/gu, "");
51
- }
52
-
53
- function safeLabel(value) {
54
- return (
55
- String(value || "item")
56
- .toLowerCase()
57
- .replace(/[^a-z0-9._-]+/gu, "-")
58
- .replace(/^-+|-+$/gu, "")
59
- .slice(0, 80) || "item"
60
- );
61
- }
62
-
63
- function isInside(parent, child) {
64
- const rel = relative(resolve(parent), resolve(child));
65
- return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
66
- }
67
-
68
- function normalizeActiveSessions(active) {
69
- const sessions = Array.isArray(active)
70
- ? active
71
- : Array.isArray(active?.sessions)
72
- ? active.sessions
73
- : Array.isArray(active?.live_sessions)
74
- ? active.live_sessions
75
- : [];
76
- return sessions
77
- .map((session) => ({
78
- sessionId: String(session?.sessionId || session?.session_id || "").trim(),
79
- phase: String(
80
- session?.phase || session?.status || "active",
81
- ).toLowerCase(),
82
- }))
83
- .filter((session) => session.sessionId);
84
- }
85
-
86
- function isLiveOwned(row, activeSessions) {
87
- const rowSession = String(row?.session_id || row?.id || "").trim();
88
- if (!rowSession) return false;
89
- return activeSessions.some(
90
- (session) => session.sessionId === rowSession && session.phase !== "stale",
91
- );
92
- }
93
-
94
- function assertProjectHash(row, rootDir) {
95
- if (!row?.project_root_hash) return;
96
- const allowed = new Set([shortHash(rootDir), stewardRootHash(rootDir)]);
97
- if (!allowed.has(String(row.project_root_hash))) {
98
- throw new Error(
99
- `project_root_hash mismatch for ${hygieneKeyForRow(row)}: ${row.project_root_hash}`,
100
- );
101
- }
102
- }
103
-
104
- function assertLakePath(lakeRoot, path, label) {
105
- if (!isInside(lakeRoot, path)) {
106
- throw new Error(`${label} must be under lakeRoot: ${path}`);
107
- }
108
- }
109
-
110
- function sourceBytes(path) {
111
- const info = statSync(path);
112
- if (info.isFile()) return info.size;
113
- if (!info.isDirectory()) return info.size || 0;
114
- return 0;
115
- }
116
-
117
- function targetPathFor({ lakeRoot, row, sourcePath, now }) {
118
- const archiveDir = join(lakeRoot, "archive", yyyymmdd(now));
119
- const label = safeLabel(hygieneKeyForRow(row));
120
- return join(archiveDir, `${label}-${basename(sourcePath)}`);
121
- }
122
-
123
- function hasSecondActorApproval(opts = {}) {
124
- if (opts.humanAck === true || opts.humanGate === true) return true;
125
- const actorSessionId = String(opts.actorSessionId || "").trim();
126
- if (!actorSessionId) return false;
127
- const hygieneKey = opts.hygieneKey;
128
- const approvals = Array.isArray(opts.approvals) ? opts.approvals : [];
129
- return approvals.some((entry) => {
130
- const ref = entry?.ref && typeof entry.ref === "object" ? entry.ref : {};
131
- if (ref.hygiene_key !== hygieneKey) return false;
132
- const approverSession = String(ref?.actor?.session_id || "").trim();
133
- return Boolean(approverSession && approverSession !== actorSessionId);
134
- });
135
- }
136
-
137
- function movePath(sourcePath, targetPath, fsOps = {}) {
138
- const ops = {
139
- copyFileSync,
140
- cpSync,
141
- existsSync,
142
- lstatSync,
143
- mkdirSync,
144
- renameSync,
145
- rmSync,
146
- unlinkSync,
147
- ...fsOps,
148
- };
149
- ops.mkdirSync(dirname(targetPath), { recursive: true });
150
- try {
151
- ops.renameSync(sourcePath, targetPath);
152
- return "rename";
153
- } catch (error) {
154
- if (error?.code !== "EXDEV") throw error;
155
- const info = ops.lstatSync(sourcePath);
156
- if (info.isDirectory()) {
157
- ops.cpSync(sourcePath, targetPath, { recursive: true, force: false });
158
- ops.rmSync(sourcePath, { recursive: true, force: false });
159
- } else {
160
- ops.copyFileSync(sourcePath, targetPath);
161
- ops.unlinkSync(sourcePath);
162
- }
163
- return "copy_unlink";
164
- }
165
- }
166
-
167
- function digestOperations(operations) {
168
- const payload = operations.map((operation) => ({
169
- hygiene_key: operation.hygiene_key,
170
- status: operation.status,
171
- source_path: operation.source_path,
172
- target_path: operation.target_path,
173
- bytes: operation.bytes,
174
- reason: operation.reason,
175
- }));
176
- return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
177
- }
178
-
179
- function rowsFromProjection(projection) {
180
- return Array.isArray(projection?.rows) ? projection.rows : [];
181
- }
182
-
183
- export async function applyHygieneArchiveActions({
184
- rootDir,
185
- lakeRoot,
186
- projection,
187
- dryRun = true,
188
- now = new Date().toISOString(),
189
- applyMode = "off",
190
- active = {},
191
- humanAck = false,
192
- humanGate = false,
193
- actorSessionId = null,
194
- approvals = [],
195
- fsOps = {},
196
- } = {}) {
197
- const archiveRoot = join(lakeRoot, "archive", yyyymmdd(now));
198
- assertLakePath(lakeRoot, archiveRoot, "archive target");
199
-
200
- const activeSessions = normalizeActiveSessions(active);
201
- const operations = [];
202
-
203
- for (const row of rowsFromProjection(projection)) {
204
- const hygieneKey = hygieneKeyForRow(row);
205
- if (row?.kind === "worktree" && row?.status === "orphaned") {
206
- operations.push({
207
- hygiene_key: hygieneKey,
208
- kind: row.kind,
209
- id: row.id,
210
- action: row.action,
211
- status: "blocked",
212
- reason: "orphan_worktree_requires_human",
213
- bytes: 0,
214
- });
215
- continue;
216
- }
217
-
218
- if (!ARCHIVABLE_ACTIONS.has(row?.action)) continue;
219
-
220
- assertProjectHash(row, rootDir);
221
-
222
- if (isLiveOwned(row, activeSessions)) {
223
- operations.push({
224
- hygiene_key: hygieneKey,
225
- kind: row.kind,
226
- id: row.id,
227
- action: row.action,
228
- status: "skipped",
229
- reason: "live_session_owned",
230
- bytes: 0,
231
- });
232
- continue;
233
- }
234
-
235
- const sourcePath = row.artifact_path ? resolve(row.artifact_path) : null;
236
- if (!sourcePath) {
237
- operations.push({
238
- hygiene_key: hygieneKey,
239
- kind: row.kind,
240
- id: row.id,
241
- action: row.action,
242
- status: "skipped",
243
- reason: "missing_artifact_path",
244
- bytes: 0,
245
- });
246
- continue;
247
- }
248
- // lake 밖 산출물은 자동 이동 대상이 아니다 — 크래시 대신 skip으로 보고한다.
249
- // (checkpoint 등 실제 산출물은 대부분 lake 밖에 있으므로 throw 하면 apply 전체가 죽는다.)
250
- if (!isInside(lakeRoot, sourcePath)) {
251
- operations.push({
252
- hygiene_key: hygieneKey,
253
- kind: row.kind,
254
- id: row.id,
255
- action: row.action,
256
- source_path: sourcePath,
257
- status: "skipped",
258
- reason: "source_outside_lake",
259
- bytes: 0,
260
- });
261
- continue;
262
- }
263
-
264
- const targetPath = targetPathFor({ lakeRoot, row, sourcePath, now });
265
- assertLakePath(lakeRoot, targetPath, "archive target");
266
-
267
- if (!existsSync(sourcePath)) {
268
- operations.push({
269
- hygiene_key: hygieneKey,
270
- kind: row.kind,
271
- id: row.id,
272
- action: row.action,
273
- source_path: sourcePath,
274
- target_path: targetPath,
275
- status: existsSync(targetPath) ? "already_archived" : "skipped",
276
- reason: existsSync(targetPath) ? undefined : "source_missing",
277
- bytes: 0,
278
- });
279
- continue;
280
- }
281
-
282
- operations.push({
283
- hygiene_key: hygieneKey,
284
- kind: row.kind,
285
- id: row.id,
286
- action: row.action,
287
- source_path: sourcePath,
288
- target_path: targetPath,
289
- status: "planned",
290
- bytes: sourceBytes(sourcePath),
291
- });
292
- }
293
-
294
- if (!dryRun) {
295
- for (const operation of operations) {
296
- if (operation.status !== "planned") continue;
297
- if (applyMode !== "archive") {
298
- operation.status = "blocked";
299
- operation.reason = "apply_mode_off";
300
- continue;
301
- }
302
- if (
303
- !hasSecondActorApproval({
304
- humanAck,
305
- humanGate,
306
- actorSessionId,
307
- approvals,
308
- hygieneKey: operation.hygiene_key,
309
- })
310
- ) {
311
- operation.status = "blocked";
312
- operation.reason = "second_actor_ack_required";
313
- continue;
314
- }
315
- operation.move_method = movePath(
316
- operation.source_path,
317
- operation.target_path,
318
- fsOps,
319
- );
320
- operation.status = "archived";
321
- }
322
- }
323
-
324
- const plannedCount = operations.filter((operation) =>
325
- ["planned", "archived", "already_archived"].includes(operation.status),
326
- ).length;
327
- const appliedCount = operations.filter(
328
- (operation) => operation.status === "archived",
329
- ).length;
330
- const blockedCount = operations.filter(
331
- (operation) => operation.status === "blocked",
332
- ).length;
333
-
334
- return {
335
- schema_version: "cto-hygiene-actions.v1",
336
- dry_run: Boolean(dryRun),
337
- apply_mode: applyMode,
338
- archive_root: archiveRoot,
339
- planned_count: plannedCount,
340
- applied_count: appliedCount,
341
- blocked_count: blockedCount,
342
- total_bytes: operations.reduce(
343
- (sum, operation) => sum + Number(operation.bytes || 0),
344
- 0,
345
- ),
346
- digest: digestOperations(operations),
347
- live_safety: {
348
- active_session_count: activeSessions.length,
349
- skipped_live_count: operations.filter(
350
- (operation) => operation.reason === "live_session_owned",
351
- ).length,
352
- },
353
- operations,
354
- };
355
- }
@@ -1,170 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { mkdir, readFile, writeFile } from "node:fs/promises";
3
- import { dirname } from "node:path";
4
-
5
- const ACTIONABLE_COUNT_KEYS = Object.freeze([
6
- "active_tasks",
7
- "stale_sessions",
8
- "orphan_worktrees",
9
- "superseded_checkpoints",
10
- "unknown_owner",
11
- ]);
12
-
13
- function stableValue(value) {
14
- if (Array.isArray(value)) return value.map(stableValue);
15
- if (value && typeof value === "object") {
16
- return Object.fromEntries(
17
- Object.keys(value)
18
- .sort()
19
- .map((key) => [key, stableValue(value[key])]),
20
- );
21
- }
22
- return value;
23
- }
24
-
25
- function stableJson(value) {
26
- return JSON.stringify(stableValue(value));
27
- }
28
-
29
- function normalizeCount(value) {
30
- return Number.isFinite(Number(value)) ? Number(value) : 0;
31
- }
32
-
33
- function actionableCounts(projection = {}) {
34
- const counts = projection?.counts || {};
35
- return Object.fromEntries(
36
- ACTIONABLE_COUNT_KEYS.map((key) => [key, normalizeCount(counts[key])]),
37
- );
38
- }
39
-
40
- function normalizeRows(rows) {
41
- return (Array.isArray(rows) ? rows : [])
42
- .map((row) => ({
43
- kind: String(row?.kind || ""),
44
- id: String(row?.id || ""),
45
- status: String(row?.status || ""),
46
- action: row?.action == null ? "" : String(row.action),
47
- owner: row?.owner == null ? "" : String(row.owner),
48
- }))
49
- .sort((a, b) =>
50
- [a.kind, a.id, a.status, a.action, a.owner]
51
- .join("\u0000")
52
- .localeCompare(
53
- [b.kind, b.id, b.status, b.action, b.owner].join("\u0000"),
54
- ),
55
- );
56
- }
57
-
58
- export function ctoHygieneStateHash(projection = {}) {
59
- const canonical = {
60
- counts: actionableCounts(projection),
61
- rows: normalizeRows(projection.rows),
62
- };
63
- return createHash("sha256").update(stableJson(canonical)).digest("hex");
64
- }
65
-
66
- function plural(count, singular, pluralWord = `${singular}s`) {
67
- return `${count} ${count === 1 ? singular : pluralWord}`;
68
- }
69
-
70
- function summarizeCounts(counts) {
71
- const parts = [];
72
- if (counts.active_tasks)
73
- parts.push(plural(counts.active_tasks, "active task"));
74
- if (counts.stale_sessions)
75
- parts.push(plural(counts.stale_sessions, "stale session"));
76
- if (counts.orphan_worktrees)
77
- parts.push(plural(counts.orphan_worktrees, "orphan worktree"));
78
- if (counts.superseded_checkpoints)
79
- parts.push(plural(counts.superseded_checkpoints, "superseded checkpoint"));
80
- if (counts.unknown_owner)
81
- parts.push(plural(counts.unknown_owner, "unknown owner"));
82
- return parts;
83
- }
84
-
85
- export function buildCtoHygieneNotification(projection = {}, opts = {}) {
86
- const counts = actionableCounts(projection);
87
- const actionable = ACTIONABLE_COUNT_KEYS.some((key) => counts[key] > 0);
88
- const hash = ctoHygieneStateHash(projection);
89
- if (!actionable) {
90
- return { actionable, hash, event: null, counts };
91
- }
92
-
93
- const summary = `CTO hygiene needs action: ${summarizeCounts(counts).join(", ")}`;
94
- return {
95
- actionable,
96
- hash,
97
- counts,
98
- event: {
99
- type: "ctoHygiene",
100
- sessionId: opts.sessionId || "cto-hygiene",
101
- summary,
102
- timestamp:
103
- typeof opts.now === "function"
104
- ? opts.now()
105
- : (opts.timestamp ?? new Date().toISOString()),
106
- },
107
- };
108
- }
109
-
110
- async function readState(stateFile) {
111
- if (!stateFile) return null;
112
- try {
113
- return JSON.parse(await readFile(stateFile, "utf8"));
114
- } catch {
115
- return null;
116
- }
117
- }
118
-
119
- async function writeState(stateFile, state) {
120
- if (!stateFile) return;
121
- await mkdir(dirname(stateFile), { recursive: true });
122
- await writeFile(stateFile, `${JSON.stringify(state, null, 2)}\n`, "utf8");
123
- }
124
-
125
- export async function notifyCtoHygieneOnce(projection = {}, opts = {}) {
126
- const notification = buildCtoHygieneNotification(projection, opts);
127
- const previous = await readState(opts.stateFile);
128
- const unchanged = previous?.hash === notification.hash;
129
- const checkedAt =
130
- typeof opts.now === "function" ? opts.now() : new Date().toISOString();
131
-
132
- if (!notification.actionable) {
133
- await writeState(opts.stateFile, {
134
- hash: notification.hash,
135
- actionable: false,
136
- checkedAt,
137
- });
138
- return {
139
- actionable: false,
140
- notified: false,
141
- reason: "not-actionable",
142
- hash: notification.hash,
143
- };
144
- }
145
-
146
- if (unchanged) {
147
- return {
148
- actionable: true,
149
- notified: false,
150
- reason: "unchanged-state",
151
- hash: notification.hash,
152
- };
153
- }
154
-
155
- const notifierResult = await opts.notifier.notify(notification.event);
156
- await writeState(opts.stateFile, {
157
- hash: notification.hash,
158
- actionable: true,
159
- notifiedAt: notification.event.timestamp,
160
- });
161
-
162
- return {
163
- actionable: true,
164
- notified: true,
165
- reason: "changed-actionable-state",
166
- hash: notification.hash,
167
- event: notification.event,
168
- notify: notifierResult,
169
- };
170
- }
@@ -1,92 +0,0 @@
1
- // hub/team/build-worker-prompt.mjs — append Completion Protocol to PRD prompt (#125)
2
- //
3
- // swarm-hypervisor injects a Completion Protocol appendix into every worker
4
- // prompt so that workers emit a sentinel-framed JSON payload conductor.mjs can
5
- // reliably capture (see sentinel-capture.mjs and extract-completion-payload.mjs).
6
- //
7
- // Pure module — no I/O — so the appendix and merge logic can be unit-tested
8
- // without spawning conductors.
9
-
10
- import { SENTINEL_BEGIN, SENTINEL_END } from "./sentinel-capture.mjs";
11
-
12
- function normalizeLeaseFiles(leaseFiles) {
13
- if (!Array.isArray(leaseFiles)) return [];
14
- return leaseFiles
15
- .map((file) => (typeof file === "string" ? file.trim() : ""))
16
- .filter(Boolean);
17
- }
18
-
19
- function formatLeaseFiles(leaseFiles) {
20
- const normalized = normalizeLeaseFiles(leaseFiles);
21
- if (normalized.length === 0) return "- (none declared)";
22
- return normalized.map((file) => `- ${file}`).join("\n");
23
- }
24
-
25
- function normalizeWorktreePath(worktreePath) {
26
- return typeof worktreePath === "string" ? worktreePath.trim() : "";
27
- }
28
-
29
- export function buildLeaseScopedAcceptanceAppendix({
30
- leaseFiles = [],
31
- worktreePath,
32
- } = {}) {
33
- const normalizedWorktreePath = normalizeWorktreePath(worktreePath);
34
- const rootLine = normalizedWorktreePath
35
- ? `작업 루트(절대경로): ${normalizedWorktreePath} — 아래 lease 경로와 모든 상대경로는 이 루트 기준으로만 해석한다.\n`
36
- : "";
37
-
38
- return `
39
-
40
- ## Lease-scoped Acceptance / Lint Guard (자동 삽입됨)
41
- ${rootLine}- 위 PRD 본문의 모든 제약과 acceptance 기준은 이 appendix 이후에도 그대로 유효하다.
42
- - 이 shard 의 파일 lease:
43
- ${formatLeaseFiles(leaseFiles)}
44
- - Acceptance, lint, and format checks are scoped to files changed by this shard; if that set is unclear, use only the lease list above.
45
- - Do not run repo-wide format/lint fixers such as \`biome check --write .\`, \`biome --write .\`, \`npm run lint:fix\`, or broad \`npm run lint\` to absorb unrelated drift.
46
- - For Biome, use \`npx biome check <changed-files-or-lease-files>\`; add \`--write\` only when every target is a changed/leased file you intend to commit.
47
- - Pre-existing lint drift outside the lease is not this shard's acceptance responsibility; report it instead of editing it.
48
- `;
49
- }
50
-
51
- export const COMPLETION_PROTOCOL_APPENDIX = `
52
-
53
- ## Completion Protocol (자동 삽입됨)
54
- <!-- swarm hypervisor 가 이 섹션을 worker prompt 에 자동 주입합니다.
55
- PRD 작성자는 이 섹션을 수정하지 마세요.
56
- 상세: hub/team/build-worker-prompt.mjs / sentinel-capture.mjs (#125). -->
57
-
58
- 작업의 마지막 단계로, stdout 에 다음 형식의 완료 payload 를 정확히 한 번 출력하라:
59
-
60
- ${SENTINEL_BEGIN}
61
- {"shard":"<shard name>","status":"ok","commits_made":[{"sha":"<40-char full sha>","message":"<commit msg>"}]}
62
- ${SENTINEL_END}
63
-
64
- 규약:
65
- - 두 sentinel 마커는 각자 자기 줄에 단독으로 출력 (앞뒤 newline)
66
- - 마커 사이 본문은 단일 JSON object (배열/primitive 금지)
67
- - status 값은 ok | failed | blocked 중 하나
68
- - payload 출력 직전 \`git log -1 --format=%H\` 로 보고할 sha 가 실재하는지 검증하라
69
- - 코드 변경이 기대되는 shard 에서 변경/커밋을 못 했으면 status:failed 와 함께 reason 필드로 사유를 보고하라 — 그 경우 빈 commits_made 에 status:ok 는 금지
70
- - no-op shard 는 status:ok + 빈 commits_made 배열 허용
71
- - 마커 쌍은 stdout 에 정확히 한 번만 출력해야 함. 재emit 시 conductor 는 첫 BEGIN..END 한 쌍만 채택하며, 이후 stdout 은 무시한다.
72
- - ${SENTINEL_BEGIN} 만 출력하고 ${SENTINEL_END} 누락 시 conductor 가 truncation 으로 명확히 reject
73
- `;
74
-
75
- /**
76
- * Append the Completion Protocol section to a PRD prompt.
77
- *
78
- * @param {string|null|undefined} prdPrompt — original PRD body
79
- * @param {{ leaseFiles?: string[], worktreePath?: string }} [opts] — shard file lease and absolute worktree root for scoped acceptance
80
- * @returns {string} prompt with appendix
81
- */
82
- export function buildWorkerPrompt(prdPrompt, opts = {}) {
83
- const body = typeof prdPrompt === "string" ? prdPrompt : "";
84
- return (
85
- body +
86
- buildLeaseScopedAcceptanceAppendix({
87
- leaseFiles: opts.leaseFiles,
88
- worktreePath: opts.worktreePath,
89
- }) +
90
- COMPLETION_PROTOCOL_APPENDIX
91
- );
92
- }
@@ -1,49 +0,0 @@
1
- // hub/team/check-mcp-hub.mjs — health-probe L2 용 hub /health ping 체커.
2
- // health-probe.mjs 의 checkMcp 로 주입되어 `mcp_initializing` state 판정에 사용.
3
- // hub /health 가 200 이면 OK (MCP transport 인프라 살아있음), 그 외는 fail.
4
-
5
- const DEFAULT_HUB_URL = "http://127.0.0.1:27888";
6
- const DEFAULT_TIMEOUT_MS = 3000;
7
-
8
- function resolveHubHealthUrl(hubUrl) {
9
- const base = hubUrl || process.env.TFX_HUB_URL || DEFAULT_HUB_URL;
10
- // `/mcp` suffix 제거 (triflux convention — bridge.mjs:54, hub-client.mjs,
11
- // lead-control.mjs, session-sync.mjs 전부 TFX_HUB_URL 을 MCP transport URL
12
- // 로 쓰고 base URL 이 필요할 때 `/mcp$` 를 strip 한다). 제거하지 않으면
13
- // `.../mcp/health` 가 되어 hub 가 404 로 응답 → L2 영구 fail → heartbeat
14
- // 이 지속적으로 `mcp_initializing` 로 grace — #173 Codex P2 review.
15
- return base.replace(/\/mcp\/?$/, "").replace(/\/+$/, "") + "/health";
16
- }
17
-
18
- /**
19
- * Hub /health 기반 L2 checker factory.
20
- * @param {object} [opts]
21
- * @param {string} [opts.hubUrl] — override. 미지정 시 TFX_HUB_URL env 또는 default.
22
- * @param {number} [opts.timeoutMs=3000] — fetch timeout (ms).
23
- * @param {typeof fetch} [opts.fetchFn] — fetch 오버라이드 (테스트용).
24
- * @returns {() => Promise<boolean>} — true = hub healthy, false = degraded/down/timeout.
25
- */
26
- export function createHubHealthChecker(opts = {}) {
27
- const url = resolveHubHealthUrl(opts.hubUrl);
28
- const timeoutMs = Number.isFinite(opts.timeoutMs)
29
- ? opts.timeoutMs
30
- : DEFAULT_TIMEOUT_MS;
31
- const fetchFn = opts.fetchFn || globalThis.fetch;
32
-
33
- return async function checkMcpHubHealth() {
34
- if (typeof fetchFn !== "function") return false;
35
- const controller = new AbortController();
36
- const timer = setTimeout(() => controller.abort(), timeoutMs);
37
- try {
38
- const res = await fetchFn(url, {
39
- method: "GET",
40
- signal: controller.signal,
41
- });
42
- return res.ok === true;
43
- } catch {
44
- return false;
45
- } finally {
46
- clearTimeout(timer);
47
- }
48
- };
49
- }