toolnet-memory 0.3.14 → 0.3.15

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 +25 -1
  4. package/bin/toolnet-memory +5 -0
  5. package/bundle/agy-hook.js +67 -67
  6. package/bundle/agy.js +61 -61
  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 +25 -24
  12. package/bundle/codex.js +71 -71
  13. package/bundle/context-runtime.js +45 -44
  14. package/bundle/context.js +15 -15
  15. package/bundle/continuity-certify.js +13 -13
  16. package/bundle/copilot-hook.js +87 -85
  17. package/bundle/copilot.js +4 -4
  18. package/bundle/cursor-hook.js +87 -85
  19. package/bundle/cursor.js +4 -4
  20. package/bundle/doctor.js +4 -4
  21. package/bundle/full-index.js +20 -20
  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 +60 -59
  26. package/bundle/grok.js +5 -5
  27. package/bundle/handoff-refresh.js +10 -10
  28. package/bundle/help-cli.js +4 -4
  29. package/bundle/impact.js +4 -4
  30. package/bundle/incremental.js +5 -4
  31. package/bundle/init.js +37 -37
  32. package/bundle/integration-status.js +4 -4
  33. package/bundle/kiro-hook.js +82 -81
  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 +80 -80
  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 +9 -3
  48. package/release-manifest.json +54 -3
@@ -1,15 +1,15 @@
1
- import{existsSync as Xs,readFileSync as Zs}from"node:fs";import{homedir as eo}from"node:os";import{join as to}from"node:path";function no(e){let t=e.trim();return t.length>=2&&t.startsWith('"')&&t.endsWith('"')?(t=t.slice(1,-1),t.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):t.length>=2&&t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function ro(){let e=process.env.TOOLNET_GLOBAL_ENV??to(eo(),".config","toolnet-memory",".env");if(!Xs(e))return;let t=Zs(e,"utf8");for(let n of t.split(/\r?\n/)){let r=n.trim();if(!r||r.startsWith("#"))continue;r.startsWith("export ")&&(r=r.slice(7));let 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]=no(r.slice(s+1)))}}ro();function fe(e,t){return e===void 0?t:["1","true","yes","on"].includes(e.toLowerCase())}function pe(e,t){if(!e)return t;let n=Number(e);return Number.isFinite(n)?n:t}function Ne(){return{memory:{autoCapture:fe(process.env.MEMORY_AUTO_CAPTURE,!0),autoRetrieve:fe(process.env.MEMORY_AUTO_RETRIEVE,!0),autoSummarize:fe(process.env.MEMORY_AUTO_SUMMARIZE,!0),autoSync:fe(process.env.MEMORY_AUTO_SYNC,!0)},retrieval:{maxCandidates:pe(process.env.MEMORY_MAX_CANDIDATES,50),rerankTop:pe(process.env.MEMORY_RERANK_TOP,10),finalContext:pe(process.env.MEMORY_FINAL_CONTEXT,5),tokenBudget:pe(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:fe(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:pe(process.env.MEMORY_LOCAL_CACHE_MB,200)}}}import{createHash as so}from"node:crypto";import{existsSync as xt,mkdirSync as oo,readFileSync as io,renameSync as ao,writeFileSync as co}from"node:fs";import{basename as uo,dirname as _e,join as Fe,parse as ln,resolve as me}from"node:path";var dn=".toolnet",lo="project.json";function fo(e){return so("sha256").update(e).digest("hex").slice(0,16)}function jt(e){return Fe(e,dn,lo)}function po(e){return xt(jt(e))}function mo(e,t){let n=me(e),r=ln(n).root;for(;;){if(po(n))return n;if(n===r||t&&n===me(t))break;let s=_e(n);if(s===n)break;n=s}return null}function go(e){let t=me(e),n=ln(t).root,r=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(r.some(o=>xt(Fe(t,o))))return t;if(t===n)break;let s=_e(t);if(s===t)break;t=s}return me(e)}function yo(e){let t;try{t=JSON.parse(io(e,"utf8"))}catch(s){throw new Error(`Invalid ToolNet project manifest: ${e}: ${s instanceof Error?s.message:String(s)}`)}if(!t||typeof t!="object")throw new Error(`Invalid ToolNet project manifest: ${e}`);let n=t;if(typeof n.id!="string"||!n.id.trim())throw new Error(`ToolNet project manifest is missing id: ${e}`);if(typeof n.name!="string"||!n.name.trim())throw new Error(`ToolNet project manifest is missing name: ${e}`);let r=new Date().toISOString();return{version:1,id:n.id,name:n.name,remote:typeof n.remote=="string"&&n.remote.trim()?n.remote:n.name,rootPath:typeof n.rootPath=="string"?n.rootPath:_e(_e(e)),createdAt:typeof n.createdAt=="string"?n.createdAt:r,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:r,graphVersion:typeof n.graphVersion=="number"?n.graphVersion:0,memoryVersion:typeof n.memoryVersion=="number"?n.memoryVersion:0,metadata:n.metadata&&typeof n.metadata=="object"?n.metadata:void 0}}function cn(e,t){let n=Fe(e,dn);oo(n,{recursive:!0});let r=jt(e),s=`${r}.tmp-${process.pid}`;co(s,JSON.stringify(t,null,2)+`
3
- `,{encoding:"utf8",mode:384}),ao(s,r)}function un(e,t){return{id:e.id,name:e.name,remote:e.remote,rootPath:t,createdAt:e.createdAt,updatedAt:e.updatedAt,graphVersion:e.graphVersion,memoryVersion:e.memoryVersion,metadata:e.metadata}}var $e=class{detect(t=process.cwd()){let n=me(t),r=go(n),o=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(f=>xt(Fe(r,f))),i=mo(n,o?r:void 0);if(i){let f=jt(i),l=yo(f);return l.rootPath!==i&&(l.rootPath=i,l.updatedAt=new Date().toISOString(),cn(i,l)),un(l,i)}let a=new Date().toISOString(),c=uo(r),u={version:1,id:fo(r),name:c,remote:c,rootPath:r,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0};return cn(r,u),un(u,r)}};var ho=[{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(t){let n=[];for(let r of ho){let s=new RegExp(r.regex.source,r.regex.flags);for(let o of t.matchAll(s))n.push({type:r.type,value:o[0]})}return n}hasSecrets(t){return this.scan(t).length>0}};var U=class{scanner=new Ke;sanitize(t){let n=t,r=this.scanner.scan(t),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(t){if(typeof t=="string")return this.sanitize(t).text;if(Array.isArray(t))return t.map(n=>this.sanitizeValue(n));if(t&&typeof t=="object"){let n={};for(let[r,s]of Object.entries(t)){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 t}};import{homedir as Wo}from"node:os";import{join as Do}from"node:path";import{DeleteObjectCommand as ko,GetObjectCommand as So,HeadObjectCommand as vo,ListObjectsV2Command as wo,PutObjectCommand as bo,S3Client as xo}from"@aws-sdk/client-s3";import{getSignedUrl as jo}from"@aws-sdk/s3-request-presigner";var Le=class{name="huggingface";client;bucket;constructor(t){this.bucket=t.bucket,this.client=new xo({region:"us-east-1",endpoint:`https://s3.hf.co/${t.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}})}async put(t,n,r="application/octet-stream"){let s=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new bo({Bucket:this.bucket,Key:t,Body:s,ContentType:r}))}async get(t){let n=await jo(this.client,new So({Bucket:this.bucket,Key:t}),{expiresIn:60}),r=await fetch(n,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`HF download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(t){let n=await this.get(t);return n?Buffer.from(n).toString("utf8"):null}async exists(t){try{return await this.client.send(new vo({Bucket:this.bucket,Key:t})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(t){await this.client.send(new ko({Bucket:this.bucket,Key:t}))}async list(t=""){let n=[],r;do{let s=await this.client.send(new wo({Bucket:this.bucket,Prefix:t||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 fn,mkdir as Mo,readFile as Ao,readdir as Io,rm as Co,stat as pn,writeFile as Po}from"node:fs/promises";import{dirname as To,join as Eo,relative as mn,resolve as Oo}from"node:path";var ge=class{constructor(t){this.root=t}root;name="local";path(t){let n=t.replace(/^\/+/,"");return Oo(this.root,n)}async put(t,n){let r=this.path(t);await Mo(To(r),{recursive:!0}),await Po(r,n)}async get(t){try{return await Ao(this.path(t))}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT")return null;throw n}}async getText(t){let n=await this.get(t);return n?Buffer.from(n).toString("utf8"):null}async exists(t){try{return await fn(this.path(t)),!0}catch{return!1}}async delete(t){await Co(this.path(t),{force:!0})}async list(t=""){let n=this.path(t),r=[];try{await fn(n)}catch{return r}let s=async i=>{let a=await Io(i,{withFileTypes:!0});for(let c of a){let u=Eo(i,c.name);if(c.isDirectory()){await s(u);continue}let f=await pn(u);r.push({key:mn(this.root,u),size:f.size,updatedAt:f.mtime.toISOString()})}},o=await pn(n);return o.isDirectory()?await s(n):r.push({key:mn(this.root,n),size:o.size,updatedAt:o.mtime.toISOString()}),r}};import{DeleteObjectCommand as Ro,GetObjectCommand as No,HeadObjectCommand as _o,ListObjectsV2Command as $o,PutObjectCommand as Fo,S3Client as Ko}from"@aws-sdk/client-s3";import{getSignedUrl as Lo}from"@aws-sdk/s3-request-presigner";var ye=class{name;client;bucket;constructor(t){this.name=t.name??"s3",this.bucket=t.bucket,this.client=new Ko({region:t.region??"us-east-1",endpoint:t.endpoint||void 0,forcePathStyle:t.forcePathStyle??!1,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}})}async put(t,n,r="application/octet-stream"){let s=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new Fo({Bucket:this.bucket,Key:t,Body:s,ContentType:r}))}async get(t){let n=await Lo(this.client,new No({Bucket:this.bucket,Key:t}),{expiresIn:60}),r=await fetch(n,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`${this.name} download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(t){let n=await this.get(t);return n?Buffer.from(n).toString("utf8"):null}async exists(t){try{return await this.client.send(new _o({Bucket:this.bucket,Key:t})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(t){await this.client.send(new Ro({Bucket:this.bucket,Key:t}))}async list(t=""){let n=[],r;do{let s=await this.client.send(new $o({Bucket:this.bucket,Prefix:t||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 Mt(e,t){return console.warn(t),new ge(e)}function gn(e){let t=e.localRoot??Do(Wo(),".toolnet-memory","storage");if(e.provider==="r2"){let n=e.r2;return n?.accountId&&n.bucket&&n.accessKeyId&&n.secretAccessKey?new ye({name:"r2",endpoint:`https://${n.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:n.bucket,forcePathStyle:!0,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Mt(t,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(e.provider==="s3"){let n=e.s3;return n?.bucket&&n.accessKeyId&&n.secretAccessKey?new ye({name:"s3",endpoint:n.endpoint,region:n.region??"us-east-1",bucket:n.bucket,forcePathStyle:n.forcePathStyle??!1,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Mt(t,"[storage] S3 credentials missing. Using local fallback.")}if(e.provider==="huggingface"){let n=e.huggingface;return n?.namespace&&n.bucket&&n.accessKeyId&&n.secretAccessKey?new Le({namespace:n.namespace,bucket:n.bucket,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Mt(t,"[storage] Hugging Face credentials missing. Using local fallback.")}return new ge(t)}function zo(e){return new Promise(t=>setTimeout(t,e))}async function yn(e,t={}){let n=Math.max(1,t.attempts??3),r=t.baseDelayMs??150,s=t.maxDelayMs??2e3,o;for(let i=1;i<=n;i++)try{return await e()}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 zo(c+u)}throw o}var qo=new Set(["put","get","getText","delete","list"]);function hn(e,t={}){return new Proxy(e,{get(n,r){let s=Reflect.get(n,r,n);return typeof s!="function"?s:qo.has(r)?(...o)=>yn(()=>Promise.resolve(s.apply(n,o)),t):s.bind(n)}})}function kn(e){let t=e.trim().replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,"").slice(0,100);if(!t||t==="."||t==="..")throw new Error("Invalid project storage folder");return t}function Sn(e){let t=e.replace(/^\/+/,"");if(t.startsWith("memories/"))return"memory/records/"+t.slice(9);if(t.startsWith("vectors/"))return"memory/vectors/"+t.slice(8);if(t.startsWith("graph/"))return"code/graph/"+t.slice(6);let n=t.match(/^(snapshots\/[^/]+\/)memories\/(.+)$/);if(n)return`${n[1]}memory/records/${n[2]}`;if(n=t.match(/^(snapshots\/[^/]+\/)vectors\/(.+)$/),n)return`${n[1]}memory/vectors/${n[2]}`;if(n=t.match(/^(snapshots\/[^/]+\/)graph\/(.+)$/),n)return`${n[1]}code/graph/${n[2]}`;let r=t.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(r)return`${r[1]}memory/records/${r[2]}`;if(r=t.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),r)return`${r[1]}memory/vectors/${r[2]}`;if(r=t.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),r)return`${r[1]}code/graph/${r[2]}`;let s=t.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return s?`${s[1]}memory/records/${s[2]}`:(s=t.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),s?`${s[1]}memory/vectors/${s[2]}`:(s=t.match(/^(projects\/[^/]+\/)graph\/(.+)$/),s?`${s[1]}code/graph/${s[2]}`:t))}var We=class{constructor(t,n,r,s){this.provider=t;this.name=t.name,this.projectId=n,this.projectName=r,this.folder=kn(s??r),this.sourcePrefix=`projects/${n}`,this.targetPrefix=`projects/${this.folder}`}provider;name;folder;sourcePrefix;targetPrefix;projectId;projectName;registryPromise;async registerProject(){let t=`${this.targetPrefix}/project.json`,n=new Date().toISOString(),r=n,s=await this.provider.getText(t);if(s){let i;try{i=JSON.parse(s)}catch(a){throw new Error(`Invalid remote ToolNet project manifest at ${t}: ${a instanceof Error?a.message:String(a)}`)}if(typeof i.id=="string"&&i.id!==this.projectId)throw new Error(["ToolNet remote project namespace collision.",`Remote folder: ${this.targetPrefix}`,`Existing project id: ${i.id}`,`Current project id: ${this.projectId}`,"Refusing to mix data from two projects."].join(" "));typeof i.createdAt=="string"&&(r=i.createdAt)}let o={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:r,updatedAt:n};await this.provider.put(t,JSON.stringify(o,null,2)+`
4
- `,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(t){if(t=Sn(t),t===this.sourcePrefix)return this.targetPrefix;if(t.startsWith(`${this.sourcePrefix}/`))return this.targetPrefix+t.slice(this.sourcePrefix.length);if(t===this.targetPrefix||t.startsWith(`${this.targetPrefix}/`))return t;if(t.startsWith("projects/"))throw new Error(["Cross-project storage access denied.",`Current project: ${this.targetPrefix}`,`Requested key: ${t}`].join(" "));return t}async put(t,n,r){return await this.ensureRegistered(),this.provider.put(this.key(t),n,r)}async get(t){return await this.ensureRegistered(),this.provider.get(this.key(t))}async getText(t){return await this.ensureRegistered(),this.provider.getText(this.key(t))}async delete(t){return await this.ensureRegistered(),this.provider.delete(this.key(t))}async exists(t){return await this.ensureRegistered(),this.provider.exists(this.key(t))}async list(t){return await this.ensureRegistered(),this.provider.list(this.key(t))}};import{spawn as Bo}from"node:child_process";function vn(e){return(e??"").trim()}function wn(e,t={}){let n=vn(e);if(!n)return!1;let r=vn(t.binary??process.env.TOOLNET_MEMORY_BIN)||"toolnet-memory";try{let s=Bo(r,["background:refresh","--project",n,"--quiet"],{detached:!0,stdio:"ignore",env:process.env});return s.on("error",()=>{}),s.unref(),!0}catch{return!1}}import{createHash as Vo}from"node:crypto";import{dirname as Ho}from"node:path";import{mkdirSync as Jo,readFileSync as Go,renameSync as Uo,writeFileSync as Yo}from"node:fs";function v(e){return Vo("sha256").update(e).digest("hex")}function At(e){if(Array.isArray(e))return e.map(At);if(e&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=At(t[r]);return n}return e}function bn(e){return JSON.stringify(At(e))}function xn(e){try{return JSON.parse(Go(e,"utf8"))}catch{return null}}function P(e,t){Jo(Ho(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;Yo(n,JSON.stringify(t,null,2)+`
5
- `,{encoding:"utf8",mode:384}),Uo(n,e)}function jn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ke(e){return e.toLowerCase().replace(/[^a-z0-9]/gu,"")}function he(e,t,n=0){if(n>8)return;if(Array.isArray(e)){for(let s of e.slice(0,50))he(s,t,n+1);return}let r=jn(e);if(r)for(let[s,o]of Object.entries(r))t(s,o,r),he(o,t,n+1)}function re(e,t){let n=[];return he(e,(r,s)=>{t.has(ke(r))&&typeof s=="string"&&s.trim()&&n.push(s.trim())}),n}function Qo(e){let t=e.trim();if(!t.startsWith("{"))return null;try{return jn(JSON.parse(t))}catch{return null}}function Xo(e){let t=e.data;for(let r of["tool","toolName","tool_name"]){let s=t[r];if(typeof s=="string"&&s.trim())return s.trim().toLowerCase()}let n="";return he(t,(r,s,o)=>{if(n)return;let i=ke(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 Zo(e){let t=re(e.data,new Set(["command","cmd","script"])),n=re(e.data,new Set(["arguments","args"]));for(let r of n){let s=Qo(r);if(s)for(let o of re(s,new Set(["command","cmd","script"])))t.push(o)}return Array.from(new Set(t.map(r=>r.trim()).filter(Boolean)))}function ei(e){let t=re(e.data,new Set(["filepath","file_path","filename","file","path","target"].map(ke)));return Array.from(new Set(t.map(n=>n.trim()).filter(n=>n.length>0&&n.length<1e3&&!n.includes(`
6
- `))))}function ti(e,t){return e.type==="file_edit"||e.type==="file_write"?"modified":/\b(delete|remove|unlink)\b/iu.test(t)?"deleted":/\b(create|add[_-]?file|new[_-]?file)\b/iu.test(t)?"created":/\b(edit|write|patch|apply[_-]?patch|replace|update[_-]?file)\b/iu.test(t)?"modified":null}function ni(e){let t=re(e.data,new Set(["patch","diff","arguments","input"].map(ke))),n=[];for(let r of t){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 ri(e){let t=e.toLowerCase();return/\b(typecheck|type-check)\b/u.test(t)||/\btsc\b[\s\S]*--noemit\b/u.test(t)?"typecheck":/\b(eslint|lint)\b/u.test(t)?"lint":/\b(vitest|jest|pytest)\b/u.test(t)||/\bgo\s+test\b/u.test(t)||/\bcargo\s+test\b/u.test(t)||/\b(npm|pnpm|yarn)\s+(run\s+)?test\b/u.test(t)?"test":/\b(npm|pnpm|yarn)\s+(run\s+)?build\b/u.test(t)||/\bcargo\s+build\b/u.test(t)||/\bgo\s+build\b/u.test(t)||/\btsc\b/u.test(t)?"build":null}function si(e){let t=null;return he(e,(n,r)=>{if(t===null&&["exitcode","code"].includes(ke(n))){if(typeof r=="number"&&Number.isFinite(r)){t=r;return}if(typeof r=="string"){let s=Number(r);Number.isFinite(s)&&(t=s)}}}),t}function oi(e){return re(e,new Set(["status","state","result","output","outputsummary","message","text"]))}function ii(e){let t=si(e.data);if(t!==null)return t===0?"passed":"failed";let n=oi(e.data).join(`
7
- `).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 ai(e){let t=[],n=new Set;for(let r of e){let s=[r.kind,r.fileAction??"",r.checkKind??"",r.checkStatus??"",r.text].join("|");n.has(s)||(n.add(s),t.push(r))}return t}function Mn(e){let t=[],n=Xo(e),r=ti(e,n);if(r)for(let s of ei(e))t.push({kind:"file",text:s,fileAction:r,confidence:e.type==="file_edit"||e.type==="file_write"?1:.96});t.push(...ni(e));for(let s of Zo(e)){t.push({kind:"command",text:s,confidence:.98});let o=ri(s);o&&t.push({kind:"test",text:s,checkKind:o,checkStatus:ii(e),confidence:.98})}return ai(t)}var ci=new Set(["content","text","message","prompt","summary","description","title","reason","last_assistant_message","lastAssistantMessage"]);function Q(e){return e.normalize("NFKC").replace(/\s+/g," ").replace(/^[\s>*#•-]+/u,"").trim()}function In(e){return Q(e).toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function Y(e,t,n=0){if(!(n>6)){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let r of e.slice(0,50))Y(r,t,n+1);return}if(!(!e||typeof e!="object"))for(let[r,s]of Object.entries(e))(ci.has(r)||["data","payload","parts","messages"].includes(r))&&Y(s,t,n+1)}}function De(e){return/\b(cancelled|canceled)\b|đã hủy|bỏ qua/iu.test(e)?"cancelled":/\b(blocked|blocker)\b|đang vướng|bị vướng|đang kẹt|chưa thể/iu.test(e)?"blocked":/\b(completed|complete|done|finished|passed)\b|hoàn thành|hoàn tất|đã xong|đã làm xong|\bxong\b/iu.test(e)?"completed":/\bin[\s_-]*progress\b|working on|đang làm|đang thực hiện|đang xử lý|đang triển khai/iu.test(e)?"in_progress":"pending"}function An(e){let t=Q(e);return/^(?:đang\s+làm|đang\s+thực\s+hiện|đang\s+xử\s+lý|đang\s+triển\s+khai|hoàn\s+thành|hoàn\s+tất|đã\s+xong|đã\s+làm\s+xong|xong|pending|in[\s_-]*progress|completed|complete|done|finished|blocked|cancelled|canceled)[.!]*$/iu.test(t)}function A(e,t,n,r,s={}){let o=Q(r),i=s.key??In(o);return{version:1,id:v([e.projectId,n,i,t.id,o,s.status??"",s.fileAction??"",s.checkKind??"",s.checkStatus??"",s.order??""].join("|")).slice(0,32),projectId:e.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:t.timestamp,sequence:t.sequence,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,eventId:t.id,sourceEventId:t.sourceEventId}}function ui(e,t,n){let r=Q(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(A(e,t,"goal",i[1],{confidence:.97}));let a=r.match(/^(?:kế hoạch|plan)\s*(?::|-)\s*(.+)$/iu);a?.[1]&&s.push(A(e,t,"plan",a[1],{confidence:.95}));let c=/\b(?:phase|giai đoạn|giai doan|stage)\s*(\d+)\s*(?:[:\-–—]\s*)?([^.;\n]{0,220})/giu,u;for(;!o&&(u=c.exec(r));){let p=Number(u[1]),d=Q(u[2]??""),g=d&&!An(d)?`Phase ${p} - ${d}`:`Phase ${p}`;s.push(A(e,t,"phase",g,{key:`phase:${p}`,order:p,status:De(r),confidence:.93}))}let f=n.match(/^\s*[-*]\s*\[([ xX])\]\s*(.+)$/u);f?.[2]&&s.push(A(e,t,"task",f[2],{status:f[1].trim()?"completed":De(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=Q(l[2]),g=An(d);s.push(A(e,t,"task",g&&p!==void 0?`TODO ${p}`:d,{key:p!==void 0?`task:${p}`:In(d),order:p,status:De(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&&s.push(A(e,t,"next_action",p,{confidence:.9}))}return/\b(blocker|blocked)\b|đang vướng|bị vướng|đang kẹt/iu.test(r)&&s.push(A(e,t,"blocker",r,{confidence:.9})),/\b(chú ý|lưu ý|warning|attention|cẩn thận)\b/iu.test(r)&&s.push(A(e,t,"warning",r,{confidence:.88})),/\b(chốt|quyết định|decided|decision)\b/iu.test(r)&&s.push(A(e,t,"decision",r,{confidence:.9})),r.length<=300&&/^(?:đang\s+(?:sửa|cập nhật|triển khai|xử lý|làm|refactor|fix)|(?:i(?:'m| am)\s+)?(?:working on|implementing|fixing|refactoring|updating|editing)\b)/iu.test(r)&&s.push(A(e,t,"activity",r,{confidence:.86})),s}function ze(e,t){if(t.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 t){if(i.type==="user_prompt"||i.role==="user"){let c=[];Y(i.data,c);let u=c.map(f=>Q(f)).find(f=>f.length>=8&&f.length<=1200&&!/^\[?toolnet\b/iu.test(f));u&&s(A(e,i,"request",u,{confidence:.96}))}for(let c of Mn(i))s(A(e,i,c.kind,c.text,{fileAction:c.fileAction,checkKind:c.checkKind,checkStatus:c.checkStatus,status:c.kind==="test"?c.checkStatus==="passed"?"completed":c.checkStatus==="failed"?"blocked":c.checkStatus==="running"?"in_progress":"pending":void 0,confidence:c.confidence}));if(i.type==="decision"){let c=[];Y(i.data,c);for(let u of c)s(A(e,i,"decision",u,{confidence:1}))}if(i.type==="todo"){let c=[];Y(i.data,c);for(let u of c)s(A(e,i,"task",u,{status:De(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(A(e,i,"file",u,{fileAction:"modified",confidence:1}))}if(i.type==="test"){let c=[];Y(i.data,c);for(let u of c)s(A(e,i,"test",u,{confidence:1}))}let a=[];Y(i.data,a);for(let c of a)for(let u of c.split(/\n+/u))for(let f of ui(e,i,u))s(f)}let o=t[t.length-1];return s(A(e,o,"session",`${e.agent}:${e.nativeSessionId}`,{key:e.sessionKey,confidence:1})),n}function Cn(e){return String(e).padStart(12,"0")}var qe=class{constructor(t){this.storage=t}storage;async write(t,n){if(n.length===0)return null;let r=Math.min(...n.map(f=>f.sequence)),s=Math.max(...n.map(f=>f.sequence)),o={version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,createdAt:n.map(f=>f.occurredAt).sort().at(-1)??new Date().toISOString(),firstSequence:r,lastSequence:s,observations:n},i=JSON.stringify(o,null,2)+`
8
- `,a=v(n.map(f=>JSON.stringify(f)).sort().join(`
9
- `)).slice(0,24),c=v(t.sessionKey).slice(0,12),u=[`projects/${t.projectId}`,"work","observations",`${Cn(r)}-${Cn(s)}-${c}-${a}.json`].join("/");return await this.storage.put(u,i,"application/json"),u}};import{join as Pn}from"node:path";import{mkdirSync as li}from"node:fs";function En(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function $(e,t=20){let n=[],r=new Set;for(let s of e.slice().reverse()){let o=En(s);if(!(!o||r.has(o))&&(r.add(o),n.push(s),n.length>=t))break}return n.reverse()}function di(e,t=20){let n=new Map;for(let r of e){let s=`${r.kind}|${En(r.command)}`;n.delete(s),n.set(s,r)}return Array.from(n.values()).slice(-t)}function fi(e){return e.kind==="phase"?/^Phase\s+\d+$/iu.test(e.text):e.kind==="task"?/^(?:TODO|Task|Việc)\s+\d+$/iu.test(e.text):!1}function Tn(e,t){let n=t.status??e?.status??"pending",r=n;e&&(e.status==="completed"&&n!=="completed"?r="completed":n==="pending"&&(e.status==="in_progress"||e.status==="blocked")&&(r=e.status));let s=e&&fi(t)?e.title:t.text;return{id:e?.id??v(t.key).slice(0,24),title:s,status:r,order:t.order??e?.order,confidence:Math.max(t.confidence,e?.confidence??0),updatedAt:t.occurredAt,updatedBy:{agent:t.agent,nativeSessionId:t.nativeSessionId,eventId:t.eventId}}}async function On(e,t){let n=`projects/${e.id}/work/observations/`,r=await t.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 t.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 Se(e,t){let r=(await On(e,t)).flatMap(m=>m.observations).sort((m,b)=>{let q=m.occurredAt.localeCompare(b.occurredAt);if(q!==0)return q;let an=m.sequence-b.sequence;return an!==0?an:m.id.localeCompare(b.id)}),s=new Map,o=new Map,i,a,c,u,f,l=[],p=[],d=[],g=[],k=[],y=new Map,h=[],S=[],T=[],E=[],C=[],O=[];for(let m of r)switch(m.kind){case"request":i=m.text;break;case"activity":a=m.text;break;case"goal":c=m.text;break;case"plan":u=m.text;break;case"phase":s.set(m.key,Tn(s.get(m.key),m));break;case"task":o.set(m.key,Tn(o.get(m.key),m));break;case"decision":l.push(m.text);break;case"blocker":p.push(m.text);break;case"warning":d.push(m.text);break;case"next_action":g.push(m.text);break;case"file":{k.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"?S.push(m.text):b==="deleted"&&T.push(m.text);break}case"command":E.push(m.text);break;case"test":C.push(m.text),m.checkKind&&O.push({kind:m.checkKind,command:m.text,status:m.checkStatus??"unknown",updatedAt:m.occurredAt,agent:m.agent,nativeSessionId:m.nativeSessionId});break;case"session":f={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)),W=x.find(m=>m.status==="in_progress")??x.find(m=>m.status==="blocked")??x.find(m=>m.status==="pending"),D=w.find(m=>m.status==="in_progress")??w.find(m=>m.status==="blocked")??w.find(m=>m.status==="pending"),wt=$([...g,...D?[D.title]:[],...!D&&W?[W.title]:[],...w.filter(m=>m.status==="pending").slice(0,5).map(m=>m.title)],8),bt=$([...p,...x.filter(m=>m.status==="blocked").map(m=>m.title),...w.filter(m=>m.status==="blocked").map(m=>m.title)],20),le={version:1,projectId:e.id,projectName:e.name,currentRequest:i,currentActivity:a,goal:c,plan:u,phases:x,tasks:w,decisions:$(l,20),blockers:bt,warnings:$(d,20),nextActions:wt,filesTouched:$(k,30),activeFiles:Array.from(y.entries()).filter(([,m])=>m!=="deleted").map(([m])=>m).slice(-5),modifiedFiles:$(h,30),createdFiles:$(S,30),deletedFiles:$(T,30),commands:$(E,20),tests:$(C,20),checks:di(O,20),currentPhase:W,currentTask:D,progress:{phasesTotal:x.length,phasesCompleted:x.filter(m=>m.status==="completed").length,tasksTotal:w.length,tasksCompleted:w.filter(m=>m.status==="completed").length,blocked:x.filter(m=>m.status==="blocked").length+w.filter(m=>m.status==="blocked").length},lastSession:f,updatedAt:r.length?r[r.length-1].occurredAt:new Date().toISOString()},de=Pn(e.rootPath,".toolnet","work");return li(de,{recursive:!0}),P(Pn(de,"current.json"),le),await t.put(`projects/${e.id}/work/current.json`,JSON.stringify(le,null,2)+`
10
- `,"application/json"),le}async function se(e,t){if((await On(e,t)).length>0)return Se(e,t);let r=await t.getText(`projects/${e.id}/work/current.json`);if(!r)return null;try{return JSON.parse(r)}catch{return null}}import{closeSync as pi,existsSync as mi,openSync as gi,readSync as yi,statSync as hi}from"node:fs";function ki(e,t){if(!mi(e))return{events:[],nextOffset:t};let n=hi(e).size,r=Number.isFinite(t)?Math.max(0,t):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let s=n-r,o=Buffer.alloc(s),i=gi(e,"r");try{yi(i,o,0,s,r)}finally{pi(i)}let a=o.toString("utf8"),c=a.lastIndexOf(`
1
+ import{existsSync as so,readFileSync as oo}from"node:fs";import{homedir as io}from"node:os";import{join as ao}from"node:path";function co(e){let t=e.trim();return t.length>=2&&t.startsWith('"')&&t.endsWith('"')?(t=t.slice(1,-1),t.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):t.length>=2&&t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function uo(){let e=process.env.TOOLNET_GLOBAL_ENV??ao(io(),".config","toolnet-memory",".env");if(!so(e))return;let t=oo(e,"utf8");for(let n of t.split(/\r?\n/)){let r=n.trim();if(!r||r.startsWith("#"))continue;r.startsWith("export ")&&(r=r.slice(7));let 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]=co(r.slice(s+1)))}}uo();function pe(e,t){return e===void 0?t:["1","true","yes","on"].includes(e.toLowerCase())}function me(e,t){if(!e)return t;let n=Number(e);return Number.isFinite(n)?n:t}function Fe(){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:me(process.env.MEMORY_MAX_CANDIDATES,50),rerankTop:me(process.env.MEMORY_RERANK_TOP,10),finalContext:me(process.env.MEMORY_FINAL_CONTEXT,5),tokenBudget:me(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:me(process.env.MEMORY_LOCAL_CACHE_MB,200)}}}import{createHash as lo}from"node:crypto";import{existsSync as Ke,mkdirSync as fo,readFileSync as po,renameSync as mo,writeFileSync as go}from"node:fs";import{basename as yo,dirname as Le,join as ge,parse as mn,resolve as se}from"node:path";var gn=".toolnet",ho="project.json";function ko(e){return lo("sha256").update(e).digest("hex").slice(0,16)}function We(e){return ge(e,gn,ho)}function So(e){return Ke(We(e))}function ln(e,t){let n=se(e),r=mn(n).root;for(;;){if(So(n))return n;if(n===r||t&&n===se(t))break;let s=Le(n);if(s===n)break;n=s}return null}function dn(e){let t=se(e),n=mn(t).root,r=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(r.some(o=>Ke(ge(t,o))))return t;if(t===n)break;let s=Le(t);if(s===t)break;t=s}return se(e)}function fn(e){let t;try{t=JSON.parse(po(e,"utf8"))}catch(s){throw new Error(`Invalid ToolNet project manifest: ${e}: ${s instanceof Error?s.message:String(s)}`)}if(!t||typeof t!="object")throw new Error(`Invalid ToolNet project manifest: ${e}`);let n=t;if(typeof n.id!="string"||!n.id.trim())throw new Error(`ToolNet project manifest is missing id: ${e}`);if(typeof n.name!="string"||!n.name.trim())throw new Error(`ToolNet project manifest is missing name: ${e}`);let r=new Date().toISOString();return{version:1,id:n.id,name:n.name,remote:typeof n.remote=="string"&&n.remote.trim()?n.remote:n.name,rootPath:typeof n.rootPath=="string"?n.rootPath:Le(Le(e)),createdAt:typeof n.createdAt=="string"?n.createdAt:r,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:r,graphVersion:typeof n.graphVersion=="number"?n.graphVersion:0,memoryVersion:typeof n.memoryVersion=="number"?n.memoryVersion:0,metadata:n.metadata&&typeof n.metadata=="object"?n.metadata:void 0}}function pn(e,t){let n=ge(e,gn);fo(n,{recursive:!0});let r=We(e),s=`${r}.tmp-${process.pid}`;go(s,JSON.stringify(t,null,2)+`
3
+ `,{encoding:"utf8",mode:384}),mo(s,r)}function It(e,t){return{id:e.id,name:e.name,remote:e.remote,rootPath:t,createdAt:e.createdAt,updatedAt:e.updatedAt,graphVersion:e.graphVersion,memoryVersion:e.memoryVersion,metadata:e.metadata}}var De=class{findExisting(t=process.cwd()){let n=se(t),r=dn(n),o=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(c=>Ke(ge(r,c))),i=ln(n,o?r:void 0);if(!i)return null;let a=fn(We(i));return It(a,i)}requireExisting(t=process.cwd()){let n=this.findExisting(t);if(!n)throw new Error("PROJECT_NOT_INITIALIZED");return n}detect(t=process.cwd()){let n=se(t),r=dn(n),o=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(f=>Ke(ge(r,f))),i=ln(n,o?r:void 0);if(i){let f=We(i),l=fn(f);return l.rootPath!==i&&(l.rootPath=i,l.updatedAt=new Date().toISOString(),pn(i,l)),It(l,i)}let a=new Date().toISOString(),c=yo(r),u={version:1,id:ko(r),name:c,remote:c,rootPath:r,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0};return pn(r,u),It(u,r)}};var vo=[{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"}],wo=new Set(["example","example-key","example-token","changeme","change-me","password","secret","your-api-key","your-token","<token>","<secret>","<password>","[redacted]"]);function yn(e){return e.normalize("NFKC").trim().toLowerCase()}function bo(e){if(e.length===0)return 0;let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);let n=0;for(let r of t.values()){let s=r/e.length;n-=s*Math.log2(s)}return n}function xo(e){return/^[a-f0-9]{32}$/iu.test(e)||/^[a-f0-9]{40}$/iu.test(e)||/^[a-f0-9]{64}$/iu.test(e)}function jo(e,t,n){let r=e.slice(Math.max(0,t-48),t),s=e.slice(n,Math.min(e.length,n+16));return/\b(?:token|secret|key|credential|authorization|password|passwd|apikey|api_key|access[_-]?key)\b/iu.test(`${r} ${s}`)}function Mo(e,t){return e.start<t.end&&t.start<e.end}function hn(e){return e.sort((t,n)=>t.start!==n.start?t.start-n.start:n.end-n.start-(t.end-t.start))}var ze=class{allowValues=new Set;enableEntropyHeuristic;constructor(t={}){for(let n of t.allowValues??[]){let r=yn(n);r&&this.allowValues.add(r)}this.enableEntropyHeuristic=t.enableEntropyHeuristic??!0}scan(t){let n=[];for(let o of vo){let i=new RegExp(o.regex.source,o.regex.flags);for(let a of t.matchAll(i))a.index===void 0||!a[0]||this.allowed(a[0])||n.push({type:o.type,value:a[0],start:a.index,end:a.index+a[0].length,confidence:o.confidence})}this.enableEntropyHeuristic&&n.push(...this.entropyMatches(t));let r=hn(n),s=[];for(let o of r)s.some(i=>Mo(i,o))||s.push(o);return hn(s)}hasSecrets(t){return this.scan(t).length>0}allowed(t){let n=yn(t);return wo.has(n)?!0:this.allowValues.has(n)}entropyMatches(t){let n=[],r=/[A-Za-z0-9_+/=-]{32,160}/g;for(let s of t.matchAll(r)){if(s.index===void 0||!s[0])continue;let o=s[0];this.allowed(o)||xo(o)||!/[A-Za-z]/u.test(o)||!/[0-9]/u.test(o)||jo(t,s.index,s.index+o.length)&&(bo(o)<3.7||n.push({type:"high_entropy_secret",value:o,start:s.index,end:s.index+o.length,confidence:"heuristic"}))}return n}};var V=class{scanner;constructor(t={}){this.scanner=new ze(t)}sanitize(t){let n=this.scanner.scan(t);if(n.length===0)return{text:t,redacted:0,secretTypes:[]};let r=t,s=[...n].sort((i,a)=>a.start-i.start),o=new Set;for(let i of s)o.add(i.type),r=r.slice(0,i.start)+`[REDACTED:${i.type}]`+r.slice(i.end);return{text:r,redacted:n.length,secretTypes:[...o].sort()}}sanitizeValue(t){if(typeof t=="string")return this.sanitize(t).text;if(Array.isArray(t))return t.map(n=>this.sanitizeValue(n));if(t&&typeof t=="object"){let n={};for(let[r,s]of Object.entries(t)){let o=r.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"");if(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]";continue}n[r]=this.sanitizeValue(s)}return n}return t}};var Ao=new V;function ye(e){return Ao.sanitizeValue(e)}import{homedir as Uo}from"node:os";import{join as Yo}from"node:path";import{DeleteObjectCommand as Io,GetObjectCommand as Po,HeadObjectCommand as Co,ListObjectsV2Command as To,PutObjectCommand as Eo,S3Client as Oo}from"@aws-sdk/client-s3";import{getSignedUrl as Ro}from"@aws-sdk/s3-request-presigner";var qe=class{name="huggingface";client;bucket;constructor(t){this.bucket=t.bucket,this.client=new Oo({region:"us-east-1",endpoint:`https://s3.hf.co/${t.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}})}async put(t,n,r="application/octet-stream"){let s=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new Eo({Bucket:this.bucket,Key:t,Body:s,ContentType:r}))}async get(t){let n=await Ro(this.client,new Po({Bucket:this.bucket,Key:t}),{expiresIn:60}),r=await fetch(n,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`HF download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(t){let n=await this.get(t);return n?Buffer.from(n).toString("utf8"):null}async exists(t){try{return await this.client.send(new Co({Bucket:this.bucket,Key:t})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(t){await this.client.send(new Io({Bucket:this.bucket,Key:t}))}async list(t=""){let n=[],r;do{let s=await this.client.send(new To({Bucket:this.bucket,Prefix:t||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 kn,mkdir as No,readFile as _o,readdir as $o,rm as Fo,stat as Sn,writeFile as Ko}from"node:fs/promises";import{dirname as Lo,join as Wo,relative as vn,resolve as Do}from"node:path";var he=class{constructor(t){this.root=t}root;name="local";path(t){let n=t.replace(/^\/+/,"");return Do(this.root,n)}async put(t,n){let r=this.path(t);await No(Lo(r),{recursive:!0}),await Ko(r,n)}async get(t){try{return await _o(this.path(t))}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT")return null;throw n}}async getText(t){let n=await this.get(t);return n?Buffer.from(n).toString("utf8"):null}async exists(t){try{return await kn(this.path(t)),!0}catch{return!1}}async delete(t){await Fo(this.path(t),{force:!0})}async list(t=""){let n=this.path(t),r=[];try{await kn(n)}catch{return r}let s=async i=>{let a=await $o(i,{withFileTypes:!0});for(let c of a){let u=Wo(i,c.name);if(c.isDirectory()){await s(u);continue}let f=await Sn(u);r.push({key:vn(this.root,u),size:f.size,updatedAt:f.mtime.toISOString()})}},o=await Sn(n);return o.isDirectory()?await s(n):r.push({key:vn(this.root,n),size:o.size,updatedAt:o.mtime.toISOString()}),r}};import{DeleteObjectCommand as zo,GetObjectCommand as qo,HeadObjectCommand as Bo,ListObjectsV2Command as Vo,PutObjectCommand as Ho,S3Client as Jo}from"@aws-sdk/client-s3";import{getSignedUrl as Go}from"@aws-sdk/s3-request-presigner";var ke=class{name;client;bucket;constructor(t){this.name=t.name??"s3",this.bucket=t.bucket,this.client=new Jo({region:t.region??"us-east-1",endpoint:t.endpoint||void 0,forcePathStyle:t.forcePathStyle??!1,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}})}async put(t,n,r="application/octet-stream"){let s=typeof n=="string"?Buffer.from(n,"utf8"):n;await this.client.send(new Ho({Bucket:this.bucket,Key:t,Body:s,ContentType:r}))}async get(t){let n=await Go(this.client,new qo({Bucket:this.bucket,Key:t}),{expiresIn:60}),r=await fetch(n,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`${this.name} download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.arrayBuffer())}async getText(t){let n=await this.get(t);return n?Buffer.from(n).toString("utf8"):null}async exists(t){try{return await this.client.send(new Bo({Bucket:this.bucket,Key:t})),!0}catch(n){if(typeof n=="object"&&n!==null&&"$metadata"in n&&n.$metadata?.httpStatusCode===404)return!1;throw n}}async delete(t){await this.client.send(new zo({Bucket:this.bucket,Key:t}))}async list(t=""){let n=[],r;do{let s=await this.client.send(new Vo({Bucket:this.bucket,Prefix:t||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 Pt(e,t){return console.warn(t),new he(e)}function wn(e){let t=e.localRoot??Yo(Uo(),".toolnet-memory","storage");if(e.provider==="r2"){let n=e.r2;return n?.accountId&&n.bucket&&n.accessKeyId&&n.secretAccessKey?new ke({name:"r2",endpoint:`https://${n.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:n.bucket,forcePathStyle:!0,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Pt(t,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(e.provider==="s3"){let n=e.s3;return n?.bucket&&n.accessKeyId&&n.secretAccessKey?new ke({name:"s3",endpoint:n.endpoint,region:n.region??"us-east-1",bucket:n.bucket,forcePathStyle:n.forcePathStyle??!1,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Pt(t,"[storage] S3 credentials missing. Using local fallback.")}if(e.provider==="huggingface"){let n=e.huggingface;return n?.namespace&&n.bucket&&n.accessKeyId&&n.secretAccessKey?new qe({namespace:n.namespace,bucket:n.bucket,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey}):Pt(t,"[storage] Hugging Face credentials missing. Using local fallback.")}return new he(t)}function Qo(e){return new Promise(t=>setTimeout(t,e))}async function bn(e,t={}){let n=Math.max(1,t.attempts??3),r=t.baseDelayMs??150,s=t.maxDelayMs??2e3,o;for(let i=1;i<=n;i++)try{return await e()}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 Qo(c+u)}throw o}var Xo=new Set(["put","get","getText","delete","list"]);function xn(e,t={}){return new Proxy(e,{get(n,r){let s=Reflect.get(n,r,n);return typeof s!="function"?s:Xo.has(r)?(...o)=>bn(()=>Promise.resolve(s.apply(n,o)),t):s.bind(n)}})}function jn(e){let t=e.trim().replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,"").slice(0,100);if(!t||t==="."||t==="..")throw new Error("Invalid project storage folder");return t}function Mn(e){let t=e.replace(/^\/+/,"");if(t.startsWith("memories/"))return"memory/records/"+t.slice(9);if(t.startsWith("vectors/"))return"memory/vectors/"+t.slice(8);if(t.startsWith("graph/"))return"code/graph/"+t.slice(6);let n=t.match(/^(snapshots\/[^/]+\/)memories\/(.+)$/);if(n)return`${n[1]}memory/records/${n[2]}`;if(n=t.match(/^(snapshots\/[^/]+\/)vectors\/(.+)$/),n)return`${n[1]}memory/vectors/${n[2]}`;if(n=t.match(/^(snapshots\/[^/]+\/)graph\/(.+)$/),n)return`${n[1]}code/graph/${n[2]}`;let r=t.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(r)return`${r[1]}memory/records/${r[2]}`;if(r=t.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),r)return`${r[1]}memory/vectors/${r[2]}`;if(r=t.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),r)return`${r[1]}code/graph/${r[2]}`;let s=t.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return s?`${s[1]}memory/records/${s[2]}`:(s=t.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),s?`${s[1]}memory/vectors/${s[2]}`:(s=t.match(/^(projects\/[^/]+\/)graph\/(.+)$/),s?`${s[1]}code/graph/${s[2]}`:t))}var Be=class{constructor(t,n,r,s){this.provider=t;this.name=t.name,this.projectId=n,this.projectName=r,this.folder=jn(s??r),this.sourcePrefix=`projects/${n}`,this.targetPrefix=`projects/${this.folder}`}provider;name;folder;sourcePrefix;targetPrefix;projectId;projectName;registryPromise;async registerProject(){let t=`${this.targetPrefix}/project.json`,n=new Date().toISOString(),r=n,s=await this.provider.getText(t);if(s){let i;try{i=JSON.parse(s)}catch(a){throw new Error(`Invalid remote ToolNet project manifest at ${t}: ${a instanceof Error?a.message:String(a)}`)}if(typeof i.id=="string"&&i.id!==this.projectId)throw new Error(["ToolNet remote project namespace collision.",`Remote folder: ${this.targetPrefix}`,`Existing project id: ${i.id}`,`Current project id: ${this.projectId}`,"Refusing to mix data from two projects."].join(" "));typeof i.createdAt=="string"&&(r=i.createdAt)}let o={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:r,updatedAt:n};await this.provider.put(t,JSON.stringify(o,null,2)+`
4
+ `,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(t){if(t=Mn(t),t===this.sourcePrefix)return this.targetPrefix;if(t.startsWith(`${this.sourcePrefix}/`))return this.targetPrefix+t.slice(this.sourcePrefix.length);if(t===this.targetPrefix||t.startsWith(`${this.targetPrefix}/`))return t;if(t.startsWith("projects/"))throw new Error(["Cross-project storage access denied.",`Current project: ${this.targetPrefix}`,`Requested key: ${t}`].join(" "));return t}async put(t,n,r){return await this.ensureRegistered(),this.provider.put(this.key(t),n,r)}async get(t){return await this.ensureRegistered(),this.provider.get(this.key(t))}async getText(t){return await this.ensureRegistered(),this.provider.getText(this.key(t))}async delete(t){return await this.ensureRegistered(),this.provider.delete(this.key(t))}async exists(t){return await this.ensureRegistered(),this.provider.exists(this.key(t))}async list(t){return await this.ensureRegistered(),this.provider.list(this.key(t))}};import{spawn as Zo}from"node:child_process";function An(e){return(e??"").trim()}function In(e,t={}){let n=An(e);if(!n)return!1;let r=An(t.binary??process.env.TOOLNET_MEMORY_BIN)||"toolnet-memory";try{let s=Zo(r,["background:refresh","--project",n,"--quiet"],{detached:!0,stdio:"ignore",env:process.env});return s.on("error",()=>{}),s.unref(),!0}catch{return!1}}import{createHash as ei}from"node:crypto";import{dirname as ti}from"node:path";import{mkdirSync as ni,readFileSync as ri,renameSync as si,writeFileSync as oi}from"node:fs";function w(e){return ei("sha256").update(e).digest("hex")}function Ct(e){if(Array.isArray(e))return e.map(Ct);if(e&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=Ct(t[r]);return n}return e}function Pn(e){return JSON.stringify(Ct(e))}function Cn(e){try{return JSON.parse(ri(e,"utf8"))}catch{return null}}function E(e,t){ni(ti(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;oi(n,JSON.stringify(t,null,2)+`
5
+ `,{encoding:"utf8",mode:384}),si(n,e)}function Tn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ve(e){return e.toLowerCase().replace(/[^a-z0-9]/gu,"")}function Se(e,t,n=0){if(n>8)return;if(Array.isArray(e)){for(let s of e.slice(0,50))Se(s,t,n+1);return}let r=Tn(e);if(r)for(let[s,o]of Object.entries(r))t(s,o,r),Se(o,t,n+1)}function oe(e,t){let n=[];return Se(e,(r,s)=>{t.has(ve(r))&&typeof s=="string"&&s.trim()&&n.push(s.trim())}),n}function ii(e){let t=e.trim();if(!t.startsWith("{"))return null;try{return Tn(JSON.parse(t))}catch{return null}}function ai(e){let t=e.data;for(let r of["tool","toolName","tool_name"]){let s=t[r];if(typeof s=="string"&&s.trim())return s.trim().toLowerCase()}let n="";return Se(t,(r,s,o)=>{if(n)return;let i=ve(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 ci(e){let t=oe(e.data,new Set(["command","cmd","script"])),n=oe(e.data,new Set(["arguments","args"]));for(let r of n){let s=ii(r);if(s)for(let o of oe(s,new Set(["command","cmd","script"])))t.push(o)}return Array.from(new Set(t.map(r=>r.trim()).filter(Boolean)))}function ui(e){let t=oe(e.data,new Set(["filepath","file_path","filename","file","path","target"].map(ve)));return Array.from(new Set(t.map(n=>n.trim()).filter(n=>n.length>0&&n.length<1e3&&!n.includes(`
6
+ `))))}function li(e,t){return e.type==="file_edit"||e.type==="file_write"?"modified":/\b(delete|remove|unlink)\b/iu.test(t)?"deleted":/\b(create|add[_-]?file|new[_-]?file)\b/iu.test(t)?"created":/\b(edit|write|patch|apply[_-]?patch|replace|update[_-]?file)\b/iu.test(t)?"modified":null}function di(e){let t=oe(e.data,new Set(["patch","diff","arguments","input"].map(ve))),n=[];for(let r of t){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 fi(e){let t=e.toLowerCase();return/\b(typecheck|type-check)\b/u.test(t)||/\btsc\b[\s\S]*--noemit\b/u.test(t)?"typecheck":/\b(eslint|lint)\b/u.test(t)?"lint":/\b(vitest|jest|pytest)\b/u.test(t)||/\bgo\s+test\b/u.test(t)||/\bcargo\s+test\b/u.test(t)||/\b(npm|pnpm|yarn)\s+(run\s+)?test\b/u.test(t)?"test":/\b(npm|pnpm|yarn)\s+(run\s+)?build\b/u.test(t)||/\bcargo\s+build\b/u.test(t)||/\bgo\s+build\b/u.test(t)||/\btsc\b/u.test(t)?"build":null}function pi(e){let t=null;return Se(e,(n,r)=>{if(t===null&&["exitcode","code"].includes(ve(n))){if(typeof r=="number"&&Number.isFinite(r)){t=r;return}if(typeof r=="string"){let s=Number(r);Number.isFinite(s)&&(t=s)}}}),t}function mi(e){return oe(e,new Set(["status","state","result","output","outputsummary","message","text"]))}function gi(e){let t=pi(e.data);if(t!==null)return t===0?"passed":"failed";let n=mi(e.data).join(`
7
+ `).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 yi(e){let t=[],n=new Set;for(let r of e){let s=[r.kind,r.fileAction??"",r.checkKind??"",r.checkStatus??"",r.text].join("|");n.has(s)||(n.add(s),t.push(r))}return t}function En(e){let t=[],n=ai(e),r=li(e,n);if(r)for(let s of ui(e))t.push({kind:"file",text:s,fileAction:r,confidence:e.type==="file_edit"||e.type==="file_write"?1:.96});t.push(...di(e));for(let s of ci(e)){t.push({kind:"command",text:s,confidence:.98});let o=fi(s);o&&t.push({kind:"test",text:s,checkKind:o,checkStatus:gi(e),confidence:.98})}return yi(t)}var hi=new Set(["content","text","message","prompt","summary","description","title","reason","last_assistant_message","lastAssistantMessage"]);function X(e){return e.normalize("NFKC").replace(/\s+/g," ").replace(/^[\s>*#•-]+/u,"").trim()}function Rn(e){return X(e).toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function Q(e,t,n=0){if(!(n>6)){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let r of e.slice(0,50))Q(r,t,n+1);return}if(!(!e||typeof e!="object"))for(let[r,s]of Object.entries(e))(hi.has(r)||["data","payload","parts","messages"].includes(r))&&Q(s,t,n+1)}}function Ve(e){return/\b(cancelled|canceled)\b|đã hủy|bỏ qua/iu.test(e)?"cancelled":/\b(blocked|blocker)\b|đang vướng|bị vướng|đang kẹt|chưa thể/iu.test(e)?"blocked":/\b(completed|complete|done|finished|passed)\b|hoàn thành|hoàn tất|đã xong|đã làm xong|\bxong\b/iu.test(e)?"completed":/\bin[\s_-]*progress\b|working on|đang làm|đang thực hiện|đang xử lý|đang triển khai/iu.test(e)?"in_progress":"pending"}function On(e){let t=X(e);return/^(?:đang\s+làm|đang\s+thực\s+hiện|đang\s+xử\s+lý|đang\s+triển\s+khai|hoàn\s+thành|hoàn\s+tất|đã\s+xong|đã\s+làm\s+xong|xong|pending|in[\s_-]*progress|completed|complete|done|finished|blocked|cancelled|canceled)[.!]*$/iu.test(t)}function I(e,t,n,r,s={}){let o=X(r),i=s.key??Rn(o);return{version:1,id:w([e.projectId,n,i,t.id,o,s.status??"",s.fileAction??"",s.checkKind??"",s.checkStatus??"",s.order??""].join("|")).slice(0,32),projectId:e.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:t.timestamp,sequence:t.sequence,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,eventId:t.id,sourceEventId:t.sourceEventId}}function ki(e,t,n){let r=X(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(e,t,"goal",i[1],{confidence:.97}));let a=r.match(/^(?:kế hoạch|plan)\s*(?::|-)\s*(.+)$/iu);a?.[1]&&s.push(I(e,t,"plan",a[1],{confidence:.95}));let c=/\b(?:phase|giai đoạn|giai doan|stage)\s*(\d+)\s*(?:[:\-–—]\s*)?([^.;\n]{0,220})/giu,u;for(;!o&&(u=c.exec(r));){let p=Number(u[1]),d=X(u[2]??""),m=d&&!On(d)?`Phase ${p} - ${d}`:`Phase ${p}`;s.push(I(e,t,"phase",m,{key:`phase:${p}`,order:p,status:Ve(r),confidence:.93}))}let f=n.match(/^\s*[-*]\s*\[([ xX])\]\s*(.+)$/u);f?.[2]&&s.push(I(e,t,"task",f[2],{status:f[1].trim()?"completed":Ve(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=X(l[2]),m=On(d);s.push(I(e,t,"task",m&&p!==void 0?`TODO ${p}`:d,{key:p!==void 0?`task:${p}`:Rn(d),order:p,status:Ve(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&&s.push(I(e,t,"next_action",p,{confidence:.9}))}return/\b(blocker|blocked)\b|đang vướng|bị vướng|đang kẹt/iu.test(r)&&s.push(I(e,t,"blocker",r,{confidence:.9})),/\b(chú ý|lưu ý|warning|attention|cẩn thận)\b/iu.test(r)&&s.push(I(e,t,"warning",r,{confidence:.88})),/\b(chốt|quyết định|decided|decision)\b/iu.test(r)&&s.push(I(e,t,"decision",r,{confidence:.9})),r.length<=300&&/^(?:đang\s+(?:sửa|cập nhật|triển khai|xử lý|làm|refactor|fix)|(?:i(?:'m| am)\s+)?(?:working on|implementing|fixing|refactoring|updating|editing)\b)/iu.test(r)&&s.push(I(e,t,"activity",r,{confidence:.86})),s}function He(e,t){if(t.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 t){if(i.type==="user_prompt"||i.role==="user"){let c=[];Q(i.data,c);let u=c.map(f=>X(f)).find(f=>f.length>=8&&f.length<=1200&&!/^\[?toolnet\b/iu.test(f));u&&s(I(e,i,"request",u,{confidence:.96}))}for(let c of En(i))s(I(e,i,c.kind,c.text,{fileAction:c.fileAction,checkKind:c.checkKind,checkStatus:c.checkStatus,status:c.kind==="test"?c.checkStatus==="passed"?"completed":c.checkStatus==="failed"?"blocked":c.checkStatus==="running"?"in_progress":"pending":void 0,confidence:c.confidence}));if(i.type==="decision"){let c=[];Q(i.data,c);for(let u of c)s(I(e,i,"decision",u,{confidence:1}))}if(i.type==="todo"){let c=[];Q(i.data,c);for(let u of c)s(I(e,i,"task",u,{status:Ve(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(e,i,"file",u,{fileAction:"modified",confidence:1}))}if(i.type==="test"){let c=[];Q(i.data,c);for(let u of c)s(I(e,i,"test",u,{confidence:1}))}let a=[];Q(i.data,a);for(let c of a)for(let u of c.split(/\n+/u))for(let f of ki(e,i,u))s(f)}let o=t[t.length-1];return s(I(e,o,"session",`${e.agent}:${e.nativeSessionId}`,{key:e.sessionKey,confidence:1})),n}function Nn(e){return String(e).padStart(12,"0")}var Je=class{constructor(t){this.storage=t}storage;async write(t,n){if(n.length===0)return null;let r=Math.min(...n.map(f=>f.sequence)),s=Math.max(...n.map(f=>f.sequence)),o={version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,createdAt:n.map(f=>f.occurredAt).sort().at(-1)??new Date().toISOString(),firstSequence:r,lastSequence:s,observations:n},i=JSON.stringify(o,null,2)+`
8
+ `,a=w(n.map(f=>JSON.stringify(f)).sort().join(`
9
+ `)).slice(0,24),c=w(t.sessionKey).slice(0,12),u=[`projects/${t.projectId}`,"work","observations",`${Nn(r)}-${Nn(s)}-${c}-${a}.json`].join("/");return await this.storage.put(u,i,"application/json"),u}};import{join as _n}from"node:path";import{mkdirSync as Si}from"node:fs";function Fn(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function F(e,t=20){let n=[],r=new Set;for(let s of e.slice().reverse()){let o=Fn(s);if(!(!o||r.has(o))&&(r.add(o),n.push(s),n.length>=t))break}return n.reverse()}function vi(e,t=20){let n=new Map;for(let r of e){let s=`${r.kind}|${Fn(r.command)}`;n.delete(s),n.set(s,r)}return Array.from(n.values()).slice(-t)}function wi(e){return e.kind==="phase"?/^Phase\s+\d+$/iu.test(e.text):e.kind==="task"?/^(?:TODO|Task|Việc)\s+\d+$/iu.test(e.text):!1}function $n(e,t){let n=t.status??e?.status??"pending",r=n;e&&(e.status==="completed"&&n!=="completed"?r="completed":n==="pending"&&(e.status==="in_progress"||e.status==="blocked")&&(r=e.status));let s=e&&wi(t)?e.title:t.text;return{id:e?.id??w(t.key).slice(0,24),title:s,status:r,order:t.order??e?.order,confidence:Math.max(t.confidence,e?.confidence??0),updatedAt:t.occurredAt,updatedBy:{agent:t.agent,nativeSessionId:t.nativeSessionId,eventId:t.eventId}}}async function Kn(e,t){let n=`projects/${e.id}/work/observations/`,r=await t.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 t.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 we(e,t){let r=(await Kn(e,t)).flatMap(y=>y.observations).sort((y,S)=>{let T=y.occurredAt.localeCompare(S.occurredAt);if(T!==0)return T;let B=y.sequence-S.sequence;return B!==0?B:y.id.localeCompare(S.id)}),s=new Map,o=new Map,i,a,c,u,f,l=[],p=[],d=[],m=[],k=[],g=new Map,h=[],v=[],x=[],O=[],C=[],R=[];for(let y of r)switch(y.kind){case"request":i=y.text;break;case"activity":a=y.text;break;case"goal":c=y.text;break;case"plan":u=y.text;break;case"phase":s.set(y.key,$n(s.get(y.key),y));break;case"task":o.set(y.key,$n(o.get(y.key),y));break;case"decision":l.push(y.text);break;case"blocker":p.push(y.text);break;case"warning":d.push(y.text);break;case"next_action":m.push(y.text);break;case"file":{k.push(y.text);let S=y.fileAction??"active";g.delete(y.text),g.set(y.text,S),S==="modified"?h.push(y.text):S==="created"?v.push(y.text):S==="deleted"&&x.push(y.text);break}case"command":O.push(y.text);break;case"test":C.push(y.text),y.checkKind&&R.push({kind:y.checkKind,command:y.text,status:y.checkStatus??"unknown",updatedAt:y.occurredAt,agent:y.agent,nativeSessionId:y.nativeSessionId});break;case"session":f={agent:y.agent,nativeSessionId:y.nativeSessionId,sessionKey:y.sessionKey,updatedAt:y.occurredAt};break}let j=Array.from(s.values()).sort((y,S)=>(y.order??Number.MAX_SAFE_INTEGER)-(S.order??Number.MAX_SAFE_INTEGER)),b=Array.from(o.values()).sort((y,S)=>(y.order??Number.MAX_SAFE_INTEGER)-(S.order??Number.MAX_SAFE_INTEGER)),D=j.find(y=>y.status==="in_progress")??j.find(y=>y.status==="blocked")??j.find(y=>y.status==="pending"),z=b.find(y=>y.status==="in_progress")??b.find(y=>y.status==="blocked")??b.find(y=>y.status==="pending"),Mt=F([...m,...z?[z.title]:[],...!z&&D?[D.title]:[],...b.filter(y=>y.status==="pending").slice(0,5).map(y=>y.title)],8),At=F([...p,...j.filter(y=>y.status==="blocked").map(y=>y.title),...b.filter(y=>y.status==="blocked").map(y=>y.title)],20),fe={version:1,projectId:e.id,projectName:e.name,currentRequest:i,currentActivity:a,goal:c,plan:u,phases:j,tasks:b,decisions:F(l,20),blockers:At,warnings:F(d,20),nextActions:Mt,filesTouched:F(k,30),activeFiles:Array.from(g.entries()).filter(([,y])=>y!=="deleted").map(([y])=>y).slice(-5),modifiedFiles:F(h,30),createdFiles:F(v,30),deletedFiles:F(x,30),commands:F(O,20),tests:F(C,20),checks:vi(R,20),currentPhase:D,currentTask:z,progress:{phasesTotal:j.length,phasesCompleted:j.filter(y=>y.status==="completed").length,tasksTotal:b.length,tasksCompleted:b.filter(y=>y.status==="completed").length,blocked:j.filter(y=>y.status==="blocked").length+b.filter(y=>y.status==="blocked").length},lastSession:f,updatedAt:r.length?r[r.length-1].occurredAt:new Date().toISOString()},$e=_n(e.rootPath,".toolnet","work");return Si($e,{recursive:!0}),E(_n($e,"current.json"),fe),await t.put(`projects/${e.id}/work/current.json`,JSON.stringify(fe,null,2)+`
10
+ `,"application/json"),fe}async function ie(e,t){if((await Kn(e,t)).length>0)return we(e,t);let r=await t.getText(`projects/${e.id}/work/current.json`);if(!r)return null;try{return JSON.parse(r)}catch{return null}}import{closeSync as bi,existsSync as xi,openSync as ji,readSync as Mi,statSync as Ai}from"node:fs";function Ii(e,t){if(!xi(e))return{events:[],nextOffset:t};let n=Ai(e).size,r=Number.isFinite(t)?Math.max(0,t):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let s=n-r,o=Buffer.alloc(s),i=ji(e,"r");try{Mi(i,o,0,s,r)}finally{bi(i)}let a=o.toString("utf8"),c=a.lastIndexOf(`
11
11
  `);if(c<0)return{events:[],nextOffset:r};let u=a.slice(0,c+1);return{events:u.split(`
12
- `).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var Be=class{constructor(t){this.options=t;this.journal=new qe(t.storage)}options;journal;async learnNew(){let t=this.options.wal.loadState(),n=Number(t.sourceCursors["work.continuity.offset"]??0),r=ki(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=ze(this.options.identity,r.events),o=!1,i=!1;return s.length>0&&(o=!!await this.journal.write(this.options.identity,s),o&&(await Se(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{existsSync as da,mkdirSync as fa}from"node:fs";import{join as It}from"node:path";import{existsSync as _n,mkdirSync as Si,readFileSync as vi,statSync as Rn,writeFileSync as wi}from"node:fs";import{dirname as bi,join as xi}from"node:path";var Nn=64*1024,ji=`# ToolNet Project Operating Manual
12
+ `).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var Ge=class{constructor(t){this.options=t;this.journal=new Je(t.storage)}options;journal;async learnNew(){let t=this.options.wal.loadState(),n=Number(t.sourceCursors["work.continuity.offset"]??0),r=Ii(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=He(this.options.identity,r.events),o=!1,i=!1;return s.length>0&&(o=!!await this.journal.write(this.options.identity,s),o&&(await we(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{existsSync as va,mkdirSync as wa}from"node:fs";import{join as Tt}from"node:path";import{existsSync as Dn,mkdirSync as Pi,readFileSync as Ci,statSync as Ln,writeFileSync as Ti}from"node:fs";import{dirname as Ei,join as Oi}from"node:path";var Wn=64*1024,Ri=`# ToolNet Project Operating Manual
13
13
 
14
14
  This file contains persistent instructions for AI agents working on this project.
15
15
 
@@ -52,44 +52,44 @@ Things an AI agent should always remember.
52
52
  <!--
53
53
  - [advisory] Prefer small focused files.
54
54
  -->
55
- `;function Ve(e){return xi(e.rootPath,".toolnet","PROJECT.md")}function Mi(e){return e.normalize("NFKC").replace(/\s+/g," ").trim()}function Ai(e){let t=[],n=new Set,r=/^\s*[-*]\s+\[(enforce|advisory)\]\s+(.+?)\s*$/gimu,s;for(;s=r.exec(e);){let o=s[1].toLowerCase(),i=Mi(s[2]);if(!i)continue;let a=`${o}:${i.toLowerCase()}`;n.has(a)||(n.add(a),t.push({id:v(a).slice(0,24),mode:o,text:i,source:"manual"}))}return t}function Ii(e){let t=Ve(e);return _n(t)||(Si(bi(t),{recursive:!0}),wi(t,ji,{encoding:"utf8",mode:384})),t}function He(e,t=!1){let n=t?Ii(e):Ve(e);if(!_n(n))return null;if(Rn(n).size>Nn)throw new Error(`PROJECT.md exceeds ${Nn} bytes`);let s=vi(n,"utf8");return{path:n,content:s,digest:v(s),rules:Ai(s),bytes:Buffer.byteLength(s,"utf8"),updatedAt:new Date(Rn(n).mtimeMs).toISOString()}}import{randomUUID as Ci}from"node:crypto";import{closeSync as Pi,existsSync as $n,fsyncSync as Ti,mkdirSync as Ei,openSync as Oi,readFileSync as Ri,statSync as Ni,unlinkSync as Fn,writeFileSync as _i}from"node:fs";import{dirname as $i,join as Fi}from"node:path";var Ki=new Int32Array(new SharedArrayBuffer(4));function Li(e){e<=0||Atomics.wait(Ki,0,0,e)}function Wi(e){return Fi(e.rootPath,".toolnet","work",".current.lock")}function Di(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code!=="ESRCH"}}function Kn(e){if(!$n(e))return null;try{let t=JSON.parse(Ri(e,"utf8"));return t.version!==1||typeof t.token!="string"||typeof t.pid!="number"||typeof t.acquiredAt!="string"?null:{version:1,token:t.token,pid:t.pid,acquiredAt:t.acquiredAt}}catch{return null}}function zi(e){try{return Date.now()-Ni(e).mtimeMs}catch{return 0}}function qi(e,t){if(!$n(e)||zi(e)<t)return!1;let n=Kn(e);return n?!Di(n.pid):!0}function Bi(e,t){if(!qi(e,t))return!1;try{return Fn(e),!0}catch{return!1}}function Vi(e,t){let n={version:1,token:t,pid:process.pid,acquiredAt:new Date().toISOString()},r=Oi(e,"wx",384);try{_i(r,`${JSON.stringify(n,null,2)}
56
- `,{encoding:"utf8"}),Ti(r)}finally{Pi(r)}}function Hi(e,t){if(Kn(e)?.token===t)try{Fn(e)}catch{}}function Ji(e,t={}){let n=Math.max(100,t.timeoutMs??5e3),r=Math.max(5,t.retryMs??20),s=Math.max(n*2,t.staleMs??3e4),o=Wi(e);Ei($i(o),{recursive:!0});let i=Ci(),a=Date.now()+n;for(;;)try{Vi(o,i);let c=!1;return()=>{c||(c=!0,Hi(o,i))}}catch(c){if(c?.code!=="EEXIST")throw c;if(Bi(o,s))continue;if(Date.now()>=a)throw new Error(`Timed out acquiring project work lock: ${o}`);Li(r)}}function Ln(e,t,n={}){let r=Ji(e,n);try{return t()}finally{r()}}import{closeSync as Gi,existsSync as Ui,fsyncSync as Yi,mkdirSync as Qi,openSync as Xi,readFileSync as Zi,renameSync as ea,writeFileSync as ta}from"node:fs";import{dirname as na,join as ra}from"node:path";function sa(e,t){Qi(na(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`,r=Xi(n,"w",384);try{ta(r,`${JSON.stringify(t,null,2)}
57
- `,{encoding:"utf8"}),Yi(r)}finally{Gi(r)}ea(n,e)}function Vn(e){return ra(e.rootPath,".toolnet","work","current.json")}function ve(e){let t=Vn(e);if(!Ui(t))return null;try{let n=JSON.parse(Zi(t,"utf8"));return n.version!==1||n.projectId!==e.id?null:n}catch{return null}}function Je(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function R(e,t,n){let r=[],s=new Set;for(let o of[...e,...t].reverse()){let i=Je(o);if(!(!i||s.has(i))&&(s.add(i),r.push(o),r.length>=n))break}return r.reverse()}function oa(e,t,n=20){let r=new Map;for(let s of[...e,...t]){let o=`${s.kind}|${Je(s.command)}`;r.delete(o),r.set(o,s)}return Array.from(r.values()).slice(-n)}function ia(e){return e.kind==="phase"?/^Phase\s+\d+$/iu.test(e.text):e.kind==="task"?/^(?:TODO|Task|Việc)\s+\d+$/iu.test(e.text):!1}function Wn(e,t){let n=t.status??e?.status??"pending",r=n;e?.status==="completed"&&n!=="completed"&&(r="completed"),e&&n==="pending"&&(e.status==="in_progress"||e.status==="blocked")&&(r=e.status);let s=e&&ia(t)?e.title:t.text;return{id:e?.id??t.id,title:s,status:r,order:t.order??e?.order,confidence:Math.max(e?.confidence??0,t.confidence),updatedAt:t.occurredAt,updatedBy:{agent:t.agent,nativeSessionId:t.nativeSessionId,eventId:t.eventId}}}function Dn(e){let t=new Map;for(let n of e){let r=n.order!==void 0?`order:${n.order}`:Je(n.title);t.set(r,n)}return t}function zn(e){return e.order!==void 0?`order:${e.order}`:Je(e.key||e.text)}function qn(e){return Array.from(e).sort((t,n)=>{let r=t.order??Number.MAX_SAFE_INTEGER,s=n.order??Number.MAX_SAFE_INTEGER;return r!==s?r-s:t.updatedAt.localeCompare(n.updatedAt)})}function Bn(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="blocked")??e.find(t=>t.status==="pending")}function aa(e,t){let n=ve(e),r=Dn(n?.phases??[]),s=Dn(n?.tasks??[]),o=n?.currentRequest,i=n?.currentActivity,a=n?.goal,c=n?.plan,u=n?.lastSession,f=[],l=[],p=[],d=[],g=[],k=[...n?.activeFiles??[]],y=[],h=[],S=[],T=[],E=[],C=[],O=[...t].sort((m,b)=>{let q=m.occurredAt.localeCompare(b.occurredAt);return q!==0?q:m.sequence-b.sequence});for(let m of O)switch(m.kind){case"request":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=zn(m);r.set(b,Wn(r.get(b),m));break}case"task":{let b=zn(m);s.set(b,Wn(s.get(b),m));break}case"decision":f.push(m.text);break;case"blocker":l.push(m.text);break;case"warning":p.push(m.text);break;case"next_action":d.push(m.text);break;case"file":{g.push(m.text);let b=m.fileAction??"active",q=k.indexOf(m.text);q>=0&&k.splice(q,1),b!=="deleted"&&k.push(m.text),b==="modified"?y.push(m.text):b==="created"?h.push(m.text):b==="deleted"&&S.push(m.text);break}case"command":T.push(m.text);break;case"test":E.push(m.text),m.checkKind&&C.push({kind:m.checkKind,command:m.text,status:m.checkStatus??"unknown",updatedAt:m.occurredAt,agent:m.agent,nativeSessionId:m.nativeSessionId});break;case"session":u={agent:m.agent,nativeSessionId:m.nativeSessionId,sessionKey:m.sessionKey,updatedAt:m.occurredAt};break}let x=qn(r.values()),w=qn(s.values()),W=Bn(x),D=Bn(w),wt=R(n?.nextActions??[],[...d,...D?[D.title]:[],...!D&&W?[W.title]:[],...w.filter(m=>m.status==="pending").slice(0,5).map(m=>m.title)],8),bt=R(n?.blockers??[],[...l,...x.filter(m=>m.status==="blocked").map(m=>m.title),...w.filter(m=>m.status==="blocked").map(m=>m.title)],20),le=O.length>0?O[O.length-1].occurredAt:n?.updatedAt??new Date().toISOString(),de={version:1,projectId:e.id,projectName:e.name,currentRequest:o,currentActivity:i,goal:a,plan:c,phases:x,tasks:w,decisions:R(n?.decisions??[],f,20),blockers:bt,warnings:R(n?.warnings??[],p,20),nextActions:wt,filesTouched:R(n?.filesTouched??[],g,30),activeFiles:R([],k,5),modifiedFiles:R(n?.modifiedFiles??[],y,30),createdFiles:R(n?.createdFiles??[],h,30),deletedFiles:R(n?.deletedFiles??[],S,30),commands:R(n?.commands??[],T,20),tests:R(n?.tests??[],E,20),checks:oa(n?.checks??[],C,20),currentPhase:W,currentTask:D,progress:{phasesTotal:x.length,phasesCompleted:x.filter(m=>m.status==="completed").length,tasksTotal:w.length,tasksCompleted:w.filter(m=>m.status==="completed").length,blocked:x.filter(m=>m.status==="blocked").length+w.filter(m=>m.status==="blocked").length},lastSession:u,updatedAt:le};return sa(Vn(e),de),de}function Hn(e,t){return Ln(e,()=>aa(e,t))}function I(e,t){let n=new Set,r=[];for(let s of e){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>=t))break}return r}function Jn(e){if(e)return{id:e.id,title:e.title,status:e.status}}function ca(e,t=[]){let n=t.slice(-10);if(n.some(s=>s.status==="failed"))return"failing";if(n.some(s=>s.status==="passed"))return"passing";let r=e.slice(-10).join(`
58
- `).toLowerCase();return/(?:failed|failing|failure|error|✗|❌)/u.test(r)?"failing":/(?:passed|passing|green|success|✓|✅)/u.test(r)?"passing":"unknown"}function ua(e){return v(JSON.stringify(e))}function la(e){let t=[];for(let n of e){if(!n)continue;let r=n.match(/https?:\/\/[^\s<>"'`)\]}]+/giu)??[];for(let s of r){let o=s.replace(/[.,;:!?]+$/gu,"").trim();o&&t.push(o)}}return I(t,30)}function Gn(e){let{project:t,identity:n,state:r}=e,s=r.activeFiles?.at(-1)??r.filesTouched.at(-1),o=r.phases.filter(S=>S.status==="completed").map(S=>S.title),i=r.tasks.filter(S=>S.status==="completed").map(S=>S.title),a=r.phases.filter(S=>S.status!=="completed"&&S.status!=="cancelled").map(S=>S.title),c=r.tasks.filter(S=>S.status!=="completed"&&S.status!=="cancelled").map(S=>S.title),u=new Set(r.tasks.filter(S=>S.status==="completed").map(S=>S.title.normalize("NFKC").toLowerCase().replace(/\s+/gu," ").trim())),f=I(r.nextActions.filter(S=>!u.has(S.normalize("NFKC").toLowerCase().replace(/\s+/gu," ").trim())),10),l=I([...c,...f],15),p=I(r.tests.slice().reverse(),10),d=I([...(r.activeFiles??[]).slice().reverse(),...r.filesTouched.slice().reverse()],20),g={schema:"toolnet.handoff.v2",version:2,project:{id:t.id,name:t.name},source:{agent:n.agent,nativeSessionId:n.nativeSessionId,sessionKey:n.sessionKey,sequence:e.sequence,reason:e.reason},capturedAt:e.capturedAt??new Date().toISOString(),goal:r.goal,request:r.currentRequest,activity:r.currentActivity,current:{phase:Jn(r.currentPhase),task:Jn(r.currentTask),file:s},completed:{phases:I(o,20),tasks:I(i,30)},remaining:{phases:I(a,20),tasks:I(c,30),todos:l},nextAction:f[0],blockers:I(r.blockers.slice().reverse(),10),decisions:I(r.decisions.slice().reverse(),10),files:{current:s,recent:d,active:I(r.activeFiles??[],10),modified:I(r.modifiedFiles??[],20),created:I(r.createdFiles??[],20),deleted:I(r.deletedFiles??[],20)},tests:{status:ca(r.tests,r.checks),recent:p,checks:(r.checks??[]).slice(-10).map(S=>({kind:S.kind,status:S.status,command:S.command}))},evidence:{commands:I((r.commands??[]).slice().reverse(),20),references:la([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(S=>S.command)])},attention:I(e.attention??[],20),progress:r.progress},{capturedAt:k,source:y,...h}=g;return{...g,stateDigest:ua(h)}}function pa(e){return!!(e.currentRequest||e.currentActivity||e.goal||e.plan||e.phases.length>0||e.tasks.length>0||e.nextActions.length>0||e.blockers.length>0||e.decisions.length>0||e.filesTouched.length>0)}function Un(e,t,n,r,s){if(!pa(n))return null;let o=He(e,!1),a=[...o?o.rules.filter(l=>l.mode==="enforce").map(l=>l.text):[],...n.warnings].slice(0,20),c=Gn({project:e,identity:t,state:n,reason:r,sequence:s,attention:a}),u=c.stateDigest;return{version:1,id:v([e.id,t.sessionKey,u].join("|")).slice(0,24),projectId:e.id,projectName:e.name,createdAt:new Date().toISOString(),reason:r,sourceSession:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,sequence: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 Yn(e,t){let n=It(e.rootPath,".toolnet","work","handoffs");fa(n,{recursive:!0});let r=It(n,`${t.id}.json`);da(r)||P(r,t),P(It(e.rootPath,".toolnet","work","handoff-latest.json"),t)}function Qn(e){let t=Un(e.project,e.identity,e.state,e.reason,e.sequence);return t?(Yn(e.project,t),t):null}var Ge=class{constructor(t){this.options=t}options;async capture(t,n){let r=ve(this.options.project);r||(r=await se(this.options.project,this.options.storage)),r||(r=await Se(this.options.project,this.options.storage));let s=Un(this.options.project,this.options.identity,r,t,n);if(!s)return null;Yn(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)+`
55
+ `;function Ue(e){return Oi(e.rootPath,".toolnet","PROJECT.md")}function Ni(e){return e.normalize("NFKC").replace(/\s+/g," ").trim()}function _i(e){let t=[],n=new Set,r=/^\s*[-*]\s+\[(enforce|advisory)\]\s+(.+?)\s*$/gimu,s;for(;s=r.exec(e);){let o=s[1].toLowerCase(),i=Ni(s[2]);if(!i)continue;let a=`${o}:${i.toLowerCase()}`;n.has(a)||(n.add(a),t.push({id:w(a).slice(0,24),mode:o,text:i,source:"manual"}))}return t}function $i(e){let t=Ue(e);return Dn(t)||(Pi(Ei(t),{recursive:!0}),Ti(t,Ri,{encoding:"utf8",mode:384})),t}function Ye(e,t=!1){let n=t?$i(e):Ue(e);if(!Dn(n))return null;if(Ln(n).size>Wn)throw new Error(`PROJECT.md exceeds ${Wn} bytes`);let s=Ci(n,"utf8");return{path:n,content:s,digest:w(s),rules:_i(s),bytes:Buffer.byteLength(s,"utf8"),updatedAt:new Date(Ln(n).mtimeMs).toISOString()}}import{randomUUID as Fi}from"node:crypto";import{closeSync as Ki,existsSync as zn,fsyncSync as Li,mkdirSync as Wi,openSync as Di,readFileSync as zi,statSync as qi,unlinkSync as qn,writeFileSync as Bi}from"node:fs";import{dirname as Vi,join as Hi}from"node:path";var Ji=new Int32Array(new SharedArrayBuffer(4));function Gi(e){e<=0||Atomics.wait(Ji,0,0,e)}function Ui(e){return Hi(e.rootPath,".toolnet","work",".current.lock")}function Yi(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code!=="ESRCH"}}function Bn(e){if(!zn(e))return null;try{let t=JSON.parse(zi(e,"utf8"));return t.version!==1||typeof t.token!="string"||typeof t.pid!="number"||typeof t.acquiredAt!="string"?null:{version:1,token:t.token,pid:t.pid,acquiredAt:t.acquiredAt}}catch{return null}}function Qi(e){try{return Date.now()-qi(e).mtimeMs}catch{return 0}}function Xi(e,t){if(!zn(e)||Qi(e)<t)return!1;let n=Bn(e);return n?!Yi(n.pid):!0}function Zi(e,t){if(!Xi(e,t))return!1;try{return qn(e),!0}catch{return!1}}function ea(e,t){let n={version:1,token:t,pid:process.pid,acquiredAt:new Date().toISOString()},r=Di(e,"wx",384);try{Bi(r,`${JSON.stringify(n,null,2)}
56
+ `,{encoding:"utf8"}),Li(r)}finally{Ki(r)}}function ta(e,t){if(Bn(e)?.token===t)try{qn(e)}catch{}}function na(e,t={}){let n=Math.max(100,t.timeoutMs??5e3),r=Math.max(5,t.retryMs??20),s=Math.max(n*2,t.staleMs??3e4),o=Ui(e);Wi(Vi(o),{recursive:!0});let i=Fi(),a=Date.now()+n;for(;;)try{ea(o,i);let c=!1;return()=>{c||(c=!0,ta(o,i))}}catch(c){if(c?.code!=="EEXIST")throw c;if(Zi(o,s))continue;if(Date.now()>=a)throw new Error(`Timed out acquiring project work lock: ${o}`);Gi(r)}}function Vn(e,t,n={}){let r=na(e,n);try{return t()}finally{r()}}import{closeSync as ra,existsSync as sa,fsyncSync as oa,mkdirSync as ia,openSync as aa,readFileSync as ca,renameSync as ua,writeFileSync as la}from"node:fs";import{dirname as da,join as fa}from"node:path";function pa(e,t){ia(da(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`,r=aa(n,"w",384);try{la(r,`${JSON.stringify(t,null,2)}
57
+ `,{encoding:"utf8"}),oa(r)}finally{ra(r)}ua(n,e)}function Qn(e){return fa(e.rootPath,".toolnet","work","current.json")}function be(e){let t=Qn(e);if(!sa(t))return null;try{let n=JSON.parse(ca(t,"utf8"));return n.version!==1||n.projectId!==e.id?null:n}catch{return null}}function Qe(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim()}function N(e,t,n){let r=[],s=new Set;for(let o of[...e,...t].reverse()){let i=Qe(o);if(!(!i||s.has(i))&&(s.add(i),r.push(o),r.length>=n))break}return r.reverse()}function ma(e,t,n=20){let r=new Map;for(let s of[...e,...t]){let o=`${s.kind}|${Qe(s.command)}`;r.delete(o),r.set(o,s)}return Array.from(r.values()).slice(-n)}function ga(e){return e.kind==="phase"?/^Phase\s+\d+$/iu.test(e.text):e.kind==="task"?/^(?:TODO|Task|Việc)\s+\d+$/iu.test(e.text):!1}function Hn(e,t){let n=t.status??e?.status??"pending",r=n;e?.status==="completed"&&n!=="completed"&&(r="completed"),e&&n==="pending"&&(e.status==="in_progress"||e.status==="blocked")&&(r=e.status);let s=e&&ga(t)?e.title:t.text;return{id:e?.id??t.id,title:s,status:r,order:t.order??e?.order,confidence:Math.max(e?.confidence??0,t.confidence),updatedAt:t.occurredAt,updatedBy:{agent:t.agent,nativeSessionId:t.nativeSessionId,eventId:t.eventId}}}function Jn(e){let t=new Map;for(let n of e){let r=n.order!==void 0?`order:${n.order}`:Qe(n.title);t.set(r,n)}return t}function Gn(e){return e.order!==void 0?`order:${e.order}`:Qe(e.key||e.text)}function Un(e){return Array.from(e).sort((t,n)=>{let r=t.order??Number.MAX_SAFE_INTEGER,s=n.order??Number.MAX_SAFE_INTEGER;return r!==s?r-s:t.updatedAt.localeCompare(n.updatedAt)})}function Yn(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="blocked")??e.find(t=>t.status==="pending")}function ya(e,t){let n=be(e),r=Jn(n?.phases??[]),s=Jn(n?.tasks??[]),o=n?.currentRequest,i=n?.currentActivity,a=n?.goal,c=n?.plan,u=n?.lastSession,f=[],l=[],p=[],d=[],m=[],k=[...n?.activeFiles??[]],g=[],h=[],v=[],x=[],O=[],C=[],R=[...t].sort((S,T)=>{let B=S.occurredAt.localeCompare(T.occurredAt);return B!==0?B:S.sequence-T.sequence});for(let S of R)switch(S.kind){case"request":o=S.text;break;case"activity":i=S.text;break;case"goal":a=S.text;break;case"plan":c=S.text;break;case"phase":{let T=Gn(S);r.set(T,Hn(r.get(T),S));break}case"task":{let T=Gn(S);s.set(T,Hn(s.get(T),S));break}case"decision":f.push(S.text);break;case"blocker":l.push(S.text);break;case"warning":p.push(S.text);break;case"next_action":d.push(S.text);break;case"file":{m.push(S.text);let T=S.fileAction??"active",B=k.indexOf(S.text);B>=0&&k.splice(B,1),T!=="deleted"&&k.push(S.text),T==="modified"?g.push(S.text):T==="created"?h.push(S.text):T==="deleted"&&v.push(S.text);break}case"command":x.push(S.text);break;case"test":O.push(S.text),S.checkKind&&C.push({kind:S.checkKind,command:S.text,status:S.checkStatus??"unknown",updatedAt:S.occurredAt,agent:S.agent,nativeSessionId:S.nativeSessionId});break;case"session":u={agent:S.agent,nativeSessionId:S.nativeSessionId,sessionKey:S.sessionKey,updatedAt:S.occurredAt};break}let j=Un(r.values()),b=Un(s.values()),D=Yn(j),z=Yn(b),Mt=N(n?.nextActions??[],[...d,...z?[z.title]:[],...!z&&D?[D.title]:[],...b.filter(S=>S.status==="pending").slice(0,5).map(S=>S.title)],8),At=N(n?.blockers??[],[...l,...j.filter(S=>S.status==="blocked").map(S=>S.title),...b.filter(S=>S.status==="blocked").map(S=>S.title)],20),fe=R.length>0?R[R.length-1].occurredAt:n?.updatedAt??new Date().toISOString(),$e={version:1,projectId:e.id,projectName:e.name,currentRequest:o,currentActivity:i,goal:a,plan:c,phases:j,tasks:b,decisions:N(n?.decisions??[],f,20),blockers:At,warnings:N(n?.warnings??[],p,20),nextActions:Mt,filesTouched:N(n?.filesTouched??[],m,30),activeFiles:N([],k,5),modifiedFiles:N(n?.modifiedFiles??[],g,30),createdFiles:N(n?.createdFiles??[],h,30),deletedFiles:N(n?.deletedFiles??[],v,30),commands:N(n?.commands??[],x,20),tests:N(n?.tests??[],O,20),checks:ma(n?.checks??[],C,20),currentPhase:D,currentTask:z,progress:{phasesTotal:j.length,phasesCompleted:j.filter(S=>S.status==="completed").length,tasksTotal:b.length,tasksCompleted:b.filter(S=>S.status==="completed").length,blocked:j.filter(S=>S.status==="blocked").length+b.filter(S=>S.status==="blocked").length},lastSession:u,updatedAt:fe},y=ye($e);return pa(Qn(e),y),y}function Xn(e,t){return Vn(e,()=>ya(e,t))}function P(e,t){let n=new Set,r=[];for(let s of e){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>=t))break}return r}function Zn(e){if(e)return{id:e.id,title:e.title,status:e.status}}function ha(e,t=[]){let n=t.slice(-10);if(n.some(s=>s.status==="failed"))return"failing";if(n.some(s=>s.status==="passed"))return"passing";let r=e.slice(-10).join(`
58
+ `).toLowerCase();return/(?:failed|failing|failure|error|✗|❌)/u.test(r)?"failing":/(?:passed|passing|green|success|✓|✅)/u.test(r)?"passing":"unknown"}function ka(e){return w(JSON.stringify(e))}function Sa(e){let t=[];for(let n of e){if(!n)continue;let r=n.match(/https?:\/\/[^\s<>"'`)\]}]+/giu)??[];for(let s of r){let o=s.replace(/[.,;:!?]+$/gu,"").trim();o&&t.push(o)}}return P(t,30)}function er(e){let{project:t,identity:n,state:r}=e,s=r.activeFiles?.at(-1)??r.filesTouched.at(-1),o=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=P(r.nextActions.filter(v=>!u.has(v.normalize("NFKC").toLowerCase().replace(/\s+/gu," ").trim())),10),l=P([...c,...f],15),p=P(r.tests.slice().reverse(),10),d=P([...(r.activeFiles??[]).slice().reverse(),...r.filesTouched.slice().reverse()],20),m={schema:"toolnet.handoff.v2",version:2,project:{id:t.id,name:t.name},source:{agent:n.agent,nativeSessionId:n.nativeSessionId,sessionKey:n.sessionKey,sequence:e.sequence,reason:e.reason},capturedAt:e.capturedAt??new Date().toISOString(),goal:r.goal,request:r.currentRequest,activity:r.currentActivity,current:{phase:Zn(r.currentPhase),task:Zn(r.currentTask),file:s},completed:{phases:P(o,20),tasks:P(i,30)},remaining:{phases:P(a,20),tasks:P(c,30),todos:l},nextAction:f[0],blockers:P(r.blockers.slice().reverse(),10),decisions:P(r.decisions.slice().reverse(),10),files:{current:s,recent:d,active:P(r.activeFiles??[],10),modified:P(r.modifiedFiles??[],20),created:P(r.createdFiles??[],20),deleted:P(r.deletedFiles??[],20)},tests:{status:ha(r.tests,r.checks),recent:p,checks:(r.checks??[]).slice(-10).map(v=>({kind:v.kind,status:v.status,command:v.command}))},evidence:{commands:P((r.commands??[]).slice().reverse(),20),references:Sa([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:P(e.attention??[],20),progress:r.progress},{capturedAt:k,source:g,...h}=m;return{...m,stateDigest:ka(h)}}function ba(e){return!!(e.currentRequest||e.currentActivity||e.goal||e.plan||e.phases.length>0||e.tasks.length>0||e.nextActions.length>0||e.blockers.length>0||e.decisions.length>0||e.filesTouched.length>0)}function tr(e,t,n,r,s){if(!ba(n))return null;let o=Ye(e,!1),a=[...o?o.rules.filter(l=>l.mode==="enforce").map(l=>l.text):[],...n.warnings].slice(0,20),c=er({project:e,identity:t,state:n,reason:r,sequence:s,attention:a}),u=c.stateDigest;return{version:1,id:w([e.id,t.sessionKey,u].join("|")).slice(0,24),projectId:e.id,projectName:e.name,createdAt:new Date().toISOString(),reason:r,sourceSession:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,sequence: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 nr(e,t){let n=Tt(e.rootPath,".toolnet","work","handoffs");wa(n,{recursive:!0});let r=Tt(n,`${t.id}.json`);va(r)||E(r,t),E(Tt(e.rootPath,".toolnet","work","handoff-latest.json"),t)}function rr(e){let t=tr(e.project,e.identity,e.state,e.reason,e.sequence);return t?(nr(e.project,t),t):null}var Xe=class{constructor(t){this.options=t}options;async capture(t,n){let r=be(this.options.project);r||(r=await ie(this.options.project,this.options.storage)),r||(r=await we(this.options.project,this.options.storage));let s=tr(this.options.project,this.options.identity,r,t,n);if(!s)return null;nr(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)+`
59
59
  `,"application/json"),await this.options.storage.put(`projects/${this.options.project.id}/work/handoff-latest.json`,JSON.stringify(s,null,2)+`
60
- `,"application/json"),s}};async function Xn(e,t){let n=await t.getText(`projects/${e.id}/work/handoff-latest.json`);if(!n)return null;try{return JSON.parse(n)}catch{return null}}import{mkdirSync as ma}from"node:fs";import{join as Zn}from"node:path";function ga(e){return{value:e.value,confidence:e.confidence,evidence:e.evidence}}function ya(e,t){if(!t)return!0;let n=e.evidence.occurredAt.localeCompare(t.evidence.occurredAt);return n!==0?n>0:e.evidence.sessionKey===t.evidence.sessionKey?e.evidence.sequence>=t.evidence.sequence:e.confidence>=t.confidence}function B(e,t){return ya(t,e)?t:e}function V(e,t=30){let n=new Set,r=[];for(let s of e){let o=s.value.normalize("NFKC").toLowerCase().replace(/\s+/g," ").trim();!o||n.has(o)||(n.add(o),r.push(s))}return r.slice(-t)}async function ha(e,t){let n=`projects/${e.id}/work/semantic/observations/`,r=await t.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 t.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 ka(e){return{key:e.scopeKey??`phase:${e.scopeOrder??0}`,order:e.scopeOrder??0,acceptanceCriteria:[],dependencies:[],openQuestions:[],constraints:[],notes:[]}}async function er(e,t){let r=(await ha(e,t)).flatMap(k=>k.observations).sort((k,y)=>{let h=k.evidence.occurredAt.localeCompare(y.evidence.occurredAt);return h!==0?h:k.evidence.sessionKey===y.evidence.sessionKey?k.evidence.sequence-y.evidence.sequence:k.id.localeCompare(y.id)}),s,o,i,a,c,u=new Map,f=[],l=[],p=[];for(let k of r){let y=ga(k);if(k.scope==="phase"&&k.scopeKey){let h=u.get(k.scopeKey)??ka(k);switch(k.kind){case"phase_objective":h.objective=B(h.objective,y);break;case"phase_why":h.why=B(h.why,y);break;case"phase_deliverable":h.deliverable=B(h.deliverable,y);break;case"acceptance_criterion":h.acceptanceCriteria.push(y);break;case"dependency":h.dependencies.push(y);break;case"open_question":h.openQuestions.push(y);break;case"constraint":h.constraints.push(y);break;case"note":h.notes.push(y);break}u.set(h.key,h);continue}switch(k.kind){case"mission":s=B(s,y);break;case"objective":o=B(o,y);break;case"why":i=B(i,y);break;case"desired_outcome":a=B(a,y);break;case"plan_rationale":c=B(c,y);break;case"open_question":f.push(y);break;case"constraint":l.push(y);break;case"note":p.push(y);break}}for(let k of u.values())k.acceptanceCriteria=V(k.acceptanceCriteria,20),k.dependencies=V(k.dependencies,15),k.openQuestions=V(k.openQuestions,15),k.constraints=V(k.constraints,15),k.notes=V(k.notes,20);let d={version:1,projectId:e.id,projectName:e.name,mission:s,activeObjective:o,why:i,desiredOutcome:a,planRationale:c,phases:Array.from(u.values()).sort((k,y)=>k.order-y.order),openQuestions:V(f,20),constraints:V(l,20),notes:V(p,20),updatedAt:r.length?r[r.length-1].evidence.occurredAt:new Date().toISOString()},g=Zn(e.rootPath,".toolnet","work");return ma(g,{recursive:!0}),P(Zn(g,"semantic-current.json"),d),await t.put(`projects/${e.id}/work/semantic/current.json`,JSON.stringify(d,null,2)+`
61
- `,"application/json"),d}async function tr(e,t){let n=await t.getText(`projects/${e.id}/work/semantic/current.json`);if(!n)return null;try{return JSON.parse(n)}catch{return null}}function Ct(e){if(!e)return 0;let t=Array.from(e).length,n=e.trim().split(/\s+/u).filter(Boolean).length;return Math.ceil(Math.max(t/3.5,n*1.3))}function j(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,Math.max(0,t-1)).trimEnd()+"\u2026"}function Sa(e){let t=[],n=!1;for(let r of e.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&&t.push(j(s,280)),t.length>=16))break}return t}function va(e){let t=[],n=[];for(let r of e.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")?t.push(c):n.push(c))}return{enforce:t,advisory:n}}function wa(e,t){let n=[];for(let r of e){let s=[...n,r].join(`
62
- `);if(Ct(s)<=t){n.push(r);continue}let o=Ct(n.join(`
63
- `)),i=Math.max(0,t-o);if(i>=16){let a=Math.floor(i*3.2),c=j(r,a);c&&n.push(c)}break}return n.join(`
64
- `).trim()}async function nr(e){let t=Math.max(256,Math.min(2e3,e.maxTokens??1e3)),n=He(e.project,!1),r=n?.content??"";r||(r=await e.storage.getText(`projects/${e.project.id}/project/manual.md`)??"");let s=va(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?Sa(r):[],c=await se(e.project,e.storage),u=await tr(e.project,e.storage),f=await Xn(e.project,e.storage),l=[];if(l.push("[TOOLNET PROJECT CONTEXT]"),l.push(`Project: ${e.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: ${Ve(e.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)}`)})),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=wa(l,t);return{version:1,projectId:e.project.id,projectName:e.project.name,text:p,estimatedTokens:Ct(p),maxTokens:t,hasManual:!!r,hasWorkState:!!c,hasHandoff:!!f,generatedAt:new Date().toISOString()}}var ba=new Set(["content","text","message","prompt","summary","description","title","reason","last_assistant_message","lastAssistantMessage"]);function oe(e){return e.normalize("NFKC").replace(/\s+/g," ").replace(/^[\s>*#•-]+/u,"").trim()}function Pt(e,t,n=0){if(!(n>6)){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let r of e.slice(0,50))Pt(r,t,n+1);return}if(!(!e||typeof e!="object"))for(let[r,s]of Object.entries(e))(ba.has(r)||["data","payload","parts","messages"].includes(r))&&Pt(s,t,n+1)}}function N(e,t,n,r,s,o=.95){let i=oe(r);return{version:1,id:v([e.projectId,n,s.type,s.key??"",i.toLowerCase(),t.id].join("|")).slice(0,32),projectId:e.projectId,kind:n,value:i,scope:s.type,scopeKey:s.key,scopeOrder:s.order,confidence:o,evidence:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,eventId:t.id,sourceEventId:t.sourceEventId,sequence:t.sequence,occurredAt:t.timestamp}}}function F(e,t){let n=e.toLowerCase();for(let r of t){let s=r.toLowerCase();if(n.startsWith(`${s}:`)||n.startsWith(`${s} -`)||n.startsWith(`${s} \u2014`))return oe(e.slice(r.length+1))}return null}function xa(e){let t=e.trimStart();return t.startsWith("- ")||t.startsWith("* ")||/^\d+[.)]\s+/u.test(t)}function ja(e){return oe(e.trim().replace(/^[-*]\s+/u,"").replace(/^\d+[.)]\s+/u,""))}function rr(e,t){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 t){let i=[];Pt(o.data,i);for(let a of i){let c={type:"project"},u=null;for(let f of a.split(/\r?\n/u)){let l=oe(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 w=Number(p[1]);c={type:"phase",key:`phase:${w}`,order:w,title:oe(p[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:oe(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(e,o,"mission",g,{type:"project"},.99)),u=null;continue}let k=F(l,["current objective","active objective","m\u1EE5c ti\xEAu hi\u1EC7n t\u1EA1i","objective","m\u1EE5c ti\xEAu","m\u1EE5c \u0111\xEDch"]);if(k){s(N(e,o,c.type==="phase"?"phase_objective":"objective",k,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(e,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(e,o,"desired_outcome",h,{type:"project"},.98)),u=null;continue}let S=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(S){s(N(e,o,"plan_rationale",S,{type:"project"},.98)),u=null;continue}let T=F(l,["deliverable","output","k\u1EBFt qu\u1EA3 c\u1EA7n \u0111\u1EA1t","ph\u1EA3i t\u1EA1o ra","\u0111\u1EA7u ra"]);if(T){s(N(e,o,"phase_deliverable",T,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(e,o,"acceptance_criterion",E,c,.98)),u="acceptance_criterion";continue}let C=F(l,["depends on","dependency","dependencies","ph\u1EE5 thu\u1ED9c","c\u1EA7n c\xF3 tr\u01B0\u1EDBc"]);if(C){s(N(e,o,"dependency",C,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(e,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(e,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&&xa(f)){s(N(e,o,u,ja(f),c,.96));continue}u=null}}}return n}function sr(e){return String(e).padStart(12,"0")}var Ue=class{constructor(t){this.storage=t}storage;async write(t,n){if(n.length===0)return null;let r=Math.min(...n.map(u=>u.evidence.sequence)),s=Math.max(...n.map(u=>u.evidence.sequence)),o={version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.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(t.sessionKey).slice(0,12),c=[`projects/${t.projectId}`,"work","semantic","observations",`${sr(r)}-${sr(s)}-${a}-${i}.json`].join("/");return await this.storage.exists(c)||await this.storage.put(c,JSON.stringify(o,null,2)+`
65
- `,"application/json"),c}};import{closeSync as Ma,existsSync as Aa,openSync as Ia,readSync as Ca,statSync as Pa}from"node:fs";function Ta(e,t){if(!Aa(e))return{events:[],nextOffset:t};let n=Pa(e).size,r=Number.isFinite(t)?Math.max(0,t):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let s=Buffer.alloc(n-r),o=Ia(e,"r");try{Ca(o,s,0,s.length,r)}finally{Ma(o)}let i=s.toString("utf8"),a=i.lastIndexOf(`
60
+ `,"application/json"),s}};async function sr(e,t){let n=await t.getText(`projects/${e.id}/work/handoff-latest.json`);if(!n)return null;try{return JSON.parse(n)}catch{return null}}import{mkdirSync as xa}from"node:fs";import{join as or}from"node:path";function ja(e){return{value:e.value,confidence:e.confidence,evidence:e.evidence}}function Ma(e,t){if(!t)return!0;let n=e.evidence.occurredAt.localeCompare(t.evidence.occurredAt);return n!==0?n>0:e.evidence.sessionKey===t.evidence.sessionKey?e.evidence.sequence>=t.evidence.sequence:e.confidence>=t.confidence}function H(e,t){return Ma(t,e)?t:e}function J(e,t=30){let n=new Set,r=[];for(let s of e){let o=s.value.normalize("NFKC").toLowerCase().replace(/\s+/g," ").trim();!o||n.has(o)||(n.add(o),r.push(s))}return r.slice(-t)}async function Aa(e,t){let n=`projects/${e.id}/work/semantic/observations/`,r=await t.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 t.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 Ia(e){return{key:e.scopeKey??`phase:${e.scopeOrder??0}`,order:e.scopeOrder??0,acceptanceCriteria:[],dependencies:[],openQuestions:[],constraints:[],notes:[]}}async function ir(e,t){let r=(await Aa(e,t)).flatMap(k=>k.observations).sort((k,g)=>{let h=k.evidence.occurredAt.localeCompare(g.evidence.occurredAt);return h!==0?h:k.evidence.sessionKey===g.evidence.sessionKey?k.evidence.sequence-g.evidence.sequence:k.id.localeCompare(g.id)}),s,o,i,a,c,u=new Map,f=[],l=[],p=[];for(let k of r){let g=ja(k);if(k.scope==="phase"&&k.scopeKey){let h=u.get(k.scopeKey)??Ia(k);switch(k.kind){case"phase_objective":h.objective=H(h.objective,g);break;case"phase_why":h.why=H(h.why,g);break;case"phase_deliverable":h.deliverable=H(h.deliverable,g);break;case"acceptance_criterion":h.acceptanceCriteria.push(g);break;case"dependency":h.dependencies.push(g);break;case"open_question":h.openQuestions.push(g);break;case"constraint":h.constraints.push(g);break;case"note":h.notes.push(g);break}u.set(h.key,h);continue}switch(k.kind){case"mission":s=H(s,g);break;case"objective":o=H(o,g);break;case"why":i=H(i,g);break;case"desired_outcome":a=H(a,g);break;case"plan_rationale":c=H(c,g);break;case"open_question":f.push(g);break;case"constraint":l.push(g);break;case"note":p.push(g);break}}for(let k of u.values())k.acceptanceCriteria=J(k.acceptanceCriteria,20),k.dependencies=J(k.dependencies,15),k.openQuestions=J(k.openQuestions,15),k.constraints=J(k.constraints,15),k.notes=J(k.notes,20);let d={version:1,projectId:e.id,projectName:e.name,mission:s,activeObjective:o,why:i,desiredOutcome:a,planRationale:c,phases:Array.from(u.values()).sort((k,g)=>k.order-g.order),openQuestions:J(f,20),constraints:J(l,20),notes:J(p,20),updatedAt:r.length?r[r.length-1].evidence.occurredAt:new Date().toISOString()},m=or(e.rootPath,".toolnet","work");return xa(m,{recursive:!0}),E(or(m,"semantic-current.json"),d),await t.put(`projects/${e.id}/work/semantic/current.json`,JSON.stringify(d,null,2)+`
61
+ `,"application/json"),d}async function ar(e,t){let n=await t.getText(`projects/${e.id}/work/semantic/current.json`);if(!n)return null;try{return JSON.parse(n)}catch{return null}}function Et(e){if(!e)return 0;let t=Array.from(e).length,n=e.trim().split(/\s+/u).filter(Boolean).length;return Math.ceil(Math.max(t/3.5,n*1.3))}function M(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,Math.max(0,t-1)).trimEnd()+"\u2026"}function Pa(e){let t=[],n=!1;for(let r of e.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&&t.push(M(s,280)),t.length>=16))break}return t}function Ca(e){let t=[],n=[];for(let r of e.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")?t.push(c):n.push(c))}return{enforce:t,advisory:n}}function Ta(e,t){let n=[];for(let r of e){let s=[...n,r].join(`
62
+ `);if(Et(s)<=t){n.push(r);continue}let o=Et(n.join(`
63
+ `)),i=Math.max(0,t-o);if(i>=16){let a=Math.floor(i*3.2),c=M(r,a);c&&n.push(c)}break}return n.join(`
64
+ `).trim()}async function cr(e){let t=Math.max(256,Math.min(2e3,e.maxTokens??1e3)),n=Ye(e.project,!1),r=n?.content??"";r||(r=await e.storage.getText(`projects/${e.project.id}/project/manual.md`)??"");let s=Ca(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?Pa(r):[],c=await ie(e.project,e.storage),u=await ar(e.project,e.storage),f=await sr(e.project,e.storage),l=[];if(l.push("[TOOLNET PROJECT CONTEXT]"),l.push(`Project: ${e.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: ${Ue(e.project)}`),o.length){l.push("","PROJECT RULES \u2014 MUST FOLLOW");for(let d of o.slice(0,24))l.push(`- [ENFORCE] ${M(d,240)}`)}if(i.length){l.push("","PROJECT PREFERENCES");for(let d of i.slice(0,10))l.push(`- ${M(d,220)}`)}if(u&&(u.mission&&l.push("","MISSION",M(u.mission.value,420)),u.activeObjective&&l.push("","CURRENT OBJECTIVE",M(u.activeObjective.value,420)),u.why&&l.push("","WHY THIS WORK MATTERS",M(u.why.value,420)),u.desiredOutcome&&l.push("","DESIRED OUTCOME",M(u.desiredOutcome.value,420)),u.planRationale&&l.push("","WHY THIS APPROACH",M(u.planRationale.value,420))),c){if(l.push("","ACTIVE WORK"),c.goal&&l.push(`Goal: ${M(c.goal,320)}`),c.plan&&l.push(`Plan: ${M(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: ${M(d.objective.value,340)}`),d.why?l.push(`Why this phase: ${M(d.why.value,340)}`):l.push("Why this phase: not explicitly recorded. Inspect existing implementation before assuming intent."),d.deliverable&&l.push(`Deliverable: ${M(d.deliverable.value,340)}`),d.dependencies.length&&l.push(`Depends on: ${d.dependencies.slice(0,4).map(m=>M(m.value,180)).join("; ")}`),d.acceptanceCriteria.length&&(l.push("","DEFINITION OF DONE"),d.acceptanceCriteria.slice(0,6).forEach(m=>{l.push(`- ${M(m.value,260)}`)})),d.openQuestions.length&&(l.push("","OPEN QUESTIONS FOR CURRENT PHASE"),d.openQuestions.slice(0,4).forEach(m=>{l.push(`- ${M(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}. ${M(d,260)}`)})),c.blockers.length&&(l.push("","BLOCKERS"),c.blockers.slice(0,5).forEach(d=>{l.push(`- ${M(d,260)}`)})),c.warnings.length&&(l.push("","ATTENTION"),c.warnings.slice(-5).forEach(d=>{l.push(`- ${M(d,260)}`)})),c.decisions.length&&(l.push("","RECENT DECISIONS"),c.decisions.slice(-5).forEach(d=>{l.push(`- ${M(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(`- ${M(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=Ta(l,t);return{version:1,projectId:e.project.id,projectName:e.project.name,text:p,estimatedTokens:Et(p),maxTokens:t,hasManual:!!r,hasWorkState:!!c,hasHandoff:!!f,generatedAt:new Date().toISOString()}}var Ea=new Set(["content","text","message","prompt","summary","description","title","reason","last_assistant_message","lastAssistantMessage"]);function ae(e){return e.normalize("NFKC").replace(/\s+/g," ").replace(/^[\s>*#•-]+/u,"").trim()}function Ot(e,t,n=0){if(!(n>6)){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let r of e.slice(0,50))Ot(r,t,n+1);return}if(!(!e||typeof e!="object"))for(let[r,s]of Object.entries(e))(Ea.has(r)||["data","payload","parts","messages"].includes(r))&&Ot(s,t,n+1)}}function _(e,t,n,r,s,o=.95){let i=ae(r);return{version:1,id:w([e.projectId,n,s.type,s.key??"",i.toLowerCase(),t.id].join("|")).slice(0,32),projectId:e.projectId,kind:n,value:i,scope:s.type,scopeKey:s.key,scopeOrder:s.order,confidence:o,evidence:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,eventId:t.id,sourceEventId:t.sourceEventId,sequence:t.sequence,occurredAt:t.timestamp}}}function K(e,t){let n=e.toLowerCase();for(let r of t){let s=r.toLowerCase();if(n.startsWith(`${s}:`)||n.startsWith(`${s} -`)||n.startsWith(`${s} \u2014`))return ae(e.slice(r.length+1))}return null}function Oa(e){let t=e.trimStart();return t.startsWith("- ")||t.startsWith("* ")||/^\d+[.)]\s+/u.test(t)}function Ra(e){return ae(e.trim().replace(/^[-*]\s+/u,"").replace(/^\d+[.)]\s+/u,""))}function ur(e,t){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 t){let i=[];Ot(o.data,i);for(let a of i){let c={type:"project"},u=null;for(let f of a.split(/\r?\n/u)){let l=ae(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:ae(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:ae(d[2]??"")},u=null;continue}let m=K(l,["mission","s\u1EE9 m\u1EC7nh","m\u1EE5c ti\xEAu t\u1ED5ng th\u1EC3","m\u1EE5c ti\xEAu project","project goal"]);if(m){s(_(e,o,"mission",m,{type:"project"},.99)),u=null;continue}let k=K(l,["current objective","active objective","m\u1EE5c ti\xEAu hi\u1EC7n t\u1EA1i","objective","m\u1EE5c ti\xEAu","m\u1EE5c \u0111\xEDch"]);if(k){s(_(e,o,c.type==="phase"?"phase_objective":"objective",k,c,.98)),u=null;continue}let g=K(l,["why","why this","why this phase","reason","rationale","v\xEC sao","l\xFD do","t\u1EA1i sao","\xFD ngh\u0129a"]);if(g){s(_(e,o,c.type==="phase"?"phase_why":"why",g,c,.98)),u=null;continue}let h=K(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(_(e,o,"desired_outcome",h,{type:"project"},.98)),u=null;continue}let v=K(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){s(_(e,o,"plan_rationale",v,{type:"project"},.98)),u=null;continue}let x=K(l,["deliverable","output","k\u1EBFt qu\u1EA3 c\u1EA7n \u0111\u1EA1t","ph\u1EA3i t\u1EA1o ra","\u0111\u1EA7u ra"]);if(x){s(_(e,o,"phase_deliverable",x,c,.97)),u=null;continue}let O=K(l,["acceptance criteria","definition of done","done khi","ho\xE0n th\xE0nh khi","ti\xEAu ch\xED ho\xE0n th\xE0nh"]);if(O){s(_(e,o,"acceptance_criterion",O,c,.98)),u="acceptance_criterion";continue}let C=K(l,["depends on","dependency","dependencies","ph\u1EE5 thu\u1ED9c","c\u1EA7n c\xF3 tr\u01B0\u1EDBc"]);if(C){s(_(e,o,"dependency",C,c,.97)),u="dependency";continue}let R=K(l,["open question","open questions","c\xE2u h\u1ECFi m\u1EDF","ch\u01B0a quy\u1EBFt \u0111\u1ECBnh","ch\u01B0a r\xF5"]);if(R){s(_(e,o,"open_question",R,c,.95)),u="open_question";continue}let j=K(l,["constraint","constraints","r\xE0ng bu\u1ED9c","gi\u1EDBi h\u1EA1n"]);if(j){s(_(e,o,"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&&Oa(f)){s(_(e,o,u,Ra(f),c,.96));continue}u=null}}}return n}function lr(e){return String(e).padStart(12,"0")}var Ze=class{constructor(t){this.storage=t}storage;async write(t,n){if(n.length===0)return null;let r=Math.min(...n.map(u=>u.evidence.sequence)),s=Math.max(...n.map(u=>u.evidence.sequence)),o={version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,firstSequence:r,lastSequence:s,createdAt:new Date().toISOString(),observations:n},i=w(n.map(u=>u.id).sort().join("|")).slice(0,16),a=w(t.sessionKey).slice(0,12),c=[`projects/${t.projectId}`,"work","semantic","observations",`${lr(r)}-${lr(s)}-${a}-${i}.json`].join("/");return await this.storage.exists(c)||await this.storage.put(c,JSON.stringify(o,null,2)+`
65
+ `,"application/json"),c}};import{closeSync as Na,existsSync as _a,openSync as $a,readSync as Fa,statSync as Ka}from"node:fs";function La(e,t){if(!_a(e))return{events:[],nextOffset:t};let n=Ka(e).size,r=Number.isFinite(t)?Math.max(0,t):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let s=Buffer.alloc(n-r),o=$a(e,"r");try{Fa(o,s,0,s.length,r)}finally{Na(o)}let i=s.toString("utf8"),a=i.lastIndexOf(`
66
66
  `);if(a<0)return{events:[],nextOffset:r};let c=i.slice(0,a+1);return{events:c.split(`
67
- `).filter(Boolean).flatMap(u=>{try{return[JSON.parse(u)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(c,"utf8")}}var Ye=class{constructor(t){this.options=t;this.journal=new Ue(t.storage)}options;journal;async learnNew(){let t=this.options.wal.loadState(),n=Number(t.sourceCursors["work.semantic.offset"]??0),r=Ta(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=rr(this.options.identity,r.events),o=!1,i=!1;return s.length>0&&(o=!!await this.journal.write(this.options.identity,s),o&&(await er(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 Ea,mkdirSync as Oa,readFileSync as Ra,writeFileSync as Na}from"node:fs";import{dirname as _a,join as or}from"node:path";function Qe(e){return e?Math.ceil(e.length/3.5):0}function Xe(e,t){if(!e)return"";if(Qe(e)<=t)return e;let r=Math.floor(t*3.5),s=e.slice(0,r),o=s.lastIndexOf("."),i=s.lastIndexOf(`
68
- `),a=Math.max(o,i);return a>r*.7?s.slice(0,a+1):s}function ir(e){return or(e.rootPath,".toolnet","context","startup.md")}function $a(e){return or(e.rootPath,".toolnet","context","startup.json")}function ar(e,t){let n=ir(e);Oa(_a(n),{recursive:!0}),Na(n,t.text.endsWith(`
67
+ `).filter(Boolean).flatMap(u=>{try{return[JSON.parse(u)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(c,"utf8")}}var et=class{constructor(t){this.options=t;this.journal=new Ze(t.storage)}options;journal;async learnNew(){let t=this.options.wal.loadState(),n=Number(t.sourceCursors["work.semantic.offset"]??0),r=La(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=ur(this.options.identity,r.events),o=!1,i=!1;return s.length>0&&(o=!!await this.journal.write(this.options.identity,s),o&&(await ir(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 Wa,mkdirSync as Da,readFileSync as za,writeFileSync as qa}from"node:fs";import{dirname as Ba,join as dr}from"node:path";function tt(e){return e?Math.ceil(e.length/3.5):0}function nt(e,t){if(!e)return"";if(tt(e)<=t)return e;let r=Math.floor(t*3.5),s=e.slice(0,r),o=s.lastIndexOf("."),i=s.lastIndexOf(`
68
+ `),a=Math.max(o,i);return a>r*.7?s.slice(0,a+1):s}function fr(e){return dr(e.rootPath,".toolnet","context","startup.md")}function Va(e){return dr(e.rootPath,".toolnet","context","startup.json")}function pr(e,t){let n=fr(e);Da(Ba(n),{recursive:!0}),qa(n,t.text.endsWith(`
69
69
  `)?t.text:t.text+`
70
- `,{encoding:"utf8",mode:384}),P($a(e),t)}async function Tt(e,t,n=800){let s=(await nr({project:e,storage:t,maxTokens:n})).text;Qe(s)>n&&(s=Xe(s,n),s+=`
70
+ `,{encoding:"utf8",mode:384}),E(Va(e),t)}async function Rt(e,t,n=800){let s=(await cr({project:e,storage:t,maxTokens:n})).text;tt(s)>n&&(s=nt(s,n),s+=`
71
71
 
72
72
  [Context trimmed by ToolNet Memory token budget]
73
- `);let i={version:1,projectId:e.id,projectName:e.name,text:s,digest:v(s),estimatedTokens:Qe(s),generatedAt:new Date().toISOString()};return ar(e,i),await t.put(`projects/${e.id}/context/startup.md`,i.text+`
73
+ `);let i={version:1,projectId:e.id,projectName:e.name,text:s,digest:w(s),estimatedTokens:tt(s),generatedAt:new Date().toISOString()};return pr(e,i),await t.put(`projects/${e.id}/context/startup.md`,i.text+`
74
74
  `,"text/markdown"),await t.put(`projects/${e.id}/context/startup.json`,JSON.stringify(i,null,2)+`
75
- `,"application/json"),i}async function cr(e,t,n=900){try{let s=await t.getText(`projects/${e.id}/context/startup.md`);if(s&&s.trim()){let o=s.trim(),i={version:1,projectId:e.id,projectName:e.name,text:o,digest:v(o),estimatedTokens:Math.ceil(o.length/3.5),generatedAt:new Date().toISOString()};return ar(e,i),i}}catch{}let r=ir(e);if(Ea(r))try{let s=Ra(r,"utf8").trim();if(s)return{version:1,projectId:e.id,projectName:e.name,text:s,digest:v(s),estimatedTokens:Math.ceil(s.length/3.5),generatedAt:new Date().toISOString()}}catch{}try{return await Tt(e,t,n)}catch{return null}}import{existsSync as vr,mkdirSync as ec,readFileSync as wr}from"node:fs";import{homedir as tc}from"node:os";import{dirname as nc,join as _t}from"node:path";var Et="memory_agent_ask";function ur(){return`
75
+ `,"application/json"),i}async function mr(e,t,n=900){try{let s=await t.getText(`projects/${e.id}/context/startup.md`);if(s&&s.trim()){let o=s.trim(),i={version:1,projectId:e.id,projectName:e.name,text:o,digest:w(o),estimatedTokens:Math.ceil(o.length/3.5),generatedAt:new Date().toISOString()};return pr(e,i),i}}catch{}let r=fr(e);if(Wa(r))try{let s=za(r,"utf8").trim();if(s)return{version:1,projectId:e.id,projectName:e.name,text:s,digest:w(s),estimatedTokens:Math.ceil(s.length/3.5),generatedAt:new Date().toISOString()}}catch{}try{return await Rt(e,t,n)}catch{return null}}import{existsSync as Ar,mkdirSync as uc,readFileSync as Ir}from"node:fs";import{homedir as lc}from"node:os";import{dirname as dc,join as Kt}from"node:path";var Nt="memory_agent_ask";function gr(){return`
76
76
  [TOOLNET MEMORY AGENT]
77
77
 
78
78
  Tool:
79
- - ${Et}
79
+ - ${Nt}
80
80
 
81
81
  For resume/continue requests:
82
82
 
83
83
  1. Use the injected ToolNet continuity handoff FIRST.
84
84
  2. If the handoff is missing or ambiguous, invoke
85
- ${Et} directly BEFORE repository/history exploration.
85
+ ${Nt} directly BEFORE repository/history exploration.
86
86
  3. NEVER reconstruct prior work from:
87
87
  - .toolnet/journal/**, .toolnet/runtime/sources/**, and legacy .toolnet/sessions/**
88
88
  - state.json
89
89
  - events.jsonl
90
90
  - raw transcripts
91
91
  4. NEVER search for the implementation/schema of
92
- ${Et}; invoke the MCP tool directly.
92
+ ${Nt}; invoke the MCP tool directly.
93
93
  5. Inspect git/source only AFTER continuity context is known.
94
94
 
95
95
  Use:
@@ -97,60 +97,60 @@ Use:
97
97
  - No AI/LLM mode exists.
98
98
 
99
99
  Current repository evidence overrides stale memory.
100
- `.trim()}import{createHash as Fa}from"node:crypto";import{chmodSync as dr,existsSync as Ka,mkdirSync as La,readFileSync as Wa,renameSync as Da,writeFileSync as fr}from"node:fs";import{dirname as pr,join as Ze}from"node:path";var Nt="toolnet.context-offload.v1",za="toolnet.context-offload-asset.v1",qa=256,Ba=new Set(["tool_call","tool_result","file_read","file_write","file_edit","command","test","artifact"]);function mr(e){return Ze(e,".toolnet","offload")}function Va(e){return Ze(mr(e),"assets")}function gr(e){return Ze(mr(e),"graph.json")}function yr(e){La(e,{recursive:!0,mode:448});try{dr(e,448)}catch{}}function Ha(e,t){yr(pr(e));let n=`${e}.${process.pid}.${Date.now()}.tmp`;fr(n,t,{encoding:"utf8",mode:384}),Da(n,e);try{dr(e,384)}catch{}}function Rt(e){return Array.isArray(e)?e.map(Rt):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Rt(n)])):e}function Ja(e){return Fa("sha256").update(JSON.stringify(Rt(e)),"utf8").digest("hex")}function Ot(){return{schema:Nt,version:1,updatedAt:new Date(0).toISOString(),nodes:[]}}function hr(e){let t=gr(e);if(!Ka(t))return Ot();try{let n=JSON.parse(Wa(t,"utf8"));return n.schema!==Nt||n.version!==1||!Array.isArray(n.nodes)?Ot():n}catch{return Ot()}}function Ga(e,t){Ha(gr(e),JSON.stringify(t,null,2)+`
101
- `)}function Ua(e,t=260){if(typeof e!="string")return null;let n=e.replace(/\s+/gu," ").trim();return n?n.slice(0,t):null}function Ya(e){let t=[...e.provenance.files??[],e.provenance.sourcePath],n=[];for(let r of t){let s=Ua(r);if(!(!s||n.includes(s))&&(n.push(s),n.length===3))break}return n}function Qa(e){return`${e.agent}:${e.sourceEventId??e.id}`.replace(/\s+/gu," ").trim().slice(0,120)}function Xa(e,t){yr(pr(e));try{return fr(e,t,{encoding:"utf8",flag:"wx",mode:384}),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function Za(e,t){let n=e.nodes.find(s=>s.id===t.id),r=n?{...n,kind:t.kind,bytes:t.bytes,sourceRefs:Array.from(new Set([...n.sourceRefs,...t.sourceRefs])).slice(-8),files:Array.from(new Set([...n.files,...t.files])).slice(0,6)}:t;return{schema:Nt,version:1,updatedAt:new Date().toISOString(),nodes:[...e.nodes.filter(s=>s.id!==t.id),r].slice(-qa)}}function kr(e,t){let n=hr(e),r=0,s=0,o=0,i=[];for(let a of t){if(!Ba.has(a.type))continue;r+=1;let c=Ja({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)+`
102
- `;Xa(Ze(Va(e),`${c}.json`),f)?s+=1:o+=1,i.push(c),n=Za(n,{id:c,kind:a.type,bytes:Buffer.byteLength(f,"utf8"),createdAt:a.timestamp,sourceRefs:[Qa(a)],files:Ya(a)})}return r>0&&Ga(e,n),{eligible:r,written:s,deduped:o,graphNodes:n.nodes.length,assetIds:i}}function lr(e,t){let n=e.replace(/\s+/gu," ").trim();return n.length<=t?n:n.slice(0,t-1).trimEnd()+"\u2026"}function Sr(e,t={}){let n=hr(e);if(n.nodes.length===0)return"";let r=Math.max(1,Math.min(12,t.maxAssets??6)),s=Math.max(320,Math.min(2400,t.maxChars??900)),o=["[TOOLNET CONTEXT OFFLOAD GRAPH]","Large tool/file payloads stay outside prompt context.","Read only a needed asset with MCP context_offload_read."];for(let i of n.nodes.slice(-r).reverse()){let a=lr(i.sourceRefs.at(-1)??"unknown",72),c=i.files.length>0?` files=${lr(i.files.join(","),120)}`:"",u=`event:${a} --offloads--> asset:${i.id.slice(0,12)} kind=${i.kind} bytes=${i.bytes}${c}`;if([...o,u].join(`
100
+ `.trim()}import{createHash as Ha}from"node:crypto";import{chmodSync as hr,existsSync as Ja,mkdirSync as Ga,readFileSync as Ua,renameSync as Ya,writeFileSync as kr}from"node:fs";import{dirname as Sr,join as rt}from"node:path";var Ft="toolnet.context-offload.v1",Qa="toolnet.context-offload-asset.v1",Xa=256,Za=new Set(["tool_call","tool_result","file_read","file_write","file_edit","command","test","artifact"]);function vr(e){return rt(e,".toolnet","offload")}function ec(e){return rt(vr(e),"assets")}function wr(e){return rt(vr(e),"graph.json")}function br(e){Ga(e,{recursive:!0,mode:448});try{hr(e,448)}catch{}}function tc(e,t){br(Sr(e));let n=`${e}.${process.pid}.${Date.now()}.tmp`;kr(n,t,{encoding:"utf8",mode:384}),Ya(n,e);try{hr(e,384)}catch{}}function $t(e){return Array.isArray(e)?e.map($t):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,$t(n)])):e}function nc(e){return Ha("sha256").update(JSON.stringify($t(e)),"utf8").digest("hex")}function _t(){return{schema:Ft,version:1,updatedAt:new Date(0).toISOString(),nodes:[]}}function xr(e){let t=wr(e);if(!Ja(t))return _t();try{let n=JSON.parse(Ua(t,"utf8"));return n.schema!==Ft||n.version!==1||!Array.isArray(n.nodes)?_t():n}catch{return _t()}}function rc(e,t){tc(wr(e),JSON.stringify(t,null,2)+`
101
+ `)}function sc(e,t=260){if(typeof e!="string")return null;let n=e.replace(/\s+/gu," ").trim();return n?n.slice(0,t):null}function oc(e){let t=[...e.provenance.files??[],e.provenance.sourcePath],n=[];for(let r of t){let s=sc(r);if(!(!s||n.includes(s))&&(n.push(s),n.length===3))break}return n}function ic(e){return`${e.agent}:${e.sourceEventId??e.id}`.replace(/\s+/gu," ").trim().slice(0,120)}function ac(e,t){br(Sr(e));try{return kr(e,t,{encoding:"utf8",flag:"wx",mode:384}),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function cc(e,t){let n=e.nodes.find(s=>s.id===t.id),r=n?{...n,kind:t.kind,bytes:t.bytes,sourceRefs:Array.from(new Set([...n.sourceRefs,...t.sourceRefs])).slice(-8),files:Array.from(new Set([...n.files,...t.files])).slice(0,6)}:t;return{schema:Ft,version:1,updatedAt:new Date().toISOString(),nodes:[...e.nodes.filter(s=>s.id!==t.id),r].slice(-Xa)}}function jr(e,t){let n=xr(e),r=0,s=0,o=0,i=[];for(let a of t){if(!Za.has(a.type))continue;r+=1;let c=nc({type:a.type,data:a.data}),u={schema:Qa,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)+`
102
+ `;ac(rt(ec(e),`${c}.json`),f)?s+=1:o+=1,i.push(c),n=cc(n,{id:c,kind:a.type,bytes:Buffer.byteLength(f,"utf8"),createdAt:a.timestamp,sourceRefs:[ic(a)],files:oc(a)})}return r>0&&rc(e,n),{eligible:r,written:s,deduped:o,graphNodes:n.nodes.length,assetIds:i}}function yr(e,t){let n=e.replace(/\s+/gu," ").trim();return n.length<=t?n:n.slice(0,t-1).trimEnd()+"\u2026"}function Mr(e,t={}){let n=xr(e);if(n.nodes.length===0)return"";let r=Math.max(1,Math.min(12,t.maxAssets??6)),s=Math.max(320,Math.min(2400,t.maxChars??900)),o=["[TOOLNET CONTEXT OFFLOAD GRAPH]","Large tool/file payloads stay outside prompt context.","Read only a needed asset with MCP context_offload_read."];for(let i of n.nodes.slice(-r).reverse()){let a=yr(i.sourceRefs.at(-1)??"unknown",72),c=i.files.length>0?` files=${yr(i.files.join(","),120)}`:"",u=`event:${a} --offloads--> asset:${i.id.slice(0,12)} kind=${i.kind} bytes=${i.bytes}${c}`;if([...o,u].join(`
103
103
  `).length>s)break;o.push(u)}return o.join(`
104
- `)}function rc(e,t,n){let r=n??_t(tc(),".config","toolnet-memory","injections","agy");return _t(r,`${e.id}-${t}.json`)}function sc(e){if(!vr(e))return null;try{return JSON.parse(wr(e,"utf8"))}catch{return null}}function H(e,t=280){let n=(e??"").replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,Math.max(0,t-1)).trimEnd()+"\u2026"}function oc(e){let t=_t(e.rootPath,".toolnet","work","current.json");if(!vr(t))return null;try{let n=JSON.parse(wr(t,"utf8"));if(n.version===1&&n.projectId===e.id)return n}catch{}return null}function ic(e,t){let n=t.tasks.filter(i=>i.status==="completed").slice(-3).map(i=>H(i.title,220)),r=Array.from(new Set([...t.currentTask?[t.currentTask.title]:[],...t.tasks.filter(i=>i.status==="in_progress"||i.status==="blocked"||i.status==="pending").slice(0,4).map(i=>i.title)].map(i=>H(i,220)).filter(Boolean))),s=t.filesTouched.at(-1),o=["[TOOLNET CONTINUITY HANDOFF]",`Project: ${e.name}`];return t.currentTask?.title?o.push(`Task: ${H(t.currentTask.title)}`):t.currentPhase?.title?o.push(`Task: ${H(t.currentPhase.title)}`):t.goal&&o.push(`Task: ${H(t.goal)}`),n.length&&o.push(`Completed: ${n.join("; ")}`),s&&o.push(`Current file: ${H(s,260)}`),r.length&&o.push(`TODO: ${r.join("; ")}`),t.nextActions.length&&o.push(`Next action: ${H(t.nextActions[0])}`),t.blockers.length&&o.push(`Blocker: ${H(t.blockers[0])}`),o.push("","CONTINUATION CONTRACT:","- Continue from this compact handoff; do not reconstruct the prior session.","- NEVER inspect .toolnet/sessions/** (legacy), .toolnet/journal/**, or .toolnet/runtime/sources/**, state.json, events.jsonl, or raw transcripts.","- If this handoff is insufficient, invoke memory_agent_ask directly.","- Do not search for memory_agent_ask implementation/schema.","- Inspect git/source only to validate current code after continuity is resolved."),o.join(`
105
- `)}async function ac(e){let t=oc(e.project);if(!t)try{t=await se(e.project,e.storage)}catch{t=null}let n=t?ic(e.project,t):"";if(!n)try{n=(await cr(e.project,e.storage,700))?.text??""}catch{n=""}let r=Sr(e.project.rootPath,{maxAssets:6,maxChars:900});return[n,r,ur()].filter(Boolean).join(`
104
+ `)}function fc(e,t,n){let r=n??Kt(lc(),".config","toolnet-memory","injections","agy");return Kt(r,`${e.id}-${t}.json`)}function pc(e){if(!Ar(e))return null;try{return JSON.parse(Ir(e,"utf8"))}catch{return null}}function G(e,t=280){let n=(e??"").replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,Math.max(0,t-1)).trimEnd()+"\u2026"}function mc(e){let t=Kt(e.rootPath,".toolnet","work","current.json");if(!Ar(t))return null;try{let n=JSON.parse(Ir(t,"utf8"));if(n.version===1&&n.projectId===e.id)return n}catch{}return null}function gc(e,t){let n=t.tasks.filter(i=>i.status==="completed").slice(-3).map(i=>G(i.title,220)),r=Array.from(new Set([...t.currentTask?[t.currentTask.title]:[],...t.tasks.filter(i=>i.status==="in_progress"||i.status==="blocked"||i.status==="pending").slice(0,4).map(i=>i.title)].map(i=>G(i,220)).filter(Boolean))),s=t.filesTouched.at(-1),o=["[TOOLNET CONTINUITY HANDOFF]",`Project: ${e.name}`];return t.currentTask?.title?o.push(`Task: ${G(t.currentTask.title)}`):t.currentPhase?.title?o.push(`Task: ${G(t.currentPhase.title)}`):t.goal&&o.push(`Task: ${G(t.goal)}`),n.length&&o.push(`Completed: ${n.join("; ")}`),s&&o.push(`Current file: ${G(s,260)}`),r.length&&o.push(`TODO: ${r.join("; ")}`),t.nextActions.length&&o.push(`Next action: ${G(t.nextActions[0])}`),t.blockers.length&&o.push(`Blocker: ${G(t.blockers[0])}`),o.push("","CONTINUATION CONTRACT:","- Continue from this compact handoff; do not reconstruct the prior session.","- NEVER inspect .toolnet/sessions/** (legacy), .toolnet/journal/**, or .toolnet/runtime/sources/**, state.json, events.jsonl, or raw transcripts.","- If this handoff is insufficient, invoke memory_agent_ask directly.","- Do not search for memory_agent_ask implementation/schema.","- Inspect git/source only to validate current code after continuity is resolved."),o.join(`
105
+ `)}async function yc(e){let t=mc(e.project);if(!t)try{t=await ie(e.project,e.storage)}catch{t=null}let n=t?gc(e.project,t):"";if(!n)try{n=(await mr(e.project,e.storage,700))?.text??""}catch{n=""}let r=Mr(e.project.rootPath,{maxAssets:6,maxChars:900});return[n,r,gr()].filter(Boolean).join(`
106
106
 
107
- `).trim()}async function br(e){let t=e.now??Date.now(),n=e.resumeAfterMs??360*60*1e3,r=rc(e.project,e.conversationId,e.markerDirectory),s=sc(r),o=s?Date.parse(s.injectedAt):0,i=o?t-o:Number.POSITIVE_INFINITY;if(s&&i<6e4)return{};let a=e.invocationNum===0,c=i>=n;if(s&&!a&&!c)return{};let u=await ac({project:e.project,storage:e.storage});return u?(ec(nc(r),{recursive:!0}),P(r,{digest:v(u),injectedAt:new Date(t).toISOString()}),{injectSteps:[{ephemeralMessage:u}]}):{}}import{existsSync as Om,mkdirSync as cc,readFileSync as Rm,renameSync as uc,writeFileSync as lc}from"node:fs";import{dirname as dc,join as fc}from"node:path";function pc(e){return fc(e.rootPath,".toolnet","context","session-origin.json")}function mc(e,t){cc(dc(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;lc(n,`${JSON.stringify(t,null,2)}
108
- `,{encoding:"utf8",mode:384}),uc(n,e)}function et(e,t){return[...e].filter(n=>n.kind===t).sort((n,r)=>{let s=n.occurredAt.localeCompare(r.occurredAt);return s!==0?s:n.sequence-r.sequence}).at(-1)}function xr(e,t){let n=et(t.observations,"file"),r=et(t.observations,"next_action"),s=et(t.observations,"blocker"),o=et(t.observations,"decision"),i={version:1,projectId:e.id,agent:t.agent,nativeSessionId:t.nativeSessionId,updatedAt:t.workState.updatedAt,currentRequest:t.workState.currentRequest,currentActivity:t.workState.currentActivity,currentTask:t.workState.currentTask?.title,currentPhase:t.workState.currentPhase?.title,lastTouchedFile:n?.text??t.workState.activeFiles?.at(-1)??t.workState.filesTouched.at(-1),latestNextAction:r?.text??t.workState.nextActions.at(-1),latestBlocker:s?.text??t.workState.blockers.at(-1),latestDecision:o?.text??t.workState.decisions.at(-1)};return mc(pc(e),i),i}import{existsSync as gc,readFileSync as yc,writeFileSync as hc}from"node:fs";import{join as kc}from"node:path";var Mr="<!-- TOOLNET:STABLE-WORK:BEGIN -->",$t="<!-- TOOLNET:STABLE-WORK:END -->";function Ft(e){switch(e.status){case"completed":return"[x]";case"in_progress":return"[~]";case"blocked":return"[!]";case"cancelled":return"[-]";default:return"[ ]"}}function K(e,t){return t.length?["",`${e}:`,...t.map(n=>`- ${n}`)]:[]}function jr(e,t){return t.length?["",`${e}:`,...t.map(n=>`- ${Ft(n)} ${n.title}`)]:[]}function Sc(e){let t=[Mr,"# ToolNet Stable Work State","",`Updated: ${e.updatedAt}`];return e.lastSession&&t.push(`Last agent: ${e.lastSession.agent}`,`Last session: ${e.lastSession.nativeSessionId}`),e.currentRequest&&t.push("","Current request:",e.currentRequest),e.currentActivity&&t.push("","Current activity:",e.currentActivity),e.goal&&t.push("","Goal:",e.goal),e.plan&&t.push("","Plan:",e.plan),e.currentPhase&&t.push("","Current phase:",`${Ft(e.currentPhase)} ${e.currentPhase.title}`),e.currentTask&&t.push("","Current task:",`${Ft(e.currentTask)} ${e.currentTask.title}`),t.push(...jr("Phases",e.phases)),t.push(...jr("TODO / Tasks",e.tasks)),t.push(...K("Next actions",e.nextActions)),t.push(...K("Blockers",e.blockers)),t.push(...K("Important decisions",e.decisions)),t.push(...K("Active files",e.activeFiles??[])),t.push(...K("Modified files",e.modifiedFiles??[])),t.push(...K("Created files",e.createdFiles??[])),t.push(...K("Deleted files",e.deletedFiles??[])),t.push(...K("Files touched",e.filesTouched)),t.push(...K("Recent commands",e.commands??[])),t.push(...K("Checks",(e.checks??[]).map(n=>`[${n.status}] ${n.kind}: ${n.command}`))),t.push("","Progress:",`- Phases: ${e.progress.phasesCompleted}/${e.progress.phasesTotal}`,`- Tasks: ${e.progress.tasksCompleted}/${e.progress.tasksTotal}`,`- Blocked: ${e.progress.blocked}`,"","Continuation:","- Resume current unfinished task.","- Never redo completed TODO/Phase unless explicitly requested.","- Ask ToolNet Memory for deeper history only when necessary.",$t),t.join(`
109
- `)}function Ar(e,t){let n=kc(e.rootPath,".toolnet","current.md"),r="";if(gc(n))try{r=yc(n,"utf8")}catch{r=""}r=r.replace(/<!-- TOOLNET:AUTO-CURRENT:BEGIN -->[\s\S]*?<!-- TOOLNET:AUTO-CURRENT:END -->/gu,"");let s=Sc(t),o=r.indexOf(Mr),i=r.indexOf($t),a;o>=0&&i>=o?a=[r.slice(0,o).trimEnd(),s,r.slice(i+$t.length).trimStart()].filter(Boolean).join(`
107
+ `).trim()}async function Pr(e){let t=e.now??Date.now(),n=e.resumeAfterMs??360*60*1e3,r=fc(e.project,e.conversationId,e.markerDirectory),s=pc(r),o=s?Date.parse(s.injectedAt):0,i=o?t-o:Number.POSITIVE_INFINITY;if(s&&i<6e4)return{};let a=e.invocationNum===0,c=i>=n;if(s&&!a&&!c)return{};let u=await yc({project:e.project,storage:e.storage});return u?(uc(dc(r),{recursive:!0}),E(r,{digest:w(u),injectedAt:new Date(t).toISOString()}),{injectSteps:[{ephemeralMessage:u}]}):{}}import{existsSync as Vm,mkdirSync as hc,readFileSync as Hm,renameSync as kc,writeFileSync as Sc}from"node:fs";import{dirname as vc,join as wc}from"node:path";function bc(e){return wc(e.rootPath,".toolnet","context","session-origin.json")}function xc(e,t){hc(vc(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;Sc(n,`${JSON.stringify(t,null,2)}
108
+ `,{encoding:"utf8",mode:384}),kc(n,e)}function st(e,t){return[...e].filter(n=>n.kind===t).sort((n,r)=>{let s=n.occurredAt.localeCompare(r.occurredAt);return s!==0?s:n.sequence-r.sequence}).at(-1)}function Cr(e,t){let n=st(t.observations,"file"),r=st(t.observations,"next_action"),s=st(t.observations,"blocker"),o=st(t.observations,"decision"),i={version:1,projectId:e.id,agent:t.agent,nativeSessionId:t.nativeSessionId,updatedAt:t.workState.updatedAt,currentRequest:t.workState.currentRequest,currentActivity:t.workState.currentActivity,currentTask:t.workState.currentTask?.title,currentPhase:t.workState.currentPhase?.title,lastTouchedFile:n?.text??t.workState.activeFiles?.at(-1)??t.workState.filesTouched.at(-1),latestNextAction:r?.text??t.workState.nextActions.at(-1),latestBlocker:s?.text??t.workState.blockers.at(-1),latestDecision:o?.text??t.workState.decisions.at(-1)};return xc(bc(e),i),i}import{existsSync as jc,readFileSync as Mc,writeFileSync as Ac}from"node:fs";import{join as Ic}from"node:path";var Er="<!-- TOOLNET:STABLE-WORK:BEGIN -->",Lt="<!-- TOOLNET:STABLE-WORK:END -->";function Wt(e){switch(e.status){case"completed":return"[x]";case"in_progress":return"[~]";case"blocked":return"[!]";case"cancelled":return"[-]";default:return"[ ]"}}function L(e,t){return t.length?["",`${e}:`,...t.map(n=>`- ${n}`)]:[]}function Tr(e,t){return t.length?["",`${e}:`,...t.map(n=>`- ${Wt(n)} ${n.title}`)]:[]}function Pc(e){let t=[Er,"# ToolNet Stable Work State","",`Updated: ${e.updatedAt}`];return e.lastSession&&t.push(`Last agent: ${e.lastSession.agent}`,`Last session: ${e.lastSession.nativeSessionId}`),e.currentRequest&&t.push("","Current request:",e.currentRequest),e.currentActivity&&t.push("","Current activity:",e.currentActivity),e.goal&&t.push("","Goal:",e.goal),e.plan&&t.push("","Plan:",e.plan),e.currentPhase&&t.push("","Current phase:",`${Wt(e.currentPhase)} ${e.currentPhase.title}`),e.currentTask&&t.push("","Current task:",`${Wt(e.currentTask)} ${e.currentTask.title}`),t.push(...Tr("Phases",e.phases)),t.push(...Tr("TODO / Tasks",e.tasks)),t.push(...L("Next actions",e.nextActions)),t.push(...L("Blockers",e.blockers)),t.push(...L("Important decisions",e.decisions)),t.push(...L("Active files",e.activeFiles??[])),t.push(...L("Modified files",e.modifiedFiles??[])),t.push(...L("Created files",e.createdFiles??[])),t.push(...L("Deleted files",e.deletedFiles??[])),t.push(...L("Files touched",e.filesTouched)),t.push(...L("Recent commands",e.commands??[])),t.push(...L("Checks",(e.checks??[]).map(n=>`[${n.status}] ${n.kind}: ${n.command}`))),t.push("","Progress:",`- Phases: ${e.progress.phasesCompleted}/${e.progress.phasesTotal}`,`- Tasks: ${e.progress.tasksCompleted}/${e.progress.tasksTotal}`,`- Blocked: ${e.progress.blocked}`,"","Continuation:","- Resume current unfinished task.","- Never redo completed TODO/Phase unless explicitly requested.","- Ask ToolNet Memory for deeper history only when necessary.",Lt),t.join(`
109
+ `)}function Or(e,t){let n=Ic(e.rootPath,".toolnet","current.md"),r="";if(jc(n))try{r=Mc(n,"utf8")}catch{r=""}r=r.replace(/<!-- TOOLNET:AUTO-CURRENT:BEGIN -->[\s\S]*?<!-- TOOLNET:AUTO-CURRENT:END -->/gu,"");let s=Pc(t),o=r.indexOf(Er),i=r.indexOf(Lt),a;o>=0&&i>=o?a=[r.slice(0,o).trimEnd(),s,r.slice(i+Lt.length).trimStart()].filter(Boolean).join(`
110
110
 
111
111
  `):a=r.trim()?`${r.trim()}
112
112
 
113
- ${s}`:s,hc(n,`${a.trim()}
114
- `,{encoding:"utf8",mode:384})}import{existsSync as Br,mkdirSync as ou,readFileSync as iu}from"node:fs";import{join as qt}from"node:path";var wc=new Set(["rule","blocker","architecture","deploy"]),bc=new Set(["fix","todo","context","next_action"]);function Kt(e){return e<0?0:e>1?1:e}function Ir(e,t){let n=Number.parseFloat(e??"");return Number.isFinite(n)?n:t}function xc(e){return e==="off"?"off":e==="balanced"?"balanced":e==="aggressive"?"aggressive":"conservative"}function Lt(){return{mode:xc(process.env.TOOLNET_MEMORY_PROMOTION),minScore:Kt(Ir(process.env.TOOLNET_PROMOTE_MIN_SCORE,.65)),minConfidence:Kt(Ir(process.env.TOOLNET_PROMOTE_MIN_CONFIDENCE,.78))}}function jc(e){switch(e){case"critical":return 1;case"high":return .85;case"normal":return .6;case"temporary":return .25}}function Mc(e){let t=Kt(jc(e.importance)*.75+e.confidence*.25);return Math.round(t*1e6)/1e6}function Ac(e){return e.evidence?e.evidence:{userExplicit:!1,sourceVerified:!1,testVerified:!1,crossSessionConfirmations:0,assistantDerived:!1}}function Ic(e,t=Lt()){if(e.importance==="temporary"||e.confidence<t.minConfidence)return"transient";let n=Ac(e);return e.kind==="rule"&&n.userExplicit?"permanent":e.kind==="rule"?"session":e.kind==="architecture"&&(n.userExplicit||n.sourceVerified||n.testVerified||n.crossSessionConfirmations>=2)?"permanent":e.kind==="architecture"?"session":e.kind==="decision"||e.kind==="todo"||e.kind==="fix"?"task":"session"}function Cc(e,t=Lt()){if(t.mode==="off")return Number.POSITIVE_INFINITY;let n=0;t.mode==="balanced"&&(n=.1),t.mode==="aggressive"&&(n=.15);let r=Math.max(t.mode==="aggressive"?.5:.55,t.minScore-n);return wc.has(e)&&(r=Math.max(.5,r-.1)),bc.has(e)&&(r=Math.max(.5,r-.05)),r}function Wt(e,t=Lt()){let n=Ic(e,t),r=Mc(e),s=Cc(e.kind,t);return n==="transient"?{knowledgeClass:n,score:r,threshold:s,persist:!1}:t.mode==="off"?{knowledgeClass:n,score:r,threshold:s,persist:!1}:{knowledgeClass:n,score:r,threshold:s,persist:r>=s}}function Cr(e,t){let n=t.toLowerCase();return n.includes("kh\xF4ng \u0111\u01B0\u1EE3c")||n.includes("tuy\u1EC7t \u0111\u1ED1i")||n.includes("must not")||n.includes("never ")?"critical":e==="rule"||e==="decision"?"high":e==="todo"||n.includes("error")||n.includes("failed")||n.includes("exception")?"normal":"temporary"}var Or=[/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],Pc=[/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],Tc=[/\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],Ec=[/\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],Oc=[/đã 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],Rc=[/\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],Nc=[/đườ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],_c=[/\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],Tr=new Set(["content","text","message","prompt","summary","description","reason","title","last_assistant_message","lastAssistantMessage","input_messages","inputMessages"]),$c=new Set(["payload","data","content","message","messages","parts","summary"]);function _(e,t){return t.some(n=>n.test(e))}function Rr(e){return e.normalize("NFKC").replace(/\r/g,"").replace(/^[\s>*#\-•]+/u,"").replace(/\s+/g," ").trim()}function Fc(e){return Rr(e).toLowerCase().replace(/[^\p{L}\p{N}:/._-]+/gu," ").replace(/\s+/g," ").trim()}function Kc(e){return!(e.length<12||e.length>1e3||(e.match(new RegExp("\\p{L}","gu"))??[]).length<6||/^(?:https?:\/\/\S+|[A-Za-z0-9+/=]{80,})$/u.test(e))}function Dt(e,t,n,r=0){if(!(r>6)&&!(typeof e=="string"&&t&&!Tr.has(t))){if(typeof e=="string"){n.push(e);return}if(Array.isArray(e)){for(let s of e.slice(0,50))Dt(s,t,n,r+1);return}if(!(!e||typeof e!="object"))for(let[s,o]of Object.entries(e))(Tr.has(s)||$c.has(s))&&Dt(o,s,n,r+1)}}function Lc(e){let t=[];Dt(e.data,void 0,t);let n=[],r=new Set;for(let s of t)for(let o of s.split(/\n+|(?<=[.!?])\s+/u)){let i=Rr(o);if(Kc(i)&&!r.has(i)&&(r.add(i),n.push(i),n.length>=50))return n}return n}function Er(e){return(e.role??(typeof e.data.role=="string"?e.data.role:"")).toLowerCase()}function Wc(e,t,n){if(n.type==="decision")return{kind:"decision",confidence:1};if(n.type==="todo")return{kind:"todo",confidence:1};let r=t==="user"||n.type==="user_prompt",s=t==="assistant"||n.type==="assistant_message";return r&&_(e,Or)?{kind:"rule",confidence:.98}:r&&_(e,Pc)?{kind:"rule",confidence:.92}:_(e,Tc)?{kind:_(e,Pr)?"architecture":"decision",confidence:r?.93:.86}:r&&_(e,Ec)?{kind:"todo",confidence:.87}:_(e,Pr)&&_(e,Rc)?{kind:"architecture",confidence:r?.88:.82}:s&&_(e,Oc)?{kind:"fix",confidence:.8}:r&&_(e,Nc)&&_(e,_c)?{kind:"context",confidence:.79}:null}function Dc(e,t,n){let r=t==="user"||n.type==="user_prompt",s=t==="assistant"||n.type==="assistant_message",o=!!n.provenance.sourcePath&&(e==="architecture"||e==="context"||e==="fix"),i=e==="fix"&&/(?:test|tests|pass|passed|passing)/iu.test(JSON.stringify(n.data));return{userExplicit:r,sourceVerified:o,testVerified:i,crossSessionConfirmations:1,assistantDerived:s}}function zc(e){switch(e){case"rule":return"rule";case"decision":case"architecture":return"decision";case"todo":return"todo";case"fix":case"context":return"code"}}function qc(e,t,n){return e==="rule"&&_(n,Or)?"critical":e==="architecture"||e==="decision"||e==="rule"?"high":e==="fix"||e==="context"?"normal":Cr(t,n)}function Nr(e,t){let n=[],r=new Set,s=new Map;for(let o of t){let i=typeof o.data.messageId=="string"?o.data.messageId:void 0,a=Er(o);i&&a&&s.set(i,a)}for(let o of t){let i=Er(o),a=typeof o.data.messageId=="string"?o.data.messageId:void 0;!i&&a&&(i=s.get(a)??"");for(let c of Lc(o)){let u=Wc(c,i,o);if(!u||u.confidence<.75)continue;let f=zc(u.kind),l=Fc(c),p=v([e.projectId,u.kind,l].join("|"));if(r.has(p))continue;r.add(p);let d=o.provenance.sourcePath?[o.provenance.sourcePath]:[],g=o.sourceEventId?[o.sourceEventId]:[];n.push({version:1,fingerprint:p,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,kind:u.kind,type:f,content:c,confidence:u.confidence,importance:qc(u.kind,f,c),evidence:Dc(u.kind,i,o),tags:[f],provenance:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,eventIds:[o.id],sourceEventIds:g,sourcePaths:d,firstSequence:o.sequence,lastSequence:o.sequence},createdAt:o.timestamp})}}return n}import{createHash as Bc}from"node:crypto";var Vc=["project-knowledge","implementation","continuation","session-context"],Hc={"project-knowledge":"Project knowledge",implementation:"Implementation state",continuation:"Work continuation","session-context":"Session context"};function zt(e){return Bc("sha256").update(e).digest("hex")}function tt(e,t){return`${e}:${zt(t).slice(0,24)}`}function Jc(e){try{return zt(JSON.stringify(e))}catch{return zt(String(e))}}function X(e){let t=new Set,n=[];for(let r of e){let s=r?.replace(/\s+/gu," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();t.has(o)||(t.add(o),n.push(s))}return n}function $r(e,t=420){let n=e.replace(/\s+/gu," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function Gc(e){return e==="rule"||e==="architecture"?"project-knowledge":e==="decision"||e==="fix"?"implementation":e==="todo"?"continuation":"session-context"}function _r(e){return e.length===0?0:e.reduce((t,n)=>t+n,0)/e.length}function Uc(e){return e.slice().sort((t,n)=>n.importanceScore-t.importanceScore||n.confidence-t.confidence||t.id.localeCompare(n.id)).slice(0,5).map(t=>$r(t.content)).join(" | ")}function Yc(e){return e.slice().sort((t,n)=>n.importanceScore-t.importanceScore||n.confidence-t.confidence||t.id.localeCompare(n.id)).slice(0,6).map(t=>$r(t.content)).join(`
115
- `)}function Fr(e,t){let n=e.slice().sort((p,d)=>p.sequence-d.sequence||p.timestamp.localeCompare(d.timestamp)||p.id.localeCompare(d.id)),r=n.map(p=>({id:tt("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:Jc(p.data)})),s=new Map,o=new Map;n.forEach((p,d)=>{let g=r[d];g&&(s.set(p.id,g.id),p.sourceEventId&&o.set(p.sourceEventId,g.id))});let i=t.map(p=>{let d=X([...p.provenance.eventIds.map(g=>s.get(g)),...p.provenance.sourceEventIds.map(g=>o.get(g))]);return{id:tt("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:X([...p.tags,"level:fact",`class:${p.knowledgeClass}`,`kind:${p.kind}`]),rawIds:d,sourcePaths:X(p.provenance.sourcePaths)}}),a=new Map;for(let p of i){let d=Gc(p.kind),g=a.get(d)??[];g.push(p),a.set(d,g)}let c=[];for(let p of Vc){let d=a.get(p);if(!d?.length)continue;let g=d.slice().sort((y,h)=>h.importanceScore-y.importanceScore||h.confidence-y.confidence||y.id.localeCompare(h.id)),k=g.map(y=>y.id);c.push({id:tt("scene",`${p}|${k.join("|")}`),level:"scene",kind:p,title:Hc[p],summary:Uc(g),factIds:k,importanceScore:Math.max(...g.map(y=>y.importanceScore)),confidence:_r(g.map(y=>y.confidence)),tags:X(["level:scene",`scene:${p}`,...g.flatMap(y=>y.tags)]),sourcePaths:X(g.flatMap(y=>y.sourcePaths))})}let u=new Map(i.map(p=>[p.id,p])),f=[];for(let p of c){let g=p.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 k=g.some(h=>h.knowledgeClass==="permanent")?"permanent":"task",y=Yc(g);f.push({id:tt("knowledge",`${p.id}|${k}|${g.map(h=>h.id).join("|")}`),level:"knowledge",knowledgeClass:k,title:p.title,content:y,sceneIds:[p.id],factIds:g.map(h=>h.id),importanceScore:Math.max(...g.map(h=>h.importanceScore)),confidence:_r(g.map(h=>h.confidence)),tags:X(["level:knowledge",`class:${k}`,`scene:${p.kind}`,...g.flatMap(h=>h.tags)]),sourcePaths:X(g.flatMap(h=>h.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 Z(){let e=Ne(),t=process.env.TOOLNET_SESSION_SAVE||"summary",n=process.env.TOOLNET_RAW_TRANSCRIPT==="on"||t==="archive"||t==="full",r=process.env.TOOLNET_MEMORY_PROMOTION||"conservative",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"||t==="full";return{sessionSave:t,rawTranscript:n,memoryPromotion:r,promoteMinScore:s,sessionSummaryMaxTokens:o,durableMemoryMaxItemsPerSession:i,archiveLocal:a,archiveRemote:c}}function Kr(e){return(e||Z()).rawTranscript}function Lr(e){return(e||Z()).durableMemoryMaxItemsPerSession}function Wr(e){return(e||Z()).sessionSummaryMaxTokens}function Dr(e){return(e||Z()).archiveRemote}var zr=new U;function qr(e){let t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{let r=JSON.parse(t);return JSON.stringify(zr.sanitizeValue(r))}catch{}let n=zr.sanitize(e).text;return n=n.replace(/("(?:api[_-]?key|token|secret|password|cookie|authorization)"\s*:\s*)"[^"]*"/gi,'$1"[REDACTED]"').replace(/('(?:api[_-]?key|token|secret|password|cookie|authorization)'\s*:\s*)'[^']*'/gi,"$1'[REDACTED]'").replace(/\b(api[_-]?key|token|secret|password|cookie|authorization)\b\s*[:=]\s*[^\s,;]+/gi,"$1=[REDACTED]").replace(/\bbearer\s+[A-Za-z0-9._~+/=-]+/gi,"Bearer [REDACTED]"),n}function Qc(e,t){let n=e.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);t==="rule"||t==="architecture"||t==="blocker"?r+=.2:t==="decision"||t==="deploy"?r+=.15:(t==="fix"||t==="next_action")&&(r+=.1),e.length<20?r-=.3:e.length>500&&(r-=.1);let 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(e)&&(r-=.4);return Math.max(0,Math.min(1,r))}function Xc(e,t){let n=[],r=new Set;for(let i of e){let a=i.split(`
116
- `).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=Qc(u,l);if(p<.3)continue;let d=qr(u);n.push({category:l,text:d,importance:p,sourceSessionId:t})}}let s=Z(),o=Lr(s);return n.sort((i,a)=>a.importance-i.importance).slice(0,o)}function Zc(e){let t=Z(),n=Wr(t),o=e.join(`
113
+ ${s}`:s,Ac(n,`${a.trim()}
114
+ `,{encoding:"utf8",mode:384})}import{existsSync as Yr,mkdirSync as mu,readFileSync as gu}from"node:fs";import{join as Ht}from"node:path";var Tc=new Set(["rule","blocker","architecture","deploy"]),Ec=new Set(["fix","todo","context","next_action"]);function Dt(e){return e<0?0:e>1?1:e}function Rr(e,t){let n=Number.parseFloat(e??"");return Number.isFinite(n)?n:t}function Oc(e){return e==="off"?"off":e==="balanced"?"balanced":e==="aggressive"?"aggressive":"conservative"}function zt(){return{mode:Oc(process.env.TOOLNET_MEMORY_PROMOTION),minScore:Dt(Rr(process.env.TOOLNET_PROMOTE_MIN_SCORE,.65)),minConfidence:Dt(Rr(process.env.TOOLNET_PROMOTE_MIN_CONFIDENCE,.78))}}function Rc(e){switch(e){case"critical":return 1;case"high":return .85;case"normal":return .6;case"temporary":return .25}}function Nc(e){let t=Dt(Rc(e.importance)*.75+e.confidence*.25);return Math.round(t*1e6)/1e6}function _c(e){return e.evidence?e.evidence:{userExplicit:!1,sourceVerified:!1,testVerified:!1,crossSessionConfirmations:0,assistantDerived:!1}}function $c(e,t=zt()){if(e.importance==="temporary"||e.confidence<t.minConfidence)return"transient";let n=_c(e);return e.kind==="rule"&&n.userExplicit?"permanent":e.kind==="rule"?"session":e.kind==="architecture"&&(n.userExplicit||n.sourceVerified||n.testVerified||n.crossSessionConfirmations>=2)?"permanent":e.kind==="architecture"?"session":e.kind==="decision"||e.kind==="todo"||e.kind==="fix"?"task":"session"}function Fc(e,t=zt()){if(t.mode==="off")return Number.POSITIVE_INFINITY;let n=0;t.mode==="balanced"&&(n=.1),t.mode==="aggressive"&&(n=.15);let r=Math.max(t.mode==="aggressive"?.5:.55,t.minScore-n);return Tc.has(e)&&(r=Math.max(.5,r-.1)),Ec.has(e)&&(r=Math.max(.5,r-.05)),r}function qt(e,t=zt()){let n=$c(e,t),r=Nc(e),s=Fc(e.kind,t);return n==="transient"?{knowledgeClass:n,score:r,threshold:s,persist:!1}:t.mode==="off"?{knowledgeClass:n,score:r,threshold:s,persist:!1}:{knowledgeClass:n,score:r,threshold:s,persist:r>=s}}function Nr(e,t){let n=t.toLowerCase();return n.includes("kh\xF4ng \u0111\u01B0\u1EE3c")||n.includes("tuy\u1EC7t \u0111\u1ED1i")||n.includes("must not")||n.includes("never ")?"critical":e==="rule"||e==="decision"?"high":e==="todo"||n.includes("error")||n.includes("failed")||n.includes("exception")?"normal":"temporary"}var Kr=[/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],Kc=[/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],Lc=[/\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],Wc=[/\btodo\b/iu,/cần làm/iu,/cần thêm/iu,/cần sửa/iu,/cần kiểm tra/iu,/tiếp theo/iu,/bước tiếp theo/iu,/còn phải/iu,/còn cần/iu,/next step/iu,/\bneed to\b/iu,/\bremaining\b/iu,/follow[- ]?up/iu],Dc=[/đã 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],_r=[/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],zc=[/\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],qc=[/đườ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],Bc=[/\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],$r=new Set(["content","text","message","prompt","summary","description","reason","title","last_assistant_message","lastAssistantMessage","input_messages","inputMessages"]),Vc=new Set(["payload","data","content","message","messages","parts","summary"]);function $(e,t){return t.some(n=>n.test(e))}function Lr(e){return e.normalize("NFKC").replace(/\r/g,"").replace(/^[\s>*#\-•]+/u,"").replace(/\s+/g," ").trim()}function Hc(e){return Lr(e).toLowerCase().replace(/[^\p{L}\p{N}:/._-]+/gu," ").replace(/\s+/g," ").trim()}function Jc(e){return!(e.length<12||e.length>1e3||(e.match(new RegExp("\\p{L}","gu"))??[]).length<6||/^(?:https?:\/\/\S+|[A-Za-z0-9+/=]{80,})$/u.test(e))}function Bt(e,t,n,r=0){if(!(r>6)&&!(typeof e=="string"&&t&&!$r.has(t))){if(typeof e=="string"){n.push(e);return}if(Array.isArray(e)){for(let s of e.slice(0,50))Bt(s,t,n,r+1);return}if(!(!e||typeof e!="object"))for(let[s,o]of Object.entries(e))($r.has(s)||Vc.has(s))&&Bt(o,s,n,r+1)}}function Gc(e){let t=[];Bt(e.data,void 0,t);let n=[],r=new Set;for(let s of t)for(let o of s.split(/\n+|(?<=[.!?])\s+/u)){let i=Lr(o);if(Jc(i)&&!r.has(i)&&(r.add(i),n.push(i),n.length>=50))return n}return n}function Fr(e){return(e.role??(typeof e.data.role=="string"?e.data.role:"")).toLowerCase()}function Uc(e,t,n){if(n.type==="decision")return{kind:"decision",confidence:1};if(n.type==="todo")return{kind:"todo",confidence:1};let r=t==="user"||n.type==="user_prompt",s=t==="assistant"||n.type==="assistant_message";return r&&$(e,Kr)?{kind:"rule",confidence:.98}:r&&$(e,Kc)?{kind:"rule",confidence:.92}:$(e,Lc)?{kind:$(e,_r)?"architecture":"decision",confidence:r?.93:.86}:r&&$(e,Wc)?{kind:"todo",confidence:.87}:$(e,_r)&&$(e,zc)?{kind:"architecture",confidence:r?.88:.82}:s&&$(e,Dc)?{kind:"fix",confidence:.8}:r&&$(e,qc)&&$(e,Bc)?{kind:"context",confidence:.79}:null}function Yc(e,t,n){let r=t==="user"||n.type==="user_prompt",s=t==="assistant"||n.type==="assistant_message",o=!!n.provenance.sourcePath&&(e==="architecture"||e==="context"||e==="fix"),i=e==="fix"&&/(?:test|tests|pass|passed|passing)/iu.test(JSON.stringify(n.data));return{userExplicit:r,sourceVerified:o,testVerified:i,crossSessionConfirmations:1,assistantDerived:s}}function Qc(e){switch(e){case"rule":return"rule";case"decision":case"architecture":return"decision";case"todo":return"todo";case"fix":case"context":return"code"}}function Xc(e,t,n){return e==="rule"&&$(n,Kr)?"critical":e==="architecture"||e==="decision"||e==="rule"?"high":e==="fix"||e==="context"?"normal":Nr(t,n)}function Wr(e,t){let n=[],r=new Set,s=new Map;for(let o of t){let i=typeof o.data.messageId=="string"?o.data.messageId:void 0,a=Fr(o);i&&a&&s.set(i,a)}for(let o of t){let i=Fr(o),a=typeof o.data.messageId=="string"?o.data.messageId:void 0;!i&&a&&(i=s.get(a)??"");for(let c of Gc(o)){let u=Uc(c,i,o);if(!u||u.confidence<.75)continue;let f=Qc(u.kind),l=Hc(c),p=w([e.projectId,u.kind,l].join("|"));if(r.has(p))continue;r.add(p);let d=o.provenance.sourcePath?[o.provenance.sourcePath]:[],m=o.sourceEventId?[o.sourceEventId]:[];n.push({version:1,fingerprint:p,projectId:e.projectId,agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,kind:u.kind,type:f,content:c,confidence:u.confidence,importance:Xc(u.kind,f,c),evidence:Yc(u.kind,i,o),tags:[f],provenance:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,eventIds:[o.id],sourceEventIds:m,sourcePaths:d,firstSequence:o.sequence,lastSequence:o.sequence},createdAt:o.timestamp})}}return n}import{createHash as Zc}from"node:crypto";var eu=["project-knowledge","implementation","continuation","session-context"],tu={"project-knowledge":"Project knowledge",implementation:"Implementation state",continuation:"Work continuation","session-context":"Session context"};function Vt(e){return Zc("sha256").update(e).digest("hex")}function ot(e,t){return`${e}:${Vt(t).slice(0,24)}`}function nu(e){try{return Vt(JSON.stringify(e))}catch{return Vt(String(e))}}function Z(e){let t=new Set,n=[];for(let r of e){let s=r?.replace(/\s+/gu," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();t.has(o)||(t.add(o),n.push(s))}return n}function zr(e,t=420){let n=e.replace(/\s+/gu," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function ru(e){return e==="rule"||e==="architecture"?"project-knowledge":e==="decision"||e==="fix"?"implementation":e==="todo"?"continuation":"session-context"}function Dr(e){return e.length===0?0:e.reduce((t,n)=>t+n,0)/e.length}function su(e){return e.slice().sort((t,n)=>n.importanceScore-t.importanceScore||n.confidence-t.confidence||t.id.localeCompare(n.id)).slice(0,5).map(t=>zr(t.content)).join(" | ")}function ou(e){return e.slice().sort((t,n)=>n.importanceScore-t.importanceScore||n.confidence-t.confidence||t.id.localeCompare(n.id)).slice(0,6).map(t=>zr(t.content)).join(`
115
+ `)}function qr(e,t){let n=e.slice().sort((p,d)=>p.sequence-d.sequence||p.timestamp.localeCompare(d.timestamp)||p.id.localeCompare(d.id)),r=n.map(p=>({id:ot("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:nu(p.data)})),s=new Map,o=new Map;n.forEach((p,d)=>{let m=r[d];m&&(s.set(p.id,m.id),p.sourceEventId&&o.set(p.sourceEventId,m.id))});let i=t.map(p=>{let d=Z([...p.provenance.eventIds.map(m=>s.get(m)),...p.provenance.sourceEventIds.map(m=>o.get(m))]);return{id:ot("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=ru(p.kind),m=a.get(d)??[];m.push(p),a.set(d,m)}let c=[];for(let p of eu){let d=a.get(p);if(!d?.length)continue;let m=d.slice().sort((g,h)=>h.importanceScore-g.importanceScore||h.confidence-g.confidence||g.id.localeCompare(h.id)),k=m.map(g=>g.id);c.push({id:ot("scene",`${p}|${k.join("|")}`),level:"scene",kind:p,title:tu[p],summary:su(m),factIds:k,importanceScore:Math.max(...m.map(g=>g.importanceScore)),confidence:Dr(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(h=>u.get(h)).filter(h=>!!h).filter(h=>(h.knowledgeClass==="permanent"||h.knowledgeClass==="task")&&h.importanceScore>=.55);if(m.length===0)continue;let k=m.some(h=>h.knowledgeClass==="permanent")?"permanent":"task",g=ou(m);f.push({id:ot("knowledge",`${p.id}|${k}|${m.map(h=>h.id).join("|")}`),level:"knowledge",knowledgeClass:k,title:p.title,content:g,sceneIds:[p.id],factIds:m.map(h=>h.id),importanceScore:Math.max(...m.map(h=>h.importanceScore)),confidence:Dr(m.map(h=>h.confidence)),tags:Z(["level:knowledge",`class:${k}`,`scene:${p.kind}`,...m.flatMap(h=>h.tags)]),sourcePaths:Z(m.flatMap(h=>h.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 ee(){let e=Fe(),t=process.env.TOOLNET_SESSION_SAVE||"summary",n=process.env.TOOLNET_RAW_TRANSCRIPT==="on"||t==="archive"||t==="full",r=process.env.TOOLNET_MEMORY_PROMOTION||"conservative",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"||t==="full";return{sessionSave:t,rawTranscript:n,memoryPromotion:r,promoteMinScore:s,sessionSummaryMaxTokens:o,durableMemoryMaxItemsPerSession:i,archiveLocal:a,archiveRemote:c}}function Br(e){return(e||ee()).rawTranscript}function Vr(e){return(e||ee()).durableMemoryMaxItemsPerSession}function Hr(e){return(e||ee()).sessionSummaryMaxTokens}function Jr(e){return(e||ee()).archiveRemote}var Gr=new V;function Ur(e){let t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{let r=JSON.parse(t);return JSON.stringify(Gr.sanitizeValue(r))}catch{}let n=Gr.sanitize(e).text;return n=n.replace(/("(?:api[_-]?key|token|secret|password|cookie|authorization)"\s*:\s*)"[^"]*"/gi,'$1"[REDACTED]"').replace(/('(?:api[_-]?key|token|secret|password|cookie|authorization)'\s*:\s*)'[^']*'/gi,"$1'[REDACTED]'").replace(/\b(api[_-]?key|token|secret|password|cookie|authorization)\b\s*[:=]\s*[^\s,;]+/gi,"$1=[REDACTED]").replace(/\bbearer\s+[A-Za-z0-9._~+/=-]+/gi,"Bearer [REDACTED]"),n}function iu(e,t){let n=e.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);t==="rule"||t==="architecture"||t==="blocker"?r+=.2:t==="decision"||t==="deploy"?r+=.15:(t==="fix"||t==="next_action")&&(r+=.1),e.length<20?r-=.3:e.length>500&&(r-=.1);let 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(e)&&(r-=.4);return Math.max(0,Math.min(1,r))}function au(e,t){let n=[],r=new Set;for(let i of e){let a=i.split(`
116
+ `).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=iu(u,l);if(p<.3)continue;let d=Ur(u);n.push({category:l,text:d,importance:p,sourceSessionId:t})}}let s=ee(),o=Vr(s);return n.sort((i,a)=>a.importance-i.importance).slice(0,o)}function cu(e){let t=ee(),n=Hr(t),o=e.join(`
117
117
 
118
118
  `).split(`
119
- `).filter(i=>{let a=i.trim();return a.length>20&&!a.startsWith("npm")&&!a.startsWith("\u2713")&&!a.startsWith("Error:")}).slice(0,20).map(i=>qr(i)).join(`
120
- `);return Xe(o,n)}function nt(e,t){let r=(Array.isArray(e)?e:e.split(`
119
+ `).filter(i=>{let a=i.trim();return a.length>20&&!a.startsWith("npm")&&!a.startsWith("\u2713")&&!a.startsWith("Error:")}).slice(0,20).map(i=>Ur(i)).join(`
120
+ `);return nt(o,n)}function it(e,t){let r=(Array.isArray(e)?e:e.split(`
121
121
 
122
- `).filter(d=>d.trim())).map(d=>typeof d=="string"?d:JSON.stringify(d)).filter(d=>d.trim()),s=Xc(r,t),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),f=s.filter(d=>d.category==="next_action").map(d=>d.text),l=s.filter(d=>d.category==="deploy").map(d=>d.text);return{summary:Zc(r),decisions:o,projectRules:i,filesChanged:a,bugsFixed:c,commands:l,blockers:u,nextActions:f,durableFacts:s}}function J(e){let t=new Set,n=[];for(let r of e){let s=r?.replace(/\s+/g," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();t.has(o)||(t.add(o),n.push(s))}return n}function eu(e){let t=new Map;for(let n of e){if(!n||!n.id||!Number.isFinite(n.sequence))continue;let r=n.sourceEventId?`${n.agent}:${n.sourceEventId}`:n.id,s=t.get(r);(!s||n.sequence>s.sequence)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.sequence-r.sequence||n.timestamp.localeCompare(r.timestamp))}function tu(e){let t=e.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_./:-]+/gu)??[],n=new Set;for(let r of t)if(!(r.length<2||/^\d+$/u.test(r))&&(n.add(r),n.size>=40))break;return[...n]}function nu(e){let t=Wt(e);return{...e,knowledgeClass:t.knowledgeClass,importanceScore:t.score,retrievalTerms:tu(e.content),tags:J([...e.tags,"level:fact",`class:${t.knowledgeClass}`,`kind:${e.kind}`])}}function ru(e){return e.map(t=>{try{return JSON.stringify({type:t.type,role:t.role,data:t.data,provenance:{sourcePath:t.provenance.sourcePath,files:t.provenance.files}})}catch{return""}}).filter(Boolean)}function su(e,t,n){let r=nt(ru(t),e.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 rt(e,t){let n=eu(t),r=Nr(e,n).map(nu),s=r.filter(f=>Wt(f).persist).sort((f,l)=>l.importanceScore-f.importanceScore),{summary:o,state:i}=su(e,n,s),a=s.map(f=>({fingerprint:f.fingerprint,kind:f.kind,knowledgeClass:f.knowledgeClass,importanceScore:f.importanceScore,content:f.content,terms:f.retrievalTerms})),c=Fr(n,s),u=f=>r.filter(l=>l.knowledgeClass===f).length;return{version:2,normalizedEvents:n,summary:o,state:i,candidates:s,retrievalIndex:a,hierarchy:c,stats:{inputEvents:t.length,normalizedEvents:n.length,extractedCandidates:r.length,persistedCandidates:s.length,permanent:u("permanent"),task:u("task"),session:u("session"),transient:u("transient")}}}function Vr(e){return qt(e.rootPath,".toolnet","memory","checkpoints")}function Hr(e){return qt(Vr(e),"latest.json")}function au(e){let t=Hr(e);if(!Br(t))return null;try{let n=JSON.parse(iu(t,"utf8"));return n.schema!=="toolnet.memory.checkpoint.v1"||n.project.id!==e.id?null:n}catch{return null}}function cu(e){return["rule","architecture","decision","fix"].includes(e)}function uu(e,t){return t.length===0?[]:rt(e,t).candidates.filter(r=>cu(r.kind)&&r.knowledgeClass!=="transient"&&r.importanceScore>=.65).map(r=>({fingerprint:r.fingerprint,kind:r.kind,content:r.content,knowledgeClass:r.knowledgeClass,importanceScore:r.importanceScore,confidence:r.confidence,createdAt:r.createdAt,agent:e.agent,nativeSessionId:e.nativeSessionId}))}function lu(e,t){let n=new Map;for(let r of[...e,...t]){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 du(e){return{request:e.currentRequest,activity:e.currentActivity,goal:e.goal,phase:e.currentPhase?{title:e.currentPhase.title,status:e.currentPhase.status}:void 0,task:e.currentTask?{title:e.currentTask.title,status:e.currentTask.status}:void 0,phases:e.phases.map(t=>({title:t.title,status:t.status})),tasks:e.tasks.map(t=>({title:t.title,status:t.status})),activeFiles:e.activeFiles??[],modifiedFiles:e.modifiedFiles??[],createdFiles:e.createdFiles??[],deletedFiles:e.deletedFiles??[],checks:e.checks??[],blockers:e.blockers,decisions:e.decisions,nextActions:e.nextActions}}function Jr(e,t,n,r){let s=au(e),o=lu(s?.durableFacts??[],uu(t,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),f=r.tasks.filter(y=>y.status!=="completed"&&y.status!=="cancelled").map(y=>y.title),l={work:du(r),durableFacts:o.map(y=>y.fingerprint).sort()},p=v(JSON.stringify(l)).slice(0,32),d={schema:"toolnet.memory.checkpoint.v1",version:1,project:{id:e.id,name:e.name},source:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,sequence:i},capturedAt:new Date().toISOString(),request:r.currentRequest,activity:r.currentActivity,goal:r.goal,current:{phase:r.currentPhase,task:r.currentTask},completed:{phases:a,tasks:c},remaining:{phases:u,tasks: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:o,stateDigest:p},g=Vr(e);ou(g,{recursive:!0,mode:448});let k=qt(g,`${p}.json`);return Br(k)||P(k,d),P(Hr(e),d),d}import{existsSync as fu}from"node:fs";import{dirname as pu,join as mu,parse as gu,resolve as yu}from"node:path";function Gr(e){for(let t of e){let n=yu(t),r=gu(n).root;for(;;){if(fu(mu(n,".toolnet","project.json")))return new $e().detect(n);if(n===r)break;let s=pu(n);if(s===n)break;n=s}}return null}import{homedir as Ys}from"node:os";import{join as ed,resolve as td}from"node:path";import{join as hu}from"node:path";function Ur(e,t){let n=e.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`${t}--${s}`;let o=r.slice(0,100);return o===n&&n.length<=100?o:`${o.slice(0,85)}--${s}`}function Yr(e,t,n){let r=t.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=Ur(r.toLowerCase(),"agent"),i=Ur(s,"session");return{projectId:e.id,projectName:e.name,projectRoot:e.rootPath,agent:r,nativeSessionId:s,sessionKey:`${r}:${s}`,remotePrefix:["projects",e.id,"runtime","sources",o,i].join("/"),localDirectory:hu(e.rootPath,".toolnet","runtime","sources",o,i)}}function Qr(e){return String(e).padStart(12,"0")}var st=class{constructor(t,n=100,r=512*1024){this.storage=t;this.maxEventsPerChunk=n;this.maxChunkBytes=r;if(n<1)throw new Error("maxEventsPerChunk must be positive");if(r<1024)throw new Error("maxChunkBytes is too small")}storage;maxEventsPerChunk;maxChunkBytes;async getJson(t){let n=await this.storage.getText(t);return n?JSON.parse(n):null}async putJson(t,n){await this.storage.put(t,JSON.stringify(n,null,2)+`
122
+ `).filter(d=>d.trim())).map(d=>typeof d=="string"?d:JSON.stringify(d)).filter(d=>d.trim()),s=au(r,t),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),f=s.filter(d=>d.category==="next_action").map(d=>d.text),l=s.filter(d=>d.category==="deploy").map(d=>d.text);return{summary:cu(r),decisions:o,projectRules:i,filesChanged:a,bugsFixed:c,commands:l,blockers:u,nextActions:f,durableFacts:s}}function U(e){let t=new Set,n=[];for(let r of e){let s=r?.replace(/\s+/g," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();t.has(o)||(t.add(o),n.push(s))}return n}function uu(e){let t=new Map;for(let n of e){if(!n||!n.id||!Number.isFinite(n.sequence))continue;let r=n.sourceEventId?`${n.agent}:${n.sourceEventId}`:n.id,s=t.get(r);(!s||n.sequence>s.sequence)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.sequence-r.sequence||n.timestamp.localeCompare(r.timestamp))}function lu(e){let t=e.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_./:-]+/gu)??[],n=new Set;for(let r of t)if(!(r.length<2||/^\d+$/u.test(r))&&(n.add(r),n.size>=40))break;return[...n]}function du(e){let t=qt(e);return{...e,knowledgeClass:t.knowledgeClass,importanceScore:t.score,retrievalTerms:lu(e.content),tags:U([...e.tags,"level:fact",`class:${t.knowledgeClass}`,`kind:${e.kind}`])}}function fu(e){return e.map(t=>{try{return JSON.stringify({type:t.type,role:t.role,data:t.data,provenance:{sourcePath:t.provenance.sourcePath,files:t.provenance.files}})}catch{return""}}).filter(Boolean)}function pu(e,t,n){let r=it(fu(t),e.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=U([...s,...r.nextActions]),c=U([...r.nextActions,...s]);return{summary:r.summary,state:{task:c[0]??a[0],decisions:U(r.decisions),files:U([...r.filesChanged,...o]),todos:a,completed:U(r.bugsFixed),blockers:U(r.blockers),nextActions:c,architecture:U(i)}}}function at(e,t){let n=uu(t),r=Wr(e,n).map(du),s=r.filter(f=>qt(f).persist).sort((f,l)=>l.importanceScore-f.importanceScore),{summary:o,state:i}=pu(e,n,s),a=s.map(f=>({fingerprint:f.fingerprint,kind:f.kind,knowledgeClass:f.knowledgeClass,importanceScore:f.importanceScore,content:f.content,terms:f.retrievalTerms})),c=qr(n,s),u=f=>r.filter(l=>l.knowledgeClass===f).length;return{version:2,normalizedEvents:n,summary:o,state:i,candidates:s,retrievalIndex:a,hierarchy:c,stats:{inputEvents:t.length,normalizedEvents:n.length,extractedCandidates:r.length,persistedCandidates:s.length,permanent:u("permanent"),task:u("task"),session:u("session"),transient:u("transient")}}}function Qr(e){return Ht(e.rootPath,".toolnet","memory","checkpoints")}function Xr(e){return Ht(Qr(e),"latest.json")}function yu(e){let t=Xr(e);if(!Yr(t))return null;try{let n=JSON.parse(gu(t,"utf8"));return n.schema!=="toolnet.memory.checkpoint.v1"||n.project.id!==e.id?null:n}catch{return null}}function hu(e){return["rule","architecture","decision","fix"].includes(e)}function ku(e,t){return t.length===0?[]:at(e,t).candidates.filter(r=>hu(r.kind)&&r.knowledgeClass!=="transient"&&r.importanceScore>=.65).map(r=>({fingerprint:r.fingerprint,kind:r.kind,content:r.content,knowledgeClass:r.knowledgeClass,importanceScore:r.importanceScore,confidence:r.confidence,createdAt:r.createdAt,agent:e.agent,nativeSessionId:e.nativeSessionId}))}function Su(e,t){let n=new Map;for(let r of[...e,...t]){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 vu(e){return{request:e.currentRequest,activity:e.currentActivity,goal:e.goal,phase:e.currentPhase?{title:e.currentPhase.title,status:e.currentPhase.status}:void 0,task:e.currentTask?{title:e.currentTask.title,status:e.currentTask.status}:void 0,phases:e.phases.map(t=>({title:t.title,status:t.status})),tasks:e.tasks.map(t=>({title:t.title,status:t.status})),activeFiles:e.activeFiles??[],modifiedFiles:e.modifiedFiles??[],createdFiles:e.createdFiles??[],deletedFiles:e.deletedFiles??[],checks:e.checks??[],blockers:e.blockers,decisions:e.decisions,nextActions:e.nextActions}}function Zr(e,t,n,r){let s=yu(e),o=Su(s?.durableFacts??[],ku(t,n)),i=n.at(-1)?.sequence??s?.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:vu(r),durableFacts:o.map(g=>g.fingerprint).sort()},p=w(JSON.stringify(l)).slice(0,32),d={schema:"toolnet.memory.checkpoint.v1",version:1,project:{id:e.id,name:e.name},source:{agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,sequence:i},capturedAt:new Date().toISOString(),request:r.currentRequest,activity:r.currentActivity,goal:r.goal,current:{phase:r.currentPhase,task:r.currentTask},completed:{phases:a,tasks:c},remaining:{phases:u,tasks: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:o,stateDigest:p},m=Qr(e);mu(m,{recursive:!0,mode:448});let k=Ht(m,`${p}.json`);return Yr(k)||E(k,d),E(Xr(e),d),d}import{existsSync as wu}from"node:fs";import{dirname as bu,join as xu,parse as ju,resolve as Mu}from"node:path";function es(e){for(let t of e){let n=Mu(t),r=ju(n).root;for(;;){if(wu(xu(n,".toolnet","project.json")))return new De().detect(n);if(n===r)break;let s=bu(n);if(s===n)break;n=s}}return null}import{homedir as no}from"node:os";import{join as ud,resolve as ld}from"node:path";import{join as Au}from"node:path";function ts(e,t){let n=e.trim(),r=n.replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,""),s=w(n).slice(0,12);if(!r||r==="."||r==="..")return`${t}--${s}`;let o=r.slice(0,100);return o===n&&n.length<=100?o:`${o.slice(0,85)}--${s}`}function ns(e,t,n){let r=t.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=ts(r.toLowerCase(),"agent"),i=ts(s,"session");return{projectId:e.id,projectName:e.name,projectRoot:e.rootPath,agent:r,nativeSessionId:s,sessionKey:`${r}:${s}`,remotePrefix:["projects",e.id,"runtime","sources",o,i].join("/"),localDirectory:Au(e.rootPath,".toolnet","runtime","sources",o,i)}}function rs(e){return String(e).padStart(12,"0")}var ct=class{constructor(t,n=100,r=512*1024){this.storage=t;this.maxEventsPerChunk=n;this.maxChunkBytes=r;if(n<1)throw new Error("maxEventsPerChunk must be positive");if(r<1024)throw new Error("maxChunkBytes is too small")}storage;maxEventsPerChunk;maxChunkBytes;async getJson(t){let n=await this.storage.getText(t);return n?JSON.parse(n):null}async putJson(t,n){await this.storage.put(t,JSON.stringify(n,null,2)+`
123
123
  `,"application/json")}async scan(t){let n=`${t.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(t){let n=[],r=[],s=0;for(let o of t){let i=Buffer.byteLength(JSON.stringify(o)+`
124
- `,"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(t){return this.getJson(`${t.remotePrefix}/session.json`)}async loadCursor(t){return this.getJson(`${t.remotePrefix}/cursor.json`)}async recover(t){let n=await this.scan(t);return{maxSequence:n.maxSequence,chunkCount:n.chunks.length}}async append(t,n,r,s={}){let o=await this.loadManifest(t),i=await this.scan(t),a=n.filter(y=>y.sequence>i.maxSequence),c=0;for(let y of this.split(a)){let h=y[0],S=y[y.length-1],T=y.map(O=>JSON.stringify(O)).join(`
124
+ `,"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(t){return this.getJson(`${t.remotePrefix}/session.json`)}async loadCursor(t){return this.getJson(`${t.remotePrefix}/cursor.json`)}async recover(t){let n=await this.scan(t);return{maxSequence:n.maxSequence,chunkCount:n.chunks.length}}async append(t,n,r,s={}){let o=await this.loadManifest(t),i=await this.scan(t),a=n.filter(g=>g.sequence>i.maxSequence),c=0;for(let g of this.split(a)){let h=g[0],v=g[g.length-1],x=g.map(R=>JSON.stringify(R)).join(`
125
125
  `)+`
126
- `,E=v(T).slice(0,16),C=[t.remotePrefix,"events",`${Qr(h.sequence)}-${Qr(S.sequence)}-${E}.jsonl`].join("/");await this.storage.exists(C)||await this.storage.put(C,T,"application/x-ndjson"),c+=y.length}let u=await this.scan(t),f=n[n.length-1],l=o?.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],g={version:1,projectId:t.projectId,projectName:t.projectName,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,status:l,createdAt:o?.createdAt??d?.timestamp??p,updatedAt:f?.timestamp??p,firstEventAt:o?.firstEventAt??d?.timestamp,lastEventAt:f?.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 k={version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,lastLocalSequence:n.length>0?n[n.length-1].sequence:u.maxSequence,lastRemoteSequence:u.maxSequence,sourceCursors:r,updatedAt:p};return await this.putJson(`${t.remotePrefix}/cursor.json`,k),await this.putJson(`${t.remotePrefix}/session.json`,g),{uploadedEvents:c,lastRemoteSequence:u.maxSequence,eventCount:g.eventCount,chunkCount:g.chunkCount,status:l}}};import{closeSync as xe,existsSync as ut,fsyncSync as Qt,mkdirSync as Nu,openSync as je,readFileSync as fs,readSync as _u,rmSync as us,statSync as Ut,truncateSync as $u,writeSync as Fu}from"node:fs";import{join as Yt}from"node:path";var ku=new Set(["thinking","reasoning","reasoningcontent","chainofthought","cot","analysistext","internalreasoning","modelthinking"]),Su=new Set(["reasoning","thinking","chain_of_thought","chain-of-thought","internal_reasoning","internal-reasoning"]);function vu(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function wu(e){for(let t of["type","kind"]){let n=e[t];if(typeof n=="string"){let r=n.toLowerCase();if(Su.has(r))return n}}return null}function Bt(e,t=0){if(t>12)return"[ToolNet nested value omitted]";if(Array.isArray(e))return e.map(o=>Bt(o,t+1));if(!e||typeof e!="object")return e;let n=e,r=wu(n);if(r)return{type:r,omitted:"[private reasoning omitted]"};let s={};for(let[o,i]of Object.entries(n))ku.has(vu(o))||(s[o]=Bt(i,t+1));return s}function bu(e){if(!e)return new Date().toISOString();let t=new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function ee(e){return e?.trim()||void 0}function Xr(e,t={}){let n={...e.provenance??{}},r=ee(e.source)??ee(t.source)??ee(n.source);return{...e,timestamp:bu(e.timestamp),source:r,turnId:ee(e.turnId)??ee(t.turnId),cwd:ee(e.cwd)??ee(t.cwd),data:Bt(e.data??{}),provenance:n}}import{randomUUID as Vt}from"node:crypto";import{closeSync as ie,existsSync as ae,fsyncSync as we,mkdirSync as Ht,openSync as be,readFileSync as Jt,readdirSync as xu,renameSync as ju,rmSync as ot,statSync as Mu,writeSync as it}from"node:fs";import{join as G}from"node:path";var Au=12e4,Iu=80,Cu="reconcile-required";function Pu(e){e<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function ce(e){return G(e,".toolnet","journal")}function ts(e){return G(ce(e),"events.jsonl")}function at(e){return G(ce(e),Cu)}function Tu(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code!=="ESRCH"}}function ns(e){if(!ae(e))return null;try{let t=JSON.parse(Jt(e,"utf8"));return t.version!==1||typeof t.token!="string"||typeof t.pid!="number"||typeof t.acquiredAt!="string"?null:{version:1,token:t.token,pid:t.pid,acquiredAt:t.acquiredAt}}catch{return null}}function Eu(e){if(!ae(e))return!1;let t=0;try{t=Date.now()-Mu(e).mtimeMs}catch{return!1}if(t<=Au)return!1;let n=ns(e);return n?!Tu(n.pid):!0}function Ou(e){if(!Eu(e))return!1;try{return ot(e,{force:!0}),!0}catch{return!1}}function rs(e){for(let t=0;t<Iu;t+=1){let n=Vt();try{let r=be(e,"wx",384),s={version:1,token:n,pid:process.pid,acquiredAt:new Date().toISOString()};try{return it(r,`${JSON.stringify(s)}
127
- `,null,"utf8"),we(r),{fd:r,token:n}}catch(o){throw ie(r),ot(e,{force:!0}),o}}catch(r){if(r?.code!=="EEXIST")throw r;if(Ou(e))continue;Pu(25)}}throw new Error(`Shared project journal is locked: ${e}`)}function ss(e,t){ie(t.fd),ns(e)?.token===t.token&&ot(e,{force:!0})}function Zr(e){if(!ae(e))return[];let t="";try{t=Jt(e,"utf8")}catch{return[]}let n=[];for(let r of t.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 os(e){if(!ae(e))return[];let t=[];for(let n of xu(e,{withFileTypes:!0})){let r=G(e,n.name);if(n.isDirectory()){t.push(...os(r));continue}n.isFile()&&n.name==="events.jsonl"&&t.push(r)}return t.sort()}function ct(e){let t=null;try{t=be(e,"r"),we(t)}catch{}finally{if(t===null)return;ie(t)}}function es(e){let t=at(e);if(!ae(t))return null;try{return Jt(t,"utf8").trim()||null}catch{return null}}function Gt(e){let t=ce(e);Ht(t,{recursive:!0,mode:448});let n=at(e),r=[Vt(),new Date().toISOString()].join("|"),s=be(n,"w",384);try{it(s,`${r}
128
- `,null,"utf8"),we(s)}finally{ie(s)}ct(t)}function Ru(e,t,n){let r=G(e,`.events.jsonl.tmp-${process.pid}-${Vt()}`),s=be(r,"w",384);try{let o=n.length===0?"":`${n.map(i=>JSON.stringify(i)).join(`
126
+ `,O=w(x).slice(0,16),C=[t.remotePrefix,"events",`${rs(h.sequence)}-${rs(v.sequence)}-${O}.jsonl`].join("/");await this.storage.exists(C)||await this.storage.put(C,x,"application/x-ndjson"),c+=g.length}let u=await this.scan(t),f=n[n.length-1],l=o?.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:t.projectId,projectName:t.projectName,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,status:l,createdAt:o?.createdAt??d?.timestamp??p,updatedAt:f?.timestamp??p,firstEventAt:o?.firstEventAt??d?.timestamp,lastEventAt:f?.timestamp??o?.lastEventAt,eventCount:u.maxSequence,chunkCount:u.chunks.length,metadata:{...o?.metadata,...s.metadata}};(s.title??o?.title)&&(m.title=s.title??o?.title);let k={version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,lastLocalSequence:n.length>0?n[n.length-1].sequence:u.maxSequence,lastRemoteSequence:u.maxSequence,sourceCursors:r,updatedAt:p};return await this.putJson(`${t.remotePrefix}/cursor.json`,k),await this.putJson(`${t.remotePrefix}/session.json`,m),{uploadedEvents:c,lastRemoteSequence:u.maxSequence,eventCount:m.eventCount,chunkCount:m.chunkCount,status:l}}};import{closeSync as Me,existsSync as pt,fsyncSync as en,mkdirSync as qu,openSync as Ae,readFileSync as ks,readSync as Bu,rmSync as gs,statSync as Xt,truncateSync as Vu,writeSync as Hu}from"node:fs";import{join as Zt}from"node:path";var Iu=new Set(["thinking","reasoning","reasoningcontent","chainofthought","cot","analysistext","internalreasoning","modelthinking"]),Pu=new Set(["reasoning","thinking","chain_of_thought","chain-of-thought","internal_reasoning","internal-reasoning"]);function Cu(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Tu(e){for(let t of["type","kind"]){let n=e[t];if(typeof n=="string"){let r=n.toLowerCase();if(Pu.has(r))return n}}return null}function Jt(e,t=0){if(t>12)return"[ToolNet nested value omitted]";if(Array.isArray(e))return e.map(o=>Jt(o,t+1));if(!e||typeof e!="object")return e;let n=e,r=Tu(n);if(r)return{type:r,omitted:"[private reasoning omitted]"};let s={};for(let[o,i]of Object.entries(n))Iu.has(Cu(o))||(s[o]=Jt(i,t+1));return s}function Eu(e){if(!e)return new Date().toISOString();let t=new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function te(e){return e?.trim()||void 0}function ss(e,t={}){let n={...e.provenance??{}},r=te(e.source)??te(t.source)??te(n.source);return{...e,timestamp:Eu(e.timestamp),source:r,turnId:te(e.turnId)??te(t.turnId),cwd:te(e.cwd)??te(t.cwd),data:Jt(e.data??{}),provenance:n}}import{randomUUID as Gt}from"node:crypto";import{closeSync as ce,existsSync as ue,fsyncSync as xe,mkdirSync as Ut,openSync as je,readFileSync as Yt,readdirSync as Ou,renameSync as Ru,rmSync as ut,statSync as Nu,writeSync as lt}from"node:fs";import{join as Y}from"node:path";var _u=12e4,$u=80,Fu="reconcile-required";function Ku(e){e<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function le(e){return Y(e,".toolnet","journal")}function as(e){return Y(le(e),"events.jsonl")}function dt(e){return Y(le(e),Fu)}function Lu(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code!=="ESRCH"}}function cs(e){if(!ue(e))return null;try{let t=JSON.parse(Yt(e,"utf8"));return t.version!==1||typeof t.token!="string"||typeof t.pid!="number"||typeof t.acquiredAt!="string"?null:{version:1,token:t.token,pid:t.pid,acquiredAt:t.acquiredAt}}catch{return null}}function Wu(e){if(!ue(e))return!1;let t=0;try{t=Date.now()-Nu(e).mtimeMs}catch{return!1}if(t<=_u)return!1;let n=cs(e);return n?!Lu(n.pid):!0}function Du(e){if(!Wu(e))return!1;try{return ut(e,{force:!0}),!0}catch{return!1}}function us(e){for(let t=0;t<$u;t+=1){let n=Gt();try{let r=je(e,"wx",384),s={version:1,token:n,pid:process.pid,acquiredAt:new Date().toISOString()};try{return lt(r,`${JSON.stringify(s)}
127
+ `,null,"utf8"),xe(r),{fd:r,token:n}}catch(o){throw ce(r),ut(e,{force:!0}),o}}catch(r){if(r?.code!=="EEXIST")throw r;if(Du(e))continue;Ku(25)}}throw new Error(`Shared project journal is locked: ${e}`)}function ls(e,t){ce(t.fd),cs(e)?.token===t.token&&ut(e,{force:!0})}function os(e){if(!ue(e))return[];let t="";try{t=Yt(e,"utf8")}catch{return[]}let n=[];for(let r of t.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 ds(e){if(!ue(e))return[];let t=[];for(let n of Ou(e,{withFileTypes:!0})){let r=Y(e,n.name);if(n.isDirectory()){t.push(...ds(r));continue}n.isFile()&&n.name==="events.jsonl"&&t.push(r)}return t.sort()}function ft(e){let t=null;try{t=je(e,"r"),xe(t)}catch{}finally{if(t===null)return;ce(t)}}function is(e){let t=dt(e);if(!ue(t))return null;try{return Yt(t,"utf8").trim()||null}catch{return null}}function Qt(e){let t=le(e);Ut(t,{recursive:!0,mode:448});let n=dt(e),r=[Gt(),new Date().toISOString()].join("|"),s=je(n,"w",384);try{lt(s,`${r}
128
+ `,null,"utf8"),xe(s)}finally{ce(s)}ft(t)}function zu(e,t,n){let r=Y(e,`.events.jsonl.tmp-${process.pid}-${Gt()}`),s=je(r,"w",384);try{let o=n.length===0?"":`${n.map(i=>JSON.stringify(i)).join(`
129
129
  `)}
130
- `;o&&it(s,o,null,"utf8"),we(s)}finally{ie(s)}ju(r,t),ct(e)}function is(e){let t=ce(e),n=ts(e),r=G(e,".toolnet","runtime","sources"),s=es(e),o=os(r),i=[],a=new Set;for(let l of Zr(n))a.has(l.id)||(a.add(l.id),i.push(l));let c=i.length,u=[];for(let l of o)for(let p of Zr(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),Ru(t,n,i);let f=es(e);return s&&f===s&&(ot(at(e),{force:!0}),ct(t)),{filesScanned:o.length,existingEvents:c,recoveredEvents:u.length,totalEvents:i.length}}function as(e){let t=ce(e);Ht(t,{recursive:!0,mode:448});let n=G(t,"journal.lock"),r=rs(n);try{return is(e)}finally{ss(n,r)}}function cs(e,t){if(t.length===0)return;let n=ce(e);Ht(n,{recursive:!0,mode:448});let r=ts(e),s=G(n,"journal.lock"),o=rs(s);try{if(ae(at(e))){is(e);return}let i=`${t.map(c=>JSON.stringify(c)).join(`
130
+ `;o&&lt(s,o,null,"utf8"),xe(s)}finally{ce(s)}Ru(r,t),ft(e)}function fs(e){let t=le(e),n=as(e),r=Y(e,".toolnet","runtime","sources"),s=is(e),o=ds(r),i=[],a=new Set;for(let l of os(n))a.has(l.id)||(a.add(l.id),i.push(l));let c=i.length,u=[];for(let l of o)for(let p of os(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),zu(t,n,i);let f=is(e);return s&&f===s&&(ut(dt(e),{force:!0}),ft(t)),{filesScanned:o.length,existingEvents:c,recoveredEvents:u.length,totalEvents:i.length}}function ps(e){let t=le(e);Ut(t,{recursive:!0,mode:448});let n=Y(t,"journal.lock"),r=us(n);try{return fs(e)}finally{ls(n,r)}}function ms(e,t){if(t.length===0)return;let n=le(e);Ut(n,{recursive:!0,mode:448});let r=as(e),s=Y(n,"journal.lock"),o=us(s);try{if(ue(dt(e))){fs(e);return}let i=`${t.map(c=>JSON.stringify(c)).join(`
131
131
  `)}
132
- `,a=be(r,"a",384);try{it(a,i,null,"utf8"),we(a)}finally{ie(a)}ct(n)}finally{ss(s,o)}}var Ku=12e4,Lu=80,ls=2e3;function Wu(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function ps(e,t){let n=Buffer.isBuffer(t)?t:Buffer.from(t,"utf8"),r=0;for(;r<n.length;){let s=Fu(e,n,r,n.length-r);if(s<=0)throw new Error("Unable to write session WAL");r+=s}}function Xt(e){let t=e.trim();if(!t)return null;try{let n=JSON.parse(t);return n.version!==1||typeof n.id!="string"||!n.id||typeof n.sequence!="number"||!Number.isFinite(n.sequence)||typeof n.projectId!="string"||!n.projectId||typeof n.timestamp!="string"?null:n}catch{return null}}function Du(e){if(!ut(e))return[];let t="";try{t=fs(e,"utf8")}catch{return[]}let n=[];for(let r of t.split(/\r?\n/)){let s=Xt(r);s&&n.push(s)}return n}function ds(e){return e.type==="session_end"||e.type==="session_idle"?"idle":e.type==="error"?"error":"active"}function zu(e){if(!ut(e))return!1;let t;try{t=fs(e)}catch{return!1}if(t.length===0||t[t.length-1]===10)return!1;let n=t.lastIndexOf(10),r=n>=0?n+1:0,s=t.subarray(r).toString("utf8").trim();if(Xt(s)){let i=je(e,"a");try{ps(i,`
133
- `),Qt(i)}finally{xe(i)}return!0}$u(e,r);let o=je(e,"a");try{Qt(o)}finally{xe(o)}return!0}function qu(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}var lt=class{constructor(t,n={}){this.identity=t;this.eventContext=n;Nu(t.localDirectory,{recursive:!0}),this.eventsFile=Yt(t.localDirectory,"events.jsonl"),this.stateFile=Yt(t.localDirectory,"state.json"),this.lockFile=Yt(t.localDirectory,"journal.lock")}identity;eventContext;eventsFile;stateFile;lockFile;initialState(){let t=new Date().toISOString();return{version:1,projectId:this.identity.projectId,agent:this.identity.agent,nativeSessionId:this.identity.nativeSessionId,status:"idle",createdAt:t,updatedAt:t,lastSequence:0,lastRemoteSequence:0,remoteByteOffset:0,sourceCursors:{},recentEventIds:[]}}loadStateUnsafe(){return xn(this.stateFile)??this.initialState()}recoverStateUnsafe(){zu(this.eventsFile);let t=this.loadStateUnsafe(),n=Du(this.eventsFile);if(n.length===0)return t;let r=n[0];for(let l of n)l.sequence<=r.sequence||(r=l);let s=n.slice(-ls).map(l=>l.id),o=ut(this.eventsFile)?Ut(this.eventsFile).size:0,i=Math.max(t.lastSequence,r.sequence),a=Math.min(t.remoteByteOffset,o),c=r.sequence>t.lastSequence;if(!(c||a!==t.remoteByteOffset||!qu(t.recentEventIds,s)||t.lastLocalEventAt!==r.timestamp))return t;let f={...t,status:ds(r),updatedAt:r.timestamp,lastLocalEventAt:r.timestamp,lastSequence:i,remoteByteOffset:a,recentEventIds:s};if(this.saveStateUnsafe(f),!c)return f;try{Gt(this.identity.projectRoot)}catch{return f}try{as(this.identity.projectRoot)}catch{}return f}loadState(){return this.withLock(()=>this.recoverStateUnsafe())}saveStateUnsafe(t){P(this.stateFile,t)}acquireLock(){for(let t=0;t<Lu;t+=1)try{return je(this.lockFile,"wx",384)}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Ut(this.lockFile).mtimeMs>Ku){us(this.lockFile,{force:!0});continue}}catch{}Wu(25)}throw new Error(`Session journal is locked: ${this.lockFile}`)}withLock(t){let n=this.acquireLock();try{return t()}finally{xe(n),us(this.lockFile,{force:!0})}}append(t){return t.length===0?[]:this.withLock(()=>{let n=this.recoverStateUnsafe(),r=new Set(n.recentEventIds),s=n.lastSequence,o=[];for(let l of t){let p=Xr(l,this.eventContext),d=p.timestamp??new Date().toISOString(),g=p.data??{},k=p.provenance?.rawDigest??v(bn(g)),y=p.sourceEventId?[this.identity.projectId,this.identity.agent,this.identity.nativeSessionId,p.sourceEventId].join("|"):[this.identity.projectId,this.identity.agent,this.identity.nativeSessionId,s+1,p.type,d,k].join("|"),h=v(y).slice(0,32);if(r.has(h))continue;s+=1;let S={version:1,id:h,sequence:s,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:k}};p.role!==void 0&&(S.role=p.role),p.turnId!==void 0&&(S.turnId=p.turnId),p.cwd!==void 0&&(S.cwd=p.cwd),p.sourceEventId!==void 0&&(S.sourceEventId=p.sourceEventId),p.sourceSequence!==void 0&&(S.sourceSequence=p.sourceSequence),o.push(S),r.add(h)}if(o.length===0)return[];let i=o.map(l=>JSON.stringify(l)).join(`
132
+ `,a=je(r,"a",384);try{lt(a,i,null,"utf8"),xe(a)}finally{ce(a)}ft(n)}finally{ls(s,o)}}var Ju=12e4,Gu=80,ys=2e3;function Uu(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Ss(e,t){let n=Buffer.isBuffer(t)?t:Buffer.from(t,"utf8"),r=0;for(;r<n.length;){let s=Hu(e,n,r,n.length-r);if(s<=0)throw new Error("Unable to write session WAL");r+=s}}function tn(e){let t=e.trim();if(!t)return null;try{let n=JSON.parse(t);return n.version!==1||typeof n.id!="string"||!n.id||typeof n.sequence!="number"||!Number.isFinite(n.sequence)||typeof n.projectId!="string"||!n.projectId||typeof n.timestamp!="string"?null:n}catch{return null}}function Yu(e){if(!pt(e))return[];let t="";try{t=ks(e,"utf8")}catch{return[]}let n=[];for(let r of t.split(/\r?\n/)){let s=tn(r);s&&n.push(s)}return n}function hs(e){return e.type==="session_end"||e.type==="session_idle"?"idle":e.type==="error"?"error":"active"}function Qu(e){if(!pt(e))return!1;let t;try{t=ks(e)}catch{return!1}if(t.length===0||t[t.length-1]===10)return!1;let n=t.lastIndexOf(10),r=n>=0?n+1:0,s=t.subarray(r).toString("utf8").trim();if(tn(s)){let i=Ae(e,"a");try{Ss(i,`
133
+ `),en(i)}finally{Me(i)}return!0}Vu(e,r);let o=Ae(e,"a");try{en(o)}finally{Me(o)}return!0}function Xu(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}var mt=class{constructor(t,n={}){this.identity=t;this.eventContext=n;qu(t.localDirectory,{recursive:!0}),this.eventsFile=Zt(t.localDirectory,"events.jsonl"),this.stateFile=Zt(t.localDirectory,"state.json"),this.lockFile=Zt(t.localDirectory,"journal.lock")}identity;eventContext;eventsFile;stateFile;lockFile;initialState(){let t=new Date().toISOString();return{version:1,projectId:this.identity.projectId,agent:this.identity.agent,nativeSessionId:this.identity.nativeSessionId,status:"idle",createdAt:t,updatedAt:t,lastSequence:0,lastRemoteSequence:0,remoteByteOffset:0,sourceCursors:{},recentEventIds:[]}}loadStateUnsafe(){return Cn(this.stateFile)??this.initialState()}recoverStateUnsafe(){Qu(this.eventsFile);let t=this.loadStateUnsafe(),n=Yu(this.eventsFile);if(n.length===0)return t;let r=n[0];for(let l of n)l.sequence<=r.sequence||(r=l);let s=n.slice(-ys).map(l=>l.id),o=pt(this.eventsFile)?Xt(this.eventsFile).size:0,i=Math.max(t.lastSequence,r.sequence),a=Math.min(t.remoteByteOffset,o),c=r.sequence>t.lastSequence;if(!(c||a!==t.remoteByteOffset||!Xu(t.recentEventIds,s)||t.lastLocalEventAt!==r.timestamp))return t;let f={...t,status:hs(r),updatedAt:r.timestamp,lastLocalEventAt:r.timestamp,lastSequence:i,remoteByteOffset:a,recentEventIds:s};if(this.saveStateUnsafe(f),!c)return f;try{Qt(this.identity.projectRoot)}catch{return f}try{ps(this.identity.projectRoot)}catch{}return f}loadState(){return this.withLock(()=>this.recoverStateUnsafe())}saveStateUnsafe(t){E(this.stateFile,t)}acquireLock(){for(let t=0;t<Gu;t+=1)try{return Ae(this.lockFile,"wx",384)}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Xt(this.lockFile).mtimeMs>Ju){gs(this.lockFile,{force:!0});continue}}catch{}Uu(25)}throw new Error(`Session journal is locked: ${this.lockFile}`)}withLock(t){let n=this.acquireLock();try{return t()}finally{Me(n),gs(this.lockFile,{force:!0})}}append(t){return t.length===0?[]:this.withLock(()=>{let n=this.recoverStateUnsafe(),r=new Set(n.recentEventIds),s=n.lastSequence,o=[];for(let l of t){let p=ss(l,this.eventContext),d=p.timestamp??new Date().toISOString(),m=p.data??{},k=p.provenance?.rawDigest??w(Pn(m)),g=ye(m),h=p.sourceEventId?[this.identity.projectId,this.identity.agent,this.identity.nativeSessionId,p.sourceEventId].join("|"):[this.identity.projectId,this.identity.agent,this.identity.nativeSessionId,s+1,p.type,d,k].join("|"),v=w(h).slice(0,32);if(r.has(v))continue;s+=1;let x={version:1,id:v,sequence:s,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:k}};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),o.push(x),r.add(v)}if(o.length===0)return[];let i=o.map(l=>JSON.stringify(l)).join(`
134
134
  `)+`
135
- `,a=je(this.eventsFile,"a",384);try{ps(a,i),Qt(a)}finally{xe(a)}try{cs(this.identity.projectRoot,o)}catch{try{Gt(this.identity.projectRoot)}catch{}}let c=o[o.length-1],u=ds(c),f=Array.from(r).slice(-ls);return this.saveStateUnsafe({...n,status:u,updatedAt:c.timestamp,lastLocalEventAt:c.timestamp,lastSequence:c.sequence,recentEventIds:f}),o})}readPending(){return this.withLock(()=>{let t=this.recoverStateUnsafe();if(!ut(this.eventsFile))return{events:[],startOffset:t.remoteByteOffset,endOffset:t.remoteByteOffset};let n=Ut(this.eventsFile).size,r=Math.min(t.remoteByteOffset,n);if(n<=r)return{events:[],startOffset:r,endOffset:n};let s=n-r,o=Buffer.alloc(s),i=je(this.eventsFile,"r");try{_u(i,o,0,s,r)}finally{xe(i)}let a=[];for(let c of o.toString("utf8").split(/\r?\n/)){let u=Xt(c);u&&a.push(u)}return{events:a,startOffset:r,endOffset:n}})}markRemote(t,n){this.withLock(()=>{let r=this.recoverStateUnsafe(),s=new Date().toISOString();this.saveStateUnsafe({...r,lastRemoteSequence:Math.max(r.lastRemoteSequence,t),remoteByteOffset:Math.max(r.remoteByteOffset,n),lastRemoteAt:s,updatedAt:s})})}setSourceCursor(t,n){this.withLock(()=>{let r=this.recoverStateUnsafe();this.saveStateUnsafe({...r,sourceCursors:{...r.sourceCursors,[t]:String(n)},updatedAt:new Date().toISOString()})})}};import{closeSync as _l,existsSync as $l,openSync as Fl,readSync as Kl,statSync as Ll}from"node:fs";import{createHash as Qu}from"node:crypto";import{existsSync as Xu,readdirSync as Zu,readFileSync as el}from"node:fs";import{basename as tl,join as Ts}from"node:path";import{randomUUID as ys}from"node:crypto";var M=class extends Error{constructor(n,r){super(n);this.statusCode=r}statusCode};function Me(e){let t=new Set,n=[];for(let r of e){let s=r.replace(/\s+/gu," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();t.has(o)||(t.add(o),n.push(s))}return n}function ne(e){let t=e.normalize("NFKD").replace(/[\u0300-\u036f]/gu,"").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"").slice(0,120);if(!t)throw new M("Invalid Wiki slug",400);return t}function ms(e){let t=[];for(let n of e.matchAll(/\[\[([^\[\]]+)\]\]/gu)){let r=n[1]?.trim();r&&t.push(ne(r))}return Me(t)}function Bu(e){return e.normalize("NFKC").toLowerCase().split(/[^\p{L}\p{N}_-]+/u).map(t=>t.trim()).filter(t=>t.length>=2)}function gs(e){return{id:`revision-${ys()}`,pageId:e.id,slug:e.slug,revision:e.revision,title:e.title,...e.summary?{summary:e.summary}:{},content:e.content,tags:[...e.tags],links:[...e.links],createdAt:e.updatedAt}}function te(e){return structuredClone(e)}var dt=class{constructor(t){this.store=t}store;state;queue=Promise.resolve();async initialize(){await this.ensureState()}async ensureState(){return this.state||(this.state=await this.store.load()),this.state}async mutate(t){let n,r=this.queue.then(async()=>{let s=await this.ensureState();n=t(s),s.updatedAt=new Date().toISOString(),await this.store.save(s)});return this.queue=r.then(()=>{},()=>{}),await r,n}async summary(){let t=await this.ensureState(),n=new Set(t.pages.flatMap(r=>r.links));return{schema:"toolnet.wiki-summary.v1",projectId:t.projectId,pages:t.pages.length,revisions:t.revisions.length,tags:Me(t.pages.flatMap(r=>r.tags)).sort((r,s)=>r.localeCompare(s)),links:t.pages.reduce((r,s)=>r+s.links.length,0),orphanPages:t.pages.filter(r=>r.links.length===0&&!n.has(r.slug)).length,automatedPages:t.pages.filter(r=>r.tags.some(s=>s.startsWith("toolnet-auto-"))).length,updatedAt:t.updatedAt}}async listPages(){let t=await this.ensureState();return te([...t.pages].sort((n,r)=>n.title.localeCompare(r.title)))}async getPage(t){let n=await this.ensureState(),r=ne(t),s=n.pages.find(o=>o.slug===r||o.id===t);if(!s)throw new M(`Wiki page not found: ${t}`,404);return te(s)}async createPage(t){return this.mutate(n=>{let r=t.title.trim(),s=t.content.trim();if(!r)throw new M("Wiki title is required",400);let o=ne(t.slug??r);if(n.pages.some(c=>c.slug===o))throw new M(`Wiki page already exists: ${o}`,409);let i=new Date().toISOString(),a={id:`wiki-${ys()}`,slug:o,title:r,...t.summary?.trim()?{summary:t.summary.trim()}:{},content:s,tags:Me(t.tags??[]),links:ms(s),revision:1,createdAt:i,updatedAt:i};return n.pages.push(a),n.revisions.push(gs(a)),te(a)})}async updatePage(t,n){return this.mutate(r=>{let s=ne(t),o=r.pages.find(i=>i.slug===s||i.id===t);if(!o)throw new M(`Wiki page not found: ${t}`,404);if(n.title!==void 0){let i=n.title.trim();if(!i)throw new M("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=ms(o.content)),n.tags!==void 0&&(o.tags=Me(n.tags)),o.revision+=1,o.updatedAt=new Date().toISOString(),r.revisions.push(gs(o)),te(o)})}async history(t){let n=await this.getPage(t),r=await this.ensureState();return te(r.revisions.filter(s=>s.pageId===n.id).sort((s,o)=>o.revision-s.revision))}async backlinks(t){let n=await this.getPage(t),r=await this.ensureState();return te(r.pages.filter(s=>s.links.includes(n.slug)).sort((s,o)=>s.title.localeCompare(o.title)))}async search(t,n=10){let r=await this.ensureState(),s=Me(Bu(t));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(),f=a.summary?.toLowerCase()??"",l=a.content.toLowerCase(),p=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),p.some(k=>k===g)?d+=5:p.some(k=>k.includes(g))&&(d+=3),f.includes(g)&&(d+=2),l.includes(g)&&(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,o)}};var hs="wiki/state.v1.json";function Vu(e){let t=new Date().toISOString();return{schema:"toolnet.wiki.v1",version:1,projectId:e.id,pages:[],revisions:[],createdAt:t,updatedAt:t}}function Hu(e,t){let n=JSON.parse(e);if(n.schema!=="toolnet.wiki.v1"||n.version!==1||n.projectId!==t.id||!Array.isArray(n.pages)||!Array.isArray(n.revisions))throw new Error("Invalid ToolNet Wiki state");return n}var ft=class{constructor(t,n){this.storage=t;this.project=n}storage;project;async load(){let t=await this.storage.getText(hs);if(!t){let n=Vu(this.project);return await this.save(n),n}return Hu(t,this.project)}async save(t){await this.storage.put(hs,JSON.stringify(t,null,2),"application/json")}};import{createHash as Ju,randomUUID as ks}from"node:crypto";var Ss="wiki/governance.v1.json",xs="toolnet.knowledge-governance.v1",vs=500,Ae={autoApproveThreshold:.86,criticalApproveThreshold:.94,staleAfterDays:90};function Gu(e,t=0,n=1){return Math.max(t,Math.min(n,e))}function Zt(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/gu," ").trim()}function ws(e){return Ju("sha256").update(e.normalize("NFKC").replace(/\s+/gu," ").trim()).digest("hex")}function Uu(e){let t=[e.title,e.summary??"",e.content.slice(0,2e3),...e.tags].join(" ").toLowerCase();return/\b(?:architecture|security|authentication|authorization|auth|database|production|deploy|deployment|payment|billing|permission|permissions|acl|credential|secret|migration)\b/u.test(t)}function Yu(e){let t=e.sourceType==="skill"?.96:e.sourceType==="memory"?.94:.88,n=e.tags.map(r=>r.toLowerCase());return(n.includes("permanent")||n.includes("task"))&&(t+=.03),e.content.length>=200&&(t+=.02),e.content.length<80&&(t-=.05),e.title.length<4&&(t-=.05),Gu(t)}function bs(e){let t=new Date().toISOString();return{schema:xs,version:1,projectId:e,policy:{...Ae},reviews:[],audit:[],createdAt:t,updatedAt:t}}function js(e){let t=e.autoApproveThreshold??Ae.autoApproveThreshold,n=e.criticalApproveThreshold??Ae.criticalApproveThreshold,r=e.staleAfterDays??Ae.staleAfterDays;if(!Number.isFinite(t)||t<.5||t>1)throw new M("Invalid autoApproveThreshold",400);if(!Number.isFinite(n)||n<.5||n>1)throw new M("Invalid criticalApproveThreshold",400);if(!Number.isInteger(r)||r<1||r>3650)throw new M("Invalid staleAfterDays",400);return{autoApproveThreshold:t,criticalApproveThreshold:n,staleAfterDays:r}}var pt=class{constructor(t,n){this.storage=t;this.project=n}storage;project;async load(){let t=await this.storage.getText(Ss);if(!t){let n=bs(this.project.id);return await this.save(n),n}try{let n=JSON.parse(t);if(n.schema!==xs||n.version!==1||n.projectId!==this.project.id||!Array.isArray(n.reviews)||!Array.isArray(n.audit))throw new Error("invalid");return{...n,policy:js(n.policy??Ae)}}catch{let n=bs(this.project.id);return await this.save(n),n}}async save(t){await this.storage.put(Ss,JSON.stringify(t,null,2),"application/json")}},mt=class{constructor(t){this.store=t}store;state;queue=Promise.resolve();async initialize(){await this.ensureState()}async ensureState(){return this.state||(this.state=await this.store.load()),this.state}audit(t,n,r,s={}){t.audit.push({id:ks(),action:n,principal:r,...s.reviewId?{reviewId:s.reviewId}:{},...s.sourceKey?{sourceKey:s.sourceKey}:{},timestamp:new Date().toISOString(),...s.metadata?{metadata:s.metadata}:{}}),t.audit.length>vs&&(t.audit=t.audit.slice(-vs))}async mutate(t){let n,r=this.queue.then(async()=>{let s=await this.ensureState();n=await t(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(t,n){return this.mutate(r=>(r.policy=js({...r.policy,...t}),this.audit(r,"policy:update",n,{metadata:{...r.policy}}),{...r.policy}))}async summary(){let t=await this.ensureState(),n=r=>t.reviews.filter(s=>s.status===r).length;return{schema:"toolnet.knowledge-governance-summary.v1",projectId:t.projectId,pending:n("pending"),approved:n("approved"),rejected:n("rejected"),superseded:n("superseded"),criticalPending:t.reviews.filter(r=>r.status==="pending"&&r.risk==="critical").length,conflictPending:t.reviews.filter(r=>r.status==="pending"&&r.risk==="conflict").length,auditEvents:t.audit.length,policy:{...t.policy},updatedAt:t.updatedAt}}async listReviews(t){let n=await this.ensureState();return structuredClone(n.reviews.filter(r=>!t||r.status===t).sort((r,s)=>s.updatedAt.localeCompare(r.updatedAt)))}async auditLog(t=100){let n=await this.ensureState(),r=Math.max(1,Math.min(500,Math.floor(t)));return structuredClone(n.audit.slice(-r).reverse())}async assess(t,n){let r=await this.ensureState(),s=Yu(t),o=Zt(t.title),i=n.filter(f=>f.slug!==t.slug&&Zt(f.title)===o&&ws(f.content)!==ws(t.content)).map(f=>f.slug),a=Uu(t),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(t,n){let r=await this.assess(t,n);return this.mutate(s=>{let o=s.reviews.find(c=>c.sourceKey===t.sourceKey&&c.digest===t.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:t.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:ks(),sourceKey:t.sourceKey,sourceType:t.sourceType,slug:t.slug,marker:t.marker,digest:t.digest,title:t.title,...t.summary?{summary:t.summary}:{},content:t.content,tags:[...new Set([...t.tags,t.marker])],confidence:r.confidence,risk:r.risk,reasons:[...r.reasons],conflicts:[...r.conflicts],status:"pending",createdAt:i,updatedAt:i};return 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(t,n){await this.mutate(r=>{let s=r.reviews.find(o=>o.sourceKey===t&&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:t}))})}async decide(t,n,r){return this.mutate(async s=>{let o=s.reviews.find(u=>u.id===t);if(!o)throw new M(`Governance review not found: ${t}`,404);if(o.status!=="pending")throw new M("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:t,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:t,sourceKey:o.sourceKey,metadata:{targetReviewId:n.targetReviewId}}),structuredClone(o);if(n.action==="merge"){if(!n.targetReviewId)throw new M("targetReviewId is required for merge",400);let u=s.reviews.find(f=>f.id===n.targetReviewId);if(!u)throw new M("Merge target review not found",404);return o.status="superseded",o.mergedInto=u.id,this.audit(s,"knowledge:merged",n.principal,{reviewId:t,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 M(`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:t,sourceKey:o.sourceKey}),structuredClone(o)})}async quality(t){let n=await this.ensureState(),r=await t.listPages(),s=Date.now(),o=n.policy.staleAfterDays*864e5,i=r.map(f=>{let l=s-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>o}}).filter(f=>f.stale).map(({stale:f,...l})=>l),a=new Map;for(let f of r){let l=Zt(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 Es="wiki/automation.v1.json",Os="toolnet.wiki-automation.v1",nn=8e3,Ms=new Set(["raw","rawtext","raw_text","rawtranscript","raw_transcript","transcript","messages","message","payload","prompt","response","assistantmessage","assistant_message","userprompt","user_prompt"]);function Ce(e){return Qu("sha256").update(JSON.stringify(e)).digest("hex")}function Ie(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function As(e){return Array.isArray(e)?e:[]}function Rs(e){return typeof e!="string"?void 0:e.replace(/\s+/gu," ").trim()||void 0}function en(e){return Array.isArray(e)?e.map(Rs).filter(t=>!!t):[]}function L(e,t){for(let n of t){let r=Rs(e[n]);if(r)return r}}function Pe(e){let t=new Set,n=[];for(let r of e){let s=r.replace(/\s+/gu," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();t.has(o)||(t.add(o),n.push(s))}return n}function gt(e,t=0,n=""){if(t>3)return[];let r=n.replace(/[^a-z0-9]/giu,"").toLowerCase();if(Ms.has(r))return[];if(typeof e=="string"){let i=e.replace(/\s+/gu," ").trim();return i.length<8?[]:[i]}if(Array.isArray(e))return e.flatMap(i=>gt(i,t+1,n));let s=Ie(e);if(!s)return[];let o=[];for(let[i,a]of Object.entries(s)){let c=i.replace(/[^a-z0-9]/giu,"").toLowerCase();Ms.has(c)||o.push(...gt(a,t+1,i))}return o}function Is(e){let n=Pe(["content","summary","text","value","statement","description","decision","task","knowledge","context","outcome","reason","rationale"].flatMap(s=>gt(e[s],0,s)));return(n.length>0?n:Pe(gt(e))).join(`
135
+ `,a=Ae(this.eventsFile,"a",384);try{Ss(a,i),en(a)}finally{Me(a)}try{ms(this.identity.projectRoot,o)}catch{try{Qt(this.identity.projectRoot)}catch{}}let c=o[o.length-1],u=hs(c),f=Array.from(r).slice(-ys);return this.saveStateUnsafe({...n,status:u,updatedAt:c.timestamp,lastLocalEventAt:c.timestamp,lastSequence:c.sequence,recentEventIds:f}),o})}readPending(){return this.withLock(()=>{let t=this.recoverStateUnsafe();if(!pt(this.eventsFile))return{events:[],startOffset:t.remoteByteOffset,endOffset:t.remoteByteOffset};let n=Xt(this.eventsFile).size,r=Math.min(t.remoteByteOffset,n);if(n<=r)return{events:[],startOffset:r,endOffset:n};let s=n-r,o=Buffer.alloc(s),i=Ae(this.eventsFile,"r");try{Bu(i,o,0,s,r)}finally{Me(i)}let a=[];for(let c of o.toString("utf8").split(/\r?\n/)){let u=tn(c);u&&a.push(u)}return{events:a,startOffset:r,endOffset:n}})}markRemote(t,n){this.withLock(()=>{let r=this.recoverStateUnsafe(),s=new Date().toISOString();this.saveStateUnsafe({...r,lastRemoteSequence:Math.max(r.lastRemoteSequence,t),remoteByteOffset:Math.max(r.remoteByteOffset,n),lastRemoteAt:s,updatedAt:s})})}setSourceCursor(t,n){this.withLock(()=>{let r=this.recoverStateUnsafe();this.saveStateUnsafe({...r,sourceCursors:{...r.sourceCursors,[t]:String(n)},updatedAt:new Date().toISOString()})})}};import{closeSync as Bl,existsSync as Vl,openSync as Hl,readSync as Jl,statSync as Gl}from"node:fs";import{createHash as il}from"node:crypto";import{existsSync as al,readdirSync as cl,readFileSync as ul}from"node:fs";import{basename as ll,join as $s}from"node:path";import{randomUUID as bs}from"node:crypto";var A=class extends Error{constructor(n,r){super(n);this.statusCode=r}statusCode};function Ie(e){let t=new Set,n=[];for(let r of e){let s=r.replace(/\s+/gu," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();t.has(o)||(t.add(o),n.push(s))}return n}function re(e){let t=e.normalize("NFKD").replace(/[\u0300-\u036f]/gu,"").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"").slice(0,120);if(!t)throw new A("Invalid Wiki slug",400);return t}function vs(e){let t=[];for(let n of e.matchAll(/\[\[([^\[\]]+)\]\]/gu)){let r=n[1]?.trim();r&&t.push(re(r))}return Ie(t)}function Zu(e){return e.normalize("NFKC").toLowerCase().split(/[^\p{L}\p{N}_-]+/u).map(t=>t.trim()).filter(t=>t.length>=2)}function ws(e){return{id:`revision-${bs()}`,pageId:e.id,slug:e.slug,revision:e.revision,title:e.title,...e.summary?{summary:e.summary}:{},content:e.content,tags:[...e.tags],links:[...e.links],createdAt:e.updatedAt}}function ne(e){return structuredClone(e)}var gt=class{constructor(t){this.store=t}store;state;queue=Promise.resolve();async initialize(){await this.ensureState()}async ensureState(){return this.state||(this.state=await this.store.load()),this.state}async mutate(t){let n,r=this.queue.then(async()=>{let s=await this.ensureState();n=t(s),s.updatedAt=new Date().toISOString(),await this.store.save(s)});return this.queue=r.then(()=>{},()=>{}),await r,n}async summary(){let t=await this.ensureState(),n=new Set(t.pages.flatMap(r=>r.links));return{schema:"toolnet.wiki-summary.v1",projectId:t.projectId,pages:t.pages.length,revisions:t.revisions.length,tags:Ie(t.pages.flatMap(r=>r.tags)).sort((r,s)=>r.localeCompare(s)),links:t.pages.reduce((r,s)=>r+s.links.length,0),orphanPages:t.pages.filter(r=>r.links.length===0&&!n.has(r.slug)).length,automatedPages:t.pages.filter(r=>r.tags.some(s=>s.startsWith("toolnet-auto-"))).length,updatedAt:t.updatedAt}}async listPages(){let t=await this.ensureState();return ne([...t.pages].sort((n,r)=>n.title.localeCompare(r.title)))}async getPage(t){let n=await this.ensureState(),r=re(t),s=n.pages.find(o=>o.slug===r||o.id===t);if(!s)throw new A(`Wiki page not found: ${t}`,404);return ne(s)}async createPage(t){return this.mutate(n=>{let r=t.title.trim(),s=t.content.trim();if(!r)throw new A("Wiki title is required",400);let o=re(t.slug??r);if(n.pages.some(c=>c.slug===o))throw new A(`Wiki page already exists: ${o}`,409);let i=new Date().toISOString(),a={id:`wiki-${bs()}`,slug:o,title:r,...t.summary?.trim()?{summary:t.summary.trim()}:{},content:s,tags:Ie(t.tags??[]),links:vs(s),revision:1,createdAt:i,updatedAt:i};return n.pages.push(a),n.revisions.push(ws(a)),ne(a)})}async updatePage(t,n){return this.mutate(r=>{let s=re(t),o=r.pages.find(i=>i.slug===s||i.id===t);if(!o)throw new A(`Wiki page not found: ${t}`,404);if(n.title!==void 0){let i=n.title.trim();if(!i)throw new A("Wiki title is required",400);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=vs(o.content)),n.tags!==void 0&&(o.tags=Ie(n.tags)),o.revision+=1,o.updatedAt=new Date().toISOString(),r.revisions.push(ws(o)),ne(o)})}async history(t){let n=await this.getPage(t),r=await this.ensureState();return ne(r.revisions.filter(s=>s.pageId===n.id).sort((s,o)=>o.revision-s.revision))}async backlinks(t){let n=await this.getPage(t),r=await this.ensureState();return ne(r.pages.filter(s=>s.links.includes(n.slug)).sort((s,o)=>s.title.localeCompare(o.title)))}async search(t,n=10){let r=await this.ensureState(),s=Ie(Zu(t));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(),f=a.summary?.toLowerCase()??"",l=a.content.toLowerCase(),p=a.tags.map(m=>m.toLowerCase()),d=0;for(let m of s)u===m&&(d+=12),c===m&&(d+=10),c.includes(m)&&(d+=6),u.includes(m)&&(d+=5),p.some(k=>k===m)?d+=5:p.some(k=>k.includes(m))&&(d+=3),f.includes(m)&&(d+=2),l.includes(m)&&(d+=1);d>0&&i.push({page:ne(a),score:d})}return i.sort((a,c)=>c.score-a.score||c.page.updatedAt.localeCompare(a.page.updatedAt)).slice(0,o)}};var xs="wiki/state.v1.json";function el(e){let t=new Date().toISOString();return{schema:"toolnet.wiki.v1",version:1,projectId:e.id,pages:[],revisions:[],createdAt:t,updatedAt:t}}function tl(e,t){let n=JSON.parse(e);if(n.schema!=="toolnet.wiki.v1"||n.version!==1||n.projectId!==t.id||!Array.isArray(n.pages)||!Array.isArray(n.revisions))throw new Error("Invalid ToolNet Wiki state");return n}var yt=class{constructor(t,n){this.storage=t;this.project=n}storage;project;async load(){let t=await this.storage.getText(xs);if(!t){let n=el(this.project);return await this.save(n),n}return tl(t,this.project)}async save(t){await this.storage.put(xs,JSON.stringify(t,null,2),"application/json")}};import{createHash as nl,randomUUID as js}from"node:crypto";var Ms="wiki/governance.v1.json",Cs="toolnet.knowledge-governance.v1",As=500,Pe={autoApproveThreshold:.86,criticalApproveThreshold:.94,staleAfterDays:90};function rl(e,t=0,n=1){return Math.max(t,Math.min(n,e))}function nn(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/gu," ").trim()}function Is(e){return nl("sha256").update(e.normalize("NFKC").replace(/\s+/gu," ").trim()).digest("hex")}function sl(e){let t=[e.title,e.summary??"",e.content.slice(0,2e3),...e.tags].join(" ").toLowerCase();return/\b(?:architecture|security|authentication|authorization|auth|database|production|deploy|deployment|payment|billing|permission|permissions|acl|credential|secret|migration)\b/u.test(t)}function ol(e){let t=e.sourceType==="skill"?.96:e.sourceType==="memory"?.94:.88,n=e.tags.map(r=>r.toLowerCase());return(n.includes("permanent")||n.includes("task"))&&(t+=.03),e.content.length>=200&&(t+=.02),e.content.length<80&&(t-=.05),e.title.length<4&&(t-=.05),rl(t)}function Ps(e){let t=new Date().toISOString();return{schema:Cs,version:1,projectId:e,policy:{...Pe},reviews:[],audit:[],createdAt:t,updatedAt:t}}function Ts(e){let t=e.autoApproveThreshold??Pe.autoApproveThreshold,n=e.criticalApproveThreshold??Pe.criticalApproveThreshold,r=e.staleAfterDays??Pe.staleAfterDays;if(!Number.isFinite(t)||t<.5||t>1)throw new A("Invalid autoApproveThreshold",400);if(!Number.isFinite(n)||n<.5||n>1)throw new A("Invalid criticalApproveThreshold",400);if(!Number.isInteger(r)||r<1||r>3650)throw new A("Invalid staleAfterDays",400);return{autoApproveThreshold:t,criticalApproveThreshold:n,staleAfterDays:r}}var ht=class{constructor(t,n){this.storage=t;this.project=n}storage;project;async load(){let t=await this.storage.getText(Ms);if(!t){let n=Ps(this.project.id);return await this.save(n),n}try{let n=JSON.parse(t);if(n.schema!==Cs||n.version!==1||n.projectId!==this.project.id||!Array.isArray(n.reviews)||!Array.isArray(n.audit))throw new Error("invalid");return{...n,policy:Ts(n.policy??Pe)}}catch{let n=Ps(this.project.id);return await this.save(n),n}}async save(t){await this.storage.put(Ms,JSON.stringify(t,null,2),"application/json")}},kt=class{constructor(t){this.store=t}store;state;queue=Promise.resolve();async initialize(){await this.ensureState()}async ensureState(){return this.state||(this.state=await this.store.load()),this.state}audit(t,n,r,s={}){t.audit.push({id:js(),action:n,principal:r,...s.reviewId?{reviewId:s.reviewId}:{},...s.sourceKey?{sourceKey:s.sourceKey}:{},timestamp:new Date().toISOString(),...s.metadata?{metadata:s.metadata}:{}}),t.audit.length>As&&(t.audit=t.audit.slice(-As))}async mutate(t){let n,r=this.queue.then(async()=>{let s=await this.ensureState();n=await t(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(t,n){return this.mutate(r=>(r.policy=Ts({...r.policy,...t}),this.audit(r,"policy:update",n,{metadata:{...r.policy}}),{...r.policy}))}async summary(){let t=await this.ensureState(),n=r=>t.reviews.filter(s=>s.status===r).length;return{schema:"toolnet.knowledge-governance-summary.v1",projectId:t.projectId,pending:n("pending"),approved:n("approved"),rejected:n("rejected"),superseded:n("superseded"),criticalPending:t.reviews.filter(r=>r.status==="pending"&&r.risk==="critical").length,conflictPending:t.reviews.filter(r=>r.status==="pending"&&r.risk==="conflict").length,auditEvents:t.audit.length,policy:{...t.policy},updatedAt:t.updatedAt}}async listReviews(t){let n=await this.ensureState();return structuredClone(n.reviews.filter(r=>!t||r.status===t).sort((r,s)=>s.updatedAt.localeCompare(r.updatedAt)))}async auditLog(t=100){let n=await this.ensureState(),r=Math.max(1,Math.min(500,Math.floor(t)));return structuredClone(n.audit.slice(-r).reverse())}async assess(t,n){let r=await this.ensureState(),s=ol(t),o=nn(t.title),i=n.filter(f=>f.slug!==t.slug&&nn(f.title)===o&&Is(f.content)!==Is(t.content)).map(f=>f.slug),a=sl(t),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(t,n){let r=await this.assess(t,n);return this.mutate(s=>{let o=s.reviews.find(c=>c.sourceKey===t.sourceKey&&c.digest===t.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:t.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:js(),sourceKey:t.sourceKey,sourceType:t.sourceType,slug:t.slug,marker:t.marker,digest:t.digest,title:t.title,...t.summary?{summary:t.summary}:{},content:t.content,tags:[...new Set([...t.tags,t.marker])],confidence:r.confidence,risk:r.risk,reasons:[...r.reasons],conflicts:[...r.conflicts],status:"pending",createdAt:i,updatedAt:i};return 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(t,n){await this.mutate(r=>{let s=r.reviews.find(o=>o.sourceKey===t&&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:t}))})}async decide(t,n,r){return this.mutate(async s=>{let o=s.reviews.find(u=>u.id===t);if(!o)throw new A(`Governance review not found: ${t}`,404);if(o.status!=="pending")throw new A("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:t,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:t,sourceKey:o.sourceKey,metadata:{targetReviewId:n.targetReviewId}}),structuredClone(o);if(n.action==="merge"){if(!n.targetReviewId)throw new A("targetReviewId is required for merge",400);let u=s.reviews.find(f=>f.id===n.targetReviewId);if(!u)throw new A("Merge target review not found",404);return o.status="superseded",o.mergedInto=u.id,this.audit(s,"knowledge:merged",n.principal,{reviewId:t,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 A(`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:t,sourceKey:o.sourceKey}),structuredClone(o)})}async quality(t){let n=await this.ensureState(),r=await t.listPages(),s=Date.now(),o=n.policy.staleAfterDays*864e5,i=r.map(f=>{let l=s-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>o}}).filter(f=>f.stale).map(({stale:f,...l})=>l),a=new Map;for(let f of r){let l=nn(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 Fs="wiki/automation.v1.json",Ks="toolnet.wiki-automation.v1",on=8e3,Es=new Set(["raw","rawtext","raw_text","rawtranscript","raw_transcript","transcript","messages","message","payload","prompt","response","assistantmessage","assistant_message","userprompt","user_prompt"]);function Te(e){return il("sha256").update(JSON.stringify(e)).digest("hex")}function Ce(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Os(e){return Array.isArray(e)?e:[]}function Ls(e){return typeof e!="string"?void 0:e.replace(/\s+/gu," ").trim()||void 0}function rn(e){return Array.isArray(e)?e.map(Ls).filter(t=>!!t):[]}function W(e,t){for(let n of t){let r=Ls(e[n]);if(r)return r}}function Ee(e){let t=new Set,n=[];for(let r of e){let s=r.replace(/\s+/gu," ").trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();t.has(o)||(t.add(o),n.push(s))}return n}function St(e,t=0,n=""){if(t>3)return[];let r=n.replace(/[^a-z0-9]/giu,"").toLowerCase();if(Es.has(r))return[];if(typeof e=="string"){let i=e.replace(/\s+/gu," ").trim();return i.length<8?[]:[i]}if(Array.isArray(e))return e.flatMap(i=>St(i,t+1,n));let s=Ce(e);if(!s)return[];let o=[];for(let[i,a]of Object.entries(s)){let c=i.replace(/[^a-z0-9]/giu,"").toLowerCase();Es.has(c)||o.push(...St(a,t+1,i))}return o}function Rs(e){let n=Ee(["content","summary","text","value","statement","description","decision","task","knowledge","context","outcome","reason","rationale"].flatMap(s=>St(e[s],0,s)));return(n.length>0?n:Ee(St(e))).join(`
136
136
 
137
- `).slice(0,nn)}function Cs(e,t){return L(e,["id","key","fingerprint","knowledgeId","sceneId"])??t}function Ps(e,t){return L(e,["title","name","topic","label","task","kind","type"])??t}function nl(e){return(L(e,["knowledgeClass","class","classification","scope"])??"").toLowerCase()}function rl(e){return(L(e,["kind","sceneKind","type"])??"").toLowerCase()}function sl(e){let t=Ie(e);if(!t)return[];let n=[],r=As(t.knowledge);for(let[o,i]of r.entries()){let a=Ie(i);if(!a)continue;let c=nl(a);if(c==="session"||c==="transient")continue;let u=Is(a);if(u.length<20)continue;let f=Cs(a,Ce(a).slice(0,16)),l=Ps(a,`Durable Memory ${o+1}`);n.push({sourceKey:`memory:${f}`,sourceType:"memory",title:l,summary:L(a,["summary","description"]),content:u,tags:Pe(["toolnet","auto","memory",...c?[c]:[]])})}let s=As(t.scenes);for(let[o,i]of s.entries()){let a=Ie(i);if(!a)continue;let c=rl(a);if(c==="session-context")continue;let u=Is(a);if(u.length<20)continue;let f=Cs(a,Ce(a).slice(0,16)),l=Ps(a,`Knowledge Scene ${o+1}`);n.push({sourceKey:`scene:${f}`,sourceType:"scene",title:l,summary:L(a,["summary","description"]),content:u,tags:Pe(["toolnet","auto","scene",...c?[c]:[]])})}return n}function ol(e){return Ts(e,".toolnet","memory","skills")}function il(e){let t=ol(e);if(!Xu(t))return{candidates:[],failed:0};let n=[],r=0,s=Zu(t).filter(o=>o.endsWith(".json")).sort();for(let o of s)try{let i=JSON.parse(el(Ts(t,o),"utf8")),a=Ie(i);if(!a||a.schema!=="toolnet.skill-memory.v1")continue;let c=L(a,["id","fingerprint"])??tl(o,".json"),u=L(a,["task"])??"",f=L(a,["title"])||u||`Reusable Skill ${c.slice(0,8)}`,l=L(a,["summary"])??void 0,p=en(a.steps),d=en(a.verification),g=en(a.files),k=[];u&&k.push(`## Task
137
+ `).slice(0,on)}function Ns(e,t){return W(e,["id","key","fingerprint","knowledgeId","sceneId"])??t}function _s(e,t){return W(e,["title","name","topic","label","task","kind","type"])??t}function dl(e){return(W(e,["knowledgeClass","class","classification","scope"])??"").toLowerCase()}function fl(e){return(W(e,["kind","sceneKind","type"])??"").toLowerCase()}function pl(e){let t=Ce(e);if(!t)return[];let n=[],r=Os(t.knowledge);for(let[o,i]of r.entries()){let a=Ce(i);if(!a)continue;let c=dl(a);if(c==="session"||c==="transient")continue;let u=Rs(a);if(u.length<20)continue;let f=Ns(a,Te(a).slice(0,16)),l=_s(a,`Durable Memory ${o+1}`);n.push({sourceKey:`memory:${f}`,sourceType:"memory",title:l,summary:W(a,["summary","description"]),content:u,tags:Ee(["toolnet","auto","memory",...c?[c]:[]])})}let s=Os(t.scenes);for(let[o,i]of s.entries()){let a=Ce(i);if(!a)continue;let c=fl(a);if(c==="session-context")continue;let u=Rs(a);if(u.length<20)continue;let f=Ns(a,Te(a).slice(0,16)),l=_s(a,`Knowledge Scene ${o+1}`);n.push({sourceKey:`scene:${f}`,sourceType:"scene",title:l,summary:W(a,["summary","description"]),content:u,tags:Ee(["toolnet","auto","scene",...c?[c]:[]])})}return n}function ml(e){return $s(e,".toolnet","memory","skills")}function gl(e){let t=ml(e);if(!al(t))return{candidates:[],failed:0};let n=[],r=0,s=cl(t).filter(o=>o.endsWith(".json")).sort();for(let o of s)try{let i=JSON.parse(ul($s(t,o),"utf8")),a=Ce(i);if(!a||a.schema!=="toolnet.skill-memory.v1")continue;let c=W(a,["id","fingerprint"])??ll(o,".json"),u=W(a,["task"])??"",f=W(a,["title"])||u||`Reusable Skill ${c.slice(0,8)}`,l=W(a,["summary"])??void 0,p=rn(a.steps),d=rn(a.verification),m=rn(a.files),k=[];u&&k.push(`## Task
138
138
  ${u}`),l&&k.push(`## Summary
139
139
  ${l}`),p.length>0&&k.push(`## Procedure
140
- ${p.map((h,S)=>`${S+1}. ${h}`).join(`
140
+ ${p.map((h,v)=>`${v+1}. ${h}`).join(`
141
141
  `)}`),d.length>0&&k.push(`## Verification
142
142
  ${d.map(h=>`- ${h}`).join(`
143
- `)}`),g.length>0&&k.push(`## Relevant Files
144
- ${g.map(h=>`- \`${h}\``).join(`
145
- `)}`);let y=k.join(`
146
-
147
- `).slice(0,nn);if(y.length<20)continue;n.push({sourceKey:`skill:${c}`,sourceType:"skill",title:f,summary:l,content:y,tags:["toolnet","auto","skill","sop"]})}catch{r+=1}return{candidates:n,failed:r}}function tn(e){let t=new Date().toISOString();return{schema:Os,version:1,projectId:e,entries:[],createdAt:t,updatedAt:t}}async function al(e,t){let n=await e.getText(Es);if(!n)return tn(t);try{let r=JSON.parse(n);return r.schema!==Os||r.version!==1||r.projectId!==t||!Array.isArray(r.entries)?tn(t):r}catch{return tn(t)}}async function cl(e,t){await e.put(Es,JSON.stringify(t,null,2),"application/json")}function ul(e){return`toolnet-auto-${Ce(e).slice(0,12)}`}function ll(e){let t=ne(e.title).slice(0,72),n=Ce(e.sourceKey).slice(0,10);return ne(`auto-${e.sourceType}-${t}-${n}`)}function dl(e){return[`> Auto-generated by ToolNet Knowledge Automation from ${e.sourceType==="skill"?"reusable Skill Memory":e.sourceType==="scene"?"semantic memory scene":"durable memory"}.`,"",e.content].join(`
148
- `).slice(0,nn)}function fl(e){return Ce({sourceType:e.sourceType,title:e.title,summary:e.summary,content:e.content,tags:e.tags})}function pl(e,t){return e.tags.includes(t)}async function Ns(e){let t=sl(e.hierarchy),n=il(e.project.rootPath),r=new Map;for(let d of[...t,...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:t.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 dt(new ft(e.storage,e.project));await i.initialize();let a=new mt(new pt(e.storage,e.project));await a.initialize();let c=await al(e.storage,e.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 s)try{let g=ul(d.sourceKey),k=fl(d),y=l.get(d.sourceKey),h=y?.slug??ll(d),S=f.get(h);if(S&&!pl(S,g)){o.skipped+=1;continue}let T=Pe([...d.tags,g]),E=dl(d),C=await a.gate({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:h,marker:g,digest:k,title:d.title,...d.summary?{summary:d.summary}:{},content:E,tags:T},[...f.values()]);if(!C.allowed){C.mode==="pending-review"?o.reviewPending+=1:o.skipped+=1;continue}C.mode==="auto-approved"?o.autoApproved+=1:C.mode==="review-approved"&&(o.reviewApproved+=1),S?y?.digest!==k?(S=await i.updatePage(h,{title:d.title,summary:d.summary??"",content:E,tags:T}),f.set(S.slug,S),o.updated+=1,o.pages.push({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:S.slug,action:"updated"})):(o.unchanged+=1,o.pages.push({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:h,action:"unchanged"})):(S=await i.createPage({slug:h,title:d.title,summary:d.summary,content:E,tags:T}),f.set(S.slug,S),o.created+=1,o.pages.push({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:S.slug,action:"created"}));let O=new Date().toISOString(),x={sourceKey:d.sourceKey,sourceType:d.sourceType,slug:h,digest:k,marker:g,updatedAt:O},w=c.entries.findIndex(W=>W.sourceKey===d.sourceKey);w>=0?c.entries[w]=x:c.entries.push(x),l.set(d.sourceKey,x),await a.markApplied(d.sourceKey,k)}catch(g){if(g instanceof M&&g.statusCode===409){o.skipped+=1;continue}o.failed+=1}let p=new Date().toISOString();return c.updatedAt=p,c.lastRunAt=p,c.entries.sort((d,g)=>d.sourceKey.localeCompare(g.sourceKey)),await cl(e.storage,c),o}import{createHash as ml}from"node:crypto";import{chmodSync as $s,existsSync as gl,mkdirSync as yl,readFileSync as Dy,readdirSync as zy,renameSync as hl,statSync as qy,writeFileSync as kl}from"node:fs";import{join as Fs}from"node:path";var Sl="toolnet.skill-memory.v1",_s=5,vl=16,wl=24,bl=32;function xl(e){return ml("sha256").update(e).digest("hex")}function Ee(e,t=Number.MAX_SAFE_INTEGER){let n=new Set,r=[];for(let s of e){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>=t))break}return r}function rn(e,t=360){let n=e.replace(/\s+/gu," ").trim();return n.length<=t?n:n.slice(0,Math.max(0,t-1)).trimEnd()+"\u2026"}function jl(e){return e.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/giu,"Bearer [REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/gu,"[REDACTED]").replace(/\b(api[_-]?key|token|password|passwd|secret)\b(\s*[:=]\s*)(["']?)[^\s"'`]+/giu,"$1$2[REDACTED]")}function z(e,t=360){return e&&rn(jl(e),t)||void 0}function Oe(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}}function Ks(e,t){for(let n of t){let r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()&&Number.isFinite(Number(r)))return Number(r)}}function Ls(e,t){for(let n of t){let r=e[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 Ws(e){let t=e.data??{};if(Ls(t,["passed","pass","success","succeeded","ok"])===!1)return!0;let r=Ks(t,["exitCode","exit_code","code","statusCode"]);if(r!==void 0&&r!==0)return!0;let s=Oe(t,["status","result","outcome"]);return!!(s&&/\b(fail(?:ed)?|error|broken|cancelled)\b/iu.test(s))}function Te(e){let t=e.data??{};if(Ws(e))return!1;if(Ls(t,["passed","pass","success","succeeded","ok"])===!0||Ks(t,["exitCode","exit_code","code","statusCode"])===0)return!0;let s=Oe(t,["status","result","outcome"]);return s&&/\b(pass(?:ed)?|success(?:ful)?|succeeded|ok|green|complete(?:d)?)\b/iu.test(s)?!0:e.type==="commit"||e.type==="deploy"}function Ds(e){let t=e.data??{},n=Oe(t,["path","file","filePath","filename","target"]);if(n)return z(n,260);let r=e.provenance?.files;return z(r?.[0],260)}function sn(e){return z(Oe(e.data??{},["command","cmd","script"]),420)}function ue(e){return z(Oe(e.data??{},["name","test","suite","title","message","text","result","status"]),300)}function Ml(e){let t=[];for(let n of[...e].sort((r,s)=>r.sequence-s.sequence))if(Te(n)){if(n.type==="test"){let r=ue(n)??sn(n)??"Tests passed";t.push(`Test passed: ${r}`);continue}if(n.type==="commit"){let r=ue(n);t.push(r?`Commit: ${r}`:"Commit completed");continue}if(n.type==="deploy"){let r=ue(n);t.push(r?`Deploy: ${r}`:"Deployment completed")}}return Ee(t,10)}function Al(e,t){let n=[];for(let r of[...e].sort((s,o)=>s.sequence-o.sequence))switch(r.type){case"file_write":case"file_edit":{let s=Ds(r);s&&n.push(`Update ${s}`);break}case"command":{if(Ws(r))break;let s=sn(r);s&&n.push(`Run: ${s}`);break}case"test":{if(!Te(r))break;let s=ue(r)??sn(r)??"project tests";n.push(`Verify: ${s}`);break}case"commit":{if(!Te(r))break;let s=ue(r);n.push(s?`Commit: ${s}`:"Commit verified changes");break}case"deploy":{if(!Te(r))break;let s=ue(r);n.push(s?`Deploy: ${s}`:"Deploy verified build");break}default:break}if(n.length===0)for(let r of t.files.slice(0,8)){let s=z(r,260);s&&n.push(`Update ${s}`)}return Ee(n,vl)}function Il(e,t){let n=[...t.files];for(let r of e){let s=Ds(r);s&&n.push(s);for(let o of r.provenance?.files??[]){let i=z(o,260);i&&n.push(i)}}return Ee(n,wl)}function Cl(e){return Ee(e.filter(t=>["file_write","file_edit","command","test","commit","deploy"].includes(t.type)).map(t=>t.id),bl)}function Pl(e){return e.map(n=>n.timestamp).filter(Boolean).sort().at(-1)??new Date(0).toISOString()}function zs(e,t,n){if(t.length===0)return[];let r=Ml(t),s=Ee(n.completed.map(g=>z(g,280)??""),_s);if(!(s.length>0||t.some(g=>["test","commit","deploy"].includes(g.type)&&Te(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=Al(t,n);if(c.length===0)return[];let u=Il(t,n),f=Cl(t),l=Math.min(...t.map(g=>g.sequence)),p=Math.max(...t.map(g=>g.sequence)),d=Pl(t);return a.slice(0,_s).map(g=>{let k=[`Reusable procedure learned from successful task: ${g}.`,u.length>0?`Files: ${u.slice(0,6).join(", ")}.`:"",r.length>0?`Verification: ${r.slice(0,4).join("; ")}.`:""].filter(Boolean),y=JSON.stringify({projectId:e.projectId,task:g,steps:c,verification:r,files:u}),h=xl(y);return{schema:Sl,version:1,id:`skill-${h.slice(0,24)}`,fingerprint:h,projectId:e.projectId,title:rn(`SOP: ${g}`,180),task:g,summary:rn(k.join(" "),900),steps:c,verification:r,files:u,source:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,firstSequence:l,lastSequence:p,eventIds:f},createdAt:d}})}function Tl(e){return Fs(e.rootPath,".toolnet","memory","skills")}function El(e){let t=Tl(e);return yl(t,{recursive:!0,mode:448}),$s(t,448),t}function qs(e,t){if(t.length===0)return{written:0,deduped:0,files:[]};let n=El(e),r=0,s=0,o=[];for(let i of t){if(i.projectId!==e.id)throw new Error(`Skill project mismatch: ${i.projectId} != ${e.id}`);let a=Fs(n,`${i.id}.json`);if(o.push(a),gl(a)){s+=1;continue}let c=`${a}.${process.pid}.${Date.now()}.tmp`;kl(c,JSON.stringify(i,null,2)+`
149
- `,{encoding:"utf8",mode:384}),hl(c,a),$s(a,384),r+=1}return{written:r,deduped:s,files:o}}function Bs(e){return String(e).padStart(12,"0")}function Ol(e){return`projects/${e.projectId}/memory/learned`}var yt=class{constructor(t){this.storage=t}storage;async write(t,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:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,createdAt:new Date().toISOString(),firstSequence:s,lastSequence:o,candidateCount:r.length,candidates:r},a=JSON.stringify(i,null,2)+`
150
- `,c=v(r.map(l=>l.fingerprint).sort().join("|")).slice(0,16),u=v(t.sessionKey).slice(0,12),f=[Ol(t),"batches",`${Bs(s)}-${Bs(o)}-${u}-${c}.json`].join("/");return await this.storage.exists(f)||await this.storage.put(f,a,"application/json"),f}};import{createHash as Rl}from"node:crypto";function Vs(e){return String(e).padStart(12,"0")}function Hs(e){return Rl("sha256").update(e).digest("hex")}function Nl(e){return`projects/${e.projectId}/memory/hierarchy`}var ht=class{constructor(t){this.storage=t}storage;async write(t,n,r){if(n.length===0||r.facts.length===0)return null;let s=Math.min(...n.map(f=>f.sequence)),o=Math.max(...n.map(f=>f.sequence)),i={schema:"toolnet.memory-hierarchy-batch.v1",version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,createdAt:new Date().toISOString(),firstSequence:s,lastSequence:o,hierarchy:r},a=Hs([...r.facts.map(f=>f.id),...r.knowledge.map(f=>f.id)].sort().join("|")).slice(0,16),c=Hs(t.sessionKey).slice(0,12),u=[Nl(t),"batches",`${Vs(s)}-${Vs(o)}-${c}-${a}.json`].join("/");return await this.storage.exists(u)||await this.storage.put(u,`${JSON.stringify(i,null,2)}
151
- `,"application/json"),u}};function Wl(e,t){if(!$l(e))return{events:[],nextOffset:t};let n=Ll(e).size,r=Number.isFinite(t)?Math.max(0,t):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let s=n-r,o=Buffer.alloc(s),i=Fl(e,"r");try{Kl(i,o,0,s,r)}finally{_l(i)}let a=o.toString("utf8"),c=a.lastIndexOf(`
143
+ `)}`),m.length>0&&k.push(`## Relevant Files
144
+ ${m.map(h=>`- \`${h}\``).join(`
145
+ `)}`);let g=k.join(`
146
+
147
+ `).slice(0,on);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 sn(e){let t=new Date().toISOString();return{schema:Ks,version:1,projectId:e,entries:[],createdAt:t,updatedAt:t}}async function yl(e,t){let n=await e.getText(Fs);if(!n)return sn(t);try{let r=JSON.parse(n);return r.schema!==Ks||r.version!==1||r.projectId!==t||!Array.isArray(r.entries)?sn(t):r}catch{return sn(t)}}async function hl(e,t){await e.put(Fs,JSON.stringify(t,null,2),"application/json")}function kl(e){return`toolnet-auto-${Te(e).slice(0,12)}`}function Sl(e){let t=re(e.title).slice(0,72),n=Te(e.sourceKey).slice(0,10);return re(`auto-${e.sourceType}-${t}-${n}`)}function vl(e){return[`> Auto-generated by ToolNet Knowledge Automation from ${e.sourceType==="skill"?"reusable Skill Memory":e.sourceType==="scene"?"semantic memory scene":"durable memory"}.`,"",e.content].join(`
148
+ `).slice(0,on)}function wl(e){return Te({sourceType:e.sourceType,title:e.title,summary:e.summary,content:e.content,tags:e.tags})}function bl(e,t){return e.tags.includes(t)}async function Ws(e){let t=pl(e.hierarchy),n=gl(e.project.rootPath),r=new Map;for(let d of[...t,...n.candidates])r.set(d.sourceKey,d);let s=[...r.values()].sort((d,m)=>d.sourceKey.localeCompare(m.sourceKey)),o={schema:"toolnet.wiki-automation-result.v1",scanned:t.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 gt(new yt(e.storage,e.project));await i.initialize();let a=new kt(new ht(e.storage,e.project));await a.initialize();let c=await yl(e.storage,e.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 s)try{let m=kl(d.sourceKey),k=wl(d),g=l.get(d.sourceKey),h=g?.slug??Sl(d),v=f.get(h);if(v&&!bl(v,m)){o.skipped+=1;continue}let x=Ee([...d.tags,m]),O=vl(d),C=await a.gate({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:h,marker:m,digest:k,title:d.title,...d.summary?{summary:d.summary}:{},content:O,tags:x},[...f.values()]);if(!C.allowed){C.mode==="pending-review"?o.reviewPending+=1:o.skipped+=1;continue}C.mode==="auto-approved"?o.autoApproved+=1:C.mode==="review-approved"&&(o.reviewApproved+=1),v?g?.digest!==k?(v=await i.updatePage(h,{title:d.title,summary:d.summary??"",content:O,tags:x}),f.set(v.slug,v),o.updated+=1,o.pages.push({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:v.slug,action:"updated"})):(o.unchanged+=1,o.pages.push({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:h,action:"unchanged"})):(v=await i.createPage({slug:h,title:d.title,summary:d.summary,content:O,tags:x}),f.set(v.slug,v),o.created+=1,o.pages.push({sourceKey:d.sourceKey,sourceType:d.sourceType,slug:v.slug,action:"created"}));let R=new Date().toISOString(),j={sourceKey:d.sourceKey,sourceType:d.sourceType,slug:h,digest:k,marker:m,updatedAt:R},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,k)}catch(m){if(m instanceof A&&m.statusCode===409){o.skipped+=1;continue}o.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 hl(e.storage,c),o}import{createHash as xl}from"node:crypto";import{chmodSync as zs,existsSync as jl,mkdirSync as Ml,readFileSync as th,readdirSync as nh,renameSync as Al,statSync as rh,writeFileSync as Il}from"node:fs";import{join as qs}from"node:path";var Pl="toolnet.skill-memory.v1",Ds=5,Cl=16,Tl=24,El=32;function Ol(e){return xl("sha256").update(e).digest("hex")}function Re(e,t=Number.MAX_SAFE_INTEGER){let n=new Set,r=[];for(let s of e){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>=t))break}return r}function an(e,t=360){let n=e.replace(/\s+/gu," ").trim();return n.length<=t?n:n.slice(0,Math.max(0,t-1)).trimEnd()+"\u2026"}function Rl(e){return e.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/giu,"Bearer [REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/gu,"[REDACTED]").replace(/\b(api[_-]?key|token|password|passwd|secret)\b(\s*[:=]\s*)(["']?)[^\s"'`]+/giu,"$1$2[REDACTED]")}function q(e,t=360){return e&&an(Rl(e),t)||void 0}function Ne(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim())return r}}function Bs(e,t){for(let n of t){let r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()&&Number.isFinite(Number(r)))return Number(r)}}function Vs(e,t){for(let n of t){let r=e[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 Hs(e){let t=e.data??{};if(Vs(t,["passed","pass","success","succeeded","ok"])===!1)return!0;let r=Bs(t,["exitCode","exit_code","code","statusCode"]);if(r!==void 0&&r!==0)return!0;let s=Ne(t,["status","result","outcome"]);return!!(s&&/\b(fail(?:ed)?|error|broken|cancelled)\b/iu.test(s))}function Oe(e){let t=e.data??{};if(Hs(e))return!1;if(Vs(t,["passed","pass","success","succeeded","ok"])===!0||Bs(t,["exitCode","exit_code","code","statusCode"])===0)return!0;let s=Ne(t,["status","result","outcome"]);return s&&/\b(pass(?:ed)?|success(?:ful)?|succeeded|ok|green|complete(?:d)?)\b/iu.test(s)?!0:e.type==="commit"||e.type==="deploy"}function Js(e){let t=e.data??{},n=Ne(t,["path","file","filePath","filename","target"]);if(n)return q(n,260);let r=e.provenance?.files;return q(r?.[0],260)}function cn(e){return q(Ne(e.data??{},["command","cmd","script"]),420)}function de(e){return q(Ne(e.data??{},["name","test","suite","title","message","text","result","status"]),300)}function Nl(e){let t=[];for(let n of[...e].sort((r,s)=>r.sequence-s.sequence))if(Oe(n)){if(n.type==="test"){let r=de(n)??cn(n)??"Tests passed";t.push(`Test passed: ${r}`);continue}if(n.type==="commit"){let r=de(n);t.push(r?`Commit: ${r}`:"Commit completed");continue}if(n.type==="deploy"){let r=de(n);t.push(r?`Deploy: ${r}`:"Deployment completed")}}return Re(t,10)}function _l(e,t){let n=[];for(let r of[...e].sort((s,o)=>s.sequence-o.sequence))switch(r.type){case"file_write":case"file_edit":{let s=Js(r);s&&n.push(`Update ${s}`);break}case"command":{if(Hs(r))break;let s=cn(r);s&&n.push(`Run: ${s}`);break}case"test":{if(!Oe(r))break;let s=de(r)??cn(r)??"project tests";n.push(`Verify: ${s}`);break}case"commit":{if(!Oe(r))break;let s=de(r);n.push(s?`Commit: ${s}`:"Commit verified changes");break}case"deploy":{if(!Oe(r))break;let s=de(r);n.push(s?`Deploy: ${s}`:"Deploy verified build");break}default:break}if(n.length===0)for(let r of t.files.slice(0,8)){let s=q(r,260);s&&n.push(`Update ${s}`)}return Re(n,Cl)}function $l(e,t){let n=[...t.files];for(let r of e){let s=Js(r);s&&n.push(s);for(let o of r.provenance?.files??[]){let i=q(o,260);i&&n.push(i)}}return Re(n,Tl)}function Fl(e){return Re(e.filter(t=>["file_write","file_edit","command","test","commit","deploy"].includes(t.type)).map(t=>t.id),El)}function Kl(e){return e.map(n=>n.timestamp).filter(Boolean).sort().at(-1)??new Date(0).toISOString()}function Gs(e,t,n){if(t.length===0)return[];let r=Nl(t),s=Re(n.completed.map(m=>q(m,280)??""),Ds);if(!(s.length>0||t.some(m=>["test","commit","deploy"].includes(m.type)&&Oe(m))))return[];let i=q(n.task,280)??q(n.nextActions[0],280),a=s.length>0?s:i?[i]:[];if(a.length===0)return[];let c=_l(t,n);if(c.length===0)return[];let u=$l(t,n),f=Fl(t),l=Math.min(...t.map(m=>m.sequence)),p=Math.max(...t.map(m=>m.sequence)),d=Kl(t);return a.slice(0,Ds).map(m=>{let k=[`Reusable procedure learned from successful task: ${m}.`,u.length>0?`Files: ${u.slice(0,6).join(", ")}.`:"",r.length>0?`Verification: ${r.slice(0,4).join("; ")}.`:""].filter(Boolean),g=JSON.stringify({projectId:e.projectId,task:m,steps:c,verification:r,files:u}),h=Ol(g);return{schema:Pl,version:1,id:`skill-${h.slice(0,24)}`,fingerprint:h,projectId:e.projectId,title:an(`SOP: ${m}`,180),task:m,summary:an(k.join(" "),900),steps:c,verification:r,files:u,source:{agent:e.agent,nativeSessionId:e.nativeSessionId,sessionKey:e.sessionKey,firstSequence:l,lastSequence:p,eventIds:f},createdAt:d}})}function Ll(e){return qs(e.rootPath,".toolnet","memory","skills")}function Wl(e){let t=Ll(e);return Ml(t,{recursive:!0,mode:448}),zs(t,448),t}function Us(e,t){if(t.length===0)return{written:0,deduped:0,files:[]};let n=Wl(e),r=0,s=0,o=[];for(let i of t){if(i.projectId!==e.id)throw new Error(`Skill project mismatch: ${i.projectId} != ${e.id}`);let a=qs(n,`${i.id}.json`);if(o.push(a),jl(a)){s+=1;continue}let c=`${a}.${process.pid}.${Date.now()}.tmp`;Il(c,JSON.stringify(i,null,2)+`
149
+ `,{encoding:"utf8",mode:384}),Al(c,a),zs(a,384),r+=1}return{written:r,deduped:s,files:o}}function Ys(e){return String(e).padStart(12,"0")}function Dl(e){return`projects/${e.projectId}/memory/learned`}var vt=class{constructor(t){this.storage=t}storage;async write(t,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:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,createdAt:new Date().toISOString(),firstSequence:s,lastSequence:o,candidateCount:r.length,candidates:r},a=JSON.stringify(i,null,2)+`
150
+ `,c=w(r.map(l=>l.fingerprint).sort().join("|")).slice(0,16),u=w(t.sessionKey).slice(0,12),f=[Dl(t),"batches",`${Ys(s)}-${Ys(o)}-${u}-${c}.json`].join("/");return await this.storage.exists(f)||await this.storage.put(f,a,"application/json"),f}};import{createHash as zl}from"node:crypto";function Qs(e){return String(e).padStart(12,"0")}function Xs(e){return zl("sha256").update(e).digest("hex")}function ql(e){return`projects/${e.projectId}/memory/hierarchy`}var wt=class{constructor(t){this.storage=t}storage;async write(t,n,r){if(n.length===0||r.facts.length===0)return null;let s=Math.min(...n.map(f=>f.sequence)),o=Math.max(...n.map(f=>f.sequence)),i={schema:"toolnet.memory-hierarchy-batch.v1",version:1,projectId:t.projectId,agent:t.agent,nativeSessionId:t.nativeSessionId,sessionKey:t.sessionKey,createdAt:new Date().toISOString(),firstSequence:s,lastSequence:o,hierarchy:r},a=Xs([...r.facts.map(f=>f.id),...r.knowledge.map(f=>f.id)].sort().join("|")).slice(0,16),c=Xs(t.sessionKey).slice(0,12),u=[ql(t),"batches",`${Qs(s)}-${Qs(o)}-${c}-${a}.json`].join("/");return await this.storage.exists(u)||await this.storage.put(u,`${JSON.stringify(i,null,2)}
151
+ `,"application/json"),u}};function Ul(e,t){if(!Vl(e))return{events:[],nextOffset:t};let n=Gl(e).size,r=Number.isFinite(t)?Math.max(0,t):0;if(r>n&&(r=0),r===n)return{events:[],nextOffset:n};let s=n-r,o=Buffer.alloc(s),i=Hl(e,"r");try{Jl(i,o,0,s,r)}finally{Bl(i)}let a=o.toString("utf8"),c=a.lastIndexOf(`
152
152
  `);if(c<0)return{events:[],nextOffset:r};let u=a.slice(0,c+1);return{events:u.split(`
153
- `).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var kt=class{constructor(t){this.options=t;this.journal=new yt(t.storage),this.hierarchyJournal=new ht(t.storage)}options;journal;hierarchyJournal;async learnNew(){let t=this.options.wal.loadState(),n=Number(t.sourceCursors["memory.learner.offset"]??0),r=Number.isFinite(n)?n:0,s=Wl(this.options.wal.eventsFile,r);if(s.events.length===0)return{scannedEvents:0,candidates:0,journalWritten:!1,nextOffset:s.nextOffset};let o=rt(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=zs(this.options.identity,s.events,o.state),f=qs(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",f.written),this.options.wal.setSourceCursor("memory.skill.deduped",f.deduped);try{let l=kr(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 Ns({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}}};function Js(e,t,n){if(process.env.TOOLNET_LOCAL_CHECKPOINT==="0"||n.length===0)return{updated:!1,observations:0};let r=ze(t,n);if(r.length===0)return{updated:!1,observations:0};let s=Hn(e,r);Ar(e,s),xr(e,{agent:t.agent,nativeSessionId:t.nativeSessionId,observations:r,workState:s});try{Jr(e,t,n,s)}catch{}try{Qn({project:e,identity:t,state:s,reason:"continuous-checkpoint",sequence:n.at(-1)?.sequence??0})}catch{}return{updated:!0,observations:r.length}}var St=class{identity;wal;remote;sanitizer=new U;learner;continuity;semantic;handoff;project;title;metadata;constructor(t){this.project=t.project,this.identity=Yr(t.project,t.agent,t.nativeSessionId),this.title=t.title,this.metadata=this.sanitizer.sanitizeValue(t.metadata??{}),this.wal=new lt(this.identity,t.eventContext),this.remote=new st(t.storage,t.maxEventsPerChunk??100,t.maxChunkBytes??512*1024),this.learner=new kt({project:t.project,storage:t.storage,identity:this.identity,wal:this.wal}),this.continuity=new Be({project:t.project,storage:t.storage,identity:this.identity,wal:this.wal}),this.semantic=new Ye({project:t.project,storage:t.storage,identity:this.identity,wal:this.wal}),this.handoff=new Ge({project:t.project,storage:t.storage,identity:this.identity})}sanitizeEvent(t){let n=t.provenance?{...t.provenance,metadata:this.sanitizer.sanitizeValue(t.provenance.metadata)}:void 0;return{...t,data:this.sanitizer.sanitizeValue(t.data??{}),provenance:n}}checkpointLocal(t){if(t.length!==0)try{Js(this.project,this.identity,t)}catch{}}start(t={}){let n=this.wal.loadState();return this.record({type:n.lastSequence===0?"session_start":"session_resume",data:t,provenance:{source:this.identity.agent}})}record(t){let n=this.wal.append([this.sanitizeEvent(t)]);return this.checkpointLocal(n),n[0]}recordMany(t){let n=this.wal.append(t.map(r=>this.sanitizeEvent(r)));return this.checkpointLocal(n),n}setSourceCursor(t,n){this.wal.setSourceCursor(t,n)}async flush(){let t=this.wal.readPending(),n=this.wal.loadState(),r=await this.remote.append(this.identity,t.events,n.sourceCursors,{title:this.title,metadata:this.metadata});if(t.events.length>0){let s=t.events[t.events.length-1];this.wal.markRemote(s.sequence,t.endOffset)}if(process.env.TOOLNET_SESSION_LEARNING!=="0")try{await this.learner.learnNew()}catch{}if(process.env.TOOLNET_WORK_CONTINUITY!=="0")try{await this.continuity.learnNew()}catch{}if(process.env.TOOLNET_SEMANTIC_CONTINUITY!=="0")try{await this.semantic.learnNew()}catch{}if(process.env.TOOLNET_SMART_HANDOFF!=="0"&&t.events.length>0)try{let s=t.events[t.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(t={}){return this.record({type:"session_idle",data:t,provenance:{source:this.identity.agent}}),this.flush()}async end(t={}){return this.record({type:"session_end",data:t,provenance:{source:this.identity.agent}}),this.flush()}status(){return this.wal.loadState()}recoverRemote(){return this.remote.recover(this.identity)}};import{existsSync as Dl,openSync as zl,closeSync as ql,readSync as Bl,statSync as Vl}from"node:fs";function Hl(e){let t=typeof e.role=="string"?e.role:"",n=typeof e.type=="string"?e.type.toLowerCase():"";return t==="user"||n.includes("user")?"user_prompt":t==="assistant"||n.includes("assistant")||n.includes("model")?"assistant_message":n.includes("tool")||"toolCall"in e||"tool_call"in e?"tool_call":n.includes("error")?"error":"message"}function Jl(e){let t=[e.timestamp,e.createdAt,e.time,e.created_at];for(let n of t){if(typeof n=="string"){let r=new Date(n);if(!Number.isNaN(r.getTime()))return r.toISOString()}if(typeof n=="number"){let r=n;r<1e11&&(r*=1e3);let s=new Date(r);if(!Number.isNaN(s.getTime()))return s.toISOString()}}return new Date().toISOString()}function Gs(e,t={offset:0}){if(!Dl(e))return{events:[],nextOffset:t.offset,reset:!1};let n=Vl(e).size,r=t.offset>n,s=r?0:t.offset;if(s===n)return{events:[],nextOffset:n,reset:r};let o=n-s,i=Buffer.alloc(o),a=zl(e,"r");try{Bl(a,i,0,o,s)}finally{ql(a)}let c=i.toString("utf8"),u=c.lastIndexOf(`
154
- `);if(u<0)return{events:[],nextOffset:s,reset:r};let f=c.slice(0,u+1),l=Buffer.byteLength(f,"utf8"),p=[],d=0;for(let g of f.split(`
155
- `)){if(!g)continue;let k=Buffer.byteLength(g+`
156
- `,"utf8"),y=s+d;d+=k;let h;try{h=JSON.parse(g)}catch{p.push({type:"custom",sourceEventId:`transcript:${y}`,sourceSequence:y,data:{format:"raw-line",content:g},provenance:{source:"agy-transcript",sourcePath:e,sourceOffset:y}});continue}let S=h&&typeof h=="object"&&!Array.isArray(h)?h:{value:h};p.push({type:Hl(S),timestamp:Jl(S),role:typeof S.role=="string"?S.role:void 0,sourceEventId:`transcript:${y}`,sourceSequence:y,data:S,provenance:{source:"agy-transcript",sourcePath:e,sourceOffset:y}})}return{events:p,nextOffset:s+l,reset:r}}var Gl=[/^<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*$/],Ul=[/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],Yl=["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 Ql(e){let t=e.toLowerCase();return Yl.some(n=>t.includes(n))}function Xl(e){if(!e.trim())return!0;for(let t of Gl)if(t.test(e))return!0;return Ql(e),!1}function Zl(e){let t=e;for(let n of Ul)t=t.replace(n,r=>{let s=r.split(/[:\s=]+/);return s.length>1?`${s[0]}: [REDACTED]`:"[REDACTED]"});return t}function on(e){let t=e.trim();return t?Xl(t)?{content:"",filtered:!0,reason:"noise"}:{content:Zl(t),filtered:!1}:{content:"",filtered:!0,reason:"empty"}}function vt(e){let t={};for(let[n,r]of Object.entries(e))if(typeof r=="string"){let s=on(r);s.filtered||(t[n]=s.content)}else r&&typeof r=="object"&&!Array.isArray(r)?t[n]=vt(r):Array.isArray(r)?t[n]=r.map(s=>{if(typeof s=="string"){let o=on(s);return o.filtered?null:o.content}return s&&typeof s=="object"?vt(s):s}).filter(s=>s!==null):t[n]=r;return t}function Us(e){let t=typeof e.type=="string"?e.type.toLowerCase():"";if(t.includes("system")||t.includes("ephemeral")||t==="tool_call"&&!e.result)return!0;if(e.data&&typeof e.data=="object"){let n=e.data,r=typeof n.content=="string"?n.content:"";if(r&&on(r).filtered)return!0}return!1}function nd(e){return e==="~"?Ys():e.startsWith("~/")?ed(Ys(),e.slice(2)):e}async function Qs(e){let t=e.conversationId.trim();if(!t)throw new Error("Agy conversationId is required");let n=td(nd(e.transcriptPath)),r=new St({project:e.project,storage:e.storage,agent:"agy",nativeSessionId:t,metadata:{source:"antigravity-hook",transcriptPath:n,workspacePaths:e.workspacePaths??[],artifactDirectoryPath:e.artifactDirectoryPath,modelName:e.modelName},eventContext:{source:"agy",cwd:e.workspacePaths?.[0]??e.project.rootPath}}),s=r.status(),o=s.sourceCursors["agy.transcript.offset"],i=o?Number(o):0,a=Gs(n,{offset:Number.isFinite(i)?i:0}),c=[];s.lastSequence===0&&c.push({type:"session_start",sourceEventId:`agy:${t}:start`,data:{workspacePaths:e.workspacePaths??[],transcriptPath:n,modelName:e.modelName},provenance:{source:"antigravity-hook",sourcePath:n}}),a.reset&&c.push({type:"custom",sourceEventId:`agy:${t}:transcript-reset:${a.nextOffset}`,data:{event:"transcript_reset",transcriptPath:n},provenance:{source:"agy-transcript",sourcePath:n}});let u=a.events.filter(p=>!Us(p.data)).map(p=>({...p,data:vt(p.data)}));c.push(...u),e.phase==="stop"&&(e.error&&c.push({type:"error",sourceEventId:["agy",t,"stop-error",e.terminationReason??"",a.nextOffset].join(":"),data:{error:e.error,terminationReason:e.terminationReason,fullyIdle:e.fullyIdle},provenance:{source:"antigravity-stop-hook"}}),e.fullyIdle&&c.push({type:"session_idle",sourceEventId:["agy",t,"idle",a.nextOffset].join(":"),data:{terminationReason:e.terminationReason,fullyIdle:!0},provenance:{source:"antigravity-stop-hook"}}));let f=r.recordMany(c);if(r.setSourceCursor("agy.transcript.offset",a.nextOffset),e.phase&&r.setSourceCursor("agy.last.phase",e.phase),u.length>0)try{let p=u.map(g=>JSON.stringify(g.data)),d=nt(p,t);r.setSourceCursor("agy.session.summary",d.summary),r.setSourceCursor("agy.session.facts_count",d.durableFacts.length),Kr()&&(Dr()||r.setSourceCursor("agy.raw_transcript.archived","local"))}catch{}let l=await r.flush();return{conversationId:t,imported:f.length,eventCount:l.eventCount,chunkCount:l.chunkCount,status:l.status,transcriptOffset:a.nextOffset,reset:a.reset}}async function rd(){let e="";for await(let t of process.stdin)e+=t.toString();if(!e.trim())return{};try{return JSON.parse(e)}catch{return{}}}function Re(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function sd(e){let t=typeof e.common=="object"&&e.common!==null?e.common:{},n=typeof e.pre_invocation_hook_args=="object"&&e.pre_invocation_hook_args!==null?e.pre_invocation_hook_args:{},r=typeof e.post_invocation_hook_args=="object"&&e.post_invocation_hook_args!==null?e.post_invocation_hook_args:{},s=typeof e.stop_hook_args=="object"&&e.stop_hook_args!==null?e.stop_hook_args:{},o=(typeof e.conversationId=="string"?e.conversationId:"")||(typeof e.conversation_id=="string"?e.conversation_id:"")||(typeof t.conversation_id=="string"?t.conversation_id:""),i=(typeof e.transcriptPath=="string"?e.transcriptPath:"")||(typeof e.transcript_path=="string"?e.transcript_path:"")||(typeof t.transcript_path=="string"?t.transcript_path:""),a=Re(e.workspacePaths).length>0?Re(e.workspacePaths):Re(e.workspace_paths).length>0?Re(e.workspace_paths):Re(t.workspace_paths),c=typeof e.invocationNum=="number"?e.invocationNum:typeof n.invocation_num=="number"?n.invocation_num:typeof e.invocation_num=="number"?e.invocation_num:void 0,u=(typeof e.artifactDirectoryPath=="string"?e.artifactDirectoryPath:"")||(typeof t.artifact_directory_path=="string"?t.artifact_directory_path:"")||(typeof e.artifact_directory_path=="string"?e.artifact_directory_path:"")||void 0,f=(typeof e.modelName=="string"?e.modelName:"")||(typeof t.model_name=="string"?t.model_name:"")||(typeof e.model_name=="string"?e.model_name:"")||void 0,l=s.fully_idle===!0||e.fullyIdle===!0||e.fully_idle===!0,p=(typeof s.termination_reason=="string"?s.termination_reason:"")||(typeof e.terminationReason=="string"?e.terminationReason:"")||(typeof e.termination_reason=="string"?e.termination_reason:"")||void 0,d=(typeof s.error=="string"&&s.error?s.error:"")||(typeof e.error=="string"&&e.error?e.error:"")||void 0;return{conversationId:o,transcriptPath:i,workspacePaths:a,invocationNum:c,artifactDirectoryPath:u,modelName:f,fullyIdle:l,terminationReason:p,error:d}}function od(e){let t=typeof e.toolCall=="object"&&e.toolCall!==null?e.toolCall:{},n=typeof t.args=="object"&&t.args!==null?t.args:{},r="";try{r=JSON.stringify(n).replace(/\\\\/g,"/").toLowerCase()}catch{r=""}return r.includes(".toolnet/journal")||r.includes(".toolnet/runtime/sources")||r.includes(".toolnet/sessions")?{decision:"deny",reason:"ToolNet continuity guard: do not replay raw .toolnet/journal, .toolnet/runtime/sources or legacy .toolnet/sessions history. Use the injected continuity handoff. If deeper history is required, invoke memory_agent_ask directly."}:{decision:"allow"}}async function id(){let e=process.argv[2]??"post",t=await rd();if(e==="pre-tool"){process.stdout.write(JSON.stringify(od(t)));return}let n=sd(t),r=n.conversationId,s=n.transcriptPath,o=n.workspacePaths,i=Gr(o);i&&(e==="pre"||e==="stop")&&wn(i.rootPath);let c={};if(i&&r)try{let u=Ne(),f=hn(gn({provider:u.storage.provider,huggingface:u.storage.huggingface,localRoot:u.storage.localRoot}),{attempts:2}),l=new We(f,i.id,i.name,i.remote??i.name);if(s)try{await Qs({project:i,storage:l,conversationId:r,transcriptPath:s,workspacePaths:o,artifactDirectoryPath:n.artifactDirectoryPath,modelName:n.modelName,phase:e,fullyIdle:n.fullyIdle,terminationReason:n.terminationReason,error:n.error})}catch{}if(e==="pre")try{c=await br({project:i,storage:l,conversationId:r,invocationNum:n.invocationNum})}catch{c={}}if(e==="stop")try{await Tt(i,l,800)}catch{}}catch{}if(e==="stop"){process.stdout.write(JSON.stringify({decision:"stop"}));return}process.stdout.write(JSON.stringify(c))}id().catch(()=>{process.argv[2]==="stop"?process.stdout.write('{"decision":"stop"}'):process.argv[2]==="pre-tool"?process.stdout.write('{"decision":"allow"}'):process.stdout.write("{}"),process.exitCode=0});export{od as buildAgyPreToolUseOutput,sd as normalizeAgyInput};
153
+ `).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}),nextOffset:r+Buffer.byteLength(u,"utf8")}}var bt=class{constructor(t){this.options=t;this.journal=new vt(t.storage),this.hierarchyJournal=new wt(t.storage)}options;journal;hierarchyJournal;async learnNew(){let t=this.options.wal.loadState(),n=Number(t.sourceCursors["memory.learner.offset"]??0),r=Number.isFinite(n)?n:0,s=Ul(this.options.wal.eventsFile,r);if(s.events.length===0)return{scannedEvents:0,candidates:0,journalWritten:!1,nextOffset:s.nextOffset};let o=at(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=Gs(this.options.identity,s.events,o.state),f=Us(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",f.written),this.options.wal.setSourceCursor("memory.skill.deduped",f.deduped);try{let l=jr(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 Ws({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}}};function Zs(e,t,n){if(process.env.TOOLNET_LOCAL_CHECKPOINT==="0"||n.length===0)return{updated:!1,observations:0};let r=He(t,n);if(r.length===0)return{updated:!1,observations:0};let s=Xn(e,r);Or(e,s),Cr(e,{agent:t.agent,nativeSessionId:t.nativeSessionId,observations:r,workState:s});try{Zr(e,t,n,s)}catch{}try{rr({project:e,identity:t,state:s,reason:"continuous-checkpoint",sequence:n.at(-1)?.sequence??0})}catch{}return{updated:!0,observations:r.length}}var xt=class{identity;wal;remote;sanitizer=new V;learner;continuity;semantic;handoff;project;title;metadata;constructor(t){this.project=t.project,this.identity=ns(t.project,t.agent,t.nativeSessionId),this.title=t.title,this.metadata=this.sanitizer.sanitizeValue(t.metadata??{}),this.wal=new mt(this.identity,t.eventContext),this.remote=new ct(t.storage,t.maxEventsPerChunk??100,t.maxChunkBytes??512*1024),this.learner=new bt({project:t.project,storage:t.storage,identity:this.identity,wal:this.wal}),this.continuity=new Ge({project:t.project,storage:t.storage,identity:this.identity,wal:this.wal}),this.semantic=new et({project:t.project,storage:t.storage,identity:this.identity,wal:this.wal}),this.handoff=new Xe({project:t.project,storage:t.storage,identity:this.identity})}sanitizeEvent(t){let n=t.provenance?{...t.provenance,metadata:this.sanitizer.sanitizeValue(t.provenance.metadata)}:void 0;return{...t,data:this.sanitizer.sanitizeValue(t.data??{}),provenance:n}}checkpointLocal(t){if(t.length!==0)try{Zs(this.project,this.identity,t)}catch{}}start(t={}){let n=this.wal.loadState();return this.record({type:n.lastSequence===0?"session_start":"session_resume",data:t,provenance:{source:this.identity.agent}})}record(t){let n=this.wal.append([this.sanitizeEvent(t)]);return this.checkpointLocal(n),n[0]}recordMany(t){let n=this.wal.append(t.map(r=>this.sanitizeEvent(r)));return this.checkpointLocal(n),n}setSourceCursor(t,n){this.wal.setSourceCursor(t,n)}async flush(){let t=this.wal.readPending(),n=this.wal.loadState(),r=await this.remote.append(this.identity,t.events,n.sourceCursors,{title:this.title,metadata:this.metadata});if(t.events.length>0){let s=t.events[t.events.length-1];this.wal.markRemote(s.sequence,t.endOffset)}if(process.env.TOOLNET_SESSION_LEARNING!=="0")try{await this.learner.learnNew()}catch{}if(process.env.TOOLNET_WORK_CONTINUITY!=="0")try{await this.continuity.learnNew()}catch{}if(process.env.TOOLNET_SEMANTIC_CONTINUITY!=="0")try{await this.semantic.learnNew()}catch{}if(process.env.TOOLNET_SMART_HANDOFF!=="0"&&t.events.length>0)try{let s=t.events[t.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(t={}){return this.record({type:"session_idle",data:t,provenance:{source:this.identity.agent}}),this.flush()}async end(t={}){return this.record({type:"session_end",data:t,provenance:{source:this.identity.agent}}),this.flush()}status(){return this.wal.loadState()}recoverRemote(){return this.remote.recover(this.identity)}};import{existsSync as Yl,openSync as Ql,closeSync as Xl,readSync as Zl,statSync as ed}from"node:fs";function td(e){let t=typeof e.role=="string"?e.role:"",n=typeof e.type=="string"?e.type.toLowerCase():"";return t==="user"||n.includes("user")?"user_prompt":t==="assistant"||n.includes("assistant")||n.includes("model")?"assistant_message":n.includes("tool")||"toolCall"in e||"tool_call"in e?"tool_call":n.includes("error")?"error":"message"}function nd(e){let t=[e.timestamp,e.createdAt,e.time,e.created_at];for(let n of t){if(typeof n=="string"){let r=new Date(n);if(!Number.isNaN(r.getTime()))return r.toISOString()}if(typeof n=="number"){let r=n;r<1e11&&(r*=1e3);let s=new Date(r);if(!Number.isNaN(s.getTime()))return s.toISOString()}}return new Date().toISOString()}function eo(e,t={offset:0}){if(!Yl(e))return{events:[],nextOffset:t.offset,reset:!1};let n=ed(e).size,r=t.offset>n,s=r?0:t.offset;if(s===n)return{events:[],nextOffset:n,reset:r};let o=n-s,i=Buffer.alloc(o),a=Ql(e,"r");try{Zl(a,i,0,o,s)}finally{Xl(a)}let c=i.toString("utf8"),u=c.lastIndexOf(`
154
+ `);if(u<0)return{events:[],nextOffset:s,reset:r};let f=c.slice(0,u+1),l=Buffer.byteLength(f,"utf8"),p=[],d=0;for(let m of f.split(`
155
+ `)){if(!m)continue;let k=Buffer.byteLength(m+`
156
+ `,"utf8"),g=s+d;d+=k;let h;try{h=JSON.parse(m)}catch{p.push({type:"custom",sourceEventId:`transcript:${g}`,sourceSequence:g,data:{format:"raw-line",content:m},provenance:{source:"agy-transcript",sourcePath:e,sourceOffset:g}});continue}let v=h&&typeof h=="object"&&!Array.isArray(h)?h:{value:h};p.push({type:td(v),timestamp:nd(v),role:typeof v.role=="string"?v.role:void 0,sourceEventId:`transcript:${g}`,sourceSequence:g,data:v,provenance:{source:"agy-transcript",sourcePath:e,sourceOffset:g}})}return{events:p,nextOffset:s+l,reset:r}}var rd=[/^<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*$/],sd=[/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],od=["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 id(e){let t=e.toLowerCase();return od.some(n=>t.includes(n))}function ad(e){if(!e.trim())return!0;for(let t of rd)if(t.test(e))return!0;return id(e),!1}function cd(e){let t=e;for(let n of sd)t=t.replace(n,r=>{let s=r.split(/[:\s=]+/);return s.length>1?`${s[0]}: [REDACTED]`:"[REDACTED]"});return t}function un(e){let t=e.trim();return t?ad(t)?{content:"",filtered:!0,reason:"noise"}:{content:cd(t),filtered:!1}:{content:"",filtered:!0,reason:"empty"}}function jt(e){let t={};for(let[n,r]of Object.entries(e))if(typeof r=="string"){let s=un(r);s.filtered||(t[n]=s.content)}else r&&typeof r=="object"&&!Array.isArray(r)?t[n]=jt(r):Array.isArray(r)?t[n]=r.map(s=>{if(typeof s=="string"){let o=un(s);return o.filtered?null:o.content}return s&&typeof s=="object"?jt(s):s}).filter(s=>s!==null):t[n]=r;return t}function to(e){let t=typeof e.type=="string"?e.type.toLowerCase():"";if(t.includes("system")||t.includes("ephemeral")||t==="tool_call"&&!e.result)return!0;if(e.data&&typeof e.data=="object"){let n=e.data,r=typeof n.content=="string"?n.content:"";if(r&&un(r).filtered)return!0}return!1}function dd(e){return e==="~"?no():e.startsWith("~/")?ud(no(),e.slice(2)):e}async function ro(e){let t=e.conversationId.trim();if(!t)throw new Error("Agy conversationId is required");let n=ld(dd(e.transcriptPath)),r=new xt({project:e.project,storage:e.storage,agent:"agy",nativeSessionId:t,metadata:{source:"antigravity-hook",transcriptPath:n,workspacePaths:e.workspacePaths??[],artifactDirectoryPath:e.artifactDirectoryPath,modelName:e.modelName},eventContext:{source:"agy",cwd:e.workspacePaths?.[0]??e.project.rootPath}}),s=r.status(),o=s.sourceCursors["agy.transcript.offset"],i=o?Number(o):0,a=eo(n,{offset:Number.isFinite(i)?i:0}),c=[];s.lastSequence===0&&c.push({type:"session_start",sourceEventId:`agy:${t}:start`,data:{workspacePaths:e.workspacePaths??[],transcriptPath:n,modelName:e.modelName},provenance:{source:"antigravity-hook",sourcePath:n}}),a.reset&&c.push({type:"custom",sourceEventId:`agy:${t}:transcript-reset:${a.nextOffset}`,data:{event:"transcript_reset",transcriptPath:n},provenance:{source:"agy-transcript",sourcePath:n}});let u=a.events.filter(p=>!to(p.data)).map(p=>({...p,data:jt(p.data)}));c.push(...u),e.phase==="stop"&&(e.error&&c.push({type:"error",sourceEventId:["agy",t,"stop-error",e.terminationReason??"",a.nextOffset].join(":"),data:{error:e.error,terminationReason:e.terminationReason,fullyIdle:e.fullyIdle},provenance:{source:"antigravity-stop-hook"}}),e.fullyIdle&&c.push({type:"session_idle",sourceEventId:["agy",t,"idle",a.nextOffset].join(":"),data:{terminationReason:e.terminationReason,fullyIdle:!0},provenance:{source:"antigravity-stop-hook"}}));let f=r.recordMany(c);if(r.setSourceCursor("agy.transcript.offset",a.nextOffset),e.phase&&r.setSourceCursor("agy.last.phase",e.phase),u.length>0)try{let p=u.map(m=>JSON.stringify(m.data)),d=it(p,t);r.setSourceCursor("agy.session.summary",d.summary),r.setSourceCursor("agy.session.facts_count",d.durableFacts.length),Br()&&(Jr()||r.setSourceCursor("agy.raw_transcript.archived","local"))}catch{}let l=await r.flush();return{conversationId:t,imported:f.length,eventCount:l.eventCount,chunkCount:l.chunkCount,status:l.status,transcriptOffset:a.nextOffset,reset:a.reset}}async function fd(){let e="";for await(let t of process.stdin)e+=t.toString();if(!e.trim())return{};try{return JSON.parse(e)}catch{return{}}}function _e(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function pd(e){let t=typeof e.common=="object"&&e.common!==null?e.common:{},n=typeof e.pre_invocation_hook_args=="object"&&e.pre_invocation_hook_args!==null?e.pre_invocation_hook_args:{},r=typeof e.post_invocation_hook_args=="object"&&e.post_invocation_hook_args!==null?e.post_invocation_hook_args:{},s=typeof e.stop_hook_args=="object"&&e.stop_hook_args!==null?e.stop_hook_args:{},o=(typeof e.conversationId=="string"?e.conversationId:"")||(typeof e.conversation_id=="string"?e.conversation_id:"")||(typeof t.conversation_id=="string"?t.conversation_id:""),i=(typeof e.transcriptPath=="string"?e.transcriptPath:"")||(typeof e.transcript_path=="string"?e.transcript_path:"")||(typeof t.transcript_path=="string"?t.transcript_path:""),a=_e(e.workspacePaths).length>0?_e(e.workspacePaths):_e(e.workspace_paths).length>0?_e(e.workspace_paths):_e(t.workspace_paths),c=typeof e.invocationNum=="number"?e.invocationNum:typeof n.invocation_num=="number"?n.invocation_num:typeof e.invocation_num=="number"?e.invocation_num:void 0,u=(typeof e.artifactDirectoryPath=="string"?e.artifactDirectoryPath:"")||(typeof t.artifact_directory_path=="string"?t.artifact_directory_path:"")||(typeof e.artifact_directory_path=="string"?e.artifact_directory_path:"")||void 0,f=(typeof e.modelName=="string"?e.modelName:"")||(typeof t.model_name=="string"?t.model_name:"")||(typeof e.model_name=="string"?e.model_name:"")||void 0,l=s.fully_idle===!0||e.fullyIdle===!0||e.fully_idle===!0,p=(typeof s.termination_reason=="string"?s.termination_reason:"")||(typeof e.terminationReason=="string"?e.terminationReason:"")||(typeof e.termination_reason=="string"?e.termination_reason:"")||void 0,d=(typeof s.error=="string"&&s.error?s.error:"")||(typeof e.error=="string"&&e.error?e.error:"")||void 0;return{conversationId:o,transcriptPath:i,workspacePaths:a,invocationNum:c,artifactDirectoryPath:u,modelName:f,fullyIdle:l,terminationReason:p,error:d}}function md(e){let t=typeof e.toolCall=="object"&&e.toolCall!==null?e.toolCall:{},n=typeof t.args=="object"&&t.args!==null?t.args:{},r="";try{r=JSON.stringify(n).replace(/\\\\/g,"/").toLowerCase()}catch{r=""}return r.includes(".toolnet/journal")||r.includes(".toolnet/runtime/sources")||r.includes(".toolnet/sessions")?{decision:"deny",reason:"ToolNet continuity guard: do not replay raw .toolnet/journal, .toolnet/runtime/sources or legacy .toolnet/sessions history. Use the injected continuity handoff. If deeper history is required, invoke memory_agent_ask directly."}:{decision:"allow"}}async function gd(){let e=process.argv[2]??"post",t=await fd();if(e==="pre-tool"){process.stdout.write(JSON.stringify(md(t)));return}let n=pd(t),r=n.conversationId,s=n.transcriptPath,o=n.workspacePaths,i=es(o);i&&(e==="pre"||e==="stop")&&In(i.rootPath);let c={};if(i&&r)try{let u=Fe(),f=xn(wn({provider:u.storage.provider,huggingface:u.storage.huggingface,localRoot:u.storage.localRoot}),{attempts:2}),l=new Be(f,i.id,i.name,i.remote??i.name);if(s)try{await ro({project:i,storage:l,conversationId:r,transcriptPath:s,workspacePaths:o,artifactDirectoryPath:n.artifactDirectoryPath,modelName:n.modelName,phase:e,fullyIdle:n.fullyIdle,terminationReason:n.terminationReason,error:n.error})}catch{}if(e==="pre")try{c=await Pr({project:i,storage:l,conversationId:r,invocationNum:n.invocationNum})}catch{c={}}if(e==="stop")try{await Rt(i,l,800)}catch{}}catch{}if(e==="stop"){process.stdout.write(JSON.stringify({decision:"stop"}));return}process.stdout.write(JSON.stringify(c))}gd().catch(()=>{process.argv[2]==="stop"?process.stdout.write('{"decision":"stop"}'):process.argv[2]==="pre-tool"?process.stdout.write('{"decision":"allow"}'):process.stdout.write("{}"),process.exitCode=0});export{md as buildAgyPreToolUseOutput,pd as normalizeAgyInput};