@causyne/agent 1.20.116 → 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.
- package/package.json +1 -1
- package/src/agentLoop.js +81 -31
- package/src/agentLoop.ts +82 -33
- package/src/browser/causyneBrowser.js +30 -7
- package/src/browser/causyneBrowser.ts +29 -7
- package/src/cliMode.js +5 -1
- package/src/memory/scopedFacts.js +171 -0
- package/src/memory/scopedFacts.ts +214 -0
- package/src/memory.d.ts +13 -1
- package/src/memory.js +9 -12
- package/src/perception.js +124 -3
- package/src/perception.ts +128 -4
- package/src/planCache.js +17 -3
- package/src/planCache.ts +17 -3
- package/src/smartToolsUse.js +4 -5
- package/src/smartToolsUse.ts +4 -6
- package/src/taskShape.js +49 -7
- package/src/taskShape.ts +55 -7
- package/src/toolPacks.js +27 -5
- package/src/toolPacks.ts +32 -5
- package/src/tools/memoryWrite.js +8 -10
- package/src/tools/memoryWrite.ts +13 -11
- package/src/tui/chatRenderer.js +4 -1
- package/src/tui/codeProgress.js +3 -2
- package/src/tui/codeProgress.ts +3 -2
- package/src/tui/codeStreamRenderer.js +41 -15
- package/src/tui/codeStreamRenderer.ts +40 -15
- package/src/tui/keys.js +3 -1
- package/src/tui/prompt.js +24 -0
- package/src/tui/scrollInteraction.js +2 -2
- package/src/tui/scrollInteraction.ts +2 -2
- package/src/tui/stageSurface.js +114 -4
- package/src/tui/turnRail.js +21 -14
- package/src/tui/turnRail.ts +19 -14
- package/src/tui/usageCard.js +89 -68
- package/src/tui/usageCard.ts +98 -91
- package/src/types/contracts.ts +3 -0
|
@@ -299,6 +299,13 @@ export function isDeadContextError(err: unknown): boolean {
|
|
|
299
299
|
|| msg.includes('Browser closed');
|
|
300
300
|
}
|
|
301
301
|
|
|
302
|
+
export function isExecutionContextDestroyedError(err: unknown): boolean {
|
|
303
|
+
const msg = errorMessage(err);
|
|
304
|
+
return msg.includes('Execution context was destroyed')
|
|
305
|
+
|| msg.includes('Cannot find context with specified id')
|
|
306
|
+
|| msg.includes('Frame was detached');
|
|
307
|
+
}
|
|
308
|
+
|
|
302
309
|
export function isPageCrashedError(err: unknown): boolean {
|
|
303
310
|
const msg = errorMessage(err);
|
|
304
311
|
return msg.includes('Page crashed')
|
|
@@ -1046,7 +1053,7 @@ export class CausyneBrowser {
|
|
|
1046
1053
|
...windowSnapshot(state.lastSnapshot, offset),
|
|
1047
1054
|
tabId: state.id,
|
|
1048
1055
|
url: state.page.url(),
|
|
1049
|
-
title: await state.page
|
|
1056
|
+
title: await this.safePageTitle(state.page),
|
|
1050
1057
|
refsCount: state.refs.size,
|
|
1051
1058
|
...(state.lastStructure ? { structure: state.lastStructure } : {})
|
|
1052
1059
|
};
|
|
@@ -1691,18 +1698,18 @@ export class CausyneBrowser {
|
|
|
1691
1698
|
? (expandSearchMacro(action.macro, action.query ?? action.text ?? '') ?? undefined)
|
|
1692
1699
|
: action.url;
|
|
1693
1700
|
const state = await this.createTab(initialUrl);
|
|
1694
|
-
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page
|
|
1701
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
|
|
1695
1702
|
}
|
|
1696
1703
|
if (action.type === 'listTabs' || action.type === 'list_tabs') {
|
|
1697
1704
|
const data = await Promise.all([...this.tabs.values()].filter(tab => !tab.page.isClosed() && !tab.crashed).map(async tab => ({
|
|
1698
|
-
tabId: tab.id, active: tab.id === this.activeTabId, url: tab.page.url(), title: await tab.page
|
|
1705
|
+
tabId: tab.id, active: tab.id === this.activeTabId, url: tab.page.url(), title: await this.safePageTitle(tab.page)
|
|
1699
1706
|
})));
|
|
1700
1707
|
return { action: action.type, data };
|
|
1701
1708
|
}
|
|
1702
1709
|
const requested = this.requestedTab(action);
|
|
1703
1710
|
const state = requested ?? await this.activeTab();
|
|
1704
1711
|
if (action.type === 'switchTab' || action.type === 'switch_tab') {
|
|
1705
|
-
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page
|
|
1712
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
|
|
1706
1713
|
}
|
|
1707
1714
|
if (action.type === 'closeTab' || action.type === 'close_tab') {
|
|
1708
1715
|
await state.page.close();
|
|
@@ -1717,12 +1724,12 @@ export class CausyneBrowser {
|
|
|
1717
1724
|
}
|
|
1718
1725
|
if (action.type === 'goto' || action.type === 'open' || action.type === 'navigate') {
|
|
1719
1726
|
await this.navigateWithMacroFallback(state, action);
|
|
1720
|
-
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page
|
|
1727
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
|
|
1721
1728
|
}
|
|
1722
1729
|
if (action.type === 'preview') {
|
|
1723
1730
|
if (typeof action.filePath !== 'string') throw new Error('preview requires filePath');
|
|
1724
1731
|
await this.preview(state, action.filePath, workspace);
|
|
1725
|
-
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page
|
|
1732
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page), output: 'Rendered in an isolated internal preview. This browser-only origin is not user-openable. Start a real local server with sysRunBg if the user needs an interactive URL.' };
|
|
1726
1733
|
}
|
|
1727
1734
|
if (action.type === 'snapshot' || action.type === 'scrape') {
|
|
1728
1735
|
const snapshot = await this.snapshot(action.offset ?? 0);
|
|
@@ -1879,7 +1886,22 @@ export class CausyneBrowser {
|
|
|
1879
1886
|
throw new Error(`Unsupported browser action: ${action.type}`);
|
|
1880
1887
|
}
|
|
1881
1888
|
state.refs.clear();
|
|
1882
|
-
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page
|
|
1889
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
/** Reads page.title() safely even if an immediate client redirect destroyed the mid-flight execution context. */
|
|
1893
|
+
private async safePageTitle(page: BrowserPage): Promise<string> {
|
|
1894
|
+
try {
|
|
1895
|
+
return await page.title();
|
|
1896
|
+
} catch (error) {
|
|
1897
|
+
if (!isExecutionContextDestroyedError(error)) throw error;
|
|
1898
|
+
try {
|
|
1899
|
+
await page.waitForLoadState('domcontentloaded', { timeout: 2000 });
|
|
1900
|
+
return await page.title();
|
|
1901
|
+
} catch {
|
|
1902
|
+
return '';
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1883
1905
|
}
|
|
1884
1906
|
|
|
1885
1907
|
private touch(): void {
|
package/src/cliMode.js
CHANGED
|
@@ -324,7 +324,11 @@ export async function chatMode({ home = false } = {}) {
|
|
|
324
324
|
// The idle footer's two facts. Both were already loaded and neither was ever
|
|
325
325
|
// displayed once the header had scrolled away.
|
|
326
326
|
cwd: process.cwd(),
|
|
327
|
-
contextLimit: resolveCharPool(config.tier, config.maxCharPool
|
|
327
|
+
contextLimit: resolveCharPool(config.tier, config.maxCharPool, {
|
|
328
|
+
provider: config.provider,
|
|
329
|
+
model: config.model,
|
|
330
|
+
overrideTokens: config.contextTokens || config.maxContextTokens
|
|
331
|
+
})
|
|
328
332
|
};
|
|
329
333
|
let surface = home && isInteractive() ? createStageSurface({ config }) : null;
|
|
330
334
|
const openedHome = Boolean(surface);
|
|
@@ -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
|
-
|
|
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
|
-
|
|
42
|
-
if (!
|
|
43
|
-
|
|
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
|
-
|
|
60
|
-
|
|
61
|
-
return mem.facts.map((fact, index) => `${index + 1}. ${fact}`).join("\n");
|
|
58
|
+
return formatMemoryContext(mem, options);
|
|
62
59
|
}
|