u-foo 3.1.7 → 4.0.1

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 (266) hide show
  1. package/OBSERVABILITY.md +65 -0
  2. package/README.md +238 -21
  3. package/README.zh-CN.md +165 -20
  4. package/SKILLS/ufoo/SKILL.md +40 -4
  5. package/SKILLS/ufoo-bus/SKILL.md +46 -3
  6. package/bin/uclaude.js +4 -0
  7. package/bin/ucodex.js +4 -0
  8. package/bin/ufoo.js +6 -4
  9. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  10. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  11. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  12. package/dist/tui/linux-x64/ufoo-tui +0 -0
  13. package/package.json +14 -7
  14. package/scripts/postinstall-skills.js +53 -0
  15. package/scripts/postinstall.js +11 -16
  16. package/scripts/smoke-native-messages.js +214 -0
  17. package/src/agents/activity/activityDetector.js +1 -1
  18. package/src/agents/activity/activityStateWriter.js +37 -38
  19. package/src/agents/capabilities/agentManagement/index.js +4 -0
  20. package/src/agents/capabilities/agentManagement/service.js +140 -0
  21. package/src/agents/capabilities/agentRouting/index.js +4 -0
  22. package/src/agents/capabilities/coding/index.js +32 -0
  23. package/src/agents/capabilities/coordination/index.js +37 -0
  24. package/src/agents/capabilities/globalRouting/index.js +5 -0
  25. package/src/agents/capabilities/groups/index.js +3 -0
  26. package/src/agents/capabilities/index.js +25 -0
  27. package/src/agents/capabilities/planning/index.js +123 -0
  28. package/src/agents/capabilities/planning/main.js +28 -0
  29. package/src/agents/capabilities/projectDiscovery/index.js +3 -0
  30. package/src/agents/capabilities/scheduling/index.js +3 -0
  31. package/src/agents/capabilities/sharedMemory/index.js +4 -0
  32. package/src/agents/capabilities/skills/index.js +12 -0
  33. package/src/agents/capabilities/taskExecution/index.js +3 -0
  34. package/src/agents/capabilities/taskReports/index.js +6 -0
  35. package/src/agents/controller/controllerToolExecutor.js +40 -22
  36. package/src/agents/controller/index.js +1 -6
  37. package/src/agents/internal/internalRunner.js +181 -76
  38. package/src/agents/launch/index.js +0 -1
  39. package/src/agents/launch/launcher.js +96 -14
  40. package/src/agents/launch/nativeCapabilities.js +40 -0
  41. package/src/agents/launch/nativeMessages.js +362 -0
  42. package/src/agents/launch/notifier.js +15 -20
  43. package/src/agents/launch/readyDetector.js +28 -14
  44. package/src/agents/profiles/coding.js +6 -0
  45. package/src/agents/profiles/globalRouter.js +2 -0
  46. package/src/agents/profiles/main.js +5 -0
  47. package/src/agents/prompts/cooperation.js +14 -0
  48. package/src/agents/prompts/defaultBootstrap.js +1 -1
  49. package/src/agents/prompts/groupBootstrap.js +32 -6
  50. package/src/agents/prompts/mainAgent.js +48 -0
  51. package/src/agents/prompts/native/system.js +4 -1
  52. package/src/agents/prompts/native/tasks.js +2 -2
  53. package/src/agents/prompts/native/ufoo.js +14 -3
  54. package/src/agents/prompts/promptProfiles.js +2 -0
  55. package/src/agents/prompts/reporting.js +16 -0
  56. package/src/agents/providers/claudeEventTranslator.js +9 -1
  57. package/src/agents/providers/claudeThreadProvider.js +47 -4
  58. package/src/agents/providers/clientIdentity.js +75 -0
  59. package/src/agents/providers/codexEventTranslator.js +68 -7
  60. package/src/agents/providers/codexThreadProvider.js +18 -8
  61. package/src/agents/providers/credentials/claude.js +10 -3
  62. package/src/agents/providers/credentials/index.js +2 -0
  63. package/src/agents/providers/directAuthStatus.js +1 -1
  64. package/src/agents/providers/index.js +1 -1
  65. package/src/agents/providers/modelSettings.js +34 -0
  66. package/src/agents/providers/modelsCatalog.js +379 -0
  67. package/src/agents/providers/nativeTransport.js +1146 -0
  68. package/src/agents/providers/runtimeConfig.js +188 -0
  69. package/src/agents/providers/thinkingLevels.js +106 -0
  70. package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
  71. package/src/agents/providers/transports/index.js +10 -0
  72. package/src/agents/providers/transports/openaiChatTransport.js +117 -0
  73. package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
  74. package/src/agents/providers/transports/responsesProtocol.js +504 -0
  75. package/src/agents/providers/transports/systemBlocks.js +16 -0
  76. package/src/agents/providers/transports/transportContract.js +50 -0
  77. package/src/agents/providers/transports/visionBlocks.js +151 -0
  78. package/src/agents/providers/upstreamRuntime.js +135 -0
  79. package/src/agents/runtime/composeCapabilities.js +89 -0
  80. package/src/agents/runtime/context/checkpointStore.js +38 -0
  81. package/src/agents/runtime/context/commandStore.js +43 -0
  82. package/src/agents/runtime/context/compaction.js +151 -0
  83. package/src/agents/runtime/context/contextBudget.js +93 -0
  84. package/src/agents/runtime/context/contextWindow.js +119 -0
  85. package/src/agents/runtime/context/fileLock.js +36 -0
  86. package/src/agents/runtime/context/replayHistory.js +28 -0
  87. package/src/agents/runtime/context/runtimeStore.js +127 -0
  88. package/src/agents/runtime/context/sessionJournal.js +360 -0
  89. package/src/agents/runtime/context/sessionStore.js +57 -0
  90. package/src/agents/runtime/core/agentLoop.js +351 -0
  91. package/src/agents/runtime/core/executionBudget.js +36 -0
  92. package/src/agents/runtime/core/stableJson.js +29 -0
  93. package/src/agents/runtime/core/toolLoopGuard.js +55 -0
  94. package/src/agents/runtime/createAgentRuntime.js +259 -0
  95. package/src/agents/runtime/index.js +14 -0
  96. package/src/agents/runtime/prompts/responseLanguage.js +12 -0
  97. package/src/agents/runtime/protocol/faultHarness.js +90 -0
  98. package/src/agents/runtime/protocol/materialize.js +107 -0
  99. package/src/agents/runtime/protocol/runObservation.js +24 -0
  100. package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
  101. package/src/agents/runtime/protocol/traceContext.js +9 -0
  102. package/src/agents/runtime/tasks/resourceLease.js +66 -0
  103. package/src/agents/runtime/tasks/scheduler.js +73 -0
  104. package/src/agents/runtime/tools/registry.js +57 -0
  105. package/src/app/chat/ChatController.js +29 -45
  106. package/src/app/chat/agentDirectory.js +9 -18
  107. package/src/app/chat/bootstrap.js +1 -2
  108. package/src/app/chat/commandExecutor.js +111 -313
  109. package/src/app/chat/commands.js +39 -45
  110. package/src/app/chat/daemonConnection.js +58 -5
  111. package/src/app/chat/daemonMessageRouter.js +61 -48
  112. package/src/app/chat/historyStore.js +12 -48
  113. package/src/app/chat/inputSubmitHandler.js +21 -35
  114. package/src/app/chat/internalAgentLogHistory.js +19 -60
  115. package/src/app/chat/launchRequestContext.js +42 -0
  116. package/src/app/chat/multiWindow/paneManager.js +91 -164
  117. package/src/app/chat/streamState.js +3 -7
  118. package/src/app/chat/transport.js +1 -1
  119. package/src/app/cli/busCoreCommands.js +9 -0
  120. package/src/app/cli/features/doctor.js +33 -0
  121. package/src/app/cli/features/init.js +5 -5
  122. package/src/app/cli/features/skills.js +16 -4
  123. package/src/app/cli/metricsCommands.js +68 -0
  124. package/src/app/cli/reportCoreCommands.js +37 -0
  125. package/src/app/cli/run.js +82 -42
  126. package/src/app/cli/traceCommands.js +36 -0
  127. package/src/code/agent.js +34 -17
  128. package/src/code/busConsumer.js +1 -3
  129. package/src/code/commands.js +1 -1
  130. package/src/code/context/artifacts.js +12 -11
  131. package/src/code/context/assembler.js +9 -9
  132. package/src/code/context/promptLayers.js +1 -13
  133. package/src/code/context/stableJson.js +2 -27
  134. package/src/code/context/stateCommit.js +2 -1
  135. package/src/code/contextWindow.js +2 -117
  136. package/src/code/conversation/sessionJournal.js +3 -349
  137. package/src/code/internalThread.js +107 -0
  138. package/src/code/launcher/ucode.js +1 -1
  139. package/src/code/launcher/ucodeBootstrap.js +1 -1
  140. package/src/code/modelCommand.js +11 -35
  141. package/src/code/nativeRunner.js +104 -2697
  142. package/src/code/protocol/faultHarness.js +2 -88
  143. package/src/code/protocol/materialize.js +2 -105
  144. package/src/code/protocol/toolCallLedger.js +5 -215
  145. package/src/code/providers/anthropicMessagesTransport.js +2 -118
  146. package/src/code/providers/modelsCatalog.js +1 -317
  147. package/src/code/providers/openaiChatTransport.js +2 -114
  148. package/src/code/providers/openaiResponsesTransport.js +2 -117
  149. package/src/code/providers/responsesProtocol.js +2 -497
  150. package/src/code/providers/transportContract.js +2 -48
  151. package/src/code/providers/visionBlocks.js +2 -149
  152. package/src/code/repl.js +2 -11
  153. package/src/code/sessionStore.js +27 -99
  154. package/src/code/taskDecomposer.js +18 -0
  155. package/src/code/thinkingLevels.js +1 -130
  156. package/src/code/toolBudget.js +1 -17
  157. package/src/code/toolLoopGuard.js +3 -49
  158. package/src/code/tools/artifactRead.js +1 -1
  159. package/src/code/tools/executor.js +373 -0
  160. package/src/code/tools/specs.js +312 -0
  161. package/src/config.js +95 -131
  162. package/src/coordination/bus/deliveryQueue.js +16 -2
  163. package/src/coordination/bus/index.js +14 -9
  164. package/src/coordination/bus/inject.js +15 -7
  165. package/src/coordination/bus/message.js +15 -1
  166. package/src/coordination/bus/nativeReceipts.js +100 -0
  167. package/src/coordination/bus/nickname.js +1 -1
  168. package/src/coordination/bus/queue.js +1 -3
  169. package/src/coordination/bus/subscriber.js +3 -2
  170. package/src/coordination/bus/utils.js +8 -4
  171. package/src/coordination/history/agentPerformance.js +279 -0
  172. package/src/coordination/history/agentSurface.js +142 -0
  173. package/src/coordination/history/agentTrace.js +249 -0
  174. package/src/coordination/memory/index.js +5 -21
  175. package/src/coordination/report/store.js +103 -83
  176. package/src/coordination/state/agentsStore.js +57 -3
  177. package/src/coordination/state/fileLock.js +2 -0
  178. package/src/coordination/state/workspaceAccess.js +36 -0
  179. package/src/orchestration/controller/index.js +1 -8
  180. package/src/orchestration/controller/launchRouting.js +1 -1
  181. package/src/orchestration/solo/commands.js +3 -1
  182. package/src/runtime/contracts/agentMode.js +26 -0
  183. package/src/runtime/contracts/eventContract.js +3 -0
  184. package/src/runtime/contracts/uiProtocol.js +20 -17
  185. package/src/runtime/daemon/agentHost.js +407 -0
  186. package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
  187. package/src/runtime/daemon/busBridge.js +396 -0
  188. package/src/runtime/daemon/claudeChannel.js +159 -0
  189. package/src/runtime/daemon/controlPlaneService.js +28 -18
  190. package/src/runtime/daemon/cronOps.js +25 -17
  191. package/src/runtime/daemon/deliveryScheduler.js +32 -5
  192. package/src/runtime/daemon/globalDaemon.js +28 -1
  193. package/src/runtime/daemon/groupOrchestrator.js +21 -5
  194. package/src/runtime/daemon/groupStatus.js +20 -0
  195. package/src/runtime/daemon/index.js +120 -375
  196. package/src/runtime/daemon/ipcServer.js +32 -10
  197. package/src/runtime/daemon/mcpConfigure.js +113 -20
  198. package/src/runtime/daemon/mcpHttpServer.js +27 -5
  199. package/src/runtime/daemon/mcpServer.js +8 -5
  200. package/src/runtime/daemon/mcpStdioProxy.js +127 -10
  201. package/src/runtime/daemon/nicknameScope.js +1 -1
  202. package/src/runtime/daemon/ops.js +68 -40
  203. package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
  204. package/src/runtime/daemon/promptRequest.js +92 -570
  205. package/src/runtime/daemon/providerSessions.js +67 -33
  206. package/src/runtime/daemon/reportControlBus.js +59 -25
  207. package/src/runtime/daemon/status.js +9 -6
  208. package/src/runtime/privacy/redactor.js +2 -2
  209. package/src/runtime/projects/identity.js +2 -1
  210. package/src/runtime/projects/registry.js +98 -38
  211. package/src/tools/controllerSchemas.js +28 -0
  212. package/src/tools/handlers/dispatchMessage.js +5 -2
  213. package/src/tools/handlers/listAgents.js +3 -1
  214. package/src/tools/handlers/readBusSummary.js +3 -1
  215. package/src/tools/handlers/readProjectRegistry.js +29 -2
  216. package/src/tools/handlers/routeAgent.js +35 -0
  217. package/src/tools/handlers/tier2.js +4 -2
  218. package/src/tools/index.js +1 -0
  219. package/src/tools/registry.js +6 -0
  220. package/src/tools/schemaFixtures.js +42 -5
  221. package/src/tools/tier0/readAgentMetrics.js +14 -0
  222. package/src/tools/tier0/readAgentTrace.js +12 -0
  223. package/src/tools/tier1/routeAgent.js +2 -2
  224. package/src/tools/tier2/runtimeCoordination.js +38 -0
  225. package/src/tools/types.js +2 -0
  226. package/src/ui/agentPresentation.js +109 -0
  227. package/src/ui/agentSettingsController.js +107 -0
  228. package/src/ui/agentSurface.js +270 -0
  229. package/src/ui/dashboardBridge.js +1 -1
  230. package/src/ui/format/banner.js +9 -15
  231. package/src/ui/format/index.js +14 -10
  232. package/src/ui/format/loopSummary.js +50 -0
  233. package/src/ui/format/markdownRenderer.js +3 -4
  234. package/src/ui/format/startupBanner.js +50 -0
  235. package/src/ui/multiPaneBusMirror.js +29 -3
  236. package/src/ui/rustChatHost.js +316 -599
  237. package/src/ui/rustMultiSession.js +288 -73
  238. package/src/ui/rustUcodeHost.js +21 -88
  239. package/src/ui/settingsBridge.js +34 -14
  240. package/src/ui/toolMergeBridge.js +0 -4
  241. package/src/ui/uiHostServer.js +5 -8
  242. package/src/agents/controller/loopObservability.js +0 -200
  243. package/src/agents/controller/loopRuntime.js +0 -472
  244. package/src/agents/controller/ufooAgent.js +0 -829
  245. package/src/agents/launch/ptyRunner.js +0 -1135
  246. package/src/agents/providers/upstreamTransport.js +0 -689
  247. package/src/app/chat/agentBar.js +0 -135
  248. package/src/app/chat/agentEnter.js +0 -70
  249. package/src/app/chat/agentSockets.js +0 -225
  250. package/src/app/chat/dashboardView.js +0 -405
  251. package/src/app/chat/multiWindow/index.js +0 -310
  252. package/src/app/chat/multiWindow/paneLayout.js +0 -84
  253. package/src/app/chat/multiWindow/renderer.js +0 -420
  254. package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
  255. package/src/app/chat/multiWindow/vtFrame.js +0 -93
  256. package/src/app/chat/rawKeyMap.js +0 -42
  257. package/src/app/chat/settingsController.js +0 -111
  258. package/src/orchestration/controller/flags.js +0 -167
  259. package/src/orchestration/controller/gateRouter.js +0 -211
  260. package/src/orchestration/controller/routerFastPath.js +0 -22
  261. package/src/orchestration/controller/routerFinalize.js +0 -222
  262. package/src/orchestration/controller/shadowGuard.js +0 -280
  263. package/src/runtime/daemon/promptLoop.js +0 -136
  264. package/src/runtime/privacy/shadowDiff.js +0 -174
  265. package/src/ui/multiWindowHandoff.js +0 -232
  266. package/src/ui/ptyHandoff.js +0 -23
@@ -0,0 +1,249 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { getUfooPaths } = require("../state/paths");
6
+ const { redactSecrets } = require("../../runtime/privacy/redactor");
7
+ const { normalizeTraceContext } = require("../../agents/runtime/protocol/traceContext");
8
+ const { observationFingerprint } = require("../../agents/runtime/protocol/runObservation");
9
+ const { summarizeAgentPerformance } = require("./agentPerformance");
10
+
11
+ const TYPES = { run_config: "run.config", task_started: "task.started", task_completed: "task.completed", task_failed: "task.failed", task_cancelled: "task.cancelled", task_paused: "task.paused",
12
+ turn_started: "model.started", turn_completed: "model.completed", turn_failed: "model.failed", tool_call: "tool.started", text_delta: "message.delta", thinking_delta: "thinking.delta", context_usage: "context.usage" };
13
+ const clip = value => String(value || "").replace(/\s+/g, " ").slice(0, 240);
14
+
15
+ /** Read-only view over canonical journals, reports, display events and queues. */
16
+ function readAgentTrace(projectRoot, options = {}) {
17
+ const root = path.resolve(projectRoot);
18
+ const paths = getUfooPaths(root);
19
+ const warnings = [];
20
+ const entries = dir => {
21
+ try { return fs.readdirSync(dir, { withFileTypes: true }); }
22
+ catch (error) { if (error.code !== "ENOENT") warnings.push({ source: path.relative(root, dir), code: error.code || "source_unavailable" }); return []; }
23
+ };
24
+ let remaining = Math.max(1, Math.floor(Number(options.maxReadBytes) || 32 * 1024 * 1024));
25
+ const read = file => {
26
+ let fd;
27
+ try {
28
+ const stat = fs.lstatSync(file);
29
+ if (stat.isSymbolicLink()) return [];
30
+ if (!stat.isFile()) { warnings.push({ source: path.relative(root, file), code: "invalid_source_type" }); return []; }
31
+ fd = fs.openSync(file, "r");
32
+ const size = fs.fstatSync(fd).size;
33
+ const count = Math.min(size, 2 * 1024 * 1024, remaining);
34
+ if (count < size) warnings.push({ source: path.relative(root, file), code: "source_tail_truncated", totalBytes: size, readBytes: count });
35
+ if (!count) return [];
36
+ remaining -= count;
37
+ const buffer = Buffer.alloc(count);
38
+ fs.readSync(fd, buffer, 0, count, size - count);
39
+ const text = buffer.toString("utf8");
40
+ let lines = text.split("\n");
41
+ if (lines.at(-1)?.trim()) { warnings.push({ source: path.relative(root, file), code: "incomplete_record" }); lines.pop(); }
42
+ if (count < size) lines.shift();
43
+ return lines.flatMap((line, index) => {
44
+ if (!line.trim()) return [];
45
+ try {
46
+ const value = JSON.parse(line);
47
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid record");
48
+ return [{ value, line: index, source: path.relative(root, file) }];
49
+ }
50
+ catch { warnings.push({ source: path.relative(root, file), code: "incomplete_or_invalid_record" }); return []; }
51
+ });
52
+ } catch (error) {
53
+ if (error.code !== "ENOENT") warnings.push({ source: path.relative(root, file), code: error.code || "source_unavailable" });
54
+ return [];
55
+ } finally { if (fd !== undefined) fs.closeSync(fd); }
56
+ };
57
+ const runtimes = [];
58
+ for (const namespace of entries(paths.agentDir).filter(e => e.isDirectory())) {
59
+ const dir = path.join(paths.agentDir, namespace.name, "runtimes");
60
+ for (const session of entries(dir).filter(e => e.isDirectory())) runtimes.push(path.join(dir, session.name, "events.jsonl"));
61
+ }
62
+ if (runtimes.length > 200) warnings.push({ code: "runtime_file_limit", total: runtimes.length, read: 200 });
63
+ const modified = file => { try { return fs.statSync(file).mtimeMs; } catch { return 0; } };
64
+ const records = runtimes.sort((a, b) => modified(b) - modified(a)).slice(0, 200).flatMap(read);
65
+ const tasks = new Map();
66
+ const events = [];
67
+ function add(event, record, index = "") {
68
+ const value = { id: `${record.source}:${record.value.eventId || record.value.seq || record.value.sequence || record.value.entry_id || record.value.timestamp || record.line}${index}`,
69
+ source: record.source, ...event, time: String(event.time || event.timestamp || event.ts || "") };
70
+ if (event.type === "observation.warning") warnings.push({ source: record.source, code: event.warning?.code || "observation_unavailable" });
71
+ delete value.eventId;
72
+ if (!options.details) { delete value.args; delete value.result; delete value.text; delete value.phase; delete value.message; delete value.error; }
73
+ events.push(value);
74
+ }
75
+ function normalize(event) {
76
+ const result = event.result || {};
77
+ return { type: event.type, time: event.time || event.timestamp || "", sequence: event.sequence,
78
+ sessionId: event.sessionId, agentId: event.agentId || (event.sessionId === "control" ? "ufoo-agent" : ""),
79
+ traceId: event.traceId, taskId: event.taskId || event.request?.taskId, taskRunId: event.taskRunId, parentTaskRunId: event.parentTaskRunId || event.request?.parentTaskRunId,
80
+ parentSessionId: event.parentSessionId, requestId: event.requestId || event.request?.requestId, turnId: event.turnId, toolCallId: event.toolCallId, toolName: event.toolName,
81
+ attemptId: event.attemptId, argumentFingerprint: event.argumentFingerprint || (event.args ? observationFingerprint(event.args) : undefined),
82
+ durationMs: event.durationMs, usage: event.usage || result.usage, status: event.status,
83
+ ...(event.configuration ? { configuration: event.configuration } : {}),
84
+ ...(event.repeatedSteps !== undefined ? { repeatedSteps: event.repeatedSteps } : {}),
85
+ ...(typeof event.text === "string" ? { textCharacters: [...event.text].length } : {}),
86
+ ...(typeof result.text === "string" ? { finalTextCharacters: [...result.text].length } : {}),
87
+ ...(event.finalTextCharacters != null ? { finalTextCharacters: event.finalTextCharacters } : {}),
88
+ ...(result.code ? { resultCode: result.code } : {}),
89
+ provider: event.provider, model: event.model, transport: event.transport, estimatedInputTokens: event.estimatedInputTokens,
90
+ ...(["model.started", "model.completed", "model.failed"].includes(event.type) ? { modelScope: event.modelScope || "api-call" } : {}),
91
+ summary: clip(event.error?.message || event.error || result.error?.message || result.error || event.text || result.text || event.phase?.type || event.type),
92
+ ...(event.args ? { args: event.args } : {}), ...(event.result ? { result: event.result, ok: result.ok } : {}),
93
+ ...(event.text ? { text: event.text } : {}), ...(event.phase ? { phase: event.phase } : {}),
94
+ ...(event.binding ? { binding: event.binding } : {}), ...(event.code ? { code: event.code } : {}), ...(event.outcome ? { outcome: event.outcome } : {}),
95
+ ...(event.warning ? { warning: event.warning } : {}),
96
+ ...(event.error ? { error: event.error } : {}),
97
+ ...(String(event.type || "").startsWith("context.compaction") ? { coveredCount: event.coveredCount, batchCount: event.batchCount, checkpointVersion: event.version, sourceArchive: event.sourceArchive } : {}) };
98
+ }
99
+ for (const record of records) {
100
+ const e = record.value;
101
+ if (e.type === "capability.state_committed") {
102
+ const assignments = e.capabilityId === "agent-management" ? e.value?.tasks : e.capabilityId === "task-execution" ? e.value?.jobs : null;
103
+ for (const task of Object.values(assignments || {})) {
104
+ const id = task.taskId || task.taskRunId || task.id;
105
+ const previous = tasks.get(id);
106
+ if (previous?.status !== task.status || previous?.report?.entry_id !== task.report?.entry_id) add({ type: "delegation.state", time: e.time,
107
+ taskId: id, taskRunId: task.taskRunId, traceId: task.traceId, parentTaskRunId: task.parentTaskRunId, parentSessionId: task.parentSessionId,
108
+ agentId: task.workerId || task.id, status: task.status, summary: `${task.status}${task.report?.phase ? ` (${task.report.phase})` : ""}` }, record, `:${id}`);
109
+ tasks.set(id, task);
110
+ }
111
+ continue;
112
+ }
113
+ if (e.type && typeof e.type !== "string") { warnings.push({ source: record.source, code: "invalid_event_type" }); continue; }
114
+ if (!e.type || ["command.started", "command.resolved"].includes(e.type)) {
115
+ if (e.type) {
116
+ const task = [...tasks.values()].find(task => task.commandIds?.includes(e.commandId));
117
+ add({ ...normalize(e), taskId: task?.taskId, parentTaskRunId: task?.parentTaskRunId, traceId: task?.traceId,
118
+ agentId: task?.workerId || "ufoo-agent", commandId: e.commandId, commandKind: e.kind,
119
+ summary: `${e.type} ${e.kind || e.commandId || ""}` }, record);
120
+ }
121
+ continue;
122
+ }
123
+ add(normalize(e), record);
124
+ }
125
+ const busFiles = entries(paths.busEventsDir).filter(e => e.isFile() && e.name.endsWith(".jsonl")).map(e => path.join(paths.busEventsDir, e.name)).sort().reverse();
126
+ if (busFiles.length > 14) warnings.push({ code: "bus_day_limit", total: busFiles.length, read: 14 });
127
+ const bus = busFiles.slice(0, 14).flatMap(read);
128
+ const nativeRuns = new Set(records.filter(r => r.source.includes("/ucode/runtimes/"))
129
+ .flatMap(r => [r.value.taskRunId, r.value.parentTaskRunId]).filter(Boolean));
130
+ const committedEvents = new Set(records.map(r => r.value.eventId).filter(Boolean));
131
+ for (const record of bus) {
132
+ const e = record.value;
133
+ if (e.event === "agent_surface") {
134
+ const surface = e.data?.surface || {};
135
+ // Native core events have their own canonical journal. Avoid displaying
136
+ // the same tool/text lifecycle again through its presentation adapter.
137
+ if (surface.type === "runtime_event") {
138
+ if (surface.event && !committedEvents.has(surface.event.eventId)) add({ ...normalize(surface.event),
139
+ agentId: e.publisher, taskId: surface.task_id || surface.taskId, time: surface.event.time || e.timestamp }, record);
140
+ continue;
141
+ }
142
+ if (nativeRuns.has(surface.taskRunId) && ["tool_call", "tool_result", "text_delta", "thinking_delta", "turn_started", "turn_completed"].includes(surface.type)) continue;
143
+ const type = surface.type === "tool_result" ? surface.status === "in_progress" ? "tool.progress" : "tool.completed" : TYPES[surface.type] || surface.type;
144
+ add({ ...normalize({ ...surface, type, modelScope: "sdk-turn", toolName: surface.name, text: surface.delta, result: surface.type === "tool_result" ? { output: surface.output,
145
+ ok: surface.is_error !== true && surface.status !== "failed" && (!Number.isFinite(surface.exitCode) || surface.exitCode === 0), exitCode: surface.exitCode } : undefined }),
146
+ time: e.timestamp, agentId: e.publisher, taskId: surface.task_id || surface.taskId, busSequence: e.seq, queueSequence: surface.queueSequence, model: surface.model, provider: surface.provider,
147
+ summary: clip(surface.error || surface.delta || surface.name || surface.phase?.type || type) }, record);
148
+ } else if (e.event === "message" && e.data?.runtime_context) {
149
+ add({ ...normalizeTraceContext(e.data.runtime_context), type: "queue.enqueued", time: e.timestamp, agentId: e.target, publisher: e.publisher,
150
+ busSequence: e.seq, taskId: e.data.task_id, summary: clip(e.data.message), ...(options.details ? { message: e.data.message } : {}) }, record);
151
+ } else if (e.event === "activity_state_changed") {
152
+ add({ type: "agent.activity", time: e.timestamp, agentId: e.publisher, status: e.data?.state, summary: [e.data?.state, e.data?.detail].filter(Boolean).join(" ") }, record);
153
+ }
154
+ }
155
+ for (const record of read(path.join(paths.agentDir, "reports.jsonl"))) {
156
+ const e = record.value;
157
+ add({ ...normalizeTraceContext(e.meta), type: `report.${e.phase}`, time: e.ts, agentId: e.agent_id, taskId: e.task_id, reportSource: e.source,
158
+ reportCharacters: [...String(e.summary || e.message || e.error || "")].length,
159
+ ...(e.meta?.cancelled ? { cancelled: true } : {}),
160
+ reportId: e.entry_id, scope: e.scope, controllerId: e.controller_id, summary: clip(e.error || e.summary || e.message || e.phase) }, record);
161
+ }
162
+ const queues = [];
163
+ for (const dir of entries(paths.busQueuesDir).filter(e => e.isDirectory())) {
164
+ const base = path.join(paths.busQueuesDir, dir.name);
165
+ for (const file of entries(base).filter(e => e.isFile() && (e.name === "pending.jsonl" || e.name.includes("processing")))) {
166
+ for (const record of read(path.join(base, file.name))) {
167
+ const e = record.value;
168
+ queues.push({ agentId: e.target, publisher: e.publisher, taskId: e.data?.task_id || e.data?.runtime_context?.taskId,
169
+ sequence: e.seq, enqueuedAt: e.timestamp, state: file.name === "pending.jsonl" ? "pending" : "claimed", source: record.source });
170
+ }
171
+ }
172
+ }
173
+ const reportQueue = path.join(paths.busDir, "control", "report");
174
+ for (const file of entries(reportQueue).filter(e => e.isFile() && (e.name === "pending.jsonl" || e.name.includes("processing")))) {
175
+ for (const record of read(path.join(reportQueue, file.name))) {
176
+ const report = record.value.data?.report;
177
+ if (report) queues.push({ kind: "report", agentId: report.agent_id, taskId: report.task_id, phase: report.phase,
178
+ state: file.name === "pending.jsonl" ? "pending" : "claimed", source: record.source });
179
+ }
180
+ }
181
+ let agents = {};
182
+ try { agents = JSON.parse(fs.readFileSync(paths.agentsFile, "utf8")).agents || {}; } catch { /* optional registration */ }
183
+ const requestedAgent = options.agent_id || "";
184
+ const agentId = Object.keys(agents).find(id => id === requestedAgent || agents[id].nickname === requestedAgent) || requestedAgent;
185
+ const selected = String(options.task_id || "");
186
+ const related = new Set(selected ? [selected] : []);
187
+ if (selected) {
188
+ // Expand only descendants; include parent lifecycle as evidence without
189
+ // pulling in unrelated sibling jobs that happen to share that parent.
190
+ let changed = true;
191
+ while (changed) {
192
+ changed = false;
193
+ for (const task of tasks.values()) if (related.has(task.taskId || task.taskRunId || task.id) || related.has(task.parentTaskRunId)) {
194
+ for (const id of [task.taskId, task.taskRunId, task.id].filter(Boolean)) if (!related.has(id)) { related.add(id); changed = true; }
195
+ }
196
+ for (const e of events) if (related.has(e.taskId) && e.taskRunId && !related.has(e.taskRunId)) { related.add(e.taskRunId); changed = true; }
197
+ }
198
+ }
199
+ const selectedTasks = [...tasks.values()].filter(t => (!selected || related.has(t.taskId || t.taskRunId || t.id)) && (!agentId || t.workerId === agentId || t.id === agentId));
200
+ const parents = new Set(selectedTasks.map(t => t.parentTaskRunId).filter(Boolean));
201
+ const since = options.since ? Date.parse(options.since) : null;
202
+ if (since !== null && !Number.isFinite(since)) throw new Error("since must be an ISO timestamp");
203
+ const scoped = events.filter(e => (!selected || related.has(e.taskId) || related.has(e.taskRunId) || parents.has(e.taskRunId))
204
+ && (!agentId || e.agentId === agentId)
205
+ && (!options.session_id || e.sessionId === options.session_id)).sort((a, b) => a.time.localeCompare(b.time)
206
+ || (a.source === b.source ? (a.sequence || a.busSequence || 0) - (b.sequence || b.busSequence || 0) : 0) || a.id.localeCompare(b.id));
207
+ const matched = scoped.filter(e => since === null || Date.parse(e.time) >= since);
208
+ const selectedQueues = queues.filter(q => (!selected || related.has(q.taskId)) && (!agentId || q.agentId === agentId));
209
+ const limit = Math.max(1, Math.min(2000, Number(options.limit) || 200));
210
+ const offset = options.offset === undefined ? Math.max(0, matched.length - limit) : Math.max(0, Math.floor(Number(options.offset) || 0));
211
+ const last = offset + limit;
212
+ const toolCalls = new Map();
213
+ for (const e of matched.filter(e => ["tool.started", "tool.completed", "tool.failed"].includes(e.type))) {
214
+ if (!e.toolCallId) warnings.push({ source: e.source, code: "missing_tool_call_id" });
215
+ const key = `${e.taskRunId || e.taskId || e.agentId}:${e.toolCallId || e.id}`;
216
+ if (!toolCalls.has(key)) toolCalls.set(key, { toolCallId: e.toolCallId, toolName: e.toolName, agentId: e.agentId, taskRunId: e.taskRunId, started: false, ended: false });
217
+ const call = toolCalls.get(key);
218
+ if (e.type === "tool.started") { call.started = true; call.startedAt ||= e.time; }
219
+ else { call.ended = true; call.endedAt = e.time; call.outcome = e.type === "tool.failed" ? "unknown" : e.ok === false ? "error" : "ok";
220
+ call.durationMs = e.durationMs ?? (call.startedAt ? Math.max(0, Date.parse(e.time) - Date.parse(call.startedAt)) : undefined); }
221
+ }
222
+ const taskView = task => options.details ? task : { taskId: task.taskId || task.id, taskRunId: task.taskRunId,
223
+ traceId: task.traceId, workerId: task.workerId, parentTaskRunId: task.parentTaskRunId, parentSessionId: task.parentSessionId,
224
+ status: task.status, reportPhase: task.report?.phase, summary: clip(task.report?.error || task.report?.summary || task.report?.message), acceptance: task.acceptance };
225
+ const performance = summarizeAgentPerformance(scoped.filter(e => !selected || related.has(e.taskId) || related.has(e.taskRunId)), selectedTasks, selectedQueues,
226
+ { ...(options.performanceQuery || { since: options.since, includeRuns: false }), warnings });
227
+ return redactSecrets({ version: 1, projectRoot: root, taskId: selected || null, total: matched.length, offset,
228
+ next_offset: last < matched.length ? last : null, has_more_before: offset > 0,
229
+ events: matched.slice(offset, last), tasks: selectedTasks.slice(-100).map(taskView),
230
+ counts: { modelCalls: matched.filter(e => e.type === "model.started" && e.modelScope === "api-call").length,
231
+ sdkTurns: matched.filter(e => e.type === "model.started" && e.modelScope === "sdk-turn").length,
232
+ modelFailures: matched.filter(e => e.type === "model.failed").length, toolCalls: toolCalls.size,
233
+ toolErrors: [...toolCalls.values()].filter(t => t.outcome === "error").length,
234
+ unresolvedTools: [...toolCalls.values()].filter(t => !t.ended || t.outcome === "unknown").length,
235
+ compactions: matched.filter(e => e.type === "context.compaction.completed").length,
236
+ compactionFailures: matched.filter(e => e.type === "context.compaction.failed").length },
237
+ tools: [...toolCalls.values()],
238
+ performance,
239
+ queues: selectedQueues.slice(-100),
240
+ incomplete: warnings.length > 0, warnings });
241
+ }
242
+
243
+ function readAgentPerformance(projectRoot, options = {}) {
244
+ const trace = readAgentTrace(projectRoot, { task_id: options.task_id, agent_id: options.agent_id, session_id: options.session_id,
245
+ maxReadBytes: options.maxReadBytes, limit: 1, performanceQuery: options });
246
+ return { projectRoot: trace.projectRoot, taskId: trace.taskId, ...trace.performance };
247
+ }
248
+
249
+ module.exports = { readAgentTrace, readAgentPerformance };
@@ -11,6 +11,7 @@ const {
11
11
  const { redactSecrets } = require("../../runtime/privacy/redactor");
12
12
  const { canonicalProjectRoot } = require("../../runtime/projects/projectId");
13
13
  const { getUfooPaths } = require("../state/paths");
14
+ const { withFileLock } = require("../state/fileLock");
14
15
 
15
16
  const SCHEMA_VERSION = "1.0";
16
17
  const ID_PREFIX = "mem-";
@@ -20,11 +21,6 @@ const HISTORY_CACHE_TTL_MS = 60 * 60 * 1000;
20
21
  const DEFAULT_PREFIX_MAX_TOKENS = 1500;
21
22
  const prefixCache = new Map();
22
23
 
23
- function sleepSync(ms) {
24
- const buffer = new SharedArrayBuffer(4);
25
- const array = new Int32Array(buffer);
26
- Atomics.wait(array, 0, 0, ms);
27
- }
28
24
 
29
25
  function normalizeId(value = "") {
30
26
  return String(value || "").trim();
@@ -168,23 +164,11 @@ class MemoryManager {
168
164
 
169
165
  withLock(fn) {
170
166
  ensureDir(this.memoryDir);
171
- const started = Date.now();
172
- while (true) {
173
- try {
174
- fs.mkdirSync(this.lockDir);
175
- break;
176
- } catch (err) {
177
- if (err && err.code !== "EEXIST") throw err;
178
- if (Date.now() - started > 5000) {
179
- throw buildMemoryError("memory_lock_timeout", "timed out waiting for memory lock");
180
- }
181
- sleepSync(10);
182
- }
183
- }
184
167
  try {
185
- return fn();
186
- } finally {
187
- fs.rmSync(this.lockDir, { recursive: true, force: true });
168
+ return withFileLock(this.indexFile, fn, { lockfilePath: this.lockDir });
169
+ } catch (error) {
170
+ if (error.code === "ELOCKED") throw buildMemoryError("memory_lock_timeout", "timed out waiting for memory lock");
171
+ throw error;
188
172
  }
189
173
  }
190
174
 
@@ -2,6 +2,8 @@ const fs = require("fs");
2
2
  const path = require("path");
3
3
  const { getUfooPaths } = require("../state/paths");
4
4
  const { redactSecrets } = require("../../runtime/privacy/redactor");
5
+ const { withFileLock } = require("../state/fileLock");
6
+ const { writeFileAtomic } = require("../bus/utils");
5
7
 
6
8
  const REPORT_PHASES = {
7
9
  START: "start",
@@ -38,7 +40,7 @@ function normalizeScope(value = "") {
38
40
  }
39
41
 
40
42
  function normalizeReportInput(input = {}, options = {}) {
41
- const ts = options.ts || new Date().toISOString();
43
+ const ts = options.ts || input.ts || new Date().toISOString();
42
44
  let phase = normalizePhase(input.phase || options.phase);
43
45
  const entryId = String(
44
46
  input.entry_id
@@ -53,7 +55,7 @@ function normalizeReportInput(input = {}, options = {}) {
53
55
  || input.task
54
56
  || options.task_id
55
57
  || options.taskId
56
- || `task-${Date.now()}`
58
+ || `task-${require("crypto").randomUUID()}`
57
59
  ).trim();
58
60
  const agentId = String(
59
61
  input.agent_id
@@ -101,7 +103,11 @@ function normalizeReportInput(input = {}, options = {}) {
101
103
  function appendReport(projectRoot, entry) {
102
104
  ensureReportDir(projectRoot);
103
105
  const { reportsFile } = getReportPaths(projectRoot);
104
- fs.appendFileSync(reportsFile, `${JSON.stringify(redactSecrets(entry))}\n`, "utf8");
106
+ return withFileLock(reportsFile, () => {
107
+ if (entry.entry_id && parseJsonLines(reportsFile).some((row) => row.entry_id === entry.entry_id)) return false;
108
+ fs.appendFileSync(reportsFile, `${JSON.stringify(redactSecrets(entry))}\n`, "utf8");
109
+ return true;
110
+ });
105
111
  }
106
112
 
107
113
  function parseJsonLines(file) {
@@ -152,34 +158,40 @@ function loadReportState(projectRoot) {
152
158
  function saveReportState(projectRoot, state) {
153
159
  ensureReportDir(projectRoot);
154
160
  const { stateFile } = getReportPaths(projectRoot);
155
- fs.writeFileSync(stateFile, JSON.stringify(redactSecrets(state), null, 2));
161
+ writeFileAtomic(stateFile, JSON.stringify(redactSecrets(state), null, 2));
156
162
  }
157
163
 
158
164
  function updateReportState(projectRoot, entry) {
159
- const state = loadReportState(projectRoot);
160
- const current = state.agents[entry.agent_id] && typeof state.agents[entry.agent_id] === "object"
161
- ? state.agents[entry.agent_id]
162
- : {};
163
- const pending = current.pending && typeof current.pending === "object"
164
- ? { ...current.pending }
165
- : {};
166
-
167
- if (entry.phase === REPORT_PHASES.START || entry.phase === REPORT_PHASES.PROGRESS) {
168
- pending[entry.task_id] = entry;
169
- } else {
170
- delete pending[entry.task_id];
171
- }
165
+ return withFileLock(getReportPaths(projectRoot).stateFile, () => {
166
+ const state = loadReportState(projectRoot);
167
+ const current = state.agents[entry.agent_id] && typeof state.agents[entry.agent_id] === "object"
168
+ ? state.agents[entry.agent_id]
169
+ : {};
170
+ const lastByTask = current.last_by_task || {};
171
+ const previous = lastByTask[entry.task_id];
172
+ if (previous && (previous.entry_id === entry.entry_id || previous.ts > entry.ts)) return state;
173
+ const pending = current.pending && typeof current.pending === "object"
174
+ ? { ...current.pending }
175
+ : {};
176
+
177
+ if (entry.phase === REPORT_PHASES.START || entry.phase === REPORT_PHASES.PROGRESS) {
178
+ pending[entry.task_id] = entry;
179
+ } else {
180
+ delete pending[entry.task_id];
181
+ }
172
182
 
173
- state.agents[entry.agent_id] = {
174
- ...current,
175
- pending,
176
- pending_count: Object.keys(pending).length,
177
- last: entry,
178
- updated_at: entry.ts,
179
- };
180
- state.updated_at = entry.ts;
181
- saveReportState(projectRoot, state);
182
- return state;
183
+ state.agents[entry.agent_id] = {
184
+ ...current,
185
+ last_by_task: { ...lastByTask, [entry.task_id]: entry },
186
+ pending,
187
+ pending_count: Object.keys(pending).length,
188
+ last: entry,
189
+ updated_at: entry.ts,
190
+ };
191
+ state.updated_at = entry.ts;
192
+ saveReportState(projectRoot, state);
193
+ return state;
194
+ });
183
195
  }
184
196
 
185
197
  function isSummaryHiddenEntry(entry) {
@@ -206,7 +218,11 @@ function getControllerInboxFile(projectRoot, controllerId = "ufoo-agent") {
206
218
  function appendControllerInboxEntry(projectRoot, controllerId, entry) {
207
219
  const file = getControllerInboxFile(projectRoot, controllerId);
208
220
  fs.mkdirSync(path.dirname(file), { recursive: true });
209
- fs.appendFileSync(file, `${JSON.stringify(redactSecrets(entry))}\n`, "utf8");
221
+ return withFileLock(file, () => {
222
+ if (entry.entry_id && parseJsonLines(file).some((row) => row.entry_id === entry.entry_id)) return false;
223
+ fs.appendFileSync(file, `${JSON.stringify(redactSecrets(entry))}\n`, "utf8");
224
+ return true;
225
+ });
210
226
  }
211
227
 
212
228
  function listControllerInboxEntries(projectRoot, controllerId = "ufoo-agent", options = {}) {
@@ -224,75 +240,79 @@ function countControllerInboxEntries(projectRoot, controllerId = "ufoo-agent") {
224
240
 
225
241
  function clearControllerInbox(projectRoot, controllerId = "ufoo-agent") {
226
242
  const file = getControllerInboxFile(projectRoot, controllerId);
227
- try {
228
- if (fs.existsSync(file)) fs.rmSync(file, { force: true });
229
- } catch {
230
- // ignore clear errors
231
- }
243
+ return withFileLock(file, () => {
244
+ try {
245
+ if (fs.existsSync(file)) fs.rmSync(file, { force: true });
246
+ } catch {
247
+ // ignore clear errors
248
+ }
249
+ });
232
250
  }
233
251
 
234
252
  function consumeControllerInboxEntries(projectRoot, controllerId = "ufoo-agent", consumed = []) {
235
253
  const file = getControllerInboxFile(projectRoot, controllerId);
236
- if (!fs.existsSync(file)) return { removed: 0, remaining: 0 };
237
- const list = Array.isArray(consumed) ? consumed : [];
238
- if (list.length === 0) {
239
- const current = parseJsonLines(file);
240
- return { removed: 0, remaining: current.length };
241
- }
242
-
243
- const idSet = new Set();
244
- const legacySerialized = new Set();
245
- for (const item of list) {
246
- if (!item) continue;
247
- if (typeof item === "string") {
248
- idSet.add(item);
249
- continue;
254
+ return withFileLock(file, () => {
255
+ if (!fs.existsSync(file)) return { removed: 0, remaining: 0 };
256
+ const list = Array.isArray(consumed) ? consumed : [];
257
+ if (list.length === 0) {
258
+ const current = parseJsonLines(file);
259
+ return { removed: 0, remaining: current.length };
250
260
  }
251
- if (typeof item === "object") {
252
- if (item.entry_id) {
253
- idSet.add(String(item.entry_id));
254
- } else {
255
- legacySerialized.add(JSON.stringify(item));
261
+
262
+ const idSet = new Set();
263
+ const legacySerialized = new Set();
264
+ for (const item of list) {
265
+ if (!item) continue;
266
+ if (typeof item === "string") {
267
+ idSet.add(item);
268
+ continue;
269
+ }
270
+ if (typeof item === "object") {
271
+ if (item.entry_id) {
272
+ idSet.add(String(item.entry_id));
273
+ } else {
274
+ legacySerialized.add(JSON.stringify(item));
275
+ }
256
276
  }
257
277
  }
258
- }
259
278
 
260
- const raw = fs.readFileSync(file, "utf8");
261
- const lines = raw.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
262
- if (lines.length === 0) {
263
- return { removed: 0, remaining: 0 };
264
- }
265
-
266
- const keptLines = [];
267
- let removed = 0;
268
- for (const line of lines) {
269
- let parsed = null;
270
- try {
271
- parsed = JSON.parse(line);
272
- } catch {
273
- parsed = null;
279
+ const raw = fs.readFileSync(file, "utf8");
280
+ const lines = raw.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
281
+ if (lines.length === 0) {
282
+ return { removed: 0, remaining: 0 };
274
283
  }
275
- if (parsed && typeof parsed === "object") {
276
- const id = parsed.entry_id ? String(parsed.entry_id) : "";
277
- if (id && idSet.has(id)) {
278
- removed += 1;
279
- continue;
284
+
285
+ const keptLines = [];
286
+ let removed = 0;
287
+ for (const line of lines) {
288
+ let parsed = null;
289
+ try {
290
+ parsed = JSON.parse(line);
291
+ } catch {
292
+ parsed = null;
280
293
  }
281
- if (!id && legacySerialized.has(JSON.stringify(parsed))) {
282
- removed += 1;
283
- continue;
294
+ if (parsed && typeof parsed === "object") {
295
+ const id = parsed.entry_id ? String(parsed.entry_id) : "";
296
+ if (id && idSet.has(id)) {
297
+ removed += 1;
298
+ continue;
299
+ }
300
+ if (!id && legacySerialized.has(JSON.stringify(parsed))) {
301
+ removed += 1;
302
+ continue;
303
+ }
284
304
  }
305
+ keptLines.push(line);
285
306
  }
286
- keptLines.push(line);
287
- }
288
307
 
289
- if (keptLines.length === 0) {
290
- fs.rmSync(file, { force: true });
291
- return { removed, remaining: 0 };
292
- }
308
+ if (keptLines.length === 0) {
309
+ fs.rmSync(file, { force: true });
310
+ return { removed, remaining: 0 };
311
+ }
293
312
 
294
- fs.writeFileSync(file, `${keptLines.join("\n")}\n`, "utf8");
295
- return { removed, remaining: keptLines.length };
313
+ writeFileAtomic(file, `${keptLines.join("\n")}\n`);
314
+ return { removed, remaining: keptLines.length };
315
+ });
296
316
  }
297
317
 
298
318
  function readReportSummary(projectRoot) {
@@ -2,6 +2,33 @@ const { getTimestamp, readJSON, writeJSON } = require("../bus/utils");
2
2
  const { appendAgentRegistryDiagnostic, summarizeAgents } = require("./agentRegistryDiagnostics");
3
3
 
4
4
  const AGENTS_SCHEMA_VERSION = 1;
5
+ const { withFileLock } = require("./fileLock");
6
+ const snapshots = new WeakMap();
7
+ const clone = (value) => JSON.parse(JSON.stringify(value));
8
+
9
+ function remember(data) {
10
+ snapshots.set(data, clone(data));
11
+ return data;
12
+ }
13
+
14
+ // Apply only fields changed since this caller's load. Unchanged fields and
15
+ // agents created by another process belong to the latest disk snapshot.
16
+ function applyChanges(current, baseline, next) {
17
+ const result = { ...current };
18
+ for (const key of new Set([...Object.keys(baseline), ...Object.keys(next)])) {
19
+ if (JSON.stringify(baseline[key]) === JSON.stringify(next[key])) continue;
20
+ if (!Object.prototype.hasOwnProperty.call(next, key)) {
21
+ delete result[key];
22
+ } else if (baseline[key] && next[key] && typeof baseline[key] === "object"
23
+ && typeof next[key] === "object" && !Array.isArray(next[key])) {
24
+ // A stale writer must not resurrect a concurrently removed record.
25
+ if (result[key]) result[key] = applyChanges(result[key], baseline[key], next[key]);
26
+ } else {
27
+ result[key] = next[key];
28
+ }
29
+ }
30
+ return result;
31
+ }
5
32
 
6
33
  function toSafeString(value) {
7
34
  return typeof value === "string" ? value : "";
@@ -94,7 +121,7 @@ function loadAgentsData(filePath) {
94
121
  source: "ufoo.agentsStore.loadAgentsData",
95
122
  reason: "missing_or_unreadable_registry",
96
123
  });
97
- return normalizeAgentsData({});
124
+ return remember(normalizeAgentsData({}));
98
125
  }
99
126
  const normalized = normalizeAgentsData(data);
100
127
  const beforeSummary = summarizeAgents(data);
@@ -106,7 +133,7 @@ function loadAgentsData(filePath) {
106
133
  after: afterSummary,
107
134
  });
108
135
  }
109
- return normalized;
136
+ return remember(normalized);
110
137
  }
111
138
 
112
139
  function parseTimestampMs(value) {
@@ -137,18 +164,31 @@ function mergeExternalActivityFields(targetMeta, diskMeta) {
137
164
  if (preferDisk) {
138
165
  targetMeta.activity_state = diskState;
139
166
  targetMeta.activity_since = diskSince;
167
+ if (diskMeta.activity_detail) targetMeta.activity_detail = diskMeta.activity_detail;
168
+ else delete targetMeta.activity_detail;
140
169
  }
141
170
  }
142
171
 
143
172
  function saveAgentsData(filePath, data, options = {}) {
173
+ return withFileLock(filePath, () => saveAgentsDataUnlocked(filePath, data, options));
174
+ }
175
+
176
+ function saveAgentsDataUnlocked(filePath, data, options = {}) {
144
177
  const source = typeof options.source === "string" && options.source
145
178
  ? options.source
146
179
  : "ufoo.agentsStore.saveAgentsData";
147
- const normalized = normalizeAgentsData(data);
180
+ let normalized = normalizeAgentsData(data);
148
181
 
149
182
  // Merge externally-managed fields from disk to avoid daemon in-memory writes
150
183
  // overwriting fresher runner/notifier state updates.
151
184
  const disk = readJSON(filePath, null);
185
+ if (!disk && require("fs").existsSync(filePath)) throw new Error(`Refusing to overwrite unreadable agent registry: ${filePath}`);
186
+ const baseline = snapshots.get(data);
187
+ if (disk) {
188
+ normalized = normalizeAgentsData(baseline
189
+ ? applyChanges(normalizeAgentsData(disk), baseline, normalized)
190
+ : { ...disk, ...normalized, agents: { ...disk.agents, ...normalized.agents } });
191
+ }
152
192
  if (disk && disk.agents && normalized.agents) {
153
193
  const droppedIds = Object.keys(disk.agents)
154
194
  .filter((id) => !Object.prototype.hasOwnProperty.call(normalized.agents, id))
@@ -177,6 +217,19 @@ function saveAgentsData(filePath, data, options = {}) {
177
217
  });
178
218
  }
179
219
  writeJSON(filePath, normalized);
220
+ Object.assign(data, normalized);
221
+ remember(data);
222
+ return normalized;
223
+ }
224
+
225
+ function updateAgentsData(filePath, mutate, options = {}) {
226
+ return withFileLock(filePath, () => {
227
+ const data = loadAgentsData(filePath);
228
+ const result = mutate(data);
229
+ if (result && typeof result.then === "function") throw new Error("Agent mutations must be synchronous");
230
+ if (result !== false) saveAgentsDataUnlocked(filePath, data, options);
231
+ return result;
232
+ });
180
233
  }
181
234
 
182
235
  module.exports = {
@@ -184,4 +237,5 @@ module.exports = {
184
237
  loadAgentsData,
185
238
  saveAgentsData,
186
239
  normalizeAgentsData,
240
+ updateAgentsData,
187
241
  };