toolnet-memory 0.3.14 → 0.3.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/.env.example +0 -1
  2. package/.release-target +1 -1
  3. package/README.md +182 -6
  4. package/bin/toolnet-memory +5 -0
  5. package/bundle/agy-hook.js +71 -71
  6. package/bundle/agy.js +65 -65
  7. package/bundle/api.js +15 -15
  8. package/bundle/auto-integrate.js +28 -28
  9. package/bundle/background-refresh.js +7 -7
  10. package/bundle/claude-hook.js +51 -50
  11. package/bundle/codex-context.js +29 -28
  12. package/bundle/codex.js +77 -77
  13. package/bundle/context-runtime.js +44 -43
  14. package/bundle/context.js +15 -15
  15. package/bundle/continuity-certify.js +13 -13
  16. package/bundle/copilot-hook.js +88 -86
  17. package/bundle/copilot.js +4 -4
  18. package/bundle/cursor-hook.js +88 -86
  19. package/bundle/cursor.js +4 -4
  20. package/bundle/doctor.js +4 -4
  21. package/bundle/full-index.js +21 -21
  22. package/bundle/gc.js +3 -0
  23. package/bundle/graph-index.js +4 -4
  24. package/bundle/graph-ui.js +3 -3
  25. package/bundle/grok-hook.js +64 -63
  26. package/bundle/grok.js +5 -5
  27. package/bundle/handoff-refresh.js +10 -10
  28. package/bundle/help-cli.js +3 -3
  29. package/bundle/impact.js +4 -4
  30. package/bundle/incremental.js +5 -4
  31. package/bundle/init.js +38 -37
  32. package/bundle/integration-status.js +4 -4
  33. package/bundle/kiro-hook.js +93 -92
  34. package/bundle/learner.js +6 -6
  35. package/bundle/mcp.js +17 -17
  36. package/bundle/memory-agent.js +7 -7
  37. package/bundle/memory-query.js +7 -7
  38. package/bundle/opencode.js +84 -84
  39. package/bundle/project-manual.js +7 -7
  40. package/bundle/recovery-certify.js +15 -15
  41. package/bundle/runtime.js +13 -12
  42. package/bundle/semantic.js +5 -5
  43. package/bundle/snapshot.js +4 -4
  44. package/bundle/status-cli.js +4 -4
  45. package/bundle/toolnet-cli.js +60 -60
  46. package/bundle/work-continuity.js +7 -7
  47. package/package.json +21 -3
  48. package/release-manifest.json +104 -3
@@ -1,71 +1,71 @@
1
- import*as ne from"fs";import*as H from"path";function ls(e){return e?Math.ceil(e.length/3.5):0}function fn(e,t){if(!e)return"";if(ls(e)<=t)return e;let r=Math.floor(t*3.5),o=e.slice(0,r),s=o.lastIndexOf("."),i=o.lastIndexOf(`
2
- `),a=Math.max(s,i);return a>r*.7?o.slice(0,a+1):o}import{createHash as ds}from"node:crypto";import{chmodSync as mn,existsSync as ps,mkdirSync as fs,readFileSync as ms,renameSync as gs,writeFileSync as gn}from"node:fs";import{dirname as yn,join as _e}from"node:path";var At="toolnet.context-offload.v1",ys="toolnet.context-offload-asset.v1",hs=256,Ss=new Set(["tool_call","tool_result","file_read","file_write","file_edit","command","test","artifact"]);function hn(e){return _e(e,".toolnet","offload")}function ks(e){return _e(hn(e),"assets")}function Sn(e){return _e(hn(e),"graph.json")}function kn(e){fs(e,{recursive:!0,mode:448});try{mn(e,448)}catch{}}function vs(e,t){kn(yn(e));let n=`${e}.${process.pid}.${Date.now()}.tmp`;gn(n,t,{encoding:"utf8",mode:384}),gs(n,e);try{mn(e,384)}catch{}}function It(e){return Array.isArray(e)?e.map(It):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,It(n)])):e}function ws(e){return ds("sha256").update(JSON.stringify(It(e)),"utf8").digest("hex")}function jt(){return{schema:At,version:1,updatedAt:new Date(0).toISOString(),nodes:[]}}function bs(e){let t=Sn(e);if(!ps(t))return jt();try{let n=JSON.parse(ms(t,"utf8"));return n.schema!==At||n.version!==1||!Array.isArray(n.nodes)?jt():n}catch{return jt()}}function xs(e,t){vs(Sn(e),JSON.stringify(t,null,2)+`
3
- `)}function js(e,t=260){if(typeof e!="string")return null;let n=e.replace(/\s+/gu," ").trim();return n?n.slice(0,t):null}function Is(e){let t=[...e.provenance.files??[],e.provenance.sourcePath],n=[];for(let r of t){let o=js(r);if(!(!o||n.includes(o))&&(n.push(o),n.length===3))break}return n}function As(e){return`${e.agent}:${e.sourceEventId??e.id}`.replace(/\s+/gu," ").trim().slice(0,120)}function Ps(e,t){kn(yn(e));try{return gn(e,t,{encoding:"utf8",flag:"wx",mode:384}),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function Cs(e,t){let n=e.nodes.find(o=>o.id===t.id),r=n?{...n,kind:t.kind,bytes:t.bytes,sourceRefs:Array.from(new Set([...n.sourceRefs,...t.sourceRefs])).slice(-8),files:Array.from(new Set([...n.files,...t.files])).slice(0,6)}:t;return{schema:At,version:1,updatedAt:new Date().toISOString(),nodes:[...e.nodes.filter(o=>o.id!==t.id),r].slice(-hs)}}function vn(e,t){let n=bs(e),r=0,o=0,s=0,i=[];for(let a of t){if(!Ss.has(a.type))continue;r+=1;let c=ws({type:a.type,data:a.data}),u={schema:ys,version:1,assetId:c,event:{type:a.type,agent:a.agent,nativeSessionId:a.nativeSessionId,timestamp:a.timestamp,sourceEventId:a.sourceEventId,provenance:a.provenance,data:a.data}},d=JSON.stringify(u,null,2)+`
4
- `;Ps(_e(ks(e),`${c}.json`),d)?o+=1:s+=1,i.push(c),n=Cs(n,{id:c,kind:a.type,bytes:Buffer.byteLength(d,"utf8"),createdAt:a.timestamp,sourceRefs:[As(a)],files:Is(a)})}return r>0&&xs(e,n),{eligible:r,written:o,deduped:s,graphNodes:n.nodes.length,assetIds:i}}import{existsSync as bn,mkdirSync as _s,readFileSync as xn,renameSync as Ks,writeFileSync as $s}from"node:fs";import{dirname as Ls,join as jn}from"node:path";import{createHash as Ms}from"node:crypto";import{dirname as Es}from"node:path";import{mkdirSync as Os,readFileSync as Ts,renameSync as Rs,writeFileSync as Ns}from"node:fs";function v(e){return Ms("sha256").update(e).digest("hex")}function Pt(e){if(Array.isArray(e))return e.map(Pt);if(e&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=Pt(t[r]);return n}return e}function Ke(e){return JSON.stringify(Pt(e))}function wn(e){try{return JSON.parse(Ts(e,"utf8"))}catch{return null}}function T(e,t){Os(Es(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;Ns(n,JSON.stringify(t,null,2)+`
5
- `,{encoding:"utf8",mode:384}),Rs(n,e)}function In(e){return jn(e.rootPath,".toolnet","context","handoff.md")}function An(e){return jn(e.rootPath,".toolnet","context","handoff.json")}function Pn(e,t){_s(Ls(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;$s(n,t.endsWith(`
1
+ import*as se from"fs";import*as J from"path";function Ks(e){return e?Math.ceil(e.length/3.5):0}function An(e,t){if(!e)return"";if(Ks(e)<=t)return e;let r=Math.floor(t*3.5),o=e.slice(0,r),s=o.lastIndexOf("."),i=o.lastIndexOf(`
2
+ `),a=Math.max(s,i);return a>r*.7?o.slice(0,a+1):o}import{createHash as $s}from"node:crypto";import{chmodSync as Pn,existsSync as Ls,mkdirSync as Fs,readFileSync as Ds,renameSync as Ws,writeFileSync as Mn}from"node:fs";import{dirname as Cn,join as He}from"node:path";var $t="toolnet.context-offload.v1",zs="toolnet.context-offload-asset.v1",qs=256,Hs=new Set(["tool_call","tool_result","file_read","file_write","file_edit","command","test","artifact"]);function En(e){return He(e,".toolnet","offload")}function Js(e){return He(En(e),"assets")}function On(e){return He(En(e),"graph.json")}function Tn(e){Fs(e,{recursive:!0,mode:448});try{Pn(e,448)}catch{}}function Vs(e,t){Tn(Cn(e));let n=`${e}.${process.pid}.${Date.now()}.tmp`;Mn(n,t,{encoding:"utf8",mode:384}),Ws(n,e);try{Pn(e,384)}catch{}}function Kt(e){return Array.isArray(e)?e.map(Kt):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Kt(n)])):e}function Bs(e){return $s("sha256").update(JSON.stringify(Kt(e)),"utf8").digest("hex")}function _t(){return{schema:$t,version:1,updatedAt:new Date(0).toISOString(),nodes:[]}}function Gs(e){let t=On(e);if(!Ls(t))return _t();try{let n=JSON.parse(Ds(t,"utf8"));return n.schema!==$t||n.version!==1||!Array.isArray(n.nodes)?_t():n}catch{return _t()}}function Us(e,t){Vs(On(e),JSON.stringify(t,null,2)+`
3
+ `)}function Ys(e,t=260){if(typeof e!="string")return null;let n=e.replace(/\s+/gu," ").trim();return n?n.slice(0,t):null}function Xs(e){let t=[...e.provenance.files??[],e.provenance.sourcePath],n=[];for(let r of t){let o=Ys(r);if(!(!o||n.includes(o))&&(n.push(o),n.length===3))break}return n}function Zs(e){return`${e.agent}:${e.sourceEventId??e.id}`.replace(/\s+/gu," ").trim().slice(0,120)}function Qs(e,t){Tn(Cn(e));try{return Mn(e,t,{encoding:"utf8",flag:"wx",mode:384}),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function ei(e,t){let n=e.nodes.find(o=>o.id===t.id),r=n?{...n,kind:t.kind,bytes:t.bytes,sourceRefs:Array.from(new Set([...n.sourceRefs,...t.sourceRefs])).slice(-8),files:Array.from(new Set([...n.files,...t.files])).slice(0,6)}:t;return{schema:$t,version:1,updatedAt:new Date().toISOString(),nodes:[...e.nodes.filter(o=>o.id!==t.id),r].slice(-qs)}}function Rn(e,t){let n=Gs(e),r=0,o=0,s=0,i=[];for(let a of t){if(!Hs.has(a.type))continue;r+=1;let c=Bs({type:a.type,data:a.data}),u={schema:zs,version:1,assetId:c,event:{type:a.type,agent:a.agent,nativeSessionId:a.nativeSessionId,timestamp:a.timestamp,sourceEventId:a.sourceEventId,provenance:a.provenance,data:a.data}},l=JSON.stringify(u,null,2)+`
4
+ `;Qs(He(Js(e),`${c}.json`),l)?o+=1:s+=1,i.push(c),n=ei(n,{id:c,kind:a.type,bytes:Buffer.byteLength(l,"utf8"),createdAt:a.timestamp,sourceRefs:[Zs(a)],files:Xs(a)})}return r>0&&Us(e,n),{eligible:r,written:o,deduped:s,graphNodes:n.nodes.length,assetIds:i}}import{existsSync as _n,mkdirSync as ai,readFileSync as Kn,renameSync as ci,writeFileSync as ui}from"node:fs";import{dirname as li,join as $n}from"node:path";import{createHash as ti}from"node:crypto";import{dirname as ni}from"node:path";import{mkdirSync as ri,readFileSync as oi,renameSync as si,writeFileSync as ii}from"node:fs";function w(e){return ti("sha256").update(e).digest("hex")}function Lt(e){if(Array.isArray(e))return e.map(Lt);if(e&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=Lt(t[r]);return n}return e}function Je(e){return JSON.stringify(Lt(e))}function Nn(e){try{return JSON.parse(oi(e,"utf8"))}catch{return null}}function R(e,t){ri(ni(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;ii(n,JSON.stringify(t,null,2)+`
5
+ `,{encoding:"utf8",mode:384}),si(n,e)}function Ln(e){return $n(e.rootPath,".toolnet","context","handoff.md")}function Fn(e){return $n(e.rootPath,".toolnet","context","handoff.json")}function Dn(e,t){ai(li(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;ui(n,t.endsWith(`
6
6
  `)?t:`${t}
7
- `,{encoding:"utf8",mode:384}),Ks(n,e)}function Fs(e,t){Pn(e,`${JSON.stringify(t,null,2)}
8
- `)}function Cn(e,t){let n=t.replace(/\r\n/g,`
9
- `).trim();if(!n)return null;let r={version:1,projectId:e.id,projectName:e.name,text:n,digest:v(n),generatedAt:new Date().toISOString()};return Pn(In(e),n),Fs(An(e),r),r}function Mn(e){let t=In(e);if(!bn(t))return null;try{let n=xn(t,"utf8").trim();if(!n)return null;let r=new Date(0).toISOString(),o=An(e);if(bn(o))try{let s=JSON.parse(xn(o,"utf8"));typeof s.generatedAt=="string"&&(r=s.generatedAt)}catch{}return{version:1,projectId:e.id,projectName:e.name,text:n,digest:v(n),generatedAt:r}}catch{return null}}function En(e){let t=H.resolve(e),n=H.parse(t).root;for(;t!==n;){let r=H.join(t,".toolnet");if(ne.existsSync(r)&&ne.statSync(r).isDirectory())return t;t=H.dirname(t)}return null}function On(e){return e.replace(/\\/g,"/").toLowerCase()}function Ct(e,t,n=0){if(!(n>6||t.length>=250)){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let r of e)if(Ct(r,t,n+1),t.length>=250)break;return}if(e&&typeof e=="object"){for(let r of Object.values(e))if(Ct(r,t,n+1),t.length>=250)break}}}function Ws(e){let t=On(e);if(t.includes(".toolnet/journal/")||t.includes(".toolnet/runtime/sources/")||t.endsWith(".toolnet/journal")||t.endsWith(".toolnet/runtime/sources")||t.includes(".toolnet/sessions/")||t.endsWith(".toolnet/sessions")||t.includes(".gemini/antigravity-cli/brain/")||t.endsWith(".gemini/antigravity-cli/brain")||t.includes("/transcript.jsonl")||t.endsWith("transcript.jsonl")||t.includes(".toolnet/")&&(t.endsWith("/events.jsonl")||t.endsWith("/state.json")||t.includes("/sessions/")))return!0;let n=process.env.CURSOR_TRANSCRIPT_PATH;return!!(n&&On(n)===t)}function Tn(e){let t=[];return Ct(e,t),t.find(Ws)?{blocked:!0,reason:"ToolNet continuity guard: do not read or reconstruct previous work from raw ToolNet/agent session history. Use the injected ToolNet handoff first; if it is insufficient, invoke the MCP tool memory_agent_ask directly. Then verify normal repository/git source truth."}:{blocked:!1}}function $e(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Rn(e,t=process.env){return $e(t.TOOLNET_HOOK_EVENT)??$e(e.hookEventName)??$e(e.hook_event_name)??$e(t.GROK_HOOK_EVENT)??""}function Nn(e){return Tn(e.toolInput??e.tool_input??e)}function _n(e){return{decision:"deny",reason:e}}import{existsSync as Jl}from"node:fs";import{join as Vl}from"node:path";import{existsSync as Ds,readFileSync as zs}from"node:fs";import{homedir as qs}from"node:os";import{join as Hs}from"node:path";function Js(e){let t=e.trim();return t.length>=2&&t.startsWith('"')&&t.endsWith('"')?(t=t.slice(1,-1),t.replace(/\\n/g,`
10
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):t.length>=2&&t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Vs(){let e=process.env.TOOLNET_GLOBAL_ENV??Hs(qs(),".config","toolnet-memory",".env");if(!Ds(e))return;let t=zs(e,"utf8");for(let n of t.split(/\r?\n/)){let r=n.trim();if(!r||r.startsWith("#"))continue;r.startsWith("export ")&&(r=r.slice(7));let o=r.indexOf("=");if(o<=0)continue;let s=r.slice(0,o).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)&&process.env[s]===void 0&&(process.env[s]=Js(r.slice(o+1)))}}Vs();function pe(e,t){return e===void 0?t:["1","true","yes","on"].includes(e.toLowerCase())}function fe(e,t){if(!e)return t;let n=Number(e);return Number.isFinite(n)?n:t}function Le(){return{memory:{autoCapture:pe(process.env.MEMORY_AUTO_CAPTURE,!0),autoRetrieve:pe(process.env.MEMORY_AUTO_RETRIEVE,!0),autoSummarize:pe(process.env.MEMORY_AUTO_SUMMARIZE,!0),autoSync:pe(process.env.MEMORY_AUTO_SYNC,!0)},retrieval:{maxCandidates:fe(process.env.MEMORY_MAX_CANDIDATES,50),rerankTop:fe(process.env.MEMORY_RERANK_TOP,10),finalContext:fe(process.env.MEMORY_FINAL_CONTEXT,5),tokenBudget:fe(process.env.MEMORY_TOKEN_BUDGET,2e3)},storage:{provider:process.env.MEMORY_STORAGE_PROVIDER??"huggingface",r2:{accountId:process.env.R2_ACCOUNT_ID,bucket:process.env.R2_BUCKET,accessKeyId:process.env.R2_ACCESS_KEY_ID,secretAccessKey:process.env.R2_SECRET_ACCESS_KEY},s3:{endpoint:process.env.S3_ENDPOINT,region:process.env.S3_REGION,bucket:process.env.S3_BUCKET,accessKeyId:process.env.S3_ACCESS_KEY_ID,secretAccessKey:process.env.S3_SECRET_ACCESS_KEY,forcePathStyle:pe(process.env.S3_FORCE_PATH_STYLE,!1)},huggingface:{namespace:process.env.HF_NAMESPACE,bucket:process.env.HF_BUCKET,accessKeyId:process.env.HF_S3_ACCESS_KEY_ID,secretAccessKey:process.env.HF_S3_SECRET_ACCESS_KEY},localRoot:process.env.MEMORY_LOCAL_STORAGE_PATH},cache:{maxMb:fe(process.env.MEMORY_LOCAL_CACHE_MB,200)}}}import{createHash as Bs}from"node:crypto";import{existsSync as Mt,mkdirSync as Gs,readFileSync as Us,renameSync as Ys,writeFileSync as Xs}from"node:fs";import{basename as Qs,dirname as Fe,join as De,parse as Ln,resolve as me}from"node:path";var Fn=".toolnet",Zs="project.json";function ei(e){return Bs("sha256").update(e).digest("hex").slice(0,16)}function Et(e){return De(e,Fn,Zs)}function ti(e){return Mt(Et(e))}function ni(e,t){let n=me(e),r=Ln(n).root;for(;;){if(ti(n))return n;if(n===r||t&&n===me(t))break;let o=Fe(n);if(o===n)break;n=o}return null}function ri(e){let t=me(e),n=Ln(t).root,r=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(r.some(s=>Mt(De(t,s))))return t;if(t===n)break;let o=Fe(t);if(o===t)break;t=o}return me(e)}function oi(e){let t;try{t=JSON.parse(Us(e,"utf8"))}catch(o){throw new Error(`Invalid ToolNet project manifest: ${e}: ${o instanceof Error?o.message:String(o)}`)}if(!t||typeof t!="object")throw new Error(`Invalid ToolNet project manifest: ${e}`);let n=t;if(typeof n.id!="string"||!n.id.trim())throw new Error(`ToolNet project manifest is missing id: ${e}`);if(typeof n.name!="string"||!n.name.trim())throw new Error(`ToolNet project manifest is missing name: ${e}`);let r=new Date().toISOString();return{version:1,id:n.id,name:n.name,remote:typeof n.remote=="string"&&n.remote.trim()?n.remote:n.name,rootPath:typeof n.rootPath=="string"?n.rootPath:Fe(Fe(e)),createdAt:typeof n.createdAt=="string"?n.createdAt:r,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:r,graphVersion:typeof n.graphVersion=="number"?n.graphVersion:0,memoryVersion:typeof n.memoryVersion=="number"?n.memoryVersion:0,metadata:n.metadata&&typeof n.metadata=="object"?n.metadata:void 0}}function Kn(e,t){let n=De(e,Fn);Gs(n,{recursive:!0});let r=Et(e),o=`${r}.tmp-${process.pid}`;Xs(o,JSON.stringify(t,null,2)+`
11
- `,{encoding:"utf8",mode:384}),Ys(o,r)}function $n(e,t){return{id:e.id,name:e.name,remote:e.remote,rootPath:t,createdAt:e.createdAt,updatedAt:e.updatedAt,graphVersion:e.graphVersion,memoryVersion:e.memoryVersion,metadata:e.metadata}}var We=class{detect(t=process.cwd()){let n=me(t),r=ri(n),s=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(d=>Mt(De(r,d))),i=ni(n,s?r:void 0);if(i){let d=Et(i),l=oi(d);return l.rootPath!==i&&(l.rootPath=i,l.updatedAt=new Date().toISOString(),Kn(i,l)),$n(l,i)}let a=new Date().toISOString(),c=Qs(r),u={version:1,id:ei(r),name:c,remote:c,rootPath:r,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0};return Kn(r,u),$n(u,r)}};var si=[{type:"openai_key",regex:/\bsk-[A-Za-z0-9_\-]{20,}\b/g},{type:"huggingface_token",regex:/\bhf_[A-Za-z0-9]{20,}\b/g},{type:"hf_s3_access_key",regex:/\bHFAK[A-Za-z0-9]{8,}\b/g},{type:"bearer_token",regex:/\bBearer\s+[A-Za-z0-9._\-]{16,}\b/gi},{type:"jwt",regex:/\beyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\b/g},{type:"private_key",regex:/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g},{type:"password_assignment",regex:/\b(password|passwd|pwd)\s*[:=]\s*["']?[^"'\s]{6,}["']?/gi},{type:"secret_assignment",regex:/\b(secret|api[_-]?key|access[_-]?token|refresh[_-]?token)\s*[:=]\s*["']?[^"'\s]{8,}["']?/gi},{type:"cookie",regex:/\b(cookie|set-cookie)\s*[:=]\s*[^;\n]{8,}/gi}],ze=class{scan(t){let n=[];for(let r of si){let o=new RegExp(r.regex.source,r.regex.flags);for(let s of t.matchAll(o))n.push({type:r.type,value:s[0]})}return n}hasSecrets(t){return this.scan(t).length>0}};var U=class{scanner=new ze;sanitize(t){let n=t,r=this.scanner.scan(t),o=new Set;for(let s of r)o.add(s.type),n=n.split(s.value).join(`[REDACTED:${s.type}]`);return{text:n,redacted:r.length,secretTypes:[...o]}}sanitizeValue(t){if(typeof t=="string")return this.sanitize(t).text;if(Array.isArray(t))return t.map(n=>this.sanitizeValue(n));if(t&&typeof t=="object"){let n={};for(let[r,o]of Object.entries(t)){let s=r.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"");s.includes("password")||s.includes("passwd")||s==="pwd"||s.includes("secret")||s.includes("token")||s.includes("cookie")||s.includes("authorization")||s.includes("apikey")||s.includes("accesskey")||s.includes("privatekey")||s.includes("clientsecret")||s.includes("credential")?n[r]="[REDACTED]":n[r]=this.sanitizeValue(o)}return n}return t}};import{homedir as Ci}from"node:os";import{join as Mi}from"node:path";import{DeleteObjectCommand as ii,GetObjectCommand as ai,HeadObjectCommand as ci,ListObjectsV2Command as ui,PutObjectCommand as li,S3Client as di}from"@aws-sdk/client-s3";import{getSignedUrl as pi}from"@aws-sdk/s3-request-presigner";var qe=class{name="huggingface";client;bucket;constructor(t){this.bucket=t.bucket,this.client=new di({region:"us-east-1",endpoint:`https://s3.hf.co/${t.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}})}async put(t,n,r="application/octet-stream"){let o=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new li({Bucket:this.bucket,Key:t,Body:o,ContentType:r}))}async get(t){let n=await pi(this.client,new ai({Bucket:this.bucket,Key:t}),{expiresIn:60}),r=await fetch(n,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`HF download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(t){let n=await this.get(t);return n?Buffer.from(n).toString("utf8"):null}async exists(t){try{return await this.client.send(new ci({Bucket:this.bucket,Key:t})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(t){await this.client.send(new ii({Bucket:this.bucket,Key:t}))}async list(t=""){let n=[],r;do{let o=await this.client.send(new ui({Bucket:this.bucket,Prefix:t||void 0,ContinuationToken:r}));for(let s of o.Contents??[])s.Key&&n.push({key:s.Key,size:s.Size,updatedAt:s.LastModified?.toISOString()});r=o.IsTruncated?o.NextContinuationToken:void 0}while(r);return n}};import{access as Wn,mkdir as fi,readFile as mi,readdir as gi,rm as yi,stat as Dn,writeFile as hi}from"node:fs/promises";import{dirname as Si,join as ki,relative as zn,resolve as vi}from"node:path";var ge=class{constructor(t){this.root=t}root;name="local";path(t){let n=t.replace(/^\/+/,"");return vi(this.root,n)}async put(t,n){let r=this.path(t);await fi(Si(r),{recursive:!0}),await hi(r,n)}async get(t){try{return await mi(this.path(t))}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT")return null;throw n}}async getText(t){let n=await this.get(t);return n?Buffer.from(n).toString("utf8"):null}async exists(t){try{return await Wn(this.path(t)),!0}catch{return!1}}async delete(t){await yi(this.path(t),{force:!0})}async list(t=""){let n=this.path(t),r=[];try{await Wn(n)}catch{return r}let o=async i=>{let a=await gi(i,{withFileTypes:!0});for(let c of a){let u=ki(i,c.name);if(c.isDirectory()){await o(u);continue}let d=await Dn(u);r.push({key:zn(this.root,u),size:d.size,updatedAt:d.mtime.toISOString()})}},s=await Dn(n);return s.isDirectory()?await o(n):r.push({key:zn(this.root,n),size:s.size,updatedAt:s.mtime.toISOString()}),r}};import{DeleteObjectCommand as wi,GetObjectCommand as bi,HeadObjectCommand as xi,ListObjectsV2Command as ji,PutObjectCommand as Ii,S3Client as Ai}from"@aws-sdk/client-s3";import{getSignedUrl as Pi}from"@aws-sdk/s3-request-presigner";var ye=class{name;client;bucket;constructor(t){this.name=t.name??"s3",this.bucket=t.bucket,this.client=new Ai({region:t.region??"us-east-1",endpoint:t.endpoint||void 0,forcePathStyle:t.forcePathStyle??!1,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}})}async put(t,n,r="application/octet-stream"){let o=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new Ii({Bucket:this.bucket,Key:t,Body:o,ContentType:r}))}async get(t){let n=await Pi(this.client,new bi({Bucket:this.bucket,Key:t}),{expiresIn:60}),r=await fetch(n,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`${this.name} download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(t){let n=await this.get(t);return n?Buffer.from(n).toString("utf8"):null}async exists(t){try{return await this.client.send(new xi({Bucket:this.bucket,Key:t})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(t){await this.client.send(new wi({Bucket:this.bucket,Key:t}))}async list(t=""){let n=[],r;do{let o=await this.client.send(new ji({Bucket:this.bucket,Prefix:t||void 0,ContinuationToken:r}));for(let s of o.Contents??[])s.Key&&n.push({key:s.Key,size:s.Size,updatedAt:s.LastModified?.toISOString()});r=o.IsTruncated?o.NextContinuationToken:void 0}while(r);return n}};function Ot(e,t){return console.warn(t),new ge(e)}function qn(e){let t=e.localRoot??Mi(Ci(),".toolnet-memory","storage");if(e.provider==="r2"){let n=e.r2;return n?.accountId&&n.bucket&&n.accessKeyId&&n.secretAccessKey?new ye({name:"r2",endpoint:`https://${n.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:n.bucket,forcePathStyle:!0,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Ot(t,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(e.provider==="s3"){let n=e.s3;return n?.bucket&&n.accessKeyId&&n.secretAccessKey?new ye({name:"s3",endpoint:n.endpoint,region:n.region??"us-east-1",bucket:n.bucket,forcePathStyle:n.forcePathStyle??!1,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Ot(t,"[storage] S3 credentials missing. Using local fallback.")}if(e.provider==="huggingface"){let n=e.huggingface;return n?.namespace&&n.bucket&&n.accessKeyId&&n.secretAccessKey?new qe({namespace:n.namespace,bucket:n.bucket,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Ot(t,"[storage] Hugging Face credentials missing. Using local fallback.")}return new ge(t)}function Ei(e){return new Promise(t=>setTimeout(t,e))}async function Hn(e,t={}){let n=Math.max(1,t.attempts??3),r=t.baseDelayMs??150,o=t.maxDelayMs??2e3,s;for(let i=1;i<=n;i++)try{return await e()}catch(a){if(s=a,i>=n)break;let c=Math.min(o,r*2**(i-1)),u=Math.floor(Math.random()*Math.max(1,c*.2));await Ei(c+u)}throw s}var Oi=new Set(["put","get","getText","delete","list"]);function Jn(e,t={}){return new Proxy(e,{get(n,r){let o=Reflect.get(n,r,n);return typeof o!="function"?o:Oi.has(r)?(...s)=>Hn(()=>Promise.resolve(o.apply(n,s)),t):o.bind(n)}})}function Vn(e){let t=e.trim().replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,"").slice(0,100);if(!t||t==="."||t==="..")throw new Error("Invalid project storage folder");return t}function Bn(e){let t=e.replace(/^\/+/,"");if(t.startsWith("memories/"))return"memory/records/"+t.slice(9);if(t.startsWith("vectors/"))return"memory/vectors/"+t.slice(8);if(t.startsWith("graph/"))return"code/graph/"+t.slice(6);let n=t.match(/^(snapshots\/[^/]+\/)memories\/(.+)$/);if(n)return`${n[1]}memory/records/${n[2]}`;if(n=t.match(/^(snapshots\/[^/]+\/)vectors\/(.+)$/),n)return`${n[1]}memory/vectors/${n[2]}`;if(n=t.match(/^(snapshots\/[^/]+\/)graph\/(.+)$/),n)return`${n[1]}code/graph/${n[2]}`;let r=t.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(r)return`${r[1]}memory/records/${r[2]}`;if(r=t.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),r)return`${r[1]}memory/vectors/${r[2]}`;if(r=t.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),r)return`${r[1]}code/graph/${r[2]}`;let o=t.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return o?`${o[1]}memory/records/${o[2]}`:(o=t.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),o?`${o[1]}memory/vectors/${o[2]}`:(o=t.match(/^(projects\/[^/]+\/)graph\/(.+)$/),o?`${o[1]}code/graph/${o[2]}`:t))}var He=class{constructor(t,n,r,o){this.provider=t;this.name=t.name,this.projectId=n,this.projectName=r,this.folder=Vn(o??r),this.sourcePrefix=`projects/${n}`,this.targetPrefix=`projects/${this.folder}`}provider;name;folder;sourcePrefix;targetPrefix;projectId;projectName;registryPromise;async registerProject(){let t=`${this.targetPrefix}/project.json`,n=new Date().toISOString(),r=n,o=await this.provider.getText(t);if(o){let i;try{i=JSON.parse(o)}catch(a){throw new Error(`Invalid remote ToolNet project manifest at ${t}: ${a instanceof Error?a.message:String(a)}`)}if(typeof i.id=="string"&&i.id!==this.projectId)throw new Error(["ToolNet remote project namespace collision.",`Remote folder: ${this.targetPrefix}`,`Existing project id: ${i.id}`,`Current project id: ${this.projectId}`,"Refusing to mix data from two projects."].join(" "));typeof i.createdAt=="string"&&(r=i.createdAt)}let s={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:r,updatedAt:n};await this.provider.put(t,JSON.stringify(s,null,2)+`
12
- `,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(t){if(t=Bn(t),t===this.sourcePrefix)return this.targetPrefix;if(t.startsWith(`${this.sourcePrefix}/`))return this.targetPrefix+t.slice(this.sourcePrefix.length);if(t===this.targetPrefix||t.startsWith(`${this.targetPrefix}/`))return t;if(t.startsWith("projects/"))throw new Error(["Cross-project storage access denied.",`Current project: ${this.targetPrefix}`,`Requested key: ${t}`].join(" "));return t}async put(t,n,r){return await this.ensureRegistered(),this.provider.put(this.key(t),n,r)}async get(t){return await this.ensureRegistered(),this.provider.get(this.key(t))}async getText(t){return await this.ensureRegistered(),this.provider.getText(this.key(t))}async delete(t){return await this.ensureRegistered(),this.provider.delete(this.key(t))}async exists(t){return await this.ensureRegistered(),this.provider.exists(this.key(t))}async list(t){return await this.ensureRegistered(),this.provider.list(this.key(t))}};import{existsSync as Di,readFileSync as zi}from"node:fs";import{join as qi}from"node:path";import{existsSync as Ti,mkdirSync as Ri,readFileSync as Ni,renameSync as _i,writeFileSync as Ki}from"node:fs";import{dirname as $i,join as Li}from"node:path";function Gn(e){return Li(e.rootPath,".toolnet","context","session-origin.json")}function Fi(e,t){Ri($i(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;Ki(n,`${JSON.stringify(t,null,2)}
13
- `,{encoding:"utf8",mode:384}),_i(n,e)}function Je(e,t){return[...e].filter(n=>n.kind===t).sort((n,r)=>{let o=n.occurredAt.localeCompare(r.occurredAt);return o!==0?o:n.sequence-r.sequence}).at(-1)}function Un(e,t){let n=Je(t.observations,"file"),r=Je(t.observations,"next_action"),o=Je(t.observations,"blocker"),s=Je(t.observations,"decision"),i={version:1,projectId:e.id,agent:t.agent,nativeSessionId:t.nativeSessionId,updatedAt:t.workState.updatedAt,currentRequest:t.workState.currentRequest,currentActivity:t.workState.currentActivity,currentTask:t.workState.currentTask?.title,currentPhase:t.workState.currentPhase?.title,lastTouchedFile:n?.text??t.workState.activeFiles?.at(-1)??t.workState.filesTouched.at(-1),latestNextAction:r?.text??t.workState.nextActions.at(-1),latestBlocker:o?.text??t.workState.blockers.at(-1),latestDecision:s?.text??t.workState.decisions.at(-1)};return Fi(Gn(e),i),i}function Wi(e){let t=Gn(e);if(!Ti(t))return null;try{let n=JSON.parse(Ni(t,"utf8"));return n.version!==1||n.projectId!==e.id?null:n}catch{return null}}function Yn(e){let t=Wi(e);if(!t)return null;let n=["Previous session:",`- Agent: ${t.agent}`,`- Session: ${t.nativeSessionId}`];return t.currentRequest&&n.push(`- Current request: ${t.currentRequest}`),t.currentActivity&&n.push(`- Current activity: ${t.currentActivity}`),t.currentPhase&&n.push(`- Current phase: ${t.currentPhase}`),t.currentTask&&n.push(`- Current task: ${t.currentTask}`),t.lastTouchedFile&&n.push(`- Last touched file: ${t.lastTouchedFile}`),t.latestBlocker&&n.push(`- Blocker: ${t.latestBlocker}`),t.latestNextAction&&n.push(`- Next action: ${t.latestNextAction}`),t.latestDecision&&n.push(`- Important decision: ${t.latestDecision}`),n.join(`
14
- `)}function Hi(e){let t=qi(e.rootPath,".toolnet","current.md");if(!Di(t))return null;try{return zi(t,"utf8").trim()}catch{return null}}function Ji(e,t){let n=t.replace(/\r\n/g,`
7
+ `,{encoding:"utf8",mode:384}),ci(n,e)}function di(e,t){Dn(e,`${JSON.stringify(t,null,2)}
8
+ `)}function Wn(e,t){let n=t.replace(/\r\n/g,`
9
+ `).trim();if(!n)return null;let r={version:1,projectId:e.id,projectName:e.name,text:n,digest:w(n),generatedAt:new Date().toISOString()};return Dn(Ln(e),n),di(Fn(e),r),r}function zn(e){let t=Ln(e);if(!_n(t))return null;try{let n=Kn(t,"utf8").trim();if(!n)return null;let r=new Date(0).toISOString(),o=Fn(e);if(_n(o))try{let s=JSON.parse(Kn(o,"utf8"));typeof s.generatedAt=="string"&&(r=s.generatedAt)}catch{}return{version:1,projectId:e.id,projectName:e.name,text:n,digest:w(n),generatedAt:r}}catch{return null}}function qn(e){let t=J.resolve(e),n=J.parse(t).root;for(;t!==n;){let r=J.join(t,".toolnet");if(se.existsSync(r)&&se.statSync(r).isDirectory())return t;t=J.dirname(t)}return null}function Hn(e){return e.replace(/\\/g,"/").toLowerCase()}function Ft(e,t,n=0){if(!(n>6||t.length>=250)){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let r of e)if(Ft(r,t,n+1),t.length>=250)break;return}if(e&&typeof e=="object"){for(let r of Object.values(e))if(Ft(r,t,n+1),t.length>=250)break}}}function pi(e){let t=Hn(e);if(t.includes(".toolnet/journal/")||t.includes(".toolnet/runtime/sources/")||t.endsWith(".toolnet/journal")||t.endsWith(".toolnet/runtime/sources")||t.includes(".toolnet/sessions/")||t.endsWith(".toolnet/sessions")||t.includes(".gemini/antigravity-cli/brain/")||t.endsWith(".gemini/antigravity-cli/brain")||t.includes("/transcript.jsonl")||t.endsWith("transcript.jsonl")||t.includes(".toolnet/")&&(t.endsWith("/events.jsonl")||t.endsWith("/state.json")||t.includes("/sessions/")))return!0;let n=process.env.CURSOR_TRANSCRIPT_PATH;return!!(n&&Hn(n)===t)}function Jn(e){let t=[];return Ft(e,t),t.find(pi)?{blocked:!0,reason:"ToolNet continuity guard: do not read or reconstruct previous work from raw ToolNet/agent session history. Use the injected ToolNet handoff first; if it is insufficient, invoke the MCP tool memory_agent_ask directly. Then verify normal repository/git source truth."}:{blocked:!1}}function Ve(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Vn(e,t=process.env){return Ve(t.TOOLNET_HOOK_EVENT)??Ve(e.hookEventName)??Ve(e.hook_event_name)??Ve(t.GROK_HOOK_EVENT)??""}function Bn(e){return Jn(e.toolInput??e.tool_input??e)}function Gn(e){return{decision:"deny",reason:e}}import{existsSync as Pd}from"node:fs";import{join as Md}from"node:path";import{existsSync as fi,readFileSync as mi}from"node:fs";import{homedir as gi}from"node:os";import{join as yi}from"node:path";function hi(e){let t=e.trim();return t.length>=2&&t.startsWith('"')&&t.endsWith('"')?(t=t.slice(1,-1),t.replace(/\\n/g,`
10
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):t.length>=2&&t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Si(){let e=process.env.TOOLNET_GLOBAL_ENV??yi(gi(),".config","toolnet-memory",".env");if(!fi(e))return;let t=mi(e,"utf8");for(let n of t.split(/\r?\n/)){let r=n.trim();if(!r||r.startsWith("#"))continue;r.startsWith("export ")&&(r=r.slice(7));let o=r.indexOf("=");if(o<=0)continue;let s=r.slice(0,o).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)&&process.env[s]===void 0&&(process.env[s]=hi(r.slice(o+1)))}}Si();function ge(e,t){return e===void 0?t:["1","true","yes","on"].includes(e.toLowerCase())}function ye(e,t){if(!e)return t;let n=Number(e);return Number.isFinite(n)?n:t}function Be(){return{memory:{autoCapture:ge(process.env.MEMORY_AUTO_CAPTURE,!0),autoRetrieve:ge(process.env.MEMORY_AUTO_RETRIEVE,!0),autoSummarize:ge(process.env.MEMORY_AUTO_SUMMARIZE,!0),autoSync:ge(process.env.MEMORY_AUTO_SYNC,!0)},retrieval:{maxCandidates:ye(process.env.MEMORY_MAX_CANDIDATES,50),rerankTop:ye(process.env.MEMORY_RERANK_TOP,10),finalContext:ye(process.env.MEMORY_FINAL_CONTEXT,5),tokenBudget:ye(process.env.MEMORY_TOKEN_BUDGET,2e3)},storage:{provider:process.env.MEMORY_STORAGE_PROVIDER??"huggingface",r2:{accountId:process.env.R2_ACCOUNT_ID,bucket:process.env.R2_BUCKET,accessKeyId:process.env.R2_ACCESS_KEY_ID,secretAccessKey:process.env.R2_SECRET_ACCESS_KEY},s3:{endpoint:process.env.S3_ENDPOINT,region:process.env.S3_REGION,bucket:process.env.S3_BUCKET,accessKeyId:process.env.S3_ACCESS_KEY_ID,secretAccessKey:process.env.S3_SECRET_ACCESS_KEY,forcePathStyle:ge(process.env.S3_FORCE_PATH_STYLE,!1)},huggingface:{namespace:process.env.HF_NAMESPACE,bucket:process.env.HF_BUCKET,accessKeyId:process.env.HF_S3_ACCESS_KEY_ID,secretAccessKey:process.env.HF_S3_SECRET_ACCESS_KEY},localRoot:process.env.MEMORY_LOCAL_STORAGE_PATH},cache:{maxMb:ye(process.env.MEMORY_LOCAL_CACHE_MB,200)}}}import{createHash as Ii}from"node:crypto";import{existsSync as Ye,mkdirSync as Ai,readFileSync as Pi,renameSync as Mi,writeFileSync as Ci}from"node:fs";import{basename as Ei,dirname as Xe,join as Se,parse as nr,resolve as Z}from"node:path";import{createHash as Xn}from"node:crypto";import{spawnSync as ki}from"node:child_process";var he="git-remote-v1",vi=new Set(["github.com","gitlab.com","bitbucket.org"]);function Zn(e,t){let n=t.replaceAll("\\","/").replace(/^\/+/u,"").replace(/\/+$/u,"").replace(/\.git$/iu,"").replace(/\/+/gu,"/");return!n||n==="."||n===".."||n.split("/").some(r=>!r||r==="."||r==="..")?null:(vi.has(e)&&(n=n.toLowerCase()),n)}function wi(e){let t;try{t=new URL(e)}catch{return null}if(!["https:","http:","ssh:","git:"].includes(t.protocol))return null;let n=t.hostname.trim().toLowerCase();if(!n)return null;let r=t.protocol==="https:"&&t.port==="443"||t.protocol==="http:"&&t.port==="80"||t.protocol==="ssh:"&&t.port==="22",o=t.port&&!r?`${n}:${t.port}`:n,s=Zn(n,t.pathname);return s?`${o}/${s}`:null}function bi(e){let t=e.match(/^(?:[^@\s/:]+@)?([^:/\s]+):(.+)$/u);if(!t)return null;let n=t[1]?.trim().toLowerCase();if(!n||n.length===1)return null;let r=Zn(n,t[2]??"");return r?`${n}/${r}`:null}function Un(e){let t=e.trim();return t?t.includes("://")?wi(t):bi(t):null}function xi(e){return Xn("sha256").update(`${he}:${e}`).digest("hex")}function Qn(e){return Xn("sha256").update(`toolnet-project:${he}:${e}`).digest("hex").slice(0,16)}function ji(e){return e.split("/").filter(Boolean).at(-1)?.trim()||null}function Dt(e,t){let n=ki("git",["-C",e,...t],{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]});return n.error||n.status!==0?null:n.stdout?.trim()||null}function Yn(e,t){let n=ji(e);return n?{scheme:he,canonicalRemote:e,fingerprint:xi(e),repositoryName:n,source:t}:null}function er(e){let t=Dt(e,["remote","get-url","origin"]);if(t){let o=Un(t);if(o)return Yn(o,"origin")}let n=Dt(e,["remote"]);if(!n)return null;let r=new Set;for(let o of n.split(/\r?\n/u).map(s=>s.trim()).filter(Boolean)){let s=Dt(e,["remote","get-url",o]);if(!s)continue;let i=Un(s);i&&r.add(i)}return r.size!==1?null:Yn([...r][0],"unique-remote")}var rr=".toolnet",Oi="project.json";function Ti(e){return Ii("sha256").update(e).digest("hex").slice(0,16)}function ie(e){return Se(e,rr,Oi)}function or(e){return Ye(ie(e))}function tr(e,t){let n=Z(e),r=nr(n).root;for(;;){if(or(n))return n;if(n===r||t&&n===Z(t))break;let o=Xe(n);if(o===n)break;n=o}return null}function Wt(e){let t=Z(e),n=nr(t).root,r=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(r.some(s=>Ye(Se(t,s))))return t;if(t===n)break;let o=Xe(t);if(o===t)break;t=o}return Z(e)}function Ge(e){let t;try{t=JSON.parse(Pi(e,"utf8"))}catch(o){throw new Error(`Invalid ToolNet project manifest: ${e}: ${o instanceof Error?o.message:String(o)}`)}if(!t||typeof t!="object")throw new Error(`Invalid ToolNet project manifest: ${e}`);let n=t;if(typeof n.id!="string"||!n.id.trim())throw new Error(`ToolNet project manifest is missing id: ${e}`);if(typeof n.name!="string"||!n.name.trim())throw new Error(`ToolNet project manifest is missing name: ${e}`);let r=new Date().toISOString();return{version:1,id:n.id,name:n.name,remote:typeof n.remote=="string"&&n.remote.trim()?n.remote:n.name,rootPath:typeof n.rootPath=="string"?n.rootPath:Xe(Xe(e)),createdAt:typeof n.createdAt=="string"?n.createdAt:r,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:r,graphVersion:typeof n.graphVersion=="number"?n.graphVersion:0,memoryVersion:typeof n.memoryVersion=="number"?n.memoryVersion:0,metadata:n.metadata&&typeof n.metadata=="object"?n.metadata:void 0}}function Ue(e,t){let n=Se(e,rr);Ai(n,{recursive:!0});let r=ie(e),o=`${r}.tmp-${process.pid}`;Ci(o,JSON.stringify(t,null,2)+`
11
+ `,{encoding:"utf8",mode:384}),Mi(o,r)}function X(e,t){return{id:e.id,name:e.name,remote:e.remote,rootPath:t,createdAt:e.createdAt,updatedAt:e.updatedAt,graphVersion:e.graphVersion,memoryVersion:e.memoryVersion,metadata:e.metadata}}function zt(e){return{version:1,scheme:he,canonicalRemote:e.canonicalRemote,fingerprint:e.fingerprint,repositoryName:e.repositoryName}}function Ri(e){let t=e.metadata?.toolnetIdentity;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t;return typeof n.fingerprint=="string"?n.fingerprint:null}var Ze=class{adopt(t,n){let r=Wt(Z(t));if(!n.id.trim())throw new Error("PROJECT_ADOPTION_INVALID_ID");if(!n.name.trim())throw new Error("PROJECT_ADOPTION_INVALID_NAME");if(!n.remote.trim())throw new Error("PROJECT_ADOPTION_INVALID_REMOTE");if(or(r)){let a=Ge(ie(r));if(a.id!==n.id)throw new Error(["PROJECT_IDENTITY_ALREADY_EXISTS",`existing=${a.id}`,`requested=${n.id}`].join(" "));return X(a,r)}let o=new Date().toISOString(),s={...n.metadata};n.gitIdentity&&(s.toolnetIdentity=zt(n.gitIdentity));let i={version:1,id:n.id.trim(),name:n.name.trim(),remote:n.remote.trim(),rootPath:r,createdAt:n.createdAt??o,updatedAt:o,graphVersion:n.graphVersion??0,memoryVersion:n.memoryVersion??0,metadata:Object.keys(s).length?s:void 0};return Ue(r,i),X(i,r)}recordGitIdentity(t,n,r={}){let o=this.requireExisting(t),s=ie(o.rootPath),i=Ge(s),a=Ri(i);if(a&&a!==n.fingerprint&&!r.allowRebind)throw new Error(["PROJECT_GIT_REMOTE_CHANGED",`existing=${a}`,`current=${n.fingerprint}`,"Use explicit rebind only when this repository identity change is intentional."].join(" "));let c=i.metadata?.toolnetIdentity;return c&&typeof c=="object"&&!Array.isArray(c)&&c.fingerprint===n.fingerprint||(i.metadata={...i.metadata,toolnetIdentity:zt(n)},i.updatedAt=new Date().toISOString(),Ue(o.rootPath,i)),X(i,o.rootPath)}findExisting(t=process.cwd()){let n=Z(t),r=Wt(n),s=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(c=>Ye(Se(r,c))),i=tr(n,s?r:void 0);if(!i)return null;let a=Ge(ie(i));return X(a,i)}requireExisting(t=process.cwd()){let n=this.findExisting(t);if(!n)throw new Error("PROJECT_NOT_INITIALIZED");return n}detect(t=process.cwd()){let n=Z(t),r=Wt(n),s=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(d=>Ye(Se(r,d))),i=tr(n,s?r:void 0);if(i){let d=ie(i),p=Ge(d);return p.rootPath!==i&&(p.rootPath=i,p.updatedAt=new Date().toISOString(),Ue(i,p)),X(p,i)}let a=new Date().toISOString(),c=Ei(r),u=er(r),l={version:1,id:u?Qn(u.canonicalRemote):Ti(r),name:c,remote:u?.repositoryName??c,rootPath:r,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0,metadata:u?{toolnetIdentity:zt(u)}:void 0};return Ue(r,l),X(l,r)}};var Ni=[{type:"openai_key",regex:/\bsk-[A-Za-z0-9_-]{20,}\b/g,confidence:"exact"},{type:"huggingface_token",regex:/\bhf_[A-Za-z0-9]{20,}\b/g,confidence:"exact"},{type:"hf_s3_access_key",regex:/\bHFAK[A-Za-z0-9]{8,}\b/g,confidence:"exact"},{type:"aws_access_key",regex:/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,confidence:"exact"},{type:"github_token",regex:/\b(?:gh[pousr]_[A-Za-z0-9]{30,255}|github_pat_[A-Za-z0-9_]{40,255})\b/g,confidence:"exact"},{type:"stripe_secret_key",regex:/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/g,confidence:"exact"},{type:"google_api_key",regex:/\bAIza[A-Za-z0-9_-]{30,}\b/g,confidence:"exact"},{type:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{16,}\b/g,confidence:"exact"},{type:"npm_token",regex:/\bnpm_[A-Za-z0-9]{20,}\b/g,confidence:"exact"},{type:"bearer_token",regex:/\bBearer\s+[A-Za-z0-9._~+/=-]{16,}\b/gi,confidence:"high"},{type:"jwt",regex:/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,confidence:"exact"},{type:"private_key",regex:/-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/g,confidence:"exact"},{type:"password_assignment",regex:/\b(?:password|passwd|pwd)\s*[:=]\s*["']?[^"' \t\r\n]{6,}["']?/gi,confidence:"high"},{type:"secret_assignment",regex:/\b(?:secret|api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|private[_-]?key)\s*[:=]\s*["']?[^"' \t\r\n]{8,}["']?/gi,confidence:"high"},{type:"cookie",regex:/\b(?:cookie|set-cookie)\s*[:=]\s*[^;\n]{8,}/gi,confidence:"high"},{type:"url_credentials",regex:/\bhttps?:\/\/[^:/@\s]+:[^/@\s]{4,}@[^/\s]+/gi,confidence:"high"}],_i=new Set(["example","example-key","example-token","changeme","change-me","password","secret","your-api-key","your-token","<token>","<secret>","<password>","[redacted]"]);function sr(e){return e.normalize("NFKC").trim().toLowerCase()}function Ki(e){if(e.length===0)return 0;let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);let n=0;for(let r of t.values()){let o=r/e.length;n-=o*Math.log2(o)}return n}function $i(e){return/^[a-f0-9]{32}$/iu.test(e)||/^[a-f0-9]{40}$/iu.test(e)||/^[a-f0-9]{64}$/iu.test(e)}function Li(e,t,n){let r=e.slice(Math.max(0,t-48),t),o=e.slice(n,Math.min(e.length,n+16));return/\b(?:token|secret|key|credential|authorization|password|passwd|apikey|api_key|access[_-]?key)\b/iu.test(`${r} ${o}`)}function Fi(e,t){return e.start<t.end&&t.start<e.end}function ir(e){return e.sort((t,n)=>t.start!==n.start?t.start-n.start:n.end-n.start-(t.end-t.start))}var Qe=class{allowValues=new Set;enableEntropyHeuristic;constructor(t={}){for(let n of t.allowValues??[]){let r=sr(n);r&&this.allowValues.add(r)}this.enableEntropyHeuristic=t.enableEntropyHeuristic??!0}scan(t){let n=[];for(let s of Ni){let i=new RegExp(s.regex.source,s.regex.flags);for(let a of t.matchAll(i))a.index===void 0||!a[0]||this.allowed(a[0])||n.push({type:s.type,value:a[0],start:a.index,end:a.index+a[0].length,confidence:s.confidence})}this.enableEntropyHeuristic&&n.push(...this.entropyMatches(t));let r=ir(n),o=[];for(let s of r)o.some(i=>Fi(i,s))||o.push(s);return ir(o)}hasSecrets(t){return this.scan(t).length>0}allowed(t){let n=sr(t);return _i.has(n)?!0:this.allowValues.has(n)}entropyMatches(t){let n=[],r=/[A-Za-z0-9_+/=-]{32,160}/g;for(let o of t.matchAll(r)){if(o.index===void 0||!o[0])continue;let s=o[0];this.allowed(s)||$i(s)||!/[A-Za-z]/u.test(s)||!/[0-9]/u.test(s)||Li(t,o.index,o.index+s.length)&&(Ki(s)<3.7||n.push({type:"high_entropy_secret",value:s,start:o.index,end:o.index+s.length,confidence:"heuristic"}))}return n}};var V=class{scanner;constructor(t={}){this.scanner=new Qe(t)}sanitize(t){let n=this.scanner.scan(t);if(n.length===0)return{text:t,redacted:0,secretTypes:[]};let r=t,o=[...n].sort((i,a)=>a.start-i.start),s=new Set;for(let i of o)s.add(i.type),r=r.slice(0,i.start)+`[REDACTED:${i.type}]`+r.slice(i.end);return{text:r,redacted:n.length,secretTypes:[...s].sort()}}sanitizeValue(t){if(typeof t=="string")return this.sanitize(t).text;if(Array.isArray(t))return t.map(n=>this.sanitizeValue(n));if(t&&typeof t=="object"){let n={};for(let[r,o]of Object.entries(t)){let s=r.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"");if(s.includes("password")||s.includes("passwd")||s==="pwd"||s.includes("secret")||s.includes("token")||s.includes("cookie")||s.includes("authorization")||s.includes("apikey")||s.includes("accesskey")||s.includes("privatekey")||s.includes("clientsecret")||s.includes("credential")){n[r]="[REDACTED]";continue}n[r]=this.sanitizeValue(o)}return n}return t}};var Di=new V;function ke(e){return Di.sanitizeValue(e)}import{homedir as ua}from"node:os";import{join as la}from"node:path";import{DeleteObjectCommand as Wi,GetObjectCommand as zi,HeadObjectCommand as qi,ListObjectsV2Command as Hi,PutObjectCommand as Ji,S3Client as Vi}from"@aws-sdk/client-s3";import{getSignedUrl as Bi}from"@aws-sdk/s3-request-presigner";var et=class{name="huggingface";client;bucket;constructor(t){this.bucket=t.bucket,this.client=new Vi({region:"us-east-1",endpoint:`https://s3.hf.co/${t.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}})}async put(t,n,r="application/octet-stream"){let o=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new Ji({Bucket:this.bucket,Key:t,Body:o,ContentType:r}))}async get(t){let n=await Bi(this.client,new zi({Bucket:this.bucket,Key:t}),{expiresIn:60}),r=await fetch(n,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`HF download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(t){let n=await this.get(t);return n?Buffer.from(n).toString("utf8"):null}async exists(t){try{return await this.client.send(new qi({Bucket:this.bucket,Key:t})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(t){await this.client.send(new Wi({Bucket:this.bucket,Key:t}))}async list(t=""){let n=[],r;do{let o=await this.client.send(new Hi({Bucket:this.bucket,Prefix:t||void 0,ContinuationToken:r}));for(let s of o.Contents??[])s.Key&&n.push({key:s.Key,size:s.Size,updatedAt:s.LastModified?.toISOString()});r=o.IsTruncated?o.NextContinuationToken:void 0}while(r);return n}};import{access as ar,mkdir as Gi,readFile as Ui,readdir as Yi,rm as Xi,stat as cr,writeFile as Zi}from"node:fs/promises";import{dirname as Qi,join as ea,relative as ur,resolve as ta}from"node:path";var ve=class{constructor(t){this.root=t}root;name="local";path(t){let n=t.replace(/^\/+/,"");return ta(this.root,n)}async put(t,n){let r=this.path(t);await Gi(Qi(r),{recursive:!0}),await Zi(r,n)}async get(t){try{return await Ui(this.path(t))}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT")return null;throw n}}async getText(t){let n=await this.get(t);return n?Buffer.from(n).toString("utf8"):null}async exists(t){try{return await ar(this.path(t)),!0}catch{return!1}}async delete(t){await Xi(this.path(t),{force:!0})}async list(t=""){let n=this.path(t),r=[];try{await ar(n)}catch{return r}let o=async i=>{let a=await Yi(i,{withFileTypes:!0});for(let c of a){let u=ea(i,c.name);if(c.isDirectory()){await o(u);continue}let l=await cr(u);r.push({key:ur(this.root,u),size:l.size,updatedAt:l.mtime.toISOString()})}},s=await cr(n);return s.isDirectory()?await o(n):r.push({key:ur(this.root,n),size:s.size,updatedAt:s.mtime.toISOString()}),r}};import{DeleteObjectCommand as na,GetObjectCommand as ra,HeadObjectCommand as oa,ListObjectsV2Command as sa,PutObjectCommand as ia,S3Client as aa}from"@aws-sdk/client-s3";import{getSignedUrl as ca}from"@aws-sdk/s3-request-presigner";var we=class{name;client;bucket;constructor(t){this.name=t.name??"s3",this.bucket=t.bucket,this.client=new aa({region:t.region??"us-east-1",endpoint:t.endpoint||void 0,forcePathStyle:t.forcePathStyle??!1,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}})}async put(t,n,r="application/octet-stream"){let o=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new ia({Bucket:this.bucket,Key:t,Body:o,ContentType:r}))}async get(t){let n=await ca(this.client,new ra({Bucket:this.bucket,Key:t}),{expiresIn:60}),r=await fetch(n,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`${this.name} download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(t){let n=await this.get(t);return n?Buffer.from(n).toString("utf8"):null}async exists(t){try{return await this.client.send(new oa({Bucket:this.bucket,Key:t})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(t){await this.client.send(new na({Bucket:this.bucket,Key:t}))}async list(t=""){let n=[],r;do{let o=await this.client.send(new sa({Bucket:this.bucket,Prefix:t||void 0,ContinuationToken:r}));for(let s of o.Contents??[])s.Key&&n.push({key:s.Key,size:s.Size,updatedAt:s.LastModified?.toISOString()});r=o.IsTruncated?o.NextContinuationToken:void 0}while(r);return n}};function qt(e,t){return console.warn(t),new ve(e)}function lr(e){let t=e.localRoot??la(ua(),".toolnet-memory","storage");if(e.provider==="r2"){let n=e.r2;return n?.accountId&&n.bucket&&n.accessKeyId&&n.secretAccessKey?new we({name:"r2",endpoint:`https://${n.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:n.bucket,forcePathStyle:!0,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):qt(t,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(e.provider==="s3"){let n=e.s3;return n?.bucket&&n.accessKeyId&&n.secretAccessKey?new we({name:"s3",endpoint:n.endpoint,region:n.region??"us-east-1",bucket:n.bucket,forcePathStyle:n.forcePathStyle??!1,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):qt(t,"[storage] S3 credentials missing. Using local fallback.")}if(e.provider==="huggingface"){let n=e.huggingface;return n?.namespace&&n.bucket&&n.accessKeyId&&n.secretAccessKey?new et({namespace:n.namespace,bucket:n.bucket,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):qt(t,"[storage] Hugging Face credentials missing. Using local fallback.")}return new ve(t)}function da(e){return new Promise(t=>setTimeout(t,e))}async function dr(e,t={}){let n=Math.max(1,t.attempts??3),r=t.baseDelayMs??150,o=t.maxDelayMs??2e3,s;for(let i=1;i<=n;i++)try{return await e()}catch(a){if(s=a,i>=n)break;let c=Math.min(o,r*2**(i-1)),u=Math.floor(Math.random()*Math.max(1,c*.2));await da(c+u)}throw s}var pa=new Set(["put","get","getText","delete","list"]);function pr(e,t={}){return new Proxy(e,{get(n,r){let o=Reflect.get(n,r,n);return typeof o!="function"?o:pa.has(r)?(...s)=>dr(()=>Promise.resolve(o.apply(n,s)),t):o.bind(n)}})}function fr(e){let t=e.trim().replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,"").slice(0,100);if(!t||t==="."||t==="..")throw new Error("Invalid project storage folder");return t}function mr(e){let t=e.replace(/^\/+/,"");if(t.startsWith("memories/"))return"memory/records/"+t.slice(9);if(t.startsWith("vectors/"))return"memory/vectors/"+t.slice(8);if(t.startsWith("graph/"))return"code/graph/"+t.slice(6);let n=t.match(/^(snapshots\/[^/]+\/)memories\/(.+)$/);if(n)return`${n[1]}memory/records/${n[2]}`;if(n=t.match(/^(snapshots\/[^/]+\/)vectors\/(.+)$/),n)return`${n[1]}memory/vectors/${n[2]}`;if(n=t.match(/^(snapshots\/[^/]+\/)graph\/(.+)$/),n)return`${n[1]}code/graph/${n[2]}`;let r=t.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(r)return`${r[1]}memory/records/${r[2]}`;if(r=t.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),r)return`${r[1]}memory/vectors/${r[2]}`;if(r=t.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),r)return`${r[1]}code/graph/${r[2]}`;let o=t.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return o?`${o[1]}memory/records/${o[2]}`:(o=t.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),o?`${o[1]}memory/vectors/${o[2]}`:(o=t.match(/^(projects\/[^/]+\/)graph\/(.+)$/),o?`${o[1]}code/graph/${o[2]}`:t))}var tt=class{constructor(t,n,r,o){this.provider=t;this.name=t.name,this.projectId=n,this.projectName=r,this.folder=fr(o??r),this.sourcePrefix=`projects/${n}`,this.targetPrefix=`projects/${this.folder}`}provider;name;folder;sourcePrefix;targetPrefix;projectId;projectName;registryPromise;async registerProject(){let t=`${this.targetPrefix}/project.json`,n=new Date().toISOString(),r=n,o=await this.provider.getText(t);if(o){let i;try{i=JSON.parse(o)}catch(a){throw new Error(`Invalid remote ToolNet project manifest at ${t}: ${a instanceof Error?a.message:String(a)}`)}if(typeof i.id=="string"&&i.id!==this.projectId)throw new Error(["ToolNet remote project namespace collision.",`Remote folder: ${this.targetPrefix}`,`Existing project id: ${i.id}`,`Current project id: ${this.projectId}`,"Refusing to mix data from two projects."].join(" "));typeof i.createdAt=="string"&&(r=i.createdAt)}let s={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:r,updatedAt:n};await this.provider.put(t,JSON.stringify(s,null,2)+`
12
+ `,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(t){if(t=mr(t),t===this.sourcePrefix)return this.targetPrefix;if(t.startsWith(`${this.sourcePrefix}/`))return this.targetPrefix+t.slice(this.sourcePrefix.length);if(t===this.targetPrefix||t.startsWith(`${this.targetPrefix}/`))return t;if(t.startsWith("projects/"))throw new Error(["Cross-project storage access denied.",`Current project: ${this.targetPrefix}`,`Requested key: ${t}`].join(" "));return t}async put(t,n,r){return await this.ensureRegistered(),this.provider.put(this.key(t),n,r)}async get(t){return await this.ensureRegistered(),this.provider.get(this.key(t))}async getText(t){return await this.ensureRegistered(),this.provider.getText(this.key(t))}async delete(t){return await this.ensureRegistered(),this.provider.delete(this.key(t))}async exists(t){return await this.ensureRegistered(),this.provider.exists(this.key(t))}async list(t){return await this.ensureRegistered(),this.provider.list(this.key(t))}};import{existsSync as ba,readFileSync as xa}from"node:fs";import{join as ja}from"node:path";import{existsSync as fa,mkdirSync as ma,readFileSync as ga,renameSync as ya,writeFileSync as ha}from"node:fs";import{dirname as Sa,join as ka}from"node:path";function gr(e){return ka(e.rootPath,".toolnet","context","session-origin.json")}function va(e,t){ma(Sa(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;ha(n,`${JSON.stringify(t,null,2)}
13
+ `,{encoding:"utf8",mode:384}),ya(n,e)}function nt(e,t){return[...e].filter(n=>n.kind===t).sort((n,r)=>{let o=n.occurredAt.localeCompare(r.occurredAt);return o!==0?o:n.sequence-r.sequence}).at(-1)}function yr(e,t){let n=nt(t.observations,"file"),r=nt(t.observations,"next_action"),o=nt(t.observations,"blocker"),s=nt(t.observations,"decision"),i={version:1,projectId:e.id,agent:t.agent,nativeSessionId:t.nativeSessionId,updatedAt:t.workState.updatedAt,currentRequest:t.workState.currentRequest,currentActivity:t.workState.currentActivity,currentTask:t.workState.currentTask?.title,currentPhase:t.workState.currentPhase?.title,lastTouchedFile:n?.text??t.workState.activeFiles?.at(-1)??t.workState.filesTouched.at(-1),latestNextAction:r?.text??t.workState.nextActions.at(-1),latestBlocker:o?.text??t.workState.blockers.at(-1),latestDecision:s?.text??t.workState.decisions.at(-1)};return va(gr(e),i),i}function wa(e){let t=gr(e);if(!fa(t))return null;try{let n=JSON.parse(ga(t,"utf8"));return n.version!==1||n.projectId!==e.id?null:n}catch{return null}}function hr(e){let t=wa(e);if(!t)return null;let n=["Previous session:",`- Agent: ${t.agent}`,`- Session: ${t.nativeSessionId}`];return t.currentRequest&&n.push(`- Current request: ${t.currentRequest}`),t.currentActivity&&n.push(`- Current activity: ${t.currentActivity}`),t.currentPhase&&n.push(`- Current phase: ${t.currentPhase}`),t.currentTask&&n.push(`- Current task: ${t.currentTask}`),t.lastTouchedFile&&n.push(`- Last touched file: ${t.lastTouchedFile}`),t.latestBlocker&&n.push(`- Blocker: ${t.latestBlocker}`),t.latestNextAction&&n.push(`- Next action: ${t.latestNextAction}`),t.latestDecision&&n.push(`- Important decision: ${t.latestDecision}`),n.join(`
14
+ `)}function Ia(e){let t=ja(e.rootPath,".toolnet","current.md");if(!ba(t))return null;try{return xa(t,"utf8").trim()}catch{return null}}function Aa(e,t){let n=t.replace(/\r\n/g,`
15
15
  `).trim(),r=2400,o=n.length>r?`${n.slice(0,r)}
16
16
 
17
- [Current work truncated for fast handoff]`:n,s=Yn(e);return["# ToolNet Fast Handoff","",`Project: ${e.name}`,"",...s?[s,""]:[],o,"","---","","Continuation rule:","- Continue unfinished work; do not redo completed steps.","- Query ToolNet Memory only when deeper history is needed."].join(`
18
- `)}function Xn(e){let t=Hi(e);if(t===null)return{updated:!1,reason:"missing-current",chars:0};if(!t.trim())return{updated:!1,reason:"empty-current",chars:0};let n=Ji(e,t);return Mn(e)?.text.trim()===n.trim()?{updated:!1,reason:"unchanged",chars:n.length}:(Cn(e,n),{updated:!0,reason:"updated",chars:n.length})}import{join as Vi}from"node:path";function Qn(e,t){let n=e.trim(),r=n.replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,""),o=v(n).slice(0,12);if(!r||r==="."||r==="..")return`${t}--${o}`;let s=r.slice(0,100);return s===n&&n.length<=100?s:`${s.slice(0,85)}--${o}`}function Ve(e,t,n){let r=t.trim(),o=n.trim();if(!r)throw new Error("Session agent is required");if(!o)throw new Error("Native session ID is required");let s=Qn(r.toLowerCase(),"agent"),i=Qn(o,"session");return{projectId:e.id,projectName:e.name,projectRoot:e.rootPath,agent:r,nativeSessionId:o,sessionKey:`${r}:${o}`,remotePrefix:["projects",e.id,"runtime","sources",s,i].join("/"),localDirectory:Vi(e.rootPath,".toolnet","runtime","sources",s,i)}}function Zn(e){return String(e).padStart(12,"0")}var Be=class{constructor(t,n=100,r=512*1024){this.storage=t;this.maxEventsPerChunk=n;this.maxChunkBytes=r;if(n<1)throw new Error("maxEventsPerChunk must be positive");if(r<1024)throw new Error("maxChunkBytes is too small")}storage;maxEventsPerChunk;maxChunkBytes;async getJson(t){let n=await this.storage.getText(t);return n?JSON.parse(n):null}async putJson(t,n){await this.storage.put(t,JSON.stringify(n,null,2)+`
17
+ [Current work truncated for fast handoff]`:n,s=hr(e);return["# ToolNet Fast Handoff","",`Project: ${e.name}`,"",...s?[s,""]:[],o,"","---","","Continuation rule:","- Continue unfinished work; do not redo completed steps.","- Query ToolNet Memory only when deeper history is needed."].join(`
18
+ `)}function Sr(e){let t=Ia(e);if(t===null)return{updated:!1,reason:"missing-current",chars:0};if(!t.trim())return{updated:!1,reason:"empty-current",chars:0};let n=Aa(e,t);return zn(e)?.text.trim()===n.trim()?{updated:!1,reason:"unchanged",chars:n.length}:(Wn(e,n),{updated:!0,reason:"updated",chars:n.length})}import{join as Pa}from"node:path";function kr(e,t){let n=e.trim(),r=n.replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,""),o=w(n).slice(0,12);if(!r||r==="."||r==="..")return`${t}--${o}`;let s=r.slice(0,100);return s===n&&n.length<=100?s:`${s.slice(0,85)}--${o}`}function rt(e,t,n){let r=t.trim(),o=n.trim();if(!r)throw new Error("Session agent is required");if(!o)throw new Error("Native session ID is required");let s=kr(r.toLowerCase(),"agent"),i=kr(o,"session");return{projectId:e.id,projectName:e.name,projectRoot:e.rootPath,agent:r,nativeSessionId:o,sessionKey:`${r}:${o}`,remotePrefix:["projects",e.id,"runtime","sources",s,i].join("/"),localDirectory:Pa(e.rootPath,".toolnet","runtime","sources",s,i)}}function vr(e){return String(e).padStart(12,"0")}var ot=class{constructor(t,n=100,r=512*1024){this.storage=t;this.maxEventsPerChunk=n;this.maxChunkBytes=r;if(n<1)throw new Error("maxEventsPerChunk must be positive");if(r<1024)throw new Error("maxChunkBytes is too small")}storage;maxEventsPerChunk;maxChunkBytes;async getJson(t){let n=await this.storage.getText(t);return n?JSON.parse(n):null}async putJson(t,n){await this.storage.put(t,JSON.stringify(n,null,2)+`
19
19
  `,"application/json")}async scan(t){let n=`${t.remotePrefix}/events/`,r=await this.storage.list(n),o=[],s=0;for(let i of r){let a=i.key.match(/\/events\/(\d+)-(\d+)-[a-f0-9]+\.jsonl$/);if(!a)continue;let c=Number(a[1]),u=Number(a[2]);!Number.isFinite(c)||!Number.isFinite(u)||(o.push({key:i.key,start:c,end:u}),s=Math.max(s,u))}return o.sort((i,a)=>i.start-a.start),{chunks:o,maxSequence:s}}split(t){let n=[],r=[],o=0;for(let s of t){let i=Buffer.byteLength(JSON.stringify(s)+`
20
- `,"utf8");r.length>0&&(r.length>=this.maxEventsPerChunk||o+i>this.maxChunkBytes)&&(n.push(r),r=[],o=0),r.push(s),o+=i}return r.length>0&&n.push(r),n}async loadManifest(t){return this.getJson(`${t.remotePrefix}/session.json`)}async loadCursor(t){return this.getJson(`${t.remotePrefix}/cursor.json`)}async recover(t){let n=await this.scan(t);return{maxSequence:n.maxSequence,chunkCount:n.chunks.length}}async append(t,n,r,o={}){let s=await this.loadManifest(t),i=await this.scan(t),a=n.filter(y=>y.sequence>i.maxSequence),c=0;for(let y of this.split(a)){let h=y[0],k=y[y.length-1],M=y.map(O=>JSON.stringify(O)).join(`
20
+ `,"utf8");r.length>0&&(r.length>=this.maxEventsPerChunk||o+i>this.maxChunkBytes)&&(n.push(r),r=[],o=0),r.push(s),o+=i}return r.length>0&&n.push(r),n}async loadManifest(t){return this.getJson(`${t.remotePrefix}/session.json`)}async loadCursor(t){return this.getJson(`${t.remotePrefix}/cursor.json`)}async recover(t){let n=await this.scan(t);return{maxSequence:n.maxSequence,chunkCount:n.chunks.length}}async append(t,n,r,o={}){let s=await this.loadManifest(t),i=await this.scan(t),a=n.filter(g=>g.sequence>i.maxSequence),c=0;for(let g of this.split(a)){let h=g[0],v=g[g.length-1],j=g.map(T=>JSON.stringify(T)).join(`
21
21
  `)+`
22
- `,E=v(M).slice(0,16),C=[t.remotePrefix,"events",`${Zn(h.sequence)}-${Zn(k.sequence)}-${E}.jsonl`].join("/");await this.storage.exists(C)||await this.storage.put(C,M,"application/x-ndjson"),c+=y.length}let u=await this.scan(t),d=n[n.length-1],l=s?.status??"active";d?.type==="session_end"||d?.type==="session_idle"?l="idle":d?.type==="error"?l="error":n.length>0&&(l="active");let f=new Date().toISOString(),p=n[0],g={version:1,projectId:t.projectId,projectName:t.projectName,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,status:l,createdAt:s?.createdAt??p?.timestamp??f,updatedAt:d?.timestamp??f,firstEventAt:s?.firstEventAt??p?.timestamp,lastEventAt:d?.timestamp??s?.lastEventAt,eventCount:u.maxSequence,chunkCount:u.chunks.length,metadata:{...s?.metadata,...o.metadata}};(o.title??s?.title)&&(g.title=o.title??s?.title);let S={version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,lastLocalSequence:n.length>0?n[n.length-1].sequence:u.maxSequence,lastRemoteSequence:u.maxSequence,sourceCursors:r,updatedAt:f};return await this.putJson(`${t.remotePrefix}/cursor.json`,S),await this.putJson(`${t.remotePrefix}/session.json`,g),{uploadedEvents:c,lastRemoteSequence:u.maxSequence,eventCount:g.eventCount,chunkCount:g.chunkCount,status:l}}};import{closeSync as ke,existsSync as Qe,fsyncSync as Ft,mkdirSync as ua,openSync as ve,readFileSync as mr,readSync as la,rmSync as dr,statSync as $t,truncateSync as da,writeSync as pa}from"node:fs";import{join as Lt}from"node:path";var Bi=new Set(["thinking","reasoning","reasoningcontent","chainofthought","cot","analysistext","internalreasoning","modelthinking"]),Gi=new Set(["reasoning","thinking","chain_of_thought","chain-of-thought","internal_reasoning","internal-reasoning"]);function Ui(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Yi(e){for(let t of["type","kind"]){let n=e[t];if(typeof n=="string"){let r=n.toLowerCase();if(Gi.has(r))return n}}return null}function Tt(e,t=0){if(t>12)return"[ToolNet nested value omitted]";if(Array.isArray(e))return e.map(s=>Tt(s,t+1));if(!e||typeof e!="object")return e;let n=e,r=Yi(n);if(r)return{type:r,omitted:"[private reasoning omitted]"};let o={};for(let[s,i]of Object.entries(n))Bi.has(Ui(s))||(o[s]=Tt(i,t+1));return o}function Xi(e){if(!e)return new Date().toISOString();let t=new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function Y(e){return e?.trim()||void 0}function er(e,t={}){let n={...e.provenance??{}},r=Y(e.source)??Y(t.source)??Y(n.source);return{...e,timestamp:Xi(e.timestamp),source:r,turnId:Y(e.turnId)??Y(t.turnId),cwd:Y(e.cwd)??Y(t.cwd),data:Tt(e.data??{}),provenance:n}}import{randomUUID as Rt}from"node:crypto";import{closeSync as re,existsSync as oe,fsyncSync as he,mkdirSync as Nt,openSync as Se,readFileSync as _t,readdirSync as Qi,renameSync as Zi,rmSync as Ge,statSync as ea,writeSync as Ue}from"node:fs";import{join as J}from"node:path";var ta=12e4,na=80,ra="reconcile-required";function oa(e){e<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function se(e){return J(e,".toolnet","journal")}function rr(e){return J(se(e),"events.jsonl")}function Ye(e){return J(se(e),ra)}function sa(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code!=="ESRCH"}}function or(e){if(!oe(e))return null;try{let t=JSON.parse(_t(e,"utf8"));return t.version!==1||typeof t.token!="string"||typeof t.pid!="number"||typeof t.acquiredAt!="string"?null:{version:1,token:t.token,pid:t.pid,acquiredAt:t.acquiredAt}}catch{return null}}function ia(e){if(!oe(e))return!1;let t=0;try{t=Date.now()-ea(e).mtimeMs}catch{return!1}if(t<=ta)return!1;let n=or(e);return n?!sa(n.pid):!0}function aa(e){if(!ia(e))return!1;try{return Ge(e,{force:!0}),!0}catch{return!1}}function sr(e){for(let t=0;t<na;t+=1){let n=Rt();try{let r=Se(e,"wx",384),o={version:1,token:n,pid:process.pid,acquiredAt:new Date().toISOString()};try{return Ue(r,`${JSON.stringify(o)}
23
- `,null,"utf8"),he(r),{fd:r,token:n}}catch(s){throw re(r),Ge(e,{force:!0}),s}}catch(r){if(r?.code!=="EEXIST")throw r;if(aa(e))continue;oa(25)}}throw new Error(`Shared project journal is locked: ${e}`)}function ir(e,t){re(t.fd),or(e)?.token===t.token&&Ge(e,{force:!0})}function tr(e){if(!oe(e))return[];let t="";try{t=_t(e,"utf8")}catch{return[]}let n=[];for(let r of t.split(/\r?\n/)){let o=r.trim();if(o)try{let s=JSON.parse(o);if(s.version!==1||typeof s.id!="string"||s.id.length===0||typeof s.projectId!="string"||s.projectId.length===0)continue;n.push(s)}catch{}}return n}function ar(e){if(!oe(e))return[];let t=[];for(let n of Qi(e,{withFileTypes:!0})){let r=J(e,n.name);if(n.isDirectory()){t.push(...ar(r));continue}n.isFile()&&n.name==="events.jsonl"&&t.push(r)}return t.sort()}function Xe(e){let t=null;try{t=Se(e,"r"),he(t)}catch{}finally{if(t===null)return;re(t)}}function nr(e){let t=Ye(e);if(!oe(t))return null;try{return _t(t,"utf8").trim()||null}catch{return null}}function Kt(e){let t=se(e);Nt(t,{recursive:!0,mode:448});let n=Ye(e),r=[Rt(),new Date().toISOString()].join("|"),o=Se(n,"w",384);try{Ue(o,`${r}
24
- `,null,"utf8"),he(o)}finally{re(o)}Xe(t)}function ca(e,t,n){let r=J(e,`.events.jsonl.tmp-${process.pid}-${Rt()}`),o=Se(r,"w",384);try{let s=n.length===0?"":`${n.map(i=>JSON.stringify(i)).join(`
22
+ `,O=w(j).slice(0,16),C=[t.remotePrefix,"events",`${vr(h.sequence)}-${vr(v.sequence)}-${O}.jsonl`].join("/");await this.storage.exists(C)||await this.storage.put(C,j,"application/x-ndjson"),c+=g.length}let u=await this.scan(t),l=n[n.length-1],d=s?.status??"active";l?.type==="session_end"||l?.type==="session_idle"?d="idle":l?.type==="error"?d="error":n.length>0&&(d="active");let p=new Date().toISOString(),f=n[0],m={version:1,projectId:t.projectId,projectName:t.projectName,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,status:d,createdAt:s?.createdAt??f?.timestamp??p,updatedAt:l?.timestamp??p,firstEventAt:s?.firstEventAt??f?.timestamp,lastEventAt:l?.timestamp??s?.lastEventAt,eventCount:u.maxSequence,chunkCount:u.chunks.length,metadata:{...s?.metadata,...o.metadata}};(o.title??s?.title)&&(m.title=o.title??s?.title);let S={version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,lastLocalSequence:n.length>0?n[n.length-1].sequence:u.maxSequence,lastRemoteSequence:u.maxSequence,sourceCursors:r,updatedAt:p};return await this.putJson(`${t.remotePrefix}/cursor.json`,S),await this.putJson(`${t.remotePrefix}/session.json`,m),{uploadedEvents:c,lastRemoteSequence:u.maxSequence,eventCount:m.eventCount,chunkCount:m.chunkCount,status:d}}};import{closeSync as je,existsSync as ut,fsyncSync as Xt,mkdirSync as Ha,openSync as Ie,readFileSync as _r,readSync as Ja,rmSync as Tr,statSync as Ut,truncateSync as Va,writeSync as Ba}from"node:fs";import{join as Yt}from"node:path";var Ma=new Set(["thinking","reasoning","reasoningcontent","chainofthought","cot","analysistext","internalreasoning","modelthinking"]),Ca=new Set(["reasoning","thinking","chain_of_thought","chain-of-thought","internal_reasoning","internal-reasoning"]);function Ea(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Oa(e){for(let t of["type","kind"]){let n=e[t];if(typeof n=="string"){let r=n.toLowerCase();if(Ca.has(r))return n}}return null}function Ht(e,t=0){if(t>12)return"[ToolNet nested value omitted]";if(Array.isArray(e))return e.map(s=>Ht(s,t+1));if(!e||typeof e!="object")return e;let n=e,r=Oa(n);if(r)return{type:r,omitted:"[private reasoning omitted]"};let o={};for(let[s,i]of Object.entries(n))Ma.has(Ea(s))||(o[s]=Ht(i,t+1));return o}function Ta(e){if(!e)return new Date().toISOString();let t=new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function Q(e){return e?.trim()||void 0}function wr(e,t={}){let n={...e.provenance??{}},r=Q(e.source)??Q(t.source)??Q(n.source);return{...e,timestamp:Ta(e.timestamp),source:r,turnId:Q(e.turnId)??Q(t.turnId),cwd:Q(e.cwd)??Q(t.cwd),data:Ht(e.data??{}),provenance:n}}import{randomUUID as Jt}from"node:crypto";import{closeSync as ae,existsSync as ce,fsyncSync as be,mkdirSync as Vt,openSync as xe,readFileSync as Bt,readdirSync as Ra,renameSync as Na,rmSync as st,statSync as _a,writeSync as it}from"node:fs";import{join as B}from"node:path";var Ka=12e4,$a=80,La="reconcile-required";function Fa(e){e<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function ue(e){return B(e,".toolnet","journal")}function jr(e){return B(ue(e),"events.jsonl")}function at(e){return B(ue(e),La)}function Da(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code!=="ESRCH"}}function Ir(e){if(!ce(e))return null;try{let t=JSON.parse(Bt(e,"utf8"));return t.version!==1||typeof t.token!="string"||typeof t.pid!="number"||typeof t.acquiredAt!="string"?null:{version:1,token:t.token,pid:t.pid,acquiredAt:t.acquiredAt}}catch{return null}}function Wa(e){if(!ce(e))return!1;let t=0;try{t=Date.now()-_a(e).mtimeMs}catch{return!1}if(t<=Ka)return!1;let n=Ir(e);return n?!Da(n.pid):!0}function za(e){if(!Wa(e))return!1;try{return st(e,{force:!0}),!0}catch{return!1}}function Ar(e){for(let t=0;t<$a;t+=1){let n=Jt();try{let r=xe(e,"wx",384),o={version:1,token:n,pid:process.pid,acquiredAt:new Date().toISOString()};try{return it(r,`${JSON.stringify(o)}
23
+ `,null,"utf8"),be(r),{fd:r,token:n}}catch(s){throw ae(r),st(e,{force:!0}),s}}catch(r){if(r?.code!=="EEXIST")throw r;if(za(e))continue;Fa(25)}}throw new Error(`Shared project journal is locked: ${e}`)}function Pr(e,t){ae(t.fd),Ir(e)?.token===t.token&&st(e,{force:!0})}function br(e){if(!ce(e))return[];let t="";try{t=Bt(e,"utf8")}catch{return[]}let n=[];for(let r of t.split(/\r?\n/)){let o=r.trim();if(o)try{let s=JSON.parse(o);if(s.version!==1||typeof s.id!="string"||s.id.length===0||typeof s.projectId!="string"||s.projectId.length===0)continue;n.push(s)}catch{}}return n}function Mr(e){if(!ce(e))return[];let t=[];for(let n of Ra(e,{withFileTypes:!0})){let r=B(e,n.name);if(n.isDirectory()){t.push(...Mr(r));continue}n.isFile()&&n.name==="events.jsonl"&&t.push(r)}return t.sort()}function ct(e){let t=null;try{t=xe(e,"r"),be(t)}catch{}finally{if(t===null)return;ae(t)}}function xr(e){let t=at(e);if(!ce(t))return null;try{return Bt(t,"utf8").trim()||null}catch{return null}}function Gt(e){let t=ue(e);Vt(t,{recursive:!0,mode:448});let n=at(e),r=[Jt(),new Date().toISOString()].join("|"),o=xe(n,"w",384);try{it(o,`${r}
24
+ `,null,"utf8"),be(o)}finally{ae(o)}ct(t)}function qa(e,t,n){let r=B(e,`.events.jsonl.tmp-${process.pid}-${Jt()}`),o=xe(r,"w",384);try{let s=n.length===0?"":`${n.map(i=>JSON.stringify(i)).join(`
25
25
  `)}
26
- `;s&&Ue(o,s,null,"utf8"),he(o)}finally{re(o)}Zi(r,t),Xe(e)}function cr(e){let t=se(e),n=rr(e),r=J(e,".toolnet","runtime","sources"),o=nr(e),s=ar(r),i=[],a=new Set;for(let l of tr(n))a.has(l.id)||(a.add(l.id),i.push(l));let c=i.length,u=[];for(let l of s)for(let f of tr(l))a.has(f.id)||(a.add(f.id),u.push(f));u.sort((l,f)=>{let p=l.timestamp.localeCompare(f.timestamp);return p!==0?p:l.id.localeCompare(f.id)}),i.push(...u),ca(t,n,i);let d=nr(e);return o&&d===o&&(Ge(Ye(e),{force:!0}),Xe(t)),{filesScanned:s.length,existingEvents:c,recoveredEvents:u.length,totalEvents:i.length}}function ur(e){let t=se(e);Nt(t,{recursive:!0,mode:448});let n=J(t,"journal.lock"),r=sr(n);try{return cr(e)}finally{ir(n,r)}}function lr(e,t){if(t.length===0)return;let n=se(e);Nt(n,{recursive:!0,mode:448});let r=rr(e),o=J(n,"journal.lock"),s=sr(o);try{if(oe(Ye(e))){cr(e);return}let i=`${t.map(c=>JSON.stringify(c)).join(`
26
+ `;s&&it(o,s,null,"utf8"),be(o)}finally{ae(o)}Na(r,t),ct(e)}function Cr(e){let t=ue(e),n=jr(e),r=B(e,".toolnet","runtime","sources"),o=xr(e),s=Mr(r),i=[],a=new Set;for(let d of br(n))a.has(d.id)||(a.add(d.id),i.push(d));let c=i.length,u=[];for(let d of s)for(let p of br(d))a.has(p.id)||(a.add(p.id),u.push(p));u.sort((d,p)=>{let f=d.timestamp.localeCompare(p.timestamp);return f!==0?f:d.id.localeCompare(p.id)}),i.push(...u),qa(t,n,i);let l=xr(e);return o&&l===o&&(st(at(e),{force:!0}),ct(t)),{filesScanned:s.length,existingEvents:c,recoveredEvents:u.length,totalEvents:i.length}}function Er(e){let t=ue(e);Vt(t,{recursive:!0,mode:448});let n=B(t,"journal.lock"),r=Ar(n);try{return Cr(e)}finally{Pr(n,r)}}function Or(e,t){if(t.length===0)return;let n=ue(e);Vt(n,{recursive:!0,mode:448});let r=jr(e),o=B(n,"journal.lock"),s=Ar(o);try{if(ce(at(e))){Cr(e);return}let i=`${t.map(c=>JSON.stringify(c)).join(`
27
27
  `)}
28
- `,a=Se(r,"a",384);try{Ue(a,i,null,"utf8"),he(a)}finally{re(a)}Xe(n)}finally{ir(o,s)}}var fa=12e4,ma=80,pr=2e3;function ga(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function gr(e,t){let n=Buffer.isBuffer(t)?t:Buffer.from(t,"utf8"),r=0;for(;r<n.length;){let o=pa(e,n,r,n.length-r);if(o<=0)throw new Error("Unable to write session WAL");r+=o}}function Wt(e){let t=e.trim();if(!t)return null;try{let n=JSON.parse(t);return n.version!==1||typeof n.id!="string"||!n.id||typeof n.sequence!="number"||!Number.isFinite(n.sequence)||typeof n.projectId!="string"||!n.projectId||typeof n.timestamp!="string"?null:n}catch{return null}}function ya(e){if(!Qe(e))return[];let t="";try{t=mr(e,"utf8")}catch{return[]}let n=[];for(let r of t.split(/\r?\n/)){let o=Wt(r);o&&n.push(o)}return n}function fr(e){return e.type==="session_end"||e.type==="session_idle"?"idle":e.type==="error"?"error":"active"}function ha(e){if(!Qe(e))return!1;let t;try{t=mr(e)}catch{return!1}if(t.length===0||t[t.length-1]===10)return!1;let n=t.lastIndexOf(10),r=n>=0?n+1:0,o=t.subarray(r).toString("utf8").trim();if(Wt(o)){let i=ve(e,"a");try{gr(i,`
29
- `),Ft(i)}finally{ke(i)}return!0}da(e,r);let s=ve(e,"a");try{Ft(s)}finally{ke(s)}return!0}function Sa(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}var ie=class{constructor(t,n={}){this.identity=t;this.eventContext=n;ua(t.localDirectory,{recursive:!0}),this.eventsFile=Lt(t.localDirectory,"events.jsonl"),this.stateFile=Lt(t.localDirectory,"state.json"),this.lockFile=Lt(t.localDirectory,"journal.lock")}identity;eventContext;eventsFile;stateFile;lockFile;initialState(){let t=new Date().toISOString();return{version:1,projectId:this.identity.projectId,agent:this.identity.agent,nativeSessionId:this.identity.nativeSessionId,status:"idle",createdAt:t,updatedAt:t,lastSequence:0,lastRemoteSequence:0,remoteByteOffset:0,sourceCursors:{},recentEventIds:[]}}loadStateUnsafe(){return wn(this.stateFile)??this.initialState()}recoverStateUnsafe(){ha(this.eventsFile);let t=this.loadStateUnsafe(),n=ya(this.eventsFile);if(n.length===0)return t;let r=n[0];for(let l of n)l.sequence<=r.sequence||(r=l);let o=n.slice(-pr).map(l=>l.id),s=Qe(this.eventsFile)?$t(this.eventsFile).size:0,i=Math.max(t.lastSequence,r.sequence),a=Math.min(t.remoteByteOffset,s),c=r.sequence>t.lastSequence;if(!(c||a!==t.remoteByteOffset||!Sa(t.recentEventIds,o)||t.lastLocalEventAt!==r.timestamp))return t;let d={...t,status:fr(r),updatedAt:r.timestamp,lastLocalEventAt:r.timestamp,lastSequence:i,remoteByteOffset:a,recentEventIds:o};if(this.saveStateUnsafe(d),!c)return d;try{Kt(this.identity.projectRoot)}catch{return d}try{ur(this.identity.projectRoot)}catch{}return d}loadState(){return this.withLock(()=>this.recoverStateUnsafe())}saveStateUnsafe(t){T(this.stateFile,t)}acquireLock(){for(let t=0;t<ma;t+=1)try{return ve(this.lockFile,"wx",384)}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-$t(this.lockFile).mtimeMs>fa){dr(this.lockFile,{force:!0});continue}}catch{}ga(25)}throw new Error(`Session journal is locked: ${this.lockFile}`)}withLock(t){let n=this.acquireLock();try{return t()}finally{ke(n),dr(this.lockFile,{force:!0})}}append(t){return t.length===0?[]:this.withLock(()=>{let n=this.recoverStateUnsafe(),r=new Set(n.recentEventIds),o=n.lastSequence,s=[];for(let l of t){let f=er(l,this.eventContext),p=f.timestamp??new Date().toISOString(),g=f.data??{},S=f.provenance?.rawDigest??v(Ke(g)),y=f.sourceEventId?[this.identity.projectId,this.identity.agent,this.identity.nativeSessionId,f.sourceEventId].join("|"):[this.identity.projectId,this.identity.agent,this.identity.nativeSessionId,o+1,f.type,p,S].join("|"),h=v(y).slice(0,32);if(r.has(h))continue;o+=1;let k={version:1,id:h,sequence:o,projectId:this.identity.projectId,agent:this.identity.agent,nativeSessionId:this.identity.nativeSessionId,sessionId:this.identity.nativeSessionId,type:f.type,timestamp:p,source:f.source??f.provenance?.source??this.identity.agent,data:g,provenance:{...f.provenance,rawDigest:S}};f.role!==void 0&&(k.role=f.role),f.turnId!==void 0&&(k.turnId=f.turnId),f.cwd!==void 0&&(k.cwd=f.cwd),f.sourceEventId!==void 0&&(k.sourceEventId=f.sourceEventId),f.sourceSequence!==void 0&&(k.sourceSequence=f.sourceSequence),s.push(k),r.add(h)}if(s.length===0)return[];let i=s.map(l=>JSON.stringify(l)).join(`
28
+ `,a=xe(r,"a",384);try{it(a,i,null,"utf8"),be(a)}finally{ae(a)}ct(n)}finally{Pr(o,s)}}var Ga=12e4,Ua=80,Rr=2e3;function Ya(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Kr(e,t){let n=Buffer.isBuffer(t)?t:Buffer.from(t,"utf8"),r=0;for(;r<n.length;){let o=Ba(e,n,r,n.length-r);if(o<=0)throw new Error("Unable to write session WAL");r+=o}}function Zt(e){let t=e.trim();if(!t)return null;try{let n=JSON.parse(t);return n.version!==1||typeof n.id!="string"||!n.id||typeof n.sequence!="number"||!Number.isFinite(n.sequence)||typeof n.projectId!="string"||!n.projectId||typeof n.timestamp!="string"?null:n}catch{return null}}function Xa(e){if(!ut(e))return[];let t="";try{t=_r(e,"utf8")}catch{return[]}let n=[];for(let r of t.split(/\r?\n/)){let o=Zt(r);o&&n.push(o)}return n}function Nr(e){return e.type==="session_end"||e.type==="session_idle"?"idle":e.type==="error"?"error":"active"}function Za(e){if(!ut(e))return!1;let t;try{t=_r(e)}catch{return!1}if(t.length===0||t[t.length-1]===10)return!1;let n=t.lastIndexOf(10),r=n>=0?n+1:0,o=t.subarray(r).toString("utf8").trim();if(Zt(o)){let i=Ie(e,"a");try{Kr(i,`
29
+ `),Xt(i)}finally{je(i)}return!0}Va(e,r);let s=Ie(e,"a");try{Xt(s)}finally{je(s)}return!0}function Qa(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}var le=class{constructor(t,n={}){this.identity=t;this.eventContext=n;Ha(t.localDirectory,{recursive:!0}),this.eventsFile=Yt(t.localDirectory,"events.jsonl"),this.stateFile=Yt(t.localDirectory,"state.json"),this.lockFile=Yt(t.localDirectory,"journal.lock")}identity;eventContext;eventsFile;stateFile;lockFile;initialState(){let t=new Date().toISOString();return{version:1,projectId:this.identity.projectId,agent:this.identity.agent,nativeSessionId:this.identity.nativeSessionId,status:"idle",createdAt:t,updatedAt:t,lastSequence:0,lastRemoteSequence:0,remoteByteOffset:0,sourceCursors:{},recentEventIds:[]}}loadStateUnsafe(){return Nn(this.stateFile)??this.initialState()}recoverStateUnsafe(){Za(this.eventsFile);let t=this.loadStateUnsafe(),n=Xa(this.eventsFile);if(n.length===0)return t;let r=n[0];for(let d of n)d.sequence<=r.sequence||(r=d);let o=n.slice(-Rr).map(d=>d.id),s=ut(this.eventsFile)?Ut(this.eventsFile).size:0,i=Math.max(t.lastSequence,r.sequence),a=Math.min(t.remoteByteOffset,s),c=r.sequence>t.lastSequence;if(!(c||a!==t.remoteByteOffset||!Qa(t.recentEventIds,o)||t.lastLocalEventAt!==r.timestamp))return t;let l={...t,status:Nr(r),updatedAt:r.timestamp,lastLocalEventAt:r.timestamp,lastSequence:i,remoteByteOffset:a,recentEventIds:o};if(this.saveStateUnsafe(l),!c)return l;try{Gt(this.identity.projectRoot)}catch{return l}try{Er(this.identity.projectRoot)}catch{}return l}loadState(){return this.withLock(()=>this.recoverStateUnsafe())}saveStateUnsafe(t){R(this.stateFile,t)}acquireLock(){for(let t=0;t<Ua;t+=1)try{return Ie(this.lockFile,"wx",384)}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Ut(this.lockFile).mtimeMs>Ga){Tr(this.lockFile,{force:!0});continue}}catch{}Ya(25)}throw new Error(`Session journal is locked: ${this.lockFile}`)}withLock(t){let n=this.acquireLock();try{return t()}finally{je(n),Tr(this.lockFile,{force:!0})}}append(t){return t.length===0?[]:this.withLock(()=>{let n=this.recoverStateUnsafe(),r=new Set(n.recentEventIds),o=n.lastSequence,s=[];for(let d of t){let p=wr(d,this.eventContext),f=p.timestamp??new Date().toISOString(),m=p.data??{},S=p.provenance?.rawDigest??w(Je(m)),g=ke(m),h=p.sourceEventId?[this.identity.projectId,this.identity.agent,this.identity.nativeSessionId,p.sourceEventId].join("|"):[this.identity.projectId,this.identity.agent,this.identity.nativeSessionId,o+1,p.type,f,S].join("|"),v=w(h).slice(0,32);if(r.has(v))continue;o+=1;let j={version:1,id:v,sequence:o,projectId:this.identity.projectId,agent:this.identity.agent,nativeSessionId:this.identity.nativeSessionId,sessionId:this.identity.nativeSessionId,type:p.type,timestamp:f,source:p.source??p.provenance?.source??this.identity.agent,data:g,provenance:{...p.provenance,rawDigest:S}};p.role!==void 0&&(j.role=p.role),p.turnId!==void 0&&(j.turnId=p.turnId),p.cwd!==void 0&&(j.cwd=p.cwd),p.sourceEventId!==void 0&&(j.sourceEventId=p.sourceEventId),p.sourceSequence!==void 0&&(j.sourceSequence=p.sourceSequence),s.push(j),r.add(v)}if(s.length===0)return[];let i=s.map(d=>JSON.stringify(d)).join(`
30
30
  `)+`
31
- `,a=ve(this.eventsFile,"a",384);try{gr(a,i),Ft(a)}finally{ke(a)}try{lr(this.identity.projectRoot,s)}catch{try{Kt(this.identity.projectRoot)}catch{}}let c=s[s.length-1],u=fr(c),d=Array.from(r).slice(-pr);return this.saveStateUnsafe({...n,status:u,updatedAt:c.timestamp,lastLocalEventAt:c.timestamp,lastSequence:c.sequence,recentEventIds:d}),s})}readPending(){return this.withLock(()=>{let t=this.recoverStateUnsafe();if(!Qe(this.eventsFile))return{events:[],startOffset:t.remoteByteOffset,endOffset:t.remoteByteOffset};let n=$t(this.eventsFile).size,r=Math.min(t.remoteByteOffset,n);if(n<=r)return{events:[],startOffset:r,endOffset:n};let o=n-r,s=Buffer.alloc(o),i=ve(this.eventsFile,"r");try{la(i,s,0,o,r)}finally{ke(i)}let a=[];for(let c of s.toString("utf8").split(/\r?\n/)){let u=Wt(c);u&&a.push(u)}return{events:a,startOffset:r,endOffset:n}})}markRemote(t,n){this.withLock(()=>{let r=this.recoverStateUnsafe(),o=new Date().toISOString();this.saveStateUnsafe({...r,lastRemoteSequence:Math.max(r.lastRemoteSequence,t),remoteByteOffset:Math.max(r.remoteByteOffset,n),lastRemoteAt:o,updatedAt:o})})}setSourceCursor(t,n){this.withLock(()=>{let r=this.recoverStateUnsafe();this.saveStateUnsafe({...r,sourceCursors:{...r.sourceCursors,[t]:String(n)},updatedAt:new Date().toISOString()})})}};import{closeSync as Gc,existsSync as Uc,openSync as Yc,readSync as Xc,statSync as Qc}from"node:fs";var ka=new Set(["rule","blocker","architecture","deploy"]),va=new Set(["fix","todo","context","next_action"]);function Dt(e){return e<0?0:e>1?1:e}function yr(e,t){let n=Number.parseFloat(e??"");return Number.isFinite(n)?n:t}function wa(e){return e==="off"?"off":e==="balanced"?"balanced":e==="aggressive"?"aggressive":"conservative"}function zt(){return{mode:wa(process.env.TOOLNET_MEMORY_PROMOTION),minScore:Dt(yr(process.env.TOOLNET_PROMOTE_MIN_SCORE,.65)),minConfidence:Dt(yr(process.env.TOOLNET_PROMOTE_MIN_CONFIDENCE,.78))}}function ba(e){switch(e){case"critical":return 1;case"high":return .85;case"normal":return .6;case"temporary":return .25}}function xa(e){let t=Dt(ba(e.importance)*.75+e.confidence*.25);return Math.round(t*1e6)/1e6}function ja(e){return e.evidence?e.evidence:{userExplicit:!1,sourceVerified:!1,testVerified:!1,crossSessionConfirmations:0,assistantDerived:!1}}function Ia(e,t=zt()){if(e.importance==="temporary"||e.confidence<t.minConfidence)return"transient";let n=ja(e);return e.kind==="rule"&&n.userExplicit?"permanent":e.kind==="rule"?"session":e.kind==="architecture"&&(n.userExplicit||n.sourceVerified||n.testVerified||n.crossSessionConfirmations>=2)?"permanent":e.kind==="architecture"?"session":e.kind==="decision"||e.kind==="todo"||e.kind==="fix"?"task":"session"}function Aa(e,t=zt()){if(t.mode==="off")return Number.POSITIVE_INFINITY;let n=0;t.mode==="balanced"&&(n=.1),t.mode==="aggressive"&&(n=.15);let r=Math.max(t.mode==="aggressive"?.5:.55,t.minScore-n);return ka.has(e)&&(r=Math.max(.5,r-.1)),va.has(e)&&(r=Math.max(.5,r-.05)),r}function qt(e,t=zt()){let n=Ia(e,t),r=xa(e),o=Aa(e.kind,t);return n==="transient"?{knowledgeClass:n,score:r,threshold:o,persist:!1}:t.mode==="off"?{knowledgeClass:n,score:r,threshold:o,persist:!1}:{knowledgeClass:n,score:r,threshold:o,persist:r>=o}}function hr(e,t){let n=t.toLowerCase();return n.includes("kh\xF4ng \u0111\u01B0\u1EE3c")||n.includes("tuy\u1EC7t \u0111\u1ED1i")||n.includes("must not")||n.includes("never ")?"critical":e==="rule"||e==="decision"?"high":e==="todo"||n.includes("error")||n.includes("failed")||n.includes("exception")?"normal":"temporary"}var wr=[/không được/iu,/tuyệt đối/iu,/bắt buộc/iu,/đừng\s+/iu,/must not/iu,/do not/iu,/don't/iu,/\bnever\b/iu],Pa=[/từ giờ/iu,/về sau/iu,/mỗi lần/iu,/luôn luôn/iu,/\bluôn\b/iu,/quy tắc/iu,/workflow/iu,/\balways\b/iu,/\brequired\b/iu,/\bmust\b/iu,/from now on/iu],Ca=[/\bchốt\b/iu,/quyết định/iu,/sẽ dùng/iu,/chọn .+ thay/iu,/đổi sang/iu,/chuyển sang/iu,/\bdecided\b/iu,/\bchosen\b/iu,/we will use/iu,/use .+ instead/iu,/switch(?:ed)? to/iu],Ma=[/\btodo\b/iu,/cần làm/iu,/cần thêm/iu,/cần sửa/iu,/cần kiểm tra/iu,/tiếp theo/iu,/bước tiếp theo/iu,/còn phải/iu,/còn cần/iu,/next step/iu,/\bneed to\b/iu,/\bremaining\b/iu,/follow[- ]?up/iu],Ea=[/đã sửa/iu,/đã fix/iu,/đã khắc phục/iu,/đã xử lý/iu,/hoàn tất/iu,/hoàn thành/iu,/\bfixed\b/iu,/\bresolved\b/iu,/\bimplemented\b/iu,/\bcompleted\b/iu,/\bpasses?\b/iu],Sr=[/kiến trúc/iu,/pipeline/iu,/adapter/iu,/schema/iu,/runtime/iu,/namespace/iu,/storage/iu,/lưu trữ/iu,/workflow/iu,/session core/iu,/memory engine/iu,/retrieval/iu],Oa=[/\bdùng\b/iu,/\btách\b/iu,/\bthay\b/iu,/\bchuyển\b/iu,/\blưu\b/iu,/\bmap\b/iu,/\buse\b/iu,/\bsplit\b/iu,/\bstore\b/iu,/\breplace\b/iu,/\bmove\b/iu],Ta=[/đường dẫn/iu,/\bpath\b/iu,/\bport\b/iu,/\bendpoint\b/iu,/\bdomain\b/iu,/\bbucket\b/iu,/\brepository\b/iu,/\brepo\b/iu,/\bbranch\b/iu,/\/[A-Za-z0-9._/-]{4,}/u],Ra=[/\blà\b/iu,/\bở\b/iu,/\bdùng\b/iu,/\bnằm\b/iu,/\bis\b/iu,/\buse\b/iu,/located/iu,/runs on/iu],kr=new Set(["content","text","message","prompt","summary","description","reason","title","last_assistant_message","lastAssistantMessage","input_messages","inputMessages"]),Na=new Set(["payload","data","content","message","messages","parts","summary"]);function R(e,t){return t.some(n=>n.test(e))}function br(e){return e.normalize("NFKC").replace(/\r/g,"").replace(/^[\s>*#\-•]+/u,"").replace(/\s+/g," ").trim()}function _a(e){return br(e).toLowerCase().replace(/[^\p{L}\p{N}:/._-]+/gu," ").replace(/\s+/g," ").trim()}function Ka(e){return!(e.length<12||e.length>1e3||(e.match(new RegExp("\\p{L}","gu"))??[]).length<6||/^(?:https?:\/\/\S+|[A-Za-z0-9+/=]{80,})$/u.test(e))}function Ht(e,t,n,r=0){if(!(r>6)&&!(typeof e=="string"&&t&&!kr.has(t))){if(typeof e=="string"){n.push(e);return}if(Array.isArray(e)){for(let o of e.slice(0,50))Ht(o,t,n,r+1);return}if(!(!e||typeof e!="object"))for(let[o,s]of Object.entries(e))(kr.has(o)||Na.has(o))&&Ht(s,o,n,r+1)}}function $a(e){let t=[];Ht(e.data,void 0,t);let n=[],r=new Set;for(let o of t)for(let s of o.split(/\n+|(?<=[.!?])\s+/u)){let i=br(s);if(Ka(i)&&!r.has(i)&&(r.add(i),n.push(i),n.length>=50))return n}return n}function vr(e){return(e.role??(typeof e.data.role=="string"?e.data.role:"")).toLowerCase()}function La(e,t,n){if(n.type==="decision")return{kind:"decision",confidence:1};if(n.type==="todo")return{kind:"todo",confidence:1};let r=t==="user"||n.type==="user_prompt",o=t==="assistant"||n.type==="assistant_message";return r&&R(e,wr)?{kind:"rule",confidence:.98}:r&&R(e,Pa)?{kind:"rule",confidence:.92}:R(e,Ca)?{kind:R(e,Sr)?"architecture":"decision",confidence:r?.93:.86}:r&&R(e,Ma)?{kind:"todo",confidence:.87}:R(e,Sr)&&R(e,Oa)?{kind:"architecture",confidence:r?.88:.82}:o&&R(e,Ea)?{kind:"fix",confidence:.8}:r&&R(e,Ta)&&R(e,Ra)?{kind:"context",confidence:.79}:null}function Fa(e,t,n){let r=t==="user"||n.type==="user_prompt",o=t==="assistant"||n.type==="assistant_message",s=!!n.provenance.sourcePath&&(e==="architecture"||e==="context"||e==="fix"),i=e==="fix"&&/(?:test|tests|pass|passed|passing)/iu.test(JSON.stringify(n.data));return{userExplicit:r,sourceVerified:s,testVerified:i,crossSessionConfirmations:1,assistantDerived:o}}function Wa(e){switch(e){case"rule":return"rule";case"decision":case"architecture":return"decision";case"todo":return"todo";case"fix":case"context":return"code"}}function Da(e,t,n){return e==="rule"&&R(n,wr)?"critical":e==="architecture"||e==="decision"||e==="rule"?"high":e==="fix"||e==="context"?"normal":hr(t,n)}function xr(e,t){let n=[],r=new Set,o=new Map;for(let s of t){let i=typeof s.data.messageId=="string"?s.data.messageId:void 0,a=vr(s);i&&a&&o.set(i,a)}for(let s of t){let i=vr(s),a=typeof s.data.messageId=="string"?s.data.messageId:void 0;!i&&a&&(i=o.get(a)??"");for(let c of $a(s)){let u=La(c,i,s);if(!u||u.confidence<.75)continue;let d=Wa(u.kind),l=_a(c),f=v([e.projectId,u.kind,l].join("|"));if(r.has(f))continue;r.add(f);let p=s.provenance.sourcePath?[s.provenance.sourcePath]:[],g=s.sourceEventId?[s.sourceEventId]:[];n.push({version:1,fingerprint:f,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,kind:u.kind,type:d,content:c,confidence:u.confidence,importance:Da(u.kind,d,c),evidence:Fa(u.kind,i,s),tags:[d],provenance:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,eventIds:[s.id],sourceEventIds:g,sourcePaths:p,firstSequence:s.sequence,lastSequence:s.sequence},createdAt:s.timestamp})}}return n}import{createHash as za}from"node:crypto";var qa=["project-knowledge","implementation","continuation","session-context"],Ha={"project-knowledge":"Project knowledge",implementation:"Implementation state",continuation:"Work continuation","session-context":"Session context"};function Jt(e){return za("sha256").update(e).digest("hex")}function Ze(e,t){return`${e}:${Jt(t).slice(0,24)}`}function Ja(e){try{return Jt(JSON.stringify(e))}catch{return Jt(String(e))}}function X(e){let t=new Set,n=[];for(let r of e){let o=r?.replace(/\s+/gu," ").trim();if(!o)continue;let s=o.normalize("NFKC").toLowerCase();t.has(s)||(t.add(s),n.push(o))}return n}function Ir(e,t=420){let n=e.replace(/\s+/gu," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function Va(e){return e==="rule"||e==="architecture"?"project-knowledge":e==="decision"||e==="fix"?"implementation":e==="todo"?"continuation":"session-context"}function jr(e){return e.length===0?0:e.reduce((t,n)=>t+n,0)/e.length}function Ba(e){return e.slice().sort((t,n)=>n.importanceScore-t.importanceScore||n.confidence-t.confidence||t.id.localeCompare(n.id)).slice(0,5).map(t=>Ir(t.content)).join(" | ")}function Ga(e){return e.slice().sort((t,n)=>n.importanceScore-t.importanceScore||n.confidence-t.confidence||t.id.localeCompare(n.id)).slice(0,6).map(t=>Ir(t.content)).join(`
32
- `)}function Ar(e,t){let n=e.slice().sort((f,p)=>f.sequence-p.sequence||f.timestamp.localeCompare(p.timestamp)||f.id.localeCompare(p.id)),r=n.map(f=>({id:Ze("raw",[f.projectId,f.agent,f.nativeSessionId,f.id,String(f.sequence)].join("|")),level:"raw",eventId:f.id,sourceEventId:f.sourceEventId,sequence:f.sequence,type:f.type,role:f.role,timestamp:f.timestamp,sourcePath:f.provenance.sourcePath,payloadDigest:Ja(f.data)})),o=new Map,s=new Map;n.forEach((f,p)=>{let g=r[p];g&&(o.set(f.id,g.id),f.sourceEventId&&s.set(f.sourceEventId,g.id))});let i=t.map(f=>{let p=X([...f.provenance.eventIds.map(g=>o.get(g)),...f.provenance.sourceEventIds.map(g=>s.get(g))]);return{id:Ze("fact",f.fingerprint),level:"fact",fingerprint:f.fingerprint,kind:f.kind,type:f.type,content:f.content,knowledgeClass:f.knowledgeClass,importanceScore:f.importanceScore,confidence:f.confidence,tags:X([...f.tags,"level:fact",`class:${f.knowledgeClass}`,`kind:${f.kind}`]),rawIds:p,sourcePaths:X(f.provenance.sourcePaths)}}),a=new Map;for(let f of i){let p=Va(f.kind),g=a.get(p)??[];g.push(f),a.set(p,g)}let c=[];for(let f of qa){let p=a.get(f);if(!p?.length)continue;let g=p.slice().sort((y,h)=>h.importanceScore-y.importanceScore||h.confidence-y.confidence||y.id.localeCompare(h.id)),S=g.map(y=>y.id);c.push({id:Ze("scene",`${f}|${S.join("|")}`),level:"scene",kind:f,title:Ha[f],summary:Ba(g),factIds:S,importanceScore:Math.max(...g.map(y=>y.importanceScore)),confidence:jr(g.map(y=>y.confidence)),tags:X(["level:scene",`scene:${f}`,...g.flatMap(y=>y.tags)]),sourcePaths:X(g.flatMap(y=>y.sourcePaths))})}let u=new Map(i.map(f=>[f.id,f])),d=[];for(let f of c){let g=f.factIds.map(h=>u.get(h)).filter(h=>!!h).filter(h=>(h.knowledgeClass==="permanent"||h.knowledgeClass==="task")&&h.importanceScore>=.55);if(g.length===0)continue;let S=g.some(h=>h.knowledgeClass==="permanent")?"permanent":"task",y=Ga(g);d.push({id:Ze("knowledge",`${f.id}|${S}|${g.map(h=>h.id).join("|")}`),level:"knowledge",knowledgeClass:S,title:f.title,content:y,sceneIds:[f.id],factIds:g.map(h=>h.id),importanceScore:Math.max(...g.map(h=>h.importanceScore)),confidence:jr(g.map(h=>h.confidence)),tags:X(["level:knowledge",`class:${S}`,`scene:${f.kind}`,...g.flatMap(h=>h.tags)]),sourcePaths:X(g.flatMap(h=>h.sourcePaths))})}let l=[];for(let f of i)for(let p of f.rawIds)l.push({from:p,to:f.id,type:"supports"});for(let f of c)for(let p of f.factIds)l.push({from:p,to:f.id,type:"belongs_to"});for(let f of d)for(let p of f.sceneIds)l.push({from:p,to:f.id,type:"promotes_to"});return{schema:"toolnet.memory-hierarchy.v1",version:1,raw:r,facts:i,scenes:c,knowledge:d,links:l,stats:{raw:r.length,facts:i.length,scenes:c.length,knowledge:d.length,links:l.length}}}function we(){let e=Le(),t=process.env.TOOLNET_SESSION_SAVE||"summary",n=process.env.TOOLNET_RAW_TRANSCRIPT==="on"||t==="archive"||t==="full",r=process.env.TOOLNET_MEMORY_PROMOTION||"conservative",o=parseFloat(process.env.TOOLNET_PROMOTE_MIN_SCORE||"0.65"),s=parseInt(process.env.TOOLNET_SESSION_SUMMARY_MAX_TOKENS||"700",10),i=parseInt(process.env.TOOLNET_DURABLE_MEMORY_MAX_ITEMS_PER_SESSION||"10",10),a=n,c=process.env.TOOLNET_RAW_TRANSCRIPT_REMOTE==="on"||t==="full";return{sessionSave:t,rawTranscript:n,memoryPromotion:r,promoteMinScore:o,sessionSummaryMaxTokens:s,durableMemoryMaxItemsPerSession:i,archiveLocal:a,archiveRemote:c}}function Pr(e){return(e||we()).durableMemoryMaxItemsPerSession}function Cr(e){return(e||we()).sessionSummaryMaxTokens}var Mr=new U;function Er(e){let t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{let r=JSON.parse(t);return JSON.stringify(Mr.sanitizeValue(r))}catch{}let n=Mr.sanitize(e).text;return n=n.replace(/("(?:api[_-]?key|token|secret|password|cookie|authorization)"\s*:\s*)"[^"]*"/gi,'$1"[REDACTED]"').replace(/('(?:api[_-]?key|token|secret|password|cookie|authorization)'\s*:\s*)'[^']*'/gi,"$1'[REDACTED]'").replace(/\b(api[_-]?key|token|secret|password|cookie|authorization)\b\s*[:=]\s*[^\s,;]+/gi,"$1=[REDACTED]").replace(/\bbearer\s+[A-Za-z0-9._~+/=-]+/gi,"Bearer [REDACTED]"),n}function Ua(e,t){let n=e.toLowerCase(),r=.5,o=["nh\u1EDB","remember","quy t\u1EAFc","rule","t\u1EEB gi\u1EDD","from now","kh\xF4ng \u0111\u01B0\u1EE3c","must not","lu\xF4n lu\xF4n","always","never","critical","important","blocker","deploy","production","architecture"];for(let i of o)n.includes(i)&&(r+=.15);t==="rule"||t==="architecture"||t==="blocker"?r+=.2:t==="decision"||t==="deploy"?r+=.15:(t==="fix"||t==="next_action")&&(r+=.1),e.length<20?r-=.3:e.length>500&&(r-=.1);let s=[/npm (notice|warn|ERR)/i,/\d+ packages? in \d+/i,/found \d+ vulnerabilities/i,/up to date/i,/added \d+ packages/i,/^(ok|done|success|error|warning)$/i];for(let i of s)i.test(e)&&(r-=.4);return Math.max(0,Math.min(1,r))}function Ya(e,t){let n=[],r=new Set;for(let i of e){let a=i.split(`
33
- `).filter(c=>c.trim());for(let c of a){let u=c.trim();if(u.length<15)continue;let d=u.toLowerCase().replace(/\s+/g," ");if(r.has(d))continue;r.add(d);let l="decision";/\b(rule|quy tắc|policy|standard|convention)\b/i.test(u)||/\b(always|never|must|should|từ giờ|không được)\b/i.test(u)?l="rule":/\b(fix|fixed|bug|issue|error|lỗi)\b/i.test(u)?l="fix":/\b(blocker|blocked|stuck|cannot|không thể)\b/i.test(u)?l="blocker":/\b(next|todo|action|task|cần làm)\b/i.test(u)?l="next_action":/\b(deploy|release|publish|ship)\b/i.test(u)?l="deploy":/\b(architecture|design|structure|pattern)\b/i.test(u)?l="architecture":/\.(ts|js|py|go|rs|java|cpp|c|h)\b/i.test(u)&&(l="file");let f=Ua(u,l);if(f<.3)continue;let p=Er(u);n.push({category:l,text:p,importance:f,sourceSessionId:t})}}let o=we(),s=Pr(o);return n.sort((i,a)=>a.importance-i.importance).slice(0,s)}function Xa(e){let t=we(),n=Cr(t),s=e.join(`
31
+ `,a=Ie(this.eventsFile,"a",384);try{Kr(a,i),Xt(a)}finally{je(a)}try{Or(this.identity.projectRoot,s)}catch{try{Gt(this.identity.projectRoot)}catch{}}let c=s[s.length-1],u=Nr(c),l=Array.from(r).slice(-Rr);return this.saveStateUnsafe({...n,status:u,updatedAt:c.timestamp,lastLocalEventAt:c.timestamp,lastSequence:c.sequence,recentEventIds:l}),s})}readPending(){return this.withLock(()=>{let t=this.recoverStateUnsafe();if(!ut(this.eventsFile))return{events:[],startOffset:t.remoteByteOffset,endOffset:t.remoteByteOffset};let n=Ut(this.eventsFile).size,r=Math.min(t.remoteByteOffset,n);if(n<=r)return{events:[],startOffset:r,endOffset:n};let o=n-r,s=Buffer.alloc(o),i=Ie(this.eventsFile,"r");try{Ja(i,s,0,o,r)}finally{je(i)}let a=[];for(let c of s.toString("utf8").split(/\r?\n/)){let u=Zt(c);u&&a.push(u)}return{events:a,startOffset:r,endOffset:n}})}markRemote(t,n){this.withLock(()=>{let r=this.recoverStateUnsafe(),o=new Date().toISOString();this.saveStateUnsafe({...r,lastRemoteSequence:Math.max(r.lastRemoteSequence,t),remoteByteOffset:Math.max(r.remoteByteOffset,n),lastRemoteAt:o,updatedAt:o})})}setSourceCursor(t,n){this.withLock(()=>{let r=this.recoverStateUnsafe();this.saveStateUnsafe({...r,sourceCursors:{...r.sourceCursors,[t]:String(n)},updatedAt:new Date().toISOString()})})}};import{closeSync as Eu,existsSync as Ou,openSync as Tu,readSync as Ru,statSync as Nu}from"node:fs";var ec=new Set(["rule","blocker","architecture","deploy"]),tc=new Set(["fix","todo","context","next_action"]);function Qt(e){return e<0?0:e>1?1:e}function $r(e,t){let n=Number.parseFloat(e??"");return Number.isFinite(n)?n:t}function nc(e){return e==="off"?"off":e==="balanced"?"balanced":e==="aggressive"?"aggressive":"conservative"}function en(){return{mode:nc(process.env.TOOLNET_MEMORY_PROMOTION),minScore:Qt($r(process.env.TOOLNET_PROMOTE_MIN_SCORE,.65)),minConfidence:Qt($r(process.env.TOOLNET_PROMOTE_MIN_CONFIDENCE,.78))}}function rc(e){switch(e){case"critical":return 1;case"high":return .85;case"normal":return .6;case"temporary":return .25}}function oc(e){let t=Qt(rc(e.importance)*.75+e.confidence*.25);return Math.round(t*1e6)/1e6}function sc(e){return e.evidence?e.evidence:{userExplicit:!1,sourceVerified:!1,testVerified:!1,crossSessionConfirmations:0,assistantDerived:!1}}function ic(e,t=en()){if(e.importance==="temporary"||e.confidence<t.minConfidence)return"transient";let n=sc(e);return e.kind==="rule"&&n.userExplicit?"permanent":e.kind==="rule"?"session":e.kind==="architecture"&&(n.userExplicit||n.sourceVerified||n.testVerified||n.crossSessionConfirmations>=2)?"permanent":e.kind==="architecture"?"session":e.kind==="decision"||e.kind==="todo"||e.kind==="next_action"||e.kind==="fix"?"task":"session"}function ac(e,t=en()){if(t.mode==="off")return Number.POSITIVE_INFINITY;let n=0;t.mode==="balanced"&&(n=.1),t.mode==="aggressive"&&(n=.15);let r=Math.max(t.mode==="aggressive"?.5:.55,t.minScore-n);return ec.has(e)&&(r=Math.max(.5,r-.1)),tc.has(e)&&(r=Math.max(.5,r-.05)),r}function tn(e,t=en()){let n=ic(e,t),r=oc(e),o=ac(e.kind,t);return n==="transient"?{knowledgeClass:n,score:r,threshold:o,persist:!1}:t.mode==="off"?{knowledgeClass:n,score:r,threshold:o,persist:!1}:{knowledgeClass:n,score:r,threshold:o,persist:r>=o}}function Lr(e,t){let n=t.toLowerCase();return n.includes("kh\xF4ng \u0111\u01B0\u1EE3c")||n.includes("tuy\u1EC7t \u0111\u1ED1i")||n.includes("must not")||n.includes("never ")?"critical":e==="rule"||e==="decision"?"high":e==="todo"||n.includes("error")||n.includes("failed")||n.includes("exception")?"normal":"temporary"}var zr=[/không được/iu,/tuyệt đối/iu,/bắt buộc/iu,/đừng\s+/iu,/must not/iu,/do not/iu,/don't/iu,/\bnever\b/iu],cc=[/từ giờ/iu,/về sau/iu,/mỗi lần/iu,/luôn luôn/iu,/\bluôn\b/iu,/quy tắc/iu,/workflow/iu,/\balways\b/iu,/\brequired\b/iu,/\bmust\b/iu,/from now on/iu],uc=[/\bchốt\b/iu,/quyết định/iu,/sẽ dùng/iu,/chọn .+ thay/iu,/đổi sang/iu,/chuyển sang/iu,/\bdecided\b/iu,/\bchosen\b/iu,/we will use/iu,/use .+ instead/iu,/switch(?:ed)? to/iu],lc=[/\btodo\b/iu,/cần làm/iu,/cần thêm/iu,/cần sửa/iu,/cần kiểm tra/iu,/tiếp theo/iu,/bước tiếp theo/iu,/còn phải/iu,/còn cần/iu,/next step/iu,/\bneed to\b/iu,/\bremaining\b/iu,/follow[- ]?up/iu],dc=[/tiếp theo/iu,/bước tiếp theo/iu,/việc tiếp theo/iu,/sau đó cần/iu,/next step/iu,/next action/iu,/follow[- ]?up/iu],pc=[/đã sửa/iu,/đã fix/iu,/đã khắc phục/iu,/đã xử lý/iu,/hoàn tất/iu,/hoàn thành/iu,/\bfixed\b/iu,/\bresolved\b/iu,/\bimplemented\b/iu,/\bcompleted\b/iu,/\bpasses?\b/iu],Fr=[/kiến trúc/iu,/pipeline/iu,/adapter/iu,/schema/iu,/runtime/iu,/namespace/iu,/storage/iu,/lưu trữ/iu,/workflow/iu,/session core/iu,/memory engine/iu,/retrieval/iu],fc=[/\bdùng\b/iu,/\btách\b/iu,/\bthay\b/iu,/\bchuyển\b/iu,/\blưu\b/iu,/\bmap\b/iu,/\buse\b/iu,/\bsplit\b/iu,/\bstore\b/iu,/\breplace\b/iu,/\bmove\b/iu],mc=[/đường dẫn/iu,/\bpath\b/iu,/\bport\b/iu,/\bendpoint\b/iu,/\bdomain\b/iu,/\bbucket\b/iu,/\brepository\b/iu,/\brepo\b/iu,/\bbranch\b/iu,/\/[A-Za-z0-9._/-]{4,}/u],gc=[/\blà\b/iu,/\bở\b/iu,/\bdùng\b/iu,/\bnằm\b/iu,/\bis\b/iu,/\buse\b/iu,/located/iu,/runs on/iu],Dr=new Set(["content","text","message","prompt","summary","description","reason","title","last_assistant_message","lastAssistantMessage","input_messages","inputMessages"]),yc=new Set(["payload","data","content","message","messages","parts","summary"]);function N(e,t){return t.some(n=>n.test(e))}function qr(e){return e.normalize("NFKC").replace(/\r/g,"").replace(/^[\s>*#\-•]+/u,"").replace(/\s+/g," ").trim()}function hc(e){return qr(e).toLowerCase().replace(/[^\p{L}\p{N}:/._-]+/gu," ").replace(/\s+/g," ").trim()}function Sc(e){return!(e.length<12||e.length>1e3||(e.match(new RegExp("\\p{L}","gu"))??[]).length<6||/^(?:https?:\/\/\S+|[A-Za-z0-9+/=]{80,})$/u.test(e))}function nn(e,t,n,r=0){if(!(r>6)&&!(typeof e=="string"&&t&&!Dr.has(t))){if(typeof e=="string"){n.push(e);return}if(Array.isArray(e)){for(let o of e.slice(0,50))nn(o,t,n,r+1);return}if(!(!e||typeof e!="object"))for(let[o,s]of Object.entries(e))(Dr.has(o)||yc.has(o))&&nn(s,o,n,r+1)}}function kc(e){let t=[];nn(e.data,void 0,t);let n=[],r=new Set;for(let o of t)for(let s of o.split(/\n+|(?<=[.!?])\s+/u)){let i=qr(s);if(Sc(i)&&!r.has(i)&&(r.add(i),n.push(i),n.length>=50))return n}return n}function Wr(e){return(e.role??(typeof e.data.role=="string"?e.data.role:"")).toLowerCase()}function vc(e,t,n){if(n.type==="decision")return{kind:"decision",confidence:1};if(n.type==="todo")return{kind:"todo",confidence:1};let r=t==="user"||n.type==="user_prompt",o=t==="assistant"||n.type==="assistant_message";return r&&N(e,zr)?{kind:"rule",confidence:.98}:r&&N(e,cc)?{kind:"rule",confidence:.92}:N(e,uc)?{kind:N(e,Fr)?"architecture":"decision",confidence:r?.93:.86}:r&&N(e,dc)?{kind:"next_action",confidence:.88}:r&&N(e,lc)?{kind:"todo",confidence:.87}:N(e,Fr)&&N(e,fc)?{kind:"architecture",confidence:r?.88:.82}:o&&N(e,pc)?{kind:"fix",confidence:.8}:r&&N(e,mc)&&N(e,gc)?{kind:"context",confidence:.79}:null}function wc(e,t,n){let r=t==="user"||n.type==="user_prompt",o=t==="assistant"||n.type==="assistant_message",s=!!n.provenance.sourcePath&&(e==="architecture"||e==="context"||e==="fix"),i=e==="fix"&&/(?:test|tests|pass|passed|passing)/iu.test(JSON.stringify(n.data));return{userExplicit:r,sourceVerified:s,testVerified:i,crossSessionConfirmations:1,assistantDerived:o}}function bc(e){switch(e){case"rule":return"rule";case"decision":case"architecture":return"decision";case"todo":case"next_action":return"todo";case"fix":case"context":return"code"}}function xc(e,t,n){return e==="rule"&&N(n,zr)?"critical":e==="architecture"||e==="decision"||e==="rule"?"high":e==="fix"||e==="context"?"normal":Lr(t,n)}function Hr(e,t){let n=[],r=new Set,o=new Map;for(let s of t){let i=typeof s.data.messageId=="string"?s.data.messageId:void 0,a=Wr(s);i&&a&&o.set(i,a)}for(let s of t){let i=Wr(s),a=typeof s.data.messageId=="string"?s.data.messageId:void 0;!i&&a&&(i=o.get(a)??"");for(let c of kc(s)){let u=vc(c,i,s);if(!u||u.confidence<.75)continue;let l=bc(u.kind),d=hc(c),p=w([e.projectId,u.kind,d].join("|"));if(r.has(p))continue;r.add(p);let f=s.provenance.sourcePath?[s.provenance.sourcePath]:[],m=s.sourceEventId?[s.sourceEventId]:[];n.push({version:1,fingerprint:p,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,kind:u.kind,type:l,content:c,confidence:u.confidence,importance:xc(u.kind,l,c),evidence:wc(u.kind,i,s),tags:[l],provenance:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,eventIds:[s.id],sourceEventIds:m,sourcePaths:f,firstSequence:s.sequence,lastSequence:s.sequence},createdAt:s.timestamp})}}return n}import{createHash as jc}from"node:crypto";var Ic=["project-knowledge","implementation","continuation","session-context"],Ac={"project-knowledge":"Project knowledge",implementation:"Implementation state",continuation:"Work continuation","session-context":"Session context"};function rn(e){return jc("sha256").update(e).digest("hex")}function lt(e,t){return`${e}:${rn(t).slice(0,24)}`}function Pc(e){try{return rn(JSON.stringify(e))}catch{return rn(String(e))}}function ee(e){let t=new Set,n=[];for(let r of e){let o=r?.replace(/\s+/gu," ").trim();if(!o)continue;let s=o.normalize("NFKC").toLowerCase();t.has(s)||(t.add(s),n.push(o))}return n}function Vr(e,t=420){let n=e.replace(/\s+/gu," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function Mc(e){return e==="rule"||e==="architecture"?"project-knowledge":e==="decision"||e==="fix"?"implementation":e==="todo"?"continuation":"session-context"}function Jr(e){return e.length===0?0:e.reduce((t,n)=>t+n,0)/e.length}function Cc(e){return e.slice().sort((t,n)=>n.importanceScore-t.importanceScore||n.confidence-t.confidence||t.id.localeCompare(n.id)).slice(0,5).map(t=>Vr(t.content)).join(" | ")}function Ec(e){return e.slice().sort((t,n)=>n.importanceScore-t.importanceScore||n.confidence-t.confidence||t.id.localeCompare(n.id)).slice(0,6).map(t=>Vr(t.content)).join(`
32
+ `)}function Br(e,t){let n=e.slice().sort((p,f)=>p.sequence-f.sequence||p.timestamp.localeCompare(f.timestamp)||p.id.localeCompare(f.id)),r=n.map(p=>({id:lt("raw",[p.projectId,p.agent,p.nativeSessionId,p.id,String(p.sequence)].join("|")),level:"raw",eventId:p.id,sourceEventId:p.sourceEventId,sequence:p.sequence,type:p.type,role:p.role,timestamp:p.timestamp,sourcePath:p.provenance.sourcePath,payloadDigest:Pc(p.data)})),o=new Map,s=new Map;n.forEach((p,f)=>{let m=r[f];m&&(o.set(p.id,m.id),p.sourceEventId&&s.set(p.sourceEventId,m.id))});let i=t.map(p=>{let f=ee([...p.provenance.eventIds.map(m=>o.get(m)),...p.provenance.sourceEventIds.map(m=>s.get(m))]);return{id:lt("fact",p.fingerprint),level:"fact",fingerprint:p.fingerprint,kind:p.kind,type:p.type,content:p.content,knowledgeClass:p.knowledgeClass,importanceScore:p.importanceScore,confidence:p.confidence,tags:ee([...p.tags,"level:fact",`class:${p.knowledgeClass}`,`kind:${p.kind}`]),rawIds:f,sourcePaths:ee(p.provenance.sourcePaths)}}),a=new Map;for(let p of i){let f=Mc(p.kind),m=a.get(f)??[];m.push(p),a.set(f,m)}let c=[];for(let p of Ic){let f=a.get(p);if(!f?.length)continue;let m=f.slice().sort((g,h)=>h.importanceScore-g.importanceScore||h.confidence-g.confidence||g.id.localeCompare(h.id)),S=m.map(g=>g.id);c.push({id:lt("scene",`${p}|${S.join("|")}`),level:"scene",kind:p,title:Ac[p],summary:Cc(m),factIds:S,importanceScore:Math.max(...m.map(g=>g.importanceScore)),confidence:Jr(m.map(g=>g.confidence)),tags:ee(["level:scene",`scene:${p}`,...m.flatMap(g=>g.tags)]),sourcePaths:ee(m.flatMap(g=>g.sourcePaths))})}let u=new Map(i.map(p=>[p.id,p])),l=[];for(let p of c){let m=p.factIds.map(h=>u.get(h)).filter(h=>!!h).filter(h=>(h.knowledgeClass==="permanent"||h.knowledgeClass==="task")&&h.importanceScore>=.55);if(m.length===0)continue;let S=m.some(h=>h.knowledgeClass==="permanent")?"permanent":"task",g=Ec(m);l.push({id:lt("knowledge",`${p.id}|${S}|${m.map(h=>h.id).join("|")}`),level:"knowledge",knowledgeClass:S,title:p.title,content:g,sceneIds:[p.id],factIds:m.map(h=>h.id),importanceScore:Math.max(...m.map(h=>h.importanceScore)),confidence:Jr(m.map(h=>h.confidence)),tags:ee(["level:knowledge",`class:${S}`,`scene:${p.kind}`,...m.flatMap(h=>h.tags)]),sourcePaths:ee(m.flatMap(h=>h.sourcePaths))})}let d=[];for(let p of i)for(let f of p.rawIds)d.push({from:f,to:p.id,type:"supports"});for(let p of c)for(let f of p.factIds)d.push({from:f,to:p.id,type:"belongs_to"});for(let p of l)for(let f of p.sceneIds)d.push({from:f,to:p.id,type:"promotes_to"});return{schema:"toolnet.memory-hierarchy.v1",version:1,raw:r,facts:i,scenes:c,knowledge:l,links:d,stats:{raw:r.length,facts:i.length,scenes:c.length,knowledge:l.length,links:d.length}}}function Ae(){let e=Be(),t=process.env.TOOLNET_SESSION_SAVE||"summary",n=process.env.TOOLNET_RAW_TRANSCRIPT==="on"||t==="archive"||t==="full",r=process.env.TOOLNET_MEMORY_PROMOTION||"conservative",o=parseFloat(process.env.TOOLNET_PROMOTE_MIN_SCORE||"0.65"),s=parseInt(process.env.TOOLNET_SESSION_SUMMARY_MAX_TOKENS||"700",10),i=parseInt(process.env.TOOLNET_DURABLE_MEMORY_MAX_ITEMS_PER_SESSION||"10",10),a=n,c=process.env.TOOLNET_RAW_TRANSCRIPT_REMOTE==="on"||t==="full";return{sessionSave:t,rawTranscript:n,memoryPromotion:r,promoteMinScore:o,sessionSummaryMaxTokens:s,durableMemoryMaxItemsPerSession:i,archiveLocal:a,archiveRemote:c}}function Gr(e){return(e||Ae()).durableMemoryMaxItemsPerSession}function Ur(e){return(e||Ae()).sessionSummaryMaxTokens}var Yr=new V;function Xr(e){let t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{let r=JSON.parse(t);return JSON.stringify(Yr.sanitizeValue(r))}catch{}let n=Yr.sanitize(e).text;return n=n.replace(/("(?:api[_-]?key|token|secret|password|cookie|authorization)"\s*:\s*)"[^"]*"/gi,'$1"[REDACTED]"').replace(/('(?:api[_-]?key|token|secret|password|cookie|authorization)'\s*:\s*)'[^']*'/gi,"$1'[REDACTED]'").replace(/\b(api[_-]?key|token|secret|password|cookie|authorization)\b\s*[:=]\s*[^\s,;]+/gi,"$1=[REDACTED]").replace(/\bbearer\s+[A-Za-z0-9._~+/=-]+/gi,"Bearer [REDACTED]"),n}function Oc(e,t){let n=e.toLowerCase(),r=.5,o=["nh\u1EDB","remember","quy t\u1EAFc","rule","t\u1EEB gi\u1EDD","from now","kh\xF4ng \u0111\u01B0\u1EE3c","must not","lu\xF4n lu\xF4n","always","never","critical","important","blocker","deploy","production","architecture"];for(let i of o)n.includes(i)&&(r+=.15);t==="rule"||t==="architecture"||t==="blocker"?r+=.2:t==="decision"||t==="deploy"?r+=.15:(t==="fix"||t==="next_action")&&(r+=.1),e.length<20?r-=.3:e.length>500&&(r-=.1);let s=[/npm (notice|warn|ERR)/i,/\d+ packages? in \d+/i,/found \d+ vulnerabilities/i,/up to date/i,/added \d+ packages/i,/^(ok|done|success|error|warning)$/i];for(let i of s)i.test(e)&&(r-=.4);return Math.max(0,Math.min(1,r))}function Tc(e,t){let n=[],r=new Set;for(let i of e){let a=i.split(`
33
+ `).filter(c=>c.trim());for(let c of a){let u=c.trim();if(u.length<15)continue;let l=u.toLowerCase().replace(/\s+/g," ");if(r.has(l))continue;r.add(l);let d="decision";/\b(rule|quy tắc|policy|standard|convention)\b/i.test(u)||/\b(always|never|must|should|từ giờ|không được)\b/i.test(u)?d="rule":/\b(fix|fixed|bug|issue|error|lỗi)\b/i.test(u)?d="fix":/\b(blocker|blocked|stuck|cannot|không thể)\b/i.test(u)?d="blocker":/\b(next|todo|action|task|cần làm)\b/i.test(u)?d="next_action":/\b(deploy|release|publish|ship)\b/i.test(u)?d="deploy":/\b(architecture|design|structure|pattern)\b/i.test(u)?d="architecture":/\.(ts|js|py|go|rs|java|cpp|c|h)\b/i.test(u)&&(d="file");let p=Oc(u,d);if(p<.3)continue;let f=Xr(u);n.push({category:d,text:f,importance:p,sourceSessionId:t})}}let o=Ae(),s=Gr(o);return n.sort((i,a)=>a.importance-i.importance).slice(0,s)}function Rc(e){let t=Ae(),n=Ur(t),s=e.join(`
34
34
 
35
35
  `).split(`
36
- `).filter(i=>{let a=i.trim();return a.length>20&&!a.startsWith("npm")&&!a.startsWith("\u2713")&&!a.startsWith("Error:")}).slice(0,20).map(i=>Er(i)).join(`
37
- `);return fn(s,n)}function Or(e,t){let r=(Array.isArray(e)?e:e.split(`
38
-
39
- `).filter(p=>p.trim())).map(p=>typeof p=="string"?p:JSON.stringify(p)).filter(p=>p.trim()),o=Ya(r,t),s=o.filter(p=>p.category==="decision").map(p=>p.text),i=o.filter(p=>p.category==="rule").map(p=>p.text),a=o.filter(p=>p.category==="file").map(p=>p.text),c=o.filter(p=>p.category==="fix").map(p=>p.text),u=o.filter(p=>p.category==="blocker").map(p=>p.text),d=o.filter(p=>p.category==="next_action").map(p=>p.text),l=o.filter(p=>p.category==="deploy").map(p=>p.text);return{summary:Xa(r),decisions:s,projectRules:i,filesChanged:a,bugsFixed:c,commands:l,blockers:u,nextActions:d,durableFacts:o}}function V(e){let t=new Set,n=[];for(let r of e){let o=r?.replace(/\s+/g," ").trim();if(!o)continue;let s=o.normalize("NFKC").toLowerCase();t.has(s)||(t.add(s),n.push(o))}return n}function Qa(e){let t=new Map;for(let n of e){if(!n||!n.id||!Number.isFinite(n.sequence))continue;let r=n.sourceEventId?`${n.agent}:${n.sourceEventId}`:n.id,o=t.get(r);(!o||n.sequence>o.sequence)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.sequence-r.sequence||n.timestamp.localeCompare(r.timestamp))}function Za(e){let t=e.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_./:-]+/gu)??[],n=new Set;for(let r of t)if(!(r.length<2||/^\d+$/u.test(r))&&(n.add(r),n.size>=40))break;return[...n]}function ec(e){let t=qt(e);return{...e,knowledgeClass:t.knowledgeClass,importanceScore:t.score,retrievalTerms:Za(e.content),tags:V([...e.tags,"level:fact",`class:${t.knowledgeClass}`,`kind:${e.kind}`])}}function tc(e){return e.map(t=>{try{return JSON.stringify({type:t.type,role:t.role,data:t.data,provenance:{sourcePath:t.provenance.sourcePath,files:t.provenance.files}})}catch{return""}}).filter(Boolean)}function nc(e,t,n){let r=Or(tc(t),e.nativeSessionId),o=n.filter(u=>u.kind==="todo").map(u=>u.content),s=n.flatMap(u=>u.provenance.sourcePaths),i=n.filter(u=>u.kind==="architecture").map(u=>u.content),a=V([...o,...r.nextActions]),c=V([...r.nextActions,...o]);return{summary:r.summary,state:{task:c[0]??a[0],decisions:V(r.decisions),files:V([...r.filesChanged,...s]),todos:a,completed:V(r.bugsFixed),blockers:V(r.blockers),nextActions:c,architecture:V(i)}}}function et(e,t){let n=Qa(t),r=xr(e,n).map(ec),o=r.filter(d=>qt(d).persist).sort((d,l)=>l.importanceScore-d.importanceScore),{summary:s,state:i}=nc(e,n,o),a=o.map(d=>({fingerprint:d.fingerprint,kind:d.kind,knowledgeClass:d.knowledgeClass,importanceScore:d.importanceScore,content:d.content,terms:d.retrievalTerms})),c=Ar(n,o),u=d=>r.filter(l=>l.knowledgeClass===d).length;return{version:2,normalizedEvents:n,summary:s,state:i,candidates:o,retrievalIndex:a,hierarchy:c,stats:{inputEvents:t.length,normalizedEvents:n.length,extractedCandidates:r.length,persistedCandidates:o.length,permanent:u("permanent"),task:u("task"),session:u("session"),transient:u("transient")}}}import{createHash as lc}from"node:crypto";import{existsSync as dc,readdirSync as pc,readFileSync as fc}from"node:fs";import{basename as mc,join as Gr}from"node:path";import{randomUUID as Nr}from"node:crypto";var j=class extends Error{constructor(n,r){super(n);this.statusCode=r}statusCode};function be(e){let t=new Set,n=[];for(let r of e){let o=r.replace(/\s+/gu," ").trim();if(!o)continue;let s=o.normalize("NFKC").toLowerCase();t.has(s)||(t.add(s),n.push(o))}return n}function Z(e){let t=e.normalize("NFKD").replace(/[\u0300-\u036f]/gu,"").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"").slice(0,120);if(!t)throw new j("Invalid Wiki slug",400);return t}function Tr(e){let t=[];for(let n of e.matchAll(/\[\[([^\[\]]+)\]\]/gu)){let r=n[1]?.trim();r&&t.push(Z(r))}return be(t)}function rc(e){return e.normalize("NFKC").toLowerCase().split(/[^\p{L}\p{N}_-]+/u).map(t=>t.trim()).filter(t=>t.length>=2)}function Rr(e){return{id:`revision-${Nr()}`,pageId:e.id,slug:e.slug,revision:e.revision,title:e.title,...e.summary?{summary:e.summary}:{},content:e.content,tags:[...e.tags],links:[...e.links],createdAt:e.updatedAt}}function Q(e){return structuredClone(e)}var tt=class{constructor(t){this.store=t}store;state;queue=Promise.resolve();async initialize(){await this.ensureState()}async ensureState(){return this.state||(this.state=await this.store.load()),this.state}async mutate(t){let n,r=this.queue.then(async()=>{let o=await this.ensureState();n=t(o),o.updatedAt=new Date().toISOString(),await this.store.save(o)});return this.queue=r.then(()=>{},()=>{}),await r,n}async summary(){let t=await this.ensureState(),n=new Set(t.pages.flatMap(r=>r.links));return{schema:"toolnet.wiki-summary.v1",projectId:t.projectId,pages:t.pages.length,revisions:t.revisions.length,tags:be(t.pages.flatMap(r=>r.tags)).sort((r,o)=>r.localeCompare(o)),links:t.pages.reduce((r,o)=>r+o.links.length,0),orphanPages:t.pages.filter(r=>r.links.length===0&&!n.has(r.slug)).length,automatedPages:t.pages.filter(r=>r.tags.some(o=>o.startsWith("toolnet-auto-"))).length,updatedAt:t.updatedAt}}async listPages(){let t=await this.ensureState();return Q([...t.pages].sort((n,r)=>n.title.localeCompare(r.title)))}async getPage(t){let n=await this.ensureState(),r=Z(t),o=n.pages.find(s=>s.slug===r||s.id===t);if(!o)throw new j(`Wiki page not found: ${t}`,404);return Q(o)}async createPage(t){return this.mutate(n=>{let r=t.title.trim(),o=t.content.trim();if(!r)throw new j("Wiki title is required",400);let s=Z(t.slug??r);if(n.pages.some(c=>c.slug===s))throw new j(`Wiki page already exists: ${s}`,409);let i=new Date().toISOString(),a={id:`wiki-${Nr()}`,slug:s,title:r,...t.summary?.trim()?{summary:t.summary.trim()}:{},content:o,tags:be(t.tags??[]),links:Tr(o),revision:1,createdAt:i,updatedAt:i};return n.pages.push(a),n.revisions.push(Rr(a)),Q(a)})}async updatePage(t,n){return this.mutate(r=>{let o=Z(t),s=r.pages.find(i=>i.slug===o||i.id===t);if(!s)throw new j(`Wiki page not found: ${t}`,404);if(n.title!==void 0){let i=n.title.trim();if(!i)throw new j("Wiki title is required",400);s.title=i}if(n.summary!==void 0){let i=n.summary.trim();i?s.summary=i:delete s.summary}return n.content!==void 0&&(s.content=n.content.trim(),s.links=Tr(s.content)),n.tags!==void 0&&(s.tags=be(n.tags)),s.revision+=1,s.updatedAt=new Date().toISOString(),r.revisions.push(Rr(s)),Q(s)})}async history(t){let n=await this.getPage(t),r=await this.ensureState();return Q(r.revisions.filter(o=>o.pageId===n.id).sort((o,s)=>s.revision-o.revision))}async backlinks(t){let n=await this.getPage(t),r=await this.ensureState();return Q(r.pages.filter(o=>o.links.includes(n.slug)).sort((o,s)=>o.title.localeCompare(s.title)))}async search(t,n=10){let r=await this.ensureState(),o=be(rc(t));if(o.length===0)return[];let s=Math.max(1,Math.min(20,Math.floor(n))),i=[];for(let a of r.pages){let c=a.title.toLowerCase(),u=a.slug.toLowerCase(),d=a.summary?.toLowerCase()??"",l=a.content.toLowerCase(),f=a.tags.map(g=>g.toLowerCase()),p=0;for(let g of o)u===g&&(p+=12),c===g&&(p+=10),c.includes(g)&&(p+=6),u.includes(g)&&(p+=5),f.some(S=>S===g)?p+=5:f.some(S=>S.includes(g))&&(p+=3),d.includes(g)&&(p+=2),l.includes(g)&&(p+=1);p>0&&i.push({page:Q(a),score:p})}return i.sort((a,c)=>c.score-a.score||c.page.updatedAt.localeCompare(a.page.updatedAt)).slice(0,s)}};var _r="wiki/state.v1.json";function oc(e){let t=new Date().toISOString();return{schema:"toolnet.wiki.v1",version:1,projectId:e.id,pages:[],revisions:[],createdAt:t,updatedAt:t}}function sc(e,t){let n=JSON.parse(e);if(n.schema!=="toolnet.wiki.v1"||n.version!==1||n.projectId!==t.id||!Array.isArray(n.pages)||!Array.isArray(n.revisions))throw new Error("Invalid ToolNet Wiki state");return n}var nt=class{constructor(t,n){this.storage=t;this.project=n}storage;project;async load(){let t=await this.storage.getText(_r);if(!t){let n=oc(this.project);return await this.save(n),n}return sc(t,this.project)}async save(t){await this.storage.put(_r,JSON.stringify(t,null,2),"application/json")}};import{createHash as ic,randomUUID as Kr}from"node:crypto";var $r="wiki/governance.v1.json",Dr="toolnet.knowledge-governance.v1",Lr=500,xe={autoApproveThreshold:.86,criticalApproveThreshold:.94,staleAfterDays:90};function ac(e,t=0,n=1){return Math.max(t,Math.min(n,e))}function Vt(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/gu," ").trim()}function Fr(e){return ic("sha256").update(e.normalize("NFKC").replace(/\s+/gu," ").trim()).digest("hex")}function cc(e){let t=[e.title,e.summary??"",e.content.slice(0,2e3),...e.tags].join(" ").toLowerCase();return/\b(?:architecture|security|authentication|authorization|auth|database|production|deploy|deployment|payment|billing|permission|permissions|acl|credential|secret|migration)\b/u.test(t)}function uc(e){let t=e.sourceType==="skill"?.96:e.sourceType==="memory"?.94:.88,n=e.tags.map(r=>r.toLowerCase());return(n.includes("permanent")||n.includes("task"))&&(t+=.03),e.content.length>=200&&(t+=.02),e.content.length<80&&(t-=.05),e.title.length<4&&(t-=.05),ac(t)}function Wr(e){let t=new Date().toISOString();return{schema:Dr,version:1,projectId:e,policy:{...xe},reviews:[],audit:[],createdAt:t,updatedAt:t}}function zr(e){let t=e.autoApproveThreshold??xe.autoApproveThreshold,n=e.criticalApproveThreshold??xe.criticalApproveThreshold,r=e.staleAfterDays??xe.staleAfterDays;if(!Number.isFinite(t)||t<.5||t>1)throw new j("Invalid autoApproveThreshold",400);if(!Number.isFinite(n)||n<.5||n>1)throw new j("Invalid criticalApproveThreshold",400);if(!Number.isInteger(r)||r<1||r>3650)throw new j("Invalid staleAfterDays",400);return{autoApproveThreshold:t,criticalApproveThreshold:n,staleAfterDays:r}}var rt=class{constructor(t,n){this.storage=t;this.project=n}storage;project;async load(){let t=await this.storage.getText($r);if(!t){let n=Wr(this.project.id);return await this.save(n),n}try{let n=JSON.parse(t);if(n.schema!==Dr||n.version!==1||n.projectId!==this.project.id||!Array.isArray(n.reviews)||!Array.isArray(n.audit))throw new Error("invalid");return{...n,policy:zr(n.policy??xe)}}catch{let n=Wr(this.project.id);return await this.save(n),n}}async save(t){await this.storage.put($r,JSON.stringify(t,null,2),"application/json")}},ot=class{constructor(t){this.store=t}store;state;queue=Promise.resolve();async initialize(){await this.ensureState()}async ensureState(){return this.state||(this.state=await this.store.load()),this.state}audit(t,n,r,o={}){t.audit.push({id:Kr(),action:n,principal:r,...o.reviewId?{reviewId:o.reviewId}:{},...o.sourceKey?{sourceKey:o.sourceKey}:{},timestamp:new Date().toISOString(),...o.metadata?{metadata:o.metadata}:{}}),t.audit.length>Lr&&(t.audit=t.audit.slice(-Lr))}async mutate(t){let n,r=this.queue.then(async()=>{let o=await this.ensureState();n=await t(o),o.updatedAt=new Date().toISOString(),await this.store.save(o)});return this.queue=r.then(()=>{},()=>{}),await r,n}async policy(){return{...(await this.ensureState()).policy}}async setPolicy(t,n){return this.mutate(r=>(r.policy=zr({...r.policy,...t}),this.audit(r,"policy:update",n,{metadata:{...r.policy}}),{...r.policy}))}async summary(){let t=await this.ensureState(),n=r=>t.reviews.filter(o=>o.status===r).length;return{schema:"toolnet.knowledge-governance-summary.v1",projectId:t.projectId,pending:n("pending"),approved:n("approved"),rejected:n("rejected"),superseded:n("superseded"),criticalPending:t.reviews.filter(r=>r.status==="pending"&&r.risk==="critical").length,conflictPending:t.reviews.filter(r=>r.status==="pending"&&r.risk==="conflict").length,auditEvents:t.audit.length,policy:{...t.policy},updatedAt:t.updatedAt}}async listReviews(t){let n=await this.ensureState();return structuredClone(n.reviews.filter(r=>!t||r.status===t).sort((r,o)=>o.updatedAt.localeCompare(r.updatedAt)))}async auditLog(t=100){let n=await this.ensureState(),r=Math.max(1,Math.min(500,Math.floor(t)));return structuredClone(n.audit.slice(-r).reverse())}async assess(t,n){let r=await this.ensureState(),o=uc(t),s=Vt(t.title),i=n.filter(d=>d.slug!==t.slug&&Vt(d.title)===s&&Fr(d.content)!==Fr(t.content)).map(d=>d.slug),a=cc(t),c=[];o<r.policy.autoApproveThreshold&&c.push(`confidence:${o.toFixed(2)}`),a&&o<r.policy.criticalApproveThreshold&&c.push("critical-knowledge"),i.length>0&&c.push("conflicting-knowledge");let u=i.length>0?"conflict":a?"critical":"normal";return{confidence:o,risk:u,requiresReview:i.length>0||o<r.policy.autoApproveThreshold||a&&o<r.policy.criticalApproveThreshold,reasons:c,conflicts:i}}async gate(t,n){let r=await this.assess(t,n);return this.mutate(o=>{let s=o.reviews.find(c=>c.sourceKey===t.sourceKey&&c.digest===t.digest);if(s?.status==="approved")return{allowed:!0,mode:"review-approved",assessment:r,review:structuredClone(s)};if(s?.status==="rejected")return{allowed:!1,mode:"rejected",assessment:r,review:structuredClone(s)};if(!r.requiresReview)return this.audit(o,"knowledge:auto-approved","system",{sourceKey:t.sourceKey,metadata:{confidence:r.confidence,risk:r.risk}}),{allowed:!0,mode:"auto-approved",assessment:r};if(s?.status==="pending")return{allowed:!1,mode:"pending-review",assessment:r,review:structuredClone(s)};let i=new Date().toISOString(),a={id:Kr(),sourceKey:t.sourceKey,sourceType:t.sourceType,slug:t.slug,marker:t.marker,digest:t.digest,title:t.title,...t.summary?{summary:t.summary}:{},content:t.content,tags:[...new Set([...t.tags,t.marker])],confidence:r.confidence,risk:r.risk,reasons:[...r.reasons],conflicts:[...r.conflicts],status:"pending",createdAt:i,updatedAt:i};return o.reviews.push(a),this.audit(o,"knowledge:review-requested","system",{reviewId:a.id,sourceKey:a.sourceKey,metadata:{confidence:a.confidence,risk:a.risk}}),{allowed:!1,mode:"pending-review",assessment:r,review:structuredClone(a)}})}async markApplied(t,n){await this.mutate(r=>{let o=r.reviews.find(s=>s.sourceKey===t&&s.digest===n&&s.status==="approved");o&&(o.appliedAt=new Date().toISOString(),o.updatedAt=o.appliedAt,this.audit(r,"knowledge:applied",o.reviewedBy??"system",{reviewId:o.id,sourceKey:t}))})}async decide(t,n,r){return this.mutate(async o=>{let s=o.reviews.find(u=>u.id===t);if(!s)throw new j(`Governance review not found: ${t}`,404);if(s.status!=="pending")throw new j("Governance review is already resolved",409);let i=new Date().toISOString();if(s.reviewedAt=i,s.reviewedBy=n.principal,s.updatedAt=i,n.note?.trim()&&(s.reviewNote=n.note.trim()),n.action==="reject")return s.status="rejected",this.audit(o,"knowledge:rejected",n.principal,{reviewId:t,sourceKey:s.sourceKey}),structuredClone(s);if(n.action==="supersede")return s.status="superseded",n.targetReviewId&&(s.supersededBy=n.targetReviewId),this.audit(o,"knowledge:superseded",n.principal,{reviewId:t,sourceKey:s.sourceKey,metadata:{targetReviewId:n.targetReviewId}}),structuredClone(s);if(n.action==="merge"){if(!n.targetReviewId)throw new j("targetReviewId is required for merge",400);let u=o.reviews.find(d=>d.id===n.targetReviewId);if(!u)throw new j("Merge target review not found",404);return s.status="superseded",s.mergedInto=u.id,this.audit(o,"knowledge:merged",n.principal,{reviewId:t,sourceKey:s.sourceKey,metadata:{targetReviewId:u.id}}),structuredClone(s)}s.status="approved";let c=(await r.listPages()).find(u=>u.slug===s.slug);if(c&&!c.tags.includes(s.marker))throw new j(`Wiki page '${s.slug}' is manually managed`,409);return c?await r.updatePage(s.slug,{title:s.title,summary:s.summary??"",content:s.content,tags:s.tags}):await r.createPage({slug:s.slug,title:s.title,...s.summary?{summary:s.summary}:{},content:s.content,tags:s.tags}),s.appliedAt=i,this.audit(o,"knowledge:approved",n.principal,{reviewId:t,sourceKey:s.sourceKey}),structuredClone(s)})}async quality(t){let n=await this.ensureState(),r=await t.listPages(),o=Date.now(),s=n.policy.staleAfterDays*864e5,i=r.map(d=>{let l=o-Date.parse(d.updatedAt);return{slug:d.slug,title:d.title,updatedAt:d.updatedAt,ageDays:Math.max(0,Math.floor(l/864e5)),stale:Number.isFinite(l)&&l>s}}).filter(d=>d.stale).map(({stale:d,...l})=>l),a=new Map;for(let d of r){let l=Vt(d.title),f=a.get(l)??[];f.push(d),a.set(l,f)}let c=[...a.entries()].filter(([,d])=>d.length>1).map(([d,l])=>({title:d,pages:l.map(f=>f.slug)})),u=n.reviews.filter(d=>d.status==="pending");return{schema:"toolnet.knowledge-quality.v1",totalPages:r.length,automatedPages:r.filter(d=>d.tags.some(l=>l.startsWith("toolnet-auto-"))).length,manualPages:r.filter(d=>!d.tags.some(l=>l.startsWith("toolnet-auto-"))).length,stalePages:i,duplicateTitles:c,pendingReviews:u.length,lowConfidenceReviews:u.filter(d=>d.confidence<n.policy.autoApproveThreshold).length,conflicts:u.filter(d=>d.risk==="conflict").length,generatedAt:new Date().toISOString()}}};var Ur="wiki/automation.v1.json",Yr="toolnet.wiki-automation.v1",Ut=8e3,qr=new Set(["raw","rawtext","raw_text","rawtranscript","raw_transcript","transcript","messages","message","payload","prompt","response","assistantmessage","assistant_message","userprompt","user_prompt"]);function Ie(e){return lc("sha256").update(JSON.stringify(e)).digest("hex")}function je(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Hr(e){return Array.isArray(e)?e:[]}function Xr(e){return typeof e!="string"?void 0:e.replace(/\s+/gu," ").trim()||void 0}function Bt(e){return Array.isArray(e)?e.map(Xr).filter(t=>!!t):[]}function K(e,t){for(let n of t){let r=Xr(e[n]);if(r)return r}}function Ae(e){let t=new Set,n=[];for(let r of e){let o=r.replace(/\s+/gu," ").trim();if(!o)continue;let s=o.normalize("NFKC").toLowerCase();t.has(s)||(t.add(s),n.push(o))}return n}function st(e,t=0,n=""){if(t>3)return[];let r=n.replace(/[^a-z0-9]/giu,"").toLowerCase();if(qr.has(r))return[];if(typeof e=="string"){let i=e.replace(/\s+/gu," ").trim();return i.length<8?[]:[i]}if(Array.isArray(e))return e.flatMap(i=>st(i,t+1,n));let o=je(e);if(!o)return[];let s=[];for(let[i,a]of Object.entries(o)){let c=i.replace(/[^a-z0-9]/giu,"").toLowerCase();qr.has(c)||s.push(...st(a,t+1,i))}return s}function Jr(e){let n=Ae(["content","summary","text","value","statement","description","decision","task","knowledge","context","outcome","reason","rationale"].flatMap(o=>st(e[o],0,o)));return(n.length>0?n:Ae(st(e))).join(`
40
-
41
- `).slice(0,Ut)}function Vr(e,t){return K(e,["id","key","fingerprint","knowledgeId","sceneId"])??t}function Br(e,t){return K(e,["title","name","topic","label","task","kind","type"])??t}function gc(e){return(K(e,["knowledgeClass","class","classification","scope"])??"").toLowerCase()}function yc(e){return(K(e,["kind","sceneKind","type"])??"").toLowerCase()}function hc(e){let t=je(e);if(!t)return[];let n=[],r=Hr(t.knowledge);for(let[s,i]of r.entries()){let a=je(i);if(!a)continue;let c=gc(a);if(c==="session"||c==="transient")continue;let u=Jr(a);if(u.length<20)continue;let d=Vr(a,Ie(a).slice(0,16)),l=Br(a,`Durable Memory ${s+1}`);n.push({sourceKey:`memory:${d}`,sourceType:"memory",title:l,summary:K(a,["summary","description"]),content:u,tags:Ae(["toolnet","auto","memory",...c?[c]:[]])})}let o=Hr(t.scenes);for(let[s,i]of o.entries()){let a=je(i);if(!a)continue;let c=yc(a);if(c==="session-context")continue;let u=Jr(a);if(u.length<20)continue;let d=Vr(a,Ie(a).slice(0,16)),l=Br(a,`Knowledge Scene ${s+1}`);n.push({sourceKey:`scene:${d}`,sourceType:"scene",title:l,summary:K(a,["summary","description"]),content:u,tags:Ae(["toolnet","auto","scene",...c?[c]:[]])})}return n}function Sc(e){return Gr(e,".toolnet","memory","skills")}function kc(e){let t=Sc(e);if(!dc(t))return{candidates:[],failed:0};let n=[],r=0,o=pc(t).filter(s=>s.endsWith(".json")).sort();for(let s of o)try{let i=JSON.parse(fc(Gr(t,s),"utf8")),a=je(i);if(!a||a.schema!=="toolnet.skill-memory.v1")continue;let c=K(a,["id","fingerprint"])??mc(s,".json"),u=K(a,["task"])??"",d=K(a,["title"])||u||`Reusable Skill ${c.slice(0,8)}`,l=K(a,["summary"])??void 0,f=Bt(a.steps),p=Bt(a.verification),g=Bt(a.files),S=[];u&&S.push(`## Task
42
- ${u}`),l&&S.push(`## Summary
43
- ${l}`),f.length>0&&S.push(`## Procedure
44
- ${f.map((h,k)=>`${k+1}. ${h}`).join(`
45
- `)}`),p.length>0&&S.push(`## Verification
46
- ${p.map(h=>`- ${h}`).join(`
47
- `)}`),g.length>0&&S.push(`## Relevant Files
48
- ${g.map(h=>`- \`${h}\``).join(`
49
- `)}`);let y=S.join(`
50
-
51
- `).slice(0,Ut);if(y.length<20)continue;n.push({sourceKey:`skill:${c}`,sourceType:"skill",title:d,summary:l,content:y,tags:["toolnet","auto","skill","sop"]})}catch{r+=1}return{candidates:n,failed:r}}function Gt(e){let t=new Date().toISOString();return{schema:Yr,version:1,projectId:e,entries:[],createdAt:t,updatedAt:t}}async function vc(e,t){let n=await e.getText(Ur);if(!n)return Gt(t);try{let r=JSON.parse(n);return r.schema!==Yr||r.version!==1||r.projectId!==t||!Array.isArray(r.entries)?Gt(t):r}catch{return Gt(t)}}async function wc(e,t){await e.put(Ur,JSON.stringify(t,null,2),"application/json")}function bc(e){return`toolnet-auto-${Ie(e).slice(0,12)}`}function xc(e){let t=Z(e.title).slice(0,72),n=Ie(e.sourceKey).slice(0,10);return Z(`auto-${e.sourceType}-${t}-${n}`)}function jc(e){return[`> Auto-generated by ToolNet Knowledge Automation from ${e.sourceType==="skill"?"reusable Skill Memory":e.sourceType==="scene"?"semantic memory scene":"durable memory"}.`,"",e.content].join(`
52
- `).slice(0,Ut)}function Ic(e){return Ie({sourceType:e.sourceType,title:e.title,summary:e.summary,content:e.content,tags:e.tags})}function Ac(e,t){return e.tags.includes(t)}async function Qr(e){let t=hc(e.hierarchy),n=kc(e.project.rootPath),r=new Map;for(let p of[...t,...n.candidates])r.set(p.sourceKey,p);let o=[...r.values()].sort((p,g)=>p.sourceKey.localeCompare(g.sourceKey)),s={schema:"toolnet.wiki-automation-result.v1",scanned:t.length+n.candidates.length,eligible:o.length,created:0,updated:0,unchanged:0,skipped:0,failed:n.failed,reviewPending:0,autoApproved:0,reviewApproved:0,pages:[]},i=new tt(new nt(e.storage,e.project));await i.initialize();let a=new ot(new rt(e.storage,e.project));await a.initialize();let c=await vc(e.storage,e.project.id),u=await i.listPages(),d=new Map(u.map(p=>[p.slug,p])),l=new Map(c.entries.map(p=>[p.sourceKey,p]));for(let p of o)try{let g=bc(p.sourceKey),S=Ic(p),y=l.get(p.sourceKey),h=y?.slug??xc(p),k=d.get(h);if(k&&!Ac(k,g)){s.skipped+=1;continue}let M=Ae([...p.tags,g]),E=jc(p),C=await a.gate({sourceKey:p.sourceKey,sourceType:p.sourceType,slug:h,marker:g,digest:S,title:p.title,...p.summary?{summary:p.summary}:{},content:E,tags:M},[...d.values()]);if(!C.allowed){C.mode==="pending-review"?s.reviewPending+=1:s.skipped+=1;continue}C.mode==="auto-approved"?s.autoApproved+=1:C.mode==="review-approved"&&(s.reviewApproved+=1),k?y?.digest!==S?(k=await i.updatePage(h,{title:p.title,summary:p.summary??"",content:E,tags:M}),d.set(k.slug,k),s.updated+=1,s.pages.push({sourceKey:p.sourceKey,sourceType:p.sourceType,slug:k.slug,action:"updated"})):(s.unchanged+=1,s.pages.push({sourceKey:p.sourceKey,sourceType:p.sourceType,slug:h,action:"unchanged"})):(k=await i.createPage({slug:h,title:p.title,summary:p.summary,content:E,tags:M}),d.set(k.slug,k),s.created+=1,s.pages.push({sourceKey:p.sourceKey,sourceType:p.sourceType,slug:k.slug,action:"created"}));let O=new Date().toISOString(),x={sourceKey:p.sourceKey,sourceType:p.sourceType,slug:h,digest:S,marker:g,updatedAt:O},w=c.entries.findIndex(W=>W.sourceKey===p.sourceKey);w>=0?c.entries[w]=x:c.entries.push(x),l.set(p.sourceKey,x),await a.markApplied(p.sourceKey,S)}catch(g){if(g instanceof j&&g.statusCode===409){s.skipped+=1;continue}s.failed+=1}let f=new Date().toISOString();return c.updatedAt=f,c.lastRunAt=f,c.entries.sort((p,g)=>p.sourceKey.localeCompare(g.sourceKey)),await wc(e.storage,c),s}import{createHash as Pc}from"node:crypto";import{chmodSync as eo,existsSync as Cc,mkdirSync as Mc,readFileSync as Vm,readdirSync as Bm,renameSync as Ec,statSync as Gm,writeFileSync as Oc}from"node:fs";import{join as to}from"node:path";var Tc="toolnet.skill-memory.v1",Zr=5,Rc=16,Nc=24,_c=32;function Kc(e){return Pc("sha256").update(e).digest("hex")}function Ce(e,t=Number.MAX_SAFE_INTEGER){let n=new Set,r=[];for(let o of e){let s=o.replace(/\s+/gu," ").trim();if(!s)continue;let i=s.normalize("NFKC").toLowerCase();if(!n.has(i)&&(n.add(i),r.push(s),r.length>=t))break}return r}function Yt(e,t=360){let n=e.replace(/\s+/gu," ").trim();return n.length<=t?n:n.slice(0,Math.max(0,t-1)).trimEnd()+"\u2026"}function $c(e){return e.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/giu,"Bearer [REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/gu,"[REDACTED]").replace(/\b(api[_-]?key|token|password|passwd|secret)\b(\s*[:=]\s*)(["']?)[^\s"'`]+/giu,"$1$2[REDACTED]")}function z(e,t=360){return e&&Yt($c(e),t)||void 0}function Me(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}}function no(e,t){for(let n of t){let r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()&&Number.isFinite(Number(r)))return Number(r)}}function ro(e,t){for(let n of t){let r=e[n];if(typeof r=="boolean")return r;if(typeof r=="string"){let o=r.trim().toLowerCase();if(["true","yes","pass","passed","success","succeeded","ok"].includes(o))return!0;if(["false","no","fail","failed","error"].includes(o))return!1}}}function oo(e){let t=e.data??{};if(ro(t,["passed","pass","success","succeeded","ok"])===!1)return!0;let r=no(t,["exitCode","exit_code","code","statusCode"]);if(r!==void 0&&r!==0)return!0;let o=Me(t,["status","result","outcome"]);return!!(o&&/\b(fail(?:ed)?|error|broken|cancelled)\b/iu.test(o))}function Pe(e){let t=e.data??{};if(oo(e))return!1;if(ro(t,["passed","pass","success","succeeded","ok"])===!0||no(t,["exitCode","exit_code","code","statusCode"])===0)return!0;let o=Me(t,["status","result","outcome"]);return o&&/\b(pass(?:ed)?|success(?:ful)?|succeeded|ok|green|complete(?:d)?)\b/iu.test(o)?!0:e.type==="commit"||e.type==="deploy"}function so(e){let t=e.data??{},n=Me(t,["path","file","filePath","filename","target"]);if(n)return z(n,260);let r=e.provenance?.files;return z(r?.[0],260)}function Xt(e){return z(Me(e.data??{},["command","cmd","script"]),420)}function ae(e){return z(Me(e.data??{},["name","test","suite","title","message","text","result","status"]),300)}function Lc(e){let t=[];for(let n of[...e].sort((r,o)=>r.sequence-o.sequence))if(Pe(n)){if(n.type==="test"){let r=ae(n)??Xt(n)??"Tests passed";t.push(`Test passed: ${r}`);continue}if(n.type==="commit"){let r=ae(n);t.push(r?`Commit: ${r}`:"Commit completed");continue}if(n.type==="deploy"){let r=ae(n);t.push(r?`Deploy: ${r}`:"Deployment completed")}}return Ce(t,10)}function Fc(e,t){let n=[];for(let r of[...e].sort((o,s)=>o.sequence-s.sequence))switch(r.type){case"file_write":case"file_edit":{let o=so(r);o&&n.push(`Update ${o}`);break}case"command":{if(oo(r))break;let o=Xt(r);o&&n.push(`Run: ${o}`);break}case"test":{if(!Pe(r))break;let o=ae(r)??Xt(r)??"project tests";n.push(`Verify: ${o}`);break}case"commit":{if(!Pe(r))break;let o=ae(r);n.push(o?`Commit: ${o}`:"Commit verified changes");break}case"deploy":{if(!Pe(r))break;let o=ae(r);n.push(o?`Deploy: ${o}`:"Deploy verified build");break}default:break}if(n.length===0)for(let r of t.files.slice(0,8)){let o=z(r,260);o&&n.push(`Update ${o}`)}return Ce(n,Rc)}function Wc(e,t){let n=[...t.files];for(let r of e){let o=so(r);o&&n.push(o);for(let s of r.provenance?.files??[]){let i=z(s,260);i&&n.push(i)}}return Ce(n,Nc)}function Dc(e){return Ce(e.filter(t=>["file_write","file_edit","command","test","commit","deploy"].includes(t.type)).map(t=>t.id),_c)}function zc(e){return e.map(n=>n.timestamp).filter(Boolean).sort().at(-1)??new Date(0).toISOString()}function io(e,t,n){if(t.length===0)return[];let r=Lc(t),o=Ce(n.completed.map(g=>z(g,280)??""),Zr);if(!(o.length>0||t.some(g=>["test","commit","deploy"].includes(g.type)&&Pe(g))))return[];let i=z(n.task,280)??z(n.nextActions[0],280),a=o.length>0?o:i?[i]:[];if(a.length===0)return[];let c=Fc(t,n);if(c.length===0)return[];let u=Wc(t,n),d=Dc(t),l=Math.min(...t.map(g=>g.sequence)),f=Math.max(...t.map(g=>g.sequence)),p=zc(t);return a.slice(0,Zr).map(g=>{let S=[`Reusable procedure learned from successful task: ${g}.`,u.length>0?`Files: ${u.slice(0,6).join(", ")}.`:"",r.length>0?`Verification: ${r.slice(0,4).join("; ")}.`:""].filter(Boolean),y=JSON.stringify({projectId:e.projectId,task:g,steps:c,verification:r,files:u}),h=Kc(y);return{schema:Tc,version:1,id:`skill-${h.slice(0,24)}`,fingerprint:h,projectId:e.projectId,title:Yt(`SOP: ${g}`,180),task:g,summary:Yt(S.join(" "),900),steps:c,verification:r,files:u,source:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,firstSequence:l,lastSequence:f,eventIds:d},createdAt:p}})}function qc(e){return to(e.rootPath,".toolnet","memory","skills")}function Hc(e){let t=qc(e);return Mc(t,{recursive:!0,mode:448}),eo(t,448),t}function ao(e,t){if(t.length===0)return{written:0,deduped:0,files:[]};let n=Hc(e),r=0,o=0,s=[];for(let i of t){if(i.projectId!==e.id)throw new Error(`Skill project mismatch: ${i.projectId} != ${e.id}`);let a=to(n,`${i.id}.json`);if(s.push(a),Cc(a)){o+=1;continue}let c=`${a}.${process.pid}.${Date.now()}.tmp`;Oc(c,JSON.stringify(i,null,2)+`
53
- `,{encoding:"utf8",mode:384}),Ec(c,a),eo(a,384),r+=1}return{written:r,deduped:o,files:s}}function co(e){return String(e).padStart(12,"0")}function Jc(e){return`projects/${e.projectId}/memory/learned`}var it=class{constructor(t){this.storage=t}storage;async write(t,n,r){if(r.length===0||n.length===0)return null;let o=Math.min(...n.map(l=>l.sequence)),s=Math.max(...n.map(l=>l.sequence)),i={version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,createdAt:new Date().toISOString(),firstSequence:o,lastSequence:s,candidateCount:r.length,candidates:r},a=JSON.stringify(i,null,2)+`
54
- `,c=v(r.map(l=>l.fingerprint).sort().join("|")).slice(0,16),u=v(t.sessionKey).slice(0,12),d=[Jc(t),"batches",`${co(o)}-${co(s)}-${u}-${c}.json`].join("/");return await this.storage.exists(d)||await this.storage.put(d,a,"application/json"),d}};import{createHash as Vc}from"node:crypto";function uo(e){return String(e).padStart(12,"0")}function lo(e){return Vc("sha256").update(e).digest("hex")}function Bc(e){return`projects/${e.projectId}/memory/hierarchy`}var at=class{constructor(t){this.storage=t}storage;async write(t,n,r){if(n.length===0||r.facts.length===0)return null;let o=Math.min(...n.map(d=>d.sequence)),s=Math.max(...n.map(d=>d.sequence)),i={schema:"toolnet.memory-hierarchy-batch.v1",version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,createdAt:new Date().toISOString(),firstSequence:o,lastSequence:s,hierarchy:r},a=lo([...r.facts.map(d=>d.id),...r.knowledge.map(d=>d.id)].sort().join("|")).slice(0,16),c=lo(t.sessionKey).slice(0,12),u=[Bc(t),"batches",`${uo(o)}-${uo(s)}-${c}-${a}.json`].join("/");return await this.storage.exists(u)||await this.storage.put(u,`${JSON.stringify(i,null,2)}
55
- `,"application/json"),u}};function Zc(e,t){if(!Uc(e))return{events:[],nextOffset:t};let n=Qc(e).size,r=Number.isFinite(t)?Math.max(0,t):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let o=n-r,s=Buffer.alloc(o),i=Yc(e,"r");try{Xc(i,s,0,o,r)}finally{Gc(i)}let a=s.toString("utf8"),c=a.lastIndexOf(`
36
+ `).filter(i=>{let a=i.trim();return a.length>20&&!a.startsWith("npm")&&!a.startsWith("\u2713")&&!a.startsWith("Error:")}).slice(0,20).map(i=>Xr(i)).join(`
37
+ `);return An(s,n)}function Zr(e,t){let r=(Array.isArray(e)?e:e.split(`
38
+
39
+ `).filter(f=>f.trim())).map(f=>typeof f=="string"?f:JSON.stringify(f)).filter(f=>f.trim()),o=Tc(r,t),s=o.filter(f=>f.category==="decision").map(f=>f.text),i=o.filter(f=>f.category==="rule").map(f=>f.text),a=o.filter(f=>f.category==="file").map(f=>f.text),c=o.filter(f=>f.category==="fix").map(f=>f.text),u=o.filter(f=>f.category==="blocker").map(f=>f.text),l=o.filter(f=>f.category==="next_action").map(f=>f.text),d=o.filter(f=>f.category==="deploy").map(f=>f.text);return{summary:Rc(r),decisions:s,projectRules:i,filesChanged:a,bugsFixed:c,commands:d,blockers:u,nextActions:l,durableFacts:o}}function G(e){let t=new Set,n=[];for(let r of e){let o=r?.replace(/\s+/g," ").trim();if(!o)continue;let s=o.normalize("NFKC").toLowerCase();t.has(s)||(t.add(s),n.push(o))}return n}function Nc(e){let t=new Map;for(let n of e){if(!n||!n.id||!Number.isFinite(n.sequence))continue;let r=n.sourceEventId?`${n.agent}:${n.sourceEventId}`:n.id,o=t.get(r);(!o||n.sequence>o.sequence)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.sequence-r.sequence||n.timestamp.localeCompare(r.timestamp))}function _c(e){let t=e.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_./:-]+/gu)??[],n=new Set;for(let r of t)if(!(r.length<2||/^\d+$/u.test(r))&&(n.add(r),n.size>=40))break;return[...n]}function Kc(e){let t=tn(e);return{...e,knowledgeClass:t.knowledgeClass,importanceScore:t.score,retrievalTerms:_c(e.content),tags:G([...e.tags,"level:fact",`class:${t.knowledgeClass}`,`kind:${e.kind}`])}}function $c(e){return e.map(t=>{try{return JSON.stringify({type:t.type,role:t.role,data:t.data,provenance:{sourcePath:t.provenance.sourcePath,files:t.provenance.files}})}catch{return""}}).filter(Boolean)}function Lc(e,t,n){let r=Zr($c(t),e.nativeSessionId),o=n.filter(u=>u.kind==="todo"||u.kind==="next_action").map(u=>u.content),s=n.flatMap(u=>u.provenance.sourcePaths),i=n.filter(u=>u.kind==="architecture").map(u=>u.content),a=G([...o,...r.nextActions]),c=G([...r.nextActions,...o]);return{summary:r.summary,state:{task:c[0]??a[0],decisions:G(r.decisions),files:G([...r.filesChanged,...s]),todos:a,completed:G(r.bugsFixed),blockers:G(r.blockers),nextActions:c,architecture:G(i)}}}function dt(e,t){let n=Nc(t),r=Hr(e,n).map(Kc),o=r.filter(l=>tn(l).persist).sort((l,d)=>d.importanceScore-l.importanceScore),{summary:s,state:i}=Lc(e,n,o),a=o.map(l=>({fingerprint:l.fingerprint,kind:l.kind,knowledgeClass:l.knowledgeClass,importanceScore:l.importanceScore,content:l.content,terms:l.retrievalTerms})),c=Br(n,o),u=l=>r.filter(d=>d.knowledgeClass===l).length;return{version:2,normalizedEvents:n,summary:s,state:i,candidates:o,retrievalIndex:a,hierarchy:c,stats:{inputEvents:t.length,normalizedEvents:n.length,extractedCandidates:r.length,persistedCandidates:o.length,permanent:u("permanent"),task:u("task"),session:u("session"),transient:u("transient")}}}import{createHash as Vc}from"node:crypto";import{existsSync as Bc,readdirSync as Gc,readFileSync as Uc}from"node:fs";import{basename as Yc,join as yo}from"node:path";import{randomUUID as to}from"node:crypto";var A=class extends Error{constructor(n,r){super(n);this.statusCode=r}statusCode};function Pe(e){let t=new Set,n=[];for(let r of e){let o=r.replace(/\s+/gu," ").trim();if(!o)continue;let s=o.normalize("NFKC").toLowerCase();t.has(s)||(t.add(s),n.push(o))}return n}function ne(e){let t=e.normalize("NFKD").replace(/[\u0300-\u036f]/gu,"").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"").slice(0,120);if(!t)throw new A("Invalid Wiki slug",400);return t}function Qr(e){let t=[];for(let n of e.matchAll(/\[\[([^\[\]]+)\]\]/gu)){let r=n[1]?.trim();r&&t.push(ne(r))}return Pe(t)}function Fc(e){return e.normalize("NFKC").toLowerCase().split(/[^\p{L}\p{N}_-]+/u).map(t=>t.trim()).filter(t=>t.length>=2)}function eo(e){return{id:`revision-${to()}`,pageId:e.id,slug:e.slug,revision:e.revision,title:e.title,...e.summary?{summary:e.summary}:{},content:e.content,tags:[...e.tags],links:[...e.links],createdAt:e.updatedAt}}function te(e){return structuredClone(e)}var pt=class{constructor(t){this.store=t}store;state;queue=Promise.resolve();async initialize(){await this.ensureState()}async ensureState(){return this.state||(this.state=await this.store.load()),this.state}async mutate(t){let n,r=this.queue.then(async()=>{let o=await this.ensureState();n=t(o),o.updatedAt=new Date().toISOString(),await this.store.save(o)});return this.queue=r.then(()=>{},()=>{}),await r,n}async summary(){let t=await this.ensureState(),n=new Set(t.pages.flatMap(r=>r.links));return{schema:"toolnet.wiki-summary.v1",projectId:t.projectId,pages:t.pages.length,revisions:t.revisions.length,tags:Pe(t.pages.flatMap(r=>r.tags)).sort((r,o)=>r.localeCompare(o)),links:t.pages.reduce((r,o)=>r+o.links.length,0),orphanPages:t.pages.filter(r=>r.links.length===0&&!n.has(r.slug)).length,automatedPages:t.pages.filter(r=>r.tags.some(o=>o.startsWith("toolnet-auto-"))).length,updatedAt:t.updatedAt}}async listPages(){let t=await this.ensureState();return te([...t.pages].sort((n,r)=>n.title.localeCompare(r.title)))}async getPage(t){let n=await this.ensureState(),r=ne(t),o=n.pages.find(s=>s.slug===r||s.id===t);if(!o)throw new A(`Wiki page not found: ${t}`,404);return te(o)}async createPage(t){return this.mutate(n=>{let r=t.title.trim(),o=t.content.trim();if(!r)throw new A("Wiki title is required",400);let s=ne(t.slug??r);if(n.pages.some(c=>c.slug===s))throw new A(`Wiki page already exists: ${s}`,409);let i=new Date().toISOString(),a={id:`wiki-${to()}`,slug:s,title:r,...t.summary?.trim()?{summary:t.summary.trim()}:{},content:o,tags:Pe(t.tags??[]),links:Qr(o),revision:1,createdAt:i,updatedAt:i};return n.pages.push(a),n.revisions.push(eo(a)),te(a)})}async updatePage(t,n){return this.mutate(r=>{let o=ne(t),s=r.pages.find(i=>i.slug===o||i.id===t);if(!s)throw new A(`Wiki page not found: ${t}`,404);if(n.title!==void 0){let i=n.title.trim();if(!i)throw new A("Wiki title is required",400);s.title=i}if(n.summary!==void 0){let i=n.summary.trim();i?s.summary=i:delete s.summary}return n.content!==void 0&&(s.content=n.content.trim(),s.links=Qr(s.content)),n.tags!==void 0&&(s.tags=Pe(n.tags)),s.revision+=1,s.updatedAt=new Date().toISOString(),r.revisions.push(eo(s)),te(s)})}async history(t){let n=await this.getPage(t),r=await this.ensureState();return te(r.revisions.filter(o=>o.pageId===n.id).sort((o,s)=>s.revision-o.revision))}async backlinks(t){let n=await this.getPage(t),r=await this.ensureState();return te(r.pages.filter(o=>o.links.includes(n.slug)).sort((o,s)=>o.title.localeCompare(s.title)))}async search(t,n=10){let r=await this.ensureState(),o=Pe(Fc(t));if(o.length===0)return[];let s=Math.max(1,Math.min(20,Math.floor(n))),i=[];for(let a of r.pages){let c=a.title.toLowerCase(),u=a.slug.toLowerCase(),l=a.summary?.toLowerCase()??"",d=a.content.toLowerCase(),p=a.tags.map(m=>m.toLowerCase()),f=0;for(let m of o)u===m&&(f+=12),c===m&&(f+=10),c.includes(m)&&(f+=6),u.includes(m)&&(f+=5),p.some(S=>S===m)?f+=5:p.some(S=>S.includes(m))&&(f+=3),l.includes(m)&&(f+=2),d.includes(m)&&(f+=1);f>0&&i.push({page:te(a),score:f})}return i.sort((a,c)=>c.score-a.score||c.page.updatedAt.localeCompare(a.page.updatedAt)).slice(0,s)}};var no="wiki/state.v1.json";function Dc(e){let t=new Date().toISOString();return{schema:"toolnet.wiki.v1",version:1,projectId:e.id,pages:[],revisions:[],createdAt:t,updatedAt:t}}function Wc(e,t){let n=JSON.parse(e);if(n.schema!=="toolnet.wiki.v1"||n.version!==1||n.projectId!==t.id||!Array.isArray(n.pages)||!Array.isArray(n.revisions))throw new Error("Invalid ToolNet Wiki state");return n}var ft=class{constructor(t,n){this.storage=t;this.project=n}storage;project;async load(){let t=await this.storage.getText(no);if(!t){let n=Dc(this.project);return await this.save(n),n}return Wc(t,this.project)}async save(t){await this.storage.put(no,JSON.stringify(t,null,2),"application/json")}};import{createHash as zc,randomUUID as ro}from"node:crypto";var oo="wiki/governance.v1.json",co="toolnet.knowledge-governance.v1",so=500,Me={autoApproveThreshold:.86,criticalApproveThreshold:.94,staleAfterDays:90};function qc(e,t=0,n=1){return Math.max(t,Math.min(n,e))}function on(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/gu," ").trim()}function io(e){return zc("sha256").update(e.normalize("NFKC").replace(/\s+/gu," ").trim()).digest("hex")}function Hc(e){let t=[e.title,e.summary??"",e.content.slice(0,2e3),...e.tags].join(" ").toLowerCase();return/\b(?:architecture|security|authentication|authorization|auth|database|production|deploy|deployment|payment|billing|permission|permissions|acl|credential|secret|migration)\b/u.test(t)}function Jc(e){let t=e.sourceType==="skill"?.96:e.sourceType==="memory"?.94:.88,n=e.tags.map(r=>r.toLowerCase());return(n.includes("permanent")||n.includes("task"))&&(t+=.03),e.content.length>=200&&(t+=.02),e.content.length<80&&(t-=.05),e.title.length<4&&(t-=.05),qc(t)}function ao(e){let t=new Date().toISOString();return{schema:co,version:1,projectId:e,policy:{...Me},reviews:[],audit:[],createdAt:t,updatedAt:t}}function uo(e){let t=e.autoApproveThreshold??Me.autoApproveThreshold,n=e.criticalApproveThreshold??Me.criticalApproveThreshold,r=e.staleAfterDays??Me.staleAfterDays;if(!Number.isFinite(t)||t<.5||t>1)throw new A("Invalid autoApproveThreshold",400);if(!Number.isFinite(n)||n<.5||n>1)throw new A("Invalid criticalApproveThreshold",400);if(!Number.isInteger(r)||r<1||r>3650)throw new A("Invalid staleAfterDays",400);return{autoApproveThreshold:t,criticalApproveThreshold:n,staleAfterDays:r}}var mt=class{constructor(t,n){this.storage=t;this.project=n}storage;project;async load(){let t=await this.storage.getText(oo);if(!t){let n=ao(this.project.id);return await this.save(n),n}try{let n=JSON.parse(t);if(n.schema!==co||n.version!==1||n.projectId!==this.project.id||!Array.isArray(n.reviews)||!Array.isArray(n.audit))throw new Error("invalid");return{...n,policy:uo(n.policy??Me)}}catch{let n=ao(this.project.id);return await this.save(n),n}}async save(t){await this.storage.put(oo,JSON.stringify(t,null,2),"application/json")}},gt=class{constructor(t){this.store=t}store;state;queue=Promise.resolve();async initialize(){await this.ensureState()}async ensureState(){return this.state||(this.state=await this.store.load()),this.state}audit(t,n,r,o={}){t.audit.push({id:ro(),action:n,principal:r,...o.reviewId?{reviewId:o.reviewId}:{},...o.sourceKey?{sourceKey:o.sourceKey}:{},timestamp:new Date().toISOString(),...o.metadata?{metadata:o.metadata}:{}}),t.audit.length>so&&(t.audit=t.audit.slice(-so))}async mutate(t){let n,r=this.queue.then(async()=>{let o=await this.ensureState();n=await t(o),o.updatedAt=new Date().toISOString(),await this.store.save(o)});return this.queue=r.then(()=>{},()=>{}),await r,n}async policy(){return{...(await this.ensureState()).policy}}async setPolicy(t,n){return this.mutate(r=>(r.policy=uo({...r.policy,...t}),this.audit(r,"policy:update",n,{metadata:{...r.policy}}),{...r.policy}))}async summary(){let t=await this.ensureState(),n=r=>t.reviews.filter(o=>o.status===r).length;return{schema:"toolnet.knowledge-governance-summary.v1",projectId:t.projectId,pending:n("pending"),approved:n("approved"),rejected:n("rejected"),superseded:n("superseded"),criticalPending:t.reviews.filter(r=>r.status==="pending"&&r.risk==="critical").length,conflictPending:t.reviews.filter(r=>r.status==="pending"&&r.risk==="conflict").length,auditEvents:t.audit.length,policy:{...t.policy},updatedAt:t.updatedAt}}async listReviews(t){let n=await this.ensureState();return structuredClone(n.reviews.filter(r=>!t||r.status===t).sort((r,o)=>o.updatedAt.localeCompare(r.updatedAt)))}async auditLog(t=100){let n=await this.ensureState(),r=Math.max(1,Math.min(500,Math.floor(t)));return structuredClone(n.audit.slice(-r).reverse())}async assess(t,n){let r=await this.ensureState(),o=Jc(t),s=on(t.title),i=n.filter(l=>l.slug!==t.slug&&on(l.title)===s&&io(l.content)!==io(t.content)).map(l=>l.slug),a=Hc(t),c=[];o<r.policy.autoApproveThreshold&&c.push(`confidence:${o.toFixed(2)}`),a&&o<r.policy.criticalApproveThreshold&&c.push("critical-knowledge"),i.length>0&&c.push("conflicting-knowledge");let u=i.length>0?"conflict":a?"critical":"normal";return{confidence:o,risk:u,requiresReview:i.length>0||o<r.policy.autoApproveThreshold||a&&o<r.policy.criticalApproveThreshold,reasons:c,conflicts:i}}async gate(t,n){let r=await this.assess(t,n);return this.mutate(o=>{let s=o.reviews.find(c=>c.sourceKey===t.sourceKey&&c.digest===t.digest);if(s?.status==="approved")return{allowed:!0,mode:"review-approved",assessment:r,review:structuredClone(s)};if(s?.status==="rejected")return{allowed:!1,mode:"rejected",assessment:r,review:structuredClone(s)};if(!r.requiresReview)return this.audit(o,"knowledge:auto-approved","system",{sourceKey:t.sourceKey,metadata:{confidence:r.confidence,risk:r.risk}}),{allowed:!0,mode:"auto-approved",assessment:r};if(s?.status==="pending")return{allowed:!1,mode:"pending-review",assessment:r,review:structuredClone(s)};let i=new Date().toISOString(),a={id:ro(),sourceKey:t.sourceKey,sourceType:t.sourceType,slug:t.slug,marker:t.marker,digest:t.digest,title:t.title,...t.summary?{summary:t.summary}:{},content:t.content,tags:[...new Set([...t.tags,t.marker])],confidence:r.confidence,risk:r.risk,reasons:[...r.reasons],conflicts:[...r.conflicts],status:"pending",createdAt:i,updatedAt:i};return o.reviews.push(a),this.audit(o,"knowledge:review-requested","system",{reviewId:a.id,sourceKey:a.sourceKey,metadata:{confidence:a.confidence,risk:a.risk}}),{allowed:!1,mode:"pending-review",assessment:r,review:structuredClone(a)}})}async markApplied(t,n){await this.mutate(r=>{let o=r.reviews.find(s=>s.sourceKey===t&&s.digest===n&&s.status==="approved");o&&(o.appliedAt=new Date().toISOString(),o.updatedAt=o.appliedAt,this.audit(r,"knowledge:applied",o.reviewedBy??"system",{reviewId:o.id,sourceKey:t}))})}async decide(t,n,r){return this.mutate(async o=>{let s=o.reviews.find(u=>u.id===t);if(!s)throw new A(`Governance review not found: ${t}`,404);if(s.status!=="pending")throw new A("Governance review is already resolved",409);let i=new Date().toISOString();if(s.reviewedAt=i,s.reviewedBy=n.principal,s.updatedAt=i,n.note?.trim()&&(s.reviewNote=n.note.trim()),n.action==="reject")return s.status="rejected",this.audit(o,"knowledge:rejected",n.principal,{reviewId:t,sourceKey:s.sourceKey}),structuredClone(s);if(n.action==="supersede")return s.status="superseded",n.targetReviewId&&(s.supersededBy=n.targetReviewId),this.audit(o,"knowledge:superseded",n.principal,{reviewId:t,sourceKey:s.sourceKey,metadata:{targetReviewId:n.targetReviewId}}),structuredClone(s);if(n.action==="merge"){if(!n.targetReviewId)throw new A("targetReviewId is required for merge",400);let u=o.reviews.find(l=>l.id===n.targetReviewId);if(!u)throw new A("Merge target review not found",404);return s.status="superseded",s.mergedInto=u.id,this.audit(o,"knowledge:merged",n.principal,{reviewId:t,sourceKey:s.sourceKey,metadata:{targetReviewId:u.id}}),structuredClone(s)}s.status="approved";let c=(await r.listPages()).find(u=>u.slug===s.slug);if(c&&!c.tags.includes(s.marker))throw new A(`Wiki page '${s.slug}' is manually managed`,409);return c?await r.updatePage(s.slug,{title:s.title,summary:s.summary??"",content:s.content,tags:s.tags}):await r.createPage({slug:s.slug,title:s.title,...s.summary?{summary:s.summary}:{},content:s.content,tags:s.tags}),s.appliedAt=i,this.audit(o,"knowledge:approved",n.principal,{reviewId:t,sourceKey:s.sourceKey}),structuredClone(s)})}async quality(t){let n=await this.ensureState(),r=await t.listPages(),o=Date.now(),s=n.policy.staleAfterDays*864e5,i=r.map(l=>{let d=o-Date.parse(l.updatedAt);return{slug:l.slug,title:l.title,updatedAt:l.updatedAt,ageDays:Math.max(0,Math.floor(d/864e5)),stale:Number.isFinite(d)&&d>s}}).filter(l=>l.stale).map(({stale:l,...d})=>d),a=new Map;for(let l of r){let d=on(l.title),p=a.get(d)??[];p.push(l),a.set(d,p)}let c=[...a.entries()].filter(([,l])=>l.length>1).map(([l,d])=>({title:l,pages:d.map(p=>p.slug)})),u=n.reviews.filter(l=>l.status==="pending");return{schema:"toolnet.knowledge-quality.v1",totalPages:r.length,automatedPages:r.filter(l=>l.tags.some(d=>d.startsWith("toolnet-auto-"))).length,manualPages:r.filter(l=>!l.tags.some(d=>d.startsWith("toolnet-auto-"))).length,stalePages:i,duplicateTitles:c,pendingReviews:u.length,lowConfidenceReviews:u.filter(l=>l.confidence<n.policy.autoApproveThreshold).length,conflicts:u.filter(l=>l.risk==="conflict").length,generatedAt:new Date().toISOString()}}};var ho="wiki/automation.v1.json",So="toolnet.wiki-automation.v1",cn=8e3,lo=new Set(["raw","rawtext","raw_text","rawtranscript","raw_transcript","transcript","messages","message","payload","prompt","response","assistantmessage","assistant_message","userprompt","user_prompt"]);function Ee(e){return Vc("sha256").update(JSON.stringify(e)).digest("hex")}function Ce(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function po(e){return Array.isArray(e)?e:[]}function ko(e){return typeof e!="string"?void 0:e.replace(/\s+/gu," ").trim()||void 0}function sn(e){return Array.isArray(e)?e.map(ko).filter(t=>!!t):[]}function $(e,t){for(let n of t){let r=ko(e[n]);if(r)return r}}function Oe(e){let t=new Set,n=[];for(let r of e){let o=r.replace(/\s+/gu," ").trim();if(!o)continue;let s=o.normalize("NFKC").toLowerCase();t.has(s)||(t.add(s),n.push(o))}return n}function yt(e,t=0,n=""){if(t>3)return[];let r=n.replace(/[^a-z0-9]/giu,"").toLowerCase();if(lo.has(r))return[];if(typeof e=="string"){let i=e.replace(/\s+/gu," ").trim();return i.length<8?[]:[i]}if(Array.isArray(e))return e.flatMap(i=>yt(i,t+1,n));let o=Ce(e);if(!o)return[];let s=[];for(let[i,a]of Object.entries(o)){let c=i.replace(/[^a-z0-9]/giu,"").toLowerCase();lo.has(c)||s.push(...yt(a,t+1,i))}return s}function fo(e){let n=Oe(["content","summary","text","value","statement","description","decision","task","knowledge","context","outcome","reason","rationale"].flatMap(o=>yt(e[o],0,o)));return(n.length>0?n:Oe(yt(e))).join(`
40
+
41
+ `).slice(0,cn)}function mo(e,t){return $(e,["id","key","fingerprint","knowledgeId","sceneId"])??t}function go(e,t){return $(e,["title","name","topic","label","task","kind","type"])??t}function Xc(e){return($(e,["knowledgeClass","class","classification","scope"])??"").toLowerCase()}function Zc(e){return($(e,["kind","sceneKind","type"])??"").toLowerCase()}function Qc(e){let t=Ce(e);if(!t)return[];let n=[],r=po(t.knowledge);for(let[s,i]of r.entries()){let a=Ce(i);if(!a)continue;let c=Xc(a);if(c==="session"||c==="transient")continue;let u=fo(a);if(u.length<20)continue;let l=mo(a,Ee(a).slice(0,16)),d=go(a,`Durable Memory ${s+1}`);n.push({sourceKey:`memory:${l}`,sourceType:"memory",title:d,summary:$(a,["summary","description"]),content:u,tags:Oe(["toolnet","auto","memory",...c?[c]:[]])})}let o=po(t.scenes);for(let[s,i]of o.entries()){let a=Ce(i);if(!a)continue;let c=Zc(a);if(c==="session-context")continue;let u=fo(a);if(u.length<20)continue;let l=mo(a,Ee(a).slice(0,16)),d=go(a,`Knowledge Scene ${s+1}`);n.push({sourceKey:`scene:${l}`,sourceType:"scene",title:d,summary:$(a,["summary","description"]),content:u,tags:Oe(["toolnet","auto","scene",...c?[c]:[]])})}return n}function eu(e){return yo(e,".toolnet","memory","skills")}function tu(e){let t=eu(e);if(!Bc(t))return{candidates:[],failed:0};let n=[],r=0,o=Gc(t).filter(s=>s.endsWith(".json")).sort();for(let s of o)try{let i=JSON.parse(Uc(yo(t,s),"utf8")),a=Ce(i);if(!a||a.schema!=="toolnet.skill-memory.v1")continue;let c=$(a,["id","fingerprint"])??Yc(s,".json"),u=$(a,["task"])??"",l=$(a,["title"])||u||`Reusable Skill ${c.slice(0,8)}`,d=$(a,["summary"])??void 0,p=sn(a.steps),f=sn(a.verification),m=sn(a.files),S=[];u&&S.push(`## Task
42
+ ${u}`),d&&S.push(`## Summary
43
+ ${d}`),p.length>0&&S.push(`## Procedure
44
+ ${p.map((h,v)=>`${v+1}. ${h}`).join(`
45
+ `)}`),f.length>0&&S.push(`## Verification
46
+ ${f.map(h=>`- ${h}`).join(`
47
+ `)}`),m.length>0&&S.push(`## Relevant Files
48
+ ${m.map(h=>`- \`${h}\``).join(`
49
+ `)}`);let g=S.join(`
50
+
51
+ `).slice(0,cn);if(g.length<20)continue;n.push({sourceKey:`skill:${c}`,sourceType:"skill",title:l,summary:d,content:g,tags:["toolnet","auto","skill","sop"]})}catch{r+=1}return{candidates:n,failed:r}}function an(e){let t=new Date().toISOString();return{schema:So,version:1,projectId:e,entries:[],createdAt:t,updatedAt:t}}async function nu(e,t){let n=await e.getText(ho);if(!n)return an(t);try{let r=JSON.parse(n);return r.schema!==So||r.version!==1||r.projectId!==t||!Array.isArray(r.entries)?an(t):r}catch{return an(t)}}async function ru(e,t){await e.put(ho,JSON.stringify(t,null,2),"application/json")}function ou(e){return`toolnet-auto-${Ee(e).slice(0,12)}`}function su(e){let t=ne(e.title).slice(0,72),n=Ee(e.sourceKey).slice(0,10);return ne(`auto-${e.sourceType}-${t}-${n}`)}function iu(e){return[`> Auto-generated by ToolNet Knowledge Automation from ${e.sourceType==="skill"?"reusable Skill Memory":e.sourceType==="scene"?"semantic memory scene":"durable memory"}.`,"",e.content].join(`
52
+ `).slice(0,cn)}function au(e){return Ee({sourceType:e.sourceType,title:e.title,summary:e.summary,content:e.content,tags:e.tags})}function cu(e,t){return e.tags.includes(t)}async function vo(e){let t=Qc(e.hierarchy),n=tu(e.project.rootPath),r=new Map;for(let f of[...t,...n.candidates])r.set(f.sourceKey,f);let o=[...r.values()].sort((f,m)=>f.sourceKey.localeCompare(m.sourceKey)),s={schema:"toolnet.wiki-automation-result.v1",scanned:t.length+n.candidates.length,eligible:o.length,created:0,updated:0,unchanged:0,skipped:0,failed:n.failed,reviewPending:0,autoApproved:0,reviewApproved:0,pages:[]},i=new pt(new ft(e.storage,e.project));await i.initialize();let a=new gt(new mt(e.storage,e.project));await a.initialize();let c=await nu(e.storage,e.project.id),u=await i.listPages(),l=new Map(u.map(f=>[f.slug,f])),d=new Map(c.entries.map(f=>[f.sourceKey,f]));for(let f of o)try{let m=ou(f.sourceKey),S=au(f),g=d.get(f.sourceKey),h=g?.slug??su(f),v=l.get(h);if(v&&!cu(v,m)){s.skipped+=1;continue}let j=Oe([...f.tags,m]),O=iu(f),C=await a.gate({sourceKey:f.sourceKey,sourceType:f.sourceType,slug:h,marker:m,digest:S,title:f.title,...f.summary?{summary:f.summary}:{},content:O,tags:j},[...l.values()]);if(!C.allowed){C.mode==="pending-review"?s.reviewPending+=1:s.skipped+=1;continue}C.mode==="auto-approved"?s.autoApproved+=1:C.mode==="review-approved"&&(s.reviewApproved+=1),v?g?.digest!==S?(v=await i.updatePage(h,{title:f.title,summary:f.summary??"",content:O,tags:j}),l.set(v.slug,v),s.updated+=1,s.pages.push({sourceKey:f.sourceKey,sourceType:f.sourceType,slug:v.slug,action:"updated"})):(s.unchanged+=1,s.pages.push({sourceKey:f.sourceKey,sourceType:f.sourceType,slug:h,action:"unchanged"})):(v=await i.createPage({slug:h,title:f.title,summary:f.summary,content:O,tags:j}),l.set(v.slug,v),s.created+=1,s.pages.push({sourceKey:f.sourceKey,sourceType:f.sourceType,slug:v.slug,action:"created"}));let T=new Date().toISOString(),I={sourceKey:f.sourceKey,sourceType:f.sourceType,slug:h,digest:S,marker:m,updatedAt:T},b=c.entries.findIndex(W=>W.sourceKey===f.sourceKey);b>=0?c.entries[b]=I:c.entries.push(I),d.set(f.sourceKey,I),await a.markApplied(f.sourceKey,S)}catch(m){if(m instanceof A&&m.statusCode===409){s.skipped+=1;continue}s.failed+=1}let p=new Date().toISOString();return c.updatedAt=p,c.lastRunAt=p,c.entries.sort((f,m)=>f.sourceKey.localeCompare(m.sourceKey)),await ru(e.storage,c),s}import{createHash as uu}from"node:crypto";import{chmodSync as bo,existsSync as lu,mkdirSync as du,readFileSync as ty,readdirSync as ny,renameSync as pu,statSync as ry,writeFileSync as fu}from"node:fs";import{join as xo}from"node:path";var mu="toolnet.skill-memory.v1",wo=5,gu=16,yu=24,hu=32;function Su(e){return uu("sha256").update(e).digest("hex")}function Re(e,t=Number.MAX_SAFE_INTEGER){let n=new Set,r=[];for(let o of e){let s=o.replace(/\s+/gu," ").trim();if(!s)continue;let i=s.normalize("NFKC").toLowerCase();if(!n.has(i)&&(n.add(i),r.push(s),r.length>=t))break}return r}function un(e,t=360){let n=e.replace(/\s+/gu," ").trim();return n.length<=t?n:n.slice(0,Math.max(0,t-1)).trimEnd()+"\u2026"}function ku(e){return e.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/giu,"Bearer [REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/gu,"[REDACTED]").replace(/\b(api[_-]?key|token|password|passwd|secret)\b(\s*[:=]\s*)(["']?)[^\s"'`]+/giu,"$1$2[REDACTED]")}function q(e,t=360){return e&&un(ku(e),t)||void 0}function Ne(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}}function jo(e,t){for(let n of t){let r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()&&Number.isFinite(Number(r)))return Number(r)}}function Io(e,t){for(let n of t){let r=e[n];if(typeof r=="boolean")return r;if(typeof r=="string"){let o=r.trim().toLowerCase();if(["true","yes","pass","passed","success","succeeded","ok"].includes(o))return!0;if(["false","no","fail","failed","error"].includes(o))return!1}}}function Ao(e){let t=e.data??{};if(Io(t,["passed","pass","success","succeeded","ok"])===!1)return!0;let r=jo(t,["exitCode","exit_code","code","statusCode"]);if(r!==void 0&&r!==0)return!0;let o=Ne(t,["status","result","outcome"]);return!!(o&&/\b(fail(?:ed)?|error|broken|cancelled)\b/iu.test(o))}function Te(e){let t=e.data??{};if(Ao(e))return!1;if(Io(t,["passed","pass","success","succeeded","ok"])===!0||jo(t,["exitCode","exit_code","code","statusCode"])===0)return!0;let o=Ne(t,["status","result","outcome"]);return o&&/\b(pass(?:ed)?|success(?:ful)?|succeeded|ok|green|complete(?:d)?)\b/iu.test(o)?!0:e.type==="commit"||e.type==="deploy"}function Po(e){let t=e.data??{},n=Ne(t,["path","file","filePath","filename","target"]);if(n)return q(n,260);let r=e.provenance?.files;return q(r?.[0],260)}function ln(e){return q(Ne(e.data??{},["command","cmd","script"]),420)}function de(e){return q(Ne(e.data??{},["name","test","suite","title","message","text","result","status"]),300)}function vu(e){let t=[];for(let n of[...e].sort((r,o)=>r.sequence-o.sequence))if(Te(n)){if(n.type==="test"){let r=de(n)??ln(n)??"Tests passed";t.push(`Test passed: ${r}`);continue}if(n.type==="commit"){let r=de(n);t.push(r?`Commit: ${r}`:"Commit completed");continue}if(n.type==="deploy"){let r=de(n);t.push(r?`Deploy: ${r}`:"Deployment completed")}}return Re(t,10)}function wu(e,t){let n=[];for(let r of[...e].sort((o,s)=>o.sequence-s.sequence))switch(r.type){case"file_write":case"file_edit":{let o=Po(r);o&&n.push(`Update ${o}`);break}case"command":{if(Ao(r))break;let o=ln(r);o&&n.push(`Run: ${o}`);break}case"test":{if(!Te(r))break;let o=de(r)??ln(r)??"project tests";n.push(`Verify: ${o}`);break}case"commit":{if(!Te(r))break;let o=de(r);n.push(o?`Commit: ${o}`:"Commit verified changes");break}case"deploy":{if(!Te(r))break;let o=de(r);n.push(o?`Deploy: ${o}`:"Deploy verified build");break}default:break}if(n.length===0)for(let r of t.files.slice(0,8)){let o=q(r,260);o&&n.push(`Update ${o}`)}return Re(n,gu)}function bu(e,t){let n=[...t.files];for(let r of e){let o=Po(r);o&&n.push(o);for(let s of r.provenance?.files??[]){let i=q(s,260);i&&n.push(i)}}return Re(n,yu)}function xu(e){return Re(e.filter(t=>["file_write","file_edit","command","test","commit","deploy"].includes(t.type)).map(t=>t.id),hu)}function ju(e){return e.map(n=>n.timestamp).filter(Boolean).sort().at(-1)??new Date(0).toISOString()}function Mo(e,t,n){if(t.length===0)return[];let r=vu(t),o=Re(n.completed.map(m=>q(m,280)??""),wo);if(!(o.length>0||t.some(m=>["test","commit","deploy"].includes(m.type)&&Te(m))))return[];let i=q(n.task,280)??q(n.nextActions[0],280),a=o.length>0?o:i?[i]:[];if(a.length===0)return[];let c=wu(t,n);if(c.length===0)return[];let u=bu(t,n),l=xu(t),d=Math.min(...t.map(m=>m.sequence)),p=Math.max(...t.map(m=>m.sequence)),f=ju(t);return a.slice(0,wo).map(m=>{let S=[`Reusable procedure learned from successful task: ${m}.`,u.length>0?`Files: ${u.slice(0,6).join(", ")}.`:"",r.length>0?`Verification: ${r.slice(0,4).join("; ")}.`:""].filter(Boolean),g=JSON.stringify({projectId:e.projectId,task:m,steps:c,verification:r,files:u}),h=Su(g);return{schema:mu,version:1,id:`skill-${h.slice(0,24)}`,fingerprint:h,projectId:e.projectId,title:un(`SOP: ${m}`,180),task:m,summary:un(S.join(" "),900),steps:c,verification:r,files:u,source:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,firstSequence:d,lastSequence:p,eventIds:l},createdAt:f}})}function Iu(e){return xo(e.rootPath,".toolnet","memory","skills")}function Au(e){let t=Iu(e);return du(t,{recursive:!0,mode:448}),bo(t,448),t}function Co(e,t){if(t.length===0)return{written:0,deduped:0,files:[]};let n=Au(e),r=0,o=0,s=[];for(let i of t){if(i.projectId!==e.id)throw new Error(`Skill project mismatch: ${i.projectId} != ${e.id}`);let a=xo(n,`${i.id}.json`);if(s.push(a),lu(a)){o+=1;continue}let c=`${a}.${process.pid}.${Date.now()}.tmp`;fu(c,JSON.stringify(i,null,2)+`
53
+ `,{encoding:"utf8",mode:384}),pu(c,a),bo(a,384),r+=1}return{written:r,deduped:o,files:s}}function Eo(e){return String(e).padStart(12,"0")}function Pu(e){return`projects/${e.projectId}/memory/learned`}var ht=class{constructor(t){this.storage=t}storage;async write(t,n,r){if(r.length===0||n.length===0)return null;let o=Math.min(...n.map(d=>d.sequence)),s=Math.max(...n.map(d=>d.sequence)),i={version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,createdAt:new Date().toISOString(),firstSequence:o,lastSequence:s,candidateCount:r.length,candidates:r},a=JSON.stringify(i,null,2)+`
54
+ `,c=w(r.map(d=>d.fingerprint).sort().join("|")).slice(0,16),u=w(t.sessionKey).slice(0,12),l=[Pu(t),"batches",`${Eo(o)}-${Eo(s)}-${u}-${c}.json`].join("/");return await this.storage.exists(l)||await this.storage.put(l,a,"application/json"),l}};import{createHash as Mu}from"node:crypto";function Oo(e){return String(e).padStart(12,"0")}function To(e){return Mu("sha256").update(e).digest("hex")}function Cu(e){return`projects/${e.projectId}/memory/hierarchy`}var St=class{constructor(t){this.storage=t}storage;async write(t,n,r){if(n.length===0||r.facts.length===0)return null;let o=Math.min(...n.map(l=>l.sequence)),s=Math.max(...n.map(l=>l.sequence)),i={schema:"toolnet.memory-hierarchy-batch.v1",version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,createdAt:new Date().toISOString(),firstSequence:o,lastSequence:s,hierarchy:r},a=To([...r.facts.map(l=>l.id),...r.knowledge.map(l=>l.id)].sort().join("|")).slice(0,16),c=To(t.sessionKey).slice(0,12),u=[Cu(t),"batches",`${Oo(o)}-${Oo(s)}-${c}-${a}.json`].join("/");return await this.storage.exists(u)||await this.storage.put(u,`${JSON.stringify(i,null,2)}
55
+ `,"application/json"),u}};function _u(e,t){if(!Ou(e))return{events:[],nextOffset:t};let n=Nu(e).size,r=Number.isFinite(t)?Math.max(0,t):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let o=n-r,s=Buffer.alloc(o),i=Tu(e,"r");try{Ru(i,s,0,o,r)}finally{Eu(i)}let a=s.toString("utf8"),c=a.lastIndexOf(`
56
56
  `);if(c<0)return{events:[],nextOffset:r};let u=a.slice(0,c+1);return{events:u.split(`
57
- `).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var ct=class{constructor(t){this.options=t;this.journal=new it(t.storage),this.hierarchyJournal=new at(t.storage)}options;journal;hierarchyJournal;async learnNew(){let t=this.options.wal.loadState(),n=Number(t.sourceCursors["memory.learner.offset"]??0),r=Number.isFinite(n)?n:0,o=Zc(this.options.wal.eventsFile,r);if(o.events.length===0)return{scannedEvents:0,candidates:0,journalWritten:!1,nextOffset:o.nextOffset};let s=et(this.options.identity,o.events),i=s.candidates,a=!1;i.length>0&&(a=!!await this.journal.write(this.options.identity,o.events,i));let c=!1;s.hierarchy.facts.length>0&&(c=!!await this.hierarchyJournal.write(this.options.identity,o.events,s.hierarchy));let u=io(this.options.identity,o.events,s.state),d=ao(this.options.project,u);this.options.wal.setSourceCursor("memory.pipeline.version",2),this.options.wal.setSourceCursor("memory.pipeline.normalized_events",s.stats.normalizedEvents),this.options.wal.setSourceCursor("memory.pipeline.persisted",s.stats.persistedCandidates),this.options.wal.setSourceCursor("memory.pipeline.permanent",s.stats.permanent),this.options.wal.setSourceCursor("memory.pipeline.task",s.stats.task),this.options.wal.setSourceCursor("memory.pipeline.session",s.stats.session),this.options.wal.setSourceCursor("memory.pipeline.transient",s.stats.transient),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.version",s.hierarchy.version),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.raw",s.hierarchy.stats.raw),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.facts",s.hierarchy.stats.facts),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.scenes",s.hierarchy.stats.scenes),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.knowledge",s.hierarchy.stats.knowledge),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.journal_written",c?1:0),this.options.wal.setSourceCursor("memory.skill.assets",u.length),this.options.wal.setSourceCursor("memory.skill.written",d.written),this.options.wal.setSourceCursor("memory.skill.deduped",d.deduped);try{let l=vn(this.options.project.rootPath,o.events);this.options.wal.setSourceCursor("memory.context_offload.eligible",l.eligible),this.options.wal.setSourceCursor("memory.context_offload.written",l.written),this.options.wal.setSourceCursor("memory.context_offload.deduped",l.deduped),this.options.wal.setSourceCursor("memory.context_offload.graph_nodes",l.graphNodes),this.options.wal.setSourceCursor("memory.context_offload.failed",0)}catch{this.options.wal.setSourceCursor("memory.context_offload.failed",1)}try{let l=await Qr({project:this.options.project,storage:this.options.storage,hierarchy:s.hierarchy});this.options.wal.setSourceCursor("memory.wiki_automation.scanned",l.scanned),this.options.wal.setSourceCursor("memory.wiki_automation.eligible",l.eligible),this.options.wal.setSourceCursor("memory.wiki_automation.created",l.created),this.options.wal.setSourceCursor("memory.wiki_automation.updated",l.updated),this.options.wal.setSourceCursor("memory.wiki_automation.unchanged",l.unchanged),this.options.wal.setSourceCursor("memory.wiki_automation.skipped",l.skipped),this.options.wal.setSourceCursor("memory.wiki_automation.failed",l.failed),this.options.wal.setSourceCursor("memory.wiki_automation.review_pending",l.reviewPending),this.options.wal.setSourceCursor("memory.wiki_automation.auto_approved",l.autoApproved),this.options.wal.setSourceCursor("memory.wiki_automation.review_approved",l.reviewApproved)}catch{this.options.wal.setSourceCursor("memory.wiki_automation.failed",1)}return this.options.wal.setSourceCursor("memory.learner.offset",o.nextOffset),{scannedEvents:o.events.length,candidates:i.length,journalWritten:a,nextOffset:o.nextOffset}}};import{closeSync as yu,existsSync as hu,openSync as Su,readSync as ku,statSync as vu}from"node:fs";function po(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Oe(e){return e.toLowerCase().replace(/[^a-z0-9]/gu,"")}function Ee(e,t,n=0){if(n>8)return;if(Array.isArray(e)){for(let o of e.slice(0,50))Ee(o,t,n+1);return}let r=po(e);if(r)for(let[o,s]of Object.entries(r))t(o,s,r),Ee(s,t,n+1)}function ce(e,t){let n=[];return Ee(e,(r,o)=>{t.has(Oe(r))&&typeof o=="string"&&o.trim()&&n.push(o.trim())}),n}function eu(e){let t=e.trim();if(!t.startsWith("{"))return null;try{return po(JSON.parse(t))}catch{return null}}function tu(e){let t=e.data;for(let r of["tool","toolName","tool_name"]){let o=t[r];if(typeof o=="string"&&o.trim())return o.trim().toLowerCase()}let n="";return Ee(t,(r,o,s)=>{if(n)return;let i=Oe(r);if(["tool","toolname"].includes(i)&&typeof o=="string"){n=o.trim().toLowerCase();return}if(i!=="name"||typeof o!="string")return;let a=typeof s.type=="string"?s.type.toLowerCase():"";(a.includes("tool")||a.includes("function")||a.includes("command"))&&(n=o.trim().toLowerCase())}),n}function nu(e){let t=ce(e.data,new Set(["command","cmd","script"])),n=ce(e.data,new Set(["arguments","args"]));for(let r of n){let o=eu(r);if(o)for(let s of ce(o,new Set(["command","cmd","script"])))t.push(s)}return Array.from(new Set(t.map(r=>r.trim()).filter(Boolean)))}function ru(e){let t=ce(e.data,new Set(["filepath","file_path","filename","file","path","target"].map(Oe)));return Array.from(new Set(t.map(n=>n.trim()).filter(n=>n.length>0&&n.length<1e3&&!n.includes(`
58
- `))))}function ou(e,t){return e.type==="file_edit"||e.type==="file_write"?"modified":/\b(delete|remove|unlink)\b/iu.test(t)?"deleted":/\b(create|add[_-]?file|new[_-]?file)\b/iu.test(t)?"created":/\b(edit|write|patch|apply[_-]?patch|replace|update[_-]?file)\b/iu.test(t)?"modified":null}function su(e){let t=ce(e.data,new Set(["patch","diff","arguments","input"].map(Oe))),n=[];for(let r of t){let o=[{regex:/^\*\*\* Update File:\s*(.+)$/gimu,action:"modified"},{regex:/^\*\*\* Add File:\s*(.+)$/gimu,action:"created"},{regex:/^\*\*\* Delete File:\s*(.+)$/gimu,action:"deleted"}];for(let s of o)for(let i of r.matchAll(s.regex)){let a=i[1]?.trim();a&&n.push({kind:"file",text:a,fileAction:s.action,confidence:.99})}}return n}function iu(e){let t=e.toLowerCase();return/\b(typecheck|type-check)\b/u.test(t)||/\btsc\b[\s\S]*--noemit\b/u.test(t)?"typecheck":/\b(eslint|lint)\b/u.test(t)?"lint":/\b(vitest|jest|pytest)\b/u.test(t)||/\bgo\s+test\b/u.test(t)||/\bcargo\s+test\b/u.test(t)||/\b(npm|pnpm|yarn)\s+(run\s+)?test\b/u.test(t)?"test":/\b(npm|pnpm|yarn)\s+(run\s+)?build\b/u.test(t)||/\bcargo\s+build\b/u.test(t)||/\bgo\s+build\b/u.test(t)||/\btsc\b/u.test(t)?"build":null}function au(e){let t=null;return Ee(e,(n,r)=>{if(t===null&&["exitcode","code"].includes(Oe(n))){if(typeof r=="number"&&Number.isFinite(r)){t=r;return}if(typeof r=="string"){let o=Number(r);Number.isFinite(o)&&(t=o)}}}),t}function cu(e){return ce(e,new Set(["status","state","result","output","outputsummary","message","text"]))}function uu(e){let t=au(e.data);if(t!==null)return t===0?"passed":"failed";let n=cu(e.data).join(`
59
- `).toLowerCase();return/\b(error|failed|failure|failing)\b/u.test(n)&&!/\b0\s+failed\b/u.test(n)?"failed":/\b(success|successful|completed|passed|green)\b/u.test(n)||/\b\d+\s+passed\b/u.test(n)?"passed":/\b(running|started|in[_ -]?progress)\b/u.test(n)?"running":"unknown"}function lu(e){let t=[],n=new Set;for(let r of e){let o=[r.kind,r.fileAction??"",r.checkKind??"",r.checkStatus??"",r.text].join("|");n.has(o)||(n.add(o),t.push(r))}return t}function fo(e){let t=[],n=tu(e),r=ou(e,n);if(r)for(let o of ru(e))t.push({kind:"file",text:o,fileAction:r,confidence:e.type==="file_edit"||e.type==="file_write"?1:.96});t.push(...su(e));for(let o of nu(e)){t.push({kind:"command",text:o,confidence:.98});let s=iu(o);s&&t.push({kind:"test",text:o,checkKind:s,checkStatus:uu(e),confidence:.98})}return lu(t)}var du=new Set(["content","text","message","prompt","summary","description","title","reason","last_assistant_message","lastAssistantMessage"]);function te(e){return e.normalize("NFKC").replace(/\s+/g," ").replace(/^[\s>*#•-]+/u,"").trim()}function go(e){return te(e).toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function ee(e,t,n=0){if(!(n>6)){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let r of e.slice(0,50))ee(r,t,n+1);return}if(!(!e||typeof e!="object"))for(let[r,o]of Object.entries(e))(du.has(r)||["data","payload","parts","messages"].includes(r))&&ee(o,t,n+1)}}function ut(e){return/\b(cancelled|canceled)\b|đã hủy|bỏ qua/iu.test(e)?"cancelled":/\b(blocked|blocker)\b|đang vướng|bị vướng|đang kẹt|chưa thể/iu.test(e)?"blocked":/\b(completed|complete|done|finished|passed)\b|hoàn thành|hoàn tất|đã xong|đã làm xong|\bxong\b/iu.test(e)?"completed":/\bin[\s_-]*progress\b|working on|đang làm|đang thực hiện|đang xử lý|đang triển khai/iu.test(e)?"in_progress":"pending"}function mo(e){let t=te(e);return/^(?:đang\s+làm|đang\s+thực\s+hiện|đang\s+xử\s+lý|đang\s+triển\s+khai|hoàn\s+thành|hoàn\s+tất|đã\s+xong|đã\s+làm\s+xong|xong|pending|in[\s_-]*progress|completed|complete|done|finished|blocked|cancelled|canceled)[.!]*$/iu.test(t)}function I(e,t,n,r,o={}){let s=te(r),i=o.key??go(s);return{version:1,id:v([e.projectId,n,i,t.id,s,o.status??"",o.fileAction??"",o.checkKind??"",o.checkStatus??"",o.order??""].join("|")).slice(0,32),projectId:e.projectId,kind:n,key:i,text:s,status:o.status,fileAction:o.fileAction,checkKind:o.checkKind,checkStatus:o.checkStatus,order:o.order,confidence:o.confidence??.85,occurredAt:t.timestamp,sequence:t.sequence,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,eventId:t.id,sourceEventId:t.sourceEventId}}function pu(e,t,n){let r=te(n);if(r.length<5||r.length>1200)return[];let o=[],s=/^(?:next|next action|next step|tiếp theo|bước tiếp theo|cần làm tiếp)\b/iu.test(r),i=r.match(/^(?:mục tiêu|goal|objective)\s*(?::|-)\s*(.+)$/iu);i?.[1]&&o.push(I(e,t,"goal",i[1],{confidence:.97}));let a=r.match(/^(?:kế hoạch|plan)\s*(?::|-)\s*(.+)$/iu);a?.[1]&&o.push(I(e,t,"plan",a[1],{confidence:.95}));let c=/\b(?:phase|giai đoạn|giai doan|stage)\s*(\d+)\s*(?:[:\-–—]\s*)?([^.;\n]{0,220})/giu,u;for(;!s&&(u=c.exec(r));){let f=Number(u[1]),p=te(u[2]??""),g=p&&!mo(p)?`Phase ${f} - ${p}`:`Phase ${f}`;o.push(I(e,t,"phase",g,{key:`phase:${f}`,order:f,status:ut(r),confidence:.93}))}let d=n.match(/^\s*[-*]\s*\[([ xX])\]\s*(.+)$/u);d?.[2]&&o.push(I(e,t,"task",d[2],{status:d[1].trim()?"completed":ut(d[2]),confidence:.96}));let l=r.match(/^(?:todo|task|việc)\s*(\d+)?(?:\s*[:.\-–—]\s*|\s+)(.+)$/iu);if(l?.[2]){let f=l[1]?Number(l[1]):void 0,p=te(l[2]),g=mo(p);o.push(I(e,t,"task",g&&f!==void 0?`TODO ${f}`:p,{key:f!==void 0?`task:${f}`:go(p),order:f,status:ut(r),confidence:.93}))}if(/^(?:next|next action|next step|tiếp theo|bước tiếp theo|cần làm tiếp)\b/iu.test(r)){let f=r.replace(/^(?:next|next action|next step|tiếp theo|bước tiếp theo|cần làm tiếp)\s*(?::|-)?\s*/iu,"");f&&o.push(I(e,t,"next_action",f,{confidence:.9}))}return/\b(blocker|blocked)\b|đang vướng|bị vướng|đang kẹt/iu.test(r)&&o.push(I(e,t,"blocker",r,{confidence:.9})),/\b(chú ý|lưu ý|warning|attention|cẩn thận)\b/iu.test(r)&&o.push(I(e,t,"warning",r,{confidence:.88})),/\b(chốt|quyết định|decided|decision)\b/iu.test(r)&&o.push(I(e,t,"decision",r,{confidence:.9})),r.length<=300&&/^(?:đang\s+(?:sửa|cập nhật|triển khai|xử lý|làm|refactor|fix)|(?:i(?:'m| am)\s+)?(?:working on|implementing|fixing|refactoring|updating|editing)\b)/iu.test(r)&&o.push(I(e,t,"activity",r,{confidence:.86})),o}function lt(e,t){if(t.length===0)return[];let n=[],r=new Set;function o(i){r.has(i.id)||(r.add(i.id),n.push(i))}for(let i of t){if(i.type==="user_prompt"||i.role==="user"){let c=[];ee(i.data,c);let u=c.map(d=>te(d)).find(d=>d.length>=8&&d.length<=1200&&!/^\[?toolnet\b/iu.test(d));u&&o(I(e,i,"request",u,{confidence:.96}))}for(let c of fo(i))o(I(e,i,c.kind,c.text,{fileAction:c.fileAction,checkKind:c.checkKind,checkStatus:c.checkStatus,status:c.kind==="test"?c.checkStatus==="passed"?"completed":c.checkStatus==="failed"?"blocked":c.checkStatus==="running"?"in_progress":"pending":void 0,confidence:c.confidence}));if(i.type==="decision"){let c=[];ee(i.data,c);for(let u of c)o(I(e,i,"decision",u,{confidence:1}))}if(i.type==="todo"){let c=[];ee(i.data,c);for(let u of c)o(I(e,i,"task",u,{status:ut(u),confidence:1}))}if(["file_write","file_edit"].includes(i.type))for(let c of["filePath","path","file"]){let u=i.data[c];typeof u=="string"&&u&&o(I(e,i,"file",u,{fileAction:"modified",confidence:1}))}if(i.type==="test"){let c=[];ee(i.data,c);for(let u of c)o(I(e,i,"test",u,{confidence:1}))}let a=[];ee(i.data,a);for(let c of a)for(let u of c.split(/\n+/u))for(let d of pu(e,i,u))o(d)}let s=t[t.length-1];return o(I(e,s,"session",`${e.agent}:${e.nativeSessionId}`,{key:e.sessionKey,confidence:1})),n}function yo(e){return String(e).padStart(12,"0")}var dt=class{constructor(t){this.storage=t}storage;async write(t,n){if(n.length===0)return null;let r=Math.min(...n.map(d=>d.sequence)),o=Math.max(...n.map(d=>d.sequence)),s={version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,createdAt:n.map(d=>d.occurredAt).sort().at(-1)??new Date().toISOString(),firstSequence:r,lastSequence:o,observations:n},i=JSON.stringify(s,null,2)+`
60
- `,a=v(n.map(d=>JSON.stringify(d)).sort().join(`
61
- `)).slice(0,24),c=v(t.sessionKey).slice(0,12),u=[`projects/${t.projectId}`,"work","observations",`${yo(r)}-${yo(o)}-${c}-${a}.json`].join("/");return await this.storage.put(u,i,"application/json"),u}};import{join as ho}from"node:path";import{mkdirSync as fu}from"node:fs";function ko(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function $(e,t=20){let n=[],r=new Set;for(let o of e.slice().reverse()){let s=ko(o);if(!(!s||r.has(s))&&(r.add(s),n.push(o),n.length>=t))break}return n.reverse()}function mu(e,t=20){let n=new Map;for(let r of e){let o=`${r.kind}|${ko(r.command)}`;n.delete(o),n.set(o,r)}return Array.from(n.values()).slice(-t)}function gu(e){return e.kind==="phase"?/^Phase\s+\d+$/iu.test(e.text):e.kind==="task"?/^(?:TODO|Task|Việc)\s+\d+$/iu.test(e.text):!1}function So(e,t){let n=t.status??e?.status??"pending",r=n;e&&(e.status==="completed"&&n!=="completed"?r="completed":n==="pending"&&(e.status==="in_progress"||e.status==="blocked")&&(r=e.status));let o=e&&gu(t)?e.title:t.text;return{id:e?.id??v(t.key).slice(0,24),title:o,status:r,order:t.order??e?.order,confidence:Math.max(t.confidence,e?.confidence??0),updatedAt:t.occurredAt,updatedBy:{agent:t.agent,nativeSessionId:t.nativeSessionId,eventId:t.eventId}}}async function vo(e,t){let n=`projects/${e.id}/work/observations/`,r=await t.list(n),o=[];for(let s of r.filter(i=>i.key.endsWith(".json")).sort((i,a)=>i.key.localeCompare(a.key))){let i=await t.getText(s.key);if(i)try{let a=JSON.parse(i);a.version===1&&Array.isArray(a.observations)&&o.push(a)}catch{}}return o}async function Te(e,t){let r=(await vo(e,t)).flatMap(m=>m.observations).sort((m,b)=>{let q=m.occurredAt.localeCompare(b.occurredAt);if(q!==0)return q;let pn=m.sequence-b.sequence;return pn!==0?pn:m.id.localeCompare(b.id)}),o=new Map,s=new Map,i,a,c,u,d,l=[],f=[],p=[],g=[],S=[],y=new Map,h=[],k=[],M=[],E=[],C=[],O=[];for(let m of r)switch(m.kind){case"request":i=m.text;break;case"activity":a=m.text;break;case"goal":c=m.text;break;case"plan":u=m.text;break;case"phase":o.set(m.key,So(o.get(m.key),m));break;case"task":s.set(m.key,So(s.get(m.key),m));break;case"decision":l.push(m.text);break;case"blocker":f.push(m.text);break;case"warning":p.push(m.text);break;case"next_action":g.push(m.text);break;case"file":{S.push(m.text);let b=m.fileAction??"active";y.delete(m.text),y.set(m.text,b),b==="modified"?h.push(m.text):b==="created"?k.push(m.text):b==="deleted"&&M.push(m.text);break}case"command":E.push(m.text);break;case"test":C.push(m.text),m.checkKind&&O.push({kind:m.checkKind,command:m.text,status:m.checkStatus??"unknown",updatedAt:m.occurredAt,agent:m.agent,nativeSessionId:m.nativeSessionId});break;case"session":d={agent:m.agent,nativeSessionId:m.nativeSessionId,sessionKey:m.sessionKey,updatedAt:m.occurredAt};break}let x=Array.from(o.values()).sort((m,b)=>(m.order??Number.MAX_SAFE_INTEGER)-(b.order??Number.MAX_SAFE_INTEGER)),w=Array.from(s.values()).sort((m,b)=>(m.order??Number.MAX_SAFE_INTEGER)-(b.order??Number.MAX_SAFE_INTEGER)),W=x.find(m=>m.status==="in_progress")??x.find(m=>m.status==="blocked")??x.find(m=>m.status==="pending"),D=w.find(m=>m.status==="in_progress")??w.find(m=>m.status==="blocked")??w.find(m=>m.status==="pending"),bt=$([...g,...D?[D.title]:[],...!D&&W?[W.title]:[],...w.filter(m=>m.status==="pending").slice(0,5).map(m=>m.title)],8),xt=$([...f,...x.filter(m=>m.status==="blocked").map(m=>m.title),...w.filter(m=>m.status==="blocked").map(m=>m.title)],20),le={version:1,projectId:e.id,projectName:e.name,currentRequest:i,currentActivity:a,goal:c,plan:u,phases:x,tasks:w,decisions:$(l,20),blockers:xt,warnings:$(p,20),nextActions:bt,filesTouched:$(S,30),activeFiles:Array.from(y.entries()).filter(([,m])=>m!=="deleted").map(([m])=>m).slice(-5),modifiedFiles:$(h,30),createdFiles:$(k,30),deletedFiles:$(M,30),commands:$(E,20),tests:$(C,20),checks:mu(O,20),currentPhase:W,currentTask:D,progress:{phasesTotal:x.length,phasesCompleted:x.filter(m=>m.status==="completed").length,tasksTotal:w.length,tasksCompleted:w.filter(m=>m.status==="completed").length,blocked:x.filter(m=>m.status==="blocked").length+w.filter(m=>m.status==="blocked").length},lastSession:d,updatedAt:r.length?r[r.length-1].occurredAt:new Date().toISOString()},de=ho(e.rootPath,".toolnet","work");return fu(de,{recursive:!0}),T(ho(de,"current.json"),le),await t.put(`projects/${e.id}/work/current.json`,JSON.stringify(le,null,2)+`
62
- `,"application/json"),le}async function wo(e,t){if((await vo(e,t)).length>0)return Te(e,t);let r=await t.getText(`projects/${e.id}/work/current.json`);if(!r)return null;try{return JSON.parse(r)}catch{return null}}function wu(e,t){if(!hu(e))return{events:[],nextOffset:t};let n=vu(e).size,r=Number.isFinite(t)?Math.max(0,t):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let o=n-r,s=Buffer.alloc(o),i=Su(e,"r");try{ku(i,s,0,o,r)}finally{yu(i)}let a=s.toString("utf8"),c=a.lastIndexOf(`
57
+ `).filter(Boolean).flatMap(d=>{try{return[JSON.parse(d)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var kt=class{constructor(t){this.options=t;this.journal=new ht(t.storage),this.hierarchyJournal=new St(t.storage)}options;journal;hierarchyJournal;async learnNew(){let t=this.options.wal.loadState(),n=Number(t.sourceCursors["memory.learner.offset"]??0),r=Number.isFinite(n)?n:0,o=_u(this.options.wal.eventsFile,r);if(o.events.length===0)return{scannedEvents:0,candidates:0,journalWritten:!1,nextOffset:o.nextOffset};let s=dt(this.options.identity,o.events),i=s.candidates,a=!1;i.length>0&&(a=!!await this.journal.write(this.options.identity,o.events,i));let c=!1;s.hierarchy.facts.length>0&&(c=!!await this.hierarchyJournal.write(this.options.identity,o.events,s.hierarchy));let u=Mo(this.options.identity,o.events,s.state),l=Co(this.options.project,u);this.options.wal.setSourceCursor("memory.pipeline.version",2),this.options.wal.setSourceCursor("memory.pipeline.normalized_events",s.stats.normalizedEvents),this.options.wal.setSourceCursor("memory.pipeline.persisted",s.stats.persistedCandidates),this.options.wal.setSourceCursor("memory.pipeline.permanent",s.stats.permanent),this.options.wal.setSourceCursor("memory.pipeline.task",s.stats.task),this.options.wal.setSourceCursor("memory.pipeline.session",s.stats.session),this.options.wal.setSourceCursor("memory.pipeline.transient",s.stats.transient),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.version",s.hierarchy.version),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.raw",s.hierarchy.stats.raw),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.facts",s.hierarchy.stats.facts),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.scenes",s.hierarchy.stats.scenes),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.knowledge",s.hierarchy.stats.knowledge),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.journal_written",c?1:0),this.options.wal.setSourceCursor("memory.skill.assets",u.length),this.options.wal.setSourceCursor("memory.skill.written",l.written),this.options.wal.setSourceCursor("memory.skill.deduped",l.deduped);try{let d=Rn(this.options.project.rootPath,o.events);this.options.wal.setSourceCursor("memory.context_offload.eligible",d.eligible),this.options.wal.setSourceCursor("memory.context_offload.written",d.written),this.options.wal.setSourceCursor("memory.context_offload.deduped",d.deduped),this.options.wal.setSourceCursor("memory.context_offload.graph_nodes",d.graphNodes),this.options.wal.setSourceCursor("memory.context_offload.failed",0)}catch{this.options.wal.setSourceCursor("memory.context_offload.failed",1)}try{let d=await vo({project:this.options.project,storage:this.options.storage,hierarchy:s.hierarchy});this.options.wal.setSourceCursor("memory.wiki_automation.scanned",d.scanned),this.options.wal.setSourceCursor("memory.wiki_automation.eligible",d.eligible),this.options.wal.setSourceCursor("memory.wiki_automation.created",d.created),this.options.wal.setSourceCursor("memory.wiki_automation.updated",d.updated),this.options.wal.setSourceCursor("memory.wiki_automation.unchanged",d.unchanged),this.options.wal.setSourceCursor("memory.wiki_automation.skipped",d.skipped),this.options.wal.setSourceCursor("memory.wiki_automation.failed",d.failed),this.options.wal.setSourceCursor("memory.wiki_automation.review_pending",d.reviewPending),this.options.wal.setSourceCursor("memory.wiki_automation.auto_approved",d.autoApproved),this.options.wal.setSourceCursor("memory.wiki_automation.review_approved",d.reviewApproved)}catch{this.options.wal.setSourceCursor("memory.wiki_automation.failed",1)}return this.options.wal.setSourceCursor("memory.learner.offset",o.nextOffset),{scannedEvents:o.events.length,candidates:i.length,journalWritten:a,nextOffset:o.nextOffset}}};import{closeSync as Zu,existsSync as Qu,openSync as el,readSync as tl,statSync as nl}from"node:fs";function Ro(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ke(e){return e.toLowerCase().replace(/[^a-z0-9]/gu,"")}function _e(e,t,n=0){if(n>8)return;if(Array.isArray(e)){for(let o of e.slice(0,50))_e(o,t,n+1);return}let r=Ro(e);if(r)for(let[o,s]of Object.entries(r))t(o,s,r),_e(s,t,n+1)}function pe(e,t){let n=[];return _e(e,(r,o)=>{t.has(Ke(r))&&typeof o=="string"&&o.trim()&&n.push(o.trim())}),n}function Ku(e){let t=e.trim();if(!t.startsWith("{"))return null;try{return Ro(JSON.parse(t))}catch{return null}}function $u(e){let t=e.data;for(let r of["tool","toolName","tool_name"]){let o=t[r];if(typeof o=="string"&&o.trim())return o.trim().toLowerCase()}let n="";return _e(t,(r,o,s)=>{if(n)return;let i=Ke(r);if(["tool","toolname"].includes(i)&&typeof o=="string"){n=o.trim().toLowerCase();return}if(i!=="name"||typeof o!="string")return;let a=typeof s.type=="string"?s.type.toLowerCase():"";(a.includes("tool")||a.includes("function")||a.includes("command"))&&(n=o.trim().toLowerCase())}),n}function Lu(e){let t=pe(e.data,new Set(["command","cmd","script"])),n=pe(e.data,new Set(["arguments","args"]));for(let r of n){let o=Ku(r);if(o)for(let s of pe(o,new Set(["command","cmd","script"])))t.push(s)}return Array.from(new Set(t.map(r=>r.trim()).filter(Boolean)))}function Fu(e){let t=pe(e.data,new Set(["filepath","file_path","filename","file","path","target"].map(Ke)));return Array.from(new Set(t.map(n=>n.trim()).filter(n=>n.length>0&&n.length<1e3&&!n.includes(`
58
+ `))))}function Du(e,t){return e.type==="file_edit"||e.type==="file_write"?"modified":/\b(delete|remove|unlink)\b/iu.test(t)?"deleted":/\b(create|add[_-]?file|new[_-]?file)\b/iu.test(t)?"created":/\b(edit|write|patch|apply[_-]?patch|replace|update[_-]?file)\b/iu.test(t)?"modified":null}function Wu(e){let t=pe(e.data,new Set(["patch","diff","arguments","input"].map(Ke))),n=[];for(let r of t){let o=[{regex:/^\*\*\* Update File:\s*(.+)$/gimu,action:"modified"},{regex:/^\*\*\* Add File:\s*(.+)$/gimu,action:"created"},{regex:/^\*\*\* Delete File:\s*(.+)$/gimu,action:"deleted"}];for(let s of o)for(let i of r.matchAll(s.regex)){let a=i[1]?.trim();a&&n.push({kind:"file",text:a,fileAction:s.action,confidence:.99})}}return n}function zu(e){let t=e.toLowerCase();return/\b(typecheck|type-check)\b/u.test(t)||/\btsc\b[\s\S]*--noemit\b/u.test(t)?"typecheck":/\b(eslint|lint)\b/u.test(t)?"lint":/\b(vitest|jest|pytest)\b/u.test(t)||/\bgo\s+test\b/u.test(t)||/\bcargo\s+test\b/u.test(t)||/\b(npm|pnpm|yarn)\s+(run\s+)?test\b/u.test(t)?"test":/\b(npm|pnpm|yarn)\s+(run\s+)?build\b/u.test(t)||/\bcargo\s+build\b/u.test(t)||/\bgo\s+build\b/u.test(t)||/\btsc\b/u.test(t)?"build":null}function qu(e){let t=null;return _e(e,(n,r)=>{if(t===null&&["exitcode","code"].includes(Ke(n))){if(typeof r=="number"&&Number.isFinite(r)){t=r;return}if(typeof r=="string"){let o=Number(r);Number.isFinite(o)&&(t=o)}}}),t}function Hu(e){return pe(e,new Set(["status","state","result","output","outputsummary","message","text"]))}function Ju(e){let t=qu(e.data);if(t!==null)return t===0?"passed":"failed";let n=Hu(e.data).join(`
59
+ `).toLowerCase();return/\b(error|failed|failure|failing)\b/u.test(n)&&!/\b0\s+failed\b/u.test(n)?"failed":/\b(success|successful|completed|passed|green)\b/u.test(n)||/\b\d+\s+passed\b/u.test(n)?"passed":/\b(running|started|in[_ -]?progress)\b/u.test(n)?"running":"unknown"}function Vu(e){let t=[],n=new Set;for(let r of e){let o=[r.kind,r.fileAction??"",r.checkKind??"",r.checkStatus??"",r.text].join("|");n.has(o)||(n.add(o),t.push(r))}return t}function No(e){let t=[],n=$u(e),r=Du(e,n);if(r)for(let o of Fu(e))t.push({kind:"file",text:o,fileAction:r,confidence:e.type==="file_edit"||e.type==="file_write"?1:.96});t.push(...Wu(e));for(let o of Lu(e)){t.push({kind:"command",text:o,confidence:.98});let s=zu(o);s&&t.push({kind:"test",text:o,checkKind:s,checkStatus:Ju(e),confidence:.98})}return Vu(t)}var Bu=new Set(["content","text","message","prompt","summary","description","title","reason","last_assistant_message","lastAssistantMessage"]);function oe(e){return e.normalize("NFKC").replace(/\s+/g," ").replace(/^[\s>*#•-]+/u,"").trim()}function Ko(e){return oe(e).toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function re(e,t,n=0){if(!(n>6)){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let r of e.slice(0,50))re(r,t,n+1);return}if(!(!e||typeof e!="object"))for(let[r,o]of Object.entries(e))(Bu.has(r)||["data","payload","parts","messages"].includes(r))&&re(o,t,n+1)}}function vt(e){return/\b(cancelled|canceled)\b|đã hủy|bỏ qua/iu.test(e)?"cancelled":/\b(blocked|blocker)\b|đang vướng|bị vướng|đang kẹt|chưa thể/iu.test(e)?"blocked":/\b(completed|complete|done|finished|passed)\b|hoàn thành|hoàn tất|đã xong|đã làm xong|\bxong\b/iu.test(e)?"completed":/\bin[\s_-]*progress\b|working on|đang làm|đang thực hiện|đang xử lý|đang triển khai/iu.test(e)?"in_progress":"pending"}function _o(e){let t=oe(e);return/^(?:đang\s+làm|đang\s+thực\s+hiện|đang\s+xử\s+lý|đang\s+triển\s+khai|hoàn\s+thành|hoàn\s+tất|đã\s+xong|đã\s+làm\s+xong|xong|pending|in[\s_-]*progress|completed|complete|done|finished|blocked|cancelled|canceled)[.!]*$/iu.test(t)}function P(e,t,n,r,o={}){let s=oe(r),i=o.key??Ko(s);return{version:1,id:w([e.projectId,n,i,t.id,s,o.status??"",o.fileAction??"",o.checkKind??"",o.checkStatus??"",o.order??""].join("|")).slice(0,32),projectId:e.projectId,kind:n,key:i,text:s,status:o.status,fileAction:o.fileAction,checkKind:o.checkKind,checkStatus:o.checkStatus,order:o.order,confidence:o.confidence??.85,occurredAt:t.timestamp,sequence:t.sequence,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,eventId:t.id,sourceEventId:t.sourceEventId}}function Gu(e,t,n){let r=oe(n);if(r.length<5||r.length>1200)return[];let o=[],s=/^(?:next|next action|next step|tiếp theo|bước tiếp theo|cần làm tiếp)\b/iu.test(r),i=r.match(/^(?:mục tiêu|goal|objective)\s*(?::|-)\s*(.+)$/iu);i?.[1]&&o.push(P(e,t,"goal",i[1],{confidence:.97}));let a=r.match(/^(?:kế hoạch|plan)\s*(?::|-)\s*(.+)$/iu);a?.[1]&&o.push(P(e,t,"plan",a[1],{confidence:.95}));let c=/\b(?:phase|giai đoạn|giai doan|stage)\s*(\d+)\s*(?:[:\-–—]\s*)?([^.;\n]{0,220})/giu,u;for(;!s&&(u=c.exec(r));){let p=Number(u[1]),f=oe(u[2]??""),m=f&&!_o(f)?`Phase ${p} - ${f}`:`Phase ${p}`;o.push(P(e,t,"phase",m,{key:`phase:${p}`,order:p,status:vt(r),confidence:.93}))}let l=n.match(/^\s*[-*]\s*\[([ xX])\]\s*(.+)$/u);l?.[2]&&o.push(P(e,t,"task",l[2],{status:l[1].trim()?"completed":vt(l[2]),confidence:.96}));let d=r.match(/^(?:todo|task|việc)\s*(\d+)?(?:\s*[:.\-–—]\s*|\s+)(.+)$/iu);if(d?.[2]){let p=d[1]?Number(d[1]):void 0,f=oe(d[2]),m=_o(f);o.push(P(e,t,"task",m&&p!==void 0?`TODO ${p}`:f,{key:p!==void 0?`task:${p}`:Ko(f),order:p,status:vt(r),confidence:.93}))}if(/^(?:next|next action|next step|tiếp theo|bước tiếp theo|cần làm tiếp)\b/iu.test(r)){let p=r.replace(/^(?:next|next action|next step|tiếp theo|bước tiếp theo|cần làm tiếp)\s*(?::|-)?\s*/iu,"");p&&o.push(P(e,t,"next_action",p,{confidence:.9}))}return/\b(blocker|blocked)\b|đang vướng|bị vướng|đang kẹt/iu.test(r)&&o.push(P(e,t,"blocker",r,{confidence:.9})),/\b(chú ý|lưu ý|warning|attention|cẩn thận)\b/iu.test(r)&&o.push(P(e,t,"warning",r,{confidence:.88})),/\b(chốt|quyết định|decided|decision)\b/iu.test(r)&&o.push(P(e,t,"decision",r,{confidence:.9})),r.length<=300&&/^(?:đang\s+(?:sửa|cập nhật|triển khai|xử lý|làm|refactor|fix)|(?:i(?:'m| am)\s+)?(?:working on|implementing|fixing|refactoring|updating|editing)\b)/iu.test(r)&&o.push(P(e,t,"activity",r,{confidence:.86})),o}function wt(e,t){if(t.length===0)return[];let n=[],r=new Set;function o(i){r.has(i.id)||(r.add(i.id),n.push(i))}for(let i of t){if(i.type==="user_prompt"||i.role==="user"){let c=[];re(i.data,c);let u=c.map(l=>oe(l)).find(l=>l.length>=8&&l.length<=1200&&!/^\[?toolnet\b/iu.test(l));u&&o(P(e,i,"request",u,{confidence:.96}))}for(let c of No(i))o(P(e,i,c.kind,c.text,{fileAction:c.fileAction,checkKind:c.checkKind,checkStatus:c.checkStatus,status:c.kind==="test"?c.checkStatus==="passed"?"completed":c.checkStatus==="failed"?"blocked":c.checkStatus==="running"?"in_progress":"pending":void 0,confidence:c.confidence}));if(i.type==="decision"){let c=[];re(i.data,c);for(let u of c)o(P(e,i,"decision",u,{confidence:1}))}if(i.type==="todo"){let c=[];re(i.data,c);for(let u of c)o(P(e,i,"task",u,{status:vt(u),confidence:1}))}if(["file_write","file_edit"].includes(i.type))for(let c of["filePath","path","file"]){let u=i.data[c];typeof u=="string"&&u&&o(P(e,i,"file",u,{fileAction:"modified",confidence:1}))}if(i.type==="test"){let c=[];re(i.data,c);for(let u of c)o(P(e,i,"test",u,{confidence:1}))}let a=[];re(i.data,a);for(let c of a)for(let u of c.split(/\n+/u))for(let l of Gu(e,i,u))o(l)}let s=t[t.length-1];return o(P(e,s,"session",`${e.agent}:${e.nativeSessionId}`,{key:e.sessionKey,confidence:1})),n}function $o(e){return String(e).padStart(12,"0")}var bt=class{constructor(t){this.storage=t}storage;async write(t,n){if(n.length===0)return null;let r=Math.min(...n.map(l=>l.sequence)),o=Math.max(...n.map(l=>l.sequence)),s={version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,createdAt:n.map(l=>l.occurredAt).sort().at(-1)??new Date().toISOString(),firstSequence:r,lastSequence:o,observations:n},i=JSON.stringify(s,null,2)+`
60
+ `,a=w(n.map(l=>JSON.stringify(l)).sort().join(`
61
+ `)).slice(0,24),c=w(t.sessionKey).slice(0,12),u=[`projects/${t.projectId}`,"work","observations",`${$o(r)}-${$o(o)}-${c}-${a}.json`].join("/");return await this.storage.put(u,i,"application/json"),u}};import{join as Lo}from"node:path";import{mkdirSync as Uu}from"node:fs";function Do(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function L(e,t=20){let n=[],r=new Set;for(let o of e.slice().reverse()){let s=Do(o);if(!(!s||r.has(s))&&(r.add(s),n.push(o),n.length>=t))break}return n.reverse()}function Yu(e,t=20){let n=new Map;for(let r of e){let o=`${r.kind}|${Do(r.command)}`;n.delete(o),n.set(o,r)}return Array.from(n.values()).slice(-t)}function Xu(e){return e.kind==="phase"?/^Phase\s+\d+$/iu.test(e.text):e.kind==="task"?/^(?:TODO|Task|Việc)\s+\d+$/iu.test(e.text):!1}function Fo(e,t){let n=t.status??e?.status??"pending",r=n;e&&(e.status==="completed"&&n!=="completed"?r="completed":n==="pending"&&(e.status==="in_progress"||e.status==="blocked")&&(r=e.status));let o=e&&Xu(t)?e.title:t.text;return{id:e?.id??w(t.key).slice(0,24),title:o,status:r,order:t.order??e?.order,confidence:Math.max(t.confidence,e?.confidence??0),updatedAt:t.occurredAt,updatedBy:{agent:t.agent,nativeSessionId:t.nativeSessionId,eventId:t.eventId}}}async function Wo(e,t){let n=`projects/${e.id}/work/observations/`,r=await t.list(n),o=[];for(let s of r.filter(i=>i.key.endsWith(".json")).sort((i,a)=>i.key.localeCompare(a.key))){let i=await t.getText(s.key);if(i)try{let a=JSON.parse(i);a.version===1&&Array.isArray(a.observations)&&o.push(a)}catch{}}return o}async function $e(e,t){let r=(await Wo(e,t)).flatMap(y=>y.observations).sort((y,k)=>{let E=y.occurredAt.localeCompare(k.occurredAt);if(E!==0)return E;let H=y.sequence-k.sequence;return H!==0?H:y.id.localeCompare(k.id)}),o=new Map,s=new Map,i,a,c,u,l,d=[],p=[],f=[],m=[],S=[],g=new Map,h=[],v=[],j=[],O=[],C=[],T=[];for(let y of r)switch(y.kind){case"request":i=y.text;break;case"activity":a=y.text;break;case"goal":c=y.text;break;case"plan":u=y.text;break;case"phase":o.set(y.key,Fo(o.get(y.key),y));break;case"task":s.set(y.key,Fo(s.get(y.key),y));break;case"decision":d.push(y.text);break;case"blocker":p.push(y.text);break;case"warning":f.push(y.text);break;case"next_action":m.push(y.text);break;case"file":{S.push(y.text);let k=y.fileAction??"active";g.delete(y.text),g.set(y.text,k),k==="modified"?h.push(y.text):k==="created"?v.push(y.text):k==="deleted"&&j.push(y.text);break}case"command":O.push(y.text);break;case"test":C.push(y.text),y.checkKind&&T.push({kind:y.checkKind,command:y.text,status:y.checkStatus??"unknown",updatedAt:y.occurredAt,agent:y.agent,nativeSessionId:y.nativeSessionId});break;case"session":l={agent:y.agent,nativeSessionId:y.nativeSessionId,sessionKey:y.sessionKey,updatedAt:y.occurredAt};break}let I=Array.from(o.values()).sort((y,k)=>(y.order??Number.MAX_SAFE_INTEGER)-(k.order??Number.MAX_SAFE_INTEGER)),b=Array.from(s.values()).sort((y,k)=>(y.order??Number.MAX_SAFE_INTEGER)-(k.order??Number.MAX_SAFE_INTEGER)),W=I.find(y=>y.status==="in_progress")??I.find(y=>y.status==="blocked")??I.find(y=>y.status==="pending"),z=b.find(y=>y.status==="in_progress")??b.find(y=>y.status==="blocked")??b.find(y=>y.status==="pending"),Rt=L([...m,...z?[z.title]:[],...!z&&W?[W.title]:[],...b.filter(y=>y.status==="pending").slice(0,5).map(y=>y.title)],8),Nt=L([...p,...I.filter(y=>y.status==="blocked").map(y=>y.title),...b.filter(y=>y.status==="blocked").map(y=>y.title)],20),me={version:1,projectId:e.id,projectName:e.name,currentRequest:i,currentActivity:a,goal:c,plan:u,phases:I,tasks:b,decisions:L(d,20),blockers:Nt,warnings:L(f,20),nextActions:Rt,filesTouched:L(S,30),activeFiles:Array.from(g.entries()).filter(([,y])=>y!=="deleted").map(([y])=>y).slice(-5),modifiedFiles:L(h,30),createdFiles:L(v,30),deletedFiles:L(j,30),commands:L(O,20),tests:L(C,20),checks:Yu(T,20),currentPhase:W,currentTask:z,progress:{phasesTotal:I.length,phasesCompleted:I.filter(y=>y.status==="completed").length,tasksTotal:b.length,tasksCompleted:b.filter(y=>y.status==="completed").length,blocked:I.filter(y=>y.status==="blocked").length+b.filter(y=>y.status==="blocked").length},lastSession:l,updatedAt:r.length?r[r.length-1].occurredAt:new Date().toISOString()},qe=Lo(e.rootPath,".toolnet","work");return Uu(qe,{recursive:!0}),R(Lo(qe,"current.json"),me),await t.put(`projects/${e.id}/work/current.json`,JSON.stringify(me,null,2)+`
62
+ `,"application/json"),me}async function zo(e,t){if((await Wo(e,t)).length>0)return $e(e,t);let r=await t.getText(`projects/${e.id}/work/current.json`);if(!r)return null;try{return JSON.parse(r)}catch{return null}}function rl(e,t){if(!Qu(e))return{events:[],nextOffset:t};let n=nl(e).size,r=Number.isFinite(t)?Math.max(0,t):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let o=n-r,s=Buffer.alloc(o),i=el(e,"r");try{tl(i,s,0,o,r)}finally{Zu(i)}let a=s.toString("utf8"),c=a.lastIndexOf(`
63
63
  `);if(c<0)return{events:[],nextOffset:r};let u=a.slice(0,c+1);return{events:u.split(`
64
- `).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var pt=class{constructor(t){this.options=t;this.journal=new dt(t.storage)}options;journal;async learnNew(){let t=this.options.wal.loadState(),n=Number(t.sourceCursors["work.continuity.offset"]??0),r=wu(this.options.wal.eventsFile,Number.isFinite(n)?n:0);if(r.events.length===0)return{scannedEvents:0,observations:0,journalWritten:!1,reconciled:!1,nextOffset:r.nextOffset};let o=lt(this.options.identity,r.events),s=!1,i=!1;return o.length>0&&(s=!!await this.journal.write(this.options.identity,o),s&&(await Te(this.options.project,this.options.storage),i=!0)),this.options.wal.setSourceCursor("work.continuity.offset",r.nextOffset),{scannedEvents:r.events.length,observations:o.length,journalWritten:s,reconciled:i,nextOffset:r.nextOffset}}};import{closeSync as Eu,existsSync as Ou,openSync as Tu,readSync as Ru,statSync as Nu}from"node:fs";var bu=new Set(["content","text","message","prompt","summary","description","title","reason","last_assistant_message","lastAssistantMessage"]);function ue(e){return e.normalize("NFKC").replace(/\s+/g," ").replace(/^[\s>*#•-]+/u,"").trim()}function Qt(e,t,n=0){if(!(n>6)){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let r of e.slice(0,50))Qt(r,t,n+1);return}if(!(!e||typeof e!="object"))for(let[r,o]of Object.entries(e))(bu.has(r)||["data","payload","parts","messages"].includes(r))&&Qt(o,t,n+1)}}function N(e,t,n,r,o,s=.95){let i=ue(r);return{version:1,id:v([e.projectId,n,o.type,o.key??"",i.toLowerCase(),t.id].join("|")).slice(0,32),projectId:e.projectId,kind:n,value:i,scope:o.type,scopeKey:o.key,scopeOrder:o.order,confidence:s,evidence:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,eventId:t.id,sourceEventId:t.sourceEventId,sequence:t.sequence,occurredAt:t.timestamp}}}function L(e,t){let n=e.toLowerCase();for(let r of t){let o=r.toLowerCase();if(n.startsWith(`${o}:`)||n.startsWith(`${o} -`)||n.startsWith(`${o} \u2014`))return ue(e.slice(r.length+1))}return null}function xu(e){let t=e.trimStart();return t.startsWith("- ")||t.startsWith("* ")||/^\d+[.)]\s+/u.test(t)}function ju(e){return ue(e.trim().replace(/^[-*]\s+/u,"").replace(/^\d+[.)]\s+/u,""))}function bo(e,t){let n=[],r=new Set;function o(s){!s.value||s.value.length<3||r.has(s.id)||(r.add(s.id),n.push(s))}for(let s of t){let i=[];Qt(s.data,i);for(let a of i){let c={type:"project"},u=null;for(let d of a.split(/\r?\n/u)){let l=ue(d);if(!l){u=null;continue}let f=l.match(/^(?:phase|giai đoạn|giai doan|stage)\s*(\d+)\s*(?:[:\-–—]\s*)?(.*)$/iu);if(f){let w=Number(f[1]);c={type:"phase",key:`phase:${w}`,order:w,title:ue(f[2]??"")},u=null;continue}let p=l.match(/^(?:todo|task|việc)\s*(\d+)\s*(?:[:\-–—]\s*)?(.*)$/iu);if(p){let w=Number(p[1]);c={type:"task",key:`task:${w}`,order:w,title:ue(p[2]??"")},u=null;continue}let g=L(l,["mission","s\u1EE9 m\u1EC7nh","m\u1EE5c ti\xEAu t\u1ED5ng th\u1EC3","m\u1EE5c ti\xEAu project","project goal"]);if(g){o(N(e,s,"mission",g,{type:"project"},.99)),u=null;continue}let S=L(l,["current objective","active objective","m\u1EE5c ti\xEAu hi\u1EC7n t\u1EA1i","objective","m\u1EE5c ti\xEAu","m\u1EE5c \u0111\xEDch"]);if(S){o(N(e,s,c.type==="phase"?"phase_objective":"objective",S,c,.98)),u=null;continue}let y=L(l,["why","why this","why this phase","reason","rationale","v\xEC sao","l\xFD do","t\u1EA1i sao","\xFD ngh\u0129a"]);if(y){o(N(e,s,c.type==="phase"?"phase_why":"why",y,c,.98)),u=null;continue}let h=L(l,["desired outcome","final outcome","k\u1EBFt qu\u1EA3 cu\u1ED1i","k\u1EBFt qu\u1EA3 mong mu\u1ED1n","m\u1EE5c ti\xEAu cu\u1ED1i"]);if(h){o(N(e,s,"desired_outcome",h,{type:"project"},.98)),u=null;continue}let k=L(l,["plan rationale","approach rationale","why this approach","t\u1EA1i sao ch\u1ECDn h\u01B0\u1EDBng n\xE0y","l\xFD do ch\u1ECDn h\u01B0\u1EDBng n\xE0y","l\xFD do ch\u1ECDn ki\u1EBFn tr\xFAc"]);if(k){o(N(e,s,"plan_rationale",k,{type:"project"},.98)),u=null;continue}let M=L(l,["deliverable","output","k\u1EBFt qu\u1EA3 c\u1EA7n \u0111\u1EA1t","ph\u1EA3i t\u1EA1o ra","\u0111\u1EA7u ra"]);if(M){o(N(e,s,"phase_deliverable",M,c,.97)),u=null;continue}let E=L(l,["acceptance criteria","definition of done","done khi","ho\xE0n th\xE0nh khi","ti\xEAu ch\xED ho\xE0n th\xE0nh"]);if(E){o(N(e,s,"acceptance_criterion",E,c,.98)),u="acceptance_criterion";continue}let C=L(l,["depends on","dependency","dependencies","ph\u1EE5 thu\u1ED9c","c\u1EA7n c\xF3 tr\u01B0\u1EDBc"]);if(C){o(N(e,s,"dependency",C,c,.97)),u="dependency";continue}let O=L(l,["open question","open questions","c\xE2u h\u1ECFi m\u1EDF","ch\u01B0a quy\u1EBFt \u0111\u1ECBnh","ch\u01B0a r\xF5"]);if(O){o(N(e,s,"open_question",O,c,.95)),u="open_question";continue}let x=L(l,["constraint","constraints","r\xE0ng bu\u1ED9c","gi\u1EDBi h\u1EA1n"]);if(x){o(N(e,s,"constraint",x,c,.97)),u="constraint";continue}if(/^(?:acceptance criteria|definition of done|done khi|tiêu chí hoàn thành)\s*:?\s*$/iu.test(l)){u="acceptance_criterion";continue}if(/^(?:dependencies|dependency|phụ thuộc)\s*:?\s*$/iu.test(l)){u="dependency";continue}if(/^(?:open questions|open question|câu hỏi mở)\s*:?\s*$/iu.test(l)){u="open_question";continue}if(/^(?:constraints|constraint|ràng buộc)\s*:?\s*$/iu.test(l)){u="constraint";continue}if(u&&xu(d)){o(N(e,s,u,ju(d),c,.96));continue}u=null}}}return n}function xo(e){return String(e).padStart(12,"0")}var ft=class{constructor(t){this.storage=t}storage;async write(t,n){if(n.length===0)return null;let r=Math.min(...n.map(u=>u.evidence.sequence)),o=Math.max(...n.map(u=>u.evidence.sequence)),s={version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,firstSequence:r,lastSequence:o,createdAt:new Date().toISOString(),observations:n},i=v(n.map(u=>u.id).sort().join("|")).slice(0,16),a=v(t.sessionKey).slice(0,12),c=[`projects/${t.projectId}`,"work","semantic","observations",`${xo(r)}-${xo(o)}-${a}-${i}.json`].join("/");return await this.storage.exists(c)||await this.storage.put(c,JSON.stringify(s,null,2)+`
65
- `,"application/json"),c}};import{mkdirSync as Iu}from"node:fs";import{join as jo}from"node:path";function Au(e){return{value:e.value,confidence:e.confidence,evidence:e.evidence}}function Pu(e,t){if(!t)return!0;let n=e.evidence.occurredAt.localeCompare(t.evidence.occurredAt);return n!==0?n>0:e.evidence.sessionKey===t.evidence.sessionKey?e.evidence.sequence>=t.evidence.sequence:e.confidence>=t.confidence}function B(e,t){return Pu(t,e)?t:e}function G(e,t=30){let n=new Set,r=[];for(let o of e){let s=o.value.normalize("NFKC").toLowerCase().replace(/\s+/g," ").trim();!s||n.has(s)||(n.add(s),r.push(o))}return r.slice(-t)}async function Cu(e,t){let n=`projects/${e.id}/work/semantic/observations/`,r=await t.list(n),o=[];for(let s of r.filter(i=>i.key.endsWith(".json")).sort((i,a)=>i.key.localeCompare(a.key))){let i=await t.getText(s.key);if(i)try{let a=JSON.parse(i);a.version===1&&Array.isArray(a.observations)&&o.push(a)}catch{}}return o}function Mu(e){return{key:e.scopeKey??`phase:${e.scopeOrder??0}`,order:e.scopeOrder??0,acceptanceCriteria:[],dependencies:[],openQuestions:[],constraints:[],notes:[]}}async function Io(e,t){let r=(await Cu(e,t)).flatMap(S=>S.observations).sort((S,y)=>{let h=S.evidence.occurredAt.localeCompare(y.evidence.occurredAt);return h!==0?h:S.evidence.sessionKey===y.evidence.sessionKey?S.evidence.sequence-y.evidence.sequence:S.id.localeCompare(y.id)}),o,s,i,a,c,u=new Map,d=[],l=[],f=[];for(let S of r){let y=Au(S);if(S.scope==="phase"&&S.scopeKey){let h=u.get(S.scopeKey)??Mu(S);switch(S.kind){case"phase_objective":h.objective=B(h.objective,y);break;case"phase_why":h.why=B(h.why,y);break;case"phase_deliverable":h.deliverable=B(h.deliverable,y);break;case"acceptance_criterion":h.acceptanceCriteria.push(y);break;case"dependency":h.dependencies.push(y);break;case"open_question":h.openQuestions.push(y);break;case"constraint":h.constraints.push(y);break;case"note":h.notes.push(y);break}u.set(h.key,h);continue}switch(S.kind){case"mission":o=B(o,y);break;case"objective":s=B(s,y);break;case"why":i=B(i,y);break;case"desired_outcome":a=B(a,y);break;case"plan_rationale":c=B(c,y);break;case"open_question":d.push(y);break;case"constraint":l.push(y);break;case"note":f.push(y);break}}for(let S of u.values())S.acceptanceCriteria=G(S.acceptanceCriteria,20),S.dependencies=G(S.dependencies,15),S.openQuestions=G(S.openQuestions,15),S.constraints=G(S.constraints,15),S.notes=G(S.notes,20);let p={version:1,projectId:e.id,projectName:e.name,mission:o,activeObjective:s,why:i,desiredOutcome:a,planRationale:c,phases:Array.from(u.values()).sort((S,y)=>S.order-y.order),openQuestions:G(d,20),constraints:G(l,20),notes:G(f,20),updatedAt:r.length?r[r.length-1].evidence.occurredAt:new Date().toISOString()},g=jo(e.rootPath,".toolnet","work");return Iu(g,{recursive:!0}),T(jo(g,"semantic-current.json"),p),await t.put(`projects/${e.id}/work/semantic/current.json`,JSON.stringify(p,null,2)+`
66
- `,"application/json"),p}function _u(e,t){if(!Ou(e))return{events:[],nextOffset:t};let n=Nu(e).size,r=Number.isFinite(t)?Math.max(0,t):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let o=Buffer.alloc(n-r),s=Tu(e,"r");try{Ru(s,o,0,o.length,r)}finally{Eu(s)}let i=o.toString("utf8"),a=i.lastIndexOf(`
64
+ `).filter(Boolean).flatMap(d=>{try{return[JSON.parse(d)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var xt=class{constructor(t){this.options=t;this.journal=new bt(t.storage)}options;journal;async learnNew(){let t=this.options.wal.loadState(),n=Number(t.sourceCursors["work.continuity.offset"]??0),r=rl(this.options.wal.eventsFile,Number.isFinite(n)?n:0);if(r.events.length===0)return{scannedEvents:0,observations:0,journalWritten:!1,reconciled:!1,nextOffset:r.nextOffset};let o=wt(this.options.identity,r.events),s=!1,i=!1;return o.length>0&&(s=!!await this.journal.write(this.options.identity,o),s&&(await $e(this.options.project,this.options.storage),i=!0)),this.options.wal.setSourceCursor("work.continuity.offset",r.nextOffset),{scannedEvents:r.events.length,observations:o.length,journalWritten:s,reconciled:i,nextOffset:r.nextOffset}}};import{closeSync as pl,existsSync as fl,openSync as ml,readSync as gl,statSync as yl}from"node:fs";var ol=new Set(["content","text","message","prompt","summary","description","title","reason","last_assistant_message","lastAssistantMessage"]);function fe(e){return e.normalize("NFKC").replace(/\s+/g," ").replace(/^[\s>*#•-]+/u,"").trim()}function dn(e,t,n=0){if(!(n>6)){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let r of e.slice(0,50))dn(r,t,n+1);return}if(!(!e||typeof e!="object"))for(let[r,o]of Object.entries(e))(ol.has(r)||["data","payload","parts","messages"].includes(r))&&dn(o,t,n+1)}}function _(e,t,n,r,o,s=.95){let i=fe(r);return{version:1,id:w([e.projectId,n,o.type,o.key??"",i.toLowerCase(),t.id].join("|")).slice(0,32),projectId:e.projectId,kind:n,value:i,scope:o.type,scopeKey:o.key,scopeOrder:o.order,confidence:s,evidence:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,eventId:t.id,sourceEventId:t.sourceEventId,sequence:t.sequence,occurredAt:t.timestamp}}}function F(e,t){let n=e.toLowerCase();for(let r of t){let o=r.toLowerCase();if(n.startsWith(`${o}:`)||n.startsWith(`${o} -`)||n.startsWith(`${o} \u2014`))return fe(e.slice(r.length+1))}return null}function sl(e){let t=e.trimStart();return t.startsWith("- ")||t.startsWith("* ")||/^\d+[.)]\s+/u.test(t)}function il(e){return fe(e.trim().replace(/^[-*]\s+/u,"").replace(/^\d+[.)]\s+/u,""))}function qo(e,t){let n=[],r=new Set;function o(s){!s.value||s.value.length<3||r.has(s.id)||(r.add(s.id),n.push(s))}for(let s of t){let i=[];dn(s.data,i);for(let a of i){let c={type:"project"},u=null;for(let l of a.split(/\r?\n/u)){let d=fe(l);if(!d){u=null;continue}let p=d.match(/^(?:phase|giai đoạn|giai doan|stage)\s*(\d+)\s*(?:[:\-–—]\s*)?(.*)$/iu);if(p){let b=Number(p[1]);c={type:"phase",key:`phase:${b}`,order:b,title:fe(p[2]??"")},u=null;continue}let f=d.match(/^(?:todo|task|việc)\s*(\d+)\s*(?:[:\-–—]\s*)?(.*)$/iu);if(f){let b=Number(f[1]);c={type:"task",key:`task:${b}`,order:b,title:fe(f[2]??"")},u=null;continue}let m=F(d,["mission","s\u1EE9 m\u1EC7nh","m\u1EE5c ti\xEAu t\u1ED5ng th\u1EC3","m\u1EE5c ti\xEAu project","project goal"]);if(m){o(_(e,s,"mission",m,{type:"project"},.99)),u=null;continue}let S=F(d,["current objective","active objective","m\u1EE5c ti\xEAu hi\u1EC7n t\u1EA1i","objective","m\u1EE5c ti\xEAu","m\u1EE5c \u0111\xEDch"]);if(S){o(_(e,s,c.type==="phase"?"phase_objective":"objective",S,c,.98)),u=null;continue}let g=F(d,["why","why this","why this phase","reason","rationale","v\xEC sao","l\xFD do","t\u1EA1i sao","\xFD ngh\u0129a"]);if(g){o(_(e,s,c.type==="phase"?"phase_why":"why",g,c,.98)),u=null;continue}let h=F(d,["desired outcome","final outcome","k\u1EBFt qu\u1EA3 cu\u1ED1i","k\u1EBFt qu\u1EA3 mong mu\u1ED1n","m\u1EE5c ti\xEAu cu\u1ED1i"]);if(h){o(_(e,s,"desired_outcome",h,{type:"project"},.98)),u=null;continue}let v=F(d,["plan rationale","approach rationale","why this approach","t\u1EA1i sao ch\u1ECDn h\u01B0\u1EDBng n\xE0y","l\xFD do ch\u1ECDn h\u01B0\u1EDBng n\xE0y","l\xFD do ch\u1ECDn ki\u1EBFn tr\xFAc"]);if(v){o(_(e,s,"plan_rationale",v,{type:"project"},.98)),u=null;continue}let j=F(d,["deliverable","output","k\u1EBFt qu\u1EA3 c\u1EA7n \u0111\u1EA1t","ph\u1EA3i t\u1EA1o ra","\u0111\u1EA7u ra"]);if(j){o(_(e,s,"phase_deliverable",j,c,.97)),u=null;continue}let O=F(d,["acceptance criteria","definition of done","done khi","ho\xE0n th\xE0nh khi","ti\xEAu ch\xED ho\xE0n th\xE0nh"]);if(O){o(_(e,s,"acceptance_criterion",O,c,.98)),u="acceptance_criterion";continue}let C=F(d,["depends on","dependency","dependencies","ph\u1EE5 thu\u1ED9c","c\u1EA7n c\xF3 tr\u01B0\u1EDBc"]);if(C){o(_(e,s,"dependency",C,c,.97)),u="dependency";continue}let T=F(d,["open question","open questions","c\xE2u h\u1ECFi m\u1EDF","ch\u01B0a quy\u1EBFt \u0111\u1ECBnh","ch\u01B0a r\xF5"]);if(T){o(_(e,s,"open_question",T,c,.95)),u="open_question";continue}let I=F(d,["constraint","constraints","r\xE0ng bu\u1ED9c","gi\u1EDBi h\u1EA1n"]);if(I){o(_(e,s,"constraint",I,c,.97)),u="constraint";continue}if(/^(?:acceptance criteria|definition of done|done khi|tiêu chí hoàn thành)\s*:?\s*$/iu.test(d)){u="acceptance_criterion";continue}if(/^(?:dependencies|dependency|phụ thuộc)\s*:?\s*$/iu.test(d)){u="dependency";continue}if(/^(?:open questions|open question|câu hỏi mở)\s*:?\s*$/iu.test(d)){u="open_question";continue}if(/^(?:constraints|constraint|ràng buộc)\s*:?\s*$/iu.test(d)){u="constraint";continue}if(u&&sl(l)){o(_(e,s,u,il(l),c,.96));continue}u=null}}}return n}function Ho(e){return String(e).padStart(12,"0")}var jt=class{constructor(t){this.storage=t}storage;async write(t,n){if(n.length===0)return null;let r=Math.min(...n.map(u=>u.evidence.sequence)),o=Math.max(...n.map(u=>u.evidence.sequence)),s={version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,firstSequence:r,lastSequence:o,createdAt:new Date().toISOString(),observations:n},i=w(n.map(u=>u.id).sort().join("|")).slice(0,16),a=w(t.sessionKey).slice(0,12),c=[`projects/${t.projectId}`,"work","semantic","observations",`${Ho(r)}-${Ho(o)}-${a}-${i}.json`].join("/");return await this.storage.exists(c)||await this.storage.put(c,JSON.stringify(s,null,2)+`
65
+ `,"application/json"),c}};import{mkdirSync as al}from"node:fs";import{join as Jo}from"node:path";function cl(e){return{value:e.value,confidence:e.confidence,evidence:e.evidence}}function ul(e,t){if(!t)return!0;let n=e.evidence.occurredAt.localeCompare(t.evidence.occurredAt);return n!==0?n>0:e.evidence.sessionKey===t.evidence.sessionKey?e.evidence.sequence>=t.evidence.sequence:e.confidence>=t.confidence}function U(e,t){return ul(t,e)?t:e}function Y(e,t=30){let n=new Set,r=[];for(let o of e){let s=o.value.normalize("NFKC").toLowerCase().replace(/\s+/g," ").trim();!s||n.has(s)||(n.add(s),r.push(o))}return r.slice(-t)}async function ll(e,t){let n=`projects/${e.id}/work/semantic/observations/`,r=await t.list(n),o=[];for(let s of r.filter(i=>i.key.endsWith(".json")).sort((i,a)=>i.key.localeCompare(a.key))){let i=await t.getText(s.key);if(i)try{let a=JSON.parse(i);a.version===1&&Array.isArray(a.observations)&&o.push(a)}catch{}}return o}function dl(e){return{key:e.scopeKey??`phase:${e.scopeOrder??0}`,order:e.scopeOrder??0,acceptanceCriteria:[],dependencies:[],openQuestions:[],constraints:[],notes:[]}}async function Vo(e,t){let r=(await ll(e,t)).flatMap(S=>S.observations).sort((S,g)=>{let h=S.evidence.occurredAt.localeCompare(g.evidence.occurredAt);return h!==0?h:S.evidence.sessionKey===g.evidence.sessionKey?S.evidence.sequence-g.evidence.sequence:S.id.localeCompare(g.id)}),o,s,i,a,c,u=new Map,l=[],d=[],p=[];for(let S of r){let g=cl(S);if(S.scope==="phase"&&S.scopeKey){let h=u.get(S.scopeKey)??dl(S);switch(S.kind){case"phase_objective":h.objective=U(h.objective,g);break;case"phase_why":h.why=U(h.why,g);break;case"phase_deliverable":h.deliverable=U(h.deliverable,g);break;case"acceptance_criterion":h.acceptanceCriteria.push(g);break;case"dependency":h.dependencies.push(g);break;case"open_question":h.openQuestions.push(g);break;case"constraint":h.constraints.push(g);break;case"note":h.notes.push(g);break}u.set(h.key,h);continue}switch(S.kind){case"mission":o=U(o,g);break;case"objective":s=U(s,g);break;case"why":i=U(i,g);break;case"desired_outcome":a=U(a,g);break;case"plan_rationale":c=U(c,g);break;case"open_question":l.push(g);break;case"constraint":d.push(g);break;case"note":p.push(g);break}}for(let S of u.values())S.acceptanceCriteria=Y(S.acceptanceCriteria,20),S.dependencies=Y(S.dependencies,15),S.openQuestions=Y(S.openQuestions,15),S.constraints=Y(S.constraints,15),S.notes=Y(S.notes,20);let f={version:1,projectId:e.id,projectName:e.name,mission:o,activeObjective:s,why:i,desiredOutcome:a,planRationale:c,phases:Array.from(u.values()).sort((S,g)=>S.order-g.order),openQuestions:Y(l,20),constraints:Y(d,20),notes:Y(p,20),updatedAt:r.length?r[r.length-1].evidence.occurredAt:new Date().toISOString()},m=Jo(e.rootPath,".toolnet","work");return al(m,{recursive:!0}),R(Jo(m,"semantic-current.json"),f),await t.put(`projects/${e.id}/work/semantic/current.json`,JSON.stringify(f,null,2)+`
66
+ `,"application/json"),f}function hl(e,t){if(!fl(e))return{events:[],nextOffset:t};let n=yl(e).size,r=Number.isFinite(t)?Math.max(0,t):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let o=Buffer.alloc(n-r),s=ml(e,"r");try{gl(s,o,0,o.length,r)}finally{pl(s)}let i=o.toString("utf8"),a=i.lastIndexOf(`
67
67
  `);if(a<0)return{events:[],nextOffset:r};let c=i.slice(0,a+1);return{events:c.split(`
68
- `).filter(Boolean).flatMap(u=>{try{return[JSON.parse(u)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(c,"utf8")}}var mt=class{constructor(t){this.options=t;this.journal=new ft(t.storage)}options;journal;async learnNew(){let t=this.options.wal.loadState(),n=Number(t.sourceCursors["work.semantic.offset"]??0),r=_u(this.options.wal.eventsFile,Number.isFinite(n)?n:0);if(r.events.length===0)return{scannedEvents:0,observations:0,journalWritten:!1,reconciled:!1,nextOffset:r.nextOffset};let o=bo(this.options.identity,r.events),s=!1,i=!1;return o.length>0&&(s=!!await this.journal.write(this.options.identity,o),s&&(await Io(this.options.project,this.options.storage),i=!0)),this.options.wal.setSourceCursor("work.semantic.offset",r.nextOffset),{scannedEvents:r.events.length,observations:o.length,journalWritten:s,reconciled:i,nextOffset:r.nextOffset}}};import{existsSync as Cl,mkdirSync as Ml}from"node:fs";import{join as en}from"node:path";import{existsSync as Co,mkdirSync as Ku,readFileSync as $u,statSync as Ao,writeFileSync as Lu}from"node:fs";import{dirname as Fu,join as Wu}from"node:path";var Po=64*1024,Du=`# ToolNet Project Operating Manual
68
+ `).filter(Boolean).flatMap(u=>{try{return[JSON.parse(u)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(c,"utf8")}}var It=class{constructor(t){this.options=t;this.journal=new jt(t.storage)}options;journal;async learnNew(){let t=this.options.wal.loadState(),n=Number(t.sourceCursors["work.semantic.offset"]??0),r=hl(this.options.wal.eventsFile,Number.isFinite(n)?n:0);if(r.events.length===0)return{scannedEvents:0,observations:0,journalWritten:!1,reconciled:!1,nextOffset:r.nextOffset};let o=qo(this.options.identity,r.events),s=!1,i=!1;return o.length>0&&(s=!!await this.journal.write(this.options.identity,o),s&&(await Vo(this.options.project,this.options.storage),i=!0)),this.options.wal.setSourceCursor("work.semantic.offset",r.nextOffset),{scannedEvents:r.events.length,observations:o.length,journalWritten:s,reconciled:i,nextOffset:r.nextOffset}}};import{existsSync as ld,mkdirSync as dd}from"node:fs";import{join as fn}from"node:path";import{existsSync as Uo,mkdirSync as Sl,readFileSync as kl,statSync as Bo,writeFileSync as vl}from"node:fs";import{dirname as wl,join as bl}from"node:path";var Go=64*1024,xl=`# ToolNet Project Operating Manual
69
69
 
70
70
  This file contains persistent instructions for AI agents working on this project.
71
71
 
@@ -108,15 +108,16 @@ Things an AI agent should always remember.
108
108
  <!--
109
109
  - [advisory] Prefer small focused files.
110
110
  -->
111
- `;function Mo(e){return Wu(e.rootPath,".toolnet","PROJECT.md")}function zu(e){return e.normalize("NFKC").replace(/\s+/g," ").trim()}function qu(e){let t=[],n=new Set,r=/^\s*[-*]\s+\[(enforce|advisory)\]\s+(.+?)\s*$/gimu,o;for(;o=r.exec(e);){let s=o[1].toLowerCase(),i=zu(o[2]);if(!i)continue;let a=`${s}:${i.toLowerCase()}`;n.has(a)||(n.add(a),t.push({id:v(a).slice(0,24),mode:s,text:i,source:"manual"}))}return t}function Hu(e){let t=Mo(e);return Co(t)||(Ku(Fu(t),{recursive:!0}),Lu(t,Du,{encoding:"utf8",mode:384})),t}function Eo(e,t=!1){let n=t?Hu(e):Mo(e);if(!Co(n))return null;if(Ao(n).size>Po)throw new Error(`PROJECT.md exceeds ${Po} bytes`);let o=$u(n,"utf8");return{path:n,content:o,digest:v(o),rules:qu(o),bytes:Buffer.byteLength(o,"utf8"),updatedAt:new Date(Ao(n).mtimeMs).toISOString()}}import{randomUUID as Ju}from"node:crypto";import{closeSync as Vu,existsSync as Oo,fsyncSync as Bu,mkdirSync as Gu,openSync as Uu,readFileSync as Yu,statSync as Xu,unlinkSync as To,writeFileSync as Qu}from"node:fs";import{dirname as Zu,join as el}from"node:path";var tl=new Int32Array(new SharedArrayBuffer(4));function nl(e){e<=0||Atomics.wait(tl,0,0,e)}function rl(e){return el(e.rootPath,".toolnet","work",".current.lock")}function ol(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code!=="ESRCH"}}function Ro(e){if(!Oo(e))return null;try{let t=JSON.parse(Yu(e,"utf8"));return t.version!==1||typeof t.token!="string"||typeof t.pid!="number"||typeof t.acquiredAt!="string"?null:{version:1,token:t.token,pid:t.pid,acquiredAt:t.acquiredAt}}catch{return null}}function sl(e){try{return Date.now()-Xu(e).mtimeMs}catch{return 0}}function il(e,t){if(!Oo(e)||sl(e)<t)return!1;let n=Ro(e);return n?!ol(n.pid):!0}function al(e,t){if(!il(e,t))return!1;try{return To(e),!0}catch{return!1}}function cl(e,t){let n={version:1,token:t,pid:process.pid,acquiredAt:new Date().toISOString()},r=Uu(e,"wx",384);try{Qu(r,`${JSON.stringify(n,null,2)}
112
- `,{encoding:"utf8"}),Bu(r)}finally{Vu(r)}}function ul(e,t){if(Ro(e)?.token===t)try{To(e)}catch{}}function ll(e,t={}){let n=Math.max(100,t.timeoutMs??5e3),r=Math.max(5,t.retryMs??20),o=Math.max(n*2,t.staleMs??3e4),s=rl(e);Gu(Zu(s),{recursive:!0});let i=Ju(),a=Date.now()+n;for(;;)try{cl(s,i);let c=!1;return()=>{c||(c=!0,ul(s,i))}}catch(c){if(c?.code!=="EEXIST")throw c;if(al(s,o))continue;if(Date.now()>=a)throw new Error(`Timed out acquiring project work lock: ${s}`);nl(r)}}function No(e,t,n={}){let r=ll(e,n);try{return t()}finally{r()}}import{closeSync as dl,existsSync as pl,fsyncSync as fl,mkdirSync as ml,openSync as gl,readFileSync as yl,renameSync as hl,writeFileSync as Sl}from"node:fs";import{dirname as kl,join as vl}from"node:path";function wl(e,t){ml(kl(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`,r=gl(n,"w",384);try{Sl(r,`${JSON.stringify(t,null,2)}
113
- `,{encoding:"utf8"}),fl(r)}finally{dl(r)}hl(n,e)}function Wo(e){return vl(e.rootPath,".toolnet","work","current.json")}function Zt(e){let t=Wo(e);if(!pl(t))return null;try{let n=JSON.parse(yl(t,"utf8"));return n.version!==1||n.projectId!==e.id?null:n}catch{return null}}function gt(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function _(e,t,n){let r=[],o=new Set;for(let s of[...e,...t].reverse()){let i=gt(s);if(!(!i||o.has(i))&&(o.add(i),r.push(s),r.length>=n))break}return r.reverse()}function bl(e,t,n=20){let r=new Map;for(let o of[...e,...t]){let s=`${o.kind}|${gt(o.command)}`;r.delete(s),r.set(s,o)}return Array.from(r.values()).slice(-n)}function xl(e){return e.kind==="phase"?/^Phase\s+\d+$/iu.test(e.text):e.kind==="task"?/^(?:TODO|Task|Việc)\s+\d+$/iu.test(e.text):!1}function _o(e,t){let n=t.status??e?.status??"pending",r=n;e?.status==="completed"&&n!=="completed"&&(r="completed"),e&&n==="pending"&&(e.status==="in_progress"||e.status==="blocked")&&(r=e.status);let o=e&&xl(t)?e.title:t.text;return{id:e?.id??t.id,title:o,status:r,order:t.order??e?.order,confidence:Math.max(e?.confidence??0,t.confidence),updatedAt:t.occurredAt,updatedBy:{agent:t.agent,nativeSessionId:t.nativeSessionId,eventId:t.eventId}}}function Ko(e){let t=new Map;for(let n of e){let r=n.order!==void 0?`order:${n.order}`:gt(n.title);t.set(r,n)}return t}function $o(e){return e.order!==void 0?`order:${e.order}`:gt(e.key||e.text)}function Lo(e){return Array.from(e).sort((t,n)=>{let r=t.order??Number.MAX_SAFE_INTEGER,o=n.order??Number.MAX_SAFE_INTEGER;return r!==o?r-o:t.updatedAt.localeCompare(n.updatedAt)})}function Fo(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="blocked")??e.find(t=>t.status==="pending")}function jl(e,t){let n=Zt(e),r=Ko(n?.phases??[]),o=Ko(n?.tasks??[]),s=n?.currentRequest,i=n?.currentActivity,a=n?.goal,c=n?.plan,u=n?.lastSession,d=[],l=[],f=[],p=[],g=[],S=[...n?.activeFiles??[]],y=[],h=[],k=[],M=[],E=[],C=[],O=[...t].sort((m,b)=>{let q=m.occurredAt.localeCompare(b.occurredAt);return q!==0?q:m.sequence-b.sequence});for(let m of O)switch(m.kind){case"request":s=m.text;break;case"activity":i=m.text;break;case"goal":a=m.text;break;case"plan":c=m.text;break;case"phase":{let b=$o(m);r.set(b,_o(r.get(b),m));break}case"task":{let b=$o(m);o.set(b,_o(o.get(b),m));break}case"decision":d.push(m.text);break;case"blocker":l.push(m.text);break;case"warning":f.push(m.text);break;case"next_action":p.push(m.text);break;case"file":{g.push(m.text);let b=m.fileAction??"active",q=S.indexOf(m.text);q>=0&&S.splice(q,1),b!=="deleted"&&S.push(m.text),b==="modified"?y.push(m.text):b==="created"?h.push(m.text):b==="deleted"&&k.push(m.text);break}case"command":M.push(m.text);break;case"test":E.push(m.text),m.checkKind&&C.push({kind:m.checkKind,command:m.text,status:m.checkStatus??"unknown",updatedAt:m.occurredAt,agent:m.agent,nativeSessionId:m.nativeSessionId});break;case"session":u={agent:m.agent,nativeSessionId:m.nativeSessionId,sessionKey:m.sessionKey,updatedAt:m.occurredAt};break}let x=Lo(r.values()),w=Lo(o.values()),W=Fo(x),D=Fo(w),bt=_(n?.nextActions??[],[...p,...D?[D.title]:[],...!D&&W?[W.title]:[],...w.filter(m=>m.status==="pending").slice(0,5).map(m=>m.title)],8),xt=_(n?.blockers??[],[...l,...x.filter(m=>m.status==="blocked").map(m=>m.title),...w.filter(m=>m.status==="blocked").map(m=>m.title)],20),le=O.length>0?O[O.length-1].occurredAt:n?.updatedAt??new Date().toISOString(),de={version:1,projectId:e.id,projectName:e.name,currentRequest:s,currentActivity:i,goal:a,plan:c,phases:x,tasks:w,decisions:_(n?.decisions??[],d,20),blockers:xt,warnings:_(n?.warnings??[],f,20),nextActions:bt,filesTouched:_(n?.filesTouched??[],g,30),activeFiles:_([],S,5),modifiedFiles:_(n?.modifiedFiles??[],y,30),createdFiles:_(n?.createdFiles??[],h,30),deletedFiles:_(n?.deletedFiles??[],k,30),commands:_(n?.commands??[],M,20),tests:_(n?.tests??[],E,20),checks:bl(n?.checks??[],C,20),currentPhase:W,currentTask:D,progress:{phasesTotal:x.length,phasesCompleted:x.filter(m=>m.status==="completed").length,tasksTotal:w.length,tasksCompleted:w.filter(m=>m.status==="completed").length,blocked:x.filter(m=>m.status==="blocked").length+w.filter(m=>m.status==="blocked").length},lastSession:u,updatedAt:le};return wl(Wo(e),de),de}function Do(e,t){return No(e,()=>jl(e,t))}function A(e,t){let n=new Set,r=[];for(let o of e){let s=o.replace(/\s+/g," ").trim();if(!s)continue;let i=s.normalize("NFKC").toLowerCase();if(!n.has(i)&&(n.add(i),r.push(s),r.length>=t))break}return r}function zo(e){if(e)return{id:e.id,title:e.title,status:e.status}}function Il(e,t=[]){let n=t.slice(-10);if(n.some(o=>o.status==="failed"))return"failing";if(n.some(o=>o.status==="passed"))return"passing";let r=e.slice(-10).join(`
114
- `).toLowerCase();return/(?:failed|failing|failure|error|✗|❌)/u.test(r)?"failing":/(?:passed|passing|green|success|✓|✅)/u.test(r)?"passing":"unknown"}function Al(e){return v(JSON.stringify(e))}function Pl(e){let t=[];for(let n of e){if(!n)continue;let r=n.match(/https?:\/\/[^\s<>"'`)\]}]+/giu)??[];for(let o of r){let s=o.replace(/[.,;:!?]+$/gu,"").trim();s&&t.push(s)}}return A(t,30)}function qo(e){let{project:t,identity:n,state:r}=e,o=r.activeFiles?.at(-1)??r.filesTouched.at(-1),s=r.phases.filter(k=>k.status==="completed").map(k=>k.title),i=r.tasks.filter(k=>k.status==="completed").map(k=>k.title),a=r.phases.filter(k=>k.status!=="completed"&&k.status!=="cancelled").map(k=>k.title),c=r.tasks.filter(k=>k.status!=="completed"&&k.status!=="cancelled").map(k=>k.title),u=new Set(r.tasks.filter(k=>k.status==="completed").map(k=>k.title.normalize("NFKC").toLowerCase().replace(/\s+/gu," ").trim())),d=A(r.nextActions.filter(k=>!u.has(k.normalize("NFKC").toLowerCase().replace(/\s+/gu," ").trim())),10),l=A([...c,...d],15),f=A(r.tests.slice().reverse(),10),p=A([...(r.activeFiles??[]).slice().reverse(),...r.filesTouched.slice().reverse()],20),g={schema:"toolnet.handoff.v2",version:2,project:{id:t.id,name:t.name},source:{agent:n.agent,nativeSessionId:n.nativeSessionId,sessionKey:n.sessionKey,sequence:e.sequence,reason:e.reason},capturedAt:e.capturedAt??new Date().toISOString(),goal:r.goal,request:r.currentRequest,activity:r.currentActivity,current:{phase:zo(r.currentPhase),task:zo(r.currentTask),file:o},completed:{phases:A(s,20),tasks:A(i,30)},remaining:{phases:A(a,20),tasks:A(c,30),todos:l},nextAction:d[0],blockers:A(r.blockers.slice().reverse(),10),decisions:A(r.decisions.slice().reverse(),10),files:{current:o,recent:p,active:A(r.activeFiles??[],10),modified:A(r.modifiedFiles??[],20),created:A(r.createdFiles??[],20),deleted:A(r.deletedFiles??[],20)},tests:{status:Il(r.tests,r.checks),recent:f,checks:(r.checks??[]).slice(-10).map(k=>({kind:k.kind,status:k.status,command:k.command}))},evidence:{commands:A((r.commands??[]).slice().reverse(),20),references:Pl([r.currentRequest,r.currentActivity,r.goal,r.plan,...r.decisions,...r.blockers,...r.warnings,...r.nextActions,...r.filesTouched,...r.commands??[],...r.tests,...(r.checks??[]).map(k=>k.command)])},attention:A(e.attention??[],20),progress:r.progress},{capturedAt:S,source:y,...h}=g;return{...g,stateDigest:Al(h)}}function El(e){return!!(e.currentRequest||e.currentActivity||e.goal||e.plan||e.phases.length>0||e.tasks.length>0||e.nextActions.length>0||e.blockers.length>0||e.decisions.length>0||e.filesTouched.length>0)}function Ho(e,t,n,r,o){if(!El(n))return null;let s=Eo(e,!1),a=[...s?s.rules.filter(l=>l.mode==="enforce").map(l=>l.text):[],...n.warnings].slice(0,20),c=qo({project:e,identity:t,state:n,reason:r,sequence:o,attention:a}),u=c.stateDigest;return{version:1,id:v([e.id,t.sessionKey,u].join("|")).slice(0,24),projectId:e.id,projectName:e.name,createdAt:new Date().toISOString(),reason:r,sourceSession:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,sequence:o},currentRequest:n.currentRequest,currentActivity:n.currentActivity,goal:n.goal,plan:n.plan,progress:n.progress,currentPhase:n.currentPhase,currentTask:n.currentTask,incompletePhases:n.phases.filter(l=>l.status!=="completed"&&l.status!=="cancelled"),incompleteTasks:n.tasks.filter(l=>l.status!=="completed"&&l.status!=="cancelled"),nextActions:c.remaining.todos.slice(0,10),blockers:n.blockers.slice(-10),decisions:n.decisions.slice(-10),warnings:n.warnings.slice(-10),attention:a,filesTouched:n.filesTouched.slice(-20),activeFiles:n.activeFiles?.slice(-10),modifiedFiles:n.modifiedFiles?.slice(-20),createdFiles:n.createdFiles?.slice(-20),deletedFiles:n.deletedFiles?.slice(-20),tests:n.tests.slice(-15),checks:n.checks?.slice(-10),stateDigest:u,continuity:c}}function Jo(e,t){let n=en(e.rootPath,".toolnet","work","handoffs");Ml(n,{recursive:!0});let r=en(n,`${t.id}.json`);Cl(r)||T(r,t),T(en(e.rootPath,".toolnet","work","handoff-latest.json"),t)}function Vo(e){let t=Ho(e.project,e.identity,e.state,e.reason,e.sequence);return t?(Jo(e.project,t),t):null}var yt=class{constructor(t){this.options=t}options;async capture(t,n){let r=Zt(this.options.project);r||(r=await wo(this.options.project,this.options.storage)),r||(r=await Te(this.options.project,this.options.storage));let o=Ho(this.options.project,this.options.identity,r,t,n);if(!o)return null;Jo(this.options.project,o);let s=`projects/${this.options.project.id}/work/handoffs/${o.id}.json`;return await this.options.storage.exists(s)||await this.options.storage.put(s,JSON.stringify(o,null,2)+`
111
+ `;function Yo(e){return bl(e.rootPath,".toolnet","PROJECT.md")}function jl(e){return e.normalize("NFKC").replace(/\s+/g," ").trim()}function Il(e){let t=[],n=new Set,r=/^\s*[-*]\s+\[(enforce|advisory)\]\s+(.+?)\s*$/gimu,o;for(;o=r.exec(e);){let s=o[1].toLowerCase(),i=jl(o[2]);if(!i)continue;let a=`${s}:${i.toLowerCase()}`;n.has(a)||(n.add(a),t.push({id:w(a).slice(0,24),mode:s,text:i,source:"manual"}))}return t}function Al(e){let t=Yo(e);return Uo(t)||(Sl(wl(t),{recursive:!0}),vl(t,xl,{encoding:"utf8",mode:384})),t}function Xo(e,t=!1){let n=t?Al(e):Yo(e);if(!Uo(n))return null;if(Bo(n).size>Go)throw new Error(`PROJECT.md exceeds ${Go} bytes`);let o=kl(n,"utf8");return{path:n,content:o,digest:w(o),rules:Il(o),bytes:Buffer.byteLength(o,"utf8"),updatedAt:new Date(Bo(n).mtimeMs).toISOString()}}import{randomUUID as Pl}from"node:crypto";import{closeSync as Ml,existsSync as Zo,fsyncSync as Cl,mkdirSync as El,openSync as Ol,readFileSync as Tl,statSync as Rl,unlinkSync as Qo,writeFileSync as Nl}from"node:fs";import{dirname as _l,join as Kl}from"node:path";var $l=new Int32Array(new SharedArrayBuffer(4));function Ll(e){e<=0||Atomics.wait($l,0,0,e)}function Fl(e){return Kl(e.rootPath,".toolnet","work",".current.lock")}function Dl(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code!=="ESRCH"}}function es(e){if(!Zo(e))return null;try{let t=JSON.parse(Tl(e,"utf8"));return t.version!==1||typeof t.token!="string"||typeof t.pid!="number"||typeof t.acquiredAt!="string"?null:{version:1,token:t.token,pid:t.pid,acquiredAt:t.acquiredAt}}catch{return null}}function Wl(e){try{return Date.now()-Rl(e).mtimeMs}catch{return 0}}function zl(e,t){if(!Zo(e)||Wl(e)<t)return!1;let n=es(e);return n?!Dl(n.pid):!0}function ql(e,t){if(!zl(e,t))return!1;try{return Qo(e),!0}catch{return!1}}function Hl(e,t){let n={version:1,token:t,pid:process.pid,acquiredAt:new Date().toISOString()},r=Ol(e,"wx",384);try{Nl(r,`${JSON.stringify(n,null,2)}
112
+ `,{encoding:"utf8"}),Cl(r)}finally{Ml(r)}}function Jl(e,t){if(es(e)?.token===t)try{Qo(e)}catch{}}function Vl(e,t={}){let n=Math.max(100,t.timeoutMs??5e3),r=Math.max(5,t.retryMs??20),o=Math.max(n*2,t.staleMs??3e4),s=Fl(e);El(_l(s),{recursive:!0});let i=Pl(),a=Date.now()+n;for(;;)try{Hl(s,i);let c=!1;return()=>{c||(c=!0,Jl(s,i))}}catch(c){if(c?.code!=="EEXIST")throw c;if(ql(s,o))continue;if(Date.now()>=a)throw new Error(`Timed out acquiring project work lock: ${s}`);Ll(r)}}function ts(e,t,n={}){let r=Vl(e,n);try{return t()}finally{r()}}import{closeSync as Bl,existsSync as Gl,fsyncSync as Ul,mkdirSync as Yl,openSync as Xl,readFileSync as Zl,renameSync as Ql,writeFileSync as ed}from"node:fs";import{dirname as td,join as nd}from"node:path";function rd(e,t){Yl(td(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`,r=Xl(n,"w",384);try{ed(r,`${JSON.stringify(t,null,2)}
113
+ `,{encoding:"utf8"}),Ul(r)}finally{Bl(r)}Ql(n,e)}function as(e){return nd(e.rootPath,".toolnet","work","current.json")}function pn(e){let t=as(e);if(!Gl(t))return null;try{let n=JSON.parse(Zl(t,"utf8"));return n.version!==1||n.projectId!==e.id?null:n}catch{return null}}function At(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function K(e,t,n){let r=[],o=new Set;for(let s of[...e,...t].reverse()){let i=At(s);if(!(!i||o.has(i))&&(o.add(i),r.push(s),r.length>=n))break}return r.reverse()}function od(e,t,n=20){let r=new Map;for(let o of[...e,...t]){let s=`${o.kind}|${At(o.command)}`;r.delete(s),r.set(s,o)}return Array.from(r.values()).slice(-n)}function sd(e){return e.kind==="phase"?/^Phase\s+\d+$/iu.test(e.text):e.kind==="task"?/^(?:TODO|Task|Việc)\s+\d+$/iu.test(e.text):!1}function ns(e,t){let n=t.status??e?.status??"pending",r=n;e?.status==="completed"&&n!=="completed"&&(r="completed"),e&&n==="pending"&&(e.status==="in_progress"||e.status==="blocked")&&(r=e.status);let o=e&&sd(t)?e.title:t.text;return{id:e?.id??t.id,title:o,status:r,order:t.order??e?.order,confidence:Math.max(e?.confidence??0,t.confidence),updatedAt:t.occurredAt,updatedBy:{agent:t.agent,nativeSessionId:t.nativeSessionId,eventId:t.eventId}}}function rs(e){let t=new Map;for(let n of e){let r=n.order!==void 0?`order:${n.order}`:At(n.title);t.set(r,n)}return t}function os(e){return e.order!==void 0?`order:${e.order}`:At(e.key||e.text)}function ss(e){return Array.from(e).sort((t,n)=>{let r=t.order??Number.MAX_SAFE_INTEGER,o=n.order??Number.MAX_SAFE_INTEGER;return r!==o?r-o:t.updatedAt.localeCompare(n.updatedAt)})}function is(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="blocked")??e.find(t=>t.status==="pending")}function id(e,t){let n=pn(e),r=rs(n?.phases??[]),o=rs(n?.tasks??[]),s=n?.currentRequest,i=n?.currentActivity,a=n?.goal,c=n?.plan,u=n?.lastSession,l=[],d=[],p=[],f=[],m=[],S=[...n?.activeFiles??[]],g=[],h=[],v=[],j=[],O=[],C=[],T=[...t].sort((k,E)=>{let H=k.occurredAt.localeCompare(E.occurredAt);return H!==0?H:k.sequence-E.sequence});for(let k of T)switch(k.kind){case"request":s=k.text;break;case"activity":i=k.text;break;case"goal":a=k.text;break;case"plan":c=k.text;break;case"phase":{let E=os(k);r.set(E,ns(r.get(E),k));break}case"task":{let E=os(k);o.set(E,ns(o.get(E),k));break}case"decision":l.push(k.text);break;case"blocker":d.push(k.text);break;case"warning":p.push(k.text);break;case"next_action":f.push(k.text);break;case"file":{m.push(k.text);let E=k.fileAction??"active",H=S.indexOf(k.text);H>=0&&S.splice(H,1),E!=="deleted"&&S.push(k.text),E==="modified"?g.push(k.text):E==="created"?h.push(k.text):E==="deleted"&&v.push(k.text);break}case"command":j.push(k.text);break;case"test":O.push(k.text),k.checkKind&&C.push({kind:k.checkKind,command:k.text,status:k.checkStatus??"unknown",updatedAt:k.occurredAt,agent:k.agent,nativeSessionId:k.nativeSessionId});break;case"session":u={agent:k.agent,nativeSessionId:k.nativeSessionId,sessionKey:k.sessionKey,updatedAt:k.occurredAt};break}let I=ss(r.values()),b=ss(o.values()),W=is(I),z=is(b),Rt=K(n?.nextActions??[],[...f,...z?[z.title]:[],...!z&&W?[W.title]:[],...b.filter(k=>k.status==="pending").slice(0,5).map(k=>k.title)],8),Nt=K(n?.blockers??[],[...d,...I.filter(k=>k.status==="blocked").map(k=>k.title),...b.filter(k=>k.status==="blocked").map(k=>k.title)],20),me=T.length>0?T[T.length-1].occurredAt:n?.updatedAt??new Date().toISOString(),qe={version:1,projectId:e.id,projectName:e.name,currentRequest:s,currentActivity:i,goal:a,plan:c,phases:I,tasks:b,decisions:K(n?.decisions??[],l,20),blockers:Nt,warnings:K(n?.warnings??[],p,20),nextActions:Rt,filesTouched:K(n?.filesTouched??[],m,30),activeFiles:K([],S,5),modifiedFiles:K(n?.modifiedFiles??[],g,30),createdFiles:K(n?.createdFiles??[],h,30),deletedFiles:K(n?.deletedFiles??[],v,30),commands:K(n?.commands??[],j,20),tests:K(n?.tests??[],O,20),checks:od(n?.checks??[],C,20),currentPhase:W,currentTask:z,progress:{phasesTotal:I.length,phasesCompleted:I.filter(k=>k.status==="completed").length,tasksTotal:b.length,tasksCompleted:b.filter(k=>k.status==="completed").length,blocked:I.filter(k=>k.status==="blocked").length+b.filter(k=>k.status==="blocked").length},lastSession:u,updatedAt:me},y=ke(qe);return rd(as(e),y),y}function cs(e,t){return ts(e,()=>id(e,t))}function M(e,t){let n=new Set,r=[];for(let o of e){let s=o.replace(/\s+/g," ").trim();if(!s)continue;let i=s.normalize("NFKC").toLowerCase();if(!n.has(i)&&(n.add(i),r.push(s),r.length>=t))break}return r}function us(e){if(e)return{id:e.id,title:e.title,status:e.status}}function ad(e,t=[]){let n=t.slice(-10);if(n.some(o=>o.status==="failed"))return"failing";if(n.some(o=>o.status==="passed"))return"passing";let r=e.slice(-10).join(`
114
+ `).toLowerCase();return/(?:failed|failing|failure|error|✗|❌)/u.test(r)?"failing":/(?:passed|passing|green|success|✓|✅)/u.test(r)?"passing":"unknown"}function cd(e){return w(JSON.stringify(e))}function ud(e){let t=[];for(let n of e){if(!n)continue;let r=n.match(/https?:\/\/[^\s<>"'`)\]}]+/giu)??[];for(let o of r){let s=o.replace(/[.,;:!?]+$/gu,"").trim();s&&t.push(s)}}return M(t,30)}function ls(e){let{project:t,identity:n,state:r}=e,o=r.activeFiles?.at(-1)??r.filesTouched.at(-1),s=r.phases.filter(v=>v.status==="completed").map(v=>v.title),i=r.tasks.filter(v=>v.status==="completed").map(v=>v.title),a=r.phases.filter(v=>v.status!=="completed"&&v.status!=="cancelled").map(v=>v.title),c=r.tasks.filter(v=>v.status!=="completed"&&v.status!=="cancelled").map(v=>v.title),u=new Set(r.tasks.filter(v=>v.status==="completed").map(v=>v.title.normalize("NFKC").toLowerCase().replace(/\s+/gu," ").trim())),l=M(r.nextActions.filter(v=>!u.has(v.normalize("NFKC").toLowerCase().replace(/\s+/gu," ").trim())),10),d=M([...c,...l],15),p=M(r.tests.slice().reverse(),10),f=M([...(r.activeFiles??[]).slice().reverse(),...r.filesTouched.slice().reverse()],20),m={schema:"toolnet.handoff.v2",version:2,project:{id:t.id,name:t.name},source:{agent:n.agent,nativeSessionId:n.nativeSessionId,sessionKey:n.sessionKey,sequence:e.sequence,reason:e.reason},capturedAt:e.capturedAt??new Date().toISOString(),goal:r.goal,request:r.currentRequest,activity:r.currentActivity,current:{phase:us(r.currentPhase),task:us(r.currentTask),file:o},completed:{phases:M(s,20),tasks:M(i,30)},remaining:{phases:M(a,20),tasks:M(c,30),todos:d},nextAction:l[0],blockers:M(r.blockers.slice().reverse(),10),decisions:M(r.decisions.slice().reverse(),10),files:{current:o,recent:f,active:M(r.activeFiles??[],10),modified:M(r.modifiedFiles??[],20),created:M(r.createdFiles??[],20),deleted:M(r.deletedFiles??[],20)},tests:{status:ad(r.tests,r.checks),recent:p,checks:(r.checks??[]).slice(-10).map(v=>({kind:v.kind,status:v.status,command:v.command}))},evidence:{commands:M((r.commands??[]).slice().reverse(),20),references:ud([r.currentRequest,r.currentActivity,r.goal,r.plan,...r.decisions,...r.blockers,...r.warnings,...r.nextActions,...r.filesTouched,...r.commands??[],...r.tests,...(r.checks??[]).map(v=>v.command)])},attention:M(e.attention??[],20),progress:r.progress},{capturedAt:S,source:g,...h}=m;return{...m,stateDigest:cd(h)}}function pd(e){return!!(e.currentRequest||e.currentActivity||e.goal||e.plan||e.phases.length>0||e.tasks.length>0||e.nextActions.length>0||e.blockers.length>0||e.decisions.length>0||e.filesTouched.length>0)}function ds(e,t,n,r,o){if(!pd(n))return null;let s=Xo(e,!1),a=[...s?s.rules.filter(d=>d.mode==="enforce").map(d=>d.text):[],...n.warnings].slice(0,20),c=ls({project:e,identity:t,state:n,reason:r,sequence:o,attention:a}),u=c.stateDigest;return{version:1,id:w([e.id,t.sessionKey,u].join("|")).slice(0,24),projectId:e.id,projectName:e.name,createdAt:new Date().toISOString(),reason:r,sourceSession:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,sequence:o},currentRequest:n.currentRequest,currentActivity:n.currentActivity,goal:n.goal,plan:n.plan,progress:n.progress,currentPhase:n.currentPhase,currentTask:n.currentTask,incompletePhases:n.phases.filter(d=>d.status!=="completed"&&d.status!=="cancelled"),incompleteTasks:n.tasks.filter(d=>d.status!=="completed"&&d.status!=="cancelled"),nextActions:c.remaining.todos.slice(0,10),blockers:n.blockers.slice(-10),decisions:n.decisions.slice(-10),warnings:n.warnings.slice(-10),attention:a,filesTouched:n.filesTouched.slice(-20),activeFiles:n.activeFiles?.slice(-10),modifiedFiles:n.modifiedFiles?.slice(-20),createdFiles:n.createdFiles?.slice(-20),deletedFiles:n.deletedFiles?.slice(-20),tests:n.tests.slice(-15),checks:n.checks?.slice(-10),stateDigest:u,continuity:c}}function ps(e,t){let n=fn(e.rootPath,".toolnet","work","handoffs");dd(n,{recursive:!0});let r=fn(n,`${t.id}.json`);ld(r)||R(r,t),R(fn(e.rootPath,".toolnet","work","handoff-latest.json"),t)}function fs(e){let t=ds(e.project,e.identity,e.state,e.reason,e.sequence);return t?(ps(e.project,t),t):null}var Pt=class{constructor(t){this.options=t}options;async capture(t,n){let r=pn(this.options.project);r||(r=await zo(this.options.project,this.options.storage)),r||(r=await $e(this.options.project,this.options.storage));let o=ds(this.options.project,this.options.identity,r,t,n);if(!o)return null;ps(this.options.project,o);let s=`projects/${this.options.project.id}/work/handoffs/${o.id}.json`;return await this.options.storage.exists(s)||await this.options.storage.put(s,JSON.stringify(o,null,2)+`
115
115
  `,"application/json"),await this.options.storage.put(`projects/${this.options.project.id}/work/handoff-latest.json`,JSON.stringify(o,null,2)+`
116
- `,"application/json"),o}};import{existsSync as Ol,readFileSync as Tl,writeFileSync as Rl}from"node:fs";import{join as Nl}from"node:path";var Go="<!-- TOOLNET:STABLE-WORK:BEGIN -->",tn="<!-- TOOLNET:STABLE-WORK:END -->";function nn(e){switch(e.status){case"completed":return"[x]";case"in_progress":return"[~]";case"blocked":return"[!]";case"cancelled":return"[-]";default:return"[ ]"}}function F(e,t){return t.length?["",`${e}:`,...t.map(n=>`- ${n}`)]:[]}function Bo(e,t){return t.length?["",`${e}:`,...t.map(n=>`- ${nn(n)} ${n.title}`)]:[]}function _l(e){let t=[Go,"# ToolNet Stable Work State","",`Updated: ${e.updatedAt}`];return e.lastSession&&t.push(`Last agent: ${e.lastSession.agent}`,`Last session: ${e.lastSession.nativeSessionId}`),e.currentRequest&&t.push("","Current request:",e.currentRequest),e.currentActivity&&t.push("","Current activity:",e.currentActivity),e.goal&&t.push("","Goal:",e.goal),e.plan&&t.push("","Plan:",e.plan),e.currentPhase&&t.push("","Current phase:",`${nn(e.currentPhase)} ${e.currentPhase.title}`),e.currentTask&&t.push("","Current task:",`${nn(e.currentTask)} ${e.currentTask.title}`),t.push(...Bo("Phases",e.phases)),t.push(...Bo("TODO / Tasks",e.tasks)),t.push(...F("Next actions",e.nextActions)),t.push(...F("Blockers",e.blockers)),t.push(...F("Important decisions",e.decisions)),t.push(...F("Active files",e.activeFiles??[])),t.push(...F("Modified files",e.modifiedFiles??[])),t.push(...F("Created files",e.createdFiles??[])),t.push(...F("Deleted files",e.deletedFiles??[])),t.push(...F("Files touched",e.filesTouched)),t.push(...F("Recent commands",e.commands??[])),t.push(...F("Checks",(e.checks??[]).map(n=>`[${n.status}] ${n.kind}: ${n.command}`))),t.push("","Progress:",`- Phases: ${e.progress.phasesCompleted}/${e.progress.phasesTotal}`,`- Tasks: ${e.progress.tasksCompleted}/${e.progress.tasksTotal}`,`- Blocked: ${e.progress.blocked}`,"","Continuation:","- Resume current unfinished task.","- Never redo completed TODO/Phase unless explicitly requested.","- Ask ToolNet Memory for deeper history only when necessary.",tn),t.join(`
117
- `)}function Uo(e,t){let n=Nl(e.rootPath,".toolnet","current.md"),r="";if(Ol(n))try{r=Tl(n,"utf8")}catch{r=""}r=r.replace(/<!-- TOOLNET:AUTO-CURRENT:BEGIN -->[\s\S]*?<!-- TOOLNET:AUTO-CURRENT:END -->/gu,"");let o=_l(t),s=r.indexOf(Go),i=r.indexOf(tn),a;s>=0&&i>=s?a=[r.slice(0,s).trimEnd(),o,r.slice(i+tn.length).trimStart()].filter(Boolean).join(`
116
+ `,"application/json"),o}};import{existsSync as fd,readFileSync as md,writeFileSync as gd}from"node:fs";import{join as yd}from"node:path";var gs="<!-- TOOLNET:STABLE-WORK:BEGIN -->",mn="<!-- TOOLNET:STABLE-WORK:END -->";function gn(e){switch(e.status){case"completed":return"[x]";case"in_progress":return"[~]";case"blocked":return"[!]";case"cancelled":return"[-]";default:return"[ ]"}}function D(e,t){return t.length?["",`${e}:`,...t.map(n=>`- ${n}`)]:[]}function ms(e,t){return t.length?["",`${e}:`,...t.map(n=>`- ${gn(n)} ${n.title}`)]:[]}function hd(e){let t=[gs,"# ToolNet Stable Work State","",`Updated: ${e.updatedAt}`];return e.lastSession&&t.push(`Last agent: ${e.lastSession.agent}`,`Last session: ${e.lastSession.nativeSessionId}`),e.currentRequest&&t.push("","Current request:",e.currentRequest),e.currentActivity&&t.push("","Current activity:",e.currentActivity),e.goal&&t.push("","Goal:",e.goal),e.plan&&t.push("","Plan:",e.plan),e.currentPhase&&t.push("","Current phase:",`${gn(e.currentPhase)} ${e.currentPhase.title}`),e.currentTask&&t.push("","Current task:",`${gn(e.currentTask)} ${e.currentTask.title}`),t.push(...ms("Phases",e.phases)),t.push(...ms("TODO / Tasks",e.tasks)),t.push(...D("Next actions",e.nextActions)),t.push(...D("Blockers",e.blockers)),t.push(...D("Important decisions",e.decisions)),t.push(...D("Active files",e.activeFiles??[])),t.push(...D("Modified files",e.modifiedFiles??[])),t.push(...D("Created files",e.createdFiles??[])),t.push(...D("Deleted files",e.deletedFiles??[])),t.push(...D("Files touched",e.filesTouched)),t.push(...D("Recent commands",e.commands??[])),t.push(...D("Checks",(e.checks??[]).map(n=>`[${n.status}] ${n.kind}: ${n.command}`))),t.push("","Progress:",`- Phases: ${e.progress.phasesCompleted}/${e.progress.phasesTotal}`,`- Tasks: ${e.progress.tasksCompleted}/${e.progress.tasksTotal}`,`- Blocked: ${e.progress.blocked}`,"","Continuation:","- Resume current unfinished task.","- Never redo completed TODO/Phase unless explicitly requested.","- Ask ToolNet Memory for deeper history only when necessary.",mn),t.join(`
117
+ `)}function ys(e,t){let n=yd(e.rootPath,".toolnet","current.md"),r="";if(fd(n))try{r=md(n,"utf8")}catch{r=""}r=r.replace(/<!-- TOOLNET:AUTO-CURRENT:BEGIN -->[\s\S]*?<!-- TOOLNET:AUTO-CURRENT:END -->/gu,"");let o=hd(t),s=r.indexOf(gs),i=r.indexOf(mn),a;s>=0&&i>=s?a=[r.slice(0,s).trimEnd(),o,r.slice(i+mn.length).trimStart()].filter(Boolean).join(`
118
118
 
119
119
  `):a=r.trim()?`${r.trim()}
120
120
 
121
- ${o}`:o,Rl(n,`${a.trim()}
122
- `,{encoding:"utf8",mode:384})}import{existsSync as Yo,mkdirSync as Kl,readFileSync as $l}from"node:fs";import{join as rn}from"node:path";function Xo(e){return rn(e.rootPath,".toolnet","memory","checkpoints")}function Qo(e){return rn(Xo(e),"latest.json")}function Ll(e){let t=Qo(e);if(!Yo(t))return null;try{let n=JSON.parse($l(t,"utf8"));return n.schema!=="toolnet.memory.checkpoint.v1"||n.project.id!==e.id?null:n}catch{return null}}function Fl(e){return["rule","architecture","decision","fix"].includes(e)}function Wl(e,t){return t.length===0?[]:et(e,t).candidates.filter(r=>Fl(r.kind)&&r.knowledgeClass!=="transient"&&r.importanceScore>=.65).map(r=>({fingerprint:r.fingerprint,kind:r.kind,content:r.content,knowledgeClass:r.knowledgeClass,importanceScore:r.importanceScore,confidence:r.confidence,createdAt:r.createdAt,agent:e.agent,nativeSessionId:e.nativeSessionId}))}function Dl(e,t){let n=new Map;for(let r of[...e,...t]){let o=n.get(r.fingerprint);(!o||r.importanceScore>o.importanceScore)&&n.set(r.fingerprint,r)}return Array.from(n.values()).sort((r,o)=>o.importanceScore-r.importanceScore||o.createdAt.localeCompare(r.createdAt)).slice(0,80)}function zl(e){return{request:e.currentRequest,activity:e.currentActivity,goal:e.goal,phase:e.currentPhase?{title:e.currentPhase.title,status:e.currentPhase.status}:void 0,task:e.currentTask?{title:e.currentTask.title,status:e.currentTask.status}:void 0,phases:e.phases.map(t=>({title:t.title,status:t.status})),tasks:e.tasks.map(t=>({title:t.title,status:t.status})),activeFiles:e.activeFiles??[],modifiedFiles:e.modifiedFiles??[],createdFiles:e.createdFiles??[],deletedFiles:e.deletedFiles??[],checks:e.checks??[],blockers:e.blockers,decisions:e.decisions,nextActions:e.nextActions}}function Zo(e,t,n,r){let o=Ll(e),s=Dl(o?.durableFacts??[],Wl(t,n)),i=n.at(-1)?.sequence??o?.source.sequence??0,a=r.phases.filter(y=>y.status==="completed").map(y=>y.title),c=r.tasks.filter(y=>y.status==="completed").map(y=>y.title),u=r.phases.filter(y=>y.status!=="completed"&&y.status!=="cancelled").map(y=>y.title),d=r.tasks.filter(y=>y.status!=="completed"&&y.status!=="cancelled").map(y=>y.title),l={work:zl(r),durableFacts:s.map(y=>y.fingerprint).sort()},f=v(JSON.stringify(l)).slice(0,32),p={schema:"toolnet.memory.checkpoint.v1",version:1,project:{id:e.id,name:e.name},source:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,sequence:i},capturedAt:new Date().toISOString(),request:r.currentRequest,activity:r.currentActivity,goal:r.goal,current:{phase:r.currentPhase,task:r.currentTask},completed:{phases:a,tasks:c},remaining:{phases:u,tasks:d},files:{active:r.activeFiles??[],modified:r.modifiedFiles??[],created:r.createdFiles??[],deleted:r.deletedFiles??[]},checks:r.checks??[],blockers:r.blockers.slice(-10),decisions:r.decisions.slice(-15),nextActions:r.nextActions.slice(0,10),durableFacts:s,stateDigest:f},g=Xo(e);Kl(g,{recursive:!0,mode:448});let S=rn(g,`${f}.json`);return Yo(S)||T(S,p),T(Qo(e),p),p}function ht(e,t,n){if(process.env.TOOLNET_LOCAL_CHECKPOINT==="0"||n.length===0)return{updated:!1,observations:0};let r=lt(t,n);if(r.length===0)return{updated:!1,observations:0};let o=Do(e,r);Uo(e,o),Un(e,{agent:t.agent,nativeSessionId:t.nativeSessionId,observations:r,workState:o});try{Zo(e,t,n,o)}catch{}try{Vo({project:e,identity:t,state:o,reason:"continuous-checkpoint",sequence:n.at(-1)?.sequence??0})}catch{}return{updated:!0,observations:r.length}}var St=class{identity;wal;remote;sanitizer=new U;learner;continuity;semantic;handoff;project;title;metadata;constructor(t){this.project=t.project,this.identity=Ve(t.project,t.agent,t.nativeSessionId),this.title=t.title,this.metadata=this.sanitizer.sanitizeValue(t.metadata??{}),this.wal=new ie(this.identity,t.eventContext),this.remote=new Be(t.storage,t.maxEventsPerChunk??100,t.maxChunkBytes??512*1024),this.learner=new ct({project:t.project,storage:t.storage,identity:this.identity,wal:this.wal}),this.continuity=new pt({project:t.project,storage:t.storage,identity:this.identity,wal:this.wal}),this.semantic=new mt({project:t.project,storage:t.storage,identity:this.identity,wal:this.wal}),this.handoff=new yt({project:t.project,storage:t.storage,identity:this.identity})}sanitizeEvent(t){let n=t.provenance?{...t.provenance,metadata:this.sanitizer.sanitizeValue(t.provenance.metadata)}:void 0;return{...t,data:this.sanitizer.sanitizeValue(t.data??{}),provenance:n}}checkpointLocal(t){if(t.length!==0)try{ht(this.project,this.identity,t)}catch{}}start(t={}){let n=this.wal.loadState();return this.record({type:n.lastSequence===0?"session_start":"session_resume",data:t,provenance:{source:this.identity.agent}})}record(t){let n=this.wal.append([this.sanitizeEvent(t)]);return this.checkpointLocal(n),n[0]}recordMany(t){let n=this.wal.append(t.map(r=>this.sanitizeEvent(r)));return this.checkpointLocal(n),n}setSourceCursor(t,n){this.wal.setSourceCursor(t,n)}async flush(){let t=this.wal.readPending(),n=this.wal.loadState(),r=await this.remote.append(this.identity,t.events,n.sourceCursors,{title:this.title,metadata:this.metadata});if(t.events.length>0){let o=t.events[t.events.length-1];this.wal.markRemote(o.sequence,t.endOffset)}if(process.env.TOOLNET_SESSION_LEARNING!=="0")try{await this.learner.learnNew()}catch{}if(process.env.TOOLNET_WORK_CONTINUITY!=="0")try{await this.continuity.learnNew()}catch{}if(process.env.TOOLNET_SEMANTIC_CONTINUITY!=="0")try{await this.semantic.learnNew()}catch{}if(process.env.TOOLNET_SMART_HANDOFF!=="0"&&t.events.length>0)try{let o=t.events[t.events.length-1],s=["session_idle","session_end","session_compact"].includes(o.type)?o.type:"checkpoint";await this.handoff.capture(s,o.sequence)}catch{}return r}async idle(t={}){return this.record({type:"session_idle",data:t,provenance:{source:this.identity.agent}}),this.flush()}async end(t={}){return this.record({type:"session_end",data:t,provenance:{source:this.identity.agent}}),this.flush()}status(){return this.wal.loadState()}recoverRemote(){return this.remote.recover(this.identity)}};var kt=4e3,on=20,sn=30,es=4,an=20;function cn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vt(e,t=0){if(t>=es)return typeof e=="string"?e.length>kt?`${e.slice(0,kt)}\u2026`:e:Array.isArray(e)?`[array:${e.length}]`:cn(e)?`[object:${Object.keys(e).length}]`:e;if(typeof e=="string")return e.length>kt?`${e.slice(0,kt)}\u2026`:e;if(Array.isArray(e)){let n=e.slice(0,on).map(r=>vt(r,t+1));return e.length>on&&n.push(`[+${e.length-on} items]`),n}if(cn(e)){let n={},r=Object.entries(e);for(let[o,s]of r.slice(0,sn))n[o]=vt(s,t+1);return r.length>sn&&(n.__truncatedKeys=r.length-sn),n}return e}function un(e,t,n=0){if(!(n>es||t.size>=an)){if(Array.isArray(e)){for(let r of e)if(un(r,t,n+1),t.size>=an)break;return}if(cn(e))for(let[r,o]of Object.entries(e)){let s=r.toLowerCase().replace(/[^a-z]/g,"");if((s==="path"||s==="filepath"||s==="filename")&&typeof o=="string"&&o.trim()&&t.add(o.trim()),un(o,t,n+1),t.size>=an)break}}}function Re(e){try{return v(Ke(e)).slice(0,20)}catch{return v(String(e)).slice(0,20)}}function ql(e){if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString()}if(typeof e=="string"&&e.trim()){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString()}return new Date().toISOString()}function Hl(e,t){let n=(e??"").toLowerCase();return n==="read"||n==="view"||n.includes("read_file")||n.includes("list_dir")||n.includes("listdir")||n.includes("grep")||n.includes("glob")||n.includes("search")?null:t.length>0&&(n.includes("edit")||n.includes("patch")||n.includes("replace"))?"file_edit":t.length>0&&(n.includes("write")||n.includes("create")||n.includes("delete"))?"file_write":n.includes("bash")||n.includes("shell")||n.includes("terminal")||n.includes("command")||n.includes("execute")?"command":"tool_result"}function ln(e,t){let r={timestamp:ql(e.timestamp),cwd:e.cwd,source:e.agent,provenance:{source:`${e.agent}-hook`}};if(e.event==="SessionStart")return[{...r,type:"session_start",sourceEventId:`${e.agent}:${e.sessionId}:start`,data:{sessionId:e.sessionId,cwd:e.cwd}}];if(e.event==="UserPromptSubmit"){let o=e.prompt?.trim();return o?[{...r,type:"user_prompt",role:"user",sourceEventId:`${e.agent}:${e.sessionId}:prompt:`+Re(o),data:{content:o}}]:[]}if(e.event==="PostToolUse"){let o=new Set;un(e.toolInput,o);let s=[...o],i=Hl(e.toolName,s);if(!i)return[];let a=vt(e.toolInput),c=vt(e.toolResponse);return[{...r,type:i,sourceEventId:[e.agent,e.sessionId,"tool",Re({toolName:e.toolName,input:a,response:c})].join(":"),data:{tool:e.toolName,input:a,response:c,files:s},provenance:{source:`${e.agent}-hook`,files:s.length>0?s:void 0}}]}if(e.event==="AssistantMessage"){let o=e.assistantResponse?.trim();return o?[{...r,type:"assistant_message",role:"assistant",sourceEventId:`${e.agent}:${e.sessionId}:assistant:`+Re(o),data:{content:o}}]:[]}if(e.event==="Stop"){let o=[],s=e.assistantResponse?.trim();return s&&o.push({...r,type:"assistant_message",role:"assistant",sourceEventId:`${e.agent}:${e.sessionId}:assistant:`+Re(s),data:{content:s}}),o.push({...r,type:"session_idle",sourceEventId:`${e.agent}:${e.sessionId}:idle:`+Re({sessionId:e.sessionId,response:s??""}),data:{sessionId:e.sessionId}}),o}return[]}function Bl(e){let t=En(e);if(!t||!Jl(Vl(t,".toolnet","project.json")))return null;try{return new We().detect(t)}catch{return null}}function Gl(e,t){let n=ln(t,e);if(n.length===0)return 0;let r=Ve(e,t.agent,t.sessionId),s=new ie(r,{source:t.agent,cwd:t.cwd}).append(n);return ht(e,r,s),s.length}async function Ul(e,t,n,r){let o=Le(),s=Jn(qn({provider:o.storage.provider,huggingface:o.storage.huggingface,localRoot:o.storage.localRoot}),{attempts:2}),i=new He(s,e.id,e.name,e.remote??e.name);await new St({project:e,storage:i,agent:t,nativeSessionId:n,metadata:{source:`${t}-hook`},eventContext:{source:t,cwd:r}}).flush()}async function ts(e,t={}){if(!e.cwd||!e.sessionId)return{active:!1,captured:0,flushed:!1};let n=Bl(e.cwd);if(!n)return{active:!1,captured:0,flushed:!1};let r=0;try{r=Gl(n,e)}catch(s){return{active:!0,projectRoot:n.rootPath,sessionId:e.sessionId,captured:0,flushed:!1,error:s instanceof Error?s.message:String(s)}}if(e.event==="PostToolUse"||e.event==="AssistantMessage"||e.event==="Stop")try{Xn(n)}catch{}if(e.event!=="Stop")return{active:!0,projectRoot:n.rootPath,sessionId:e.sessionId,captured:r,flushed:!1};let o=t.flushSession??Ul;try{return await o(n,e.agent,e.sessionId,e.cwd),{active:!0,projectRoot:n.rootPath,sessionId:e.sessionId,captured:r,flushed:!0}}catch(s){return{active:!0,projectRoot:n.rootPath,sessionId:e.sessionId,captured:r,flushed:!1,error:s instanceof Error?s.message:String(s)}}}function ns(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Ne(...e){for(let t of e){let n=ns(t);if(n)return n}}function Yl(e){switch(ns(e)){case"SessionStart":case"sessionStart":case"session_start":return"SessionStart";case"UserPromptSubmit":case"userPromptSubmit":case"user_prompt_submit":return"UserPromptSubmit";case"PostToolUse":case"postToolUse":case"post_tool_use":return"PostToolUse";case"Stop":case"stop":return"Stop";default:return null}}function rs(e,t=process.env){let n=Yl(t.TOOLNET_HOOK_EVENT??e.hookEventName??e.hook_event_name);if(!n)return null;let r=Ne(e.sessionId,e.session_id,t.GROK_SESSION_ID),o=Ne(e.cwd,e.workspaceRoot,t.GROK_WORKSPACE_ROOT,t.CLAUDE_PROJECT_DIR);return!r||!o?null:{agent:"grok",event:n,sessionId:r,cwd:o,timestamp:typeof e.timestamp=="string"||typeof e.timestamp=="number"?e.timestamp:void 0,prompt:Ne(e.prompt),toolName:Ne(e.toolName,e.tool_name),toolInput:e.toolInput??e.tool_input,toolResponse:e.toolResult??e.tool_result??e.toolResponse,assistantResponse:Ne(e.response,e.assistantResponse,e.lastAssistantMessage)}}async function os(e,t={},n=process.env){let r=rs(e,n);return r?ts(r,t):{active:!1,captured:0,flushed:!1}}import{createHash as Xl}from"node:crypto";import{closeSync as Ql,existsSync as Zl,mkdirSync as ed,openSync as td,readFileSync as nd,rmSync as rd,statSync as ss,writeFileSync as od}from"node:fs";import{tmpdir as sd}from"node:os";import{join as is}from"node:path";function P(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function dn(e){if(Array.isArray(e))return e.map(dn);if(e&&typeof e=="object"){let t=e;return Object.fromEntries(Object.keys(t).sort().map(n=>[n,dn(t[n])]))}return e}function wt(e){return P(e.sessionId)??P(e.session_id)??P(e.conversation_id)??P(e.conversationId)??"unknown-session"}function id(e){return P(e.toolUseId)??P(e.tool_use_id)??P(e.toolCallId)??P(e.tool_call_id)??P(e.callId)??P(e.call_id)??P(e.generation_id)??P(e.generationId)}function ad(e){return P(e.prompt)??P(e.userPrompt)??P(e.user_prompt)??P(e.originalPrompt)??P(e.original_prompt)}function cd(e){let t=e.timestamp;return typeof t=="string"||typeof t=="number"?String(t):void 0}function ud(e){let t=id(e.input),n=ad(e.input),r=cd(e.input),o=t?{agent:e.agent,event:e.event,session:wt(e.input),nativeId:t}:n?{agent:e.agent,event:e.event,session:wt(e.input),prompt:n,timestamp:r}:{agent:e.agent,event:e.event,session:wt(e.input),input:dn(e.input)};return Xl("sha256").update(JSON.stringify(o)).digest("hex")}function ld(e){return e.directory??is(sd(),"toolnet-memory-hook-dedupe")}function dd(e){try{let t=JSON.parse(nd(e,"utf8"));return typeof t.createdAt=="number"?t.createdAt:ss(e).mtimeMs}catch{try{return ss(e).mtimeMs}catch{return}}}function pd(e,t,n){let r=dd(e);return r===void 0||t-r>n}function as(e){let t=e.ttlMs??1e4,n=e.nowMs??Date.now(),r=ld(e),o=ud(e),s=is(r,`${o}.json`);ed(r,{recursive:!0,mode:448});for(let i=0;i<2;i+=1)try{let a=td(s,"wx",384);try{od(a,JSON.stringify({createdAt:n,agent:e.agent,event:e.event,sessionId:wt(e.input)}),"utf8")}finally{Ql(a)}return{duplicate:!1,key:o,file:s}}catch(a){if((a&&typeof a=="object"&&"code"in a?String(a.code):"")!=="EEXIST")throw a;if(i===0&&Zl(s)&&pd(s,n,t)){rd(s,{force:!0});continue}return{duplicate:!0,key:o,file:s}}return{duplicate:!0,key:o,file:s}}import{spawn as fd}from"node:child_process";function cs(e){return(e??"").trim()}function us(e,t={}){let n=cs(e);if(!n)return!1;let r=cs(t.binary??process.env.TOOLNET_MEMORY_BIN)||"toolnet-memory";try{let o=fd(r,["background:refresh","--project",n,"--quiet"],{detached:!0,stdio:"ignore",env:process.env});return o.on("error",()=>{}),o.unref(),!0}catch{return!1}}async function md(){let e="";for await(let t of process.stdin)e+=t.toString();if(!e.trim())return{};try{return JSON.parse(e)}catch{return{}}}async function gd(){let e=await md(),t=Rn(e);if(t==="PreToolUse"||t==="preToolUse"||t==="pre_tool_use"){let o=Nn(e);o.blocked&&process.stdout.write(JSON.stringify(_n(o.reason??"ToolNet continuity guard blocked this tool.")));return}if(t&&as({agent:"grok",event:t,input:e,directory:process.env.TOOLNET_HOOK_DEDUPE_DIR}).duplicate)return;let n=await os(e);(t==="SessionStart"||t==="sessionStart"||t==="session_start"||t==="Stop"||t==="stop")&&n.projectRoot&&us(n.projectRoot)}gd().catch(()=>{process.exitCode=0});
121
+ ${o}`:o,gd(n,`${a.trim()}
122
+ `,{encoding:"utf8",mode:384})}import{existsSync as hs,mkdirSync as Sd,readFileSync as kd}from"node:fs";import{join as yn}from"node:path";function Ss(e){return yn(e.rootPath,".toolnet","memory","checkpoints")}function ks(e){return yn(Ss(e),"latest.json")}function vd(e){let t=ks(e);if(!hs(t))return null;try{let n=JSON.parse(kd(t,"utf8"));return n.schema!=="toolnet.memory.checkpoint.v1"||n.project.id!==e.id?null:n}catch{return null}}function wd(e){return["rule","architecture","decision","fix"].includes(e)}function bd(e,t){return t.length===0?[]:dt(e,t).candidates.filter(r=>wd(r.kind)&&r.knowledgeClass!=="transient"&&r.importanceScore>=.65).map(r=>({fingerprint:r.fingerprint,kind:r.kind,content:r.content,knowledgeClass:r.knowledgeClass,importanceScore:r.importanceScore,confidence:r.confidence,createdAt:r.createdAt,agent:e.agent,nativeSessionId:e.nativeSessionId}))}function xd(e,t){let n=new Map;for(let r of[...e,...t]){let o=n.get(r.fingerprint);(!o||r.importanceScore>o.importanceScore)&&n.set(r.fingerprint,r)}return Array.from(n.values()).sort((r,o)=>o.importanceScore-r.importanceScore||o.createdAt.localeCompare(r.createdAt)).slice(0,80)}function jd(e){return{request:e.currentRequest,activity:e.currentActivity,goal:e.goal,phase:e.currentPhase?{title:e.currentPhase.title,status:e.currentPhase.status}:void 0,task:e.currentTask?{title:e.currentTask.title,status:e.currentTask.status}:void 0,phases:e.phases.map(t=>({title:t.title,status:t.status})),tasks:e.tasks.map(t=>({title:t.title,status:t.status})),activeFiles:e.activeFiles??[],modifiedFiles:e.modifiedFiles??[],createdFiles:e.createdFiles??[],deletedFiles:e.deletedFiles??[],checks:e.checks??[],blockers:e.blockers,decisions:e.decisions,nextActions:e.nextActions}}function vs(e,t,n,r){let o=vd(e),s=xd(o?.durableFacts??[],bd(t,n)),i=n.at(-1)?.sequence??o?.source.sequence??0,a=r.phases.filter(g=>g.status==="completed").map(g=>g.title),c=r.tasks.filter(g=>g.status==="completed").map(g=>g.title),u=r.phases.filter(g=>g.status!=="completed"&&g.status!=="cancelled").map(g=>g.title),l=r.tasks.filter(g=>g.status!=="completed"&&g.status!=="cancelled").map(g=>g.title),d={work:jd(r),durableFacts:s.map(g=>g.fingerprint).sort()},p=w(JSON.stringify(d)).slice(0,32),f={schema:"toolnet.memory.checkpoint.v1",version:1,project:{id:e.id,name:e.name},source:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,sequence:i},capturedAt:new Date().toISOString(),request:r.currentRequest,activity:r.currentActivity,goal:r.goal,current:{phase:r.currentPhase,task:r.currentTask},completed:{phases:a,tasks:c},remaining:{phases:u,tasks:l},files:{active:r.activeFiles??[],modified:r.modifiedFiles??[],created:r.createdFiles??[],deleted:r.deletedFiles??[]},checks:r.checks??[],blockers:r.blockers.slice(-10),decisions:r.decisions.slice(-15),nextActions:r.nextActions.slice(0,10),durableFacts:s,stateDigest:p},m=Ss(e);Sd(m,{recursive:!0,mode:448});let S=yn(m,`${p}.json`);return hs(S)||R(S,f),R(ks(e),f),f}function Mt(e,t,n){if(process.env.TOOLNET_LOCAL_CHECKPOINT==="0"||n.length===0)return{updated:!1,observations:0};let r=wt(t,n);if(r.length===0)return{updated:!1,observations:0};let o=cs(e,r);ys(e,o),yr(e,{agent:t.agent,nativeSessionId:t.nativeSessionId,observations:r,workState:o});try{vs(e,t,n,o)}catch{}try{fs({project:e,identity:t,state:o,reason:"continuous-checkpoint",sequence:n.at(-1)?.sequence??0})}catch{}return{updated:!0,observations:r.length}}var Ct=class{identity;wal;remote;sanitizer=new V;learner;continuity;semantic;handoff;project;title;metadata;constructor(t){this.project=t.project,this.identity=rt(t.project,t.agent,t.nativeSessionId),this.title=t.title,this.metadata=this.sanitizer.sanitizeValue(t.metadata??{}),this.wal=new le(this.identity,t.eventContext),this.remote=new ot(t.storage,t.maxEventsPerChunk??100,t.maxChunkBytes??512*1024),this.learner=new kt({project:t.project,storage:t.storage,identity:this.identity,wal:this.wal}),this.continuity=new xt({project:t.project,storage:t.storage,identity:this.identity,wal:this.wal}),this.semantic=new It({project:t.project,storage:t.storage,identity:this.identity,wal:this.wal}),this.handoff=new Pt({project:t.project,storage:t.storage,identity:this.identity})}sanitizeEvent(t){let n=t.provenance?{...t.provenance,metadata:this.sanitizer.sanitizeValue(t.provenance.metadata)}:void 0;return{...t,data:this.sanitizer.sanitizeValue(t.data??{}),provenance:n}}checkpointLocal(t){if(t.length!==0)try{Mt(this.project,this.identity,t)}catch{}}start(t={}){let n=this.wal.loadState();return this.record({type:n.lastSequence===0?"session_start":"session_resume",data:t,provenance:{source:this.identity.agent}})}record(t){let n=this.wal.append([this.sanitizeEvent(t)]);return this.checkpointLocal(n),n[0]}recordMany(t){let n=this.wal.append(t.map(r=>this.sanitizeEvent(r)));return this.checkpointLocal(n),n}setSourceCursor(t,n){this.wal.setSourceCursor(t,n)}async flush(){let t=this.wal.readPending(),n=this.wal.loadState(),r=await this.remote.append(this.identity,t.events,n.sourceCursors,{title:this.title,metadata:this.metadata});if(t.events.length>0){let o=t.events[t.events.length-1];this.wal.markRemote(o.sequence,t.endOffset)}if(process.env.TOOLNET_SESSION_LEARNING!=="0")try{await this.learner.learnNew()}catch{}if(process.env.TOOLNET_WORK_CONTINUITY!=="0")try{await this.continuity.learnNew()}catch{}if(process.env.TOOLNET_SEMANTIC_CONTINUITY!=="0")try{await this.semantic.learnNew()}catch{}if(process.env.TOOLNET_SMART_HANDOFF!=="0"&&t.events.length>0)try{let o=t.events[t.events.length-1],s=["session_idle","session_end","session_compact"].includes(o.type)?o.type:"checkpoint";await this.handoff.capture(s,o.sequence)}catch{}return r}async idle(t={}){return this.record({type:"session_idle",data:t,provenance:{source:this.identity.agent}}),this.flush()}async end(t={}){return this.record({type:"session_end",data:t,provenance:{source:this.identity.agent}}),this.flush()}status(){return this.wal.loadState()}recoverRemote(){return this.remote.recover(this.identity)}};var Et=4e3,hn=20,Sn=30,ws=4,kn=20;function vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ot(e,t=0){if(t>=ws)return typeof e=="string"?e.length>Et?`${e.slice(0,Et)}\u2026`:e:Array.isArray(e)?`[array:${e.length}]`:vn(e)?`[object:${Object.keys(e).length}]`:e;if(typeof e=="string")return e.length>Et?`${e.slice(0,Et)}\u2026`:e;if(Array.isArray(e)){let n=e.slice(0,hn).map(r=>Ot(r,t+1));return e.length>hn&&n.push(`[+${e.length-hn} items]`),n}if(vn(e)){let n={},r=Object.entries(e);for(let[o,s]of r.slice(0,Sn))n[o]=Ot(s,t+1);return r.length>Sn&&(n.__truncatedKeys=r.length-Sn),n}return e}function wn(e,t,n=0){if(!(n>ws||t.size>=kn)){if(Array.isArray(e)){for(let r of e)if(wn(r,t,n+1),t.size>=kn)break;return}if(vn(e))for(let[r,o]of Object.entries(e)){let s=r.toLowerCase().replace(/[^a-z]/g,"");if((s==="path"||s==="filepath"||s==="filename")&&typeof o=="string"&&o.trim()&&t.add(o.trim()),wn(o,t,n+1),t.size>=kn)break}}}function Le(e){try{return w(Je(e)).slice(0,20)}catch{return w(String(e)).slice(0,20)}}function Id(e){if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString()}if(typeof e=="string"&&e.trim()){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString()}return new Date().toISOString()}function Ad(e,t){let n=(e??"").toLowerCase();return n==="read"||n==="view"||n.includes("read_file")||n.includes("list_dir")||n.includes("listdir")||n.includes("grep")||n.includes("glob")||n.includes("search")?null:t.length>0&&(n.includes("edit")||n.includes("patch")||n.includes("replace"))?"file_edit":t.length>0&&(n.includes("write")||n.includes("create")||n.includes("delete"))?"file_write":n.includes("bash")||n.includes("shell")||n.includes("terminal")||n.includes("command")||n.includes("execute")?"command":"tool_result"}function bn(e,t){let r={timestamp:Id(e.timestamp),cwd:e.cwd,source:e.agent,provenance:{source:`${e.agent}-hook`}};if(e.event==="SessionStart")return[{...r,type:"session_start",sourceEventId:`${e.agent}:${e.sessionId}:start`,data:{sessionId:e.sessionId,cwd:e.cwd}}];if(e.event==="UserPromptSubmit"){let o=e.prompt?.trim();return o?[{...r,type:"user_prompt",role:"user",sourceEventId:`${e.agent}:${e.sessionId}:prompt:`+Le(o),data:{content:o}}]:[]}if(e.event==="PostToolUse"){let o=new Set;wn(e.toolInput,o);let s=[...o],i=Ad(e.toolName,s);if(!i)return[];let a=Ot(e.toolInput),c=Ot(e.toolResponse);return[{...r,type:i,sourceEventId:[e.agent,e.sessionId,"tool",Le({toolName:e.toolName,input:a,response:c})].join(":"),data:{tool:e.toolName,input:a,response:c,files:s},provenance:{source:`${e.agent}-hook`,files:s.length>0?s:void 0}}]}if(e.event==="AssistantMessage"){let o=e.assistantResponse?.trim();return o?[{...r,type:"assistant_message",role:"assistant",sourceEventId:`${e.agent}:${e.sessionId}:assistant:`+Le(o),data:{content:o}}]:[]}if(e.event==="Stop"){let o=[],s=e.assistantResponse?.trim();return s&&o.push({...r,type:"assistant_message",role:"assistant",sourceEventId:`${e.agent}:${e.sessionId}:assistant:`+Le(s),data:{content:s}}),o.push({...r,type:"session_idle",sourceEventId:`${e.agent}:${e.sessionId}:idle:`+Le({sessionId:e.sessionId,response:s??""}),data:{sessionId:e.sessionId}}),o}return[]}function Cd(e){let t=qn(e);if(!t||!Pd(Md(t,".toolnet","project.json")))return null;try{return new Ze().detect(t)}catch{return null}}function Ed(e,t){let n=bn(t,e);if(n.length===0)return 0;let r=rt(e,t.agent,t.sessionId),s=new le(r,{source:t.agent,cwd:t.cwd}).append(n);return Mt(e,r,s),s.length}async function Od(e,t,n,r){let o=Be(),s=pr(lr({provider:o.storage.provider,huggingface:o.storage.huggingface,localRoot:o.storage.localRoot}),{attempts:2}),i=new tt(s,e.id,e.name,e.remote??e.name);await new Ct({project:e,storage:i,agent:t,nativeSessionId:n,metadata:{source:`${t}-hook`},eventContext:{source:t,cwd:r}}).flush()}async function bs(e,t={}){if(!e.cwd||!e.sessionId)return{active:!1,captured:0,flushed:!1};let n=Cd(e.cwd);if(!n)return{active:!1,captured:0,flushed:!1};let r=0;try{r=Ed(n,e)}catch(s){return{active:!0,projectRoot:n.rootPath,sessionId:e.sessionId,captured:0,flushed:!1,error:s instanceof Error?s.message:String(s)}}if(e.event==="PostToolUse"||e.event==="AssistantMessage"||e.event==="Stop")try{Sr(n)}catch{}if(e.event!=="Stop")return{active:!0,projectRoot:n.rootPath,sessionId:e.sessionId,captured:r,flushed:!1};let o=t.flushSession??Od;try{return await o(n,e.agent,e.sessionId,e.cwd),{active:!0,projectRoot:n.rootPath,sessionId:e.sessionId,captured:r,flushed:!0}}catch(s){return{active:!0,projectRoot:n.rootPath,sessionId:e.sessionId,captured:r,flushed:!1,error:s instanceof Error?s.message:String(s)}}}function xs(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Fe(...e){for(let t of e){let n=xs(t);if(n)return n}}function Td(e){switch(xs(e)){case"SessionStart":case"sessionStart":case"session_start":return"SessionStart";case"UserPromptSubmit":case"userPromptSubmit":case"user_prompt_submit":return"UserPromptSubmit";case"PostToolUse":case"postToolUse":case"post_tool_use":return"PostToolUse";case"Stop":case"stop":return"Stop";default:return null}}function js(e,t=process.env){let n=Td(t.TOOLNET_HOOK_EVENT??e.hookEventName??e.hook_event_name);if(!n)return null;let r=Fe(e.sessionId,e.session_id,t.GROK_SESSION_ID),o=Fe(e.cwd,e.workspaceRoot,t.GROK_WORKSPACE_ROOT,t.CLAUDE_PROJECT_DIR);return!r||!o?null:{agent:"grok",event:n,sessionId:r,cwd:o,timestamp:typeof e.timestamp=="string"||typeof e.timestamp=="number"?e.timestamp:void 0,prompt:Fe(e.prompt),toolName:Fe(e.toolName,e.tool_name),toolInput:e.toolInput??e.tool_input,toolResponse:e.toolResult??e.tool_result??e.toolResponse,assistantResponse:Fe(e.response,e.assistantResponse,e.lastAssistantMessage)}}async function Is(e,t={},n=process.env){let r=js(e,n);return r?bs(r,t):{active:!1,captured:0,flushed:!1}}import{createHash as Rd,randomUUID as Nd}from"node:crypto";import{closeSync as _d,existsSync as In,fsyncSync as Kd,mkdirSync as $d,openSync as Ld,readFileSync as Ps,readdirSync as Fd,rmSync as Dd,statSync as Ms,writeFileSync as Wd}from"node:fs";import{tmpdir as zd}from"node:os";import{dirname as qd,join as De,parse as Hd,resolve as We}from"node:path";var Jd=1e4,Vd=64,xn=2;function x(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Cs(e){return Rd("sha256").update(e).digest("hex")}function ze(e){if(Array.isArray(e))return e.map(ze);if(e&&typeof e=="object"){let t=e;return Object.fromEntries(Object.keys(t).sort().map(n=>[n,ze(t[n])]))}return e}function Es(e){return x(e.sessionId)??x(e.session_id)??x(e.conversation_id)??x(e.conversationId)??"unknown-session"}function Bd(e){return x(e.toolUseId)??x(e.tool_use_id)??x(e.toolCallId)??x(e.tool_call_id)??x(e.callId)??x(e.call_id)??x(e.generation_id)??x(e.generationId)??x(e.sourceEventId)??x(e.source_event_id)}function Gd(e){return x(e.prompt)??x(e.userPrompt)??x(e.user_prompt)??x(e.originalPrompt)??x(e.original_prompt)}function Ud(e){let t=e.timestamp;return typeof t=="string"||typeof t=="number"?String(t):void 0}var Yd=new Set(["pid","processId","process_id","cwd","projectRoot","project_root","hookSource","hook_source","transformedPrompt","transformed_prompt","sessionId","session_id","conversation_id","conversationId","toolUseId","tool_use_id","toolCallId","tool_call_id","callId","call_id","generation_id","generationId","sourceEventId","source_event_id","timestamp"]);function Xd(e,t){if(!t)return e;let n=e.replaceAll("\\","/"),r=We(t).replaceAll("\\","/").replace(/\/+$/u,"");return!r||!n.includes(r)?e:n.split(r).join("<PROJECT>")}function Tt(e,t){if(typeof e=="string")return Xd(e,t);if(Array.isArray(e))return e.map(n=>Tt(n,t));if(e&&typeof e=="object"){let n=e,r={};for(let o of Object.keys(n).sort())Yd.has(o)||(r[o]=Tt(n[o],t));return r}return e}function Zd(e,t){let n=Tt(e,t);return Cs(JSON.stringify(ze(n)))}function Qd(e){return De(e,".toolnet","project.json")}function Os(e){let t=We(e),n=Qd(t);if(!In(n))return null;let r;try{r=JSON.parse(Ps(n,"utf8"))}catch{return null}if(!r||typeof r!="object"||Array.isArray(r))return null;let o=x(r.id);return o?{root:t,id:o}:null}function ep(e){let t=We(e),n=Hd(t).root;for(;;){let r=Os(t);if(r)return r;if(t===n)return null;let o=qd(t);if(o===t)return null;t=o}}function tp(e){return x(e.cwd)??x(e.projectRoot)??x(e.project_root)}function As(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function np(e){if(e.directory)return{directory:We(e.directory),scope:"explicit",...e.projectRoot?{projectRoot:We(e.projectRoot)}:{},...e.projectId?{projectId:e.projectId}:{}};let t=null;if(e.projectRoot&&(t=Os(e.projectRoot)),!t){let n=tp(e.input)??process.cwd();t=ep(n)}if(t){if(e.projectId&&e.projectId!==t.id)throw new Error(["Hook dedupe project mismatch.",`Expected: ${e.projectId}.`,`Resolved: ${t.id}.`].join(" "));return{directory:De(t.root,".toolnet","runtime","dedupe","hooks"),scope:"project",projectRoot:t.root,projectId:t.id}}return{directory:De(zd(),"toolnet-memory-hook-dedupe"),scope:"temporary",...e.projectId?{projectId:e.projectId}:{}}}function rp(e,t,n){let r=Bd(e.input),o=Gd(e.input),s=Ud(e.input),i={projectId:t.projectId??e.projectId??"unscoped",agent:e.agent,event:e.event,session:Es(e.input),payloadFingerprint:n},a=r?{...i,nativeId:r}:o?{...i,prompt:o,timestamp:s}:{...i,input:ze(Tt(e.input,t.projectRoot))};return Cs(JSON.stringify(ze(a)))}function jn(e){if(!In(e))return null;let t;try{t=JSON.parse(Ps(e,"utf8"))}catch{return null}if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t;return n.version!==xn||typeof n.token!="string"||!n.token||typeof n.createdAt!="number"||!Number.isFinite(n.createdAt)||typeof n.agent!="string"||typeof n.event!="string"||typeof n.sessionId!="string"||typeof n.payloadFingerprint!="string"?null:{version:xn,token:n.token,createdAt:n.createdAt,...typeof n.projectId=="string"&&n.projectId?{projectId:n.projectId}:{},agent:n.agent,event:n.event,sessionId:n.sessionId,payloadFingerprint:n.payloadFingerprint}}function op(e){let t=jn(e);if(t)return t.createdAt;try{return Ms(e).mtimeMs}catch{return}}function sp(e,t,n){let r=op(e);return r===void 0?!0:t-r>n}function Ts(e,t,n){if(!In(e))return!0;if(!sp(e,t,n))return!1;let r=jn(e);if(r){let o=jn(e);if(!o||o.token!==r.token||o.createdAt!==r.createdAt||t-o.createdAt<=n)return!1}else{let o=0;try{o=t-Ms(e).mtimeMs}catch{return!0}if(o<=n)return!1}try{return Dd(e,{force:!0}),!0}catch{return!1}}function ip(e,t,n,r,o){let s;try{s=Fd(e)}catch{return 0}let i=0,a=0;for(let c of s.sort()){if(i>=r)break;if(!c.endsWith(".json"))continue;let u=De(e,c);o&&u===o||(i+=1,Ts(u,t,n)&&(a+=1))}return a}function Rs(e){let t=As(e.ttlMs??Jd,"ttlMs"),n=As(e.cleanupLimit??Vd,"cleanupLimit"),r=e.nowMs??Date.now(),o=np(e),s=Zd(e.input,o.projectRoot),i=rp(e,o,s),a=De(o.directory,`${i}.json`);$d(o.directory,{recursive:!0,mode:448}),ip(o.directory,r,t,n,a);for(let c=0;c<2;c+=1){let u=Nd();try{let l=Ld(a,"wx",384),d={version:xn,token:u,createdAt:r,...o.projectId?{projectId:o.projectId}:{},agent:e.agent,event:e.event,sessionId:Es(e.input),payloadFingerprint:s};try{Wd(l,`${JSON.stringify(d)}
123
+ `,"utf8"),Kd(l)}finally{_d(l)}return{duplicate:!1,key:i,file:a,directory:o.directory,scope:o.scope,...o.projectId?{projectId:o.projectId}:{},payloadFingerprint:s}}catch(l){if((l&&typeof l=="object"&&"code"in l?String(l.code):"")!=="EEXIST")throw l;if(c===0&&Ts(a,r,t))continue;return{duplicate:!0,key:i,file:a,directory:o.directory,scope:o.scope,...o.projectId?{projectId:o.projectId}:{},payloadFingerprint:s}}}return{duplicate:!0,key:i,file:a,directory:o.directory,scope:o.scope,...o.projectId?{projectId:o.projectId}:{},payloadFingerprint:s}}import{spawn as ap}from"node:child_process";function Ns(e){return(e??"").trim()}function _s(e,t={}){let n=Ns(e);if(!n)return!1;let r=Ns(t.binary??process.env.TOOLNET_MEMORY_BIN)||"toolnet-memory";try{let o=ap(r,["background:refresh","--project",n,"--quiet"],{detached:!0,stdio:"ignore",env:process.env});return o.on("error",()=>{}),o.unref(),!0}catch{return!1}}async function cp(){let e="";for await(let t of process.stdin)e+=t.toString();if(!e.trim())return{};try{return JSON.parse(e)}catch{return{}}}async function up(){let e=await cp(),t=Vn(e);if(t==="PreToolUse"||t==="preToolUse"||t==="pre_tool_use"){let o=Bn(e);o.blocked&&process.stdout.write(JSON.stringify(Gn(o.reason??"ToolNet continuity guard blocked this tool.")));return}if(t&&Rs({agent:"grok",event:t,input:e,directory:process.env.TOOLNET_HOOK_DEDUPE_DIR}).duplicate)return;let n=await Is(e);(t==="SessionStart"||t==="sessionStart"||t==="session_start"||t==="Stop"||t==="stop")&&n.projectRoot&&_s(n.projectRoot)}up().catch(()=>{process.exitCode=0});