@causyne/agent 1.20.124 → 1.20.128

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 (254) hide show
  1. package/bin/causyne.js +1 -1
  2. package/docs/THIRD_PARTY_NOTICES.md +36 -2
  3. package/package.json +6 -4
  4. package/src/acp/protocol.ts +19 -1
  5. package/src/acp/server.js +282 -8
  6. package/src/acp/server.ts +284 -8
  7. package/src/agent/abortableDelay.js +2 -2
  8. package/src/agent/abortableDelay.ts +2 -2
  9. package/src/agent/errorClassifier.js +9 -1
  10. package/src/agent/errorClassifier.ts +8 -1
  11. package/src/agentLoop.js +142 -53
  12. package/src/agentLoop.ts +151 -50
  13. package/src/approvalPolicy.js +34 -10
  14. package/src/approvalPolicy.ts +42 -11
  15. package/src/browser/causyneBrowser.js +61 -3
  16. package/src/browser/causyneBrowser.ts +65 -3
  17. package/src/browser/urlPolicy.js +14 -1
  18. package/src/browser/urlPolicy.ts +12 -1
  19. package/src/cliMode.js +21 -9
  20. package/src/cliMode.ts +20 -8
  21. package/src/commands.js +365 -45
  22. package/src/commands.ts +403 -45
  23. package/src/config.js +19 -4
  24. package/src/config.ts +18 -4
  25. package/src/core/contextCompactor.js +54 -7
  26. package/src/core/contextCompactor.ts +63 -7
  27. package/src/core/goalLoop.js +257 -0
  28. package/src/core/goalLoop.ts +310 -0
  29. package/src/entrypoint.js +135 -3
  30. package/src/entrypoint.ts +136 -3
  31. package/src/game/causyneCoreBridge.js +686 -0
  32. package/src/game/causyneCoreBridge.ts +702 -0
  33. package/src/game/gameLauncher.js +287 -0
  34. package/src/game/gameLauncher.ts +352 -0
  35. package/src/game/gameProvisioner.js +425 -0
  36. package/src/game/gameProvisioner.ts +488 -0
  37. package/src/headlessCli.js +19 -12
  38. package/src/headlessCli.ts +22 -8
  39. package/src/infra/atomicWriter.js +40 -4
  40. package/src/infra/atomicWriter.ts +36 -4
  41. package/src/launchIntent.js +73 -3
  42. package/src/launchIntent.ts +76 -3
  43. package/src/lsp/lspClient.js +83 -12
  44. package/src/lsp/lspClient.ts +75 -12
  45. package/src/mcp/mcpRegistry.js +75 -8
  46. package/src/mcp/mcpRegistry.ts +70 -7
  47. package/src/memory/contextBudget.js +2 -0
  48. package/src/memory/contextBudget.ts +1 -0
  49. package/src/memory/episodicStore.js +40 -0
  50. package/src/memory/episodicStore.ts +46 -0
  51. package/src/memory.js +67 -0
  52. package/src/memory.ts +65 -0
  53. package/src/modelVariants.js +45 -0
  54. package/src/modelVariants.ts +54 -0
  55. package/src/outputRecovery.js +3 -2
  56. package/src/outputRecovery.ts +4 -2
  57. package/src/permissionPresets.js +327 -0
  58. package/src/permissionPresets.ts +361 -0
  59. package/src/personalization.js +365 -0
  60. package/src/personalization.ts +471 -0
  61. package/src/projectInstructions.js +30 -10
  62. package/src/projectInstructions.ts +31 -12
  63. package/src/providers/acp.js +3 -2
  64. package/src/providers/acp.ts +3 -2
  65. package/src/providers/antigravity.js +64 -9
  66. package/src/providers/antigravity.ts +75 -9
  67. package/src/providers/byokHttp.js +7 -1
  68. package/src/providers/byokHttp.ts +6 -1
  69. package/src/providers/byokStream.js +21 -8
  70. package/src/providers/byokStream.ts +17 -7
  71. package/src/providers/dashscope-byok.js +21 -5
  72. package/src/providers/dashscope-byok.ts +29 -11
  73. package/src/providers/moonshot.js +26 -7
  74. package/src/providers/moonshot.ts +34 -13
  75. package/src/providers/muse.js +6 -0
  76. package/src/providers/muse.ts +8 -0
  77. package/src/providers/ollama.js +39 -7
  78. package/src/providers/ollama.ts +36 -7
  79. package/src/providers/openai-compatible.js +16 -3
  80. package/src/providers/openai-compatible.ts +13 -3
  81. package/src/providers/openai.js +62 -4
  82. package/src/providers/openai.ts +50 -4
  83. package/src/providers/openrouter.js +19 -4
  84. package/src/providers/openrouter.ts +21 -4
  85. package/src/providers/qwen-byok.js +21 -5
  86. package/src/providers/qwen-byok.ts +29 -11
  87. package/src/providers/xai.js +26 -10
  88. package/src/providers/xai.ts +34 -16
  89. package/src/reporting.js +4 -2
  90. package/src/reporting.ts +4 -2
  91. package/src/sandbox.js +34 -0
  92. package/src/sandbox.ts +43 -0
  93. package/src/scheduler/scheduler.js +372 -0
  94. package/src/scheduler/scheduler.ts +433 -0
  95. package/src/sessionSearchIndex.js +267 -0
  96. package/src/sessionSearchIndex.ts +311 -0
  97. package/src/skillsManager.js +2 -3
  98. package/src/skillsManager.ts +2 -3
  99. package/src/toolPacks.js +6 -0
  100. package/src/toolPacks.ts +6 -0
  101. package/src/tools/applyPatch.js +1 -1
  102. package/src/tools/applyPatch.ts +1 -1
  103. package/src/tools/generateMediaViaApi.js +4 -3
  104. package/src/tools/generateMediaViaApi.ts +4 -3
  105. package/src/tools/memoryWrite.js +15 -1
  106. package/src/tools/memoryWrite.ts +16 -1
  107. package/src/tools/nativeEngine.js +2 -2
  108. package/src/tools/nativeEngine.ts +2 -2
  109. package/src/tools/openSourceToolProvisioner.js +2 -2
  110. package/src/tools/openSourceToolProvisioner.ts +2 -2
  111. package/src/tools/osSandbox.js +1 -1
  112. package/src/tools/osSandbox.ts +1 -1
  113. package/src/tools/payloadSanitizer.js +0 -1
  114. package/src/tools/payloadSanitizer.ts +0 -1
  115. package/src/tools/pdfReader.js +122 -20
  116. package/src/tools/pdfReader.ts +111 -20
  117. package/src/tools/presentDeliverable.js +103 -0
  118. package/src/tools/presentDeliverable.ts +127 -0
  119. package/src/tools/ptcRuntime.js +444 -0
  120. package/src/tools/ptcRuntime.ts +490 -0
  121. package/src/tools/ptyTerminal.js +1108 -0
  122. package/src/tools/ptyTerminal.ts +1245 -0
  123. package/src/tools/registry.js +21 -12
  124. package/src/tools/registry.ts +21 -12
  125. package/src/tools/toolOutputStore.js +26 -4
  126. package/src/tools/toolOutputStore.ts +22 -4
  127. package/src/tools/webFetch.js +158 -11
  128. package/src/tools/webFetch.ts +145 -11
  129. package/src/tools/webSearch.js +123 -36
  130. package/src/tools/webSearch.ts +124 -33
  131. package/src/tui/banner.js +5 -1
  132. package/src/tui/banner.ts +6 -1
  133. package/src/tui/chatRenderer.js +1 -2
  134. package/src/tui/chatRenderer.ts +1 -2
  135. package/src/tui/completion.js +1 -0
  136. package/src/tui/completion.ts +1 -0
  137. package/src/tui/composerControls.js +111 -27
  138. package/src/tui/composerControls.ts +124 -28
  139. package/src/tui/dialogs.js +3 -16
  140. package/src/tui/dialogs.ts +3 -16
  141. package/src/tui/home.js +1 -0
  142. package/src/tui/home.ts +1 -0
  143. package/src/tui/invocation.js +1 -2
  144. package/src/tui/invocation.ts +1 -2
  145. package/src/tui/modelPicker.js +22 -12
  146. package/src/tui/modelPicker.ts +22 -12
  147. package/src/tui/overlay.js +2 -5
  148. package/src/tui/overlay.ts +2 -5
  149. package/src/tui/prompt.js +6 -4
  150. package/src/tui/prompt.ts +6 -4
  151. package/src/tui/selectList.js +4 -12
  152. package/src/tui/selectList.ts +4 -12
  153. package/src/tui/setup.js +22 -9
  154. package/src/tui/setup.ts +26 -9
  155. package/src/tui/statusLine.ts +2 -0
  156. package/src/web/client/browserPanel.js +905 -0
  157. package/src/web/client/browserPanel.ts +872 -0
  158. package/src/web/client/chatStream.js +321 -0
  159. package/src/web/client/chatStream.ts +297 -0
  160. package/src/web/client/cliPanel.js +165 -0
  161. package/src/web/client/cliPanel.ts +171 -0
  162. package/src/web/client/composer.js +204 -0
  163. package/src/web/client/composer.ts +209 -0
  164. package/src/web/client/diffPanel.js +176 -0
  165. package/src/web/client/diffPanel.ts +203 -0
  166. package/src/web/client/dom.js +271 -0
  167. package/src/web/client/dom.ts +272 -0
  168. package/src/web/client/filesAndCanvas.js +233 -0
  169. package/src/web/client/filesAndCanvas.ts +240 -0
  170. package/src/web/client/gameLauncherUi.js +78 -0
  171. package/src/web/client/gameLauncherUi.ts +78 -0
  172. package/src/web/client/main.js +316 -0
  173. package/src/web/client/main.ts +391 -0
  174. package/src/web/client/markdown.js +364 -0
  175. package/src/web/client/markdown.ts +373 -0
  176. package/src/web/client/modelPicker.js +455 -0
  177. package/src/web/client/modelPicker.ts +451 -0
  178. package/src/web/client/permissionPresetsUi.js +307 -0
  179. package/src/web/client/permissionPresetsUi.ts +333 -0
  180. package/src/web/client/sessions.js +353 -0
  181. package/src/web/client/sessions.ts +372 -0
  182. package/src/web/client/settingsModal.js +824 -0
  183. package/src/web/client/settingsModal.ts +959 -0
  184. package/src/web/client/state.js +280 -0
  185. package/src/web/client/state.ts +259 -0
  186. package/src/web/client/streamSmoother.js +127 -0
  187. package/src/web/client/streamSmoother.ts +119 -0
  188. package/src/web/client/studioLayout.js +89 -0
  189. package/src/web/client/studioLayout.ts +103 -0
  190. package/src/web/client/studioShell.js +660 -0
  191. package/src/web/client/studioShell.ts +672 -0
  192. package/src/web/client/studioStart.js +77 -0
  193. package/src/web/client/studioStart.ts +89 -0
  194. package/src/web/client/terminalPanel.js +606 -0
  195. package/src/web/client/terminalPanel.ts +632 -0
  196. package/src/web/client/terminalTheme.js +249 -0
  197. package/src/web/client/terminalTheme.ts +258 -0
  198. package/src/web/client/turnView.js +934 -0
  199. package/src/web/client/turnView.ts +981 -0
  200. package/src/web/client/types.js +1 -0
  201. package/src/web/client/types.ts +322 -0
  202. package/src/web/client/validators.js +147 -0
  203. package/src/web/client/validators.ts +140 -0
  204. package/src/web/server/activeRuns.js +152 -0
  205. package/src/web/server/activeRuns.ts +171 -0
  206. package/src/web/server/routesBrowser.js +409 -0
  207. package/src/web/server/routesBrowser.ts +435 -0
  208. package/src/web/server/routesChat.js +304 -0
  209. package/src/web/server/routesChat.ts +347 -0
  210. package/src/web/server/routesCore.js +472 -0
  211. package/src/web/server/routesCore.ts +522 -0
  212. package/src/web/server/routesSettings.js +344 -0
  213. package/src/web/server/routesSettings.ts +397 -0
  214. package/src/web/server/routesTerminal.js +162 -0
  215. package/src/web/server/routesTerminal.ts +182 -0
  216. package/src/web/server/routesWorkspace.js +510 -0
  217. package/src/web/server/routesWorkspace.ts +546 -0
  218. package/src/web/server/security.js +98 -0
  219. package/src/web/server/security.ts +108 -0
  220. package/src/web/server/sessionTranscript.js +586 -0
  221. package/src/web/server/sessionTranscript.ts +566 -0
  222. package/src/web/server/staticAssets.js +104 -0
  223. package/src/web/server/staticAssets.ts +116 -0
  224. package/src/web/server/types.js +1 -0
  225. package/src/web/server/types.ts +135 -0
  226. package/src/web/server/workspaceFiles.js +368 -0
  227. package/src/web/server/workspaceFiles.ts +363 -0
  228. package/src/web/skybridgeServer.js +78 -2448
  229. package/src/web/skybridgeServer.ts +120 -2600
  230. package/src/web/skybridgeUi.js +20 -450
  231. package/src/web/skybridgeUi.ts +24 -455
  232. package/src/web/styles/agent.css +380 -0
  233. package/src/web/styles/composer.css +193 -0
  234. package/src/web/styles/overlays.css +935 -0
  235. package/src/web/styles/shell.css +387 -0
  236. package/src/web/styles/studio.css +951 -0
  237. package/src/web/styles/thread.css +221 -0
  238. package/src/web/styles/tokens.css +94 -0
  239. package/src/web/ui/brandMark.js +73 -0
  240. package/src/web/ui/brandMark.ts +82 -0
  241. package/src/web/ui/modalsTemplate.js +388 -0
  242. package/src/web/ui/modalsTemplate.ts +388 -0
  243. package/src/web/ui/sidebarTemplate.js +63 -0
  244. package/src/web/ui/sidebarTemplate.ts +64 -0
  245. package/src/web/ui/studioTemplate.js +256 -0
  246. package/src/web/ui/studioTemplate.ts +256 -0
  247. package/src/web/ui/workspaceTemplate.js +72 -0
  248. package/src/web/ui/workspaceTemplate.ts +73 -0
  249. package/src/worktreeManager.js +16 -1
  250. package/src/worktreeManager.ts +22 -1
  251. package/src/web/skybridgeClientScript.js +0 -3951
  252. package/src/web/skybridgeClientScript.ts +0 -3952
  253. package/src/web/skybridgeStyles.js +0 -827
  254. package/src/web/skybridgeStyles.ts +0 -828
@@ -0,0 +1,365 @@
1
+ /**
2
+ * Causyne Agent — Per-Project & Global Personalization + Memory Governance
3
+ *
4
+ * Primary behavior is per-project (workspace-scoped) so each repository/project
5
+ * maintains its own high-priority personalization contract and memory policy
6
+ * without leaking into unrelated workspaces:
7
+ * - Project instructions : `<workspaceRoot>/.causyne/personalization.md`
8
+ * - Project settings : `<workspaceRoot>/.causyne/settings.json`
9
+ * - Global instructions : `~/.causyne/CAUSYNE.md`
10
+ * - Global memory prefs : `~/.causyne/config.json` (`memory: { enabled, allowToolAssisted }`)
11
+ *
12
+ * Security invariants:
13
+ * - Fixed allowlisted filenames only (no arbitrary path writes).
14
+ * - Refuses symlinks on both parent `.causyne` directory and target files.
15
+ * - Atomic file writes via `atomicWriteFileSync`.
16
+ * - Enforces 16 KiB single-file cap matching `projectInstructions.ts`.
17
+ */
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import { causyneHome } from './utils/paths.js';
21
+ import { loadConfig, saveConfig } from './config.js';
22
+ import { atomicWriteFileSync } from './infra/atomicWriter.js';
23
+ import { clearMemory, clearMemoryForWorkspace, getMemoryStats } from './memory.js';
24
+ import { episodicStore } from './memory/episodicStore.js';
25
+ import { loadProjectInstructions } from './projectInstructions.js';
26
+ import { safeDisplay } from './tui/text.js';
27
+ export const MAX_PERSONALIZATION_BYTES = 16_384;
28
+ const MAX_SETTINGS_JSON_BYTES = 64 * 1024;
29
+ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
30
+ const EXTERNAL_TOOL_ASSISTED_NAMES = new Set([
31
+ 'web_search',
32
+ 'web_fetch',
33
+ 'browser_act',
34
+ 'search_web',
35
+ 'read_url_content',
36
+ 'browser_navigate',
37
+ 'browser_read_page',
38
+ 'browser_interact',
39
+ 'browser_extract',
40
+ 'browser_screenshot',
41
+ 'browser_tabs'
42
+ ]);
43
+ function resolveHomeDir(env = process.env) {
44
+ const override = env.CAUSYNE_HOME && String(env.CAUSYNE_HOME).trim();
45
+ return override ? path.resolve(override) : causyneHome();
46
+ }
47
+ export function resolveProjectPersonalizationPath(workspaceRoot) {
48
+ return path.join(path.resolve(workspaceRoot), '.causyne', 'personalization.md');
49
+ }
50
+ export function resolveProjectSettingsPath(workspaceRoot) {
51
+ return path.join(path.resolve(workspaceRoot), '.causyne', 'settings.json');
52
+ }
53
+ export function resolveGlobalPersonalizationPath(env = process.env) {
54
+ return path.join(resolveHomeDir(env), 'CAUSYNE.md');
55
+ }
56
+ function assertNotSymlinkIfPresent(targetPath, expectedKind) {
57
+ try {
58
+ const stat = fs.lstatSync(targetPath);
59
+ if (stat.isSymbolicLink()) {
60
+ throw new Error(`Refusing symlink at ${safeDisplay(path.basename(targetPath))}`);
61
+ }
62
+ if (expectedKind === 'dir' && !stat.isDirectory()) {
63
+ throw new Error(`Expected directory at ${safeDisplay(path.basename(targetPath))}`);
64
+ }
65
+ if (expectedKind === 'file' && !stat.isFile()) {
66
+ throw new Error(`Expected regular file at ${safeDisplay(path.basename(targetPath))}`);
67
+ }
68
+ }
69
+ catch (err) {
70
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
71
+ if (code === 'ENOENT')
72
+ return;
73
+ throw err;
74
+ }
75
+ }
76
+ function ensureSafeDirectory(dirPath, mode) {
77
+ assertNotSymlinkIfPresent(dirPath, 'dir');
78
+ fs.mkdirSync(dirPath, { recursive: true, mode });
79
+ assertNotSymlinkIfPresent(dirPath, 'dir');
80
+ }
81
+ function readSafeMarkdownFile(filePath, scope, displayPath) {
82
+ try {
83
+ const stat = fs.lstatSync(filePath);
84
+ if (stat.isSymbolicLink() || !stat.isFile()) {
85
+ return {
86
+ scope,
87
+ path: filePath,
88
+ displayPath,
89
+ exists: false,
90
+ content: '',
91
+ bytes: 0,
92
+ maxBytes: MAX_PERSONALIZATION_BYTES
93
+ };
94
+ }
95
+ const raw = fs.readFileSync(filePath, 'utf8').replace(/^\uFEFF/, '').replace(/\r\n/g, '\n');
96
+ const clamped = raw.length > MAX_PERSONALIZATION_BYTES ? raw.slice(0, MAX_PERSONALIZATION_BYTES) : raw;
97
+ return {
98
+ scope,
99
+ path: filePath,
100
+ displayPath,
101
+ exists: true,
102
+ content: clamped,
103
+ bytes: Buffer.byteLength(clamped, 'utf8'),
104
+ maxBytes: MAX_PERSONALIZATION_BYTES
105
+ };
106
+ }
107
+ catch {
108
+ return {
109
+ scope,
110
+ path: filePath,
111
+ displayPath,
112
+ exists: false,
113
+ content: '',
114
+ bytes: 0,
115
+ maxBytes: MAX_PERSONALIZATION_BYTES
116
+ };
117
+ }
118
+ }
119
+ function readProjectSettingsRaw(workspaceRoot) {
120
+ const settingsPath = resolveProjectSettingsPath(workspaceRoot);
121
+ try {
122
+ const dirPath = path.dirname(settingsPath);
123
+ const dirStat = fs.lstatSync(dirPath);
124
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory())
125
+ return {};
126
+ const stat = fs.lstatSync(settingsPath);
127
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size === 0 || stat.size > MAX_SETTINGS_JSON_BYTES) {
128
+ return {};
129
+ }
130
+ const parsed = JSON.parse(fs.readFileSync(settingsPath, 'utf8').replace(/^\uFEFF/, ''));
131
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
132
+ return {};
133
+ const clean = Object.create(null);
134
+ for (const [k, v] of Object.entries(parsed)) {
135
+ if (!FORBIDDEN_KEYS.has(k))
136
+ clean[k] = v;
137
+ }
138
+ return { ...clean };
139
+ }
140
+ catch {
141
+ return {};
142
+ }
143
+ }
144
+ function writeProjectSettingsRaw(workspaceRoot, nextData) {
145
+ const settingsPath = resolveProjectSettingsPath(workspaceRoot);
146
+ const dirPath = path.dirname(settingsPath);
147
+ ensureSafeDirectory(dirPath, 0o755);
148
+ assertNotSymlinkIfPresent(settingsPath, 'file');
149
+ atomicWriteFileSync(settingsPath, `${JSON.stringify(nextData, null, 2)}\n`, { mode: 0o644 });
150
+ }
151
+ function readGlobalMemoryDefaults() {
152
+ const config = loadConfig();
153
+ const raw = config.memory && typeof config.memory === 'object' && !Array.isArray(config.memory)
154
+ ? config.memory
155
+ : {};
156
+ return {
157
+ enabled: raw.enabled !== false,
158
+ allowToolAssisted: raw.allowToolAssisted !== false
159
+ };
160
+ }
161
+ function readProjectMemoryOverrides(workspaceRoot) {
162
+ const rawSettings = readProjectSettingsRaw(workspaceRoot);
163
+ const rawMem = rawSettings.memory && typeof rawSettings.memory === 'object' && !Array.isArray(rawSettings.memory)
164
+ ? rawSettings.memory
165
+ : {};
166
+ const overrides = {};
167
+ if (typeof rawMem.enabled === 'boolean')
168
+ overrides.enabled = rawMem.enabled;
169
+ if (typeof rawMem.allowToolAssisted === 'boolean')
170
+ overrides.allowToolAssisted = rawMem.allowToolAssisted;
171
+ return overrides;
172
+ }
173
+ /**
174
+ * Resolves the effective Causyne Memory policy for a workspace:
175
+ * per-project overrides in `<workspace>/.causyne/settings.json` take precedence
176
+ * over global defaults in `~/.causyne/config.json`.
177
+ */
178
+ export function resolveEffectiveMemoryPolicy(workspaceRoot) {
179
+ const globalDefaults = readGlobalMemoryDefaults();
180
+ const projectOverrides = workspaceRoot ? readProjectMemoryOverrides(workspaceRoot) : {};
181
+ const hasProjectOverride = typeof projectOverrides.enabled === 'boolean' || typeof projectOverrides.allowToolAssisted === 'boolean';
182
+ return {
183
+ enabled: typeof projectOverrides.enabled === 'boolean' ? projectOverrides.enabled : globalDefaults.enabled,
184
+ allowToolAssisted: typeof projectOverrides.allowToolAssisted === 'boolean'
185
+ ? projectOverrides.allowToolAssisted
186
+ : globalDefaults.allowToolAssisted,
187
+ source: hasProjectOverride ? 'project' : 'global',
188
+ projectOverrides,
189
+ globalDefaults
190
+ };
191
+ }
192
+ /**
193
+ * Returns true if a tool invocation brings external/untrusted context
194
+ * (MCP servers, web search, web fetch, or live web browsing), which is gated
195
+ * when `allowToolAssisted` memory generation is turned off.
196
+ */
197
+ export function isExternalToolAssistedToolName(toolName) {
198
+ const normalized = String(toolName || '').trim().toLowerCase();
199
+ if (!normalized)
200
+ return false;
201
+ if (normalized.startsWith('mcp__') || normalized.startsWith('mcp_') || normalized.startsWith('mcp:')) {
202
+ return true;
203
+ }
204
+ return EXTERNAL_TOOL_ASSISTED_NAMES.has(normalized);
205
+ }
206
+ /**
207
+ * Atomically saves project-scoped (`.causyne/personalization.md`) or global (`~/.causyne/CAUSYNE.md`)
208
+ * personalization instructions. Refuses symlinks and enforces the 16 KiB size ceiling.
209
+ */
210
+ export function savePersonalizationInstructions(workspaceRoot, scope, rawContent, env = process.env) {
211
+ if (typeof rawContent !== 'string') {
212
+ throw new Error('Personalization instructions must be a string.');
213
+ }
214
+ if (rawContent.includes('\0')) {
215
+ throw new Error('Personalization instructions must not contain NUL bytes.');
216
+ }
217
+ const normalized = rawContent.replace(/\r\n/g, '\n');
218
+ const byteLen = Buffer.byteLength(normalized, 'utf8');
219
+ if (byteLen > MAX_PERSONALIZATION_BYTES) {
220
+ throw new Error(`Personalization instructions exceed maximum size (${MAX_PERSONALIZATION_BYTES} bytes).`);
221
+ }
222
+ const targetPath = scope === 'global'
223
+ ? resolveGlobalPersonalizationPath(env)
224
+ : resolveProjectPersonalizationPath(workspaceRoot);
225
+ const displayPath = scope === 'global' ? '~/.causyne/CAUSYNE.md' : '.causyne/personalization.md';
226
+ const dirPath = path.dirname(targetPath);
227
+ if (normalized.trim().length === 0) {
228
+ assertNotSymlinkIfPresent(dirPath, 'dir');
229
+ assertNotSymlinkIfPresent(targetPath, 'file');
230
+ try {
231
+ if (fs.existsSync(targetPath))
232
+ fs.unlinkSync(targetPath);
233
+ }
234
+ catch {
235
+ // Ignore if absent
236
+ }
237
+ return readSafeMarkdownFile(targetPath, scope, displayPath);
238
+ }
239
+ ensureSafeDirectory(dirPath, scope === 'global' ? 0o700 : 0o755);
240
+ assertNotSymlinkIfPresent(targetPath, 'file');
241
+ const payload = normalized.endsWith('\n') ? normalized : `${normalized}\n`;
242
+ atomicWriteFileSync(targetPath, payload, { mode: scope === 'global' ? 0o600 : 0o644 });
243
+ return readSafeMarkdownFile(targetPath, scope, displayPath);
244
+ }
245
+ /**
246
+ * Updates memory preferences for either `'project'` (`<workspace>/.causyne/settings.json`)
247
+ * or `'global'` (`~/.causyne/config.json`). Passing `null` on a project field clears the
248
+ * per-project override so it inherits the global default.
249
+ */
250
+ export function saveMemoryPreferences(workspaceRoot, scope, patch) {
251
+ if (scope === 'global') {
252
+ const config = loadConfig();
253
+ const current = readGlobalMemoryDefaults();
254
+ const next = {
255
+ enabled: typeof patch.enabled === 'boolean' ? patch.enabled : current.enabled,
256
+ allowToolAssisted: typeof patch.allowToolAssisted === 'boolean'
257
+ ? patch.allowToolAssisted
258
+ : current.allowToolAssisted
259
+ };
260
+ config.memory = next;
261
+ saveConfig(config);
262
+ return resolveEffectiveMemoryPolicy(workspaceRoot);
263
+ }
264
+ const settings = readProjectSettingsRaw(workspaceRoot);
265
+ const currentMem = settings.memory && typeof settings.memory === 'object' && !Array.isArray(settings.memory)
266
+ ? { ...settings.memory }
267
+ : {};
268
+ if (patch.enabled === null) {
269
+ delete currentMem.enabled;
270
+ }
271
+ else if (typeof patch.enabled === 'boolean') {
272
+ currentMem.enabled = patch.enabled;
273
+ }
274
+ if (patch.allowToolAssisted === null) {
275
+ delete currentMem.allowToolAssisted;
276
+ }
277
+ else if (typeof patch.allowToolAssisted === 'boolean') {
278
+ currentMem.allowToolAssisted = patch.allowToolAssisted;
279
+ }
280
+ if (Object.keys(currentMem).length === 0) {
281
+ delete settings.memory;
282
+ }
283
+ else {
284
+ settings.memory = currentMem;
285
+ }
286
+ writeProjectSettingsRaw(workspaceRoot, settings);
287
+ return resolveEffectiveMemoryPolicy(workspaceRoot);
288
+ }
289
+ /**
290
+ * Collects live memory counts across persistent facts (`memory.json`) and
291
+ * episodic observations/summaries (`episodic-memory.json`).
292
+ */
293
+ export function collectMemoryStats(workspaceRoot) {
294
+ const factStats = getMemoryStats(workspaceRoot);
295
+ const epStats = episodicStore.getStats(workspaceRoot);
296
+ return {
297
+ projectFacts: factStats.projectFacts,
298
+ totalFacts: factStats.totalFacts,
299
+ projectObservations: epStats.projectObservations,
300
+ totalObservations: epStats.totalObservations,
301
+ projectSummaries: epStats.projectSummaries,
302
+ totalSummaries: epStats.totalSummaries
303
+ };
304
+ }
305
+ /**
306
+ * Deletes stored Causyne memories for either the active project (`'project'`)
307
+ * or across all projects (`'all'`).
308
+ */
309
+ export function deleteCausyneMemories(workspaceRoot, scope = 'project') {
310
+ let factsRemoved = 0;
311
+ let observationsRemoved = 0;
312
+ let summariesRemoved = 0;
313
+ if (scope === 'all') {
314
+ const beforeFacts = getMemoryStats(workspaceRoot).totalFacts;
315
+ clearMemory();
316
+ factsRemoved = beforeFacts;
317
+ const epCleared = episodicStore.clearAll();
318
+ observationsRemoved = epCleared.observationsRemoved;
319
+ summariesRemoved = epCleared.summariesRemoved;
320
+ }
321
+ else {
322
+ factsRemoved = clearMemoryForWorkspace(workspaceRoot);
323
+ const epCleared = episodicStore.clearProject(workspaceRoot);
324
+ observationsRemoved = epCleared.observationsRemoved;
325
+ summariesRemoved = epCleared.summariesRemoved;
326
+ }
327
+ return {
328
+ scope,
329
+ factsRemoved,
330
+ observationsRemoved,
331
+ summariesRemoved,
332
+ memoryStats: collectMemoryStats(workspaceRoot)
333
+ };
334
+ }
335
+ /**
336
+ * Returns the full Personalization + Memory state for Web Studio GUI and CLI inspection.
337
+ */
338
+ export function readPersonalizationOverview(workspaceRoot, env = process.env) {
339
+ const resolvedWs = path.resolve(workspaceRoot);
340
+ const projectDoc = readSafeMarkdownFile(resolveProjectPersonalizationPath(resolvedWs), 'project', '.causyne/personalization.md');
341
+ const globalDoc = readSafeMarkdownFile(resolveGlobalPersonalizationPath(env), 'global', '~/.causyne/CAUSYNE.md');
342
+ const loaded = loadProjectInstructions(resolvedWs, env, { includeUnmatchedScoped: true });
343
+ const activeRules = loaded.entries.map((entry) => {
344
+ const rel = path.relative(loaded.workspaceRoot, entry.sourcePath);
345
+ const label = entry.scope === 'global'
346
+ ? `~/.causyne/${path.basename(entry.sourcePath)}`
347
+ : (rel && !rel.startsWith('..') ? rel.replace(/\\/g, '/') : entry.sourcePath);
348
+ return {
349
+ scope: entry.scope,
350
+ label,
351
+ sourcePath: entry.sourcePath,
352
+ bytes: entry.bytes,
353
+ truncated: entry.truncated,
354
+ ...(entry.globs && entry.globs.length > 0 ? { globs: entry.globs } : {})
355
+ };
356
+ });
357
+ return {
358
+ workspaceRoot: resolvedWs,
359
+ project: projectDoc,
360
+ global: globalDoc,
361
+ memory: resolveEffectiveMemoryPolicy(resolvedWs),
362
+ memoryStats: collectMemoryStats(resolvedWs),
363
+ activeRules
364
+ };
365
+ }