@causyne/agent 1.20.116 → 1.20.118
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 +7 -2
- 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 +24 -4
- package/src/commands.js +7 -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/plugins/pluginManager.js +74 -0
- package/src/reporting.js +12 -4
- package/src/skillsManager.js +3 -2
- package/src/skillsManager.ts +3 -2
- 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/tools/pluginManager.js +17 -2
- 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/composerControls.js +16 -3
- package/src/tui/composerControls.ts +14 -3
- package/src/tui/keys.js +3 -1
- package/src/tui/prompt.js +146 -16
- 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 +164 -71
- package/src/tui/usageCard.ts +187 -96
- package/src/tui/workspaceSwitch.js +2 -0
- package/src/tui/workspaceSwitch.ts +1 -0
- package/src/types/contracts.ts +3 -0
- package/src/verification/boundedExplorer.js +119 -0
- package/src/verification/cliProbe.js +116 -0
- package/src/verification/featureMap.js +78 -0
- package/src/verification/interactivePty.js +188 -0
- package/src/verification/propertyProbe.js +121 -0
- package/src/verification/ptyProbe.js +125 -0
- package/src/verification/skillCatalog.d.ts +1 -0
- package/src/verification/skillCatalog.js +60 -0
- package/src/verification/statechart.js +143 -0
- package/src/verification/uiRuntime.js +57 -0
- package/src/verificationPlan.js +1 -1
- package/src/verificationPlan.ts +1 -1
|
@@ -234,6 +234,12 @@ export function isDeadContextError(err) {
|
|
|
234
234
|
|| msg.includes('Context closed')
|
|
235
235
|
|| msg.includes('Browser closed');
|
|
236
236
|
}
|
|
237
|
+
export function isExecutionContextDestroyedError(err) {
|
|
238
|
+
const msg = errorMessage(err);
|
|
239
|
+
return msg.includes('Execution context was destroyed')
|
|
240
|
+
|| msg.includes('Cannot find context with specified id')
|
|
241
|
+
|| msg.includes('Frame was detached');
|
|
242
|
+
}
|
|
237
243
|
export function isPageCrashedError(err) {
|
|
238
244
|
const msg = errorMessage(err);
|
|
239
245
|
return msg.includes('Page crashed')
|
|
@@ -776,7 +782,7 @@ export class CausyneBrowser {
|
|
|
776
782
|
...windowSnapshot(state.lastSnapshot, offset),
|
|
777
783
|
tabId: state.id,
|
|
778
784
|
url: state.page.url(),
|
|
779
|
-
title: await state.page
|
|
785
|
+
title: await this.safePageTitle(state.page),
|
|
780
786
|
refsCount: state.refs.size,
|
|
781
787
|
...(state.lastStructure ? { structure: state.lastStructure } : {})
|
|
782
788
|
};
|
|
@@ -1469,18 +1475,18 @@ export class CausyneBrowser {
|
|
|
1469
1475
|
? (expandSearchMacro(action.macro, action.query ?? action.text ?? '') ?? undefined)
|
|
1470
1476
|
: action.url;
|
|
1471
1477
|
const state = await this.createTab(initialUrl);
|
|
1472
|
-
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page
|
|
1478
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
|
|
1473
1479
|
}
|
|
1474
1480
|
if (action.type === 'listTabs' || action.type === 'list_tabs') {
|
|
1475
1481
|
const data = await Promise.all([...this.tabs.values()].filter(tab => !tab.page.isClosed() && !tab.crashed).map(async (tab) => ({
|
|
1476
|
-
tabId: tab.id, active: tab.id === this.activeTabId, url: tab.page.url(), title: await tab.page
|
|
1482
|
+
tabId: tab.id, active: tab.id === this.activeTabId, url: tab.page.url(), title: await this.safePageTitle(tab.page)
|
|
1477
1483
|
})));
|
|
1478
1484
|
return { action: action.type, data };
|
|
1479
1485
|
}
|
|
1480
1486
|
const requested = this.requestedTab(action);
|
|
1481
1487
|
const state = requested ?? await this.activeTab();
|
|
1482
1488
|
if (action.type === 'switchTab' || action.type === 'switch_tab') {
|
|
1483
|
-
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page
|
|
1489
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
|
|
1484
1490
|
}
|
|
1485
1491
|
if (action.type === 'closeTab' || action.type === 'close_tab') {
|
|
1486
1492
|
await state.page.close();
|
|
@@ -1496,13 +1502,13 @@ export class CausyneBrowser {
|
|
|
1496
1502
|
}
|
|
1497
1503
|
if (action.type === 'goto' || action.type === 'open' || action.type === 'navigate') {
|
|
1498
1504
|
await this.navigateWithMacroFallback(state, action);
|
|
1499
|
-
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page
|
|
1505
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
|
|
1500
1506
|
}
|
|
1501
1507
|
if (action.type === 'preview') {
|
|
1502
1508
|
if (typeof action.filePath !== 'string')
|
|
1503
1509
|
throw new Error('preview requires filePath');
|
|
1504
1510
|
await this.preview(state, action.filePath, workspace);
|
|
1505
|
-
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page
|
|
1511
|
+
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.' };
|
|
1506
1512
|
}
|
|
1507
1513
|
if (action.type === 'snapshot' || action.type === 'scrape') {
|
|
1508
1514
|
const snapshot = await this.snapshot(action.offset ?? 0);
|
|
@@ -1678,7 +1684,24 @@ export class CausyneBrowser {
|
|
|
1678
1684
|
throw new Error(`Unsupported browser action: ${action.type}`);
|
|
1679
1685
|
}
|
|
1680
1686
|
state.refs.clear();
|
|
1681
|
-
return { action: action.type, tabId: state.id, url: state.page.url(), title: await state.page
|
|
1687
|
+
return { action: action.type, tabId: state.id, url: state.page.url(), title: await this.safePageTitle(state.page) };
|
|
1688
|
+
}
|
|
1689
|
+
/** Reads page.title() safely even if an immediate client redirect destroyed the mid-flight execution context. */
|
|
1690
|
+
async safePageTitle(page) {
|
|
1691
|
+
try {
|
|
1692
|
+
return await page.title();
|
|
1693
|
+
}
|
|
1694
|
+
catch (error) {
|
|
1695
|
+
if (!isExecutionContextDestroyedError(error))
|
|
1696
|
+
throw error;
|
|
1697
|
+
try {
|
|
1698
|
+
await page.waitForLoadState('domcontentloaded', { timeout: 2000 });
|
|
1699
|
+
return await page.title();
|
|
1700
|
+
}
|
|
1701
|
+
catch {
|
|
1702
|
+
return '';
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1682
1705
|
}
|
|
1683
1706
|
touch() {
|
|
1684
1707
|
if (this.idleTimer)
|
|
@@ -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
|
@@ -66,6 +66,9 @@ export class LocalCLIConnection {
|
|
|
66
66
|
|
|
67
67
|
try {
|
|
68
68
|
this.renderer.handle(msg);
|
|
69
|
+
if (msg.type === 'usage_update' && typeof this.onUsageUpdate === 'function') {
|
|
70
|
+
this.onUsageUpdate(msg);
|
|
71
|
+
}
|
|
69
72
|
} catch (e) {
|
|
70
73
|
// This used to be `catch(e) {}` around the whole method, so a render bug
|
|
71
74
|
// silently ate the frame and the transcript just went quiet. Report it
|
|
@@ -324,7 +327,11 @@ export async function chatMode({ home = false } = {}) {
|
|
|
324
327
|
// The idle footer's two facts. Both were already loaded and neither was ever
|
|
325
328
|
// displayed once the header had scrolled away.
|
|
326
329
|
cwd: process.cwd(),
|
|
327
|
-
contextLimit: resolveCharPool(config.tier, config.maxCharPool
|
|
330
|
+
contextLimit: resolveCharPool(config.tier, config.maxCharPool, {
|
|
331
|
+
provider: config.provider,
|
|
332
|
+
model: config.model,
|
|
333
|
+
overrideTokens: config.contextTokens || config.maxContextTokens
|
|
334
|
+
})
|
|
328
335
|
};
|
|
329
336
|
let surface = home && isInteractive() ? createStageSurface({ config }) : null;
|
|
330
337
|
const openedHome = Boolean(surface);
|
|
@@ -373,12 +380,24 @@ export async function chatMode({ home = false } = {}) {
|
|
|
373
380
|
messageActionLoop: loop,
|
|
374
381
|
onInterrupt: () => loop.abort(),
|
|
375
382
|
getMode: () => loop.config?.autonomyMode || config.autonomyMode || 'B',
|
|
376
|
-
onOpenMode: () =>
|
|
377
|
-
|
|
378
|
-
|
|
383
|
+
onOpenMode: async () => {
|
|
384
|
+
await openModeControl(prompt, loop);
|
|
385
|
+
prompt?.refreshPinnedPanels?.(loop);
|
|
386
|
+
},
|
|
387
|
+
onOpenModel: async () => {
|
|
388
|
+
await runInteractiveModelPicker(prompt, { loadConfig, saveConfig }, { loop });
|
|
389
|
+
prompt?.refreshPinnedPanels?.(loop);
|
|
390
|
+
},
|
|
391
|
+
onOpenVariant: async () => {
|
|
392
|
+
await openVariantControl(prompt);
|
|
393
|
+
prompt?.refreshPinnedPanels?.(loop);
|
|
394
|
+
},
|
|
379
395
|
onExit: () => { if (prompt) prompt.stop(); process.exit(0); },
|
|
380
396
|
onExpand: () => conn.renderer.expandLastOutput()
|
|
381
397
|
});
|
|
398
|
+
conn.onUsageUpdate = () => {
|
|
399
|
+
if (prompt && typeof prompt.refreshPinnedPanels === 'function') prompt.refreshPinnedPanels(loop);
|
|
400
|
+
};
|
|
382
401
|
if (surface) prompt.attachSurface(surface);
|
|
383
402
|
prompt.attach(conn.renderer);
|
|
384
403
|
prompt.start();
|
|
@@ -627,6 +646,7 @@ export async function chatMode({ home = false } = {}) {
|
|
|
627
646
|
if (commandResult.output && (commandResult.output.includes('Now using') || commandResult.output.includes('Active model switched') || commandResult.output.includes('Saved API key'))) {
|
|
628
647
|
conn.renderer.write(homeStatusLine({ config: loadConfig() }) + '\n');
|
|
629
648
|
}
|
|
649
|
+
if (prompt && typeof prompt.refreshPinnedPanels === 'function') prompt.refreshPinnedPanels(loop);
|
|
630
650
|
if (commandResult.effect === 'exit') { finish(); break; }
|
|
631
651
|
continue;
|
|
632
652
|
}
|
package/src/commands.js
CHANGED
|
@@ -2055,7 +2055,13 @@ export const COMMANDS = [
|
|
|
2055
2055
|
description: 'Show the current provider, autonomy mode and workspace scope',
|
|
2056
2056
|
dialogTitle: 'Status',
|
|
2057
2057
|
// One builder, shared with `causyne status`, so status output cannot drift.
|
|
2058
|
-
run: (argv, ctx) =>
|
|
2058
|
+
run: (argv, ctx = {}) => {
|
|
2059
|
+
if (ctx.prompt && typeof ctx.prompt.toggleStatusCard === 'function') {
|
|
2060
|
+
ctx.prompt.toggleStatusCard(ctx.loop);
|
|
2061
|
+
return ok('', { effect: 'silent' });
|
|
2062
|
+
}
|
|
2063
|
+
return ok(buildStatusText({ loop: ctx.loop || null }));
|
|
2064
|
+
}
|
|
2059
2065
|
},
|
|
2060
2066
|
|
|
2061
2067
|
{
|
|
@@ -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;
|