u-foo 4.0.10 → 4.1.2

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 (71) hide show
  1. package/OPTIONAL_SKILLS/ufoo-bus-poll/SKILL.md +27 -0
  2. package/README.md +279 -789
  3. package/README.zh-CN.md +290 -439
  4. package/SKILLS/ufoo/SKILL.md +7 -0
  5. package/bin/ufoo.js +36 -3
  6. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  7. package/docs/OBSERVABILITY.md +4 -2
  8. package/docs/README.md +1 -0
  9. package/package.json +6 -2
  10. package/scripts/pack-desktop.js +174 -0
  11. package/src/agents/capabilities/coding/index.js +26 -3
  12. package/src/agents/capabilities/index.js +2 -1
  13. package/src/agents/capabilities/mac/index.js +145 -0
  14. package/src/agents/capabilities/planning/index.js +1 -1
  15. package/src/agents/capabilities/turnRecall/index.js +5 -16
  16. package/src/agents/profiles/coding.js +1 -1
  17. package/src/agents/profiles/main.js +1 -1
  18. package/src/agents/providers/nativeTransport.js +105 -116
  19. package/src/agents/providers/runtimeConfig.js +15 -4
  20. package/src/agents/providers/transports/anthropicCache.js +78 -0
  21. package/src/agents/providers/transports/antigravityTransport.js +3 -2
  22. package/src/agents/providers/transports/openaiResponsesTransport.js +7 -12
  23. package/src/agents/providers/transports/requestCacheObservation.js +61 -0
  24. package/src/agents/providers/transports/responsesProtocol.js +54 -46
  25. package/src/agents/providers/upstreamRuntime.js +2 -2
  26. package/src/agents/runtime/context/contextWindow.js +10 -0
  27. package/src/agents/runtime/context/slidingWindowManager.js +97 -41
  28. package/src/agents/runtime/context/topicSelector.js +4 -2
  29. package/src/agents/runtime/context/turnAnalyzer.js +17 -29
  30. package/src/agents/runtime/core/agentLoop.js +23 -7
  31. package/src/agents/runtime/createAgentRuntime.js +1 -1
  32. package/src/agents/runtime/protocol/auxiliaryModelRequest.js +28 -0
  33. package/src/app/chat/ChatController.js +1 -0
  34. package/src/app/chat/commandExecutor.js +25 -0
  35. package/src/app/chat/commands.js +2 -0
  36. package/src/app/chat/daemonMessageRouter.js +30 -3
  37. package/src/app/cli/appCommands.js +107 -0
  38. package/src/app/cli/features/skills.js +2 -0
  39. package/src/app/cli/macCommands.js +321 -0
  40. package/src/app/cli/metricsCommands.js +6 -1
  41. package/src/app/cli/run.js +26 -0
  42. package/src/app/cli/setupCommands.js +1 -0
  43. package/src/code/agent.js +1 -0
  44. package/src/code/context/assembler.js +8 -6
  45. package/src/code/context/promptLayers.js +3 -1
  46. package/src/code/context/stateCommit.js +2 -2
  47. package/src/code/context/transcript.js +11 -5
  48. package/src/code/nativeRunner.js +25 -5
  49. package/src/code/skills/loader.js +10 -2
  50. package/src/code/skills/render.js +8 -1
  51. package/src/config.js +42 -0
  52. package/src/coordination/bus/activate.js +44 -19
  53. package/src/coordination/history/agentPerformance.js +88 -11
  54. package/src/coordination/history/agentTrace.js +2 -0
  55. package/src/coordination/history/modelInputCost.js +52 -0
  56. package/src/runtime/contracts/uiProtocol.js +26 -0
  57. package/src/runtime/daemon/agentHost.js +35 -12
  58. package/src/runtime/daemon/mcpStdioProxy.js +3 -2
  59. package/src/runtime/mac/helperClient.js +279 -0
  60. package/src/runtime/mac/helperCompiler.js +235 -0
  61. package/src/runtime/mac/macSession.js +866 -0
  62. package/src/runtime/mac/native/ufoo_mac_helper.swift +2493 -0
  63. package/src/runtime/mac/paths.js +63 -0
  64. package/src/ui/agentSettingsController.js +12 -5
  65. package/src/ui/cliHandoff.js +484 -0
  66. package/src/ui/desktopArchive.js +41 -0
  67. package/src/ui/desktopUiHost.js +1601 -0
  68. package/src/ui/desktopUiHostCli.js +66 -0
  69. package/src/ui/format/index.js +17 -0
  70. package/src/ui/rustChatHost.js +45 -6
  71. package/src/ui/workspaceInspector.js +621 -0
@@ -0,0 +1,621 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Workspace inspection & context management helpers for the Desktop Right Inspector:
5
+ * - Changes: Git status, worktrees, unified/split-ready diffs, and worker reports
6
+ * - Docs: Safe workspace document/file listing and line-ranged reading
7
+ * - Context: Decisions (.ufoo/context/decisions/) & Shared Memory (.ufoo/memory/)
8
+ */
9
+
10
+ const fs = require("fs");
11
+ const path = require("path");
12
+ const { spawnSync } = require("child_process");
13
+ const matter = require("gray-matter");
14
+ const { resolveWorkspacePath, isPathInside } = require("../code/tools/common");
15
+ const { redactSecrets } = require("../runtime/privacy/redactor");
16
+ const { canonicalProjectRoot } = require("../runtime/projects/projectId");
17
+ const { listReports, readReportSummary } = require("../coordination/report/store");
18
+ const DecisionsManager = require("../coordination/context/decisions");
19
+ const { MemoryManager } = require("../coordination/memory");
20
+
21
+ const IGNORED_DIRS = new Set([
22
+ ".git",
23
+ ".ufoo",
24
+ "node_modules",
25
+ "target",
26
+ "dist",
27
+ "build",
28
+ ".next",
29
+ ".turbo",
30
+ "coverage",
31
+ "__pycache__",
32
+ ".venv",
33
+ ]);
34
+
35
+ const BINARY_EXTENSIONS = new Set([
36
+ ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".icns",
37
+ ".pdf", ".zip", ".tar", ".gz", ".dmg", ".pkg",
38
+ ".woff", ".woff2", ".ttf", ".otf",
39
+ ".node", ".dylib", ".so", ".dll", ".exe", ".o", ".a",
40
+ ]);
41
+
42
+ const PINNED_DOC_NAMES = [
43
+ "README.md",
44
+ "README.zh-CN.md",
45
+ "AGENTS.md",
46
+ "CLAUDE.md",
47
+ "docs/PROJECT.md",
48
+ "docs/README.md",
49
+ "docs/OBSERVABILITY.md",
50
+ ];
51
+
52
+ function safeCanonicalRoot(projectRoot) {
53
+ const raw = String(projectRoot || "").trim();
54
+ if (!raw) throw new Error("projectRoot is required");
55
+ try {
56
+ return canonicalProjectRoot(raw);
57
+ } catch {
58
+ return path.resolve(raw);
59
+ }
60
+ }
61
+
62
+ function runGit(cwd, args, maxBuffer = 2 * 1024 * 1024) {
63
+ try {
64
+ const res = spawnSync("git", args, {
65
+ cwd,
66
+ encoding: "utf8",
67
+ timeout: 5000,
68
+ maxBuffer,
69
+ });
70
+ return {
71
+ ok: res.status === 0,
72
+ status: res.status,
73
+ stdout: String(res.stdout || ""),
74
+ stderr: String(res.stderr || ""),
75
+ };
76
+ } catch (err) {
77
+ return {
78
+ ok: false,
79
+ status: -1,
80
+ stdout: "",
81
+ stderr: err && err.message ? err.message : String(err),
82
+ };
83
+ }
84
+ }
85
+
86
+ function listGitWorktrees(projectRoot) {
87
+ const root = safeCanonicalRoot(projectRoot);
88
+ const res = runGit(root, ["worktree", "list", "--porcelain"]);
89
+ if (!res.ok || !res.stdout.trim()) {
90
+ return [{
91
+ path: root,
92
+ branch: detectGitBranch(root),
93
+ head: "",
94
+ isMain: true,
95
+ }];
96
+ }
97
+
98
+ const worktrees = [];
99
+ let current = null;
100
+ for (const line of res.stdout.split(/\r?\n/)) {
101
+ if (!line.trim()) {
102
+ if (current && current.path) worktrees.push(current);
103
+ current = null;
104
+ continue;
105
+ }
106
+ if (line.startsWith("worktree ")) {
107
+ if (current && current.path) worktrees.push(current);
108
+ const wtPath = safeCanonicalRoot(line.slice(9).trim());
109
+ current = {
110
+ path: wtPath,
111
+ head: "",
112
+ branch: "",
113
+ detached: false,
114
+ isMain: wtPath === root,
115
+ };
116
+ } else if (current && line.startsWith("HEAD ")) {
117
+ current.head = line.slice(5).trim().slice(0, 8);
118
+ } else if (current && line.startsWith("branch ")) {
119
+ current.branch = line.slice(7).trim().replace(/^refs\/heads\//, "");
120
+ } else if (current && line === "detached") {
121
+ current.detached = true;
122
+ }
123
+ }
124
+ if (current && current.path) worktrees.push(current);
125
+ return worktrees.length > 0
126
+ ? worktrees
127
+ : [{ path: root, branch: detectGitBranch(root), head: "", isMain: true }];
128
+ }
129
+
130
+ function detectGitBranch(cwd) {
131
+ const res = runGit(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]);
132
+ if (!res.ok) return "";
133
+ return res.stdout.trim();
134
+ }
135
+
136
+ function parsePorcelainStatus(stdout = "", numstatMap = new Map()) {
137
+ const files = [];
138
+ for (const rawLine of String(stdout || "").split(/\r?\n/)) {
139
+ if (rawLine.length < 4) continue;
140
+ const indexStatus = rawLine[0];
141
+ const workTreeStatus = rawLine[1];
142
+ let filePath = rawLine.slice(3).trim();
143
+ let origPath = "";
144
+ if (filePath.includes(" -> ")) {
145
+ const parts = filePath.split(" -> ");
146
+ origPath = parts[0].replace(/^"|"$/g, "");
147
+ filePath = parts[1].replace(/^"|"$/g, "");
148
+ } else {
149
+ filePath = filePath.replace(/^"|"$/g, "");
150
+ }
151
+ if (!filePath) continue;
152
+
153
+ let kind = "modified";
154
+ if (indexStatus === "?" && workTreeStatus === "?") kind = "untracked";
155
+ else if (indexStatus === "A" || workTreeStatus === "A") kind = "added";
156
+ else if (indexStatus === "D" || workTreeStatus === "D") kind = "deleted";
157
+ else if (indexStatus === "R" || workTreeStatus === "R") kind = "renamed";
158
+ else if (indexStatus === "U" || workTreeStatus === "U") kind = "conflicted";
159
+
160
+ const stats = numstatMap.get(filePath) || { additions: 0, deletions: 0 };
161
+ files.push({
162
+ path: filePath,
163
+ origPath,
164
+ kind,
165
+ code: `${indexStatus}${workTreeStatus}`.trim() || "M",
166
+ staged: indexStatus !== " " && indexStatus !== "?",
167
+ unstaged: workTreeStatus !== " ",
168
+ additions: stats.additions,
169
+ deletions: stats.deletions,
170
+ });
171
+ }
172
+ return files;
173
+ }
174
+
175
+ function loadNumstatMap(cwd) {
176
+ const map = new Map();
177
+ for (const extra of [[], ["--cached"]]) {
178
+ const res = runGit(cwd, ["diff", "--numstat", ...extra]);
179
+ if (!res.ok) continue;
180
+ for (const line of res.stdout.split(/\r?\n/)) {
181
+ if (!line.trim()) continue;
182
+ const [addRaw, delRaw, rawPath] = line.split("\t");
183
+ if (!rawPath) continue;
184
+ const cleanPath = rawPath.includes(" => ")
185
+ ? rawPath.replace(/\{([^}]*?)\s*=>\s*([^}]*?)\}/g, "$2").split(" => ").pop().trim()
186
+ : rawPath.trim();
187
+ const prev = map.get(cleanPath) || { additions: 0, deletions: 0 };
188
+ const add = Number.parseInt(addRaw, 10);
189
+ const del = Number.parseInt(delRaw, 10);
190
+ map.set(cleanPath, {
191
+ additions: prev.additions + (Number.isFinite(add) ? add : 0),
192
+ deletions: prev.deletions + (Number.isFinite(del) ? del : 0),
193
+ });
194
+ }
195
+ }
196
+ return map;
197
+ }
198
+
199
+ function buildUntrackedPseudoDiff(targetRoot, relPath, maxBytes = 128 * 1024) {
200
+ try {
201
+ const { resolved } = resolveWorkspacePath(targetRoot, relPath);
202
+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) return "";
203
+ const ext = path.extname(resolved).toLowerCase();
204
+ if (BINARY_EXTENSIONS.has(ext)) return `Binary file ${relPath} (untracked)`;
205
+ const stat = fs.statSync(resolved);
206
+ const fd = fs.openSync(resolved, "r");
207
+ try {
208
+ const len = Math.min(stat.size, maxBytes);
209
+ const buf = Buffer.alloc(len);
210
+ fs.readSync(fd, buf, 0, len, 0);
211
+ if (buf.includes(0)) return `Binary file ${relPath} (untracked)`;
212
+ const lines = redactSecrets(buf.toString("utf8")).replace(/\r\n/g, "\n").split("\n");
213
+ const header = [
214
+ `diff --git a/${relPath} b/${relPath}`,
215
+ "new file mode 100644",
216
+ "--- /dev/null",
217
+ `+++ b/${relPath}`,
218
+ `@@ -0,0 +1,${lines.length} @@`,
219
+ ];
220
+ const body = lines.map((line) => `+${line}`);
221
+ if (stat.size > maxBytes) body.push("\\ Truncated large untracked file");
222
+ return [...header, ...body].join("\n");
223
+ } finally {
224
+ fs.closeSync(fd);
225
+ }
226
+ } catch {
227
+ return "";
228
+ }
229
+ }
230
+
231
+ function readFileDiff(targetRoot, relPath, fileEntry = null) {
232
+ const clean = String(relPath || "").trim();
233
+ if (!clean) return "";
234
+ resolveWorkspacePath(targetRoot, clean);
235
+ if (fileEntry && fileEntry.kind === "untracked") {
236
+ return buildUntrackedPseudoDiff(targetRoot, clean);
237
+ }
238
+ const headCheck = runGit(targetRoot, ["rev-parse", "--verify", "HEAD"]);
239
+ const args = headCheck.ok
240
+ ? ["diff", "HEAD", "--", clean]
241
+ : ["diff", "--cached", "--", clean];
242
+ let diffRes = runGit(targetRoot, args);
243
+ let patch = diffRes.stdout || "";
244
+ if (!patch.trim()) {
245
+ diffRes = runGit(targetRoot, ["diff", "--", clean]);
246
+ patch = diffRes.stdout || "";
247
+ }
248
+ if (!patch.trim()) {
249
+ patch = buildUntrackedPseudoDiff(targetRoot, clean);
250
+ }
251
+ return redactSecrets(patch.slice(0, 256 * 1024));
252
+ }
253
+
254
+ function loadWorkspaceChanges(projectRoot, options = {}) {
255
+ const root = safeCanonicalRoot(projectRoot);
256
+ const worktrees = listGitWorktrees(root);
257
+ const requestedWt = options.worktreeRoot ? safeCanonicalRoot(options.worktreeRoot) : root;
258
+ const validWt = worktrees.some((wt) => wt.path === requestedWt) ? requestedWt : root;
259
+ const branch = detectGitBranch(validWt);
260
+ const statusRes = runGit(validWt, ["status", "--porcelain=v1", "-uall"]);
261
+ const isGitRepo = statusRes.ok;
262
+ const numstatMap = isGitRepo ? loadNumstatMap(validWt) : new Map();
263
+ const files = isGitRepo ? parsePorcelainStatus(statusRes.stdout, numstatMap) : [];
264
+
265
+ for (const item of files) {
266
+ if (item.kind === "untracked" && item.additions === 0) {
267
+ try {
268
+ const { resolved } = resolveWorkspacePath(validWt, item.path);
269
+ const stat = fs.statSync(resolved);
270
+ if (stat.isFile() && stat.size <= 128 * 1024 && !BINARY_EXTENSIONS.has(path.extname(resolved).toLowerCase())) {
271
+ item.additions = fs.readFileSync(resolved, "utf8").split(/\r?\n/).length;
272
+ }
273
+ } catch {
274
+ // ignore stat failures
275
+ }
276
+ }
277
+ }
278
+
279
+ const selectedFile = String(options.filePath || (files[0] && files[0].path) || "").trim();
280
+ const selectedEntry = files.find((f) => f.path === selectedFile) || null;
281
+ const diff = isGitRepo && selectedFile ? readFileDiff(validWt, selectedFile, selectedEntry) : "";
282
+
283
+ const reports = listReports(root, {
284
+ num: Number(options.reportLimit) || 25,
285
+ agent: options.agentId || "",
286
+ });
287
+ const reportSummary = readReportSummary(root);
288
+
289
+ const totals = files.reduce(
290
+ (acc, item) => ({
291
+ additions: acc.additions + (item.additions || 0),
292
+ deletions: acc.deletions + (item.deletions || 0),
293
+ }),
294
+ { additions: 0, deletions: 0 }
295
+ );
296
+
297
+ return {
298
+ projectRoot: root,
299
+ worktreeRoot: validWt,
300
+ isGitRepo,
301
+ branch,
302
+ worktrees,
303
+ files,
304
+ totals,
305
+ selectedFile,
306
+ diff,
307
+ reports,
308
+ reportSummary,
309
+ };
310
+ }
311
+
312
+ function inferLanguage(filePath = "") {
313
+ const ext = path.extname(filePath).toLowerCase();
314
+ const map = {
315
+ ".js": "javascript",
316
+ ".cjs": "javascript",
317
+ ".mjs": "javascript",
318
+ ".jsx": "jsx",
319
+ ".ts": "typescript",
320
+ ".tsx": "tsx",
321
+ ".rs": "rust",
322
+ ".md": "markdown",
323
+ ".json": "json",
324
+ ".toml": "toml",
325
+ ".yaml": "yaml",
326
+ ".yml": "yaml",
327
+ ".css": "css",
328
+ ".html": "html",
329
+ ".sh": "bash",
330
+ ".swift": "swift",
331
+ ".py": "python",
332
+ };
333
+ return map[ext] || "plaintext";
334
+ }
335
+
336
+ function collectWorkspaceFiles(root, { maxFiles = 350, maxDepth = 4, query = "" } = {}) {
337
+ const results = [];
338
+ const needle = String(query || "").trim().toLowerCase();
339
+
340
+ function walk(currentDir, depth) {
341
+ if (results.length >= maxFiles || depth > maxDepth) return;
342
+ let entries = [];
343
+ try {
344
+ entries = fs.readdirSync(currentDir, { withFileTypes: true });
345
+ } catch {
346
+ return;
347
+ }
348
+ entries.sort((a, b) => {
349
+ if (a.isDirectory() !== b.isDirectory()) return a.isDirectory() ? -1 : 1;
350
+ return a.name.localeCompare(b.name);
351
+ });
352
+ for (const entry of entries) {
353
+ if (results.length >= maxFiles) return;
354
+ if (entry.name.startsWith(".") && entry.name !== ".env.example") {
355
+ if (entry.isDirectory() || IGNORED_DIRS.has(entry.name)) continue;
356
+ }
357
+ if (entry.isDirectory()) {
358
+ if (IGNORED_DIRS.has(entry.name)) continue;
359
+ walk(path.join(currentDir, entry.name), depth + 1);
360
+ } else if (entry.isFile()) {
361
+ const ext = path.extname(entry.name).toLowerCase();
362
+ if (BINARY_EXTENSIONS.has(ext)) continue;
363
+ const rel = path.relative(root, path.join(currentDir, entry.name)).split(path.sep).join("/");
364
+ if (needle && !rel.toLowerCase().includes(needle)) continue;
365
+ results.push({
366
+ path: rel,
367
+ name: entry.name,
368
+ isMarkdown: ext === ".md",
369
+ pinned: PINNED_DOC_NAMES.includes(rel),
370
+ });
371
+ }
372
+ }
373
+ }
374
+
375
+ walk(root, 0);
376
+ results.sort((a, b) => {
377
+ if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;
378
+ if (a.isMarkdown !== b.isMarkdown) return a.isMarkdown ? -1 : 1;
379
+ return a.path.localeCompare(b.path);
380
+ });
381
+ return results;
382
+ }
383
+
384
+ function normalizeRequestedDocPath(root, requested = "") {
385
+ let clean = String(requested || "").trim();
386
+ if (!clean) return "";
387
+ clean = clean.replace(/^file:\/\//i, "");
388
+ let lineAnchor = 0;
389
+ const hashMatch = clean.match(/#L(\d+)(?:-L?\d+)?$/i);
390
+ if (hashMatch) {
391
+ lineAnchor = Number.parseInt(hashMatch[1], 10) || 0;
392
+ clean = clean.slice(0, hashMatch.index);
393
+ }
394
+ const colonMatch = clean.match(/:(\d+)(?::\d+)?$/);
395
+ if (colonMatch && !fs.existsSync(path.resolve(root, clean))) {
396
+ lineAnchor = lineAnchor || Number.parseInt(colonMatch[1], 10) || 0;
397
+ clean = clean.slice(0, colonMatch.index);
398
+ }
399
+ if (path.isAbsolute(clean)) {
400
+ const candidate = safeCanonicalRoot(path.dirname(clean));
401
+ const full = path.join(candidate, path.basename(clean));
402
+ if (isPathInside(root, full)) {
403
+ clean = path.relative(root, full).split(path.sep).join("/");
404
+ }
405
+ }
406
+ return { path: clean, anchorLine: lineAnchor };
407
+ }
408
+
409
+ function loadWorkspaceDocs(projectRoot, options = {}) {
410
+ const root = safeCanonicalRoot(projectRoot);
411
+ const targetRoot = options.worktreeRoot && isPathInside(root, path.resolve(options.worktreeRoot))
412
+ ? path.resolve(options.worktreeRoot)
413
+ : root;
414
+ const files = collectWorkspaceFiles(targetRoot, {
415
+ query: options.query || "",
416
+ maxFiles: Number(options.maxFiles) || 350,
417
+ });
418
+
419
+ const parsedTarget = options.filePath
420
+ ? normalizeRequestedDocPath(targetRoot, options.filePath)
421
+ : null;
422
+ const defaultFile = (files.find((f) => f.pinned) || files[0] || {}).path || "";
423
+ const selectedPath = (parsedTarget && parsedTarget.path) || defaultFile;
424
+ const anchorLine = (parsedTarget && parsedTarget.anchorLine) || Number(options.anchorLine) || 0;
425
+
426
+ let document = null;
427
+ if (selectedPath) {
428
+ try {
429
+ const { resolved } = resolveWorkspacePath(targetRoot, selectedPath);
430
+ if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) {
431
+ const stat = fs.statSync(resolved);
432
+ const maxBytes = 256 * 1024;
433
+ const fd = fs.openSync(resolved, "r");
434
+ try {
435
+ const len = Math.min(stat.size, maxBytes);
436
+ const buf = Buffer.alloc(len);
437
+ fs.readSync(fd, buf, 0, len, 0);
438
+ const rawText = redactSecrets(buf.toString("utf8")).replace(/\r\n/g, "\n");
439
+ const allLines = rawText.split("\n");
440
+ const startLine = Math.max(1, Number(options.startLine) || 1);
441
+ const endLine = Math.min(allLines.length, Number(options.endLine) || allLines.length);
442
+ document = {
443
+ path: path.relative(targetRoot, resolved).split(path.sep).join("/"),
444
+ absolutePath: resolved,
445
+ language: inferLanguage(resolved),
446
+ content: allLines.slice(startLine - 1, endLine).join("\n"),
447
+ totalLines: allLines.length,
448
+ startLine,
449
+ endLine,
450
+ anchorLine,
451
+ truncated: stat.size > maxBytes,
452
+ sizeBytes: stat.size,
453
+ };
454
+ } finally {
455
+ fs.closeSync(fd);
456
+ }
457
+ }
458
+ } catch (err) {
459
+ document = {
460
+ path: selectedPath,
461
+ error: err && err.message ? err.message : String(err),
462
+ };
463
+ }
464
+ }
465
+
466
+ return {
467
+ projectRoot: root,
468
+ files,
469
+ selectedPath: document ? document.path : selectedPath,
470
+ document,
471
+ };
472
+ }
473
+
474
+ function writeDecisionsIndexQuiet(manager) {
475
+ const decisions = manager.readDecisions();
476
+ const entries = manager.buildIndexEntries(decisions);
477
+ fs.mkdirSync(manager.contextDir, { recursive: true });
478
+ const lines = entries.map((e) => JSON.stringify(e));
479
+ const output = lines.length ? `${lines.join("\n")}\n` : "";
480
+ fs.writeFileSync(manager.indexFile, output, "utf8");
481
+ }
482
+
483
+ function createStructuredDecision(projectRoot, input = {}) {
484
+ const root = safeCanonicalRoot(projectRoot);
485
+ const manager = new DecisionsManager(root);
486
+ const title = String(input.title || "").trim();
487
+ if (!title) throw new Error("Decision title is required");
488
+
489
+ const author = String(input.author || process.env.UFOO_NICKNAME || process.env.USER || "user").trim();
490
+ const nickname = String(input.nickname || author).trim();
491
+ const status = String(input.status || "open").trim() || "open";
492
+ const num = manager.nextNumber();
493
+ const slug = manager.slugify(title);
494
+ const nick = manager.slugify(nickname);
495
+ const date = new Date().toISOString().slice(0, 10);
496
+
497
+ fs.mkdirSync(manager.contextDir, { recursive: true });
498
+ fs.mkdirSync(manager.decisionsDir, { recursive: true });
499
+
500
+ const file = `${num}-${nick}-${slug}.md`;
501
+ const filePath = path.join(manager.decisionsDir, file);
502
+ const contextText = String(input.context || "Recorded from Ufoo Desktop.").trim();
503
+ const decisionText = String(input.decision || title).trim();
504
+ const implicationsText = String(input.implications || "Keep related runtime and documentation aligned.").trim();
505
+
506
+ const markdown = matter.stringify(
507
+ `# DECISION ${num}: ${title}\n\n`
508
+ + `Date: ${date}\n`
509
+ + `Author: ${author}\n`
510
+ + `Nickname: ${nickname}\n\n`
511
+ + `Context:\n${contextText}\n\n`
512
+ + `Decision:\n${decisionText}\n\n`
513
+ + `Implications:\n${implicationsText}\n`,
514
+ {
515
+ status,
516
+ nickname,
517
+ created_at: new Date().toISOString(),
518
+ }
519
+ );
520
+ fs.writeFileSync(filePath, redactSecrets(markdown), "utf8");
521
+ writeDecisionsIndexQuiet(manager);
522
+ return { file, filePath };
523
+ }
524
+
525
+ function updateDecisionStatus(projectRoot, input = {}) {
526
+ const root = safeCanonicalRoot(projectRoot);
527
+ const manager = new DecisionsManager(root);
528
+ const targetFile = path.basename(String(input.file || "").trim());
529
+ const nextStatus = String(input.status || "").trim().toLowerCase();
530
+ if (!targetFile || !["open", "resolved", "superseded"].includes(nextStatus)) {
531
+ throw new Error("Valid decision file and status (open|resolved|superseded) are required");
532
+ }
533
+ const filePath = path.join(manager.decisionsDir, targetFile);
534
+ if (!fs.existsSync(filePath)) {
535
+ throw new Error(`Decision not found: ${targetFile}`);
536
+ }
537
+ const raw = fs.readFileSync(filePath, "utf8");
538
+ const parsed = matter(raw);
539
+ const nextData = {
540
+ ...parsed.data,
541
+ status: nextStatus,
542
+ };
543
+ if (nextStatus !== "open") {
544
+ nextData.resolved_at = new Date().toISOString();
545
+ nextData.resolved_by = String(input.actor || process.env.USER || "user");
546
+ } else {
547
+ delete nextData.resolved_at;
548
+ delete nextData.resolved_by;
549
+ }
550
+ const updated = matter.stringify(`${parsed.content.trim()}\n`, nextData);
551
+ fs.writeFileSync(filePath, updated, "utf8");
552
+ writeDecisionsIndexQuiet(manager);
553
+ return { file: targetFile, status: nextStatus };
554
+ }
555
+
556
+ function handleWorkspaceContext(projectRoot, payload = {}) {
557
+ const root = safeCanonicalRoot(projectRoot);
558
+ const operation = String(payload.operation || "snapshot").trim();
559
+ const decisionsManager = new DecisionsManager(root);
560
+ const memoryManager = new MemoryManager(root, { ensure: operation.startsWith("memory.") });
561
+
562
+ if (operation === "decision.create") {
563
+ createStructuredDecision(root, payload);
564
+ } else if (operation === "decision.set_status") {
565
+ updateDecisionStatus(root, payload);
566
+ } else if (operation === "memory.add") {
567
+ memoryManager.add({
568
+ title: payload.title,
569
+ body: payload.body,
570
+ tags: payload.tags || [],
571
+ source: "user:desktop",
572
+ }, { actor: "user:desktop", source: "desktop" });
573
+ } else if (operation === "memory.update") {
574
+ memoryManager.update(payload.id, {
575
+ ...(payload.title !== undefined ? { title: payload.title } : {}),
576
+ ...(payload.body !== undefined ? { body: payload.body } : {}),
577
+ ...(payload.tags !== undefined ? { tags: payload.tags } : {}),
578
+ }, { actor: "user:desktop", source: "desktop" });
579
+ } else if (operation === "memory.archive") {
580
+ memoryManager.archive(payload.id, { actor: "user:desktop", source: "desktop" });
581
+ } else if (operation !== "snapshot") {
582
+ throw new Error(`Unsupported workspace.context operation: ${operation}`);
583
+ }
584
+
585
+ const decisions = decisionsManager.readDecisions().map((item) => ({
586
+ file: item.file,
587
+ status: item.status || "open",
588
+ title: item.title,
589
+ author: item.data?.author || decisionsManager.extractField(item.body, "Author") || item.data?.nickname || "",
590
+ date: item.data?.created_at || decisionsManager.extractField(item.body, "Date") || "",
591
+ body: redactSecrets(item.body || ""),
592
+ }));
593
+
594
+ const query = String(payload.query || "").trim();
595
+ const memories = query
596
+ ? memoryManager.search(query, { limit: 50, includeArchived: Boolean(payload.includeArchived) })
597
+ : memoryManager.list({ limit: 100, includeArchived: Boolean(payload.includeArchived) });
598
+
599
+ return {
600
+ projectRoot: root,
601
+ decisions,
602
+ openDecisionCount: decisions.filter((d) => d.status === "open").length,
603
+ memories: memories.map((m) => ({
604
+ id: m.id,
605
+ title: m.title,
606
+ body: redactSecrets(m.body || ""),
607
+ tags: m.tags || [],
608
+ status: m.status || "active",
609
+ updated_at: m.updated_at || "",
610
+ created_at: m.created_at || "",
611
+ })),
612
+ };
613
+ }
614
+
615
+ module.exports = {
616
+ loadWorkspaceChanges,
617
+ loadWorkspaceDocs,
618
+ handleWorkspaceContext,
619
+ listGitWorktrees,
620
+ detectGitBranch,
621
+ };