@causyne/agent 1.20.120 → 1.20.122

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 (276) hide show
  1. package/README.md +3 -3
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +81 -26
  4. package/src/acp/agentCatalog.ts +73 -29
  5. package/src/acp/client.js +210 -53
  6. package/src/acp/client.ts +202 -52
  7. package/src/acp/peerProfiles.js +55 -22
  8. package/src/acp/peerProfiles.ts +51 -22
  9. package/src/acp/protocol.js +37 -8
  10. package/src/acp/protocol.ts +30 -8
  11. package/src/acp/server.js +123 -25
  12. package/src/acp/server.ts +124 -24
  13. package/src/agent/errorClassifier.js +117 -0
  14. package/src/agent/errorClassifier.ts +165 -0
  15. package/src/agent/promptIntent.js +200 -0
  16. package/src/agent/promptIntent.ts +203 -0
  17. package/src/agent/toolArgValidator.js +97 -0
  18. package/src/agent/toolArgValidator.ts +112 -0
  19. package/src/agentLoop.js +33 -344
  20. package/src/agentLoop.ts +51 -352
  21. package/src/approvalGrants.js +19 -7
  22. package/src/approvalGrants.ts +20 -7
  23. package/src/approvalPolicy.js +48 -15
  24. package/src/approvalPolicy.ts +46 -15
  25. package/src/autoUpdate.js +116 -10
  26. package/src/autoUpdate.ts +149 -10
  27. package/src/browser/causyneBrowser.js +3 -2
  28. package/src/browser/causyneBrowser.ts +3 -2
  29. package/src/browser/searchProviders.js +1 -1
  30. package/src/browser/searchProviders.ts +1 -1
  31. package/src/cliMode.js +16 -2
  32. package/src/commands.js +10 -9
  33. package/src/config.js +288 -272
  34. package/src/config.ts +342 -0
  35. package/src/configVault.js +271 -0
  36. package/src/configVault.ts +273 -0
  37. package/src/continuum/compactor.js +2 -1
  38. package/src/continuum/compactor.ts +2 -1
  39. package/src/continuum/sanitizer.js +10 -3
  40. package/src/continuum/sanitizer.ts +9 -3
  41. package/src/continuum/ui/continuumPickerView.js +3 -2
  42. package/src/continuum/ui/continuumPickerView.ts +3 -2
  43. package/src/core/contextCompactor.js +70 -11
  44. package/src/core/contextCompactor.ts +83 -11
  45. package/src/cortex/vectorDb.js +26 -15
  46. package/src/cortex/vectorDb.ts +26 -16
  47. package/src/creative/liveBridge.js +7 -5
  48. package/src/creative/liveBridge.ts +7 -5
  49. package/src/creative/studioScripts.js +16 -5
  50. package/src/creative/studioScripts.ts +14 -5
  51. package/src/decisionPolicy.js +16 -4
  52. package/src/decisionPolicy.ts +14 -4
  53. package/src/documentEngine/antiSlopAuditor.js +10 -5
  54. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  55. package/src/documentEngine/documentForge.js +47 -15
  56. package/src/documentEngine/documentForge.ts +43 -14
  57. package/src/dynamicCatalogue.js +42 -73
  58. package/src/dynamicCatalogue.ts +74 -60
  59. package/src/engines/design.js +2 -1
  60. package/src/engines/design.ts +2 -1
  61. package/src/engines/film.js +4 -4
  62. package/src/engines/film.ts +2 -2
  63. package/src/engines/light.js +2 -1
  64. package/src/engines/light.ts +2 -1
  65. package/src/engines/registry.js +1 -1
  66. package/src/engines/registry.ts +1 -1
  67. package/src/engines/reverseHarness.js +4 -3
  68. package/src/engines/reverseHarness.ts +4 -3
  69. package/src/entrypoint.js +77 -4
  70. package/src/headlessCli.js +305 -0
  71. package/src/headlessCli.ts +381 -0
  72. package/src/historyPruner.js +3 -2
  73. package/src/historyPruner.ts +3 -2
  74. package/src/hooks.js +3 -0
  75. package/src/hooks.ts +3 -0
  76. package/src/implementationPlan.js +21 -11
  77. package/src/implementationPlan.ts +21 -11
  78. package/src/infra/atomicWriter.js +4 -1
  79. package/src/infra/atomicWriter.ts +4 -1
  80. package/src/launchIntent.js +1 -1
  81. package/src/launchIntent.ts +1 -1
  82. package/src/mcp/mcpClient.js +38 -11
  83. package/src/mcp/mcpClient.ts +44 -11
  84. package/src/mcp/mcpRegistry.js +2 -5
  85. package/src/mcp/mcpRegistry.ts +2 -5
  86. package/src/mcp/mcpSecurity.js +189 -0
  87. package/src/mcp/mcpSecurity.ts +190 -0
  88. package/src/memory/scopedFacts.js +1 -1
  89. package/src/memory/scopedFacts.ts +1 -1
  90. package/src/memory/symbolFolder.js +1 -1
  91. package/src/memory/symbolFolder.ts +1 -1
  92. package/src/modelRouter.js +1 -1
  93. package/src/modelRouter.ts +1 -1
  94. package/src/observer/evidence.js +10 -4
  95. package/src/observer/evidence.ts +10 -4
  96. package/src/osKeychain.js +263 -0
  97. package/src/osKeychain.ts +287 -0
  98. package/src/perception.js +3 -2
  99. package/src/perception.ts +3 -2
  100. package/src/planCache.js +2 -2
  101. package/src/planCache.ts +2 -2
  102. package/src/pluginsFactory/pluginsFactory.js +19 -11
  103. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  104. package/src/promptMentions.js +2 -2
  105. package/src/promptMentions.ts +2 -2
  106. package/src/providers/acp.js +1 -1
  107. package/src/providers/acp.ts +1 -1
  108. package/src/providers/anthropic.js +328 -385
  109. package/src/providers/anthropic.ts +386 -0
  110. package/src/providers/antigravity.js +10 -4
  111. package/src/providers/antigravity.ts +10 -4
  112. package/src/providers/base.js +221 -319
  113. package/src/providers/base.ts +340 -0
  114. package/src/providers/byokHttp.js +397 -0
  115. package/src/providers/byokHttp.ts +497 -0
  116. package/src/providers/byokStream.js +748 -0
  117. package/src/providers/byokStream.ts +863 -0
  118. package/src/providers/dashscope-byok.js +98 -81
  119. package/src/providers/dashscope-byok.ts +114 -0
  120. package/src/providers/deepseek.js +74 -64
  121. package/src/providers/deepseek.ts +99 -0
  122. package/src/providers/factory.js +35 -28
  123. package/src/providers/factory.ts +40 -0
  124. package/src/providers/gemini.js +229 -253
  125. package/src/providers/gemini.ts +261 -0
  126. package/src/providers/loopGuard.js +9 -5
  127. package/src/providers/loopGuard.ts +10 -5
  128. package/src/providers/moonshot.js +71 -64
  129. package/src/providers/moonshot.ts +93 -0
  130. package/src/providers/muse.js +82 -152
  131. package/src/providers/muse.ts +122 -0
  132. package/src/providers/ollama.js +116 -93
  133. package/src/providers/ollama.ts +135 -0
  134. package/src/providers/openai-compatible.js +114 -65
  135. package/src/providers/openai-compatible.ts +139 -0
  136. package/src/providers/openai.js +22 -15
  137. package/src/providers/openai.ts +30 -0
  138. package/src/providers/openrouter.js +194 -98
  139. package/src/providers/openrouter.ts +202 -97
  140. package/src/providers/pi.js +6 -0
  141. package/src/providers/pi.ts +6 -0
  142. package/src/providers/qwen-byok.js +97 -71
  143. package/src/providers/qwen-byok.ts +113 -0
  144. package/src/providers/toolContracts.js +40 -14
  145. package/src/providers/toolContracts.ts +35 -14
  146. package/src/providers/wireNormalizer.js +78 -11
  147. package/src/providers/wireNormalizer.ts +68 -12
  148. package/src/providers/xai.js +74 -64
  149. package/src/providers/xai.ts +97 -0
  150. package/src/reliability/assetEvidence.js +4 -2
  151. package/src/reliability/assetEvidence.ts +4 -2
  152. package/src/sandbox.js +486 -530
  153. package/src/sandbox.ts +552 -0
  154. package/src/sandboxPolicy.js +1287 -0
  155. package/src/sandboxPolicy.ts +1381 -0
  156. package/src/sessionJournal.js +55 -3
  157. package/src/sessionJournal.ts +58 -3
  158. package/src/skills/skillResourceSafety.js +19 -8
  159. package/src/skills/skillResourceSafety.ts +16 -7
  160. package/src/skillsManager.js +3 -3
  161. package/src/skillsManager.ts +3 -3
  162. package/src/smartToolsUse.js +28 -4
  163. package/src/smartToolsUse.ts +29 -7
  164. package/src/stallGuard.js +45 -22
  165. package/src/stallGuard.ts +46 -22
  166. package/src/subagentJournal.js +6 -4
  167. package/src/subagentJournal.ts +6 -4
  168. package/src/textDiff.js +6 -1
  169. package/src/textDiff.ts +6 -1
  170. package/src/timeMachine.js +7 -1
  171. package/src/timeMachine.ts +7 -1
  172. package/src/tokenTracker.js +43 -28
  173. package/src/tokenTracker.ts +44 -30
  174. package/src/toolPacks.js +3 -1
  175. package/src/toolPacks.ts +3 -1
  176. package/src/tools/archive.js +245 -35
  177. package/src/tools/archive.ts +244 -35
  178. package/src/tools/computerUse.js +7 -3
  179. package/src/tools/computerUse.ts +7 -3
  180. package/src/tools/creativeApps.js +13 -8
  181. package/src/tools/creativeApps.ts +22 -9
  182. package/src/tools/deferredMcpSearch.js +26 -14
  183. package/src/tools/deferredMcpSearch.ts +26 -14
  184. package/src/tools/desktopOpen.js +69 -10
  185. package/src/tools/desktopOpen.ts +70 -11
  186. package/src/tools/documentForge.js +167 -82
  187. package/src/tools/documentForge.ts +169 -84
  188. package/src/tools/fsEdit.js +101 -30
  189. package/src/tools/fsEdit.ts +105 -32
  190. package/src/tools/fsFind.js +8 -5
  191. package/src/tools/fsFind.ts +7 -4
  192. package/src/tools/fsRead.js +119 -13
  193. package/src/tools/fsRead.ts +124 -13
  194. package/src/tools/fsWrite.js +17 -5
  195. package/src/tools/fsWrite.ts +17 -7
  196. package/src/tools/generateMediaViaApi.js +82 -19
  197. package/src/tools/generateMediaViaApi.ts +80 -19
  198. package/src/tools/memoryRecall.js +62 -11
  199. package/src/tools/memoryRecall.ts +70 -13
  200. package/src/tools/memoryWrite.js +27 -14
  201. package/src/tools/memoryWrite.ts +30 -14
  202. package/src/tools/multiEdit.js +100 -30
  203. package/src/tools/multiEdit.ts +104 -32
  204. package/src/tools/nativeEngine.js +33 -18
  205. package/src/tools/nativeEngine.ts +31 -18
  206. package/src/tools/openSourceToolProvisioner.js +49 -14
  207. package/src/tools/openSourceToolProvisioner.ts +54 -15
  208. package/src/tools/osSandbox.js +513 -0
  209. package/src/tools/osSandbox.ts +588 -0
  210. package/src/tools/payloadSanitizer.js +40 -8
  211. package/src/tools/payloadSanitizer.ts +39 -8
  212. package/src/tools/peerAgent.js +96 -34
  213. package/src/tools/peerAgent.ts +114 -37
  214. package/src/tools/persistentShell.js +8 -3
  215. package/src/tools/pluginsFactory.js +38 -6
  216. package/src/tools/pluginsFactory.ts +42 -6
  217. package/src/tools/readNativeSkill.js +10 -8
  218. package/src/tools/readNativeSkill.ts +10 -8
  219. package/src/tools/requestDecision.js +10 -3
  220. package/src/tools/requestDecision.ts +10 -3
  221. package/src/tools/resolveAutomator.js +91 -17
  222. package/src/tools/resolveAutomator.ts +102 -17
  223. package/src/tools/reverseEngineering.js +168 -41
  224. package/src/tools/reverseEngineering.ts +161 -41
  225. package/src/tools/subprocessEnv.js +197 -0
  226. package/src/tools/subprocessEnv.ts +212 -0
  227. package/src/tools/sysRun.js +108 -35
  228. package/src/tools/sysRun.ts +119 -31
  229. package/src/tools/toolDispatch.js +24 -1
  230. package/src/tools/toolDispatch.ts +21 -1
  231. package/src/tools/toolOutputStore.js +62 -23
  232. package/src/tools/toolOutputStore.ts +56 -23
  233. package/src/tools/toolScanner.js +13 -10
  234. package/src/tools/toolScanner.ts +13 -10
  235. package/src/tools/toolSelfRepair.js +94 -28
  236. package/src/tools/toolSelfRepair.ts +96 -28
  237. package/src/tools/uiForge.js +71 -6
  238. package/src/tools/uiForge.ts +74 -6
  239. package/src/tools/viewImage.js +62 -17
  240. package/src/tools/viewImage.ts +57 -12
  241. package/src/tools/visionInspector.js +15 -3
  242. package/src/tools/visionInspector.ts +15 -3
  243. package/src/tools/walkerSafety.js +2 -0
  244. package/src/tools/walkerSafety.ts +1 -0
  245. package/src/tools/webFetch.js +105 -10
  246. package/src/tools/webFetch.ts +105 -11
  247. package/src/tui/banner.js +3 -2
  248. package/src/tui/banner.ts +3 -2
  249. package/src/tui/consoleGuard.js +12 -4
  250. package/src/tui/consoleGuard.ts +9 -4
  251. package/src/tui/messageInteraction.js +2 -3
  252. package/src/tui/messageInteraction.ts +2 -3
  253. package/src/tui/modelPicker.js +1 -0
  254. package/src/tui/modelPicker.ts +1 -0
  255. package/src/tui/overlay.js +3 -1
  256. package/src/tui/overlay.ts +3 -1
  257. package/src/tui/sessionPicker.js +3 -2
  258. package/src/tui/sessionPicker.ts +3 -2
  259. package/src/tui/sessionPickerView.js +7 -1
  260. package/src/tui/sessionPickerView.ts +6 -1
  261. package/src/tui/toolOutputNormalizer.js +2 -3
  262. package/src/tui/toolOutputNormalizer.ts +4 -3
  263. package/src/tui/viewport.js +4 -4
  264. package/src/tui/viewport.ts +5 -5
  265. package/src/tui/workspaceIdentity.js +2 -1
  266. package/src/tui/workspaceIdentity.ts +2 -1
  267. package/src/uncertainty.js +8 -3
  268. package/src/uncertainty.ts +8 -3
  269. package/src/utils/paths.js +8 -5
  270. package/src/utils/paths.ts +9 -7
  271. package/src/vfeTracker.js +9 -3
  272. package/src/vfeTracker.ts +9 -3
  273. package/src/config.d.ts +0 -2
  274. package/src/providers/base.d.ts +0 -94
  275. package/src/providers/factory.d.ts +0 -1
  276. package/src/sandbox.d.ts +0 -1
@@ -31,11 +31,18 @@ export interface CodexCompactedState {
31
31
  readonly toolsSummary: string;
32
32
  }
33
33
 
34
+ export interface PlanStepAnchor {
35
+ readonly step?: string | undefined;
36
+ readonly title?: string | undefined;
37
+ readonly status?: string | undefined;
38
+ }
39
+
34
40
  export interface CompactionOptions {
35
41
  readonly keepRecentTurns?: number;
36
42
  readonly taskId?: string;
37
43
  readonly originalPrompt?: string;
38
44
  readonly maxCharPool?: number;
45
+ readonly activePlan?: readonly PlanStepAnchor[] | undefined;
39
46
  }
40
47
 
41
48
  export interface CompactionResult {
@@ -49,13 +56,58 @@ export interface CompactionResult {
49
56
  readonly reason?: string;
50
57
  }
51
58
 
59
+ /**
60
+ * Adjusts a candidate compaction split index so compaction NEVER severs a
61
+ * `role: 'tool'` result from its preceding `role: 'assistant'` `tool_calls`
62
+ * message (which would cause HTTP 400 invalid tool-turn errors on OpenAI,
63
+ * Anthropic, and Gemini).
64
+ *
65
+ * Returns a safe `splitIndex` in `[1, messages.length - 2]`, or `-1` if no
66
+ * safe split exists.
67
+ */
68
+ export function findSafeCompactionSplitIndex(
69
+ messages: ReadonlyArray<{ role?: string; tool_calls?: unknown }>,
70
+ targetSplitIndex: number
71
+ ): number {
72
+ const maxSplit = messages.length - 2;
73
+ if (maxSplit < 1) return -1;
74
+ let split = Math.min(Math.max(1, targetSplitIndex), maxSplit);
75
+
76
+ // If the first retained message (`split + 1`) is a `tool` result, walk back
77
+ // until the owning `assistant` message with `tool_calls` is also retained.
78
+ if (messages[split + 1]?.role === 'tool') {
79
+ let back = split;
80
+ while (back >= 1 && messages[back + 1]?.role === 'tool') {
81
+ back -= 1;
82
+ }
83
+ // Also retain the owning `assistant` message if `back + 1` was still `tool`
84
+ if (back >= 1 && messages[back]?.role === 'assistant' && Array.isArray(messages[back]?.tool_calls)) {
85
+ back -= 1;
86
+ }
87
+ if (back >= 1 && messages[back + 1]?.role !== 'tool') {
88
+ return back;
89
+ }
90
+ // Otherwise walk forward past the contiguous `tool` results while keeping at least 1 recent message
91
+ let forward = split;
92
+ while (forward < maxSplit && messages[forward + 1]?.role === 'tool') {
93
+ forward += 1;
94
+ }
95
+ if (forward <= maxSplit && messages[forward + 1]?.role !== 'tool') {
96
+ return forward;
97
+ }
98
+ return -1;
99
+ }
100
+
101
+ return split;
102
+ }
103
+
52
104
  /**
53
105
  * Extracts a high-fidelity, structured state summary from dropped message history.
54
- * Mirrors the state preservation architecture of OpenAI Codex and Claude Code.
55
106
  */
56
107
  export function buildCodexStyleSummary(
57
108
  droppedMessages: readonly ToolObservation[],
58
- originalPrompt?: string
109
+ originalPrompt?: string,
110
+ extra?: { activePlan?: readonly PlanStepAnchor[] | undefined }
59
111
  ): string {
60
112
  const createdFiles = new Set<string>();
61
113
  const modifiedFiles = new Set<string>();
@@ -77,11 +129,11 @@ export function buildCodexStyleSummary(
77
129
  if (typeof rawArgs === 'string') {
78
130
  const parsed = JSON.parse(rawArgs);
79
131
  if (parsed && typeof parsed === 'object') {
80
- const target = String(parsed.path || parsed.file_path || parsed.target || '');
132
+ const target = String(parsed.path || parsed.file_path || parsed.target || parsed.destination || '');
81
133
  if (target) {
82
134
  if (['fs_write', 'write_to_file', 'writeFile'].includes(fnName)) {
83
135
  createdFiles.add(target);
84
- } else if (['fs_edit', 'replace_file_content', 'multi_replace_file_content'].includes(fnName)) {
136
+ } else if (['fs_edit', 'MultiEdit', 'multi_edit', 'fs_move', 'replace_file_content', 'multi_replace_file_content'].includes(fnName)) {
85
137
  modifiedFiles.add(target);
86
138
  } else if (['fs_read', 'view_file', 'readFile'].includes(fnName)) {
87
139
  inspectedFiles.add(target);
@@ -167,6 +219,21 @@ export function buildCodexStyleSummary(
167
219
  sections.push(`**Prior Failures Handled:** ${[...failures].slice(0, 4).join(' | ')}`);
168
220
  }
169
221
 
222
+ if (Array.isArray(extra?.activePlan) && extra.activePlan.length > 0) {
223
+ const planLines = extra.activePlan
224
+ .slice(0, 12)
225
+ .map(item => {
226
+ const label = String(item.step || item.title || '').trim();
227
+ if (!label) return '';
228
+ const status = String(item.status || 'pending').trim();
229
+ return `- [${status}] ${label}`;
230
+ })
231
+ .filter(Boolean);
232
+ if (planLines.length > 0) {
233
+ sections.push(`**Active Implementation Plan:**\n${planLines.join('\n')}`);
234
+ }
235
+ }
236
+
170
237
  sections.push(
171
238
  '**Directive for Continuation:** Completed workspace files and session artifacts on disk are preserved. '
172
239
  + 'Do not re-scan or repeat verified setup steps. Continue forward execution and complete the remaining requirements.'
@@ -215,9 +282,10 @@ export function compactSessionMessages(
215
282
  taskId: options.taskId ?? 'compaction'
216
283
  });
217
284
 
218
- // Calculate split index for physical compaction:
285
+ // Calculate turn-boundary-safe split index for physical compaction:
219
286
  // Messages from index 1 to splitIndex will be collapsed into a single summary
220
- const splitIndex = messages.length - keepRecentTurns - 1;
287
+ // without ever orphaning a `role: 'tool'` result from its `assistant` `tool_calls`.
288
+ const splitIndex = findSafeCompactionSplitIndex(messages, messages.length - keepRecentTurns - 1);
221
289
  if (splitIndex < 1) {
222
290
  return {
223
291
  compacted: false,
@@ -227,7 +295,7 @@ export function compactSessionMessages(
227
295
  initialChars,
228
296
  finalChars: measureMessages(messages),
229
297
  summaryText: '',
230
- reason: 'Split index out of range.'
298
+ reason: 'Split index out of range or would break an active tool-call turn.'
231
299
  };
232
300
  }
233
301
 
@@ -236,7 +304,9 @@ export function compactSessionMessages(
236
304
  ? messages[0].content
237
305
  : options.originalPrompt;
238
306
 
239
- const structuredSummary = buildCodexStyleSummary(dropped, rootPrompt);
307
+ const structuredSummary = buildCodexStyleSummary(dropped, rootPrompt, {
308
+ activePlan: options.activePlan
309
+ });
240
310
  const fullRecoverableSummary = buildRecoverableDroppedSummary(dropped, structuredSummary);
241
311
 
242
312
  const removed = compactInPlace(messages, splitIndex, fullRecoverableSummary);
@@ -275,7 +345,8 @@ export function autoCompactIfUnderPressure(
275
345
  const result = compactSessionMessages(loop.messages, {
276
346
  keepRecentTurns: 4,
277
347
  taskId: loop.taskId,
278
- originalPrompt: loop.currentTaskPrompt || loop.userPrompt
348
+ originalPrompt: loop.currentTaskPrompt || loop.userPrompt,
349
+ activePlan: Array.isArray(loop._implementationPlan) ? loop._implementationPlan : undefined
279
350
  });
280
351
 
281
352
  if (result.compacted) {
@@ -320,7 +391,8 @@ export async function runCompactSlashCommand(
320
391
  const result = compactSessionMessages(loop.messages, {
321
392
  keepRecentTurns: 4,
322
393
  taskId: loop.taskId || 'manual-compact',
323
- originalPrompt: loop.currentTaskPrompt || loop.userPrompt
394
+ originalPrompt: loop.currentTaskPrompt || loop.userPrompt,
395
+ activePlan: Array.isArray(loop._implementationPlan) ? loop._implementationPlan : undefined
324
396
  });
325
397
 
326
398
  if (!result.compacted) {
@@ -338,7 +410,7 @@ export async function runCompactSlashCommand(
338
410
  const finalKb = (result.finalChars / 1024).toFixed(1);
339
411
 
340
412
  const report = [
341
- '✔ Context successfully compacted (OpenAI Codex structured state model).',
413
+ '✔ Context successfully compacted (Causyne structured state model).',
342
414
  '',
343
415
  ` • Earlier messages condensed: ${result.removedCount}`,
344
416
  ` • Memory reclaimed: ${reclaimedKb} KB (~${result.reclaimedTokens.toLocaleString()} tokens)`,
@@ -75,24 +75,35 @@ export class VectorDB {
75
75
  isInitialized = false;
76
76
  isNeural = false;
77
77
  db = null;
78
+ ensureDbPromise = null;
78
79
  async ensureDb() {
79
80
  if (this.db)
80
81
  return;
81
- if (!fs.existsSync(CORTEX_DIR)) {
82
- fs.mkdirSync(CORTEX_DIR, { recursive: true, mode: 0o700 });
82
+ if (this.ensureDbPromise)
83
+ return this.ensureDbPromise;
84
+ this.ensureDbPromise = (async () => {
85
+ if (!fs.existsSync(CORTEX_DIR)) {
86
+ fs.mkdirSync(CORTEX_DIR, { recursive: true, mode: 0o700 });
87
+ }
88
+ this.db = await openCortexDatabase(CORTEX_DB_FILE);
89
+ // Create the task_memories table if it doesn't exist
90
+ // embedding_vector is stored as a JSON string array of floats
91
+ this.db.exec(`
92
+ CREATE TABLE IF NOT EXISTS task_memories (
93
+ id TEXT PRIMARY KEY,
94
+ text TEXT NOT NULL,
95
+ embedding_vector TEXT NOT NULL,
96
+ timestamp INTEGER NOT NULL
97
+ )
98
+ `);
99
+ this.migrateSchema();
100
+ })();
101
+ try {
102
+ await this.ensureDbPromise;
103
+ }
104
+ finally {
105
+ this.ensureDbPromise = null;
83
106
  }
84
- this.db = await openCortexDatabase(CORTEX_DB_FILE);
85
- // Create the task_memories table if it doesn't exist
86
- // embedding_vector is stored as a JSON string array of floats
87
- this.db.exec(`
88
- CREATE TABLE IF NOT EXISTS task_memories (
89
- id TEXT PRIMARY KEY,
90
- text TEXT NOT NULL,
91
- embedding_vector TEXT NOT NULL,
92
- timestamp INTEGER NOT NULL
93
- )
94
- `);
95
- this.migrateSchema();
96
107
  }
97
108
  /**
98
109
  * Bring an existing store up to the current schema, additively.
@@ -224,7 +235,7 @@ export class VectorDB {
224
235
  const ageMs = Math.max(0, now - (memory.timestamp || 0));
225
236
  // OBLIVION: S = BASE_HALF_LIFE * (1 + hits * REINFORCEMENT_ALPHA) * tierMultiplier
226
237
  // R = e^(-t/S) — adaptive retention that rewards reinforced memories with slower decay
227
- const tierMult = TIER_MULTIPLIERS[memory.kind] ?? 1.0;
238
+ const tierMult = Object.hasOwn(TIER_MULTIPLIERS, memory.kind) ? TIER_MULTIPLIERS[memory.kind] : 1.0;
228
239
  const stability = Math.max(1, RECENCY_HALF_LIFE_MS * (1 + (memory.hits || 0) * REINFORCEMENT_ALPHA) * tierMult);
229
240
  const retention = Math.exp(-ageMs / stability);
230
241
  scored.push({
@@ -123,28 +123,38 @@ export class VectorDB {
123
123
  public isInitialized: boolean = false;
124
124
  public isNeural: boolean = false;
125
125
  public db: CortexDatabase | null = null;
126
+ private ensureDbPromise: Promise<void> | null = null;
126
127
 
127
128
  async ensureDb(): Promise<void> {
128
129
  if (this.db) return;
130
+ if (this.ensureDbPromise) return this.ensureDbPromise;
129
131
 
130
- if (!fs.existsSync(CORTEX_DIR)) {
131
- fs.mkdirSync(CORTEX_DIR, { recursive: true, mode: 0o700 });
132
- }
132
+ this.ensureDbPromise = (async () => {
133
+ if (!fs.existsSync(CORTEX_DIR)) {
134
+ fs.mkdirSync(CORTEX_DIR, { recursive: true, mode: 0o700 });
135
+ }
136
+
137
+ this.db = await openCortexDatabase(CORTEX_DB_FILE);
133
138
 
134
- this.db = await openCortexDatabase(CORTEX_DB_FILE);
139
+ // Create the task_memories table if it doesn't exist
140
+ // embedding_vector is stored as a JSON string array of floats
141
+ this.db.exec(`
142
+ CREATE TABLE IF NOT EXISTS task_memories (
143
+ id TEXT PRIMARY KEY,
144
+ text TEXT NOT NULL,
145
+ embedding_vector TEXT NOT NULL,
146
+ timestamp INTEGER NOT NULL
147
+ )
148
+ `);
135
149
 
136
- // Create the task_memories table if it doesn't exist
137
- // embedding_vector is stored as a JSON string array of floats
138
- this.db.exec(`
139
- CREATE TABLE IF NOT EXISTS task_memories (
140
- id TEXT PRIMARY KEY,
141
- text TEXT NOT NULL,
142
- embedding_vector TEXT NOT NULL,
143
- timestamp INTEGER NOT NULL
144
- )
145
- `);
150
+ this.migrateSchema();
151
+ })();
146
152
 
147
- this.migrateSchema();
153
+ try {
154
+ await this.ensureDbPromise;
155
+ } finally {
156
+ this.ensureDbPromise = null;
157
+ }
148
158
  }
149
159
 
150
160
  /**
@@ -299,7 +309,7 @@ export class VectorDB {
299
309
  const ageMs = Math.max(0, now - (memory.timestamp || 0));
300
310
  // OBLIVION: S = BASE_HALF_LIFE * (1 + hits * REINFORCEMENT_ALPHA) * tierMultiplier
301
311
  // R = e^(-t/S) — adaptive retention that rewards reinforced memories with slower decay
302
- const tierMult = TIER_MULTIPLIERS[memory.kind] ?? 1.0;
312
+ const tierMult = Object.hasOwn(TIER_MULTIPLIERS, memory.kind) ? TIER_MULTIPLIERS[memory.kind]! : 1.0;
303
313
  const stability = Math.max(1, RECENCY_HALF_LIFE_MS * (1 + (memory.hits || 0) * REINFORCEMENT_ALPHA) * tierMult);
304
314
  const retention = Math.exp(-ageMs / stability);
305
315
  scored.push({
@@ -124,7 +124,7 @@ export function validateAdobeLiveJob(value) {
124
124
  }
125
125
  const raw = value;
126
126
  const hostInput = String(raw.host ?? 'photoshop').trim().toLowerCase();
127
- const canonicalHost = ADOBE_HOST_ALIASES[hostInput];
127
+ const canonicalHost = Object.hasOwn(ADOBE_HOST_ALIASES, hostInput) ? ADOBE_HOST_ALIASES[hostInput] : undefined;
128
128
  if (!canonicalHost) {
129
129
  throw new Error(`Unsupported Adobe host "${String(raw.host)}". Supported hosts: photoshop, premiere, after-effects, illustrator, indesign, media-encoder.`);
130
130
  }
@@ -669,7 +669,7 @@ export function validateGameEngineJob(value) {
669
669
  }
670
670
  const raw = value;
671
671
  const engineInput = String(raw.engine ?? raw.host ?? 'unreal').trim().toLowerCase();
672
- const canonicalEngine = GAME_ENGINE_ALIASES[engineInput];
672
+ const canonicalEngine = Object.hasOwn(GAME_ENGINE_ALIASES, engineInput) ? GAME_ENGINE_ALIASES[engineInput] : undefined;
673
673
  if (!canonicalEngine) {
674
674
  throw new Error(`Unsupported game engine "${String(raw.engine ?? raw.host)}". Supported engines: unreal, unity, godot.`);
675
675
  }
@@ -1013,8 +1013,10 @@ export async function runGameEngineBridge(value, workspace = process.cwd(), sign
1013
1013
  }
1014
1014
  if (job.canonicalEngine === 'unity') {
1015
1015
  const destRel = (job.destinationFolder || 'Assets/CausyneAssets').replace(/^\/+|\/+$/g, '');
1016
- const normalizedDestRel = destRel.startsWith('Assets') ? destRel : path.join('Assets', destRel);
1017
- const destAbs = path.join(projectRoot, normalizedDestRel);
1016
+ const normalizedDestRel = (destRel === 'Assets' || destRel.startsWith('Assets/') || destRel.startsWith('Assets\\'))
1017
+ ? destRel
1018
+ : path.join('Assets', destRel);
1019
+ const destAbs = await resolveWorkspacePath(normalizedDestRel, projectRoot, false);
1018
1020
  const editorDir = path.join(projectRoot, 'Assets', 'Editor');
1019
1021
  await fs.mkdir(destAbs, { recursive: true });
1020
1022
  await fs.mkdir(editorDir, { recursive: true });
@@ -1066,7 +1068,7 @@ export async function runGameEngineBridge(value, workspace = process.cwd(), sign
1066
1068
  }
1067
1069
  // Godot 4 Engine Bridge
1068
1070
  const destRel = (job.destinationFolder || 'assets/causyne').replace(/^res:\/\/|^\/+|\/+$/g, '');
1069
- const destAbs = path.join(projectRoot, destRel);
1071
+ const destAbs = await resolveWorkspacePath(destRel || 'assets/causyne', projectRoot, false);
1070
1072
  await fs.mkdir(destAbs, { recursive: true });
1071
1073
  const resPaths = [];
1072
1074
  for (const srcFile of resolvedAssets) {
@@ -218,7 +218,7 @@ export function validateAdobeLiveJob(value: unknown): AdobeLiveJob {
218
218
  }
219
219
  const raw = value as Record<string, unknown>;
220
220
  const hostInput = String(raw.host ?? 'photoshop').trim().toLowerCase();
221
- const canonicalHost = ADOBE_HOST_ALIASES[hostInput];
221
+ const canonicalHost = Object.hasOwn(ADOBE_HOST_ALIASES, hostInput) ? ADOBE_HOST_ALIASES[hostInput] : undefined;
222
222
  if (!canonicalHost) {
223
223
  throw new Error(
224
224
  `Unsupported Adobe host "${String(raw.host)}". Supported hosts: photoshop, premiere, after-effects, illustrator, indesign, media-encoder.`
@@ -903,7 +903,7 @@ export function validateGameEngineJob(value: unknown): GameEngineJob {
903
903
  }
904
904
  const raw = value as Record<string, unknown>;
905
905
  const engineInput = String(raw.engine ?? raw.host ?? 'unreal').trim().toLowerCase();
906
- const canonicalEngine = GAME_ENGINE_ALIASES[engineInput];
906
+ const canonicalEngine = Object.hasOwn(GAME_ENGINE_ALIASES, engineInput) ? GAME_ENGINE_ALIASES[engineInput] : undefined;
907
907
  if (!canonicalEngine) {
908
908
  throw new Error(
909
909
  `Unsupported game engine "${String(raw.engine ?? raw.host)}". Supported engines: unreal, unity, godot.`
@@ -1273,8 +1273,10 @@ export async function runGameEngineBridge(
1273
1273
 
1274
1274
  if (job.canonicalEngine === 'unity') {
1275
1275
  const destRel = (job.destinationFolder || 'Assets/CausyneAssets').replace(/^\/+|\/+$/g, '');
1276
- const normalizedDestRel = destRel.startsWith('Assets') ? destRel : path.join('Assets', destRel);
1277
- const destAbs = path.join(projectRoot, normalizedDestRel);
1276
+ const normalizedDestRel = (destRel === 'Assets' || destRel.startsWith('Assets/') || destRel.startsWith('Assets\\'))
1277
+ ? destRel
1278
+ : path.join('Assets', destRel);
1279
+ const destAbs = await resolveWorkspacePath(normalizedDestRel, projectRoot, false);
1278
1280
  const editorDir = path.join(projectRoot, 'Assets', 'Editor');
1279
1281
  await fs.mkdir(destAbs, { recursive: true });
1280
1282
  await fs.mkdir(editorDir, { recursive: true });
@@ -1335,7 +1337,7 @@ export async function runGameEngineBridge(
1335
1337
 
1336
1338
  // Godot 4 Engine Bridge
1337
1339
  const destRel = (job.destinationFolder || 'assets/causyne').replace(/^res:\/\/|^\/+|\/+$/g, '');
1338
- const destAbs = path.join(projectRoot, destRel);
1340
+ const destAbs = await resolveWorkspacePath(destRel || 'assets/causyne', projectRoot, false);
1339
1341
  await fs.mkdir(destAbs, { recursive: true });
1340
1342
 
1341
1343
  const resPaths: string[] = [];
@@ -301,19 +301,30 @@ export async function findHostApplication(host) {
301
301
  const programFiles = process.env.ProgramFiles || 'C:\\Program Files';
302
302
  const folderPattern = host === 'photoshop' ? /Photoshop/i : host === 'premiere' ? /Premiere/i : /After Effects/i;
303
303
  const exePattern = host === 'photoshop' ? /Photoshop\.exe$/i : host === 'premiere' ? /Premiere\.exe$/i : /AfterFX\.exe$/i;
304
- try {
305
- const topDirs = await fs.readdir(programFiles);
304
+ const searchRoots = [path.join(programFiles, 'Adobe'), programFiles];
305
+ for (const rootDir of searchRoots) {
306
+ let topDirs;
307
+ try {
308
+ topDirs = await fs.readdir(rootDir);
309
+ }
310
+ catch {
311
+ continue;
312
+ }
306
313
  for (const dir of topDirs) {
307
- const fullDir = path.join(programFiles, dir);
308
- if (folderPattern.test(dir)) {
314
+ if (!folderPattern.test(dir))
315
+ continue;
316
+ const fullDir = path.join(rootDir, dir);
317
+ try {
309
318
  const files = await fs.readdir(fullDir);
310
319
  const foundExe = files.find(f => exePattern.test(f));
311
320
  if (foundExe)
312
321
  return path.join(fullDir, foundExe);
313
322
  }
323
+ catch {
324
+ // Ignore non-directory entries or unreadable subdirs
325
+ }
314
326
  }
315
327
  }
316
- catch { /* Ignore filesystem search failures */ }
317
328
  }
318
329
  return null;
319
330
  }
@@ -304,17 +304,26 @@ export async function findHostApplication(host: CanonicalHost): Promise<string |
304
304
  const programFiles = process.env.ProgramFiles || 'C:\\Program Files';
305
305
  const folderPattern = host === 'photoshop' ? /Photoshop/i : host === 'premiere' ? /Premiere/i : /After Effects/i;
306
306
  const exePattern = host === 'photoshop' ? /Photoshop\.exe$/i : host === 'premiere' ? /Premiere\.exe$/i : /AfterFX\.exe$/i;
307
- try {
308
- const topDirs = await fs.readdir(programFiles);
307
+ const searchRoots = [path.join(programFiles, 'Adobe'), programFiles];
308
+ for (const rootDir of searchRoots) {
309
+ let topDirs: string[];
310
+ try {
311
+ topDirs = await fs.readdir(rootDir);
312
+ } catch {
313
+ continue;
314
+ }
309
315
  for (const dir of topDirs) {
310
- const fullDir = path.join(programFiles, dir);
311
- if (folderPattern.test(dir)) {
316
+ if (!folderPattern.test(dir)) continue;
317
+ const fullDir = path.join(rootDir, dir);
318
+ try {
312
319
  const files = await fs.readdir(fullDir);
313
320
  const foundExe = files.find(f => exePattern.test(f));
314
321
  if (foundExe) return path.join(fullDir, foundExe);
322
+ } catch {
323
+ // Ignore non-directory entries or unreadable subdirs
315
324
  }
316
325
  }
317
- } catch { /* Ignore filesystem search failures */ }
326
+ }
318
327
  }
319
328
 
320
329
  return null;
@@ -49,7 +49,7 @@ function splitCommandSegments(command) {
49
49
  continue;
50
50
  }
51
51
  if (!inSingle && !inDouble) {
52
- if (ch === ';') {
52
+ if (ch === ';' || ch === '\n' || ch === '\r') {
53
53
  if (current.trim())
54
54
  segments.push(current.trim());
55
55
  current = '';
@@ -62,13 +62,25 @@ function splitCommandSegments(command) {
62
62
  i++;
63
63
  continue;
64
64
  }
65
- if (ch === '|' && command[i + 1] === '|') {
65
+ if (ch === '&' && command[i - 1] !== '>' && command[i + 1] !== '>') {
66
+ if (current.trim())
67
+ segments.push(current.trim());
68
+ current = '';
69
+ continue;
70
+ }
71
+ if (ch === '|' && (command[i + 1] === '|' || command[i + 1] === '&')) {
66
72
  if (current.trim())
67
73
  segments.push(current.trim());
68
74
  current = '';
69
75
  i++;
70
76
  continue;
71
77
  }
78
+ if (ch === '|') {
79
+ if (current.trim())
80
+ segments.push(current.trim());
81
+ current = '';
82
+ continue;
83
+ }
72
84
  }
73
85
  current += ch;
74
86
  }
@@ -77,7 +89,7 @@ function splitCommandSegments(command) {
77
89
  return segments;
78
90
  }
79
91
  const READ_ONLY_CMD_PATTERNS = [
80
- String.raw `^\s*(?:pwd|ls|find|rg|grep|cat|sed|awk|head|tail|wc|diff|file|stat|which|whereis|type|du|df|pdfinfo|pdftotext|identify|mediainfo|ffprobe|otool|readelf|nm|ps|lsof|top|uptime|whoami|id|uname|env|printenv|echo|printf|pytest)\b`,
92
+ String.raw `(?:pwd|ls|find|rg|grep|cat|sed|awk|head|tail|wc|diff|file|stat|which|whereis|type|du|df|pdfinfo|pdftotext|identify|mediainfo|ffprobe|otool|readelf|nm|ps|lsof|top|uptime|whoami|id|uname|env|printenv|echo|printf|pytest)\b`,
81
93
  String.raw `(?:\.\/)?gradlew?\s+(?:test\S*|check\S*|lint\S*)\b`,
82
94
  String.raw `mvn\s+(?:test\S*|verify\S*)\b`,
83
95
  String.raw `git\s+(?:status|diff|log|show|branch|tag|remote|rev-parse|describe)\b`,
@@ -93,7 +105,7 @@ const READ_ONLY_CMD_PATTERNS = [
93
105
  String.raw `go\s+test\b`,
94
106
  String.raw `curl\s+(?:-I|-sI|-s\b|--head)\b`
95
107
  ];
96
- const READ_ONLY_CMD_REGEX = new RegExp(READ_ONLY_CMD_PATTERNS.join('|'), 'i');
108
+ const READ_ONLY_CMD_REGEX = new RegExp(`^\\s*(?:${READ_ONLY_CMD_PATTERNS.join('|')})`, 'i');
97
109
  export function isReadOnlyShellCommand(command) {
98
110
  const trimmed = command.trim();
99
111
  if (!trimmed)
@@ -85,7 +85,7 @@ function splitCommandSegments(command: string): string[] {
85
85
  continue;
86
86
  }
87
87
  if (!inSingle && !inDouble) {
88
- if (ch === ';') {
88
+ if (ch === ';' || ch === '\n' || ch === '\r') {
89
89
  if (current.trim()) segments.push(current.trim());
90
90
  current = '';
91
91
  continue;
@@ -96,12 +96,22 @@ function splitCommandSegments(command: string): string[] {
96
96
  i++;
97
97
  continue;
98
98
  }
99
- if (ch === '|' && command[i + 1] === '|') {
99
+ if (ch === '&' && command[i - 1] !== '>' && command[i + 1] !== '>') {
100
+ if (current.trim()) segments.push(current.trim());
101
+ current = '';
102
+ continue;
103
+ }
104
+ if (ch === '|' && (command[i + 1] === '|' || command[i + 1] === '&')) {
100
105
  if (current.trim()) segments.push(current.trim());
101
106
  current = '';
102
107
  i++;
103
108
  continue;
104
109
  }
110
+ if (ch === '|') {
111
+ if (current.trim()) segments.push(current.trim());
112
+ current = '';
113
+ continue;
114
+ }
105
115
  }
106
116
  current += ch;
107
117
  }
@@ -110,7 +120,7 @@ function splitCommandSegments(command: string): string[] {
110
120
  }
111
121
 
112
122
  const READ_ONLY_CMD_PATTERNS = [
113
- String.raw`^\s*(?:pwd|ls|find|rg|grep|cat|sed|awk|head|tail|wc|diff|file|stat|which|whereis|type|du|df|pdfinfo|pdftotext|identify|mediainfo|ffprobe|otool|readelf|nm|ps|lsof|top|uptime|whoami|id|uname|env|printenv|echo|printf|pytest)\b`,
123
+ String.raw`(?:pwd|ls|find|rg|grep|cat|sed|awk|head|tail|wc|diff|file|stat|which|whereis|type|du|df|pdfinfo|pdftotext|identify|mediainfo|ffprobe|otool|readelf|nm|ps|lsof|top|uptime|whoami|id|uname|env|printenv|echo|printf|pytest)\b`,
114
124
  String.raw`(?:\.\/)?gradlew?\s+(?:test\S*|check\S*|lint\S*)\b`,
115
125
  String.raw`mvn\s+(?:test\S*|verify\S*)\b`,
116
126
  String.raw`git\s+(?:status|diff|log|show|branch|tag|remote|rev-parse|describe)\b`,
@@ -126,7 +136,7 @@ const READ_ONLY_CMD_PATTERNS = [
126
136
  String.raw`go\s+test\b`,
127
137
  String.raw`curl\s+(?:-I|-sI|-s\b|--head)\b`
128
138
  ];
129
- const READ_ONLY_CMD_REGEX = new RegExp(READ_ONLY_CMD_PATTERNS.join('|'), 'i');
139
+ const READ_ONLY_CMD_REGEX = new RegExp(`^\\s*(?:${READ_ONLY_CMD_PATTERNS.join('|')})`, 'i');
130
140
 
131
141
  export function isReadOnlyShellCommand(command: string): boolean {
132
142
  const trimmed = command.trim();
@@ -106,11 +106,16 @@ export function auditBudgetArithmetic(spec) {
106
106
  let taxCalculated;
107
107
  let differenceFromTarget;
108
108
  if (spec.grossUpTaxRate !== undefined) {
109
- const divisor = 1 - spec.grossUpTaxRate;
110
- grossCalculated = Math.round(grandTotal / divisor);
111
- taxCalculated = grossCalculated - grandTotal;
112
- if (spec.targetGross !== undefined) {
113
- differenceFromTarget = grossCalculated - spec.targetGross;
109
+ if (!Number.isFinite(spec.grossUpTaxRate) || spec.grossUpTaxRate < 0 || spec.grossUpTaxRate >= 1) {
110
+ categoryErrors.push(`Invalid grossUpTaxRate "${spec.grossUpTaxRate}": must be a finite fraction in [0, 1)`);
111
+ }
112
+ else {
113
+ const divisor = 1 - spec.grossUpTaxRate;
114
+ grossCalculated = Math.round(grandTotal / divisor);
115
+ taxCalculated = grossCalculated - grandTotal;
116
+ if (spec.targetGross !== undefined) {
117
+ differenceFromTarget = grossCalculated - spec.targetGross;
118
+ }
114
119
  }
115
120
  }
116
121
  const valid = itemErrors.length === 0 && categoryErrors.length === 0 && (differenceFromTarget === undefined || differenceFromTarget === 0);
@@ -166,12 +166,18 @@ export function auditBudgetArithmetic(spec: ArithmeticBudgetSpec): {
166
166
  let differenceFromTarget: number | undefined;
167
167
 
168
168
  if (spec.grossUpTaxRate !== undefined) {
169
- const divisor = 1 - spec.grossUpTaxRate;
170
- grossCalculated = Math.round(grandTotal / divisor);
171
- taxCalculated = grossCalculated - grandTotal;
169
+ if (!Number.isFinite(spec.grossUpTaxRate) || spec.grossUpTaxRate < 0 || spec.grossUpTaxRate >= 1) {
170
+ categoryErrors.push(
171
+ `Invalid grossUpTaxRate "${spec.grossUpTaxRate}": must be a finite fraction in [0, 1)`
172
+ );
173
+ } else {
174
+ const divisor = 1 - spec.grossUpTaxRate;
175
+ grossCalculated = Math.round(grandTotal / divisor);
176
+ taxCalculated = grossCalculated - grandTotal;
172
177
 
173
- if (spec.targetGross !== undefined) {
174
- differenceFromTarget = grossCalculated - spec.targetGross;
178
+ if (spec.targetGross !== undefined) {
179
+ differenceFromTarget = grossCalculated - spec.targetGross;
180
+ }
175
181
  }
176
182
  }
177
183