@crewx/memory 0.1.23-rc.254 → 0.1.23-rc.256

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/README.md CHANGED
@@ -1,7 +1,35 @@
1
1
  # @crewx/memory
2
2
 
3
+ ## Known limits
4
+
5
+ - On the POSIX replacement path (Darwin and Linux), replacing an entry with an extended ACL can drop that ACL. Windows replacement uses `ReplaceFileW` so the operating system carries the target ACL.
6
+ - A clean read racing a full write and recovery cycle is not detected.
7
+
3
8
  Memory engine for CrewX - markdown + frontmatter based long-term memory.
4
9
 
5
10
  ```bash
6
11
  crewx memory index <agent_id>
7
12
  ```
13
+
14
+ ## Native command routing
15
+
16
+ On supported npm installations, ordinary reads use the packaged Go reader: `index` (including `--full` and `--recent`), `get`/`read`, `find`, `list` (including `--category`, `--tag`, and `--json`), `recent`/`ls`, `stats`, and `tags` with or without a topic. CRUD writes (`save`, `update`, `delete`/`rm`, and `merge`) use the packaged Go writer by default on macOS, Linux, and Windows. Empty or invalid argument forms keep the existing Node validation behavior.
17
+
18
+ ```bash
19
+ crewx memory index <agent_id>
20
+ crewx memory index <agent_id> --full
21
+ crewx memory index <agent_id> --recent=30
22
+ crewx memory get <agent_id> <memory_id>
23
+ crewx memory read <agent_id> <memory_id>
24
+ crewx memory find <agent_id> "<non-empty query>"
25
+ crewx memory list <agent_id> --category=decision --tag=crewx,api
26
+ crewx memory list <agent_id> --json
27
+ crewx memory recent <agent_id> 30
28
+ crewx memory ls <agent_id> 30
29
+ crewx memory stats <agent_id>
30
+ crewx memory tags <agent_id> [topic]
31
+ ```
32
+
33
+ AI-backed commands, graph/mindmap, help, and unsupported invocations remain on the existing Node implementation. CrewX Desktop also stays on Node until shell-native packaging is available. Set `CREWX_MEMORY_RUNTIME=node` to force the existing implementation. `auto` is the default and falls back before execution when the command or packaged artifact lacks the required capability. `CREWX_MEMORY_RUNTIME=go` requires native support and reports an actionable error when unavailable. A native operation that has started is never retried in Node.
34
+
35
+ The package includes native artifacts for macOS arm64/amd64, Linux arm64/amd64, and Windows amd64. Runtime artifact lookup is confined to the installed `@crewx/memory` package; no downloads are performed.
package/SKILL.md CHANGED
@@ -8,6 +8,19 @@ metadata:
8
8
 
9
9
  # Memory V2 Skill
10
10
 
11
+ ## Native command routing
12
+
13
+ The default `auto` runtime uses the packaged Go reader for ordinary read commands and their existing options/aliases:
14
+
15
+ - `index` with `--full` and `--recent`
16
+ - `get` / `read`, and `find`
17
+ - `list` with `--category`, `--tag`, and `--json`
18
+ - `recent` / `ls`, `stats`, and `tags [topic]`
19
+
20
+ Empty or invalid argument forms keep the existing Node validation behavior. `auto` checks the packaged artifact's protocol capability before starting an operation and falls back before execution when unsupported. It never retries a failed native operation in Node. Set `CREWX_MEMORY_RUNTIME=node` to roll back explicitly; set `CREWX_MEMORY_RUNTIME=go` to require native support and fail with an actionable error when it is unavailable.
21
+
22
+ CRUD writes (`save`, `update`, `delete` / `rm`, and `merge`) use the packaged Go writer by default on macOS, Linux, and Windows. AI-backed commands, graph/mindmap, help, and other unsupported operations continue through the existing Node implementation. CrewX Desktop also stays on Node until shell-native packaging is available.
23
+
11
24
  A long-term memory management skill based on markdown + frontmatter.
12
25
 
13
26
  ## Installation
@@ -1,7 +1,8 @@
1
+ import { getMemoryConfig } from './settings';
2
+ export { getMemoryConfig };
1
3
  export declare const SUMMARIZER_FAILURE_THRESHOLD = 3;
2
4
  export declare const SUMMARIZE_LOCK_STALE_MS: number;
3
5
  import { MemoryEntry, SaveOptions, IndexOptions, ListOptions, UpdateOptions, DeleteOptions, MergeOptions, SummarizeOptions, SummaryResult, MemoryEngineConfig } from './types';
4
- export declare function getMemoryConfig(): Record<string, unknown>;
5
6
  export declare class MemoryEngine {
6
7
  private readonly dataDir;
7
8
  private readonly summaryDays;
@@ -13,6 +14,9 @@ export declare class MemoryEngine {
13
14
  private readonly searcherTimeout;
14
15
  private readonly searchIndexCache;
15
16
  constructor(config?: MemoryEngineConfig);
17
+ private nativeSettings;
18
+ private useNative;
19
+ private runNative;
16
20
  private getAgentDir;
17
21
  private getEntriesDir;
18
22
  private getEntryFilesFingerprint;
@@ -22,6 +26,7 @@ export declare class MemoryEngine {
22
26
  private createFindActionContext;
23
27
  private getSummaryPath;
24
28
  private getDirtySummaryPath;
29
+ private markSummaryDirty;
25
30
  private getSummarizeLockPath;
26
31
  private ensureDir;
27
32
  private generateId;
@@ -29,7 +34,6 @@ export declare class MemoryEngine {
29
34
  private getLocalISO8601;
30
35
  private getPrimaryTag;
31
36
  private toEntryTimestamp;
32
- private markSummaryDirty;
33
37
  private getSummarizerHealthPath;
34
38
  private readSummarizerHealth;
35
39
  private writeSummarizerHealth;
@@ -37,9 +41,11 @@ export declare class MemoryEngine {
37
41
  private recordSummarizerSuccess;
38
42
  private notifySummarizerDegraded;
39
43
  loadAllEntries(agentId: string): MemoryEntry[];
44
+ private loadAllEntriesRaw;
40
45
  private findEntryById;
41
46
  save(agentId: string, summary: string, category?: string, options?: SaveOptions): void;
42
47
  index(agentId: string, options?: IndexOptions): void;
48
+ private indexCaptured;
43
49
  private generateIndexContent;
44
50
  topic(agentId: string, topicName: string): void;
45
51
  recent(agentId: string, days?: number): void;
@@ -50,16 +56,24 @@ export declare class MemoryEngine {
50
56
  private toDateString;
51
57
  private readEntryBody;
52
58
  find(agentId: string, keyword: string): void;
59
+ private findCaptured;
53
60
  list(agentId: string, options?: ListOptions): void;
54
61
  stats(agentId: string): void;
55
62
  tags(agentId: string): void;
56
63
  get(agentId: string, memoryId: string): void;
64
+ private getCaptured;
57
65
  update(agentId: string, memoryId: string, options?: UpdateOptions): void;
58
66
  delete(agentId: string, memoryId: string, options?: DeleteOptions): void;
59
67
  merge(agentId: string, memoryId1: string, memoryId2: string, options?: MergeOptions): void;
60
68
  private buildFallbackSummary;
61
69
  private callSummarizer;
70
+ private captureSummarySnapshot;
71
+ private summaryPathExists;
72
+ private readMutationGeneration;
73
+ private readOptionalFile;
74
+ private publishSummarySnapshot;
62
75
  generateSummary(agentId: string, options?: SummarizeOptions): SummaryResult;
76
+ private generateSummaryFromSnapshot;
63
77
  summarize(agentId: string, options?: SummarizeOptions): void;
64
78
  private isSummarizeLockStale;
65
79
  private acquireSummarizeLock;
@@ -1,12 +1,12 @@
1
- "use strict";var v=exports&&exports.__importDefault||function($){return $&&$.__esModule?$:{"default":$}};Object.defineProperty(exports,"__esModule",{value:true});exports.CATEGORIES=exports.MemoryEngine=exports.SUMMARIZE_LOCK_STALE_MS=exports.SUMMARIZER_FAILURE_THRESHOLD=void 0;exports.getMemoryConfig=P;exports.createMemoryEngine=Z;const l=v(require("fs"));const D=v(require("path"));const N=require("child_process");const B=require("nanoid");const H=v(require("js-yaml"));const T=require("./parser");const j=require("./summarizer-failure");const _=require("@crewx/knowledge-core");const z=require("@crewx/sdk");exports.SUMMARIZER_FAILURE_THRESHOLD=3;const U=".summarizer-health.json";const M=50;function q(){const $=(0,z.resolveCrewxExecutable)({env:process.env,cwd:process.cwd()});if(!$.ok){const n=new Error((0,z.formatCrewxExecutableFailure)($));Object.assign(n,{code:"CLI_UNRESOLVABLE"});throw n}const e=(0,z.createCrewxChildInvocation)($,{baseEnv:process.env});const t=(0,z.resolveWindowsSpawnProgram)({command:e.command,env:e.env,cwd:process.cwd(),packageName:"crewx",allowShellFallback:true});const r=(0,z.materializeWindowsSpawnProgram)(t,e.args);return{command:r.command,args:r.argv,env:e.env,shell:r.shell,windowsHide:r.windowsHide}}function k($,e){const t=q();return(0,N.execFileSync)(t.command,[...t.args,...$],{...e,env:t.env,...t.shell===void 0?{}:{shell:t.shell},...t.windowsHide===void 0?{}:{windowsHide:t.windowsHide}})}exports.SUMMARIZE_LOCK_STALE_MS=10*60*1e3;function O($){const e=$.match(/📄 Response:\s*─+\s*([\s\S]*?)(?=📁 Working Directory|$)/);if(e?.[1]){const t=e[1].trim();const r=t.split("\n")[0]?.trim()??"";if(!r.startsWith("{")){return t}return I(t)}return I($)}function I($){const e=$.split("\n").filter(o=>o.trim().startsWith("{"));let t="";let r=false;for(const o of e){try{const i=JSON.parse(o);if(i.type==="message"&&i.role==="assistant"){r=true;if(i.content)t+=i.content}}catch(i){}}if(r)return t.trim()||null;const n=$.trim();if(n.length===0)return null;const s=n.split("\n")[0]?.trim()??"";if(s.startsWith("{"))return null;return n}function W(){try{return(0,N.execSync)("git rev-parse --show-toplevel",{encoding:"utf8"}).trim()}catch{return process.cwd()}}function P(){try{const $=process.env.CREWX_CONFIG??D.default.join(W(),"crewx.yaml");const e=l.default.readFileSync($,"utf8");const t=H.default.load(e);const r=t?.settings;return r?.memory??{}}catch{return{}}}class L{constructor(e={}){this.searchIndexCache=new Map;const t=P();this.dataDir=e.dataDir??process.env["MEMORY_DATA_DIR"]??D.default.resolve(process.cwd(),"memory");this.summaryDays=e.summaryDays??(t.summary_days!=null?Number(t.summary_days):void 0)??(parseInt(process.env["MEMORY_SUMMARY_DAYS"]??"",10)||7);this.recentDays=e.recentDays??(t.recent_days!=null?Number(t.recent_days):void 0)??(parseInt(process.env["MEMORY_RECENT_DAYS"]??"",10)||30);this.shortTermHours=e.shortTermHours??(t.short_term_hours!=null?Number(t.short_term_hours):void 0)??24;this.summarizerAgent=e.summarizerAgent??t.summarizer_agent??"@memory_summarizer";this.searcherAgent=e.searcherAgent??t.searcher_agent??"@memory_searcher";this.summarizerTimeout=e.summarizerTimeout??(t.summarizer_timeout!=null?Number(t.summarizer_timeout):void 0)??48e4;this.searcherTimeout=e.searcherTimeout??(t.searcher_timeout!=null?Number(t.searcher_timeout):void 0)??3e5}getAgentDir(e){return D.default.join(this.dataDir,e)}getEntriesDir(e){return D.default.join(this.getAgentDir(e),"entries")}getEntryFilesFingerprint(e){const t=this.getEntriesDir(e);if(!l.default.existsSync(t))return{files:[],fingerprint:""};const r=l.default.readdirSync(t).filter(s=>s.endsWith(".md")).sort();const n=r.map(s=>{const o=l.default.statSync(D.default.join(t,s));return`${s}\0${o.size}\0${o.mtimeMs}`}).join("");return{files:r,fingerprint:n}}buildSearchIndex(e,t){const r=this.getEntriesDir(e);const n=t.map(s=>{const o=l.default.readFileSync(D.default.join(r,s),"utf-8");const{data:i,content:d}=(0,T.parseFrontmatter)(o);return{...i,file:s,body:d}});return(0,_.createSearchIndex)(n,{summary:3,tags:2,body:1})}getSearchIndex(e){const t=this.getEntryFilesFingerprint(e);const r=this.searchIndexCache.get(e);if(r?.fingerprint===t.fingerprint){return{files:t.files,index:r.index}}const n=this.buildSearchIndex(e,t.files);this.searchIndexCache.set(e,{fingerprint:t.fingerprint,index:n});return{files:t.files,index:n}}invalidateSearchIndex(e){this.searchIndexCache.delete(e)}createFindActionContext(e,t,r){return{commandId:"memory.find",params:{agentId:e,query:t},resultTags:[...new Set(r.flatMap(n=>n.tags??[]))].slice(0,3),resultIds:r.slice(0,3).map(n=>n.id),resultCount:r.length}}getSummaryPath(e){return D.default.join(this.getAgentDir(e),"summary.md")}getDirtySummaryPath(e){return D.default.join(this.getAgentDir(e),".dirty-summary")}getSummarizeLockPath(){return D.default.join(this.dataDir,".summarize.lock")}ensureDir(e){if(!l.default.existsSync(e)){l.default.mkdirSync(e,{recursive:true})}}generateId(){return(0,B.nanoid)(6)}getToday(){return new Date().toISOString().slice(0,10)}getLocalISO8601(){const e=new Date;const t=-e.getTimezoneOffset();const r=t>=0?"+":"-";const n=String(Math.floor(Math.abs(t)/60)).padStart(2,"0");const s=String(Math.abs(t)%60).padStart(2,"0");const o=e.getFullYear();const i=String(e.getMonth()+1).padStart(2,"0");const d=String(e.getDate()).padStart(2,"0");const f=String(e.getHours()).padStart(2,"0");const a=String(e.getMinutes()).padStart(2,"0");const c=String(e.getSeconds()).padStart(2,"0");return`${o}-${i}-${d}T${f}:${a}:${c}${r}${n}:${s}`}getPrimaryTag(e){return e.tags?.[0]??"general"}toEntryTimestamp(e){if(e["created_at"])return String(e["created_at"]);const t=e["date"];const r=t&&typeof t==="object"&&typeof t.toISOString==="function"?t.toISOString().slice(0,10):String(t??"");if(r.includes("T"))return r;return r+"T09:00:00+09:00"}markSummaryDirty(e){this.ensureDir(this.getAgentDir(e));l.default.writeFileSync(this.getDirtySummaryPath(e),String(Date.now()),"utf-8")}getSummarizerHealthPath(){return D.default.join(this.dataDir,U)}readSummarizerHealth(){try{const e=l.default.readFileSync(this.getSummarizerHealthPath(),"utf-8");const t=JSON.parse(e);return{consecutiveFailures:typeof t.consecutiveFailures==="number"?t.consecutiveFailures:0,notified:Boolean(t.notified),lastError:t.lastError}}catch{return{consecutiveFailures:0,notified:false}}}writeSummarizerHealth(e){this.ensureDir(this.dataDir);l.default.writeFileSync(this.getSummarizerHealthPath(),JSON.stringify(e),"utf-8")}recordSummarizerFailure(e){const t=this.readSummarizerHealth();t.consecutiveFailures+=1;t.lastError=e.code||e.message?e:void 0;if(t.consecutiveFailures>=exports.SUMMARIZER_FAILURE_THRESHOLD&&!t.notified){this.notifySummarizerDegraded(t.consecutiveFailures,t.lastError);t.notified=true}this.writeSummarizerHealth(t)}recordSummarizerSuccess(){const e=this.readSummarizerHealth();if(e.consecutiveFailures===0&&!e.notified)return;this.writeSummarizerHealth({consecutiveFailures:0,notified:false})}notifySummarizerDegraded(e,t){try{k(["notify","AI memory summarization keeps failing \u2014 falling back to mechanical summaries","--level=warning","--body=callSummarizer(agent="+this.summarizerAgent+") failed "+e+" times in a row (last error: "+(0,j.formatSummarizerLastError)(t)+"), so summarization switched to the fallback (mechanical) path."],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:15e3})}catch(r){const n=r;console.error(`[memory] failed to send summarizer-health notify: ${n.message}`)}}loadAllEntries(e){const t=this.getEntriesDir(e);if(!l.default.existsSync(t))return[];const r=l.default.readdirSync(t).filter(s=>s.endsWith(".md"));const n=[];for(const s of r){const o=l.default.readFileSync(D.default.join(t,s),"utf-8");const{data:i,content:d}=(0,T.parseFrontmatter)(o);const f=d.replace(/^#[^\n]*\n*/m,"").trim();const a=Boolean(f)&&f!=="(Add details here)";const c=i;n.push({...c,file:s,hasBody:a})}n.sort((s,o)=>this.toEntryTimestamp(o).localeCompare(this.toEntryTimestamp(s)));return n}findEntryById(e,t){const r=this.getEntriesDir(e);if(!l.default.existsSync(r))return null;const n=l.default.readdirSync(r).filter(s=>s.endsWith(".md"));for(const s of n){const o=D.default.join(r,s);const i=l.default.readFileSync(o,"utf-8");const{data:d,content:f}=(0,T.parseFrontmatter)(i);if(d.id===t){return{file:s,filePath:o,data:d,content:f}}}return null}save(e,t,r="general",n={}){this.ensureDir(this.getEntriesDir(e));const s=this.generateId();const o=this.getLocalISO8601();const i=Array.isArray(n.tags)?n.tags:n.tags?n.tags.split(",").map(h=>h.trim()):[];const d=(0,T.stringifyFrontmatter)({id:s,type:"memory",date:o,category:r,tags:i,summary:t,...n.important?{important:true}:{}});const f=`${s}.md`;const a=D.default.join(this.getEntriesDir(e),f);const c=n.body??"(Add details here)";const m=`${d}
1
+ "use strict";var L=exports&&exports.__importDefault||function(S){return S&&S.__esModule?S:{"default":S}};Object.defineProperty(exports,"__esModule",{value:true});exports.CATEGORIES=exports.MemoryEngine=exports.SUMMARIZE_LOCK_STALE_MS=exports.SUMMARIZER_FAILURE_THRESHOLD=exports.getMemoryConfig=void 0;exports.createMemoryEngine=K;const d=L(require("fs"));const E=L(require("path"));const U=require("child_process");const G=require("nanoid");const b=require("./parser");const g=require("./storage");const D=require("./native-adapter");const j=require("./settings");Object.defineProperty(exports,"getMemoryConfig",{enumerable:true,get:function(){return j.getMemoryConfig}});const P=require("./summarizer-failure");const M=require("@crewx/knowledge-core");const N=require("@crewx/sdk");exports.SUMMARIZER_FAILURE_THRESHOLD=3;const Z=".summarizer-health.json";const _=50;function J(){const S=(0,N.resolveCrewxExecutable)({env:process.env,cwd:process.cwd()});if(!S.ok){const n=new Error((0,N.formatCrewxExecutableFailure)(S));Object.assign(n,{code:"CLI_UNRESOLVABLE"});throw n}const e=(0,N.createCrewxChildInvocation)(S,{baseEnv:process.env});const t=(0,N.resolveWindowsSpawnProgram)({command:e.command,env:e.env,cwd:process.cwd(),packageName:"crewx",allowShellFallback:true});const r=(0,N.materializeWindowsSpawnProgram)(t,e.args);return{command:r.command,args:r.argv,env:e.env,shell:r.shell,windowsHide:r.windowsHide}}function k(S,e){const t=J();return(0,U.execFileSync)(t.command,[...t.args,...S],{...e,env:t.env,...t.shell===void 0?{}:{shell:t.shell},...t.windowsHide===void 0?{}:{windowsHide:t.windowsHide}})}exports.SUMMARIZE_LOCK_STALE_MS=10*60*1e3;function z(S,e,t){let r=[];let n;let s=false;let o;try{o=(0,g.withRecoveredAgentReadSync)(S,i=>{r=[];n=void 0;s=false;if(i.recovered)t?.();const l=console.log;const u=console.error;console.log=(...a)=>r.push({method:"log",args:a});console.error=(...a)=>r.push({method:"error",args:a});try{o=e();return o}catch(a){n=a;s=true;return void 0}finally{console.log=l;console.error=u}})}catch(i){throw i}for(const i of r)console[i.method](...i.args);if(s)throw n;return o}function O(S,e){if(S===null||e===null)return S===e;return S.equals(e)}function B(S){const e=S.match(/📄 Response:\s*─+\s*([\s\S]*?)(?=📁 Working Directory|$)/);if(e?.[1]){const t=e[1].trim();const r=t.split("\n")[0]?.trim()??"";if(!r.startsWith("{")){return t}return H(t)}return H(S)}function H(S){const e=S.split("\n").filter(o=>o.trim().startsWith("{"));let t="";let r=false;for(const o of e){try{const i=JSON.parse(o);if(i.type==="message"&&i.role==="assistant"){r=true;if(i.content)t+=i.content}}catch(i){}}if(r)return t.trim()||null;const n=S.trim();if(n.length===0)return null;const s=n.split("\n")[0]?.trim()??"";if(s.startsWith("{"))return null;return n}class W{constructor(e={}){this.searchIndexCache=new Map;const t=(0,j.resolveEngineSettings)(e);this.dataDir=t.dataDir;this.summaryDays=t.summaryDays;this.recentDays=t.recentDays;this.shortTermHours=t.shortTermHours;this.summarizerAgent=t.summarizerAgent;this.searcherAgent=t.searcherAgent;this.summarizerTimeout=t.summarizerTimeout;this.searcherTimeout=t.searcherTimeout}nativeSettings(){return{dataDir:this.dataDir,summaryDays:this.summaryDays,recentDays:this.recentDays,shortTermHours:this.shortTermHours,summarizerAgent:this.summarizerAgent,searcherAgent:this.searcherAgent,summarizerTimeout:this.summarizerTimeout,searcherTimeout:this.searcherTimeout}}useNative(){const e=(0,D.nativeRuntimeMode)();if(e==="node")return false;if(e==="go")return true;return(0,D.isNativeAdapterAvailable)()}runNative(e,t=false){const r=e();(0,D.writeNativeOutput)(r);if(r.exitCode===0)return;if(t)process.exit(r.exitCode);throw new Error(r.stderr.trim()||r.stdout.trim()||`native memory command failed (exit ${r.exitCode})`)}getAgentDir(e){return E.default.join(this.dataDir,e)}getEntriesDir(e){return E.default.join(this.getAgentDir(e),"entries")}getEntryFilesFingerprint(e){const t=this.getEntriesDir(e);if(!d.default.existsSync(t))return{files:[],fingerprint:""};const r=d.default.readdirSync(t).filter(s=>s.endsWith(".md")).sort();const n=r.map(s=>{const o=d.default.statSync(E.default.join(t,s));return`${s}\0${o.size}\0${o.mtimeMs}`}).join("");return{files:r,fingerprint:n}}buildSearchIndex(e,t){const r=this.getEntriesDir(e);const n=t.map(s=>{const o=d.default.readFileSync(E.default.join(r,s),"utf-8");const{data:i,content:l}=(0,b.parseFrontmatter)(o);return{...i,file:s,body:l}});return(0,M.createSearchIndex)(n,{summary:3,tags:2,body:1})}getSearchIndex(e){const t=this.getEntryFilesFingerprint(e);const r=this.searchIndexCache.get(e);if(r?.fingerprint===t.fingerprint){return{files:t.files,index:r.index}}const n=this.buildSearchIndex(e,t.files);this.searchIndexCache.set(e,{fingerprint:t.fingerprint,index:n});return{files:t.files,index:n}}invalidateSearchIndex(e){this.searchIndexCache.delete(e)}createFindActionContext(e,t,r){return{commandId:"memory.find",params:{agentId:e,query:t},resultTags:[...new Set(r.flatMap(n=>n.tags??[]))].slice(0,3),resultIds:r.slice(0,3).map(n=>n.id),resultCount:r.length}}getSummaryPath(e){return E.default.join(this.getAgentDir(e),"summary.md")}getDirtySummaryPath(e){return E.default.join(this.getAgentDir(e),".dirty-summary")}markSummaryDirty(e){this.ensureDir(this.getAgentDir(e));d.default.writeFileSync(this.getDirtySummaryPath(e),String(Date.now()),"utf-8")}getSummarizeLockPath(){return E.default.join(this.dataDir,".summarize.lock")}ensureDir(e){if(!d.default.existsSync(e)){d.default.mkdirSync(e,{recursive:true})}}generateId(){return(0,G.nanoid)(6)}getToday(){return new Date().toISOString().slice(0,10)}getLocalISO8601(){const e=new Date;const t=-e.getTimezoneOffset();const r=t>=0?"+":"-";const n=String(Math.floor(Math.abs(t)/60)).padStart(2,"0");const s=String(Math.abs(t)%60).padStart(2,"0");const o=e.getFullYear();const i=String(e.getMonth()+1).padStart(2,"0");const l=String(e.getDate()).padStart(2,"0");const u=String(e.getHours()).padStart(2,"0");const a=String(e.getMinutes()).padStart(2,"0");const c=String(e.getSeconds()).padStart(2,"0");return`${o}-${i}-${l}T${u}:${a}:${c}${r}${n}:${s}`}getPrimaryTag(e){return e.tags?.[0]??"general"}toEntryTimestamp(e){if(e["created_at"])return String(e["created_at"]);const t=e["date"];const r=t&&typeof t==="object"&&typeof t.toISOString==="function"?t.toISOString().slice(0,10):String(t??"");if(r.includes("T"))return r;return r+"T09:00:00+09:00"}getSummarizerHealthPath(){return E.default.join(this.dataDir,Z)}readSummarizerHealth(){try{const e=d.default.readFileSync(this.getSummarizerHealthPath(),"utf-8");const t=JSON.parse(e);return{consecutiveFailures:typeof t.consecutiveFailures==="number"?t.consecutiveFailures:0,notified:Boolean(t.notified),lastError:t.lastError}}catch{return{consecutiveFailures:0,notified:false}}}writeSummarizerHealth(e){this.ensureDir(this.dataDir);d.default.writeFileSync(this.getSummarizerHealthPath(),JSON.stringify(e),"utf-8")}recordSummarizerFailure(e){const t=this.readSummarizerHealth();t.consecutiveFailures+=1;t.lastError=e.code||e.message?e:void 0;if(t.consecutiveFailures>=exports.SUMMARIZER_FAILURE_THRESHOLD&&!t.notified){this.notifySummarizerDegraded(t.consecutiveFailures,t.lastError);t.notified=true}this.writeSummarizerHealth(t)}recordSummarizerSuccess(){const e=this.readSummarizerHealth();if(e.consecutiveFailures===0&&!e.notified)return;this.writeSummarizerHealth({consecutiveFailures:0,notified:false})}notifySummarizerDegraded(e,t){try{k(["notify","AI memory summarization keeps failing \u2014 falling back to mechanical summaries","--level=warning","--body=callSummarizer(agent="+this.summarizerAgent+") failed "+e+" times in a row (last error: "+(0,P.formatSummarizerLastError)(t)+"), so summarization switched to the fallback (mechanical) path."],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:15e3})}catch(r){const n=r;console.error(`[memory] failed to send summarizer-health notify: ${n.message}`)}}loadAllEntries(e){if(this.useNative())return(0,D.nativeLoadAllEntries)(this.dataDir,e,false);return(0,g.withRecoveredAgentReadSync)(this.getAgentDir(e),()=>this.loadAllEntriesRaw(e))}loadAllEntriesRaw(e,t=false){const r=this.getEntriesDir(e);if(!d.default.existsSync(r))return[];const n=d.default.readdirSync(r).filter(o=>o.endsWith(".md"));const s=[];for(const o of n){const i=d.default.readFileSync(E.default.join(r,o),"utf-8");const{data:l,content:u}=(0,b.parseFrontmatter)(i);const a=u.replace(/^#[^\n]*\n*/m,"").trim();const c=Boolean(a)&&a!=="(Add details here)";const m=l;s.push({...m,file:o,hasBody:c,...t?{body:a}:{}})}s.sort((o,i)=>this.toEntryTimestamp(i).localeCompare(this.toEntryTimestamp(o)));return s}findEntryById(e,t){const r=this.getEntriesDir(e);if(!d.default.existsSync(r))return null;const n=d.default.readdirSync(r).filter(s=>s.endsWith(".md"));for(const s of n){const o=E.default.join(r,s);const i=d.default.readFileSync(o,"utf-8");const{data:l,content:u}=(0,b.parseFrontmatter)(i);if(l.id===t){return{file:s,filePath:o,data:l,content:u}}}return null}save(e,t,r="general",n={}){if(this.useNative()){const m=Array.isArray(n.tags)?n.tags.join(","):n.tags;this.runNative(()=>(0,D.nativeRunCommand)(this.dataDir,"save",[e,t,r],{tags:m,important:n.important},{body:n.body,rawSave:true}));return}const s=Array.isArray(n.tags)?n.tags:n.tags?n.tags.split(",").map(m=>m.trim()):[];const o=this.getAgentDir(e);const i=m=>{const f=this.generateId();const $=this.getLocalISO8601();const h=(0,b.stringifyFrontmatter)({id:f,type:"memory",date:$,category:r,tags:s,summary:t,...n.important?{important:true}:{}});const y=`${f}.md`;const p=n.body??"(Add details here)";const w=`${h}
2
2
 
3
3
  # ${t}
4
4
 
5
- ${c}
6
- `;l.default.writeFileSync(a,m,"utf-8");this.invalidateSearchIndex(e);console.log(`\u2705 Saved: data/${e}/entries/${f}`);console.log(` ID: ${s}`);console.log(` Tags: ${i.join(", ")||"(none)"}`);console.log(` Category: ${r}`);try{this.markSummaryDirty(e);console.log(` \u{1F4DD} summary.md update scheduled`)}catch(h){}const u={commandId:"memory.save",params:{agentId:e,tags:i.join(",")},resultTags:i.slice(0,3),resultCount:1};const y=(0,_.generateNextActions)(u);const g=(0,_.formatActions)(y);if(g)console.log(g)}index(e,t={}){const r=this.getSummaryPath(e);const n=this.loadAllEntries(e);const s=[...new Set(n.map(u=>this.getPrimaryTag(u)))];if(t.recent){const u=parseInt(String(t.recent),10)||this.recentDays;this.recent(e,u);return}const o=new Date(Date.now()-this.shortTermHours*60*60*1e3).toISOString();const i=n.filter(u=>this.toEntryTimestamp(u)>=o);console.log(`# ${e} memory summary
7
- `);const d=l.default.existsSync(r)?(0,T.parseFrontmatter)(l.default.readFileSync(r,"utf-8")).data.last_updated??"-":"-";console.log(`> ${n.length} items | topics ${s.length} items | updated: ${d}`);if(t.full){const u={};for(const g of n){const h=g.category??"general";u[h]=(u[h]??0)+1}const y=Object.entries(u).sort((g,h)=>h[1]-g[1]).map(([g,h])=>`${g}:${h}`).join(" ");console.log(`> \u{1F4CA} ${y}`)}console.log("");if(i.length>0){const u=[...i].sort((y,g)=>{const h=y.important?1:0;const w=g.important?1:0;if(h!==w)return w-h;return this.toEntryTimestamp(g).localeCompare(this.toEntryTimestamp(y))});console.log(`## \u{1F525} last Task (24h)
8
- `);for(const y of u){const g=y.important?"\u2B50 ":"";console.log(`- ${g}[${y.id}] ${y.summary} (${this.getPrimaryTag(y)})`)}console.log("")}if(t.full){if(l.default.existsSync(r)){const u=l.default.readFileSync(r,"utf-8");const{content:y}=(0,T.parseFrontmatter)(u);if(n.length>0){const g=n[0]?.date;const h=n[n.length-1]?.date;const w=g?new Date(`${g}T00:00:00Z`):null;const E=h?new Date(`${h}T00:00:00Z`):null;if(w&&E&&!Number.isNaN(w.getTime())&&!Number.isNaN(E.getTime())){const F=24*60*60*1e3;const S=Math.max(1,Math.floor((w.getTime()-E.getTime())/F)+1);const A=x=>`${String(x.getMonth()+1).padStart(2,"0")}/${String(x.getDate()).padStart(2,"0")}`;console.log("---");console.log(`\u{1F4CB} Topic summary (${A(E)} ~ ${A(w)}, ${S} days)
9
- `)}}console.log(y.trim())}else{for(const u of s.sort()){const y=n.filter(g=>this.getPrimaryTag(g)===u).length;console.log(`- **${u}** (${y} items)`)}}}const f=t.full?"memory.index-full":"memory.index";const a={commandId:f,params:{agentId:e},resultTags:s.slice(0,3),resultIds:n.slice(0,3).map(u=>u.id),resultCount:n.length};const c=(0,_.generateNextActions)(a);const m=(0,_.formatActions)(c);if(m)console.log(m)}generateIndexContent(e){const t=this.loadAllEntries(e);const r=this.getToday();const n=new Date(Date.now()-this.recentDays*24*60*60*1e3).toISOString().slice(0,10);const s={};const o=[];for(const c of t){if(c.date>=n)o.push(c);const m=c.category??"general";if(!s[m])s[m]=[];s[m].push(c)}let i=`# ${e} memory
5
+ ${p}
6
+ `;let A;if(m&&process.platform!=="win32"){(0,g.commitMemoryFiles)(o,[{path:`entries/${y}`,contents:Buffer.from(w,"utf8")}],{token:m});A=(0,g.writeDirtySummaryMarkerBestEffort)(o,m)}else{this.ensureDir(this.getEntriesDir(e));d.default.writeFileSync(E.default.join(this.getEntriesDir(e),y),w,"utf-8");if(m){(0,g.advanceWindowsMemoryGeneration)(o,m);A=(0,g.writeDirtySummaryMarkerBestEffort)(o,m)}else{try{this.markSummaryDirty(e);A=true}catch{A=false}}}return{id:f,filename:y,scheduleSummary:A}};const l=process.platform==="win32"?(0,g.withWindowsMemoryWriterLock)(o,m=>i(m)):(0,g.withMemoryWriterLock)(o,m=>i(m));this.invalidateSearchIndex(e);console.log(`\u2705 Saved: data/${e}/entries/${l.filename}`);console.log(` ID: ${l.id}`);console.log(` Tags: ${s.join(", ")||"(none)"}`);console.log(` Category: ${r}`);if(l.scheduleSummary)console.log(` \u{1F4DD} summary.md update scheduled`);const u={commandId:"memory.save",params:{agentId:e,tags:s.join(",")},resultTags:s.slice(0,3),resultCount:1};const a=(0,M.generateNextActions)(u);const c=(0,M.formatActions)(a);if(c)console.log(c)}index(e,t={}){if(this.useNative()){this.runNative(()=>(0,D.nativeRunCommand)(this.dataDir,"index",[e],{full:t.full,recent:t.recent}));return}if(t.recent){const r=parseInt(String(t.recent),10)||this.recentDays;this.recent(e,r);return}z(this.getAgentDir(e),()=>this.indexCaptured(e,t))}indexCaptured(e,t){const r=this.getSummaryPath(e);const n=this.loadAllEntriesRaw(e);const s=[...new Set(n.map(f=>this.getPrimaryTag(f)))];const o=new Date(Date.now()-this.shortTermHours*60*60*1e3).toISOString();const i=n.filter(f=>this.toEntryTimestamp(f)>=o);console.log(`# ${e} memory summary
7
+ `);const l=d.default.existsSync(r)?(0,b.parseFrontmatter)(d.default.readFileSync(r,"utf-8")).data.last_updated??"-":"-";console.log(`> ${n.length} items | topics ${s.length} items | updated: ${l}`);if(t.full){const f={};for(const h of n){const y=h.category??"general";f[y]=(f[y]??0)+1}const $=Object.entries(f).sort((h,y)=>y[1]-h[1]).map(([h,y])=>`${h}:${y}`).join(" ");console.log(`> \u{1F4CA} ${$}`)}console.log("");if(i.length>0){const f=[...i].sort(($,h)=>{const y=$.important?1:0;const p=h.important?1:0;if(y!==p)return p-y;return this.toEntryTimestamp(h).localeCompare(this.toEntryTimestamp($))});console.log(`## \u{1F525} last Task (24h)
8
+ `);for(const $ of f){const h=$.important?"\u2B50 ":"";console.log(`- ${h}[${$.id}] ${$.summary} (${this.getPrimaryTag($)})`)}console.log("")}if(t.full){if(d.default.existsSync(r)){const f=d.default.readFileSync(r,"utf-8");const{content:$}=(0,b.parseFrontmatter)(f);if(n.length>0){const h=n[0]?.date;const y=n[n.length-1]?.date;const p=h?new Date(`${h}T00:00:00Z`):null;const w=y?new Date(`${y}T00:00:00Z`):null;if(p&&w&&!Number.isNaN(p.getTime())&&!Number.isNaN(w.getTime())){const A=24*60*60*1e3;const C=Math.max(1,Math.floor((p.getTime()-w.getTime())/A)+1);const v=x=>`${String(x.getMonth()+1).padStart(2,"0")}/${String(x.getDate()).padStart(2,"0")}`;console.log("---");console.log(`\u{1F4CB} Topic summary (${v(w)} ~ ${v(p)}, ${C} days)
9
+ `)}}console.log($.trim())}else{for(const f of s.sort()){const $=n.filter(h=>this.getPrimaryTag(h)===f).length;console.log(`- **${f}** (${$} items)`)}}}const u=t.full?"memory.index-full":"memory.index";const a={commandId:u,params:{agentId:e},resultTags:s.slice(0,3),resultIds:n.slice(0,3).map(f=>f.id),resultCount:n.length};const c=(0,M.generateNextActions)(a);const m=(0,M.formatActions)(c);if(m)console.log(m)}generateIndexContent(e){const t=this.loadAllEntries(e);const r=this.getToday();const n=new Date(Date.now()-this.recentDays*24*60*60*1e3).toISOString().slice(0,10);const s={};const o=[];for(const c of t){if(c.date>=n)o.push(c);const m=c.category??"general";if(!s[m])s[m]=[];s[m].push(c)}let i=`# ${e} memory
10
10
 
11
11
  `;i+=`> Last Updated: ${r}
12
12
  `;i+=`> Total: ${t.length} memories
@@ -22,78 +22,78 @@ ${c}
22
22
  `}i+=`## \u{1F3F7}\uFE0F By category
23
23
 
24
24
  `;for(const[c,m]of Object.entries(s).sort()){i+=`- **${c}**: ${m.length} items
25
- `}const d=t.length-o.length;const f=t[t.length-1]?.date??"-";const a=t[0]?.date??"-";i+=`
25
+ `}const l=t.length-o.length;const u=t[t.length-1]?.date??"-";const a=t[0]?.date??"-";i+=`
26
26
  ## \u{1F4CA} Stats
27
27
 
28
- `;i+=`- Total: ${t.length} items (${f} ~ ${a})
28
+ `;i+=`- Total: ${t.length} items (${u} ~ ${a})
29
29
  `;i+=`- Last ${this.recentDays} days: ${o.length} items
30
- `;if(d>0)i+=`- Older than ${this.recentDays} days: ${d} items
31
- `;return i}topic(e,t){const r=this.loadAllEntries(e);const n=r.filter(s=>this.getPrimaryTag(s)===t);if(n.length===0){console.log(`No memories found for topic '${t}'.`);return}console.log(`## \u{1F4C2} Topic: ${t} (${n.length} items)
32
- `);for(const s of n){console.log(`### [${s.date}] ${s.summary}`);console.log(`- File: data/${e}/entries/${s.file}`);console.log(`- Category: ${s.category??"-"}`);console.log(`- Tags: ${(s.tags??[]).join(", ")||"-"}`);console.log("")}}recent(e,t=30){const r=this.getRecentEntries(e,t);if(r.length===0){console.log(`No memories found in the last ${t} days.`);return}console.log(`## \u{1F525} Last ${t} days (${r.length} items)
33
- `);for(const n of r){const s=n.hasBody?" \u{1F4C4}":"";const o=String(n.date).includes("T")?String(n.date).slice(0,16).replace("T"," "):n.date;console.log(`[${n.id}] [${o}] [${n.category??"-"}] ${n.summary}${s}`)}}getRecentEntries(e,t=30,r={}){const n=this.loadAllEntries(e);const s=new Date(Date.now()-t*24*60*60*1e3).toISOString().slice(0,10);const o=n.filter(i=>this.resolveRecentDate(e,i).slice(0,10)>=s);if(!r.includeBody)return o;return o.map(i=>({...i,body:this.readEntryBody(e,i.file)}))}resolveRecentDate(e,t){const r=this.toDateString(t.updated);if(r)return r;const n=this.toDateString(t["created_at"]);if(n)return n;const s=this.toDateString(t.date);if(s)return s;try{const o=D.default.join(this.getEntriesDir(e),t.file);return l.default.statSync(o).mtime.toISOString()}catch{return""}}toDateString(e){if(e&&typeof e==="object"&&typeof e.toISOString==="function"){return e.toISOString()}return typeof e==="string"?e:""}readEntryBody(e,t){try{const r=l.default.readFileSync(D.default.join(this.getEntriesDir(e),t),"utf-8");const{content:n}=(0,T.parseFrontmatter)(r);return n.replace(/^#[^\n]*\n*/m,"").trim()}catch{return""}}find(e,t){const{files:r,index:n}=this.getSearchIndex(e);if(r.length===0){console.log("No memories found.");return}const s=n.search(t,M+1);const o=s.length>M;const i=s.slice(0,M);if(i.length===0){console.log(`No related memories found for '${t}'.`);return}const d=o?`, top ${M}`:"";console.log(`## \u{1F50D} Search results: "${t}" (${i.length} items${d}, sorted by BM25 score)
34
- `);for(const m of i){const u=m._score!=null?` [${m._score}pts]`:"";console.log(`[${m.id}] [${m.date}] [${this.getPrimaryTag(m)}]${u} ${m.summary}`)}const f=this.createFindActionContext(e,t,i);const a=(0,_.generateNextActions)(f);const c=(0,_.formatActions)(a);if(c)console.log(c)}list(e,t={}){const r=this.loadAllEntries(e);let n=r;if(t.category){n=n.filter(a=>a.category===t.category)}if(t.tag){const a=t.tag.split(",").map(c=>c.trim());n=n.filter(c=>a.every(m=>(c.tags??[]).includes(m)))}if(t.json){const a=this.getEntriesDir(e);const c=n.map(m=>{let u="";if(m.file){try{const y=l.default.readFileSync(D.default.join(a,m.file),"utf-8");const{content:g}=(0,T.parseFrontmatter)(y);const h=g.replace(/^#[^\n]*\n*/m,"").trim();if(h!=="(Add details here)")u=h}catch(y){}}return{id:m.id,title:m.summary??"",category:m.category??"general",tags:m.tags??[],created_at:m.date??"",content:u}});console.log(JSON.stringify(c,null,2));return}if(n.length===0){const a=[];if(t.category)a.push(`category=${t.category}`);if(t.tag)a.push(`tag=${t.tag}`);console.log(`No memories match the filters. (${a.join(", ")||"all"})`);return}console.log(`## \u{1F4CB} List: ${e} (${n.length} items)
35
- `);for(const a of n){console.log(`[${a.id}] [${a.date}] [${this.getPrimaryTag(a)}] ${a.summary}`)}const s=[...new Set(n.flatMap(a=>a.tags??[]))].slice(0,3);const o=n.slice(0,3).map(a=>a.id);const i={commandId:"memory.list",params:{agentId:e,...t.category?{category:t.category}:{}},resultTags:s,resultIds:o,resultCount:n.length};const d=(0,_.generateNextActions)(i);const f=(0,_.formatActions)(d);if(f)console.log(f)}stats(e){const t=this.loadAllEntries(e);if(t.length===0){console.log("No memories found.");return}const r={};for(const a of t){const c=a.category??"general";r[c]=(r[c]??0)+1}const n={};for(const a of t){for(const c of a.tags??[]){n[c]=(n[c]??0)+1}}console.log(`# ${e} Stats (${t.length} items)
36
- `);console.log(`## By category`);for(const[a,c]of Object.entries(r).sort((m,u)=>u[1]-m[1])){console.log(` ${a}: ${c} items`)}console.log(`
37
- ## Top 20 Tags`);const s=Object.entries(n).sort((a,c)=>c[1]-a[1]).slice(0,20);for(const[a,c]of s){console.log(` ${a}: ${c} items`)}const o=Object.entries(r).sort((a,c)=>c[1]-a[1]).map(a=>a[0]);const i={commandId:"memory.stats",params:{agentId:e},resultTags:o.slice(0,3),resultCount:t.length};const d=(0,_.generateNextActions)(i);const f=(0,_.formatActions)(d);if(f)console.log(f)}tags(e){const t=this.loadAllEntries(e);if(t.length===0){console.log("No memories found.");return}const r={};for(const s of t){for(const o of s.tags??[]){r[o]=(r[o]??0)+1}}const n=Object.entries(r).sort((s,o)=>o[1]-s[1]);if(n.length===0){console.log("No tags found.");return}console.log(`## \u{1F3F7}\uFE0F All tags (${n.length} items)
38
- `);for(const[s,o]of n){console.log(` ${s}: ${o} items`)}}get(e,t){const r=this.getEntriesDir(e);if(!l.default.existsSync(r)){console.log("No memories found.");return}const n=l.default.readdirSync(r).filter(s=>s.endsWith(".md"));for(const s of n){const o=D.default.join(r,s);const i=l.default.readFileSync(o,"utf-8");const{data:d,content:f}=(0,T.parseFrontmatter)(i);if(d.id===t){const a=d;console.log(`## \u{1F4C4} ${a.summary}
30
+ `;if(l>0)i+=`- Older than ${this.recentDays} days: ${l} items
31
+ `;return i}topic(e,t){if(this.useNative()){this.runNative(()=>(0,D.nativeRunCommand)(this.dataDir,"tags",[e,t]));return}const r=this.loadAllEntries(e);const n=r.filter(s=>this.getPrimaryTag(s)===t);if(n.length===0){console.log(`No memories found for topic '${t}'.`);return}console.log(`## \u{1F4C2} Topic: ${t} (${n.length} items)
32
+ `);for(const s of n){console.log(`### [${s.date}] ${s.summary}`);console.log(`- File: data/${e}/entries/${s.file}`);console.log(`- Category: ${s.category??"-"}`);console.log(`- Tags: ${(s.tags??[]).join(", ")||"-"}`);console.log("")}}recent(e,t=30){if(this.useNative()){this.runNative(()=>(0,D.nativeRunCommand)(this.dataDir,"recent",[e,String(t)]));return}const r=this.getRecentEntries(e,t);if(r.length===0){console.log(`No memories found in the last ${t} days.`);return}console.log(`## \u{1F525} Last ${t} days (${r.length} items)
33
+ `);for(const n of r){const s=n.hasBody?" \u{1F4C4}":"";const o=String(n.date).includes("T")?String(n.date).slice(0,16).replace("T"," "):n.date;console.log(`[${n.id}] [${o}] [${n.category??"-"}] ${n.summary}${s}`)}}getRecentEntries(e,t=30,r={}){if(this.useNative())return(0,D.nativeGetRecentEntries)(this.dataDir,e,t,r);return(0,g.withRecoveredAgentReadSync)(this.getAgentDir(e),()=>{const n=this.loadAllEntriesRaw(e);const s=new Date(Date.now()-t*24*60*60*1e3).toISOString().slice(0,10);const o=n.filter(i=>this.resolveRecentDate(e,i).slice(0,10)>=s);if(!r.includeBody)return o;return o.map(i=>({...i,body:this.readEntryBody(e,i.file)}))})}resolveRecentDate(e,t){const r=this.toDateString(t.updated);if(r)return r;const n=this.toDateString(t["created_at"]);if(n)return n;const s=this.toDateString(t.date);if(s)return s;try{const o=E.default.join(this.getEntriesDir(e),t.file);return d.default.statSync(o).mtime.toISOString()}catch{return""}}toDateString(e){if(e&&typeof e==="object"&&typeof e.toISOString==="function"){return e.toISOString()}return typeof e==="string"?e:""}readEntryBody(e,t){try{const r=d.default.readFileSync(E.default.join(this.getEntriesDir(e),t),"utf-8");const{content:n}=(0,b.parseFrontmatter)(r);return n.replace(/^#[^\n]*\n*/m,"").trim()}catch{return""}}find(e,t){if(this.useNative()){this.runNative(()=>(0,D.nativeRunCommand)(this.dataDir,"find",[e,t]));return}z(this.getAgentDir(e),()=>this.findCaptured(e,t),()=>this.invalidateSearchIndex(e))}findCaptured(e,t){const{files:r,index:n}=this.getSearchIndex(e);if(r.length===0){console.log("No memories found.");return}const s=n.search(t,_+1);const o=s.length>_;const i=s.slice(0,_);if(i.length===0){console.log(`No related memories found for '${t}'.`);return}const l=o?`, top ${_}`:"";console.log(`## \u{1F50D} Search results: "${t}" (${i.length} items${l}, sorted by BM25 score)
34
+ `);for(const m of i){const f=m._score!=null?` [${m._score}pts]`:"";console.log(`[${m.id}] [${m.date}] [${this.getPrimaryTag(m)}]${f} ${m.summary}`)}const u=this.createFindActionContext(e,t,i);const a=(0,M.generateNextActions)(u);const c=(0,M.formatActions)(a);if(c)console.log(c)}list(e,t={}){if(this.useNative()){this.runNative(()=>(0,D.nativeRunCommand)(this.dataDir,"list",[e],{category:t.category,tag:t.tag,json:t.json,sort:t.sort}));return}const r=t.json?(0,g.withRecoveredAgentReadSync)(this.getAgentDir(e),()=>this.loadAllEntriesRaw(e,true)):this.loadAllEntries(e);let n=r;if(t.category){n=n.filter(a=>a.category===t.category)}if(t.tag){const a=t.tag.split(",").map(c=>c.trim());n=n.filter(c=>a.every(m=>(c.tags??[]).includes(m)))}if(t.json){const a=n.map(c=>{return{id:c.id,title:c.summary??"",category:c.category??"general",tags:c.tags??[],created_at:c.date??"",content:c.body&&c.body!=="(Add details here)"?c.body:""}});console.log(JSON.stringify(a,null,2));return}if(n.length===0){const a=[];if(t.category)a.push(`category=${t.category}`);if(t.tag)a.push(`tag=${t.tag}`);console.log(`No memories match the filters. (${a.join(", ")||"all"})`);return}console.log(`## \u{1F4CB} List: ${e} (${n.length} items)
35
+ `);for(const a of n){console.log(`[${a.id}] [${a.date}] [${this.getPrimaryTag(a)}] ${a.summary}`)}const s=[...new Set(n.flatMap(a=>a.tags??[]))].slice(0,3);const o=n.slice(0,3).map(a=>a.id);const i={commandId:"memory.list",params:{agentId:e,...t.category?{category:t.category}:{}},resultTags:s,resultIds:o,resultCount:n.length};const l=(0,M.generateNextActions)(i);const u=(0,M.formatActions)(l);if(u)console.log(u)}stats(e){if(this.useNative()){this.runNative(()=>(0,D.nativeRunCommand)(this.dataDir,"stats",[e]));return}const t=this.loadAllEntries(e);if(t.length===0){console.log("No memories found.");return}const r={};for(const a of t){const c=a.category??"general";r[c]=(r[c]??0)+1}const n={};for(const a of t){for(const c of a.tags??[]){n[c]=(n[c]??0)+1}}console.log(`# ${e} Stats (${t.length} items)
36
+ `);console.log(`## By category`);for(const[a,c]of Object.entries(r).sort((m,f)=>f[1]-m[1])){console.log(` ${a}: ${c} items`)}console.log(`
37
+ ## Top 20 Tags`);const s=Object.entries(n).sort((a,c)=>c[1]-a[1]).slice(0,20);for(const[a,c]of s){console.log(` ${a}: ${c} items`)}const o=Object.entries(r).sort((a,c)=>c[1]-a[1]).map(a=>a[0]);const i={commandId:"memory.stats",params:{agentId:e},resultTags:o.slice(0,3),resultCount:t.length};const l=(0,M.generateNextActions)(i);const u=(0,M.formatActions)(l);if(u)console.log(u)}tags(e){if(this.useNative()){this.runNative(()=>(0,D.nativeRunCommand)(this.dataDir,"tags",[e]));return}const t=this.loadAllEntries(e);if(t.length===0){console.log("No memories found.");return}const r={};for(const s of t){for(const o of s.tags??[]){r[o]=(r[o]??0)+1}}const n=Object.entries(r).sort((s,o)=>o[1]-s[1]);if(n.length===0){console.log("No tags found.");return}console.log(`## \u{1F3F7}\uFE0F All tags (${n.length} items)
38
+ `);for(const[s,o]of n){console.log(` ${s}: ${o} items`)}}get(e,t){if(this.useNative()){this.runNative(()=>(0,D.nativeRunCommand)(this.dataDir,"get",[e,t]));return}z(this.getAgentDir(e),()=>this.getCaptured(e,t))}getCaptured(e,t){const r=this.getEntriesDir(e);if(!d.default.existsSync(r)){console.log("No memories found.");return}const n=d.default.readdirSync(r).filter(s=>s.endsWith(".md"));for(const s of n){const o=E.default.join(r,s);const i=d.default.readFileSync(o,"utf-8");const{data:l,content:u}=(0,b.parseFrontmatter)(i);if(l.id===t){const a=l;console.log(`## \u{1F4C4} ${a.summary}
39
39
  `);console.log(`- ID: ${a.id}`);console.log(`- Date: ${a.date}`);console.log(`- Category: ${a.category??"-"}`);console.log(`- Tags: ${(a.tags??[]).join(", ")||"-"}`);console.log(`- File: data/${e}/entries/${s}`);console.log(`
40
40
  ---
41
- `);console.log(f.trim());const c=D.default.join(this.getAgentDir(e),"graph.json");if(l.default.existsSync(c)){try{const g=JSON.parse(l.default.readFileSync(c,"utf-8"));const h=g.edges.filter(w=>w.from===t||w.to===t).sort((w,E)=>E.weight-w.weight).slice(0,5);if(h.length>0){const w={};g.nodes.forEach(E=>{w[E.id]=E});console.log(`
41
+ `);console.log(u.trim());const c=E.default.join(this.getAgentDir(e),"graph.json");if(d.default.existsSync(c)){try{const h=JSON.parse(d.default.readFileSync(c,"utf-8"));const y=h.edges.filter(p=>p.from===t||p.to===t).sort((p,w)=>w.weight-p.weight).slice(0,5);if(y.length>0){const p={};h.nodes.forEach(w=>{p[w.id]=w});console.log(`
42
42
  ---
43
- `);console.log(`## \u{1F517} Related memories (${h.length} items)
44
- `);for(const E of h){const F=E.from===t?E.to:E.from;const S=w[F];if(S){console.log(`[${E.weight}] [${F}] ${S.summary.slice(0,50)}...`)}}}}catch(g){}}const m={commandId:"memory.get",params:{agentId:e,id:t},resultTags:(a.tags??[]).slice(0,3),resultIds:[t],resultCount:1};const u=(0,_.generateNextActions)(m);const y=(0,_.formatActions)(u);if(y)console.log(y);return}}console.log(`ID '${t}' not found.`)}update(e,t,r={}){const n=this.findEntryById(e,t);if(!n){console.log(`\u274C ID '${t}' not found.`);process.exit(1)}const{filePath:s,data:o,content:i}=n;const d=i.replace(/^#[^\n]*\n*/m,"").trim();const f=Array.isArray(r.tags)?r.tags:r.tags?r.tags.split(",").map(y=>y.trim()):o.tags??[];const a={...o,summary:r.summary??o.summary,category:r.category??o.category,tags:f,updated:this.getToday()};if(r.important){a["important"]=true}else if(r["no-important"]){delete a["important"]}const c=r.body??d??"(Add details here)";const m=(0,T.stringifyFrontmatter)(a);const u=`${m}
43
+ `);console.log(`## \u{1F517} Related memories (${y.length} items)
44
+ `);for(const w of y){const A=w.from===t?w.to:w.from;const C=p[A];if(C){console.log(`[${w.weight}] [${A}] ${C.summary.slice(0,50)}...`)}}}}catch(h){}}const m={commandId:"memory.get",params:{agentId:e,id:t},resultTags:(a.tags??[]).slice(0,3),resultIds:[t],resultCount:1};const f=(0,M.generateNextActions)(m);const $=(0,M.formatActions)(f);if($)console.log($);return}}console.log(`ID '${t}' not found.`)}update(e,t,r={}){if(this.useNative()){this.runNative(()=>(0,D.nativeRunCommand)(this.dataDir,"update",[e,t],{summary:r.summary,category:r.category,tags:r.tags,important:r.important,"no-important":r["no-important"]},{body:r.body}),true);return}const n=this.getAgentDir(e);const s=i=>{const l=this.findEntryById(e,t);if(!l){console.log(`\u274C ID '${t}' not found.`);process.exit(1)}const{data:u,content:a}=l;const c=a.replace(/^#[^\n]*\n*/m,"").trim();const m=Array.isArray(r.tags)?r.tags:r.tags?r.tags.split(",").map(p=>p.trim()):u.tags??[];const f={...u,summary:r.summary??u.summary,category:r.category??u.category,tags:m,updated:this.getToday()};if(r.important){f["important"]=true}else if(r["no-important"]){delete f["important"]}const $=r.body??c??"(Add details here)";const h=(0,b.stringifyFrontmatter)(f);const y=`${h}
45
45
 
46
- # ${String(a["summary"])}
46
+ # ${String(f["summary"])}
47
47
 
48
- ${c}
49
- `;l.default.writeFileSync(s,u,"utf-8");this.invalidateSearchIndex(e);console.log(`\u2705 Updated: ${n.file}`);console.log(` ID: ${t}`);if(r.summary)console.log(` Summary: ${String(a["summary"])}`);if(r.category)console.log(` Category: ${String(a["category"])}`);if(r.tags)console.log(` Tags: ${a["tags"].join(", ")}`);if(r.body)console.log(` Body: (updated)`)}delete(e,t,r={}){const n=this.findEntryById(e,t);if(!n){console.log(`\u274C ID '${t}' not found.`);process.exit(1)}if(!r.force){console.log(`\u26A0\uFE0F Delete target: [${n.data.id}] ${n.data.summary}`);console.log(` File: ${n.file}`);console.log(`
50
- Add --force to delete it.`);console.log(`Example: memory delete ${e} ${t} --force`);return}l.default.unlinkSync(n.filePath);this.invalidateSearchIndex(e);console.log(`\u{1F5D1}\uFE0F Deleted: ${n.file}`);console.log(` ID: ${t}`);console.log(` Summary: ${n.data.summary}`);try{this.markSummaryDirty(e);console.log(` \u{1F4DD} summary.md update scheduled`)}catch(s){}}merge(e,t,r,n={}){const s=this.findEntryById(e,t);const o=this.findEntryById(e,r);if(!s){console.log(`\u274C ID '${t}' not found.`);process.exit(1)}if(!o){console.log(`\u274C ID '${r}' not found.`);process.exit(1)}const i=s.content.replace(/^#[^\n]*\n*/m,"").trim();const d=o.content.replace(/^#[^\n]*\n*/m,"").trim();const f=n.summary??`${s.data.summary} + ${o.data.summary}`;const a=`## Merged memory 1 (${s.data.id}, ${s.data.date})
51
- ${s.data.summary}
48
+ ${$}
49
+ `;if(i&&process.platform!=="win32"){(0,g.assertMemoryOverwritePermission)(n,`entries/${l.file}`,i);(0,g.commitMemoryFiles)(n,[{path:`entries/${l.file}`,contents:Buffer.from(y,"utf8")}],{token:i})}else{d.default.writeFileSync(l.filePath,y,"utf-8");if(i)(0,g.advanceWindowsMemoryGeneration)(n,i)}return{entry:l,newData:f}};const o=process.platform==="win32"?(0,g.withWindowsMemoryWriterLock)(n,i=>s(i)):(0,g.withMemoryWriterLock)(n,i=>s(i));this.invalidateSearchIndex(e);console.log(`\u2705 Updated: ${o.entry.file}`);console.log(` ID: ${t}`);if(r.summary)console.log(` Summary: ${String(o.newData["summary"])}`);if(r.category)console.log(` Category: ${String(o.newData["category"])}`);if(r.tags)console.log(` Tags: ${o.newData["tags"].join(", ")}`);if(r.body)console.log(` Body: (updated)`)}delete(e,t,r={}){if(this.useNative()){this.runNative(()=>(0,D.nativeRunCommand)(this.dataDir,"delete",[e,t],{force:r.force}),true);return}if(!r.force){const i=z(this.getAgentDir(e),()=>{const l=this.findEntryById(e,t);if(!l){console.log(`\u274C ID '${t}' not found.`);return false}console.log(`\u26A0\uFE0F Delete target: [${l.data.id}] ${l.data.summary}`);console.log(` File: ${l.file}`);console.log(`
50
+ Add --force to delete it.`);console.log(`Example: memory delete ${e} ${t} --force`);return true});if(!i)process.exit(1);return}const n=this.getAgentDir(e);const s=i=>{const l=this.findEntryById(e,t);if(!l){return{entry:null,scheduleSummary:false}}if(i&&process.platform!=="win32"){(0,g.commitMemoryFiles)(n,[{path:`entries/${l.file}`,contents:null}],{token:i});return{entry:l,scheduleSummary:(0,g.writeDirtySummaryMarkerBestEffort)(n,i)}}d.default.unlinkSync(l.filePath);if(i)(0,g.advanceWindowsMemoryGeneration)(n,i);let u=false;try{if(i)u=(0,g.writeDirtySummaryMarkerBestEffort)(n,i);else{this.markSummaryDirty(e);u=true}}catch{}return{entry:l,scheduleSummary:u}};const o=process.platform==="win32"?(0,g.withWindowsMemoryWriterLock)(n,i=>s(i)):(0,g.withMemoryWriterLock)(n,i=>s(i));if(!o.entry){console.log(`\u274C ID '${t}' not found.`);process.exit(1)}this.invalidateSearchIndex(e);console.log(`\u{1F5D1}\uFE0F Deleted: ${o.entry.file}`);console.log(` ID: ${t}`);console.log(` Summary: ${o.entry.data.summary}`);if(o.scheduleSummary)console.log(` \u{1F4DD} summary.md update scheduled`)}merge(e,t,r,n={}){if(this.useNative()){this.runNative(()=>(0,D.nativeRunCommand)(this.dataDir,"merge",[e,t,r],{summary:n.summary}),true);return}if(t===r){console.error("cannot merge a memory entry with itself");process.exit(1)}const s=this.getAgentDir(e);const o=l=>{const u=this.findEntryById(e,t);const a=this.findEntryById(e,r);if(!u){console.log(`\u274C ID '${t}' not found.`);process.exit(1)}if(!a){console.log(`\u274C ID '${r}' not found.`);process.exit(1)}if(u.file===a.file){console.error("cannot merge a memory entry with itself");process.exit(1)}const c=u.content.replace(/^#[^\n]*\n*/m,"").trim();const m=a.content.replace(/^#[^\n]*\n*/m,"").trim();const f=n.summary??`${u.data.summary} + ${a.data.summary}`;const $=`## Merged memory 1 (${u.data.id}, ${u.data.date})
51
+ ${u.data.summary}
52
52
 
53
- ${i!=="(Add details here)"?i:"(No details)"}
53
+ ${c!=="(Add details here)"?c:"(No details)"}
54
54
 
55
55
  ---
56
56
 
57
- ## Merged memory 2 (${o.data.id}, ${o.data.date})
58
- ${o.data.summary}
57
+ ## Merged memory 2 (${a.data.id}, ${a.data.date})
58
+ ${a.data.summary}
59
59
 
60
- ${d!=="(Add details here)"?d:"(No details)"}`;const c=[...new Set([...s.data.tags??[],...o.data.tags??[]])];const m=s.data.date>o.data.date?s.data.date:o.data.date;const u=this.generateId();const y={id:u,type:"memory",date:m,category:s.data.category,tags:c,summary:f,merged_from:[t,r]};const g=`${u}.md`;const h=D.default.join(this.getEntriesDir(e),g);const w=(0,T.stringifyFrontmatter)(y);const E=`${w}
60
+ ${m!=="(Add details here)"?m:"(No details)"}`;const h=[...new Set([...u.data.tags??[],...a.data.tags??[]])];const y=u.data.date>a.data.date?u.data.date:a.data.date;const p=this.generateId();const w={id:p,type:"memory",date:y,category:u.data.category,tags:h,summary:f,merged_from:[t,r]};const A=`${p}.md`;const C=(0,b.stringifyFrontmatter)(w);const v=`${C}
61
61
 
62
62
  # ${f}
63
63
 
64
- ${a}
65
- `;l.default.writeFileSync(h,E,"utf-8");l.default.unlinkSync(s.filePath);l.default.unlinkSync(o.filePath);this.invalidateSearchIndex(e);console.log(`\u{1F500} Merge complete!`);console.log(` New ID: ${u}`);console.log(` New file: ${g}`);console.log(` Merged memory: [${t}] + [${r}]`);console.log(` Summary: ${f}`)}buildFallbackSummary(e){const t={};for(const s of e){const o=this.getPrimaryTag(s);if(!t[o])t[o]=[];t[o].push(s)}const r=s=>{if(!s)return"-";const o=String(s).includes("T")?s:`${s}T00:00:00Z`;const i=new Date(o);if(Number.isNaN(i.getTime()))return"-";return`${String(i.getMonth()+1).padStart(2,"0")}/${String(i.getDate()).padStart(2,"0")}`};let n="";for(const[s,o]of Object.entries(t).sort()){const i=o.map(c=>c.date).filter(Boolean).sort();const d=i[0];const f=i[i.length-1];const a=d&&f?`, ${r(d)}~${r(f)}`:"";n+=`## ${s} (${o.length} items${a})
64
+ ${$}
65
+ `;if(l&&process.platform!=="win32"){(0,g.commitMemoryFiles)(s,[{path:`entries/${A}`,contents:Buffer.from(v,"utf8")},{path:`entries/${u.file}`,contents:null},{path:`entries/${a.file}`,contents:null}],{token:l})}else{d.default.writeFileSync(E.default.join(this.getEntriesDir(e),A),v,"utf-8");d.default.unlinkSync(u.filePath);d.default.unlinkSync(a.filePath);if(l)(0,g.advanceWindowsMemoryGeneration)(s,l)}return{filename:A,newId:p,mergedSummary:f}};const i=process.platform==="win32"?(0,g.withWindowsMemoryWriterLock)(s,l=>o(l)):(0,g.withMemoryWriterLock)(s,l=>o(l));this.invalidateSearchIndex(e);console.log(`\u{1F500} Merge complete!`);console.log(` New ID: ${i.newId}`);console.log(` New file: ${i.filename}`);console.log(` Merged memory: [${t}] + [${r}]`);console.log(` Summary: ${i.mergedSummary}`)}buildFallbackSummary(e){const t={};for(const s of e){const o=this.getPrimaryTag(s);if(!t[o])t[o]=[];t[o].push(s)}const r=s=>{if(!s)return"-";const o=String(s).includes("T")?s:`${s}T00:00:00Z`;const i=new Date(o);if(Number.isNaN(i.getTime()))return"-";return`${String(i.getMonth()+1).padStart(2,"0")}/${String(i.getDate()).padStart(2,"0")}`};let n="";for(const[s,o]of Object.entries(t).sort()){const i=o.map(c=>c.date).filter(Boolean).sort();const l=i[0];const u=i[i.length-1];const a=l&&u?`, ${r(l)}~${r(u)}`:"";n+=`## ${s} (${o.length} items${a})
66
66
  `;for(const c of o)n+=`- [${c.date}] ${c.summary}
67
67
  `;for(const c of o)n+=`\u2192 [entries/${c.file}](entries/${c.file})
68
68
  `;n+=`
69
- `}return n}callSummarizer(e){try{const t=k(["q",this.summarizerAgent],{encoding:"utf-8",timeout:this.summarizerTimeout,stdio:["pipe","pipe","pipe"],input:e});const r=O(t);this.recordSummarizerSuccess();return r}catch(t){const r=t;const n=r.code==="ETIMEDOUT"||r.killed?`timed out after ${this.summarizerTimeout}ms`:r.message;console.error(`[memory] callSummarizer failed (agent=${this.summarizerAgent}), falling back to raw entry list: ${n}`);this.recordSummarizerFailure((0,j.describeSummarizerFailure)(r,this.summarizerTimeout));return null}}generateSummary(e,t={}){const r=this.loadAllEntries(e);if(r.length===0)return{status:"empty"};const n=new Date(Date.now()-this.summaryDays*24*60*60*1e3).toISOString().slice(0,10);const s=t.force?r:r.filter(S=>S.date>=n);if(s.length===0)return{status:"empty",entryCount:r.length};const o=this.getSummaryPath(e);const i=l.default.existsSync(o)?(0,T.parseFrontmatter)(l.default.readFileSync(o,"utf-8")):null;const d=i?.data?.last_entry_id??null;const f=i?.content.trim()??null;const a=(S,A)=>{if(!A)return S;const x=S.findIndex(p=>p.id===A);if(x===-1)return S;return S.slice(0,x)};const c=a(s,d);if(c.length===0&&!t.force){return{status:"up-to-date",entryCount:r.length}}const m=t.force?s:c;const u=[...m].reverse().map(S=>{if(S.file){try{const A=l.default.readFileSync(D.default.join(this.getEntriesDir(e),S.file),"utf-8");const{content:x}=(0,T.parseFrontmatter)(A);const p=x.replace(/^#[^\n]*\n*/m,"").trim();return{...S,body:p}}catch(A){}}return S});const y=[...new Set(s.map(S=>this.getPrimaryTag(S)))].sort();const g=(S,A,x)=>{let p=`You are a memory summarizer for an AI agent.
69
+ `}return n}callSummarizer(e){try{const t=k(["q",this.summarizerAgent],{encoding:"utf-8",timeout:this.summarizerTimeout,stdio:["pipe","pipe","pipe"],input:e});const r=B(t);this.recordSummarizerSuccess();return r}catch(t){const r=t;const n=r.code==="ETIMEDOUT"||r.killed?`timed out after ${this.summarizerTimeout}ms`:r.message;console.error(`[memory] callSummarizer failed (agent=${this.summarizerAgent}), falling back to raw entry list: ${n}`);this.recordSummarizerFailure((0,P.describeSummarizerFailure)(r,this.summarizerTimeout));return null}}captureSummarySnapshot(e){const t=this.getAgentDir(e);if(!this.summaryPathExists(t)){return{generation:"0",dirtyMarker:null,summaryContents:null,entries:[]}}const r=()=>{const n=this.readMutationGeneration(t);const s=this.readOptionalFile(E.default.join(t,".dirty-summary"));const o=this.readOptionalFile(this.getSummaryPath(e));const i=this.loadAllEntriesRaw(e).map(l=>{const u=d.default.readFileSync(E.default.join(this.getEntriesDir(e),l.file),"utf8");const{content:a}=(0,b.parseFrontmatter)(u);return{...l,body:a.replace(/^#[^\n]*\n*/m,"").trim()}});return{generation:n,dirtyMarker:s,summaryContents:o,entries:i}};return process.platform==="win32"?(0,g.withRecoveredAgentReadSync)(t,r):(0,g.withMemoryWriterLock)(t,r)}summaryPathExists(e){if(process.platform!=="win32")return d.default.existsSync(e);try{d.default.statSync(e);return true}catch(t){if(t.code==="ENOENT")return false;throw t}}readMutationGeneration(e){const t=this.readOptionalFile(E.default.join(e,".memory-mutation-generation"));if(!t)return"0";const r=t.toString("utf8");if(!/^(0|[1-9]\d*)$/u.test(r))throw new Error("memory mutation generation is invalid");return r}readOptionalFile(e){try{return d.default.readFileSync(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}publishSummarySnapshot(e,t,r,n){const s=this.getAgentDir(e);if(process.platform==="win32"){(0,g.withWindowsMemoryWriterLock)(s,()=>{const o=this.readMutationGeneration(s);const i=this.readOptionalFile(this.getSummaryPath(e));const l=this.readOptionalFile(this.getDirtySummaryPath(e));if(o!==t.generation||!O(i,t.summaryContents)){throw new Error("memory changed while summary was being generated; retry later")}if(n&&!O(l,t.dirtyMarker)){throw new Error("memory summary marker changed while summary was being generated; retry later")}if(r)d.default.writeFileSync(this.getSummaryPath(e),r);if(n&&l)d.default.unlinkSync(this.getDirtySummaryPath(e))});return}(0,g.withMemoryWriterLock)(s,o=>{const i=this.readMutationGeneration(s);const l=this.readOptionalFile(this.getSummaryPath(e));const u=this.readOptionalFile(this.getDirtySummaryPath(e));if(i!==t.generation||!O(l,t.summaryContents)){throw new Error("memory changed while summary was being generated; retry later")}if(n&&!O(u,t.dirtyMarker)){throw new Error("memory summary marker changed while summary was being generated; retry later")}const a=[];if(r){(0,g.assertMemoryOverwritePermission)(s,"summary.md",o);a.push({path:"summary.md",contents:r})}if(n)a.push({path:".dirty-summary",contents:null});if(a.length>0)(0,g.commitMemoryFiles)(s,a,{token:o,advanceGeneration:false})})}generateSummary(e,t={}){if(this.useNative())return(0,D.nativeGenerateSummary)(this.nativeSettings(),e,Boolean(t.force));const r=this.captureSummarySnapshot(e);return this.generateSummaryFromSnapshot(e,t,r,false)}generateSummaryFromSnapshot(e,t,r,n){const s=r.entries;if(s.length===0){if(n)this.publishSummarySnapshot(e,r,null,true);return{status:"empty"}}const o=new Date(Date.now()-this.summaryDays*24*60*60*1e3).toISOString().slice(0,10);const i=t.force?s:s.filter(v=>v.date>=o);if(i.length===0){if(n)this.publishSummarySnapshot(e,r,null,true);return{status:"empty",entryCount:s.length}}const l=r.summaryContents?(0,b.parseFrontmatter)(r.summaryContents.toString("utf8")):null;const u=l?.data?.last_entry_id??null;const a=l?.content.trim()??null;const c=(v,x)=>{if(!x)return v;const R=v.findIndex(T=>T.id===x);if(R===-1)return v;return v.slice(0,R)};const m=c(i,u);if(m.length===0&&!t.force){if(n)this.publishSummarySnapshot(e,r,null,true);return{status:"up-to-date",entryCount:s.length}}const f=t.force?i:m;const $=[...f].reverse();const h=[...new Set(i.map(v=>this.getPrimaryTag(v)))].sort();const y=(v,x,R)=>{let T=`You are a memory summarizer for an AI agent.
70
70
 
71
- `;if(S){p+=`## Existing summary:
72
- ${S}
71
+ `;if(v){T+=`## Existing summary:
72
+ ${v}
73
73
 
74
74
  ## New entries to incorporate:
75
- `}else{p+=`## All entries:
76
- `}for(const b of A){const C=b.important?" [important]":"";p+=`- [${b.id}] [${b.date}] [${this.getPrimaryTag(b)}]${C} ${b.summary}`;if(b.body&&b.body!=="(Add details here)"){p+=` \u2014 ${b.body.slice(0,200)}`}p+=` (file: entries/${b.file})
77
- `}p+=`
75
+ `}else{T+=`## All entries:
76
+ `}for(const F of x){const q=F.important?" [important]":"";T+=`- [${F.id}] [${F.date}] [${this.getPrimaryTag(F)}]${q} ${F.summary}`;if(F.body&&F.body!=="(Add details here)"){T+=` \u2014 ${F.body.slice(0,200)}`}T+=` (file: entries/${F.file})
77
+ `}T+=`
78
78
  ## Instructions:
79
- `;p+=`- Group by topic, each topic as ## heading with entry count and date range, e.g. "## mcp-http (4 items, 01/28~02/14)"
80
- `;p+=`- Write concise Korean summary per topic (2-5 sentences)
81
- `;p+=`- After each topic summary, list relevant entry file links as "\u2192 [entries/filename](entries/filename)"
82
- `;p+=`- Highlight key decisions, insights, and action items
83
- `;p+=`- If there's an existing summary, merge new information into it
84
- `;p+=`- Topics to cover: ${x.join(", ")}
85
- `;p+=`- Output ONLY the markdown body (topic sections), no frontmatter or top-level heading
86
- `;return p};const h=g(t.force?null:f,u,y);const w=this.callSummarizer(h);const E=s[0]?.id;if(!w){const S=s.map(p=>{if(p.file){try{const b=l.default.readFileSync(D.default.join(this.getEntriesDir(e),p.file),"utf-8");const{content:C}=(0,T.parseFrontmatter)(b);const R=C.replace(/^#[^\n]*\n*/m,"").trim();return{...p,body:R}}catch(b){}}return p});const A=this.buildFallbackSummary(S);const x=(0,T.stringifyFrontmatter)({last_entry_id:E,last_updated:this.getToday(),entry_count:r.length,summary_days:this.summaryDays,summarizer:"fallback"});l.default.writeFileSync(o,`${x}
79
+ `;T+=`- Group by topic, each topic as ## heading with entry count and date range, e.g. "## mcp-http (4 items, 01/28~02/14)"
80
+ `;T+=`- Write concise Korean summary per topic (2-5 sentences)
81
+ `;T+=`- After each topic summary, list relevant entry file links as "\u2192 [entries/filename](entries/filename)"
82
+ `;T+=`- Highlight key decisions, insights, and action items
83
+ `;T+=`- If there's an existing summary, merge new information into it
84
+ `;T+=`- Topics to cover: ${R.join(", ")}
85
+ `;T+=`- Output ONLY the markdown body (topic sections), no frontmatter or top-level heading
86
+ `;return T};const p=y(t.force?null:a,$,h);const w=this.callSummarizer(p);const A=i[0]?.id;if(!w){const v=this.buildFallbackSummary(i);const x=(0,b.stringifyFrontmatter)({last_entry_id:A,last_updated:this.getToday(),entry_count:s.length,summary_days:this.summaryDays,summarizer:"fallback"});this.publishSummarySnapshot(e,r,Buffer.from(`${x}
87
87
 
88
- ${A}`,"utf-8");return{status:"fallback",entryCount:r.length,newEntries:m.length}}const F=(0,T.stringifyFrontmatter)({last_entry_id:E,last_updated:this.getToday(),entry_count:r.length,summary_days:this.summaryDays,summarizer:"memory_summarizer"});l.default.writeFileSync(o,`${F}
88
+ ${v}`,"utf8"),n);return{status:"fallback",entryCount:s.length,newEntries:f.length}}const C=(0,b.stringifyFrontmatter)({last_entry_id:A,last_updated:this.getToday(),entry_count:s.length,summary_days:this.summaryDays,summarizer:"memory_summarizer"});this.publishSummarySnapshot(e,r,Buffer.from(`${C}
89
89
 
90
90
  ${w}
91
- `,"utf-8");return{status:"updated",entryCount:r.length,newEntries:m.length}}summarize(e,t={}){const r=this.loadAllEntries(e);if(r.length===0){console.log("No memories found.");return}console.log(`\u{1F4DD} Starting summary generation (${r.length} items entries)
92
- `);const n=this.generateSummary(e,{force:t.force});if(n.status==="up-to-date"){console.log("\u2705 summary.md is up to date.")}else if(n.status==="fallback"){console.log(`\u{1F4CB} Fallback summary generated (AI call failed)`)}else if(n.status==="updated"){console.log(`\u{1F916} Summary complete (${n.newEntries} items applied)`)}console.log(` File: data/${e}/summary.md`);console.log(` entries: ${n.entryCount} items`)}isSummarizeLockStale(e){let t;try{t=l.default.readFileSync(e,"utf-8")}catch{return true}const r=t.match(/^pid=(\d+)/m);const n=r?Number(r[1]):NaN;if(Number.isFinite(n)){try{process.kill(n,0);return false}catch(s){const o=s;if(o.code==="ESRCH")return true}}try{const s=l.default.statSync(e);return Date.now()-s.mtimeMs>exports.SUMMARIZE_LOCK_STALE_MS}catch{return true}}acquireSummarizeLock(){const e=this.getSummarizeLockPath();const t=`pid=${process.pid}
91
+ `,"utf8"),n);return{status:"updated",entryCount:s.length,newEntries:f.length}}summarize(e,t={}){if(this.useNative()){this.runNative(()=>(0,D.nativeRunHostCommand)(this.nativeSettings(),"summarize",[e],{force:t.force}));return}const r=this.loadAllEntries(e);if(r.length===0){console.log("No memories found.");return}console.log(`\u{1F4DD} Starting summary generation (${r.length} items entries)
92
+ `);const n=this.generateSummary(e,{force:t.force});if(n.status==="up-to-date"){console.log("\u2705 summary.md is up to date.")}else if(n.status==="fallback"){console.log(`\u{1F4CB} Fallback summary generated (AI call failed)`)}else if(n.status==="updated"){console.log(`\u{1F916} Summary complete (${n.newEntries} items applied)`)}console.log(` File: data/${e}/summary.md`);console.log(` entries: ${n.entryCount} items`)}isSummarizeLockStale(e){let t;try{t=d.default.readFileSync(e,"utf-8")}catch{return true}const r=t.match(/^pid=(\d+)/m);const n=r?Number(r[1]):NaN;if(Number.isFinite(n)){try{process.kill(n,0);return false}catch(s){const o=s;if(o.code==="ESRCH")return true}}try{const s=d.default.statSync(e);return Date.now()-s.mtimeMs>exports.SUMMARIZE_LOCK_STALE_MS}catch{return true}}acquireSummarizeLock(){const e=this.getSummarizeLockPath();const t=`pid=${process.pid}
93
93
  mtime=${new Date().toISOString()}
94
- `;try{const r=l.default.openSync(e,"wx");l.default.writeSync(r,t);l.default.closeSync(r);return true}catch(r){const n=r;if(n.code!=="EEXIST")throw n}if(!this.isSummarizeLockStale(e)){return false}l.default.writeFileSync(e,t,"utf-8");return true}releaseSummarizeLock(){try{l.default.unlinkSync(this.getSummarizeLockPath())}catch{}}summarizeDirty(){if(!l.default.existsSync(this.dataDir)){console.log(`\u{1F4A1} Register debounce cron:`);console.log(`crewx cron add "*/1 * * * *" "crewx memory summarize-dirty" --mode command --name "memory-debounce"`);return}if(!this.acquireSummarizeLock()){console.log(`\u23ED\uFE0F summarize-dirty is already running (lock held) \u2014 skipping this run.`);return}try{const e=l.default.readdirSync(this.dataDir,{withFileTypes:true}).filter(t=>t.isDirectory()).map(t=>t.name);for(const t of e){const r=this.getDirtySummaryPath(t);if(!l.default.existsSync(r))continue;try{const n=this.generateSummary(t);if(n.status==="updated"){console.log(`\u{1F916} ${t} summary.md updated (${n.newEntries} items applied)`)}else if(n.status==="fallback"){console.log(`\u{1F4CB} ${t} Fallback summary generated (AI call failed)`)}else if(n.status==="up-to-date"){console.log(`\u2705 ${t} summary.md is up to date.`)}else if(n.status==="empty"){console.log(`\u2139\uFE0F ${t} has no memories to summarize.`)}l.default.unlinkSync(r)}catch(n){console.error(`\u274C ${t} summary.md update failed: ${n.message}`)}}}finally{this.releaseSummarizeLock()}console.log(`\u{1F4A1} Register debounce cron:`);console.log(`crewx cron add "*/1 * * * *" "crewx memory summarize-dirty" --mode command --name "memory-debounce"`)}search(e,t){const r=this.loadAllEntries(e);if(r.length===0){console.log("No memories found.");return}const n=r.map(o=>`[${o.id}] [${o.date}] [${this.getPrimaryTag(o)}] ${o.summary}`).join("\n");const s=`Memory list:
94
+ `;try{const r=d.default.openSync(e,"wx");d.default.writeSync(r,t);d.default.closeSync(r);return true}catch(r){const n=r;if(n.code!=="EEXIST")throw n}if(!this.isSummarizeLockStale(e)){return false}d.default.writeFileSync(e,t,"utf-8");return true}releaseSummarizeLock(){try{d.default.unlinkSync(this.getSummarizeLockPath())}catch{}}summarizeDirty(){if(this.useNative()){this.runNative(()=>(0,D.nativeRunHostCommand)(this.nativeSettings(),"summarize-dirty",[]));return}if(!this.summaryPathExists(this.dataDir)){console.log(`\u{1F4A1} Register debounce cron:`);console.log(`crewx cron add "*/1 * * * *" "crewx memory summarize-dirty" --mode command --name "memory-debounce"`);return}const e=process.platform==="win32"?d.default.readdirSync(this.dataDir,{withFileTypes:true}).filter(t=>t.isDirectory()).map(t=>t.name):null;if(e){for(const t of e){if(!this.summaryPathExists(this.getAgentDir(t)))continue;(0,g.assertWindowsLegacyMemoryClean)(this.getAgentDir(t))}}if(!this.acquireSummarizeLock()){console.log(`\u23ED\uFE0F summarize-dirty is already running (lock held) \u2014 skipping this run.`);return}try{const t=e??d.default.readdirSync(this.dataDir,{withFileTypes:true}).filter(r=>r.isDirectory()).map(r=>r.name);for(const r of t){try{const n=this.captureSummarySnapshot(r);if(n.dirtyMarker===null)continue;const s=this.generateSummaryFromSnapshot(r,{},n,true);if(s.status==="updated"){console.log(`\u{1F916} ${r} summary.md updated (${s.newEntries} items applied)`)}else if(s.status==="fallback"){console.log(`\u{1F4CB} ${r} Fallback summary generated (AI call failed)`)}else if(s.status==="up-to-date"){console.log(`\u2705 ${r} summary.md is up to date.`)}else if(s.status==="empty"){console.log(`\u2139\uFE0F ${r} has no memories to summarize.`)}}catch(n){console.error(`\u274C ${r} summary.md update failed: ${n.message}`)}}}finally{this.releaseSummarizeLock()}console.log(`\u{1F4A1} Register debounce cron:`);console.log(`crewx cron add "*/1 * * * *" "crewx memory summarize-dirty" --mode command --name "memory-debounce"`)}search(e,t){if(this.useNative()){this.runNative(()=>(0,D.nativeRunHostCommand)(this.nativeSettings(),"search",[e,t]));return}const r=this.loadAllEntries(e);if(r.length===0){console.log("No memories found.");return}const n=r.map(o=>`[${o.id}] [${o.date}] [${this.getPrimaryTag(o)}] ${o.summary}`).join("\n");const s=`Memory list:
95
95
  ${n}
96
96
 
97
97
  Question: "${t}"`;try{console.log(`\u{1F50D} "${t}" searching... (${this.searcherAgent})
98
- `);const o=k(["q",`${this.searcherAgent} ${s}`],{encoding:"utf-8",timeout:this.searcherTimeout,stdio:["pipe","pipe","pipe"]});const i=O(o);if(i){console.log(`## \u{1F9E0} Semantic search results
99
- `);console.log(i)}else{console.log(o.trim())}}catch(o){const i=o;if(i.code==="ETIMEDOUT"||i.killed){console.log("Search failed: timed out (max 5 minutes)")}else{console.log("Search failed:",i.message)}console.log("\n\u{1F4A1} Tip: try keyword search with the find command.")}}}exports.MemoryEngine=L;function Z($){return new L($)}var Y=require("./types");Object.defineProperty(exports,"CATEGORIES",{enumerable:true,get:function(){return Y.CATEGORIES}});
98
+ `);const o=k(["q",`${this.searcherAgent} ${s}`],{encoding:"utf-8",timeout:this.searcherTimeout,stdio:["pipe","pipe","pipe"]});const i=B(o);if(i){console.log(`## \u{1F9E0} Semantic search results
99
+ `);console.log(i)}else{console.log(o.trim())}}catch(o){const i=o;if(i.code==="ETIMEDOUT"||i.killed){console.log("Search failed: timed out (max 5 minutes)")}else{console.log("Search failed:",i.message)}console.log("\n\u{1F4A1} Tip: try keyword search with the find command.")}}}exports.MemoryEngine=W;function K(S){return new W(S)}var Y=require("./types");Object.defineProperty(exports,"CATEGORIES",{enumerable:true,get:function(){return Y.CATEGORIES}});
@@ -0,0 +1,2 @@
1
+ export {};
2
+
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});const t=require("@crewx/sdk");function o(){const r=process.argv[2];let s="";process.stdin.setEncoding("utf8");process.stdin.on("data",e=>{s+=e});process.stdin.on("end",()=>{let e="";if(r==="code"){e=(0,t.classifyTaskError)({status:"failed",error:s}).errorCode??""}else if(r==="redact"){e=(0,t.redactTechnicalMessage)(s)??""}process.stdout.write(JSON.stringify({value:e}))})}o();
@@ -56,6 +56,8 @@ export declare function renderText(viewGraph: Graph, agentId: string, filtered:
56
56
  export declare class MindmapEngine {
57
57
  private readonly dataDir;
58
58
  constructor(dataDir: string);
59
+ private useNative;
60
+ private runNative;
59
61
  private getAgentDir;
60
62
  private getEntriesDir;
61
63
  private getGraphPath;
@@ -1,9 +1,9 @@
1
- "use strict";var S=exports&&exports.__importDefault||function(a){return a&&a.__esModule?a:{"default":a}};Object.defineProperty(exports,"__esModule",{value:true});exports.MindmapEngine=void 0;exports.loadAllEntries=w;exports.buildGraph=k;exports.saveGraph=b;exports.loadGraph=f;exports.generateHtml=E;exports.filterGraphByPeriod=P;exports.renderMermaid=T;exports.renderText=N;const g=S(require("fs"));const p=S(require("path"));const x=require("child_process");const O=require("./parser");const j=require("@crewx/knowledge-core");const $=24;const M=7;const D=30;const L={stm:{label:`STM ${$}h`,ms:$*60*60*1e3},mtm:{label:`MTM ${M}d`,ms:M*24*60*60*1e3},ltm:{label:`LTM ${D}d`,ms:D*24*60*60*1e3}};const A=["#6366f1","#8b5cf6","#ec4899","#f43f5e","#f97316","#eab308","#22c55e","#14b8a6","#06b6d4","#3b82f6"];function w(a){if(!g.default.existsSync(a))return[];const t=g.default.readdirSync(a).filter(i=>i.endsWith(".md"));const o=[];for(const i of t){const n=g.default.readFileSync(p.default.join(a,i),"utf-8");const{data:r,content:s}=(0,O.parseFrontmatter)(n);o.push({file:i,content:s,...r})}return o}function k(a,t={}){const{edgeThreshold:o=.3,includeSameDay:i=false}=t;const n=w(a);if(n.length===0){return null}const r=n.map(e=>({id:e.id,type:e["type"]||"memory",category:e.category||"general",tags:e.tags||[],date:e.date||"",summary:e.summary||"",body:e.content||""}));const s=(0,j.buildGraph)(r,{edgeThreshold:o,includeSameDay:i});return{nodes:s.nodes.map(e=>({...e,important:n.find(l=>l.id===e.id)?.important})),edges:s.edges,stats:s.stats,updated:new Date().toISOString()}}function b(a,t){t.updated=new Date().toISOString();g.default.writeFileSync(a,JSON.stringify(t,null,2),"utf-8")}function f(a){if(!g.default.existsSync(a)){return{nodes:[],edges:[],stats:{nodeCount:0,edgeCount:0},updated:null}}return JSON.parse(g.default.readFileSync(a,"utf-8"))}function E(a,t={}){const{colors:o=A,title:i="Memory Graph"}=t;if(Object.keys(a).length===0){return null}const n={};for(const[s,e]of Object.entries(a)){if(!e||!e.nodes||e.nodes.length===0){continue}const l=[...new Set(e.nodes.map(c=>c.tags?.[0]||"general"))];const d={};l.forEach((c,m)=>{d[c]=o[m%o.length]});const u=e.nodes.map(c=>{const m=c.summary?String(c.summary):c.id?String(c.id):"Unknown";const v=c.tags?.[0]||"general";return{id:c.id||"unknown",label:m.slice(0,40),fullLabel:m,topic:v,date:c.date||"-",color:d[v]}});const h=e.edges.map(c=>({source:c.from,target:c.to,weight:c.weight,type:c.type}));n[s]={nodes:u,links:h,topics:l,topicColors:d,updated:e.updated}}const r=Object.keys(n).map(s=>`<option value="${s}">${s}</option>`).join("");return`<!DOCTYPE html>
1
+ "use strict";var $=exports&&exports.__importDefault||function(s){return s&&s.__esModule?s:{"default":s}};Object.defineProperty(exports,"__esModule",{value:true});exports.MindmapEngine=void 0;exports.loadAllEntries=x;exports.buildGraph=k;exports.saveGraph=y;exports.loadGraph=p;exports.generateHtml=E;exports.filterGraphByPeriod=P;exports.renderMermaid=T;exports.renderText=O;const g=$(require("fs"));const f=$(require("path"));const w=require("child_process");const j=require("./parser");const A=require("./storage");const L=require("@crewx/knowledge-core");const b=require("./native-adapter");const M=24;const N=7;const D=30;const R={stm:{label:`STM ${M}h`,ms:M*60*60*1e3},mtm:{label:`MTM ${N}d`,ms:N*24*60*60*1e3},ltm:{label:`LTM ${D}d`,ms:D*24*60*60*1e3}};const _=["#6366f1","#8b5cf6","#ec4899","#f43f5e","#f97316","#eab308","#22c55e","#14b8a6","#06b6d4","#3b82f6"];function x(s){return(0,A.withRecoveredAgentReadSync)(f.default.dirname(s),()=>C(s))}function C(s){if(!g.default.existsSync(s))return[];const t=g.default.readdirSync(s).filter(r=>r.endsWith(".md"));const n=[];for(const r of t){const o=g.default.readFileSync(f.default.join(s,r),"utf-8");const{data:a,content:i}=(0,j.parseFrontmatter)(o);n.push({file:r,content:i,...a})}return n}function k(s,t={}){const{edgeThreshold:n=.3,includeSameDay:r=false}=t;const o=x(s);if(o.length===0){return null}const a=o.map(e=>({id:e.id,type:e["type"]||"memory",category:e.category||"general",tags:e.tags||[],date:e.date||"",summary:e.summary||"",body:e.content||""}));const i=(0,L.buildGraph)(a,{edgeThreshold:n,includeSameDay:r});return{nodes:i.nodes.map(e=>({...e,important:o.find(l=>l.id===e.id)?.important})),edges:i.edges,stats:i.stats,updated:new Date().toISOString()}}function y(s,t){t.updated=new Date().toISOString();g.default.writeFileSync(s,JSON.stringify(t,null,2),"utf-8")}function p(s){if(!g.default.existsSync(s)){return{nodes:[],edges:[],stats:{nodeCount:0,edgeCount:0},updated:null}}return JSON.parse(g.default.readFileSync(s,"utf-8"))}function E(s,t={}){const{colors:n=_,title:r="Memory Graph"}=t;if(Object.keys(s).length===0){return null}const o={};for(const[i,e]of Object.entries(s)){if(!e||!e.nodes||e.nodes.length===0){continue}const l=[...new Set(e.nodes.map(c=>c.tags?.[0]||"general"))];const d={};l.forEach((c,m)=>{d[c]=n[m%n.length]});const u=e.nodes.map(c=>{const m=c.summary?String(c.summary):c.id?String(c.id):"Unknown";const S=c.tags?.[0]||"general";return{id:c.id||"unknown",label:m.slice(0,40),fullLabel:m,topic:S,date:c.date||"-",color:d[S]}});const h=e.edges.map(c=>({source:c.from,target:c.to,weight:c.weight,type:c.type}));o[i]={nodes:u,links:h,topics:l,topicColors:d,updated:e.updated}}const a=Object.keys(o).map(i=>`<option value="${i}">${i}</option>`).join("");return`<!DOCTYPE html>
2
2
  <html lang="en">
3
3
  <head>
4
4
  <meta charset="UTF-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>${i}</title>
6
+ <title>${r}</title>
7
7
  <script src="https://d3js.org/d3.v7.min.js"><\/script>
8
8
  <style>
9
9
  * { margin: 0; padding: 0; box-sizing: border-box; }
@@ -110,8 +110,8 @@
110
110
  <div id="graph"></div>
111
111
 
112
112
  <div class="controls">
113
- <h3>\u{1F4CA} ${i}</h3>
114
- <select id="agentSelect">${r}</select>
113
+ <h3>\u{1F4CA} ${r}</h3>
114
+ <select id="agentSelect">${a}</select>
115
115
  <select id="periodSelect">
116
116
  <option value="all">All</option>
117
117
  <option value="stm">STM (24h)</option>
@@ -127,7 +127,7 @@
127
127
  <div class="tooltip" style="display:none"></div>
128
128
 
129
129
  <script>
130
- const agentData = ${JSON.stringify(n)};
130
+ const agentData = ${JSON.stringify(o)};
131
131
 
132
132
  const urlParams = new URLSearchParams(window.location.search);
133
133
  const agentFromUrl = urlParams.get('agent');
@@ -325,14 +325,14 @@
325
325
  });
326
326
  <\/script>
327
327
  </body>
328
- </html>`}function F(a){if(!a)return null;const t=String(a);const o=t.includes("T")?new Date(t):new Date(`${t}T00:00:00Z`);return Number.isNaN(o.getTime())?null:o}function P(a,t){if(!t||t===true||t==="all"){return{graph:a,label:null,invalid:false}}const o=String(t).toLowerCase();const i=L[o];if(!i){return{graph:a,label:null,invalid:true}}const n=Date.now()-i.ms;const r=(a.nodes||[]).filter(l=>{const d=F(l.date);return d&&d.getTime()>=n});const s=new Set(r.map(l=>l.id));const e=(a.edges||[]).filter(l=>s.has(l.from)&&s.has(l.to));return{graph:{...a,nodes:r,edges:e,stats:{nodeCount:r.length,edgeCount:e.length}},label:i.label,invalid:false}}function R(a,t=30){const o=a?String(a):"";if(o.length<=t)return o;return o.slice(0,t)}function _(a){return String(a).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\r?\n/g," ")}function y(a){return String(a||"").replace(/[^a-zA-Z0-9_-]/g,"_")}function C(a,t){if(!t||t.length===0)return a;const o=new Map;for(const n of t){if(n&&n.id){o.set(n.id,Boolean(n.important))}}if(o.size===0)return a;const i=(a.nodes||[]).map(n=>{if(o.has(n.id)){return{...n,important:o.get(n.id)}}return n});return{...a,nodes:i}}function T(a){const t=[];t.push("```mermaid");t.push("graph LR");const o={};for(const r of a.nodes||[]){const s=r.tags?.[0]||"general";if(!o[s])o[s]=[];o[s].push(r)}const i=Object.keys(o).sort((r,s)=>r.localeCompare(s));for(const r of i){const s=y(r||"general");t.push(` subgraph ${s}`);const e=o[r].slice().sort((l,d)=>{const u=String(l.id||"");const h=String(d.id||"");return u.localeCompare(h)});for(const l of e){const d=R(l.summary||l.id||"Unknown",30);const u=l.important?`\u2B50 ${d}`:d;const h=_(u);const c=y(l.id);t.push(` ${c}["${h}"]`)}t.push(" end")}const n=(a.edges||[]).filter(r=>Number(r.weight)>=.5);for(const r of n){const s=y(r.from);const e=y(r.to);const l=Number.isFinite(r.weight)?r.weight:Number(r.weight);const d=Number.isFinite(l)?l:r.weight;t.push(` ${s} -->|${d}| ${e}`)}t.push("```");return t.join("\n")}function N(a,t,o){console.log(`# ${t} relation graph
329
- `);if(o.label&&!o.invalid){console.log(`> (Period filter: ${o.label})`)}console.log(`> Last updated: ${a.updated||"-"}`);console.log(`> Nodes: ${a.nodes.length} items | Edges: ${a.edges.length} items
330
- `);if(a.nodes.length===0){console.log("No nodes match this period.");return}const i={};for(const s of a.nodes){const e=s.tags?.[0]||"general";if(!i[e])i[e]=[];i[e].push(s)}console.log(`## Clusters by tag
331
- `);for(const[s,e]of Object.entries(i).sort((l,d)=>d[1].length-l[1].length)){console.log(`### ${s} (${e.length} items)`);for(const l of e.slice(0,5)){const d=a.edges.filter(u=>u.from===l.id||u.to===l.id).length;console.log(`- [${l.id}] ${l.summary} (Relations: ${d})`)}if(e.length>5){console.log(`- ... plus ${e.length-5} items`)}console.log("")}const n={};for(const s of a.edges){n[s.from]=(n[s.from]||0)+1;n[s.to]=(n[s.to]||0)+1}const r=Object.entries(n).sort((s,e)=>e[1]-s[1]).slice(0,5);if(r.length>0){console.log(`## Hub nodes (highly connected memories)
332
- `);const s={};a.nodes.forEach(e=>s[e.id]=e);for(const[e,l]of r){const d=s[e];if(d){console.log(`- [${e}] ${d.summary} - ${l} relations`)}}}}class G{constructor(t){this.dataDir=t}getAgentDir(t){return p.default.join(this.dataDir,t)}getEntriesDir(t){return p.default.join(this.getAgentDir(t),"entries")}getGraphPath(t){return p.default.join(this.getAgentDir(t),"graph.json")}getHtmlPath(){return p.default.join(this.dataDir,"mindmap.html")}build(t,o={}){console.log(`\u{1F528} Building graph for ${t}...
333
- `);const i=this.getEntriesDir(t);const n=k(i,{edgeThreshold:.3,...o});if(!n){console.log("No memories found.");return}b(this.getGraphPath(t),n);console.log(`\u2705 Graph build complete!`);console.log(` Nodes: ${n.stats.nodeCount} items`);console.log(` Edges: ${n.stats.edgeCount} items`);console.log(` File: ${t}/graph.json`);if(n.edges.length>0){console.log(`
334
- \u{1F4CA} Top relations (top 10 by weight):`);const r=n.edges.sort((e,l)=>l.weight-e.weight).slice(0,10);const s={};n.nodes.forEach(e=>s[e.id]=e.summary);for(const e of r){const l=(s[e.from]||e.from).slice(0,25);const d=(s[e.to]||e.to).slice(0,25);console.log(` [${e.weight}] ${l}... \u2194 ${d}...`)}}}show(t,o={}){const i=f(this.getGraphPath(t));if(!i.nodes||i.nodes.length===0){console.log("No graph found. Run the build command first.");return}const n=P(i,o.period);if(n.invalid){console.log(`\u26A0\uFE0F Unknown period: ${o.period} (stm|mtm|ltm)`)}let r=n.invalid?i:n.graph;const s=w(this.getEntriesDir(t));r=C(r,s);const e=z(o.format);if(e==="text"){N(r,t,n);return}if(!r.nodes||r.nodes.length===0){console.log("No nodes match this period.");return}if(n.label&&!n.invalid){console.log(`(Period filter: ${n.label})`)}console.log(T(r))}related(t,o){const i=f(this.getGraphPath(t));if(!i.nodes||i.nodes.length===0){console.log("No graph found. Run the build command first.");return}const n=i.nodes.find(e=>e.id===o);if(!n){console.log(`ID '${o}' not found.`);return}console.log(`## \u{1F517} [${o}] ${n.summary}
335
- `);console.log(`- Date: ${n.date||"-"}`);console.log(`- Tags: ${(n.tags||[]).join(", ")||"-"}
336
- `);const r=i.edges.filter(e=>e.from===o||e.to===o);if(r.length===0){console.log("No related memories found.");return}console.log(`### Related memories (${r.length} items)
337
- `);const s={};i.nodes.forEach(e=>s[e.id]=e);r.sort((e,l)=>l.weight-e.weight);for(const e of r){const l=e.from===o?e.to:e.from;const d=s[l];if(d){const u=e.reasons.join(", ");console.log(`[${e.weight}] [${l}] ${d.summary}`);console.log(` \u2514\u2500 Relation reason: ${u}`)}}}add(t,o,i,n="manual"){const r=f(this.getGraphPath(t));if(!r.nodes||r.nodes.length===0){console.log("No graph found. Run the build command first.");return}const s=r.nodes.find(d=>d.id===o);const e=r.nodes.find(d=>d.id===i);if(!s){console.log(`ID '${o}' not found.`);return}if(!e){console.log(`ID '${i}' not found.`);return}const l=r.edges.find(d=>d.from===o&&d.to===i||d.from===i&&d.to===o);if(l){console.log(`Already related: weight ${l.weight}`);return}r.edges.push({from:o,to:i,type:n,weight:1,reasons:[n],manual:true});b(this.getGraphPath(t),r);console.log(`\u2705 Relation added!`);console.log(` ${(s.summary||"").slice(0,30)}...`);console.log(` \u2194`);console.log(` ${(e.summary||"").slice(0,30)}...`)}remove(t,o,i){const n=f(this.getGraphPath(t));if(!n.edges||n.edges.length===0){console.log("No relations found.");return}const r=n.edges.findIndex(s=>s.from===o&&s.to===i||s.from===i&&s.to===o);if(r===-1){console.log("Relation not found.");return}n.edges.splice(r,1);b(this.getGraphPath(t),n);console.log(`\u{1F5D1}\uFE0F Relation removed: ${o} \u2194 ${i}`)}html(){if(!g.default.existsSync(this.dataDir)){console.log("Data directory not found.");return}const t=g.default.readdirSync(this.dataDir).filter(e=>{const l=p.default.join(this.dataDir,e);try{return g.default.statSync(l).isDirectory()}catch{return false}});const o={};let i=0;let n=0;for(const e of t){const l=f(this.getGraphPath(e));if(l.nodes&&l.nodes.length>0){o[e]=l;i+=l.nodes.length;n+=l.edges.length}}if(Object.keys(o).length===0){console.log("No graph found. Run the build command first.");return}const r=E(o,{title:"Memory Graph - All Agents"});if(!r){console.log("HTML generation failed");return}const s=this.getHtmlPath();g.default.writeFileSync(s,r,"utf-8");console.log(`\u2705 Shared graph visualization generated!`);console.log(` File: ${s}`);console.log(` Agents: ${Object.keys(o).length} items`);console.log(` all Nodes: ${i} items | all Edges: ${n} items`);console.log(`
338
- Open in browser: open ${s}`)}open(t){const o=this.getHtmlPath();if(!g.default.existsSync(o)){console.log("mindmap.html not found. Run the html command first.");return}const i=`file://${o}${t?"?agent="+t:""}`;try{(0,x.execSync)(`osascript -e 'tell application "Google Chrome" to open location "${i}"'`);console.log(`\u2705 Opening graph in Chrome: ${t||"all"}`)}catch{try{(0,x.execSync)(`osascript -e 'tell application "Safari" to open location "${i}"'`);console.log(`\u2705 Opening graph in Safari: ${t||"all"}`)}catch{(0,x.execSync)(`open "${i}"`);console.log(`\u2705 Opening graph in the default browser: ${t||"all"}`)}}}}exports.MindmapEngine=G;function z(a){if(!a||a===true)return"mermaid";return String(a).toLowerCase()}
328
+ </html>`}function F(s){if(!s)return null;const t=String(s);const n=t.includes("T")?new Date(t):new Date(`${t}T00:00:00Z`);return Number.isNaN(n.getTime())?null:n}function P(s,t){if(!t||t===true||t==="all"){return{graph:s,label:null,invalid:false}}const n=String(t).toLowerCase();const r=R[n];if(!r){return{graph:s,label:null,invalid:true}}const o=Date.now()-r.ms;const a=(s.nodes||[]).filter(l=>{const d=F(l.date);return d&&d.getTime()>=o});const i=new Set(a.map(l=>l.id));const e=(s.edges||[]).filter(l=>i.has(l.from)&&i.has(l.to));return{graph:{...s,nodes:a,edges:e,stats:{nodeCount:a.length,edgeCount:e.length}},label:r.label,invalid:false}}function G(s,t=30){const n=s?String(s):"";if(n.length<=t)return n;return n.slice(0,t)}function z(s){return String(s).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\r?\n/g," ")}function v(s){return String(s||"").replace(/[^a-zA-Z0-9_-]/g,"_")}function U(s,t){if(!t||t.length===0)return s;const n=new Map;for(const o of t){if(o&&o.id){n.set(o.id,Boolean(o.important))}}if(n.size===0)return s;const r=(s.nodes||[]).map(o=>{if(n.has(o.id)){return{...o,important:n.get(o.id)}}return o});return{...s,nodes:r}}function T(s){const t=[];t.push("```mermaid");t.push("graph LR");const n={};for(const a of s.nodes||[]){const i=a.tags?.[0]||"general";if(!n[i])n[i]=[];n[i].push(a)}const r=Object.keys(n).sort((a,i)=>a.localeCompare(i));for(const a of r){const i=v(a||"general");t.push(` subgraph ${i}`);const e=n[a].slice().sort((l,d)=>{const u=String(l.id||"");const h=String(d.id||"");return u.localeCompare(h)});for(const l of e){const d=G(l.summary||l.id||"Unknown",30);const u=l.important?`\u2B50 ${d}`:d;const h=z(u);const c=v(l.id);t.push(` ${c}["${h}"]`)}t.push(" end")}const o=(s.edges||[]).filter(a=>Number(a.weight)>=.5);for(const a of o){const i=v(a.from);const e=v(a.to);const l=Number.isFinite(a.weight)?a.weight:Number(a.weight);const d=Number.isFinite(l)?l:a.weight;t.push(` ${i} -->|${d}| ${e}`)}t.push("```");return t.join("\n")}function O(s,t,n){console.log(`# ${t} relation graph
329
+ `);if(n.label&&!n.invalid){console.log(`> (Period filter: ${n.label})`)}console.log(`> Last updated: ${s.updated||"-"}`);console.log(`> Nodes: ${s.nodes.length} items | Edges: ${s.edges.length} items
330
+ `);if(s.nodes.length===0){console.log("No nodes match this period.");return}const r={};for(const i of s.nodes){const e=i.tags?.[0]||"general";if(!r[e])r[e]=[];r[e].push(i)}console.log(`## Clusters by tag
331
+ `);for(const[i,e]of Object.entries(r).sort((l,d)=>d[1].length-l[1].length)){console.log(`### ${i} (${e.length} items)`);for(const l of e.slice(0,5)){const d=s.edges.filter(u=>u.from===l.id||u.to===l.id).length;console.log(`- [${l.id}] ${l.summary} (Relations: ${d})`)}if(e.length>5){console.log(`- ... plus ${e.length-5} items`)}console.log("")}const o={};for(const i of s.edges){o[i.from]=(o[i.from]||0)+1;o[i.to]=(o[i.to]||0)+1}const a=Object.entries(o).sort((i,e)=>e[1]-i[1]).slice(0,5);if(a.length>0){console.log(`## Hub nodes (highly connected memories)
332
+ `);const i={};s.nodes.forEach(e=>i[e.id]=e);for(const[e,l]of a){const d=i[e];if(d){console.log(`- [${e}] ${d.summary} - ${l} relations`)}}}}class B{constructor(t){this.dataDir=t}useNative(){const t=(0,b.nativeRuntimeMode)();if(t==="node")return false;if(t==="go")return true;return(0,b.isNativeAdapterAvailable)()}runNative(t,n={}){const r=(0,b.nativeRunCommand)(this.dataDir,"mindmap",t,n);(0,b.writeNativeOutput)(r);if(r.exitCode!==0){throw new Error(r.stderr.trim()||r.stdout.trim()||`native graph command failed (exit ${r.exitCode})`)}}getAgentDir(t){return f.default.join(this.dataDir,t)}getEntriesDir(t){return f.default.join(this.getAgentDir(t),"entries")}getGraphPath(t){return f.default.join(this.getAgentDir(t),"graph.json")}getHtmlPath(){return f.default.join(this.dataDir,"mindmap.html")}build(t,n={}){if(this.useNative()){this.runNative(["build",t],{...n});return}console.log(`\u{1F528} Building graph for ${t}...
333
+ `);const r=this.getEntriesDir(t);const o=k(r,{edgeThreshold:.3,...n});if(!o){console.log("No memories found.");return}y(this.getGraphPath(t),o);console.log(`\u2705 Graph build complete!`);console.log(` Nodes: ${o.stats.nodeCount} items`);console.log(` Edges: ${o.stats.edgeCount} items`);console.log(` File: ${t}/graph.json`);if(o.edges.length>0){console.log(`
334
+ \u{1F4CA} Top relations (top 10 by weight):`);const a=o.edges.sort((e,l)=>l.weight-e.weight).slice(0,10);const i={};o.nodes.forEach(e=>i[e.id]=e.summary);for(const e of a){const l=(i[e.from]||e.from).slice(0,25);const d=(i[e.to]||e.to).slice(0,25);console.log(` [${e.weight}] ${l}... \u2194 ${d}...`)}}}show(t,n={}){if(this.useNative()){this.runNative(["show",t],{period:n.period,format:n.format});return}const r=p(this.getGraphPath(t));if(!r.nodes||r.nodes.length===0){console.log("No graph found. Run the build command first.");return}const o=P(r,n.period);if(o.invalid){console.log(`\u26A0\uFE0F Unknown period: ${n.period} (stm|mtm|ltm)`)}let a=o.invalid?r:o.graph;const i=x(this.getEntriesDir(t));a=U(a,i);const e=H(n.format);if(e==="text"){O(a,t,o);return}if(!a.nodes||a.nodes.length===0){console.log("No nodes match this period.");return}if(o.label&&!o.invalid){console.log(`(Period filter: ${o.label})`)}console.log(T(a))}related(t,n){if(this.useNative()){this.runNative(["related",t,n]);return}const r=p(this.getGraphPath(t));if(!r.nodes||r.nodes.length===0){console.log("No graph found. Run the build command first.");return}const o=r.nodes.find(e=>e.id===n);if(!o){console.log(`ID '${n}' not found.`);return}console.log(`## \u{1F517} [${n}] ${o.summary}
335
+ `);console.log(`- Date: ${o.date||"-"}`);console.log(`- Tags: ${(o.tags||[]).join(", ")||"-"}
336
+ `);const a=r.edges.filter(e=>e.from===n||e.to===n);if(a.length===0){console.log("No related memories found.");return}console.log(`### Related memories (${a.length} items)
337
+ `);const i={};r.nodes.forEach(e=>i[e.id]=e);a.sort((e,l)=>l.weight-e.weight);for(const e of a){const l=e.from===n?e.to:e.from;const d=i[l];if(d){const u=e.reasons.join(", ");console.log(`[${e.weight}] [${l}] ${d.summary}`);console.log(` \u2514\u2500 Relation reason: ${u}`)}}}add(t,n,r,o="manual"){if(this.useNative()){this.runNative(["add",t,n,r,o]);return}const a=p(this.getGraphPath(t));if(!a.nodes||a.nodes.length===0){console.log("No graph found. Run the build command first.");return}const i=a.nodes.find(d=>d.id===n);const e=a.nodes.find(d=>d.id===r);if(!i){console.log(`ID '${n}' not found.`);return}if(!e){console.log(`ID '${r}' not found.`);return}const l=a.edges.find(d=>d.from===n&&d.to===r||d.from===r&&d.to===n);if(l){console.log(`Already related: weight ${l.weight}`);return}a.edges.push({from:n,to:r,type:o,weight:1,reasons:[o],manual:true});y(this.getGraphPath(t),a);console.log(`\u2705 Relation added!`);console.log(` ${(i.summary||"").slice(0,30)}...`);console.log(` \u2194`);console.log(` ${(e.summary||"").slice(0,30)}...`)}remove(t,n,r){if(this.useNative()){this.runNative(["remove",t,n,r]);return}const o=p(this.getGraphPath(t));if(!o.edges||o.edges.length===0){console.log("No relations found.");return}const a=o.edges.findIndex(i=>i.from===n&&i.to===r||i.from===r&&i.to===n);if(a===-1){console.log("Relation not found.");return}o.edges.splice(a,1);y(this.getGraphPath(t),o);console.log(`\u{1F5D1}\uFE0F Relation removed: ${n} \u2194 ${r}`)}html(){if(this.useNative()){this.runNative(["html"]);return}if(!g.default.existsSync(this.dataDir)){console.log("Data directory not found.");return}const t=g.default.readdirSync(this.dataDir).filter(e=>{const l=f.default.join(this.dataDir,e);try{return g.default.statSync(l).isDirectory()}catch{return false}});const n={};let r=0;let o=0;for(const e of t){const l=p(this.getGraphPath(e));if(l.nodes&&l.nodes.length>0){n[e]=l;r+=l.nodes.length;o+=l.edges.length}}if(Object.keys(n).length===0){console.log("No graph found. Run the build command first.");return}const a=E(n,{title:"Memory Graph - All Agents"});if(!a){console.log("HTML generation failed");return}const i=this.getHtmlPath();g.default.writeFileSync(i,a,"utf-8");console.log(`\u2705 Shared graph visualization generated!`);console.log(` File: ${i}`);console.log(` Agents: ${Object.keys(n).length} items`);console.log(` all Nodes: ${r} items | all Edges: ${o} items`);console.log(`
338
+ Open in browser: open ${i}`)}open(t){const n=this.getHtmlPath();if(!g.default.existsSync(n)){console.log("mindmap.html not found. Run the html command first.");return}const r=`file://${n}${t?"?agent="+t:""}`;try{(0,w.execSync)(`osascript -e 'tell application "Google Chrome" to open location "${r}"'`);console.log(`\u2705 Opening graph in Chrome: ${t||"all"}`)}catch{try{(0,w.execSync)(`osascript -e 'tell application "Safari" to open location "${r}"'`);console.log(`\u2705 Opening graph in Safari: ${t||"all"}`)}catch{(0,w.execSync)(`open "${r}"`);console.log(`\u2705 Opening graph in the default browser: ${t||"all"}`)}}}}exports.MindmapEngine=B;function H(s){if(!s||s===true)return"mermaid";return String(s).toLowerCase()}
@@ -0,0 +1,45 @@
1
+ import type { MemoryEntry } from './types';
2
+ import { type PreparedNativeHost } from './native-host';
3
+ import type { MemoryEngineSettings } from './settings';
4
+ export interface NativeMemoryArtifact {
5
+ executablePath: string;
6
+ packageRoot: string;
7
+ packageVersion: string;
8
+ protocol: number;
9
+ capabilities: string[];
10
+ }
11
+ export type NativeRuntimeMode = 'auto' | 'go' | 'node';
12
+ export interface NativeRpcResponse {
13
+ version: number;
14
+ ok: boolean;
15
+ exitCode: number;
16
+ stdout: string;
17
+ stderr: string;
18
+ result?: unknown;
19
+ error?: string;
20
+ }
21
+ export declare const NATIVE_API_CAPABILITY = "memory.api.v1";
22
+ export declare function getNativeMemoryArtifact(): NativeMemoryArtifact | null;
23
+ export declare function nativeRuntimeMode(): NativeRuntimeMode;
24
+ export declare function isNativeAdapterAvailable(): boolean;
25
+ export declare function callNativeRpc(payload: Record<string, unknown>, options?: {
26
+ env?: NodeJS.ProcessEnv;
27
+ }): NativeRpcResponse;
28
+ export declare function writeNativeOutput(response: Pick<NativeRpcResponse, 'stdout' | 'stderr'>): void;
29
+ export declare function hostFor(settings: MemoryEngineSettings): PreparedNativeHost;
30
+ export declare function nativeLoadAllEntries(dataDir: string, agentId: string, includeBodies?: boolean): MemoryEntry[];
31
+ export declare function nativeGetRecentEntries(dataDir: string, agentId: string, days?: number, opts?: {
32
+ includeBody?: boolean;
33
+ }): MemoryEntry[];
34
+ export declare function nativeRunCommand(dataDir: string, command: string, args: string[], flags?: Record<string, unknown>, extra?: {
35
+ body?: string;
36
+ rawSave?: boolean;
37
+ }): NativeRpcResponse;
38
+ export declare function nativeRunHostCommand(settings: MemoryEngineSettings, command: string, args: string[], flags?: Record<string, unknown>): NativeRpcResponse;
39
+ export declare function nativeGenerateSummary(settings: MemoryEngineSettings, agentId: string, force: boolean): {
40
+ status: 'empty' | 'up-to-date' | 'fallback' | 'updated' | 'cancelled';
41
+ entryCount: number;
42
+ newEntries: number;
43
+ pending: boolean;
44
+ };
45
+
@@ -0,0 +1 @@
1
+ "use strict";var w=exports&&exports.__createBinding||(Object.create?(function(e,r,i,t){if(t===void 0)t=i;var n=Object.getOwnPropertyDescriptor(r,i);if(!n||("get"in n?!r.__esModule:n.writable||n.configurable)){n={enumerable:true,get:function(){return r[i]}}}Object.defineProperty(e,t,n)}):(function(e,r,i,t){if(t===void 0)t=i;e[t]=r[i]}));var g=exports&&exports.__setModuleDefault||(Object.create?(function(e,r){Object.defineProperty(e,"default",{enumerable:true,value:r})}):function(e,r){e["default"]=r});var y=exports&&exports.__importStar||(function(){var e=function(r){e=Object.getOwnPropertyNames||function(i){var t=[];for(var n in i)if(Object.prototype.hasOwnProperty.call(i,n))t[t.length]=n;return t};return e(r)};return function(r){if(r&&r.__esModule)return r;var i={};if(r!=null){for(var t=e(r),n=0;n<t.length;n++)if(t[n]!=="default")w(i,r,t[n])}g(i,r);return i}})();Object.defineProperty(exports,"__esModule",{value:true});exports.NATIVE_API_CAPABILITY=void 0;exports.getNativeMemoryArtifact=p;exports.nativeRuntimeMode=_;exports.isNativeAdapterAvailable=I;exports.callNativeRpc=c;exports.writeNativeOutput=M;exports.hostFor=m;exports.nativeLoadAllEntries=j;exports.nativeGetRecentEntries=C;exports.nativeRunCommand=T;exports.nativeRunHostCommand=V;exports.nativeGenerateSummary=B;const o=y(require("fs"));const s=y(require("path"));const b=require("child_process");const A=require("./native-host");exports.NATIVE_API_CAPABILITY="memory.api.v1";const N=4;const E=512*1024*1024;let l;function O(){const e=[];if(process.env.CREWX_SHELL_NATIVE_DIR){e.push(s.join(process.env.CREWX_SHELL_NATIVE_DIR,"@crewx","memory"))}const r=process.resourcesPath;if(typeof r==="string"){e.push(s.join(r,"shell-native","node_modules","@crewx","memory"))}let i=__dirname;for(let t=0;t<4;t++){e.push(i);const n=s.dirname(i);if(n===i)break;i=n}return e}function P(e){try{return JSON.parse(o.readFileSync(s.join(e,"package.json"),"utf8"))}catch{return null}}function R(e){const r=P(e);if(!r||r.name!=="@crewx/memory")return null;const i=s.join(e,"go","native-manifest.json");if(!o.existsSync(i))return null;const t=JSON.parse(o.readFileSync(i,"utf8"));if(typeof t.packageVersion!=="string"||!t.packageVersion)return null;if(r.version!==t.packageVersion)return null;const n=Number(t.protocol);if(n!==N)return null;if(!Array.isArray(t.capabilities)||!t.capabilities.includes(exports.NATIVE_API_CAPABILITY))return null;const a={darwin:"darwin",linux:"linux",win32:"windows"}[process.platform];const v={arm64:"arm64",x64:"amd64"}[process.arch];if(!a||!v)return null;const u=t.targets?.[`${a}-${v}`];if(!u||typeof u.file!=="string")return null;const f=s.resolve(e,...u.file.split("/"));if(!o.existsSync(f))return null;if(process.platform!=="win32"){try{const d=o.statSync(f);if((d.mode&73)===0)o.chmodSync(f,d.mode|493)}catch{}}const h=Array.isArray(u.capabilities)?u.capabilities.filter(d=>typeof d==="string"):t.capabilities;return{executablePath:f,packageRoot:e,packageVersion:t.packageVersion,protocol:n,capabilities:h}}function p(){if(l!==void 0)return l;l=null;for(const e of O()){try{const r=R(e);if(r){l=r;break}}catch{}}return l}function _(){const e=process.env.CREWX_MEMORY_RUNTIME??"auto";return e==="go"||e==="node"?e:"auto"}function I(){if(_()==="node")return false;return p()!==null}function S(){const e=p();if(!e){throw new Error("Native memory executable is unavailable. Reinstall @crewx/memory, or set CREWX_MEMORY_RUNTIME=node to use the existing implementation.")}return e}function c(e,r={}){const i=S();const t=(0,b.spawnSync)(i.executablePath,[`--crewx-memory-protocol=${i.protocol}`,`--crewx-memory-version=${i.packageVersion}`,"api","rpc"],{input:JSON.stringify({version:1,...e}),encoding:"utf8",env:r.env??process.env,maxBuffer:E,windowsHide:true});if(t.error)throw t.error;const n=(t.stderr??"").trim();let a;try{a=JSON.parse(t.stdout??"")}catch{if(t.status===null){throw new Error(`Native memory was terminated${t.signal?` (${t.signal})`:""}.`)}throw new Error(`Native memory returned an invalid response (exit ${t.status})${n?`: ${n}`:""}`)}if(t.status!==0||!a.ok){throw new Error(a.error??(n||`Native memory failed (exit ${t.status})`))}return a}function M(e){if(e.stdout)process.stdout.write(e.stdout);if(e.stderr)process.stderr.write(e.stderr)}function m(e){return(0,A.prepareNativeHost)(e)}function j(e,r,i=false){const t=c({op:"entries",dataDir:e,args:[r],includeBody:i});return t.result??[]}function C(e,r,i=30,t={}){const n=c({op:"recent",dataDir:e,args:[r],days:i,includeBody:Boolean(t.includeBody)});return n.result??[]}function T(e,r,i,t={},n={}){return c({op:"command",dataDir:e,command:r,args:i,flags:t,...n.body===void 0?{}:{body:n.body},...n.rawSave?{rawSave:true}:{}})}function V(e,r,i,t={}){const n=m(e);return c({op:"command",dataDir:e.dataDir,command:r,args:i,flags:t,host:n.request},{env:n.env})}function B(e,r,i){const t=m(e);const n=c({op:"summary",dataDir:e.dataDir,args:[r],flags:{force:i},host:t.request},{env:t.env});if(n.stderr)process.stderr.write(n.stderr);return n.result}
@@ -0,0 +1,35 @@
1
+ import { type MemoryEngineSettings } from './settings';
2
+ export interface NativeHostCommand {
3
+ command: string;
4
+ args: string[];
5
+ shell: boolean;
6
+ windowsHide: boolean;
7
+ }
8
+ export interface NativeHostRequest {
9
+ crewx: NativeHostCommand | null;
10
+ crewxError?: string;
11
+ classifier: NativeHostCommand;
12
+ summary: {
13
+ summaryDays: number;
14
+ summarizerAgent: string;
15
+ summarizerTimeoutMs: number;
16
+ searcherAgent: string;
17
+ searcherTimeoutMs: number;
18
+ };
19
+ }
20
+ export interface PreparedNativeHost {
21
+ env: NodeJS.ProcessEnv;
22
+ request: NativeHostRequest;
23
+ }
24
+ interface ResolvedCrewxChild {
25
+ command: string;
26
+ args: string[];
27
+ env: NodeJS.ProcessEnv;
28
+ shell: boolean;
29
+ windowsHide: boolean;
30
+ }
31
+ export declare function resolveCrewxChild(env?: NodeJS.ProcessEnv, cwd?: string): ResolvedCrewxChild;
32
+ export declare function prepareNativeHost(settings: MemoryEngineSettings, env?: NodeJS.ProcessEnv): PreparedNativeHost;
33
+ export declare function prepareCliHostRequest(env?: NodeJS.ProcessEnv): PreparedNativeHost;
34
+ export {};
35
+
@@ -0,0 +1 @@
1
+ "use strict";var l=exports&&exports.__createBinding||(Object.create?(function(t,e,n,r){if(r===void 0)r=n;var a=Object.getOwnPropertyDescriptor(e,n);if(!a||("get"in a?!e.__esModule:a.writable||a.configurable)){a={enumerable:true,get:function(){return e[n]}}}Object.defineProperty(t,r,a)}):(function(t,e,n,r){if(r===void 0)r=n;t[r]=e[n]}));var d=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:true,value:e})}):function(t,e){t["default"]=e});var f=exports&&exports.__importStar||(function(){var t=function(e){t=Object.getOwnPropertyNames||function(n){var r=[];for(var a in n)if(Object.prototype.hasOwnProperty.call(n,a))r[r.length]=a;return r};return t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null){for(var r=t(e),a=0;a<r.length;a++)if(r[a]!=="default")l(n,e,r[a])}d(n,e);return n}})();Object.defineProperty(exports,"__esModule",{value:true});exports.resolveCrewxChild=c;exports.prepareNativeHost=u;exports.prepareCliHostRequest=h;const m=f(require("path"));const s=require("@crewx/sdk");const v=require("./settings");function c(t=process.env,e=process.cwd()){const n=(0,s.resolveCrewxExecutable)({env:t,cwd:e});if(!n.ok){const o=new Error((0,s.formatCrewxExecutableFailure)(n));Object.assign(o,{code:"CLI_UNRESOLVABLE"});throw o}const r=(0,s.createCrewxChildInvocation)(n,{baseEnv:t});const a=(0,s.resolveWindowsSpawnProgram)({command:r.command,env:r.env,cwd:e,packageName:"crewx",allowShellFallback:true});const i=(0,s.materializeWindowsSpawnProgram)(a,r.args);return{command:i.command,args:i.argv,env:r.env,shell:i.shell===true,windowsHide:i.windowsHide===true}}function u(t,e=process.env){let n=null;let r;let a={...e};try{const i=c(e);n={command:i.command,args:i.args,shell:i.shell,windowsHide:i.windowsHide};a={...i.env}}catch(i){r=i instanceof Error?i.message:String(i)}if(process.versions.electron)a.ELECTRON_RUN_AS_NODE="1";return{env:a,request:{crewx:n,...r===void 0?{}:{crewxError:r},classifier:{command:process.execPath,args:[m.join(__dirname,"host-classifier.js")],shell:false,windowsHide:true},summary:{summaryDays:t.summaryDays,summarizerAgent:t.summarizerAgent,summarizerTimeoutMs:t.summarizerTimeout,searcherAgent:t.searcherAgent,searcherTimeoutMs:t.searcherTimeout}}}}function h(t=process.env){return u((0,v.resolveEngineSettings)({}),t)}
@@ -1,3 +1,6 @@
1
- export { parseFrontmatter, stringifyFrontmatter } from '@crewx/knowledge-core';
2
- export type { ParsedFrontmatter } from '@crewx/knowledge-core';
1
+ import { stringifyFrontmatter } from '@crewx/knowledge-core';
2
+ import type { ParsedFrontmatter } from '@crewx/knowledge-core';
3
+ export declare function parseFrontmatter(raw: string): ParsedFrontmatter;
4
+ export { stringifyFrontmatter };
5
+ export type { ParsedFrontmatter };
3
6
 
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.stringifyFrontmatter=exports.parseFrontmatter=void 0;var e=require("@crewx/knowledge-core");Object.defineProperty(exports,"parseFrontmatter",{enumerable:true,get:function(){return e.parseFrontmatter}});Object.defineProperty(exports,"stringifyFrontmatter",{enumerable:true,get:function(){return e.stringifyFrontmatter}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.stringifyFrontmatter=void 0;exports.parseFrontmatter=a;const e=require("@crewx/knowledge-core");Object.defineProperty(exports,"stringifyFrontmatter",{enumerable:true,get:function(){return e.stringifyFrontmatter}});const n="Invalid memory frontmatter YAML";function a(o){let r;try{r=(0,e.parseFrontmatter)(o)}catch(t){if(t instanceof Error&&t.name==="YAMLException"){throw new Error(n)}throw t}if(r.data===null||typeof r.data!=="object"||Array.isArray(r.data)){throw new Error(n)}return r}
@@ -0,0 +1,14 @@
1
+ import type { MemoryEngineConfig } from './types';
2
+ export declare function getMemoryConfig(): Record<string, unknown>;
3
+ export interface MemoryEngineSettings {
4
+ dataDir: string;
5
+ summaryDays: number;
6
+ recentDays: number;
7
+ shortTermHours: number;
8
+ summarizerAgent: string;
9
+ searcherAgent: string;
10
+ summarizerTimeout: number;
11
+ searcherTimeout: number;
12
+ }
13
+ export declare function resolveEngineSettings(config?: MemoryEngineConfig): MemoryEngineSettings;
14
+
@@ -0,0 +1 @@
1
+ "use strict";var n=exports&&exports.__importDefault||function(e){return e&&e.__esModule?e:{"default":e}};Object.defineProperty(exports,"__esModule",{value:true});exports.getMemoryConfig=o;exports.resolveEngineSettings=g;const d=n(require("fs"));const u=n(require("path"));const y=require("child_process");const h=n(require("js-yaml"));function f(){try{return(0,y.execSync)("git rev-parse --show-toplevel",{encoding:"utf8"}).trim()}catch{return process.cwd()}}function o(){try{const e=process.env.CREWX_CONFIG??u.default.join(f(),"crewx.yaml");const r=d.default.readFileSync(e,"utf8");const t=h.default.load(r);const s=t?.settings;return s?.memory??{}}catch{return{}}}function g(e={}){const r=o();const t=e.dataDir??process.env["MEMORY_DATA_DIR"]??u.default.resolve(process.cwd(),"memory");const s=e.summaryDays??(r.summary_days!=null?Number(r.summary_days):void 0)??(parseInt(process.env["MEMORY_SUMMARY_DAYS"]??"",10)||7);const a=e.recentDays??(r.recent_days!=null?Number(r.recent_days):void 0)??(parseInt(process.env["MEMORY_RECENT_DAYS"]??"",10)||30);const m=e.shortTermHours??(r.short_term_hours!=null?Number(r.short_term_hours):void 0)??24;const c=e.summarizerAgent??r.summarizer_agent??"@memory_summarizer";const i=e.searcherAgent??r.searcher_agent??"@memory_searcher";const _=e.summarizerTimeout??(r.summarizer_timeout!=null?Number(r.summarizer_timeout):void 0)??48e4;const l=e.searcherTimeout??(r.searcher_timeout!=null?Number(r.searcher_timeout):void 0)??3e5;return{dataDir:t,summaryDays:s,recentDays:a,shortTermHours:m,summarizerAgent:c,searcherAgent:i,summarizerTimeout:_,searcherTimeout:l}}
@@ -0,0 +1,42 @@
1
+ interface LockOwner {
2
+ version: number;
3
+ pid: number;
4
+ host: string;
5
+ token: string;
6
+ }
7
+ export interface MemoryFileChange {
8
+ path: string;
9
+ contents: Uint8Array | null;
10
+ }
11
+ export interface MemoryWriterToken {
12
+ readonly agentDir: string;
13
+ readonly owner: LockOwner;
14
+ readonly recovered: boolean;
15
+ }
16
+ export interface MemoryReadToken {
17
+ readonly agentDir: string;
18
+ readonly held: boolean;
19
+ readonly recovered: boolean;
20
+ }
21
+ export interface CommitMemoryFilesOptions {
22
+ token: MemoryWriterToken;
23
+ fault?: (stage: string, transactionDir: string) => void;
24
+ advanceGeneration?: boolean;
25
+ }
26
+ export declare class MemoryJournalCrash extends Error {
27
+ readonly stage: string;
28
+ constructor(stage: string);
29
+ }
30
+ export declare function nextDirtyMarker(agentDir: string, now?: number): Buffer;
31
+ export declare function assertMemoryOverwritePermission(agentDir: string, relativePath: string, token: MemoryWriterToken): void;
32
+ export declare function writeDirtySummaryMarkerBestEffort(agentDir: string, token: MemoryWriterToken, now?: number): boolean;
33
+ export declare function assertWindowsLegacyMemoryClean(agentDir: string, expectedOwnerToken?: string): void;
34
+ export declare function withWindowsMemoryWriterLock<T>(agentDir: string, operation: (token: MemoryWriterToken) => T, waitMs?: number): T;
35
+ export declare function advanceWindowsMemoryGeneration(agentDir: string, token: MemoryWriterToken): string;
36
+ export declare function withMemoryWriterLock<T>(agentDir: string, operation: (token: MemoryWriterToken) => T, waitMs?: number): T;
37
+ export declare function withMemoryWriterLockAsync<T>(agentDir: string, operation: (token: MemoryWriterToken) => Promise<T>, waitMs?: number): Promise<T>;
38
+ export declare function withRecoveredAgentReadSync<T>(agentDir: string, operation: (token: MemoryReadToken) => T): T;
39
+ export declare function withRecoveredAgentRead<T>(agentDir: string, operation: (token: MemoryReadToken) => Promise<T>): Promise<T>;
40
+ export declare function commitMemoryFiles(agentDir: string, changes: MemoryFileChange[], options: CommitMemoryFilesOptions): void;
41
+ export {};
42
+
@@ -0,0 +1 @@
1
+ "use strict";var Er=exports&&exports.__createBinding||(Object.create?(function(r,t,e,o){if(o===void 0)o=e;var n=Object.getOwnPropertyDescriptor(t,e);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable)){n={enumerable:true,get:function(){return t[e]}}}Object.defineProperty(r,o,n)}):(function(r,t,e,o){if(o===void 0)o=e;r[o]=t[e]}));var Sr=exports&&exports.__setModuleDefault||(Object.create?(function(r,t){Object.defineProperty(r,"default",{enumerable:true,value:t})}):function(r,t){r["default"]=t});var F=exports&&exports.__importStar||(function(){var r=function(t){r=Object.getOwnPropertyNames||function(e){var o=[];for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n))o[o.length]=n;return o};return r(t)};return function(t){if(t&&t.__esModule)return t;var e={};if(t!=null){for(var o=r(t),n=0;n<o.length;n++)if(o[n]!=="default")Er(e,t,o[n])}Sr(e,t);return e}})();Object.defineProperty(exports,"__esModule",{value:true});exports.MemoryJournalCrash=void 0;exports.nextDirtyMarker=G;exports.assertMemoryOverwritePermission=ir;exports.writeDirtySummaryMarkerBestEffort=kr;exports.assertWindowsLegacyMemoryClean=g;exports.withWindowsMemoryWriterLock=vr;exports.advanceWindowsMemoryGeneration=Nr;exports.withMemoryWriterLock=sr;exports.withMemoryWriterLockAsync=cr;exports.withRecoveredAgentReadSync=Or;exports.withRecoveredAgentRead=Mr;exports.commitMemoryFiles=jr;const x=F(require("crypto"));const s=F(require("fs"));const er=F(require("os"));const m=F(require("path"));const gr=require("worker_threads");const S=".memory-writer.lock";const v=".memory-writer-reaper";const O=".memory-transactions";const P=".memory-mutation-generation";const C="retired-";const tr="prepared-";const J=3e4;const M=5;const or=2;const nr="memory-write-v2\n";class A extends Error{constructor(t){super(`simulated memory journal crash at ${t}`);this.stage=t;this.name="MemoryJournalCrash"}}exports.MemoryJournalCrash=A;function G(r,t=Date.now()){const e=$r(r);const o=Math.max(Math.trunc(t),e+1);if(!Number.isSafeInteger(o))throw new Error("memory dirty marker is outside the safe integer range");return Buffer.from(String(o),"utf8")}function ir(r,t,e){if(process.platform==="win32")throw new Error("coordinated memory writes are unavailable on Windows");if(!e||e.agentDir!==r||!e.owner.token){throw new Error("memory overwrite check requires the held writer lock token")}const o=Y(t);const n=W(r,o);const i=h(n);if(!i)return;const a=s.constants.O_NOFOLLOW??0;const c=s.openSync(n,s.constants.O_WRONLY|a);try{const y=s.fstatSync(c,{bigint:true});const f=s.lstatSync(n,{bigint:true});if(!y.isFile()||f.isSymbolicLink()||!f.isFile()||y.dev!==f.dev||y.ino!==f.ino){throw new Error("memory overwrite target changed during permission check")}}finally{s.closeSync(c)}}function kr(r,t,e=Date.now()){if(!t||t.agentDir!==r||!t.owner.token){throw new Error("memory dirty marker update requires the held writer lock token")}try{if(process.platform==="win32"){g(r,t.owner.token);s.writeFileSync(m.join(r,".dirty-summary"),G(r,e));return true}ir(r,".dirty-summary",t);I(m.join(r,".dirty-summary"),G(r,e));return true}catch{return false}}function g(r,t){if(process.platform!=="win32")return;const e=m.join(r,S);const o=h(e);if(o){if(!o.isDirectory()||o.isSymbolicLink()){throw new Error(`Windows legacy memory access is blocked by pending ${S} state`)}if(!t||L(e).token!==t){throw new Error(`Windows legacy memory access is blocked by pending ${S} state`)}}if(h(m.join(r,v))){throw new Error(`Windows legacy memory access is blocked by pending ${v} state`)}const n=m.join(r,O);const i=h(n);if(!i)return;if(!i.isDirectory()||i.isSymbolicLink()){throw new Error("Windows legacy memory access is blocked by an unverifiable transactions path")}for(const a of s.readdirSync(n)){const c=h(m.join(n,a));if(!a.startsWith(C)||!c?.isDirectory()||c.isSymbolicLink()){throw new Error(`Windows legacy memory access is blocked by pending transaction ${a}`)}}}function vr(r,t,e=J){if(process.platform!=="win32")throw new Error("Windows legacy memory lock is only available on Windows");R(r);const o=ar(r,Date.now()+e);try{g(r,o.token);return t({agentDir:r,owner:o,recovered:false})}finally{U(r,o)}}function Nr(r,t){if(process.platform!=="win32")throw new Error("Windows memory generation is only available on Windows");if(!t||t.agentDir!==r||!t.owner.token){throw new Error("memory generation update requires the held writer lock token")}g(r,t.owner.token);const e=hr(dr(r));s.writeFileSync(m.join(r,P),e,{encoding:"utf8",mode:384});return e}function sr(r,t,e=J){if(process.platform==="win32")throw new Error("coordinated memory writes are unavailable on Windows");R(r);const o=ar(r,Date.now()+e);try{const n=mr(r);return t({agentDir:r,owner:o,recovered:n})}finally{U(r,o)}}async function cr(r,t,e=J){if(process.platform==="win32")throw new Error("coordinated memory writes are unavailable on Windows");R(r);const o=await Br(r,Date.now()+e);try{const n=mr(r);return await t({agentDir:r,owner:o,recovered:n})}finally{U(r,o)}}function Or(r,t){if(process.platform==="win32"){g(r);try{return t({agentDir:r,held:false,recovered:false})}finally{g(r)}}let e=T(r);if(!e){const o=t({agentDir:r,held:false,recovered:false});e=T(r);if(!e)return o}return sr(r,o=>t({agentDir:r,held:true,recovered:e||o.recovered}))}async function Mr(r,t){if(process.platform==="win32"){g(r);try{return await t({agentDir:r,held:false,recovered:false})}finally{g(r)}}let e=T(r);if(!e){const o=await t({agentDir:r,held:false,recovered:false});e=T(r);if(!e)return o}return cr(r,async o=>t({agentDir:r,held:true,recovered:e||o.recovered}))}function jr(r,t,e){if(process.platform==="win32")throw new Error("coordinated memory writes are unavailable on Windows");const{token:o}=e;if(!o||o.agentDir!==r||!o.owner.token){throw new Error("memory commit requires the held writer lock token")}if(t.length===0)return;const n=dr(r);const i=e.advanceGeneration!==false;const a=i?hr(n):n;const c=Wr(r,t,n,a);const y=m.join(r,O);R(y);d(r);const f=x.randomBytes(16).toString("hex");const w=m.join(y,`${tr}${f}`);const u=m.join(y,`txn-${f}`);s.mkdirSync(w,{mode:448});try{I(m.join(w,"manifest.json"),Buffer.from(JSON.stringify(c)));d(w);d(y);s.renameSync(w,u);d(y)}catch(l){j(w);throw l}let b=false;let E=false;try{k(e.fault,"journal:prepared",u);ur(r,c,true,e.fault,u);if(i)V(r,a);k(e.fault,"generation:advanced",u);b=true;I(m.join(u,"COMMITTED"),Buffer.from(nr,"utf8"),void 0,l=>k(e.fault,`commit-marker:${l}`,u));E=true;try{k(e.fault,"commit:marked",u)}catch(l){if(l instanceof A)throw l;return}}catch(l){if(b&&!E)throw l;if(E){if(l instanceof A)throw l;return}if(l instanceof A)throw l;try{yr(r,u,c,false)}catch{}throw l}if(E){lr(r,c);try{H(y,u,e.fault)}catch(l){if(l instanceof A)throw l}}}function $r(r){try{const t=m.join(r,".dirty-summary");const e=s.lstatSync(t);if(!e.isFile()||e.isSymbolicLink())throw new Error("memory dirty-summary marker is not a regular file");const o=s.readFileSync(t,"utf8").trim();if(!/^(0|[1-9]\d*)$/u.test(o))return 0;const n=Number(o);return Number.isSafeInteger(n)?n:0}catch(t){if(p(t,"ENOENT"))return 0;throw t}}function Ar(){return process.platform==="win32"?"node-windows-v1":"posix-v1"}function Lr(r){return process.platform==="win32"?r==="node-windows-v1":r==="posix-v1"}function T(r){for(const e of[S,v]){const o=h(m.join(r,e));if(o){if(!o.isDirectory()||o.isSymbolicLink())throw new Error(`memory recovery control ${e} is not a regular directory`);return true}}const t=h(m.join(r,O));if(!t)return false;if(!t.isDirectory()||t.isSymbolicLink())throw new Error("memory transactions path is not a regular directory");return s.readdirSync(m.join(r,O)).some(e=>e.startsWith("txn-"))}function ar(r,t){const e=m.join(r,S);const o=m.join(r,v);while(true){if(h(o)){if(Date.now()>=t)throw new Error("memory write lock recovery is already active or needs manual recovery");Q(M);continue}const n=K();try{s.mkdirSync(e,{mode:448});try{z(e,n);return n}catch(a){j(e);throw a}}catch(a){if(!p(a,"EEXIST"))throw a}let i;try{i=L(e)}catch(a){if(Date.now()>=t)throw new Error(`memory write lock owner cannot be verified; manual recovery required: ${_(a)}`);Q(M);continue}if(X(i)){if(Date.now()>=t)throw new Error(`memory write lock is held by pid ${i.pid}`);Q(M);continue}fr(r,i);if(Date.now()>=t)throw new Error("memory write lock could not be reclaimed before timeout")}}async function Br(r,t){const e=m.join(r,S);const o=m.join(r,v);while(true){if(h(o)){if(Date.now()>=t)throw new Error("memory write lock recovery is already active or needs manual recovery");await Z(M);continue}const n=K();try{s.mkdirSync(e,{mode:448});try{z(e,n);return n}catch(a){j(e);throw a}}catch(a){if(!p(a,"EEXIST"))throw a}let i;try{i=L(e)}catch(a){if(Date.now()>=t)throw new Error(`memory write lock owner cannot be verified; manual recovery required: ${_(a)}`);await Z(M);continue}if(X(i)){if(Date.now()>=t)throw new Error(`memory write lock is held by pid ${i.pid}`);await Z(M);continue}fr(r,i);if(Date.now()>=t)throw new Error("memory write lock could not be reclaimed before timeout")}}function K(){return{version:1,pid:process.pid,host:er.hostname(),token:x.randomBytes(16).toString("hex")}}function z(r,t){const e=s.openSync(m.join(r,"owner.json"),"wx",384);try{s.writeFileSync(e,JSON.stringify(t));s.fsyncSync(e)}finally{s.closeSync(e)}d(r);d(m.dirname(r))}function L(r){const t=s.lstatSync(r);if(!t.isDirectory()||t.isSymbolicLink())throw new Error("memory write lock is not a regular directory");const e=m.join(r,"owner.json");const o=s.lstatSync(e);if(!o.isFile()||o.isSymbolicLink())throw new Error("memory write lock owner is not a regular file");const n=JSON.parse(s.readFileSync(e,"utf8"));if(n.version!==1||!Number.isSafeInteger(n.pid)||(n.pid??0)<=0||typeof n.host!=="string"||typeof n.token!=="string"||n.token.length===0){throw new Error("invalid memory write lock owner")}return n}function X(r){if(!r.host||r.host!==er.hostname())return true;try{process.kill(r.pid,0);return true}catch(t){return!p(t,"ESRCH")}}function fr(r,t){const e=m.join(r,v);try{s.mkdirSync(e,{mode:448})}catch(o){if(p(o,"EEXIST"))return;throw new Error(`create memory write lock recovery guard: ${_(o)}`)}try{z(e,K());const o=m.join(r,S);let n;try{n=L(o)}catch(a){if(p(a,"ENOENT"))return;throw a}if(n.token!==t.token||X(n))return;const i=m.join(r,`.memory-writer-stale-${x.randomBytes(16).toString("hex")}`);try{s.renameSync(o,i)}catch(a){if(p(a,"ENOENT"))return;throw new Error(`move stale memory write lock: ${_(a)}`)}s.rmSync(i,{recursive:true,force:true});d(r)}finally{s.rmSync(e,{recursive:true,force:true});d(r)}}function U(r,t){const e=m.join(r,S);try{if(L(e).token===t.token){s.rmSync(e,{recursive:true,force:true});d(r)}}catch{}}function Wr(r,t,e,o){if(t.length===0)throw new Error("memory transaction files must be nonempty");const n=new Set;const i=t.map(a=>{const c=Y(a.path);const y=N(c);if(n.has(y))throw new Error(`duplicate memory transaction path ${JSON.stringify(c)}`);n.add(y);const f=W(r,c);let w=Buffer.alloc(0);let u=false;try{w=s.readFileSync(f);u=true}catch(E){if(!p(E,"ENOENT"))throw E}const b=u?s.statSync(f,{bigint:true}):void 0;if(b&&!b.isFile())throw new Error(`memory transaction target ${c} is not a regular file`);return{path:c,beforeExists:u,before:u?w.toString("base64"):null,afterExists:a.contents!==null,after:a.contents===null?null:Buffer.from(a.contents).toString("base64"),...b?{beforeMode:Number(b.mode&4095n),beforeMtimeNs:b.mtimeNs.toString()}:{}}});return{version:2,backend:Ar(),generationBefore:e,generationAfter:o,files:i}}function mr(r){const t=m.join(r,O);let e;try{const c=s.lstatSync(t);if(!c.isDirectory()||c.isSymbolicLink())throw new Error("memory transactions path is not a regular directory");e=s.readdirSync(t)}catch(c){if(p(c,"ENOENT"))return false;throw new Error(`read memory transaction directory: ${_(c)}`)}const o=[];const n=new Set;const i=[];const a=[];for(const c of e){if(c.startsWith(C)){i.push(m.join(t,c));continue}if(c.startsWith(tr)){a.push(m.join(t,c));continue}if(!c.startsWith("txn-"))continue;const y=m.join(t,c);const f=s.lstatSync(y);if(!f.isDirectory()||f.isSymbolicLink())throw new Error(`memory transaction ${c} is not a regular directory`);const w=m.join(y,"manifest.json");let u;try{const l=s.lstatSync(w);if(!l.isFile()||l.isSymbolicLink())throw new Error("active memory transaction manifest is not a regular file");u=s.readFileSync(w,"utf8")}catch(l){if(p(l,"ENOENT"))throw new Error("active memory transaction is missing its manifest");throw l}const b=Ir(u,r);for(const l of b.files){const $=N(l.path);if(n.has($)){throw new Error(`duplicate active memory transaction destination ${JSON.stringify(l.path)}`)}n.add($)}const E=Rr(y);o.push({dir:y,manifest:b,committed:E})}for(const c of o)yr(r,c.dir,c.manifest,c.committed);for(const c of i)j(c);for(const c of a)j(c);if(o.length>0||i.length>0||a.length>0)d(t);return o.length>0}function yr(r,t,e,o){if(o){lr(r,e);V(r,e.generationAfter);H(m.dirname(t),t);return}ur(r,e,false);V(r,e.generationBefore);H(m.dirname(t),t)}function lr(r,t){for(const e of t.files){const o=W(r,e.path);const n=h(o);if(!e.afterExists){if(n)throw new Error(`committed memory transaction target ${JSON.stringify(e.path)} should be absent`);continue}if(!n||!n.isFile()||n.isSymbolicLink()){throw new Error(`committed memory transaction target ${JSON.stringify(e.path)} is missing or not a regular file`)}const i=s.readFileSync(o);const a=Buffer.from(e.after,"base64");if(!i.equals(a)){throw new Error(`committed memory transaction target ${JSON.stringify(e.path)} does not match its after-image`)}}}function ur(r,t,e,o,n=""){for(const i of t.files){const a=W(r,i.path);const c=e?i.afterExists:i.beforeExists;const y=e?i.after:i.before;if(!c){try{s.unlinkSync(a);d(m.dirname(a))}catch(u){if(!p(u,"ENOENT"))throw u}k(o,`target:${i.path}`,n);continue}const f=Buffer.from(y,"base64");const w=!e&&i.beforeExists?{mode:i.beforeMode,mtimeNs:i.beforeMtimeNs}:void 0;I(a,f,w);k(o,`target:${i.path}`,n)}}function Ir(r,t){let e;try{e=JSON.parse(r)}catch{throw new Error("memory transaction manifest root is invalid")}if(!br(e)||e.version!==or||!Array.isArray(e.files)||e.files.length===0){throw new Error(`memory transaction manifest is invalid or unsupported (expected version ${or})`)}if(typeof e.backend!=="string"||!Lr(e.backend)){throw new Error(`unsupported memory transaction backend ${String(e.backend)} on ${process.platform}`)}const o=B(e.generationBefore,"generationBefore");const n=B(e.generationAfter,"generationAfter");const i=BigInt(o);const a=BigInt(n);if(a<i||a>i+1n)throw new Error("memory transaction generation change is invalid");const c=new Set;const y=e.files.map(f=>{if(!br(f)||typeof f.path!=="string"||typeof f.beforeExists!=="boolean"||typeof f.afterExists!=="boolean"||!Object.prototype.hasOwnProperty.call(f,"before")||!Object.prototype.hasOwnProperty.call(f,"after")){throw new Error("memory transaction file image is incomplete")}const w=Y(f.path);const u=N(w);if(c.has(u))throw new Error(`duplicate memory transaction path ${JSON.stringify(w)}`);c.add(u);const b=wr(f.before,f.beforeExists,"before");const E=wr(f.after,f.afterExists,"after");const l=Object.prototype.hasOwnProperty.call(f,"beforeMode");const $=Object.prototype.hasOwnProperty.call(f,"beforeMtimeNs");let q;let D;if(f.beforeExists){if(!l||!$||!Number.isInteger(f.beforeMode)||Number(f.beforeMode)<0||Number(f.beforeMode)>4095||typeof f.beforeMtimeNs!=="string"||!/^(0|-?[1-9]\d*)$/u.test(f.beforeMtimeNs)){throw new Error("memory transaction before-image metadata is incomplete or invalid")}const rr=BigInt(f.beforeMtimeNs);if(rr<-(1n<<63n)||rr>(1n<<63n)-1n){throw new Error("memory transaction before-image mtime is outside signed 64-bit range")}q=Number(f.beforeMode);D=f.beforeMtimeNs}else if(l||$){throw new Error("memory transaction absent before-image must not include metadata")}W(t,w);return{path:w,beforeExists:f.beforeExists,before:b,afterExists:f.afterExists,after:E,...q===void 0?{}:{beforeMode:q,beforeMtimeNs:D}}});return{version:2,backend:e.backend,generationBefore:o,generationAfter:n,files:y}}function wr(r,t,e){if(r===null){if(t)throw new Error(`memory transaction ${e}-image is null but marked present`);return null}if(!t||typeof r!=="string")throw new Error(`memory transaction ${e}-image is invalid`);const o=Buffer.from(r,"base64");if(o.toString("base64")!==r)throw new Error(`memory transaction ${e}-image is noncanonical base64`);return r}function B(r,t){if(typeof r!=="string"||!/^(0|[1-9]\d*)$/u.test(r))throw new Error(`memory transaction ${t} is invalid`);return r}function dr(r){try{const t=m.join(r,P);const e=s.lstatSync(t);if(!e.isFile()||e.isSymbolicLink())throw new Error("memory mutation generation is not a regular file");const o=s.readFileSync(t,"utf8");return B(o,"mutation generation")}catch(t){if(p(t,"ENOENT"))return"0";throw t}}function V(r,t){B(t,"mutation generation");I(m.join(r,P),Buffer.from(t,"utf8"))}function hr(r){return(BigInt(B(r,"mutation generation"))+1n).toString()}function Rr(r){const t=m.join(r,"COMMITTED");let e;try{e=s.lstatSync(t)}catch(o){if(p(o,"ENOENT"))return false;throw o}if(!e.isFile()||e.isSymbolicLink())throw new Error("memory transaction commit marker is not a regular file");if(s.readFileSync(t,"utf8")!==nr)throw new Error("memory transaction commit marker is invalid");return true}function H(r,t,e){const o=m.join(r,`${C}${m.basename(t)}`);k(e,"retire:before-rename",t);s.renameSync(t,o);d(r);k(e,"cleanup:after-retire",o);j(o);try{d(r)}catch{}}function N(r){return process.platform==="darwin"||process.platform==="win32"?r.normalize("NFD").toLowerCase().normalize("NFD"):r}function Y(r){if(typeof r!=="string"||r.length===0||r.includes("\\")||r.includes("\0")||m.posix.isAbsolute(r)||m.win32.isAbsolute(r)||m.win32.parse(r).root){throw new Error(`unsafe memory transaction path ${JSON.stringify(r)}`)}const t=m.posix.normalize(r);if(t!==r||t==="."||t===".."||t.startsWith("../")){throw new Error(`unsafe memory transaction path ${JSON.stringify(r)}`)}const e=r.split("/");if(e.some(i=>i===""||i==="."||i===".."))throw new Error(`unsafe memory transaction path ${JSON.stringify(r)}`);const o=N(r).split("/");const n=o[0];if([S,v,O,P].some(i=>N(i)===n)||o.some(i=>i.startsWith(N(".memory-tmp-"))||i.startsWith(N(".memory-writer-stale-")))){throw new Error(`memory transaction control file ${JSON.stringify(r)} cannot be a target`)}return r}function W(r,t){const e=m.resolve(r);const o=m.resolve(e,...t.split("/"));if(o!==e&&!o.startsWith(`${e}${m.sep}`))throw new Error("memory transaction path escapes agent directory");const n=h(e);if(n&&(!n.isDirectory()||n.isSymbolicLink()))throw new Error("memory agent directory is not a regular directory");let i=e;const a=t.split("/");for(const y of a.slice(0,-1)){i=m.join(i,y);const f=h(i);if(f&&(!f.isDirectory()||f.isSymbolicLink()))throw new Error("memory transaction path contains a non-directory or symlink")}const c=h(o);if(c&&(c.isSymbolicLink()||!c.isFile()))throw new Error("memory transaction target is not a regular file");return o}function I(r,t,e,o){const n=m.dirname(r);R(n);const i=h(r);if(i?.isSymbolicLink())throw new Error("memory atomic target is a symlink");const a=e?.mode??(i?Number(i.mode&4095):438);const c=m.join(n,`.memory-tmp-${x.randomBytes(12).toString("hex")}`);s.mkdirSync(c,{mode:448});const y=m.join(c,"payload");let f;try{d(n);f=s.openSync(y,"wx",a);o?.("temp-write");s.writeFileSync(f,t);if(e||i)s.fchmodSync(f,a);if(e){if(BigInt(e.mtimeNs)<0n)_r(y,e.mtimeNs);else s.futimesSync(f,new Date,pr(e.mtimeNs));Fr(y,e)}o?.("file-fsync");s.fsyncSync(f);s.closeSync(f);f=void 0;d(c);o?.("pre-rename");s.renameSync(y,r);o?.("post-rename");o?.("dir-fsync");d(n)}catch(w){if(f!==void 0){try{s.closeSync(f)}catch{}}throw w}finally{try{s.rmSync(c,{recursive:true,force:true})}catch{}try{d(n)}catch{}}}function _r(r,t){const e=new SharedArrayBuffer(8+1024);const o=new Int32Array(e,0,2);const n=new Uint8Array(e,8);const i=["const { workerData } = require('node:worker_threads');","const fs = require('node:fs');","const state = new Int32Array(workerData.shared, 0, 2);","const errorBytes = new Uint8Array(workerData.shared, 8);","const finish = (error) => {"," if (error) {"," const bytes = Buffer.from(String(error.stack || error));"," const length = Math.min(bytes.length, errorBytes.length);"," errorBytes.set(bytes.subarray(0, length));"," Atomics.store(state, 1, length);"," }"," Atomics.store(state, 0, 1);"," Atomics.notify(state, 0);","};","let fd;","try {"," fd = fs.openSync(workerData.target, 'r');"," const binding = process.binding('fs');"," const request = new binding.FSReqCallback();"," request.oncomplete = (error) => {"," try {"," if (error) throw error;"," fs.fsyncSync(fd);"," } catch (syncError) { error = syncError; }"," try { fs.closeSync(fd); } catch (closeError) { if (!error) error = closeError; }"," finish(error);"," };"," binding.futimes(fd, Date.now() / 1000, workerData.mtimeSeconds, request);","} catch (error) {"," if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }"," finish(error);","}"].join("\n");const a=new gr.Worker(i,{eval:true,workerData:{shared:e,target:r,mtimeSeconds:pr(t)}});a.unref();if(Atomics.wait(o,0,0,3e4)==="timed-out"){void a.terminate();throw new Error("timed out restoring pre-epoch memory mtime")}const c=Atomics.load(o,1);if(c>0){throw new Error(Buffer.from(n.subarray(0,c)).toString("utf8"))}}function Fr(r,t){const e=s.statSync(r,{bigint:true});if(Number(e.mode&4095n)!==t.mode){throw new Error(`memory rollback mode ${Number(e.mode&4095n)} does not match before-image ${t.mode}`)}const o=BigInt(t.mtimeNs);const n=e.mtimeNs-o;if((n<0n?-n:n)>10000n){throw new Error(`memory rollback mtime ${e.mtimeNs} does not match before-image ${o}`)}}function pr(r){const t=1000000000n;const e=BigInt(r);let o=e/t;let n=e%t;if(n<0){o-=1n;n+=t}return Number(o)+Number(n)/Number(t)}function d(r){if(process.platform==="win32")return;const t=s.openSync(r,"r");try{s.fsyncSync(t)}finally{s.closeSync(t)}}function R(r){const t=[];let e=m.resolve(r);while(true){const o=h(e);if(o){if(!o.isDirectory()||o.isSymbolicLink())throw new Error(`memory directory ${e} is not a regular directory`);break}t.push(e);const n=m.dirname(e);if(n===e)break;e=n}s.mkdirSync(r,{recursive:true,mode:493});for(const o of t.reverse())d(m.dirname(o))}function h(r){try{return s.lstatSync(r)}catch(t){if(p(t,"ENOENT"))return void 0;throw t}}function k(r,t,e){r?.(t,e)}function Q(r){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,r)}function Z(r){return new Promise(t=>setTimeout(t,r))}function j(r){try{s.rmSync(r,{recursive:true,force:true})}catch{}}function br(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)}function p(r,t){return typeof r==="object"&&r!==null&&"code"in r&&r.code===t}function _(r){return r instanceof Error?r.message:String(r)}
@@ -0,0 +1,6 @@
1
+ export interface NativeMemoryWriteEffects {
2
+ version: 1;
3
+ scheduleSummary: boolean;
4
+ }
5
+ export declare function applyNativeMemoryWriteEffects(dataDir: string, agentId: string, effects: NativeMemoryWriteEffects): boolean;
6
+
@@ -0,0 +1 @@
1
+ "use strict";var a=exports&&exports.__createBinding||(Object.create?(function(i,e,n,r){if(r===void 0)r=n;var t=Object.getOwnPropertyDescriptor(e,n);if(!t||("get"in t?!e.__esModule:t.writable||t.configurable)){t={enumerable:true,get:function(){return e[n]}}}Object.defineProperty(i,r,t)}):(function(i,e,n,r){if(r===void 0)r=n;i[r]=e[n]}));var f=exports&&exports.__setModuleDefault||(Object.create?(function(i,e){Object.defineProperty(i,"default",{enumerable:true,value:e})}):function(i,e){i["default"]=e});var c=exports&&exports.__importStar||(function(){var i=function(e){i=Object.getOwnPropertyNames||function(n){var r=[];for(var t in n)if(Object.prototype.hasOwnProperty.call(n,t))r[r.length]=t;return r};return i(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null){for(var r=i(e),t=0;t<r.length;t++)if(r[t]!=="default")a(n,e,r[t])}f(n,e);return n}})();Object.defineProperty(exports,"__esModule",{value:true});exports.applyNativeMemoryWriteEffects=l;const o=c(require("path"));const u=require("./storage");function l(i,e,n){if(n.version!==1||typeof n.scheduleSummary!=="boolean"){throw new Error("native memory write effects are invalid")}if(!n.scheduleSummary)return true;const r=o.join(i,e);if(process.platform==="win32"){try{return(0,u.withWindowsMemoryWriterLock)(r,t=>(0,u.writeDirtySummaryMarkerBestEffort)(r,t))}catch{return false}}try{return(0,u.withMemoryWriterLock)(r,t=>(0,u.writeDirtySummaryMarkerBestEffort)(r,t))}catch{return false}}
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,74 @@
1
+ {
2
+ "formatVersion": 1,
3
+ "protocol": 4,
4
+ "capabilities": [
5
+ "memory.read.basic.v1",
6
+ "memory.read.ordinary.v1",
7
+ "memory.graph.v1",
8
+ "memory.api.v1",
9
+ "memory.summary.v1"
10
+ ],
11
+ "packageVersion": "0.1.23-rc.256",
12
+ "targets": {
13
+ "darwin-arm64": {
14
+ "file": "go/bin/crewx-memory-darwin-arm64",
15
+ "sha256": "790a64a3dbd69caabc7baf0215e09afd1a420b85a33493125536d76b7131219d",
16
+ "capabilities": [
17
+ "memory.read.basic.v1",
18
+ "memory.read.ordinary.v1",
19
+ "memory.graph.v1",
20
+ "memory.api.v1",
21
+ "memory.summary.v1",
22
+ "memory.write.crud.v2"
23
+ ]
24
+ },
25
+ "darwin-amd64": {
26
+ "file": "go/bin/crewx-memory-darwin-amd64",
27
+ "sha256": "284d24900ddb00e3ad8c661488372057aada1070af3c6e04eb37b075eb3c3655",
28
+ "capabilities": [
29
+ "memory.read.basic.v1",
30
+ "memory.read.ordinary.v1",
31
+ "memory.graph.v1",
32
+ "memory.api.v1",
33
+ "memory.summary.v1",
34
+ "memory.write.crud.v2"
35
+ ]
36
+ },
37
+ "linux-amd64": {
38
+ "file": "go/bin/crewx-memory-linux-amd64",
39
+ "sha256": "76899074c5072ecd1471370ff4ba6ef3a9124c240a32735bef4f5f1a0ff51f40",
40
+ "capabilities": [
41
+ "memory.read.basic.v1",
42
+ "memory.read.ordinary.v1",
43
+ "memory.graph.v1",
44
+ "memory.api.v1",
45
+ "memory.summary.v1",
46
+ "memory.write.crud.v2"
47
+ ]
48
+ },
49
+ "linux-arm64": {
50
+ "file": "go/bin/crewx-memory-linux-arm64",
51
+ "sha256": "b795c1a24bf0e33b0582185a672edac9031e182e1cb861e52f40e1ffb0c8d641",
52
+ "capabilities": [
53
+ "memory.read.basic.v1",
54
+ "memory.read.ordinary.v1",
55
+ "memory.graph.v1",
56
+ "memory.api.v1",
57
+ "memory.summary.v1",
58
+ "memory.write.crud.v2"
59
+ ]
60
+ },
61
+ "windows-amd64": {
62
+ "file": "go/bin/crewx-memory-windows-amd64.exe",
63
+ "sha256": "76b82b3b5a078d45fc1ffa5b0e3e4d98b2d836a41ebdeb44ef42585abd4b10a3",
64
+ "capabilities": [
65
+ "memory.read.basic.v1",
66
+ "memory.read.ordinary.v1",
67
+ "memory.graph.v1",
68
+ "memory.api.v1",
69
+ "memory.summary.v1",
70
+ "memory.write.crud.v2"
71
+ ]
72
+ }
73
+ }
74
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewx/memory",
3
- "version": "0.1.23-rc.254",
3
+ "version": "0.1.23-rc.256",
4
4
  "description": "Memory engine for CrewX - markdown + frontmatter based long-term memory",
5
5
  "type": "commonjs",
6
6
  "main": "dist/src/engine.js",
@@ -23,7 +23,9 @@
23
23
  },
24
24
  "files": [
25
25
  "dist",
26
- "SKILL.md"
26
+ "SKILL.md",
27
+ "go/bin",
28
+ "go/native-manifest.json"
27
29
  ],
28
30
  "keywords": [
29
31
  "crewx",
@@ -36,9 +38,9 @@
36
38
  "gray-matter": "^4.0.3",
37
39
  "js-yaml": "^4.1.0",
38
40
  "nanoid": "^3.3.11",
39
- "@crewx/sdk": "0.9.0-rc.236",
40
- "@crewx/shared": "0.0.6-rc.151",
41
- "@crewx/knowledge-core": "0.1.17-rc.247"
41
+ "@crewx/sdk": "0.9.0-rc.238",
42
+ "@crewx/shared": "0.0.6-rc.153",
43
+ "@crewx/knowledge-core": "0.1.17-rc.249"
42
44
  },
43
45
  "devDependencies": {
44
46
  "@types/js-yaml": "^4.0.9",