@causyne/agent 1.20.25 → 1.20.28
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/native-skills/android/android-debugging-and-testing/SKILL.md +1 -1
- package/package.json +1 -1
- package/src/agentLoop.js +60 -4
- package/src/agentLoop.ts +56 -4
- package/src/browser/causyneBrowser.js +1 -1
- package/src/browser/causyneBrowser.ts +1 -1
- package/src/browser/searchProviders.js +1 -1
- package/src/browser/searchProviders.ts +1 -1
- package/src/compiledSkills.js +3 -1
- package/src/decideTools.js +9 -1
- package/src/decideTools.ts +7 -1
- package/src/dynamicCatalogue.js +3 -1
- package/src/dynamicCatalogue.ts +3 -1
- package/src/launchIntent.js +1 -1
- package/src/launchIntent.ts +1 -1
- package/src/mcp/mcpRegistry.js +6 -2
- package/src/mcp/mcpRegistry.ts +5 -2
- package/src/memory/actrRanker.js +78 -0
- package/src/memory/actrRanker.ts +111 -0
- package/src/memory/contextBudget.js +131 -0
- package/src/memory/contextBudget.ts +155 -0
- package/src/memory/episodicStore.js +651 -0
- package/src/memory/episodicStore.ts +787 -0
- package/src/memory/episodicTypes.js +8 -0
- package/src/memory/episodicTypes.ts +124 -0
- package/src/memory/nearDuplicate.js +179 -0
- package/src/memory/nearDuplicate.ts +232 -0
- package/src/memory/symbolFolder.js +301 -0
- package/src/memory/symbolFolder.ts +327 -0
- package/src/toolPacks.js +1 -0
- package/src/toolPacks.ts +1 -0
- package/src/tools/desktopOpen.js +9 -2
- package/src/tools/desktopOpen.ts +8 -2
- package/src/tools/memoryRecall.js +211 -0
- package/src/tools/memoryRecall.ts +251 -0
- package/src/tools/nativeEngine.js +16 -2
- package/src/tools/nativeEngine.ts +16 -2
- package/src/tools/registry.js +2 -1
- package/src/tools/subagentOrchestrator.js +3 -2
- package/src/tools/sysRun.js +76 -7
- package/src/tools/sysRun.ts +82 -7
- package/src/tools/toolSelfRepair.js +4 -1
- package/src/tools/toolSelfRepair.ts +4 -1
- package/src/toolsList.js +1 -0
- package/src/toolsList.ts +1 -0
|
@@ -21,7 +21,7 @@ Diagnose runtime issues, stream-install APKs, launch activities, and capture cra
|
|
|
21
21
|
- **Done when:** `adb install` output explicitly returns `Performing Streamed Install` and `Success`.
|
|
22
22
|
|
|
23
23
|
3. Launch and verify foreground Activity lifecycle.
|
|
24
|
-
- Run `adb -s <serial> shell am start -n <package>/<activity>`.
|
|
24
|
+
- Run `adb -s <serial> shell am start -W -n <package>/<activity>`. The `-W` flag forces the ActivityManager to wait until launch and foreground resume are complete before returning, eliminating timing race conditions.
|
|
25
25
|
- Do not rely on chaining `sleep && pidof` in compound expressions, as timing differences cause exit code 1. Instead, query the activity manager directly:
|
|
26
26
|
`adb -s <serial> shell dumpsys activity activities | grep -E "mResumedActivity|topResumedActivity"`
|
|
27
27
|
- Confirm the target activity matches the resumed activity record.
|
package/package.json
CHANGED
package/src/agentLoop.js
CHANGED
|
@@ -20,6 +20,7 @@ import { getMemoryContextString } from './memory.js';
|
|
|
20
20
|
import { MemoryManager } from './memoryManager.js';
|
|
21
21
|
import { cortexDb } from './cortex/vectorDb.js';
|
|
22
22
|
import { buildStructuralSummary, condenseAndSave } from './cortex/autoCondenser.js';
|
|
23
|
+
import { episodicStore, compileToolObservation } from './memory/episodicStore.js';
|
|
23
24
|
import { buildCodexStyleSummary, compactSessionMessages, autoCompactIfUnderPressure } from './core/contextCompactor.js';
|
|
24
25
|
import { analyzeTask, buildTaskBrief } from './taskShape.js';
|
|
25
26
|
import { lookupPlan, recordPlan, recordPlanAsync, recordMiss, renderPlanHint, toStep, recordAPCPipelineLatency, lookupAlternativeStep, failureClass } from './planCache.js';
|
|
@@ -298,6 +299,14 @@ You possess native reverse engineering capabilities powered by the Reverse Engin
|
|
|
298
299
|
- **Prefer REST APIs (curl) for External Services**: When interacting with external services (like web, email, chat), prioritize finding and using official REST APIs via \`curl\` or simple scripts over browser scraping.
|
|
299
300
|
- **Web/UI Verification Requirement**: Prefer \`browser_act\` preview for static workspace HTML and ES modules; it does not need a separate HTTP server. Use \`sysRunBg\` only when a real application server is required. Do not kill unrelated processes to claim a port. For web development, UI components, and frontend applications, ALWAYS verify your rendered output before concluding. Use \`browser_act\` (preview and snapshot) or \`screenshot\`/\`vision_inspect_ui\` to inspect the visual/DOM state of your web pages. Report DOM inspection separately from visual inspection; only claim visual inspection when you actually receive and inspect image pixels.
|
|
300
301
|
|
|
302
|
+
# Execution Environment & Toolchains in sysRun
|
|
303
|
+
- Subprocesses executed via \`sysRun\` have an enriched toolchain environment automatically configured:
|
|
304
|
+
1. **Android SDK**: \`ANDROID_HOME\`, \`ANDROID_SDK_ROOT\`, \`platform-tools\` (\`adb\`), \`cmdline-tools\`, \`emulator\`, and \`build-tools\` are already pre-configured in \`PATH\`. You do NOT need to prepend \`export PATH=...\`.
|
|
305
|
+
2. **Java JDK**: \`JAVA_HOME\` and JDK bin directories are automatically discovered and set in the environment. You do NOT need to prepend \`export JAVA_HOME=...\`.
|
|
306
|
+
3. **Local Binaries & Package Managers**: \`~/.local/bin\` (where official CLIs such as Google's \`android\` CLI reside), \`/opt/homebrew/bin\`, and language runtimes are pre-configured in \`PATH\`.
|
|
307
|
+
4. **Activity Launch Verification**: When launching an Activity via ADB, use \`adb -s <serial> shell am start -W -n <package>/<activity>\` (\`-W\` waits for the activity launch to complete before returning), or query resumed activities via \`dumpsys activity activities\`.
|
|
308
|
+
5. **Multiple Emulators/Devices**: When multiple devices or emulators are connected, specify \`-s <serial>\` (e.g. \`adb -s emulator-5554 ...\`) or set \`export ANDROID_SERIAL=<serial>\`.
|
|
309
|
+
|
|
301
310
|
# Universal Tool Calling & Registry Discipline
|
|
302
311
|
1. **Strict Registry Adherence**: Use ONLY the tools declared in the catalogue. Invoke tools using exact parameter names specified in the schema. Do not invent or rename parameters.
|
|
303
312
|
2. **Valid JSON Formatting**: All tool call arguments must be valid JSON objects. Never include raw unescaped newlines or trailing commas inside argument strings.
|
|
@@ -882,7 +891,14 @@ export class AgentLoop {
|
|
|
882
891
|
catch (e) {
|
|
883
892
|
this.debugLog(`plan cache hint skipped: ${e.message}`);
|
|
884
893
|
}
|
|
885
|
-
|
|
894
|
+
let episodicContext = '';
|
|
895
|
+
try {
|
|
896
|
+
episodicContext = episodicStore.buildStartupEpisodicContext(this.workspaceRoot);
|
|
897
|
+
}
|
|
898
|
+
catch (e) {
|
|
899
|
+
this.debugLog(`episodic context build skipped: ${e.message}`);
|
|
900
|
+
}
|
|
901
|
+
return { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext };
|
|
886
902
|
}
|
|
887
903
|
rearmAbortController() {
|
|
888
904
|
this.abortController = new AbortController();
|
|
@@ -974,7 +990,7 @@ export class AgentLoop {
|
|
|
974
990
|
'fs_read', 'fs_list', 'fs_find', 'fs_search',
|
|
975
991
|
'code_search_ast', 'code_list_symbols', 'code_search_ripgrep', 'codebase_search',
|
|
976
992
|
'web_fetch', 'web_search', 'pdf_read', 'fs_read_skill',
|
|
977
|
-
'check_system_specs', 'process_list', 'view_image'
|
|
993
|
+
'check_system_specs', 'process_list', 'view_image', 'memory_recall'
|
|
978
994
|
]);
|
|
979
995
|
/** How many reads may be in flight at once. */
|
|
980
996
|
static PREFETCH_CONCURRENCY = 6;
|
|
@@ -1913,7 +1929,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
1913
1929
|
if (!this.staticContext) {
|
|
1914
1930
|
this.staticContext = await this.buildStaticContext();
|
|
1915
1931
|
}
|
|
1916
|
-
const { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint } = this.staticContext;
|
|
1932
|
+
const { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext } = this.staticContext;
|
|
1917
1933
|
// --- WORKSPACE AWARENESS ---
|
|
1918
1934
|
// perception.buildContext() output used to be computed and discarded,
|
|
1919
1935
|
// leaving the agent blind and forcing it to rediscover the project with
|
|
@@ -2019,7 +2035,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2019
2035
|
// is byte-identical every step; cached.
|
|
2020
2036
|
{
|
|
2021
2037
|
role: 'system',
|
|
2022
|
-
content: `${providerPrompt}${designContext}${workspaceSummary}${lessonsLearned}${planHint ? '\n' + planHint + '\n' : ''}${antiRepeatDirective}\n${universalSkillsContext}`,
|
|
2038
|
+
content: `${providerPrompt}${designContext}${workspaceSummary}${lessonsLearned}${episodicContext ? '\n\n' + episodicContext : ''}${planHint ? '\n' + planHint + '\n' : ''}${antiRepeatDirective}\n${universalSkillsContext}`,
|
|
2023
2039
|
cacheAnchor: true
|
|
2024
2040
|
},
|
|
2025
2041
|
// [4] THE INVOKED SKILL, when the user named one.
|
|
@@ -2309,6 +2325,18 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2309
2325
|
...(isFailed ? { error: action.detail || `${action.name} failed` } : {})
|
|
2310
2326
|
};
|
|
2311
2327
|
coldObserver.recordToolOutcome(this.taskId, action.name, actionArgs, actionOutcome);
|
|
2328
|
+
try {
|
|
2329
|
+
const compiledObs = compileToolObservation({
|
|
2330
|
+
taskId: this.taskId,
|
|
2331
|
+
workspace: this.workspaceRoot,
|
|
2332
|
+
toolName: action.name,
|
|
2333
|
+
args: actionArgs,
|
|
2334
|
+
result: actionOutcome
|
|
2335
|
+
});
|
|
2336
|
+
if (compiledObs)
|
|
2337
|
+
episodicStore.recordObservation(compiledObs);
|
|
2338
|
+
}
|
|
2339
|
+
catch { /* never block peer action on episodic recording */ }
|
|
2312
2340
|
const recovery = this.timeMachine.observe(action.name, actionArgs, actionOutcome, coldObserver.getToolOutcomes(this.taskId));
|
|
2313
2341
|
// Pause now, not at the end of a potentially long peer turn.
|
|
2314
2342
|
// An abort is a yield checkpoint, not a user denial or task success.
|
|
@@ -3107,6 +3135,22 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3107
3135
|
catch (e) {
|
|
3108
3136
|
this.debugLog(`plan cache write skipped: ${e.message}`);
|
|
3109
3137
|
}
|
|
3138
|
+
try {
|
|
3139
|
+
const reqText = String(this.currentTaskPrompt || this.userPrompt || '').trim();
|
|
3140
|
+
const completedText = String(response.content || 'Completed task execution.').replace(/\s+/g, ' ').trim();
|
|
3141
|
+
if (reqText && (this.stepsCompleted > 0 || completedNativeActionIds.size > 0)) {
|
|
3142
|
+
episodicStore.recordSessionSummary({
|
|
3143
|
+
taskId: this.taskId,
|
|
3144
|
+
workspace: this.workspaceRoot,
|
|
3145
|
+
request: reqText.slice(0, 260),
|
|
3146
|
+
completed: completedText.slice(0, 320),
|
|
3147
|
+
learned: Array.isArray(this._implementationPlan) && this._implementationPlan.length > 0
|
|
3148
|
+
? `Completed ${this._implementationPlan.length}-step plan.`
|
|
3149
|
+
: ''
|
|
3150
|
+
});
|
|
3151
|
+
}
|
|
3152
|
+
}
|
|
3153
|
+
catch { /* never block completion on session summary recording */ }
|
|
3110
3154
|
auditLog.log({ event: 'task_complete', taskId: this.taskId, steps: this.stepsCompleted });
|
|
3111
3155
|
this.emitEvent({ type: 'task_complete', taskId: this.taskId });
|
|
3112
3156
|
break;
|
|
@@ -3661,6 +3705,18 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3661
3705
|
? { success: true, _is_image_marker: true, visionDelivered: imageCanReachModel, filename: result.filename, mimeType: result.mimeType }
|
|
3662
3706
|
: result;
|
|
3663
3707
|
coldObserver.recordToolOutcome(this.taskId, functionName, args, observedResult);
|
|
3708
|
+
try {
|
|
3709
|
+
const compiledObs = compileToolObservation({
|
|
3710
|
+
taskId: this.taskId,
|
|
3711
|
+
workspace: this.workspaceRoot,
|
|
3712
|
+
toolName: functionName,
|
|
3713
|
+
args: args || {},
|
|
3714
|
+
result: observedResult && typeof observedResult === 'object' ? observedResult : { success: true }
|
|
3715
|
+
});
|
|
3716
|
+
if (compiledObs)
|
|
3717
|
+
episodicStore.recordObservation(compiledObs);
|
|
3718
|
+
}
|
|
3719
|
+
catch { /* never block tool execution on episodic recording */ }
|
|
3664
3720
|
const recovery = this.timeMachine.observe(functionName, args, observedResult, coldObserver.getToolOutcomes(this.taskId));
|
|
3665
3721
|
const verdict = await this.handleRecovery(recovery, functionName);
|
|
3666
3722
|
if (result && (result.success === false || typeof result.error === 'string')) {
|
package/src/agentLoop.ts
CHANGED
|
@@ -22,6 +22,7 @@ import { getMemoryContextString } from './memory.js';
|
|
|
22
22
|
import { MemoryManager } from './memoryManager.js';
|
|
23
23
|
import { cortexDb } from './cortex/vectorDb.js';
|
|
24
24
|
import { buildStructuralSummary, condenseAndSave } from './cortex/autoCondenser.js';
|
|
25
|
+
import { episodicStore, compileToolObservation } from './memory/episodicStore.js';
|
|
25
26
|
import { buildCodexStyleSummary, compactSessionMessages, autoCompactIfUnderPressure } from './core/contextCompactor.js';
|
|
26
27
|
import { analyzeTask, buildTaskBrief } from './taskShape.js';
|
|
27
28
|
import {
|
|
@@ -380,6 +381,14 @@ You possess native reverse engineering capabilities powered by the Reverse Engin
|
|
|
380
381
|
- **Prefer REST APIs (curl) for External Services**: When interacting with external services (like web, email, chat), prioritize finding and using official REST APIs via \`curl\` or simple scripts over browser scraping.
|
|
381
382
|
- **Web/UI Verification Requirement**: Prefer \`browser_act\` preview for static workspace HTML and ES modules; it does not need a separate HTTP server. Use \`sysRunBg\` only when a real application server is required. Do not kill unrelated processes to claim a port. For web development, UI components, and frontend applications, ALWAYS verify your rendered output before concluding. Use \`browser_act\` (preview and snapshot) or \`screenshot\`/\`vision_inspect_ui\` to inspect the visual/DOM state of your web pages. Report DOM inspection separately from visual inspection; only claim visual inspection when you actually receive and inspect image pixels.
|
|
382
383
|
|
|
384
|
+
# Execution Environment & Toolchains in sysRun
|
|
385
|
+
- Subprocesses executed via \`sysRun\` have an enriched toolchain environment automatically configured:
|
|
386
|
+
1. **Android SDK**: \`ANDROID_HOME\`, \`ANDROID_SDK_ROOT\`, \`platform-tools\` (\`adb\`), \`cmdline-tools\`, \`emulator\`, and \`build-tools\` are already pre-configured in \`PATH\`. You do NOT need to prepend \`export PATH=...\`.
|
|
387
|
+
2. **Java JDK**: \`JAVA_HOME\` and JDK bin directories are automatically discovered and set in the environment. You do NOT need to prepend \`export JAVA_HOME=...\`.
|
|
388
|
+
3. **Local Binaries & Package Managers**: \`~/.local/bin\` (where official CLIs such as Google's \`android\` CLI reside), \`/opt/homebrew/bin\`, and language runtimes are pre-configured in \`PATH\`.
|
|
389
|
+
4. **Activity Launch Verification**: When launching an Activity via ADB, use \`adb -s <serial> shell am start -W -n <package>/<activity>\` (\`-W\` waits for the activity launch to complete before returning), or query resumed activities via \`dumpsys activity activities\`.
|
|
390
|
+
5. **Multiple Emulators/Devices**: When multiple devices or emulators are connected, specify \`-s <serial>\` (e.g. \`adb -s emulator-5554 ...\`) or set \`export ANDROID_SERIAL=<serial>\`.
|
|
391
|
+
|
|
383
392
|
# Universal Tool Calling & Registry Discipline
|
|
384
393
|
1. **Strict Registry Adherence**: Use ONLY the tools declared in the catalogue. Invoke tools using exact parameter names specified in the schema. Do not invent or rename parameters.
|
|
385
394
|
2. **Valid JSON Formatting**: All tool call arguments must be valid JSON objects. Never include raw unescaped newlines or trailing commas inside argument strings.
|
|
@@ -993,7 +1002,14 @@ export class AgentLoop {
|
|
|
993
1002
|
this.debugLog(`plan cache hint skipped: ${e.message}`);
|
|
994
1003
|
}
|
|
995
1004
|
|
|
996
|
-
|
|
1005
|
+
let episodicContext = '';
|
|
1006
|
+
try {
|
|
1007
|
+
episodicContext = episodicStore.buildStartupEpisodicContext(this.workspaceRoot);
|
|
1008
|
+
} catch (e: any) {
|
|
1009
|
+
this.debugLog(`episodic context build skipped: ${e.message}`);
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
return { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext };
|
|
997
1013
|
}
|
|
998
1014
|
|
|
999
1015
|
|
|
@@ -1085,7 +1101,7 @@ export class AgentLoop {
|
|
|
1085
1101
|
'fs_read', 'fs_list', 'fs_find', 'fs_search',
|
|
1086
1102
|
'code_search_ast', 'code_list_symbols', 'code_search_ripgrep', 'codebase_search',
|
|
1087
1103
|
'web_fetch', 'web_search', 'pdf_read', 'fs_read_skill',
|
|
1088
|
-
'check_system_specs', 'process_list', 'view_image'
|
|
1104
|
+
'check_system_specs', 'process_list', 'view_image', 'memory_recall'
|
|
1089
1105
|
]);
|
|
1090
1106
|
|
|
1091
1107
|
/** How many reads may be in flight at once. */
|
|
@@ -2021,7 +2037,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2021
2037
|
if (!this.staticContext) {
|
|
2022
2038
|
this.staticContext = await this.buildStaticContext();
|
|
2023
2039
|
}
|
|
2024
|
-
const { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint } = this.staticContext;
|
|
2040
|
+
const { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext } = this.staticContext;
|
|
2025
2041
|
|
|
2026
2042
|
// --- WORKSPACE AWARENESS ---
|
|
2027
2043
|
// perception.buildContext() output used to be computed and discarded,
|
|
@@ -2136,7 +2152,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2136
2152
|
// is byte-identical every step; cached.
|
|
2137
2153
|
{
|
|
2138
2154
|
role: 'system',
|
|
2139
|
-
content: `${providerPrompt}${designContext}${workspaceSummary}${lessonsLearned}${planHint ? '\n' + planHint + '\n' : ''}${antiRepeatDirective}\n${universalSkillsContext}`,
|
|
2155
|
+
content: `${providerPrompt}${designContext}${workspaceSummary}${lessonsLearned}${episodicContext ? '\n\n' + episodicContext : ''}${planHint ? '\n' + planHint + '\n' : ''}${antiRepeatDirective}\n${universalSkillsContext}`,
|
|
2140
2156
|
cacheAnchor: true
|
|
2141
2157
|
},
|
|
2142
2158
|
// [4] THE INVOKED SKILL, when the user named one.
|
|
@@ -2425,6 +2441,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2425
2441
|
...(isFailed ? { error: action.detail || `${action.name} failed` } : {})
|
|
2426
2442
|
};
|
|
2427
2443
|
coldObserver.recordToolOutcome(this.taskId, action.name, actionArgs, actionOutcome);
|
|
2444
|
+
try {
|
|
2445
|
+
const compiledObs = compileToolObservation({
|
|
2446
|
+
taskId: this.taskId,
|
|
2447
|
+
workspace: this.workspaceRoot,
|
|
2448
|
+
toolName: action.name,
|
|
2449
|
+
args: actionArgs,
|
|
2450
|
+
result: actionOutcome
|
|
2451
|
+
});
|
|
2452
|
+
if (compiledObs) episodicStore.recordObservation(compiledObs);
|
|
2453
|
+
} catch { /* never block peer action on episodic recording */ }
|
|
2428
2454
|
const recovery = this.timeMachine.observe(
|
|
2429
2455
|
action.name, actionArgs, actionOutcome, coldObserver.getToolOutcomes(this.taskId)
|
|
2430
2456
|
);
|
|
@@ -3275,6 +3301,22 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3275
3301
|
this.debugLog(`plan cache write skipped: ${e.message}`);
|
|
3276
3302
|
}
|
|
3277
3303
|
|
|
3304
|
+
try {
|
|
3305
|
+
const reqText = String(this.currentTaskPrompt || this.userPrompt || '').trim();
|
|
3306
|
+
const completedText = String(response.content || 'Completed task execution.').replace(/\s+/g, ' ').trim();
|
|
3307
|
+
if (reqText && (this.stepsCompleted > 0 || completedNativeActionIds.size > 0)) {
|
|
3308
|
+
episodicStore.recordSessionSummary({
|
|
3309
|
+
taskId: this.taskId,
|
|
3310
|
+
workspace: this.workspaceRoot,
|
|
3311
|
+
request: reqText.slice(0, 260),
|
|
3312
|
+
completed: completedText.slice(0, 320),
|
|
3313
|
+
learned: Array.isArray(this._implementationPlan) && this._implementationPlan.length > 0
|
|
3314
|
+
? `Completed ${this._implementationPlan.length}-step plan.`
|
|
3315
|
+
: ''
|
|
3316
|
+
});
|
|
3317
|
+
}
|
|
3318
|
+
} catch { /* never block completion on session summary recording */ }
|
|
3319
|
+
|
|
3278
3320
|
auditLog.log({ event: 'task_complete', taskId: this.taskId, steps: this.stepsCompleted });
|
|
3279
3321
|
this.emitEvent({ type: 'task_complete', taskId: this.taskId });
|
|
3280
3322
|
break;
|
|
@@ -3880,6 +3922,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3880
3922
|
? { success: true, _is_image_marker: true, visionDelivered: imageCanReachModel, filename: result.filename, mimeType: result.mimeType }
|
|
3881
3923
|
: result;
|
|
3882
3924
|
coldObserver.recordToolOutcome(this.taskId, functionName, args, observedResult);
|
|
3925
|
+
try {
|
|
3926
|
+
const compiledObs = compileToolObservation({
|
|
3927
|
+
taskId: this.taskId,
|
|
3928
|
+
workspace: this.workspaceRoot,
|
|
3929
|
+
toolName: functionName,
|
|
3930
|
+
args: args || {},
|
|
3931
|
+
result: observedResult && typeof observedResult === 'object' ? observedResult : { success: true }
|
|
3932
|
+
});
|
|
3933
|
+
if (compiledObs) episodicStore.recordObservation(compiledObs);
|
|
3934
|
+
} catch { /* never block tool execution on episodic recording */ }
|
|
3883
3935
|
const recovery = this.timeMachine.observe(
|
|
3884
3936
|
functionName, args, observedResult, coldObserver.getToolOutcomes(this.taskId)
|
|
3885
3937
|
);
|
|
@@ -1001,7 +1001,7 @@ export class CausyneBrowser {
|
|
|
1001
1001
|
if (nextCounter > MAX_SNAPSHOT_NODES)
|
|
1002
1002
|
break;
|
|
1003
1003
|
const frameUrl = frame.url();
|
|
1004
|
-
if (!frameUrl || frameUrl === 'about:blank' || frameUrl.startsWith('javascript:') || frameUrl.startsWith('data:')) {
|
|
1004
|
+
if (!frameUrl || frameUrl === 'about:blank' || frameUrl.startsWith('javascript:') || frameUrl.startsWith('data:') || frameUrl.startsWith('vbscript:')) {
|
|
1005
1005
|
continue;
|
|
1006
1006
|
}
|
|
1007
1007
|
if (IFRAME_SKIP_PATTERNS.some(pattern => pattern.test(frameUrl)))
|
|
@@ -1248,7 +1248,7 @@ export class CausyneBrowser {
|
|
|
1248
1248
|
for (const frame of childFrames.slice(0, MAX_IFRAMES_TO_PROCESS)) {
|
|
1249
1249
|
if (nextCounter > MAX_SNAPSHOT_NODES) break;
|
|
1250
1250
|
const frameUrl = frame.url();
|
|
1251
|
-
if (!frameUrl || frameUrl === 'about:blank' || frameUrl.startsWith('javascript:') || frameUrl.startsWith('data:')) {
|
|
1251
|
+
if (!frameUrl || frameUrl === 'about:blank' || frameUrl.startsWith('javascript:') || frameUrl.startsWith('data:') || frameUrl.startsWith('vbscript:')) {
|
|
1252
1252
|
continue;
|
|
1253
1253
|
}
|
|
1254
1254
|
if (IFRAME_SKIP_PATTERNS.some(pattern => pattern.test(frameUrl))) continue;
|
|
@@ -54,7 +54,7 @@ export function parseDuckDuckGoHtml(html) {
|
|
|
54
54
|
let href = decodeEntities(anchor[1] ?? '');
|
|
55
55
|
try {
|
|
56
56
|
const candidate = new URL(href, 'https://html.duckduckgo.com/');
|
|
57
|
-
if (candidate.hostname.endsWith('duckduckgo.com') && candidate.pathname.startsWith('/l/')) {
|
|
57
|
+
if ((candidate.hostname === 'duckduckgo.com' || candidate.hostname.endsWith('.duckduckgo.com')) && candidate.pathname.startsWith('/l/')) {
|
|
58
58
|
href = candidate.searchParams.get('uddg') ?? href;
|
|
59
59
|
}
|
|
60
60
|
}
|
|
@@ -64,7 +64,7 @@ export function parseDuckDuckGoHtml(html: string): SearchResult[] {
|
|
|
64
64
|
let href = decodeEntities(anchor[1] ?? '');
|
|
65
65
|
try {
|
|
66
66
|
const candidate = new URL(href, 'https://html.duckduckgo.com/');
|
|
67
|
-
if (candidate.hostname.endsWith('duckduckgo.com') && candidate.pathname.startsWith('/l/')) {
|
|
67
|
+
if ((candidate.hostname === 'duckduckgo.com' || candidate.hostname.endsWith('.duckduckgo.com')) && candidate.pathname.startsWith('/l/')) {
|
|
68
68
|
href = candidate.searchParams.get('uddg') ?? href;
|
|
69
69
|
}
|
|
70
70
|
} catch {
|
package/src/compiledSkills.js
CHANGED
|
@@ -693,7 +693,9 @@ export const COMPILED_SKILLS = {
|
|
|
693
693
|
"eamed Install` and `Success`.\n",
|
|
694
694
|
"\n",
|
|
695
695
|
"3. Launch and verify foreground Activity lifecycle.\n",
|
|
696
|
-
" - Run `adb -s <serial> shell am start -n <package>/<activity
|
|
696
|
+
" - Run `adb -s <serial> shell am start -W -n <package>/<activity>`. The `",
|
|
697
|
+
"-W` flag forces the ActivityManager to wait until launch and foreground res",
|
|
698
|
+
"ume are complete before returning, eliminating timing race conditions.\n",
|
|
697
699
|
" - Do not rely on chaining `sleep && pidof` in compound expressions, as t",
|
|
698
700
|
"iming differences cause exit code 1. Instead, query the activity manager di",
|
|
699
701
|
"rectly:\n",
|
package/src/decideTools.js
CHANGED
|
@@ -40,7 +40,8 @@ const TRIGGERS = [
|
|
|
40
40
|
{ pattern: /\b(kill|terminate|port \d+|processes?)\b/i, tools: ['process_list', 'proc_term'], why: 'process control' },
|
|
41
41
|
{ pattern: /\b(zip|unzip|archive|extract|tarball)\b/i, tools: ['archive'], why: 'archive handling' },
|
|
42
42
|
{ pattern: /\b(sub-?agents?|in parallel|delegate)\b/i, tools: ['agent_subagent_orchestrate'], why: 'delegation' },
|
|
43
|
-
{ pattern: /\b(symbols?|definitions?|ast)\b/i, tools: ['code_list_symbols', 'code_search_ast'], why: 'structural code search' },
|
|
43
|
+
{ pattern: /\b(symbols?|definitions?|ast|outline|fold)\b/i, tools: ['code_list_symbols', 'code_search_ast', 'memory_recall'], why: 'structural code search' },
|
|
44
|
+
{ pattern: /\b(past session|previous session|episodic|remember|recall|history|earlier fix|memory_recall|memory_write)\b/i, tools: ['memory_recall', 'memory_write'], why: 'episodic memory recall' },
|
|
44
45
|
{ pattern: /\b(syntax|compile|typecheck|lint)\b/i, tools: ['code_verify_syntax'], why: 'static check' },
|
|
45
46
|
{ pattern: /\b(godot|\.tscn|gdscript)\b/i, tools: ['godot_act', 'game_scene_build'], why: 'Godot work' },
|
|
46
47
|
{ pattern: /\b(clipboard)\b/i, tools: ['clipboard'], why: 'clipboard' },
|
|
@@ -138,6 +139,13 @@ export function decideTools(input) {
|
|
|
138
139
|
}
|
|
139
140
|
if ((input.cachedTools?.length ?? 0) > 0)
|
|
140
141
|
reasons.push('proven route');
|
|
142
|
+
if (/\b(memory_recall|memory_write|episodic|past session|previous session|symbol outline|folded? symbol)\b/i.test(prompt)) {
|
|
143
|
+
const intentMemory = toolsForText(prompt, input.list);
|
|
144
|
+
for (const name of intentMemory.tools)
|
|
145
|
+
tools.push(name);
|
|
146
|
+
for (const why of intentMemory.reasons)
|
|
147
|
+
reasons.push(why);
|
|
148
|
+
}
|
|
141
149
|
}
|
|
142
150
|
if (input.text) {
|
|
143
151
|
const found = toolsForText(input.text, input.list);
|
package/src/decideTools.ts
CHANGED
|
@@ -87,7 +87,8 @@ const TRIGGERS: readonly Trigger[] = [
|
|
|
87
87
|
{ pattern: /\b(kill|terminate|port \d+|processes?)\b/i, tools: ['process_list', 'proc_term'], why: 'process control' },
|
|
88
88
|
{ pattern: /\b(zip|unzip|archive|extract|tarball)\b/i, tools: ['archive'], why: 'archive handling' },
|
|
89
89
|
{ pattern: /\b(sub-?agents?|in parallel|delegate)\b/i, tools: ['agent_subagent_orchestrate'], why: 'delegation' },
|
|
90
|
-
{ pattern: /\b(symbols?|definitions?|ast)\b/i, tools: ['code_list_symbols', 'code_search_ast'], why: 'structural code search' },
|
|
90
|
+
{ pattern: /\b(symbols?|definitions?|ast|outline|fold)\b/i, tools: ['code_list_symbols', 'code_search_ast', 'memory_recall'], why: 'structural code search' },
|
|
91
|
+
{ pattern: /\b(past session|previous session|episodic|remember|recall|history|earlier fix|memory_recall|memory_write)\b/i, tools: ['memory_recall', 'memory_write'], why: 'episodic memory recall' },
|
|
91
92
|
{ pattern: /\b(syntax|compile|typecheck|lint)\b/i, tools: ['code_verify_syntax'], why: 'static check' },
|
|
92
93
|
{ pattern: /\b(godot|\.tscn|gdscript)\b/i, tools: ['godot_act', 'game_scene_build'], why: 'Godot work' },
|
|
93
94
|
{ pattern: /\b(clipboard)\b/i, tools: ['clipboard'], why: 'clipboard' },
|
|
@@ -176,6 +177,11 @@ export function decideTools(input: DecideToolsInput): ToolDecision {
|
|
|
176
177
|
// A cached route admits IDs only, never an entire domain or permissions.
|
|
177
178
|
}
|
|
178
179
|
if ((input.cachedTools?.length ?? 0) > 0) reasons.push('proven route');
|
|
180
|
+
if (/\b(memory_recall|memory_write|episodic|past session|previous session|symbol outline|folded? symbol)\b/i.test(prompt)) {
|
|
181
|
+
const intentMemory = toolsForText(prompt, input.list);
|
|
182
|
+
for (const name of intentMemory.tools) tools.push(name);
|
|
183
|
+
for (const why of intentMemory.reasons) reasons.push(why);
|
|
184
|
+
}
|
|
179
185
|
}
|
|
180
186
|
|
|
181
187
|
if (input.text) {
|
package/src/dynamicCatalogue.js
CHANGED
|
@@ -197,7 +197,9 @@ export function computeProviderAuthFingerprint(provider, config = {}) {
|
|
|
197
197
|
}
|
|
198
198
|
else {
|
|
199
199
|
const key = config.apiKey || (config.providerKeys && config.providerKeys[norm]) || '';
|
|
200
|
-
const keyDigest = key
|
|
200
|
+
const keyDigest = key
|
|
201
|
+
? crypto.scryptSync(key, 'causyne-catalog-cache-salt', 16).toString('hex').slice(0, 12)
|
|
202
|
+
: 'nokey';
|
|
201
203
|
parts.push(keyDigest, config.baseUrl || '');
|
|
202
204
|
}
|
|
203
205
|
return crypto.createHash('sha256').update(parts.join('|')).digest('hex').slice(0, 16);
|
package/src/dynamicCatalogue.ts
CHANGED
|
@@ -226,7 +226,9 @@ export function computeProviderAuthFingerprint(
|
|
|
226
226
|
}
|
|
227
227
|
} else {
|
|
228
228
|
const key = config.apiKey || (config.providerKeys && config.providerKeys[norm]) || '';
|
|
229
|
-
const keyDigest = key
|
|
229
|
+
const keyDigest = key
|
|
230
|
+
? crypto.scryptSync(key, 'causyne-catalog-cache-salt', 16).toString('hex').slice(0, 12)
|
|
231
|
+
: 'nokey';
|
|
230
232
|
parts.push(keyDigest, config.baseUrl || '');
|
|
231
233
|
}
|
|
232
234
|
|
package/src/launchIntent.js
CHANGED
|
@@ -3,7 +3,7 @@ const CHANGE_VERBS = /\b(create|build|make|write|edit|fix|modify|change|update|i
|
|
|
3
3
|
const SERVER_COMMAND = /^\s*(?:python(?:3(?:\.\d+)?)?\s+(?:-u\s+)?(?:\S*\/)?server\.py\b|python(?:3(?:\.\d+)?)?\s+-m\s+http\.server\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve)\b|(?:npx|bunx)\s+(?:vite|next\s+dev|http-server)\b|uvicorn\b|gunicorn\b|flask\s+run\b)/i;
|
|
4
4
|
const READ_ONLY_COMMAND = /^\s*(?:pwd|ls|rg|grep|cat|head|tail|find|which|where|ps|pgrep|lsof|netstat|ss|git\s+(?:status|diff|log|show)|node\s+(?:-v|--version)|python(?:3(?:\.\d+)?)?\s+(?:-V|--version))\b/i;
|
|
5
5
|
const OPEN_COMMAND = /^\s*(?:open|xdg-open|start)\s+\S+/i;
|
|
6
|
-
const LOCAL_HEALTH_CHECK = /^\s*curl\
|
|
6
|
+
const LOCAL_HEALTH_CHECK = /^\s*curl\b[^;&|><`$()]*https?:\/\/(?:localhost|127\.0\.0\.1):\d+(?:\/\S*)?\s*$/i;
|
|
7
7
|
const PORT_CLEANUP_COMMAND = /^\s*(?:pkill|kill|fuser)\b/i;
|
|
8
8
|
const MUTATION_TOOLS = new Set([
|
|
9
9
|
'fs_write', 'fs_edit', 'fs_delete', 'fs_move',
|
package/src/launchIntent.ts
CHANGED
|
@@ -3,7 +3,7 @@ const CHANGE_VERBS = /\b(create|build|make|write|edit|fix|modify|change|update|i
|
|
|
3
3
|
const SERVER_COMMAND = /^\s*(?:python(?:3(?:\.\d+)?)?\s+(?:-u\s+)?(?:\S*\/)?server\.py\b|python(?:3(?:\.\d+)?)?\s+-m\s+http\.server\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve)\b|(?:npx|bunx)\s+(?:vite|next\s+dev|http-server)\b|uvicorn\b|gunicorn\b|flask\s+run\b)/i;
|
|
4
4
|
const READ_ONLY_COMMAND = /^\s*(?:pwd|ls|rg|grep|cat|head|tail|find|which|where|ps|pgrep|lsof|netstat|ss|git\s+(?:status|diff|log|show)|node\s+(?:-v|--version)|python(?:3(?:\.\d+)?)?\s+(?:-V|--version))\b/i;
|
|
5
5
|
const OPEN_COMMAND = /^\s*(?:open|xdg-open|start)\s+\S+/i;
|
|
6
|
-
const LOCAL_HEALTH_CHECK = /^\s*curl\
|
|
6
|
+
const LOCAL_HEALTH_CHECK = /^\s*curl\b[^;&|><`$()]*https?:\/\/(?:localhost|127\.0\.0\.1):\d+(?:\/\S*)?\s*$/i;
|
|
7
7
|
const PORT_CLEANUP_COMMAND = /^\s*(?:pkill|kill|fuser)\b/i;
|
|
8
8
|
|
|
9
9
|
const MUTATION_TOOLS = new Set([
|
package/src/mcp/mcpRegistry.js
CHANGED
|
@@ -229,9 +229,13 @@ export function parseToolName(name) {
|
|
|
229
229
|
return null;
|
|
230
230
|
const rest = name.slice(NAMESPACE.length);
|
|
231
231
|
const separator = rest.indexOf('__');
|
|
232
|
-
if (separator <= 0
|
|
232
|
+
if (separator <= 0)
|
|
233
233
|
return null;
|
|
234
|
-
|
|
234
|
+
const server = rest.slice(0, separator);
|
|
235
|
+
const tool = rest.slice(separator + 2);
|
|
236
|
+
if (!server || !tool)
|
|
237
|
+
return null;
|
|
238
|
+
return { server, tool };
|
|
235
239
|
}
|
|
236
240
|
export async function connectServer(name) {
|
|
237
241
|
const definition = configuredServers().find(server => server.name === name);
|
package/src/mcp/mcpRegistry.ts
CHANGED
|
@@ -262,8 +262,11 @@ export function parseToolName(name: unknown): { server: string; tool: string } |
|
|
|
262
262
|
if (!isMcpToolName(name)) return null;
|
|
263
263
|
const rest = name.slice(NAMESPACE.length);
|
|
264
264
|
const separator = rest.indexOf('__');
|
|
265
|
-
if (separator <= 0
|
|
266
|
-
|
|
265
|
+
if (separator <= 0) return null;
|
|
266
|
+
const server = rest.slice(0, separator);
|
|
267
|
+
const tool = rest.slice(separator + 2);
|
|
268
|
+
if (!server || !tool) return null;
|
|
269
|
+
return { server, tool };
|
|
267
270
|
}
|
|
268
271
|
|
|
269
272
|
export async function connectServer(name: string): Promise<McpClient> {
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/memory/actrRanker.ts
|
|
3
|
+
* ACT-R Cognitive Base-Level Activation Ranking for Causyne Episodic Memory.
|
|
4
|
+
*
|
|
5
|
+
* Ranks observations using Anderson's ACT-R power-law decay and reinforcement formula:
|
|
6
|
+
* score = ln(1 + t_created^(-d) + alpha * sum(t_reinforce^(-d)))
|
|
7
|
+
*
|
|
8
|
+
* Preserves a recency head of `ceil(count / 4)` so brand-new observations remain
|
|
9
|
+
* at the top of the context while repeatedly reinforced architectural decisions
|
|
10
|
+
* and bugfixes from older sessions climb into the active budget.
|
|
11
|
+
*
|
|
12
|
+
* Authorship: Strict TypeScript (Causyne Agent).
|
|
13
|
+
*/
|
|
14
|
+
const DEFAULT_DECAY = 0.5;
|
|
15
|
+
const DEFAULT_ALPHA = 0.5;
|
|
16
|
+
const DEFAULT_TIME_UNIT_MS = 3_600_000;
|
|
17
|
+
const DEFAULT_MIN_TIME_UNITS = 0.05;
|
|
18
|
+
/**
|
|
19
|
+
* Compute the ACT-R base-level activation strength for an observation.
|
|
20
|
+
*/
|
|
21
|
+
export function computeObservationStrength(createdAtEpochMs, reinforcedAtEpochsMs, nowMs = Date.now(), config = {}) {
|
|
22
|
+
const decay = config.decay ?? DEFAULT_DECAY;
|
|
23
|
+
const alpha = config.reinforcementAlpha ?? DEFAULT_ALPHA;
|
|
24
|
+
const timeUnitMs = config.timeUnitMs ?? DEFAULT_TIME_UNIT_MS;
|
|
25
|
+
const minUnits = config.minTimeUnits ?? DEFAULT_MIN_TIME_UNITS;
|
|
26
|
+
const ageUnits = Math.max(minUnits, (nowMs - createdAtEpochMs) / timeUnitMs);
|
|
27
|
+
let sumPower = Math.pow(ageUnits, -decay);
|
|
28
|
+
for (const rEpoch of reinforcedAtEpochsMs) {
|
|
29
|
+
if (!Number.isFinite(rEpoch))
|
|
30
|
+
continue;
|
|
31
|
+
const rAgeUnits = Math.max(minUnits, (nowMs - rEpoch) / timeUnitMs);
|
|
32
|
+
sumPower += alpha * Math.pow(rAgeUnits, -decay);
|
|
33
|
+
}
|
|
34
|
+
return Math.log(1 + sumPower);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Rank a candidate pool of observations (expected in DESC created_at_epoch order,
|
|
38
|
+
* or sorted internally) down to `count` items using ACT-R strength with recency head.
|
|
39
|
+
*
|
|
40
|
+
* The newest `ceil(count / 4)` items are pinned as the recency head so immediate
|
|
41
|
+
* session continuity is never displaced. The remaining `count - headCount` slots
|
|
42
|
+
* are filled from the rest of the pool ranked by ACT-R activation score (ties broken
|
|
43
|
+
* by newer createdAtEpochMs).
|
|
44
|
+
*/
|
|
45
|
+
export function rankObservationsByStrength(pool, count, nowMs = Date.now(), config = {}) {
|
|
46
|
+
if (count <= 0 || pool.length === 0)
|
|
47
|
+
return [];
|
|
48
|
+
const sortedByRecency = [...pool].sort((a, b) => {
|
|
49
|
+
if (b.createdAtEpochMs !== a.createdAtEpochMs) {
|
|
50
|
+
return b.createdAtEpochMs - a.createdAtEpochMs;
|
|
51
|
+
}
|
|
52
|
+
return b.id - a.id;
|
|
53
|
+
});
|
|
54
|
+
if (sortedByRecency.length <= count) {
|
|
55
|
+
return sortedByRecency;
|
|
56
|
+
}
|
|
57
|
+
const headCount = Math.min(sortedByRecency.length, Math.ceil(count / 4));
|
|
58
|
+
const head = sortedByRecency.slice(0, headCount);
|
|
59
|
+
const tailBudget = Math.max(0, count - head.length);
|
|
60
|
+
if (tailBudget === 0) {
|
|
61
|
+
return head;
|
|
62
|
+
}
|
|
63
|
+
const tailCandidates = sortedByRecency.slice(headCount);
|
|
64
|
+
const scored = tailCandidates.map((obs) => ({
|
|
65
|
+
obs,
|
|
66
|
+
score: computeObservationStrength(obs.createdAtEpochMs, obs.reinforcedAtEpochsMs, nowMs, config)
|
|
67
|
+
}));
|
|
68
|
+
scored.sort((a, b) => {
|
|
69
|
+
if (b.score !== a.score)
|
|
70
|
+
return b.score - a.score;
|
|
71
|
+
if (b.obs.createdAtEpochMs !== a.obs.createdAtEpochMs) {
|
|
72
|
+
return b.obs.createdAtEpochMs - a.obs.createdAtEpochMs;
|
|
73
|
+
}
|
|
74
|
+
return b.obs.id - a.obs.id;
|
|
75
|
+
});
|
|
76
|
+
const selectedTail = scored.slice(0, tailBudget).map((item) => item.obs);
|
|
77
|
+
return [...head, ...selectedTail];
|
|
78
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/memory/actrRanker.ts
|
|
3
|
+
* ACT-R Cognitive Base-Level Activation Ranking for Causyne Episodic Memory.
|
|
4
|
+
*
|
|
5
|
+
* Ranks observations using Anderson's ACT-R power-law decay and reinforcement formula:
|
|
6
|
+
* score = ln(1 + t_created^(-d) + alpha * sum(t_reinforce^(-d)))
|
|
7
|
+
*
|
|
8
|
+
* Preserves a recency head of `ceil(count / 4)` so brand-new observations remain
|
|
9
|
+
* at the top of the context while repeatedly reinforced architectural decisions
|
|
10
|
+
* and bugfixes from older sessions climb into the active budget.
|
|
11
|
+
*
|
|
12
|
+
* Authorship: Strict TypeScript (Causyne Agent).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { EpisodicObservation } from './episodicTypes.js';
|
|
16
|
+
|
|
17
|
+
export interface ActrStrengthConfig {
|
|
18
|
+
/** Power-law decay exponent `d` (default: 0.5, standard ACT-R). */
|
|
19
|
+
readonly decay?: number | undefined;
|
|
20
|
+
/** Weight `alpha` applied to each reinforcement event (default: 0.5). */
|
|
21
|
+
readonly reinforcementAlpha?: number | undefined;
|
|
22
|
+
/** Time scale in milliseconds (default: 3,600,000 ms = 1 hour). */
|
|
23
|
+
readonly timeUnitMs?: number | undefined;
|
|
24
|
+
/** Floor in time units to avoid singularity at t = 0 (default: 0.05). */
|
|
25
|
+
readonly minTimeUnits?: number | undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const DEFAULT_DECAY = 0.5;
|
|
29
|
+
const DEFAULT_ALPHA = 0.5;
|
|
30
|
+
const DEFAULT_TIME_UNIT_MS = 3_600_000;
|
|
31
|
+
const DEFAULT_MIN_TIME_UNITS = 0.05;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Compute the ACT-R base-level activation strength for an observation.
|
|
35
|
+
*/
|
|
36
|
+
export function computeObservationStrength(
|
|
37
|
+
createdAtEpochMs: number,
|
|
38
|
+
reinforcedAtEpochsMs: readonly number[],
|
|
39
|
+
nowMs: number = Date.now(),
|
|
40
|
+
config: ActrStrengthConfig = {}
|
|
41
|
+
): number {
|
|
42
|
+
const decay = config.decay ?? DEFAULT_DECAY;
|
|
43
|
+
const alpha = config.reinforcementAlpha ?? DEFAULT_ALPHA;
|
|
44
|
+
const timeUnitMs = config.timeUnitMs ?? DEFAULT_TIME_UNIT_MS;
|
|
45
|
+
const minUnits = config.minTimeUnits ?? DEFAULT_MIN_TIME_UNITS;
|
|
46
|
+
|
|
47
|
+
const ageUnits = Math.max(minUnits, (nowMs - createdAtEpochMs) / timeUnitMs);
|
|
48
|
+
let sumPower = Math.pow(ageUnits, -decay);
|
|
49
|
+
|
|
50
|
+
for (const rEpoch of reinforcedAtEpochsMs) {
|
|
51
|
+
if (!Number.isFinite(rEpoch)) continue;
|
|
52
|
+
const rAgeUnits = Math.max(minUnits, (nowMs - rEpoch) / timeUnitMs);
|
|
53
|
+
sumPower += alpha * Math.pow(rAgeUnits, -decay);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return Math.log(1 + sumPower);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Rank a candidate pool of observations (expected in DESC created_at_epoch order,
|
|
61
|
+
* or sorted internally) down to `count` items using ACT-R strength with recency head.
|
|
62
|
+
*
|
|
63
|
+
* The newest `ceil(count / 4)` items are pinned as the recency head so immediate
|
|
64
|
+
* session continuity is never displaced. The remaining `count - headCount` slots
|
|
65
|
+
* are filled from the rest of the pool ranked by ACT-R activation score (ties broken
|
|
66
|
+
* by newer createdAtEpochMs).
|
|
67
|
+
*/
|
|
68
|
+
export function rankObservationsByStrength(
|
|
69
|
+
pool: readonly EpisodicObservation[],
|
|
70
|
+
count: number,
|
|
71
|
+
nowMs: number = Date.now(),
|
|
72
|
+
config: ActrStrengthConfig = {}
|
|
73
|
+
): EpisodicObservation[] {
|
|
74
|
+
if (count <= 0 || pool.length === 0) return [];
|
|
75
|
+
|
|
76
|
+
const sortedByRecency = [...pool].sort((a, b) => {
|
|
77
|
+
if (b.createdAtEpochMs !== a.createdAtEpochMs) {
|
|
78
|
+
return b.createdAtEpochMs - a.createdAtEpochMs;
|
|
79
|
+
}
|
|
80
|
+
return b.id - a.id;
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
if (sortedByRecency.length <= count) {
|
|
84
|
+
return sortedByRecency;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const headCount = Math.min(sortedByRecency.length, Math.ceil(count / 4));
|
|
88
|
+
const head = sortedByRecency.slice(0, headCount);
|
|
89
|
+
const tailBudget = Math.max(0, count - head.length);
|
|
90
|
+
if (tailBudget === 0) {
|
|
91
|
+
return head;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const tailCandidates = sortedByRecency.slice(headCount);
|
|
95
|
+
const scored = tailCandidates.map((obs) => ({
|
|
96
|
+
obs,
|
|
97
|
+
score: computeObservationStrength(obs.createdAtEpochMs, obs.reinforcedAtEpochsMs, nowMs, config)
|
|
98
|
+
}));
|
|
99
|
+
|
|
100
|
+
scored.sort((a, b) => {
|
|
101
|
+
if (b.score !== a.score) return b.score - a.score;
|
|
102
|
+
if (b.obs.createdAtEpochMs !== a.obs.createdAtEpochMs) {
|
|
103
|
+
return b.obs.createdAtEpochMs - a.obs.createdAtEpochMs;
|
|
104
|
+
}
|
|
105
|
+
return b.obs.id - a.obs.id;
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
const selectedTail = scored.slice(0, tailBudget).map((item) => item.obs);
|
|
109
|
+
return [...head, ...selectedTail];
|
|
110
|
+
}
|
|
111
|
+
|