@triflux/core 10.1.0 → 10.26.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 (145) hide show
  1. package/hooks/agent-route-guard.mjs +14 -10
  2. package/hooks/cross-review-tracker.mjs +21 -8
  3. package/hooks/error-context.mjs +20 -8
  4. package/hooks/hook-adaptive-collector.mjs +18 -16
  5. package/hooks/hook-manager.mjs +93 -32
  6. package/hooks/hook-orchestrator.mjs +267 -35
  7. package/hooks/hook-registry.json +343 -256
  8. package/hooks/hooks.json +49 -1
  9. package/hooks/keyword-rules.json +191 -31
  10. package/hooks/lib/resolve-root.mjs +1 -1
  11. package/hooks/mcp-config-watcher.mjs +6 -2
  12. package/hooks/permission-safe-allow.mjs +233 -0
  13. package/hooks/pipeline-stop.mjs +369 -22
  14. package/hooks/post-tool-tips.mjs +306 -0
  15. package/hooks/pre-compact-snapshot.mjs +181 -0
  16. package/hooks/safety-guard.mjs +262 -34
  17. package/hooks/session-end-cleanup.mjs +345 -0
  18. package/hooks/session-start-fast.mjs +214 -0
  19. package/hooks/subagent-tracker.mjs +267 -0
  20. package/hooks/subagent-verifier.mjs +9 -4
  21. package/hub/account-broker.mjs +1036 -66
  22. package/hub/adaptive-diagnostic.mjs +75 -48
  23. package/hub/adaptive-inject.mjs +96 -58
  24. package/hub/adaptive-memory.mjs +156 -42
  25. package/hub/adaptive.mjs +60 -31
  26. package/hub/assign-callbacks.mjs +163 -126
  27. package/hub/bridge.mjs +1051 -290
  28. package/hub/cli-adapter-base.mjs +321 -97
  29. package/hub/codex-adapter.mjs +179 -93
  30. package/hub/codex-compat.mjs +4 -4
  31. package/hub/codex-preflight.mjs +113 -37
  32. package/hub/delegator/contracts.mjs +22 -21
  33. package/hub/delegator/index.mjs +14 -14
  34. package/hub/delegator/schema/delegator-tools.schema.json +1 -1
  35. package/hub/delegator/service.mjs +93 -64
  36. package/hub/delegator/tool-definitions.mjs +35 -35
  37. package/hub/dynamic-routing-engine.mjs +511 -0
  38. package/hub/fullcycle.mjs +34 -18
  39. package/hub/gemini-adapter.mjs +82 -108
  40. package/hub/hitl.mjs +202 -143
  41. package/hub/intent.mjs +167 -38
  42. package/hub/lib/bash-path.mjs +73 -0
  43. package/hub/lib/cache-guard.mjs +43 -17
  44. package/hub/lib/env-detect.mjs +145 -0
  45. package/hub/lib/hosts-compat.mjs +319 -0
  46. package/hub/lib/mcp-response-cache.mjs +239 -0
  47. package/hub/lib/memory-store.mjs +285 -111
  48. package/hub/lib/path-utils.mjs +165 -0
  49. package/hub/lib/phase-manager.mjs +493 -0
  50. package/hub/lib/process-utils.mjs +797 -104
  51. package/hub/lib/prompt-tmp.mjs +33 -0
  52. package/hub/lib/risk-tier.mjs +53 -0
  53. package/hub/lib/spawn-trace.mjs +561 -0
  54. package/hub/lib/ssh-command.mjs +44 -24
  55. package/hub/lib/ssh-retry.mjs +5 -1
  56. package/hub/lib/staged-file-detect.mjs +43 -0
  57. package/hub/lib/state-snapshot.mjs +293 -0
  58. package/hub/lib/tfx-route-args.mjs +309 -0
  59. package/hub/lib/timeline-adapter.mjs +190 -0
  60. package/hub/lib/trace-recorder.mjs +153 -0
  61. package/hub/lib/uuidv7.mjs +4 -3
  62. package/hub/memory-doctor.mjs +266 -106
  63. package/hub/middleware/quota-middleware.mjs +70 -0
  64. package/hub/middleware/request-logger.mjs +61 -34
  65. package/hub/paths.mjs +9 -9
  66. package/hub/pipeline/gates/confidence.mjs +34 -15
  67. package/hub/pipeline/gates/consensus.mjs +27 -15
  68. package/hub/pipeline/gates/index.mjs +7 -3
  69. package/hub/pipeline/gates/selfcheck.mjs +57 -19
  70. package/hub/pipeline/index.mjs +77 -42
  71. package/hub/pipeline/state.mjs +10 -10
  72. package/hub/pipeline/transitions.mjs +40 -23
  73. package/hub/platform.mjs +65 -48
  74. package/hub/quality/deslop.mjs +70 -49
  75. package/hub/reflexion.mjs +87 -13
  76. package/hub/research.mjs +33 -25
  77. package/hub/router.mjs +941 -791
  78. package/hub/routing/complexity.mjs +132 -29
  79. package/hub/routing/index.mjs +17 -12
  80. package/hub/routing/q-learning.mjs +78 -30
  81. package/hub/routing-snapshot.mjs +261 -0
  82. package/hub/session-fingerprint.mjs +127 -61
  83. package/hub/state.mjs +86 -44
  84. package/hub/team/claude-daemon-control.mjs +1130 -0
  85. package/hub/team/retry-state-machine.mjs +336 -0
  86. package/hub/token-mode.mjs +72 -71
  87. package/hub/workers/worker-utils.mjs +23 -17
  88. package/hud/colors.mjs +27 -9
  89. package/hud/constants.mjs +190 -27
  90. package/hud/context-monitor.mjs +133 -44
  91. package/hud/hud-qos-status.mjs +157 -50
  92. package/hud/mission-board.mjs +56 -0
  93. package/hud/providers/claude.mjs +398 -114
  94. package/hud/providers/codex.mjs +96 -21
  95. package/hud/providers/gemini.mjs +210 -52
  96. package/hud/renderers.mjs +440 -127
  97. package/hud/terminal.mjs +101 -31
  98. package/hud/utils.mjs +81 -39
  99. package/mesh/index.mjs +69 -0
  100. package/mesh/mesh-budget.mjs +137 -0
  101. package/mesh/mesh-heartbeat.mjs +100 -0
  102. package/mesh/mesh-protocol.mjs +96 -0
  103. package/mesh/mesh-queue.mjs +163 -0
  104. package/mesh/mesh-registry.mjs +78 -0
  105. package/mesh/mesh-router.mjs +77 -0
  106. package/package.json +5 -1
  107. package/scripts/lib/agent-json.mjs +27 -0
  108. package/scripts/lib/async.mjs +174 -0
  109. package/scripts/lib/claudemd-scanner.mjs +6 -1
  110. package/scripts/lib/cli-agy.mjs +62 -0
  111. package/scripts/lib/cli-claude.mjs +78 -0
  112. package/scripts/lib/cli-codex.mjs +199 -0
  113. package/scripts/lib/cli-gemini.mjs +37 -0
  114. package/scripts/lib/codex-recovery.sh +50 -0
  115. package/scripts/lib/context.mjs +3 -3
  116. package/scripts/lib/cross-review-utils.mjs +13 -5
  117. package/scripts/lib/doctor-env-checks.mjs +121 -0
  118. package/scripts/lib/dynamic-route-cli.mjs +107 -0
  119. package/scripts/lib/env-probe.mjs +58 -30
  120. package/scripts/lib/env.mjs +14 -0
  121. package/scripts/lib/gemini-profiles.mjs +44 -10
  122. package/scripts/lib/handoff.mjs +33 -17
  123. package/scripts/lib/hook-utils.mjs +8 -6
  124. package/scripts/lib/hub.mjs +48 -0
  125. package/scripts/lib/keyword-rules.mjs +49 -20
  126. package/scripts/lib/logger.mjs +24 -24
  127. package/scripts/lib/mcp-filter.mjs +391 -247
  128. package/scripts/lib/mcp-gateway-health-check.mjs +159 -0
  129. package/scripts/lib/mcp-gateway-servers.mjs +70 -0
  130. package/scripts/lib/mcp-gateway-wrapper-check.mjs +35 -0
  131. package/scripts/lib/mcp-guard-engine.mjs +1281 -115
  132. package/scripts/lib/mcp-health.mjs +773 -0
  133. package/scripts/lib/mcp-manifest.mjs +24 -14
  134. package/scripts/lib/mcp-server-catalog.mjs +355 -118
  135. package/scripts/lib/pid.mjs +63 -0
  136. package/scripts/lib/process-utils.mjs +26 -0
  137. package/scripts/lib/psmux-info.mjs +117 -12
  138. package/scripts/lib/quota.mjs +47 -0
  139. package/scripts/lib/remote-spawn-transfer.mjs +44 -14
  140. package/scripts/lib/skill-state.mjs +220 -0
  141. package/scripts/lib/skill-template.mjs +32 -7
  142. package/scripts/lib/team.mjs +75 -0
  143. package/scripts/lib/timeout.mjs +66 -0
  144. package/scripts/lib/tmp.mjs +26 -0
  145. package/scripts/lib/toml.mjs +113 -0
@@ -0,0 +1,511 @@
1
+ // hub/dynamic-routing-engine.mjs
2
+ //
3
+ // PRD: .omx/plans/prd-dynamic-routing-engine.md
4
+ //
5
+ // Phase 0 — pure deterministic classifier. Takes a `request`, a `snapshot`
6
+ // (from `hub/routing-snapshot.mjs`), and a `policy` (loaded from
7
+ // `config/routing-policy.json`), then emits a single `RouteDecision`.
8
+ //
9
+ // Phase 0 contract:
10
+ // - no callers yet (dormant). conductor/swarm/tfx-route.sh integration is Phase 1+.
11
+ // - pure function: same (request, snapshot, policy) → same RouteDecision.
12
+ // - no network, no disk reads, no clock reads outside the explicit `now` arg.
13
+ // - fallback policy = codex-default. fails closed.
14
+ // - scenario evaluators are first-match-wins in policy.scenarios order.
15
+
16
+ import { createHash } from "node:crypto";
17
+ import { readFileSync } from "node:fs";
18
+ import { dirname, join } from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+
21
+ import { buildRoutingSnapshot } from "./routing-snapshot.mjs";
22
+
23
+ function stableStringify(obj) {
24
+ if (obj === null || typeof obj !== "object") return JSON.stringify(obj);
25
+ if (Array.isArray(obj)) return `[${obj.map(stableStringify).join(",")}]`;
26
+ const keys = Object.keys(obj).sort();
27
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(",")}}`;
28
+ }
29
+
30
+ function hashInputs(request, snapshot) {
31
+ return createHash("sha256")
32
+ .update(stableStringify({ request, snapshot }))
33
+ .digest("hex")
34
+ .slice(0, 16);
35
+ }
36
+
37
+ function makeFallback(policy, trigger, inputsHash, now) {
38
+ const fb = policy?.fallback ?? {};
39
+ return {
40
+ decisionId: inputsHash,
41
+ mode: fb.default_mode ?? "codex-default",
42
+ scenario: "fallback",
43
+ lane: "single",
44
+ shards: [
45
+ {
46
+ cli: fb.default_cli ?? "codex",
47
+ accountId: null,
48
+ model: fb.default_model ?? "gpt-5.5",
49
+ riskTier: "safe",
50
+ reason: trigger,
51
+ },
52
+ ],
53
+ rationale: {
54
+ inputsHash,
55
+ biasScore: null,
56
+ alternatives: [],
57
+ },
58
+ fallback: { trigger, action: "codex-default" },
59
+ snapshotAgeMs: snapshotAge(undefined, now),
60
+ confidence: 50,
61
+ };
62
+ }
63
+
64
+ function snapshotAge(snapshot, now) {
65
+ if (!snapshot || typeof snapshot !== "object") return null;
66
+ const observed = Number(snapshot.observedAt);
67
+ if (!Number.isFinite(observed)) return null;
68
+ return Math.max(0, now - observed);
69
+ }
70
+
71
+ function checkFreshness(snapshot, freshness, now) {
72
+ if (!snapshot) return "hud_null";
73
+ const max = freshness?.max_snapshot_age_ms ?? 900_000;
74
+ const skewMax = freshness?.max_cross_provider_skew_ms ?? 300_000;
75
+
76
+ const claude = snapshot.claude;
77
+ const codex = snapshot.codex;
78
+ if (!claude && !codex) return "hud_null";
79
+ if (claude && (claude.isStale || claude.error))
80
+ return "claude_stale_or_error";
81
+ if (codex && (codex.isStale || codex.error)) return "codex_stale_or_error";
82
+
83
+ const claudeAge = claude?.observedAt ? now - claude.observedAt : null;
84
+ const codexAge = codex?.observedAt ? now - codex.observedAt : null;
85
+ if (claudeAge !== null && claudeAge > max) return "claude_age_exceeded";
86
+ if (codexAge !== null && codexAge > max) return "codex_age_exceeded";
87
+ if (claudeAge !== null && codexAge !== null) {
88
+ if (Math.abs(claudeAge - codexAge) > skewMax)
89
+ return "cross_provider_skew_exceeded";
90
+ }
91
+
92
+ if (claude?.weeklyResetsAt !== null && claude?.weeklyResetsAt !== undefined) {
93
+ if (
94
+ claude.weeklyResetsAt <
95
+ now - (freshness?.local_clock_skew_guard_ms ?? 60_000)
96
+ ) {
97
+ return "claude_weekly_reset_in_past";
98
+ }
99
+ }
100
+
101
+ return null;
102
+ }
103
+
104
+ function brokerAvailableCount(snapshot, provider) {
105
+ const accounts = snapshot?.broker?.[provider] ?? [];
106
+ return accounts.filter((a) => a.circuitState !== "open").length;
107
+ }
108
+
109
+ function brokerAllCircuitsOpen(snapshot) {
110
+ const groups = snapshot?.broker;
111
+ if (!groups) return false;
112
+ const all = [];
113
+ for (const provider of Object.keys(groups)) {
114
+ for (const acct of groups[provider] ?? []) all.push(acct);
115
+ }
116
+ if (all.length === 0) return true;
117
+ return all.every((a) => a.circuitState === "open");
118
+ }
119
+
120
+ // ─── Scenario evaluators ──────────────────────────────────────────────
121
+ // Each returns either null (no match) or a partial RouteDecision payload
122
+ // `{ scenario, lane, shards, riskTier?, reasonCodes }` to be wrapped by
123
+ // `makeScenarioDecision()` below.
124
+
125
+ function evalS1(ctx) {
126
+ const { snapshot, scenario, policy, now } = ctx;
127
+ const claude = snapshot.claude;
128
+ if (!claude) return null;
129
+ const resetIn = (claude.weeklyResetsAt ?? Number.POSITIVE_INFINITY) - now;
130
+ if (
131
+ resetIn >
132
+ (scenario.when.weeklyResetsAtLteMs ?? policy.thresholds.reset_imminent_ms)
133
+ )
134
+ return null;
135
+ if ((claude.weeklyPercent ?? 100) >= (scenario.when.weeklyPercentLt ?? 100))
136
+ return null;
137
+ if (
138
+ scenario.when.hasMultipleAccounts &&
139
+ brokerAvailableCount(snapshot, "claude") < 2
140
+ )
141
+ return null;
142
+ return {
143
+ lane: scenario.then.lane ?? "multi",
144
+ shards: [
145
+ { cli: "claude", riskTier: "stretch", reason: scenario.then.reason },
146
+ ],
147
+ };
148
+ }
149
+
150
+ function evalS2(ctx) {
151
+ const { snapshot, scenario, policy, now } = ctx;
152
+ const codex = snapshot.codex;
153
+ if (!codex) return null;
154
+ const buckets = codex.buckets ?? {};
155
+ const window =
156
+ scenario.when.weeklyResetsAtLteMs ?? policy.thresholds.reset_imminent_ms;
157
+ const usageCeiling = scenario.when.weeklyPercentLt ?? 100;
158
+ // Inspect both primary and secondary legs so a fresh secondary tier with
159
+ // imminent reset is not silently ignored when primary is exhausted.
160
+ const anyLegMatches = Object.values(buckets).some((b) =>
161
+ [b?.primary, b?.secondary].some((leg) => {
162
+ if (!leg) return false;
163
+ if (!leg.resetsAt) return false;
164
+ if (leg.resetsAt - now > window) return false;
165
+ return (leg.usedPercent ?? 100) < usageCeiling;
166
+ }),
167
+ );
168
+ if (!anyLegMatches) return null;
169
+ return {
170
+ lane: scenario.then.lane ?? "swarm",
171
+ shards: [
172
+ { cli: "codex", riskTier: "stretch", reason: scenario.then.reason },
173
+ ],
174
+ };
175
+ }
176
+
177
+ function evalS3(ctx) {
178
+ const { snapshot, scenario, now } = ctx;
179
+ const claude = snapshot.claude;
180
+ const codex = snapshot.codex;
181
+ if (!claude || !codex) return null;
182
+ if ((claude.weeklyPercent ?? 0) < scenario.when.claude_weekly_percent_gte)
183
+ return null;
184
+ const codexAnyBucket = Object.values(codex.buckets ?? {}).some(
185
+ (b) =>
186
+ (b?.primary?.usedPercent ?? 100) < scenario.when.codex_weekly_percent_lt,
187
+ );
188
+ if (!codexAnyBucket) return null;
189
+ const resetIn = (claude.weeklyResetsAt ?? 0) - now;
190
+ if (resetIn <= scenario.when.claude_weekly_resets_at_gt_ms) return null;
191
+ return {
192
+ lane: scenario.then.lane ?? "single",
193
+ shards: [{ cli: "codex", riskTier: "safe", reason: scenario.then.reason }],
194
+ };
195
+ }
196
+
197
+ function evalS4(ctx) {
198
+ const { snapshot, scenario } = ctx;
199
+ const claude = snapshot.broker?.claude ?? [];
200
+ if (claude.length < (scenario.when.accountCountGte ?? 2)) return null;
201
+ // Staggered = at least 2 distinct cooldown/expiresAt anchors.
202
+ const anchors = new Set(
203
+ claude.map((a) => `${a.cooldownUntil ?? 0}-${a.expiresAt ?? 0}`),
204
+ );
205
+ if (scenario.when.staggered && anchors.size < 2) return null;
206
+ return {
207
+ lane: scenario.then.lane ?? "multi",
208
+ shards: claude.map((a) => ({
209
+ cli: "claude",
210
+ accountId: a.id,
211
+ riskTier: "stretch",
212
+ reason: scenario.then.reason,
213
+ })),
214
+ };
215
+ }
216
+
217
+ function evalS5(ctx) {
218
+ const { request, snapshot, scenario } = ctx;
219
+ if ((request?.team_size ?? 1) < (scenario.when.request_team_size_gte ?? 2))
220
+ return null;
221
+ const claude = snapshot.broker?.claude ?? [];
222
+ if (claude.length < (scenario.when.accountCountGte ?? 2)) return null;
223
+ const wanted = Math.min(request.team_size, claude.length);
224
+ return {
225
+ lane: scenario.then.lane ?? "swarm",
226
+ atomic: scenario.then.atomic,
227
+ atomicPolicy: scenario.then.atomic_policy ?? "balanced",
228
+ shards: claude.slice(0, wanted).map((a) => ({
229
+ cli: "claude",
230
+ accountId: a.id,
231
+ riskTier: "stretch",
232
+ reason: scenario.then.reason,
233
+ })),
234
+ };
235
+ }
236
+
237
+ function evalS6(ctx) {
238
+ const { snapshot, scenario, now } = ctx;
239
+ const all = [];
240
+ for (const p of Object.keys(snapshot.broker ?? {})) {
241
+ const accounts = snapshot.broker[p];
242
+ if (!Array.isArray(accounts)) continue;
243
+ for (const a of accounts) all.push({ ...a, provider: p });
244
+ }
245
+ const window = scenario.when.expiresAtLteMs ?? 604_800_000;
246
+ const usageCeiling = scenario.when.weeklyPercentLt ?? null;
247
+ const expiring = all.filter((a) => {
248
+ if (!a.expiresAt) return false;
249
+ // Past-dated expirations are dead accounts, not drain targets.
250
+ if (a.expiresAt - now <= 0) return false;
251
+ if (a.expiresAt - now > window) return false;
252
+ if (scenario.when.circuitStateNotOpen && a.circuitState === "open")
253
+ return false;
254
+ if (usageCeiling !== null) {
255
+ const usage = providerUsagePercent(snapshot, a.provider);
256
+ if (usage !== null && usage >= usageCeiling) return false;
257
+ }
258
+ return true;
259
+ });
260
+ if (expiring.length === 0) return null;
261
+ return {
262
+ lane: scenario.then.lane ?? "single",
263
+ riskTier: scenario.then.riskTier ?? "drain",
264
+ shards: expiring.map((a) => ({
265
+ cli: a.provider === "claude" ? "claude" : "codex",
266
+ accountId: a.id,
267
+ riskTier: "drain",
268
+ reason: scenario.then.reason,
269
+ })),
270
+ };
271
+ }
272
+
273
+ function providerUsagePercent(snapshot, provider) {
274
+ if (provider === "claude") {
275
+ return typeof snapshot.claude?.weeklyPercent === "number"
276
+ ? snapshot.claude.weeklyPercent
277
+ : null;
278
+ }
279
+ if (provider === "codex") {
280
+ const buckets = Object.values(snapshot.codex?.buckets ?? {});
281
+ if (buckets.length === 0) return null;
282
+ let max = 0;
283
+ for (const b of buckets) {
284
+ for (const leg of [b?.primary, b?.secondary]) {
285
+ if (typeof leg?.usedPercent === "number" && leg.usedPercent > max) {
286
+ max = leg.usedPercent;
287
+ }
288
+ }
289
+ }
290
+ return max;
291
+ }
292
+ return null;
293
+ }
294
+
295
+ const SCENARIO_EVALUATORS = {
296
+ S1: evalS1,
297
+ S2: evalS2,
298
+ S3: evalS3,
299
+ S4: evalS4,
300
+ S5: evalS5,
301
+ S6: evalS6,
302
+ };
303
+
304
+ function makeScenarioDecision({ match, scenario, inputsHash, snapshot, now }) {
305
+ return {
306
+ decisionId: inputsHash,
307
+ mode: "dynamic-overlay",
308
+ scenario: scenario.id,
309
+ lane: match.lane,
310
+ shards: match.shards,
311
+ atomic: match.atomic ?? null,
312
+ atomicPolicy: match.atomicPolicy ?? null,
313
+ rationale: {
314
+ inputsHash,
315
+ biasScore: null,
316
+ alternatives: [],
317
+ scenarioName: scenario.name,
318
+ },
319
+ fallback: { trigger: null, action: "codex-default" },
320
+ snapshotAgeMs: snapshotAge(snapshot, now),
321
+ confidence: 72,
322
+ };
323
+ }
324
+
325
+ function brokerIsEmpty(snapshot) {
326
+ const groups = snapshot?.broker;
327
+ if (!groups || typeof groups !== "object") return true;
328
+ for (const p of Object.keys(groups)) {
329
+ const accounts = groups[p];
330
+ if (Array.isArray(accounts) && accounts.length > 0) return false;
331
+ }
332
+ return true;
333
+ }
334
+
335
+ /**
336
+ * @param {object} request
337
+ * @param {object} snapshot
338
+ * @param {object} policy
339
+ * @param {object} options
340
+ * @param {number} options.now — REQUIRED. Pure-fn contract: callers must
341
+ * supply the current epoch; the engine itself never reads the clock.
342
+ */
343
+ export function evaluateDynamicRoute(request, snapshot, policy, options) {
344
+ if (!options || typeof options.now !== "number") {
345
+ throw new TypeError(
346
+ "evaluateDynamicRoute: options.now (epoch ms) is required for pure-fn contract",
347
+ );
348
+ }
349
+ const { now } = options;
350
+ const inputsHash = hashInputs(request, snapshot);
351
+
352
+ if (!policy || !Array.isArray(policy.scenarios)) {
353
+ return makeFallback(
354
+ { fallback: { default_mode: "codex-default" } },
355
+ "policy_missing",
356
+ inputsHash,
357
+ now,
358
+ );
359
+ }
360
+
361
+ const freshnessVeto = checkFreshness(snapshot, policy.freshness, now);
362
+ if (freshnessVeto)
363
+ return makeFallback(policy, freshnessVeto, inputsHash, now);
364
+
365
+ if (brokerIsEmpty(snapshot)) {
366
+ return makeFallback(policy, "broker_empty", inputsHash, now);
367
+ }
368
+
369
+ if (brokerAllCircuitsOpen(snapshot)) {
370
+ return makeFallback(policy, "all_circuits_open", inputsHash, now);
371
+ }
372
+
373
+ for (const scenario of policy.scenarios) {
374
+ const evaluator = SCENARIO_EVALUATORS[scenario.id];
375
+ if (!evaluator) continue;
376
+ const match = evaluator({
377
+ request: request ?? {},
378
+ snapshot,
379
+ scenario,
380
+ policy,
381
+ now,
382
+ });
383
+ if (match)
384
+ return makeScenarioDecision({
385
+ match,
386
+ scenario,
387
+ inputsHash,
388
+ snapshot,
389
+ now,
390
+ });
391
+ }
392
+
393
+ return makeFallback(policy, "no_scenario_matched", inputsHash, now);
394
+ }
395
+
396
+ // ─── Phase 1 — caller-friendly facade ─────────────────────────────────
397
+ //
398
+ // Phase 0 keeps `evaluateDynamicRoute()` pure. Callers (conductor,
399
+ // swarm-hypervisor, tfx-route.sh) would otherwise duplicate the same
400
+ // plumbing: snapshot build + policy load + clock read. The facade below
401
+ // folds that plumbing into a single factory with opt-in env gating.
402
+ //
403
+ // Contract:
404
+ // - `evaluateDynamicRoute()` pure-fn signature is preserved unchanged.
405
+ // - `createDynamicRouter()` returns a router whose `routeRequest()` is
406
+ // a `null-router` (always emits the fallback decision) unless the
407
+ // opt-in `TRIFLUX_DYNAMIC_ROUTING` env flag is set.
408
+ // - Callers can inject `policy`, `snapshot`, `snapshotProvider`, `nowFn`
409
+ // for deterministic testing without touching disk or HUD providers.
410
+
411
+ const DEFAULT_POLICY_PATH = join(
412
+ dirname(fileURLToPath(import.meta.url)),
413
+ "..",
414
+ "config",
415
+ "routing-policy.json",
416
+ );
417
+
418
+ export function isDynamicRoutingEnabled(env = process.env) {
419
+ const flag = env.TRIFLUX_DYNAMIC_ROUTING;
420
+ return flag === "1" || flag === "true";
421
+ }
422
+
423
+ function loadPolicy(policyPath = DEFAULT_POLICY_PATH) {
424
+ // Missing/invalid policy → null. evaluateDynamicRoute() will then fall
425
+ // back to codex-default, which is the documented fail-closed behaviour.
426
+ try {
427
+ const raw = readFileSync(policyPath, "utf8");
428
+ return JSON.parse(raw);
429
+ } catch {
430
+ return null;
431
+ }
432
+ }
433
+
434
+ /**
435
+ * Caller-friendly factory. Works with zero arguments — defaults to
436
+ * `process.env`, the production `routing-policy.json`, and a snapshot
437
+ * provider that calls `buildRoutingSnapshot()`. Opt-in env-gated:
438
+ * `TRIFLUX_DYNAMIC_ROUTING=1|true` enables scenario evaluation; anything
439
+ * else returns a null-router that always emits the fallback decision.
440
+ *
441
+ * @param {object} [opts]
442
+ * @param {string} [opts.policyPath] — override the policy file path.
443
+ * @param {object} [opts.policy] — inject a policy object directly (testing).
444
+ * @param {(args:{forceRefresh:boolean, now:number}) => Promise<object>} [opts.snapshotProvider]
445
+ * @param {NodeJS.ProcessEnv} [opts.env] — override env (testing).
446
+ * @param {() => number} [opts.nowFn] — override clock (testing).
447
+ */
448
+ export function createDynamicRouter(opts = {}) {
449
+ const env = opts.env || process.env;
450
+ const enabled = isDynamicRoutingEnabled(env);
451
+ const policy =
452
+ opts.policy !== undefined
453
+ ? opts.policy
454
+ : enabled
455
+ ? loadPolicy(opts.policyPath)
456
+ : null;
457
+ const snapshotProvider =
458
+ opts.snapshotProvider ||
459
+ (async ({ forceRefresh, now }) =>
460
+ buildRoutingSnapshot({ forceRefresh, now }));
461
+ const nowFn = opts.nowFn || (() => Date.now());
462
+
463
+ return {
464
+ enabled,
465
+ /**
466
+ * @param {object} request
467
+ * @param {{ snapshot?: object, now?: number, forceRefresh?: boolean }} [callOpts]
468
+ * @returns {Promise<object>} RouteDecision
469
+ */
470
+ async routeRequest(request, callOpts = {}) {
471
+ const now = typeof callOpts.now === "number" ? callOpts.now : nowFn();
472
+ if (!enabled) {
473
+ // null-router: opt-in env absent → always fallback decision.
474
+ return evaluateDynamicRoute(request, {}, null, { now });
475
+ }
476
+ const snapshot =
477
+ callOpts.snapshot !== undefined
478
+ ? callOpts.snapshot
479
+ : await snapshotProvider({
480
+ forceRefresh: Boolean(callOpts.forceRefresh),
481
+ now,
482
+ });
483
+ return evaluateDynamicRoute(request, snapshot, policy, { now });
484
+ },
485
+ getPolicy() {
486
+ return policy;
487
+ },
488
+ };
489
+ }
490
+
491
+ /**
492
+ * Top-level convenience. Equivalent to
493
+ * `createDynamicRouter(opts).routeRequest(request, opts)`.
494
+ */
495
+ export async function routeRequest(request, opts = {}) {
496
+ const router = createDynamicRouter(opts);
497
+ return router.routeRequest(request, opts);
498
+ }
499
+
500
+ export const __internal__ = {
501
+ hashInputs,
502
+ checkFreshness,
503
+ brokerAvailableCount,
504
+ brokerAllCircuitsOpen,
505
+ brokerIsEmpty,
506
+ providerUsagePercent,
507
+ SCENARIO_EVALUATORS,
508
+ loadPolicy,
509
+ isDynamicRoutingEnabled,
510
+ DEFAULT_POLICY_PATH,
511
+ };
package/hub/fullcycle.mjs CHANGED
@@ -1,25 +1,32 @@
1
1
  // hub/fullcycle.mjs — tfx-fullcycle runtime artifact/state helpers
2
2
 
3
- import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
4
- import { join, resolve } from 'node:path';
5
- import { ensureTfxDirs, TFX_FULLCYCLE_DIR, TFX_PLANS_DIR } from './paths.mjs';
3
+ import {
4
+ existsSync,
5
+ mkdirSync,
6
+ readdirSync,
7
+ readFileSync,
8
+ statSync,
9
+ writeFileSync,
10
+ } from "node:fs";
11
+ import { join, resolve } from "node:path";
12
+ import { ensureTfxDirs, TFX_FULLCYCLE_DIR, TFX_PLANS_DIR } from "./paths.mjs";
6
13
 
7
14
  function safeResolve(baseDir, relativePath) {
8
15
  const base = resolve(baseDir);
9
16
  const target = resolve(join(baseDir, relativePath));
10
17
  if (!target.startsWith(base)) {
11
- throw new Error('Invalid fullcycle path: path traversal detected');
18
+ throw new Error("Invalid fullcycle path: path traversal detected");
12
19
  }
13
20
  return target;
14
21
  }
15
22
 
16
- /** @experimental */
23
+ /** @experimental 런타임 미연결 — 향후 통합 예정 */
17
24
  export function createFullcycleRunId(now = new Date()) {
18
25
  return now
19
26
  .toISOString()
20
- .replace(/[:.]/g, '-')
21
- .replace('T', '_')
22
- .replace('Z', 'Z');
27
+ .replace(/[:.]/g, "-")
28
+ .replace("T", "_")
29
+ .replace("Z", "Z");
23
30
  }
24
31
 
25
32
  export function getFullcycleRunDir(runId, baseDir = process.cwd()) {
@@ -33,32 +40,41 @@ export function ensureFullcycleRunDir(runId, baseDir = process.cwd()) {
33
40
  return dir;
34
41
  }
35
42
 
36
- export function saveFullcycleArtifact(runId, filename, content, baseDir = process.cwd()) {
37
- if (!filename || typeof filename !== 'string') {
38
- throw new Error('Artifact filename is required');
43
+ export function saveFullcycleArtifact(
44
+ runId,
45
+ filename,
46
+ content,
47
+ baseDir = process.cwd(),
48
+ ) {
49
+ if (!filename || typeof filename !== "string") {
50
+ throw new Error("Artifact filename is required");
39
51
  }
40
52
 
41
53
  const dir = ensureFullcycleRunDir(runId, baseDir);
42
54
  const path = safeResolve(dir, filename);
43
- writeFileSync(path, content, 'utf8');
55
+ writeFileSync(path, content, "utf8");
44
56
  return path;
45
57
  }
46
58
 
47
- export function readFullcycleArtifact(runId, filename, baseDir = process.cwd()) {
59
+ export function readFullcycleArtifact(
60
+ runId,
61
+ filename,
62
+ baseDir = process.cwd(),
63
+ ) {
48
64
  const dir = getFullcycleRunDir(runId, baseDir);
49
65
  const path = safeResolve(dir, filename);
50
66
  if (!existsSync(path)) return null;
51
- return readFileSync(path, 'utf8');
67
+ return readFileSync(path, "utf8");
52
68
  }
53
69
 
54
70
  export function writeFullcycleState(runId, state, baseDir = process.cwd()) {
55
- const payload = typeof state === 'object' && state !== null ? state : {};
71
+ const payload = typeof state === "object" && state !== null ? state : {};
56
72
  const serialized = JSON.stringify(payload, null, 2);
57
- return saveFullcycleArtifact(runId, 'state.json', serialized, baseDir);
73
+ return saveFullcycleArtifact(runId, "state.json", serialized, baseDir);
58
74
  }
59
75
 
60
76
  export function readFullcycleState(runId, baseDir = process.cwd()) {
61
- const content = readFullcycleArtifact(runId, 'state.json', baseDir);
77
+ const content = readFullcycleArtifact(runId, "state.json", baseDir);
62
78
  if (!content) return null;
63
79
  try {
64
80
  return JSON.parse(content);
@@ -87,7 +103,7 @@ export function shouldStopQaLoop(failureHistory = [], maxRepeats = 3) {
87
103
  if (!Array.isArray(failureHistory) || maxRepeats <= 1) return false;
88
104
 
89
105
  const normalized = failureHistory
90
- .map((entry) => String(entry ?? '').trim())
106
+ .map((entry) => String(entry ?? "").trim())
91
107
  .filter(Boolean);
92
108
 
93
109
  if (normalized.length < maxRepeats) return false;