@triflux/core 10.51.0 → 10.52.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.
- package/hub/bridge.mjs +65 -1172
- package/hub/index.mjs +2 -18
- package/hub/lib/process-utils.mjs +1 -33
- package/hub/team/claude-daemon-control.mjs +1 -2
- package/hub/team/claude-session-projection.mjs +5 -73
- package/hub/team/nativeProxy.mjs +759 -0
- package/hub/team/session-context.mjs +1 -1
- package/hud/constants.mjs +2 -0
- package/hud/hud-qos-status.mjs +21 -5
- package/hud/providers/gemini.mjs +20 -0
- package/hud/renderers.mjs +79 -46
- package/hud/utils.mjs +9 -5
- package/package.json +2 -4
- package/scripts/lib/agent-route-policy.mjs +0 -67
- package/scripts/lib/cli-claude.mjs +0 -12
- package/scripts/lib/env-probe.mjs +0 -70
- package/scripts/lib/legacy-mcp-cleanup.mjs +283 -0
- package/scripts/lib/mcp-guard-engine.mjs +40 -98
- package/scripts/lib/session-presence.mjs +1 -99
- package/hub/adaptive-diagnostic.mjs +0 -350
- package/hub/adaptive-inject.mjs +0 -224
- package/hub/adaptive-memory.mjs +0 -277
- package/hub/adaptive.mjs +0 -172
- package/hub/assign-callbacks.mjs +0 -170
- package/hub/delegator/contracts.mjs +0 -38
- package/hub/delegator/index.mjs +0 -14
- package/hub/delegator/schema/delegator-tools.schema.json +0 -250
- package/hub/delegator/service.mjs +0 -336
- package/hub/delegator/tool-definitions.mjs +0 -35
- package/hub/hitl.mjs +0 -202
- package/hub/lib/known-errors.json +0 -72
- package/hub/lib/memory-store.mjs +0 -1001
- package/hub/lib/phase-manager.mjs +0 -493
- package/hub/lib/state-snapshot.mjs +0 -293
- package/hub/lib/trace-recorder.mjs +0 -153
- package/hub/lib/uuidv7.mjs +0 -45
- package/hub/memory-doctor.mjs +0 -640
- package/hub/middleware/quota-middleware.mjs +0 -70
- package/hub/middleware/request-logger.mjs +0 -191
- package/hub/paths.mjs +0 -24
- package/hub/pipeline/index.mjs +0 -163
- package/hub/pipeline/state.mjs +0 -191
- package/hub/pipeline/transitions.mjs +0 -131
- package/hub/reflexion.mjs +0 -290
- package/hub/role-contract.mjs +0 -312
- package/hub/router.mjs +0 -2026
- package/hub/session-fingerprint.mjs +0 -418
- package/hub/state.mjs +0 -300
- package/hub/team/synapse-http.mjs +0 -311
- package/hub/team-bridge.mjs +0 -27
- package/scripts/lib/claudemd-scanner.mjs +0 -26
- package/scripts/lib/context.mjs +0 -51
- package/scripts/lib/handoff.mjs +0 -187
- package/scripts/lib/logger.mjs +0 -122
- package/scripts/lib/stealth-fetch.mjs +0 -176
|
@@ -1,311 +0,0 @@
|
|
|
1
|
-
import { execFileSync } from "node:child_process";
|
|
2
|
-
import { createHash } from "node:crypto";
|
|
3
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
-
import { homedir, hostname } from "node:os";
|
|
5
|
-
import { dirname, join } from "node:path";
|
|
6
|
-
import { normalizeRoleKey } from "../role-contract.mjs";
|
|
7
|
-
|
|
8
|
-
const HUB_DEFAULT_PORT = 27888;
|
|
9
|
-
// Same token file as hub/bridge.mjs (HUB_TOKEN_FILE). Kept inline rather than
|
|
10
|
-
// imported so this helper stays dependency-free and byte-identical across the
|
|
11
|
-
// packages/core mirror (which cannot carry relative cross-package imports).
|
|
12
|
-
const HUB_TOKEN_FILE = join(homedir(), ".claude", ".tfx-hub-token");
|
|
13
|
-
|
|
14
|
-
// In-flight fire-and-forget POSTs. A short-lived caller (the SessionStart hook,
|
|
15
|
-
// which process.exit(0)s immediately after firing register) must be able to
|
|
16
|
-
// flush these before the process dies: Node's process.exit() abandons pending
|
|
17
|
-
// socket I/O, so an un-awaited loopback POST is created but never written.
|
|
18
|
-
// Callers on an exit budget drain this set via drainPendingSynapse() first.
|
|
19
|
-
const inFlightSynapse = new Set();
|
|
20
|
-
|
|
21
|
-
function normalizeToken(raw) {
|
|
22
|
-
if (raw == null) return null;
|
|
23
|
-
const token = String(raw).trim();
|
|
24
|
-
return token || null;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function opaqueId(prefix, value) {
|
|
28
|
-
return `${prefix}_${createHash("sha256")
|
|
29
|
-
.update(String(value || ""))
|
|
30
|
-
.digest("base64url")
|
|
31
|
-
.slice(0, 22)}`;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
function normalizedProjectId(value) {
|
|
35
|
-
try {
|
|
36
|
-
return normalizeRoleKey({ project_id: value, role_kind: "cto" }).project_id;
|
|
37
|
-
} catch {
|
|
38
|
-
return "";
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function resolveProjectId(cwd, meta, opts = {}) {
|
|
43
|
-
const explicit = meta?.project_id || process.env.TFX_PROJECT_ID;
|
|
44
|
-
if (explicit) return normalizedProjectId(explicit);
|
|
45
|
-
if (typeof opts.resolveProjectId === "function") {
|
|
46
|
-
return normalizedProjectId(opts.resolveProjectId(cwd));
|
|
47
|
-
}
|
|
48
|
-
let current = cwd;
|
|
49
|
-
while (current) {
|
|
50
|
-
const manifest = join(current, ".triflux", "project.json");
|
|
51
|
-
if (existsSync(manifest)) {
|
|
52
|
-
try {
|
|
53
|
-
const parsed = JSON.parse(readFileSync(manifest, "utf8"));
|
|
54
|
-
if (parsed?.schema_version !== "tfx.project.v1") return "";
|
|
55
|
-
return normalizedProjectId(parsed.project_id);
|
|
56
|
-
} catch {
|
|
57
|
-
return "";
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
const parent = dirname(current);
|
|
61
|
-
if (parent === current) break;
|
|
62
|
-
current = parent;
|
|
63
|
-
}
|
|
64
|
-
return "";
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function inferSessionCli(meta, opts = {}) {
|
|
68
|
-
const explicit = String(meta?.cli || meta?.actor_cli || "")
|
|
69
|
-
.trim()
|
|
70
|
-
.toLowerCase();
|
|
71
|
-
if (explicit === "codex" || explicit === "claude") return explicit;
|
|
72
|
-
const entrypoint = String(opts.entrypoint ?? process.argv[1] ?? "");
|
|
73
|
-
if (entrypoint.includes("codex-session-hook")) return "codex";
|
|
74
|
-
if (entrypoint.includes("agy-session-hook")) return "other";
|
|
75
|
-
return "claude";
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
function resolveTmuxSession(meta, opts = {}) {
|
|
79
|
-
const explicit =
|
|
80
|
-
meta?.tmux_session || meta?.session_name || process.env.TFX_TMUX_SESSION;
|
|
81
|
-
if (explicit) return String(explicit).trim();
|
|
82
|
-
if (!process.env.TMUX) return "";
|
|
83
|
-
try {
|
|
84
|
-
const run =
|
|
85
|
-
opts.tmuxSessionName ||
|
|
86
|
-
(() =>
|
|
87
|
-
execFileSync("tmux", ["display-message", "-p", "#{session_name}"], {
|
|
88
|
-
encoding: "utf8",
|
|
89
|
-
timeout: 200,
|
|
90
|
-
windowsHide: true,
|
|
91
|
-
}));
|
|
92
|
-
return String(run() || "").trim();
|
|
93
|
-
} catch {
|
|
94
|
-
return "";
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export function buildSynapseRegistrationMeta(meta, opts = {}) {
|
|
99
|
-
if (!meta || meta.sessionKind !== "interactive") return meta;
|
|
100
|
-
const sessionId = String(meta.sessionId || "").trim();
|
|
101
|
-
if (!sessionId) return meta;
|
|
102
|
-
const cwd = typeof meta.cwd === "string" ? meta.cwd : process.cwd();
|
|
103
|
-
const cli = inferSessionCli(meta, opts);
|
|
104
|
-
const hostId = String(
|
|
105
|
-
meta.host_id ||
|
|
106
|
-
process.env.TFX_HOST_ID ||
|
|
107
|
-
opaqueId("hst", opts.hostname?.() || hostname()),
|
|
108
|
-
).trim();
|
|
109
|
-
const expiresAtMs = Number(opts.nowMs?.() ?? Date.now()) + 299000;
|
|
110
|
-
const transportLocators = [];
|
|
111
|
-
if (cli === "claude") {
|
|
112
|
-
transportLocators.push({
|
|
113
|
-
schema_version: "tfx.transport-locator.v1",
|
|
114
|
-
transport_id: opaqueId("trn", `claude-uds:${hostId}:${sessionId}`),
|
|
115
|
-
kind: "claude-uds",
|
|
116
|
-
host_id: hostId,
|
|
117
|
-
capabilities: ["probe", "wake", "activate", "interrupt"],
|
|
118
|
-
priority: 100,
|
|
119
|
-
expires_at_ms: expiresAtMs,
|
|
120
|
-
locator: {
|
|
121
|
-
session_id: sessionId,
|
|
122
|
-
bridge_id: String(
|
|
123
|
-
meta.bridge_id || process.env.TFX_BRIDGE_ID || "local-hub",
|
|
124
|
-
),
|
|
125
|
-
},
|
|
126
|
-
});
|
|
127
|
-
}
|
|
128
|
-
const tmuxSession = resolveTmuxSession(meta, opts);
|
|
129
|
-
if (tmuxSession) {
|
|
130
|
-
const muxServerSource =
|
|
131
|
-
meta.mux_server_id ||
|
|
132
|
-
process.env.TFX_MUX_SERVER_ID ||
|
|
133
|
-
String(process.env.TMUX || "default").split(",", 1)[0];
|
|
134
|
-
transportLocators.push({
|
|
135
|
-
schema_version: "tfx.transport-locator.v1",
|
|
136
|
-
transport_id: opaqueId("trn", `tmux:${hostId}:${tmuxSession}`),
|
|
137
|
-
kind: "tmux",
|
|
138
|
-
host_id: hostId,
|
|
139
|
-
capabilities: ["probe", "wake", "activate", "interrupt"],
|
|
140
|
-
priority: cli === "codex" ? 100 : 50,
|
|
141
|
-
expires_at_ms: expiresAtMs,
|
|
142
|
-
locator: {
|
|
143
|
-
session_name: tmuxSession,
|
|
144
|
-
mux_server_id: opaqueId("mux", muxServerSource),
|
|
145
|
-
},
|
|
146
|
-
});
|
|
147
|
-
}
|
|
148
|
-
const directAgentId = `session:${sessionId}`;
|
|
149
|
-
return {
|
|
150
|
-
...meta,
|
|
151
|
-
agent_id:
|
|
152
|
-
meta.agent_id ||
|
|
153
|
-
(directAgentId.length <= 64 && /^[a-zA-Z0-9._:-]+$/u.test(directAgentId)
|
|
154
|
-
? directAgentId
|
|
155
|
-
: opaqueId("session", sessionId)),
|
|
156
|
-
cli,
|
|
157
|
-
project_id: resolveProjectId(cwd, meta, opts) || undefined,
|
|
158
|
-
session_id: meta.session_id || sessionId,
|
|
159
|
-
host_id: hostId,
|
|
160
|
-
transport_locators_json:
|
|
161
|
-
meta.transport_locators_json ?? JSON.stringify(transportLocators),
|
|
162
|
-
};
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
// Mirrors hub/bridge.mjs:readHubToken — env override first, then the token file.
|
|
166
|
-
// Missing token → null (backward-compatible with token-less hubs).
|
|
167
|
-
function readHubToken() {
|
|
168
|
-
const envToken = normalizeToken(process.env.TFX_HUB_TOKEN);
|
|
169
|
-
if (envToken) return envToken;
|
|
170
|
-
try {
|
|
171
|
-
return normalizeToken(readFileSync(HUB_TOKEN_FILE, "utf8"));
|
|
172
|
-
} catch {
|
|
173
|
-
return null;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// Wrap IPv6 hosts in [...] so they form a valid URL authority (cf. bridge.mjs).
|
|
178
|
-
function formatHostForUrl(host) {
|
|
179
|
-
return String(host).includes(":") ? `[${host}]` : host;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
// Resolve the hub base URL from env (TFX_HUB_URL / TFX_HUB_PORT) before falling
|
|
183
|
-
// back to the loopback default, so a cascaded / non-default hub port is hit
|
|
184
|
-
// instead of silently posting to 127.0.0.1:27888 and missing the live hub.
|
|
185
|
-
function resolveSynapseBaseUrl() {
|
|
186
|
-
const envUrl = normalizeToken(process.env.TFX_HUB_URL);
|
|
187
|
-
if (envUrl) return envUrl.replace(/\/mcp$/, "");
|
|
188
|
-
|
|
189
|
-
const envPort = Number.parseInt(String(process.env.TFX_HUB_PORT ?? ""), 10);
|
|
190
|
-
if (Number.isFinite(envPort) && envPort > 0) {
|
|
191
|
-
return `http://${formatHostForUrl("127.0.0.1")}:${envPort}`;
|
|
192
|
-
}
|
|
193
|
-
return `http://${formatHostForUrl("127.0.0.1")}:${HUB_DEFAULT_PORT}`;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
function resolveSynapseFetch(fetchImpl) {
|
|
197
|
-
if (fetchImpl === null) return null;
|
|
198
|
-
if (typeof fetchImpl === "function") return fetchImpl;
|
|
199
|
-
if (typeof globalThis.fetch === "function") {
|
|
200
|
-
return globalThis.fetch.bind(globalThis);
|
|
201
|
-
}
|
|
202
|
-
return null;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
export function buildSynapseTaskSummary(prompt, maxLength = 100) {
|
|
206
|
-
if (maxLength <= 0) return "";
|
|
207
|
-
return String(prompt ?? "").slice(0, maxLength);
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
export function fireAndForgetSynapse(path, payload, opts = {}) {
|
|
211
|
-
const fetchImpl = resolveSynapseFetch(opts.fetchImpl);
|
|
212
|
-
if (!fetchImpl) return false;
|
|
213
|
-
|
|
214
|
-
try {
|
|
215
|
-
const baseUrl = opts.baseUrl || resolveSynapseBaseUrl();
|
|
216
|
-
const url = new URL(path, baseUrl).toString();
|
|
217
|
-
const headers = { "content-type": "application/json" };
|
|
218
|
-
// token: false explicitly skips auth; otherwise reuse the hub token so a
|
|
219
|
-
// token-required hub does not 401 (the failure would be swallowed silently).
|
|
220
|
-
if (opts.token !== false) {
|
|
221
|
-
const token =
|
|
222
|
-
typeof opts.token === "string" && opts.token.trim()
|
|
223
|
-
? opts.token.trim()
|
|
224
|
-
: readHubToken();
|
|
225
|
-
if (token) headers.Authorization = `Bearer ${token}`;
|
|
226
|
-
}
|
|
227
|
-
const init = {
|
|
228
|
-
method: "POST",
|
|
229
|
-
headers,
|
|
230
|
-
body: JSON.stringify(payload),
|
|
231
|
-
};
|
|
232
|
-
// Optional bounded timeout so callers on a teardown budget (e.g. SessionEnd)
|
|
233
|
-
// cannot hang the host process if the hub stalls. The timer is unref'd so it
|
|
234
|
-
// never keeps the event loop (and thus the hook process) alive on its own.
|
|
235
|
-
let timer = null;
|
|
236
|
-
const timeoutMs = Number(opts.timeoutMs);
|
|
237
|
-
if (
|
|
238
|
-
Number.isFinite(timeoutMs) &&
|
|
239
|
-
timeoutMs > 0 &&
|
|
240
|
-
typeof AbortController === "function"
|
|
241
|
-
) {
|
|
242
|
-
const controller = new AbortController();
|
|
243
|
-
init.signal = controller.signal;
|
|
244
|
-
timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
245
|
-
if (typeof timer.unref === "function") timer.unref();
|
|
246
|
-
}
|
|
247
|
-
const tracked = Promise.resolve(fetchImpl(url, init))
|
|
248
|
-
.catch(() => {})
|
|
249
|
-
.finally(() => {
|
|
250
|
-
if (timer) clearTimeout(timer);
|
|
251
|
-
inFlightSynapse.delete(tracked);
|
|
252
|
-
});
|
|
253
|
-
inFlightSynapse.add(tracked);
|
|
254
|
-
return true;
|
|
255
|
-
} catch {
|
|
256
|
-
return false;
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
// Await any in-flight fire-and-forget Synapse POSTs, bounded by timeoutMs so a
|
|
261
|
-
// stalled hub can never hang the caller. The SessionStart hook calls this right
|
|
262
|
-
// before process.exit(0) so the register POST actually flushes to the socket.
|
|
263
|
-
export function drainPendingSynapse(timeoutMs = 1000) {
|
|
264
|
-
if (inFlightSynapse.size === 0) return Promise.resolve();
|
|
265
|
-
const settled = Promise.allSettled([...inFlightSynapse]);
|
|
266
|
-
const ms = Number(timeoutMs);
|
|
267
|
-
if (!Number.isFinite(ms) || ms <= 0) return settled;
|
|
268
|
-
let timeout = null;
|
|
269
|
-
const timeoutPromise = new Promise((resolve) => {
|
|
270
|
-
// Keep this timer ref'ed: drainPendingSynapse() is awaited specifically
|
|
271
|
-
// to hold the process open until either in-flight POSTs settle or the
|
|
272
|
-
// bounded drain budget expires. An unref'ed timer can let Node's test
|
|
273
|
-
// runner/process exit before the Promise resolves when no other handles
|
|
274
|
-
// remain.
|
|
275
|
-
timeout = setTimeout(resolve, ms);
|
|
276
|
-
});
|
|
277
|
-
return Promise.race([settled, timeoutPromise]).finally(() => {
|
|
278
|
-
if (timeout) clearTimeout(timeout);
|
|
279
|
-
});
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
export function registerSynapseSession(meta, opts = {}) {
|
|
283
|
-
return fireAndForgetSynapse(
|
|
284
|
-
"/synapse/register",
|
|
285
|
-
buildSynapseRegistrationMeta(meta, opts),
|
|
286
|
-
opts,
|
|
287
|
-
);
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
export function heartbeatSynapseSession(
|
|
291
|
-
sessionId,
|
|
292
|
-
partialMeta = {},
|
|
293
|
-
opts = {},
|
|
294
|
-
) {
|
|
295
|
-
// The live route reads `{ sessionId, partial }` (hub/server.mjs
|
|
296
|
-
// /synapse/heartbeat → synapseRegistry.heartbeat(sessionId, partial)), so the
|
|
297
|
-
// helper must nest the meta under `partial` rather than spreading it top-level.
|
|
298
|
-
return fireAndForgetSynapse(
|
|
299
|
-
"/synapse/heartbeat",
|
|
300
|
-
{
|
|
301
|
-
sessionId,
|
|
302
|
-
partial:
|
|
303
|
-
partialMeta && typeof partialMeta === "object" ? partialMeta : {},
|
|
304
|
-
},
|
|
305
|
-
opts,
|
|
306
|
-
);
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
export function unregisterSynapseSession(sessionId, opts = {}) {
|
|
310
|
-
return fireAndForgetSynapse("/synapse/unregister", { sessionId }, opts);
|
|
311
|
-
}
|
package/hub/team-bridge.mjs
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
// @triflux/core — team-bridge 인터페이스
|
|
2
|
-
// remote 패키지가 런타임에 구현을 주입한다.
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* @typedef {object} TeamBridge
|
|
6
|
-
* @property {(args?: object) => Promise<object>} teamInfo
|
|
7
|
-
* @property {(args?: object) => Promise<object>} teamTaskList
|
|
8
|
-
* @property {(args?: object) => Promise<object>} teamTaskUpdate
|
|
9
|
-
* @property {(args?: object) => Promise<object>} teamSendMessage
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
/** @type {TeamBridge | null} */
|
|
13
|
-
let _bridge = null;
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* @param {TeamBridge | null} impl
|
|
17
|
-
*/
|
|
18
|
-
export function registerTeamBridge(impl) {
|
|
19
|
-
_bridge = impl;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* @returns {TeamBridge | null}
|
|
24
|
-
*/
|
|
25
|
-
export function getTeamBridge() {
|
|
26
|
-
return _bridge;
|
|
27
|
-
}
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import { existsSync } from "node:fs";
|
|
2
|
-
import { homedir } from "node:os";
|
|
3
|
-
import { join, resolve } from "node:path";
|
|
4
|
-
|
|
5
|
-
export function findAllClaudeMdPaths(options = {}) {
|
|
6
|
-
const cwd = options.cwd ? resolve(options.cwd) : process.cwd();
|
|
7
|
-
const homeDir = options.homeDir ? resolve(options.homeDir) : homedir();
|
|
8
|
-
const includeGlobal = options.includeGlobal !== false;
|
|
9
|
-
const includeProject = options.includeProject !== false;
|
|
10
|
-
|
|
11
|
-
const candidates = [];
|
|
12
|
-
if (includeGlobal) candidates.push(join(homeDir, ".claude", "CLAUDE.md"));
|
|
13
|
-
if (includeProject) candidates.push(join(cwd, "CLAUDE.md"));
|
|
14
|
-
|
|
15
|
-
const seen = new Set();
|
|
16
|
-
const paths = [];
|
|
17
|
-
for (const candidate of candidates) {
|
|
18
|
-
const normalized = resolve(candidate);
|
|
19
|
-
if (seen.has(normalized)) continue;
|
|
20
|
-
seen.add(normalized);
|
|
21
|
-
if (existsSync(normalized)) {
|
|
22
|
-
paths.push(normalized);
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
return paths;
|
|
26
|
-
}
|
package/scripts/lib/context.mjs
DELETED
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 요청별 로그 컨텍스트 전파 (AsyncLocalStorage 기반).
|
|
3
|
-
*
|
|
4
|
-
* Hub HTTP 서버의 요청마다 correlationId를 자동 할당하여,
|
|
5
|
-
* 하나의 요청에서 발생한 모든 로그를 추적할 수 있다.
|
|
6
|
-
*
|
|
7
|
-
* 사용법:
|
|
8
|
-
* import { getCorrelationId, withRequestContext } from './lib/context.mjs';
|
|
9
|
-
*
|
|
10
|
-
* // 미들웨어에서 컨텍스트 생성
|
|
11
|
-
* withRequestContext({ method: 'POST', path: '/bridge/result' }, () => {
|
|
12
|
-
* const correlationId = getCorrelationId();
|
|
13
|
-
* });
|
|
14
|
-
*
|
|
15
|
-
*/
|
|
16
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
17
|
-
import { randomUUID } from "node:crypto";
|
|
18
|
-
|
|
19
|
-
import { logger } from "./logger.mjs";
|
|
20
|
-
|
|
21
|
-
/** @type {AsyncLocalStorage<{logger: import('pino').Logger, correlationId: string}>} */
|
|
22
|
-
const asyncLocalStorage = new AsyncLocalStorage();
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* 현재 요청의 상관 ID를 반환한다.
|
|
26
|
-
*
|
|
27
|
-
* @returns {string|undefined}
|
|
28
|
-
*/
|
|
29
|
-
export function getCorrelationId() {
|
|
30
|
-
return asyncLocalStorage.getStore()?.correlationId;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* 요청 컨텍스트를 생성하고 콜백을 실행한다.
|
|
35
|
-
*
|
|
36
|
-
* @param {object} context — 컨텍스트 필드 (method, path 등)
|
|
37
|
-
* @param {string} [context.correlationId] — 외부에서 전달된 상관 ID (없으면 자동 생성)
|
|
38
|
-
* @param {function} callback — 컨텍스트 내에서 실행할 함수
|
|
39
|
-
* @returns {*}
|
|
40
|
-
*/
|
|
41
|
-
export function withRequestContext(context, callback) {
|
|
42
|
-
const correlationId = context.correlationId || randomUUID();
|
|
43
|
-
const { correlationId: _, ...rest } = context;
|
|
44
|
-
|
|
45
|
-
const store = {
|
|
46
|
-
correlationId,
|
|
47
|
-
logger: logger.child({ correlationId, ...rest }),
|
|
48
|
-
};
|
|
49
|
-
|
|
50
|
-
return asyncLocalStorage.run(store, callback);
|
|
51
|
-
}
|
package/scripts/lib/handoff.mjs
DELETED
|
@@ -1,187 +0,0 @@
|
|
|
1
|
-
import { execSync } from "node:child_process";
|
|
2
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
-
import { basename, resolve } from "node:path";
|
|
4
|
-
import { findAllClaudeMdPaths } from "./claudemd-scanner.mjs";
|
|
5
|
-
|
|
6
|
-
function runCommand(command, cwd, executor = execSync) {
|
|
7
|
-
try {
|
|
8
|
-
const output = executor(command, {
|
|
9
|
-
cwd,
|
|
10
|
-
encoding: "utf8",
|
|
11
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
12
|
-
windowsHide: true,
|
|
13
|
-
});
|
|
14
|
-
return String(output || "").trimEnd();
|
|
15
|
-
} catch {
|
|
16
|
-
return "";
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function parseStatusLines(statusText) {
|
|
21
|
-
const lines = String(statusText || "")
|
|
22
|
-
.split(/\r?\n/u)
|
|
23
|
-
.filter(Boolean);
|
|
24
|
-
const changedFiles = [];
|
|
25
|
-
const status = [];
|
|
26
|
-
|
|
27
|
-
for (const line of lines) {
|
|
28
|
-
const normalized = line.trimEnd();
|
|
29
|
-
if (!normalized) continue;
|
|
30
|
-
|
|
31
|
-
const rawStatus = normalized.slice(0, 2).trim() || "??";
|
|
32
|
-
const rawPath = normalized.slice(3).trim();
|
|
33
|
-
const filePath = rawPath.includes(" -> ")
|
|
34
|
-
? rawPath.split(" -> ").at(-1)?.trim()
|
|
35
|
-
: rawPath;
|
|
36
|
-
if (!filePath) continue;
|
|
37
|
-
|
|
38
|
-
changedFiles.push(filePath);
|
|
39
|
-
status.push({ path: filePath, status: rawStatus });
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
return {
|
|
43
|
-
changedFiles: Array.from(new Set(changedFiles)),
|
|
44
|
-
status,
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function normalizeDecisionLine(line) {
|
|
49
|
-
return String(line || "")
|
|
50
|
-
.trim()
|
|
51
|
-
.replace(/^[-*]\s+/u, "")
|
|
52
|
-
.trim();
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function parseDecisionFile(decisionFile) {
|
|
56
|
-
if (!decisionFile) return [];
|
|
57
|
-
const absolute = resolve(decisionFile);
|
|
58
|
-
if (!existsSync(absolute)) return [];
|
|
59
|
-
|
|
60
|
-
const raw = readFileSync(absolute, "utf8");
|
|
61
|
-
return raw
|
|
62
|
-
.split(/\r?\n/u)
|
|
63
|
-
.map(normalizeDecisionLine)
|
|
64
|
-
.filter((line) => line.length > 0);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function normalizeDecisions(decisions, decisionFile) {
|
|
68
|
-
const merged = [
|
|
69
|
-
...(Array.isArray(decisions) ? decisions : []),
|
|
70
|
-
...parseDecisionFile(decisionFile),
|
|
71
|
-
]
|
|
72
|
-
.map(normalizeDecisionLine)
|
|
73
|
-
.filter(Boolean);
|
|
74
|
-
|
|
75
|
-
return Array.from(new Set(merged));
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
function formatAheadBehind(value) {
|
|
79
|
-
if (!value) return null;
|
|
80
|
-
const [behindRaw, aheadRaw] = value.split(/\s+/u);
|
|
81
|
-
const behind = Number.parseInt(behindRaw, 10);
|
|
82
|
-
const ahead = Number.parseInt(aheadRaw, 10);
|
|
83
|
-
if (!Number.isFinite(behind) || !Number.isFinite(ahead)) return null;
|
|
84
|
-
return { ahead, behind };
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
export function collectHandoffContext(options = {}) {
|
|
88
|
-
const cwd = resolve(options.cwd || process.cwd());
|
|
89
|
-
const executor =
|
|
90
|
-
typeof options.commandRunner === "function"
|
|
91
|
-
? options.commandRunner
|
|
92
|
-
: execSync;
|
|
93
|
-
const target = options.target === "local" ? "local" : "remote";
|
|
94
|
-
const decisions = normalizeDecisions(options.decisions, options.decisionFile);
|
|
95
|
-
const generatedAt = options.generatedAt || new Date().toISOString();
|
|
96
|
-
const claudeMdPaths = Array.isArray(options.claudeMdPaths)
|
|
97
|
-
? options.claudeMdPaths
|
|
98
|
-
: findAllClaudeMdPaths({
|
|
99
|
-
cwd,
|
|
100
|
-
homeDir: options.homeDir,
|
|
101
|
-
});
|
|
102
|
-
|
|
103
|
-
const gitRoot = runCommand("git rev-parse --show-toplevel", cwd, executor);
|
|
104
|
-
const branch =
|
|
105
|
-
runCommand("git rev-parse --abbrev-ref HEAD", cwd, executor) || null;
|
|
106
|
-
const shortStatus = runCommand("git status --short", cwd, executor);
|
|
107
|
-
const diffStat = runCommand("git diff --stat --no-color", cwd, executor);
|
|
108
|
-
const upstreamRaw = runCommand(
|
|
109
|
-
"git rev-list --left-right --count @{upstream}...HEAD",
|
|
110
|
-
cwd,
|
|
111
|
-
executor,
|
|
112
|
-
);
|
|
113
|
-
const parsedStatus = parseStatusLines(shortStatus);
|
|
114
|
-
|
|
115
|
-
return {
|
|
116
|
-
generatedAt,
|
|
117
|
-
target,
|
|
118
|
-
cwd,
|
|
119
|
-
gitRoot: gitRoot || null,
|
|
120
|
-
repository: gitRoot ? basename(gitRoot) : basename(cwd),
|
|
121
|
-
branch,
|
|
122
|
-
upstream: formatAheadBehind(upstreamRaw),
|
|
123
|
-
changedFiles: parsedStatus.changedFiles,
|
|
124
|
-
fileStatus: parsedStatus.status,
|
|
125
|
-
diffStat,
|
|
126
|
-
decisions,
|
|
127
|
-
claudeMdPaths,
|
|
128
|
-
};
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export function buildHandoffPrompt(context) {
|
|
132
|
-
const safeContext = context || collectHandoffContext();
|
|
133
|
-
const branch = safeContext.branch || "unknown";
|
|
134
|
-
const upstream = safeContext.upstream
|
|
135
|
-
? `ahead ${safeContext.upstream.ahead}, behind ${safeContext.upstream.behind}`
|
|
136
|
-
: "unknown";
|
|
137
|
-
const changedFiles =
|
|
138
|
-
safeContext.changedFiles.length > 0
|
|
139
|
-
? safeContext.changedFiles.map((file) => `- ${file}`).join("\n")
|
|
140
|
-
: "- 변경 파일 없음";
|
|
141
|
-
const decisions =
|
|
142
|
-
safeContext.decisions.length > 0
|
|
143
|
-
? safeContext.decisions.map((decision) => `- ${decision}`).join("\n")
|
|
144
|
-
: "- 명시된 결정사항 없음";
|
|
145
|
-
const claudeMdList =
|
|
146
|
-
Array.isArray(safeContext.claudeMdPaths) &&
|
|
147
|
-
safeContext.claudeMdPaths.length > 0
|
|
148
|
-
? safeContext.claudeMdPaths.map((path) => `- ${path}`).join("\n")
|
|
149
|
-
: "- 자동 탐지된 CLAUDE.md 없음";
|
|
150
|
-
const diffStat = safeContext.diffStat || "(diff stat 없음)";
|
|
151
|
-
|
|
152
|
-
return [
|
|
153
|
-
"## TFX Remote Handoff",
|
|
154
|
-
`- generated_at: ${safeContext.generatedAt}`,
|
|
155
|
-
`- target: ${safeContext.target}`,
|
|
156
|
-
`- repository: ${safeContext.repository}`,
|
|
157
|
-
`- branch: ${branch} (${upstream})`,
|
|
158
|
-
`- cwd: ${safeContext.cwd}`,
|
|
159
|
-
"",
|
|
160
|
-
"### 변경 파일",
|
|
161
|
-
changedFiles,
|
|
162
|
-
"",
|
|
163
|
-
"### 변경 요약 (git diff --stat)",
|
|
164
|
-
"```",
|
|
165
|
-
diffStat,
|
|
166
|
-
"```",
|
|
167
|
-
"",
|
|
168
|
-
"### 결정사항",
|
|
169
|
-
decisions,
|
|
170
|
-
"",
|
|
171
|
-
"### CLAUDE.md 참조",
|
|
172
|
-
claudeMdList,
|
|
173
|
-
"",
|
|
174
|
-
"### 다음 세션 지시",
|
|
175
|
-
"- 위 변경사항을 먼저 검토하고 누락된 테스트를 확인하세요.",
|
|
176
|
-
"- 필요 시 CLAUDE.md 지침을 재확인한 뒤 작업을 이어가세요.",
|
|
177
|
-
"- 작업 완료 후 변경 파일과 검증 결과를 요약하세요.",
|
|
178
|
-
].join("\n");
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
export function serializeHandoff(options = {}) {
|
|
182
|
-
const context = collectHandoffContext(options);
|
|
183
|
-
return {
|
|
184
|
-
...context,
|
|
185
|
-
prompt: buildHandoffPrompt(context),
|
|
186
|
-
};
|
|
187
|
-
}
|