@plainconceptsplatform/loop-task 2.6.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 (202) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +534 -0
  3. package/dist/app/App.js +132 -0
  4. package/dist/app/BoardLayout.js +5 -0
  5. package/dist/app/index.js +48 -0
  6. package/dist/app/providers/index.js +1 -0
  7. package/dist/app/router/index.js +16 -0
  8. package/dist/app/types.js +1 -0
  9. package/dist/cli/import-validator.js +152 -0
  10. package/dist/cli/import-writer.js +81 -0
  11. package/dist/cli.js +573 -0
  12. package/dist/client/cli-format.js +7 -0
  13. package/dist/client/commands.js +162 -0
  14. package/dist/client/ipc.js +96 -0
  15. package/dist/client/project-commands.js +164 -0
  16. package/dist/core/command/command-runner.js +300 -0
  17. package/dist/core/command/process-tree.js +73 -0
  18. package/dist/core/command/resolve-cwd.js +8 -0
  19. package/dist/core/command/stdout-capture-transform.js +73 -0
  20. package/dist/core/context/context-parser.js +65 -0
  21. package/dist/core/context/log-context.js +3 -0
  22. package/dist/core/context/template.js +20 -0
  23. package/dist/core/context/validate-context.js +19 -0
  24. package/dist/core/foreground/index.js +81 -0
  25. package/dist/core/logging/bounded-log-reader.js +368 -0
  26. package/dist/core/logging/log-follower.js +26 -0
  27. package/dist/core/logging/log-parser.js +29 -0
  28. package/dist/core/logging/log-rotator.js +34 -0
  29. package/dist/core/logging/rotating-log-stream.js +137 -0
  30. package/dist/core/loop/chain-executor.js +171 -0
  31. package/dist/core/loop/delay-utils.js +65 -0
  32. package/dist/core/loop/loop-controller.js +240 -0
  33. package/dist/core/loop/loop-runner.js +194 -0
  34. package/dist/core/loop/run-executor.js +144 -0
  35. package/dist/core/loop/types.js +1 -0
  36. package/dist/core/scheduling/index.js +16 -0
  37. package/dist/daemon/daemon-log.js +11 -0
  38. package/dist/daemon/diagnostics.js +85 -0
  39. package/dist/daemon/http/helpers.js +81 -0
  40. package/dist/daemon/http/openapi.js +119 -0
  41. package/dist/daemon/http/route-loops.js +311 -0
  42. package/dist/daemon/http/route-misc.js +60 -0
  43. package/dist/daemon/http/route-projects.js +55 -0
  44. package/dist/daemon/http/route-tasks.js +141 -0
  45. package/dist/daemon/http/routes.js +19 -0
  46. package/dist/daemon/http/server.js +82 -0
  47. package/dist/daemon/http/sse.js +36 -0
  48. package/dist/daemon/index.js +189 -0
  49. package/dist/daemon/ipc/send.js +5 -0
  50. package/dist/daemon/managers/loop-entry.js +27 -0
  51. package/dist/daemon/managers/loop-manager.js +346 -0
  52. package/dist/daemon/managers/loop-options.js +17 -0
  53. package/dist/daemon/managers/loop-serialization.js +53 -0
  54. package/dist/daemon/managers/project-manager.js +170 -0
  55. package/dist/daemon/managers/task-manager.js +94 -0
  56. package/dist/daemon/mcp/index.js +2 -0
  57. package/dist/daemon/mcp/openapi-sync.js +50 -0
  58. package/dist/daemon/mcp/server.js +167 -0
  59. package/dist/daemon/mcp/tools.js +382 -0
  60. package/dist/daemon/recipe/deferred-reload.js +32 -0
  61. package/dist/daemon/recipe/diagram-reader.js +26 -0
  62. package/dist/daemon/recipe/file-writer.js +52 -0
  63. package/dist/daemon/recipe/id-remapper.js +46 -0
  64. package/dist/daemon/recipe/runtime-state.js +23 -0
  65. package/dist/daemon/recipe/scanner.js +165 -0
  66. package/dist/daemon/recipe/task-store.js +33 -0
  67. package/dist/daemon/recipe/validator.js +35 -0
  68. package/dist/daemon/server/handlers/diagnostics-handlers.js +7 -0
  69. package/dist/daemon/server/handlers/index.js +101 -0
  70. package/dist/daemon/server/handlers/log-handlers.js +129 -0
  71. package/dist/daemon/server/handlers/loop-handlers.js +64 -0
  72. package/dist/daemon/server/handlers/project-handlers.js +42 -0
  73. package/dist/daemon/server/handlers/settings-handlers.js +8 -0
  74. package/dist/daemon/server/handlers/task-handlers.js +20 -0
  75. package/dist/daemon/server/handlers/telemetry-handlers.js +5 -0
  76. package/dist/daemon/server/index.js +117 -0
  77. package/dist/daemon/settings-manager.js +73 -0
  78. package/dist/daemon/spawner/index.js +204 -0
  79. package/dist/daemon/state/index.js +209 -0
  80. package/dist/daemon/telemetry/agent-integrations/agent-integration.js +1 -0
  81. package/dist/daemon/telemetry/agent-integrations/claude-code-integration.js +55 -0
  82. package/dist/daemon/telemetry/agent-integrations/detect-agent-integration.js +20 -0
  83. package/dist/daemon/telemetry/agent-integrations/index.js +3 -0
  84. package/dist/daemon/telemetry/agent-integrations/opencode-integration.js +72 -0
  85. package/dist/daemon/telemetry/index.js +6 -0
  86. package/dist/daemon/telemetry/noop-telemetry-adapter.js +53 -0
  87. package/dist/daemon/telemetry/open-telemetry-adapter.js +464 -0
  88. package/dist/daemon/telemetry/telemetry-manager.js +147 -0
  89. package/dist/daemon/telemetry/telemetry-redaction.js +67 -0
  90. package/dist/daemon/telemetry/telemetry-types.js +45 -0
  91. package/dist/daemon/telemetry/telemetry.js +1 -0
  92. package/dist/daemon/watcher/index.js +250 -0
  93. package/dist/duration.js +24 -0
  94. package/dist/entities/loops/filters.js +109 -0
  95. package/dist/entities/loops/index.js +1 -0
  96. package/dist/entities/projects/filters.js +69 -0
  97. package/dist/entities/projects/index.js +1 -0
  98. package/dist/entities/tasks/filters.js +41 -0
  99. package/dist/entities/tasks/index.js +1 -0
  100. package/dist/entry.js +16 -0
  101. package/dist/esm-loader.js +39 -0
  102. package/dist/features/chain-editor/ChainEditor.js +116 -0
  103. package/dist/features/chain-editor/mermaidToAscii.js +375 -0
  104. package/dist/features/chain-editor/renderChainDiagram.js +106 -0
  105. package/dist/features/code-editor/CodeEditorModal.js +84 -0
  106. package/dist/features/code-editor/CodeEditorPreview.js +14 -0
  107. package/dist/features/code-editor/useEditorKeyboard.js +150 -0
  108. package/dist/features/code-editor/useModalDimensions.js +9 -0
  109. package/dist/features/commands/commands.js +132 -0
  110. package/dist/features/commands/useCommandHandlers.js +280 -0
  111. package/dist/features/commands/useContextualActions.js +78 -0
  112. package/dist/features/commands/useGlobalShortcuts.js +154 -0
  113. package/dist/features/forms/FormRouter.js +46 -0
  114. package/dist/features/overlays/ContextHelpModal.js +8 -0
  115. package/dist/features/overlays/DiagramModal.js +45 -0
  116. package/dist/features/overlays/ExportModal.js +51 -0
  117. package/dist/features/overlays/HelpGuideModal.js +23 -0
  118. package/dist/features/overlays/HelpModal.js +59 -0
  119. package/dist/features/overlays/OverlayStack.js +10 -0
  120. package/dist/features/overlays/ProjectsModal.js +42 -0
  121. package/dist/features/overlays/TaskPickerModal.js +62 -0
  122. package/dist/features/overlays/WelcomeScreen.js +74 -0
  123. package/dist/features/overlays/useOverlayStack.js +55 -0
  124. package/dist/features/state/useAppState.js +151 -0
  125. package/dist/logger.js +25 -0
  126. package/dist/loop-config.js +152 -0
  127. package/dist/shared/clipboard.js +111 -0
  128. package/dist/shared/config/constants.js +104 -0
  129. package/dist/shared/config/paths.js +67 -0
  130. package/dist/shared/container/index.js +24 -0
  131. package/dist/shared/fs-utils.js +44 -0
  132. package/dist/shared/hooks/useBreakpoint.js +11 -0
  133. package/dist/shared/hooks/useDaemonSettings.js +41 -0
  134. package/dist/shared/hooks/useInject.js +6 -0
  135. package/dist/shared/hooks/useLogStream.js +37 -0
  136. package/dist/shared/hooks/useLoopFormValidation.js +131 -0
  137. package/dist/shared/hooks/useLoopPolling.js +30 -0
  138. package/dist/shared/hooks/useMouseScroll.js +56 -0
  139. package/dist/shared/hooks/useUndoRedo.js +77 -0
  140. package/dist/shared/i18n/en.json +709 -0
  141. package/dist/shared/i18n/index.js +11 -0
  142. package/dist/shared/providers/InversifyProvider.js +6 -0
  143. package/dist/shared/services/export-service.js +43 -0
  144. package/dist/shared/services/log-service.js +28 -0
  145. package/dist/shared/services/loop-service.js +78 -0
  146. package/dist/shared/services/project-service.js +39 -0
  147. package/dist/shared/services/settings-service.js +102 -0
  148. package/dist/shared/services/task-service.js +41 -0
  149. package/dist/shared/services/types.js +8 -0
  150. package/dist/shared/sleep.js +17 -0
  151. package/dist/shared/tail.js +4 -0
  152. package/dist/shared/ui/Button.js +18 -0
  153. package/dist/shared/ui/DebugPanel.js +9 -0
  154. package/dist/shared/ui/FocusableButton.js +18 -0
  155. package/dist/shared/ui/FocusableInput.js +72 -0
  156. package/dist/shared/ui/FocusableList.js +48 -0
  157. package/dist/shared/ui/Modal.js +13 -0
  158. package/dist/shared/ui/SelectModal.js +78 -0
  159. package/dist/shared/ui/Toast.js +37 -0
  160. package/dist/shared/ui/format.js +117 -0
  161. package/dist/shared/ui/hooks/useHoverState.js +11 -0
  162. package/dist/shared/ui/state.js +9 -0
  163. package/dist/shared/ui/theme.js +96 -0
  164. package/dist/shared/utils/log-lines.js +13 -0
  165. package/dist/shared/utils/paste.js +37 -0
  166. package/dist/shared/utils/syntax.js +128 -0
  167. package/dist/shared/utils/validation.js +56 -0
  168. package/dist/types.js +1 -0
  169. package/dist/visual-evidence/capture.js +51 -0
  170. package/dist/visual-evidence/cli.js +85 -0
  171. package/dist/visual-evidence/evidence-required.js +71 -0
  172. package/dist/visual-evidence/index.js +10 -0
  173. package/dist/visual-evidence/launch.js +61 -0
  174. package/dist/visual-evidence/manifest.js +32 -0
  175. package/dist/visual-evidence/openspec-resolver.js +45 -0
  176. package/dist/visual-evidence/publish.js +126 -0
  177. package/dist/visual-evidence/run.js +121 -0
  178. package/dist/visual-evidence/scenario-registry.js +132 -0
  179. package/dist/widgets/command-input/CommandDropdown.js +69 -0
  180. package/dist/widgets/command-input/CommandInput.js +133 -0
  181. package/dist/widgets/command-input/HintBar.js +9 -0
  182. package/dist/widgets/command-input/InputModes.js +72 -0
  183. package/dist/widgets/commands-browser/CommandsBrowserModal.js +85 -0
  184. package/dist/widgets/header/Header.js +54 -0
  185. package/dist/widgets/header/TabBar.js +20 -0
  186. package/dist/widgets/left-panel/LeftPanel.js +34 -0
  187. package/dist/widgets/left-panel/Navigator.js +107 -0
  188. package/dist/widgets/left-panel/ProjectsPage.js +76 -0
  189. package/dist/widgets/left-panel/ProjectsPageParts.js +34 -0
  190. package/dist/widgets/left-panel/TaskBrowser.js +132 -0
  191. package/dist/widgets/log-modal/LogModal.js +211 -0
  192. package/dist/widgets/loop-form/CreateForm.js +82 -0
  193. package/dist/widgets/loop-form/TextField.js +9 -0
  194. package/dist/widgets/loop-form/WizardForm.js +199 -0
  195. package/dist/widgets/loop-form/useCreateSteps.js +135 -0
  196. package/dist/widgets/loop-form/useHandleComplete.js +94 -0
  197. package/dist/widgets/project-form/ProjectForm.js +83 -0
  198. package/dist/widgets/right-panel/Inspector.js +41 -0
  199. package/dist/widgets/right-panel/RightPanel.js +38 -0
  200. package/dist/widgets/right-panel/RunHistory.js +187 -0
  201. package/dist/widgets/task-form/TaskForm.js +272 -0
  202. package/package.json +119 -0
@@ -0,0 +1,368 @@
1
+ import fs from "node:fs";
2
+ const DEFAULT_TAIL_WINDOW = 64 * 1024;
3
+ const INCREMENTAL_READ_CHUNK = 64 * 1024;
4
+ const MAX_RESPONSE_BYTES = 10 * 1024 * 1024;
5
+ export function tailFileBounded(logPath, lineCount, windowBytes = DEFAULT_TAIL_WINDOW) {
6
+ if (!fs.existsSync(logPath))
7
+ return [];
8
+ const size = fs.statSync(logPath).size;
9
+ if (size === 0)
10
+ return [];
11
+ if (lineCount <= 0) {
12
+ const data = readBounded(logPath, 0, Math.min(size, MAX_RESPONSE_BYTES));
13
+ return splitLines(data);
14
+ }
15
+ const readSize = Math.min(windowBytes, size);
16
+ const offset = size - readSize;
17
+ const fd = fs.openSync(logPath, "r");
18
+ const buf = Buffer.allocUnsafe(readSize);
19
+ let bytesRead;
20
+ try {
21
+ bytesRead = fs.readSync(fd, buf, 0, readSize, offset);
22
+ }
23
+ finally {
24
+ fs.closeSync(fd);
25
+ }
26
+ const text = buf.toString("utf-8", 0, bytesRead);
27
+ const lines = text.split("\n").filter((l) => l.length > 0);
28
+ return lines.slice(-lineCount);
29
+ }
30
+ export function readByteRange(logPath, start, end) {
31
+ if (!fs.existsSync(logPath))
32
+ return "";
33
+ const size = fs.statSync(logPath).size;
34
+ if (size === 0 || start >= size)
35
+ return "";
36
+ const effectiveEnd = end ?? size;
37
+ const readEnd = Math.min(effectiveEnd, size);
38
+ const readLen = Math.min(readEnd - start, MAX_RESPONSE_BYTES);
39
+ if (readLen <= 0)
40
+ return "";
41
+ const fd = fs.openSync(logPath, "r");
42
+ const buf = Buffer.allocUnsafe(readLen);
43
+ let bytesRead;
44
+ try {
45
+ bytesRead = fs.readSync(fd, buf, 0, readLen, start);
46
+ }
47
+ finally {
48
+ fs.closeSync(fd);
49
+ }
50
+ return buf.toString("utf-8", 0, bytesRead);
51
+ }
52
+ export function readBounded(logPath, offset, maxBytes = MAX_RESPONSE_BYTES) {
53
+ if (!fs.existsSync(logPath))
54
+ return "";
55
+ const size = fs.statSync(logPath).size;
56
+ if (size === 0 || offset >= size)
57
+ return "";
58
+ const readLen = Math.min(size - offset, maxBytes);
59
+ const fd = fs.openSync(logPath, "r");
60
+ const buf = Buffer.allocUnsafe(readLen);
61
+ let bytesRead;
62
+ try {
63
+ bytesRead = fs.readSync(fd, buf, 0, readLen, offset);
64
+ }
65
+ finally {
66
+ fs.closeSync(fd);
67
+ }
68
+ return buf.toString("utf-8", 0, bytesRead);
69
+ }
70
+ export function readIncremental(logPath, fromOffset, highWaterMark = INCREMENTAL_READ_CHUNK, maxTotalBytes = MAX_RESPONSE_BYTES) {
71
+ if (!fs.existsSync(logPath))
72
+ return { lines: [], newOffset: fromOffset };
73
+ const size = fs.statSync(logPath).size;
74
+ if (size <= fromOffset)
75
+ return { lines: [], newOffset: fromOffset };
76
+ const totalToRead = Math.min(size - fromOffset, maxTotalBytes);
77
+ const fd = fs.openSync(logPath, "r");
78
+ try {
79
+ const chunks = [];
80
+ let totalRead = 0;
81
+ let currentOffset = fromOffset;
82
+ while (totalRead < totalToRead) {
83
+ const chunkSize = Math.min(highWaterMark, totalToRead - totalRead);
84
+ const buf = Buffer.allocUnsafe(chunkSize);
85
+ const bytesRead = fs.readSync(fd, buf, 0, chunkSize, currentOffset);
86
+ if (bytesRead === 0)
87
+ break;
88
+ chunks.push(bytesRead < chunkSize ? buf.subarray(0, bytesRead) : buf);
89
+ totalRead += bytesRead;
90
+ currentOffset += bytesRead;
91
+ }
92
+ if (chunks.length === 0) {
93
+ return { lines: [], newOffset: fromOffset };
94
+ }
95
+ const text = chunks.length === 1
96
+ ? chunks[0].toString("utf-8")
97
+ : Buffer.concat(chunks, totalRead).toString("utf-8");
98
+ return { lines: splitLines(text), newOffset: fromOffset + totalRead };
99
+ }
100
+ finally {
101
+ fs.closeSync(fd);
102
+ }
103
+ }
104
+ const DEFAULT_REATTACH_DELAY_MS = 25;
105
+ const DEFAULT_MAX_REATTACH_ATTEMPTS = 40;
106
+ const DEFAULT_POLL_INTERVAL_MS = 100;
107
+ const GENERATION_SCAN_MAX = 20;
108
+ function readFdBatch(fd, offset, maxBytes) {
109
+ const buf = Buffer.allocUnsafe(maxBytes);
110
+ const bytesRead = fs.readSync(fd, buf, 0, maxBytes, offset);
111
+ return { text: buf.toString("utf-8", 0, bytesRead), bytesRead };
112
+ }
113
+ export class IncrementalFileWatcher {
114
+ constructor(options) {
115
+ this.watcher = null;
116
+ this.closed = false;
117
+ this.paused = false;
118
+ this.polling = false;
119
+ this.pendingPoll = false;
120
+ this.reattachTimer = null;
121
+ this.reattachAttempts = 0;
122
+ this.pollTimer = null;
123
+ this.currentIno = null;
124
+ this.catchup = [];
125
+ this.logPath = options.logPath;
126
+ this.currentOffset = options.initialOffset;
127
+ this.onLines = options.onLines;
128
+ this.onEnd = options.onEnd;
129
+ this.onError = options.onError;
130
+ this.reattachDelayMs = options.reattachDelayMs ?? DEFAULT_REATTACH_DELAY_MS;
131
+ this.maxReattachAttempts = options.maxReattachAttempts ?? DEFAULT_MAX_REATTACH_ATTEMPTS;
132
+ this.readBatchBytes = options.readBatchBytes ?? MAX_RESPONSE_BYTES;
133
+ this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
134
+ }
135
+ start() {
136
+ this.attach();
137
+ this.pollTimer = setInterval(() => {
138
+ this.pendingPoll = true;
139
+ this.drain();
140
+ }, this.pollIntervalMs);
141
+ this.pollTimer.unref?.();
142
+ }
143
+ pause() {
144
+ this.paused = true;
145
+ }
146
+ resume() {
147
+ if (!this.paused)
148
+ return;
149
+ this.paused = false;
150
+ if (this.closed)
151
+ return;
152
+ this.pendingPoll = true;
153
+ setImmediate(() => this.drain());
154
+ }
155
+ close() {
156
+ if (this.closed)
157
+ return;
158
+ this.closed = true;
159
+ if (this.reattachTimer) {
160
+ clearTimeout(this.reattachTimer);
161
+ this.reattachTimer = null;
162
+ }
163
+ if (this.pollTimer) {
164
+ clearInterval(this.pollTimer);
165
+ this.pollTimer = null;
166
+ }
167
+ for (const entry of this.catchup) {
168
+ try {
169
+ fs.closeSync(entry.fd);
170
+ }
171
+ catch { /* */ }
172
+ }
173
+ this.catchup = [];
174
+ this.watcher?.close();
175
+ this.watcher = null;
176
+ }
177
+ attach() {
178
+ if (this.closed)
179
+ return;
180
+ try {
181
+ this.watcher = fs.watch(this.logPath, (eventType) => this.handleEvent(eventType));
182
+ }
183
+ catch {
184
+ this.scheduleReattach();
185
+ return;
186
+ }
187
+ this.reattachAttempts = 0;
188
+ this.pendingPoll = true;
189
+ this.drain();
190
+ }
191
+ detach() {
192
+ this.watcher?.close();
193
+ this.watcher = null;
194
+ }
195
+ handleEvent(eventType) {
196
+ if (this.closed)
197
+ return;
198
+ if (eventType === "rename") {
199
+ this.detach();
200
+ this.recoverFromRotation();
201
+ return;
202
+ }
203
+ this.pendingPoll = true;
204
+ this.drain();
205
+ }
206
+ recoverFromRotation() {
207
+ if (this.closed)
208
+ return;
209
+ if (!fs.existsSync(this.logPath)) {
210
+ this.scheduleReattach();
211
+ return;
212
+ }
213
+ try {
214
+ const stat = fs.statSync(this.logPath);
215
+ if (this.isRotation(stat)) {
216
+ this.beginCatchup(stat);
217
+ }
218
+ }
219
+ catch {
220
+ /* raced another rotation */
221
+ }
222
+ this.attach();
223
+ }
224
+ isRotation(stat) {
225
+ if (stat.size < this.currentOffset)
226
+ return true;
227
+ if (this.currentIno !== null && stat.ino) {
228
+ return stat.ino !== this.currentIno;
229
+ }
230
+ return false;
231
+ }
232
+ beginCatchup(currentStat) {
233
+ const gens = [];
234
+ for (let index = 1; index <= GENERATION_SCAN_MAX; index++) {
235
+ const genPath = `${this.logPath}.${index}`;
236
+ if (!fs.existsSync(genPath))
237
+ break;
238
+ try {
239
+ const fd = fs.openSync(genPath, "r");
240
+ const stat = fs.fstatSync(fd);
241
+ gens.push({ fd, ino: stat.ino, size: stat.size });
242
+ }
243
+ catch {
244
+ break;
245
+ }
246
+ }
247
+ let matched = -1;
248
+ if (this.currentIno !== null) {
249
+ matched = gens.findIndex((g) => g.ino !== 0 && g.ino === this.currentIno);
250
+ }
251
+ if (matched === -1 && this.currentOffset > 0 && gens.length > 0 && gens[0].size > this.currentOffset) {
252
+ matched = 0;
253
+ }
254
+ for (let index = matched; index >= 0; index--) {
255
+ const gen = gens[index];
256
+ const offset = index === matched ? Math.min(this.currentOffset, gen.size) : 0;
257
+ if (offset < gen.size) {
258
+ this.catchup.push({ fd: gen.fd, size: gen.size, offset });
259
+ }
260
+ else {
261
+ try {
262
+ fs.closeSync(gen.fd);
263
+ }
264
+ catch { /* */ }
265
+ }
266
+ }
267
+ for (let index = matched + 1; index < gens.length; index++) {
268
+ try {
269
+ fs.closeSync(gens[index].fd);
270
+ }
271
+ catch { /* */ }
272
+ }
273
+ this.currentOffset = 0;
274
+ this.currentIno = currentStat.ino || null;
275
+ }
276
+ drainCatchupBatch() {
277
+ const head = this.catchup[0];
278
+ const toRead = Math.min(this.readBatchBytes, head.size - head.offset);
279
+ const { text, bytesRead } = readFdBatch(head.fd, head.offset, toRead);
280
+ head.offset += bytesRead;
281
+ if (head.offset >= head.size || bytesRead === 0) {
282
+ try {
283
+ fs.closeSync(head.fd);
284
+ }
285
+ catch { /* */ }
286
+ this.catchup.shift();
287
+ }
288
+ this.pendingPoll = true;
289
+ const lines = splitLines(text);
290
+ if (lines.length > 0) {
291
+ this.onLines(lines);
292
+ }
293
+ }
294
+ scheduleReattach() {
295
+ if (this.closed || this.reattachTimer)
296
+ return;
297
+ if (this.reattachAttempts >= this.maxReattachAttempts) {
298
+ this.close();
299
+ this.onEnd();
300
+ return;
301
+ }
302
+ this.reattachAttempts++;
303
+ this.reattachTimer = setTimeout(() => {
304
+ this.reattachTimer = null;
305
+ if (this.closed)
306
+ return;
307
+ if (fs.existsSync(this.logPath)) {
308
+ this.attach();
309
+ }
310
+ else {
311
+ this.scheduleReattach();
312
+ }
313
+ }, this.reattachDelayMs);
314
+ this.reattachTimer.unref?.();
315
+ }
316
+ drain() {
317
+ if (this.closed || this.paused || this.polling || !this.pendingPoll)
318
+ return;
319
+ this.polling = true;
320
+ this.pendingPoll = false;
321
+ try {
322
+ this.drainOnce();
323
+ }
324
+ catch (err) {
325
+ this.polling = false;
326
+ if (err.code === "ENOENT") {
327
+ this.detach();
328
+ this.pendingPoll = true;
329
+ this.recoverFromRotation();
330
+ return;
331
+ }
332
+ this.close();
333
+ this.onError(err instanceof Error ? err : new Error(String(err)));
334
+ return;
335
+ }
336
+ this.polling = false;
337
+ if (this.pendingPoll && !this.paused && !this.closed) {
338
+ setImmediate(() => this.drain());
339
+ }
340
+ }
341
+ drainOnce() {
342
+ if (this.catchup.length > 0) {
343
+ this.drainCatchupBatch();
344
+ return;
345
+ }
346
+ const stat = fs.statSync(this.logPath);
347
+ if (this.isRotation(stat)) {
348
+ this.beginCatchup(stat);
349
+ this.pendingPoll = true;
350
+ return;
351
+ }
352
+ this.currentIno = stat.ino || null;
353
+ if (stat.size > this.currentOffset) {
354
+ const startOffset = this.currentOffset;
355
+ const result = readIncremental(this.logPath, this.currentOffset, INCREMENTAL_READ_CHUNK, this.readBatchBytes);
356
+ this.currentOffset = result.newOffset;
357
+ if (result.newOffset - startOffset >= this.readBatchBytes) {
358
+ this.pendingPoll = true;
359
+ }
360
+ if (result.lines.length > 0) {
361
+ this.onLines(result.lines);
362
+ }
363
+ }
364
+ }
365
+ }
366
+ function splitLines(text) {
367
+ return text.split("\n").filter((l) => l.length > 0);
368
+ }
@@ -0,0 +1,26 @@
1
+ import { IncrementalFileWatcher } from "./bounded-log-reader.js";
2
+ import { FOLLOW_READ_BATCH_BYTES } from "../../shared/config/constants.js";
3
+ export function followLogFile(options) {
4
+ const { logPath, initialOffset, dest, formatLine, onEnd, onError } = options;
5
+ const watcher = new IncrementalFileWatcher({
6
+ logPath,
7
+ initialOffset,
8
+ readBatchBytes: FOLLOW_READ_BATCH_BYTES,
9
+ onLines: (lines) => {
10
+ if (dest.destroyed)
11
+ return;
12
+ let writable = true;
13
+ for (const line of lines) {
14
+ writable = dest.write(formatLine(line));
15
+ }
16
+ if (!writable) {
17
+ watcher.pause();
18
+ dest.once("drain", () => watcher.resume());
19
+ }
20
+ },
21
+ onEnd,
22
+ onError,
23
+ });
24
+ watcher.start();
25
+ return watcher;
26
+ }
@@ -0,0 +1,29 @@
1
+ const RUN_HEADER_RE = /^\[Run #(\d+)/;
2
+ const EXIT_MARKER_RE = /^\[exit /;
3
+ export function splitLogByRuns(content) {
4
+ const lines = content.split("\n");
5
+ const runs = [];
6
+ let currentRun = null;
7
+ for (const line of lines) {
8
+ const headerMatch = line.match(RUN_HEADER_RE);
9
+ if (headerMatch) {
10
+ if (currentRun) {
11
+ runs.push(currentRun);
12
+ }
13
+ currentRun = { runNumber: parseInt(headerMatch[1], 10), lines: [] };
14
+ continue;
15
+ }
16
+ if (currentRun && EXIT_MARKER_RE.test(line)) {
17
+ runs.push(currentRun);
18
+ currentRun = null;
19
+ continue;
20
+ }
21
+ if (currentRun) {
22
+ currentRun.lines.push(line);
23
+ }
24
+ }
25
+ if (currentRun) {
26
+ runs.push(currentRun);
27
+ }
28
+ return runs;
29
+ }
@@ -0,0 +1,34 @@
1
+ import fs from "node:fs";
2
+ import { MAX_LOG_BYTES, MAX_LOG_GENERATIONS } from "../../shared/config/constants.js";
3
+ import { RotatingWriteStream } from "./rotating-log-stream.js";
4
+ export function rotateLogIfNeeded(logPath, currentStream) {
5
+ if (!fs.existsSync(logPath)) {
6
+ return currentStream;
7
+ }
8
+ const size = fs.statSync(logPath).size;
9
+ if (size < MAX_LOG_BYTES) {
10
+ return currentStream;
11
+ }
12
+ if (currentStream instanceof RotatingWriteStream) {
13
+ currentStream.end();
14
+ }
15
+ else {
16
+ currentStream?.end();
17
+ }
18
+ for (let index = MAX_LOG_GENERATIONS; index >= 1; index--) {
19
+ const currentPath = `${logPath}.${index}`;
20
+ if (!fs.existsSync(currentPath)) {
21
+ continue;
22
+ }
23
+ if (index === MAX_LOG_GENERATIONS) {
24
+ fs.unlinkSync(currentPath);
25
+ continue;
26
+ }
27
+ fs.renameSync(currentPath, `${logPath}.${index + 1}`);
28
+ }
29
+ fs.renameSync(logPath, `${logPath}.1`);
30
+ return RotatingWriteStream.create(logPath);
31
+ }
32
+ export function createLogStream(logPath) {
33
+ return RotatingWriteStream.create(logPath);
34
+ }
@@ -0,0 +1,137 @@
1
+ import fs from "node:fs";
2
+ import { Writable } from "node:stream";
3
+ import { MAX_LOG_BYTES, MAX_LOG_GENERATIONS } from "../../shared/config/constants.js";
4
+ function safeCreateWriteStream(path) {
5
+ const stream = fs.createWriteStream(path, { flags: "a" });
6
+ stream.on("error", () => { });
7
+ return stream;
8
+ }
9
+ export class RotatingWriteStream extends Writable {
10
+ static create(basePath, maxBytes = MAX_LOG_BYTES, maxGenerations = MAX_LOG_GENERATIONS) {
11
+ return new RotatingWriteStream(basePath, maxBytes, maxGenerations);
12
+ }
13
+ constructor(basePath, maxBytes, maxGenerations) {
14
+ super({ decodeStrings: true, highWaterMark: 64 * 1024 });
15
+ this._bytesWritten = 0;
16
+ this._rotating = false;
17
+ this._rotationWaiters = [];
18
+ this.basePath = basePath;
19
+ this.maxBytes = maxBytes;
20
+ this.maxGenerations = maxGenerations;
21
+ this.innerStream = safeCreateWriteStream(basePath);
22
+ try {
23
+ if (fs.existsSync(basePath)) {
24
+ this._bytesWritten = fs.statSync(basePath).size;
25
+ }
26
+ }
27
+ catch {
28
+ this._bytesWritten = 0;
29
+ }
30
+ }
31
+ get bytesWritten() {
32
+ return this._bytesWritten;
33
+ }
34
+ _write(chunk, _encoding, callback) {
35
+ const proceed = () => this.writeChunk(chunk, callback);
36
+ if (this._rotating) {
37
+ this._rotationWaiters.push(proceed);
38
+ return;
39
+ }
40
+ if (this._bytesWritten >= this.maxBytes) {
41
+ this.rotateThen(proceed);
42
+ return;
43
+ }
44
+ proceed();
45
+ }
46
+ writeChunk(chunk, callback) {
47
+ this._bytesWritten += chunk.byteLength;
48
+ if (!this.innerStream.writable) {
49
+ callback(new Error("stream not writable"));
50
+ return;
51
+ }
52
+ const canWrite = this.innerStream.write(chunk);
53
+ if (canWrite) {
54
+ callback();
55
+ return;
56
+ }
57
+ const inner = this.innerStream;
58
+ const onDrain = () => {
59
+ inner.off("error", onError);
60
+ callback();
61
+ };
62
+ const onError = () => {
63
+ inner.off("drain", onDrain);
64
+ callback();
65
+ };
66
+ inner.once("drain", onDrain);
67
+ inner.once("error", onError);
68
+ }
69
+ _final(callback) {
70
+ const finish = () => {
71
+ this.innerStream.end(() => {
72
+ callback();
73
+ });
74
+ };
75
+ if (this._rotating) {
76
+ this._rotationWaiters.push(finish);
77
+ }
78
+ else {
79
+ finish();
80
+ }
81
+ }
82
+ rotateIfNeeded() {
83
+ if (this._rotating)
84
+ return false;
85
+ if (this._bytesWritten < this.maxBytes)
86
+ return false;
87
+ this.rotateThen(() => { });
88
+ return true;
89
+ }
90
+ rotateThen(next) {
91
+ this._rotationWaiters.push(next);
92
+ if (this._rotating)
93
+ return;
94
+ this._rotating = true;
95
+ this._bytesWritten = 0;
96
+ const old = this.innerStream;
97
+ let finished = false;
98
+ const finishRotation = () => {
99
+ if (finished)
100
+ return;
101
+ finished = true;
102
+ this.shiftGenerations();
103
+ this._rotating = false;
104
+ const waiters = this._rotationWaiters;
105
+ this._rotationWaiters = [];
106
+ for (const waiter of waiters)
107
+ waiter();
108
+ };
109
+ old.once("error", finishRotation);
110
+ old.end(finishRotation);
111
+ }
112
+ shiftGenerations() {
113
+ try {
114
+ for (let index = this.maxGenerations; index >= 1; index--) {
115
+ const currentPath = `${this.basePath}.${index}`;
116
+ if (!fs.existsSync(currentPath))
117
+ continue;
118
+ if (index === this.maxGenerations) {
119
+ fs.unlinkSync(currentPath);
120
+ continue;
121
+ }
122
+ fs.renameSync(currentPath, `${this.basePath}.${index + 1}`);
123
+ }
124
+ if (fs.existsSync(this.basePath)) {
125
+ fs.renameSync(this.basePath, `${this.basePath}.1`);
126
+ }
127
+ }
128
+ catch {
129
+ /* a locked or vanished generation must not break logging */
130
+ }
131
+ const dir = this.basePath.substring(0, this.basePath.lastIndexOf("/"));
132
+ if (dir && !fs.existsSync(dir)) {
133
+ return;
134
+ }
135
+ this.innerStream = safeCreateWriteStream(this.basePath);
136
+ }
137
+ }