@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,165 @@
1
+ // hub/lib/path-utils.mjs — Windows/POSIX 경로 변환 유틸리티
2
+
3
+ /**
4
+ * Windows 경로를 Git Bash 스타일 POSIX 경로로 변환한다.
5
+ * C:\foo\bar → /c/foo/bar
6
+ * 이미 POSIX 경로면 그대로 반환.
7
+ * null/undefined → 빈 문자열
8
+ * @param {string|null|undefined} windowsPath
9
+ * @returns {string}
10
+ */
11
+ export function toPosixPath(windowsPath) {
12
+ if (windowsPath == null) return "";
13
+ const p = String(windowsPath);
14
+ if (!p) return "";
15
+
16
+ // 이미 POSIX 경로 (/ 로 시작하거나 드라이브 레터 없음)
17
+ const winDriveMatch = p.match(/^([A-Za-z]):[/\\](.*)/);
18
+ if (!winDriveMatch) {
19
+ // 백슬래시만 있는 상대 경로도 forward slash로 변환
20
+ return p.replace(/\\/g, "/");
21
+ }
22
+
23
+ const drive = winDriveMatch[1].toLowerCase();
24
+ const rest = winDriveMatch[2].replace(/\\/g, "/");
25
+ return `/${drive}/${rest}`;
26
+ }
27
+
28
+ /**
29
+ * POSIX 경로(Git Bash 스타일)를 Windows 경로로 변환한다.
30
+ * /c/foo/bar → C:\foo\bar
31
+ * 이미 Windows 경로면 그대로 반환.
32
+ * null/undefined → 빈 문자열
33
+ * @param {string|null|undefined} posixPath
34
+ * @returns {string}
35
+ */
36
+ export function toWindowsPath(posixPath) {
37
+ if (posixPath == null) return "";
38
+ const p = String(posixPath);
39
+ if (!p) return "";
40
+
41
+ // 이미 Windows 경로
42
+ if (/^[A-Za-z]:/.test(p)) {
43
+ return p.replace(/\//g, "\\");
44
+ }
45
+
46
+ // Git Bash 스타일: /c/foo/bar
47
+ const gitBashMatch = p.match(/^\/([a-zA-Z])(\/.*)?$/);
48
+ if (gitBashMatch) {
49
+ const drive = gitBashMatch[1].toUpperCase();
50
+ const rest = gitBashMatch[2] ? gitBashMatch[2].replace(/\//g, "\\") : "\\";
51
+ return `${drive}:${rest}`;
52
+ }
53
+
54
+ return p;
55
+ }
56
+
57
+ /**
58
+ * 현재 OS에 맞게 경로를 정규화한다.
59
+ * win32: backslash, 그 외: forward slash
60
+ * @param {string|null|undefined} p
61
+ * @returns {string}
62
+ */
63
+ export function normalizePath(p) {
64
+ if (p == null) return "";
65
+ const str = String(p);
66
+ if (process.platform === "win32") {
67
+ return str.replace(/\//g, "\\");
68
+ }
69
+ return str.replace(/\\/g, "/");
70
+ }
71
+
72
+ /**
73
+ * 쉘 타입에 맞는 경로로 변환한다.
74
+ * @param {string|null|undefined} path
75
+ * @param {'git-bash'|'wsl'|'cmd'|'powershell'} shellType
76
+ * @returns {string}
77
+ */
78
+ export function resolveShellPath(path, shellType) {
79
+ if (path == null) return "";
80
+ const p = String(path);
81
+
82
+ switch (shellType) {
83
+ case "git-bash":
84
+ return toPosixPath(p);
85
+
86
+ case "wsl": {
87
+ // Git Bash 경로를 먼저 Windows로 변환 후 WSL 형식으로
88
+ const winPath = /^[A-Za-z]:/.test(p) ? p : toWindowsPath(p);
89
+ const wslDriveMatch = winPath.match(/^([A-Za-z]):[/\\](.*)/);
90
+ if (wslDriveMatch) {
91
+ const drive = wslDriveMatch[1].toLowerCase();
92
+ const rest = wslDriveMatch[2].replace(/\\/g, "/");
93
+ return rest ? `/mnt/${drive}/${rest}` : `/mnt/${drive}`;
94
+ }
95
+ // 이미 /mnt/ 형식이면 그대로
96
+ if (p.startsWith("/mnt/")) return p;
97
+ return p.replace(/\\/g, "/");
98
+ }
99
+
100
+ case "cmd":
101
+ case "powershell":
102
+ return toWindowsPath(p);
103
+
104
+ default:
105
+ return p;
106
+ }
107
+ }
108
+
109
+ /**
110
+ * 환경 변수와 플랫폼 정보로 현재 쉘 타입을 추론한다.
111
+ * @returns {'git-bash'|'wsl'|'cmd'|'powershell'|'unix'}
112
+ */
113
+ export function detectShellType() {
114
+ // WSL 감지: WSL_DISTRO_NAME 또는 WSLENV
115
+ if (process.env.WSL_DISTRO_NAME || process.env.WSLENV) {
116
+ return "wsl";
117
+ }
118
+
119
+ // Windows 플랫폼
120
+ if (process.platform === "win32") {
121
+ const shell = process.env.SHELL || "";
122
+ const term = process.env.TERM || "";
123
+ const msystem = process.env.MSYSTEM || "";
124
+
125
+ // Git Bash 감지: SHELL=/usr/bin/bash + MSYSTEM=MINGW64 등
126
+ if (
127
+ shell.includes("bash") ||
128
+ msystem.startsWith("MINGW") ||
129
+ msystem.startsWith("MSYS") ||
130
+ term === "xterm"
131
+ ) {
132
+ return "git-bash";
133
+ }
134
+
135
+ // PowerShell 감지
136
+ if (process.env.PSModulePath || process.env.PSHOME) {
137
+ return "powershell";
138
+ }
139
+
140
+ return "cmd";
141
+ }
142
+
143
+ // 비-Windows
144
+ return "unix";
145
+ }
146
+
147
+ /**
148
+ * WSL 경로 여부를 확인한다 (/mnt/ 시작).
149
+ * @param {string|null|undefined} p
150
+ * @returns {boolean}
151
+ */
152
+ export function isWslPath(p) {
153
+ if (p == null) return false;
154
+ return String(p).startsWith("/mnt/");
155
+ }
156
+
157
+ /**
158
+ * Git Bash 경로 여부를 확인한다 (/c/ 또는 /d/ 등 단일 소문자 드라이브 레터).
159
+ * @param {string|null|undefined} p
160
+ * @returns {boolean}
161
+ */
162
+ export function isGitBashPath(p) {
163
+ if (p == null) return false;
164
+ return /^\/[a-zA-Z](\/|$)/.test(String(p));
165
+ }
@@ -0,0 +1,493 @@
1
+ import { existsSync } from "node:fs";
2
+ import {
3
+ mkdir,
4
+ readdir,
5
+ readFile,
6
+ rename,
7
+ stat,
8
+ unlink,
9
+ writeFile,
10
+ } from "node:fs/promises";
11
+ import os from "node:os";
12
+ import { dirname, join } from "node:path";
13
+
14
+ /**
15
+ * @typedef {"Research" | "Strategy" | "Execution" | "Validation"} WorkPhase
16
+ */
17
+
18
+ /**
19
+ * @typedef {"active" | "complete" | "failed"} PhaseStatus
20
+ */
21
+
22
+ /**
23
+ * @typedef {WorkPhase | "complete"} LegacyPhase
24
+ */
25
+
26
+ /**
27
+ * @typedef {object} PhaseRecord
28
+ * @property {WorkPhase | "complete"} phase
29
+ * @property {PhaseStatus} phaseStatus
30
+ * @property {WorkPhase | null} lastPhase
31
+ */
32
+
33
+ export const PHASE_ENUM = Object.freeze([
34
+ "Research",
35
+ "Strategy",
36
+ "Execution",
37
+ "Validation",
38
+ ]);
39
+
40
+ export const PHASE_STATUS = Object.freeze(["active", "complete", "failed"]);
41
+
42
+ const PHASE_SET = new Set(PHASE_ENUM);
43
+ const PHASE_STATUS_SET = new Set(PHASE_STATUS);
44
+
45
+ /**
46
+ * @returns {string}
47
+ */
48
+ function getHomeDir() {
49
+ return process.env.HOME || process.env.USERPROFILE || os.homedir();
50
+ }
51
+
52
+ /**
53
+ * @param {unknown} value
54
+ * @returns {value is WorkPhase}
55
+ */
56
+ function isWorkPhase(value) {
57
+ return PHASE_SET.has(String(value));
58
+ }
59
+
60
+ /**
61
+ * @param {unknown} value
62
+ * @returns {value is PhaseStatus}
63
+ */
64
+ function isPhaseStatus(value) {
65
+ return PHASE_STATUS_SET.has(String(value));
66
+ }
67
+
68
+ /**
69
+ * @param {unknown} value
70
+ * @returns {WorkPhase | null}
71
+ */
72
+ function coerceWorkPhase(value) {
73
+ const phase = coerceLegacyPhase(value);
74
+ return phase === "complete" ? null : phase;
75
+ }
76
+
77
+ /**
78
+ * @param {string} runId
79
+ * @returns {{fullcycleStatePath: string, phaseStatePath: string}}
80
+ */
81
+ function getRunPaths(runId) {
82
+ return {
83
+ fullcycleStatePath: join(
84
+ process.cwd(),
85
+ ".tfx",
86
+ "fullcycle",
87
+ runId,
88
+ "state.json",
89
+ ),
90
+ phaseStatePath: join(process.cwd(), ".tfx", "phases", `${runId}.json`),
91
+ };
92
+ }
93
+
94
+ /**
95
+ * @param {string} runId
96
+ * @returns {string | null}
97
+ */
98
+ function resolveReadPath(runId) {
99
+ const { fullcycleStatePath, phaseStatePath } = getRunPaths(runId);
100
+ if (existsSync(fullcycleStatePath)) return fullcycleStatePath;
101
+ if (existsSync(phaseStatePath)) return phaseStatePath;
102
+ return null;
103
+ }
104
+
105
+ /**
106
+ * @param {string} runId
107
+ * @returns {string}
108
+ */
109
+ function resolveWritePath(runId) {
110
+ const { fullcycleStatePath, phaseStatePath } = getRunPaths(runId);
111
+ const fullcycleDir = dirname(fullcycleStatePath);
112
+
113
+ if (
114
+ existsSync(fullcycleStatePath) ||
115
+ existsSync(fullcycleDir) ||
116
+ !existsSync(phaseStatePath)
117
+ ) {
118
+ return fullcycleStatePath;
119
+ }
120
+
121
+ return phaseStatePath;
122
+ }
123
+
124
+ /**
125
+ * @param {string} tempPath
126
+ * @param {string} targetPath
127
+ * @returns {Promise<void>}
128
+ */
129
+ async function safeReplaceFile(tempPath, targetPath) {
130
+ try {
131
+ await rename(tempPath, targetPath);
132
+ } catch (error) {
133
+ if (!["EEXIST", "EPERM", "EACCES"].includes(error?.code)) {
134
+ try {
135
+ await unlink(tempPath);
136
+ } catch {}
137
+ throw error;
138
+ }
139
+
140
+ try {
141
+ await unlink(targetPath);
142
+ } catch {}
143
+
144
+ await rename(tempPath, targetPath);
145
+ }
146
+ }
147
+
148
+ /**
149
+ * @param {string} targetPath
150
+ * @param {Record<string, unknown>} payload
151
+ * @returns {Promise<void>}
152
+ */
153
+ async function writeJsonAtomic(targetPath, payload) {
154
+ const tempPath = `${targetPath}.${process.pid}.${Date.now()}.tmp`;
155
+ await mkdir(dirname(targetPath), { recursive: true });
156
+ await writeFile(tempPath, `${JSON.stringify(payload, null, 2)}\n`, {
157
+ encoding: "utf8",
158
+ mode: 0o600,
159
+ });
160
+ await safeReplaceFile(tempPath, targetPath);
161
+ }
162
+
163
+ /**
164
+ * @param {string} targetPath
165
+ * @param {string} content
166
+ * @returns {Promise<void>}
167
+ */
168
+ async function writeTextAtomic(targetPath, content) {
169
+ const tempPath = `${targetPath}.${process.pid}.${Date.now()}.tmp`;
170
+ await mkdir(dirname(targetPath), { recursive: true });
171
+ await writeFile(tempPath, content, {
172
+ encoding: "utf8",
173
+ mode: 0o600,
174
+ });
175
+ await safeReplaceFile(tempPath, targetPath);
176
+ }
177
+
178
+ /**
179
+ * @param {string} filePath
180
+ * @returns {Promise<Record<string, unknown> | null>}
181
+ */
182
+ async function readJsonFile(filePath) {
183
+ try {
184
+ const raw = await readFile(filePath, "utf8");
185
+ return JSON.parse(raw);
186
+ } catch (error) {
187
+ if (error?.code === "ENOENT") {
188
+ return null;
189
+ }
190
+ throw error;
191
+ }
192
+ }
193
+
194
+ /**
195
+ * @param {Record<string, unknown>} data
196
+ * @returns {PhaseRecord | null}
197
+ */
198
+ function phaseRecordFromData(data) {
199
+ const explicitPhase = isWorkPhase(data.phase) ? data.phase : null;
200
+ const explicitStatus = isPhaseStatus(data.phase_status)
201
+ ? data.phase_status
202
+ : null;
203
+ const explicitLastPhase = isWorkPhase(data.last_phase)
204
+ ? data.last_phase
205
+ : null;
206
+ const legacyLastPhase =
207
+ explicitLastPhase || coerceWorkPhase(data.last_successful_phase);
208
+
209
+ if (explicitPhase) {
210
+ return {
211
+ phase: explicitPhase,
212
+ phaseStatus: explicitStatus || "active",
213
+ lastPhase: legacyLastPhase,
214
+ };
215
+ }
216
+
217
+ const legacyPhase = coerceLegacyPhase(data.current_phase);
218
+ if (!legacyPhase) {
219
+ return null;
220
+ }
221
+
222
+ if (legacyPhase === "complete") {
223
+ return {
224
+ phase: legacyLastPhase || "complete",
225
+ phaseStatus: explicitStatus || "complete",
226
+ lastPhase: legacyLastPhase,
227
+ };
228
+ }
229
+
230
+ return {
231
+ phase: legacyPhase,
232
+ phaseStatus: explicitStatus || "active",
233
+ lastPhase: legacyLastPhase,
234
+ };
235
+ }
236
+
237
+ /**
238
+ * @param {WorkPhase | "complete"} phase
239
+ * @returns {string}
240
+ */
241
+ function toLegacyPhaseName(phase) {
242
+ return phase === "complete" ? "complete" : phase.toLowerCase();
243
+ }
244
+
245
+ /**
246
+ * @param {Record<string, unknown>} data
247
+ * @param {PhaseRecord} record
248
+ * @returns {Record<string, unknown>}
249
+ */
250
+ function applyPhaseRecord(data, record) {
251
+ const next = {
252
+ ...data,
253
+ phase_status: record.phaseStatus,
254
+ current_phase: toLegacyPhaseName(record.phase),
255
+ };
256
+
257
+ if (record.phase !== "complete") {
258
+ next.phase = record.phase;
259
+ }
260
+
261
+ if (record.lastPhase) {
262
+ next.last_phase = record.lastPhase;
263
+ next.last_successful_phase = record.lastPhase.toLowerCase();
264
+ }
265
+
266
+ if (record.phaseStatus === "complete" && record.phase !== "complete") {
267
+ next.last_phase = record.phase;
268
+ next.last_successful_phase = record.phase.toLowerCase();
269
+ }
270
+
271
+ return next;
272
+ }
273
+
274
+ /**
275
+ * @param {string} content
276
+ * @returns {{lines: string[], bodyLines: string[], eol: string} | null}
277
+ */
278
+ function parseFrontmatter(content) {
279
+ const eol = content.includes("\r\n") ? "\r\n" : "\n";
280
+ const lines = content.split(/\r?\n/);
281
+
282
+ if (lines[0] !== "---") {
283
+ return null;
284
+ }
285
+
286
+ const closingIndex = lines.indexOf("---", 1);
287
+ if (closingIndex === -1) {
288
+ return null;
289
+ }
290
+
291
+ return {
292
+ lines: lines.slice(1, closingIndex),
293
+ bodyLines: lines.slice(closingIndex + 1),
294
+ eol,
295
+ };
296
+ }
297
+
298
+ /**
299
+ * @param {string[]} lines
300
+ * @param {Record<string, string>} fields
301
+ * @returns {string[]}
302
+ */
303
+ function upsertFrontmatterLines(lines, fields) {
304
+ const nextLines = [...lines];
305
+
306
+ for (const [key, value] of Object.entries(fields)) {
307
+ const keyPrefix = `${key}:`;
308
+ const index = nextLines.findIndex((line) => line.startsWith(keyPrefix));
309
+
310
+ if (index >= 0) {
311
+ nextLines[index] = `${key}: ${value}`;
312
+ continue;
313
+ }
314
+
315
+ nextLines.push(`${key}: ${value}`);
316
+ }
317
+
318
+ return nextLines;
319
+ }
320
+
321
+ /**
322
+ * @param {string} content
323
+ * @param {Record<string, string>} fields
324
+ * @returns {string | null}
325
+ */
326
+ function injectFrontmatterFields(content, fields) {
327
+ const parsed = parseFrontmatter(content);
328
+ if (!parsed) {
329
+ return null;
330
+ }
331
+
332
+ const updatedLines = upsertFrontmatterLines(parsed.lines, fields);
333
+ return ["---", ...updatedLines, "---", ...parsed.bodyLines].join(parsed.eol);
334
+ }
335
+
336
+ /**
337
+ * @param {string} runId
338
+ * @returns {Promise<PhaseRecord | null>}
339
+ */
340
+ export async function readPhase(runId) {
341
+ const statePath = resolveReadPath(runId);
342
+ if (!statePath) {
343
+ return null;
344
+ }
345
+
346
+ const data = await readJsonFile(statePath);
347
+ if (!data) {
348
+ return null;
349
+ }
350
+
351
+ const record = phaseRecordFromData(data);
352
+ if (!record) {
353
+ return null;
354
+ }
355
+
356
+ if (!isWorkPhase(data.phase)) {
357
+ await writeJsonAtomic(statePath, applyPhaseRecord(data, record));
358
+ }
359
+
360
+ return record;
361
+ }
362
+
363
+ /**
364
+ * @param {string} runId
365
+ * @param {WorkPhase} phase
366
+ * @param {PhaseStatus} [status="active"]
367
+ * @returns {Promise<void>}
368
+ */
369
+ export async function writePhase(runId, phase, status = "active") {
370
+ if (!isWorkPhase(phase)) {
371
+ throw new Error(`Invalid phase: ${phase}`);
372
+ }
373
+
374
+ if (!isPhaseStatus(status)) {
375
+ throw new Error(`Invalid phase status: ${status}`);
376
+ }
377
+
378
+ const statePath = resolveWritePath(runId);
379
+ const current = (await readJsonFile(statePath)) || {};
380
+ const next = {
381
+ ...current,
382
+ run_id: current.run_id || runId,
383
+ phase,
384
+ phase_status: status,
385
+ current_phase: phase.toLowerCase(),
386
+ };
387
+
388
+ if (status === "complete") {
389
+ next.last_phase = phase;
390
+ next.last_successful_phase = phase.toLowerCase();
391
+ }
392
+
393
+ await writeJsonAtomic(statePath, next);
394
+ }
395
+
396
+ /**
397
+ * @param {string} runId
398
+ * @param {string} slug
399
+ * @returns {Promise<void>}
400
+ */
401
+ export async function syncToGstack(runId, slug) {
402
+ const gstackRoot = join(getHomeDir(), ".gstack");
403
+ if (!existsSync(gstackRoot)) {
404
+ return;
405
+ }
406
+
407
+ const record = await readPhase(runId);
408
+ if (!record) {
409
+ return;
410
+ }
411
+
412
+ const phase = record.phase === "complete" ? record.lastPhase : record.phase;
413
+ if (!phase) {
414
+ return;
415
+ }
416
+
417
+ const checkpointsDir = join(gstackRoot, "projects", slug, "checkpoints");
418
+ if (!existsSync(checkpointsDir)) {
419
+ return;
420
+ }
421
+
422
+ const entries = await readdir(checkpointsDir, { withFileTypes: true });
423
+ const markdownFiles = entries
424
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".md"))
425
+ .map((entry) => join(checkpointsDir, entry.name));
426
+
427
+ if (markdownFiles.length === 0) {
428
+ return;
429
+ }
430
+
431
+ const latestFile = (
432
+ await Promise.all(
433
+ markdownFiles.map(async (filePath) => ({
434
+ filePath,
435
+ stats: await stat(filePath),
436
+ })),
437
+ )
438
+ ).sort((left, right) => right.stats.mtimeMs - left.stats.mtimeMs)[0]
439
+ ?.filePath;
440
+
441
+ if (!latestFile) {
442
+ return;
443
+ }
444
+
445
+ const currentContent = await readFile(latestFile, "utf8");
446
+ const nextContent = injectFrontmatterFields(currentContent, {
447
+ phase,
448
+ triflux_run_id: runId,
449
+ });
450
+
451
+ if (!nextContent || nextContent === currentContent) {
452
+ return;
453
+ }
454
+
455
+ await writeTextAtomic(latestFile, nextContent);
456
+ }
457
+
458
+ /**
459
+ * @param {unknown} text
460
+ * @returns {LegacyPhase | null}
461
+ */
462
+ export function coerceLegacyPhase(text) {
463
+ if (text == null) {
464
+ return null;
465
+ }
466
+
467
+ const value = String(text).trim();
468
+ if (!value) {
469
+ return null;
470
+ }
471
+
472
+ if (/^complete$/i.test(value)) {
473
+ return "complete";
474
+ }
475
+
476
+ if (/interview|research|phase1/i.test(value)) {
477
+ return "Research";
478
+ }
479
+
480
+ if (/plan|strategy|phase2/i.test(value)) {
481
+ return "Strategy";
482
+ }
483
+
484
+ if (/exec|ship|phase3|phase4/i.test(value)) {
485
+ return "Execution";
486
+ }
487
+
488
+ if (/valid|qa|review|phase5/i.test(value)) {
489
+ return "Validation";
490
+ }
491
+
492
+ return null;
493
+ }