u-foo 4.0.3 → 4.0.10

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 (160) hide show
  1. package/README.md +239 -19
  2. package/README.zh-CN.md +3 -3
  3. package/bin/ucode.js +10 -2
  4. package/bin/ufoo.js +3 -0
  5. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  6. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  7. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  8. package/dist/tui/linux-x64/ufoo-tui +0 -0
  9. package/{OBSERVABILITY.md → docs/OBSERVABILITY.md} +3 -3
  10. package/docs/README.md +27 -0
  11. package/extensions/ufoo-browser/LICENSE +152 -0
  12. package/extensions/ufoo-browser/NOTICE +10 -0
  13. package/extensions/ufoo-browser/README.md +30 -0
  14. package/extensions/ufoo-browser/background.js +409 -0
  15. package/extensions/ufoo-browser/icons/icon-128.png +0 -0
  16. package/extensions/ufoo-browser/icons/icon-16.png +0 -0
  17. package/extensions/ufoo-browser/icons/icon-256.png +0 -0
  18. package/extensions/ufoo-browser/icons/icon-32.png +0 -0
  19. package/extensions/ufoo-browser/icons/icon-48.png +0 -0
  20. package/extensions/ufoo-browser/icons/logo.png +0 -0
  21. package/extensions/ufoo-browser/icons/toolbar-16.png +0 -0
  22. package/extensions/ufoo-browser/icons/toolbar-32.png +0 -0
  23. package/extensions/ufoo-browser/icons/toolbar-logo.png +0 -0
  24. package/extensions/ufoo-browser/manifest.json +30 -0
  25. package/extensions/ufoo-browser/popup.css +71 -0
  26. package/extensions/ufoo-browser/popup.html +44 -0
  27. package/extensions/ufoo-browser/popup.js +153 -0
  28. package/package.json +7 -5
  29. package/scripts/postinstall.js +6 -0
  30. package/src/agents/capabilities/browser/index.js +49 -0
  31. package/src/agents/capabilities/coding/backgroundHooks.js +94 -0
  32. package/src/agents/capabilities/coding/index.js +30 -1
  33. package/src/agents/capabilities/index.js +5 -2
  34. package/src/agents/capabilities/planning/index.js +44 -5
  35. package/src/agents/capabilities/turnRecall/index.js +341 -0
  36. package/src/agents/controller/controllerToolExecutor.js +2 -2
  37. package/src/agents/internal/internalRunner.js +30 -8
  38. package/src/agents/internal/taskControl.js +107 -0
  39. package/src/agents/profiles/coding.js +1 -1
  40. package/src/agents/profiles/main.js +1 -1
  41. package/src/agents/prompts/mainAgent.js +1 -0
  42. package/src/agents/prompts/native/toolDescriptions/bash.js +7 -1
  43. package/src/agents/providers/claudeSessionFiles.js +1 -1
  44. package/src/agents/providers/codexThreadProvider.js +6 -1
  45. package/src/agents/providers/credentials/agy.js +171 -0
  46. package/src/agents/providers/directAuthStatus.js +20 -2
  47. package/src/agents/providers/modelsCatalog.js +26 -5
  48. package/src/agents/providers/nativeTransport.js +145 -73
  49. package/src/agents/providers/providerId.js +17 -0
  50. package/src/agents/providers/runtimeConfig.js +67 -20
  51. package/src/agents/providers/transports/antigravityTransport.js +242 -0
  52. package/src/agents/providers/transports/index.js +1 -0
  53. package/src/agents/providers/transports/openaiChatTransport.js +3 -2
  54. package/src/agents/providers/transports/openaiResponsesTransport.js +2 -1
  55. package/src/agents/providers/transports/responsesProtocol.js +119 -18
  56. package/src/agents/providers/transports/transportContract.js +1 -0
  57. package/src/agents/providers/upstreamRuntime.js +3 -1
  58. package/src/agents/runtime/context/contextBudget.js +1 -19
  59. package/src/agents/runtime/context/contextWindow.js +5 -0
  60. package/src/agents/runtime/context/replayHistory.js +16 -10
  61. package/src/agents/runtime/context/runtimeStore.js +0 -1
  62. package/src/agents/runtime/context/sessionJournal.js +1 -1
  63. package/src/agents/runtime/context/slidingWindowManager.js +792 -0
  64. package/src/agents/runtime/context/topicSelector.js +338 -0
  65. package/src/agents/runtime/context/turnAnalyzer.js +767 -0
  66. package/src/agents/runtime/context/turnIndexStore.js +515 -0
  67. package/src/agents/runtime/core/agentLoop.js +140 -35
  68. package/src/agents/runtime/core/executionBudget.js +2 -1
  69. package/src/agents/runtime/core/toolErrorGuard.js +39 -0
  70. package/src/agents/runtime/createAgentRuntime.js +80 -7
  71. package/src/agents/runtime/index.js +5 -0
  72. package/src/agents/runtime/protocol/materialize.js +1 -1
  73. package/src/agents/runtime/tasks/hooks.js +137 -0
  74. package/src/app/chat/ChatController.js +8 -4
  75. package/src/app/chat/daemonMessageRouter.js +3 -1
  76. package/src/app/chat/inputSubmitHandler.js +2 -2
  77. package/src/app/chat/transport.js +1 -1
  78. package/src/app/cli/browserCommands.js +340 -0
  79. package/src/app/cli/busCoreCommands.js +63 -3
  80. package/src/app/cli/features/doctor.js +21 -0
  81. package/src/app/cli/metricsCommands.js +1 -1
  82. package/src/app/cli/run.js +81 -1
  83. package/src/app/cli/setupCommands.js +200 -0
  84. package/src/code/UcodeController.js +31 -1
  85. package/src/code/agent.js +76 -25
  86. package/src/code/busConsumer.js +13 -12
  87. package/src/code/commands.js +0 -1
  88. package/src/code/context/assembler.js +11 -88
  89. package/src/code/context/planGraphService.js +121 -6
  90. package/src/code/context/planProjection.js +10 -2
  91. package/src/code/context/reducers.js +172 -4
  92. package/src/code/context/stateCommit.js +0 -32
  93. package/src/code/context/transcript.js +7 -4
  94. package/src/code/internalThread.js +9 -1
  95. package/src/code/launcher/ucode.js +4 -2
  96. package/src/code/modelCommand.js +6 -5
  97. package/src/code/nativeRunner.js +232 -62
  98. package/src/code/repl.js +27 -1
  99. package/src/code/runtime/agentWakeup.js +20 -3
  100. package/src/code/runtime/backgroundWakeHost.js +45 -0
  101. package/src/code/runtime/taskFocusContext.js +7 -0
  102. package/src/code/runtime/taskLoop.js +24 -1
  103. package/src/code/sessionStore.js +14 -10
  104. package/src/code/taskDecomposer.js +16 -7
  105. package/src/code/tools/backgroundProcess.js +23 -0
  106. package/src/code/tools/bash.js +764 -12
  107. package/src/code/tools/executor.js +13 -4
  108. package/src/code/tools/planGraph.js +1 -0
  109. package/src/code/tools/specs.js +62 -4
  110. package/src/code/tools/taskRun.js +38 -0
  111. package/src/config.js +92 -6
  112. package/src/coordination/bus/index.js +2 -2
  113. package/src/coordination/bus/message.js +10 -1
  114. package/src/coordination/bus/nickname.js +3 -1
  115. package/src/coordination/bus/subscriber.js +25 -10
  116. package/src/coordination/bus/utils.js +4 -0
  117. package/src/coordination/bus/wakeEndpoint.js +198 -0
  118. package/src/coordination/history/agentPerformance.js +18 -18
  119. package/src/coordination/history/agentTrace.js +7 -3
  120. package/src/coordination/state/paths.js +4 -0
  121. package/src/coordination/state/workspaceAccess.js +3 -1
  122. package/src/orchestration/groups/modelConfig.js +66 -0
  123. package/src/orchestration/groups/validateTemplate.js +2 -0
  124. package/src/runtime/browser/broker.js +1027 -0
  125. package/src/runtime/browser/brokerClient.js +108 -0
  126. package/src/runtime/browser/componentInstaller.js +275 -0
  127. package/src/runtime/browser/installState.js +329 -0
  128. package/src/runtime/browser/manifest.js +145 -0
  129. package/src/runtime/browser/native-host-runner.js +198 -0
  130. package/src/runtime/browser/nativeHost.js +213 -0
  131. package/src/runtime/browser/nativeMessagingProtocol.js +50 -0
  132. package/src/runtime/browser/paths.js +134 -0
  133. package/src/runtime/browser/playwrightSession.js +614 -0
  134. package/src/runtime/daemon/agentHost.js +175 -28
  135. package/src/runtime/daemon/busBridge.js +2 -1
  136. package/src/runtime/daemon/deliveryScheduler.js +70 -2
  137. package/src/runtime/daemon/globalDaemon.js +20 -0
  138. package/src/runtime/daemon/groupOrchestrator.js +20 -1
  139. package/src/runtime/daemon/index.js +6 -4
  140. package/src/runtime/daemon/ops.js +14 -8
  141. package/src/tools/handlers/listAgents.js +1 -1
  142. package/src/tools/handlers/readBusSummary.js +1 -1
  143. package/src/tools/handlers/routeAgent.js +122 -5
  144. package/src/tools/schemaFixtures.js +1 -1
  145. package/src/ui/agentSurface.js +60 -6
  146. package/src/ui/format/index.js +34 -2
  147. package/src/ui/format/markdownRenderer.js +4 -2
  148. package/src/ui/rustChatHost.js +22 -7
  149. package/src/ui/rustMultiSession.js +14 -2
  150. package/src/ui/rustUcodeHost.js +249 -80
  151. package/src/ui/ucodeAgentSession.js +88 -0
  152. package/templates/groups/build-lane.json +57 -3
  153. package/templates/groups/build-ultra.json +114 -6
  154. package/templates/groups/design-system.json +57 -3
  155. package/templates/groups/product-discovery.json +57 -3
  156. package/templates/groups/ui-plan-review.json +57 -3
  157. package/templates/groups/ui-polish.json +57 -3
  158. package/templates/groups/verify-ship.json +57 -3
  159. package/src/agents/runtime/context/checkpointStore.js +0 -38
  160. package/src/agents/runtime/context/compaction.js +0 -151
@@ -0,0 +1,515 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { randomUUID } = require("crypto");
6
+ const { withFileLock } = require("./fileLock");
7
+
8
+ const SAFE_NAMESPACE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;
9
+ const SAFE_SESSION_ID = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
10
+
11
+ const TURN_KINDS = new Set(["user", "system_wake", "tool_continuation", "resumed_interaction"]);
12
+ const TURN_OUTCOMES = new Set(["completed", "failed", "cancelled", "interrupted", "paused", "unknown"]);
13
+
14
+ function ensureValidNamespace(namespace) {
15
+ const value = String(namespace || "runtime").trim();
16
+ if (!SAFE_NAMESPACE.test(value)) throw new Error(`Invalid context namespace: ${namespace}`);
17
+ return value;
18
+ }
19
+
20
+ function ensureValidSessionId(sessionId) {
21
+ const value = String(sessionId || "default").trim();
22
+ if (!SAFE_SESSION_ID.test(value)) throw new Error(`Invalid context sessionId: ${sessionId}`);
23
+ return value;
24
+ }
25
+
26
+ function dedupeStrings(values, limit = 64) {
27
+ if (!Array.isArray(values)) return [];
28
+ const seen = new Set();
29
+ const result = [];
30
+ for (const raw of values) {
31
+ const item = typeof raw === "string" ? raw.trim() : "";
32
+ if (!item || seen.has(item)) continue;
33
+ seen.add(item);
34
+ result.push(item);
35
+ if (result.length >= limit) break;
36
+ }
37
+ return result;
38
+ }
39
+
40
+ function clampString(value, maxChars = 1200) {
41
+ const text = typeof value === "string" ? value.trim() : "";
42
+ if (!text) return "";
43
+ return text.length > maxChars ? `${text.slice(0, Math.max(0, maxChars - 3))}...` : text;
44
+ }
45
+
46
+ function normalizeTopic(value) {
47
+ const raw = String(value || "").trim().toLowerCase()
48
+ .replace(/[^a-z0-9\u4e00-\u9fff_/-]+/g, "-")
49
+ .replace(/^-+|-+$/g, "");
50
+ return raw ? raw.slice(0, 64) : "general";
51
+ }
52
+
53
+ function normalizeTurnRecord(input = {}, fallbackIndex = 0) {
54
+ const turnId = String(input.turnId || "").trim();
55
+ if (!turnId) throw new Error("turnId is required");
56
+ const turnIndex = Number.isInteger(input.turnIndex) && input.turnIndex >= 0 ? input.turnIndex : fallbackIndex;
57
+ const historyOffset = Number.isInteger(input.historyOffset) && input.historyOffset >= 0 ? input.historyOffset : 0;
58
+ const historyEnd = Number.isInteger(input.historyEnd) && input.historyEnd >= historyOffset ? input.historyEnd : historyOffset;
59
+ const turnKind = TURN_KINDS.has(input.turnKind) ? input.turnKind : "user";
60
+ const outcome = TURN_OUTCOMES.has(input.outcome) ? input.outcome : "completed";
61
+ return {
62
+ turnId,
63
+ turnIndex,
64
+ historyOffset,
65
+ historyEnd,
66
+ turnKind,
67
+ outcome,
68
+ startedAt: input.startedAt || input.ts || new Date().toISOString(),
69
+ endedAt: input.endedAt || input.ts || new Date().toISOString(),
70
+ topic: normalizeTopic(input.topic),
71
+ rawUserText: clampString(input.rawUserText, 1200),
72
+ userSummary: clampString(input.userSummary, 360),
73
+ assistantSummary: clampString(input.assistantSummary, 500),
74
+ keyActions: dedupeStrings(input.keyActions, 24),
75
+ touchedFiles: dedupeStrings(input.touchedFiles, 48),
76
+ modifiedFiles: dedupeStrings(input.modifiedFiles, 48),
77
+ artifactIds: dedupeStrings(input.artifactIds, 32),
78
+ decisions: dedupeStrings(input.decisions, 16),
79
+ keywords: dedupeStrings(input.keywords, 48),
80
+ enrichmentVersion: Number.isInteger(input.enrichmentVersion) && input.enrichmentVersion > 0 ? input.enrichmentVersion : 1,
81
+ enrichedAt: input.enrichedAt || null,
82
+ contentHash: typeof input.contentHash === "string" ? input.contentHash : "",
83
+ revision: Number.isInteger(input.revision) && input.revision > 0 ? input.revision : 1,
84
+ };
85
+ }
86
+
87
+ function mergeTurnRecords(existing, incoming, options = {}) {
88
+ const phase = options.phase || (incoming.enrichmentVersion >= 2 ? "B" : "A");
89
+ if (!existing) return normalizeTurnRecord(incoming, options.fallbackIndex || 0);
90
+
91
+ if (phase === "B") {
92
+ if (options.expectedHash && existing.contentHash && options.expectedHash !== existing.contentHash) {
93
+ return existing;
94
+ }
95
+ const nextTopic = incoming.topic && normalizeTopic(incoming.topic) !== "general"
96
+ ? normalizeTopic(incoming.topic)
97
+ : existing.topic;
98
+ return {
99
+ ...existing,
100
+ topic: nextTopic,
101
+ userSummary: clampString(incoming.userSummary, 360) || existing.userSummary,
102
+ assistantSummary: clampString(incoming.assistantSummary, 500) || existing.assistantSummary,
103
+ keyActions: dedupeStrings([...existing.keyActions, ...(incoming.keyActions || [])], 24),
104
+ touchedFiles: dedupeStrings([...existing.touchedFiles, ...(incoming.touchedFiles || [])], 48),
105
+ modifiedFiles: dedupeStrings([...existing.modifiedFiles, ...(incoming.modifiedFiles || [])], 48),
106
+ artifactIds: dedupeStrings([...existing.artifactIds, ...(incoming.artifactIds || [])], 32),
107
+ decisions: dedupeStrings([...existing.decisions, ...(incoming.decisions || [])], 16),
108
+ keywords: dedupeStrings([...existing.keywords, ...(incoming.keywords || [])], 48),
109
+ enrichmentVersion: Math.max(existing.enrichmentVersion || 1, Number(incoming.enrichmentVersion) || 2),
110
+ enrichedAt: incoming.enrichedAt || new Date().toISOString(),
111
+ revision: (existing.revision || 1) + 1,
112
+ };
113
+ }
114
+
115
+ // Phase A update (e.g., resuming a paused turn or re-indexing a completed turn).
116
+ const normalized = normalizeTurnRecord(incoming, existing.turnIndex);
117
+ const hashChanged = existing.contentHash && normalized.contentHash && existing.contentHash !== normalized.contentHash;
118
+ const keepEnrichedTopic = existing.enrichmentVersion >= 2 && existing.topic && existing.topic !== "general" && normalized.topic === "general";
119
+ return {
120
+ ...normalized,
121
+ turnIndex: existing.turnIndex,
122
+ startedAt: existing.startedAt || normalized.startedAt,
123
+ topic: keepEnrichedTopic ? existing.topic : normalized.topic,
124
+ userSummary: existing.enrichmentVersion >= 2 && !hashChanged && existing.userSummary
125
+ ? existing.userSummary
126
+ : (normalized.userSummary || existing.userSummary),
127
+ assistantSummary: normalized.assistantSummary || existing.assistantSummary,
128
+ keyActions: dedupeStrings([...existing.keyActions, ...normalized.keyActions], 24),
129
+ touchedFiles: dedupeStrings([...existing.touchedFiles, ...normalized.touchedFiles], 48),
130
+ modifiedFiles: dedupeStrings([...existing.modifiedFiles, ...normalized.modifiedFiles], 48),
131
+ artifactIds: dedupeStrings([...existing.artifactIds, ...normalized.artifactIds], 32),
132
+ decisions: dedupeStrings([...existing.decisions, ...normalized.decisions], 16),
133
+ keywords: dedupeStrings([...existing.keywords, ...normalized.keywords], 48),
134
+ enrichmentVersion: hashChanged ? 1 : Math.max(existing.enrichmentVersion || 1, normalized.enrichmentVersion || 1),
135
+ enrichedAt: hashChanged ? null : (normalized.enrichedAt || existing.enrichedAt),
136
+ revision: (existing.revision || 1) + 1,
137
+ };
138
+ }
139
+
140
+ function tokenizeForSearch(text) {
141
+ const input = String(text || "");
142
+ if (!input.trim()) return [];
143
+ const tokens = [];
144
+
145
+ // Full path-like segments and filenames.
146
+ const pathMatches = input.match(/[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)+/g) || [];
147
+ for (const fullPath of pathMatches) {
148
+ const lower = fullPath.toLowerCase();
149
+ tokens.push({ term: lower, weight: 1.5 });
150
+ const base = path.posix.basename(lower);
151
+ if (base) tokens.push({ term: base, weight: 1.3 });
152
+ const stem = base.replace(/\.[a-z0-9]+$/, "");
153
+ if (stem && stem !== base) tokens.push({ term: stem, weight: 1.1 });
154
+ }
155
+
156
+ // Identifiers and ASCII words + camelCase/snake_case sub-tokens.
157
+ const asciiMatches = input.match(/[a-zA-Z0-9][a-zA-Z0-9_.-]*/g) || [];
158
+ for (const rawWord of asciiMatches) {
159
+ const lower = rawWord.toLowerCase();
160
+ if (lower.length >= 2) tokens.push({ term: lower, weight: 1.0 });
161
+ const subParts = rawWord
162
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
163
+ .split(/[^a-zA-Z0-9]+/)
164
+ .map((s) => s.toLowerCase())
165
+ .filter((s) => s.length >= 2);
166
+ for (const part of subParts) {
167
+ if (part !== lower) tokens.push({ term: part, weight: 0.7 });
168
+ }
169
+ }
170
+
171
+ // CJK contiguous runs -> overlapping bigrams + fallback unigrams.
172
+ const cjkRuns = input.match(/[\u4e00-\u9fff]+/g) || [];
173
+ for (const run of cjkRuns) {
174
+ if (run.length === 1) {
175
+ tokens.push({ term: run, weight: 0.9 });
176
+ continue;
177
+ }
178
+ for (let i = 0; i < run.length - 1; i += 1) {
179
+ tokens.push({ term: run.slice(i, i + 2), weight: 1.1 });
180
+ }
181
+ for (let i = 0; i < run.length; i += 1) {
182
+ tokens.push({ term: run[i], weight: 0.3 });
183
+ }
184
+ }
185
+
186
+ return tokens;
187
+ }
188
+
189
+ function buildTurnTermMap(turn) {
190
+ const fieldInputs = [
191
+ { text: turn.topic, weight: 2.5 },
192
+ { text: [...(turn.modifiedFiles || []), ...(turn.touchedFiles || [])].join(" "), weight: 3.0 },
193
+ { text: [...(turn.artifactIds || []), ...(turn.keywords || [])].join(" "), weight: 2.2 },
194
+ { text: `${turn.userSummary || ""} ${turn.assistantSummary || ""}`, weight: 1.6 },
195
+ { text: turn.rawUserText || "", weight: 1.3 },
196
+ { text: [...(turn.keyActions || []), ...(turn.decisions || [])].join(" "), weight: 1.2 },
197
+ ];
198
+ const termFreq = new Map();
199
+ for (const { text, weight } of fieldInputs) {
200
+ for (const { term, weight: tokenWeight } of tokenizeForSearch(text)) {
201
+ const prev = termFreq.get(term) || 0;
202
+ termFreq.set(term, prev + weight * tokenWeight);
203
+ }
204
+ }
205
+ return termFreq;
206
+ }
207
+
208
+ function appendJsonLineLocked(filePath, lineText) {
209
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
210
+ const fd = fs.openSync(filePath, "a", 0o600);
211
+ try {
212
+ fs.writeFileSync(fd, lineText, "utf8");
213
+ fs.fsyncSync(fd);
214
+ } finally {
215
+ fs.closeSync(fd);
216
+ }
217
+ }
218
+
219
+ function writeAtomicLocked(filePath, text) {
220
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
221
+ const tempPath = `${filePath}.${process.pid}-${randomUUID()}.tmp`;
222
+ let fd;
223
+ try {
224
+ fd = fs.openSync(tempPath, "w", 0o600);
225
+ fs.writeFileSync(fd, text, "utf8");
226
+ fs.fsyncSync(fd);
227
+ fs.closeSync(fd);
228
+ fd = null;
229
+ fs.renameSync(tempPath, filePath);
230
+ } finally {
231
+ if (fd !== null && fd !== undefined) {
232
+ try { fs.closeSync(fd); } catch {}
233
+ }
234
+ if (fs.existsSync(tempPath)) {
235
+ try { fs.rmSync(tempPath, { force: true }); } catch {}
236
+ }
237
+ }
238
+ }
239
+
240
+ function readTurnsFromDisk(turnsFile, { repairTornTail = false } = {}) {
241
+ if (!fs.existsSync(turnsFile)) return { records: [], order: [], validBytes: 0 };
242
+ const raw = fs.readFileSync(turnsFile);
243
+ if (!raw.length) return { records: [], order: [], validBytes: 0 };
244
+ const text = raw.toString("utf8");
245
+ const lines = text.split("\n");
246
+ const hasTrailingNewline = text.endsWith("\n");
247
+ const limit = hasTrailingNewline ? lines.length - 1 : lines.length;
248
+ const byId = new Map();
249
+ const order = [];
250
+ let byteCursor = 0;
251
+ let validBytes = 0;
252
+
253
+ for (let i = 0; i < limit; i += 1) {
254
+ const line = lines[i];
255
+ const lineBytes = Buffer.byteLength(`${line}\n`, "utf8");
256
+ const isLastFragment = i === limit - 1 && !hasTrailingNewline;
257
+ if (!line.trim()) {
258
+ byteCursor += isLastFragment ? Buffer.byteLength(line, "utf8") : lineBytes;
259
+ if (!isLastFragment) validBytes = byteCursor;
260
+ continue;
261
+ }
262
+ try {
263
+ const parsed = JSON.parse(line);
264
+ if (parsed && typeof parsed === "object" && parsed.turnId) {
265
+ if (!byId.has(parsed.turnId)) order.push(parsed.turnId);
266
+ byId.set(parsed.turnId, parsed);
267
+ }
268
+ byteCursor += isLastFragment ? Buffer.byteLength(line, "utf8") : lineBytes;
269
+ if (!isLastFragment) validBytes = byteCursor;
270
+ } catch {
271
+ // Truncated tail after a crash. Stop before the corrupt fragment.
272
+ if (repairTornTail && validBytes < raw.length) {
273
+ try { fs.truncateSync(turnsFile, validBytes); } catch {}
274
+ }
275
+ break;
276
+ }
277
+ }
278
+
279
+ const records = order.map((id) => byId.get(id)).filter(Boolean);
280
+ records.sort((a, b) => (a.turnIndex || 0) - (b.turnIndex || 0));
281
+ return { records, order, validBytes };
282
+ }
283
+
284
+ function createTurnIndexStore({
285
+ workspaceRoot = process.cwd(),
286
+ namespace = "runtime",
287
+ sessionId = "default",
288
+ redact = null,
289
+ } = {}) {
290
+ const ns = ensureValidNamespace(namespace);
291
+ const sid = ensureValidSessionId(sessionId);
292
+ const dir = path.join(path.resolve(workspaceRoot || process.cwd()), ".ufoo", "agent", ns, "context");
293
+ const turnsFile = path.join(dir, `${sid}.turns.jsonl`);
294
+ const windowFile = path.join(dir, `${sid}.window.json`);
295
+ const sanitize = typeof redact === "function" ? redact : (value) => value;
296
+
297
+ function listTurnsLocked(filter = {}) {
298
+ const { records } = readTurnsFromDisk(turnsFile, { repairTornTail: false });
299
+ let result = records;
300
+ if (filter.topic) {
301
+ const targetTopic = normalizeTopic(filter.topic);
302
+ result = result.filter((record) => normalizeTopic(record.topic) === targetTopic);
303
+ }
304
+ if (Array.isArray(filter.outcomes) && filter.outcomes.length) {
305
+ const allowed = new Set(filter.outcomes);
306
+ result = result.filter((record) => allowed.has(record.outcome));
307
+ }
308
+ if (Array.isArray(filter.excludeTurnIds) && filter.excludeTurnIds.length) {
309
+ const excluded = new Set(filter.excludeTurnIds);
310
+ result = result.filter((record) => !excluded.has(record.turnId));
311
+ }
312
+ return result;
313
+ }
314
+
315
+ function listTurns(filter = {}) {
316
+ if (!fs.existsSync(turnsFile)) return [];
317
+ return withFileLock(turnsFile, () => listTurnsLocked(filter));
318
+ }
319
+
320
+ function getTurn(turnId) {
321
+ const id = String(turnId || "").trim();
322
+ if (!id || !fs.existsSync(turnsFile)) return null;
323
+ return withFileLock(turnsFile, () => {
324
+ const { records } = readTurnsFromDisk(turnsFile, { repairTornTail: false });
325
+ return records.find((record) => record.turnId === id) || null;
326
+ });
327
+ }
328
+
329
+ function upsertTurn(record, options = {}) {
330
+ return withFileLock(turnsFile, () => {
331
+ const { records } = readTurnsFromDisk(turnsFile, { repairTornTail: true });
332
+ const existingIndex = records.findIndex((item) => item.turnId === record.turnId);
333
+ const existing = existingIndex >= 0 ? records[existingIndex] : null;
334
+ const nextFallbackIndex = records.reduce((max, item) => Math.max(max, (item.turnIndex || 0) + 1), 0);
335
+ const merged = mergeTurnRecords(existing, record, {
336
+ ...options,
337
+ fallbackIndex: nextFallbackIndex,
338
+ });
339
+ const safeRecord = sanitize(merged);
340
+ if (existing) {
341
+ if (options.phase === "B" && safeRecord === existing) return existing;
342
+ records[existingIndex] = safeRecord;
343
+ const body = records.map((item) => JSON.stringify(item)).join("\n") + "\n";
344
+ writeAtomicLocked(turnsFile, body);
345
+ } else {
346
+ appendJsonLineLocked(turnsFile, `${JSON.stringify(safeRecord)}\n`);
347
+ }
348
+ return safeRecord;
349
+ });
350
+ }
351
+
352
+ function listTopics() {
353
+ const turns = listTurns();
354
+ const groups = new Map();
355
+ for (const turn of turns) {
356
+ const topic = normalizeTopic(turn.topic);
357
+ const existing = groups.get(topic);
358
+ if (!existing) {
359
+ groups.set(topic, {
360
+ topic,
361
+ turnCount: 1,
362
+ firstTurnIndex: turn.turnIndex,
363
+ lastTurnIndex: turn.turnIndex,
364
+ lastTurnId: turn.turnId,
365
+ modifiedFilesCount: (turn.modifiedFiles || []).length,
366
+ summary: turn.userSummary || turn.assistantSummary || turn.rawUserText || "",
367
+ });
368
+ } else {
369
+ existing.turnCount += 1;
370
+ existing.lastTurnIndex = Math.max(existing.lastTurnIndex, turn.turnIndex);
371
+ existing.lastTurnId = turn.turnId;
372
+ existing.modifiedFilesCount += (turn.modifiedFiles || []).length;
373
+ if (turn.userSummary || turn.assistantSummary) {
374
+ existing.summary = turn.userSummary || turn.assistantSummary;
375
+ }
376
+ }
377
+ }
378
+ return [...groups.values()].sort((a, b) => b.lastTurnIndex - a.lastTurnIndex);
379
+ }
380
+
381
+ function search(query = "", options = {}) {
382
+ const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : 8;
383
+ const turns = listTurns({
384
+ topic: options.topic,
385
+ outcomes: options.outcomes,
386
+ excludeTurnIds: options.excludeTurnIds,
387
+ });
388
+ if (!turns.length) return [];
389
+
390
+ const trimmedQuery = String(query || "").trim();
391
+ if (!trimmedQuery) {
392
+ return turns.slice(-limit).reverse().map((turn) => ({ turn, score: 1, matchedTerms: [] }));
393
+ }
394
+
395
+ const queryTokens = tokenizeForSearch(trimmedQuery);
396
+ const uniqueQueryTerms = new Map();
397
+ for (const { term, weight } of queryTokens) {
398
+ uniqueQueryTerms.set(term, Math.max(uniqueQueryTerms.get(term) || 0, weight));
399
+ }
400
+ if (!uniqueQueryTerms.size) return [];
401
+
402
+ const termMaps = turns.map((turn) => buildTurnTermMap(turn));
403
+ const docFreq = new Map();
404
+ for (const term of uniqueQueryTerms.keys()) {
405
+ let df = 0;
406
+ for (const map of termMaps) {
407
+ if (map.has(term)) df += 1;
408
+ }
409
+ docFreq.set(term, df);
410
+ }
411
+
412
+ const totalDocs = turns.length;
413
+ const lowerQuery = trimmedQuery.toLowerCase();
414
+ const scored = [];
415
+ for (let i = 0; i < turns.length; i += 1) {
416
+ const turn = turns[i];
417
+ const map = termMaps[i];
418
+ let score = 0;
419
+ const matchedTerms = [];
420
+
421
+ if (turn.turnId.toLowerCase() === lowerQuery) {
422
+ score += 12;
423
+ matchedTerms.push(turn.turnId);
424
+ }
425
+
426
+ for (const [term, qWeight] of uniqueQueryTerms.entries()) {
427
+ const tf = map.get(term) || 0;
428
+ if (tf <= 0) continue;
429
+ const df = docFreq.get(term) || 1;
430
+ const idf = Math.log(1 + (totalDocs - df + 0.5) / (df + 0.5));
431
+ const bm25 = (tf / (tf + 1.2)) * idf * qWeight;
432
+ score += bm25;
433
+ matchedTerms.push(term);
434
+ }
435
+
436
+ // Bonus for exact path or symbol substring match in files/keywords.
437
+ const pathAndKeywordHaystack = [
438
+ ...(turn.touchedFiles || []),
439
+ ...(turn.modifiedFiles || []),
440
+ ...(turn.keywords || []),
441
+ ].join("\n").toLowerCase();
442
+ for (const [term] of uniqueQueryTerms.entries()) {
443
+ if (term.length >= 4 && pathAndKeywordHaystack.includes(term)) {
444
+ score += 0.6;
445
+ }
446
+ }
447
+
448
+ if (score > 0) {
449
+ scored.push({
450
+ turn,
451
+ score: Number(score.toFixed(4)),
452
+ matchedTerms: dedupeStrings(matchedTerms, 16),
453
+ });
454
+ }
455
+ }
456
+
457
+ scored.sort((a, b) => (b.score - a.score) || ((b.turn.turnIndex || 0) - (a.turn.turnIndex || 0)));
458
+ return scored.slice(0, limit);
459
+ }
460
+
461
+ function loadWindowState() {
462
+ if (!fs.existsSync(windowFile)) return null;
463
+ return withFileLock(windowFile, () => {
464
+ if (!fs.existsSync(windowFile)) return null;
465
+ try {
466
+ const parsed = JSON.parse(fs.readFileSync(windowFile, "utf8"));
467
+ return parsed && typeof parsed === "object" ? parsed : null;
468
+ } catch {
469
+ return null;
470
+ }
471
+ });
472
+ }
473
+
474
+ function saveWindowState(state) {
475
+ return withFileLock(windowFile, () => {
476
+ const payload = sanitize({
477
+ version: 1,
478
+ ...state,
479
+ updatedAt: new Date().toISOString(),
480
+ });
481
+ writeAtomicLocked(windowFile, `${JSON.stringify(payload, null, 2)}\n`);
482
+ return payload;
483
+ });
484
+ }
485
+
486
+ function remove() {
487
+ for (const filePath of [turnsFile, windowFile]) {
488
+ try {
489
+ if (fs.existsSync(filePath)) fs.rmSync(filePath, { force: true });
490
+ } catch {}
491
+ }
492
+ }
493
+
494
+ return Object.freeze({
495
+ dir,
496
+ turnsFile,
497
+ windowFile,
498
+ namespace: ns,
499
+ sessionId: sid,
500
+ upsertTurn,
501
+ listTurns,
502
+ getTurn,
503
+ listTopics,
504
+ search,
505
+ loadWindowState,
506
+ saveWindowState,
507
+ remove,
508
+ });
509
+ }
510
+
511
+ module.exports = {
512
+ createTurnIndexStore,
513
+ normalizeTopic,
514
+ tokenizeForSearch,
515
+ };