@causyne/agent 1.20.112 → 1.20.117

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 (169) hide show
  1. package/docs/ARCHITECTURE.md +29 -0
  2. package/package.json +1 -1
  3. package/src/agentLoop.js +153 -68
  4. package/src/agentLoop.ts +152 -71
  5. package/src/browser/browserRuntime.js +13 -8
  6. package/src/browser/browserRuntime.ts +16 -8
  7. package/src/browser/causyneBrowser.js +37 -9
  8. package/src/browser/causyneBrowser.ts +37 -9
  9. package/src/browser/searchProviders.js +18 -7
  10. package/src/browser/searchProviders.ts +17 -5
  11. package/src/browser/snapshotWindow.js +1 -1
  12. package/src/browser/snapshotWindow.ts +1 -1
  13. package/src/browser/urlPolicy.js +21 -10
  14. package/src/browser/urlPolicy.ts +19 -10
  15. package/src/browser/workspacePreview.js +13 -1
  16. package/src/browser/workspacePreview.ts +11 -1
  17. package/src/cliMode.js +5 -1
  18. package/src/computerUse/visionGrounding.js +31 -27
  19. package/src/computerUse/visionGrounding.ts +27 -27
  20. package/src/continuum/ui/continuumPicker.js +14 -6
  21. package/src/continuum/ui/continuumPicker.ts +13 -6
  22. package/src/continuum/ui/continuumPickerView.js +24 -15
  23. package/src/continuum/ui/continuumPickerView.ts +24 -16
  24. package/src/memory/scopedFacts.js +171 -0
  25. package/src/memory/scopedFacts.ts +214 -0
  26. package/src/memory.d.ts +13 -1
  27. package/src/memory.js +9 -12
  28. package/src/observer/advisory.js +32 -22
  29. package/src/observer/advisory.ts +30 -18
  30. package/src/observer/coldObserver.js +21 -33
  31. package/src/observer/coldObserver.ts +20 -33
  32. package/src/observer/evidence.js +20 -13
  33. package/src/observer/evidence.ts +21 -13
  34. package/src/observer.js +47 -12
  35. package/src/observer.ts +50 -18
  36. package/src/perception.js +124 -3
  37. package/src/perception.ts +128 -4
  38. package/src/planCache.js +17 -3
  39. package/src/planCache.ts +17 -3
  40. package/src/pluginsFactory/discovery.js +28 -16
  41. package/src/pluginsFactory/discovery.ts +29 -16
  42. package/src/pluginsFactory/pluginsFactory.js +213 -38
  43. package/src/pluginsFactory/pluginsFactory.ts +218 -39
  44. package/src/pluginsFactory/strategy.js +26 -16
  45. package/src/pluginsFactory/strategy.ts +34 -19
  46. package/src/pluginsFactory/templates.js +183 -62
  47. package/src/pluginsFactory/templates.ts +174 -54
  48. package/src/smartToolsUse.js +4 -5
  49. package/src/smartToolsUse.ts +4 -6
  50. package/src/taskShape.js +49 -7
  51. package/src/taskShape.ts +55 -7
  52. package/src/timeMachine.js +43 -22
  53. package/src/timeMachine.ts +44 -22
  54. package/src/tool-scripts/desktop_act.applescript +1 -0
  55. package/src/toolPacks.js +27 -5
  56. package/src/toolPacks.ts +32 -5
  57. package/src/tools/computerUse.js +23 -10
  58. package/src/tools/computerUse.ts +19 -8
  59. package/src/tools/desktopAct.js +12 -1
  60. package/src/tools/memoryWrite.js +8 -10
  61. package/src/tools/memoryWrite.ts +13 -11
  62. package/src/tools/pluginsFactory.js +108 -5
  63. package/src/tools/pluginsFactory.ts +115 -5
  64. package/src/tui/CausyneRotor.js +24 -10
  65. package/src/tui/CausyneRotor.ts +25 -10
  66. package/src/tui/activityLayout.js +9 -5
  67. package/src/tui/activityLayout.ts +9 -5
  68. package/src/tui/ask.js +34 -14
  69. package/src/tui/banner.js +55 -18
  70. package/src/tui/banner.ts +52 -17
  71. package/src/tui/block.js +47 -20
  72. package/src/tui/block.ts +54 -27
  73. package/src/tui/chatRenderer.js +139 -84
  74. package/src/tui/chatboxClipboard.js +12 -5
  75. package/src/tui/chatboxClipboard.ts +10 -4
  76. package/src/tui/clipboardImage.js +52 -42
  77. package/src/tui/clipboardImage.ts +50 -39
  78. package/src/tui/clipboardSync.js +12 -1
  79. package/src/tui/clipboardSync.ts +9 -1
  80. package/src/tui/codeProgress.js +60 -28
  81. package/src/tui/codeProgress.ts +60 -27
  82. package/src/tui/codeStreamRenderer.js +94 -23
  83. package/src/tui/codeStreamRenderer.ts +92 -23
  84. package/src/tui/commandPresentation.js +9 -2
  85. package/src/tui/commandPresentation.ts +9 -2
  86. package/src/tui/completion.js +45 -23
  87. package/src/tui/composerControls.js +21 -10
  88. package/src/tui/composerControls.ts +18 -10
  89. package/src/tui/composerGeometry.js +6 -4
  90. package/src/tui/composerGeometry.ts +6 -4
  91. package/src/tui/consoleGuard.js +29 -7
  92. package/src/tui/consoleGuard.ts +28 -7
  93. package/src/tui/dialogs.js +134 -71
  94. package/src/tui/diff.js +8 -4
  95. package/src/tui/history.js +6 -5
  96. package/src/tui/home.js +25 -13
  97. package/src/tui/homeView.js +37 -18
  98. package/src/tui/homeView.ts +38 -18
  99. package/src/tui/inlineSlash.js +6 -5
  100. package/src/tui/inlineSlash.ts +6 -5
  101. package/src/tui/keys.js +36 -18
  102. package/src/tui/layout.js +27 -9
  103. package/src/tui/layout.ts +26 -9
  104. package/src/tui/lineEditor.js +49 -23
  105. package/src/tui/markdownMath.js +64 -14
  106. package/src/tui/markdownMath.ts +69 -13
  107. package/src/tui/messageActionPlacement.js +28 -13
  108. package/src/tui/messageActionPlacement.ts +28 -13
  109. package/src/tui/messageInteraction.js +111 -46
  110. package/src/tui/messageInteraction.ts +115 -47
  111. package/src/tui/modelPicker.js +44 -15
  112. package/src/tui/modelPicker.ts +48 -15
  113. package/src/tui/observerPicker.js +56 -13
  114. package/src/tui/observerPicker.ts +73 -30
  115. package/src/tui/overlay.js +79 -35
  116. package/src/tui/overlay.ts +81 -34
  117. package/src/tui/prompt.js +186 -94
  118. package/src/tui/runningLight.js +1 -1
  119. package/src/tui/runningLight.ts +1 -1
  120. package/src/tui/scrollInteraction.js +64 -36
  121. package/src/tui/scrollInteraction.ts +70 -37
  122. package/src/tui/selectList.js +60 -32
  123. package/src/tui/sessionLayout.js +11 -3
  124. package/src/tui/sessionLayout.ts +10 -3
  125. package/src/tui/sessionPicker.js +74 -46
  126. package/src/tui/sessionPicker.ts +73 -48
  127. package/src/tui/sessionPickerView.js +32 -19
  128. package/src/tui/sessionPickerView.ts +31 -18
  129. package/src/tui/sessionSidebar.js +87 -57
  130. package/src/tui/sessionSidebar.ts +90 -54
  131. package/src/tui/setup.js +28 -3
  132. package/src/tui/setup.ts +27 -3
  133. package/src/tui/skillAuthoring.js +11 -5
  134. package/src/tui/skillAuthoring.ts +11 -5
  135. package/src/tui/smartLinkClick.js +75 -23
  136. package/src/tui/smartLinkClick.ts +86 -26
  137. package/src/tui/stage.js +47 -16
  138. package/src/tui/stage.ts +53 -18
  139. package/src/tui/stageSurface.js +232 -51
  140. package/src/tui/statusLine.js +85 -53
  141. package/src/tui/statusLine.ts +82 -46
  142. package/src/tui/terminalInputFramer.js +5 -2
  143. package/src/tui/text.js +117 -46
  144. package/src/tui/text.ts +113 -43
  145. package/src/tui/textLayout.js +6 -4
  146. package/src/tui/textLayout.ts +11 -5
  147. package/src/tui/theme.js +17 -8
  148. package/src/tui/thinkingBox.js +95 -95
  149. package/src/tui/thinkingBox.ts +105 -80
  150. package/src/tui/toolActivityPolicy.js +8 -1
  151. package/src/tui/toolActivityPolicy.ts +7 -1
  152. package/src/tui/toolDisplay.js +15 -6
  153. package/src/tui/toolDisplay.ts +16 -6
  154. package/src/tui/toolOutputNormalizer.js +16 -3
  155. package/src/tui/toolOutputNormalizer.ts +13 -3
  156. package/src/tui/transcript.js +15 -9
  157. package/src/tui/turnRail.js +176 -80
  158. package/src/tui/turnRail.ts +173 -71
  159. package/src/tui/usageCard.js +136 -80
  160. package/src/tui/usageCard.ts +145 -103
  161. package/src/tui/viewport.js +48 -23
  162. package/src/tui/viewport.ts +48 -27
  163. package/src/tui/viewportAnchor.js +2 -2
  164. package/src/tui/viewportAnchor.ts +2 -2
  165. package/src/tui/workspaceFileIndex.js +8 -6
  166. package/src/tui/workspaceFileIndex.ts +8 -6
  167. package/src/tui/workspaceSwitch.js +13 -10
  168. package/src/tui/workspaceSwitch.ts +11 -7
  169. package/src/types/contracts.ts +3 -0
@@ -0,0 +1,171 @@
1
+ import path from 'node:path';
2
+ const DEFAULT_MAX_FACTS = 100;
3
+ const DEFAULT_CONTEXT_MAX_FACTS = 12;
4
+ const DEFAULT_CONTEXT_MAX_CHARS = 1800;
5
+ const TEST_JUNK_PATTERN = /^test fact\b/i;
6
+ const HISTORICAL_DELIVERABLE_PATTERN = /^(?:(?:Re)?Built|Upgraded|Deployed|Implemented)\b/i;
7
+ const WINDOWS_ABS_PATH_PATTERN = /^[A-Za-z]:\\/;
8
+ function normalizeWorkspace(workspace) {
9
+ if (typeof workspace !== 'string')
10
+ return undefined;
11
+ const trimmed = workspace.trim();
12
+ if (!trimmed)
13
+ return undefined;
14
+ return path.resolve(trimmed);
15
+ }
16
+ function isPathWithinOrSame(candidatePath, rootPath) {
17
+ const rel = path.relative(path.resolve(rootPath), path.resolve(candidatePath));
18
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
19
+ }
20
+ function extractEmbeddedAbsolutePaths(text) {
21
+ const found = [];
22
+ const posixRoots = ['/Users/', '/home/', '/private/', '/var/', '/opt/', '/srv/', '/workspace/', '/repos/'];
23
+ const tokens = text.split(/[\s()`'",;<>\[\]]+/);
24
+ for (const raw of tokens) {
25
+ if (!raw)
26
+ continue;
27
+ if (posixRoots.some(prefix => raw.startsWith(prefix)) || WINDOWS_ABS_PATH_PATTERN.test(raw)) {
28
+ found.push(raw);
29
+ }
30
+ }
31
+ return found;
32
+ }
33
+ export function normalizeMemoryData(raw) {
34
+ const obj = raw && typeof raw === 'object' ? raw : {};
35
+ const rawFacts = Array.isArray(obj.facts) ? obj.facts : [];
36
+ const facts = [];
37
+ const seenFacts = new Set();
38
+ for (const item of rawFacts) {
39
+ if (typeof item !== 'string')
40
+ continue;
41
+ const trimmed = item.trim();
42
+ if (!trimmed || seenFacts.has(trimmed))
43
+ continue;
44
+ seenFacts.add(trimmed);
45
+ facts.push(trimmed);
46
+ }
47
+ const rawEntries = Array.isArray(obj.entries) ? obj.entries : [];
48
+ const entries = [];
49
+ const seenEntries = new Set();
50
+ for (const item of rawEntries) {
51
+ if (!item || typeof item !== 'object')
52
+ continue;
53
+ const rec = item;
54
+ const text = typeof rec.text === 'string' ? rec.text.trim() : '';
55
+ if (!text)
56
+ continue;
57
+ const workspace = normalizeWorkspace(typeof rec.workspace === 'string' ? rec.workspace : undefined);
58
+ const createdAt = typeof rec.createdAt === 'number' && Number.isFinite(rec.createdAt) ? rec.createdAt : undefined;
59
+ const dedupKey = `${workspace || '*'}\0${text}`;
60
+ if (seenEntries.has(dedupKey))
61
+ continue;
62
+ seenEntries.add(dedupKey);
63
+ entries.push({
64
+ text,
65
+ ...(workspace ? { workspace } : {}),
66
+ ...(createdAt !== undefined ? { createdAt } : {})
67
+ });
68
+ }
69
+ return { facts, ...(entries.length > 0 ? { entries } : {}) };
70
+ }
71
+ export function recordScopedFact(rawMemory, factText, options = {}) {
72
+ const memory = normalizeMemoryData(rawMemory);
73
+ const text = String(factText || '').trim();
74
+ const maxFacts = Math.max(1, options.maxFacts ?? DEFAULT_MAX_FACTS);
75
+ const workspace = normalizeWorkspace(options.workspace);
76
+ const nowMs = typeof options.nowMs === 'number' && Number.isFinite(options.nowMs) ? options.nowMs : Date.now();
77
+ if (!text) {
78
+ return { memory, alreadyKnown: true };
79
+ }
80
+ const entries = [...(memory.entries || [])];
81
+ const existingEntry = entries.find(e => e.text === text && (e.workspace || '') === (workspace || ''));
82
+ const alreadyKnown = memory.facts.includes(text) && Boolean(!workspace || existingEntry);
83
+ if (!memory.facts.includes(text)) {
84
+ memory.facts.push(text);
85
+ while (memory.facts.length > maxFacts) {
86
+ memory.facts.shift();
87
+ }
88
+ }
89
+ if (!existingEntry) {
90
+ entries.push({
91
+ text,
92
+ ...(workspace ? { workspace } : {}),
93
+ createdAt: nowMs
94
+ });
95
+ while (entries.length > maxFacts) {
96
+ entries.shift();
97
+ }
98
+ }
99
+ else {
100
+ existingEntry.createdAt = nowMs;
101
+ }
102
+ return {
103
+ memory: {
104
+ facts: memory.facts,
105
+ entries
106
+ },
107
+ alreadyKnown
108
+ };
109
+ }
110
+ function isFactRelevantToWorkspace(text, entry, resolvedWorkspace) {
111
+ if (!text || TEST_JUNK_PATTERN.test(text))
112
+ return false;
113
+ if (!resolvedWorkspace)
114
+ return true;
115
+ if (entry?.workspace) {
116
+ return path.resolve(entry.workspace) === resolvedWorkspace;
117
+ }
118
+ const embeddedPaths = extractEmbeddedAbsolutePaths(text);
119
+ if (embeddedPaths.length > 0) {
120
+ const anyMatchesCurrent = embeddedPaths.some(p => isPathWithinOrSame(p, resolvedWorkspace));
121
+ if (!anyMatchesCurrent)
122
+ return false;
123
+ }
124
+ if (HISTORICAL_DELIVERABLE_PATTERN.test(text)) {
125
+ const projectName = path.basename(resolvedWorkspace).toLowerCase();
126
+ const mentionsWorkspacePath = text.includes(resolvedWorkspace)
127
+ || (projectName.length >= 4 && text.toLowerCase().includes(projectName));
128
+ if (!mentionsWorkspacePath)
129
+ return false;
130
+ }
131
+ return true;
132
+ }
133
+ export function formatMemoryContext(rawMemory, options) {
134
+ const memory = normalizeMemoryData(rawMemory);
135
+ const opts = typeof options === 'string'
136
+ ? { workspaceRoot: options }
137
+ : (options || {});
138
+ const resolvedWorkspace = normalizeWorkspace(opts.workspaceRoot);
139
+ const maxFacts = Math.max(1, opts.maxFacts ?? DEFAULT_CONTEXT_MAX_FACTS);
140
+ const maxChars = Math.max(200, opts.maxChars ?? DEFAULT_CONTEXT_MAX_CHARS);
141
+ const entryByText = new Map();
142
+ for (const entry of memory.entries || []) {
143
+ if (resolvedWorkspace && entry.workspace && path.resolve(entry.workspace) === resolvedWorkspace) {
144
+ entryByText.set(entry.text, entry);
145
+ }
146
+ else if (!entryByText.has(entry.text)) {
147
+ entryByText.set(entry.text, entry);
148
+ }
149
+ }
150
+ const relevant = [];
151
+ for (const factText of memory.facts) {
152
+ if (isFactRelevantToWorkspace(factText, entryByText.get(factText), resolvedWorkspace)) {
153
+ relevant.push(factText);
154
+ }
155
+ }
156
+ if (relevant.length === 0) {
157
+ return 'No workspace-relevant prior memory facts available.';
158
+ }
159
+ // Keep the most recent relevant facts within the character budget.
160
+ const selectedReversed = [];
161
+ let charCount = 0;
162
+ for (let i = relevant.length - 1; i >= 0 && selectedReversed.length < maxFacts; i--) {
163
+ const item = relevant[i];
164
+ if (charCount + item.length > maxChars && selectedReversed.length > 0)
165
+ break;
166
+ charCount += item.length;
167
+ selectedReversed.push(item);
168
+ }
169
+ const selected = selectedReversed.reverse();
170
+ return selected.map((fact, index) => `${index + 1}. ${fact}`).join('\n');
171
+ }
@@ -0,0 +1,214 @@
1
+ import path from 'node:path';
2
+
3
+ export interface ScopedFactEntry {
4
+ text: string;
5
+ workspace?: string | undefined;
6
+ createdAt?: number | undefined;
7
+ }
8
+
9
+ export interface PersistentMemoryData {
10
+ facts: string[];
11
+ entries?: ScopedFactEntry[] | undefined;
12
+ }
13
+
14
+ export interface RecordFactOptions {
15
+ workspace?: string | undefined;
16
+ nowMs?: number | undefined;
17
+ maxFacts?: number | undefined;
18
+ }
19
+
20
+ export interface FormatMemoryOptions {
21
+ workspaceRoot?: string | undefined;
22
+ maxFacts?: number | undefined;
23
+ maxChars?: number | undefined;
24
+ }
25
+
26
+ const DEFAULT_MAX_FACTS = 100;
27
+ const DEFAULT_CONTEXT_MAX_FACTS = 12;
28
+ const DEFAULT_CONTEXT_MAX_CHARS = 1800;
29
+
30
+ const TEST_JUNK_PATTERN = /^test fact\b/i;
31
+ const HISTORICAL_DELIVERABLE_PATTERN = /^(?:(?:Re)?Built|Upgraded|Deployed|Implemented)\b/i;
32
+ const WINDOWS_ABS_PATH_PATTERN = /^[A-Za-z]:\\/;
33
+
34
+ function normalizeWorkspace(workspace?: string | null): string | undefined {
35
+ if (typeof workspace !== 'string') return undefined;
36
+ const trimmed = workspace.trim();
37
+ if (!trimmed) return undefined;
38
+ return path.resolve(trimmed);
39
+ }
40
+
41
+ function isPathWithinOrSame(candidatePath: string, rootPath: string): boolean {
42
+ const rel = path.relative(path.resolve(rootPath), path.resolve(candidatePath));
43
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
44
+ }
45
+
46
+ function extractEmbeddedAbsolutePaths(text: string): string[] {
47
+ const found: string[] = [];
48
+ const posixRoots = ['/Users/', '/home/', '/private/', '/var/', '/opt/', '/srv/', '/workspace/', '/repos/'];
49
+ const tokens = text.split(/[\s()`'",;<>\[\]]+/);
50
+ for (const raw of tokens) {
51
+ if (!raw) continue;
52
+ if (posixRoots.some(prefix => raw.startsWith(prefix)) || WINDOWS_ABS_PATH_PATTERN.test(raw)) {
53
+ found.push(raw);
54
+ }
55
+ }
56
+ return found;
57
+ }
58
+
59
+ export function normalizeMemoryData(raw: unknown): PersistentMemoryData {
60
+ const obj = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
61
+ const rawFacts = Array.isArray(obj.facts) ? obj.facts : [];
62
+ const facts: string[] = [];
63
+ const seenFacts = new Set<string>();
64
+ for (const item of rawFacts) {
65
+ if (typeof item !== 'string') continue;
66
+ const trimmed = item.trim();
67
+ if (!trimmed || seenFacts.has(trimmed)) continue;
68
+ seenFacts.add(trimmed);
69
+ facts.push(trimmed);
70
+ }
71
+
72
+ const rawEntries = Array.isArray(obj.entries) ? obj.entries : [];
73
+ const entries: ScopedFactEntry[] = [];
74
+ const seenEntries = new Set<string>();
75
+ for (const item of rawEntries) {
76
+ if (!item || typeof item !== 'object') continue;
77
+ const rec = item as Record<string, unknown>;
78
+ const text = typeof rec.text === 'string' ? rec.text.trim() : '';
79
+ if (!text) continue;
80
+ const workspace = normalizeWorkspace(typeof rec.workspace === 'string' ? rec.workspace : undefined);
81
+ const createdAt = typeof rec.createdAt === 'number' && Number.isFinite(rec.createdAt) ? rec.createdAt : undefined;
82
+ const dedupKey = `${workspace || '*'}\0${text}`;
83
+ if (seenEntries.has(dedupKey)) continue;
84
+ seenEntries.add(dedupKey);
85
+ entries.push({
86
+ text,
87
+ ...(workspace ? { workspace } : {}),
88
+ ...(createdAt !== undefined ? { createdAt } : {})
89
+ });
90
+ }
91
+
92
+ return { facts, ...(entries.length > 0 ? { entries } : {}) };
93
+ }
94
+
95
+ export function recordScopedFact(
96
+ rawMemory: unknown,
97
+ factText: string,
98
+ options: RecordFactOptions = {}
99
+ ): { memory: PersistentMemoryData; alreadyKnown: boolean } {
100
+ const memory = normalizeMemoryData(rawMemory);
101
+ const text = String(factText || '').trim();
102
+ const maxFacts = Math.max(1, options.maxFacts ?? DEFAULT_MAX_FACTS);
103
+ const workspace = normalizeWorkspace(options.workspace);
104
+ const nowMs = typeof options.nowMs === 'number' && Number.isFinite(options.nowMs) ? options.nowMs : Date.now();
105
+
106
+ if (!text) {
107
+ return { memory, alreadyKnown: true };
108
+ }
109
+
110
+ const entries = [...(memory.entries || [])];
111
+ const existingEntry = entries.find(e => e.text === text && (e.workspace || '') === (workspace || ''));
112
+ const alreadyKnown = memory.facts.includes(text) && Boolean(!workspace || existingEntry);
113
+
114
+ if (!memory.facts.includes(text)) {
115
+ memory.facts.push(text);
116
+ while (memory.facts.length > maxFacts) {
117
+ memory.facts.shift();
118
+ }
119
+ }
120
+
121
+ if (!existingEntry) {
122
+ entries.push({
123
+ text,
124
+ ...(workspace ? { workspace } : {}),
125
+ createdAt: nowMs
126
+ });
127
+ while (entries.length > maxFacts) {
128
+ entries.shift();
129
+ }
130
+ } else {
131
+ existingEntry.createdAt = nowMs;
132
+ }
133
+
134
+ return {
135
+ memory: {
136
+ facts: memory.facts,
137
+ entries
138
+ },
139
+ alreadyKnown
140
+ };
141
+ }
142
+
143
+ function isFactRelevantToWorkspace(
144
+ text: string,
145
+ entry: ScopedFactEntry | undefined,
146
+ resolvedWorkspace: string | undefined
147
+ ): boolean {
148
+ if (!text || TEST_JUNK_PATTERN.test(text)) return false;
149
+ if (!resolvedWorkspace) return true;
150
+
151
+ if (entry?.workspace) {
152
+ return path.resolve(entry.workspace) === resolvedWorkspace;
153
+ }
154
+
155
+ const embeddedPaths = extractEmbeddedAbsolutePaths(text);
156
+ if (embeddedPaths.length > 0) {
157
+ const anyMatchesCurrent = embeddedPaths.some(p => isPathWithinOrSame(p, resolvedWorkspace));
158
+ if (!anyMatchesCurrent) return false;
159
+ }
160
+
161
+ if (HISTORICAL_DELIVERABLE_PATTERN.test(text)) {
162
+ const projectName = path.basename(resolvedWorkspace).toLowerCase();
163
+ const mentionsWorkspacePath = text.includes(resolvedWorkspace)
164
+ || (projectName.length >= 4 && text.toLowerCase().includes(projectName));
165
+ if (!mentionsWorkspacePath) return false;
166
+ }
167
+
168
+ return true;
169
+ }
170
+
171
+ export function formatMemoryContext(
172
+ rawMemory: unknown,
173
+ options?: string | FormatMemoryOptions
174
+ ): string {
175
+ const memory = normalizeMemoryData(rawMemory);
176
+ const opts: FormatMemoryOptions = typeof options === 'string'
177
+ ? { workspaceRoot: options }
178
+ : (options || {});
179
+ const resolvedWorkspace = normalizeWorkspace(opts.workspaceRoot);
180
+ const maxFacts = Math.max(1, opts.maxFacts ?? DEFAULT_CONTEXT_MAX_FACTS);
181
+ const maxChars = Math.max(200, opts.maxChars ?? DEFAULT_CONTEXT_MAX_CHARS);
182
+
183
+ const entryByText = new Map<string, ScopedFactEntry>();
184
+ for (const entry of memory.entries || []) {
185
+ if (resolvedWorkspace && entry.workspace && path.resolve(entry.workspace) === resolvedWorkspace) {
186
+ entryByText.set(entry.text, entry);
187
+ } else if (!entryByText.has(entry.text)) {
188
+ entryByText.set(entry.text, entry);
189
+ }
190
+ }
191
+
192
+ const relevant: string[] = [];
193
+ for (const factText of memory.facts) {
194
+ if (isFactRelevantToWorkspace(factText, entryByText.get(factText), resolvedWorkspace)) {
195
+ relevant.push(factText);
196
+ }
197
+ }
198
+
199
+ if (relevant.length === 0) {
200
+ return 'No workspace-relevant prior memory facts available.';
201
+ }
202
+
203
+ // Keep the most recent relevant facts within the character budget.
204
+ const selectedReversed: string[] = [];
205
+ let charCount = 0;
206
+ for (let i = relevant.length - 1; i >= 0 && selectedReversed.length < maxFacts; i--) {
207
+ const item = relevant[i]!;
208
+ if (charCount + item.length > maxChars && selectedReversed.length > 0) break;
209
+ charCount += item.length;
210
+ selectedReversed.push(item);
211
+ }
212
+ const selected = selectedReversed.reverse();
213
+ return selected.map((fact, index) => `${index + 1}. ${fact}`).join('\n');
214
+ }
package/src/memory.d.ts CHANGED
@@ -1 +1,13 @@
1
- export function getMemoryContextString(...args: any[]): any;
1
+ import type {
2
+ PersistentMemoryData,
3
+ RecordFactOptions,
4
+ FormatMemoryOptions
5
+ } from './memory/scopedFacts.js';
6
+
7
+ export type MemoryStoreData = PersistentMemoryData;
8
+
9
+ export function getMemory(): MemoryStoreData;
10
+ export function saveMemory(data: MemoryStoreData): void;
11
+ export function addFact(factStr: string, options?: RecordFactOptions): void;
12
+ export function clearMemory(): void;
13
+ export function getMemoryContextString(options?: string | FormatMemoryOptions): string;
package/src/memory.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
- import os from 'os';
4
3
  import { causyneHome } from './utils/paths.js';
4
+ import { formatMemoryContext, normalizeMemoryData, recordScopedFact } from './memory/scopedFacts.js';
5
5
 
6
6
  const MEMORY_FILE_PATH = path.join(causyneHome(), 'memory.json');
7
7
 
@@ -20,7 +20,7 @@ export function getMemory() {
20
20
  try {
21
21
  initMemory();
22
22
  const data = fs.readFileSync(MEMORY_FILE_PATH, 'utf-8');
23
- return JSON.parse(data);
23
+ return normalizeMemoryData(JSON.parse(data));
24
24
  } catch (e) {
25
25
  console.error("Failed to read memory.json:", e.message);
26
26
  return { facts: [] };
@@ -36,27 +36,24 @@ export function saveMemory(data) {
36
36
  }
37
37
  }
38
38
 
39
- export function addFact(factStr) {
39
+ export function addFact(factStr, options = {}) {
40
40
  const mem = getMemory();
41
- // Only add if it doesn't already exist to avoid duplicates
42
- if (!mem.facts.includes(factStr)) {
43
- mem.facts.push(factStr);
44
- saveMemory(mem);
41
+ const { memory, alreadyKnown } = recordScopedFact(mem, factStr, options);
42
+ if (!alreadyKnown || options.workspace) {
43
+ saveMemory(memory);
45
44
  }
46
45
  }
47
46
 
48
47
  export function clearMemory() {
49
48
  try {
50
49
  initMemory();
51
- fs.writeFileSync(MEMORY_FILE_PATH, JSON.stringify({ facts: [] }, null, 2));
50
+ fs.writeFileSync(MEMORY_FILE_PATH, JSON.stringify({ facts: [], entries: [] }, null, 2));
52
51
  } catch (e) {
53
52
  console.error("Failed to clear memory:", e.message);
54
53
  }
55
54
  }
56
55
 
57
- export function getMemoryContextString() {
56
+ export function getMemoryContextString(options = undefined) {
58
57
  const mem = getMemory();
59
- if (!mem || !mem.facts || mem.facts.length === 0) return "No prior memory facts available.";
60
-
61
- return mem.facts.map((fact, index) => `${index + 1}. ${fact}`).join("\n");
58
+ return formatMemoryContext(mem, options);
62
59
  }
@@ -54,29 +54,36 @@ function compactArguments(args) {
54
54
  return redact(JSON.stringify(allowed));
55
55
  }
56
56
  function parseVerdict(content) {
57
- const match = content.match(/\{[\s\S]*\}/);
58
- if (!match)
59
- return null;
60
- try {
61
- const parsed = JSON.parse(match[0]);
62
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
63
- return null;
64
- const record = parsed;
65
- const risk = record.risk;
66
- const confidence = record.confidence;
67
- if (typeof risk !== 'number' || !Number.isFinite(risk))
68
- return null;
69
- if (typeof confidence !== 'number' || !Number.isFinite(confidence))
70
- return null;
71
- return {
72
- risk: Math.max(0, Math.min(1, risk)),
73
- confidence: Math.max(0, Math.min(1, confidence)),
74
- observation: typeof record.observation === 'string' ? record.observation.slice(0, 400) : ''
75
- };
76
- }
77
- catch {
57
+ const closeIndex = content.lastIndexOf('}');
58
+ if (closeIndex < 0)
78
59
  return null;
60
+ let searchEnd = closeIndex;
61
+ while (searchEnd >= 0) {
62
+ const openIndex = content.lastIndexOf('{', searchEnd);
63
+ if (openIndex < 0)
64
+ break;
65
+ const candidate = content.slice(openIndex, closeIndex + 1);
66
+ try {
67
+ const parsed = JSON.parse(candidate);
68
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
69
+ const record = parsed;
70
+ const risk = record.risk;
71
+ const confidence = record.confidence;
72
+ if (typeof risk === 'number' && Number.isFinite(risk) && typeof confidence === 'number' && Number.isFinite(confidence)) {
73
+ return {
74
+ risk: Math.max(0, Math.min(1, risk)),
75
+ confidence: Math.max(0, Math.min(1, confidence)),
76
+ observation: typeof record.observation === 'string' ? record.observation.slice(0, 400) : ''
77
+ };
78
+ }
79
+ }
80
+ }
81
+ catch {
82
+ // Try an earlier opening brace if the suffix was nested inside outer braces.
83
+ }
84
+ searchEnd = openIndex - 1;
79
85
  }
86
+ return null;
80
87
  }
81
88
  export async function queryAdvisory(input, options) {
82
89
  if (!isLoopbackEndpoint(options.endpoint))
@@ -141,7 +148,10 @@ export async function probeAdvisory(options) {
141
148
  }
142
149
  const start = Date.now();
143
150
  const controller = new AbortController();
144
- const timer = setTimeout(() => controller.abort(), Math.max(500, options.timeoutMs));
151
+ const safeTimeoutMs = Number.isFinite(options.timeoutMs)
152
+ ? Math.max(500, Math.min(30_000, Math.floor(options.timeoutMs)))
153
+ : 2500;
154
+ const timer = setTimeout(() => controller.abort(), safeTimeoutMs);
145
155
  try {
146
156
  const base = options.endpoint.replace(/\/+$/, '').replace(/\/chat\/completions$/, '');
147
157
  const response = await fetch(`${base}/models`, { signal: controller.signal });
@@ -72,24 +72,33 @@ function compactArguments(args: Record<string, unknown>): string {
72
72
  }
73
73
 
74
74
  function parseVerdict(content: string): AdvisoryVerdict | null {
75
- const match = content.match(/\{[\s\S]*\}/);
76
- if (!match) return null;
77
- try {
78
- const parsed: unknown = JSON.parse(match[0]);
79
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
80
- const record = parsed as Record<string, unknown>;
81
- const risk = record.risk;
82
- const confidence = record.confidence;
83
- if (typeof risk !== 'number' || !Number.isFinite(risk)) return null;
84
- if (typeof confidence !== 'number' || !Number.isFinite(confidence)) return null;
85
- return {
86
- risk: Math.max(0, Math.min(1, risk)),
87
- confidence: Math.max(0, Math.min(1, confidence)),
88
- observation: typeof record.observation === 'string' ? record.observation.slice(0, 400) : ''
89
- };
90
- } catch {
91
- return null;
75
+ const closeIndex = content.lastIndexOf('}');
76
+ if (closeIndex < 0) return null;
77
+ let searchEnd = closeIndex;
78
+ while (searchEnd >= 0) {
79
+ const openIndex = content.lastIndexOf('{', searchEnd);
80
+ if (openIndex < 0) break;
81
+ const candidate = content.slice(openIndex, closeIndex + 1);
82
+ try {
83
+ const parsed: unknown = JSON.parse(candidate);
84
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
85
+ const record = parsed as Record<string, unknown>;
86
+ const risk = record.risk;
87
+ const confidence = record.confidence;
88
+ if (typeof risk === 'number' && Number.isFinite(risk) && typeof confidence === 'number' && Number.isFinite(confidence)) {
89
+ return {
90
+ risk: Math.max(0, Math.min(1, risk)),
91
+ confidence: Math.max(0, Math.min(1, confidence)),
92
+ observation: typeof record.observation === 'string' ? record.observation.slice(0, 400) : ''
93
+ };
94
+ }
95
+ }
96
+ } catch {
97
+ // Try an earlier opening brace if the suffix was nested inside outer braces.
98
+ }
99
+ searchEnd = openIndex - 1;
92
100
  }
101
+ return null;
93
102
  }
94
103
 
95
104
  export async function queryAdvisory(
@@ -150,7 +159,10 @@ export async function probeAdvisory(options: AdvisoryOptions): Promise<{ healthy
150
159
  }
151
160
  const start = Date.now();
152
161
  const controller = new AbortController();
153
- const timer = setTimeout(() => controller.abort(), Math.max(500, options.timeoutMs));
162
+ const safeTimeoutMs = Number.isFinite(options.timeoutMs)
163
+ ? Math.max(500, Math.min(30_000, Math.floor(options.timeoutMs)))
164
+ : 2500;
165
+ const timer = setTimeout(() => controller.abort(), safeTimeoutMs);
154
166
  try {
155
167
  const base = options.endpoint.replace(/\/+$/, '').replace(/\/chat\/completions$/, '');
156
168
  const response = await fetch(`${base}/models`, { signal: controller.signal });
@@ -4,7 +4,7 @@ import path from 'node:path';
4
4
  import { auditLog } from '../auditLog.js';
5
5
  import { isLaunchOnlyPrompt } from '../launchIntent.js';
6
6
  import { causyneHome } from '../utils/paths.js';
7
- import { boundedArgs, outcomeFromResult, scanMutation } from './evidence.js';
7
+ import { outcomeFromResult, scanMutation } from './evidence.js';
8
8
  import { isLoopbackEndpoint, probeAdvisory, queryAdvisory } from './advisory.js';
9
9
  const CONFIG_FILE = path.join(causyneHome(), 'observer.json');
10
10
  const MAX_AUDIT_RECORDS = 200;
@@ -122,39 +122,18 @@ function confirmThreshold(strictness) {
122
122
  return 0.45;
123
123
  return 0.62;
124
124
  }
125
- function nestedError(result) {
126
- if (result === null || typeof result !== 'object' || Array.isArray(result))
127
- return '';
128
- const record = result;
129
- return typeof record.error === 'string' ? record.error : '';
130
- }
131
125
  function normalizeOutcome(entry) {
132
126
  const args = entry.args && typeof entry.args === 'object' && !Array.isArray(entry.args)
133
127
  ? entry.args
134
128
  : {};
135
- const result = entry.result;
136
- const error = nestedError(result);
137
- const command = entry.command
138
- || (typeof args.command === 'string' ? args.command : '')
139
- || (typeof args.CommandLine === 'string' ? args.CommandLine : '')
140
- || (typeof args.commandLine === 'string' ? args.commandLine : '')
141
- || (typeof args.cmd === 'string' ? args.cmd : '')
142
- || (typeof args.script === 'string' ? args.script : '')
143
- || (['run_command', 'run', 'execute', 'exec', 'bash', 'terminal', 'sh', 'zsh', 'sysrun'].includes(String(entry.tool || '').toLowerCase()) && typeof args.detail === 'string' ? args.detail : '');
129
+ const normalized = outcomeFromResult(entry.tool, args, entry.result, 0);
130
+ const command = typeof entry.command === 'string' && entry.command.trim() ? entry.command : normalized.command;
131
+ const targetPath = typeof entry.path === 'string' && entry.path.trim() ? entry.path : normalized.path;
144
132
  return {
145
- tool: entry.tool,
146
- args: boundedArgs(args),
147
- success: entry.success === true && !error,
148
- error: error.slice(0, 600),
149
- exitCode: result !== null && typeof result === 'object' && !Array.isArray(result)
150
- && typeof result.exitCode === 'number'
151
- ? result.exitCode
152
- : null,
133
+ ...normalized,
134
+ success: entry.success === true && normalized.success,
153
135
  command: command.slice(0, 600),
154
- path: entry.path
155
- || (typeof args.path === 'string' ? args.path : '')
156
- || (typeof args.file_path === 'string' ? args.file_path : ''),
157
- at: 0
136
+ path: targetPath.slice(0, 400)
158
137
  };
159
138
  }
160
139
  function claimText(agentClaim) {
@@ -181,7 +160,16 @@ export class ColdObserver {
181
160
  advisoryCooldownUntil = 0;
182
161
  static instance = null;
183
162
  constructor(configPartial) {
184
- this.config = { ...DEFAULT_CONFIG, ...readStoredConfig(), ...(configPartial || {}) };
163
+ const base = { ...DEFAULT_CONFIG, ...readStoredConfig() };
164
+ const partial = configPartial || {};
165
+ this.config = {
166
+ enabled: typeof partial.enabled === 'boolean' ? partial.enabled : base.enabled,
167
+ mode: normalizeMode(partial.mode) ?? base.mode,
168
+ endpoint: typeof partial.endpoint === 'string' ? partial.endpoint.trim().replace(/\/+$/, '') : base.endpoint,
169
+ model: typeof partial.model === 'string' ? partial.model.trim().slice(0, 200) : base.model,
170
+ timeoutMs: boundedTimeout(partial.timeoutMs) ?? base.timeoutMs,
171
+ strictness: normalizeStrictness(partial.strictness) ?? base.strictness
172
+ };
185
173
  }
186
174
  static getInstance() {
187
175
  if (!ColdObserver.instance)
@@ -401,10 +389,10 @@ export class ColdObserver {
401
389
  && /\.(?:[cm]?[jt]sx?|py|rb|php|go|rs|java|kt|kts|swift|c|cc|cpp|h|hpp|cs|fs|sh|sql|html|css|scss|sass|vue|svelte)$/i.test(outcome.path);
402
390
  const lastCodeChange = outcomes.findLastIndex(isCodeMutation);
403
391
  const checks = outcomes.slice(lastCodeChange + 1);
404
- const hasTestRun = checks.some((outcome) => outcome.success
405
- && (TEST_COMMAND.test(outcome.command) || TEST_COMMAND.test(outcome.tool)));
406
- const hasBuildRun = checks.some((outcome) => outcome.success
407
- && (BUILD_OR_CHECK_COMMAND.test(outcome.command) || outcome.tool === 'code_verify_syntax'));
392
+ const testChecks = checks.filter((outcome) => TEST_COMMAND.test(outcome.command) || TEST_COMMAND.test(outcome.tool));
393
+ const buildChecks = checks.filter((outcome) => BUILD_OR_CHECK_COMMAND.test(outcome.command) || outcome.tool === 'code_verify_syntax');
394
+ const hasTestRun = testChecks.length > 0 && testChecks[testChecks.length - 1].success;
395
+ const hasBuildRun = buildChecks.length > 0 && buildChecks[buildChecks.length - 1].success;
408
396
  const isLaunch = isLaunchOnlyPrompt(turnState.userPrompt || '');
409
397
  const modifiedCode = lastCodeChange >= 0;
410
398
  const declarativeOnly = modifiedCode && outcomes.filter(isCodeMutation).every(outcome => /\.(?:html|css)$/i.test(outcome.path));