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
package/bundle/codex.js CHANGED
@@ -1,61 +1,61 @@
1
- import{existsSync as Rd,readFileSync as Nd}from"node:fs";import{spawn as _d}from"node:child_process";import{homedir as $d}from"node:os";import{join as Kd}from"node:path";import{existsSync as mo,readFileSync as go}from"node:fs";import{homedir as yo}from"node:os";import{join as ho}from"node:path";function So(t){let e=t.trim();return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?(e=e.slice(1,-1),e.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function ko(){let t=process.env.TOOLNET_GLOBAL_ENV??ho(yo(),".config","toolnet-memory",".env");if(!mo(t))return;let e=go(t,"utf8");for(let n of e.split(/\r?\n/)){let r=n.trim();if(!r||r.startsWith("#"))continue;r.startsWith("export ")&&(r=r.slice(7));let s=r.indexOf("=");if(s<=0)continue;let o=r.slice(0,s).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)&&process.env[o]===void 0&&(process.env[o]=So(r.slice(s+1)))}}ko();function pe(t,e){return t===void 0?e:["1","true","yes","on"].includes(t.toLowerCase())}function fe(t,e){if(!t)return e;let n=Number(t);return Number.isFinite(n)?n:e}function Ne(){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 vo}from"node:crypto";import{existsSync as Pt,mkdirSync as wo,readFileSync as bo,renameSync as xo,writeFileSync as jo}from"node:fs";import{basename as Co,dirname as _e,join as $e,parse as Sn,resolve as me}from"node:path";var kn=".toolnet",Io="project.json";function Ao(t){return vo("sha256").update(t).digest("hex").slice(0,16)}function Et(t){return $e(t,kn,Io)}function Mo(t){return Pt(Et(t))}function Po(t,e){let n=me(t),r=Sn(n).root;for(;;){if(Mo(n))return n;if(n===r||e&&n===me(e))break;let s=_e(n);if(s===n)break;n=s}return null}function Eo(t){let e=me(t),n=Sn(e).root,r=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(r.some(o=>Pt($e(e,o))))return e;if(e===n)break;let s=_e(e);if(s===e)break;e=s}return me(t)}function Oo(t){let e;try{e=JSON.parse(bo(t,"utf8"))}catch(s){throw new Error(`Invalid ToolNet project manifest: ${t}: ${s instanceof Error?s.message:String(s)}`)}if(!e||typeof e!="object")throw new Error(`Invalid ToolNet project manifest: ${t}`);let n=e;if(typeof n.id!="string"||!n.id.trim())throw new Error(`ToolNet project manifest is missing id: ${t}`);if(typeof n.name!="string"||!n.name.trim())throw new Error(`ToolNet project manifest is missing name: ${t}`);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:_e(_e(t)),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 yn(t,e){let n=$e(t,kn);wo(n,{recursive:!0});let r=Et(t),s=`${r}.tmp-${process.pid}`;jo(s,JSON.stringify(e,null,2)+`
3
- `,{encoding:"utf8",mode:384}),xo(s,r)}function hn(t,e){return{id:t.id,name:t.name,remote:t.remote,rootPath:e,createdAt:t.createdAt,updatedAt:t.updatedAt,graphVersion:t.graphVersion,memoryVersion:t.memoryVersion,metadata:t.metadata}}var ne=class{detect(e=process.cwd()){let n=me(e),r=Eo(n),o=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(p=>Pt($e(r,p))),i=Po(n,o?r:void 0);if(i){let p=Et(i),l=Oo(p);return l.rootPath!==i&&(l.rootPath=i,l.updatedAt=new Date().toISOString(),yn(i,l)),hn(l,i)}let a=new Date().toISOString(),c=Co(r),u={version:1,id:Ao(r),name:c,remote:c,rootPath:r,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0};return yn(r,u),hn(u,r)}};var To=[{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}],Ke=class{scan(e){let n=[];for(let r of To){let s=new RegExp(r.regex.source,r.regex.flags);for(let o of e.matchAll(s))n.push({type:r.type,value:o[0]})}return n}hasSecrets(e){return this.scan(e).length>0}};var G=class{scanner=new Ke;sanitize(e){let n=e,r=this.scanner.scan(e),s=new Set;for(let o of r)s.add(o.type),n=n.split(o.value).join(`[REDACTED:${o.type}]`);return{text:n,redacted:r.length,secretTypes:[...s]}}sanitizeValue(e){if(typeof e=="string")return this.sanitize(e).text;if(Array.isArray(e))return e.map(n=>this.sanitizeValue(n));if(e&&typeof e=="object"){let n={};for(let[r,s]of Object.entries(e)){let o=r.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"");o.includes("password")||o.includes("passwd")||o==="pwd"||o.includes("secret")||o.includes("token")||o.includes("cookie")||o.includes("authorization")||o.includes("apikey")||o.includes("accesskey")||o.includes("privatekey")||o.includes("clientsecret")||o.includes("credential")?n[r]="[REDACTED]":n[r]=this.sanitizeValue(s)}return n}return e}};import{homedir as ti}from"node:os";import{join as ni}from"node:path";import{DeleteObjectCommand as Ro,GetObjectCommand as No,HeadObjectCommand as _o,ListObjectsV2Command as $o,PutObjectCommand as Ko,S3Client as Fo}from"@aws-sdk/client-s3";import{getSignedUrl as Wo}from"@aws-sdk/s3-request-presigner";var Fe=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new Fo({region:"us-east-1",endpoint:`https://s3.hf.co/${e.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,n,r="application/octet-stream"){let s=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new Ko({Bucket:this.bucket,Key:e,Body:s,ContentType:r}))}async get(e){let n=await Wo(this.client,new No({Bucket:this.bucket,Key:e}),{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(e){let n=await this.get(e);return n?Buffer.from(n).toString("utf8"):null}async exists(e){try{return await this.client.send(new _o({Bucket:this.bucket,Key:e})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(e){await this.client.send(new Ro({Bucket:this.bucket,Key:e}))}async list(e=""){let n=[],r;do{let s=await this.client.send(new $o({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let o of s.Contents??[])o.Key&&n.push({key:o.Key,size:o.Size,updatedAt:o.LastModified?.toISOString()});r=s.IsTruncated?s.NextContinuationToken:void 0}while(r);return n}};import{access as vn,mkdir as Lo,readFile as Do,readdir as zo,rm as qo,stat as wn,writeFile as Bo}from"node:fs/promises";import{dirname as Jo,join as Ho,relative as bn,resolve as Vo}from"node:path";var ge=class{constructor(e){this.root=e}root;name="local";path(e){let n=e.replace(/^\/+/,"");return Vo(this.root,n)}async put(e,n){let r=this.path(e);await Lo(Jo(r),{recursive:!0}),await Bo(r,n)}async get(e){try{return await Do(this.path(e))}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT")return null;throw n}}async getText(e){let n=await this.get(e);return n?Buffer.from(n).toString("utf8"):null}async exists(e){try{return await vn(this.path(e)),!0}catch{return!1}}async delete(e){await qo(this.path(e),{force:!0})}async list(e=""){let n=this.path(e),r=[];try{await vn(n)}catch{return r}let s=async i=>{let a=await zo(i,{withFileTypes:!0});for(let c of a){let u=Ho(i,c.name);if(c.isDirectory()){await s(u);continue}let p=await wn(u);r.push({key:bn(this.root,u),size:p.size,updatedAt:p.mtime.toISOString()})}},o=await wn(n);return o.isDirectory()?await s(n):r.push({key:bn(this.root,n),size:o.size,updatedAt:o.mtime.toISOString()}),r}};import{DeleteObjectCommand as Go,GetObjectCommand as Uo,HeadObjectCommand as Yo,ListObjectsV2Command as Xo,PutObjectCommand as Qo,S3Client as Zo}from"@aws-sdk/client-s3";import{getSignedUrl as ei}from"@aws-sdk/s3-request-presigner";var ye=class{name;client;bucket;constructor(e){this.name=e.name??"s3",this.bucket=e.bucket,this.client=new Zo({region:e.region??"us-east-1",endpoint:e.endpoint||void 0,forcePathStyle:e.forcePathStyle??!1,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,n,r="application/octet-stream"){let s=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new Qo({Bucket:this.bucket,Key:e,Body:s,ContentType:r}))}async get(e){let n=await ei(this.client,new Uo({Bucket:this.bucket,Key:e}),{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(e){let n=await this.get(e);return n?Buffer.from(n).toString("utf8"):null}async exists(e){try{return await this.client.send(new Yo({Bucket:this.bucket,Key:e})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(e){await this.client.send(new Go({Bucket:this.bucket,Key:e}))}async list(e=""){let n=[],r;do{let s=await this.client.send(new Xo({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let o of s.Contents??[])o.Key&&n.push({key:o.Key,size:o.Size,updatedAt:o.LastModified?.toISOString()});r=s.IsTruncated?s.NextContinuationToken:void 0}while(r);return n}};function Ot(t,e){return console.warn(e),new ge(t)}function xn(t){let e=t.localRoot??ni(ti(),".toolnet-memory","storage");if(t.provider==="r2"){let n=t.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(e,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(t.provider==="s3"){let n=t.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(e,"[storage] S3 credentials missing. Using local fallback.")}if(t.provider==="huggingface"){let n=t.huggingface;return n?.namespace&&n.bucket&&n.accessKeyId&&n.secretAccessKey?new Fe({namespace:n.namespace,bucket:n.bucket,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Ot(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new ge(e)}function ri(t){return new Promise(e=>setTimeout(e,t))}async function jn(t,e={}){let n=Math.max(1,e.attempts??3),r=e.baseDelayMs??150,s=e.maxDelayMs??2e3,o;for(let i=1;i<=n;i++)try{return await t()}catch(a){if(o=a,i>=n)break;let c=Math.min(s,r*2**(i-1)),u=Math.floor(Math.random()*Math.max(1,c*.2));await ri(c+u)}throw o}var si=new Set(["put","get","getText","delete","list"]);function Cn(t,e={}){return new Proxy(t,{get(n,r){let s=Reflect.get(n,r,n);return typeof s!="function"?s:si.has(r)?(...o)=>jn(()=>Promise.resolve(s.apply(n,o)),e):s.bind(n)}})}function In(t){let e=t.trim().replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,"").slice(0,100);if(!e||e==="."||e==="..")throw new Error("Invalid project storage folder");return e}function An(t){let e=t.replace(/^\/+/,"");if(e.startsWith("memories/"))return"memory/records/"+e.slice(9);if(e.startsWith("vectors/"))return"memory/vectors/"+e.slice(8);if(e.startsWith("graph/"))return"code/graph/"+e.slice(6);let n=e.match(/^(snapshots\/[^/]+\/)memories\/(.+)$/);if(n)return`${n[1]}memory/records/${n[2]}`;if(n=e.match(/^(snapshots\/[^/]+\/)vectors\/(.+)$/),n)return`${n[1]}memory/vectors/${n[2]}`;if(n=e.match(/^(snapshots\/[^/]+\/)graph\/(.+)$/),n)return`${n[1]}code/graph/${n[2]}`;let r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(r)return`${r[1]}memory/records/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),r)return`${r[1]}memory/vectors/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),r)return`${r[1]}code/graph/${r[2]}`;let s=e.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return s?`${s[1]}memory/records/${s[2]}`:(s=e.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),s?`${s[1]}memory/vectors/${s[2]}`:(s=e.match(/^(projects\/[^/]+\/)graph\/(.+)$/),s?`${s[1]}code/graph/${s[2]}`:e))}var We=class{constructor(e,n,r,s){this.provider=e;this.name=e.name,this.projectId=n,this.projectName=r,this.folder=In(s??r),this.sourcePrefix=`projects/${n}`,this.targetPrefix=`projects/${this.folder}`}provider;name;folder;sourcePrefix;targetPrefix;projectId;projectName;registryPromise;async registerProject(){let e=`${this.targetPrefix}/project.json`,n=new Date().toISOString(),r=n,s=await this.provider.getText(e);if(s){let i;try{i=JSON.parse(s)}catch(a){throw new Error(`Invalid remote ToolNet project manifest at ${e}: ${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 o={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:r,updatedAt:n};await this.provider.put(e,JSON.stringify(o,null,2)+`
4
- `,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(e){if(e=An(e),e===this.sourcePrefix)return this.targetPrefix;if(e.startsWith(`${this.sourcePrefix}/`))return this.targetPrefix+e.slice(this.sourcePrefix.length);if(e===this.targetPrefix||e.startsWith(`${this.targetPrefix}/`))return e;if(e.startsWith("projects/"))throw new Error(["Cross-project storage access denied.",`Current project: ${this.targetPrefix}`,`Requested key: ${e}`].join(" "));return e}async put(e,n,r){return await this.ensureRegistered(),this.provider.put(this.key(e),n,r)}async get(e){return await this.ensureRegistered(),this.provider.get(this.key(e))}async getText(e){return await this.ensureRegistered(),this.provider.getText(this.key(e))}async delete(e){return await this.ensureRegistered(),this.provider.delete(this.key(e))}async exists(e){return await this.ensureRegistered(),this.provider.exists(this.key(e))}async list(e){return await this.ensureRegistered(),this.provider.list(this.key(e))}};import{join as di}from"node:path";import{createHash as oi}from"node:crypto";import{dirname as ii}from"node:path";import{mkdirSync as ai,readFileSync as ci,renameSync as ui,writeFileSync as li}from"node:fs";function v(t){return oi("sha256").update(t).digest("hex")}function Tt(t){if(Array.isArray(t))return t.map(Tt);if(t&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e).sort())n[r]=Tt(e[r]);return n}return t}function Mn(t){return JSON.stringify(Tt(t))}function Pn(t){try{return JSON.parse(ci(t,"utf8"))}catch{return null}}function T(t,e){ai(ii(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;li(n,JSON.stringify(e,null,2)+`
5
- `,{encoding:"utf8",mode:384}),ui(n,t)}function En(t,e){let n=t.trim(),r=n.replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,""),s=v(n).slice(0,12);if(!r||r==="."||r==="..")return`${e}--${s}`;let o=r.slice(0,100);return o===n&&n.length<=100?o:`${o.slice(0,85)}--${s}`}function Le(t,e,n){let r=e.trim(),s=n.trim();if(!r)throw new Error("Session agent is required");if(!s)throw new Error("Native session ID is required");let o=En(r.toLowerCase(),"agent"),i=En(s,"session");return{projectId:t.id,projectName:t.name,projectRoot:t.rootPath,agent:r,nativeSessionId:s,sessionKey:`${r}:${s}`,remotePrefix:["projects",t.id,"runtime","sources",o,i].join("/"),localDirectory:di(t.rootPath,".toolnet","runtime","sources",o,i)}}function On(t){return String(t).padStart(12,"0")}var De=class{constructor(e,n=100,r=512*1024){this.storage=e;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(e){let n=await this.storage.getText(e);return n?JSON.parse(n):null}async putJson(e,n){await this.storage.put(e,JSON.stringify(n,null,2)+`
6
- `,"application/json")}async scan(e){let n=`${e.remotePrefix}/events/`,r=await this.storage.list(n),s=[],o=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)||(s.push({key:i.key,start:c,end:u}),o=Math.max(o,u))}return s.sort((i,a)=>i.start-a.start),{chunks:s,maxSequence:o}}split(e){let n=[],r=[],s=0;for(let o of e){let i=Buffer.byteLength(JSON.stringify(o)+`
7
- `,"utf8");r.length>0&&(r.length>=this.maxEventsPerChunk||s+i>this.maxChunkBytes)&&(n.push(r),r=[],s=0),r.push(o),s+=i}return r.length>0&&n.push(r),n}async loadManifest(e){return this.getJson(`${e.remotePrefix}/session.json`)}async loadCursor(e){return this.getJson(`${e.remotePrefix}/cursor.json`)}async recover(e){let n=await this.scan(e);return{maxSequence:n.maxSequence,chunkCount:n.chunks.length}}async append(e,n,r,s={}){let o=await this.loadManifest(e),i=await this.scan(e),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],P=y.map(O=>JSON.stringify(O)).join(`
1
+ import{existsSync as sp,readFileSync as ip}from"node:fs";import{spawn as ap}from"node:child_process";import{homedir as cp}from"node:os";import{join as up}from"node:path";import{existsSync as Es,readFileSync as Os}from"node:fs";import{homedir as Ts}from"node:os";import{join as Rs}from"node:path";function Ns(t){let e=t.trim();return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?(e=e.slice(1,-1),e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function _s(){let t=process.env.TOOLNET_GLOBAL_ENV??Rs(Ts(),".config","toolnet-memory",".env");if(!Es(t))return;let e=Os(t,"utf8");for(let n of e.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]=Ns(r.slice(o+1)))}}_s();function ge(t,e){return t===void 0?e:["1","true","yes","on"].includes(t.toLowerCase())}function ye(t,e){if(!t)return e;let n=Number(t);return Number.isFinite(n)?n:e}function We(){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 zs}from"node:crypto";import{existsSync as qe,mkdirSync as qs,readFileSync as Vs,renameSync as Hs,writeFileSync as Bs}from"node:fs";import{basename as Js,dirname as Ve,join as Se,parse as On,resolve as X}from"node:path";import{createHash as Cn}from"node:crypto";import{spawnSync as Ks}from"node:child_process";var he="git-remote-v1",$s=new Set(["github.com","gitlab.com","bitbucket.org"]);function An(t,e){let n=e.replaceAll("\\","/").replace(/^\/+/u,"").replace(/\/+$/u,"").replace(/\.git$/iu,"").replace(/\/+/gu,"/");return!n||n==="."||n===".."||n.split("/").some(r=>!r||r==="."||r==="..")?null:($s.has(t)&&(n=n.toLowerCase()),n)}function Ls(t){let e;try{e=new URL(t)}catch{return null}if(!["https:","http:","ssh:","git:"].includes(e.protocol))return null;let n=e.hostname.trim().toLowerCase();if(!n)return null;let r=e.protocol==="https:"&&e.port==="443"||e.protocol==="http:"&&e.port==="80"||e.protocol==="ssh:"&&e.port==="22",o=e.port&&!r?`${n}:${e.port}`:n,s=An(n,e.pathname);return s?`${o}/${s}`:null}function Fs(t){let e=t.match(/^(?:[^@\s/:]+@)?([^:/\s]+):(.+)$/u);if(!e)return null;let n=e[1]?.trim().toLowerCase();if(!n||n.length===1)return null;let r=An(n,e[2]??"");return r?`${n}/${r}`:null}function jn(t){let e=t.trim();return e?e.includes("://")?Ls(e):Fs(e):null}function Ws(t){return Cn("sha256").update(`${he}:${t}`).digest("hex")}function Mn(t){return Cn("sha256").update(`toolnet-project:${he}:${t}`).digest("hex").slice(0,16)}function Ds(t){return t.split("/").filter(Boolean).at(-1)?.trim()||null}function $t(t,e){let n=Ks("git",["-C",t,...e],{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]});return n.error||n.status!==0?null:n.stdout?.trim()||null}function In(t,e){let n=Ds(t);return n?{scheme:he,canonicalRemote:t,fingerprint:Ws(t),repositoryName:n,source:e}:null}function Pn(t){let e=$t(t,["remote","get-url","origin"]);if(e){let o=jn(e);if(o)return In(o,"origin")}let n=$t(t,["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=$t(t,["remote","get-url",o]);if(!s)continue;let i=jn(s);i&&r.add(i)}return r.size!==1?null:In([...r][0],"unique-remote")}var Tn=".toolnet",Gs="project.json";function Us(t){return zs("sha256").update(t).digest("hex").slice(0,16)}function se(t){return Se(t,Tn,Gs)}function Rn(t){return qe(se(t))}function En(t,e){let n=X(t),r=On(n).root;for(;;){if(Rn(n))return n;if(n===r||e&&n===X(e))break;let o=Ve(n);if(o===n)break;n=o}return null}function Lt(t){let e=X(t),n=On(e).root,r=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(r.some(s=>qe(Se(e,s))))return e;if(e===n)break;let o=Ve(e);if(o===e)break;e=o}return X(t)}function De(t){let e;try{e=JSON.parse(Vs(t,"utf8"))}catch(o){throw new Error(`Invalid ToolNet project manifest: ${t}: ${o instanceof Error?o.message:String(o)}`)}if(!e||typeof e!="object")throw new Error(`Invalid ToolNet project manifest: ${t}`);let n=e;if(typeof n.id!="string"||!n.id.trim())throw new Error(`ToolNet project manifest is missing id: ${t}`);if(typeof n.name!="string"||!n.name.trim())throw new Error(`ToolNet project manifest is missing name: ${t}`);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:Ve(Ve(t)),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 ze(t,e){let n=Se(t,Tn);qs(n,{recursive:!0});let r=se(t),o=`${r}.tmp-${process.pid}`;Bs(o,JSON.stringify(e,null,2)+`
3
+ `,{encoding:"utf8",mode:384}),Hs(o,r)}function Y(t,e){return{id:t.id,name:t.name,remote:t.remote,rootPath:e,createdAt:t.createdAt,updatedAt:t.updatedAt,graphVersion:t.graphVersion,memoryVersion:t.memoryVersion,metadata:t.metadata}}function Ft(t){return{version:1,scheme:he,canonicalRemote:t.canonicalRemote,fingerprint:t.fingerprint,repositoryName:t.repositoryName}}function Ys(t){let e=t.metadata?.toolnetIdentity;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;return typeof n.fingerprint=="string"?n.fingerprint:null}var ie=class{adopt(e,n){let r=Lt(X(e));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(Rn(r)){let a=De(se(r));if(a.id!==n.id)throw new Error(["PROJECT_IDENTITY_ALREADY_EXISTS",`existing=${a.id}`,`requested=${n.id}`].join(" "));return Y(a,r)}let o=new Date().toISOString(),s={...n.metadata};n.gitIdentity&&(s.toolnetIdentity=Ft(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 ze(r,i),Y(i,r)}recordGitIdentity(e,n,r={}){let o=this.requireExisting(e),s=se(o.rootPath),i=De(s),a=Ys(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:Ft(n)},i.updatedAt=new Date().toISOString(),ze(o.rootPath,i)),Y(i,o.rootPath)}findExisting(e=process.cwd()){let n=X(e),r=Lt(n),s=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(c=>qe(Se(r,c))),i=En(n,s?r:void 0);if(!i)return null;let a=De(se(i));return Y(a,i)}requireExisting(e=process.cwd()){let n=this.findExisting(e);if(!n)throw new Error("PROJECT_NOT_INITIALIZED");return n}detect(e=process.cwd()){let n=X(e),r=Lt(n),s=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(l=>qe(Se(r,l))),i=En(n,s?r:void 0);if(i){let l=se(i),p=De(l);return p.rootPath!==i&&(p.rootPath=i,p.updatedAt=new Date().toISOString(),ze(i,p)),Y(p,i)}let a=new Date().toISOString(),c=Js(r),u=Pn(r),f={version:1,id:u?Mn(u.canonicalRemote):Us(r),name:c,remote:u?.repositoryName??c,rootPath:r,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0,metadata:u?{toolnetIdentity:Ft(u)}:void 0};return ze(r,f),Y(f,r)}};var Xs=[{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"}],Qs=new Set(["example","example-key","example-token","changeme","change-me","password","secret","your-api-key","your-token","<token>","<secret>","<password>","[redacted]"]);function Nn(t){return t.normalize("NFKC").trim().toLowerCase()}function Zs(t){if(t.length===0)return 0;let e=new Map;for(let r of t)e.set(r,(e.get(r)??0)+1);let n=0;for(let r of e.values()){let o=r/t.length;n-=o*Math.log2(o)}return n}function ei(t){return/^[a-f0-9]{32}$/iu.test(t)||/^[a-f0-9]{40}$/iu.test(t)||/^[a-f0-9]{64}$/iu.test(t)}function ti(t,e,n){let r=t.slice(Math.max(0,e-48),e),o=t.slice(n,Math.min(t.length,n+16));return/\b(?:token|secret|key|credential|authorization|password|passwd|apikey|api_key|access[_-]?key)\b/iu.test(`${r} ${o}`)}function ni(t,e){return t.start<e.end&&e.start<t.end}function _n(t){return t.sort((e,n)=>e.start!==n.start?e.start-n.start:n.end-n.start-(e.end-e.start))}var He=class{allowValues=new Set;enableEntropyHeuristic;constructor(e={}){for(let n of e.allowValues??[]){let r=Nn(n);r&&this.allowValues.add(r)}this.enableEntropyHeuristic=e.enableEntropyHeuristic??!0}scan(e){let n=[];for(let s of Xs){let i=new RegExp(s.regex.source,s.regex.flags);for(let a of e.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(e));let r=_n(n),o=[];for(let s of r)o.some(i=>ni(i,s))||o.push(s);return _n(o)}hasSecrets(e){return this.scan(e).length>0}allowed(e){let n=Nn(e);return Qs.has(n)?!0:this.allowValues.has(n)}entropyMatches(e){let n=[],r=/[A-Za-z0-9_+/=-]{32,160}/g;for(let o of e.matchAll(r)){if(o.index===void 0||!o[0])continue;let s=o[0];this.allowed(s)||ei(s)||!/[A-Za-z]/u.test(s)||!/[0-9]/u.test(s)||ti(e,o.index,o.index+s.length)&&(Zs(s)<3.7||n.push({type:"high_entropy_secret",value:s,start:o.index,end:o.index+s.length,confidence:"heuristic"}))}return n}};var H=class{scanner;constructor(e={}){this.scanner=new He(e)}sanitize(e){let n=this.scanner.scan(e);if(n.length===0)return{text:e,redacted:0,secretTypes:[]};let r=e,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(e){if(typeof e=="string")return this.sanitize(e).text;if(Array.isArray(e))return e.map(n=>this.sanitizeValue(n));if(e&&typeof e=="object"){let n={};for(let[r,o]of Object.entries(e)){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 e}};var ri=new H;function ke(t){return ri.sanitizeValue(t)}import{homedir as Ci}from"node:os";import{join as Ai}from"node:path";import{DeleteObjectCommand as oi,GetObjectCommand as si,HeadObjectCommand as ii,ListObjectsV2Command as ai,PutObjectCommand as ci,S3Client as ui}from"@aws-sdk/client-s3";import{getSignedUrl as li}from"@aws-sdk/s3-request-presigner";var Be=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new ui({region:"us-east-1",endpoint:`https://s3.hf.co/${e.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,n,r="application/octet-stream"){let o=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new ci({Bucket:this.bucket,Key:e,Body:o,ContentType:r}))}async get(e){let n=await li(this.client,new si({Bucket:this.bucket,Key:e}),{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(e){let n=await this.get(e);return n?Buffer.from(n).toString("utf8"):null}async exists(e){try{return await this.client.send(new ii({Bucket:this.bucket,Key:e})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(e){await this.client.send(new oi({Bucket:this.bucket,Key:e}))}async list(e=""){let n=[],r;do{let o=await this.client.send(new ai({Bucket:this.bucket,Prefix:e||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 Kn,mkdir as di,readFile as pi,readdir as fi,rm as mi,stat as $n,writeFile as gi}from"node:fs/promises";import{dirname as yi,join as hi,relative as Ln,resolve as Si}from"node:path";var ve=class{constructor(e){this.root=e}root;name="local";path(e){let n=e.replace(/^\/+/,"");return Si(this.root,n)}async put(e,n){let r=this.path(e);await di(yi(r),{recursive:!0}),await gi(r,n)}async get(e){try{return await pi(this.path(e))}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT")return null;throw n}}async getText(e){let n=await this.get(e);return n?Buffer.from(n).toString("utf8"):null}async exists(e){try{return await Kn(this.path(e)),!0}catch{return!1}}async delete(e){await mi(this.path(e),{force:!0})}async list(e=""){let n=this.path(e),r=[];try{await Kn(n)}catch{return r}let o=async i=>{let a=await fi(i,{withFileTypes:!0});for(let c of a){let u=hi(i,c.name);if(c.isDirectory()){await o(u);continue}let f=await $n(u);r.push({key:Ln(this.root,u),size:f.size,updatedAt:f.mtime.toISOString()})}},s=await $n(n);return s.isDirectory()?await o(n):r.push({key:Ln(this.root,n),size:s.size,updatedAt:s.mtime.toISOString()}),r}};import{DeleteObjectCommand as ki,GetObjectCommand as vi,HeadObjectCommand as wi,ListObjectsV2Command as bi,PutObjectCommand as xi,S3Client as ji}from"@aws-sdk/client-s3";import{getSignedUrl as Ii}from"@aws-sdk/s3-request-presigner";var we=class{name;client;bucket;constructor(e){this.name=e.name??"s3",this.bucket=e.bucket,this.client=new ji({region:e.region??"us-east-1",endpoint:e.endpoint||void 0,forcePathStyle:e.forcePathStyle??!1,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,n,r="application/octet-stream"){let o=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new xi({Bucket:this.bucket,Key:e,Body:o,ContentType:r}))}async get(e){let n=await Ii(this.client,new vi({Bucket:this.bucket,Key:e}),{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(e){let n=await this.get(e);return n?Buffer.from(n).toString("utf8"):null}async exists(e){try{return await this.client.send(new wi({Bucket:this.bucket,Key:e})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(e){await this.client.send(new ki({Bucket:this.bucket,Key:e}))}async list(e=""){let n=[],r;do{let o=await this.client.send(new bi({Bucket:this.bucket,Prefix:e||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 Wt(t,e){return console.warn(e),new ve(t)}function Fn(t){let e=t.localRoot??Ai(Ci(),".toolnet-memory","storage");if(t.provider==="r2"){let n=t.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}):Wt(e,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(t.provider==="s3"){let n=t.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}):Wt(e,"[storage] S3 credentials missing. Using local fallback.")}if(t.provider==="huggingface"){let n=t.huggingface;return n?.namespace&&n.bucket&&n.accessKeyId&&n.secretAccessKey?new Be({namespace:n.namespace,bucket:n.bucket,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Wt(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new ve(e)}function Mi(t){return new Promise(e=>setTimeout(e,t))}async function Wn(t,e={}){let n=Math.max(1,e.attempts??3),r=e.baseDelayMs??150,o=e.maxDelayMs??2e3,s;for(let i=1;i<=n;i++)try{return await t()}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 Mi(c+u)}throw s}var Pi=new Set(["put","get","getText","delete","list"]);function Dn(t,e={}){return new Proxy(t,{get(n,r){let o=Reflect.get(n,r,n);return typeof o!="function"?o:Pi.has(r)?(...s)=>Wn(()=>Promise.resolve(o.apply(n,s)),e):o.bind(n)}})}function zn(t){let e=t.trim().replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,"").slice(0,100);if(!e||e==="."||e==="..")throw new Error("Invalid project storage folder");return e}function qn(t){let e=t.replace(/^\/+/,"");if(e.startsWith("memories/"))return"memory/records/"+e.slice(9);if(e.startsWith("vectors/"))return"memory/vectors/"+e.slice(8);if(e.startsWith("graph/"))return"code/graph/"+e.slice(6);let n=e.match(/^(snapshots\/[^/]+\/)memories\/(.+)$/);if(n)return`${n[1]}memory/records/${n[2]}`;if(n=e.match(/^(snapshots\/[^/]+\/)vectors\/(.+)$/),n)return`${n[1]}memory/vectors/${n[2]}`;if(n=e.match(/^(snapshots\/[^/]+\/)graph\/(.+)$/),n)return`${n[1]}code/graph/${n[2]}`;let r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(r)return`${r[1]}memory/records/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),r)return`${r[1]}memory/vectors/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),r)return`${r[1]}code/graph/${r[2]}`;let o=e.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return o?`${o[1]}memory/records/${o[2]}`:(o=e.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),o?`${o[1]}memory/vectors/${o[2]}`:(o=e.match(/^(projects\/[^/]+\/)graph\/(.+)$/),o?`${o[1]}code/graph/${o[2]}`:e))}var Je=class{constructor(e,n,r,o){this.provider=e;this.name=e.name,this.projectId=n,this.projectName=r,this.folder=zn(o??r),this.sourcePrefix=`projects/${n}`,this.targetPrefix=`projects/${this.folder}`}provider;name;folder;sourcePrefix;targetPrefix;projectId;projectName;registryPromise;async registerProject(){let e=`${this.targetPrefix}/project.json`,n=new Date().toISOString(),r=n,o=await this.provider.getText(e);if(o){let i;try{i=JSON.parse(o)}catch(a){throw new Error(`Invalid remote ToolNet project manifest at ${e}: ${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(e,JSON.stringify(s,null,2)+`
4
+ `,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(e){if(e=qn(e),e===this.sourcePrefix)return this.targetPrefix;if(e.startsWith(`${this.sourcePrefix}/`))return this.targetPrefix+e.slice(this.sourcePrefix.length);if(e===this.targetPrefix||e.startsWith(`${this.targetPrefix}/`))return e;if(e.startsWith("projects/"))throw new Error(["Cross-project storage access denied.",`Current project: ${this.targetPrefix}`,`Requested key: ${e}`].join(" "));return e}async put(e,n,r){return await this.ensureRegistered(),this.provider.put(this.key(e),n,r)}async get(e){return await this.ensureRegistered(),this.provider.get(this.key(e))}async getText(e){return await this.ensureRegistered(),this.provider.getText(this.key(e))}async delete(e){return await this.ensureRegistered(),this.provider.delete(this.key(e))}async exists(e){return await this.ensureRegistered(),this.provider.exists(this.key(e))}async list(e){return await this.ensureRegistered(),this.provider.list(this.key(e))}};import{join as Ki}from"node:path";import{createHash as Ei}from"node:crypto";import{dirname as Oi}from"node:path";import{mkdirSync as Ti,readFileSync as Ri,renameSync as Ni,writeFileSync as _i}from"node:fs";function w(t){return Ei("sha256").update(t).digest("hex")}function Dt(t){if(Array.isArray(t))return t.map(Dt);if(t&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e).sort())n[r]=Dt(e[r]);return n}return t}function Vn(t){return JSON.stringify(Dt(t))}function Hn(t){try{return JSON.parse(Ri(t,"utf8"))}catch{return null}}function R(t,e){Ti(Oi(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;_i(n,JSON.stringify(e,null,2)+`
5
+ `,{encoding:"utf8",mode:384}),Ni(n,t)}function Bn(t,e){let n=t.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`${e}--${o}`;let s=r.slice(0,100);return s===n&&n.length<=100?s:`${s.slice(0,85)}--${o}`}function Ge(t,e,n){let r=e.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=Bn(r.toLowerCase(),"agent"),i=Bn(o,"session");return{projectId:t.id,projectName:t.name,projectRoot:t.rootPath,agent:r,nativeSessionId:o,sessionKey:`${r}:${o}`,remotePrefix:["projects",t.id,"runtime","sources",s,i].join("/"),localDirectory:Ki(t.rootPath,".toolnet","runtime","sources",s,i)}}function Jn(t){return String(t).padStart(12,"0")}var Ue=class{constructor(e,n=100,r=512*1024){this.storage=e;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(e){let n=await this.storage.getText(e);return n?JSON.parse(n):null}async putJson(e,n){await this.storage.put(e,JSON.stringify(n,null,2)+`
6
+ `,"application/json")}async scan(e){let n=`${e.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(e){let n=[],r=[],o=0;for(let s of e){let i=Buffer.byteLength(JSON.stringify(s)+`
7
+ `,"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(e){return this.getJson(`${e.remotePrefix}/session.json`)}async loadCursor(e){return this.getJson(`${e.remotePrefix}/cursor.json`)}async recover(e){let n=await this.scan(e);return{maxSequence:n.maxSequence,chunkCount:n.chunks.length}}async append(e,n,r,o={}){let s=await this.loadManifest(e),i=await this.scan(e),a=n.filter(g=>g.sequence>i.maxSequence),c=0;for(let g of this.split(a)){let y=g[0],v=g[g.length-1],x=g.map(T=>JSON.stringify(T)).join(`
8
8
  `)+`
9
- `,E=v(P).slice(0,16),M=[e.remotePrefix,"events",`${On(h.sequence)}-${On(k.sequence)}-${E}.jsonl`].join("/");await this.storage.exists(M)||await this.storage.put(M,P,"application/x-ndjson"),c+=y.length}let u=await this.scan(e),p=n[n.length-1],l=o?.status??"active";p?.type==="session_end"||p?.type==="session_idle"?l="idle":p?.type==="error"?l="error":n.length>0&&(l="active");let f=new Date().toISOString(),d=n[0],g={version:1,projectId:e.projectId,projectName:e.projectName,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,status:l,createdAt:o?.createdAt??d?.timestamp??f,updatedAt:p?.timestamp??f,firstEventAt:o?.firstEventAt??d?.timestamp,lastEventAt:p?.timestamp??o?.lastEventAt,eventCount:u.maxSequence,chunkCount:u.chunks.length,metadata:{...o?.metadata,...s.metadata}};(s.title??o?.title)&&(g.title=s.title??o?.title);let S={version:1,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,lastLocalSequence:n.length>0?n[n.length-1].sequence:u.maxSequence,lastRemoteSequence:u.maxSequence,sourceCursors:r,updatedAt:f};return await this.putJson(`${e.remotePrefix}/cursor.json`,S),await this.putJson(`${e.remotePrefix}/session.json`,g),{uploadedEvents:c,lastRemoteSequence:u.maxSequence,eventCount:g.eventCount,chunkCount:g.chunkCount,status:l}}};import{closeSync as ke,existsSync as He,fsyncSync as Lt,mkdirSync as Mi,openSync as ve,readFileSync as Hn,readSync as Pi,rmSync as qn,statSync as Ft,truncateSync as Ei,writeSync as Oi}from"node:fs";import{join as Wt}from"node:path";var pi=new Set(["thinking","reasoning","reasoningcontent","chainofthought","cot","analysistext","internalreasoning","modelthinking"]),fi=new Set(["reasoning","thinking","chain_of_thought","chain-of-thought","internal_reasoning","internal-reasoning"]);function mi(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function gi(t){for(let e of["type","kind"]){let n=t[e];if(typeof n=="string"){let r=n.toLowerCase();if(fi.has(r))return n}}return null}function Rt(t,e=0){if(e>12)return"[ToolNet nested value omitted]";if(Array.isArray(t))return t.map(o=>Rt(o,e+1));if(!t||typeof t!="object")return t;let n=t,r=gi(n);if(r)return{type:r,omitted:"[private reasoning omitted]"};let s={};for(let[o,i]of Object.entries(n))pi.has(mi(o))||(s[o]=Rt(i,e+1));return s}function yi(t){if(!t)return new Date().toISOString();let e=new Date(t);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()}function U(t){return t?.trim()||void 0}function Tn(t,e={}){let n={...t.provenance??{}},r=U(t.source)??U(e.source)??U(n.source);return{...t,timestamp:yi(t.timestamp),source:r,turnId:U(t.turnId)??U(e.turnId),cwd:U(t.cwd)??U(e.cwd),data:Rt(t.data??{}),provenance:n}}import{randomUUID as Nt}from"node:crypto";import{closeSync as re,existsSync as se,fsyncSync as he,mkdirSync as _t,openSync as Se,readFileSync as $t,readdirSync as hi,renameSync as Si,rmSync as ze,statSync as ki,writeSync as qe}from"node:fs";import{join as B}from"node:path";var vi=12e4,wi=80,bi="reconcile-required";function xi(t){t<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function oe(t){return B(t,".toolnet","journal")}function _n(t){return B(oe(t),"events.jsonl")}function Be(t){return B(oe(t),bi)}function ji(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e?.code!=="ESRCH"}}function $n(t){if(!se(t))return null;try{let e=JSON.parse($t(t,"utf8"));return e.version!==1||typeof e.token!="string"||typeof e.pid!="number"||typeof e.acquiredAt!="string"?null:{version:1,token:e.token,pid:e.pid,acquiredAt:e.acquiredAt}}catch{return null}}function Ci(t){if(!se(t))return!1;let e=0;try{e=Date.now()-ki(t).mtimeMs}catch{return!1}if(e<=vi)return!1;let n=$n(t);return n?!ji(n.pid):!0}function Ii(t){if(!Ci(t))return!1;try{return ze(t,{force:!0}),!0}catch{return!1}}function Kn(t){for(let e=0;e<wi;e+=1){let n=Nt();try{let r=Se(t,"wx",384),s={version:1,token:n,pid:process.pid,acquiredAt:new Date().toISOString()};try{return qe(r,`${JSON.stringify(s)}
10
- `,null,"utf8"),he(r),{fd:r,token:n}}catch(o){throw re(r),ze(t,{force:!0}),o}}catch(r){if(r?.code!=="EEXIST")throw r;if(Ii(t))continue;xi(25)}}throw new Error(`Shared project journal is locked: ${t}`)}function Fn(t,e){re(e.fd),$n(t)?.token===e.token&&ze(t,{force:!0})}function Rn(t){if(!se(t))return[];let e="";try{e=$t(t,"utf8")}catch{return[]}let n=[];for(let r of e.split(/\r?\n/)){let s=r.trim();if(s)try{let o=JSON.parse(s);if(o.version!==1||typeof o.id!="string"||o.id.length===0||typeof o.projectId!="string"||o.projectId.length===0)continue;n.push(o)}catch{}}return n}function Wn(t){if(!se(t))return[];let e=[];for(let n of hi(t,{withFileTypes:!0})){let r=B(t,n.name);if(n.isDirectory()){e.push(...Wn(r));continue}n.isFile()&&n.name==="events.jsonl"&&e.push(r)}return e.sort()}function Je(t){let e=null;try{e=Se(t,"r"),he(e)}catch{}finally{if(e===null)return;re(e)}}function Nn(t){let e=Be(t);if(!se(e))return null;try{return $t(e,"utf8").trim()||null}catch{return null}}function Kt(t){let e=oe(t);_t(e,{recursive:!0,mode:448});let n=Be(t),r=[Nt(),new Date().toISOString()].join("|"),s=Se(n,"w",384);try{qe(s,`${r}
11
- `,null,"utf8"),he(s)}finally{re(s)}Je(e)}function Ai(t,e,n){let r=B(t,`.events.jsonl.tmp-${process.pid}-${Nt()}`),s=Se(r,"w",384);try{let o=n.length===0?"":`${n.map(i=>JSON.stringify(i)).join(`
9
+ `,O=w(x).slice(0,16),P=[e.remotePrefix,"events",`${Jn(y.sequence)}-${Jn(v.sequence)}-${O}.jsonl`].join("/");await this.storage.exists(P)||await this.storage.put(P,x,"application/x-ndjson"),c+=g.length}let u=await this.scan(e),f=n[n.length-1],l=s?.status??"active";f?.type==="session_end"||f?.type==="session_idle"?l="idle":f?.type==="error"?l="error":n.length>0&&(l="active");let p=new Date().toISOString(),d=n[0],m={version:1,projectId:e.projectId,projectName:e.projectName,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,status:l,createdAt:s?.createdAt??d?.timestamp??p,updatedAt:f?.timestamp??p,firstEventAt:s?.firstEventAt??d?.timestamp,lastEventAt:f?.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:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,lastLocalSequence:n.length>0?n[n.length-1].sequence:u.maxSequence,lastRemoteSequence:u.maxSequence,sourceCursors:r,updatedAt:p};return await this.putJson(`${e.remotePrefix}/cursor.json`,S),await this.putJson(`${e.remotePrefix}/session.json`,m),{uploadedEvents:c,lastRemoteSequence:u.maxSequence,eventCount:m.eventCount,chunkCount:m.chunkCount,status:l}}};import{closeSync as je,existsSync as et,fsyncSync as Ut,mkdirSync as Zi,openSync as Ie,readFileSync as cr,readSync as ea,rmSync as sr,statSync as Jt,truncateSync as ta,writeSync as na}from"node:fs";import{join as Gt}from"node:path";var $i=new Set(["thinking","reasoning","reasoningcontent","chainofthought","cot","analysistext","internalreasoning","modelthinking"]),Li=new Set(["reasoning","thinking","chain_of_thought","chain-of-thought","internal_reasoning","internal-reasoning"]);function Fi(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Wi(t){for(let e of["type","kind"]){let n=t[e];if(typeof n=="string"){let r=n.toLowerCase();if(Li.has(r))return n}}return null}function zt(t,e=0){if(e>12)return"[ToolNet nested value omitted]";if(Array.isArray(t))return t.map(s=>zt(s,e+1));if(!t||typeof t!="object")return t;let n=t,r=Wi(n);if(r)return{type:r,omitted:"[private reasoning omitted]"};let o={};for(let[s,i]of Object.entries(n))$i.has(Fi(s))||(o[s]=zt(i,e+1));return o}function Di(t){if(!t)return new Date().toISOString();let e=new Date(t);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()}function Q(t){return t?.trim()||void 0}function Gn(t,e={}){let n={...t.provenance??{}},r=Q(t.source)??Q(e.source)??Q(n.source);return{...t,timestamp:Di(t.timestamp),source:r,turnId:Q(t.turnId)??Q(e.turnId),cwd:Q(t.cwd)??Q(e.cwd),data:zt(t.data??{}),provenance:n}}import{randomUUID as qt}from"node:crypto";import{closeSync as ae,existsSync as ce,fsyncSync as be,mkdirSync as Vt,openSync as xe,readFileSync as Ht,readdirSync as zi,renameSync as qi,rmSync as Ye,statSync as Vi,writeSync as Xe}from"node:fs";import{join as B}from"node:path";var Hi=12e4,Bi=80,Ji="reconcile-required";function Gi(t){t<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function ue(t){return B(t,".toolnet","journal")}function Xn(t){return B(ue(t),"events.jsonl")}function Qe(t){return B(ue(t),Ji)}function Ui(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e?.code!=="ESRCH"}}function Qn(t){if(!ce(t))return null;try{let e=JSON.parse(Ht(t,"utf8"));return e.version!==1||typeof e.token!="string"||typeof e.pid!="number"||typeof e.acquiredAt!="string"?null:{version:1,token:e.token,pid:e.pid,acquiredAt:e.acquiredAt}}catch{return null}}function Yi(t){if(!ce(t))return!1;let e=0;try{e=Date.now()-Vi(t).mtimeMs}catch{return!1}if(e<=Hi)return!1;let n=Qn(t);return n?!Ui(n.pid):!0}function Xi(t){if(!Yi(t))return!1;try{return Ye(t,{force:!0}),!0}catch{return!1}}function Zn(t){for(let e=0;e<Bi;e+=1){let n=qt();try{let r=xe(t,"wx",384),o={version:1,token:n,pid:process.pid,acquiredAt:new Date().toISOString()};try{return Xe(r,`${JSON.stringify(o)}
10
+ `,null,"utf8"),be(r),{fd:r,token:n}}catch(s){throw ae(r),Ye(t,{force:!0}),s}}catch(r){if(r?.code!=="EEXIST")throw r;if(Xi(t))continue;Gi(25)}}throw new Error(`Shared project journal is locked: ${t}`)}function er(t,e){ae(e.fd),Qn(t)?.token===e.token&&Ye(t,{force:!0})}function Un(t){if(!ce(t))return[];let e="";try{e=Ht(t,"utf8")}catch{return[]}let n=[];for(let r of e.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 tr(t){if(!ce(t))return[];let e=[];for(let n of zi(t,{withFileTypes:!0})){let r=B(t,n.name);if(n.isDirectory()){e.push(...tr(r));continue}n.isFile()&&n.name==="events.jsonl"&&e.push(r)}return e.sort()}function Ze(t){let e=null;try{e=xe(t,"r"),be(e)}catch{}finally{if(e===null)return;ae(e)}}function Yn(t){let e=Qe(t);if(!ce(e))return null;try{return Ht(e,"utf8").trim()||null}catch{return null}}function Bt(t){let e=ue(t);Vt(e,{recursive:!0,mode:448});let n=Qe(t),r=[qt(),new Date().toISOString()].join("|"),o=xe(n,"w",384);try{Xe(o,`${r}
11
+ `,null,"utf8"),be(o)}finally{ae(o)}Ze(e)}function Qi(t,e,n){let r=B(t,`.events.jsonl.tmp-${process.pid}-${qt()}`),o=xe(r,"w",384);try{let s=n.length===0?"":`${n.map(i=>JSON.stringify(i)).join(`
12
12
  `)}
13
- `;o&&qe(s,o,null,"utf8"),he(s)}finally{re(s)}Si(r,e),Je(t)}function Ln(t){let e=oe(t),n=_n(t),r=B(t,".toolnet","runtime","sources"),s=Nn(t),o=Wn(r),i=[],a=new Set;for(let l of Rn(n))a.has(l.id)||(a.add(l.id),i.push(l));let c=i.length,u=[];for(let l of o)for(let f of Rn(l))a.has(f.id)||(a.add(f.id),u.push(f));u.sort((l,f)=>{let d=l.timestamp.localeCompare(f.timestamp);return d!==0?d:l.id.localeCompare(f.id)}),i.push(...u),Ai(e,n,i);let p=Nn(t);return s&&p===s&&(ze(Be(t),{force:!0}),Je(e)),{filesScanned:o.length,existingEvents:c,recoveredEvents:u.length,totalEvents:i.length}}function Dn(t){let e=oe(t);_t(e,{recursive:!0,mode:448});let n=B(e,"journal.lock"),r=Kn(n);try{return Ln(t)}finally{Fn(n,r)}}function zn(t,e){if(e.length===0)return;let n=oe(t);_t(n,{recursive:!0,mode:448});let r=_n(t),s=B(n,"journal.lock"),o=Kn(s);try{if(se(Be(t))){Ln(t);return}let i=`${e.map(c=>JSON.stringify(c)).join(`
13
+ `;s&&Xe(o,s,null,"utf8"),be(o)}finally{ae(o)}qi(r,e),Ze(t)}function nr(t){let e=ue(t),n=Xn(t),r=B(t,".toolnet","runtime","sources"),o=Yn(t),s=tr(r),i=[],a=new Set;for(let l of Un(n))a.has(l.id)||(a.add(l.id),i.push(l));let c=i.length,u=[];for(let l of s)for(let p of Un(l))a.has(p.id)||(a.add(p.id),u.push(p));u.sort((l,p)=>{let d=l.timestamp.localeCompare(p.timestamp);return d!==0?d:l.id.localeCompare(p.id)}),i.push(...u),Qi(e,n,i);let f=Yn(t);return o&&f===o&&(Ye(Qe(t),{force:!0}),Ze(e)),{filesScanned:s.length,existingEvents:c,recoveredEvents:u.length,totalEvents:i.length}}function rr(t){let e=ue(t);Vt(e,{recursive:!0,mode:448});let n=B(e,"journal.lock"),r=Zn(n);try{return nr(t)}finally{er(n,r)}}function or(t,e){if(e.length===0)return;let n=ue(t);Vt(n,{recursive:!0,mode:448});let r=Xn(t),o=B(n,"journal.lock"),s=Zn(o);try{if(ce(Qe(t))){nr(t);return}let i=`${e.map(c=>JSON.stringify(c)).join(`
14
14
  `)}
15
- `,a=Se(r,"a",384);try{qe(a,i,null,"utf8"),he(a)}finally{re(a)}Je(n)}finally{Fn(s,o)}}var Ti=12e4,Ri=80,Bn=2e3;function Ni(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Vn(t,e){let n=Buffer.isBuffer(e)?e:Buffer.from(e,"utf8"),r=0;for(;r<n.length;){let s=Oi(t,n,r,n.length-r);if(s<=0)throw new Error("Unable to write session WAL");r+=s}}function Dt(t){let e=t.trim();if(!e)return null;try{let n=JSON.parse(e);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 _i(t){if(!He(t))return[];let e="";try{e=Hn(t,"utf8")}catch{return[]}let n=[];for(let r of e.split(/\r?\n/)){let s=Dt(r);s&&n.push(s)}return n}function Jn(t){return t.type==="session_end"||t.type==="session_idle"?"idle":t.type==="error"?"error":"active"}function $i(t){if(!He(t))return!1;let e;try{e=Hn(t)}catch{return!1}if(e.length===0||e[e.length-1]===10)return!1;let n=e.lastIndexOf(10),r=n>=0?n+1:0,s=e.subarray(r).toString("utf8").trim();if(Dt(s)){let i=ve(t,"a");try{Vn(i,`
16
- `),Lt(i)}finally{ke(i)}return!0}Ei(t,r);let o=ve(t,"a");try{Lt(o)}finally{ke(o)}return!0}function Ki(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0}var Ve=class{constructor(e,n={}){this.identity=e;this.eventContext=n;Mi(e.localDirectory,{recursive:!0}),this.eventsFile=Wt(e.localDirectory,"events.jsonl"),this.stateFile=Wt(e.localDirectory,"state.json"),this.lockFile=Wt(e.localDirectory,"journal.lock")}identity;eventContext;eventsFile;stateFile;lockFile;initialState(){let e=new Date().toISOString();return{version:1,projectId:this.identity.projectId,agent:this.identity.agent,nativeSessionId:this.identity.nativeSessionId,status:"idle",createdAt:e,updatedAt:e,lastSequence:0,lastRemoteSequence:0,remoteByteOffset:0,sourceCursors:{},recentEventIds:[]}}loadStateUnsafe(){return Pn(this.stateFile)??this.initialState()}recoverStateUnsafe(){$i(this.eventsFile);let e=this.loadStateUnsafe(),n=_i(this.eventsFile);if(n.length===0)return e;let r=n[0];for(let l of n)l.sequence<=r.sequence||(r=l);let s=n.slice(-Bn).map(l=>l.id),o=He(this.eventsFile)?Ft(this.eventsFile).size:0,i=Math.max(e.lastSequence,r.sequence),a=Math.min(e.remoteByteOffset,o),c=r.sequence>e.lastSequence;if(!(c||a!==e.remoteByteOffset||!Ki(e.recentEventIds,s)||e.lastLocalEventAt!==r.timestamp))return e;let p={...e,status:Jn(r),updatedAt:r.timestamp,lastLocalEventAt:r.timestamp,lastSequence:i,remoteByteOffset:a,recentEventIds:s};if(this.saveStateUnsafe(p),!c)return p;try{Kt(this.identity.projectRoot)}catch{return p}try{Dn(this.identity.projectRoot)}catch{}return p}loadState(){return this.withLock(()=>this.recoverStateUnsafe())}saveStateUnsafe(e){T(this.stateFile,e)}acquireLock(){for(let e=0;e<Ri;e+=1)try{return ve(this.lockFile,"wx",384)}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Ft(this.lockFile).mtimeMs>Ti){qn(this.lockFile,{force:!0});continue}}catch{}Ni(25)}throw new Error(`Session journal is locked: ${this.lockFile}`)}withLock(e){let n=this.acquireLock();try{return e()}finally{ke(n),qn(this.lockFile,{force:!0})}}append(e){return e.length===0?[]:this.withLock(()=>{let n=this.recoverStateUnsafe(),r=new Set(n.recentEventIds),s=n.lastSequence,o=[];for(let l of e){let f=Tn(l,this.eventContext),d=f.timestamp??new Date().toISOString(),g=f.data??{},S=f.provenance?.rawDigest??v(Mn(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,s+1,f.type,d,S].join("|"),h=v(y).slice(0,32);if(r.has(h))continue;s+=1;let k={version:1,id:h,sequence:s,projectId:this.identity.projectId,agent:this.identity.agent,nativeSessionId:this.identity.nativeSessionId,sessionId:this.identity.nativeSessionId,type:f.type,timestamp:d,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),o.push(k),r.add(h)}if(o.length===0)return[];let i=o.map(l=>JSON.stringify(l)).join(`
15
+ `,a=xe(r,"a",384);try{Xe(a,i,null,"utf8"),be(a)}finally{ae(a)}Ze(n)}finally{er(o,s)}}var ra=12e4,oa=80,ir=2e3;function sa(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function ur(t,e){let n=Buffer.isBuffer(e)?e:Buffer.from(e,"utf8"),r=0;for(;r<n.length;){let o=na(t,n,r,n.length-r);if(o<=0)throw new Error("Unable to write session WAL");r+=o}}function Yt(t){let e=t.trim();if(!e)return null;try{let n=JSON.parse(e);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 ia(t){if(!et(t))return[];let e="";try{e=cr(t,"utf8")}catch{return[]}let n=[];for(let r of e.split(/\r?\n/)){let o=Yt(r);o&&n.push(o)}return n}function ar(t){return t.type==="session_end"||t.type==="session_idle"?"idle":t.type==="error"?"error":"active"}function aa(t){if(!et(t))return!1;let e;try{e=cr(t)}catch{return!1}if(e.length===0||e[e.length-1]===10)return!1;let n=e.lastIndexOf(10),r=n>=0?n+1:0,o=e.subarray(r).toString("utf8").trim();if(Yt(o)){let i=Ie(t,"a");try{ur(i,`
16
+ `),Ut(i)}finally{je(i)}return!0}ta(t,r);let s=Ie(t,"a");try{Ut(s)}finally{je(s)}return!0}function ca(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0}var tt=class{constructor(e,n={}){this.identity=e;this.eventContext=n;Zi(e.localDirectory,{recursive:!0}),this.eventsFile=Gt(e.localDirectory,"events.jsonl"),this.stateFile=Gt(e.localDirectory,"state.json"),this.lockFile=Gt(e.localDirectory,"journal.lock")}identity;eventContext;eventsFile;stateFile;lockFile;initialState(){let e=new Date().toISOString();return{version:1,projectId:this.identity.projectId,agent:this.identity.agent,nativeSessionId:this.identity.nativeSessionId,status:"idle",createdAt:e,updatedAt:e,lastSequence:0,lastRemoteSequence:0,remoteByteOffset:0,sourceCursors:{},recentEventIds:[]}}loadStateUnsafe(){return Hn(this.stateFile)??this.initialState()}recoverStateUnsafe(){aa(this.eventsFile);let e=this.loadStateUnsafe(),n=ia(this.eventsFile);if(n.length===0)return e;let r=n[0];for(let l of n)l.sequence<=r.sequence||(r=l);let o=n.slice(-ir).map(l=>l.id),s=et(this.eventsFile)?Jt(this.eventsFile).size:0,i=Math.max(e.lastSequence,r.sequence),a=Math.min(e.remoteByteOffset,s),c=r.sequence>e.lastSequence;if(!(c||a!==e.remoteByteOffset||!ca(e.recentEventIds,o)||e.lastLocalEventAt!==r.timestamp))return e;let f={...e,status:ar(r),updatedAt:r.timestamp,lastLocalEventAt:r.timestamp,lastSequence:i,remoteByteOffset:a,recentEventIds:o};if(this.saveStateUnsafe(f),!c)return f;try{Bt(this.identity.projectRoot)}catch{return f}try{rr(this.identity.projectRoot)}catch{}return f}loadState(){return this.withLock(()=>this.recoverStateUnsafe())}saveStateUnsafe(e){R(this.stateFile,e)}acquireLock(){for(let e=0;e<oa;e+=1)try{return Ie(this.lockFile,"wx",384)}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Jt(this.lockFile).mtimeMs>ra){sr(this.lockFile,{force:!0});continue}}catch{}sa(25)}throw new Error(`Session journal is locked: ${this.lockFile}`)}withLock(e){let n=this.acquireLock();try{return e()}finally{je(n),sr(this.lockFile,{force:!0})}}append(e){return e.length===0?[]:this.withLock(()=>{let n=this.recoverStateUnsafe(),r=new Set(n.recentEventIds),o=n.lastSequence,s=[];for(let l of e){let p=Gn(l,this.eventContext),d=p.timestamp??new Date().toISOString(),m=p.data??{},S=p.provenance?.rawDigest??w(Vn(m)),g=ke(m),y=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,d,S].join("|"),v=w(y).slice(0,32);if(r.has(v))continue;o+=1;let x={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:d,source:p.source??p.provenance?.source??this.identity.agent,data:g,provenance:{...p.provenance,rawDigest:S}};p.role!==void 0&&(x.role=p.role),p.turnId!==void 0&&(x.turnId=p.turnId),p.cwd!==void 0&&(x.cwd=p.cwd),p.sourceEventId!==void 0&&(x.sourceEventId=p.sourceEventId),p.sourceSequence!==void 0&&(x.sourceSequence=p.sourceSequence),s.push(x),r.add(v)}if(s.length===0)return[];let i=s.map(l=>JSON.stringify(l)).join(`
17
17
  `)+`
18
- `,a=ve(this.eventsFile,"a",384);try{Vn(a,i),Lt(a)}finally{ke(a)}try{zn(this.identity.projectRoot,o)}catch{try{Kt(this.identity.projectRoot)}catch{}}let c=o[o.length-1],u=Jn(c),p=Array.from(r).slice(-Bn);return this.saveStateUnsafe({...n,status:u,updatedAt:c.timestamp,lastLocalEventAt:c.timestamp,lastSequence:c.sequence,recentEventIds:p}),o})}readPending(){return this.withLock(()=>{let e=this.recoverStateUnsafe();if(!He(this.eventsFile))return{events:[],startOffset:e.remoteByteOffset,endOffset:e.remoteByteOffset};let n=Ft(this.eventsFile).size,r=Math.min(e.remoteByteOffset,n);if(n<=r)return{events:[],startOffset:r,endOffset:n};let s=n-r,o=Buffer.alloc(s),i=ve(this.eventsFile,"r");try{Pi(i,o,0,s,r)}finally{ke(i)}let a=[];for(let c of o.toString("utf8").split(/\r?\n/)){let u=Dt(c);u&&a.push(u)}return{events:a,startOffset:r,endOffset:n}})}markRemote(e,n){this.withLock(()=>{let r=this.recoverStateUnsafe(),s=new Date().toISOString();this.saveStateUnsafe({...r,lastRemoteSequence:Math.max(r.lastRemoteSequence,e),remoteByteOffset:Math.max(r.remoteByteOffset,n),lastRemoteAt:s,updatedAt:s})})}setSourceCursor(e,n){this.withLock(()=>{let r=this.recoverStateUnsafe();this.saveStateUnsafe({...r,sourceCursors:{...r.sourceCursors,[e]:String(n)},updatedAt:new Date().toISOString()})})}};import{closeSync as Oc,existsSync as Tc,openSync as Rc,readSync as Nc,statSync as _c}from"node:fs";var Fi=new Set(["rule","blocker","architecture","deploy"]),Wi=new Set(["fix","todo","context","next_action"]);function zt(t){return t<0?0:t>1?1:t}function Gn(t,e){let n=Number.parseFloat(t??"");return Number.isFinite(n)?n:e}function Li(t){return t==="off"?"off":t==="balanced"?"balanced":t==="aggressive"?"aggressive":"conservative"}function qt(){return{mode:Li(process.env.TOOLNET_MEMORY_PROMOTION),minScore:zt(Gn(process.env.TOOLNET_PROMOTE_MIN_SCORE,.65)),minConfidence:zt(Gn(process.env.TOOLNET_PROMOTE_MIN_CONFIDENCE,.78))}}function Di(t){switch(t){case"critical":return 1;case"high":return .85;case"normal":return .6;case"temporary":return .25}}function zi(t){let e=zt(Di(t.importance)*.75+t.confidence*.25);return Math.round(e*1e6)/1e6}function qi(t){return t.evidence?t.evidence:{userExplicit:!1,sourceVerified:!1,testVerified:!1,crossSessionConfirmations:0,assistantDerived:!1}}function Bi(t,e=qt()){if(t.importance==="temporary"||t.confidence<e.minConfidence)return"transient";let n=qi(t);return t.kind==="rule"&&n.userExplicit?"permanent":t.kind==="rule"?"session":t.kind==="architecture"&&(n.userExplicit||n.sourceVerified||n.testVerified||n.crossSessionConfirmations>=2)?"permanent":t.kind==="architecture"?"session":t.kind==="decision"||t.kind==="todo"||t.kind==="fix"?"task":"session"}function Ji(t,e=qt()){if(e.mode==="off")return Number.POSITIVE_INFINITY;let n=0;e.mode==="balanced"&&(n=.1),e.mode==="aggressive"&&(n=.15);let r=Math.max(e.mode==="aggressive"?.5:.55,e.minScore-n);return Fi.has(t)&&(r=Math.max(.5,r-.1)),Wi.has(t)&&(r=Math.max(.5,r-.05)),r}function Bt(t,e=qt()){let n=Bi(t,e),r=zi(t),s=Ji(t.kind,e);return n==="transient"?{knowledgeClass:n,score:r,threshold:s,persist:!1}:e.mode==="off"?{knowledgeClass:n,score:r,threshold:s,persist:!1}:{knowledgeClass:n,score:r,threshold:s,persist:r>=s}}function Un(t,e){let n=e.toLowerCase();return n.includes("kh\xF4ng \u0111\u01B0\u1EE3c")||n.includes("tuy\u1EC7t \u0111\u1ED1i")||n.includes("must not")||n.includes("never ")?"critical":t==="rule"||t==="decision"?"high":t==="todo"||n.includes("error")||n.includes("failed")||n.includes("exception")?"normal":"temporary"}var Zn=[/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],Hi=[/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],Vi=[/\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],Gi=[/\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],Ui=[/đã 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],Yn=[/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],Yi=[/\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],Xi=[/đườ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],Qi=[/\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],Xn=new Set(["content","text","message","prompt","summary","description","reason","title","last_assistant_message","lastAssistantMessage","input_messages","inputMessages"]),Zi=new Set(["payload","data","content","message","messages","parts","summary"]);function R(t,e){return e.some(n=>n.test(t))}function er(t){return t.normalize("NFKC").replace(/\r/g,"").replace(/^[\s>*#\-•]+/u,"").replace(/\s+/g," ").trim()}function ea(t){return er(t).toLowerCase().replace(/[^\p{L}\p{N}:/._-]+/gu," ").replace(/\s+/g," ").trim()}function ta(t){return!(t.length<12||t.length>1e3||(t.match(new RegExp("\\p{L}","gu"))??[]).length<6||/^(?:https?:\/\/\S+|[A-Za-z0-9+/=]{80,})$/u.test(t))}function Jt(t,e,n,r=0){if(!(r>6)&&!(typeof t=="string"&&e&&!Xn.has(e))){if(typeof t=="string"){n.push(t);return}if(Array.isArray(t)){for(let s of t.slice(0,50))Jt(s,e,n,r+1);return}if(!(!t||typeof t!="object"))for(let[s,o]of Object.entries(t))(Xn.has(s)||Zi.has(s))&&Jt(o,s,n,r+1)}}function na(t){let e=[];Jt(t.data,void 0,e);let n=[],r=new Set;for(let s of e)for(let o of s.split(/\n+|(?<=[.!?])\s+/u)){let i=er(o);if(ta(i)&&!r.has(i)&&(r.add(i),n.push(i),n.length>=50))return n}return n}function Qn(t){return(t.role??(typeof t.data.role=="string"?t.data.role:"")).toLowerCase()}function ra(t,e,n){if(n.type==="decision")return{kind:"decision",confidence:1};if(n.type==="todo")return{kind:"todo",confidence:1};let r=e==="user"||n.type==="user_prompt",s=e==="assistant"||n.type==="assistant_message";return r&&R(t,Zn)?{kind:"rule",confidence:.98}:r&&R(t,Hi)?{kind:"rule",confidence:.92}:R(t,Vi)?{kind:R(t,Yn)?"architecture":"decision",confidence:r?.93:.86}:r&&R(t,Gi)?{kind:"todo",confidence:.87}:R(t,Yn)&&R(t,Yi)?{kind:"architecture",confidence:r?.88:.82}:s&&R(t,Ui)?{kind:"fix",confidence:.8}:r&&R(t,Xi)&&R(t,Qi)?{kind:"context",confidence:.79}:null}function sa(t,e,n){let r=e==="user"||n.type==="user_prompt",s=e==="assistant"||n.type==="assistant_message",o=!!n.provenance.sourcePath&&(t==="architecture"||t==="context"||t==="fix"),i=t==="fix"&&/(?:test|tests|pass|passed|passing)/iu.test(JSON.stringify(n.data));return{userExplicit:r,sourceVerified:o,testVerified:i,crossSessionConfirmations:1,assistantDerived:s}}function oa(t){switch(t){case"rule":return"rule";case"decision":case"architecture":return"decision";case"todo":return"todo";case"fix":case"context":return"code"}}function ia(t,e,n){return t==="rule"&&R(n,Zn)?"critical":t==="architecture"||t==="decision"||t==="rule"?"high":t==="fix"||t==="context"?"normal":Un(e,n)}function tr(t,e){let n=[],r=new Set,s=new Map;for(let o of e){let i=typeof o.data.messageId=="string"?o.data.messageId:void 0,a=Qn(o);i&&a&&s.set(i,a)}for(let o of e){let i=Qn(o),a=typeof o.data.messageId=="string"?o.data.messageId:void 0;!i&&a&&(i=s.get(a)??"");for(let c of na(o)){let u=ra(c,i,o);if(!u||u.confidence<.75)continue;let p=oa(u.kind),l=ea(c),f=v([t.projectId,u.kind,l].join("|"));if(r.has(f))continue;r.add(f);let d=o.provenance.sourcePath?[o.provenance.sourcePath]:[],g=o.sourceEventId?[o.sourceEventId]:[];n.push({version:1,fingerprint:f,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,kind:u.kind,type:p,content:c,confidence:u.confidence,importance:ia(u.kind,p,c),evidence:sa(u.kind,i,o),tags:[p],provenance:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,eventIds:[o.id],sourceEventIds:g,sourcePaths:d,firstSequence:o.sequence,lastSequence:o.sequence},createdAt:o.timestamp})}}return n}import{createHash as aa}from"node:crypto";var ca=["project-knowledge","implementation","continuation","session-context"],ua={"project-knowledge":"Project knowledge",implementation:"Implementation state",continuation:"Work continuation","session-context":"Session context"};function Ht(t){return aa("sha256").update(t).digest("hex")}function Ge(t,e){return`${t}:${Ht(e).slice(0,24)}`}function la(t){try{return Ht(JSON.stringify(t))}catch{return Ht(String(t))}}function Y(t){let e=new Set,n=[];for(let r of t){let s=r?.replace(/\s+/gu," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();e.has(o)||(e.add(o),n.push(s))}return n}function rr(t,e=420){let n=t.replace(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1)).trimEnd()}\u2026`}function da(t){return t==="rule"||t==="architecture"?"project-knowledge":t==="decision"||t==="fix"?"implementation":t==="todo"?"continuation":"session-context"}function nr(t){return t.length===0?0:t.reduce((e,n)=>e+n,0)/t.length}function pa(t){return t.slice().sort((e,n)=>n.importanceScore-e.importanceScore||n.confidence-e.confidence||e.id.localeCompare(n.id)).slice(0,5).map(e=>rr(e.content)).join(" | ")}function fa(t){return t.slice().sort((e,n)=>n.importanceScore-e.importanceScore||n.confidence-e.confidence||e.id.localeCompare(n.id)).slice(0,6).map(e=>rr(e.content)).join(`
19
- `)}function sr(t,e){let n=t.slice().sort((f,d)=>f.sequence-d.sequence||f.timestamp.localeCompare(d.timestamp)||f.id.localeCompare(d.id)),r=n.map(f=>({id:Ge("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:la(f.data)})),s=new Map,o=new Map;n.forEach((f,d)=>{let g=r[d];g&&(s.set(f.id,g.id),f.sourceEventId&&o.set(f.sourceEventId,g.id))});let i=e.map(f=>{let d=Y([...f.provenance.eventIds.map(g=>s.get(g)),...f.provenance.sourceEventIds.map(g=>o.get(g))]);return{id:Ge("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:Y([...f.tags,"level:fact",`class:${f.knowledgeClass}`,`kind:${f.kind}`]),rawIds:d,sourcePaths:Y(f.provenance.sourcePaths)}}),a=new Map;for(let f of i){let d=da(f.kind),g=a.get(d)??[];g.push(f),a.set(d,g)}let c=[];for(let f of ca){let d=a.get(f);if(!d?.length)continue;let g=d.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:Ge("scene",`${f}|${S.join("|")}`),level:"scene",kind:f,title:ua[f],summary:pa(g),factIds:S,importanceScore:Math.max(...g.map(y=>y.importanceScore)),confidence:nr(g.map(y=>y.confidence)),tags:Y(["level:scene",`scene:${f}`,...g.flatMap(y=>y.tags)]),sourcePaths:Y(g.flatMap(y=>y.sourcePaths))})}let u=new Map(i.map(f=>[f.id,f])),p=[];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=fa(g);p.push({id:Ge("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:nr(g.map(h=>h.confidence)),tags:Y(["level:knowledge",`class:${S}`,`scene:${f.kind}`,...g.flatMap(h=>h.tags)]),sourcePaths:Y(g.flatMap(h=>h.sourcePaths))})}let l=[];for(let f of i)for(let d of f.rawIds)l.push({from:d,to:f.id,type:"supports"});for(let f of c)for(let d of f.factIds)l.push({from:d,to:f.id,type:"belongs_to"});for(let f of p)for(let d of f.sceneIds)l.push({from:d,to:f.id,type:"promotes_to"});return{schema:"toolnet.memory-hierarchy.v1",version:1,raw:r,facts:i,scenes:c,knowledge:p,links:l,stats:{raw:r.length,facts:i.length,scenes:c.length,knowledge:p.length,links:l.length}}}function Ue(t){return t?Math.ceil(t.length/3.5):0}function Ye(t,e){if(!t)return"";if(Ue(t)<=e)return t;let r=Math.floor(e*3.5),s=t.slice(0,r),o=s.lastIndexOf("."),i=s.lastIndexOf(`
20
- `),a=Math.max(o,i);return a>r*.7?s.slice(0,a+1):s}function X(){let t=Ne(),e=process.env.TOOLNET_SESSION_SAVE||"summary",n=process.env.TOOLNET_RAW_TRANSCRIPT==="on"||e==="archive"||e==="full",r=process.env.TOOLNET_MEMORY_PROMOTION||"conservative",s=parseFloat(process.env.TOOLNET_PROMOTE_MIN_SCORE||"0.65"),o=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"||e==="full";return{sessionSave:e,rawTranscript:n,memoryPromotion:r,promoteMinScore:s,sessionSummaryMaxTokens:o,durableMemoryMaxItemsPerSession:i,archiveLocal:a,archiveRemote:c}}function or(t){return(t||X()).rawTranscript}function ir(t){return(t||X()).durableMemoryMaxItemsPerSession}function ar(t){return(t||X()).sessionSummaryMaxTokens}function cr(t){return(t||X()).archiveRemote}var ur=new G;function lr(t){let e=t.trim();if(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))try{let r=JSON.parse(e);return JSON.stringify(ur.sanitizeValue(r))}catch{}let n=ur.sanitize(t).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 ma(t,e){let n=t.toLowerCase(),r=.5,s=["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 s)n.includes(i)&&(r+=.15);e==="rule"||e==="architecture"||e==="blocker"?r+=.2:e==="decision"||e==="deploy"?r+=.15:(e==="fix"||e==="next_action")&&(r+=.1),t.length<20?r-=.3:t.length>500&&(r-=.1);let o=[/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 o)i.test(t)&&(r-=.4);return Math.max(0,Math.min(1,r))}function ga(t,e){let n=[],r=new Set;for(let i of t){let a=i.split(`
21
- `).filter(c=>c.trim());for(let c of a){let u=c.trim();if(u.length<15)continue;let p=u.toLowerCase().replace(/\s+/g," ");if(r.has(p))continue;r.add(p);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=ma(u,l);if(f<.3)continue;let d=lr(u);n.push({category:l,text:d,importance:f,sourceSessionId:e})}}let s=X(),o=ir(s);return n.sort((i,a)=>a.importance-i.importance).slice(0,o)}function ya(t){let e=X(),n=ar(e),o=t.join(`
18
+ `,a=Ie(this.eventsFile,"a",384);try{ur(a,i),Ut(a)}finally{je(a)}try{or(this.identity.projectRoot,s)}catch{try{Bt(this.identity.projectRoot)}catch{}}let c=s[s.length-1],u=ar(c),f=Array.from(r).slice(-ir);return this.saveStateUnsafe({...n,status:u,updatedAt:c.timestamp,lastLocalEventAt:c.timestamp,lastSequence:c.sequence,recentEventIds:f}),s})}readPending(){return this.withLock(()=>{let e=this.recoverStateUnsafe();if(!et(this.eventsFile))return{events:[],startOffset:e.remoteByteOffset,endOffset:e.remoteByteOffset};let n=Jt(this.eventsFile).size,r=Math.min(e.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{ea(i,s,0,o,r)}finally{je(i)}let a=[];for(let c of s.toString("utf8").split(/\r?\n/)){let u=Yt(c);u&&a.push(u)}return{events:a,startOffset:r,endOffset:n}})}markRemote(e,n){this.withLock(()=>{let r=this.recoverStateUnsafe(),o=new Date().toISOString();this.saveStateUnsafe({...r,lastRemoteSequence:Math.max(r.lastRemoteSequence,e),remoteByteOffset:Math.max(r.remoteByteOffset,n),lastRemoteAt:o,updatedAt:o})})}setSourceCursor(e,n){this.withLock(()=>{let r=this.recoverStateUnsafe();this.saveStateUnsafe({...r,sourceCursors:{...r.sourceCursors,[e]:String(n)},updatedAt:new Date().toISOString()})})}};import{closeSync as ru,existsSync as ou,openSync as su,readSync as iu,statSync as au}from"node:fs";var ua=new Set(["rule","blocker","architecture","deploy"]),la=new Set(["fix","todo","context","next_action"]);function Xt(t){return t<0?0:t>1?1:t}function lr(t,e){let n=Number.parseFloat(t??"");return Number.isFinite(n)?n:e}function da(t){return t==="off"?"off":t==="balanced"?"balanced":t==="aggressive"?"aggressive":"conservative"}function Qt(){return{mode:da(process.env.TOOLNET_MEMORY_PROMOTION),minScore:Xt(lr(process.env.TOOLNET_PROMOTE_MIN_SCORE,.65)),minConfidence:Xt(lr(process.env.TOOLNET_PROMOTE_MIN_CONFIDENCE,.78))}}function pa(t){switch(t){case"critical":return 1;case"high":return .85;case"normal":return .6;case"temporary":return .25}}function fa(t){let e=Xt(pa(t.importance)*.75+t.confidence*.25);return Math.round(e*1e6)/1e6}function ma(t){return t.evidence?t.evidence:{userExplicit:!1,sourceVerified:!1,testVerified:!1,crossSessionConfirmations:0,assistantDerived:!1}}function ga(t,e=Qt()){if(t.importance==="temporary"||t.confidence<e.minConfidence)return"transient";let n=ma(t);return t.kind==="rule"&&n.userExplicit?"permanent":t.kind==="rule"?"session":t.kind==="architecture"&&(n.userExplicit||n.sourceVerified||n.testVerified||n.crossSessionConfirmations>=2)?"permanent":t.kind==="architecture"?"session":t.kind==="decision"||t.kind==="todo"||t.kind==="next_action"||t.kind==="fix"?"task":"session"}function ya(t,e=Qt()){if(e.mode==="off")return Number.POSITIVE_INFINITY;let n=0;e.mode==="balanced"&&(n=.1),e.mode==="aggressive"&&(n=.15);let r=Math.max(e.mode==="aggressive"?.5:.55,e.minScore-n);return ua.has(t)&&(r=Math.max(.5,r-.1)),la.has(t)&&(r=Math.max(.5,r-.05)),r}function Zt(t,e=Qt()){let n=ga(t,e),r=fa(t),o=ya(t.kind,e);return n==="transient"?{knowledgeClass:n,score:r,threshold:o,persist:!1}:e.mode==="off"?{knowledgeClass:n,score:r,threshold:o,persist:!1}:{knowledgeClass:n,score:r,threshold:o,persist:r>=o}}function dr(t,e){let n=e.toLowerCase();return n.includes("kh\xF4ng \u0111\u01B0\u1EE3c")||n.includes("tuy\u1EC7t \u0111\u1ED1i")||n.includes("must not")||n.includes("never ")?"critical":t==="rule"||t==="decision"?"high":t==="todo"||n.includes("error")||n.includes("failed")||n.includes("exception")?"normal":"temporary"}var gr=[/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],ha=[/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],Sa=[/\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],ka=[/\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],va=[/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],wa=[/đã 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],pr=[/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],ba=[/\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],xa=[/đườ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],ja=[/\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],fr=new Set(["content","text","message","prompt","summary","description","reason","title","last_assistant_message","lastAssistantMessage","input_messages","inputMessages"]),Ia=new Set(["payload","data","content","message","messages","parts","summary"]);function N(t,e){return e.some(n=>n.test(t))}function yr(t){return t.normalize("NFKC").replace(/\r/g,"").replace(/^[\s>*#\-•]+/u,"").replace(/\s+/g," ").trim()}function Ca(t){return yr(t).toLowerCase().replace(/[^\p{L}\p{N}:/._-]+/gu," ").replace(/\s+/g," ").trim()}function Aa(t){return!(t.length<12||t.length>1e3||(t.match(new RegExp("\\p{L}","gu"))??[]).length<6||/^(?:https?:\/\/\S+|[A-Za-z0-9+/=]{80,})$/u.test(t))}function en(t,e,n,r=0){if(!(r>6)&&!(typeof t=="string"&&e&&!fr.has(e))){if(typeof t=="string"){n.push(t);return}if(Array.isArray(t)){for(let o of t.slice(0,50))en(o,e,n,r+1);return}if(!(!t||typeof t!="object"))for(let[o,s]of Object.entries(t))(fr.has(o)||Ia.has(o))&&en(s,o,n,r+1)}}function Ma(t){let e=[];en(t.data,void 0,e);let n=[],r=new Set;for(let o of e)for(let s of o.split(/\n+|(?<=[.!?])\s+/u)){let i=yr(s);if(Aa(i)&&!r.has(i)&&(r.add(i),n.push(i),n.length>=50))return n}return n}function mr(t){return(t.role??(typeof t.data.role=="string"?t.data.role:"")).toLowerCase()}function Pa(t,e,n){if(n.type==="decision")return{kind:"decision",confidence:1};if(n.type==="todo")return{kind:"todo",confidence:1};let r=e==="user"||n.type==="user_prompt",o=e==="assistant"||n.type==="assistant_message";return r&&N(t,gr)?{kind:"rule",confidence:.98}:r&&N(t,ha)?{kind:"rule",confidence:.92}:N(t,Sa)?{kind:N(t,pr)?"architecture":"decision",confidence:r?.93:.86}:r&&N(t,va)?{kind:"next_action",confidence:.88}:r&&N(t,ka)?{kind:"todo",confidence:.87}:N(t,pr)&&N(t,ba)?{kind:"architecture",confidence:r?.88:.82}:o&&N(t,wa)?{kind:"fix",confidence:.8}:r&&N(t,xa)&&N(t,ja)?{kind:"context",confidence:.79}:null}function Ea(t,e,n){let r=e==="user"||n.type==="user_prompt",o=e==="assistant"||n.type==="assistant_message",s=!!n.provenance.sourcePath&&(t==="architecture"||t==="context"||t==="fix"),i=t==="fix"&&/(?:test|tests|pass|passed|passing)/iu.test(JSON.stringify(n.data));return{userExplicit:r,sourceVerified:s,testVerified:i,crossSessionConfirmations:1,assistantDerived:o}}function Oa(t){switch(t){case"rule":return"rule";case"decision":case"architecture":return"decision";case"todo":case"next_action":return"todo";case"fix":case"context":return"code"}}function Ta(t,e,n){return t==="rule"&&N(n,gr)?"critical":t==="architecture"||t==="decision"||t==="rule"?"high":t==="fix"||t==="context"?"normal":dr(e,n)}function hr(t,e){let n=[],r=new Set,o=new Map;for(let s of e){let i=typeof s.data.messageId=="string"?s.data.messageId:void 0,a=mr(s);i&&a&&o.set(i,a)}for(let s of e){let i=mr(s),a=typeof s.data.messageId=="string"?s.data.messageId:void 0;!i&&a&&(i=o.get(a)??"");for(let c of Ma(s)){let u=Pa(c,i,s);if(!u||u.confidence<.75)continue;let f=Oa(u.kind),l=Ca(c),p=w([t.projectId,u.kind,l].join("|"));if(r.has(p))continue;r.add(p);let d=s.provenance.sourcePath?[s.provenance.sourcePath]:[],m=s.sourceEventId?[s.sourceEventId]:[];n.push({version:1,fingerprint:p,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,kind:u.kind,type:f,content:c,confidence:u.confidence,importance:Ta(u.kind,f,c),evidence:Ea(u.kind,i,s),tags:[f],provenance:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,eventIds:[s.id],sourceEventIds:m,sourcePaths:d,firstSequence:s.sequence,lastSequence:s.sequence},createdAt:s.timestamp})}}return n}import{createHash as Ra}from"node:crypto";var Na=["project-knowledge","implementation","continuation","session-context"],_a={"project-knowledge":"Project knowledge",implementation:"Implementation state",continuation:"Work continuation","session-context":"Session context"};function tn(t){return Ra("sha256").update(t).digest("hex")}function nt(t,e){return`${t}:${tn(e).slice(0,24)}`}function Ka(t){try{return tn(JSON.stringify(t))}catch{return tn(String(t))}}function Z(t){let e=new Set,n=[];for(let r of t){let o=r?.replace(/\s+/gu," ").trim();if(!o)continue;let s=o.normalize("NFKC").toLowerCase();e.has(s)||(e.add(s),n.push(o))}return n}function kr(t,e=420){let n=t.replace(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1)).trimEnd()}\u2026`}function $a(t){return t==="rule"||t==="architecture"?"project-knowledge":t==="decision"||t==="fix"?"implementation":t==="todo"?"continuation":"session-context"}function Sr(t){return t.length===0?0:t.reduce((e,n)=>e+n,0)/t.length}function La(t){return t.slice().sort((e,n)=>n.importanceScore-e.importanceScore||n.confidence-e.confidence||e.id.localeCompare(n.id)).slice(0,5).map(e=>kr(e.content)).join(" | ")}function Fa(t){return t.slice().sort((e,n)=>n.importanceScore-e.importanceScore||n.confidence-e.confidence||e.id.localeCompare(n.id)).slice(0,6).map(e=>kr(e.content)).join(`
19
+ `)}function vr(t,e){let n=t.slice().sort((p,d)=>p.sequence-d.sequence||p.timestamp.localeCompare(d.timestamp)||p.id.localeCompare(d.id)),r=n.map(p=>({id:nt("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:Ka(p.data)})),o=new Map,s=new Map;n.forEach((p,d)=>{let m=r[d];m&&(o.set(p.id,m.id),p.sourceEventId&&s.set(p.sourceEventId,m.id))});let i=e.map(p=>{let d=Z([...p.provenance.eventIds.map(m=>o.get(m)),...p.provenance.sourceEventIds.map(m=>s.get(m))]);return{id:nt("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:Z([...p.tags,"level:fact",`class:${p.knowledgeClass}`,`kind:${p.kind}`]),rawIds:d,sourcePaths:Z(p.provenance.sourcePaths)}}),a=new Map;for(let p of i){let d=$a(p.kind),m=a.get(d)??[];m.push(p),a.set(d,m)}let c=[];for(let p of Na){let d=a.get(p);if(!d?.length)continue;let m=d.slice().sort((g,y)=>y.importanceScore-g.importanceScore||y.confidence-g.confidence||g.id.localeCompare(y.id)),S=m.map(g=>g.id);c.push({id:nt("scene",`${p}|${S.join("|")}`),level:"scene",kind:p,title:_a[p],summary:La(m),factIds:S,importanceScore:Math.max(...m.map(g=>g.importanceScore)),confidence:Sr(m.map(g=>g.confidence)),tags:Z(["level:scene",`scene:${p}`,...m.flatMap(g=>g.tags)]),sourcePaths:Z(m.flatMap(g=>g.sourcePaths))})}let u=new Map(i.map(p=>[p.id,p])),f=[];for(let p of c){let m=p.factIds.map(y=>u.get(y)).filter(y=>!!y).filter(y=>(y.knowledgeClass==="permanent"||y.knowledgeClass==="task")&&y.importanceScore>=.55);if(m.length===0)continue;let S=m.some(y=>y.knowledgeClass==="permanent")?"permanent":"task",g=Fa(m);f.push({id:nt("knowledge",`${p.id}|${S}|${m.map(y=>y.id).join("|")}`),level:"knowledge",knowledgeClass:S,title:p.title,content:g,sceneIds:[p.id],factIds:m.map(y=>y.id),importanceScore:Math.max(...m.map(y=>y.importanceScore)),confidence:Sr(m.map(y=>y.confidence)),tags:Z(["level:knowledge",`class:${S}`,`scene:${p.kind}`,...m.flatMap(y=>y.tags)]),sourcePaths:Z(m.flatMap(y=>y.sourcePaths))})}let l=[];for(let p of i)for(let d of p.rawIds)l.push({from:d,to:p.id,type:"supports"});for(let p of c)for(let d of p.factIds)l.push({from:d,to:p.id,type:"belongs_to"});for(let p of f)for(let d of p.sceneIds)l.push({from:d,to:p.id,type:"promotes_to"});return{schema:"toolnet.memory-hierarchy.v1",version:1,raw:r,facts:i,scenes:c,knowledge:f,links:l,stats:{raw:r.length,facts:i.length,scenes:c.length,knowledge:f.length,links:l.length}}}function rt(t){return t?Math.ceil(t.length/3.5):0}function ot(t,e){if(!t)return"";if(rt(t)<=e)return t;let r=Math.floor(e*3.5),o=t.slice(0,r),s=o.lastIndexOf("."),i=o.lastIndexOf(`
20
+ `),a=Math.max(s,i);return a>r*.7?o.slice(0,a+1):o}function ee(){let t=We(),e=process.env.TOOLNET_SESSION_SAVE||"summary",n=process.env.TOOLNET_RAW_TRANSCRIPT==="on"||e==="archive"||e==="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"||e==="full";return{sessionSave:e,rawTranscript:n,memoryPromotion:r,promoteMinScore:o,sessionSummaryMaxTokens:s,durableMemoryMaxItemsPerSession:i,archiveLocal:a,archiveRemote:c}}function wr(t){return(t||ee()).rawTranscript}function br(t){return(t||ee()).durableMemoryMaxItemsPerSession}function xr(t){return(t||ee()).sessionSummaryMaxTokens}function jr(t){return(t||ee()).archiveRemote}var Ir=new H;function Cr(t){let e=t.trim();if(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))try{let r=JSON.parse(e);return JSON.stringify(Ir.sanitizeValue(r))}catch{}let n=Ir.sanitize(t).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 Wa(t,e){let n=t.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);e==="rule"||e==="architecture"||e==="blocker"?r+=.2:e==="decision"||e==="deploy"?r+=.15:(e==="fix"||e==="next_action")&&(r+=.1),t.length<20?r-=.3:t.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(t)&&(r-=.4);return Math.max(0,Math.min(1,r))}function Da(t,e){let n=[],r=new Set;for(let i of t){let a=i.split(`
21
+ `).filter(c=>c.trim());for(let c of a){let u=c.trim();if(u.length<15)continue;let f=u.toLowerCase().replace(/\s+/g," ");if(r.has(f))continue;r.add(f);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 p=Wa(u,l);if(p<.3)continue;let d=Cr(u);n.push({category:l,text:d,importance:p,sourceSessionId:e})}}let o=ee(),s=br(o);return n.sort((i,a)=>a.importance-i.importance).slice(0,s)}function za(t){let e=ee(),n=xr(e),s=t.join(`
22
22
 
23
23
  `).split(`
24
- `).filter(i=>{let a=i.trim();return a.length>20&&!a.startsWith("npm")&&!a.startsWith("\u2713")&&!a.startsWith("Error:")}).slice(0,20).map(i=>lr(i)).join(`
25
- `);return Ye(o,n)}function Xe(t,e){let r=(Array.isArray(t)?t:t.split(`
24
+ `).filter(i=>{let a=i.trim();return a.length>20&&!a.startsWith("npm")&&!a.startsWith("\u2713")&&!a.startsWith("Error:")}).slice(0,20).map(i=>Cr(i)).join(`
25
+ `);return ot(s,n)}function st(t,e){let r=(Array.isArray(t)?t:t.split(`
26
26
 
27
- `).filter(d=>d.trim())).map(d=>typeof d=="string"?d:JSON.stringify(d)).filter(d=>d.trim()),s=ga(r,e),o=s.filter(d=>d.category==="decision").map(d=>d.text),i=s.filter(d=>d.category==="rule").map(d=>d.text),a=s.filter(d=>d.category==="file").map(d=>d.text),c=s.filter(d=>d.category==="fix").map(d=>d.text),u=s.filter(d=>d.category==="blocker").map(d=>d.text),p=s.filter(d=>d.category==="next_action").map(d=>d.text),l=s.filter(d=>d.category==="deploy").map(d=>d.text);return{summary:ya(r),decisions:o,projectRules:i,filesChanged:a,bugsFixed:c,commands:l,blockers:u,nextActions:p,durableFacts:s}}function J(t){let e=new Set,n=[];for(let r of t){let s=r?.replace(/\s+/g," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();e.has(o)||(e.add(o),n.push(s))}return n}function ha(t){let e=new Map;for(let n of t){if(!n||!n.id||!Number.isFinite(n.sequence))continue;let r=n.sourceEventId?`${n.agent}:${n.sourceEventId}`:n.id,s=e.get(r);(!s||n.sequence>s.sequence)&&e.set(r,n)}return[...e.values()].sort((n,r)=>n.sequence-r.sequence||n.timestamp.localeCompare(r.timestamp))}function Sa(t){let e=t.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_./:-]+/gu)??[],n=new Set;for(let r of e)if(!(r.length<2||/^\d+$/u.test(r))&&(n.add(r),n.size>=40))break;return[...n]}function ka(t){let e=Bt(t);return{...t,knowledgeClass:e.knowledgeClass,importanceScore:e.score,retrievalTerms:Sa(t.content),tags:J([...t.tags,"level:fact",`class:${e.knowledgeClass}`,`kind:${t.kind}`])}}function va(t){return t.map(e=>{try{return JSON.stringify({type:e.type,role:e.role,data:e.data,provenance:{sourcePath:e.provenance.sourcePath,files:e.provenance.files}})}catch{return""}}).filter(Boolean)}function wa(t,e,n){let r=Xe(va(e),t.nativeSessionId),s=n.filter(u=>u.kind==="todo").map(u=>u.content),o=n.flatMap(u=>u.provenance.sourcePaths),i=n.filter(u=>u.kind==="architecture").map(u=>u.content),a=J([...s,...r.nextActions]),c=J([...r.nextActions,...s]);return{summary:r.summary,state:{task:c[0]??a[0],decisions:J(r.decisions),files:J([...r.filesChanged,...o]),todos:a,completed:J(r.bugsFixed),blockers:J(r.blockers),nextActions:c,architecture:J(i)}}}function Qe(t,e){let n=ha(e),r=tr(t,n).map(ka),s=r.filter(p=>Bt(p).persist).sort((p,l)=>l.importanceScore-p.importanceScore),{summary:o,state:i}=wa(t,n,s),a=s.map(p=>({fingerprint:p.fingerprint,kind:p.kind,knowledgeClass:p.knowledgeClass,importanceScore:p.importanceScore,content:p.content,terms:p.retrievalTerms})),c=sr(n,s),u=p=>r.filter(l=>l.knowledgeClass===p).length;return{version:2,normalizedEvents:n,summary:o,state:i,candidates:s,retrievalIndex:a,hierarchy:c,stats:{inputEvents:e.length,normalizedEvents:n.length,extractedCandidates:r.length,persistedCandidates:s.length,permanent:u("permanent"),task:u("task"),session:u("session"),transient:u("transient")}}}import{createHash as ba}from"node:crypto";import{chmodSync as dr,existsSync as xa,mkdirSync as ja,readFileSync as Ca,renameSync as Ia,writeFileSync as pr}from"node:fs";import{dirname as fr,join as Ze}from"node:path";var Ut="toolnet.context-offload.v1",Aa="toolnet.context-offload-asset.v1",Ma=256,Pa=new Set(["tool_call","tool_result","file_read","file_write","file_edit","command","test","artifact"]);function mr(t){return Ze(t,".toolnet","offload")}function Ea(t){return Ze(mr(t),"assets")}function gr(t){return Ze(mr(t),"graph.json")}function yr(t){ja(t,{recursive:!0,mode:448});try{dr(t,448)}catch{}}function Oa(t,e){yr(fr(t));let n=`${t}.${process.pid}.${Date.now()}.tmp`;pr(n,e,{encoding:"utf8",mode:384}),Ia(n,t);try{dr(t,384)}catch{}}function Gt(t){return Array.isArray(t)?t.map(Gt):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,Gt(n)])):t}function Ta(t){return ba("sha256").update(JSON.stringify(Gt(t)),"utf8").digest("hex")}function Vt(){return{schema:Ut,version:1,updatedAt:new Date(0).toISOString(),nodes:[]}}function Ra(t){let e=gr(t);if(!xa(e))return Vt();try{let n=JSON.parse(Ca(e,"utf8"));return n.schema!==Ut||n.version!==1||!Array.isArray(n.nodes)?Vt():n}catch{return Vt()}}function Na(t,e){Oa(gr(t),JSON.stringify(e,null,2)+`
28
- `)}function _a(t,e=260){if(typeof t!="string")return null;let n=t.replace(/\s+/gu," ").trim();return n?n.slice(0,e):null}function $a(t){let e=[...t.provenance.files??[],t.provenance.sourcePath],n=[];for(let r of e){let s=_a(r);if(!(!s||n.includes(s))&&(n.push(s),n.length===3))break}return n}function Ka(t){return`${t.agent}:${t.sourceEventId??t.id}`.replace(/\s+/gu," ").trim().slice(0,120)}function Fa(t,e){yr(fr(t));try{return pr(t,e,{encoding:"utf8",flag:"wx",mode:384}),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function Wa(t,e){let n=t.nodes.find(s=>s.id===e.id),r=n?{...n,kind:e.kind,bytes:e.bytes,sourceRefs:Array.from(new Set([...n.sourceRefs,...e.sourceRefs])).slice(-8),files:Array.from(new Set([...n.files,...e.files])).slice(0,6)}:e;return{schema:Ut,version:1,updatedAt:new Date().toISOString(),nodes:[...t.nodes.filter(s=>s.id!==e.id),r].slice(-Ma)}}function hr(t,e){let n=Ra(t),r=0,s=0,o=0,i=[];for(let a of e){if(!Pa.has(a.type))continue;r+=1;let c=Ta({type:a.type,data:a.data}),u={schema:Aa,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}},p=JSON.stringify(u,null,2)+`
29
- `;Fa(Ze(Ea(t),`${c}.json`),p)?s+=1:o+=1,i.push(c),n=Wa(n,{id:c,kind:a.type,bytes:Buffer.byteLength(p,"utf8"),createdAt:a.timestamp,sourceRefs:[Ka(a)],files:$a(a)})}return r>0&&Na(t,n),{eligible:r,written:s,deduped:o,graphNodes:n.nodes.length,assetIds:i}}import{createHash as Va}from"node:crypto";import{existsSync as Ga,readdirSync as Ua,readFileSync as Ya}from"node:fs";import{basename as Xa,join as Nr}from"node:path";import{randomUUID as vr}from"node:crypto";var C=class extends Error{constructor(n,r){super(n);this.statusCode=r}statusCode};function we(t){let e=new Set,n=[];for(let r of t){let s=r.replace(/\s+/gu," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();e.has(o)||(e.add(o),n.push(s))}return n}function Z(t){let e=t.normalize("NFKD").replace(/[\u0300-\u036f]/gu,"").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"").slice(0,120);if(!e)throw new C("Invalid Wiki slug",400);return e}function Sr(t){let e=[];for(let n of t.matchAll(/\[\[([^\[\]]+)\]\]/gu)){let r=n[1]?.trim();r&&e.push(Z(r))}return we(e)}function La(t){return t.normalize("NFKC").toLowerCase().split(/[^\p{L}\p{N}_-]+/u).map(e=>e.trim()).filter(e=>e.length>=2)}function kr(t){return{id:`revision-${vr()}`,pageId:t.id,slug:t.slug,revision:t.revision,title:t.title,...t.summary?{summary:t.summary}:{},content:t.content,tags:[...t.tags],links:[...t.links],createdAt:t.updatedAt}}function Q(t){return structuredClone(t)}var et=class{constructor(e){this.store=e}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(e){let n,r=this.queue.then(async()=>{let s=await this.ensureState();n=e(s),s.updatedAt=new Date().toISOString(),await this.store.save(s)});return this.queue=r.then(()=>{},()=>{}),await r,n}async summary(){let e=await this.ensureState(),n=new Set(e.pages.flatMap(r=>r.links));return{schema:"toolnet.wiki-summary.v1",projectId:e.projectId,pages:e.pages.length,revisions:e.revisions.length,tags:we(e.pages.flatMap(r=>r.tags)).sort((r,s)=>r.localeCompare(s)),links:e.pages.reduce((r,s)=>r+s.links.length,0),orphanPages:e.pages.filter(r=>r.links.length===0&&!n.has(r.slug)).length,automatedPages:e.pages.filter(r=>r.tags.some(s=>s.startsWith("toolnet-auto-"))).length,updatedAt:e.updatedAt}}async listPages(){let e=await this.ensureState();return Q([...e.pages].sort((n,r)=>n.title.localeCompare(r.title)))}async getPage(e){let n=await this.ensureState(),r=Z(e),s=n.pages.find(o=>o.slug===r||o.id===e);if(!s)throw new C(`Wiki page not found: ${e}`,404);return Q(s)}async createPage(e){return this.mutate(n=>{let r=e.title.trim(),s=e.content.trim();if(!r)throw new C("Wiki title is required",400);let o=Z(e.slug??r);if(n.pages.some(c=>c.slug===o))throw new C(`Wiki page already exists: ${o}`,409);let i=new Date().toISOString(),a={id:`wiki-${vr()}`,slug:o,title:r,...e.summary?.trim()?{summary:e.summary.trim()}:{},content:s,tags:we(e.tags??[]),links:Sr(s),revision:1,createdAt:i,updatedAt:i};return n.pages.push(a),n.revisions.push(kr(a)),Q(a)})}async updatePage(e,n){return this.mutate(r=>{let s=Z(e),o=r.pages.find(i=>i.slug===s||i.id===e);if(!o)throw new C(`Wiki page not found: ${e}`,404);if(n.title!==void 0){let i=n.title.trim();if(!i)throw new C("Wiki title is required",400);o.title=i}if(n.summary!==void 0){let i=n.summary.trim();i?o.summary=i:delete o.summary}return n.content!==void 0&&(o.content=n.content.trim(),o.links=Sr(o.content)),n.tags!==void 0&&(o.tags=we(n.tags)),o.revision+=1,o.updatedAt=new Date().toISOString(),r.revisions.push(kr(o)),Q(o)})}async history(e){let n=await this.getPage(e),r=await this.ensureState();return Q(r.revisions.filter(s=>s.pageId===n.id).sort((s,o)=>o.revision-s.revision))}async backlinks(e){let n=await this.getPage(e),r=await this.ensureState();return Q(r.pages.filter(s=>s.links.includes(n.slug)).sort((s,o)=>s.title.localeCompare(o.title)))}async search(e,n=10){let r=await this.ensureState(),s=we(La(e));if(s.length===0)return[];let o=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(),p=a.summary?.toLowerCase()??"",l=a.content.toLowerCase(),f=a.tags.map(g=>g.toLowerCase()),d=0;for(let g of s)u===g&&(d+=12),c===g&&(d+=10),c.includes(g)&&(d+=6),u.includes(g)&&(d+=5),f.some(S=>S===g)?d+=5:f.some(S=>S.includes(g))&&(d+=3),p.includes(g)&&(d+=2),l.includes(g)&&(d+=1);d>0&&i.push({page:Q(a),score:d})}return i.sort((a,c)=>c.score-a.score||c.page.updatedAt.localeCompare(a.page.updatedAt)).slice(0,o)}};var wr="wiki/state.v1.json";function Da(t){let e=new Date().toISOString();return{schema:"toolnet.wiki.v1",version:1,projectId:t.id,pages:[],revisions:[],createdAt:e,updatedAt:e}}function za(t,e){let n=JSON.parse(t);if(n.schema!=="toolnet.wiki.v1"||n.version!==1||n.projectId!==e.id||!Array.isArray(n.pages)||!Array.isArray(n.revisions))throw new Error("Invalid ToolNet Wiki state");return n}var tt=class{constructor(e,n){this.storage=e;this.project=n}storage;project;async load(){let e=await this.storage.getText(wr);if(!e){let n=Da(this.project);return await this.save(n),n}return za(e,this.project)}async save(e){await this.storage.put(wr,JSON.stringify(e,null,2),"application/json")}};import{createHash as qa,randomUUID as br}from"node:crypto";var xr="wiki/governance.v1.json",Ar="toolnet.knowledge-governance.v1",jr=500,be={autoApproveThreshold:.86,criticalApproveThreshold:.94,staleAfterDays:90};function Ba(t,e=0,n=1){return Math.max(e,Math.min(n,t))}function Yt(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/gu," ").trim()}function Cr(t){return qa("sha256").update(t.normalize("NFKC").replace(/\s+/gu," ").trim()).digest("hex")}function Ja(t){let e=[t.title,t.summary??"",t.content.slice(0,2e3),...t.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(e)}function Ha(t){let e=t.sourceType==="skill"?.96:t.sourceType==="memory"?.94:.88,n=t.tags.map(r=>r.toLowerCase());return(n.includes("permanent")||n.includes("task"))&&(e+=.03),t.content.length>=200&&(e+=.02),t.content.length<80&&(e-=.05),t.title.length<4&&(e-=.05),Ba(e)}function Ir(t){let e=new Date().toISOString();return{schema:Ar,version:1,projectId:t,policy:{...be},reviews:[],audit:[],createdAt:e,updatedAt:e}}function Mr(t){let e=t.autoApproveThreshold??be.autoApproveThreshold,n=t.criticalApproveThreshold??be.criticalApproveThreshold,r=t.staleAfterDays??be.staleAfterDays;if(!Number.isFinite(e)||e<.5||e>1)throw new C("Invalid autoApproveThreshold",400);if(!Number.isFinite(n)||n<.5||n>1)throw new C("Invalid criticalApproveThreshold",400);if(!Number.isInteger(r)||r<1||r>3650)throw new C("Invalid staleAfterDays",400);return{autoApproveThreshold:e,criticalApproveThreshold:n,staleAfterDays:r}}var nt=class{constructor(e,n){this.storage=e;this.project=n}storage;project;async load(){let e=await this.storage.getText(xr);if(!e){let n=Ir(this.project.id);return await this.save(n),n}try{let n=JSON.parse(e);if(n.schema!==Ar||n.version!==1||n.projectId!==this.project.id||!Array.isArray(n.reviews)||!Array.isArray(n.audit))throw new Error("invalid");return{...n,policy:Mr(n.policy??be)}}catch{let n=Ir(this.project.id);return await this.save(n),n}}async save(e){await this.storage.put(xr,JSON.stringify(e,null,2),"application/json")}},rt=class{constructor(e){this.store=e}store;state;queue=Promise.resolve();async initialize(){await this.ensureState()}async ensureState(){return this.state||(this.state=await this.store.load()),this.state}audit(e,n,r,s={}){e.audit.push({id:br(),action:n,principal:r,...s.reviewId?{reviewId:s.reviewId}:{},...s.sourceKey?{sourceKey:s.sourceKey}:{},timestamp:new Date().toISOString(),...s.metadata?{metadata:s.metadata}:{}}),e.audit.length>jr&&(e.audit=e.audit.slice(-jr))}async mutate(e){let n,r=this.queue.then(async()=>{let s=await this.ensureState();n=await e(s),s.updatedAt=new Date().toISOString(),await this.store.save(s)});return this.queue=r.then(()=>{},()=>{}),await r,n}async policy(){return{...(await this.ensureState()).policy}}async setPolicy(e,n){return this.mutate(r=>(r.policy=Mr({...r.policy,...e}),this.audit(r,"policy:update",n,{metadata:{...r.policy}}),{...r.policy}))}async summary(){let e=await this.ensureState(),n=r=>e.reviews.filter(s=>s.status===r).length;return{schema:"toolnet.knowledge-governance-summary.v1",projectId:e.projectId,pending:n("pending"),approved:n("approved"),rejected:n("rejected"),superseded:n("superseded"),criticalPending:e.reviews.filter(r=>r.status==="pending"&&r.risk==="critical").length,conflictPending:e.reviews.filter(r=>r.status==="pending"&&r.risk==="conflict").length,auditEvents:e.audit.length,policy:{...e.policy},updatedAt:e.updatedAt}}async listReviews(e){let n=await this.ensureState();return structuredClone(n.reviews.filter(r=>!e||r.status===e).sort((r,s)=>s.updatedAt.localeCompare(r.updatedAt)))}async auditLog(e=100){let n=await this.ensureState(),r=Math.max(1,Math.min(500,Math.floor(e)));return structuredClone(n.audit.slice(-r).reverse())}async assess(e,n){let r=await this.ensureState(),s=Ha(e),o=Yt(e.title),i=n.filter(p=>p.slug!==e.slug&&Yt(p.title)===o&&Cr(p.content)!==Cr(e.content)).map(p=>p.slug),a=Ja(e),c=[];s<r.policy.autoApproveThreshold&&c.push(`confidence:${s.toFixed(2)}`),a&&s<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:s,risk:u,requiresReview:i.length>0||s<r.policy.autoApproveThreshold||a&&s<r.policy.criticalApproveThreshold,reasons:c,conflicts:i}}async gate(e,n){let r=await this.assess(e,n);return this.mutate(s=>{let o=s.reviews.find(c=>c.sourceKey===e.sourceKey&&c.digest===e.digest);if(o?.status==="approved")return{allowed:!0,mode:"review-approved",assessment:r,review:structuredClone(o)};if(o?.status==="rejected")return{allowed:!1,mode:"rejected",assessment:r,review:structuredClone(o)};if(!r.requiresReview)return this.audit(s,"knowledge:auto-approved","system",{sourceKey:e.sourceKey,metadata:{confidence:r.confidence,risk:r.risk}}),{allowed:!0,mode:"auto-approved",assessment:r};if(o?.status==="pending")return{allowed:!1,mode:"pending-review",assessment:r,review:structuredClone(o)};let i=new Date().toISOString(),a={id:br(),sourceKey:e.sourceKey,sourceType:e.sourceType,slug:e.slug,marker:e.marker,digest:e.digest,title:e.title,...e.summary?{summary:e.summary}:{},content:e.content,tags:[...new Set([...e.tags,e.marker])],confidence:r.confidence,risk:r.risk,reasons:[...r.reasons],conflicts:[...r.conflicts],status:"pending",createdAt:i,updatedAt:i};return s.reviews.push(a),this.audit(s,"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(e,n){await this.mutate(r=>{let s=r.reviews.find(o=>o.sourceKey===e&&o.digest===n&&o.status==="approved");s&&(s.appliedAt=new Date().toISOString(),s.updatedAt=s.appliedAt,this.audit(r,"knowledge:applied",s.reviewedBy??"system",{reviewId:s.id,sourceKey:e}))})}async decide(e,n,r){return this.mutate(async s=>{let o=s.reviews.find(u=>u.id===e);if(!o)throw new C(`Governance review not found: ${e}`,404);if(o.status!=="pending")throw new C("Governance review is already resolved",409);let i=new Date().toISOString();if(o.reviewedAt=i,o.reviewedBy=n.principal,o.updatedAt=i,n.note?.trim()&&(o.reviewNote=n.note.trim()),n.action==="reject")return o.status="rejected",this.audit(s,"knowledge:rejected",n.principal,{reviewId:e,sourceKey:o.sourceKey}),structuredClone(o);if(n.action==="supersede")return o.status="superseded",n.targetReviewId&&(o.supersededBy=n.targetReviewId),this.audit(s,"knowledge:superseded",n.principal,{reviewId:e,sourceKey:o.sourceKey,metadata:{targetReviewId:n.targetReviewId}}),structuredClone(o);if(n.action==="merge"){if(!n.targetReviewId)throw new C("targetReviewId is required for merge",400);let u=s.reviews.find(p=>p.id===n.targetReviewId);if(!u)throw new C("Merge target review not found",404);return o.status="superseded",o.mergedInto=u.id,this.audit(s,"knowledge:merged",n.principal,{reviewId:e,sourceKey:o.sourceKey,metadata:{targetReviewId:u.id}}),structuredClone(o)}o.status="approved";let c=(await r.listPages()).find(u=>u.slug===o.slug);if(c&&!c.tags.includes(o.marker))throw new C(`Wiki page '${o.slug}' is manually managed`,409);return c?await r.updatePage(o.slug,{title:o.title,summary:o.summary??"",content:o.content,tags:o.tags}):await r.createPage({slug:o.slug,title:o.title,...o.summary?{summary:o.summary}:{},content:o.content,tags:o.tags}),o.appliedAt=i,this.audit(s,"knowledge:approved",n.principal,{reviewId:e,sourceKey:o.sourceKey}),structuredClone(o)})}async quality(e){let n=await this.ensureState(),r=await e.listPages(),s=Date.now(),o=n.policy.staleAfterDays*864e5,i=r.map(p=>{let l=s-Date.parse(p.updatedAt);return{slug:p.slug,title:p.title,updatedAt:p.updatedAt,ageDays:Math.max(0,Math.floor(l/864e5)),stale:Number.isFinite(l)&&l>o}}).filter(p=>p.stale).map(({stale:p,...l})=>l),a=new Map;for(let p of r){let l=Yt(p.title),f=a.get(l)??[];f.push(p),a.set(l,f)}let c=[...a.entries()].filter(([,p])=>p.length>1).map(([p,l])=>({title:p,pages:l.map(f=>f.slug)})),u=n.reviews.filter(p=>p.status==="pending");return{schema:"toolnet.knowledge-quality.v1",totalPages:r.length,automatedPages:r.filter(p=>p.tags.some(l=>l.startsWith("toolnet-auto-"))).length,manualPages:r.filter(p=>!p.tags.some(l=>l.startsWith("toolnet-auto-"))).length,stalePages:i,duplicateTitles:c,pendingReviews:u.length,lowConfidenceReviews:u.filter(p=>p.confidence<n.policy.autoApproveThreshold).length,conflicts:u.filter(p=>p.risk==="conflict").length,generatedAt:new Date().toISOString()}}};var _r="wiki/automation.v1.json",$r="toolnet.wiki-automation.v1",Zt=8e3,Pr=new Set(["raw","rawtext","raw_text","rawtranscript","raw_transcript","transcript","messages","message","payload","prompt","response","assistantmessage","assistant_message","userprompt","user_prompt"]);function je(t){return Va("sha256").update(JSON.stringify(t)).digest("hex")}function xe(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Er(t){return Array.isArray(t)?t:[]}function Kr(t){return typeof t!="string"?void 0:t.replace(/\s+/gu," ").trim()||void 0}function Xt(t){return Array.isArray(t)?t.map(Kr).filter(e=>!!e):[]}function $(t,e){for(let n of e){let r=Kr(t[n]);if(r)return r}}function Ce(t){let e=new Set,n=[];for(let r of t){let s=r.replace(/\s+/gu," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();e.has(o)||(e.add(o),n.push(s))}return n}function st(t,e=0,n=""){if(e>3)return[];let r=n.replace(/[^a-z0-9]/giu,"").toLowerCase();if(Pr.has(r))return[];if(typeof t=="string"){let i=t.replace(/\s+/gu," ").trim();return i.length<8?[]:[i]}if(Array.isArray(t))return t.flatMap(i=>st(i,e+1,n));let s=xe(t);if(!s)return[];let o=[];for(let[i,a]of Object.entries(s)){let c=i.replace(/[^a-z0-9]/giu,"").toLowerCase();Pr.has(c)||o.push(...st(a,e+1,i))}return o}function Or(t){let n=Ce(["content","summary","text","value","statement","description","decision","task","knowledge","context","outcome","reason","rationale"].flatMap(s=>st(t[s],0,s)));return(n.length>0?n:Ce(st(t))).join(`
27
+ `).filter(d=>d.trim())).map(d=>typeof d=="string"?d:JSON.stringify(d)).filter(d=>d.trim()),o=Da(r,e),s=o.filter(d=>d.category==="decision").map(d=>d.text),i=o.filter(d=>d.category==="rule").map(d=>d.text),a=o.filter(d=>d.category==="file").map(d=>d.text),c=o.filter(d=>d.category==="fix").map(d=>d.text),u=o.filter(d=>d.category==="blocker").map(d=>d.text),f=o.filter(d=>d.category==="next_action").map(d=>d.text),l=o.filter(d=>d.category==="deploy").map(d=>d.text);return{summary:za(r),decisions:s,projectRules:i,filesChanged:a,bugsFixed:c,commands:l,blockers:u,nextActions:f,durableFacts:o}}function J(t){let e=new Set,n=[];for(let r of t){let o=r?.replace(/\s+/g," ").trim();if(!o)continue;let s=o.normalize("NFKC").toLowerCase();e.has(s)||(e.add(s),n.push(o))}return n}function qa(t){let e=new Map;for(let n of t){if(!n||!n.id||!Number.isFinite(n.sequence))continue;let r=n.sourceEventId?`${n.agent}:${n.sourceEventId}`:n.id,o=e.get(r);(!o||n.sequence>o.sequence)&&e.set(r,n)}return[...e.values()].sort((n,r)=>n.sequence-r.sequence||n.timestamp.localeCompare(r.timestamp))}function Va(t){let e=t.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_./:-]+/gu)??[],n=new Set;for(let r of e)if(!(r.length<2||/^\d+$/u.test(r))&&(n.add(r),n.size>=40))break;return[...n]}function Ha(t){let e=Zt(t);return{...t,knowledgeClass:e.knowledgeClass,importanceScore:e.score,retrievalTerms:Va(t.content),tags:J([...t.tags,"level:fact",`class:${e.knowledgeClass}`,`kind:${t.kind}`])}}function Ba(t){return t.map(e=>{try{return JSON.stringify({type:e.type,role:e.role,data:e.data,provenance:{sourcePath:e.provenance.sourcePath,files:e.provenance.files}})}catch{return""}}).filter(Boolean)}function Ja(t,e,n){let r=st(Ba(e),t.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=J([...o,...r.nextActions]),c=J([...r.nextActions,...o]);return{summary:r.summary,state:{task:c[0]??a[0],decisions:J(r.decisions),files:J([...r.filesChanged,...s]),todos:a,completed:J(r.bugsFixed),blockers:J(r.blockers),nextActions:c,architecture:J(i)}}}function it(t,e){let n=qa(e),r=hr(t,n).map(Ha),o=r.filter(f=>Zt(f).persist).sort((f,l)=>l.importanceScore-f.importanceScore),{summary:s,state:i}=Ja(t,n,o),a=o.map(f=>({fingerprint:f.fingerprint,kind:f.kind,knowledgeClass:f.knowledgeClass,importanceScore:f.importanceScore,content:f.content,terms:f.retrievalTerms})),c=vr(n,o),u=f=>r.filter(l=>l.knowledgeClass===f).length;return{version:2,normalizedEvents:n,summary:s,state:i,candidates:o,retrievalIndex:a,hierarchy:c,stats:{inputEvents:e.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 Ga}from"node:crypto";import{chmodSync as Ar,existsSync as Ua,mkdirSync as Ya,readFileSync as Xa,renameSync as Qa,writeFileSync as Mr}from"node:fs";import{dirname as Pr,join as at}from"node:path";var on="toolnet.context-offload.v1",Za="toolnet.context-offload-asset.v1",ec=256,tc=new Set(["tool_call","tool_result","file_read","file_write","file_edit","command","test","artifact"]);function Er(t){return at(t,".toolnet","offload")}function nc(t){return at(Er(t),"assets")}function Or(t){return at(Er(t),"graph.json")}function Tr(t){Ya(t,{recursive:!0,mode:448});try{Ar(t,448)}catch{}}function rc(t,e){Tr(Pr(t));let n=`${t}.${process.pid}.${Date.now()}.tmp`;Mr(n,e,{encoding:"utf8",mode:384}),Qa(n,t);try{Ar(t,384)}catch{}}function rn(t){return Array.isArray(t)?t.map(rn):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,rn(n)])):t}function oc(t){return Ga("sha256").update(JSON.stringify(rn(t)),"utf8").digest("hex")}function nn(){return{schema:on,version:1,updatedAt:new Date(0).toISOString(),nodes:[]}}function sc(t){let e=Or(t);if(!Ua(e))return nn();try{let n=JSON.parse(Xa(e,"utf8"));return n.schema!==on||n.version!==1||!Array.isArray(n.nodes)?nn():n}catch{return nn()}}function ic(t,e){rc(Or(t),JSON.stringify(e,null,2)+`
28
+ `)}function ac(t,e=260){if(typeof t!="string")return null;let n=t.replace(/\s+/gu," ").trim();return n?n.slice(0,e):null}function cc(t){let e=[...t.provenance.files??[],t.provenance.sourcePath],n=[];for(let r of e){let o=ac(r);if(!(!o||n.includes(o))&&(n.push(o),n.length===3))break}return n}function uc(t){return`${t.agent}:${t.sourceEventId??t.id}`.replace(/\s+/gu," ").trim().slice(0,120)}function lc(t,e){Tr(Pr(t));try{return Mr(t,e,{encoding:"utf8",flag:"wx",mode:384}),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function dc(t,e){let n=t.nodes.find(o=>o.id===e.id),r=n?{...n,kind:e.kind,bytes:e.bytes,sourceRefs:Array.from(new Set([...n.sourceRefs,...e.sourceRefs])).slice(-8),files:Array.from(new Set([...n.files,...e.files])).slice(0,6)}:e;return{schema:on,version:1,updatedAt:new Date().toISOString(),nodes:[...t.nodes.filter(o=>o.id!==e.id),r].slice(-ec)}}function Rr(t,e){let n=sc(t),r=0,o=0,s=0,i=[];for(let a of e){if(!tc.has(a.type))continue;r+=1;let c=oc({type:a.type,data:a.data}),u={schema:Za,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}},f=JSON.stringify(u,null,2)+`
29
+ `;lc(at(nc(t),`${c}.json`),f)?o+=1:s+=1,i.push(c),n=dc(n,{id:c,kind:a.type,bytes:Buffer.byteLength(f,"utf8"),createdAt:a.timestamp,sourceRefs:[uc(a)],files:cc(a)})}return r>0&&ic(t,n),{eligible:r,written:o,deduped:s,graphNodes:n.nodes.length,assetIds:i}}import{createHash as kc}from"node:crypto";import{existsSync as vc,readdirSync as wc,readFileSync as bc}from"node:fs";import{basename as xc,join as Yr}from"node:path";import{randomUUID as Kr}from"node:crypto";var C=class extends Error{constructor(n,r){super(n);this.statusCode=r}statusCode};function Ce(t){let e=new Set,n=[];for(let r of t){let o=r.replace(/\s+/gu," ").trim();if(!o)continue;let s=o.normalize("NFKC").toLowerCase();e.has(s)||(e.add(s),n.push(o))}return n}function ne(t){let e=t.normalize("NFKD").replace(/[\u0300-\u036f]/gu,"").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"").slice(0,120);if(!e)throw new C("Invalid Wiki slug",400);return e}function Nr(t){let e=[];for(let n of t.matchAll(/\[\[([^\[\]]+)\]\]/gu)){let r=n[1]?.trim();r&&e.push(ne(r))}return Ce(e)}function pc(t){return t.normalize("NFKC").toLowerCase().split(/[^\p{L}\p{N}_-]+/u).map(e=>e.trim()).filter(e=>e.length>=2)}function _r(t){return{id:`revision-${Kr()}`,pageId:t.id,slug:t.slug,revision:t.revision,title:t.title,...t.summary?{summary:t.summary}:{},content:t.content,tags:[...t.tags],links:[...t.links],createdAt:t.updatedAt}}function te(t){return structuredClone(t)}var ct=class{constructor(e){this.store=e}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(e){let n,r=this.queue.then(async()=>{let o=await this.ensureState();n=e(o),o.updatedAt=new Date().toISOString(),await this.store.save(o)});return this.queue=r.then(()=>{},()=>{}),await r,n}async summary(){let e=await this.ensureState(),n=new Set(e.pages.flatMap(r=>r.links));return{schema:"toolnet.wiki-summary.v1",projectId:e.projectId,pages:e.pages.length,revisions:e.revisions.length,tags:Ce(e.pages.flatMap(r=>r.tags)).sort((r,o)=>r.localeCompare(o)),links:e.pages.reduce((r,o)=>r+o.links.length,0),orphanPages:e.pages.filter(r=>r.links.length===0&&!n.has(r.slug)).length,automatedPages:e.pages.filter(r=>r.tags.some(o=>o.startsWith("toolnet-auto-"))).length,updatedAt:e.updatedAt}}async listPages(){let e=await this.ensureState();return te([...e.pages].sort((n,r)=>n.title.localeCompare(r.title)))}async getPage(e){let n=await this.ensureState(),r=ne(e),o=n.pages.find(s=>s.slug===r||s.id===e);if(!o)throw new C(`Wiki page not found: ${e}`,404);return te(o)}async createPage(e){return this.mutate(n=>{let r=e.title.trim(),o=e.content.trim();if(!r)throw new C("Wiki title is required",400);let s=ne(e.slug??r);if(n.pages.some(c=>c.slug===s))throw new C(`Wiki page already exists: ${s}`,409);let i=new Date().toISOString(),a={id:`wiki-${Kr()}`,slug:s,title:r,...e.summary?.trim()?{summary:e.summary.trim()}:{},content:o,tags:Ce(e.tags??[]),links:Nr(o),revision:1,createdAt:i,updatedAt:i};return n.pages.push(a),n.revisions.push(_r(a)),te(a)})}async updatePage(e,n){return this.mutate(r=>{let o=ne(e),s=r.pages.find(i=>i.slug===o||i.id===e);if(!s)throw new C(`Wiki page not found: ${e}`,404);if(n.title!==void 0){let i=n.title.trim();if(!i)throw new C("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=Nr(s.content)),n.tags!==void 0&&(s.tags=Ce(n.tags)),s.revision+=1,s.updatedAt=new Date().toISOString(),r.revisions.push(_r(s)),te(s)})}async history(e){let n=await this.getPage(e),r=await this.ensureState();return te(r.revisions.filter(o=>o.pageId===n.id).sort((o,s)=>s.revision-o.revision))}async backlinks(e){let n=await this.getPage(e),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(e,n=10){let r=await this.ensureState(),o=Ce(pc(e));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(),f=a.summary?.toLowerCase()??"",l=a.content.toLowerCase(),p=a.tags.map(m=>m.toLowerCase()),d=0;for(let m of o)u===m&&(d+=12),c===m&&(d+=10),c.includes(m)&&(d+=6),u.includes(m)&&(d+=5),p.some(S=>S===m)?d+=5:p.some(S=>S.includes(m))&&(d+=3),f.includes(m)&&(d+=2),l.includes(m)&&(d+=1);d>0&&i.push({page:te(a),score:d})}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 fc(t){let e=new Date().toISOString();return{schema:"toolnet.wiki.v1",version:1,projectId:t.id,pages:[],revisions:[],createdAt:e,updatedAt:e}}function mc(t,e){let n=JSON.parse(t);if(n.schema!=="toolnet.wiki.v1"||n.version!==1||n.projectId!==e.id||!Array.isArray(n.pages)||!Array.isArray(n.revisions))throw new Error("Invalid ToolNet Wiki state");return n}var ut=class{constructor(e,n){this.storage=e;this.project=n}storage;project;async load(){let e=await this.storage.getText($r);if(!e){let n=fc(this.project);return await this.save(n),n}return mc(e,this.project)}async save(e){await this.storage.put($r,JSON.stringify(e,null,2),"application/json")}};import{createHash as gc,randomUUID as Lr}from"node:crypto";var Fr="wiki/governance.v1.json",qr="toolnet.knowledge-governance.v1",Wr=500,Ae={autoApproveThreshold:.86,criticalApproveThreshold:.94,staleAfterDays:90};function yc(t,e=0,n=1){return Math.max(e,Math.min(n,t))}function sn(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/gu," ").trim()}function Dr(t){return gc("sha256").update(t.normalize("NFKC").replace(/\s+/gu," ").trim()).digest("hex")}function hc(t){let e=[t.title,t.summary??"",t.content.slice(0,2e3),...t.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(e)}function Sc(t){let e=t.sourceType==="skill"?.96:t.sourceType==="memory"?.94:.88,n=t.tags.map(r=>r.toLowerCase());return(n.includes("permanent")||n.includes("task"))&&(e+=.03),t.content.length>=200&&(e+=.02),t.content.length<80&&(e-=.05),t.title.length<4&&(e-=.05),yc(e)}function zr(t){let e=new Date().toISOString();return{schema:qr,version:1,projectId:t,policy:{...Ae},reviews:[],audit:[],createdAt:e,updatedAt:e}}function Vr(t){let e=t.autoApproveThreshold??Ae.autoApproveThreshold,n=t.criticalApproveThreshold??Ae.criticalApproveThreshold,r=t.staleAfterDays??Ae.staleAfterDays;if(!Number.isFinite(e)||e<.5||e>1)throw new C("Invalid autoApproveThreshold",400);if(!Number.isFinite(n)||n<.5||n>1)throw new C("Invalid criticalApproveThreshold",400);if(!Number.isInteger(r)||r<1||r>3650)throw new C("Invalid staleAfterDays",400);return{autoApproveThreshold:e,criticalApproveThreshold:n,staleAfterDays:r}}var lt=class{constructor(e,n){this.storage=e;this.project=n}storage;project;async load(){let e=await this.storage.getText(Fr);if(!e){let n=zr(this.project.id);return await this.save(n),n}try{let n=JSON.parse(e);if(n.schema!==qr||n.version!==1||n.projectId!==this.project.id||!Array.isArray(n.reviews)||!Array.isArray(n.audit))throw new Error("invalid");return{...n,policy:Vr(n.policy??Ae)}}catch{let n=zr(this.project.id);return await this.save(n),n}}async save(e){await this.storage.put(Fr,JSON.stringify(e,null,2),"application/json")}},dt=class{constructor(e){this.store=e}store;state;queue=Promise.resolve();async initialize(){await this.ensureState()}async ensureState(){return this.state||(this.state=await this.store.load()),this.state}audit(e,n,r,o={}){e.audit.push({id:Lr(),action:n,principal:r,...o.reviewId?{reviewId:o.reviewId}:{},...o.sourceKey?{sourceKey:o.sourceKey}:{},timestamp:new Date().toISOString(),...o.metadata?{metadata:o.metadata}:{}}),e.audit.length>Wr&&(e.audit=e.audit.slice(-Wr))}async mutate(e){let n,r=this.queue.then(async()=>{let o=await this.ensureState();n=await e(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(e,n){return this.mutate(r=>(r.policy=Vr({...r.policy,...e}),this.audit(r,"policy:update",n,{metadata:{...r.policy}}),{...r.policy}))}async summary(){let e=await this.ensureState(),n=r=>e.reviews.filter(o=>o.status===r).length;return{schema:"toolnet.knowledge-governance-summary.v1",projectId:e.projectId,pending:n("pending"),approved:n("approved"),rejected:n("rejected"),superseded:n("superseded"),criticalPending:e.reviews.filter(r=>r.status==="pending"&&r.risk==="critical").length,conflictPending:e.reviews.filter(r=>r.status==="pending"&&r.risk==="conflict").length,auditEvents:e.audit.length,policy:{...e.policy},updatedAt:e.updatedAt}}async listReviews(e){let n=await this.ensureState();return structuredClone(n.reviews.filter(r=>!e||r.status===e).sort((r,o)=>o.updatedAt.localeCompare(r.updatedAt)))}async auditLog(e=100){let n=await this.ensureState(),r=Math.max(1,Math.min(500,Math.floor(e)));return structuredClone(n.audit.slice(-r).reverse())}async assess(e,n){let r=await this.ensureState(),o=Sc(e),s=sn(e.title),i=n.filter(f=>f.slug!==e.slug&&sn(f.title)===s&&Dr(f.content)!==Dr(e.content)).map(f=>f.slug),a=hc(e),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(e,n){let r=await this.assess(e,n);return this.mutate(o=>{let s=o.reviews.find(c=>c.sourceKey===e.sourceKey&&c.digest===e.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:e.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:Lr(),sourceKey:e.sourceKey,sourceType:e.sourceType,slug:e.slug,marker:e.marker,digest:e.digest,title:e.title,...e.summary?{summary:e.summary}:{},content:e.content,tags:[...new Set([...e.tags,e.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(e,n){await this.mutate(r=>{let o=r.reviews.find(s=>s.sourceKey===e&&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:e}))})}async decide(e,n,r){return this.mutate(async o=>{let s=o.reviews.find(u=>u.id===e);if(!s)throw new C(`Governance review not found: ${e}`,404);if(s.status!=="pending")throw new C("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:e,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:e,sourceKey:s.sourceKey,metadata:{targetReviewId:n.targetReviewId}}),structuredClone(s);if(n.action==="merge"){if(!n.targetReviewId)throw new C("targetReviewId is required for merge",400);let u=o.reviews.find(f=>f.id===n.targetReviewId);if(!u)throw new C("Merge target review not found",404);return s.status="superseded",s.mergedInto=u.id,this.audit(o,"knowledge:merged",n.principal,{reviewId:e,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 C(`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:e,sourceKey:s.sourceKey}),structuredClone(s)})}async quality(e){let n=await this.ensureState(),r=await e.listPages(),o=Date.now(),s=n.policy.staleAfterDays*864e5,i=r.map(f=>{let l=o-Date.parse(f.updatedAt);return{slug:f.slug,title:f.title,updatedAt:f.updatedAt,ageDays:Math.max(0,Math.floor(l/864e5)),stale:Number.isFinite(l)&&l>s}}).filter(f=>f.stale).map(({stale:f,...l})=>l),a=new Map;for(let f of r){let l=sn(f.title),p=a.get(l)??[];p.push(f),a.set(l,p)}let c=[...a.entries()].filter(([,f])=>f.length>1).map(([f,l])=>({title:f,pages:l.map(p=>p.slug)})),u=n.reviews.filter(f=>f.status==="pending");return{schema:"toolnet.knowledge-quality.v1",totalPages:r.length,automatedPages:r.filter(f=>f.tags.some(l=>l.startsWith("toolnet-auto-"))).length,manualPages:r.filter(f=>!f.tags.some(l=>l.startsWith("toolnet-auto-"))).length,stalePages:i,duplicateTitles:c,pendingReviews:u.length,lowConfidenceReviews:u.filter(f=>f.confidence<n.policy.autoApproveThreshold).length,conflicts:u.filter(f=>f.risk==="conflict").length,generatedAt:new Date().toISOString()}}};var Xr="wiki/automation.v1.json",Qr="toolnet.wiki-automation.v1",un=8e3,Hr=new Set(["raw","rawtext","raw_text","rawtranscript","raw_transcript","transcript","messages","message","payload","prompt","response","assistantmessage","assistant_message","userprompt","user_prompt"]);function Pe(t){return kc("sha256").update(JSON.stringify(t)).digest("hex")}function Me(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Br(t){return Array.isArray(t)?t:[]}function Zr(t){return typeof t!="string"?void 0:t.replace(/\s+/gu," ").trim()||void 0}function an(t){return Array.isArray(t)?t.map(Zr).filter(e=>!!e):[]}function $(t,e){for(let n of e){let r=Zr(t[n]);if(r)return r}}function Ee(t){let e=new Set,n=[];for(let r of t){let o=r.replace(/\s+/gu," ").trim();if(!o)continue;let s=o.normalize("NFKC").toLowerCase();e.has(s)||(e.add(s),n.push(o))}return n}function pt(t,e=0,n=""){if(e>3)return[];let r=n.replace(/[^a-z0-9]/giu,"").toLowerCase();if(Hr.has(r))return[];if(typeof t=="string"){let i=t.replace(/\s+/gu," ").trim();return i.length<8?[]:[i]}if(Array.isArray(t))return t.flatMap(i=>pt(i,e+1,n));let o=Me(t);if(!o)return[];let s=[];for(let[i,a]of Object.entries(o)){let c=i.replace(/[^a-z0-9]/giu,"").toLowerCase();Hr.has(c)||s.push(...pt(a,e+1,i))}return s}function Jr(t){let n=Ee(["content","summary","text","value","statement","description","decision","task","knowledge","context","outcome","reason","rationale"].flatMap(o=>pt(t[o],0,o)));return(n.length>0?n:Ee(pt(t))).join(`
30
30
 
31
- `).slice(0,Zt)}function Tr(t,e){return $(t,["id","key","fingerprint","knowledgeId","sceneId"])??e}function Rr(t,e){return $(t,["title","name","topic","label","task","kind","type"])??e}function Qa(t){return($(t,["knowledgeClass","class","classification","scope"])??"").toLowerCase()}function Za(t){return($(t,["kind","sceneKind","type"])??"").toLowerCase()}function ec(t){let e=xe(t);if(!e)return[];let n=[],r=Er(e.knowledge);for(let[o,i]of r.entries()){let a=xe(i);if(!a)continue;let c=Qa(a);if(c==="session"||c==="transient")continue;let u=Or(a);if(u.length<20)continue;let p=Tr(a,je(a).slice(0,16)),l=Rr(a,`Durable Memory ${o+1}`);n.push({sourceKey:`memory:${p}`,sourceType:"memory",title:l,summary:$(a,["summary","description"]),content:u,tags:Ce(["toolnet","auto","memory",...c?[c]:[]])})}let s=Er(e.scenes);for(let[o,i]of s.entries()){let a=xe(i);if(!a)continue;let c=Za(a);if(c==="session-context")continue;let u=Or(a);if(u.length<20)continue;let p=Tr(a,je(a).slice(0,16)),l=Rr(a,`Knowledge Scene ${o+1}`);n.push({sourceKey:`scene:${p}`,sourceType:"scene",title:l,summary:$(a,["summary","description"]),content:u,tags:Ce(["toolnet","auto","scene",...c?[c]:[]])})}return n}function tc(t){return Nr(t,".toolnet","memory","skills")}function nc(t){let e=tc(t);if(!Ga(e))return{candidates:[],failed:0};let n=[],r=0,s=Ua(e).filter(o=>o.endsWith(".json")).sort();for(let o of s)try{let i=JSON.parse(Ya(Nr(e,o),"utf8")),a=xe(i);if(!a||a.schema!=="toolnet.skill-memory.v1")continue;let c=$(a,["id","fingerprint"])??Xa(o,".json"),u=$(a,["task"])??"",p=$(a,["title"])||u||`Reusable Skill ${c.slice(0,8)}`,l=$(a,["summary"])??void 0,f=Xt(a.steps),d=Xt(a.verification),g=Xt(a.files),S=[];u&&S.push(`## Task
31
+ `).slice(0,un)}function Gr(t,e){return $(t,["id","key","fingerprint","knowledgeId","sceneId"])??e}function Ur(t,e){return $(t,["title","name","topic","label","task","kind","type"])??e}function jc(t){return($(t,["knowledgeClass","class","classification","scope"])??"").toLowerCase()}function Ic(t){return($(t,["kind","sceneKind","type"])??"").toLowerCase()}function Cc(t){let e=Me(t);if(!e)return[];let n=[],r=Br(e.knowledge);for(let[s,i]of r.entries()){let a=Me(i);if(!a)continue;let c=jc(a);if(c==="session"||c==="transient")continue;let u=Jr(a);if(u.length<20)continue;let f=Gr(a,Pe(a).slice(0,16)),l=Ur(a,`Durable Memory ${s+1}`);n.push({sourceKey:`memory:${f}`,sourceType:"memory",title:l,summary:$(a,["summary","description"]),content:u,tags:Ee(["toolnet","auto","memory",...c?[c]:[]])})}let o=Br(e.scenes);for(let[s,i]of o.entries()){let a=Me(i);if(!a)continue;let c=Ic(a);if(c==="session-context")continue;let u=Jr(a);if(u.length<20)continue;let f=Gr(a,Pe(a).slice(0,16)),l=Ur(a,`Knowledge Scene ${s+1}`);n.push({sourceKey:`scene:${f}`,sourceType:"scene",title:l,summary:$(a,["summary","description"]),content:u,tags:Ee(["toolnet","auto","scene",...c?[c]:[]])})}return n}function Ac(t){return Yr(t,".toolnet","memory","skills")}function Mc(t){let e=Ac(t);if(!vc(e))return{candidates:[],failed:0};let n=[],r=0,o=wc(e).filter(s=>s.endsWith(".json")).sort();for(let s of o)try{let i=JSON.parse(bc(Yr(e,s),"utf8")),a=Me(i);if(!a||a.schema!=="toolnet.skill-memory.v1")continue;let c=$(a,["id","fingerprint"])??xc(s,".json"),u=$(a,["task"])??"",f=$(a,["title"])||u||`Reusable Skill ${c.slice(0,8)}`,l=$(a,["summary"])??void 0,p=an(a.steps),d=an(a.verification),m=an(a.files),S=[];u&&S.push(`## Task
32
32
  ${u}`),l&&S.push(`## Summary
33
- ${l}`),f.length>0&&S.push(`## Procedure
34
- ${f.map((h,k)=>`${k+1}. ${h}`).join(`
33
+ ${l}`),p.length>0&&S.push(`## Procedure
34
+ ${p.map((y,v)=>`${v+1}. ${y}`).join(`
35
35
  `)}`),d.length>0&&S.push(`## Verification
36
- ${d.map(h=>`- ${h}`).join(`
37
- `)}`),g.length>0&&S.push(`## Relevant Files
38
- ${g.map(h=>`- \`${h}\``).join(`
39
- `)}`);let y=S.join(`
40
-
41
- `).slice(0,Zt);if(y.length<20)continue;n.push({sourceKey:`skill:${c}`,sourceType:"skill",title:p,summary:l,content:y,tags:["toolnet","auto","skill","sop"]})}catch{r+=1}return{candidates:n,failed:r}}function Qt(t){let e=new Date().toISOString();return{schema:$r,version:1,projectId:t,entries:[],createdAt:e,updatedAt:e}}async function rc(t,e){let n=await t.getText(_r);if(!n)return Qt(e);try{let r=JSON.parse(n);return r.schema!==$r||r.version!==1||r.projectId!==e||!Array.isArray(r.entries)?Qt(e):r}catch{return Qt(e)}}async function sc(t,e){await t.put(_r,JSON.stringify(e,null,2),"application/json")}function oc(t){return`toolnet-auto-${je(t).slice(0,12)}`}function ic(t){let e=Z(t.title).slice(0,72),n=je(t.sourceKey).slice(0,10);return Z(`auto-${t.sourceType}-${e}-${n}`)}function ac(t){return[`> Auto-generated by ToolNet Knowledge Automation from ${t.sourceType==="skill"?"reusable Skill Memory":t.sourceType==="scene"?"semantic memory scene":"durable memory"}.`,"",t.content].join(`
42
- `).slice(0,Zt)}function cc(t){return je({sourceType:t.sourceType,title:t.title,summary:t.summary,content:t.content,tags:t.tags})}function uc(t,e){return t.tags.includes(e)}async function Fr(t){let e=ec(t.hierarchy),n=nc(t.project.rootPath),r=new Map;for(let d of[...e,...n.candidates])r.set(d.sourceKey,d);let s=[...r.values()].sort((d,g)=>d.sourceKey.localeCompare(g.sourceKey)),o={schema:"toolnet.wiki-automation-result.v1",scanned:e.length+n.candidates.length,eligible:s.length,created:0,updated:0,unchanged:0,skipped:0,failed:n.failed,reviewPending:0,autoApproved:0,reviewApproved:0,pages:[]},i=new et(new tt(t.storage,t.project));await i.initialize();let a=new rt(new nt(t.storage,t.project));await a.initialize();let c=await rc(t.storage,t.project.id),u=await i.listPages(),p=new Map(u.map(d=>[d.slug,d])),l=new Map(c.entries.map(d=>[d.sourceKey,d]));for(let d of s)try{let g=oc(d.sourceKey),S=cc(d),y=l.get(d.sourceKey),h=y?.slug??ic(d),k=p.get(h);if(k&&!uc(k,g)){o.skipped+=1;continue}let P=Ce([...d.tags,g]),E=ac(d),M=await a.gate({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:h,marker:g,digest:S,title:d.title,...d.summary?{summary:d.summary}:{},content:E,tags:P},[...p.values()]);if(!M.allowed){M.mode==="pending-review"?o.reviewPending+=1:o.skipped+=1;continue}M.mode==="auto-approved"?o.autoApproved+=1:M.mode==="review-approved"&&(o.reviewApproved+=1),k?y?.digest!==S?(k=await i.updatePage(h,{title:d.title,summary:d.summary??"",content:E,tags:P}),p.set(k.slug,k),o.updated+=1,o.pages.push({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:k.slug,action:"updated"})):(o.unchanged+=1,o.pages.push({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:h,action:"unchanged"})):(k=await i.createPage({slug:h,title:d.title,summary:d.summary,content:E,tags:P}),p.set(k.slug,k),o.created+=1,o.pages.push({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:k.slug,action:"created"}));let O=new Date().toISOString(),x={sourceKey:d.sourceKey,sourceType:d.sourceType,slug:h,digest:S,marker:g,updatedAt:O},w=c.entries.findIndex(L=>L.sourceKey===d.sourceKey);w>=0?c.entries[w]=x:c.entries.push(x),l.set(d.sourceKey,x),await a.markApplied(d.sourceKey,S)}catch(g){if(g instanceof C&&g.statusCode===409){o.skipped+=1;continue}o.failed+=1}let f=new Date().toISOString();return c.updatedAt=f,c.lastRunAt=f,c.entries.sort((d,g)=>d.sourceKey.localeCompare(g.sourceKey)),await sc(t.storage,c),o}import{createHash as lc}from"node:crypto";import{chmodSync as Lr,existsSync as dc,mkdirSync as pc,readFileSync as Bm,readdirSync as Jm,renameSync as fc,statSync as Hm,writeFileSync as mc}from"node:fs";import{join as Dr}from"node:path";var gc="toolnet.skill-memory.v1",Wr=5,yc=16,hc=24,Sc=32;function kc(t){return lc("sha256").update(t).digest("hex")}function Ae(t,e=Number.MAX_SAFE_INTEGER){let n=new Set,r=[];for(let s of t){let o=s.replace(/\s+/gu," ").trim();if(!o)continue;let i=o.normalize("NFKC").toLowerCase();if(!n.has(i)&&(n.add(i),r.push(o),r.length>=e))break}return r}function en(t,e=360){let n=t.replace(/\s+/gu," ").trim();return n.length<=e?n:n.slice(0,Math.max(0,e-1)).trimEnd()+"\u2026"}function vc(t){return t.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(t,e=360){return t&&en(vc(t),e)||void 0}function Me(t,e){for(let n of e){let r=t[n];if(typeof r=="string"&&r.trim())return r}}function zr(t,e){for(let n of e){let r=t[n];if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()&&Number.isFinite(Number(r)))return Number(r)}}function qr(t,e){for(let n of e){let r=t[n];if(typeof r=="boolean")return r;if(typeof r=="string"){let s=r.trim().toLowerCase();if(["true","yes","pass","passed","success","succeeded","ok"].includes(s))return!0;if(["false","no","fail","failed","error"].includes(s))return!1}}}function Br(t){let e=t.data??{};if(qr(e,["passed","pass","success","succeeded","ok"])===!1)return!0;let r=zr(e,["exitCode","exit_code","code","statusCode"]);if(r!==void 0&&r!==0)return!0;let s=Me(e,["status","result","outcome"]);return!!(s&&/\b(fail(?:ed)?|error|broken|cancelled)\b/iu.test(s))}function Ie(t){let e=t.data??{};if(Br(t))return!1;if(qr(e,["passed","pass","success","succeeded","ok"])===!0||zr(e,["exitCode","exit_code","code","statusCode"])===0)return!0;let s=Me(e,["status","result","outcome"]);return s&&/\b(pass(?:ed)?|success(?:ful)?|succeeded|ok|green|complete(?:d)?)\b/iu.test(s)?!0:t.type==="commit"||t.type==="deploy"}function Jr(t){let e=t.data??{},n=Me(e,["path","file","filePath","filename","target"]);if(n)return z(n,260);let r=t.provenance?.files;return z(r?.[0],260)}function tn(t){return z(Me(t.data??{},["command","cmd","script"]),420)}function ie(t){return z(Me(t.data??{},["name","test","suite","title","message","text","result","status"]),300)}function wc(t){let e=[];for(let n of[...t].sort((r,s)=>r.sequence-s.sequence))if(Ie(n)){if(n.type==="test"){let r=ie(n)??tn(n)??"Tests passed";e.push(`Test passed: ${r}`);continue}if(n.type==="commit"){let r=ie(n);e.push(r?`Commit: ${r}`:"Commit completed");continue}if(n.type==="deploy"){let r=ie(n);e.push(r?`Deploy: ${r}`:"Deployment completed")}}return Ae(e,10)}function bc(t,e){let n=[];for(let r of[...t].sort((s,o)=>s.sequence-o.sequence))switch(r.type){case"file_write":case"file_edit":{let s=Jr(r);s&&n.push(`Update ${s}`);break}case"command":{if(Br(r))break;let s=tn(r);s&&n.push(`Run: ${s}`);break}case"test":{if(!Ie(r))break;let s=ie(r)??tn(r)??"project tests";n.push(`Verify: ${s}`);break}case"commit":{if(!Ie(r))break;let s=ie(r);n.push(s?`Commit: ${s}`:"Commit verified changes");break}case"deploy":{if(!Ie(r))break;let s=ie(r);n.push(s?`Deploy: ${s}`:"Deploy verified build");break}default:break}if(n.length===0)for(let r of e.files.slice(0,8)){let s=z(r,260);s&&n.push(`Update ${s}`)}return Ae(n,yc)}function xc(t,e){let n=[...e.files];for(let r of t){let s=Jr(r);s&&n.push(s);for(let o of r.provenance?.files??[]){let i=z(o,260);i&&n.push(i)}}return Ae(n,hc)}function jc(t){return Ae(t.filter(e=>["file_write","file_edit","command","test","commit","deploy"].includes(e.type)).map(e=>e.id),Sc)}function Cc(t){return t.map(n=>n.timestamp).filter(Boolean).sort().at(-1)??new Date(0).toISOString()}function Hr(t,e,n){if(e.length===0)return[];let r=wc(e),s=Ae(n.completed.map(g=>z(g,280)??""),Wr);if(!(s.length>0||e.some(g=>["test","commit","deploy"].includes(g.type)&&Ie(g))))return[];let i=z(n.task,280)??z(n.nextActions[0],280),a=s.length>0?s:i?[i]:[];if(a.length===0)return[];let c=bc(e,n);if(c.length===0)return[];let u=xc(e,n),p=jc(e),l=Math.min(...e.map(g=>g.sequence)),f=Math.max(...e.map(g=>g.sequence)),d=Cc(e);return a.slice(0,Wr).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:t.projectId,task:g,steps:c,verification:r,files:u}),h=kc(y);return{schema:gc,version:1,id:`skill-${h.slice(0,24)}`,fingerprint:h,projectId:t.projectId,title:en(`SOP: ${g}`,180),task:g,summary:en(S.join(" "),900),steps:c,verification:r,files:u,source:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,firstSequence:l,lastSequence:f,eventIds:p},createdAt:d}})}function Ic(t){return Dr(t.rootPath,".toolnet","memory","skills")}function Ac(t){let e=Ic(t);return pc(e,{recursive:!0,mode:448}),Lr(e,448),e}function Vr(t,e){if(e.length===0)return{written:0,deduped:0,files:[]};let n=Ac(t),r=0,s=0,o=[];for(let i of e){if(i.projectId!==t.id)throw new Error(`Skill project mismatch: ${i.projectId} != ${t.id}`);let a=Dr(n,`${i.id}.json`);if(o.push(a),dc(a)){s+=1;continue}let c=`${a}.${process.pid}.${Date.now()}.tmp`;mc(c,JSON.stringify(i,null,2)+`
43
- `,{encoding:"utf8",mode:384}),fc(c,a),Lr(a,384),r+=1}return{written:r,deduped:s,files:o}}function Gr(t){return String(t).padStart(12,"0")}function Mc(t){return`projects/${t.projectId}/memory/learned`}var ot=class{constructor(e){this.storage=e}storage;async write(e,n,r){if(r.length===0||n.length===0)return null;let s=Math.min(...n.map(l=>l.sequence)),o=Math.max(...n.map(l=>l.sequence)),i={version:1,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,createdAt:new Date().toISOString(),firstSequence:s,lastSequence:o,candidateCount:r.length,candidates:r},a=JSON.stringify(i,null,2)+`
44
- `,c=v(r.map(l=>l.fingerprint).sort().join("|")).slice(0,16),u=v(e.sessionKey).slice(0,12),p=[Mc(e),"batches",`${Gr(s)}-${Gr(o)}-${u}-${c}.json`].join("/");return await this.storage.exists(p)||await this.storage.put(p,a,"application/json"),p}};import{createHash as Pc}from"node:crypto";function Ur(t){return String(t).padStart(12,"0")}function Yr(t){return Pc("sha256").update(t).digest("hex")}function Ec(t){return`projects/${t.projectId}/memory/hierarchy`}var it=class{constructor(e){this.storage=e}storage;async write(e,n,r){if(n.length===0||r.facts.length===0)return null;let s=Math.min(...n.map(p=>p.sequence)),o=Math.max(...n.map(p=>p.sequence)),i={schema:"toolnet.memory-hierarchy-batch.v1",version:1,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,createdAt:new Date().toISOString(),firstSequence:s,lastSequence:o,hierarchy:r},a=Yr([...r.facts.map(p=>p.id),...r.knowledge.map(p=>p.id)].sort().join("|")).slice(0,16),c=Yr(e.sessionKey).slice(0,12),u=[Ec(e),"batches",`${Ur(s)}-${Ur(o)}-${c}-${a}.json`].join("/");return await this.storage.exists(u)||await this.storage.put(u,`${JSON.stringify(i,null,2)}
45
- `,"application/json"),u}};function $c(t,e){if(!Tc(t))return{events:[],nextOffset:e};let n=_c(t).size,r=Number.isFinite(e)?Math.max(0,e):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let s=n-r,o=Buffer.alloc(s),i=Rc(t,"r");try{Nc(i,o,0,s,r)}finally{Oc(i)}let a=o.toString("utf8"),c=a.lastIndexOf(`
36
+ ${d.map(y=>`- ${y}`).join(`
37
+ `)}`),m.length>0&&S.push(`## Relevant Files
38
+ ${m.map(y=>`- \`${y}\``).join(`
39
+ `)}`);let g=S.join(`
40
+
41
+ `).slice(0,un);if(g.length<20)continue;n.push({sourceKey:`skill:${c}`,sourceType:"skill",title:f,summary:l,content:g,tags:["toolnet","auto","skill","sop"]})}catch{r+=1}return{candidates:n,failed:r}}function cn(t){let e=new Date().toISOString();return{schema:Qr,version:1,projectId:t,entries:[],createdAt:e,updatedAt:e}}async function Pc(t,e){let n=await t.getText(Xr);if(!n)return cn(e);try{let r=JSON.parse(n);return r.schema!==Qr||r.version!==1||r.projectId!==e||!Array.isArray(r.entries)?cn(e):r}catch{return cn(e)}}async function Ec(t,e){await t.put(Xr,JSON.stringify(e,null,2),"application/json")}function Oc(t){return`toolnet-auto-${Pe(t).slice(0,12)}`}function Tc(t){let e=ne(t.title).slice(0,72),n=Pe(t.sourceKey).slice(0,10);return ne(`auto-${t.sourceType}-${e}-${n}`)}function Rc(t){return[`> Auto-generated by ToolNet Knowledge Automation from ${t.sourceType==="skill"?"reusable Skill Memory":t.sourceType==="scene"?"semantic memory scene":"durable memory"}.`,"",t.content].join(`
42
+ `).slice(0,un)}function Nc(t){return Pe({sourceType:t.sourceType,title:t.title,summary:t.summary,content:t.content,tags:t.tags})}function _c(t,e){return t.tags.includes(e)}async function eo(t){let e=Cc(t.hierarchy),n=Mc(t.project.rootPath),r=new Map;for(let d of[...e,...n.candidates])r.set(d.sourceKey,d);let o=[...r.values()].sort((d,m)=>d.sourceKey.localeCompare(m.sourceKey)),s={schema:"toolnet.wiki-automation-result.v1",scanned:e.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 ct(new ut(t.storage,t.project));await i.initialize();let a=new dt(new lt(t.storage,t.project));await a.initialize();let c=await Pc(t.storage,t.project.id),u=await i.listPages(),f=new Map(u.map(d=>[d.slug,d])),l=new Map(c.entries.map(d=>[d.sourceKey,d]));for(let d of o)try{let m=Oc(d.sourceKey),S=Nc(d),g=l.get(d.sourceKey),y=g?.slug??Tc(d),v=f.get(y);if(v&&!_c(v,m)){s.skipped+=1;continue}let x=Ee([...d.tags,m]),O=Rc(d),P=await a.gate({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:y,marker:m,digest:S,title:d.title,...d.summary?{summary:d.summary}:{},content:O,tags:x},[...f.values()]);if(!P.allowed){P.mode==="pending-review"?s.reviewPending+=1:s.skipped+=1;continue}P.mode==="auto-approved"?s.autoApproved+=1:P.mode==="review-approved"&&(s.reviewApproved+=1),v?g?.digest!==S?(v=await i.updatePage(y,{title:d.title,summary:d.summary??"",content:O,tags:x}),f.set(v.slug,v),s.updated+=1,s.pages.push({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:v.slug,action:"updated"})):(s.unchanged+=1,s.pages.push({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:y,action:"unchanged"})):(v=await i.createPage({slug:y,title:d.title,summary:d.summary,content:O,tags:x}),f.set(v.slug,v),s.created+=1,s.pages.push({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:v.slug,action:"created"}));let T=new Date().toISOString(),j={sourceKey:d.sourceKey,sourceType:d.sourceType,slug:y,digest:S,marker:m,updatedAt:T},b=c.entries.findIndex(D=>D.sourceKey===d.sourceKey);b>=0?c.entries[b]=j:c.entries.push(j),l.set(d.sourceKey,j),await a.markApplied(d.sourceKey,S)}catch(m){if(m instanceof C&&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((d,m)=>d.sourceKey.localeCompare(m.sourceKey)),await Ec(t.storage,c),s}import{createHash as Kc}from"node:crypto";import{chmodSync as no,existsSync as $c,mkdirSync as Lc,readFileSync as Mg,readdirSync as Pg,renameSync as Fc,statSync as Eg,writeFileSync as Wc}from"node:fs";import{join as ro}from"node:path";var Dc="toolnet.skill-memory.v1",to=5,zc=16,qc=24,Vc=32;function Hc(t){return Kc("sha256").update(t).digest("hex")}function Te(t,e=Number.MAX_SAFE_INTEGER){let n=new Set,r=[];for(let o of t){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>=e))break}return r}function ln(t,e=360){let n=t.replace(/\s+/gu," ").trim();return n.length<=e?n:n.slice(0,Math.max(0,e-1)).trimEnd()+"\u2026"}function Bc(t){return t.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(t,e=360){return t&&ln(Bc(t),e)||void 0}function Re(t,e){for(let n of e){let r=t[n];if(typeof r=="string"&&r.trim())return r}}function oo(t,e){for(let n of e){let r=t[n];if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()&&Number.isFinite(Number(r)))return Number(r)}}function so(t,e){for(let n of e){let r=t[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 io(t){let e=t.data??{};if(so(e,["passed","pass","success","succeeded","ok"])===!1)return!0;let r=oo(e,["exitCode","exit_code","code","statusCode"]);if(r!==void 0&&r!==0)return!0;let o=Re(e,["status","result","outcome"]);return!!(o&&/\b(fail(?:ed)?|error|broken|cancelled)\b/iu.test(o))}function Oe(t){let e=t.data??{};if(io(t))return!1;if(so(e,["passed","pass","success","succeeded","ok"])===!0||oo(e,["exitCode","exit_code","code","statusCode"])===0)return!0;let o=Re(e,["status","result","outcome"]);return o&&/\b(pass(?:ed)?|success(?:ful)?|succeeded|ok|green|complete(?:d)?)\b/iu.test(o)?!0:t.type==="commit"||t.type==="deploy"}function ao(t){let e=t.data??{},n=Re(e,["path","file","filePath","filename","target"]);if(n)return q(n,260);let r=t.provenance?.files;return q(r?.[0],260)}function dn(t){return q(Re(t.data??{},["command","cmd","script"]),420)}function le(t){return q(Re(t.data??{},["name","test","suite","title","message","text","result","status"]),300)}function Jc(t){let e=[];for(let n of[...t].sort((r,o)=>r.sequence-o.sequence))if(Oe(n)){if(n.type==="test"){let r=le(n)??dn(n)??"Tests passed";e.push(`Test passed: ${r}`);continue}if(n.type==="commit"){let r=le(n);e.push(r?`Commit: ${r}`:"Commit completed");continue}if(n.type==="deploy"){let r=le(n);e.push(r?`Deploy: ${r}`:"Deployment completed")}}return Te(e,10)}function Gc(t,e){let n=[];for(let r of[...t].sort((o,s)=>o.sequence-s.sequence))switch(r.type){case"file_write":case"file_edit":{let o=ao(r);o&&n.push(`Update ${o}`);break}case"command":{if(io(r))break;let o=dn(r);o&&n.push(`Run: ${o}`);break}case"test":{if(!Oe(r))break;let o=le(r)??dn(r)??"project tests";n.push(`Verify: ${o}`);break}case"commit":{if(!Oe(r))break;let o=le(r);n.push(o?`Commit: ${o}`:"Commit verified changes");break}case"deploy":{if(!Oe(r))break;let o=le(r);n.push(o?`Deploy: ${o}`:"Deploy verified build");break}default:break}if(n.length===0)for(let r of e.files.slice(0,8)){let o=q(r,260);o&&n.push(`Update ${o}`)}return Te(n,zc)}function Uc(t,e){let n=[...e.files];for(let r of t){let o=ao(r);o&&n.push(o);for(let s of r.provenance?.files??[]){let i=q(s,260);i&&n.push(i)}}return Te(n,qc)}function Yc(t){return Te(t.filter(e=>["file_write","file_edit","command","test","commit","deploy"].includes(e.type)).map(e=>e.id),Vc)}function Xc(t){return t.map(n=>n.timestamp).filter(Boolean).sort().at(-1)??new Date(0).toISOString()}function co(t,e,n){if(e.length===0)return[];let r=Jc(e),o=Te(n.completed.map(m=>q(m,280)??""),to);if(!(o.length>0||e.some(m=>["test","commit","deploy"].includes(m.type)&&Oe(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=Gc(e,n);if(c.length===0)return[];let u=Uc(e,n),f=Yc(e),l=Math.min(...e.map(m=>m.sequence)),p=Math.max(...e.map(m=>m.sequence)),d=Xc(e);return a.slice(0,to).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:t.projectId,task:m,steps:c,verification:r,files:u}),y=Hc(g);return{schema:Dc,version:1,id:`skill-${y.slice(0,24)}`,fingerprint:y,projectId:t.projectId,title:ln(`SOP: ${m}`,180),task:m,summary:ln(S.join(" "),900),steps:c,verification:r,files:u,source:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,firstSequence:l,lastSequence:p,eventIds:f},createdAt:d}})}function Qc(t){return ro(t.rootPath,".toolnet","memory","skills")}function Zc(t){let e=Qc(t);return Lc(e,{recursive:!0,mode:448}),no(e,448),e}function uo(t,e){if(e.length===0)return{written:0,deduped:0,files:[]};let n=Zc(t),r=0,o=0,s=[];for(let i of e){if(i.projectId!==t.id)throw new Error(`Skill project mismatch: ${i.projectId} != ${t.id}`);let a=ro(n,`${i.id}.json`);if(s.push(a),$c(a)){o+=1;continue}let c=`${a}.${process.pid}.${Date.now()}.tmp`;Wc(c,JSON.stringify(i,null,2)+`
43
+ `,{encoding:"utf8",mode:384}),Fc(c,a),no(a,384),r+=1}return{written:r,deduped:o,files:s}}function lo(t){return String(t).padStart(12,"0")}function eu(t){return`projects/${t.projectId}/memory/learned`}var ft=class{constructor(e){this.storage=e}storage;async write(e,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:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,createdAt:new Date().toISOString(),firstSequence:o,lastSequence:s,candidateCount:r.length,candidates:r},a=JSON.stringify(i,null,2)+`
44
+ `,c=w(r.map(l=>l.fingerprint).sort().join("|")).slice(0,16),u=w(e.sessionKey).slice(0,12),f=[eu(e),"batches",`${lo(o)}-${lo(s)}-${u}-${c}.json`].join("/");return await this.storage.exists(f)||await this.storage.put(f,a,"application/json"),f}};import{createHash as tu}from"node:crypto";function po(t){return String(t).padStart(12,"0")}function fo(t){return tu("sha256").update(t).digest("hex")}function nu(t){return`projects/${t.projectId}/memory/hierarchy`}var mt=class{constructor(e){this.storage=e}storage;async write(e,n,r){if(n.length===0||r.facts.length===0)return null;let o=Math.min(...n.map(f=>f.sequence)),s=Math.max(...n.map(f=>f.sequence)),i={schema:"toolnet.memory-hierarchy-batch.v1",version:1,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,createdAt:new Date().toISOString(),firstSequence:o,lastSequence:s,hierarchy:r},a=fo([...r.facts.map(f=>f.id),...r.knowledge.map(f=>f.id)].sort().join("|")).slice(0,16),c=fo(e.sessionKey).slice(0,12),u=[nu(e),"batches",`${po(o)}-${po(s)}-${c}-${a}.json`].join("/");return await this.storage.exists(u)||await this.storage.put(u,`${JSON.stringify(i,null,2)}
45
+ `,"application/json"),u}};function cu(t,e){if(!ou(t))return{events:[],nextOffset:e};let n=au(t).size,r=Number.isFinite(e)?Math.max(0,e):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let o=n-r,s=Buffer.alloc(o),i=su(t,"r");try{iu(i,s,0,o,r)}finally{ru(i)}let a=s.toString("utf8"),c=a.lastIndexOf(`
46
46
  `);if(c<0)return{events:[],nextOffset:r};let u=a.slice(0,c+1);return{events:u.split(`
47
- `).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var at=class{constructor(e){this.options=e;this.journal=new ot(e.storage),this.hierarchyJournal=new it(e.storage)}options;journal;hierarchyJournal;async learnNew(){let e=this.options.wal.loadState(),n=Number(e.sourceCursors["memory.learner.offset"]??0),r=Number.isFinite(n)?n:0,s=$c(this.options.wal.eventsFile,r);if(s.events.length===0)return{scannedEvents:0,candidates:0,journalWritten:!1,nextOffset:s.nextOffset};let o=Qe(this.options.identity,s.events),i=o.candidates,a=!1;i.length>0&&(a=!!await this.journal.write(this.options.identity,s.events,i));let c=!1;o.hierarchy.facts.length>0&&(c=!!await this.hierarchyJournal.write(this.options.identity,s.events,o.hierarchy));let u=Hr(this.options.identity,s.events,o.state),p=Vr(this.options.project,u);this.options.wal.setSourceCursor("memory.pipeline.version",2),this.options.wal.setSourceCursor("memory.pipeline.normalized_events",o.stats.normalizedEvents),this.options.wal.setSourceCursor("memory.pipeline.persisted",o.stats.persistedCandidates),this.options.wal.setSourceCursor("memory.pipeline.permanent",o.stats.permanent),this.options.wal.setSourceCursor("memory.pipeline.task",o.stats.task),this.options.wal.setSourceCursor("memory.pipeline.session",o.stats.session),this.options.wal.setSourceCursor("memory.pipeline.transient",o.stats.transient),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.version",o.hierarchy.version),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.raw",o.hierarchy.stats.raw),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.facts",o.hierarchy.stats.facts),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.scenes",o.hierarchy.stats.scenes),this.options.wal.setSourceCursor("memory.pipeline.hierarchy.knowledge",o.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",p.written),this.options.wal.setSourceCursor("memory.skill.deduped",p.deduped);try{let l=hr(this.options.project.rootPath,s.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 Fr({project:this.options.project,storage:this.options.storage,hierarchy:o.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",s.nextOffset),{scannedEvents:s.events.length,candidates:i.length,journalWritten:a,nextOffset:s.nextOffset}}};import{closeSync as Zc,existsSync as eu,openSync as tu,readSync as nu,statSync as ru}from"node:fs";function Xr(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Ee(t){return t.toLowerCase().replace(/[^a-z0-9]/gu,"")}function Pe(t,e,n=0){if(n>8)return;if(Array.isArray(t)){for(let s of t.slice(0,50))Pe(s,e,n+1);return}let r=Xr(t);if(r)for(let[s,o]of Object.entries(r))e(s,o,r),Pe(o,e,n+1)}function ae(t,e){let n=[];return Pe(t,(r,s)=>{e.has(Ee(r))&&typeof s=="string"&&s.trim()&&n.push(s.trim())}),n}function Kc(t){let e=t.trim();if(!e.startsWith("{"))return null;try{return Xr(JSON.parse(e))}catch{return null}}function Fc(t){let e=t.data;for(let r of["tool","toolName","tool_name"]){let s=e[r];if(typeof s=="string"&&s.trim())return s.trim().toLowerCase()}let n="";return Pe(e,(r,s,o)=>{if(n)return;let i=Ee(r);if(["tool","toolname"].includes(i)&&typeof s=="string"){n=s.trim().toLowerCase();return}if(i!=="name"||typeof s!="string")return;let a=typeof o.type=="string"?o.type.toLowerCase():"";(a.includes("tool")||a.includes("function")||a.includes("command"))&&(n=s.trim().toLowerCase())}),n}function Wc(t){let e=ae(t.data,new Set(["command","cmd","script"])),n=ae(t.data,new Set(["arguments","args"]));for(let r of n){let s=Kc(r);if(s)for(let o of ae(s,new Set(["command","cmd","script"])))e.push(o)}return Array.from(new Set(e.map(r=>r.trim()).filter(Boolean)))}function Lc(t){let e=ae(t.data,new Set(["filepath","file_path","filename","file","path","target"].map(Ee)));return Array.from(new Set(e.map(n=>n.trim()).filter(n=>n.length>0&&n.length<1e3&&!n.includes(`
48
- `))))}function Dc(t,e){return t.type==="file_edit"||t.type==="file_write"?"modified":/\b(delete|remove|unlink)\b/iu.test(e)?"deleted":/\b(create|add[_-]?file|new[_-]?file)\b/iu.test(e)?"created":/\b(edit|write|patch|apply[_-]?patch|replace|update[_-]?file)\b/iu.test(e)?"modified":null}function zc(t){let e=ae(t.data,new Set(["patch","diff","arguments","input"].map(Ee))),n=[];for(let r of e){let s=[{regex:/^\*\*\* Update File:\s*(.+)$/gimu,action:"modified"},{regex:/^\*\*\* Add File:\s*(.+)$/gimu,action:"created"},{regex:/^\*\*\* Delete File:\s*(.+)$/gimu,action:"deleted"}];for(let o of s)for(let i of r.matchAll(o.regex)){let a=i[1]?.trim();a&&n.push({kind:"file",text:a,fileAction:o.action,confidence:.99})}}return n}function qc(t){let e=t.toLowerCase();return/\b(typecheck|type-check)\b/u.test(e)||/\btsc\b[\s\S]*--noemit\b/u.test(e)?"typecheck":/\b(eslint|lint)\b/u.test(e)?"lint":/\b(vitest|jest|pytest)\b/u.test(e)||/\bgo\s+test\b/u.test(e)||/\bcargo\s+test\b/u.test(e)||/\b(npm|pnpm|yarn)\s+(run\s+)?test\b/u.test(e)?"test":/\b(npm|pnpm|yarn)\s+(run\s+)?build\b/u.test(e)||/\bcargo\s+build\b/u.test(e)||/\bgo\s+build\b/u.test(e)||/\btsc\b/u.test(e)?"build":null}function Bc(t){let e=null;return Pe(t,(n,r)=>{if(e===null&&["exitcode","code"].includes(Ee(n))){if(typeof r=="number"&&Number.isFinite(r)){e=r;return}if(typeof r=="string"){let s=Number(r);Number.isFinite(s)&&(e=s)}}}),e}function Jc(t){return ae(t,new Set(["status","state","result","output","outputsummary","message","text"]))}function Hc(t){let e=Bc(t.data);if(e!==null)return e===0?"passed":"failed";let n=Jc(t.data).join(`
49
- `).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 Vc(t){let e=[],n=new Set;for(let r of t){let s=[r.kind,r.fileAction??"",r.checkKind??"",r.checkStatus??"",r.text].join("|");n.has(s)||(n.add(s),e.push(r))}return e}function Qr(t){let e=[],n=Fc(t),r=Dc(t,n);if(r)for(let s of Lc(t))e.push({kind:"file",text:s,fileAction:r,confidence:t.type==="file_edit"||t.type==="file_write"?1:.96});e.push(...zc(t));for(let s of Wc(t)){e.push({kind:"command",text:s,confidence:.98});let o=qc(s);o&&e.push({kind:"test",text:s,checkKind:o,checkStatus:Hc(t),confidence:.98})}return Vc(e)}var Gc=new Set(["content","text","message","prompt","summary","description","title","reason","last_assistant_message","lastAssistantMessage"]);function te(t){return t.normalize("NFKC").replace(/\s+/g," ").replace(/^[\s>*#•-]+/u,"").trim()}function es(t){return te(t).toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function ee(t,e,n=0){if(!(n>6)){if(typeof t=="string"){e.push(t);return}if(Array.isArray(t)){for(let r of t.slice(0,50))ee(r,e,n+1);return}if(!(!t||typeof t!="object"))for(let[r,s]of Object.entries(t))(Gc.has(r)||["data","payload","parts","messages"].includes(r))&&ee(s,e,n+1)}}function ct(t){return/\b(cancelled|canceled)\b|đã hủy|bỏ qua/iu.test(t)?"cancelled":/\b(blocked|blocker)\b|đang vướng|bị vướng|đang kẹt|chưa thể/iu.test(t)?"blocked":/\b(completed|complete|done|finished|passed)\b|hoàn thành|hoàn tất|đã xong|đã làm xong|\bxong\b/iu.test(t)?"completed":/\bin[\s_-]*progress\b|working on|đang làm|đang thực hiện|đang xử lý|đang triển khai/iu.test(t)?"in_progress":"pending"}function Zr(t){let e=te(t);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(e)}function I(t,e,n,r,s={}){let o=te(r),i=s.key??es(o);return{version:1,id:v([t.projectId,n,i,e.id,o,s.status??"",s.fileAction??"",s.checkKind??"",s.checkStatus??"",s.order??""].join("|")).slice(0,32),projectId:t.projectId,kind:n,key:i,text:o,status:s.status,fileAction:s.fileAction,checkKind:s.checkKind,checkStatus:s.checkStatus,order:s.order,confidence:s.confidence??.85,occurredAt:e.timestamp,sequence:e.sequence,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,eventId:e.id,sourceEventId:e.sourceEventId}}function Uc(t,e,n){let r=te(n);if(r.length<5||r.length>1200)return[];let s=[],o=/^(?: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]&&s.push(I(t,e,"goal",i[1],{confidence:.97}));let a=r.match(/^(?:kế hoạch|plan)\s*(?::|-)\s*(.+)$/iu);a?.[1]&&s.push(I(t,e,"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(;!o&&(u=c.exec(r));){let f=Number(u[1]),d=te(u[2]??""),g=d&&!Zr(d)?`Phase ${f} - ${d}`:`Phase ${f}`;s.push(I(t,e,"phase",g,{key:`phase:${f}`,order:f,status:ct(r),confidence:.93}))}let p=n.match(/^\s*[-*]\s*\[([ xX])\]\s*(.+)$/u);p?.[2]&&s.push(I(t,e,"task",p[2],{status:p[1].trim()?"completed":ct(p[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,d=te(l[2]),g=Zr(d);s.push(I(t,e,"task",g&&f!==void 0?`TODO ${f}`:d,{key:f!==void 0?`task:${f}`:es(d),order:f,status:ct(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&&s.push(I(t,e,"next_action",f,{confidence:.9}))}return/\b(blocker|blocked)\b|đang vướng|bị vướng|đang kẹt/iu.test(r)&&s.push(I(t,e,"blocker",r,{confidence:.9})),/\b(chú ý|lưu ý|warning|attention|cẩn thận)\b/iu.test(r)&&s.push(I(t,e,"warning",r,{confidence:.88})),/\b(chốt|quyết định|decided|decision)\b/iu.test(r)&&s.push(I(t,e,"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)&&s.push(I(t,e,"activity",r,{confidence:.86})),s}function ce(t,e){if(e.length===0)return[];let n=[],r=new Set;function s(i){r.has(i.id)||(r.add(i.id),n.push(i))}for(let i of e){if(i.type==="user_prompt"||i.role==="user"){let c=[];ee(i.data,c);let u=c.map(p=>te(p)).find(p=>p.length>=8&&p.length<=1200&&!/^\[?toolnet\b/iu.test(p));u&&s(I(t,i,"request",u,{confidence:.96}))}for(let c of Qr(i))s(I(t,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)s(I(t,i,"decision",u,{confidence:1}))}if(i.type==="todo"){let c=[];ee(i.data,c);for(let u of c)s(I(t,i,"task",u,{status:ct(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&&s(I(t,i,"file",u,{fileAction:"modified",confidence:1}))}if(i.type==="test"){let c=[];ee(i.data,c);for(let u of c)s(I(t,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 p of Uc(t,i,u))s(p)}let o=e[e.length-1];return s(I(t,o,"session",`${t.agent}:${t.nativeSessionId}`,{key:t.sessionKey,confidence:1})),n}function ts(t){return String(t).padStart(12,"0")}var ut=class{constructor(e){this.storage=e}storage;async write(e,n){if(n.length===0)return null;let r=Math.min(...n.map(p=>p.sequence)),s=Math.max(...n.map(p=>p.sequence)),o={version:1,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,createdAt:n.map(p=>p.occurredAt).sort().at(-1)??new Date().toISOString(),firstSequence:r,lastSequence:s,observations:n},i=JSON.stringify(o,null,2)+`
50
- `,a=v(n.map(p=>JSON.stringify(p)).sort().join(`
51
- `)).slice(0,24),c=v(e.sessionKey).slice(0,12),u=[`projects/${e.projectId}`,"work","observations",`${ts(r)}-${ts(s)}-${c}-${a}.json`].join("/");return await this.storage.put(u,i,"application/json"),u}};import{join as ns}from"node:path";import{mkdirSync as Yc}from"node:fs";function ss(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function K(t,e=20){let n=[],r=new Set;for(let s of t.slice().reverse()){let o=ss(s);if(!(!o||r.has(o))&&(r.add(o),n.push(s),n.length>=e))break}return n.reverse()}function Xc(t,e=20){let n=new Map;for(let r of t){let s=`${r.kind}|${ss(r.command)}`;n.delete(s),n.set(s,r)}return Array.from(n.values()).slice(-e)}function Qc(t){return t.kind==="phase"?/^Phase\s+\d+$/iu.test(t.text):t.kind==="task"?/^(?:TODO|Task|Việc)\s+\d+$/iu.test(t.text):!1}function rs(t,e){let n=e.status??t?.status??"pending",r=n;t&&(t.status==="completed"&&n!=="completed"?r="completed":n==="pending"&&(t.status==="in_progress"||t.status==="blocked")&&(r=t.status));let s=t&&Qc(e)?t.title:e.text;return{id:t?.id??v(e.key).slice(0,24),title:s,status:r,order:e.order??t?.order,confidence:Math.max(e.confidence,t?.confidence??0),updatedAt:e.occurredAt,updatedBy:{agent:e.agent,nativeSessionId:e.nativeSessionId,eventId:e.eventId}}}async function os(t,e){let n=`projects/${t.id}/work/observations/`,r=await e.list(n),s=[];for(let o of r.filter(i=>i.key.endsWith(".json")).sort((i,a)=>i.key.localeCompare(a.key))){let i=await e.getText(o.key);if(i)try{let a=JSON.parse(i);a.version===1&&Array.isArray(a.observations)&&s.push(a)}catch{}}return s}async function Oe(t,e){let r=(await os(t,e)).flatMap(m=>m.observations).sort((m,b)=>{let q=m.occurredAt.localeCompare(b.occurredAt);if(q!==0)return q;let gn=m.sequence-b.sequence;return gn!==0?gn:m.id.localeCompare(b.id)}),s=new Map,o=new Map,i,a,c,u,p,l=[],f=[],d=[],g=[],S=[],y=new Map,h=[],k=[],P=[],E=[],M=[],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":s.set(m.key,rs(s.get(m.key),m));break;case"task":o.set(m.key,rs(o.get(m.key),m));break;case"decision":l.push(m.text);break;case"blocker":f.push(m.text);break;case"warning":d.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"&&P.push(m.text);break}case"command":E.push(m.text);break;case"test":M.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":p={agent:m.agent,nativeSessionId:m.nativeSessionId,sessionKey:m.sessionKey,updatedAt:m.occurredAt};break}let x=Array.from(s.values()).sort((m,b)=>(m.order??Number.MAX_SAFE_INTEGER)-(b.order??Number.MAX_SAFE_INTEGER)),w=Array.from(o.values()).sort((m,b)=>(m.order??Number.MAX_SAFE_INTEGER)-(b.order??Number.MAX_SAFE_INTEGER)),L=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"),At=K([...g,...D?[D.title]:[],...!D&&L?[L.title]:[],...w.filter(m=>m.status==="pending").slice(0,5).map(m=>m.title)],8),Mt=K([...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:t.id,projectName:t.name,currentRequest:i,currentActivity:a,goal:c,plan:u,phases:x,tasks:w,decisions:K(l,20),blockers:Mt,warnings:K(d,20),nextActions:At,filesTouched:K(S,30),activeFiles:Array.from(y.entries()).filter(([,m])=>m!=="deleted").map(([m])=>m).slice(-5),modifiedFiles:K(h,30),createdFiles:K(k,30),deletedFiles:K(P,30),commands:K(E,20),tests:K(M,20),checks:Xc(O,20),currentPhase:L,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:p,updatedAt:r.length?r[r.length-1].occurredAt:new Date().toISOString()},de=ns(t.rootPath,".toolnet","work");return Yc(de,{recursive:!0}),T(ns(de,"current.json"),le),await e.put(`projects/${t.id}/work/current.json`,JSON.stringify(le,null,2)+`
52
- `,"application/json"),le}async function lt(t,e){if((await os(t,e)).length>0)return Oe(t,e);let r=await e.getText(`projects/${t.id}/work/current.json`);if(!r)return null;try{return JSON.parse(r)}catch{return null}}function su(t,e){if(!eu(t))return{events:[],nextOffset:e};let n=ru(t).size,r=Number.isFinite(e)?Math.max(0,e):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let s=n-r,o=Buffer.alloc(s),i=tu(t,"r");try{nu(i,o,0,s,r)}finally{Zc(i)}let a=o.toString("utf8"),c=a.lastIndexOf(`
47
+ `).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var gt=class{constructor(e){this.options=e;this.journal=new ft(e.storage),this.hierarchyJournal=new mt(e.storage)}options;journal;hierarchyJournal;async learnNew(){let e=this.options.wal.loadState(),n=Number(e.sourceCursors["memory.learner.offset"]??0),r=Number.isFinite(n)?n:0,o=cu(this.options.wal.eventsFile,r);if(o.events.length===0)return{scannedEvents:0,candidates:0,journalWritten:!1,nextOffset:o.nextOffset};let s=it(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=co(this.options.identity,o.events,s.state),f=uo(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",f.written),this.options.wal.setSourceCursor("memory.skill.deduped",f.deduped);try{let l=Rr(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 eo({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 Iu,existsSync as Cu,openSync as Au,readSync as Mu,statSync as Pu}from"node:fs";function mo(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function _e(t){return t.toLowerCase().replace(/[^a-z0-9]/gu,"")}function Ne(t,e,n=0){if(n>8)return;if(Array.isArray(t)){for(let o of t.slice(0,50))Ne(o,e,n+1);return}let r=mo(t);if(r)for(let[o,s]of Object.entries(r))e(o,s,r),Ne(s,e,n+1)}function de(t,e){let n=[];return Ne(t,(r,o)=>{e.has(_e(r))&&typeof o=="string"&&o.trim()&&n.push(o.trim())}),n}function uu(t){let e=t.trim();if(!e.startsWith("{"))return null;try{return mo(JSON.parse(e))}catch{return null}}function lu(t){let e=t.data;for(let r of["tool","toolName","tool_name"]){let o=e[r];if(typeof o=="string"&&o.trim())return o.trim().toLowerCase()}let n="";return Ne(e,(r,o,s)=>{if(n)return;let i=_e(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 du(t){let e=de(t.data,new Set(["command","cmd","script"])),n=de(t.data,new Set(["arguments","args"]));for(let r of n){let o=uu(r);if(o)for(let s of de(o,new Set(["command","cmd","script"])))e.push(s)}return Array.from(new Set(e.map(r=>r.trim()).filter(Boolean)))}function pu(t){let e=de(t.data,new Set(["filepath","file_path","filename","file","path","target"].map(_e)));return Array.from(new Set(e.map(n=>n.trim()).filter(n=>n.length>0&&n.length<1e3&&!n.includes(`
48
+ `))))}function fu(t,e){return t.type==="file_edit"||t.type==="file_write"?"modified":/\b(delete|remove|unlink)\b/iu.test(e)?"deleted":/\b(create|add[_-]?file|new[_-]?file)\b/iu.test(e)?"created":/\b(edit|write|patch|apply[_-]?patch|replace|update[_-]?file)\b/iu.test(e)?"modified":null}function mu(t){let e=de(t.data,new Set(["patch","diff","arguments","input"].map(_e))),n=[];for(let r of e){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 gu(t){let e=t.toLowerCase();return/\b(typecheck|type-check)\b/u.test(e)||/\btsc\b[\s\S]*--noemit\b/u.test(e)?"typecheck":/\b(eslint|lint)\b/u.test(e)?"lint":/\b(vitest|jest|pytest)\b/u.test(e)||/\bgo\s+test\b/u.test(e)||/\bcargo\s+test\b/u.test(e)||/\b(npm|pnpm|yarn)\s+(run\s+)?test\b/u.test(e)?"test":/\b(npm|pnpm|yarn)\s+(run\s+)?build\b/u.test(e)||/\bcargo\s+build\b/u.test(e)||/\bgo\s+build\b/u.test(e)||/\btsc\b/u.test(e)?"build":null}function yu(t){let e=null;return Ne(t,(n,r)=>{if(e===null&&["exitcode","code"].includes(_e(n))){if(typeof r=="number"&&Number.isFinite(r)){e=r;return}if(typeof r=="string"){let o=Number(r);Number.isFinite(o)&&(e=o)}}}),e}function hu(t){return de(t,new Set(["status","state","result","output","outputsummary","message","text"]))}function Su(t){let e=yu(t.data);if(e!==null)return e===0?"passed":"failed";let n=hu(t.data).join(`
49
+ `).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 ku(t){let e=[],n=new Set;for(let r of t){let o=[r.kind,r.fileAction??"",r.checkKind??"",r.checkStatus??"",r.text].join("|");n.has(o)||(n.add(o),e.push(r))}return e}function go(t){let e=[],n=lu(t),r=fu(t,n);if(r)for(let o of pu(t))e.push({kind:"file",text:o,fileAction:r,confidence:t.type==="file_edit"||t.type==="file_write"?1:.96});e.push(...mu(t));for(let o of du(t)){e.push({kind:"command",text:o,confidence:.98});let s=gu(o);s&&e.push({kind:"test",text:o,checkKind:s,checkStatus:Su(t),confidence:.98})}return ku(e)}var vu=new Set(["content","text","message","prompt","summary","description","title","reason","last_assistant_message","lastAssistantMessage"]);function oe(t){return t.normalize("NFKC").replace(/\s+/g," ").replace(/^[\s>*#•-]+/u,"").trim()}function ho(t){return oe(t).toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function re(t,e,n=0){if(!(n>6)){if(typeof t=="string"){e.push(t);return}if(Array.isArray(t)){for(let r of t.slice(0,50))re(r,e,n+1);return}if(!(!t||typeof t!="object"))for(let[r,o]of Object.entries(t))(vu.has(r)||["data","payload","parts","messages"].includes(r))&&re(o,e,n+1)}}function yt(t){return/\b(cancelled|canceled)\b|đã hủy|bỏ qua/iu.test(t)?"cancelled":/\b(blocked|blocker)\b|đang vướng|bị vướng|đang kẹt|chưa thể/iu.test(t)?"blocked":/\b(completed|complete|done|finished|passed)\b|hoàn thành|hoàn tất|đã xong|đã làm xong|\bxong\b/iu.test(t)?"completed":/\bin[\s_-]*progress\b|working on|đang làm|đang thực hiện|đang xử lý|đang triển khai/iu.test(t)?"in_progress":"pending"}function yo(t){let e=oe(t);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(e)}function A(t,e,n,r,o={}){let s=oe(r),i=o.key??ho(s);return{version:1,id:w([t.projectId,n,i,e.id,s,o.status??"",o.fileAction??"",o.checkKind??"",o.checkStatus??"",o.order??""].join("|")).slice(0,32),projectId:t.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:e.timestamp,sequence:e.sequence,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,eventId:e.id,sourceEventId:e.sourceEventId}}function wu(t,e,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(A(t,e,"goal",i[1],{confidence:.97}));let a=r.match(/^(?:kế hoạch|plan)\s*(?::|-)\s*(.+)$/iu);a?.[1]&&o.push(A(t,e,"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]),d=oe(u[2]??""),m=d&&!yo(d)?`Phase ${p} - ${d}`:`Phase ${p}`;o.push(A(t,e,"phase",m,{key:`phase:${p}`,order:p,status:yt(r),confidence:.93}))}let f=n.match(/^\s*[-*]\s*\[([ xX])\]\s*(.+)$/u);f?.[2]&&o.push(A(t,e,"task",f[2],{status:f[1].trim()?"completed":yt(f[2]),confidence:.96}));let l=r.match(/^(?:todo|task|việc)\s*(\d+)?(?:\s*[:.\-–—]\s*|\s+)(.+)$/iu);if(l?.[2]){let p=l[1]?Number(l[1]):void 0,d=oe(l[2]),m=yo(d);o.push(A(t,e,"task",m&&p!==void 0?`TODO ${p}`:d,{key:p!==void 0?`task:${p}`:ho(d),order:p,status:yt(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(A(t,e,"next_action",p,{confidence:.9}))}return/\b(blocker|blocked)\b|đang vướng|bị vướng|đang kẹt/iu.test(r)&&o.push(A(t,e,"blocker",r,{confidence:.9})),/\b(chú ý|lưu ý|warning|attention|cẩn thận)\b/iu.test(r)&&o.push(A(t,e,"warning",r,{confidence:.88})),/\b(chốt|quyết định|decided|decision)\b/iu.test(r)&&o.push(A(t,e,"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(A(t,e,"activity",r,{confidence:.86})),o}function pe(t,e){if(e.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 e){if(i.type==="user_prompt"||i.role==="user"){let c=[];re(i.data,c);let u=c.map(f=>oe(f)).find(f=>f.length>=8&&f.length<=1200&&!/^\[?toolnet\b/iu.test(f));u&&o(A(t,i,"request",u,{confidence:.96}))}for(let c of go(i))o(A(t,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(A(t,i,"decision",u,{confidence:1}))}if(i.type==="todo"){let c=[];re(i.data,c);for(let u of c)o(A(t,i,"task",u,{status:yt(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(A(t,i,"file",u,{fileAction:"modified",confidence:1}))}if(i.type==="test"){let c=[];re(i.data,c);for(let u of c)o(A(t,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 f of wu(t,i,u))o(f)}let s=e[e.length-1];return o(A(t,s,"session",`${t.agent}:${t.nativeSessionId}`,{key:t.sessionKey,confidence:1})),n}function So(t){return String(t).padStart(12,"0")}var ht=class{constructor(e){this.storage=e}storage;async write(e,n){if(n.length===0)return null;let r=Math.min(...n.map(f=>f.sequence)),o=Math.max(...n.map(f=>f.sequence)),s={version:1,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,createdAt:n.map(f=>f.occurredAt).sort().at(-1)??new Date().toISOString(),firstSequence:r,lastSequence:o,observations:n},i=JSON.stringify(s,null,2)+`
50
+ `,a=w(n.map(f=>JSON.stringify(f)).sort().join(`
51
+ `)).slice(0,24),c=w(e.sessionKey).slice(0,12),u=[`projects/${e.projectId}`,"work","observations",`${So(r)}-${So(o)}-${c}-${a}.json`].join("/");return await this.storage.put(u,i,"application/json"),u}};import{join as ko}from"node:path";import{mkdirSync as bu}from"node:fs";function wo(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function L(t,e=20){let n=[],r=new Set;for(let o of t.slice().reverse()){let s=wo(o);if(!(!s||r.has(s))&&(r.add(s),n.push(o),n.length>=e))break}return n.reverse()}function xu(t,e=20){let n=new Map;for(let r of t){let o=`${r.kind}|${wo(r.command)}`;n.delete(o),n.set(o,r)}return Array.from(n.values()).slice(-e)}function ju(t){return t.kind==="phase"?/^Phase\s+\d+$/iu.test(t.text):t.kind==="task"?/^(?:TODO|Task|Việc)\s+\d+$/iu.test(t.text):!1}function vo(t,e){let n=e.status??t?.status??"pending",r=n;t&&(t.status==="completed"&&n!=="completed"?r="completed":n==="pending"&&(t.status==="in_progress"||t.status==="blocked")&&(r=t.status));let o=t&&ju(e)?t.title:e.text;return{id:t?.id??w(e.key).slice(0,24),title:o,status:r,order:e.order??t?.order,confidence:Math.max(e.confidence,t?.confidence??0),updatedAt:e.occurredAt,updatedBy:{agent:e.agent,nativeSessionId:e.nativeSessionId,eventId:e.eventId}}}async function bo(t,e){let n=`projects/${t.id}/work/observations/`,r=await e.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 e.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 Ke(t,e){let r=(await bo(t,e)).flatMap(h=>h.observations).sort((h,k)=>{let E=h.occurredAt.localeCompare(k.occurredAt);if(E!==0)return E;let V=h.sequence-k.sequence;return V!==0?V:h.id.localeCompare(k.id)}),o=new Map,s=new Map,i,a,c,u,f,l=[],p=[],d=[],m=[],S=[],g=new Map,y=[],v=[],x=[],O=[],P=[],T=[];for(let h of r)switch(h.kind){case"request":i=h.text;break;case"activity":a=h.text;break;case"goal":c=h.text;break;case"plan":u=h.text;break;case"phase":o.set(h.key,vo(o.get(h.key),h));break;case"task":s.set(h.key,vo(s.get(h.key),h));break;case"decision":l.push(h.text);break;case"blocker":p.push(h.text);break;case"warning":d.push(h.text);break;case"next_action":m.push(h.text);break;case"file":{S.push(h.text);let k=h.fileAction??"active";g.delete(h.text),g.set(h.text,k),k==="modified"?y.push(h.text):k==="created"?v.push(h.text):k==="deleted"&&x.push(h.text);break}case"command":O.push(h.text);break;case"test":P.push(h.text),h.checkKind&&T.push({kind:h.checkKind,command:h.text,status:h.checkStatus??"unknown",updatedAt:h.occurredAt,agent:h.agent,nativeSessionId:h.nativeSessionId});break;case"session":f={agent:h.agent,nativeSessionId:h.nativeSessionId,sessionKey:h.sessionKey,updatedAt:h.occurredAt};break}let j=Array.from(o.values()).sort((h,k)=>(h.order??Number.MAX_SAFE_INTEGER)-(k.order??Number.MAX_SAFE_INTEGER)),b=Array.from(s.values()).sort((h,k)=>(h.order??Number.MAX_SAFE_INTEGER)-(k.order??Number.MAX_SAFE_INTEGER)),D=j.find(h=>h.status==="in_progress")??j.find(h=>h.status==="blocked")??j.find(h=>h.status==="pending"),z=b.find(h=>h.status==="in_progress")??b.find(h=>h.status==="blocked")??b.find(h=>h.status==="pending"),_t=L([...m,...z?[z.title]:[],...!z&&D?[D.title]:[],...b.filter(h=>h.status==="pending").slice(0,5).map(h=>h.title)],8),Kt=L([...p,...j.filter(h=>h.status==="blocked").map(h=>h.title),...b.filter(h=>h.status==="blocked").map(h=>h.title)],20),me={version:1,projectId:t.id,projectName:t.name,currentRequest:i,currentActivity:a,goal:c,plan:u,phases:j,tasks:b,decisions:L(l,20),blockers:Kt,warnings:L(d,20),nextActions:_t,filesTouched:L(S,30),activeFiles:Array.from(g.entries()).filter(([,h])=>h!=="deleted").map(([h])=>h).slice(-5),modifiedFiles:L(y,30),createdFiles:L(v,30),deletedFiles:L(x,30),commands:L(O,20),tests:L(P,20),checks:xu(T,20),currentPhase:D,currentTask:z,progress:{phasesTotal:j.length,phasesCompleted:j.filter(h=>h.status==="completed").length,tasksTotal:b.length,tasksCompleted:b.filter(h=>h.status==="completed").length,blocked:j.filter(h=>h.status==="blocked").length+b.filter(h=>h.status==="blocked").length},lastSession:f,updatedAt:r.length?r[r.length-1].occurredAt:new Date().toISOString()},Fe=ko(t.rootPath,".toolnet","work");return bu(Fe,{recursive:!0}),R(ko(Fe,"current.json"),me),await e.put(`projects/${t.id}/work/current.json`,JSON.stringify(me,null,2)+`
52
+ `,"application/json"),me}async function St(t,e){if((await bo(t,e)).length>0)return Ke(t,e);let r=await e.getText(`projects/${t.id}/work/current.json`);if(!r)return null;try{return JSON.parse(r)}catch{return null}}function Eu(t,e){if(!Cu(t))return{events:[],nextOffset:e};let n=Pu(t).size,r=Number.isFinite(e)?Math.max(0,e):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let o=n-r,s=Buffer.alloc(o),i=Au(t,"r");try{Mu(i,s,0,o,r)}finally{Iu(i)}let a=s.toString("utf8"),c=a.lastIndexOf(`
53
53
  `);if(c<0)return{events:[],nextOffset:r};let u=a.slice(0,c+1);return{events:u.split(`
54
- `).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var dt=class{constructor(e){this.options=e;this.journal=new ut(e.storage)}options;journal;async learnNew(){let e=this.options.wal.loadState(),n=Number(e.sourceCursors["work.continuity.offset"]??0),r=su(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 s=ce(this.options.identity,r.events),o=!1,i=!1;return s.length>0&&(o=!!await this.journal.write(this.options.identity,s),o&&(await Oe(this.options.project,this.options.storage),i=!0)),this.options.wal.setSourceCursor("work.continuity.offset",r.nextOffset),{scannedEvents:r.events.length,observations:s.length,journalWritten:o,reconciled:i,nextOffset:r.nextOffset}}};import{closeSync as fu,existsSync as mu,openSync as gu,readSync as yu,statSync as hu}from"node:fs";var ou=new Set(["content","text","message","prompt","summary","description","title","reason","last_assistant_message","lastAssistantMessage"]);function ue(t){return t.normalize("NFKC").replace(/\s+/g," ").replace(/^[\s>*#•-]+/u,"").trim()}function nn(t,e,n=0){if(!(n>6)){if(typeof t=="string"){e.push(t);return}if(Array.isArray(t)){for(let r of t.slice(0,50))nn(r,e,n+1);return}if(!(!t||typeof t!="object"))for(let[r,s]of Object.entries(t))(ou.has(r)||["data","payload","parts","messages"].includes(r))&&nn(s,e,n+1)}}function N(t,e,n,r,s,o=.95){let i=ue(r);return{version:1,id:v([t.projectId,n,s.type,s.key??"",i.toLowerCase(),e.id].join("|")).slice(0,32),projectId:t.projectId,kind:n,value:i,scope:s.type,scopeKey:s.key,scopeOrder:s.order,confidence:o,evidence:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,eventId:e.id,sourceEventId:e.sourceEventId,sequence:e.sequence,occurredAt:e.timestamp}}}function F(t,e){let n=t.toLowerCase();for(let r of e){let s=r.toLowerCase();if(n.startsWith(`${s}:`)||n.startsWith(`${s} -`)||n.startsWith(`${s} \u2014`))return ue(t.slice(r.length+1))}return null}function iu(t){let e=t.trimStart();return e.startsWith("- ")||e.startsWith("* ")||/^\d+[.)]\s+/u.test(e)}function au(t){return ue(t.trim().replace(/^[-*]\s+/u,"").replace(/^\d+[.)]\s+/u,""))}function is(t,e){let n=[],r=new Set;function s(o){!o.value||o.value.length<3||r.has(o.id)||(r.add(o.id),n.push(o))}for(let o of e){let i=[];nn(o.data,i);for(let a of i){let c={type:"project"},u=null;for(let p of a.split(/\r?\n/u)){let l=ue(p);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 d=l.match(/^(?:todo|task|việc)\s*(\d+)\s*(?:[:\-–—]\s*)?(.*)$/iu);if(d){let w=Number(d[1]);c={type:"task",key:`task:${w}`,order:w,title:ue(d[2]??"")},u=null;continue}let g=F(l,["mission","s\u1EE9 m\u1EC7nh","m\u1EE5c ti\xEAu t\u1ED5ng th\u1EC3","m\u1EE5c ti\xEAu project","project goal"]);if(g){s(N(t,o,"mission",g,{type:"project"},.99)),u=null;continue}let S=F(l,["current objective","active objective","m\u1EE5c ti\xEAu hi\u1EC7n t\u1EA1i","objective","m\u1EE5c ti\xEAu","m\u1EE5c \u0111\xEDch"]);if(S){s(N(t,o,c.type==="phase"?"phase_objective":"objective",S,c,.98)),u=null;continue}let y=F(l,["why","why this","why this phase","reason","rationale","v\xEC sao","l\xFD do","t\u1EA1i sao","\xFD ngh\u0129a"]);if(y){s(N(t,o,c.type==="phase"?"phase_why":"why",y,c,.98)),u=null;continue}let h=F(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){s(N(t,o,"desired_outcome",h,{type:"project"},.98)),u=null;continue}let k=F(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){s(N(t,o,"plan_rationale",k,{type:"project"},.98)),u=null;continue}let P=F(l,["deliverable","output","k\u1EBFt qu\u1EA3 c\u1EA7n \u0111\u1EA1t","ph\u1EA3i t\u1EA1o ra","\u0111\u1EA7u ra"]);if(P){s(N(t,o,"phase_deliverable",P,c,.97)),u=null;continue}let E=F(l,["acceptance criteria","definition of done","done khi","ho\xE0n th\xE0nh khi","ti\xEAu ch\xED ho\xE0n th\xE0nh"]);if(E){s(N(t,o,"acceptance_criterion",E,c,.98)),u="acceptance_criterion";continue}let M=F(l,["depends on","dependency","dependencies","ph\u1EE5 thu\u1ED9c","c\u1EA7n c\xF3 tr\u01B0\u1EDBc"]);if(M){s(N(t,o,"dependency",M,c,.97)),u="dependency";continue}let O=F(l,["open question","open questions","c\xE2u h\u1ECFi m\u1EDF","ch\u01B0a quy\u1EBFt \u0111\u1ECBnh","ch\u01B0a r\xF5"]);if(O){s(N(t,o,"open_question",O,c,.95)),u="open_question";continue}let x=F(l,["constraint","constraints","r\xE0ng bu\u1ED9c","gi\u1EDBi h\u1EA1n"]);if(x){s(N(t,o,"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&&iu(p)){s(N(t,o,u,au(p),c,.96));continue}u=null}}}return n}function as(t){return String(t).padStart(12,"0")}var pt=class{constructor(e){this.storage=e}storage;async write(e,n){if(n.length===0)return null;let r=Math.min(...n.map(u=>u.evidence.sequence)),s=Math.max(...n.map(u=>u.evidence.sequence)),o={version:1,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,firstSequence:r,lastSequence:s,createdAt:new Date().toISOString(),observations:n},i=v(n.map(u=>u.id).sort().join("|")).slice(0,16),a=v(e.sessionKey).slice(0,12),c=[`projects/${e.projectId}`,"work","semantic","observations",`${as(r)}-${as(s)}-${a}-${i}.json`].join("/");return await this.storage.exists(c)||await this.storage.put(c,JSON.stringify(o,null,2)+`
55
- `,"application/json"),c}};import{mkdirSync as cu}from"node:fs";import{join as cs}from"node:path";function uu(t){return{value:t.value,confidence:t.confidence,evidence:t.evidence}}function lu(t,e){if(!e)return!0;let n=t.evidence.occurredAt.localeCompare(e.evidence.occurredAt);return n!==0?n>0:t.evidence.sessionKey===e.evidence.sessionKey?t.evidence.sequence>=e.evidence.sequence:t.confidence>=e.confidence}function H(t,e){return lu(e,t)?e:t}function V(t,e=30){let n=new Set,r=[];for(let s of t){let o=s.value.normalize("NFKC").toLowerCase().replace(/\s+/g," ").trim();!o||n.has(o)||(n.add(o),r.push(s))}return r.slice(-e)}async function du(t,e){let n=`projects/${t.id}/work/semantic/observations/`,r=await e.list(n),s=[];for(let o of r.filter(i=>i.key.endsWith(".json")).sort((i,a)=>i.key.localeCompare(a.key))){let i=await e.getText(o.key);if(i)try{let a=JSON.parse(i);a.version===1&&Array.isArray(a.observations)&&s.push(a)}catch{}}return s}function pu(t){return{key:t.scopeKey??`phase:${t.scopeOrder??0}`,order:t.scopeOrder??0,acceptanceCriteria:[],dependencies:[],openQuestions:[],constraints:[],notes:[]}}async function us(t,e){let r=(await du(t,e)).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)}),s,o,i,a,c,u=new Map,p=[],l=[],f=[];for(let S of r){let y=uu(S);if(S.scope==="phase"&&S.scopeKey){let h=u.get(S.scopeKey)??pu(S);switch(S.kind){case"phase_objective":h.objective=H(h.objective,y);break;case"phase_why":h.why=H(h.why,y);break;case"phase_deliverable":h.deliverable=H(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":s=H(s,y);break;case"objective":o=H(o,y);break;case"why":i=H(i,y);break;case"desired_outcome":a=H(a,y);break;case"plan_rationale":c=H(c,y);break;case"open_question":p.push(y);break;case"constraint":l.push(y);break;case"note":f.push(y);break}}for(let S of u.values())S.acceptanceCriteria=V(S.acceptanceCriteria,20),S.dependencies=V(S.dependencies,15),S.openQuestions=V(S.openQuestions,15),S.constraints=V(S.constraints,15),S.notes=V(S.notes,20);let d={version:1,projectId:t.id,projectName:t.name,mission:s,activeObjective:o,why:i,desiredOutcome:a,planRationale:c,phases:Array.from(u.values()).sort((S,y)=>S.order-y.order),openQuestions:V(p,20),constraints:V(l,20),notes:V(f,20),updatedAt:r.length?r[r.length-1].evidence.occurredAt:new Date().toISOString()},g=cs(t.rootPath,".toolnet","work");return cu(g,{recursive:!0}),T(cs(g,"semantic-current.json"),d),await e.put(`projects/${t.id}/work/semantic/current.json`,JSON.stringify(d,null,2)+`
56
- `,"application/json"),d}async function ls(t,e){let n=await e.getText(`projects/${t.id}/work/semantic/current.json`);if(!n)return null;try{return JSON.parse(n)}catch{return null}}function Su(t,e){if(!mu(t))return{events:[],nextOffset:e};let n=hu(t).size,r=Number.isFinite(e)?Math.max(0,e):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let s=Buffer.alloc(n-r),o=gu(t,"r");try{yu(o,s,0,s.length,r)}finally{fu(o)}let i=s.toString("utf8"),a=i.lastIndexOf(`
54
+ `).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var kt=class{constructor(e){this.options=e;this.journal=new ht(e.storage)}options;journal;async learnNew(){let e=this.options.wal.loadState(),n=Number(e.sourceCursors["work.continuity.offset"]??0),r=Eu(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=pe(this.options.identity,r.events),s=!1,i=!1;return o.length>0&&(s=!!await this.journal.write(this.options.identity,o),s&&(await Ke(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 Fu,existsSync as Wu,openSync as Du,readSync as zu,statSync as qu}from"node:fs";var Ou=new Set(["content","text","message","prompt","summary","description","title","reason","last_assistant_message","lastAssistantMessage"]);function fe(t){return t.normalize("NFKC").replace(/\s+/g," ").replace(/^[\s>*#•-]+/u,"").trim()}function pn(t,e,n=0){if(!(n>6)){if(typeof t=="string"){e.push(t);return}if(Array.isArray(t)){for(let r of t.slice(0,50))pn(r,e,n+1);return}if(!(!t||typeof t!="object"))for(let[r,o]of Object.entries(t))(Ou.has(r)||["data","payload","parts","messages"].includes(r))&&pn(o,e,n+1)}}function _(t,e,n,r,o,s=.95){let i=fe(r);return{version:1,id:w([t.projectId,n,o.type,o.key??"",i.toLowerCase(),e.id].join("|")).slice(0,32),projectId:t.projectId,kind:n,value:i,scope:o.type,scopeKey:o.key,scopeOrder:o.order,confidence:s,evidence:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,eventId:e.id,sourceEventId:e.sourceEventId,sequence:e.sequence,occurredAt:e.timestamp}}}function F(t,e){let n=t.toLowerCase();for(let r of e){let o=r.toLowerCase();if(n.startsWith(`${o}:`)||n.startsWith(`${o} -`)||n.startsWith(`${o} \u2014`))return fe(t.slice(r.length+1))}return null}function Tu(t){let e=t.trimStart();return e.startsWith("- ")||e.startsWith("* ")||/^\d+[.)]\s+/u.test(e)}function Ru(t){return fe(t.trim().replace(/^[-*]\s+/u,"").replace(/^\d+[.)]\s+/u,""))}function xo(t,e){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 e){let i=[];pn(s.data,i);for(let a of i){let c={type:"project"},u=null;for(let f of a.split(/\r?\n/u)){let l=fe(f);if(!l){u=null;continue}let p=l.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 d=l.match(/^(?:todo|task|việc)\s*(\d+)\s*(?:[:\-–—]\s*)?(.*)$/iu);if(d){let b=Number(d[1]);c={type:"task",key:`task:${b}`,order:b,title:fe(d[2]??"")},u=null;continue}let m=F(l,["mission","s\u1EE9 m\u1EC7nh","m\u1EE5c ti\xEAu t\u1ED5ng th\u1EC3","m\u1EE5c ti\xEAu project","project goal"]);if(m){o(_(t,s,"mission",m,{type:"project"},.99)),u=null;continue}let S=F(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(_(t,s,c.type==="phase"?"phase_objective":"objective",S,c,.98)),u=null;continue}let g=F(l,["why","why this","why this phase","reason","rationale","v\xEC sao","l\xFD do","t\u1EA1i sao","\xFD ngh\u0129a"]);if(g){o(_(t,s,c.type==="phase"?"phase_why":"why",g,c,.98)),u=null;continue}let y=F(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(y){o(_(t,s,"desired_outcome",y,{type:"project"},.98)),u=null;continue}let v=F(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(v){o(_(t,s,"plan_rationale",v,{type:"project"},.98)),u=null;continue}let x=F(l,["deliverable","output","k\u1EBFt qu\u1EA3 c\u1EA7n \u0111\u1EA1t","ph\u1EA3i t\u1EA1o ra","\u0111\u1EA7u ra"]);if(x){o(_(t,s,"phase_deliverable",x,c,.97)),u=null;continue}let O=F(l,["acceptance criteria","definition of done","done khi","ho\xE0n th\xE0nh khi","ti\xEAu ch\xED ho\xE0n th\xE0nh"]);if(O){o(_(t,s,"acceptance_criterion",O,c,.98)),u="acceptance_criterion";continue}let P=F(l,["depends on","dependency","dependencies","ph\u1EE5 thu\u1ED9c","c\u1EA7n c\xF3 tr\u01B0\u1EDBc"]);if(P){o(_(t,s,"dependency",P,c,.97)),u="dependency";continue}let T=F(l,["open question","open questions","c\xE2u h\u1ECFi m\u1EDF","ch\u01B0a quy\u1EBFt \u0111\u1ECBnh","ch\u01B0a r\xF5"]);if(T){o(_(t,s,"open_question",T,c,.95)),u="open_question";continue}let j=F(l,["constraint","constraints","r\xE0ng bu\u1ED9c","gi\u1EDBi h\u1EA1n"]);if(j){o(_(t,s,"constraint",j,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&&Tu(f)){o(_(t,s,u,Ru(f),c,.96));continue}u=null}}}return n}function jo(t){return String(t).padStart(12,"0")}var vt=class{constructor(e){this.storage=e}storage;async write(e,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:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.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(e.sessionKey).slice(0,12),c=[`projects/${e.projectId}`,"work","semantic","observations",`${jo(r)}-${jo(o)}-${a}-${i}.json`].join("/");return await this.storage.exists(c)||await this.storage.put(c,JSON.stringify(s,null,2)+`
55
+ `,"application/json"),c}};import{mkdirSync as Nu}from"node:fs";import{join as Io}from"node:path";function _u(t){return{value:t.value,confidence:t.confidence,evidence:t.evidence}}function Ku(t,e){if(!e)return!0;let n=t.evidence.occurredAt.localeCompare(e.evidence.occurredAt);return n!==0?n>0:t.evidence.sessionKey===e.evidence.sessionKey?t.evidence.sequence>=e.evidence.sequence:t.confidence>=e.confidence}function G(t,e){return Ku(e,t)?e:t}function U(t,e=30){let n=new Set,r=[];for(let o of t){let s=o.value.normalize("NFKC").toLowerCase().replace(/\s+/g," ").trim();!s||n.has(s)||(n.add(s),r.push(o))}return r.slice(-e)}async function $u(t,e){let n=`projects/${t.id}/work/semantic/observations/`,r=await e.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 e.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 Lu(t){return{key:t.scopeKey??`phase:${t.scopeOrder??0}`,order:t.scopeOrder??0,acceptanceCriteria:[],dependencies:[],openQuestions:[],constraints:[],notes:[]}}async function Co(t,e){let r=(await $u(t,e)).flatMap(S=>S.observations).sort((S,g)=>{let y=S.evidence.occurredAt.localeCompare(g.evidence.occurredAt);return y!==0?y: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,f=[],l=[],p=[];for(let S of r){let g=_u(S);if(S.scope==="phase"&&S.scopeKey){let y=u.get(S.scopeKey)??Lu(S);switch(S.kind){case"phase_objective":y.objective=G(y.objective,g);break;case"phase_why":y.why=G(y.why,g);break;case"phase_deliverable":y.deliverable=G(y.deliverable,g);break;case"acceptance_criterion":y.acceptanceCriteria.push(g);break;case"dependency":y.dependencies.push(g);break;case"open_question":y.openQuestions.push(g);break;case"constraint":y.constraints.push(g);break;case"note":y.notes.push(g);break}u.set(y.key,y);continue}switch(S.kind){case"mission":o=G(o,g);break;case"objective":s=G(s,g);break;case"why":i=G(i,g);break;case"desired_outcome":a=G(a,g);break;case"plan_rationale":c=G(c,g);break;case"open_question":f.push(g);break;case"constraint":l.push(g);break;case"note":p.push(g);break}}for(let S of u.values())S.acceptanceCriteria=U(S.acceptanceCriteria,20),S.dependencies=U(S.dependencies,15),S.openQuestions=U(S.openQuestions,15),S.constraints=U(S.constraints,15),S.notes=U(S.notes,20);let d={version:1,projectId:t.id,projectName:t.name,mission:o,activeObjective:s,why:i,desiredOutcome:a,planRationale:c,phases:Array.from(u.values()).sort((S,g)=>S.order-g.order),openQuestions:U(f,20),constraints:U(l,20),notes:U(p,20),updatedAt:r.length?r[r.length-1].evidence.occurredAt:new Date().toISOString()},m=Io(t.rootPath,".toolnet","work");return Nu(m,{recursive:!0}),R(Io(m,"semantic-current.json"),d),await e.put(`projects/${t.id}/work/semantic/current.json`,JSON.stringify(d,null,2)+`
56
+ `,"application/json"),d}async function Ao(t,e){let n=await e.getText(`projects/${t.id}/work/semantic/current.json`);if(!n)return null;try{return JSON.parse(n)}catch{return null}}function Vu(t,e){if(!Wu(t))return{events:[],nextOffset:e};let n=qu(t).size,r=Number.isFinite(e)?Math.max(0,e):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let o=Buffer.alloc(n-r),s=Du(t,"r");try{zu(s,o,0,o.length,r)}finally{Fu(s)}let i=o.toString("utf8"),a=i.lastIndexOf(`
57
57
  `);if(a<0)return{events:[],nextOffset:r};let c=i.slice(0,a+1);return{events:c.split(`
58
- `).filter(Boolean).flatMap(u=>{try{return[JSON.parse(u)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(c,"utf8")}}var ft=class{constructor(e){this.options=e;this.journal=new pt(e.storage)}options;journal;async learnNew(){let e=this.options.wal.loadState(),n=Number(e.sourceCursors["work.semantic.offset"]??0),r=Su(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 s=is(this.options.identity,r.events),o=!1,i=!1;return s.length>0&&(o=!!await this.journal.write(this.options.identity,s),o&&(await us(this.options.project,this.options.storage),i=!0)),this.options.wal.setSourceCursor("work.semantic.offset",r.nextOffset),{scannedEvents:r.events.length,observations:s.length,journalWritten:o,reconciled:i,nextOffset:r.nextOffset}}};import{existsSync as dl,mkdirSync as pl}from"node:fs";import{join as sn}from"node:path";import{existsSync as fs,mkdirSync as ku,readFileSync as vu,statSync as ds,writeFileSync as wu}from"node:fs";import{dirname as bu,join as xu}from"node:path";var ps=64*1024,ju=`# ToolNet Project Operating Manual
58
+ `).filter(Boolean).flatMap(u=>{try{return[JSON.parse(u)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(c,"utf8")}}var wt=class{constructor(e){this.options=e;this.journal=new vt(e.storage)}options;journal;async learnNew(){let e=this.options.wal.loadState(),n=Number(e.sourceCursors["work.semantic.offset"]??0),r=Vu(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=xo(this.options.identity,r.events),s=!1,i=!1;return o.length>0&&(s=!!await this.journal.write(this.options.identity,o),s&&(await Co(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 $l,mkdirSync as Ll}from"node:fs";import{join as mn}from"node:path";import{existsSync as Eo,mkdirSync as Hu,readFileSync as Bu,statSync as Mo,writeFileSync as Ju}from"node:fs";import{dirname as Gu,join as Uu}from"node:path";var Po=64*1024,Yu=`# ToolNet Project Operating Manual
59
59
 
60
60
  This file contains persistent instructions for AI agents working on this project.
61
61
 
@@ -98,52 +98,52 @@ Things an AI agent should always remember.
98
98
  <!--
99
99
  - [advisory] Prefer small focused files.
100
100
  -->
101
- `;function mt(t){return xu(t.rootPath,".toolnet","PROJECT.md")}function Cu(t){return t.normalize("NFKC").replace(/\s+/g," ").trim()}function Iu(t){let e=[],n=new Set,r=/^\s*[-*]\s+\[(enforce|advisory)\]\s+(.+?)\s*$/gimu,s;for(;s=r.exec(t);){let o=s[1].toLowerCase(),i=Cu(s[2]);if(!i)continue;let a=`${o}:${i.toLowerCase()}`;n.has(a)||(n.add(a),e.push({id:v(a).slice(0,24),mode:o,text:i,source:"manual"}))}return e}function Au(t){let e=mt(t);return fs(e)||(ku(bu(e),{recursive:!0}),wu(e,ju,{encoding:"utf8",mode:384})),e}function gt(t,e=!1){let n=e?Au(t):mt(t);if(!fs(n))return null;if(ds(n).size>ps)throw new Error(`PROJECT.md exceeds ${ps} bytes`);let s=vu(n,"utf8");return{path:n,content:s,digest:v(s),rules:Iu(s),bytes:Buffer.byteLength(s,"utf8"),updatedAt:new Date(ds(n).mtimeMs).toISOString()}}import{randomUUID as Mu}from"node:crypto";import{closeSync as Pu,existsSync as ms,fsyncSync as Eu,mkdirSync as Ou,openSync as Tu,readFileSync as Ru,statSync as Nu,unlinkSync as gs,writeFileSync as _u}from"node:fs";import{dirname as $u,join as Ku}from"node:path";var Fu=new Int32Array(new SharedArrayBuffer(4));function Wu(t){t<=0||Atomics.wait(Fu,0,0,t)}function Lu(t){return Ku(t.rootPath,".toolnet","work",".current.lock")}function Du(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e?.code!=="ESRCH"}}function ys(t){if(!ms(t))return null;try{let e=JSON.parse(Ru(t,"utf8"));return e.version!==1||typeof e.token!="string"||typeof e.pid!="number"||typeof e.acquiredAt!="string"?null:{version:1,token:e.token,pid:e.pid,acquiredAt:e.acquiredAt}}catch{return null}}function zu(t){try{return Date.now()-Nu(t).mtimeMs}catch{return 0}}function qu(t,e){if(!ms(t)||zu(t)<e)return!1;let n=ys(t);return n?!Du(n.pid):!0}function Bu(t,e){if(!qu(t,e))return!1;try{return gs(t),!0}catch{return!1}}function Ju(t,e){let n={version:1,token:e,pid:process.pid,acquiredAt:new Date().toISOString()},r=Tu(t,"wx",384);try{_u(r,`${JSON.stringify(n,null,2)}
102
- `,{encoding:"utf8"}),Eu(r)}finally{Pu(r)}}function Hu(t,e){if(ys(t)?.token===e)try{gs(t)}catch{}}function Vu(t,e={}){let n=Math.max(100,e.timeoutMs??5e3),r=Math.max(5,e.retryMs??20),s=Math.max(n*2,e.staleMs??3e4),o=Lu(t);Ou($u(o),{recursive:!0});let i=Mu(),a=Date.now()+n;for(;;)try{Ju(o,i);let c=!1;return()=>{c||(c=!0,Hu(o,i))}}catch(c){if(c?.code!=="EEXIST")throw c;if(Bu(o,s))continue;if(Date.now()>=a)throw new Error(`Timed out acquiring project work lock: ${o}`);Wu(r)}}function hs(t,e,n={}){let r=Vu(t,n);try{return e()}finally{r()}}import{closeSync as Gu,existsSync as Uu,fsyncSync as Yu,mkdirSync as Xu,openSync as Qu,readFileSync as Zu,renameSync as el,writeFileSync as tl}from"node:fs";import{dirname as nl,join as rl}from"node:path";function sl(t,e){Xu(nl(t),{recursive:!0});let n=`${t}.tmp-${process.pid}-${Date.now()}`,r=Qu(n,"w",384);try{tl(r,`${JSON.stringify(e,null,2)}
103
- `,{encoding:"utf8"}),Yu(r)}finally{Gu(r)}el(n,t)}function xs(t){return rl(t.rootPath,".toolnet","work","current.json")}function rn(t){let e=xs(t);if(!Uu(e))return null;try{let n=JSON.parse(Zu(e,"utf8"));return n.version!==1||n.projectId!==t.id?null:n}catch{return null}}function yt(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function _(t,e,n){let r=[],s=new Set;for(let o of[...t,...e].reverse()){let i=yt(o);if(!(!i||s.has(i))&&(s.add(i),r.push(o),r.length>=n))break}return r.reverse()}function ol(t,e,n=20){let r=new Map;for(let s of[...t,...e]){let o=`${s.kind}|${yt(s.command)}`;r.delete(o),r.set(o,s)}return Array.from(r.values()).slice(-n)}function il(t){return t.kind==="phase"?/^Phase\s+\d+$/iu.test(t.text):t.kind==="task"?/^(?:TODO|Task|Việc)\s+\d+$/iu.test(t.text):!1}function Ss(t,e){let n=e.status??t?.status??"pending",r=n;t?.status==="completed"&&n!=="completed"&&(r="completed"),t&&n==="pending"&&(t.status==="in_progress"||t.status==="blocked")&&(r=t.status);let s=t&&il(e)?t.title:e.text;return{id:t?.id??e.id,title:s,status:r,order:e.order??t?.order,confidence:Math.max(t?.confidence??0,e.confidence),updatedAt:e.occurredAt,updatedBy:{agent:e.agent,nativeSessionId:e.nativeSessionId,eventId:e.eventId}}}function ks(t){let e=new Map;for(let n of t){let r=n.order!==void 0?`order:${n.order}`:yt(n.title);e.set(r,n)}return e}function vs(t){return t.order!==void 0?`order:${t.order}`:yt(t.key||t.text)}function ws(t){return Array.from(t).sort((e,n)=>{let r=e.order??Number.MAX_SAFE_INTEGER,s=n.order??Number.MAX_SAFE_INTEGER;return r!==s?r-s:e.updatedAt.localeCompare(n.updatedAt)})}function bs(t){return t.find(e=>e.status==="in_progress")??t.find(e=>e.status==="blocked")??t.find(e=>e.status==="pending")}function al(t,e){let n=rn(t),r=ks(n?.phases??[]),s=ks(n?.tasks??[]),o=n?.currentRequest,i=n?.currentActivity,a=n?.goal,c=n?.plan,u=n?.lastSession,p=[],l=[],f=[],d=[],g=[],S=[...n?.activeFiles??[]],y=[],h=[],k=[],P=[],E=[],M=[],O=[...e].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":o=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=vs(m);r.set(b,Ss(r.get(b),m));break}case"task":{let b=vs(m);s.set(b,Ss(s.get(b),m));break}case"decision":p.push(m.text);break;case"blocker":l.push(m.text);break;case"warning":f.push(m.text);break;case"next_action":d.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":P.push(m.text);break;case"test":E.push(m.text),m.checkKind&&M.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=ws(r.values()),w=ws(s.values()),L=bs(x),D=bs(w),At=_(n?.nextActions??[],[...d,...D?[D.title]:[],...!D&&L?[L.title]:[],...w.filter(m=>m.status==="pending").slice(0,5).map(m=>m.title)],8),Mt=_(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:t.id,projectName:t.name,currentRequest:o,currentActivity:i,goal:a,plan:c,phases:x,tasks:w,decisions:_(n?.decisions??[],p,20),blockers:Mt,warnings:_(n?.warnings??[],f,20),nextActions:At,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??[],P,20),tests:_(n?.tests??[],E,20),checks:ol(n?.checks??[],M,20),currentPhase:L,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 sl(xs(t),de),de}function ht(t,e){return hs(t,()=>al(t,e))}function A(t,e){let n=new Set,r=[];for(let s of t){let o=s.replace(/\s+/g," ").trim();if(!o)continue;let i=o.normalize("NFKC").toLowerCase();if(!n.has(i)&&(n.add(i),r.push(o),r.length>=e))break}return r}function js(t){if(t)return{id:t.id,title:t.title,status:t.status}}function cl(t,e=[]){let n=e.slice(-10);if(n.some(s=>s.status==="failed"))return"failing";if(n.some(s=>s.status==="passed"))return"passing";let r=t.slice(-10).join(`
104
- `).toLowerCase();return/(?:failed|failing|failure|error|✗|❌)/u.test(r)?"failing":/(?:passed|passing|green|success|✓|✅)/u.test(r)?"passing":"unknown"}function ul(t){return v(JSON.stringify(t))}function ll(t){let e=[];for(let n of t){if(!n)continue;let r=n.match(/https?:\/\/[^\s<>"'`)\]}]+/giu)??[];for(let s of r){let o=s.replace(/[.,;:!?]+$/gu,"").trim();o&&e.push(o)}}return A(e,30)}function Cs(t){let{project:e,identity:n,state:r}=t,s=r.activeFiles?.at(-1)??r.filesTouched.at(-1),o=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())),p=A(r.nextActions.filter(k=>!u.has(k.normalize("NFKC").toLowerCase().replace(/\s+/gu," ").trim())),10),l=A([...c,...p],15),f=A(r.tests.slice().reverse(),10),d=A([...(r.activeFiles??[]).slice().reverse(),...r.filesTouched.slice().reverse()],20),g={schema:"toolnet.handoff.v2",version:2,project:{id:e.id,name:e.name},source:{agent:n.agent,nativeSessionId:n.nativeSessionId,sessionKey:n.sessionKey,sequence:t.sequence,reason:t.reason},capturedAt:t.capturedAt??new Date().toISOString(),goal:r.goal,request:r.currentRequest,activity:r.currentActivity,current:{phase:js(r.currentPhase),task:js(r.currentTask),file:s},completed:{phases:A(o,20),tasks:A(i,30)},remaining:{phases:A(a,20),tasks:A(c,30),todos:l},nextAction:p[0],blockers:A(r.blockers.slice().reverse(),10),decisions:A(r.decisions.slice().reverse(),10),files:{current:s,recent:d,active:A(r.activeFiles??[],10),modified:A(r.modifiedFiles??[],20),created:A(r.createdFiles??[],20),deleted:A(r.deletedFiles??[],20)},tests:{status:cl(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:ll([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(t.attention??[],20),progress:r.progress},{capturedAt:S,source:y,...h}=g;return{...g,stateDigest:ul(h)}}function fl(t){return!!(t.currentRequest||t.currentActivity||t.goal||t.plan||t.phases.length>0||t.tasks.length>0||t.nextActions.length>0||t.blockers.length>0||t.decisions.length>0||t.filesTouched.length>0)}function Is(t,e,n,r,s){if(!fl(n))return null;let o=gt(t,!1),a=[...o?o.rules.filter(l=>l.mode==="enforce").map(l=>l.text):[],...n.warnings].slice(0,20),c=Cs({project:t,identity:e,state:n,reason:r,sequence:s,attention:a}),u=c.stateDigest;return{version:1,id:v([t.id,e.sessionKey,u].join("|")).slice(0,24),projectId:t.id,projectName:t.name,createdAt:new Date().toISOString(),reason:r,sourceSession:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,sequence:s},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 As(t,e){let n=sn(t.rootPath,".toolnet","work","handoffs");pl(n,{recursive:!0});let r=sn(n,`${e.id}.json`);dl(r)||T(r,e),T(sn(t.rootPath,".toolnet","work","handoff-latest.json"),e)}function Ms(t){let e=Is(t.project,t.identity,t.state,t.reason,t.sequence);return e?(As(t.project,e),e):null}var St=class{constructor(e){this.options=e}options;async capture(e,n){let r=rn(this.options.project);r||(r=await lt(this.options.project,this.options.storage)),r||(r=await Oe(this.options.project,this.options.storage));let s=Is(this.options.project,this.options.identity,r,e,n);if(!s)return null;As(this.options.project,s);let o=`projects/${this.options.project.id}/work/handoffs/${s.id}.json`;return await this.options.storage.exists(o)||await this.options.storage.put(o,JSON.stringify(s,null,2)+`
105
- `,"application/json"),await this.options.storage.put(`projects/${this.options.project.id}/work/handoff-latest.json`,JSON.stringify(s,null,2)+`
106
- `,"application/json"),s}};async function Ps(t,e){let n=await e.getText(`projects/${t.id}/work/handoff-latest.json`);if(!n)return null;try{return JSON.parse(n)}catch{return null}}import{existsSync as ml,readFileSync as gl,writeFileSync as yl}from"node:fs";import{join as hl}from"node:path";var Os="<!-- TOOLNET:STABLE-WORK:BEGIN -->",on="<!-- TOOLNET:STABLE-WORK:END -->";function an(t){switch(t.status){case"completed":return"[x]";case"in_progress":return"[~]";case"blocked":return"[!]";case"cancelled":return"[-]";default:return"[ ]"}}function W(t,e){return e.length?["",`${t}:`,...e.map(n=>`- ${n}`)]:[]}function Es(t,e){return e.length?["",`${t}:`,...e.map(n=>`- ${an(n)} ${n.title}`)]:[]}function Sl(t){let e=[Os,"# ToolNet Stable Work State","",`Updated: ${t.updatedAt}`];return t.lastSession&&e.push(`Last agent: ${t.lastSession.agent}`,`Last session: ${t.lastSession.nativeSessionId}`),t.currentRequest&&e.push("","Current request:",t.currentRequest),t.currentActivity&&e.push("","Current activity:",t.currentActivity),t.goal&&e.push("","Goal:",t.goal),t.plan&&e.push("","Plan:",t.plan),t.currentPhase&&e.push("","Current phase:",`${an(t.currentPhase)} ${t.currentPhase.title}`),t.currentTask&&e.push("","Current task:",`${an(t.currentTask)} ${t.currentTask.title}`),e.push(...Es("Phases",t.phases)),e.push(...Es("TODO / Tasks",t.tasks)),e.push(...W("Next actions",t.nextActions)),e.push(...W("Blockers",t.blockers)),e.push(...W("Important decisions",t.decisions)),e.push(...W("Active files",t.activeFiles??[])),e.push(...W("Modified files",t.modifiedFiles??[])),e.push(...W("Created files",t.createdFiles??[])),e.push(...W("Deleted files",t.deletedFiles??[])),e.push(...W("Files touched",t.filesTouched)),e.push(...W("Recent commands",t.commands??[])),e.push(...W("Checks",(t.checks??[]).map(n=>`[${n.status}] ${n.kind}: ${n.command}`))),e.push("","Progress:",`- Phases: ${t.progress.phasesCompleted}/${t.progress.phasesTotal}`,`- Tasks: ${t.progress.tasksCompleted}/${t.progress.tasksTotal}`,`- Blocked: ${t.progress.blocked}`,"","Continuation:","- Resume current unfinished task.","- Never redo completed TODO/Phase unless explicitly requested.","- Ask ToolNet Memory for deeper history only when necessary.",on),e.join(`
107
- `)}function kt(t,e){let n=hl(t.rootPath,".toolnet","current.md"),r="";if(ml(n))try{r=gl(n,"utf8")}catch{r=""}r=r.replace(/<!-- TOOLNET:AUTO-CURRENT:BEGIN -->[\s\S]*?<!-- TOOLNET:AUTO-CURRENT:END -->/gu,"");let s=Sl(e),o=r.indexOf(Os),i=r.indexOf(on),a;o>=0&&i>=o?a=[r.slice(0,o).trimEnd(),s,r.slice(i+on.length).trimStart()].filter(Boolean).join(`
101
+ `;function bt(t){return Uu(t.rootPath,".toolnet","PROJECT.md")}function Xu(t){return t.normalize("NFKC").replace(/\s+/g," ").trim()}function Qu(t){let e=[],n=new Set,r=/^\s*[-*]\s+\[(enforce|advisory)\]\s+(.+?)\s*$/gimu,o;for(;o=r.exec(t);){let s=o[1].toLowerCase(),i=Xu(o[2]);if(!i)continue;let a=`${s}:${i.toLowerCase()}`;n.has(a)||(n.add(a),e.push({id:w(a).slice(0,24),mode:s,text:i,source:"manual"}))}return e}function Zu(t){let e=bt(t);return Eo(e)||(Hu(Gu(e),{recursive:!0}),Ju(e,Yu,{encoding:"utf8",mode:384})),e}function xt(t,e=!1){let n=e?Zu(t):bt(t);if(!Eo(n))return null;if(Mo(n).size>Po)throw new Error(`PROJECT.md exceeds ${Po} bytes`);let o=Bu(n,"utf8");return{path:n,content:o,digest:w(o),rules:Qu(o),bytes:Buffer.byteLength(o,"utf8"),updatedAt:new Date(Mo(n).mtimeMs).toISOString()}}import{randomUUID as el}from"node:crypto";import{closeSync as tl,existsSync as Oo,fsyncSync as nl,mkdirSync as rl,openSync as ol,readFileSync as sl,statSync as il,unlinkSync as To,writeFileSync as al}from"node:fs";import{dirname as cl,join as ul}from"node:path";var ll=new Int32Array(new SharedArrayBuffer(4));function dl(t){t<=0||Atomics.wait(ll,0,0,t)}function pl(t){return ul(t.rootPath,".toolnet","work",".current.lock")}function fl(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e?.code!=="ESRCH"}}function Ro(t){if(!Oo(t))return null;try{let e=JSON.parse(sl(t,"utf8"));return e.version!==1||typeof e.token!="string"||typeof e.pid!="number"||typeof e.acquiredAt!="string"?null:{version:1,token:e.token,pid:e.pid,acquiredAt:e.acquiredAt}}catch{return null}}function ml(t){try{return Date.now()-il(t).mtimeMs}catch{return 0}}function gl(t,e){if(!Oo(t)||ml(t)<e)return!1;let n=Ro(t);return n?!fl(n.pid):!0}function yl(t,e){if(!gl(t,e))return!1;try{return To(t),!0}catch{return!1}}function hl(t,e){let n={version:1,token:e,pid:process.pid,acquiredAt:new Date().toISOString()},r=ol(t,"wx",384);try{al(r,`${JSON.stringify(n,null,2)}
102
+ `,{encoding:"utf8"}),nl(r)}finally{tl(r)}}function Sl(t,e){if(Ro(t)?.token===e)try{To(t)}catch{}}function kl(t,e={}){let n=Math.max(100,e.timeoutMs??5e3),r=Math.max(5,e.retryMs??20),o=Math.max(n*2,e.staleMs??3e4),s=pl(t);rl(cl(s),{recursive:!0});let i=el(),a=Date.now()+n;for(;;)try{hl(s,i);let c=!1;return()=>{c||(c=!0,Sl(s,i))}}catch(c){if(c?.code!=="EEXIST")throw c;if(yl(s,o))continue;if(Date.now()>=a)throw new Error(`Timed out acquiring project work lock: ${s}`);dl(r)}}function No(t,e,n={}){let r=kl(t,n);try{return e()}finally{r()}}import{closeSync as vl,existsSync as wl,fsyncSync as bl,mkdirSync as xl,openSync as jl,readFileSync as Il,renameSync as Cl,writeFileSync as Al}from"node:fs";import{dirname as Ml,join as Pl}from"node:path";function El(t,e){xl(Ml(t),{recursive:!0});let n=`${t}.tmp-${process.pid}-${Date.now()}`,r=jl(n,"w",384);try{Al(r,`${JSON.stringify(e,null,2)}
103
+ `,{encoding:"utf8"}),bl(r)}finally{vl(r)}Cl(n,t)}function Wo(t){return Pl(t.rootPath,".toolnet","work","current.json")}function fn(t){let e=Wo(t);if(!wl(e))return null;try{let n=JSON.parse(Il(e,"utf8"));return n.version!==1||n.projectId!==t.id?null:n}catch{return null}}function jt(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function K(t,e,n){let r=[],o=new Set;for(let s of[...t,...e].reverse()){let i=jt(s);if(!(!i||o.has(i))&&(o.add(i),r.push(s),r.length>=n))break}return r.reverse()}function Ol(t,e,n=20){let r=new Map;for(let o of[...t,...e]){let s=`${o.kind}|${jt(o.command)}`;r.delete(s),r.set(s,o)}return Array.from(r.values()).slice(-n)}function Tl(t){return t.kind==="phase"?/^Phase\s+\d+$/iu.test(t.text):t.kind==="task"?/^(?:TODO|Task|Việc)\s+\d+$/iu.test(t.text):!1}function _o(t,e){let n=e.status??t?.status??"pending",r=n;t?.status==="completed"&&n!=="completed"&&(r="completed"),t&&n==="pending"&&(t.status==="in_progress"||t.status==="blocked")&&(r=t.status);let o=t&&Tl(e)?t.title:e.text;return{id:t?.id??e.id,title:o,status:r,order:e.order??t?.order,confidence:Math.max(t?.confidence??0,e.confidence),updatedAt:e.occurredAt,updatedBy:{agent:e.agent,nativeSessionId:e.nativeSessionId,eventId:e.eventId}}}function Ko(t){let e=new Map;for(let n of t){let r=n.order!==void 0?`order:${n.order}`:jt(n.title);e.set(r,n)}return e}function $o(t){return t.order!==void 0?`order:${t.order}`:jt(t.key||t.text)}function Lo(t){return Array.from(t).sort((e,n)=>{let r=e.order??Number.MAX_SAFE_INTEGER,o=n.order??Number.MAX_SAFE_INTEGER;return r!==o?r-o:e.updatedAt.localeCompare(n.updatedAt)})}function Fo(t){return t.find(e=>e.status==="in_progress")??t.find(e=>e.status==="blocked")??t.find(e=>e.status==="pending")}function Rl(t,e){let n=fn(t),r=Ko(n?.phases??[]),o=Ko(n?.tasks??[]),s=n?.currentRequest,i=n?.currentActivity,a=n?.goal,c=n?.plan,u=n?.lastSession,f=[],l=[],p=[],d=[],m=[],S=[...n?.activeFiles??[]],g=[],y=[],v=[],x=[],O=[],P=[],T=[...e].sort((k,E)=>{let V=k.occurredAt.localeCompare(E.occurredAt);return V!==0?V: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=$o(k);r.set(E,_o(r.get(E),k));break}case"task":{let E=$o(k);o.set(E,_o(o.get(E),k));break}case"decision":f.push(k.text);break;case"blocker":l.push(k.text);break;case"warning":p.push(k.text);break;case"next_action":d.push(k.text);break;case"file":{m.push(k.text);let E=k.fileAction??"active",V=S.indexOf(k.text);V>=0&&S.splice(V,1),E!=="deleted"&&S.push(k.text),E==="modified"?g.push(k.text):E==="created"?y.push(k.text):E==="deleted"&&v.push(k.text);break}case"command":x.push(k.text);break;case"test":O.push(k.text),k.checkKind&&P.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 j=Lo(r.values()),b=Lo(o.values()),D=Fo(j),z=Fo(b),_t=K(n?.nextActions??[],[...d,...z?[z.title]:[],...!z&&D?[D.title]:[],...b.filter(k=>k.status==="pending").slice(0,5).map(k=>k.title)],8),Kt=K(n?.blockers??[],[...l,...j.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(),Fe={version:1,projectId:t.id,projectName:t.name,currentRequest:s,currentActivity:i,goal:a,plan:c,phases:j,tasks:b,decisions:K(n?.decisions??[],f,20),blockers:Kt,warnings:K(n?.warnings??[],p,20),nextActions:_t,filesTouched:K(n?.filesTouched??[],m,30),activeFiles:K([],S,5),modifiedFiles:K(n?.modifiedFiles??[],g,30),createdFiles:K(n?.createdFiles??[],y,30),deletedFiles:K(n?.deletedFiles??[],v,30),commands:K(n?.commands??[],x,20),tests:K(n?.tests??[],O,20),checks:Ol(n?.checks??[],P,20),currentPhase:D,currentTask:z,progress:{phasesTotal:j.length,phasesCompleted:j.filter(k=>k.status==="completed").length,tasksTotal:b.length,tasksCompleted:b.filter(k=>k.status==="completed").length,blocked:j.filter(k=>k.status==="blocked").length+b.filter(k=>k.status==="blocked").length},lastSession:u,updatedAt:me},h=ke(Fe);return El(Wo(t),h),h}function It(t,e){return No(t,()=>Rl(t,e))}function M(t,e){let n=new Set,r=[];for(let o of t){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>=e))break}return r}function Do(t){if(t)return{id:t.id,title:t.title,status:t.status}}function Nl(t,e=[]){let n=e.slice(-10);if(n.some(o=>o.status==="failed"))return"failing";if(n.some(o=>o.status==="passed"))return"passing";let r=t.slice(-10).join(`
104
+ `).toLowerCase();return/(?:failed|failing|failure|error|✗|❌)/u.test(r)?"failing":/(?:passed|passing|green|success|✓|✅)/u.test(r)?"passing":"unknown"}function _l(t){return w(JSON.stringify(t))}function Kl(t){let e=[];for(let n of t){if(!n)continue;let r=n.match(/https?:\/\/[^\s<>"'`)\]}]+/giu)??[];for(let o of r){let s=o.replace(/[.,;:!?]+$/gu,"").trim();s&&e.push(s)}}return M(e,30)}function zo(t){let{project:e,identity:n,state:r}=t,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())),f=M(r.nextActions.filter(v=>!u.has(v.normalize("NFKC").toLowerCase().replace(/\s+/gu," ").trim())),10),l=M([...c,...f],15),p=M(r.tests.slice().reverse(),10),d=M([...(r.activeFiles??[]).slice().reverse(),...r.filesTouched.slice().reverse()],20),m={schema:"toolnet.handoff.v2",version:2,project:{id:e.id,name:e.name},source:{agent:n.agent,nativeSessionId:n.nativeSessionId,sessionKey:n.sessionKey,sequence:t.sequence,reason:t.reason},capturedAt:t.capturedAt??new Date().toISOString(),goal:r.goal,request:r.currentRequest,activity:r.currentActivity,current:{phase:Do(r.currentPhase),task:Do(r.currentTask),file:o},completed:{phases:M(s,20),tasks:M(i,30)},remaining:{phases:M(a,20),tasks:M(c,30),todos:l},nextAction:f[0],blockers:M(r.blockers.slice().reverse(),10),decisions:M(r.decisions.slice().reverse(),10),files:{current:o,recent:d,active:M(r.activeFiles??[],10),modified:M(r.modifiedFiles??[],20),created:M(r.createdFiles??[],20),deleted:M(r.deletedFiles??[],20)},tests:{status:Nl(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:Kl([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(t.attention??[],20),progress:r.progress},{capturedAt:S,source:g,...y}=m;return{...m,stateDigest:_l(y)}}function Fl(t){return!!(t.currentRequest||t.currentActivity||t.goal||t.plan||t.phases.length>0||t.tasks.length>0||t.nextActions.length>0||t.blockers.length>0||t.decisions.length>0||t.filesTouched.length>0)}function qo(t,e,n,r,o){if(!Fl(n))return null;let s=xt(t,!1),a=[...s?s.rules.filter(l=>l.mode==="enforce").map(l=>l.text):[],...n.warnings].slice(0,20),c=zo({project:t,identity:e,state:n,reason:r,sequence:o,attention:a}),u=c.stateDigest;return{version:1,id:w([t.id,e.sessionKey,u].join("|")).slice(0,24),projectId:t.id,projectName:t.name,createdAt:new Date().toISOString(),reason:r,sourceSession:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.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 Vo(t,e){let n=mn(t.rootPath,".toolnet","work","handoffs");Ll(n,{recursive:!0});let r=mn(n,`${e.id}.json`);$l(r)||R(r,e),R(mn(t.rootPath,".toolnet","work","handoff-latest.json"),e)}function Ho(t){let e=qo(t.project,t.identity,t.state,t.reason,t.sequence);return e?(Vo(t.project,e),e):null}var Ct=class{constructor(e){this.options=e}options;async capture(e,n){let r=fn(this.options.project);r||(r=await St(this.options.project,this.options.storage)),r||(r=await Ke(this.options.project,this.options.storage));let o=qo(this.options.project,this.options.identity,r,e,n);if(!o)return null;Vo(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)+`
105
+ `,"application/json"),await this.options.storage.put(`projects/${this.options.project.id}/work/handoff-latest.json`,JSON.stringify(o,null,2)+`
106
+ `,"application/json"),o}};async function Bo(t,e){let n=await e.getText(`projects/${t.id}/work/handoff-latest.json`);if(!n)return null;try{return JSON.parse(n)}catch{return null}}import{existsSync as Wl,readFileSync as Dl,writeFileSync as zl}from"node:fs";import{join as ql}from"node:path";var Go="<!-- TOOLNET:STABLE-WORK:BEGIN -->",gn="<!-- TOOLNET:STABLE-WORK:END -->";function yn(t){switch(t.status){case"completed":return"[x]";case"in_progress":return"[~]";case"blocked":return"[!]";case"cancelled":return"[-]";default:return"[ ]"}}function W(t,e){return e.length?["",`${t}:`,...e.map(n=>`- ${n}`)]:[]}function Jo(t,e){return e.length?["",`${t}:`,...e.map(n=>`- ${yn(n)} ${n.title}`)]:[]}function Vl(t){let e=[Go,"# ToolNet Stable Work State","",`Updated: ${t.updatedAt}`];return t.lastSession&&e.push(`Last agent: ${t.lastSession.agent}`,`Last session: ${t.lastSession.nativeSessionId}`),t.currentRequest&&e.push("","Current request:",t.currentRequest),t.currentActivity&&e.push("","Current activity:",t.currentActivity),t.goal&&e.push("","Goal:",t.goal),t.plan&&e.push("","Plan:",t.plan),t.currentPhase&&e.push("","Current phase:",`${yn(t.currentPhase)} ${t.currentPhase.title}`),t.currentTask&&e.push("","Current task:",`${yn(t.currentTask)} ${t.currentTask.title}`),e.push(...Jo("Phases",t.phases)),e.push(...Jo("TODO / Tasks",t.tasks)),e.push(...W("Next actions",t.nextActions)),e.push(...W("Blockers",t.blockers)),e.push(...W("Important decisions",t.decisions)),e.push(...W("Active files",t.activeFiles??[])),e.push(...W("Modified files",t.modifiedFiles??[])),e.push(...W("Created files",t.createdFiles??[])),e.push(...W("Deleted files",t.deletedFiles??[])),e.push(...W("Files touched",t.filesTouched)),e.push(...W("Recent commands",t.commands??[])),e.push(...W("Checks",(t.checks??[]).map(n=>`[${n.status}] ${n.kind}: ${n.command}`))),e.push("","Progress:",`- Phases: ${t.progress.phasesCompleted}/${t.progress.phasesTotal}`,`- Tasks: ${t.progress.tasksCompleted}/${t.progress.tasksTotal}`,`- Blocked: ${t.progress.blocked}`,"","Continuation:","- Resume current unfinished task.","- Never redo completed TODO/Phase unless explicitly requested.","- Ask ToolNet Memory for deeper history only when necessary.",gn),e.join(`
107
+ `)}function At(t,e){let n=ql(t.rootPath,".toolnet","current.md"),r="";if(Wl(n))try{r=Dl(n,"utf8")}catch{r=""}r=r.replace(/<!-- TOOLNET:AUTO-CURRENT:BEGIN -->[\s\S]*?<!-- TOOLNET:AUTO-CURRENT:END -->/gu,"");let o=Vl(e),s=r.indexOf(Go),i=r.indexOf(gn),a;s>=0&&i>=s?a=[r.slice(0,s).trimEnd(),o,r.slice(i+gn.length).trimStart()].filter(Boolean).join(`
108
108
 
109
109
  `):a=r.trim()?`${r.trim()}
110
110
 
111
- ${s}`:s,yl(n,`${a.trim()}
112
- `,{encoding:"utf8",mode:384})}import{existsSync as kl,mkdirSync as vl,readFileSync as wl,renameSync as bl,writeFileSync as xl}from"node:fs";import{dirname as jl,join as Cl}from"node:path";function Ts(t){return Cl(t.rootPath,".toolnet","context","session-origin.json")}function Il(t,e){vl(jl(t),{recursive:!0});let n=`${t}.tmp-${process.pid}-${Date.now()}`;xl(n,`${JSON.stringify(e,null,2)}
113
- `,{encoding:"utf8",mode:384}),bl(n,t)}function vt(t,e){return[...t].filter(n=>n.kind===e).sort((n,r)=>{let s=n.occurredAt.localeCompare(r.occurredAt);return s!==0?s:n.sequence-r.sequence}).at(-1)}function wt(t,e){let n=vt(e.observations,"file"),r=vt(e.observations,"next_action"),s=vt(e.observations,"blocker"),o=vt(e.observations,"decision"),i={version:1,projectId:t.id,agent:e.agent,nativeSessionId:e.nativeSessionId,updatedAt:e.workState.updatedAt,currentRequest:e.workState.currentRequest,currentActivity:e.workState.currentActivity,currentTask:e.workState.currentTask?.title,currentPhase:e.workState.currentPhase?.title,lastTouchedFile:n?.text??e.workState.activeFiles?.at(-1)??e.workState.filesTouched.at(-1),latestNextAction:r?.text??e.workState.nextActions.at(-1),latestBlocker:s?.text??e.workState.blockers.at(-1),latestDecision:o?.text??e.workState.decisions.at(-1)};return Il(Ts(t),i),i}function Al(t){let e=Ts(t);if(!kl(e))return null;try{let n=JSON.parse(wl(e,"utf8"));return n.version!==1||n.projectId!==t.id?null:n}catch{return null}}function Rs(t){let e=Al(t);if(!e)return null;let n=["Previous session:",`- Agent: ${e.agent}`,`- Session: ${e.nativeSessionId}`];return e.currentRequest&&n.push(`- Current request: ${e.currentRequest}`),e.currentActivity&&n.push(`- Current activity: ${e.currentActivity}`),e.currentPhase&&n.push(`- Current phase: ${e.currentPhase}`),e.currentTask&&n.push(`- Current task: ${e.currentTask}`),e.lastTouchedFile&&n.push(`- Last touched file: ${e.lastTouchedFile}`),e.latestBlocker&&n.push(`- Blocker: ${e.latestBlocker}`),e.latestNextAction&&n.push(`- Next action: ${e.latestNextAction}`),e.latestDecision&&n.push(`- Important decision: ${e.latestDecision}`),n.join(`
114
- `)}import{existsSync as Ns,mkdirSync as Ml,readFileSync as Pl}from"node:fs";import{join as cn}from"node:path";function _s(t){return cn(t.rootPath,".toolnet","memory","checkpoints")}function $s(t){return cn(_s(t),"latest.json")}function El(t){let e=$s(t);if(!Ns(e))return null;try{let n=JSON.parse(Pl(e,"utf8"));return n.schema!=="toolnet.memory.checkpoint.v1"||n.project.id!==t.id?null:n}catch{return null}}function Ol(t){return["rule","architecture","decision","fix"].includes(t)}function Tl(t,e){return e.length===0?[]:Qe(t,e).candidates.filter(r=>Ol(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:t.agent,nativeSessionId:t.nativeSessionId}))}function Rl(t,e){let n=new Map;for(let r of[...t,...e]){let s=n.get(r.fingerprint);(!s||r.importanceScore>s.importanceScore)&&n.set(r.fingerprint,r)}return Array.from(n.values()).sort((r,s)=>s.importanceScore-r.importanceScore||s.createdAt.localeCompare(r.createdAt)).slice(0,80)}function Nl(t){return{request:t.currentRequest,activity:t.currentActivity,goal:t.goal,phase:t.currentPhase?{title:t.currentPhase.title,status:t.currentPhase.status}:void 0,task:t.currentTask?{title:t.currentTask.title,status:t.currentTask.status}:void 0,phases:t.phases.map(e=>({title:e.title,status:e.status})),tasks:t.tasks.map(e=>({title:e.title,status:e.status})),activeFiles:t.activeFiles??[],modifiedFiles:t.modifiedFiles??[],createdFiles:t.createdFiles??[],deletedFiles:t.deletedFiles??[],checks:t.checks??[],blockers:t.blockers,decisions:t.decisions,nextActions:t.nextActions}}function Ks(t,e,n,r){let s=El(t),o=Rl(s?.durableFacts??[],Tl(e,n)),i=n.at(-1)?.sequence??s?.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),p=r.tasks.filter(y=>y.status!=="completed"&&y.status!=="cancelled").map(y=>y.title),l={work:Nl(r),durableFacts:o.map(y=>y.fingerprint).sort()},f=v(JSON.stringify(l)).slice(0,32),d={schema:"toolnet.memory.checkpoint.v1",version:1,project:{id:t.id,name:t.name},source:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.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:p},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:o,stateDigest:f},g=_s(t);Ml(g,{recursive:!0,mode:448});let S=cn(g,`${f}.json`);return Ns(S)||T(S,d),T($s(t),d),d}function Fs(t,e,n){if(process.env.TOOLNET_LOCAL_CHECKPOINT==="0"||n.length===0)return{updated:!1,observations:0};let r=ce(e,n);if(r.length===0)return{updated:!1,observations:0};let s=ht(t,r);kt(t,s),wt(t,{agent:e.agent,nativeSessionId:e.nativeSessionId,observations:r,workState:s});try{Ks(t,e,n,s)}catch{}try{Ms({project:t,identity:e,state:s,reason:"continuous-checkpoint",sequence:n.at(-1)?.sequence??0})}catch{}return{updated:!0,observations:r.length}}var bt=class{identity;wal;remote;sanitizer=new G;learner;continuity;semantic;handoff;project;title;metadata;constructor(e){this.project=e.project,this.identity=Le(e.project,e.agent,e.nativeSessionId),this.title=e.title,this.metadata=this.sanitizer.sanitizeValue(e.metadata??{}),this.wal=new Ve(this.identity,e.eventContext),this.remote=new De(e.storage,e.maxEventsPerChunk??100,e.maxChunkBytes??512*1024),this.learner=new at({project:e.project,storage:e.storage,identity:this.identity,wal:this.wal}),this.continuity=new dt({project:e.project,storage:e.storage,identity:this.identity,wal:this.wal}),this.semantic=new ft({project:e.project,storage:e.storage,identity:this.identity,wal:this.wal}),this.handoff=new St({project:e.project,storage:e.storage,identity:this.identity})}sanitizeEvent(e){let n=e.provenance?{...e.provenance,metadata:this.sanitizer.sanitizeValue(e.provenance.metadata)}:void 0;return{...e,data:this.sanitizer.sanitizeValue(e.data??{}),provenance:n}}checkpointLocal(e){if(e.length!==0)try{Fs(this.project,this.identity,e)}catch{}}start(e={}){let n=this.wal.loadState();return this.record({type:n.lastSequence===0?"session_start":"session_resume",data:e,provenance:{source:this.identity.agent}})}record(e){let n=this.wal.append([this.sanitizeEvent(e)]);return this.checkpointLocal(n),n[0]}recordMany(e){let n=this.wal.append(e.map(r=>this.sanitizeEvent(r)));return this.checkpointLocal(n),n}setSourceCursor(e,n){this.wal.setSourceCursor(e,n)}async flush(){let e=this.wal.readPending(),n=this.wal.loadState(),r=await this.remote.append(this.identity,e.events,n.sourceCursors,{title:this.title,metadata:this.metadata});if(e.events.length>0){let s=e.events[e.events.length-1];this.wal.markRemote(s.sequence,e.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"&&e.events.length>0)try{let s=e.events[e.events.length-1],o=["session_idle","session_end","session_compact"].includes(s.type)?s.type:"checkpoint";await this.handoff.capture(o,s.sequence)}catch{}return r}async idle(e={}){return this.record({type:"session_idle",data:e,provenance:{source:this.identity.agent}}),this.flush()}async end(e={}){return this.record({type:"session_end",data:e,provenance:{source:this.identity.agent}}),this.flush()}status(){return this.wal.loadState()}recoverRemote(){return this.remote.recover(this.identity)}};import{existsSync as _l,readFileSync as $l,readdirSync as Kl,statSync as Ws}from"node:fs";import{homedir as Fl}from"node:os";import{join as xt,resolve as Ls}from"node:path";function Ds(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Wl(){return process.env.CODEX_HOME??xt(Fl(),".codex")}function Te(t){let e="";try{e=$l(t,"utf8").slice(0,128*1024)}catch{return{raw:{}}}for(let n of e.split(`
115
- `))if(n)try{let r=Ds(JSON.parse(n));if(r.type!=="session_meta")continue;let s=Ds(r.payload),o=[s.id,s.thread_id,s.threadId,s.session_id,s.sessionId].find(a=>typeof a=="string"),i=typeof s.cwd=="string"?s.cwd:void 0;return{threadId:o,cwd:i,raw:s}}catch{}return{raw:{}}}function un(t,e){if(!_l(t))return;let n;try{n=Kl(t,{withFileTypes:!0})}catch{return}for(let r of n){let s=xt(t,r.name);if(r.isDirectory()){un(s,e);continue}r.isFile()&&r.name.endsWith(".jsonl")&&e.push(s)}}function ln(){let t=Wl(),e=[];return un(xt(t,"sessions"),e),un(xt(t,"archived_sessions"),e),e.sort((n,r)=>{try{return Ws(r).mtimeMs-Ws(n).mtimeMs}catch{return 0}})}function dn(t){let e=ln(),n=e.find(r=>r.includes(t));if(n)return n;for(let r of e)if(Te(r).threadId===t)return r;return null}function jt(t,e){let n=Ls(t),r=Ls(e);return r===n||r.startsWith(n+"/")||n.startsWith(r+"/")}import{closeSync as Ll,existsSync as Dl,openSync as zl,readSync as ql,statSync as Bl}from"node:fs";function zs(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Jl(t){let e=t.timestamp;if(typeof e=="string"){let n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return new Date().toISOString()}function Hl(t){let e=typeof t.type=="string"?t.type.toLowerCase():"",n=zs(t.payload),r=typeof n.type=="string"?n.type.toLowerCase():"",s=typeof n.role=="string"?n.role.toLowerCase():void 0;return e==="session_meta"?{type:"custom"}:s==="user"||r==="user_message"?{type:"user_prompt",role:"user"}:s==="assistant"||r==="agent_message"||r==="assistant_message"?{type:"assistant_message",role:"assistant"}:r.includes("function_call")||r.includes("tool_call")||r.includes("exec_command_begin")||r.includes("exec_command_start")?{type:"tool_call"}:r.includes("function_call_output")||r.includes("tool_result")||r.includes("exec_command_end")||r.includes("exec_command_complete")?{type:"tool_result"}:r.includes("error")?{type:"error"}:e.includes("compacted")||r.includes("compacted")?{type:"session_compact"}:{type:"custom",role:s}}function qs(t,e=0){if(!Dl(t))return{events:[],nextOffset:e,reset:!1};let n=Bl(t).size,r=e>n,s=r?0:e;if(s>=n)return{events:[],nextOffset:n,reset:r};let o=n-s,i=Buffer.alloc(o),a=zl(t,"r");try{ql(a,i,0,o,s)}finally{Ll(a)}let c=i.toString("utf8"),u=c.lastIndexOf(`
116
- `);if(u<0)return{events:[],nextOffset:s,reset:r};let p=c.slice(0,u+1),l=0,f=[];for(let d of p.split(`
117
- `)){if(!d)continue;let g=Buffer.byteLength(d+`
118
- `,"utf8"),S=s+l;l+=g;let y;try{y=JSON.parse(d)}catch{continue}let h=zs(y),k=Hl(h);f.push({type:k.type,timestamp:Jl(h),role:k.role,sourceEventId:`rollout:${S}`,sourceSequence:S,data:h,provenance:{source:"codex-rollout",sourcePath:t,sourceOffset:S}})}return{events:f,nextOffset:s+Buffer.byteLength(p,"utf8"),reset:r}}var Vl=[/^<SYSTEM MESSAGE>/i,/^<EPHEMERAL MESSAGE>/i,/^<system>/i,/^<ephemeral>/i,/^ManageTask:/i,/^Task \d+ status:/i,/^Task \d+ killed/i,/^Task \d+ loading/i,/^Thought for \d+ tokens/i,/^Prioritizing Tool Usage/i,/^Tool call:/i,/^Tool response:/i,/^npm notice/i,/^npm WARN/i,/^added \d+ packages/i,/^removed \d+ packages/i,/^up to date/i,/^\d+ packages are looking for funding/i,/^run `npm fund` for details/i,/^[\d.]+%/,/^\[={10,}\]/,/^Loading\.\.\./i,/^Processing\.\.\./i,/^bash-\d+\.\d+\$/,/^\$ /,/^\s*$/],Gl=[/api[_-]?key[:\s=]+[^\s]+/gi,/token[:\s=]+[^\s]+/gi,/secret[:\s=]+[^\s]+/gi,/password[:\s=]+[^\s]+/gi,/bearer\s+[^\s]+/gi,/authorization:\s*[^\s]+/gi],Ul=["decision","decided","rule","convention","architecture","pattern","fixed","resolved","implemented","created","updated","deleted","deployed","blocker","blocked","issue","bug","error","next","todo","action","requirement","must","should","important"];function Yl(t){let e=t.toLowerCase();return Ul.some(n=>e.includes(n))}function Xl(t){if(!t.trim())return!0;for(let e of Vl)if(e.test(t))return!0;return Yl(t),!1}function Ql(t){let e=t;for(let n of Gl)e=e.replace(n,r=>{let s=r.split(/[:\s=]+/);return s.length>1?`${s[0]}: [REDACTED]`:"[REDACTED]"});return e}function pn(t){let e=t.trim();return e?Xl(e)?{content:"",filtered:!0,reason:"noise"}:{content:Ql(e),filtered:!1}:{content:"",filtered:!0,reason:"empty"}}function Ct(t){let e={};for(let[n,r]of Object.entries(t))if(typeof r=="string"){let s=pn(r);s.filtered||(e[n]=s.content)}else r&&typeof r=="object"&&!Array.isArray(r)?e[n]=Ct(r):Array.isArray(r)?e[n]=r.map(s=>{if(typeof s=="string"){let o=pn(s);return o.filtered?null:o.content}return s&&typeof s=="object"?Ct(s):s}).filter(s=>s!==null):e[n]=r;return e}function Bs(t){let e=typeof t.type=="string"?t.type.toLowerCase():"";if(e.includes("system")||e.includes("ephemeral")||e==="tool_call"&&!t.result)return!0;if(t.data&&typeof t.data=="object"){let n=t.data,r=typeof n.content=="string"?n.content:"";if(r&&pn(r).filtered)return!0}return!1}async function Re(t){let e=t.threadId.trim();if(!e)throw new Error("Codex thread ID is required");let n=Te(t.rolloutPath),r=t.cwd??n.cwd;if(r&&!jt(t.project.rootPath,r))throw new Error(`Codex thread does not belong to project: ${r}`);if(n.threadId&&n.threadId!==e)throw new Error(`Codex rollout thread mismatch: expected ${e}, got ${n.threadId}`);let s=new bt({project:t.project,storage:t.storage,agent:"codex",nativeSessionId:e,metadata:{source:"codex-rollout",rolloutPath:t.rolloutPath,cwd:r,client:t.client},eventContext:{source:"codex",cwd:r??t.project.rootPath,turnId:t.turnId}}),o=s.status(),i=o.sourceCursors["codex.rollout.path"],a=Number(o.sourceCursors["codex.rollout.offset"]??0);i&&i!==t.rolloutPath&&(a=0),(!Number.isFinite(a)||a<0)&&(a=0);let c=qs(t.rolloutPath,a),u=[];o.lastSequence===0&&u.push({type:"session_start",sourceEventId:`codex:${e}:start`,data:{threadId:e,cwd:r,rolloutPath:t.rolloutPath,sessionMeta:n.raw},provenance:{source:"codex-rollout",sourcePath:t.rolloutPath}}),i&&i!==t.rolloutPath&&u.push({type:"custom",sourceEventId:`codex:${e}:rollout-rotation:${t.rolloutPath}`,data:{event:"rollout_rotation",previousPath:i,rolloutPath:t.rolloutPath},provenance:{source:"codex-rollout"}}),c.reset&&u.push({type:"custom",sourceEventId:`codex:${e}:rollout-reset:${c.nextOffset}`,data:{event:"rollout_reset"},provenance:{source:"codex-rollout",sourcePath:t.rolloutPath}});let p=c.events.filter(d=>!Bs(d.data)).map(d=>({...d,data:Ct(d.data)}));if(u.push(...p),p.length>0)try{let d=Le(t.project,"codex",e),g=p.map((h,k)=>({version:1,id:`codex-work-${e}-${h.sourceSequence??k}`,sequence:k+1,projectId:t.project.id,agent:"codex",nativeSessionId:e,type:h.type,timestamp:h.timestamp??new Date().toISOString(),role:h.role,sourceEventId:h.sourceEventId,sourceSequence:h.sourceSequence,data:h.data??{},provenance:h.provenance??{}})),S=ce(d,g),y=ht(t.project,S);kt(t.project,y),wt(t.project,{agent:"codex",nativeSessionId:e,observations:S,workState:y})}catch{}t.idle&&t.turnId&&u.push({type:"session_idle",sourceEventId:`codex:${e}:turn:${t.turnId}:idle`,data:{turnId:t.turnId,client:t.client},provenance:{source:"codex-notify"}});let l=s.recordMany(u);if(s.setSourceCursor("codex.rollout.path",t.rolloutPath),s.setSourceCursor("codex.rollout.offset",c.nextOffset),t.turnId&&s.setSourceCursor("codex.last.turn",t.turnId),t.idle&&p.length>0)try{let d=p.map(S=>JSON.stringify(S.data)),g=Xe(d,e);s.setSourceCursor("codex.session.summary",g.summary),s.setSourceCursor("codex.session.facts_count",g.durableFacts.length),or()&&!cr()&&s.setSourceCursor("codex.raw_transcript.archived","local")}catch{}let f=await s.flush();return{threadId:e,imported:l.length,rolloutEvents:c.events.length,eventCount:f.eventCount,chunkCount:f.chunkCount,status:f.status,rolloutOffset:c.nextOffset,reset:c.reset}}import{existsSync as Zl}from"node:fs";import{dirname as ed,join as td,parse as nd,resolve as rd}from"node:path";function Js(t){let e=rd(t),n=nd(e).root;for(;;){if(Zl(td(e,".toolnet","project.json")))return new ne().detect(e);if(e===n)break;let r=ed(e);if(r===e)break;e=r}return null}async function Hs(t,e,n=100){let r=[];for(let s of ln()){let o=Te(s);if(!(!o.threadId||!o.cwd)&&jt(t.rootPath,o.cwd)&&(r.push(await Re({project:t,storage:e,threadId:o.threadId,rolloutPath:s,cwd:o.cwd})),r.length>=n))break}return r}import{existsSync as sd,mkdirSync as Vs,readFileSync as od,writeFileSync as Gs}from"node:fs";import{homedir as Us}from"node:os";import{dirname as Ys,join as fn}from"node:path";function id(t){let e=[],n=/"((?:\\.|[^"\\])*)"|'([^']*)'/g,r;for(;r=n.exec(t);){let s=r[1]??r[2]??"";try{e.push(r[1]!==void 0?JSON.parse(`"${s}"`):s)}catch{e.push(s)}}return e}function Xs(t={}){let e=t.configFile??fn(process.env.CODEX_HOME??fn(Us(),".codex"),"config.toml"),n=t.previousFile??fn(Us(),".config","toolnet-memory","codex-notify-previous.json");Vs(Ys(e),{recursive:!0}),Vs(Ys(n),{recursive:!0});let r=sd(e)?od(e,"utf8"):"",s=t.binary??"toolnet-memory",o=`notify = [${JSON.stringify(s)}, "session:codex-notify"]`,i=r.split(`
119
- `),a=i.findIndex(f=>/^\s*\[/.test(f));a<0&&(a=i.length);let c=-1,u=-1;for(let f=0;f<a;f+=1)if(/^\s*notify\s*=/.test(i[f])){if(c=f,u=f,i[f].includes("[")&&!i[f].includes("]"))for(;u+1<a&&(u+=1,!i[u].includes("]")););break}let p=[];if(c>=0){let f=i.slice(c,u+1).join(`
120
- `);p=id(f),i.splice(c,u-c+1,o)}else a=i.findIndex(f=>/^\s*\[/.test(f)),a<0&&(a=i.length),i.splice(a,0,o);let l=p.length>=2&&p[p.length-1]==="session:codex-notify";return p.length>0&&!l&&Gs(n,JSON.stringify(p,null,2)+`
111
+ ${o}`:o,zl(n,`${a.trim()}
112
+ `,{encoding:"utf8",mode:384})}import{existsSync as Hl,mkdirSync as Bl,readFileSync as Jl,renameSync as Gl,writeFileSync as Ul}from"node:fs";import{dirname as Yl,join as Xl}from"node:path";function Uo(t){return Xl(t.rootPath,".toolnet","context","session-origin.json")}function Ql(t,e){Bl(Yl(t),{recursive:!0});let n=`${t}.tmp-${process.pid}-${Date.now()}`;Ul(n,`${JSON.stringify(e,null,2)}
113
+ `,{encoding:"utf8",mode:384}),Gl(n,t)}function Mt(t,e){return[...t].filter(n=>n.kind===e).sort((n,r)=>{let o=n.occurredAt.localeCompare(r.occurredAt);return o!==0?o:n.sequence-r.sequence}).at(-1)}function Pt(t,e){let n=Mt(e.observations,"file"),r=Mt(e.observations,"next_action"),o=Mt(e.observations,"blocker"),s=Mt(e.observations,"decision"),i={version:1,projectId:t.id,agent:e.agent,nativeSessionId:e.nativeSessionId,updatedAt:e.workState.updatedAt,currentRequest:e.workState.currentRequest,currentActivity:e.workState.currentActivity,currentTask:e.workState.currentTask?.title,currentPhase:e.workState.currentPhase?.title,lastTouchedFile:n?.text??e.workState.activeFiles?.at(-1)??e.workState.filesTouched.at(-1),latestNextAction:r?.text??e.workState.nextActions.at(-1),latestBlocker:o?.text??e.workState.blockers.at(-1),latestDecision:s?.text??e.workState.decisions.at(-1)};return Ql(Uo(t),i),i}function Zl(t){let e=Uo(t);if(!Hl(e))return null;try{let n=JSON.parse(Jl(e,"utf8"));return n.version!==1||n.projectId!==t.id?null:n}catch{return null}}function Yo(t){let e=Zl(t);if(!e)return null;let n=["Previous session:",`- Agent: ${e.agent}`,`- Session: ${e.nativeSessionId}`];return e.currentRequest&&n.push(`- Current request: ${e.currentRequest}`),e.currentActivity&&n.push(`- Current activity: ${e.currentActivity}`),e.currentPhase&&n.push(`- Current phase: ${e.currentPhase}`),e.currentTask&&n.push(`- Current task: ${e.currentTask}`),e.lastTouchedFile&&n.push(`- Last touched file: ${e.lastTouchedFile}`),e.latestBlocker&&n.push(`- Blocker: ${e.latestBlocker}`),e.latestNextAction&&n.push(`- Next action: ${e.latestNextAction}`),e.latestDecision&&n.push(`- Important decision: ${e.latestDecision}`),n.join(`
114
+ `)}import{existsSync as Xo,mkdirSync as ed,readFileSync as td}from"node:fs";import{join as hn}from"node:path";function Qo(t){return hn(t.rootPath,".toolnet","memory","checkpoints")}function Zo(t){return hn(Qo(t),"latest.json")}function nd(t){let e=Zo(t);if(!Xo(e))return null;try{let n=JSON.parse(td(e,"utf8"));return n.schema!=="toolnet.memory.checkpoint.v1"||n.project.id!==t.id?null:n}catch{return null}}function rd(t){return["rule","architecture","decision","fix"].includes(t)}function od(t,e){return e.length===0?[]:it(t,e).candidates.filter(r=>rd(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:t.agent,nativeSessionId:t.nativeSessionId}))}function sd(t,e){let n=new Map;for(let r of[...t,...e]){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 id(t){return{request:t.currentRequest,activity:t.currentActivity,goal:t.goal,phase:t.currentPhase?{title:t.currentPhase.title,status:t.currentPhase.status}:void 0,task:t.currentTask?{title:t.currentTask.title,status:t.currentTask.status}:void 0,phases:t.phases.map(e=>({title:e.title,status:e.status})),tasks:t.tasks.map(e=>({title:e.title,status:e.status})),activeFiles:t.activeFiles??[],modifiedFiles:t.modifiedFiles??[],createdFiles:t.createdFiles??[],deletedFiles:t.deletedFiles??[],checks:t.checks??[],blockers:t.blockers,decisions:t.decisions,nextActions:t.nextActions}}function es(t,e,n,r){let o=nd(t),s=sd(o?.durableFacts??[],od(e,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),f=r.tasks.filter(g=>g.status!=="completed"&&g.status!=="cancelled").map(g=>g.title),l={work:id(r),durableFacts:s.map(g=>g.fingerprint).sort()},p=w(JSON.stringify(l)).slice(0,32),d={schema:"toolnet.memory.checkpoint.v1",version:1,project:{id:t.id,name:t.name},source:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.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:f},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=Qo(t);ed(m,{recursive:!0,mode:448});let S=hn(m,`${p}.json`);return Xo(S)||R(S,d),R(Zo(t),d),d}function ts(t,e,n){if(process.env.TOOLNET_LOCAL_CHECKPOINT==="0"||n.length===0)return{updated:!1,observations:0};let r=pe(e,n);if(r.length===0)return{updated:!1,observations:0};let o=It(t,r);At(t,o),Pt(t,{agent:e.agent,nativeSessionId:e.nativeSessionId,observations:r,workState:o});try{es(t,e,n,o)}catch{}try{Ho({project:t,identity:e,state:o,reason:"continuous-checkpoint",sequence:n.at(-1)?.sequence??0})}catch{}return{updated:!0,observations:r.length}}var Et=class{identity;wal;remote;sanitizer=new H;learner;continuity;semantic;handoff;project;title;metadata;constructor(e){this.project=e.project,this.identity=Ge(e.project,e.agent,e.nativeSessionId),this.title=e.title,this.metadata=this.sanitizer.sanitizeValue(e.metadata??{}),this.wal=new tt(this.identity,e.eventContext),this.remote=new Ue(e.storage,e.maxEventsPerChunk??100,e.maxChunkBytes??512*1024),this.learner=new gt({project:e.project,storage:e.storage,identity:this.identity,wal:this.wal}),this.continuity=new kt({project:e.project,storage:e.storage,identity:this.identity,wal:this.wal}),this.semantic=new wt({project:e.project,storage:e.storage,identity:this.identity,wal:this.wal}),this.handoff=new Ct({project:e.project,storage:e.storage,identity:this.identity})}sanitizeEvent(e){let n=e.provenance?{...e.provenance,metadata:this.sanitizer.sanitizeValue(e.provenance.metadata)}:void 0;return{...e,data:this.sanitizer.sanitizeValue(e.data??{}),provenance:n}}checkpointLocal(e){if(e.length!==0)try{ts(this.project,this.identity,e)}catch{}}start(e={}){let n=this.wal.loadState();return this.record({type:n.lastSequence===0?"session_start":"session_resume",data:e,provenance:{source:this.identity.agent}})}record(e){let n=this.wal.append([this.sanitizeEvent(e)]);return this.checkpointLocal(n),n[0]}recordMany(e){let n=this.wal.append(e.map(r=>this.sanitizeEvent(r)));return this.checkpointLocal(n),n}setSourceCursor(e,n){this.wal.setSourceCursor(e,n)}async flush(){let e=this.wal.readPending(),n=this.wal.loadState(),r=await this.remote.append(this.identity,e.events,n.sourceCursors,{title:this.title,metadata:this.metadata});if(e.events.length>0){let o=e.events[e.events.length-1];this.wal.markRemote(o.sequence,e.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"&&e.events.length>0)try{let o=e.events[e.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(e={}){return this.record({type:"session_idle",data:e,provenance:{source:this.identity.agent}}),this.flush()}async end(e={}){return this.record({type:"session_end",data:e,provenance:{source:this.identity.agent}}),this.flush()}status(){return this.wal.loadState()}recoverRemote(){return this.remote.recover(this.identity)}};import{existsSync as ad,readFileSync as cd,readdirSync as ud,statSync as ns}from"node:fs";import{homedir as ld}from"node:os";import{join as Ot,resolve as rs}from"node:path";function os(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function dd(){return process.env.CODEX_HOME??Ot(ld(),".codex")}function $e(t){let e="";try{e=cd(t,"utf8").slice(0,128*1024)}catch{return{raw:{}}}for(let n of e.split(`
115
+ `))if(n)try{let r=os(JSON.parse(n));if(r.type!=="session_meta")continue;let o=os(r.payload),s=[o.id,o.thread_id,o.threadId,o.session_id,o.sessionId].find(a=>typeof a=="string"),i=typeof o.cwd=="string"?o.cwd:void 0;return{threadId:s,cwd:i,raw:o}}catch{}return{raw:{}}}function Sn(t,e){if(!ad(t))return;let n;try{n=ud(t,{withFileTypes:!0})}catch{return}for(let r of n){let o=Ot(t,r.name);if(r.isDirectory()){Sn(o,e);continue}r.isFile()&&r.name.endsWith(".jsonl")&&e.push(o)}}function kn(){let t=dd(),e=[];return Sn(Ot(t,"sessions"),e),Sn(Ot(t,"archived_sessions"),e),e.sort((n,r)=>{try{return ns(r).mtimeMs-ns(n).mtimeMs}catch{return 0}})}function vn(t){let e=kn(),n=e.find(r=>r.includes(t));if(n)return n;for(let r of e)if($e(r).threadId===t)return r;return null}function Tt(t,e){let n=rs(t),r=rs(e);return r===n||r.startsWith(n+"/")||n.startsWith(r+"/")}import{closeSync as pd,existsSync as fd,openSync as md,readSync as gd,statSync as yd}from"node:fs";function ss(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function hd(t){let e=t.timestamp;if(typeof e=="string"){let n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return new Date().toISOString()}function Sd(t){let e=typeof t.type=="string"?t.type.toLowerCase():"",n=ss(t.payload),r=typeof n.type=="string"?n.type.toLowerCase():"",o=typeof n.role=="string"?n.role.toLowerCase():void 0;return e==="session_meta"?{type:"custom"}:o==="user"||r==="user_message"?{type:"user_prompt",role:"user"}:o==="assistant"||r==="agent_message"||r==="assistant_message"?{type:"assistant_message",role:"assistant"}:r.includes("function_call")||r.includes("tool_call")||r.includes("exec_command_begin")||r.includes("exec_command_start")?{type:"tool_call"}:r.includes("function_call_output")||r.includes("tool_result")||r.includes("exec_command_end")||r.includes("exec_command_complete")?{type:"tool_result"}:r.includes("error")?{type:"error"}:e.includes("compacted")||r.includes("compacted")?{type:"session_compact"}:{type:"custom",role:o}}function is(t,e=0){if(!fd(t))return{events:[],nextOffset:e,reset:!1};let n=yd(t).size,r=e>n,o=r?0:e;if(o>=n)return{events:[],nextOffset:n,reset:r};let s=n-o,i=Buffer.alloc(s),a=md(t,"r");try{gd(a,i,0,s,o)}finally{pd(a)}let c=i.toString("utf8"),u=c.lastIndexOf(`
116
+ `);if(u<0)return{events:[],nextOffset:o,reset:r};let f=c.slice(0,u+1),l=0,p=[];for(let d of f.split(`
117
+ `)){if(!d)continue;let m=Buffer.byteLength(d+`
118
+ `,"utf8"),S=o+l;l+=m;let g;try{g=JSON.parse(d)}catch{continue}let y=ss(g),v=Sd(y);p.push({type:v.type,timestamp:hd(y),role:v.role,sourceEventId:`rollout:${S}`,sourceSequence:S,data:y,provenance:{source:"codex-rollout",sourcePath:t,sourceOffset:S}})}return{events:p,nextOffset:o+Buffer.byteLength(f,"utf8"),reset:r}}var kd=[/^<SYSTEM MESSAGE>/i,/^<EPHEMERAL MESSAGE>/i,/^<system>/i,/^<ephemeral>/i,/^ManageTask:/i,/^Task \d+ status:/i,/^Task \d+ killed/i,/^Task \d+ loading/i,/^Thought for \d+ tokens/i,/^Prioritizing Tool Usage/i,/^Tool call:/i,/^Tool response:/i,/^npm notice/i,/^npm WARN/i,/^added \d+ packages/i,/^removed \d+ packages/i,/^up to date/i,/^\d+ packages are looking for funding/i,/^run `npm fund` for details/i,/^[\d.]+%/,/^\[={10,}\]/,/^Loading\.\.\./i,/^Processing\.\.\./i,/^bash-\d+\.\d+\$/,/^\$ /,/^\s*$/],vd=[/api[_-]?key[:\s=]+[^\s]+/gi,/token[:\s=]+[^\s]+/gi,/secret[:\s=]+[^\s]+/gi,/password[:\s=]+[^\s]+/gi,/bearer\s+[^\s]+/gi,/authorization:\s*[^\s]+/gi],wd=["decision","decided","rule","convention","architecture","pattern","fixed","resolved","implemented","created","updated","deleted","deployed","blocker","blocked","issue","bug","error","next","todo","action","requirement","must","should","important"];function bd(t){let e=t.toLowerCase();return wd.some(n=>e.includes(n))}function xd(t){if(!t.trim())return!0;for(let e of kd)if(e.test(t))return!0;return bd(t),!1}function jd(t){let e=t;for(let n of vd)e=e.replace(n,r=>{let o=r.split(/[:\s=]+/);return o.length>1?`${o[0]}: [REDACTED]`:"[REDACTED]"});return e}function wn(t){let e=t.trim();return e?xd(e)?{content:"",filtered:!0,reason:"noise"}:{content:jd(e),filtered:!1}:{content:"",filtered:!0,reason:"empty"}}function Rt(t){let e={};for(let[n,r]of Object.entries(t))if(typeof r=="string"){let o=wn(r);o.filtered||(e[n]=o.content)}else r&&typeof r=="object"&&!Array.isArray(r)?e[n]=Rt(r):Array.isArray(r)?e[n]=r.map(o=>{if(typeof o=="string"){let s=wn(o);return s.filtered?null:s.content}return o&&typeof o=="object"?Rt(o):o}).filter(o=>o!==null):e[n]=r;return e}function as(t){let e=typeof t.type=="string"?t.type.toLowerCase():"";if(e.includes("system")||e.includes("ephemeral")||e==="tool_call"&&!t.result)return!0;if(t.data&&typeof t.data=="object"){let n=t.data,r=typeof n.content=="string"?n.content:"";if(r&&wn(r).filtered)return!0}return!1}async function Le(t){let e=t.threadId.trim();if(!e)throw new Error("Codex thread ID is required");let n=$e(t.rolloutPath),r=t.cwd??n.cwd;if(r&&!Tt(t.project.rootPath,r))throw new Error(`Codex thread does not belong to project: ${r}`);if(n.threadId&&n.threadId!==e)throw new Error(`Codex rollout thread mismatch: expected ${e}, got ${n.threadId}`);let o=new Et({project:t.project,storage:t.storage,agent:"codex",nativeSessionId:e,metadata:{source:"codex-rollout",rolloutPath:t.rolloutPath,cwd:r,client:t.client},eventContext:{source:"codex",cwd:r??t.project.rootPath,turnId:t.turnId}}),s=o.status(),i=s.sourceCursors["codex.rollout.path"],a=Number(s.sourceCursors["codex.rollout.offset"]??0);i&&i!==t.rolloutPath&&(a=0),(!Number.isFinite(a)||a<0)&&(a=0);let c=is(t.rolloutPath,a),u=[];s.lastSequence===0&&u.push({type:"session_start",sourceEventId:`codex:${e}:start`,data:{threadId:e,cwd:r,rolloutPath:t.rolloutPath,sessionMeta:n.raw},provenance:{source:"codex-rollout",sourcePath:t.rolloutPath}}),i&&i!==t.rolloutPath&&u.push({type:"custom",sourceEventId:`codex:${e}:rollout-rotation:${t.rolloutPath}`,data:{event:"rollout_rotation",previousPath:i,rolloutPath:t.rolloutPath},provenance:{source:"codex-rollout"}}),c.reset&&u.push({type:"custom",sourceEventId:`codex:${e}:rollout-reset:${c.nextOffset}`,data:{event:"rollout_reset"},provenance:{source:"codex-rollout",sourcePath:t.rolloutPath}});let f=c.events.filter(d=>!as(d.data)).map(d=>({...d,data:Rt(d.data)}));if(u.push(...f),f.length>0)try{let d=Ge(t.project,"codex",e),m=f.map((y,v)=>({version:1,id:`codex-work-${e}-${y.sourceSequence??v}`,sequence:v+1,projectId:t.project.id,agent:"codex",nativeSessionId:e,type:y.type,timestamp:y.timestamp??new Date().toISOString(),role:y.role,sourceEventId:y.sourceEventId,sourceSequence:y.sourceSequence,data:y.data??{},provenance:y.provenance??{}})),S=pe(d,m),g=It(t.project,S);At(t.project,g),Pt(t.project,{agent:"codex",nativeSessionId:e,observations:S,workState:g})}catch{}t.idle&&t.turnId&&u.push({type:"session_idle",sourceEventId:`codex:${e}:turn:${t.turnId}:idle`,data:{turnId:t.turnId,client:t.client},provenance:{source:"codex-notify"}});let l=o.recordMany(u);if(o.setSourceCursor("codex.rollout.path",t.rolloutPath),o.setSourceCursor("codex.rollout.offset",c.nextOffset),t.turnId&&o.setSourceCursor("codex.last.turn",t.turnId),t.idle&&f.length>0)try{let d=f.map(S=>JSON.stringify(S.data)),m=st(d,e);o.setSourceCursor("codex.session.summary",m.summary),o.setSourceCursor("codex.session.facts_count",m.durableFacts.length),wr()&&!jr()&&o.setSourceCursor("codex.raw_transcript.archived","local")}catch{}let p=await o.flush();return{threadId:e,imported:l.length,rolloutEvents:c.events.length,eventCount:p.eventCount,chunkCount:p.chunkCount,status:p.status,rolloutOffset:c.nextOffset,reset:c.reset}}import{existsSync as Id}from"node:fs";import{dirname as Cd,join as Ad,parse as Md,resolve as Pd}from"node:path";function cs(t){let e=Pd(t),n=Md(e).root;for(;;){if(Id(Ad(e,".toolnet","project.json")))return new ie().detect(e);if(e===n)break;let r=Cd(e);if(r===e)break;e=r}return null}async function us(t,e,n=100){let r=[];for(let o of kn()){let s=$e(o);if(!(!s.threadId||!s.cwd)&&Tt(t.rootPath,s.cwd)&&(r.push(await Le({project:t,storage:e,threadId:s.threadId,rolloutPath:o,cwd:s.cwd})),r.length>=n))break}return r}import{existsSync as Ed,mkdirSync as ls,readFileSync as Od,writeFileSync as ds}from"node:fs";import{homedir as ps}from"node:os";import{dirname as fs,join as bn}from"node:path";function Td(t){let e=[],n=/"((?:\\.|[^"\\])*)"|'([^']*)'/g,r;for(;r=n.exec(t);){let o=r[1]??r[2]??"";try{e.push(r[1]!==void 0?JSON.parse(`"${o}"`):o)}catch{e.push(o)}}return e}function ms(t={}){let e=t.configFile??bn(process.env.CODEX_HOME??bn(ps(),".codex"),"config.toml"),n=t.previousFile??bn(ps(),".config","toolnet-memory","codex-notify-previous.json");ls(fs(e),{recursive:!0}),ls(fs(n),{recursive:!0});let r=Ed(e)?Od(e,"utf8"):"",o=t.binary??"toolnet-memory",s=`notify = [${JSON.stringify(o)}, "session:codex-notify"]`,i=r.split(`
119
+ `),a=i.findIndex(p=>/^\s*\[/.test(p));a<0&&(a=i.length);let c=-1,u=-1;for(let p=0;p<a;p+=1)if(/^\s*notify\s*=/.test(i[p])){if(c=p,u=p,i[p].includes("[")&&!i[p].includes("]"))for(;u+1<a&&(u+=1,!i[u].includes("]")););break}let f=[];if(c>=0){let p=i.slice(c,u+1).join(`
120
+ `);f=Td(p),i.splice(c,u-c+1,s)}else a=i.findIndex(p=>/^\s*\[/.test(p)),a<0&&(a=i.length),i.splice(a,0,s);let l=f.length>=2&&f[f.length-1]==="session:codex-notify";return f.length>0&&!l&&ds(n,JSON.stringify(f,null,2)+`
121
121
  `,{encoding:"utf8",mode:384}),r=i.join(`
122
122
  `),r.endsWith(`
123
123
  `)||(r+=`
124
- `),Gs(e,r,{encoding:"utf8",mode:384}),{configFile:e,previousFile:n,preservedPrevious:p.length>0&&!l}}import{existsSync as ad,mkdirSync as cd,readFileSync as ud,writeFileSync as ld}from"node:fs";import{homedir as dd}from"node:os";import{dirname as pd,join as Qs}from"node:path";function fd(t){return`'${t.replace(/'/g,"'\\''")}'`}function Zs(t={}){let e=t.hooksFile??Qs(process.env.CODEX_HOME??Qs(dd(),".codex"),"hooks.json");cd(pd(e),{recursive:!0});let n={};if(ad(e))try{n=JSON.parse(ud(e,"utf8"))}catch(a){throw new Error(`Invalid existing Codex hooks.json: ${a instanceof Error?a.message:String(a)}`)}let r=n.hooks&&typeof n.hooks=="object"&&!Array.isArray(n.hooks)?n.hooks:{};n.hooks=r;let o=(Array.isArray(r.SessionStart)?r.SessionStart:[]).filter(a=>{try{return!JSON.stringify(a).includes("session:codex-context")}catch{return!0}}),i=t.binary??"toolnet-memory";return o.push({matcher:"startup|resume|clear|compact",hooks:[{type:"command",command:`${fd(i)} session:codex-context`,timeout:15,additionalContextLimit:1e3,statusMessage:"Loading ToolNet project continuity"}]}),r.SessionStart=o,ld(e,JSON.stringify(n,null,2)+`
125
- `,{encoding:"utf8",mode:384}),e}import{existsSync as Ph,mkdirSync as hd,readFileSync as Eh,writeFileSync as Sd}from"node:fs";import{dirname as kd,join as to}from"node:path";function mn(t){if(!t)return 0;let e=Array.from(t).length,n=t.trim().split(/\s+/u).filter(Boolean).length;return Math.ceil(Math.max(e/3.5,n*1.3))}function j(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:n.slice(0,Math.max(0,e-1)).trimEnd()+"\u2026"}function md(t){let e=[],n=!1;for(let r of t.split(/\r?\n/u)){let s=r.trim();if(s.includes("<!--")&&(n=!0),n){s.includes("-->")&&(n=!1);continue}let o=s.toLowerCase();if(!(!s||s.startsWith("#")||s==="```"||o.startsWith("- [enforce]")||o.startsWith("* [enforce]")||o.startsWith("- [advisory]")||o.startsWith("* [advisory]"))&&(s=s.replace(/^[-*]\s+/u,""),s&&e.push(j(s,280)),e.length>=16))break}return e}function gd(t){let e=[],n=[];for(let r of t.split(/\\r?\\n/u)){let s=r.trim(),o=s.toLowerCase(),a=["- [enforce]","* [enforce]","- [advisory]","* [advisory]"].find(u=>o.startsWith(u));if(!a)continue;let c=s.slice(a.length).trim();c&&(a.includes("enforce")?e.push(c):n.push(c))}return{enforce:e,advisory:n}}function yd(t,e){let n=[];for(let r of t){let s=[...n,r].join(`
126
- `);if(mn(s)<=e){n.push(r);continue}let o=mn(n.join(`
127
- `)),i=Math.max(0,e-o);if(i>=16){let a=Math.floor(i*3.2),c=j(r,a);c&&n.push(c)}break}return n.join(`
128
- `).trim()}async function eo(t){let e=Math.max(256,Math.min(2e3,t.maxTokens??1e3)),n=gt(t.project,!1),r=n?.content??"";r||(r=await t.storage.getText(`projects/${t.project.id}/project/manual.md`)??"");let s=gd(r),o=n?n.rules.filter(d=>d.mode==="enforce").map(d=>d.text):s.enforce,i=n?n.rules.filter(d=>d.mode==="advisory").map(d=>d.text):s.advisory,a=r?md(r):[],c=await lt(t.project,t.storage),u=await ls(t.project,t.storage),p=await Ps(t.project,t.storage),l=[];if(l.push("[TOOLNET PROJECT CONTEXT]"),l.push(`Project: ${t.project.name}`),l.push("Continue existing project state. Do not restart completed work unless evidence shows it is necessary."),r&&l.push(`Full operating manual: ${mt(t.project)}`),o.length){l.push("","PROJECT RULES \u2014 MUST FOLLOW");for(let d of o.slice(0,24))l.push(`- [ENFORCE] ${j(d,240)}`)}if(i.length){l.push("","PROJECT PREFERENCES");for(let d of i.slice(0,10))l.push(`- ${j(d,220)}`)}if(u&&(u.mission&&l.push("","MISSION",j(u.mission.value,420)),u.activeObjective&&l.push("","CURRENT OBJECTIVE",j(u.activeObjective.value,420)),u.why&&l.push("","WHY THIS WORK MATTERS",j(u.why.value,420)),u.desiredOutcome&&l.push("","DESIRED OUTCOME",j(u.desiredOutcome.value,420)),u.planRationale&&l.push("","WHY THIS APPROACH",j(u.planRationale.value,420))),c){if(l.push("","ACTIVE WORK"),c.goal&&l.push(`Goal: ${j(c.goal,320)}`),c.plan&&l.push(`Plan: ${j(c.plan,320)}`),l.push(`Progress: phases ${c.progress.phasesCompleted}/${c.progress.phasesTotal}; tasks ${c.progress.tasksCompleted}/${c.progress.tasksTotal}; blocked ${c.progress.blocked}`),c.currentPhase&&l.push(`Current phase: ${c.currentPhase.title} [${c.currentPhase.status}]`),c.currentPhase&&u){let d=u.phases.find(g=>g.order===c.currentPhase?.order);d&&(d.objective&&l.push(`Phase objective: ${j(d.objective.value,340)}`),d.why?l.push(`Why this phase: ${j(d.why.value,340)}`):l.push("Why this phase: not explicitly recorded. Inspect existing implementation before assuming intent."),d.deliverable&&l.push(`Deliverable: ${j(d.deliverable.value,340)}`),d.dependencies.length&&l.push(`Depends on: ${d.dependencies.slice(0,4).map(g=>j(g.value,180)).join("; ")}`),d.acceptanceCriteria.length&&(l.push("","DEFINITION OF DONE"),d.acceptanceCriteria.slice(0,6).forEach(g=>{l.push(`- ${j(g.value,260)}`)})),d.openQuestions.length&&(l.push("","OPEN QUESTIONS FOR CURRENT PHASE"),d.openQuestions.slice(0,4).forEach(g=>{l.push(`- ${j(g.value,260)}`)})))}c.currentTask&&l.push(`Current task: ${c.currentTask.title} [${c.currentTask.status}]`),c.nextActions.length&&(l.push("","NEXT ACTIONS"),c.nextActions.slice(0,6).forEach((d,g)=>{l.push(`${g+1}. ${j(d,260)}`)})),c.blockers.length&&(l.push("","BLOCKERS"),c.blockers.slice(0,5).forEach(d=>{l.push(`- ${j(d,260)}`)})),c.warnings.length&&(l.push("","ATTENTION"),c.warnings.slice(-5).forEach(d=>{l.push(`- ${j(d,260)}`)})),c.decisions.length&&(l.push("","RECENT DECISIONS"),c.decisions.slice(-5).forEach(d=>{l.push(`- ${j(d,260)}`)})),c.lastSession&&l.push("",`Last work session: ${c.lastSession.agent} / ${c.lastSession.nativeSessionId}`)}if(u&&u.openQuestions.length&&(l.push("","UNRESOLVED QUESTIONS"),u.openQuestions.slice(0,5).forEach(d=>{l.push(`- ${j(d.value,260)}`)})),p&&l.push(`Latest handoff: ${p.reason} / ${p.sourceSession.agent}`),a.length){l.push("","OPERATING NOTES");for(let d of a)l.push(`- ${d}`)}l.push("","Before changing anything: verify the current repository state and continue from the active phase/task above.");let f=yd(l,e);return{version:1,projectId:t.project.id,projectName:t.project.name,text:f,estimatedTokens:mn(f),maxTokens:e,hasManual:!!r,hasWorkState:!!c,hasHandoff:!!p,generatedAt:new Date().toISOString()}}function vd(t){return to(t.rootPath,".toolnet","context","startup.md")}function wd(t){return to(t.rootPath,".toolnet","context","startup.json")}function bd(t,e){let n=vd(t);hd(kd(n),{recursive:!0}),Sd(n,e.text.endsWith(`
124
+ `),ds(e,r,{encoding:"utf8",mode:384}),{configFile:e,previousFile:n,preservedPrevious:f.length>0&&!l}}import{existsSync as Rd,mkdirSync as Nd,readFileSync as _d,writeFileSync as Kd}from"node:fs";import{homedir as $d}from"node:os";import{dirname as Ld,join as gs}from"node:path";function Fd(t){return`'${t.replace(/'/g,"'\\''")}'`}function ys(t={}){let e=t.hooksFile??gs(process.env.CODEX_HOME??gs($d(),".codex"),"hooks.json");Nd(Ld(e),{recursive:!0});let n={};if(Rd(e))try{n=JSON.parse(_d(e,"utf8"))}catch(a){throw new Error(`Invalid existing Codex hooks.json: ${a instanceof Error?a.message:String(a)}`)}let r=n.hooks&&typeof n.hooks=="object"&&!Array.isArray(n.hooks)?n.hooks:{};n.hooks=r;let s=(Array.isArray(r.SessionStart)?r.SessionStart:[]).filter(a=>{try{return!JSON.stringify(a).includes("session:codex-context")}catch{return!0}}),i=t.binary??"toolnet-memory";return s.push({matcher:"startup|resume|clear|compact",hooks:[{type:"command",command:`${Fd(i)} session:codex-context`,timeout:15,additionalContextLimit:1e3,statusMessage:"Loading ToolNet project continuity"}]}),r.SessionStart=s,Kd(e,JSON.stringify(n,null,2)+`
125
+ `,{encoding:"utf8",mode:384}),e}import{existsSync as mS,mkdirSync as qd,readFileSync as gS,writeFileSync as Vd}from"node:fs";import{dirname as Hd,join as Ss}from"node:path";function xn(t){if(!t)return 0;let e=Array.from(t).length,n=t.trim().split(/\s+/u).filter(Boolean).length;return Math.ceil(Math.max(e/3.5,n*1.3))}function I(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:n.slice(0,Math.max(0,e-1)).trimEnd()+"\u2026"}function Wd(t){let e=[],n=!1;for(let r of t.split(/\r?\n/u)){let o=r.trim();if(o.includes("<!--")&&(n=!0),n){o.includes("-->")&&(n=!1);continue}let s=o.toLowerCase();if(!(!o||o.startsWith("#")||o==="```"||s.startsWith("- [enforce]")||s.startsWith("* [enforce]")||s.startsWith("- [advisory]")||s.startsWith("* [advisory]"))&&(o=o.replace(/^[-*]\s+/u,""),o&&e.push(I(o,280)),e.length>=16))break}return e}function Dd(t){let e=[],n=[];for(let r of t.split(/\\r?\\n/u)){let o=r.trim(),s=o.toLowerCase(),a=["- [enforce]","* [enforce]","- [advisory]","* [advisory]"].find(u=>s.startsWith(u));if(!a)continue;let c=o.slice(a.length).trim();c&&(a.includes("enforce")?e.push(c):n.push(c))}return{enforce:e,advisory:n}}function zd(t,e){let n=[];for(let r of t){let o=[...n,r].join(`
126
+ `);if(xn(o)<=e){n.push(r);continue}let s=xn(n.join(`
127
+ `)),i=Math.max(0,e-s);if(i>=16){let a=Math.floor(i*3.2),c=I(r,a);c&&n.push(c)}break}return n.join(`
128
+ `).trim()}async function hs(t){let e=Math.max(256,Math.min(2e3,t.maxTokens??1e3)),n=xt(t.project,!1),r=n?.content??"";r||(r=await t.storage.getText(`projects/${t.project.id}/project/manual.md`)??"");let o=Dd(r),s=n?n.rules.filter(d=>d.mode==="enforce").map(d=>d.text):o.enforce,i=n?n.rules.filter(d=>d.mode==="advisory").map(d=>d.text):o.advisory,a=r?Wd(r):[],c=await St(t.project,t.storage),u=await Ao(t.project,t.storage),f=await Bo(t.project,t.storage),l=[];if(l.push("[TOOLNET PROJECT CONTEXT]"),l.push(`Project: ${t.project.name}`),l.push("Continue existing project state. Do not restart completed work unless evidence shows it is necessary."),r&&l.push(`Full operating manual: ${bt(t.project)}`),s.length){l.push("","PROJECT RULES \u2014 MUST FOLLOW");for(let d of s.slice(0,24))l.push(`- [ENFORCE] ${I(d,240)}`)}if(i.length){l.push("","PROJECT PREFERENCES");for(let d of i.slice(0,10))l.push(`- ${I(d,220)}`)}if(u&&(u.mission&&l.push("","MISSION",I(u.mission.value,420)),u.activeObjective&&l.push("","CURRENT OBJECTIVE",I(u.activeObjective.value,420)),u.why&&l.push("","WHY THIS WORK MATTERS",I(u.why.value,420)),u.desiredOutcome&&l.push("","DESIRED OUTCOME",I(u.desiredOutcome.value,420)),u.planRationale&&l.push("","WHY THIS APPROACH",I(u.planRationale.value,420))),c){if(l.push("","ACTIVE WORK"),c.goal&&l.push(`Goal: ${I(c.goal,320)}`),c.plan&&l.push(`Plan: ${I(c.plan,320)}`),l.push(`Progress: phases ${c.progress.phasesCompleted}/${c.progress.phasesTotal}; tasks ${c.progress.tasksCompleted}/${c.progress.tasksTotal}; blocked ${c.progress.blocked}`),c.currentPhase&&l.push(`Current phase: ${c.currentPhase.title} [${c.currentPhase.status}]`),c.currentPhase&&u){let d=u.phases.find(m=>m.order===c.currentPhase?.order);d&&(d.objective&&l.push(`Phase objective: ${I(d.objective.value,340)}`),d.why?l.push(`Why this phase: ${I(d.why.value,340)}`):l.push("Why this phase: not explicitly recorded. Inspect existing implementation before assuming intent."),d.deliverable&&l.push(`Deliverable: ${I(d.deliverable.value,340)}`),d.dependencies.length&&l.push(`Depends on: ${d.dependencies.slice(0,4).map(m=>I(m.value,180)).join("; ")}`),d.acceptanceCriteria.length&&(l.push("","DEFINITION OF DONE"),d.acceptanceCriteria.slice(0,6).forEach(m=>{l.push(`- ${I(m.value,260)}`)})),d.openQuestions.length&&(l.push("","OPEN QUESTIONS FOR CURRENT PHASE"),d.openQuestions.slice(0,4).forEach(m=>{l.push(`- ${I(m.value,260)}`)})))}c.currentTask&&l.push(`Current task: ${c.currentTask.title} [${c.currentTask.status}]`),c.nextActions.length&&(l.push("","NEXT ACTIONS"),c.nextActions.slice(0,6).forEach((d,m)=>{l.push(`${m+1}. ${I(d,260)}`)})),c.blockers.length&&(l.push("","BLOCKERS"),c.blockers.slice(0,5).forEach(d=>{l.push(`- ${I(d,260)}`)})),c.warnings.length&&(l.push("","ATTENTION"),c.warnings.slice(-5).forEach(d=>{l.push(`- ${I(d,260)}`)})),c.decisions.length&&(l.push("","RECENT DECISIONS"),c.decisions.slice(-5).forEach(d=>{l.push(`- ${I(d,260)}`)})),c.lastSession&&l.push("",`Last work session: ${c.lastSession.agent} / ${c.lastSession.nativeSessionId}`)}if(u&&u.openQuestions.length&&(l.push("","UNRESOLVED QUESTIONS"),u.openQuestions.slice(0,5).forEach(d=>{l.push(`- ${I(d.value,260)}`)})),f&&l.push(`Latest handoff: ${f.reason} / ${f.sourceSession.agent}`),a.length){l.push("","OPERATING NOTES");for(let d of a)l.push(`- ${d}`)}l.push("","Before changing anything: verify the current repository state and continue from the active phase/task above.");let p=zd(l,e);return{version:1,projectId:t.project.id,projectName:t.project.name,text:p,estimatedTokens:xn(p),maxTokens:e,hasManual:!!r,hasWorkState:!!c,hasHandoff:!!f,generatedAt:new Date().toISOString()}}function Bd(t){return Ss(t.rootPath,".toolnet","context","startup.md")}function Jd(t){return Ss(t.rootPath,".toolnet","context","startup.json")}function Gd(t,e){let n=Bd(t);qd(Hd(n),{recursive:!0}),Vd(n,e.text.endsWith(`
129
129
  `)?e.text:e.text+`
130
- `,{encoding:"utf8",mode:384}),T(wd(t),e)}async function no(t,e,n=800){let s=(await eo({project:t,storage:e,maxTokens:n})).text;Ue(s)>n&&(s=Ye(s,n),s+=`
130
+ `,{encoding:"utf8",mode:384}),R(Jd(t),e)}async function ks(t,e,n=800){let o=(await hs({project:t,storage:e,maxTokens:n})).text;rt(o)>n&&(o=ot(o,n),o+=`
131
131
 
132
132
  [Context trimmed by ToolNet Memory token budget]
133
- `);let i={version:1,projectId:t.id,projectName:t.name,text:s,digest:v(s),estimatedTokens:Ue(s),generatedAt:new Date().toISOString()};return bd(t,i),await e.put(`projects/${t.id}/context/startup.md`,i.text+`
133
+ `);let i={version:1,projectId:t.id,projectName:t.name,text:o,digest:w(o),estimatedTokens:rt(o),generatedAt:new Date().toISOString()};return Gd(t,i),await e.put(`projects/${t.id}/context/startup.md`,i.text+`
134
134
  `,"text/markdown"),await e.put(`projects/${t.id}/context/startup.json`,JSON.stringify(i,null,2)+`
135
- `,"application/json"),i}import{existsSync as Md,readFileSync as Pd}from"node:fs";import{join as Ed}from"node:path";import{existsSync as ro,mkdirSync as xd,readFileSync as so,renameSync as jd,writeFileSync as Cd}from"node:fs";import{dirname as Id,join as oo}from"node:path";function io(t){return oo(t.rootPath,".toolnet","context","handoff.md")}function ao(t){return oo(t.rootPath,".toolnet","context","handoff.json")}function co(t,e){xd(Id(t),{recursive:!0});let n=`${t}.tmp-${process.pid}-${Date.now()}`;Cd(n,e.endsWith(`
135
+ `,"application/json"),i}import{existsSync as ep,readFileSync as tp}from"node:fs";import{join as np}from"node:path";import{existsSync as vs,mkdirSync as Ud,readFileSync as ws,renameSync as Yd,writeFileSync as Xd}from"node:fs";import{dirname as Qd,join as bs}from"node:path";function xs(t){return bs(t.rootPath,".toolnet","context","handoff.md")}function js(t){return bs(t.rootPath,".toolnet","context","handoff.json")}function Is(t,e){Ud(Qd(t),{recursive:!0});let n=`${t}.tmp-${process.pid}-${Date.now()}`;Xd(n,e.endsWith(`
136
136
  `)?e:`${e}
137
- `,{encoding:"utf8",mode:384}),jd(n,t)}function Ad(t,e){co(t,`${JSON.stringify(e,null,2)}
138
- `)}function uo(t,e){let n=e.replace(/\r\n/g,`
139
- `).trim();if(!n)return null;let r={version:1,projectId:t.id,projectName:t.name,text:n,digest:v(n),generatedAt:new Date().toISOString()};return co(io(t),n),Ad(ao(t),r),r}function lo(t){let e=io(t);if(!ro(e))return null;try{let n=so(e,"utf8").trim();if(!n)return null;let r=new Date(0).toISOString(),s=ao(t);if(ro(s))try{let o=JSON.parse(so(s,"utf8"));typeof o.generatedAt=="string"&&(r=o.generatedAt)}catch{}return{version:1,projectId:t.id,projectName:t.name,text:n,digest:v(n),generatedAt:r}}catch{return null}}function Od(t){let e=Ed(t.rootPath,".toolnet","current.md");if(!Md(e))return null;try{return Pd(e,"utf8").trim()}catch{return null}}function Td(t,e){let n=e.replace(/\r\n/g,`
140
- `).trim(),r=2400,s=n.length>r?`${n.slice(0,r)}
137
+ `,{encoding:"utf8",mode:384}),Yd(n,t)}function Zd(t,e){Is(t,`${JSON.stringify(e,null,2)}
138
+ `)}function Cs(t,e){let n=e.replace(/\r\n/g,`
139
+ `).trim();if(!n)return null;let r={version:1,projectId:t.id,projectName:t.name,text:n,digest:w(n),generatedAt:new Date().toISOString()};return Is(xs(t),n),Zd(js(t),r),r}function As(t){let e=xs(t);if(!vs(e))return null;try{let n=ws(e,"utf8").trim();if(!n)return null;let r=new Date(0).toISOString(),o=js(t);if(vs(o))try{let s=JSON.parse(ws(o,"utf8"));typeof s.generatedAt=="string"&&(r=s.generatedAt)}catch{}return{version:1,projectId:t.id,projectName:t.name,text:n,digest:w(n),generatedAt:r}}catch{return null}}function rp(t){let e=np(t.rootPath,".toolnet","current.md");if(!ep(e))return null;try{return tp(e,"utf8").trim()}catch{return null}}function op(t,e){let n=e.replace(/\r\n/g,`
140
+ `).trim(),r=2400,o=n.length>r?`${n.slice(0,r)}
141
141
 
142
- [Current work truncated for fast handoff]`:n,o=Rs(t);return["# ToolNet Fast Handoff","",`Project: ${t.name}`,"",...o?[o,""]:[],s,"","---","","Continuation rule:","- Continue unfinished work; do not redo completed steps.","- Query ToolNet Memory only when deeper history is needed."].join(`
143
- `)}function po(t){let e=Od(t);if(e===null)return{updated:!1,reason:"missing-current",chars:0};if(!e.trim())return{updated:!1,reason:"empty-current",chars:0};let n=Td(t,e);return lo(t)?.text.trim()===n.trim()?{updated:!1,reason:"unchanged",chars:n.length}:(uo(t,n),{updated:!0,reason:"updated",chars:n.length})}function It(t,e){let n=t.indexOf(e);return n>=0?t[n+1]:void 0}function fo(t){let e=Ne(),n=Cn(xn({provider:e.storage.provider,huggingface:e.storage.huggingface,localRoot:e.storage.localRoot}),{attempts:3});return new We(n,t.id,t.name,t.remote??t.name)}async function Fd(t){for(let e=0;e<10;e+=1){let n=dn(t);if(n)return n;await new Promise(r=>setTimeout(r,150))}return null}function Wd(t){let e=Kd($d(),".config","toolnet-memory","codex-notify-previous.json");if(Rd(e))try{let n=JSON.parse(Nd(e,"utf8"));if(!Array.isArray(n)||n.length===0||!n.every(s=>typeof s=="string"))return;_d(n[0],[...n.slice(1),t],{detached:!0,stdio:"ignore"}).unref()}catch{}}async function Ld(t){let e;try{e=JSON.parse(t)}catch{return}if(e.type!=="agent-turn-complete")return;let r=typeof e["thread-id"]=="string"?e["thread-id"]:"",s=typeof e["turn-id"]=="string"?e["turn-id"]:"",o=typeof e.cwd=="string"?e.cwd:"",i=typeof e.client=="string"?e.client:void 0;if(!r||!o)return;let a=Js(o);if(!a)return;let c=await Fd(r);if(!c)return;let u=fo(a);await Re({project:a,storage:u,threadId:r,rolloutPath:c,cwd:o,turnId:s,client:i,idle:!0});try{await no(a,u,800)}catch{}try{po(a)}catch{}}async function Dd(){let[t="help",...e]=process.argv.slice(2);if(t==="install-notify"){let o=It(e,"--bin"),i=Xs({binary:o}),a=Zs({binary:o});console.log(`\u2705 Codex notify installed: ${i.configFile}`),i.preservedPrevious&&console.log(`\u2705 Previous notify preserved: ${i.previousFile}`),console.log(`\u2705 Codex SessionStart context hook: ${a}`);return}if(t==="notify"){let o=e[e.length-1]??"";try{await Ld(o)}finally{Wd(o)}return}let n=It(e,"--project")??process.cwd(),r=new ne().detect(n),s=fo(r);if(t==="sync"){let o=e[0];if(!o)throw new Error("Usage: sync <thread-id>");let i=It(e,"--rollout")??dn(o);if(!i)throw new Error(`Codex rollout not found for ${o}`);let a=await Re({project:r,storage:s,threadId:o,rolloutPath:i,idle:e.includes("--idle")});console.log(JSON.stringify(a,null,2));return}if(t==="recover"){let o=Number(It(e,"--limit")??100),i=await Hs(r,s,Number.isFinite(o)?o:100);console.log(JSON.stringify({project:r.name,sessions:i.length,imported:i.reduce((a,c)=>a+c.imported,0)},null,2));return}console.log(`Codex Session Adapter
142
+ [Current work truncated for fast handoff]`:n,s=Yo(t);return["# ToolNet Fast Handoff","",`Project: ${t.name}`,"",...s?[s,""]:[],o,"","---","","Continuation rule:","- Continue unfinished work; do not redo completed steps.","- Query ToolNet Memory only when deeper history is needed."].join(`
143
+ `)}function Ms(t){let e=rp(t);if(e===null)return{updated:!1,reason:"missing-current",chars:0};if(!e.trim())return{updated:!1,reason:"empty-current",chars:0};let n=op(t,e);return As(t)?.text.trim()===n.trim()?{updated:!1,reason:"unchanged",chars:n.length}:(Cs(t,n),{updated:!0,reason:"updated",chars:n.length})}function Nt(t,e){let n=t.indexOf(e);return n>=0?t[n+1]:void 0}function Ps(t){let e=We(),n=Dn(Fn({provider:e.storage.provider,huggingface:e.storage.huggingface,localRoot:e.storage.localRoot}),{attempts:3});return new Je(n,t.id,t.name,t.remote??t.name)}async function lp(t){for(let e=0;e<10;e+=1){let n=vn(t);if(n)return n;await new Promise(r=>setTimeout(r,150))}return null}function dp(t){let e=up(cp(),".config","toolnet-memory","codex-notify-previous.json");if(sp(e))try{let n=JSON.parse(ip(e,"utf8"));if(!Array.isArray(n)||n.length===0||!n.every(o=>typeof o=="string"))return;ap(n[0],[...n.slice(1),t],{detached:!0,stdio:"ignore"}).unref()}catch{}}async function pp(t){let e;try{e=JSON.parse(t)}catch{return}if(e.type!=="agent-turn-complete")return;let r=typeof e["thread-id"]=="string"?e["thread-id"]:"",o=typeof e["turn-id"]=="string"?e["turn-id"]:"",s=typeof e.cwd=="string"?e.cwd:"",i=typeof e.client=="string"?e.client:void 0;if(!r||!s)return;let a=cs(s);if(!a)return;let c=await lp(r);if(!c)return;let u=Ps(a);await Le({project:a,storage:u,threadId:r,rolloutPath:c,cwd:s,turnId:o,client:i,idle:!0});try{await ks(a,u,800)}catch{}try{Ms(a)}catch{}}async function fp(){let[t="help",...e]=process.argv.slice(2);if(t==="install-notify"){let s=Nt(e,"--bin"),i=ms({binary:s}),a=ys({binary:s});console.log(`\u2705 Codex notify installed: ${i.configFile}`),i.preservedPrevious&&console.log(`\u2705 Previous notify preserved: ${i.previousFile}`),console.log(`\u2705 Codex SessionStart context hook: ${a}`);return}if(t==="notify"){let s=e[e.length-1]??"";try{await pp(s)}finally{dp(s)}return}let n=Nt(e,"--project")??process.cwd(),r=new ie().detect(n),o=Ps(r);if(t==="sync"){let s=e[0];if(!s)throw new Error("Usage: sync <thread-id>");let i=Nt(e,"--rollout")??vn(s);if(!i)throw new Error(`Codex rollout not found for ${s}`);let a=await Le({project:r,storage:o,threadId:s,rolloutPath:i,idle:e.includes("--idle")});console.log(JSON.stringify(a,null,2));return}if(t==="recover"){let s=Number(Nt(e,"--limit")??100),i=await us(r,o,Number.isFinite(s)?s:100);console.log(JSON.stringify({project:r.name,sessions:i.length,imported:i.reduce((a,c)=>a+c.imported,0)},null,2));return}console.log(`Codex Session Adapter
144
144
 
145
145
  Commands:
146
146
  install-notify
147
147
  sync <thread-id> [--project PATH]
148
148
  recover [--project PATH] [--limit N]
149
- `)}Dd().catch(t=>{process.argv[2]==="notify"&&process.exit(0),console.error(t instanceof Error?t.message:t),process.exit(1)});
149
+ `)}fp().catch(t=>{process.argv[2]==="notify"&&process.exit(0),console.error(t instanceof Error?t.message:t),process.exit(1)});